diff --git a/AUTHORS b/AUTHORS index 68e6c8f..42b0db5 100644 --- a/AUTHORS +++ b/AUTHORS
@@ -423,6 +423,7 @@ Jin Yang <jin.a.yang@intel.com> Jincheol Jo <jincheol.jo@navercorp.com> Jing Zhao <zhaojing7@xiaomi.com> +Jinglong Zuo <zuojinglong@xiaomi.com> Jingwei Liu <kingweiliu@gmail.com> Jingyi Wei <wjywbs@gmail.com> Jinho Bang <jinho.bang@samsung.com>
diff --git a/DEPS b/DEPS index b495f4d..72dfa18 100644 --- a/DEPS +++ b/DEPS
@@ -138,11 +138,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': 'bb74990a11d91ebe0ff474107c6dae3c0aadf308', + 'skia_revision': 'd6199ec7236b18853f58b51c54faae0b8c6cb582', # 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': '05e98a6eb753853cfbdabf257eba8cc633d5975f', + 'v8_revision': '7b60ccba767a2cde33badc5c35e05e67e8723275', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling swarming_client # and whatever else without interference from each other. @@ -150,7 +150,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': '28394c2295335929c17bbfe0ab74f923cd234ff2', + 'angle_revision': 'c75d6dc843460627e63709dbf17be70b24df8ddc', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. @@ -189,7 +189,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': '7fde521bd918d2299cce80c306ecc2cac9f51303', + 'freetype_revision': '78c02bc110b6a605c41487d8c26ae18960df251b', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling HarfBuzz # and whatever else without interference from each other. @@ -201,7 +201,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling catapult # and whatever else without interference from each other. - 'catapult_revision': 'ace1f8b4d2279930d39c9406820089f131ec7b25', + 'catapult_revision': '4d6b614ed206214c292146d55a0f20f12ad5a4e6', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -273,7 +273,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': 'fa8190ae44d23df92c1ed67c63f50c6d79843c83', + 'dawn_revision': '05f7ad5ac8f9945d2f52209d6c7c1c64a56e06fb', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -477,7 +477,7 @@ }, 'src/ios/third_party/material_components_ios/src': { - 'url': Var('chromium_git') + '/external/github.com/material-components/material-components-ios.git' + '@' + '08c3cc4722becd9233d8160356adb5cb423c5ee5', + 'url': Var('chromium_git') + '/external/github.com/material-components/material-components-ios.git' + '@' + 'df4ef89b8001252758209b93f2c830779002cfc1', 'condition': 'checkout_ios', }, @@ -807,7 +807,7 @@ # Build tools for Chrome OS. Note: This depends on third_party/pyelftools. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'd3ac0bd691bf7a9b52ec0ccc92dbef1265b087dd', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '457b2fb698ea3075a2d5d3dac02d057f2d297ecd', 'condition': 'checkout_linux', }, @@ -822,7 +822,7 @@ # For Linux and Chromium OS. 'src/third_party/cros_system_api': { - 'url': Var('chromium_git') + '/chromiumos/platform2/system_api.git' + '@' + 'a67d91d30a5a37cee98a9685f2082ecdf92168ad', + 'url': Var('chromium_git') + '/chromiumos/platform2/system_api.git' + '@' + 'fa76a090a15950aa0cee528c73aee6e2293db90f', 'condition': 'checkout_linux', }, @@ -1187,7 +1187,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + 'c63be46c502089deed3fc93217425e4b6ea2f517', + Var('android_git') + '/platform/external/perfetto.git' + '@' + '0b2e12b08cdcb8be58c992c8702cee90e0420324', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1355,7 +1355,7 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + '6f0b34abee8dba611c253738d955c59f703c147a', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '4606ded90ca9542d5452b348e5415df67aa3622a', + Var('webrtc_git') + '/src.git' + '@' + 'ab6fc1154f37e712ffdd729bb1fcdd3e91b2bada', 'src/third_party/xdg-utils': { 'url': Var('chromium_git') + '/chromium/deps/xdg-utils.git' + '@' + 'd80274d5869b17b8c9067a1022e4416ee7ed5e0d', @@ -1396,7 +1396,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@179aecf4b85da736b3bbb8227925417f28a2e563', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@9a234fca6ba5fe6f45b7b0264c0b1ed8d0f5c107', 'condition': 'checkout_src_internal', },
diff --git a/apps/launcher.cc b/apps/launcher.cc index 953efb4..fe8835f9 100644 --- a/apps/launcher.cc +++ b/apps/launcher.cc
@@ -54,7 +54,6 @@ using content::BrowserThread; using extensions::AppRuntimeEventRouter; -using extensions::api::app_runtime::PlayStoreStatus; using extensions::app_file_handler_util::CreateFileEntry; using extensions::app_file_handler_util::FileHandlerCanHandleEntry; using extensions::app_file_handler_util::FileHandlerForId; @@ -368,11 +367,9 @@ const extensions::Extension* app, const base::CommandLine& command_line, const base::FilePath& current_directory, - extensions::AppLaunchSource source, - PlayStoreStatus play_store_status) { + extensions::AppLaunchSource source) { LaunchPlatformAppWithCommandLineAndLaunchId(context, app, "", command_line, - current_directory, source, - play_store_status); + current_directory, source); } void LaunchPlatformAppWithCommandLineAndLaunchId( @@ -381,8 +378,7 @@ const std::string& launch_id, const base::CommandLine& command_line, const base::FilePath& current_directory, - extensions::AppLaunchSource source, - PlayStoreStatus play_store_status) { + extensions::AppLaunchSource source) { // An app with "kiosk_only" should not be installed and launched // outside of ChromeOS kiosk mode in the first place. This is a defensive // check in case this scenario does occur. @@ -415,8 +411,6 @@ args[0] == about_blank_url)) { std::unique_ptr<app_runtime::LaunchData> launch_data = std::make_unique<app_runtime::LaunchData>(); - if (play_store_status != PlayStoreStatus::PLAY_STORE_STATUS_UNKNOWN) - launch_data->play_store_status = play_store_status; if (!launch_id.empty()) launch_data->id.reset(new std::string(launch_id)); AppRuntimeEventRouter::DispatchOnLaunchedEvent(context, app, source,
diff --git a/apps/launcher.h b/apps/launcher.h index 74678f3..6738bffe 100644 --- a/apps/launcher.h +++ b/apps/launcher.h
@@ -39,15 +39,11 @@ // |command_line| means there is no launch data. If non-empty, // |current_directory| is used to expand any relative paths on the command line. // |source| is one of the enumerated values which trace how the app is launched. -void LaunchPlatformAppWithCommandLine( - content::BrowserContext* context, - const extensions::Extension* app, - const base::CommandLine& command_line, - const base::FilePath& current_directory, - extensions::AppLaunchSource source, - extensions::api::app_runtime::PlayStoreStatus play_store_status = - extensions::api::app_runtime::PlayStoreStatus:: - PLAY_STORE_STATUS_UNKNOWN); +void LaunchPlatformAppWithCommandLine(content::BrowserContext* context, + const extensions::Extension* app, + const base::CommandLine& command_line, + const base::FilePath& current_directory, + extensions::AppLaunchSource source); // As above but includes |launch_id|, an id that can be passed to // an app when launched in order to support multiple shelf items per app. @@ -57,10 +53,7 @@ const std::string& launch_id, const base::CommandLine& command_line, const base::FilePath& current_directory, - extensions::AppLaunchSource source, - extensions::api::app_runtime::PlayStoreStatus play_store_status = - extensions::api::app_runtime::PlayStoreStatus:: - PLAY_STORE_STATUS_UNKNOWN); + extensions::AppLaunchSource source); // Launches the platform app |app| by issuing an onLaunched event with the // contents of |file_path| available through the launch data.
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index 336b375..242a01c 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -484,8 +484,6 @@ "multi_user/multi_user_window_manager_impl.cc", "multi_user/user_switch_animator.cc", "multi_user/user_switch_animator.h", - "network_connect_delegate_mus.cc", - "network_connect_delegate_mus.h", "policy/policy_recommendation_restorer.cc", "policy/policy_recommendation_restorer.h", "root_window_controller.cc", @@ -877,8 +875,6 @@ "system/time/time_tray_item_view.h", "system/time/time_view.cc", "system/time/time_view.h", - "system/toast/toast_data.cc", - "system/toast/toast_data.h", "system/toast/toast_manager.cc", "system/toast/toast_manager.h", "system/toast/toast_overlay.cc",
diff --git a/ash/accelerators/accelerator_controller_impl.cc b/ash/accelerators/accelerator_controller_impl.cc index df182d8..179eb2e 100644 --- a/ash/accelerators/accelerator_controller_impl.cc +++ b/ash/accelerators/accelerator_controller_impl.cc
@@ -35,6 +35,7 @@ #include "ash/public/cpp/ash_switches.h" #include "ash/public/cpp/new_window_delegate.h" #include "ash/public/cpp/notification_utils.h" +#include "ash/public/cpp/toast_data.h" #include "ash/public/cpp/voice_interaction_controller.h" #include "ash/public/interfaces/accessibility_controller.mojom.h" #include "ash/resources/vector_icons/vector_icons.h" @@ -54,7 +55,6 @@ #include "ash/system/palette/palette_utils.h" #include "ash/system/power/power_button_controller.h" #include "ash/system/status_area_widget.h" -#include "ash/system/toast/toast_data.h" #include "ash/system/toast/toast_manager.h" #include "ash/system/tray/system_tray_notifier.h" #include "ash/system/unified/unified_system_tray.h"
diff --git a/ash/accelerators/debug_commands.cc b/ash/accelerators/debug_commands.cc index 0258861e..dccf90c 100644 --- a/ash/accelerators/debug_commands.cc +++ b/ash/accelerators/debug_commands.cc
@@ -6,9 +6,9 @@ #include "ash/accelerators/accelerator_commands.h" #include "ash/public/cpp/ash_switches.h" +#include "ash/public/cpp/toast_data.h" #include "ash/root_window_controller.h" #include "ash/shell.h" -#include "ash/system/toast/toast_data.h" #include "ash/system/toast/toast_manager.h" #include "ash/touch/touch_devices_controller.h" #include "ash/wallpaper/wallpaper_controller_impl.h"
diff --git a/ash/assistant/assistant_ui_controller.cc b/ash/assistant/assistant_ui_controller.cc index 3dab6bf..8652f5e5 100644 --- a/ash/assistant/assistant_ui_controller.cc +++ b/ash/assistant/assistant_ui_controller.cc
@@ -14,11 +14,11 @@ #include "ash/assistant/util/histogram_util.h" #include "ash/multi_user/multi_user_window_manager_impl.h" #include "ash/public/cpp/app_list/app_list_features.h" +#include "ash/public/cpp/toast_data.h" #include "ash/public/cpp/voice_interaction_controller.h" #include "ash/session/session_controller_impl.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" -#include "ash/system/toast/toast_data.h" #include "ash/system/toast/toast_manager.h" #include "base/bind.h" #include "base/optional.h"
diff --git a/ash/login/login_screen_controller.cc b/ash/login/login_screen_controller.cc index 2014f2c..60c2ecf 100644 --- a/ash/login/login_screen_controller.cc +++ b/ash/login/login_screen_controller.cc
@@ -12,6 +12,7 @@ #include "ash/login/ui/parent_access_widget.h" #include "ash/public/cpp/ash_pref_names.h" #include "ash/public/cpp/login_screen_client.h" +#include "ash/public/cpp/toast_data.h" #include "ash/root_window_controller.h" #include "ash/session/session_controller_impl.h" #include "ash/shelf/login_shelf_view.h" @@ -20,7 +21,6 @@ #include "ash/shell.h" #include "ash/system/status_area_widget.h" #include "ash/system/status_area_widget_delegate.h" -#include "ash/system/toast/toast_data.h" #include "ash/system/toast/toast_manager.h" #include "ash/system/tray/system_tray_notifier.h" #include "base/bind.h"
diff --git a/ash/network_connect_delegate_mus.cc b/ash/network_connect_delegate_mus.cc deleted file mode 100644 index b1b9d669..0000000 --- a/ash/network_connect_delegate_mus.cc +++ /dev/null
@@ -1,55 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ash/network_connect_delegate_mus.h" - -#include "ash/public/cpp/system_tray_client.h" -#include "ash/shell.h" -#include "ash/system/model/system_tray_model.h" -#include "base/logging.h" - -namespace ash { - -NetworkConnectDelegateMus::NetworkConnectDelegateMus() = default; - -NetworkConnectDelegateMus::~NetworkConnectDelegateMus() = default; - -void NetworkConnectDelegateMus::ShowNetworkConfigure( - const std::string& network_id) { - Shell::Get()->system_tray_model()->client()->ShowNetworkConfigure(network_id); -} - -void NetworkConnectDelegateMus::ShowNetworkSettings( - const std::string& network_id) { - Shell::Get()->system_tray_model()->client()->ShowNetworkSettings(network_id); -} - -bool NetworkConnectDelegateMus::ShowEnrollNetwork( - const std::string& network_id) { - // TODO(mash): http://crbug.com/644355 - NOTIMPLEMENTED_LOG_ONCE(); - return false; -} - -void NetworkConnectDelegateMus::ShowMobileSetupDialog( - const std::string& network_id) { - // TODO(mash): http://crbug.com/644355 - NOTIMPLEMENTED_LOG_ONCE(); -} - -void NetworkConnectDelegateMus::ShowNetworkConnectError( - const std::string& error_name, - const std::string& network_id) { - // TODO(mash): http://crbug.com/644355 - LOG(ERROR) << "Network Connect Error: " << error_name - << " For: " << network_id; -} - -void NetworkConnectDelegateMus::ShowMobileActivationError( - const std::string& network_id) { - // TODO(mash): http://crbug.com/644355 - LOG(ERROR) << "Mobile Activation Error For: " << network_id; -} - -} // namespace ash
diff --git a/ash/network_connect_delegate_mus.h b/ash/network_connect_delegate_mus.h deleted file mode 100644 index d030487f2..0000000 --- a/ash/network_connect_delegate_mus.h +++ /dev/null
@@ -1,37 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef ASH_NETWORK_CONNECT_DELEGATE_MUS_H_ -#define ASH_NETWORK_CONNECT_DELEGATE_MUS_H_ - -#include "base/macros.h" -#include "chromeos/network/network_connect.h" - -namespace ash { - -// Routes requests to show network config UI over the mojom::SystemTrayClient -// interface. -// TODO(mash): Replace NetworkConnect::Delegate with a client interface on -// a mojo NetworkConfig service. http://crbug.com/644355 -class NetworkConnectDelegateMus : public chromeos::NetworkConnect::Delegate { - public: - NetworkConnectDelegateMus(); - ~NetworkConnectDelegateMus() override; - - // chromeos::NetworkConnect::Delegate: - void ShowNetworkConfigure(const std::string& network_id) override; - void ShowNetworkSettings(const std::string& network_id) override; - bool ShowEnrollNetwork(const std::string& network_id) override; - void ShowMobileSetupDialog(const std::string& network_id) override; - void ShowNetworkConnectError(const std::string& error_name, - const std::string& network_id) override; - void ShowMobileActivationError(const std::string& network_id) override; - - private: - DISALLOW_COPY_AND_ASSIGN(NetworkConnectDelegateMus); -}; - -} // namespace ash - -#endif // ASH_NETWORK_CONNECT_DELEGATE_MUS_H_
diff --git a/ash/public/cpp/BUILD.gn b/ash/public/cpp/BUILD.gn index 19848563..4562da8f 100644 --- a/ash/public/cpp/BUILD.gn +++ b/ash/public/cpp/BUILD.gn
@@ -169,6 +169,8 @@ "tablet_mode.cc", "tablet_mode.h", "tablet_mode_toggle_observer.h", + "toast_data.cc", + "toast_data.h", "touch_uma.cc", "touch_uma.h", "update_types.h",
diff --git a/ash/system/toast/toast_data.cc b/ash/public/cpp/toast_data.cc similarity index 94% rename from ash/system/toast/toast_data.cc rename to ash/public/cpp/toast_data.cc index 2128d147..7659901 100644 --- a/ash/system/toast/toast_data.cc +++ b/ash/public/cpp/toast_data.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 "ash/system/toast/toast_data.h" +#include "ash/public/cpp/toast_data.h" #include <utility>
diff --git a/ash/system/toast/toast_data.h b/ash/public/cpp/toast_data.h similarity index 81% rename from ash/system/toast/toast_data.h rename to ash/public/cpp/toast_data.h index d3259a5..51939d6 100644 --- a/ash/system/toast/toast_data.h +++ b/ash/public/cpp/toast_data.h
@@ -2,18 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef ASH_SYSTEM_TOAST_TOAST_DATA_H_ -#define ASH_SYSTEM_TOAST_TOAST_DATA_H_ +#ifndef ASH_PUBLIC_CPP_TOAST_DATA_H_ +#define ASH_PUBLIC_CPP_TOAST_DATA_H_ #include <string> -#include "ash/ash_export.h" +#include "ash/public/cpp/ash_public_export.h" #include "base/optional.h" #include "base/strings/string16.h" namespace ash { -struct ASH_EXPORT ToastData { +struct ASH_PUBLIC_EXPORT ToastData { // "|duration_ms| == -1" means the toast view should be displayed until the // dismiss button is clicked. static const int32_t kInfiniteDuration = -1; @@ -35,4 +35,4 @@ } // namespace ash -#endif // ASH_SYSTEM_TOAST_TOAST_DATA_H_ +#endif // ASH_PUBLIC_CPP_TOAST_DATA_H_
diff --git a/ash/system/message_center/ash_message_center_lock_screen_controller.cc b/ash/system/message_center/ash_message_center_lock_screen_controller.cc index 6c76e5d62..d21d6b5 100644 --- a/ash/system/message_center/ash_message_center_lock_screen_controller.cc +++ b/ash/system/message_center/ash_message_center_lock_screen_controller.cc
@@ -7,12 +7,12 @@ #include "ash/login/ui/lock_screen.h" #include "ash/public/cpp/ash_features.h" #include "ash/public/cpp/ash_pref_names.h" +#include "ash/public/cpp/toast_data.h" #include "ash/session/session_controller_impl.h" #include "ash/shelf/shelf.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" #include "ash/system/status_area_widget.h" -#include "ash/system/toast/toast_data.h" #include "ash/system/toast/toast_manager.h" #include "ash/system/unified/unified_system_tray.h" #include "base/strings/utf_string_conversions.h"
diff --git a/ash/system/palette/tools/capture_region_mode.cc b/ash/system/palette/tools/capture_region_mode.cc index b65d4a7..477f1b8 100644 --- a/ash/system/palette/tools/capture_region_mode.cc +++ b/ash/system/palette/tools/capture_region_mode.cc
@@ -4,11 +4,11 @@ #include "ash/system/palette/tools/capture_region_mode.h" +#include "ash/public/cpp/toast_data.h" #include "ash/resources/vector_icons/vector_icons.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" #include "ash/system/palette/palette_ids.h" -#include "ash/system/toast/toast_data.h" #include "ash/system/toast/toast_manager.h" #include "ash/utility/screenshot_controller.h" #include "base/bind.h"
diff --git a/ash/system/palette/tools/metalayer_mode.cc b/ash/system/palette/tools/metalayer_mode.cc index c76e7d6..564057a 100644 --- a/ash/system/palette/tools/metalayer_mode.cc +++ b/ash/system/palette/tools/metalayer_mode.cc
@@ -4,13 +4,13 @@ #include "ash/system/palette/tools/metalayer_mode.h" +#include "ash/public/cpp/toast_data.h" #include "ash/public/cpp/voice_interaction_controller.h" #include "ash/resources/vector_icons/vector_icons.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" #include "ash/system/palette/palette_ids.h" #include "ash/system/palette/palette_utils.h" -#include "ash/system/toast/toast_data.h" #include "ash/system/toast/toast_manager.h" #include "ash/system/tray/hover_highlight_view.h" #include "ash/system/tray/tray_constants.h"
diff --git a/ash/system/toast/toast_manager.h b/ash/system/toast/toast_manager.h index e2811ba..e22b2ae 100644 --- a/ash/system/toast/toast_manager.h +++ b/ash/system/toast/toast_manager.h
@@ -9,8 +9,8 @@ #include <string> #include "ash/ash_export.h" +#include "ash/public/cpp/toast_data.h" #include "ash/session/session_observer.h" -#include "ash/system/toast/toast_data.h" #include "ash/system/toast/toast_overlay.h" #include "base/containers/circular_deque.h" #include "base/memory/weak_ptr.h"
diff --git a/ash/wm/splitview/split_view_utils.cc b/ash/wm/splitview/split_view_utils.cc index 0a63faf2..cb5f1e8a 100644 --- a/ash/wm/splitview/split_view_utils.cc +++ b/ash/wm/splitview/split_view_utils.cc
@@ -9,10 +9,10 @@ #include "ash/kiosk_next/kiosk_next_shell_controller_impl.h" #include "ash/public/cpp/ash_features.h" #include "ash/public/cpp/ash_switches.h" +#include "ash/public/cpp/toast_data.h" #include "ash/screen_util.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" -#include "ash/system/toast/toast_data.h" #include "ash/system/toast/toast_manager.h" #include "ash/wm/screen_pinning_controller.h" #include "ash/wm/splitview/split_view_constants.h"
diff --git a/base/android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java b/base/android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java index 56588d7d..6466822 100644 --- a/base/android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java +++ b/base/android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java
@@ -4,8 +4,12 @@ package org.chromium.base.library_loader; +import android.annotation.SuppressLint; +import android.content.Context; + import org.chromium.base.CommandLine; import org.chromium.base.ContextUtils; +import org.chromium.base.Log; import org.chromium.base.SysUtils; import org.chromium.base.TraceEvent; import org.chromium.base.annotations.CalledByNative; @@ -15,6 +19,8 @@ import org.chromium.base.task.PostTask; import org.chromium.base.task.TaskTraits; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.util.concurrent.atomic.AtomicBoolean; /** @@ -48,9 +54,10 @@ } } + private static final String TAG = "LibraryPrefetcher"; // One-way switch that becomes true once // {@link asyncPrefetchLibrariesToMemory} has been called. - private final static AtomicBoolean sPrefetchLibraryHasBeenCalled = new AtomicBoolean(); + private static final AtomicBoolean sPrefetchLibraryHasBeenCalled = new AtomicBoolean(); /** * Prefetches the native libraries in a background thread. @@ -98,10 +105,36 @@ }); } + @SuppressLint("WrongConstant") public static void pinOrderedCodeInMemory() { try (TraceEvent e = TraceEvent.scoped("LibraryPrefetcher::pinOrderedCodeInMemory")) { OrderedCodeInfo info = nativeGetOrderedCodeInfo(); - if (info != null) TraceEvent.instant("pinOrderedCodeInMemory", info.toString()); + if (info == null) return; + TraceEvent.instant("pinOrderedCodeInMemory", info.toString()); + + Context context = ContextUtils.getApplicationContext(); + Object pinner = context.getSystemService("pinner"); + if (pinner == null) { + Log.w(TAG, "Cannot get PinnerService."); + return; + } + + // Reflection is required because the method is neither visible in the platform, nor + // available everywhere. + try { + Method pinRangeFromFile = pinner.getClass().getMethod( + "pinRangeFromFile", String.class, int.class, int.class); + boolean ok = (Boolean) pinRangeFromFile.invoke( + pinner, info.filename, (int) info.startOffset, (int) info.length); + if (!ok) { + Log.e(TAG, "Not allowed to call the method, should not happen"); + } else { + Log.i(TAG, "Successfully pinned ordered code"); + } + } catch ( + NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) { + Log.w(TAG, "Error invoking the method. " + ex.getMessage()); + } } }
diff --git a/base/task/promise/promise.h b/base/task/promise/promise.h index 00d7946..4a3374b 100644 --- a/base/task/promise/promise.h +++ b/base/task/promise/promise.h
@@ -5,6 +5,7 @@ #ifndef BASE_TASK_PROMISE_PROMISE_H_ #define BASE_TASK_PROMISE_PROMISE_H_ +#include "base/run_loop.h" #include "base/task/post_task.h" #include "base/task/promise/all_container_executor.h" #include "base/task/promise/all_tuple_executor.h" @@ -72,6 +73,47 @@ return abstract_promise_->IsCanceled(); } + // Waits until the promise has settled and if resolved it returns the resolved + // value. + template <typename T = ResolveType, + std::enable_if_t<!std::is_reference<T>::value && + !std::is_void<T>::value>* = nullptr> + T TakeResolveValueForTesting() { + static_assert(!std::is_same<NoResolve, T>::value, + "A NoResolve promise can't resolve."); + if (!abstract_promise_->IsSettled()) { + RunLoop run_loop; + FinallyHere(FROM_HERE, run_loop.QuitClosure()); + run_loop.Run(); + } + DCHECK(abstract_promise_->IsResolved()) + << "Can't take resolved value, promise wasn't resolved."; + return std::move( + unique_any_cast<Resolved<T>>(&abstract_promise_->TakeValue().value()) + ->value); + } + + // Waits until the promise has settled and if rejected it returns the rejected + // value. + template <typename T = RejectType, + std::enable_if_t<!std::is_reference<T>::value && + !std::is_void<T>::value>* = nullptr> + T TakeRejectValueForTesting() { + static_assert(!std::is_same<NoReject, T>::value, + "A NoReject promise can't reject."); + if (!abstract_promise_->IsSettled()) { + RunLoop run_loop; + FinallyHere(FROM_HERE, run_loop.QuitClosure()); + run_loop.Run(); + } + abstract_promise_->IgnoreUncaughtCatchForTesting(); + DCHECK(abstract_promise_->IsRejected()) + << "Can't take rejected value, promise wasn't rejected."; + return std::move( + unique_any_cast<Rejected<T>>(&abstract_promise_->TakeValue().value()) + ->value); + } + bool IsResolvedForTesting() const { DCHECK(abstract_promise_); return abstract_promise_->IsResolved();
diff --git a/base/task/promise/promise_unittest.cc b/base/task/promise/promise_unittest.cc index 21ad2f1..57eb356 100644 --- a/base/task/promise/promise_unittest.cc +++ b/base/task/promise/promise_unittest.cc
@@ -2057,4 +2057,64 @@ mpr4.Reject(); } +TEST_F(PromiseTest, TakeResolveValueForTesting) { + ManualPromiseResolver<void> p1(FROM_HERE); + + Promise<int> p2 = + p1.promise().ThenHere(FROM_HERE, BindOnce([]() { return 123; })); + + p1.Resolve(); + + EXPECT_EQ(123, p2.TakeResolveValueForTesting()); +} + +TEST_F(PromiseTest, TakeResolveValueForTestingMoveOnlyType) { + ManualPromiseResolver<void> p1(FROM_HERE); + + Promise<std::unique_ptr<int>> p2 = p1.promise().ThenHere( + FROM_HERE, BindOnce([]() { return std::make_unique<int>(123); })); + + p1.Resolve(); + + EXPECT_EQ(123, *p2.TakeResolveValueForTesting()); +} + +TEST_F(PromiseTest, TakeResolveValueForTestingNotResolved) { + ManualPromiseResolver<int, int> p1(FROM_HERE, + RejectPolicy::kCatchNotRequired); + + p1.Reject(123); + + EXPECT_DCHECK_DEATH({ p1.promise().TakeResolveValueForTesting(); }); +} + +TEST_F(PromiseTest, TakeRejectedValueForTesting) { + ManualPromiseResolver<void, void> p1(FROM_HERE); + + Promise<int, int> p2 = p1.promise().ThenHere( + FROM_HERE, BindOnce([]() { return Resolved<int>(123); }), + BindOnce([]() { return Rejected<int>(456); })); + + p1.Reject(); + + EXPECT_EQ(456, p2.TakeRejectValueForTesting()); +} + +TEST_F(PromiseTest, TakeRejectedValueForTestingMoveOnlyType) { + ManualPromiseResolver<void, std::unique_ptr<int>> p1(FROM_HERE); + + p1.Reject(std::make_unique<int>(456)); + + EXPECT_EQ(456, *p1.promise().TakeRejectValueForTesting()); +} + +TEST_F(PromiseTest, TakeRejectedValueForTestingNotRejected) { + ManualPromiseResolver<int, int> p1(FROM_HERE, + RejectPolicy::kCatchNotRequired); + + p1.Resolve(123); + + EXPECT_DCHECK_DEATH({ p1.promise().TakeRejectValueForTesting(); }); +} + } // namespace base
diff --git a/base/test/test_mock_time_task_runner.h b/base/test/test_mock_time_task_runner.h index b5d081d6..c4de731 100644 --- a/base/test/test_mock_time_task_runner.h +++ b/base/test/test_mock_time_task_runner.h
@@ -64,6 +64,9 @@ // // This is a slightly more sophisticated version of TestSimpleTaskRunner, in // that it supports running delayed tasks in the correct temporal order. +// +// ATTENTION: Consider using base::test::ScopedTaskEnvironment with a +// base::test::ScopedTaskEnvironment::MOCK_TIME constructor parameter instead. class TestMockTimeTaskRunner : public SingleThreadTaskRunner, public RunLoop::Delegate { public: @@ -84,7 +87,7 @@ // } // // // Mock main task runner. - // base::test::ScopedTaskEnvironment scoped_task_environment_; + // base::MessageLoop message_loop_; // base::ScopedMockTimeMessageLoopTaskRunner main_task_runner_; // // // Mock foo task runner.
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1 index 07c9c07..ac3d99ce 100644 --- a/build/fuchsia/linux.sdk.sha1 +++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@ -8910995301683410640 \ No newline at end of file +8910952372606612720 \ No newline at end of file
diff --git a/build/fuchsia/mac.sdk.sha1 b/build/fuchsia/mac.sdk.sha1 index 62b17b26..562af1b9 100644 --- a/build/fuchsia/mac.sdk.sha1 +++ b/build/fuchsia/mac.sdk.sha1
@@ -1 +1 @@ -8911000999377944560 \ No newline at end of file +8910955625084904032 \ No newline at end of file
diff --git a/cc/layers/picture_layer.cc b/cc/layers/picture_layer.cc index 5447882..2d1bdfb 100644 --- a/cc/layers/picture_layer.cc +++ b/cc/layers/picture_layer.cc
@@ -82,7 +82,7 @@ } layer_impl->UpdateRasterSource(recording_source_->CreateRasterSource(), - &last_updated_invalidation_, nullptr); + &last_updated_invalidation_, nullptr, nullptr); DCHECK(last_updated_invalidation_.IsEmpty()); }
diff --git a/cc/layers/picture_layer_impl.cc b/cc/layers/picture_layer_impl.cc index b1b2ebd..1bae1c75 100644 --- a/cc/layers/picture_layer_impl.cc +++ b/cc/layers/picture_layer_impl.cc
@@ -223,8 +223,8 @@ layer_tree_impl()->create_low_res_tiling() ? 2u : 1u); layer_impl->set_gpu_raster_max_texture_size(gpu_raster_max_texture_size_); - layer_impl->UpdateRasterSource(raster_source_, &invalidation_, - tilings_.get()); + layer_impl->UpdateRasterSource(raster_source_, &invalidation_, tilings_.get(), + &paint_worklet_records_); DCHECK(invalidation_.IsEmpty()); // After syncing a solid color layer, the active layer has no tilings. @@ -731,7 +731,8 @@ void PictureLayerImpl::UpdateRasterSource( scoped_refptr<RasterSource> raster_source, Region* new_invalidation, - const PictureLayerTilingSet* pending_set) { + const PictureLayerTilingSet* pending_set, + const PaintWorkletRecordMap* pending_paint_worklet_records) { // The bounds and the pile size may differ if the pile wasn't updated (ie. // PictureLayer::Update didn't happen). In that case the pile will be empty. DCHECK(raster_source->GetSize().IsEmpty() || @@ -747,9 +748,16 @@ // Unregister for all images on the current raster source, if the recording // was updated. - if (recording_updated) + if (recording_updated) { UnregisterAnimatedImages(); + // When the display list changes, the set of PaintWorklets may also change. + if (pending_paint_worklet_records) + paint_worklet_records_ = *pending_paint_worklet_records; + else + SetPaintWorkletInputs(raster_source->GetPaintWorkletInputs()); + } + // The |raster_source_| is initially null, so have to check for that for the // first frame. bool could_have_tilings = raster_source_.get() && CanHaveTilings(); @@ -1722,6 +1730,13 @@ return ImageInvalidationResult::kInvalidated; } +void PictureLayerImpl::SetPaintWorkletRecordForTesting( + scoped_refptr<PaintWorkletInput> input, + sk_sp<PaintRecord> record) { + DCHECK(paint_worklet_records_.find(input) != paint_worklet_records_.end()); + paint_worklet_records_[input] = std::move(record); +} + void PictureLayerImpl::RegisterAnimatedImages() { if (!raster_source_ || !raster_source_->GetDisplayItemList()) return; @@ -1750,6 +1765,16 @@ controller->UnregisterAnimationDriver(data.paint_image_id, this); } +void PictureLayerImpl::SetPaintWorkletInputs( + const std::vector<scoped_refptr<PaintWorkletInput>>& inputs) { + PaintWorkletRecordMap new_records; + for (const auto& input : inputs) { + // Attempt to re-use an existing PaintRecord if possible. + new_records[input] = std::move(paint_worklet_records_[input]); + } + paint_worklet_records_.swap(new_records); +} + std::unique_ptr<base::DictionaryValue> PictureLayerImpl::LayerAsJson() const { auto result = LayerImpl::LayerAsJson(); auto dictionary = std::make_unique<base::DictionaryValue>();
diff --git a/cc/layers/picture_layer_impl.h b/cc/layers/picture_layer_impl.h index d97e820..40fab0ce 100644 --- a/cc/layers/picture_layer_impl.h +++ b/cc/layers/picture_layer_impl.h
@@ -74,9 +74,13 @@ void set_gpu_raster_max_texture_size(gfx::Size gpu_raster_max_texture_size) { gpu_raster_max_texture_size_ = gpu_raster_max_texture_size; } - void UpdateRasterSource(scoped_refptr<RasterSource> raster_source, - Region* new_invalidation, - const PictureLayerTilingSet* pending_set); + using PaintWorkletRecordMap = + base::flat_map<scoped_refptr<PaintWorkletInput>, sk_sp<PaintRecord>>; + void UpdateRasterSource( + scoped_refptr<RasterSource> raster_source, + Region* new_invalidation, + const PictureLayerTilingSet* pending_set, + const PaintWorkletRecordMap* pending_paint_worklet_records); bool UpdateTiles(); // Returns true if the LCD state changed. bool UpdateCanUseLCDTextAfterCommit(); @@ -127,6 +131,13 @@ const Region& InvalidationForTesting() const { return invalidation_; } + void SetPaintWorkletRecordForTesting(scoped_refptr<PaintWorkletInput>, + sk_sp<PaintRecord>); + + const PaintWorkletRecordMap& GetPaintWorkletRecordMapForTesting() const { + return paint_worklet_records_; + } + protected: PictureLayerImpl(LayerTreeImpl* tree_impl, int id, @@ -161,6 +172,10 @@ std::unique_ptr<base::DictionaryValue> LayerAsJson() const override; + // Set the collection of PaintWorkletInputs that are part of this layer. + void SetPaintWorkletInputs( + const std::vector<scoped_refptr<PaintWorkletInput>>& inputs); + PictureLayerImpl* twin_layer_; std::unique_ptr<PictureLayerTilingSet> tilings_; @@ -209,6 +224,13 @@ // of comparing pointers, since objects pointed to are not guaranteed to // exist. std::vector<PictureLayerTiling*> last_append_quads_tilings_; + + // The set of PaintWorkletInputs that are part of this PictureLayerImpl, and + // their painted results (if any). During commit, Blink hands us a set of + // PaintWorkletInputs that are part of this layer. These are then painted + // asynchronously on a worklet thread, triggered from + // |LayerTreeHostImpl::UpdateSyncTreeAfterCommitOrImplSideInvalidation|. + PaintWorkletRecordMap paint_worklet_records_; }; } // namespace cc
diff --git a/cc/layers/picture_layer_impl_unittest.cc b/cc/layers/picture_layer_impl_unittest.cc index d98fed6..c9a39cf 100644 --- a/cc/layers/picture_layer_impl_unittest.cc +++ b/cc/layers/picture_layer_impl_unittest.cc
@@ -31,6 +31,7 @@ #include "cc/test/layer_test_common.h" #include "cc/test/skia_common.h" #include "cc/test/test_layer_tree_host_base.h" +#include "cc/test/test_paint_worklet_input.h" #include "cc/test/test_task_graph_runner.h" #include "cc/tiles/tiling_set_raster_queue_all.h" #include "cc/tiles/tiling_set_raster_queue_required.h" @@ -5536,5 +5537,62 @@ EXPECT_FALSE(active_layer()->ShouldAnimate(image2.stable_id())); } +TEST_F(PictureLayerImplTest, PaintWorkletInputs) { + gfx::Size layer_bounds(1000, 1000); + + // Set up a raster source with 2 PaintWorkletInputs. + auto recording_source = FakeRecordingSource::CreateRecordingSource( + gfx::Rect(layer_bounds), layer_bounds); + scoped_refptr<TestPaintWorkletInput> input1 = + base::MakeRefCounted<TestPaintWorkletInput>(gfx::SizeF(100, 100)); + PaintImage image1 = CreatePaintWorkletPaintImage(input1); + scoped_refptr<TestPaintWorkletInput> input2 = + base::MakeRefCounted<TestPaintWorkletInput>(gfx::SizeF(50, 50)); + PaintImage image2 = CreatePaintWorkletPaintImage(input2); + recording_source->add_draw_image(image1, gfx::Point(100, 100)); + recording_source->add_draw_image(image2, gfx::Point(500, 500)); + recording_source->Rerecord(); + scoped_refptr<RasterSource> raster_source = + recording_source->CreateRasterSource(); + + // All inputs should be registered on the pending layer. + SetupPendingTree(raster_source, gfx::Size(), Region(gfx::Rect(layer_bounds))); + EXPECT_EQ(pending_layer()->GetPaintWorkletRecordMapForTesting().size(), 2u); + EXPECT_TRUE( + pending_layer()->GetPaintWorkletRecordMapForTesting().contains(input1)); + EXPECT_TRUE( + pending_layer()->GetPaintWorkletRecordMapForTesting().contains(input2)); + + // Specify a record for one of the inputs. + sk_sp<PaintRecord> record1 = sk_make_sp<PaintOpBuffer>(); + pending_layer()->SetPaintWorkletRecordForTesting(input1, record1); + + // Now activate and make sure the active layer is registered as well, with the + // appropriate record. + ActivateTree(); + EXPECT_EQ(active_layer()->GetPaintWorkletRecordMapForTesting().size(), 2u); + auto it = active_layer()->GetPaintWorkletRecordMapForTesting().find(input1); + ASSERT_NE(it, active_layer()->GetPaintWorkletRecordMapForTesting().end()); + EXPECT_EQ(it->second, record1); + EXPECT_TRUE( + active_layer()->GetPaintWorkletRecordMapForTesting().contains(input2)); + + // Committing new PaintWorkletInputs (in a new raster source) should replace + // the previous ones. + recording_source = FakeRecordingSource::CreateRecordingSource( + gfx::Rect(layer_bounds), layer_bounds); + scoped_refptr<TestPaintWorkletInput> input3 = + base::MakeRefCounted<TestPaintWorkletInput>(gfx::SizeF(12, 12)); + PaintImage image3 = CreatePaintWorkletPaintImage(input3); + recording_source->add_draw_image(image3, gfx::Point(10, 10)); + recording_source->Rerecord(); + raster_source = recording_source->CreateRasterSource(); + + SetupPendingTree(raster_source, gfx::Size(), Region(gfx::Rect(layer_bounds))); + EXPECT_EQ(pending_layer()->GetPaintWorkletRecordMapForTesting().size(), 1u); + EXPECT_TRUE( + pending_layer()->GetPaintWorkletRecordMapForTesting().contains(input3)); +} + } // namespace } // namespace cc
diff --git a/cc/paint/discardable_image_map.cc b/cc/paint/discardable_image_map.cc index 23ccb20..e5f689b1 100644 --- a/cc/paint/discardable_image_map.cc +++ b/cc/paint/discardable_image_map.cc
@@ -103,6 +103,9 @@ TakeAnimatedImagesMetadata() { return std::move(animated_images_metadata_); } + std::vector<scoped_refptr<PaintWorkletInput>> TakePaintWorkletInputs() { + return std::move(paint_worklet_inputs_); + } void RecordColorHistograms() const { if (color_stats_total_image_count_ > 0) { @@ -354,7 +357,9 @@ SkIRect src_irect; src_rect.roundOut(&src_irect); - if (!paint_image.IsPaintWorklet()) { + if (paint_image.IsPaintWorklet()) { + paint_worklet_inputs_.push_back(paint_image.paint_worklet_input()); + } else { // Make a note if any image was originally specified in a non-sRGB color // space. SkColorSpace* source_color_space = paint_image.color_space(); @@ -406,6 +411,7 @@ base::flat_map<PaintImage::Id, DiscardableImageMap::Rects> image_id_to_rects_; std::vector<DiscardableImageMap::AnimatedImageMetadata> animated_images_metadata_; + std::vector<scoped_refptr<PaintWorkletInput>> paint_worklet_inputs_; base::flat_map<PaintImage::Id, PaintImage::DecodingMode> decoding_mode_map_; bool only_gather_animated_images_ = false; @@ -434,6 +440,7 @@ generator.RecordColorHistograms(); image_id_to_rects_ = generator.TakeImageIdToRectsMap(); animated_images_metadata_ = generator.TakeAnimatedImagesMetadata(); + paint_worklet_inputs_ = generator.TakePaintWorkletInputs(); decoding_mode_map_ = generator.TakeDecodingModeMap(); all_images_are_srgb_ = generator.all_images_are_srgb(); auto images = generator.TakeImages();
diff --git a/cc/paint/discardable_image_map.h b/cc/paint/discardable_image_map.h index a9d1bb96..dd494fa 100644 --- a/cc/paint/discardable_image_map.h +++ b/cc/paint/discardable_image_map.h
@@ -70,6 +70,11 @@ base::flat_map<PaintImage::Id, PaintImage::DecodingMode> TakeDecodingModeMap(); + const std::vector<scoped_refptr<PaintWorkletInput>>& paint_worklet_inputs() + const { + return paint_worklet_inputs_; + } + private: friend class ScopedMetadataGenerator; friend class DiscardableImageMapTest; @@ -86,6 +91,8 @@ bool all_images_are_srgb_ = false; RTree<DrawImage> images_rtree_; + + std::vector<scoped_refptr<PaintWorkletInput>> paint_worklet_inputs_; }; } // namespace cc
diff --git a/cc/paint/discardable_image_map_unittest.cc b/cc/paint/discardable_image_map_unittest.cc index 8e4a073..4a6fae21 100644 --- a/cc/paint/discardable_image_map_unittest.cc +++ b/cc/paint/discardable_image_map_unittest.cc
@@ -732,6 +732,33 @@ EXPECT_DCHECK_DEATH(images[2]->frame_index()); } +TEST_F(DiscardableImageMapTest, GathersPaintWorklets) { + gfx::Rect visible_rect(1000, 1000); + FakeContentLayerClient content_layer_client; + content_layer_client.set_bounds(visible_rect.size()); + + gfx::Size image_size(100, 100); + PaintImage static_image = CreateDiscardablePaintImage(image_size); + scoped_refptr<TestPaintWorkletInput> input = + base::MakeRefCounted<TestPaintWorkletInput>(gfx::SizeF(image_size)); + PaintImage paint_worklet_image = CreatePaintWorkletPaintImage(input); + + PaintFlags flags; + content_layer_client.add_draw_image(static_image, gfx::Point(0, 0), flags); + content_layer_client.add_draw_image(paint_worklet_image, gfx::Point(100, 100), + flags); + + scoped_refptr<DisplayItemList> display_list = + content_layer_client.PaintContentsToDisplayList( + ContentLayerClient::PAINTING_BEHAVIOR_NORMAL); + display_list->GenerateDiscardableImagesMetadata(); + const auto& paint_worklet_inputs = + display_list->discardable_image_map().paint_worklet_inputs(); + + ASSERT_EQ(paint_worklet_inputs.size(), 1u); + EXPECT_EQ(paint_worklet_inputs[0], input); +} + TEST_F(DiscardableImageMapTest, CapturesImagesInPaintRecordShaders) { // Create the record to use in the shader. auto shader_record = sk_make_sp<PaintOpBuffer>();
diff --git a/cc/raster/raster_source.cc b/cc/raster/raster_source.cc index 8c490e48..76c8859 100644 --- a/cc/raster/raster_source.cc +++ b/cc/raster/raster_source.cc
@@ -255,6 +255,13 @@ display_list_->EmitTraceSnapshot(); } +std::vector<scoped_refptr<PaintWorkletInput>> +RasterSource::GetPaintWorkletInputs() const { + if (!display_list_) + return {}; + return display_list_->discardable_image_map().paint_worklet_inputs(); +} + RasterSource::PlaybackSettings::PlaybackSettings() = default; RasterSource::PlaybackSettings::PlaybackSettings(const PlaybackSettings&) =
diff --git a/cc/raster/raster_source.h b/cc/raster/raster_source.h index 4866e607..25bd76b 100644 --- a/cc/raster/raster_source.h +++ b/cc/raster/raster_source.h
@@ -113,6 +113,8 @@ return display_list_; } + std::vector<scoped_refptr<PaintWorkletInput>> GetPaintWorkletInputs() const; + float recording_scale_factor() const { return recording_scale_factor_; } SkColor background_color() const { return background_color_; }
diff --git a/cc/test/fake_mask_layer_impl.cc b/cc/test/fake_mask_layer_impl.cc index 925fe389..d71d93c 100644 --- a/cc/test/fake_mask_layer_impl.cc +++ b/cc/test/fake_mask_layer_impl.cc
@@ -15,7 +15,7 @@ : PictureLayerImpl(tree_impl, id, mask_type) { SetBounds(raster_source->GetSize()); Region region; - UpdateRasterSource(raster_source, ®ion, nullptr); + UpdateRasterSource(raster_source, ®ion, nullptr, nullptr); } std::unique_ptr<FakeMaskLayerImpl> FakeMaskLayerImpl::Create(
diff --git a/cc/test/fake_picture_layer_impl.cc b/cc/test/fake_picture_layer_impl.cc index 38ed760..73f05851 100644 --- a/cc/test/fake_picture_layer_impl.cc +++ b/cc/test/fake_picture_layer_impl.cc
@@ -100,9 +100,11 @@ DCHECK(layer_tree_impl()->IsPendingTree()); Region invalidation_temp = invalidation; const PictureLayerTilingSet* pending_set = nullptr; + const PaintWorkletRecordMap* pending_paint_worklet_records = nullptr; set_gpu_raster_max_texture_size( layer_tree_impl()->GetDeviceViewport().size()); - UpdateRasterSource(raster_source, &invalidation_temp, pending_set); + UpdateRasterSource(raster_source, &invalidation_temp, pending_set, + pending_paint_worklet_records); } void FakePictureLayerImpl::CreateAllTiles() {
diff --git a/cc/trees/layer_tree_host_impl_unittest.cc b/cc/trees/layer_tree_host_impl_unittest.cc index 1b24d40..3138584 100644 --- a/cc/trees/layer_tree_host_impl_unittest.cc +++ b/cc/trees/layer_tree_host_impl_unittest.cc
@@ -12831,7 +12831,7 @@ layer->SetDrawsContent(true); layer->tilings()->AddTiling(gfx::AxisTransform2d(), raster_source_with_tiles); layer->UpdateRasterSource(raster_source_with_tiles, &empty_invalidation, - nullptr); + nullptr, nullptr); layer->tilings()->tiling_at(0)->set_resolution( TileResolution::HIGH_RESOLUTION); layer->tilings()->tiling_at(0)->CreateAllTilesForTesting();
diff --git a/chrome/VERSION b/chrome/VERSION index a63656e2..0684ea3 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=77 MINOR=0 -BUILD=3822 +BUILD=3823 PATCH=0
diff --git a/chrome/android/features/autofill_assistant/BUILD.gn b/chrome/android/features/autofill_assistant/BUILD.gn index ab79f09e..543701312 100644 --- a/chrome/android/features/autofill_assistant/BUILD.gn +++ b/chrome/android/features/autofill_assistant/BUILD.gn
@@ -153,6 +153,7 @@ testonly = true java_files = [ + "javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantInfoBoxUiTest.java", "javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiTest.java", "javatests/src/org/chromium/chrome/browser/autofill_assistant/EditDistanceTest.java", ] @@ -165,6 +166,7 @@ "//chrome/android:chrome_test_util_java", "//content/public/test/android:content_java_test_support", "//net/android:net_java_test_support", + "//third_party/android_deps:com_android_support_design_java", "//third_party/android_deps:com_android_support_recyclerview_v7_java", "//third_party/android_support_test_runner:runner_java", "//third_party/junit",
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/details/AssistantDetailsViewBinder.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/details/AssistantDetailsViewBinder.java index 73058fd6..c0b2b6ca 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/details/AssistantDetailsViewBinder.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/details/AssistantDetailsViewBinder.java
@@ -171,6 +171,7 @@ hideIfEmpty(viewHolder.mDescriptionLine1View); hideIfEmpty(viewHolder.mDescriptionLine2View); hideIfEmpty(viewHolder.mDescriptionLine3View); + hideIfEmpty(viewHolder.mPriceAttributionView); // If no price provided, hide the price view (containing separator, price label, and price). viewHolder.mPriceView.setVisibility(
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/infobox/AssistantInfoBox.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/infobox/AssistantInfoBox.java index f7d8920..f3772c24 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/infobox/AssistantInfoBox.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/infobox/AssistantInfoBox.java
@@ -20,11 +20,11 @@ this.mExplanation = explanation; } - String getImagePath() { + public String getImagePath() { return mImagePath; } - String getExplanation() { + public String getExplanation() { return mExplanation; }
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/infobox/AssistantInfoBoxCoordinator.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/infobox/AssistantInfoBoxCoordinator.java index da49b6ed7..8911f7c 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/infobox/AssistantInfoBoxCoordinator.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/infobox/AssistantInfoBoxCoordinator.java
@@ -10,6 +10,9 @@ import org.chromium.chrome.autofill_assistant.R; import org.chromium.chrome.browser.autofill_assistant.infobox.AssistantInfoBoxViewBinder.ViewHolder; +import org.chromium.chrome.browser.image_fetcher.ImageFetcher; +import org.chromium.chrome.browser.image_fetcher.ImageFetcherConfig; +import org.chromium.chrome.browser.image_fetcher.ImageFetcherFactory; import org.chromium.ui.modelutil.PropertyModelChangeProcessor; /** @@ -20,10 +23,17 @@ private AssistantInfoBoxViewBinder mViewBinder; public AssistantInfoBoxCoordinator(Context context, AssistantInfoBoxModel model) { + this(context, model, + ImageFetcherFactory.createImageFetcher(ImageFetcherConfig.DISK_CACHE_ONLY)); + } + + /** Used for testing to inject an image fetcher. */ + public AssistantInfoBoxCoordinator( + Context context, AssistantInfoBoxModel model, ImageFetcher imageFetcher) { mView = LayoutInflater.from(context).inflate( R.layout.autofill_assistant_info_box, /* root= */ null); ViewHolder viewHolder = new ViewHolder(context, mView); - mViewBinder = new AssistantInfoBoxViewBinder(context); + mViewBinder = new AssistantInfoBoxViewBinder(context, imageFetcher); PropertyModelChangeProcessor.create(model, viewHolder, mViewBinder); // InfoBox view is initially hidden.
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/infobox/AssistantInfoBoxViewBinder.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/infobox/AssistantInfoBoxViewBinder.java index d6393ef..a7fd3828 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/infobox/AssistantInfoBoxViewBinder.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/infobox/AssistantInfoBoxViewBinder.java
@@ -12,8 +12,6 @@ import org.chromium.chrome.autofill_assistant.R; import org.chromium.chrome.browser.image_fetcher.ImageFetcher; -import org.chromium.chrome.browser.image_fetcher.ImageFetcherConfig; -import org.chromium.chrome.browser.image_fetcher.ImageFetcherFactory; import org.chromium.ui.modelutil.PropertyKey; import org.chromium.ui.modelutil.PropertyModelChangeProcessor; @@ -39,9 +37,10 @@ private final Context mContext; private ImageFetcher mImageFetcher; - AssistantInfoBoxViewBinder(Context context) { + /** Allows to inject an image fetcher for testing. */ + AssistantInfoBoxViewBinder(Context context, ImageFetcher imageFetcher) { mContext = context; - mImageFetcher = ImageFetcherFactory.createImageFetcher(ImageFetcherConfig.DISK_CACHE_ONLY); + mImageFetcher = imageFetcher; } /**
diff --git a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantInfoBoxUiTest.java b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantInfoBoxUiTest.java new file mode 100644 index 0000000..7d7a161b --- /dev/null +++ b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantInfoBoxUiTest.java
@@ -0,0 +1,169 @@ +// 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. + +package org.chromium.chrome.browser.autofill_assistant; + +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.support.design.widget.CoordinatorLayout; +import android.support.test.InstrumentationRegistry; +import android.support.test.filters.SmallTest; +import android.view.Gravity; +import android.view.ViewGroup; +import android.widget.TextView; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.chromium.base.Callback; +import org.chromium.base.ThreadUtils; +import org.chromium.base.test.util.CommandLineFlags; +import org.chromium.chrome.autofill_assistant.R; +import org.chromium.chrome.browser.ChromeSwitches; +import org.chromium.chrome.browser.autofill_assistant.infobox.AssistantInfoBox; +import org.chromium.chrome.browser.autofill_assistant.infobox.AssistantInfoBoxCoordinator; +import org.chromium.chrome.browser.autofill_assistant.infobox.AssistantInfoBoxModel; +import org.chromium.chrome.browser.customtabs.CustomTabActivity; +import org.chromium.chrome.browser.customtabs.CustomTabActivityTestRule; +import org.chromium.chrome.browser.customtabs.CustomTabsTestUtils; +import org.chromium.chrome.browser.image_fetcher.ImageFetcher; +import org.chromium.chrome.browser.image_fetcher.ImageFetcherConfig; +import org.chromium.chrome.test.ChromeJUnit4ClassRunner; +import org.chromium.content_public.browser.test.util.TestThreadUtils; + +import jp.tomorrowkey.android.gifplayer.BaseGifImage; + +/** + * Tests for the Autofill Assistant infobox. + */ +@RunWith(ChromeJUnit4ClassRunner.class) +@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) +public class AutofillAssistantInfoBoxUiTest { + private class MockImageFetcher extends ImageFetcher { + @Override + public void fetchGif(String url, String clientName, Callback<BaseGifImage> callback) {} + + @Override + public void fetchImage( + String url, String clientName, int width, int height, Callback<Bitmap> callback) { + callback.onResult(BitmapFactory.decodeResource( + getActivity().getResources(), R.drawable.btn_close)); + } + + @Override + public void clear() {} + + @Override + public @ImageFetcherConfig int getConfig() { + return ImageFetcherConfig.IN_MEMORY_ONLY; + } + + @Override + public void destroy() {} + } + + @Rule + public CustomTabActivityTestRule mCustomTabActivityTestRule = new CustomTabActivityTestRule(); + + @Before + public void setUp() throws Exception { + mCustomTabActivityTestRule.startCustomTabActivityWithIntent( + CustomTabsTestUtils.createMinimalCustomTabIntent( + InstrumentationRegistry.getTargetContext(), "about:blank")); + } + + private CustomTabActivity getActivity() { + return mCustomTabActivityTestRule.getActivity(); + } + + private TextView getExplanationView(AssistantInfoBoxCoordinator coordinator) { + return coordinator.getView().findViewById(R.id.info_box_explanation); + } + + /** Creates a coordinator for use in UI tests, and adds it to the global view hierarchy. */ + private AssistantInfoBoxCoordinator createCoordinator(AssistantInfoBoxModel model) { + ThreadUtils.assertOnUiThread(); + AssistantInfoBoxCoordinator coordinator = new AssistantInfoBoxCoordinator( + InstrumentationRegistry.getTargetContext(), model, new MockImageFetcher()); + + CoordinatorLayout.LayoutParams lp = new CoordinatorLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); + lp.gravity = Gravity.BOTTOM; + + ViewGroup chromeCoordinatorView = getActivity().findViewById(R.id.coordinator); + chromeCoordinatorView.addView(coordinator.getView(), lp); + + return coordinator; + } + + /** Tests assumptions about the initial state of the infobox. */ + @Test + @SmallTest + public void testInitialState() { + TestThreadUtils.runOnUiThreadBlocking(() -> { + AssistantInfoBoxModel model = new AssistantInfoBoxModel(); + AssistantInfoBoxCoordinator coordinator = createCoordinator(model); + + Assert.assertNull(model.get(AssistantInfoBoxModel.INFO_BOX)); + Assert.assertFalse(coordinator.getView().isShown()); + }); + } + + /** Tests for an infobox with a message, but without an image. */ + @Test + @SmallTest + public void testMessageNoImage() { + TestThreadUtils.runOnUiThreadBlocking(() -> { + AssistantInfoBoxModel model = new AssistantInfoBoxModel(); + AssistantInfoBoxCoordinator coordinator = createCoordinator(model); + + AssistantInfoBox infoBox = new AssistantInfoBox("", "Message"); + model.set(AssistantInfoBoxModel.INFO_BOX, infoBox); + + Assert.assertTrue(getExplanationView(coordinator).isShown()); + Assert.assertNull("Image should not be set", + getExplanationView(coordinator).getCompoundDrawables()[1]); + Assert.assertEquals( + infoBox.getExplanation(), getExplanationView(coordinator).getText()); + }); + } + + /** Tests for an infobox with message and image. */ + @Test + @SmallTest + public void testImage() { + TestThreadUtils.runOnUiThreadBlocking(() -> { + AssistantInfoBoxModel model = new AssistantInfoBoxModel(); + AssistantInfoBoxCoordinator coordinator = createCoordinator(model); + + AssistantInfoBox infoBox = new AssistantInfoBox("x", "Message"); + model.set(AssistantInfoBoxModel.INFO_BOX, infoBox); + + Assert.assertTrue(getExplanationView(coordinator).isShown()); + Assert.assertNotNull("Image should be set", + getExplanationView(coordinator).getCompoundDrawables()[1]); + Assert.assertEquals( + infoBox.getExplanation(), getExplanationView(coordinator).getText()); + }); + } + + @Test + @SmallTest + public void testVisibility() { + TestThreadUtils.runOnUiThreadBlocking(() -> { + AssistantInfoBoxModel model = new AssistantInfoBoxModel(); + AssistantInfoBoxCoordinator coordinator = createCoordinator(model); + + AssistantInfoBox infoBox = new AssistantInfoBox("", ""); + model.set(AssistantInfoBoxModel.INFO_BOX, infoBox); + Assert.assertTrue(coordinator.getView().isShown()); + + model.set(AssistantInfoBoxModel.INFO_BOX, null); + Assert.assertFalse(coordinator.getView().isShown()); + }); + } +}
diff --git a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingComponentBridge.java b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingComponentBridge.java index 5b383b2..e2198e83 100644 --- a/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingComponentBridge.java +++ b/chrome/android/features/keyboard_accessory/internal/java/src/org/chromium/chrome/browser/keyboard_accessory/ManualFillingComponentBridge.java
@@ -76,8 +76,8 @@ : "Controller has been destroyed but the bridge wasn't cleaned up!"; ManualFillingMetricsRecorder.recordActionSelected( AccessoryAction.GENERATE_PASSWORD_AUTOMATIC); - mManualFillingComponent.dismiss(); - nativeOnGenerationRequested(mNativeView); + nativeOnOptionSelected( + mNativeView, AccessoryAction.GENERATE_PASSWORD_AUTOMATIC); })}; } else { generationAction = new Action[0]; @@ -180,7 +180,6 @@ long nativeManualFillingViewAndroid, int tabType, UserInfoField userInfoField); private native void nativeOnOptionSelected( long nativeManualFillingViewAndroid, int accessoryAction); - private native void nativeOnGenerationRequested(long nativeManualFillingViewAndroid); private static native void nativeCachePasswordSheetDataForTesting( WebContents webContents, String[] userNames, String[] passwords);
diff --git a/chrome/android/profiles/newest.txt b/chrome/android/profiles/newest.txt index 18dd791b..6d75ab1 100644 --- a/chrome/android/profiles/newest.txt +++ b/chrome/android/profiles/newest.txt
@@ -1 +1 @@ -chromeos-chrome-amd64-77.0.3820.0_rc-r1-merged.afdo.bz2 \ No newline at end of file +chromeos-chrome-amd64-77.0.3822.0_rc-r1-merged.afdo.bz2 \ No newline at end of file
diff --git a/chrome/android/webapk/libs/client/src/org/chromium/webapk/lib/client/WebApkValidator.java b/chrome/android/webapk/libs/client/src/org/chromium/webapk/lib/client/WebApkValidator.java index 00370144..c74d78df 100644 --- a/chrome/android/webapk/libs/client/src/org/chromium/webapk/lib/client/WebApkValidator.java +++ b/chrome/android/webapk/libs/client/src/org/chromium/webapk/lib/client/WebApkValidator.java
@@ -45,6 +45,7 @@ private static byte[] sExpectedSignature; private static byte[] sCommentSignedPublicKeyBytes; private static PublicKey sCommentSignedPublicKey; + private static boolean sDisableValidation; private static boolean sOverrideValidationForTesting; /** @@ -188,7 +189,8 @@ * @return true iff the WebAPK is installed and passes security checks */ public static boolean isValidWebApk(Context context, String webappPackageName) { - if (sExpectedSignature == null || sCommentSignedPublicKeyBytes == null) { + if ((sExpectedSignature == null || sCommentSignedPublicKeyBytes == null) + && !sDisableValidation) { Log.wtf(TAG, "WebApk validation failure - expected signature not set." + "missing call to WebApkValidator.initWithBrowserHostSignature"); @@ -208,7 +210,7 @@ if (isNotWebApkQuick(packageInfo)) { return false; } - if (sOverrideValidationForTesting) { + if (sDisableValidation || sOverrideValidationForTesting) { if (DEBUG) { Log.d(TAG, "Ok! Looks like a WebApk (has start url) and validation is disabled."); } @@ -354,7 +356,7 @@ } /** - * Disables all verification performed by this class. This is meant only for development with + * Disables all validation performed by this class. This is meant only for development with * unsigned WebApks and should never be enabled in a real build. */ public static void disableValidationForTesting() { @@ -362,6 +364,14 @@ } /** + * Disables all validation performed by this class. This should only be called when some other + * means of validating WebApks is already present and otherwise should never be called. + */ + public static void disableValidationUnsafe() { + sDisableValidation = true; + } + + /** * Lazy evaluate the creation of the Public Key as the KeyFactories may not yet be initialized. * @return The decoded PublicKey or null */
diff --git a/chrome/android/webapk/shell_apk/request_update_for_version.gni b/chrome/android/webapk/shell_apk/request_update_for_version.gni index a45fe14..a57c8e7 100644 --- a/chrome/android/webapk/shell_apk/request_update_for_version.gni +++ b/chrome/android/webapk/shell_apk/request_update_for_version.gni
@@ -6,4 +6,4 @@ # if the WebAPK's ShellAPK version is less than # |request_update_for_shell_apk_version|. The version should be incremented # after a new ShellAPK has been uploaded to the WebAPK Minting Server. -request_update_for_shell_apk_version = 63 +request_update_for_shell_apk_version = 89
diff --git a/chrome/app/chromeos_strings.grdp b/chrome/app/chromeos_strings.grdp index af2b73c..ced3ad1 100644 --- a/chrome/app/chromeos_strings.grdp +++ b/chrome/app/chromeos_strings.grdp
@@ -4009,6 +4009,9 @@ </message> <!-- Strings for per-account Migration welcome screen --> + <message name="IDS_ACCOUNT_MIGRATION_WELCOME_PAGE_TITLE" desc="Title for the Account Migration Welcome page."> + Sign in again + </message> <message name="IDS_ACCOUNT_MIGRATION_WELCOME_TITLE" desc="Title for the Account Migration Welcome screen."> Sign in again to update <ph name="USER_EMAIL">$1<ex>john.doe@example.com</ex></ph> </message>
diff --git a/chrome/app/settings_strings.grdp b/chrome/app/settings_strings.grdp index 45ab61c..2138406 100644 --- a/chrome/app/settings_strings.grdp +++ b/chrome/app/settings_strings.grdp
@@ -3696,12 +3696,21 @@ <message name="IDS_SETTINGS_ACCOUNT_MANAGER_UNMIGRATED_ACCOUNT_PLACEHOLDER" desc="Placeholder text for the unmigrated account in Account Manager."> Not updated yet </message> + <message name="IDS_SETTINGS_ACCOUNT_MANAGER_MORE_ACTIONS_TOOLTIP" desc="Tooltip text (shows on hover or for screenreaders) for a button that shows a menu with more actions when clicked or tapped."> + More actions, <ph name="EMAIL">$1<ex>abcd@google.com</ex></ph> + </message> <message name="IDS_SETTINGS_ACCOUNT_MANAGER_MIGRATION_LABEL" desc="Label of the migration button on Account Manager Settings page."> Update account </message> <message name="IDS_SETTINGS_ACCOUNT_MANAGER_REAUTHENTICATION_LABEL" desc="Label of the re-authentication button on Account Manager Settings page."> Sign in </message> + <message name="IDS_SETTINGS_ACCOUNT_MANAGER_MIGRATION_TOOLTIP" desc="Tooltip text (shows on hover or for screenreaders) for the migration button on Account Manager Settings page."> + Update account, <ph name="EMAIL">$1<ex>abcd@google.com</ex></ph> + </message> + <message name="IDS_SETTINGS_ACCOUNT_MANAGER_REAUTHENTICATION_TOOLTIP" desc="Tooltip text (shows on hover or for screenreaders) for the re-authentication button on Account Manager Settings page."> + Sign in, <ph name="EMAIL">$1<ex>abcd@google.com</ex></ph> + </message> <message name="IDS_SETTINGS_ACCOUNT_MANAGER_REMOVE_ACCOUNT_LABEL" desc="Label of the Remove account button in Account Manager."> Remove this account </message>
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 67d0fbcd..e3a635c 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -5345,6 +5345,10 @@ sources += [ "android/download/mock_download_controller.cc", "android/download/mock_download_controller.h", + "autofill/mock_address_accessory_controller.cc", + "autofill/mock_address_accessory_controller.h", + "autofill/mock_manual_filling_view.cc", + "autofill/mock_manual_filling_view.h", ] deps += [ "//chrome/android:test_support_jni_headers" ] } else {
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index b7af879..efdcad4c 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -2365,6 +2365,10 @@ flag_descriptions::kFileManagerFeedbackPanelName, flag_descriptions::kFileManagerFeedbackPanelDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kEnableFileManagerFeedbackPanel)}, + {"file-manager-format-dialog", + flag_descriptions::kFileManagerFormatDialogName, + flag_descriptions::kFileManagerFormatDialogDescription, kOsCrOS, + FEATURE_VALUE_TYPE(chromeos::features::kEnableFileManagerFormatDialog)}, {"file-manager-piex-wasm", flag_descriptions::kFileManagerPiexWasmName, flag_descriptions::kFileManagerPiexWasmDescription, kOsCrOS, FEATURE_VALUE_TYPE(chromeos::features::kEnableFileManagerPiexWasm)},
diff --git a/chrome/browser/about_flags_unittest.cc b/chrome/browser/about_flags_unittest.cc index 55e33882..de09cde 100644 --- a/chrome/browser/about_flags_unittest.cc +++ b/chrome/browser/about_flags_unittest.cc
@@ -176,7 +176,7 @@ << base::JoinString(missing_flags, "\n "); } -TEST(AboutFlagsTest, DISABLED_EveryFlagHasNonEmptyOwners) { +TEST(AboutFlagsTest, EveryFlagHasNonEmptyOwners) { FlagMetadataMap metadata = LoadFlagMetadata(); std::vector<std::string> sad_flags;
diff --git a/chrome/browser/android/explore_sites/history_statistics_reporter.cc b/chrome/browser/android/explore_sites/history_statistics_reporter.cc index 65a734c..e545087 100644 --- a/chrome/browser/android/explore_sites/history_statistics_reporter.cc +++ b/chrome/browser/android/explore_sites/history_statistics_reporter.cc
@@ -38,7 +38,6 @@ : history_service_(history_service), prefs_(prefs), clock_(clock), - cancelable_task_tracker_(new base::CancelableTaskTracker()), history_service_observer_(this), weak_ptr_factory_(this) {} @@ -92,9 +91,9 @@ void HistoryStatisticsReporter::ComputeStatistics() { history_service_->CountUniqueHostsVisitedLastMonth( - base::BindRepeating(&HistoryStatisticsReporter::ReportStatistics, - weak_ptr_factory_.GetWeakPtr()), - cancelable_task_tracker_.get()); + base::BindOnce(&HistoryStatisticsReporter::ReportStatistics, + weak_ptr_factory_.GetWeakPtr()), + &cancelable_task_tracker_); } void HistoryStatisticsReporter::ReportStatistics(
diff --git a/chrome/browser/android/explore_sites/history_statistics_reporter.h b/chrome/browser/android/explore_sites/history_statistics_reporter.h index b25bccf1a..58867f4 100644 --- a/chrome/browser/android/explore_sites/history_statistics_reporter.h +++ b/chrome/browser/android/explore_sites/history_statistics_reporter.h
@@ -10,6 +10,7 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/scoped_observer.h" +#include "base/task/cancelable_task_tracker.h" #include "base/time/clock.h" #include "components/history/core/browser/history_service.h" #include "components/history/core/browser/history_service_observer.h" @@ -47,7 +48,7 @@ PrefService* prefs_; base::Clock* clock_; - std::unique_ptr<base::CancelableTaskTracker> cancelable_task_tracker_; + base::CancelableTaskTracker cancelable_task_tracker_; ScopedObserver<history::HistoryService, history::HistoryServiceObserver> history_service_observer_; bool attempted_to_report_once_ = false;
diff --git a/chrome/browser/android/webapk/webapk_update_manager.cc b/chrome/browser/android/webapk/webapk_update_manager.cc index b8b4a85..9772c2b 100644 --- a/chrome/browser/android/webapk/webapk_update_manager.cc +++ b/chrome/browser/android/webapk/webapk_update_manager.cc
@@ -14,6 +14,7 @@ #include "base/files/file_path.h" #include "base/strings/string16.h" #include "base/threading/thread_task_runner_handle.h" +#include "chrome/browser/android/color_helpers.h" #include "chrome/browser/android/shortcut_info.h" #include "chrome/browser/android/webapk/webapk_install_service.h" #include "chrome/browser/android/webapk/webapk_installer.h" @@ -88,8 +89,8 @@ info.display = static_cast<blink::WebDisplayMode>(java_display_mode); info.orientation = static_cast<blink::WebScreenOrientationLockType>(java_orientation); - info.theme_color = (int64_t)java_theme_color; - info.background_color = (int64_t)java_background_color; + info.theme_color = JavaColorToOptionalSkColor(java_theme_color); + info.background_color = JavaColorToOptionalSkColor(java_background_color); info.best_primary_icon_url = GURL(ConvertJavaStringToUTF8(env, java_primary_icon_url)); info.best_badge_icon_url =
diff --git a/chrome/browser/autocomplete/shortcuts_provider_extension_unittest.cc b/chrome/browser/autocomplete/shortcuts_provider_extension_unittest.cc index 0629215..e59730d 100644 --- a/chrome/browser/autocomplete/shortcuts_provider_extension_unittest.cc +++ b/chrome/browser/autocomplete/shortcuts_provider_extension_unittest.cc
@@ -40,7 +40,8 @@ struct TestShortcutData shortcut_test_db[] = { {"BD85DBA2-8C29-49F9-84AE-48E1E90880F1", "echo echo", "echo echo", "chrome-extension://cedabbhfglmiikkmdgcpjdkocfcmbkee/?q=echo", - "Run Echo command: echo", "0,0", "Echo", "0,4", ui::PAGE_TRANSITION_TYPED, + AutocompleteMatch::DocumentType::NONE, "Run Echo command: echo", "0,0", + "Echo", "0,4", ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::EXTENSION_APP_DEPRECATED, "", 1, 1}, };
diff --git a/chrome/browser/autofill/manual_filling_controller.h b/chrome/browser/autofill/manual_filling_controller.h index f279ae3..a077ba4 100644 --- a/chrome/browser/autofill/manual_filling_controller.h +++ b/chrome/browser/autofill/manual_filling_controller.h
@@ -71,15 +71,21 @@ // Requests to show the accessory bar. The accessory will only be shown // when the keyboard becomes visible. + // TODO(crbug.com/965478): Rename method to reflect latest logic changes. virtual void ShowWhenKeyboardIsVisible(FillingSource source) = 0; // Requests to show the touch to fill sheet. virtual void ShowTouchToFillSheet( const autofill::AccessorySheetData& data) = 0; + // This signals that the accessory data corresponding to |source| doesn't + // need to be shown anymore. If no FillingSource needs to be shown, the + // accessory sheet and bar will be hidden. + virtual void DeactivateFillingSource(FillingSource source) = 0; + // Requests to hide the accessory. This hides both the accessory sheet // (if open) and the accessory bar. - virtual void Hide(FillingSource source) = 0; + virtual void Hide() = 0; // Notifies the view that automatic password generation status changed. // @@ -104,14 +110,6 @@ virtual void OnOptionSelected( autofill::AccessoryAction selected_action) const = 0; - // Called by the UI code to signal that the user requested password - // generation. This should prompt a modal dialog with the generated password. - // - // TODO(crbug.com/905669): This controller doesn't need to know about password - // generation. Generalize this to forward an action request from the UI to a - // type-specific accessory controller. - virtual void OnGenerationRequested() = 0; - // Gets an icon for the currently focused frame and passes it to // |icon_callback|. The callback is invoked with an image unless an icon for // a new origin was called. In the latter case, the callback is dropped.
diff --git a/chrome/browser/autofill/manual_filling_controller_impl.cc b/chrome/browser/autofill/manual_filling_controller_impl.cc index 78021f9..085bc282 100644 --- a/chrome/browser/autofill/manual_filling_controller_impl.cc +++ b/chrome/browser/autofill/manual_filling_controller_impl.cc
@@ -11,7 +11,6 @@ #include "chrome/browser/autofill/address_accessory_controller.h" #include "chrome/browser/password_manager/password_accessory_controller.h" #include "chrome/browser/password_manager/password_accessory_metrics_util.h" -#include "chrome/browser/password_manager/password_generation_controller.h" #include "chrome/browser/password_manager/touch_to_fill_controller.h" #include "chrome/browser/profiles/profile.h" #include "components/autofill/core/common/autofill_features.h" @@ -44,21 +43,17 @@ content::WebContents* web_contents, base::WeakPtr<PasswordAccessoryController> pwd_controller, base::WeakPtr<AddressAccessoryController> address_controller, - PasswordGenerationController* pwd_generation_controller_for_testing, std::unique_ptr<ManualFillingViewInterface> view) { DCHECK(web_contents) << "Need valid WebContents to attach controller to!"; DCHECK(!FromWebContents(web_contents)) << "Controller already attached!"; DCHECK(pwd_controller); DCHECK(address_controller); - DCHECK(pwd_generation_controller_for_testing); DCHECK(view); web_contents->SetUserData( - UserDataKey(), - base::WrapUnique(new ManualFillingControllerImpl( - web_contents, std::move(pwd_controller), - std::move(address_controller), pwd_generation_controller_for_testing, - std::move(view)))); + UserDataKey(), base::WrapUnique(new ManualFillingControllerImpl( + web_contents, std::move(pwd_controller), + std::move(address_controller), std::move(view)))); FromWebContents(web_contents)->Initialize(); } @@ -111,7 +106,8 @@ view_->ShowTouchToFillSheet(); } -void ManualFillingControllerImpl::Hide(FillingSource source) { +void ManualFillingControllerImpl::DeactivateFillingSource( + FillingSource source) { if (source == FillingSource::AUTOFILL && !base::FeatureList::IsEnabled( autofill::features::kAutofillKeyboardAccessory)) { @@ -123,6 +119,10 @@ view_->Hide(); } +void ManualFillingControllerImpl::Hide() { + view_->Hide(); +} + void ManualFillingControllerImpl::OnFillingTriggered( AccessoryTabType type, const autofill::UserInfo::Field& selection) { @@ -136,16 +136,6 @@ GetControllerForAction(selected_action)->OnOptionSelected(selected_action); } -void ManualFillingControllerImpl::OnGenerationRequested() { - PasswordGenerationController* pwd_generation_controller = - pwd_generation_controller_for_testing_ - ? pwd_generation_controller_for_testing_ - : PasswordGenerationController::GetIfExisting(web_contents_); - - DCHECK(pwd_generation_controller); - pwd_generation_controller->OnGenerationRequested(); -} - void ManualFillingControllerImpl::GetFavicon( int desired_size_in_pixel, base::OnceCallback<void(const gfx::Image&)> icon_callback) { @@ -193,13 +183,10 @@ content::WebContents* web_contents, base::WeakPtr<PasswordAccessoryController> pwd_controller, base::WeakPtr<AddressAccessoryController> address_controller, - PasswordGenerationController* pwd_generation_controller_for_testing, std::unique_ptr<ManualFillingViewInterface> view) : web_contents_(web_contents), pwd_controller_(std::move(pwd_controller)), address_controller_(std::move(address_controller)), - pwd_generation_controller_for_testing_( - pwd_generation_controller_for_testing), view_(std::move(view)) {} AccessoryController* ManualFillingControllerImpl::GetControllerForTab( @@ -226,6 +213,7 @@ switch (action) { case AccessoryAction::GENERATE_PASSWORD_MANUAL: case AccessoryAction::MANAGE_PASSWORDS: + case AccessoryAction::GENERATE_PASSWORD_AUTOMATIC: return pwd_controller_.get(); case AccessoryAction::MANAGE_ADDRESSES: return address_controller_.get(); @@ -233,7 +221,6 @@ // TODO(crbug.com/902425): Return credit card controller. case AccessoryAction::AUTOFILL_SUGGESTION: case AccessoryAction::COUNT: - case AccessoryAction::GENERATE_PASSWORD_AUTOMATIC: break; // Intentional failure; } NOTREACHED() << "Controller not defined for action: "
diff --git a/chrome/browser/autofill/manual_filling_controller_impl.h b/chrome/browser/autofill/manual_filling_controller_impl.h index 27182a8e..a1e2610 100644 --- a/chrome/browser/autofill/manual_filling_controller_impl.h +++ b/chrome/browser/autofill/manual_filling_controller_impl.h
@@ -19,7 +19,6 @@ } class AccessoryController; class PasswordAccessoryController; -class PasswordGenerationController; class TouchToFillController; // Use ManualFillingController::GetOrCreate to obtain instances of this class. @@ -36,13 +35,13 @@ void OnFilledIntoFocusedField(autofill::FillingStatus status) override; void ShowWhenKeyboardIsVisible(FillingSource source) override; void ShowTouchToFillSheet(const autofill::AccessorySheetData& data) override; - void Hide(FillingSource source) override; + void DeactivateFillingSource(FillingSource source) override; + void Hide() override; void OnAutomaticGenerationStatusChanged(bool available) override; void OnFillingTriggered(autofill::AccessoryTabType type, const autofill::UserInfo::Field& selection) override; void OnOptionSelected( autofill::AccessoryAction selected_action) const override; - void OnGenerationRequested() override; void GetFavicon( int desired_size_in_pixel, base::OnceCallback<void(const gfx::Image&)> icon_callback) override; @@ -58,7 +57,6 @@ content::WebContents* web_contents, base::WeakPtr<PasswordAccessoryController> pwd_controller, base::WeakPtr<autofill::AddressAccessoryController> address_controller, - PasswordGenerationController* pwd_generation_controller_for_testing, std::unique_ptr<ManualFillingViewInterface> test_view); #if defined(UNIT_TEST) @@ -90,7 +88,6 @@ content::WebContents* web_contents, base::WeakPtr<PasswordAccessoryController> pwd_controller, base::WeakPtr<autofill::AddressAccessoryController> address_controller, - PasswordGenerationController* pwd_generation_controller_for_testing, std::unique_ptr<ManualFillingViewInterface> view); // Returns the controller that is responsible for a tab of given |type|. @@ -115,11 +112,6 @@ // The touch to fill controller object to forward view requests to. base::WeakPtr<TouchToFillController> touch_to_fill_controller_; - // A password generation controller used in tests which receives requests - // from the view. - PasswordGenerationController* pwd_generation_controller_for_testing_ = - nullptr; - // Hold the native instance of the view. Must be last declared and initialized // member so the view can be created in the constructor with a fully set up // controller instance.
diff --git a/chrome/browser/autofill/manual_filling_controller_impl_unittest.cc b/chrome/browser/autofill/manual_filling_controller_impl_unittest.cc index 81ba628..169d3166 100644 --- a/chrome/browser/autofill/manual_filling_controller_impl_unittest.cc +++ b/chrome/browser/autofill/manual_filling_controller_impl_unittest.cc
@@ -13,10 +13,9 @@ #include "base/callback.h" #include "base/strings/utf_string_conversions.h" #include "base/test/scoped_feature_list.h" -#include "chrome/browser/autofill/address_accessory_controller.h" -#include "chrome/browser/autofill/manual_filling_view_interface.h" +#include "chrome/browser/autofill/mock_address_accessory_controller.h" +#include "chrome/browser/autofill/mock_manual_filling_view.h" #include "chrome/browser/password_manager/password_accessory_controller.h" -#include "chrome/browser/password_manager/password_generation_controller.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "components/autofill/core/common/autofill_features.h" #include "components/password_manager/core/common/password_manager_features.h" @@ -25,7 +24,6 @@ namespace { using autofill::AccessoryAction; -using autofill::AddressAccessoryController; using autofill::mojom::FocusedFieldType; using testing::_; using testing::AnyNumber; @@ -43,6 +41,7 @@ const url::Origin&)); MOCK_METHOD1(OnFilledIntoFocusedField, void(autofill::FillingStatus)); MOCK_METHOD2(RefreshSuggestionsForField, void(FocusedFieldType, bool)); + MOCK_METHOD1(OnGenerationRequested, void(bool)); MOCK_METHOD0(DidNavigateMainFrame, void()); MOCK_METHOD2(GetFavicon, void(int, base::OnceCallback<void(const gfx::Image&)>)); @@ -50,53 +49,6 @@ MOCK_METHOD1(OnOptionSelected, void(AccessoryAction selected_action)); }; -class MockAddressAccessoryController : public AddressAccessoryController { - public: - MOCK_METHOD2( - SavePasswordsForOrigin, - void(const std::map<base::string16, const autofill::PasswordForm*>&, - const url::Origin&)); - MOCK_METHOD1(OnFillingTriggered, void(const autofill::UserInfo::Field&)); - MOCK_METHOD1(OnOptionSelected, void(AccessoryAction selected_action)); - MOCK_METHOD0(RefreshSuggestions, void()); -}; - -class MockPasswordGenerationController : public PasswordGenerationController { - public: - MOCK_METHOD2( - OnAutomaticGenerationAvailable, - void(const autofill::password_generation::PasswordGenerationUIData&, - const base::WeakPtr<password_manager::PasswordManagerDriver>&)); - MOCK_METHOD0(OnGenerationElementLostFocus, void()); - MOCK_METHOD0(OnGenerationRequested, void()); - MOCK_METHOD2(GeneratedPasswordAccepted, - void(const base::string16&, - base::WeakPtr<password_manager::PasswordManagerDriver>)); - MOCK_METHOD0(GeneratedPasswordRejected, void()); - MOCK_CONST_METHOD0(top_level_native_window, gfx::NativeWindow()); -}; - -// The mock view mocks the platform-specific implementation. That also means -// that we have to care about the lifespan of the Controller because that would -// usually be responsibility of the view. -class MockPasswordAccessoryView : public ManualFillingViewInterface { - public: - MockPasswordAccessoryView() = default; - - MOCK_METHOD1(OnItemsAvailable, void(const autofill::AccessorySheetData&)); - MOCK_METHOD1(OnFillingTriggered, void(const autofill::UserInfo::Field&)); - MOCK_METHOD0(OnViewDestroyed, void()); - MOCK_METHOD1(OnAutomaticGenerationStatusChanged, void(bool)); - MOCK_METHOD0(CloseAccessorySheet, void()); - MOCK_METHOD0(SwapSheetWithKeyboard, void()); - MOCK_METHOD0(ShowWhenKeyboardIsVisible, void()); - MOCK_METHOD0(ShowTouchToFillSheet, void()); - MOCK_METHOD0(Hide, void()); - - private: - DISALLOW_COPY_AND_ASSIGN(MockPasswordAccessoryView); -}; - autofill::AccessorySheetData dummy_accessory_sheet_data() { constexpr char kExampleAccessorySheetDataTitle[] = "Example title"; return autofill::AccessorySheetData( @@ -115,8 +67,8 @@ NavigateAndCommit(GURL(kExampleSite)); ManualFillingControllerImpl::CreateForWebContentsForTesting( web_contents(), mock_pwd_controller_.AsWeakPtr(), - mock_address_controller_.AsWeakPtr(), &mock_pwd_generation_controller_, - std::make_unique<StrictMock<MockPasswordAccessoryView>>()); + mock_address_controller_.AsWeakPtr(), + std::make_unique<StrictMock<MockManualFillingView>>()); NavigateAndCommit(GURL(kExampleSite)); } @@ -124,14 +76,13 @@ return ManualFillingControllerImpl::FromWebContents(web_contents()); } - MockPasswordAccessoryView* view() { - return static_cast<MockPasswordAccessoryView*>(controller()->view()); + MockManualFillingView* view() { + return static_cast<MockManualFillingView*>(controller()->view()); } protected: NiceMock<MockPasswordAccessoryController> mock_pwd_controller_; NiceMock<MockAddressAccessoryController> mock_address_controller_; - NiceMock<MockPasswordGenerationController> mock_pwd_generation_controller_; }; TEST_F(ManualFillingControllerTest, IsNotRecreatedForSameWebContents) { @@ -186,7 +137,7 @@ EXPECT_CALL(*view(), ShowWhenKeyboardIsVisible()); controller()->ShowWhenKeyboardIsVisible(FillingSource::PASSWORD_FALLBACKS); EXPECT_CALL(*view(), Hide()); - controller()->Hide(FillingSource::PASSWORD_FALLBACKS); + controller()->DeactivateFillingSource(FillingSource::PASSWORD_FALLBACKS); } TEST_F(ManualFillingControllerTest, RelaysShowTouchToFillSheet) { @@ -207,12 +158,12 @@ // Hiding just one of two active filling sources won't have any effect. EXPECT_CALL(*view(), Hide()).Times(0); - controller()->Hide(FillingSource::PASSWORD_FALLBACKS); + controller()->DeactivateFillingSource(FillingSource::PASSWORD_FALLBACKS); testing::Mock::VerifyAndClearExpectations(view()); // Hiding the remaining second source will result in the view being hidden. EXPECT_CALL(*view(), Hide()).Times(1); - controller()->Hide(FillingSource::AUTOFILL); + controller()->DeactivateFillingSource(FillingSource::AUTOFILL); } TEST_F(ManualFillingControllerTest, OnAutomaticGenerationStatusChanged) { @@ -252,9 +203,16 @@ controller()->OnOptionSelected(AccessoryAction::MANAGE_ADDRESSES); } -TEST_F(ManualFillingControllerTest, OnGenerationRequested) { - EXPECT_CALL(mock_pwd_generation_controller_, OnGenerationRequested()); - controller()->OnGenerationRequested(); +TEST_F(ManualFillingControllerTest, OnAutomaticGenerationRequested) { + EXPECT_CALL(mock_pwd_controller_, + OnOptionSelected(AccessoryAction::GENERATE_PASSWORD_AUTOMATIC)); + controller()->OnOptionSelected(AccessoryAction::GENERATE_PASSWORD_AUTOMATIC); +} + +TEST_F(ManualFillingControllerTest, OnManualGenerationRequested) { + EXPECT_CALL(mock_pwd_controller_, + OnOptionSelected(AccessoryAction::GENERATE_PASSWORD_MANUAL)); + controller()->OnOptionSelected(AccessoryAction::GENERATE_PASSWORD_MANUAL); } TEST_F(ManualFillingControllerTest, GetFavicon) {
diff --git a/chrome/browser/autofill/mock_address_accessory_controller.cc b/chrome/browser/autofill/mock_address_accessory_controller.cc new file mode 100644 index 0000000..1d6fee2 --- /dev/null +++ b/chrome/browser/autofill/mock_address_accessory_controller.cc
@@ -0,0 +1,8 @@ +// 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 "chrome/browser/autofill/mock_address_accessory_controller.h" + +MockAddressAccessoryController::MockAddressAccessoryController() = default; +MockAddressAccessoryController::~MockAddressAccessoryController() = default;
diff --git a/chrome/browser/autofill/mock_address_accessory_controller.h b/chrome/browser/autofill/mock_address_accessory_controller.h new file mode 100644 index 0000000..3b37062 --- /dev/null +++ b/chrome/browser/autofill/mock_address_accessory_controller.h
@@ -0,0 +1,29 @@ +// 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. + +#ifndef CHROME_BROWSER_AUTOFILL_MOCK_ADDRESS_ACCESSORY_CONTROLLER_H_ +#define CHROME_BROWSER_AUTOFILL_MOCK_ADDRESS_ACCESSORY_CONTROLLER_H_ + +#include "base/macros.h" +#include "chrome/browser/autofill/address_accessory_controller.h" +#include "components/autofill/core/browser/ui/accessory_sheet_data.h" +#include "components/autofill/core/browser/ui/accessory_sheet_enums.h" +#include "testing/gmock/include/gmock/gmock.h" + +class MockAddressAccessoryController + : public autofill::AddressAccessoryController { + public: + MockAddressAccessoryController(); + ~MockAddressAccessoryController() override; + + MOCK_METHOD1(OnFillingTriggered, void(const autofill::UserInfo::Field&)); + MOCK_METHOD1(OnOptionSelected, + void(autofill::AccessoryAction selected_action)); + MOCK_METHOD0(RefreshSuggestions, void()); + + private: + DISALLOW_COPY_AND_ASSIGN(MockAddressAccessoryController); +}; + +#endif // CHROME_BROWSER_AUTOFILL_MOCK_ADDRESS_ACCESSORY_CONTROLLER_H_
diff --git a/chrome/browser/autofill/mock_manual_filling_controller.h b/chrome/browser/autofill/mock_manual_filling_controller.h index 9cd774f..19a8f02 100644 --- a/chrome/browser/autofill/mock_manual_filling_controller.h +++ b/chrome/browser/autofill/mock_manual_filling_controller.h
@@ -5,6 +5,7 @@ #ifndef CHROME_BROWSER_AUTOFILL_MOCK_MANUAL_FILLING_CONTROLLER_H_ #define CHROME_BROWSER_AUTOFILL_MOCK_MANUAL_FILLING_CONTROLLER_H_ +#include "base/macros.h" #include "chrome/browser/autofill/manual_filling_controller.h" #include "testing/gmock/include/gmock/gmock.h" @@ -23,7 +24,9 @@ MOCK_METHOD1(ShowWhenKeyboardIsVisible, void(ManualFillingController::FillingSource)); MOCK_METHOD1(ShowTouchToFillSheet, void(const autofill::AccessorySheetData&)); - MOCK_METHOD1(Hide, void(ManualFillingController::FillingSource)); + MOCK_METHOD1(DeactivateFillingSource, + void(ManualFillingController::FillingSource)); + MOCK_METHOD0(Hide, void()); MOCK_METHOD2(GetFavicon, void(int, base::OnceCallback<void(const gfx::Image&)>)); MOCK_METHOD2(OnFillingTriggered, @@ -31,8 +34,10 @@ const autofill::UserInfo::Field&)); MOCK_CONST_METHOD1(OnOptionSelected, void(autofill::AccessoryAction selected_action)); - MOCK_METHOD0(OnGenerationRequested, void()); MOCK_CONST_METHOD0(container_view, gfx::NativeView()); + + private: + DISALLOW_COPY_AND_ASSIGN(MockManualFillingController); }; #endif // CHROME_BROWSER_AUTOFILL_MOCK_MANUAL_FILLING_CONTROLLER_H_
diff --git a/chrome/browser/autofill/mock_manual_filling_view.cc b/chrome/browser/autofill/mock_manual_filling_view.cc new file mode 100644 index 0000000..e52e78c --- /dev/null +++ b/chrome/browser/autofill/mock_manual_filling_view.cc
@@ -0,0 +1,8 @@ +// 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 "chrome/browser/autofill/mock_manual_filling_view.h" + +MockManualFillingView::MockManualFillingView() = default; +MockManualFillingView::~MockManualFillingView() = default;
diff --git a/chrome/browser/autofill/mock_manual_filling_view.h b/chrome/browser/autofill/mock_manual_filling_view.h new file mode 100644 index 0000000..be21dfb --- /dev/null +++ b/chrome/browser/autofill/mock_manual_filling_view.h
@@ -0,0 +1,29 @@ +// 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. + +#ifndef CHROME_BROWSER_AUTOFILL_MOCK_MANUAL_FILLING_VIEW_H_ +#define CHROME_BROWSER_AUTOFILL_MOCK_MANUAL_FILLING_VIEW_H_ + +#include "chrome/browser/autofill/manual_filling_view_interface.h" +#include "components/autofill/core/browser/ui/accessory_sheet_data.h" +#include "testing/gmock/include/gmock/gmock.h" + +class MockManualFillingView : public ManualFillingViewInterface { + public: + MockManualFillingView(); + ~MockManualFillingView() override; + + MOCK_METHOD1(OnItemsAvailable, void(const autofill::AccessorySheetData&)); + MOCK_METHOD1(OnAutomaticGenerationStatusChanged, void(bool)); + MOCK_METHOD0(CloseAccessorySheet, void()); + MOCK_METHOD0(SwapSheetWithKeyboard, void()); + MOCK_METHOD0(ShowWhenKeyboardIsVisible, void()); + MOCK_METHOD0(ShowTouchToFillSheet, void()); + MOCK_METHOD0(Hide, void()); + + private: + DISALLOW_COPY_AND_ASSIGN(MockManualFillingView); +}; + +#endif // CHROME_BROWSER_AUTOFILL_MOCK_MANUAL_FILLING_VIEW_H_
diff --git a/chrome/browser/browser_resources.grd b/chrome/browser/browser_resources.grd index c34b713e..5dbee70 100644 --- a/chrome/browser/browser_resources.grd +++ b/chrome/browser/browser_resources.grd
@@ -431,14 +431,14 @@ <include name="IDR_SITE_ENGAGEMENT_JS" file="resources\engagement\site_engagement.js" flattenhtml="true" type="BINDATA" compress="gzip" /> <include name="IDR_SITE_ENGAGEMENT_DETAILS_MOJOM_LITE_JS" file="${root_gen_dir}\chrome\browser\engagement\site_engagement_details.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" /> <include name="IDR_URL_MOJOM_LITE_JS" file="${root_gen_dir}\url\mojom\url.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" /> + <include name="IDR_SYNC_DISABLED_CONFIRMATION_HTML" file="resources\signin\sync_confirmation\sync_disabled_confirmation.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" /> + <include name="IDR_SYNC_DISABLED_CONFIRMATION_JS" file="resources\signin\sync_confirmation\sync_disabled_confirmation.js" type="BINDATA" /> <include name="IDR_SYNC_CONFIRMATION_HTML" file="resources\signin\sync_confirmation\sync_confirmation.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" /> <include name="IDR_SYNC_CONFIRMATION_JS" file="resources\signin\sync_confirmation\sync_confirmation.js" type="BINDATA" /> - <include name="IDR_DICE_SYNC_CONFIRMATION_HTML" file="resources\signin\dice_sync_confirmation\sync_confirmation.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" /> - <include name="IDR_DICE_SYNC_CONFIRMATION_JS" file="resources\signin\dice_sync_confirmation\sync_confirmation.js" type="BINDATA" /> - <include name="IDR_DICE_SYNC_CONFIRMATION_BROWSER_PROXY_HTML" file="resources\signin\dice_sync_confirmation\sync_confirmation_browser_proxy.html" type="BINDATA" /> - <include name="IDR_DICE_SYNC_CONFIRMATION_BROWSER_PROXY_JS" file="resources\signin\dice_sync_confirmation\sync_confirmation_browser_proxy.js" type="BINDATA" /> - <include name="IDR_DICE_SYNC_CONFIRMATION_APP_HTML" file="resources\signin\dice_sync_confirmation\sync_confirmation_app.html" type="BINDATA" flattenhtml="true" allowexternalscript="true" /> - <include name="IDR_DICE_SYNC_CONFIRMATION_APP_JS" file="resources\signin\dice_sync_confirmation\sync_confirmation_app.js" type="BINDATA" /> + <include name="IDR_SYNC_CONFIRMATION_BROWSER_PROXY_HTML" file="resources\signin\sync_confirmation\sync_confirmation_browser_proxy.html" type="BINDATA" /> + <include name="IDR_SYNC_CONFIRMATION_BROWSER_PROXY_JS" file="resources\signin\sync_confirmation\sync_confirmation_browser_proxy.js" type="BINDATA" /> + <include name="IDR_SYNC_CONFIRMATION_APP_HTML" file="resources\signin\sync_confirmation\sync_confirmation_app.html" type="BINDATA" flattenhtml="true" allowexternalscript="true" /> + <include name="IDR_SYNC_CONFIRMATION_APP_JS" file="resources\signin\sync_confirmation\sync_confirmation_app.js" type="BINDATA" /> <include name="IDR_SIGNIN_EMAIL_CONFIRMATION_HTML" file="resources\signin\signin_email_confirmation\signin_email_confirmation.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" /> <include name="IDR_SIGNIN_EMAIL_CONFIRMATION_JS" file="resources\signin\signin_email_confirmation\signin_email_confirmation.js" type="BINDATA" /> <include name="IDR_SIGNIN_ERROR_HTML" file="resources\signin\signin_error\signin_error.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
diff --git a/chrome/browser/chromeos/BUILD.gn b/chrome/browser/chromeos/BUILD.gn index 27da15d..7a4c6c4b 100644 --- a/chrome/browser/chromeos/BUILD.gn +++ b/chrome/browser/chromeos/BUILD.gn
@@ -1555,6 +1555,8 @@ "policy/cached_policy_key_loader_chromeos.h", "policy/cloud_external_data_manager_base.cc", "policy/cloud_external_data_manager_base.h", + "policy/cloud_external_data_policy_handler.cc", + "policy/cloud_external_data_policy_handler.h", "policy/cloud_external_data_policy_observer.cc", "policy/cloud_external_data_policy_observer.h", "policy/cloud_external_data_store.cc", @@ -1636,6 +1638,8 @@ "policy/login_profile_policy_provider.h", "policy/minimum_version_policy_handler.cc", "policy/minimum_version_policy_handler.h", + "policy/native_printers_external_data_handler.cc", + "policy/native_printers_external_data_handler.h", "policy/network_configuration_updater.cc", "policy/network_configuration_updater.h", "policy/off_hours/device_off_hours_controller.cc", @@ -1709,6 +1713,8 @@ "policy/upload_job.h", "policy/upload_job_impl.cc", "policy/upload_job_impl.h", + "policy/user_avatar_image_external_data_handler.cc", + "policy/user_avatar_image_external_data_handler.h", "policy/user_cloud_external_data_manager.cc", "policy/user_cloud_external_data_manager.h", "policy/user_cloud_policy_manager_chromeos.cc", @@ -1730,6 +1736,8 @@ "policy/value_validation/onc_policy_value_validator_base.h", "policy/value_validation/onc_user_policy_value_validator.cc", "policy/value_validation/onc_user_policy_value_validator.h", + "policy/wallpaper_image_external_data_handler.cc", + "policy/wallpaper_image_external_data_handler.h", "policy/wildcard_login_checker.cc", "policy/wildcard_login_checker.h", "power/auto_screen_brightness/adapter.cc",
diff --git a/chrome/browser/chromeos/arc/arc_service_launcher.cc b/chrome/browser/chromeos/arc/arc_service_launcher.cc index 317f432d..f25f393 100644 --- a/chrome/browser/chromeos/arc/arc_service_launcher.cc +++ b/chrome/browser/chromeos/arc/arc_service_launcher.cc
@@ -10,6 +10,7 @@ #include "ash/public/interfaces/constants.mojom.h" #include "base/bind.h" #include "base/logging.h" +#include "base/task/post_task.h" #include "chrome/browser/apps/app_service/arc_apps_factory.h" #include "chrome/browser/chromeos/apps/apk_web_app_service.h" #include "chrome/browser/chromeos/arc/accessibility/arc_accessibility_helper_bridge.h" @@ -50,6 +51,7 @@ #include "components/arc/app_permissions/arc_app_permissions_bridge.h" #include "components/arc/appfuse/arc_appfuse_bridge.h" #include "components/arc/arc_service_manager.h" +#include "components/arc/arc_util.h" #include "components/arc/audio/arc_audio_bridge.h" #include "components/arc/camera/arc_camera_bridge.h" #include "components/arc/clipboard/arc_clipboard_bridge.h" @@ -80,6 +82,10 @@ namespace arc { namespace { +// The file that specifies if the environment is ARCVM or ARC. It contains 1 in +// ARCVM and 0 in ARC. +constexpr base::FilePath::CharType kIsArcVm[] = "/run/chrome/is_arcvm"; + // ChromeBrowserMainPartsChromeos owns. ArcServiceLauncher* g_arc_service_launcher = nullptr; @@ -96,6 +102,14 @@ DCHECK(g_arc_service_launcher == nullptr); g_arc_service_launcher = this; + // Write kIsArcVm file to be 1 or 0. + base::PostTaskWithTraits( + FROM_HERE, {base::MayBlock()}, + base::BindOnce([](const base::FilePath& filename, const char* data, + int size) { base::WriteFile(filename, data, size); }, + base::FilePath(kIsArcVm), + arc::IsArcVmEnabled() ? "1" : "0", 1)); + ash::mojom::CrosDisplayConfigControllerPtr cros_display_config; content::ServiceManagerConnection::GetForProcess() ->GetConnector()
diff --git a/chrome/browser/chromeos/extensions/file_manager/private_api_strings.cc b/chrome/browser/chromeos/extensions/file_manager/private_api_strings.cc index 89eb209d..e0adda74 100644 --- a/chrome/browser/chromeos/extensions/file_manager/private_api_strings.cc +++ b/chrome/browser/chromeos/extensions/file_manager/private_api_strings.cc
@@ -58,6 +58,9 @@ dict->SetBoolean("FEEDBACK_PANEL_ENABLED", base::FeatureList::IsEnabled( chromeos::features::kEnableFileManagerFeedbackPanel)); + dict->SetBoolean("FORMAT_DIALOG_ENABLED", + base::FeatureList::IsEnabled( + chromeos::features::kEnableFileManagerFormatDialog)); dict->SetBoolean( "MY_FILES_VOLUME_ENABLED", base::FeatureList::IsEnabled(chromeos::features::kMyFilesVolume));
diff --git a/chrome/browser/chromeos/login/users/chrome_user_manager_impl.cc b/chrome/browser/chromeos/login/users/chrome_user_manager_impl.cc index a3965e61..e91260c2 100644 --- a/chrome/browser/chromeos/login/users/chrome_user_manager_impl.cc +++ b/chrome/browser/chromeos/login/users/chrome_user_manager_impl.cc
@@ -51,7 +51,9 @@ #include "chrome/browser/chromeos/login/users/supervised_user_manager_impl.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/chromeos/policy/device_network_configuration_updater.h" -#include "chrome/browser/chromeos/printing/bulk_printers_calculator.h" +#include "chrome/browser/chromeos/policy/native_printers_external_data_handler.h" +#include "chrome/browser/chromeos/policy/user_avatar_image_external_data_handler.h" +#include "chrome/browser/chromeos/policy/wallpaper_image_external_data_handler.h" #include "chrome/browser/chromeos/printing/bulk_printers_calculator_factory.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/chromeos/session_length_limiter.h" @@ -191,11 +193,6 @@ ->GetMinimumVersionPolicyHandler(); } -base::WeakPtr<BulkPrintersCalculator> GetBulkPrintersCalculator( - const AccountId& account_id) { - return BulkPrintersCalculatorFactory::Get()->GetForAccountId(account_id); -} - // Starts bluetooth logging service for accounts ending with |kGoogleDotCom| // and certain devices. void MaybeStartBluetoothLogging(const AccountId& account_id) { @@ -385,21 +382,15 @@ GetMinimumVersionPolicyHandler()->AddObserver(this); } - avatar_policy_observer_ = - std::make_unique<policy::CloudExternalDataPolicyObserver>( - cros_settings_, device_local_account_policy_service, - policy::key::kUserAvatarImage, this); - avatar_policy_observer_->Init(); - wallpaper_policy_observer_ = - std::make_unique<policy::CloudExternalDataPolicyObserver>( - cros_settings_, device_local_account_policy_service, - policy::key::kWallpaperImage, this); - wallpaper_policy_observer_->Init(); - printers_policy_observer_ = - std::make_unique<policy::CloudExternalDataPolicyObserver>( - cros_settings_, device_local_account_policy_service, - policy::key::kNativePrintersBulkConfiguration, this); - printers_policy_observer_->Init(); + cloud_external_data_policy_handlers_.emplace_back( + std::make_unique<policy::UserAvatarImageExternalDataHandler>( + cros_settings_, device_local_account_policy_service)); + cloud_external_data_policy_handlers_.emplace_back( + std::make_unique<policy::WallpaperImageExternalDataHandler>( + cros_settings_, device_local_account_policy_service)); + cloud_external_data_policy_handlers_.emplace_back( + std::make_unique<policy::NativePrintersExternalDataHandler>( + cros_settings_, device_local_account_policy_service)); // Record the stored session length for enrolled device. if (IsEnterpriseManaged()) @@ -444,10 +435,7 @@ it->second->Shutdown(); } multi_profile_user_controller_.reset(); - avatar_policy_observer_.reset(); - wallpaper_policy_observer_.reset(); - // Remove the observer before shutting down the printer policy objects. - printers_policy_observer_.reset(); + cloud_external_data_policy_handlers_.clear(); BulkPrintersCalculatorFactory::Get()->ShutdownProfiles(); registrar_.RemoveAll(); } @@ -604,9 +592,7 @@ } void ChromeUserManagerImpl::StopPolicyObserverForTesting() { - avatar_policy_observer_.reset(); - wallpaper_policy_observer_.reset(); - printers_policy_observer_.reset(); + cloud_external_data_policy_handlers_.clear(); } void ChromeUserManagerImpl::Observe( @@ -673,52 +659,6 @@ RetrieveTrustedDevicePolicies(); } -void ChromeUserManagerImpl::OnExternalDataSet(const std::string& policy, - const std::string& user_id) { - const AccountId account_id = user_manager::known_user::GetAccountId( - user_id, std::string() /* id */, AccountType::UNKNOWN); - if (policy == policy::key::kUserAvatarImage) - GetUserImageManager(account_id)->OnExternalDataSet(policy); - else if (policy == policy::key::kNativePrintersBulkConfiguration) - GetBulkPrintersCalculator(account_id)->ClearData(); - else if (policy != policy::key::kWallpaperImage) - NOTREACHED(); -} - -void ChromeUserManagerImpl::OnExternalDataCleared(const std::string& policy, - const std::string& user_id) { - const AccountId account_id = user_manager::known_user::GetAccountId( - user_id, std::string() /* id */, AccountType::UNKNOWN); - if (policy == policy::key::kUserAvatarImage) - GetUserImageManager(account_id)->OnExternalDataCleared(policy); - else if (policy == policy::key::kNativePrintersBulkConfiguration) - GetBulkPrintersCalculator(account_id)->ClearData(); - else if (policy == policy::key::kWallpaperImage) - WallpaperControllerClient::Get()->RemovePolicyWallpaper(account_id); - else - NOTREACHED(); -} - -void ChromeUserManagerImpl::OnExternalDataFetched( - const std::string& policy, - const std::string& user_id, - std::unique_ptr<std::string> data, - const base::FilePath& file_path) { - const AccountId account_id = user_manager::known_user::GetAccountId( - user_id, std::string() /* id */, AccountType::UNKNOWN); - if (policy == policy::key::kUserAvatarImage) { - GetUserImageManager(account_id) - ->OnExternalDataFetched(policy, std::move(data)); - } else if (policy == policy::key::kNativePrintersBulkConfiguration) { - GetBulkPrintersCalculator(account_id)->SetData(std::move(data)); - } else if (policy == policy::key::kWallpaperImage) { - WallpaperControllerClient::Get()->SetPolicyWallpaper(account_id, - std::move(data)); - } else { - NOTREACHED(); - } -} - void ChromeUserManagerImpl::OnPolicyUpdated(const std::string& user_id) { const AccountId account_id = user_manager::known_user::GetAccountId( user_id, std::string() /* id */, AccountType::UNKNOWN); @@ -1129,9 +1069,8 @@ const AccountId& account_id) { // Wallpaper removal depends on user preference, so it must happen before // |known_user::RemovePrefs|. See https://crbug.com/778077. - WallpaperControllerClient::Get()->RemoveUserWallpaper(account_id); - GetUserImageManager(account_id)->DeleteUserImage(); - BulkPrintersCalculatorFactory::Get()->RemoveForUserId(account_id); + for (auto& handler : cloud_external_data_policy_handlers_) + handler->RemoveForAccountId(account_id); // TODO(tbarzic): Forward data removal request to ash::HammerDeviceHandler, // instead of removing the prefs value here. if (GetLocalState()->FindPreference(ash::prefs::kDetachableBaseDevices)) {
diff --git a/chrome/browser/chromeos/login/users/chrome_user_manager_impl.h b/chrome/browser/chromeos/login/users/chrome_user_manager_impl.h index 4aacd1e..01ba750 100644 --- a/chrome/browser/chromeos/login/users/chrome_user_manager_impl.h +++ b/chrome/browser/chromeos/login/users/chrome_user_manager_impl.h
@@ -22,7 +22,6 @@ #include "chrome/browser/chromeos/login/users/avatar/user_image_manager_impl.h" #include "chrome/browser/chromeos/login/users/chrome_user_manager.h" #include "chrome/browser/chromeos/login/users/multi_profile_user_controller_delegate.h" -#include "chrome/browser/chromeos/policy/cloud_external_data_policy_observer.h" #include "chrome/browser/chromeos/policy/device_local_account.h" #include "chrome/browser/chromeos/policy/device_local_account_policy_service.h" #include "chrome/browser/chromeos/policy/minimum_version_policy_handler.h" @@ -44,6 +43,10 @@ class RemoveUserDelegate; } +namespace policy { +class CloudExternalDataPolicyHandler; +} // namespace policy + namespace chromeos { class MultiProfileUserController; @@ -55,7 +58,6 @@ : public ChromeUserManager, public content::NotificationObserver, public DeviceSettingsService::Observer, - public policy::CloudExternalDataPolicyObserver::Delegate, public policy::DeviceLocalAccountPolicyService::Observer, public policy::MinimumVersionPolicyHandler::Observer, public MultiProfileUserControllerDelegate { @@ -118,16 +120,6 @@ // DeviceSettingsService::Observer implementation: void OwnershipStatusChanged() override; - // policy::CloudExternalDataPolicyObserver::Delegate implementation: - void OnExternalDataSet(const std::string& policy, - const std::string& user_id) override; - void OnExternalDataCleared(const std::string& policy, - const std::string& user_id) override; - void OnExternalDataFetched(const std::string& policy, - const std::string& user_id, - std::unique_ptr<std::string> data, - const base::FilePath& file_path) override; - // policy::DeviceLocalAccountPolicyService::Observer implementation. void OnPolicyUpdated(const std::string& user_id) override; void OnDeviceLocalAccountsChanged() override; @@ -286,17 +278,8 @@ std::unique_ptr<MultiProfileUserController> multi_profile_user_controller_; - // Observer for the policy that can be used to manage user images. - std::unique_ptr<policy::CloudExternalDataPolicyObserver> - avatar_policy_observer_; - - // Observer for the policy that can be used to manage wallpapers. - std::unique_ptr<policy::CloudExternalDataPolicyObserver> - wallpaper_policy_observer_; - - // Observer for the policy that provides policy printers. - std::unique_ptr<policy::CloudExternalDataPolicyObserver> - printers_policy_observer_; + std::vector<std::unique_ptr<policy::CloudExternalDataPolicyHandler>> + cloud_external_data_policy_handlers_; base::WeakPtrFactory<ChromeUserManagerImpl> weak_factory_;
diff --git a/chrome/browser/chromeos/policy/android_management_client_unittest.cc b/chrome/browser/chromeos/policy/android_management_client_unittest.cc index 3bd4f15..d108cf3d 100644 --- a/chrome/browser/chromeos/policy/android_management_client_unittest.cc +++ b/chrome/browser/chromeos/policy/android_management_client_unittest.cc
@@ -8,9 +8,9 @@ #include "base/bind_helpers.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/test/mock_callback.h" +#include "base/test/scoped_task_environment.h" #include "base/time/time.h" #include "chrome/browser/chromeos/policy/android_management_client.h" #include "components/policy/core/common/cloud/cloud_policy_constants.h" @@ -62,7 +62,7 @@ // Protobuf is used in successfil responsees. em::DeviceManagementResponse android_management_response_; - base::MessageLoop loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; MockDeviceManagementService service_; StrictMock<base::MockCallback<AndroidManagementClient::StatusCallback>> callback_observer_;
diff --git a/chrome/browser/chromeos/policy/cloud_external_data_manager_base_unittest.cc b/chrome/browser/chromeos/policy/cloud_external_data_manager_base_unittest.cc index 0fb8656..a968d38c 100644 --- a/chrome/browser/chromeos/policy/cloud_external_data_manager_base_unittest.cc +++ b/chrome/browser/chromeos/policy/cloud_external_data_manager_base_unittest.cc
@@ -12,10 +12,10 @@ #include "base/files/file_path.h" #include "base/files/scoped_temp_dir.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/optional.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" +#include "base/test/scoped_task_environment.h" #include "base/test/test_simple_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" @@ -93,7 +93,7 @@ const std::string& repsonse_data, net::HttpStatusCode response_code); - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; base::ScopedTempDir temp_dir_; std::unique_ptr<ResourceCache> resource_cache_; MockCloudPolicyStore cloud_policy_store_; @@ -114,9 +114,9 @@ void CloudExternalDataManagerBaseTest::SetUp() { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - resource_cache_.reset(new ResourceCache(temp_dir_.GetPath(), - message_loop_.task_runner(), - /* max_cache_size */ base::nullopt)); + resource_cache_.reset(new ResourceCache( + temp_dir_.GetPath(), scoped_task_environment_.GetMainThreadTaskRunner(), + /* max_cache_size */ base::nullopt)); SetUpExternalDataManager(); // Set |kStringPolicy| to a string value. @@ -153,10 +153,12 @@ void CloudExternalDataManagerBaseTest::SetUpExternalDataManager() { external_data_manager_ = std::make_unique<CloudExternalDataManagerBase>( - policy_details_.GetCallback(), message_loop_.task_runner()); + policy_details_.GetCallback(), + scoped_task_environment_.GetMainThreadTaskRunner()); external_data_manager_->SetExternalDataStore( std::make_unique<CloudExternalDataStore>( - kCacheKey, message_loop_.task_runner(), resource_cache_.get())); + kCacheKey, scoped_task_environment_.GetMainThreadTaskRunner(), + resource_cache_.get())); external_data_manager_->SetPolicyStore(&cloud_policy_store_); } @@ -296,7 +298,8 @@ base::RunLoop().RunUntilIdle(); std::string data; EXPECT_FALSE( - CloudExternalDataStore(kCacheKey, message_loop_.task_runner(), + CloudExternalDataStore(kCacheKey, + scoped_task_environment_.GetMainThreadTaskRunner(), resource_cache_.get()) .Load(k10BytePolicy, crypto::SHA256HashString(k10ByteData), 10, &data) .empty()); @@ -352,8 +355,9 @@ // Verify that the downloaded data is present in the cache. external_data_manager_.reset(); base::RunLoop().RunUntilIdle(); - CloudExternalDataStore cache(kCacheKey, message_loop_.task_runner(), - resource_cache_.get()); + CloudExternalDataStore cache( + kCacheKey, scoped_task_environment_.GetMainThreadTaskRunner(), + resource_cache_.get()); std::string data; EXPECT_FALSE( cache @@ -479,11 +483,13 @@ // Store valid external data for |k10BytePolicy| in the cache. external_data_manager_.reset(); base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(CloudExternalDataStore(kCacheKey, message_loop_.task_runner(), - resource_cache_.get()) - .Store(k10BytePolicy, crypto::SHA256HashString(k10ByteData), - k10ByteData) - .empty()); + EXPECT_FALSE( + CloudExternalDataStore(kCacheKey, + scoped_task_environment_.GetMainThreadTaskRunner(), + resource_cache_.get()) + .Store(k10BytePolicy, crypto::SHA256HashString(k10ByteData), + k10ByteData) + .empty()); // Instantiate an external_data_manager_ that uses the primed cache. SetUpExternalDataManager(); @@ -506,7 +512,8 @@ external_data_manager_.reset(); base::RunLoop().RunUntilIdle(); std::unique_ptr<CloudExternalDataStore> cache(new CloudExternalDataStore( - kCacheKey, message_loop_.task_runner(), resource_cache_.get())); + kCacheKey, scoped_task_environment_.GetMainThreadTaskRunner(), + resource_cache_.get())); // Store valid external data for |k10BytePolicy| in the cache. EXPECT_FALSE(cache ->Store(k10BytePolicy, crypto::SHA256HashString(k10ByteData), @@ -531,8 +538,9 @@ external_data_manager_.reset(); base::RunLoop().RunUntilIdle(); - cache.reset(new CloudExternalDataStore(kCacheKey, message_loop_.task_runner(), - resource_cache_.get())); + cache.reset(new CloudExternalDataStore( + kCacheKey, scoped_task_environment_.GetMainThreadTaskRunner(), + resource_cache_.get())); std::string data; // Verify that the valid external data for |k10BytePolicy| is still in the // cache. @@ -560,7 +568,8 @@ external_data_manager_.reset(); base::RunLoop().RunUntilIdle(); std::unique_ptr<CloudExternalDataStore> cache(new CloudExternalDataStore( - kCacheKey, message_loop_.task_runner(), resource_cache_.get())); + kCacheKey, scoped_task_environment_.GetMainThreadTaskRunner(), + resource_cache_.get())); EXPECT_FALSE(cache ->Store(k20BytePolicy, crypto::SHA256HashString(k20ByteData), k20ByteData) @@ -582,8 +591,9 @@ // the cache. external_data_manager_.reset(); base::RunLoop().RunUntilIdle(); - cache.reset(new CloudExternalDataStore(kCacheKey, message_loop_.task_runner(), - resource_cache_.get())); + cache.reset(new CloudExternalDataStore( + kCacheKey, scoped_task_environment_.GetMainThreadTaskRunner(), + resource_cache_.get())); std::string data; EXPECT_TRUE(cache ->Load(k20BytePolicy, crypto::SHA256HashString(k20ByteData), @@ -596,7 +606,8 @@ external_data_manager_.reset(); base::RunLoop().RunUntilIdle(); std::unique_ptr<CloudExternalDataStore> cache(new CloudExternalDataStore( - kCacheKey, message_loop_.task_runner(), resource_cache_.get())); + kCacheKey, scoped_task_environment_.GetMainThreadTaskRunner(), + resource_cache_.get())); // Store external data for |k10BytePolicy| that exceeds the maximal external // data size allowed for that policy. EXPECT_FALSE(cache @@ -647,8 +658,9 @@ external_data_manager_.reset(); base::RunLoop().RunUntilIdle(); - cache.reset(new CloudExternalDataStore(kCacheKey, message_loop_.task_runner(), - resource_cache_.get())); + cache.reset(new CloudExternalDataStore( + kCacheKey, scoped_task_environment_.GetMainThreadTaskRunner(), + resource_cache_.get())); std::string data; // Verify that the invalid external data for |k10BytePolicy| has been pruned // from the cache. Load() will return |false| in two cases:
diff --git a/chrome/browser/chromeos/policy/cloud_external_data_policy_handler.cc b/chrome/browser/chromeos/policy/cloud_external_data_policy_handler.cc new file mode 100644 index 0000000..680b47c --- /dev/null +++ b/chrome/browser/chromeos/policy/cloud_external_data_policy_handler.cc
@@ -0,0 +1,20 @@ +// 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 "chrome/browser/chromeos/policy/cloud_external_data_policy_handler.h" + +#include "components/user_manager/known_user.h" + +namespace policy { + +CloudExternalDataPolicyHandler::CloudExternalDataPolicyHandler() = default; + +// static +AccountId CloudExternalDataPolicyHandler::GetAccountId( + const std::string& user_id) { + return user_manager::known_user::GetAccountId(user_id, std::string() /* id */, + AccountType::UNKNOWN); +} + +} // namespace policy
diff --git a/chrome/browser/chromeos/policy/cloud_external_data_policy_handler.h b/chrome/browser/chromeos/policy/cloud_external_data_policy_handler.h new file mode 100644 index 0000000..e92185b --- /dev/null +++ b/chrome/browser/chromeos/policy/cloud_external_data_policy_handler.h
@@ -0,0 +1,29 @@ +// 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. + +#ifndef CHROME_BROWSER_CHROMEOS_POLICY_CLOUD_EXTERNAL_DATA_POLICY_HANDLER_H_ +#define CHROME_BROWSER_CHROMEOS_POLICY_CLOUD_EXTERNAL_DATA_POLICY_HANDLER_H_ + +#include "chrome/browser/chromeos/policy/cloud_external_data_policy_observer.h" + +namespace policy { + +// Base class for handling per-user external resources like wallpaper or avatar +// images. +class CloudExternalDataPolicyHandler + : public CloudExternalDataPolicyObserver::Delegate { + public: + CloudExternalDataPolicyHandler(); + + virtual void RemoveForAccountId(const AccountId& account_id) = 0; + + static AccountId GetAccountId(const std::string& user_id); + + private: + DISALLOW_COPY_AND_ASSIGN(CloudExternalDataPolicyHandler); +}; + +} // namespace policy + +#endif // CHROME_BROWSER_CHROMEOS_POLICY_CLOUD_EXTERNAL_DATA_POLICY_HANDLER_H_
diff --git a/chrome/browser/chromeos/policy/native_printers_external_data_handler.cc b/chrome/browser/chromeos/policy/native_printers_external_data_handler.cc new file mode 100644 index 0000000..3c97de6 --- /dev/null +++ b/chrome/browser/chromeos/policy/native_printers_external_data_handler.cc
@@ -0,0 +1,65 @@ +// 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 "chrome/browser/chromeos/policy/native_printers_external_data_handler.h" + +#include <utility> + +#include "base/memory/weak_ptr.h" +#include "chrome/browser/chromeos/printing/bulk_printers_calculator.h" +#include "chrome/browser/chromeos/printing/bulk_printers_calculator_factory.h" +#include "chrome/browser/chromeos/settings/cros_settings.h" +#include "components/policy/policy_constants.h" + +namespace policy { + +namespace { + +base::WeakPtr<chromeos::BulkPrintersCalculator> GetBulkPrintersCalculator( + const std::string& user_id) { + return chromeos::BulkPrintersCalculatorFactory::Get()->GetForAccountId( + CloudExternalDataPolicyHandler::GetAccountId(user_id)); +} + +} // namespace + +NativePrintersExternalDataHandler::NativePrintersExternalDataHandler( + chromeos::CrosSettings* cros_settings, + DeviceLocalAccountPolicyService* policy_service) + : native_printers_observer_(cros_settings, + policy_service, + key::kNativePrintersBulkConfiguration, + this) { + native_printers_observer_.Init(); +} + +NativePrintersExternalDataHandler::~NativePrintersExternalDataHandler() = + default; + +void NativePrintersExternalDataHandler::OnExternalDataSet( + const std::string& policy, + const std::string& user_id) { + GetBulkPrintersCalculator(user_id)->ClearData(); +} + +void NativePrintersExternalDataHandler::OnExternalDataCleared( + const std::string& policy, + const std::string& user_id) { + GetBulkPrintersCalculator(user_id)->ClearData(); +} + +void NativePrintersExternalDataHandler::OnExternalDataFetched( + const std::string& policy, + const std::string& user_id, + std::unique_ptr<std::string> data, + const base::FilePath& file_path) { + GetBulkPrintersCalculator(user_id)->SetData(std::move(data)); +} + +void NativePrintersExternalDataHandler::RemoveForAccountId( + const AccountId& account_id) { + chromeos::BulkPrintersCalculatorFactory::Get()->RemoveForUserId(account_id); +} + +} // namespace policy
diff --git a/chrome/browser/chromeos/policy/native_printers_external_data_handler.h b/chrome/browser/chromeos/policy/native_printers_external_data_handler.h new file mode 100644 index 0000000..52a87111 --- /dev/null +++ b/chrome/browser/chromeos/policy/native_printers_external_data_handler.h
@@ -0,0 +1,48 @@ +// 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. + +#ifndef CHROME_BROWSER_CHROMEOS_POLICY_NATIVE_PRINTERS_EXTERNAL_DATA_HANDLER_H_ +#define CHROME_BROWSER_CHROMEOS_POLICY_NATIVE_PRINTERS_EXTERNAL_DATA_HANDLER_H_ + +#include <memory> +#include <string> + +#include "chrome/browser/chromeos/policy/cloud_external_data_policy_handler.h" + +namespace chromeos { +class CrosSettings; +} // namespace chromeos + +namespace policy { + +class DeviceLocalAccountPolicyService; + +class NativePrintersExternalDataHandler + : public CloudExternalDataPolicyHandler { + public: + NativePrintersExternalDataHandler( + chromeos::CrosSettings* cros_settings, + DeviceLocalAccountPolicyService* policy_service); + ~NativePrintersExternalDataHandler() override; + + // CloudExternalDataPolicyHandler: + void OnExternalDataSet(const std::string& policy, + const std::string& user_id) override; + void OnExternalDataCleared(const std::string& policy, + const std::string& user_id) override; + void OnExternalDataFetched(const std::string& policy, + const std::string& user_id, + std::unique_ptr<std::string> data, + const base::FilePath& file_path) override; + void RemoveForAccountId(const AccountId& account_id) override; + + private: + CloudExternalDataPolicyObserver native_printers_observer_; + + DISALLOW_COPY_AND_ASSIGN(NativePrintersExternalDataHandler); +}; + +} // namespace policy + +#endif // CHROME_BROWSER_CHROMEOS_POLICY_NATIVE_PRINTERS_EXTERNAL_DATA_HANDLER_H_
diff --git a/chrome/browser/chromeos/policy/server_backed_state_keys_broker_unittest.cc b/chrome/browser/chromeos/policy/server_backed_state_keys_broker_unittest.cc index 7ccef7f..c55f0da7 100644 --- a/chrome/browser/chromeos/policy/server_backed_state_keys_broker_unittest.cc +++ b/chrome/browser/chromeos/policy/server_backed_state_keys_broker_unittest.cc
@@ -7,9 +7,9 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/test/scoped_mock_time_message_loop_task_runner.h" +#include "base/test/scoped_task_environment.h" #include "chromeos/dbus/session_manager/fake_session_manager_client.h" #include "testing/gtest/include/gtest/gtest.h" @@ -44,7 +44,7 @@ } protected: - base::MessageLoop loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; base::ScopedMockTimeMessageLoopTaskRunner mocked_main_runner_; chromeos::FakeSessionManagerClient fake_session_manager_client_; ServerBackedStateKeysBroker broker_;
diff --git a/chrome/browser/chromeos/policy/user_avatar_image_external_data_handler.cc b/chrome/browser/chromeos/policy/user_avatar_image_external_data_handler.cc new file mode 100644 index 0000000..d22dec4 --- /dev/null +++ b/chrome/browser/chromeos/policy/user_avatar_image_external_data_handler.cc
@@ -0,0 +1,65 @@ +// 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 "chrome/browser/chromeos/policy/user_avatar_image_external_data_handler.h" + +#include <utility> + +#include "chrome/browser/chromeos/login/users/avatar/user_image_manager.h" +#include "chrome/browser/chromeos/login/users/chrome_user_manager.h" +#include "chrome/browser/chromeos/settings/cros_settings.h" +#include "components/policy/policy_constants.h" + +namespace policy { + +namespace { + +chromeos::UserImageManager* GetUserImageManager(const std::string& user_id) { + return chromeos::ChromeUserManager::Get()->GetUserImageManager( + CloudExternalDataPolicyHandler::GetAccountId(user_id)); +} + +} // namespace + +UserAvatarImageExternalDataHandler::UserAvatarImageExternalDataHandler( + chromeos::CrosSettings* cros_settings, + DeviceLocalAccountPolicyService* policy_service) + : user_avatar_image_observer_(cros_settings, + policy_service, + key::kUserAvatarImage, + this) { + user_avatar_image_observer_.Init(); +} + +UserAvatarImageExternalDataHandler::~UserAvatarImageExternalDataHandler() = + default; + +void UserAvatarImageExternalDataHandler::OnExternalDataSet( + const std::string& policy, + const std::string& user_id) { + GetUserImageManager(user_id)->OnExternalDataSet(policy); +} + +void UserAvatarImageExternalDataHandler::OnExternalDataCleared( + const std::string& policy, + const std::string& user_id) { + GetUserImageManager(user_id)->OnExternalDataCleared(policy); +} + +void UserAvatarImageExternalDataHandler::OnExternalDataFetched( + const std::string& policy, + const std::string& user_id, + std::unique_ptr<std::string> data, + const base::FilePath& file_path) { + GetUserImageManager(user_id)->OnExternalDataFetched(policy, std::move(data)); +} + +void UserAvatarImageExternalDataHandler::RemoveForAccountId( + const AccountId& account_id) { + chromeos::ChromeUserManager::Get() + ->GetUserImageManager(account_id) + ->DeleteUserImage(); +} + +} // namespace policy
diff --git a/chrome/browser/chromeos/policy/user_avatar_image_external_data_handler.h b/chrome/browser/chromeos/policy/user_avatar_image_external_data_handler.h new file mode 100644 index 0000000..8bf1535 --- /dev/null +++ b/chrome/browser/chromeos/policy/user_avatar_image_external_data_handler.h
@@ -0,0 +1,48 @@ +// 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. + +#ifndef CHROME_BROWSER_CHROMEOS_POLICY_USER_AVATAR_IMAGE_EXTERNAL_DATA_HANDLER_H_ +#define CHROME_BROWSER_CHROMEOS_POLICY_USER_AVATAR_IMAGE_EXTERNAL_DATA_HANDLER_H_ + +#include <memory> +#include <string> + +#include "chrome/browser/chromeos/policy/cloud_external_data_policy_handler.h" + +namespace chromeos { +class CrosSettings; +} // namespace chromeos + +namespace policy { + +class DeviceLocalAccountPolicyService; + +class UserAvatarImageExternalDataHandler + : public CloudExternalDataPolicyHandler { + public: + UserAvatarImageExternalDataHandler( + chromeos::CrosSettings* cros_settings, + DeviceLocalAccountPolicyService* policy_service); + ~UserAvatarImageExternalDataHandler() override; + + // CloudExternalDataPolicyHandler: + void OnExternalDataSet(const std::string& policy, + const std::string& user_id) override; + void OnExternalDataCleared(const std::string& policy, + const std::string& user_id) override; + void OnExternalDataFetched(const std::string& policy, + const std::string& user_id, + std::unique_ptr<std::string> data, + const base::FilePath& file_path) override; + void RemoveForAccountId(const AccountId& account_id) override; + + private: + CloudExternalDataPolicyObserver user_avatar_image_observer_; + + DISALLOW_COPY_AND_ASSIGN(UserAvatarImageExternalDataHandler); +}; + +} // namespace policy + +#endif // CHROME_BROWSER_CHROMEOS_POLICY_USER_AVATAR_IMAGE_EXTERNAL_DATA_HANDLER_H_
diff --git a/chrome/browser/chromeos/policy/wallpaper_image_external_data_handler.cc b/chrome/browser/chromeos/policy/wallpaper_image_external_data_handler.cc new file mode 100644 index 0000000..1944de1 --- /dev/null +++ b/chrome/browser/chromeos/policy/wallpaper_image_external_data_handler.cc
@@ -0,0 +1,49 @@ +// 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 "chrome/browser/chromeos/policy/wallpaper_image_external_data_handler.h" + +#include <utility> + +#include "chrome/browser/chromeos/settings/cros_settings.h" +#include "chrome/browser/ui/ash/wallpaper_controller_client.h" +#include "components/policy/policy_constants.h" + +namespace policy { + +WallpaperImageExternalDataHandler::WallpaperImageExternalDataHandler( + chromeos::CrosSettings* cros_settings, + DeviceLocalAccountPolicyService* policy_service) + : wallpaper_image_observer_(cros_settings, + policy_service, + key::kWallpaperImage, + this) { + wallpaper_image_observer_.Init(); +} + +WallpaperImageExternalDataHandler::~WallpaperImageExternalDataHandler() = + default; + +void WallpaperImageExternalDataHandler::OnExternalDataCleared( + const std::string& policy, + const std::string& user_id) { + WallpaperControllerClient::Get()->RemovePolicyWallpaper( + CloudExternalDataPolicyHandler::GetAccountId(user_id)); +} + +void WallpaperImageExternalDataHandler::OnExternalDataFetched( + const std::string& policy, + const std::string& user_id, + std::unique_ptr<std::string> data, + const base::FilePath& file_path) { + WallpaperControllerClient::Get()->SetPolicyWallpaper( + CloudExternalDataPolicyHandler::GetAccountId(user_id), std::move(data)); +} + +void WallpaperImageExternalDataHandler::RemoveForAccountId( + const AccountId& account_id) { + WallpaperControllerClient::Get()->RemoveUserWallpaper(account_id); +} + +} // namespace policy
diff --git a/chrome/browser/chromeos/policy/wallpaper_image_external_data_handler.h b/chrome/browser/chromeos/policy/wallpaper_image_external_data_handler.h new file mode 100644 index 0000000..ba2cf38 --- /dev/null +++ b/chrome/browser/chromeos/policy/wallpaper_image_external_data_handler.h
@@ -0,0 +1,46 @@ +// 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. + +#ifndef CHROME_BROWSER_CHROMEOS_POLICY_WALLPAPER_IMAGE_EXTERNAL_DATA_HANDLER_H_ +#define CHROME_BROWSER_CHROMEOS_POLICY_WALLPAPER_IMAGE_EXTERNAL_DATA_HANDLER_H_ + +#include <memory> +#include <string> + +#include "chrome/browser/chromeos/policy/cloud_external_data_policy_handler.h" + +namespace chromeos { +class CrosSettings; +} // namespace chromeos + +namespace policy { + +class DeviceLocalAccountPolicyService; + +class WallpaperImageExternalDataHandler + : public CloudExternalDataPolicyHandler { + public: + WallpaperImageExternalDataHandler( + chromeos::CrosSettings* cros_settings, + DeviceLocalAccountPolicyService* policy_service); + ~WallpaperImageExternalDataHandler() override; + + // CloudExternalDataPolicyHandler: + void OnExternalDataCleared(const std::string& policy, + const std::string& user_id) override; + void OnExternalDataFetched(const std::string& policy, + const std::string& user_id, + std::unique_ptr<std::string> data, + const base::FilePath& file_path) override; + void RemoveForAccountId(const AccountId& account_id) override; + + private: + CloudExternalDataPolicyObserver wallpaper_image_observer_; + + DISALLOW_COPY_AND_ASSIGN(WallpaperImageExternalDataHandler); +}; + +} // namespace policy + +#endif // CHROME_BROWSER_CHROMEOS_POLICY_WALLPAPER_IMAGE_EXTERNAL_DATA_HANDLER_H_
diff --git a/chrome/browser/chromeos/settings/device_identity_provider.h b/chrome/browser/chromeos/settings/device_identity_provider.h index e9b9bc96..86780b0 100644 --- a/chrome/browser/chromeos/settings/device_identity_provider.h +++ b/chrome/browser/chromeos/settings/device_identity_provider.h
@@ -14,7 +14,7 @@ // Identity provider implementation backed by DeviceOAuth2TokenService. class DeviceIdentityProvider : public invalidation::IdentityProvider, - public OAuth2TokenService::Observer { + public OAuth2TokenServiceObserver { public: explicit DeviceIdentityProvider( chromeos::DeviceOAuth2TokenService* token_service); @@ -32,7 +32,7 @@ const std::string& access_token) override; void SetActiveAccountId(const std::string& account_id) override; - // OAuth2TokenService::Observer: + // OAuth2TokenServiceObserver: void OnRefreshTokenAvailable(const CoreAccountId& account_id) override; void OnRefreshTokenRevoked(const CoreAccountId& account_id) override;
diff --git a/chrome/browser/chromeos/settings/device_oauth2_token_service_unittest.cc b/chrome/browser/chromeos/settings/device_oauth2_token_service_unittest.cc index ff1d41e..ffafa5e 100644 --- a/chrome/browser/chromeos/settings/device_oauth2_token_service_unittest.cc +++ b/chrome/browser/chromeos/settings/device_oauth2_token_service_unittest.cc
@@ -45,7 +45,7 @@ namespace { -class MockOAuth2TokenServiceObserver : public OAuth2TokenService::Observer { +class MockOAuth2TokenServiceObserver : public OAuth2TokenServiceObserver { public: MockOAuth2TokenServiceObserver(); ~MockOAuth2TokenServiceObserver() override;
diff --git a/chrome/browser/download/download_history.cc b/chrome/browser/download/download_history.cc index 4462695..c1bc066 100644 --- a/chrome/browser/download/download_history.cc +++ b/chrome/browser/download/download_history.cc
@@ -221,8 +221,8 @@ void DownloadHistory::HistoryAdapter::CreateDownload( const history::DownloadRow& info, - const history::HistoryService::DownloadCreateCallback& callback) { - history_->CreateDownload(info, callback); + history::HistoryService::DownloadCreateCallback callback) { + history_->CreateDownload(info, std::move(callback)); } void DownloadHistory::HistoryAdapter::UpdateDownload(
diff --git a/chrome/browser/download/download_history.h b/chrome/browser/download/download_history.h index ae5ed06f..882c97e 100644 --- a/chrome/browser/download/download_history.h +++ b/chrome/browser/download/download_history.h
@@ -40,7 +40,7 @@ virtual void CreateDownload( const history::DownloadRow& info, - const history::HistoryService::DownloadCreateCallback& callback); + history::HistoryService::DownloadCreateCallback callback); virtual void UpdateDownload(const history::DownloadRow& data, bool should_commit_immediately);
diff --git a/chrome/browser/download/download_history_unittest.cc b/chrome/browser/download/download_history_unittest.cc index 6741658..fc1f1ce1 100644 --- a/chrome/browser/download/download_history_unittest.cc +++ b/chrome/browser/download/download_history_unittest.cc
@@ -71,14 +71,15 @@ void set_slow_create_download(bool slow) { slow_create_download_ = slow; } - void CreateDownload(const history::DownloadRow& info, - const history::HistoryService::DownloadCreateCallback& - callback) override { + void CreateDownload( + const history::DownloadRow& info, + history::HistoryService::DownloadCreateCallback callback) override { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); create_download_info_ = info; // Must not call CreateDownload() again before FinishCreateDownload()! DCHECK(create_download_callback_.is_null()); - create_download_callback_ = base::Bind(callback, !fail_create_download_); + create_download_callback_ = + base::BindOnce(std::move(callback), !fail_create_download_); fail_create_download_ = false; if (!slow_create_download_) FinishCreateDownload(); @@ -86,8 +87,7 @@ void FinishCreateDownload() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - create_download_callback_.Run(); - create_download_callback_.Reset(); + std::move(create_download_callback_).Run(); } void UpdateDownload(const history::DownloadRow& info, @@ -170,7 +170,7 @@ bool slow_create_download_ = false; bool fail_create_download_ = false; bool should_commit_immediately_ = false; - base::Closure create_download_callback_; + base::OnceClosure create_download_callback_; history::DownloadRow update_download_; std::unique_ptr<InfoVector> expect_query_downloads_; IdSet remove_downloads_;
diff --git a/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc b/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc index 08affbf8..37d701d 100644 --- a/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc +++ b/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc
@@ -303,8 +303,6 @@ const char EPKPChallengeMachineKey::kNonEnterpriseDeviceError[] = "The device is not enterprise enrolled."; -const char EPKPChallengeMachineKey::kKeyName[] = "attest-ent-machine"; - EPKPChallengeMachineKey::EPKPChallengeMachineKey() : EPKPChallengeKeyBase() { } @@ -380,7 +378,7 @@ PrepareKey(chromeos::attestation::KEY_DEVICE, EmptyAccountId(), // Not used. - kKeyName, + chromeos::attestation::kEnterpriseMachineKey, chromeos::attestation::PROFILE_ENTERPRISE_MACHINE_CERTIFICATE, false, // user consent is not required. base::Bind(&EPKPChallengeMachineKey::PrepareKeyCallback, @@ -400,7 +398,8 @@ async_caller_->TpmAttestationSignEnterpriseChallenge( chromeos::attestation::KEY_DEVICE, cryptohome::Identification(), // Not used. - kKeyName, GetEnterpriseDomain(), GetDeviceId(), + chromeos::attestation::kEnterpriseMachineKey, GetEnterpriseDomain(), + GetDeviceId(), register_key ? chromeos::attestation::CHALLENGE_INCLUDE_SIGNED_PUBLIC_KEY : chromeos::attestation::CHALLENGE_OPTION_NONE, challenge, @@ -420,7 +419,7 @@ async_caller_->TpmAttestationRegisterKey( chromeos::attestation::KEY_DEVICE, cryptohome::Identification(), // Not used. - kKeyName, + chromeos::attestation::kEnterpriseMachineKey, base::Bind(&EPKPChallengeMachineKey::RegisterKeyCallback, base::Unretained(this), response)); } else { @@ -450,8 +449,6 @@ const char EPKPChallengeUserKey::kUserKeyNotAvailable[] = "User keys cannot be challenged in this profile."; -const char EPKPChallengeUserKey::kKeyName[] = "attest-ent-user"; - EPKPChallengeUserKey::EPKPChallengeUserKey() : EPKPChallengeKeyBase() { } @@ -544,7 +541,8 @@ return; } - PrepareKey(chromeos::attestation::KEY_USER, GetAccountId(), kKeyName, + PrepareKey(chromeos::attestation::KEY_USER, GetAccountId(), + chromeos::attestation::kEnterpriseUserKey, chromeos::attestation::PROFILE_ENTERPRISE_USER_CERTIFICATE, require_user_consent, base::Bind(&EPKPChallengeUserKey::PrepareKeyCallback, @@ -563,12 +561,13 @@ // Everything is checked. Sign the challenge. async_caller_->TpmAttestationSignEnterpriseChallenge( chromeos::attestation::KEY_USER, - cryptohome::Identification(GetAccountId()), kKeyName, GetUserEmail(), - GetDeviceId(), + cryptohome::Identification(GetAccountId()), + chromeos::attestation::kEnterpriseUserKey, GetUserEmail(), GetDeviceId(), register_key ? chromeos::attestation::CHALLENGE_INCLUDE_SIGNED_PUBLIC_KEY : chromeos::attestation::CHALLENGE_OPTION_NONE, - challenge, base::Bind(&EPKPChallengeUserKey::SignChallengeCallback, - base::Unretained(this), register_key)); + challenge, + base::Bind(&EPKPChallengeUserKey::SignChallengeCallback, + base::Unretained(this), register_key)); } void EPKPChallengeUserKey::SignChallengeCallback(bool register_key, @@ -582,7 +581,8 @@ if (register_key) { async_caller_->TpmAttestationRegisterKey( chromeos::attestation::KEY_USER, - cryptohome::Identification(GetAccountId()), kKeyName, + cryptohome::Identification(GetAccountId()), + chromeos::attestation::kEnterpriseUserKey, base::Bind(&EPKPChallengeUserKey::RegisterKeyCallback, base::Unretained(this), response)); } else {
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index 87aab73..1541558f 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -2025,6 +2025,11 @@ "expiry_milestone": 78 }, { + "name": "file-manager-format-dialog", + "owners": [ "austinct" ], + "expiry_milestone": 78 + }, + { // See https://crbug.com/904630, offical builds only. "name": "file-manager-piex-wasm", "owners": [ "noel" ],
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index 97920a8..fa65c63 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -3111,6 +3111,12 @@ "Enable feedback panel in the Files app."; const char kFileManagerFeedbackPanelName[] = "Files App. feedback panel"; +const char kFileManagerFormatDialogName[] = + "Enable enhanced Files App format dialog."; +const char kFileManagerFormatDialogDescription[] = + "Enable the enhanced external media format dialog in Files App, with " + "with support for labelling and also NTFS/exFAT filesystems."; + const char kFileManagerPiexWasmName[] = "Enable FilesApp piex-wasm module"; const char kFileManagerPiexWasmDescription[] = "Enable the FilesApp piex-wasm raw image extractor module.";
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index b4f8ad7d..87d7270 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -1860,6 +1860,9 @@ extern const char kFileManagerFeedbackPanelDescription[]; extern const char kFileManagerFeedbackPanelName[]; +extern const char kFileManagerFormatDialogDescription[]; +extern const char kFileManagerFormatDialogName[]; + extern const char kFileManagerPiexWasmName[]; extern const char kFileManagerPiexWasmDescription[];
diff --git a/chrome/browser/net/profile_network_context_service.cc b/chrome/browser/net/profile_network_context_service.cc index fc7be14..dcf8e67 100644 --- a/chrome/browser/net/profile_network_context_service.cc +++ b/chrome/browser/net/profile_network_context_service.cc
@@ -15,6 +15,7 @@ #include "base/metrics/histogram_macros.h" #include "base/task/post_task.h" #include "chrome/browser/browser_process.h" +#include "chrome/browser/content_settings/cookie_settings_factory.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings.h" #include "chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings_factory.h" @@ -28,8 +29,8 @@ #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "components/certificate_transparency/pref_names.h" +#include "components/content_settings/core/browser/cookie_settings.h" #include "components/content_settings/core/browser/host_content_settings_map.h" -#include "components/content_settings/core/common/pref_names.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_params.h" #include "components/language/core/browser/pref_names.h" #include "components/metrics/metrics_pref_names.h" @@ -96,7 +97,9 @@ } // namespace ProfileNetworkContextService::ProfileNetworkContextService(Profile* profile) - : profile_(profile), proxy_config_monitor_(profile) { + : profile_(profile), + proxy_config_monitor_(profile), + cookie_settings_observer_(this) { PrefService* profile_prefs = profile->GetPrefs(); quic_allowed_.Init( prefs::kQuicAllowed, profile_prefs, @@ -110,11 +113,9 @@ prefs::kEnableReferrers, profile_prefs, base::BindRepeating(&ProfileNetworkContextService::UpdateReferrersEnabled, base::Unretained(this))); - block_third_party_cookies_.Init( - prefs::kBlockThirdPartyCookies, profile_prefs, - base::BindRepeating( - &ProfileNetworkContextService::UpdateBlockThirdPartyCookies, - base::Unretained(this))); + cookie_settings_ = CookieSettingsFactory::GetForProfile(profile); + cookie_settings_observer_.Add(cookie_settings_.get()); + DisableQuicIfNotAllowed(); // Observe content settings so they can be synced to the network service. @@ -222,7 +223,8 @@ ComputeAcceptLanguage())); } -void ProfileNetworkContextService::UpdateBlockThirdPartyCookies() { +void ProfileNetworkContextService::OnThirdPartyCookieBlockingChanged( + bool block_third_party_cookies) { content::BrowserContext::ForEachStoragePartition( profile_, base::BindRepeating( [](bool block_third_party_cookies, @@ -230,7 +232,7 @@ storage_partition->GetCookieManagerForBrowserProcess() ->BlockThirdPartyCookies(block_third_party_cookies); }, - block_third_party_cookies_.GetValue())); + block_third_party_cookies)); } std::string ProfileNetworkContextService::ComputeAcceptLanguage() const { @@ -332,7 +334,7 @@ network_context_params->cookie_manager_params = network::mojom::CookieManagerParams::New(); network_context_params->cookie_manager_params->block_third_party_cookies = - block_third_party_cookies_.GetValue(); + cookie_settings_->ShouldBlockThirdPartyCookies(); network_context_params->cookie_manager_params ->secure_origin_cookies_allowed_schemes.push_back( content::kChromeUIScheme);
diff --git a/chrome/browser/net/profile_network_context_service.h b/chrome/browser/net/profile_network_context_service.h index b068f6d..c4a44388 100644 --- a/chrome/browser/net/profile_network_context_service.h +++ b/chrome/browser/net/profile_network_context_service.h
@@ -10,10 +10,13 @@ #include "base/files/file_path.h" #include "base/macros.h" +#include "base/memory/scoped_refptr.h" +#include "base/scoped_observer.h" #include "base/timer/timer.h" #include "build/build_config.h" #include "chrome/browser/net/proxy_config_monitor.h" #include "components/content_settings/core/browser/content_settings_observer.h" +#include "components/content_settings/core/browser/cookie_settings.h" #include "components/keyed_service/core/keyed_service.h" #include "components/prefs/pref_change_registrar.h" #include "components/prefs/pref_member.h" @@ -29,8 +32,10 @@ // KeyedService that initializes and provides access to the NetworkContexts for // a Profile. This will eventually replace ProfileIOData. -class ProfileNetworkContextService : public KeyedService, - public content_settings::Observer { +class ProfileNetworkContextService + : public KeyedService, + public content_settings::Observer, + public content_settings::CookieSettings::Observer { public: explicit ProfileNetworkContextService(Profile* profile); ~ProfileNetworkContextService() override; @@ -98,16 +103,23 @@ ContentSettingsType content_type, const std::string& resource_identifier) override; + // content_settings::CookieSettings::Observer: + void OnThirdPartyCookieBlockingChanged( + bool block_third_party_cookies) override; + Profile* const profile_; ProxyConfigMonitor proxy_config_monitor_; BooleanPrefMember quic_allowed_; StringPrefMember pref_accept_language_; - BooleanPrefMember block_third_party_cookies_; BooleanPrefMember enable_referrers_; PrefChangeRegistrar pref_change_registrar_; + scoped_refptr<content_settings::CookieSettings> cookie_settings_; + ScopedObserver<content_settings::CookieSettings, ProfileNetworkContextService> + cookie_settings_observer_; + // Used to post schedule CT policy updates base::OneShotTimer ct_policy_update_timer_;
diff --git a/chrome/browser/offline_pages/offliner_helper.cc b/chrome/browser/offline_pages/offliner_helper.cc index e9f7b75..e48298a1 100644 --- a/chrome/browser/offline_pages/offliner_helper.cc +++ b/chrome/browser/offline_pages/offliner_helper.cc
@@ -4,19 +4,20 @@ #include "chrome/browser/offline_pages/offliner_helper.h" +#include "chrome/browser/content_settings/cookie_settings_factory.h" #include "chrome/browser/net/prediction_options.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h" -#include "components/content_settings/core/common/pref_names.h" +#include "components/content_settings/core/browser/cookie_settings.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_context.h" namespace offline_pages { bool AreThirdPartyCookiesBlocked(content::BrowserContext* browser_context) { - return Profile::FromBrowserContext(browser_context) - ->GetPrefs() - ->GetBoolean(prefs::kBlockThirdPartyCookies); + auto settings = CookieSettingsFactory::GetForProfile( + Profile::FromBrowserContext(browser_context)); + return settings->ShouldBlockThirdPartyCookies(); } bool IsNetworkPredictionDisabled(content::BrowserContext* browser_context) {
diff --git a/chrome/browser/page_load_metrics/observers/data_saver_site_breakdown_metrics_observer_browsertest.cc b/chrome/browser/page_load_metrics/observers/data_saver_site_breakdown_metrics_observer_browsertest.cc index ca9130a..2f316979 100644 --- a/chrome/browser/page_load_metrics/observers/data_saver_site_breakdown_metrics_observer_browsertest.cc +++ b/chrome/browser/page_load_metrics/observers/data_saver_site_breakdown_metrics_observer_browsertest.cc
@@ -8,6 +8,7 @@ #include "base/command_line.h" #include "base/run_loop.h" +#include "base/strings/stringprintf.h" #include "base/test/scoped_feature_list.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings.h" @@ -59,7 +60,10 @@ : public InProcessBrowserTest { protected: void SetUp() override { - scoped_feature_list_.InitWithFeatures({features::kLazyImageLoading}, {}); + scoped_feature_list_.InitWithFeaturesAndParameters( + {{features::kLazyImageLoading, + {{"automatic-lazy-load-images-enabled", "true"}}}}, + {}); InProcessBrowserTest::SetUp(); } @@ -71,6 +75,16 @@ true); } + void WaitForDBToInitialize() { + base::RunLoop run_loop; + DataReductionProxyChromeSettingsFactory::GetForBrowserContext( + browser()->profile()) + ->data_reduction_proxy_service() + ->GetDBTaskRunnerForTesting() + ->PostTask(FROM_HERE, run_loop.QuitClosure()); + run_loop.Run(); + } + void SetUpCommandLine(base::CommandLine* command_line) override { command_line->AppendSwitch( data_reduction_proxy::switches::kEnableDataReductionProxy); @@ -106,6 +120,15 @@ return 0; } + void ScrollToAndWaitForScroll(unsigned int scroll_offset) { + ASSERT_TRUE(content::ExecuteScript( + browser()->tab_strip_model()->GetActiveWebContents(), + base::StringPrintf("window.scrollTo(0, %d);", scroll_offset))); + content::RenderFrameSubmissionObserver observer( + browser()->tab_strip_model()->GetActiveWebContents()); + observer.WaitForScrollOffset(gfx::Vector2dF(0, scroll_offset)); + } + private: base::test::ScopedFeatureList scoped_feature_list_; }; @@ -146,7 +169,8 @@ } IN_PROC_BROWSER_TEST_F(DataSaverSiteBreakdownMetricsObserverBrowserTest, - DISABLED_LazyImagesDataSavings) { + LazyImagesDataSavings) { + WaitForDBToInitialize(); ASSERT_TRUE(embedded_test_server()->Start()); GURL test_url( @@ -169,9 +193,9 @@ data_savings_before_navigation); } -// TODO(rajendrant): Re-enable scrolling browser tests. https://crbug.com/949319 IN_PROC_BROWSER_TEST_F(DataSaverSiteBreakdownMetricsObserverBrowserTest, - DISABLED_LazyImagesDataSavingsScrollRemovesSavings) { + LazyImagesDataSavingsScrollRemovesSavings) { + WaitForDBToInitialize(); ASSERT_TRUE(embedded_test_server()->Start()); GURL test_url( @@ -183,10 +207,7 @@ ui_test_utils::NavigateToURL(browser(), test_url); // Scroll to remove data savings by loading the images. - ASSERT_TRUE(content::ExecuteScript( - browser()->tab_strip_model()->GetActiveWebContents(), - "window.scrollTo(0, 10000);")); - + ScrollToAndWaitForScroll(10000); base::RunLoop().RunUntilIdle(); // Navigate away to force the histogram recording.
diff --git a/chrome/browser/password_manager/chrome_password_manager_client.cc b/chrome/browser/password_manager/chrome_password_manager_client.cc index fef201e9..5af40e6e 100644 --- a/chrome/browser/password_manager/chrome_password_manager_client.cc +++ b/chrome/browser/password_manager/chrome_password_manager_client.cc
@@ -104,6 +104,7 @@ #include "chrome/browser/password_manager/auto_signin_first_run_dialog_android.h" #include "chrome/browser/password_manager/generated_password_saved_infobar_delegate_android.h" #include "chrome/browser/password_manager/password_accessory_controller.h" +#include "chrome/browser/password_manager/password_accessory_controller_impl.h" #include "chrome/browser/password_manager/password_generation_controller.h" #include "chrome/browser/password_manager/save_password_infobar_delegate_android.h" #include "chrome/browser/password_manager/update_password_infobar_delegate_android.h" @@ -118,6 +119,7 @@ #endif using autofill::PasswordForm; +using autofill::mojom::FocusedFieldType; using password_manager::BadMessageReason; using password_manager::ContentPasswordManagerDriverFactory; using password_manager::PasswordManagerClientHelper; @@ -382,13 +384,25 @@ } void ChromePasswordManagerClient::GeneratePassword() { - password_manager::ContentPasswordManagerDriver* driver = +#if defined(OS_ANDROID) + PasswordGenerationController* generation_controller = + PasswordGenerationController::GetIfExisting(web_contents()); + base::WeakPtr<password_manager::PasswordManagerDriver> driver = + generation_controller->GetActiveFrameDriver(); + if (!driver) + return; + password_manager::ContentPasswordManagerDriver* content_driver = + static_cast<password_manager::ContentPasswordManagerDriver*>( + driver.get()); +#else + password_manager::ContentPasswordManagerDriver* content_driver = driver_factory_->GetDriverForFrame(web_contents()->GetFocusedFrame()); +#endif // Using unretained pointer is safe because |this| outlives // ContentPasswordManagerDriver that holds the connection. - driver->GeneratePassword(base::BindOnce( + content_driver->GeneratePassword(base::BindOnce( &ChromePasswordManagerClient::ShowManualPasswordGenerationPopup, - base::Unretained(this), base::AsWeakPtr(driver))); + base::Unretained(this), base::AsWeakPtr(content_driver))); } void ChromePasswordManagerClient::NotifyUserAutoSignin( @@ -707,21 +721,21 @@ return; #if defined(OS_ANDROID) if (PasswordGenerationController::AllowedForWebContents(web_contents())) { - password_manager::PasswordManagerDriver* driver = - driver_factory_->GetDriverForFrame( - password_generation_driver_bindings_.GetCurrentTargetFrame()); - DCHECK(driver); - password_manager_.SetGenerationElementAndReasonForForm( - driver, ui_data.password_form, ui_data.generation_element, - false /* is_manually_triggered */); - PasswordGenerationController::GetOrCreate(web_contents()) - ->OnAutomaticGenerationAvailable(ui_data, driver->AsWeakPtr()); + password_manager::PasswordManagerDriver* driver = + driver_factory_->GetDriverForFrame( + password_generation_driver_bindings_.GetCurrentTargetFrame()); + DCHECK(driver); - gfx::RectF element_bounds_in_screen_space = TransformToRootCoordinates( - password_generation_driver_bindings_.GetCurrentTargetFrame(), - ui_data.bounds); - driver->GetPasswordAutofillManager()->MaybeShowPasswordSuggestions( - element_bounds_in_screen_space, ui_data.text_direction); + PasswordGenerationController* generation_controller = + PasswordGenerationController::GetIfExisting(web_contents()); + DCHECK(generation_controller); + + gfx::RectF element_bounds_in_screen_space = TransformToRootCoordinates( + password_generation_driver_bindings_.GetCurrentTargetFrame(), + ui_data.bounds); + + generation_controller->OnAutomaticGenerationAvailable( + driver, ui_data, element_bounds_in_screen_space); } #else password_manager::ContentPasswordManagerDriver* driver = @@ -817,13 +831,8 @@ } void ChromePasswordManagerClient::GenerationElementLostFocus() { -#if defined(OS_ANDROID) - PasswordGenerationController* generation_controller = - PasswordGenerationController::GetIfExisting(web_contents()); - if (generation_controller) { - generation_controller->OnGenerationElementLostFocus(); - } -#endif + // TODO(crbug.com/968046): Look into removing this since FocusedInputChanged + // seems to be a good replacement. if (popup_controller_) popup_controller_->GenerationElementLostFocus(); } @@ -1006,8 +1015,17 @@ BadMessageReason:: CPMD_BAD_ORIGIN_SHOW_MANUAL_PASSWORD_GENERATION_POPUP)) return; +#if defined(OS_ANDROID) + PasswordGenerationController* password_generation_controller = + PasswordGenerationController::GetIfExisting(web_contents()); + DCHECK(password_generation_controller); + + password_generation_controller->ShowManualGenerationDialog(driver.get(), + ui_data.value()); +#else ShowPasswordGenerationPopup(driver.get(), *ui_data, true /* is_manually_triggered */); +#endif } void ChromePasswordManagerClient::ShowPasswordGenerationPopup( @@ -1041,12 +1059,25 @@ password_manager::PasswordManagerDriver* driver, autofill::mojom::FocusedFieldType focused_field_type) { #if defined(OS_ANDROID) - if (PasswordAccessoryController::AllowedForWebContents(web_contents())) { + password_manager::ContentPasswordManagerDriver* content_driver = + static_cast<password_manager::ContentPasswordManagerDriver*>(driver); + if (!PasswordAccessoryControllerImpl::ShouldAcceptFocusEvent( + web_contents(), content_driver, focused_field_type)) + return; + + if (!PasswordAccessoryController::AllowedForWebContents(web_contents())) + return; + + if (web_contents()->GetFocusedFrame()) { PasswordAccessoryController::GetOrCreate(web_contents()) ->RefreshSuggestionsForField( focused_field_type, password_manager_util::ManualPasswordGenerationEnabled(driver)); } + + PasswordGenerationController::GetOrCreate(web_contents()) + ->FocusedInputChanged(focused_field_type, + base::AsWeakPtr(content_driver)); #endif // defined(OS_ANDROID) }
diff --git a/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc b/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc index f6abf5f5..1cf40ce 100644 --- a/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc +++ b/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc
@@ -17,13 +17,16 @@ #include "base/strings/string16.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" +#include "build/build_config.h" #include "chrome/browser/metrics/chrome_metrics_service_accessor.h" #include "chrome/browser/password_manager/password_store_factory.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "chrome/test/base/testing_profile.h" #include "components/autofill/content/common/autofill_agent.mojom.h" +#include "components/autofill/core/browser/test_autofill_client.h" #include "components/autofill/core/common/password_form.h" +#include "components/password_manager/content/browser/content_password_manager_driver.h" #include "components/password_manager/content/browser/password_manager_internals_service_factory.h" #include "components/password_manager/core/browser/credentials_filter.h" #include "components/password_manager/core/browser/log_manager.h" @@ -33,6 +36,7 @@ #include "components/password_manager/core/browser/password_manager.h" #include "components/password_manager/core/browser/password_manager_internals_service.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" +#include "components/password_manager/core/browser/stub_password_manager_client.h" #include "components/password_manager/core/common/credential_manager_types.h" #include "components/password_manager/core/common/password_manager_pref_names.h" #include "components/prefs/pref_registry_simple.h" @@ -63,14 +67,24 @@ #include "components/safe_browsing/password_protection/mock_password_protection_service.h" #endif +#if defined(OS_ANDROID) +#include "chrome/browser/autofill/manual_filling_controller_impl.h" +#include "chrome/browser/autofill/mock_address_accessory_controller.h" +#include "chrome/browser/autofill/mock_manual_filling_view.h" +#include "chrome/browser/password_manager/password_accessory_controller_impl.h" +#include "chrome/browser/password_manager/password_generation_controller.h" +#endif // defined(OS_ANDROID) + using autofill::PasswordForm; +using autofill::mojom::FocusedFieldType; using content::BrowserContext; using content::WebContents; using password_manager::PasswordManagerClient; using sessions::GetPasswordStateFromNavigation; using sessions::SerializedNavigationEntry; -using testing::Return; using testing::_; +using testing::NiceMock; +using testing::Return; namespace { // TODO(crbug.com/474577): Get rid of the mocked client in the client's own @@ -730,3 +744,111 @@ client->ShowManualFallbackForSaving(std::move(form_manager), false, false); client->HideManualFallbackForSaving(); } + +#if defined(OS_ANDROID) +class ChromePasswordManagerClientAndroidTest + : public ChromePasswordManagerClientTest { + protected: + std::unique_ptr<password_manager::ContentPasswordManagerDriver> + CreateContentPasswordManagerDriver(content::RenderFrameHost* rfh); + + private: + autofill::TestAutofillClient test_autofill_client_; +}; + +std::unique_ptr<password_manager::ContentPasswordManagerDriver> +ChromePasswordManagerClientAndroidTest::CreateContentPasswordManagerDriver( + content::RenderFrameHost* rfh) { + return std::make_unique<password_manager::ContentPasswordManagerDriver>( + rfh, GetClient(), &test_autofill_client_); +} + +TEST_F(ChromePasswordManagerClientAndroidTest, + FocusedInputChangedNoFrameFillableField) { + ASSERT_FALSE(web_contents()->GetFocusedFrame()); + + ChromePasswordManagerClient* client = GetClient(); + + std::unique_ptr<password_manager::ContentPasswordManagerDriver> driver = + CreateContentPasswordManagerDriver(main_rfh()); + client->FocusedInputChanged(driver.get(), + FocusedFieldType::kFillablePasswordField); + + PasswordGenerationController* pwd_generation_controller = + PasswordGenerationController::GetIfExisting(web_contents()); + EXPECT_FALSE(pwd_generation_controller); +} + +TEST_F(ChromePasswordManagerClientAndroidTest, + FocusedInputChangedNoFrameNoField) { + std::unique_ptr<password_manager::ContentPasswordManagerDriver> driver = + CreateContentPasswordManagerDriver(main_rfh()); + + // Simulate that an element was focused before as far as the generation + // controller is concerned. + PasswordGenerationController* pwd_generation_controller = + PasswordGenerationController::GetOrCreate(web_contents()); + pwd_generation_controller->FocusedInputChanged( + FocusedFieldType::kFillablePasswordField, driver.get()->AsWeakPtr()); + + ChromePasswordManagerClient* client = GetClient(); + + NiceMock<MockAddressAccessoryController> mock_address_controller_; + ManualFillingControllerImpl::CreateForWebContentsForTesting( + web_contents(), + PasswordAccessoryControllerImpl::GetOrCreate(web_contents())->AsWeakPtr(), + mock_address_controller_.AsWeakPtr(), + std::make_unique<MockManualFillingView>()); + + ASSERT_FALSE(web_contents()->GetFocusedFrame()); + ASSERT_TRUE(pwd_generation_controller->GetActiveFrameDriver()); + client->FocusedInputChanged(driver.get(), FocusedFieldType::kUnknown); + + // Check that the event was processed by the generation controller and that + // the active frame driver was unset. + EXPECT_FALSE(pwd_generation_controller->GetActiveFrameDriver()); +} + +TEST_F(ChromePasswordManagerClientAndroidTest, FocusedInputChangedWrongFrame) { + ChromePasswordManagerClient* client = GetClient(); + + // Set up the main frame. + NavigateAndCommit(GURL("https://example.com")); + FocusWebContentsOnMainFrame(); + + content::RenderFrameHost* subframe = + content::RenderFrameHostTester::For(main_rfh())->AppendChild("subframe"); + std::unique_ptr<password_manager::ContentPasswordManagerDriver> driver = + CreateContentPasswordManagerDriver(subframe); + client->FocusedInputChanged(driver.get(), + FocusedFieldType::kFillablePasswordField); + + PasswordGenerationController* pwd_generation_controller = + PasswordGenerationController::GetIfExisting(web_contents()); + + // Check that no generation controller was created, since this event should be + // rejected and not passed on to a generation controller. + EXPECT_FALSE(pwd_generation_controller); +} + +TEST_F(ChromePasswordManagerClientAndroidTest, FocusedInputChangedGoodFrame) { + ChromePasswordManagerClient* client = GetClient(); + + NiceMock<MockAddressAccessoryController> mock_address_controller_; + ManualFillingControllerImpl::CreateForWebContentsForTesting( + web_contents(), + PasswordAccessoryControllerImpl::GetOrCreate(web_contents())->AsWeakPtr(), + mock_address_controller_.AsWeakPtr(), + std::make_unique<MockManualFillingView>()); + + std::unique_ptr<password_manager::ContentPasswordManagerDriver> driver = + CreateContentPasswordManagerDriver(main_rfh()); + FocusWebContentsOnMainFrame(); + client->FocusedInputChanged(driver.get(), + FocusedFieldType::kFillablePasswordField); + + PasswordGenerationController* pwd_generation_controller = + PasswordGenerationController::GetIfExisting(web_contents()); + EXPECT_TRUE(pwd_generation_controller); +} +#endif // defined(OS_ANDROID)
diff --git a/chrome/browser/password_manager/password_accessory_controller.h b/chrome/browser/password_manager/password_accessory_controller.h index d96ab41..41e1e1a 100644 --- a/chrome/browser/password_manager/password_accessory_controller.h +++ b/chrome/browser/password_manager/password_accessory_controller.h
@@ -76,6 +76,11 @@ autofill::mojom::FocusedFieldType focused_field_type, bool is_manual_generation_available) = 0; + // Signals that generation was requested from the accessory. |manual| + // indicates whether generation was requested via the manual fallback or from + // the automatically provided button. + virtual void OnGenerationRequested(bool manual) = 0; + // Reacts to a navigation on the main frame, e.g. by clearing caches. virtual void DidNavigateMainFrame() = 0;
diff --git a/chrome/browser/password_manager/password_accessory_controller_impl.cc b/chrome/browser/password_manager/password_accessory_controller_impl.cc index 90777fd..a8159e7 100644 --- a/chrome/browser/password_manager/password_accessory_controller_impl.cc +++ b/chrome/browser/password_manager/password_accessory_controller_impl.cc
@@ -16,10 +16,12 @@ #include "chrome/browser/autofill/manual_filling_utils.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/password_manager/password_accessory_metrics_util.h" +#include "chrome/browser/password_manager/password_generation_controller.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/passwords/manage_passwords_view_utils.h" #include "chrome/browser/vr/vr_tab_helper.h" #include "chrome/grit/generated_resources.h" +#include "components/autofill/core/browser/ui/accessory_sheet_enums.h" #include "components/autofill/core/common/autofill_util.h" #include "components/autofill/core/common/password_form.h" #include "components/autofill/core/common/password_generation_util.h" @@ -149,6 +151,29 @@ web_contents, std::move(mf_controller), favicon_service))); } +// static +bool PasswordAccessoryControllerImpl::ShouldAcceptFocusEvent( + content::WebContents* web_contents, + password_manager::ContentPasswordManagerDriver* driver, + FocusedFieldType focused_field_type) { + // Only react to focus events that are sent for the current focused frame. + // This is used to make sure that obsolette events that come in an unexpected + // order are not processed. Example: (Frame1, focus) -> (Frame2, focus) -> + // (Frame1, unfocus) would otherwise unset all the data set for Frame2, which + // would be wrong. + if (web_contents->GetFocusedFrame() && + driver->render_frame_host() == web_contents->GetFocusedFrame()) + return true; + + // The one event that is accepted even if there is no focused frame is an + // "unfocus" event that resulted in all frames being unfocused. This can be + // used to reset the state of the accessory. + if (!web_contents->GetFocusedFrame() && + focused_field_type == FocusedFieldType::kUnknown) + return true; + return false; +} + void PasswordAccessoryControllerImpl::SavePasswordsForOrigin( const std::map<base::string16, const PasswordForm*>& best_matches, const url::Origin& origin) { @@ -176,7 +201,14 @@ return; } if (selected_action == autofill::AccessoryAction::GENERATE_PASSWORD_MANUAL) { - // TODO(https://crbug.com/835234): Invoke manual generation. + OnGenerationRequested(true /* manual */); + GetManualFillingController()->Hide(); + return; + } + if (selected_action == + autofill::AccessoryAction::GENERATE_PASSWORD_AUTOMATIC) { + OnGenerationRequested(false /* manual */); + GetManualFillingController()->Hide(); return; } NOTREACHED() << "Unhandled selected action: " @@ -236,10 +268,19 @@ GetManualFillingController()->ShowWhenKeyboardIsVisible( FillingSource::PASSWORD_FALLBACKS); } else { - GetManualFillingController()->Hide(FillingSource::PASSWORD_FALLBACKS); + GetManualFillingController()->DeactivateFillingSource( + FillingSource::PASSWORD_FALLBACKS); } } +void PasswordAccessoryControllerImpl::OnGenerationRequested(bool manual) { + PasswordGenerationController* pwd_generation_controller = + PasswordGenerationController::GetIfExisting(web_contents_); + + DCHECK(pwd_generation_controller); + pwd_generation_controller->OnGenerationRequested(manual); +} + void PasswordAccessoryControllerImpl::DidNavigateMainFrame() { favicon_tracker_.TryCancelAll(); // If there is a request pending, cancel it. icons_request_data_.clear();
diff --git a/chrome/browser/password_manager/password_accessory_controller_impl.h b/chrome/browser/password_manager/password_accessory_controller_impl.h index 2d341f8f..fa34093a 100644 --- a/chrome/browser/password_manager/password_accessory_controller_impl.h +++ b/chrome/browser/password_manager/password_accessory_controller_impl.h
@@ -28,6 +28,10 @@ class FaviconService; } // namespace favicon +namespace password_manager { +class ContentPasswordManagerDriver; +} // namespace password_manager + class ManualFillingController; // Encapsulates the data needed from the password manager backend to @@ -71,6 +75,7 @@ void RefreshSuggestionsForField( autofill::mojom::FocusedFieldType focused_field_type, bool is_manual_generation_available) override; + void OnGenerationRequested(bool manual) override; void DidNavigateMainFrame() override; void GetFavicon( int desired_size_in_pixel, @@ -84,6 +89,16 @@ base::WeakPtr<ManualFillingController> mf_controller, favicon::FaviconService* favicon_service); + // True if the focus event was sent for the current focused frame or if it is + // a blur event and no frame is focused. This check avoids reacting to + // obsolete events that arrived in an unexpected order. + // TODO(crbug.com/968162): Introduce the concept of active frame to the + // accessory controller and move this check in the controller. + static bool ShouldAcceptFocusEvent( + content::WebContents* web_contents, + password_manager::ContentPasswordManagerDriver* driver, + autofill::mojom::FocusedFieldType focused_field_type); + private: // Data allowing to cache favicons and favicon-related requests. struct FaviconRequestData;
diff --git a/chrome/browser/password_manager/password_accessory_controller_impl_unittest.cc b/chrome/browser/password_manager/password_accessory_controller_impl_unittest.cc index b8d028f..b9e945d 100644 --- a/chrome/browser/password_manager/password_accessory_controller_impl_unittest.cc +++ b/chrome/browser/password_manager/password_accessory_controller_impl_unittest.cc
@@ -16,6 +16,8 @@ #include "base/test/metrics/histogram_tester.h" #include "base/test/mock_callback.h" #include "chrome/browser/autofill/mock_manual_filling_controller.h" +#include "chrome/browser/password_manager/password_generation_controller.h" +#include "chrome/browser/password_manager/password_generation_controller_impl.h" #include "chrome/grit/generated_resources.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "components/autofill/core/common/password_form.h" @@ -30,6 +32,7 @@ #include "ui/gfx/codec/png_codec.h" namespace { +using autofill::AccessoryAction; using autofill::AccessorySheetData; using autofill::AccessoryTabType; using autofill::FillingStatus; @@ -50,6 +53,29 @@ constexpr char kExampleDomain[] = "example.com"; constexpr int kIconSize = 75; // An example size for favicons (=> 3.5*20px). +class MockPasswordGenerationController + : public PasswordGenerationControllerImpl { + public: + static void CreateForWebContents(content::WebContents* web_contents); + + explicit MockPasswordGenerationController(content::WebContents* web_contents); + + MOCK_METHOD1(OnGenerationRequested, void(bool)); +}; + +// static +void MockPasswordGenerationController::CreateForWebContents( + content::WebContents* web_contents) { + ASSERT_FALSE(FromWebContents(web_contents)); + web_contents->SetUserData( + UserDataKey(), + base::WrapUnique(new MockPasswordGenerationController(web_contents))); +} + +MockPasswordGenerationController::MockPasswordGenerationController( + content::WebContents* web_contents) + : PasswordGenerationControllerImpl(web_contents) {} + // Creates a new map entry in the |first| element of the returned pair. The // |second| element holds the PasswordForm that the |first| element points to. // That way, the pointer only points to a valid address in the called scope. @@ -126,6 +152,7 @@ ASSERT_EQ(url::Origin::Create(GURL(kExampleSite)), web_contents()->GetFocusedFrame()->GetLastCommittedOrigin()); + MockPasswordGenerationController::CreateForWebContents(web_contents()); PasswordAccessoryControllerImpl::CreateForWebContentsForTesting( web_contents(), mock_manual_filling_controller_.AsWeakPtr(), favicon_service()); @@ -136,7 +163,6 @@ return PasswordAccessoryControllerImpl::FromWebContents(web_contents()); } - favicon::MockFaviconService* favicon_service() { return mock_favicon_service_.get(); } @@ -173,7 +199,7 @@ true, false) .Build())); EXPECT_CALL(mock_manual_filling_controller_, - Hide(FillingSource::PASSWORD_FALLBACKS)); + DeactivateFillingSource(FillingSource::PASSWORD_FALLBACKS)); controller()->RefreshSuggestionsForField( FocusedFieldType::kFillableUsernameField, /*is_manual_generation_available=*/false); @@ -194,7 +220,7 @@ password_for_str(no_user_str()), true, false) .Build())); EXPECT_CALL(mock_manual_filling_controller_, - Hide(FillingSource::PASSWORD_FALLBACKS)); + DeactivateFillingSource(FillingSource::PASSWORD_FALLBACKS)); controller()->RefreshSuggestionsForField( FocusedFieldType::kFillableUsernameField, /*is_manual_generation_available=*/false); @@ -233,7 +259,7 @@ false) .Build())); EXPECT_CALL(mock_manual_filling_controller_, - Hide(FillingSource::PASSWORD_FALLBACKS)); + DeactivateFillingSource(FillingSource::PASSWORD_FALLBACKS)); controller()->RefreshSuggestionsForField( FocusedFieldType::kFillableUsernameField, /*is_manual_generation_available=*/false); @@ -256,7 +282,7 @@ true, false) .Build())); EXPECT_CALL(mock_manual_filling_controller_, - Hide(FillingSource::PASSWORD_FALLBACKS)); + DeactivateFillingSource(FillingSource::PASSWORD_FALLBACKS)); controller()->RefreshSuggestionsForField( FocusedFieldType::kFillableUsernameField, /*is_manual_generation_available=*/false); @@ -273,7 +299,7 @@ PasswordAccessorySheetDataBuilder(passwords_empty_str(kExampleDomain)) .Build())); EXPECT_CALL(mock_manual_filling_controller_, - Hide(FillingSource::PASSWORD_FALLBACKS)); + DeactivateFillingSource(FillingSource::PASSWORD_FALLBACKS)); controller()->RefreshSuggestionsForField( FocusedFieldType::kFillableUsernameField, /*is_manual_generation_available=*/false); @@ -310,7 +336,7 @@ true, false) .Build())); EXPECT_CALL(mock_manual_filling_controller_, - Hide(FillingSource::PASSWORD_FALLBACKS)); + DeactivateFillingSource(FillingSource::PASSWORD_FALLBACKS)); controller()->RefreshSuggestionsForField( FocusedFieldType::kFillableUsernameField, /*is_manual_generation_available=*/false); @@ -350,7 +376,7 @@ true, false) .Build())); EXPECT_CALL(mock_manual_filling_controller_, - Hide(FillingSource::PASSWORD_FALLBACKS)); + DeactivateFillingSource(FillingSource::PASSWORD_FALLBACKS)); controller()->RefreshSuggestionsForField( FocusedFieldType::kFillableUsernameField, /*is_manual_generation_available=*/false); @@ -369,7 +395,7 @@ true, false) .Build())); EXPECT_CALL(mock_manual_filling_controller_, - Hide(FillingSource::PASSWORD_FALLBACKS)); + DeactivateFillingSource(FillingSource::PASSWORD_FALLBACKS)); controller()->RefreshSuggestionsForField( FocusedFieldType::kFillableUsernameField, /*is_manual_generation_available=*/false); @@ -392,7 +418,7 @@ true, false) .Build())); EXPECT_CALL(mock_manual_filling_controller_, - Hide(FillingSource::PASSWORD_FALLBACKS)); + DeactivateFillingSource(FillingSource::PASSWORD_FALLBACKS)); controller()->RefreshSuggestionsForField( FocusedFieldType::kFillableUsernameField, /*is_manual_generation_available=*/false); @@ -406,7 +432,7 @@ PasswordAccessorySheetDataBuilder(passwords_empty_str(kExampleDomain)) .Build())); EXPECT_CALL(mock_manual_filling_controller_, - Hide(FillingSource::PASSWORD_FALLBACKS)); + DeactivateFillingSource(FillingSource::PASSWORD_FALLBACKS)); controller()->RefreshSuggestionsForField( FocusedFieldType::kUnfillableElement, /*is_manual_generation_available=*/false); @@ -429,7 +455,7 @@ true, false) .Build())); EXPECT_CALL(mock_manual_filling_controller_, - Hide(FillingSource::PASSWORD_FALLBACKS)); + DeactivateFillingSource(FillingSource::PASSWORD_FALLBACKS)); controller()->RefreshSuggestionsForField( FocusedFieldType::kFillableUsernameField, /*is_manual_generation_available=*/false); @@ -446,7 +472,7 @@ passwords_empty_str("random.other-site.org")) .Build())); EXPECT_CALL(mock_manual_filling_controller_, - Hide(FillingSource::PASSWORD_FALLBACKS)); + DeactivateFillingSource(FillingSource::PASSWORD_FALLBACKS)); controller()->RefreshSuggestionsForField( FocusedFieldType::kUnfillableElement, /*is_manual_generation_available=*/false); @@ -459,7 +485,7 @@ mock_manual_filling_controller_, RefreshSuggestionsForField(FocusedFieldType::kFillableUsernameField, _)); EXPECT_CALL(mock_manual_filling_controller_, - Hide(FillingSource::PASSWORD_FALLBACKS)); + DeactivateFillingSource(FillingSource::PASSWORD_FALLBACKS)); controller()->RefreshSuggestionsForField( FocusedFieldType::kFillableUsernameField, /*is_manual_generation_available=*/false); @@ -486,7 +512,7 @@ mock_manual_filling_controller_, RefreshSuggestionsForField(FocusedFieldType::kFillableUsernameField, _)); EXPECT_CALL(mock_manual_filling_controller_, - Hide(FillingSource::PASSWORD_FALLBACKS)); + DeactivateFillingSource(FillingSource::PASSWORD_FALLBACKS)); controller()->RefreshSuggestionsForField( FocusedFieldType::kFillableUsernameField, /*is_manual_generation_available=*/false); @@ -533,7 +559,7 @@ mock_manual_filling_controller_, RefreshSuggestionsForField(FocusedFieldType::kFillableUsernameField, _)); EXPECT_CALL(mock_manual_filling_controller_, - Hide(FillingSource::PASSWORD_FALLBACKS)); + DeactivateFillingSource(FillingSource::PASSWORD_FALLBACKS)); controller()->RefreshSuggestionsForField( FocusedFieldType::kFillableUsernameField, /*is_manual_generation_available=*/false); @@ -568,7 +594,7 @@ mock_manual_filling_controller_, RefreshSuggestionsForField(FocusedFieldType::kFillableUsernameField, _)); EXPECT_CALL(mock_manual_filling_controller_, - Hide(FillingSource::PASSWORD_FALLBACKS)); + DeactivateFillingSource(FillingSource::PASSWORD_FALLBACKS)); controller()->RefreshSuggestionsForField( FocusedFieldType::kFillableUsernameField, /*is_manual_generation_available=*/false); @@ -596,7 +622,7 @@ RefreshSuggestionsForField(FocusedFieldType::kFillableUsernameField, _)) .Times(2); EXPECT_CALL(mock_manual_filling_controller_, - Hide(FillingSource::PASSWORD_FALLBACKS)); + DeactivateFillingSource(FillingSource::PASSWORD_FALLBACKS)); controller()->RefreshSuggestionsForField( FocusedFieldType::kFillableUsernameField, false); @@ -622,13 +648,21 @@ EXPECT_CALL(mock_callback, Run).Times(0); controller()->GetFavicon(kIconSize, mock_callback.Get()); EXPECT_CALL(mock_manual_filling_controller_, - Hide(FillingSource::PASSWORD_FALLBACKS)); + DeactivateFillingSource(FillingSource::PASSWORD_FALLBACKS)); controller()->RefreshSuggestionsForField( FocusedFieldType::kFillableUsernameField, false); base::RunLoop().RunUntilIdle(); } +TEST_F(PasswordAccessoryControllerTest, OnAutomaticGenerationRequested) { + MockPasswordGenerationController* mock_pwd_generation_controller = + static_cast<MockPasswordGenerationController*>( + PasswordGenerationController::GetIfExisting(web_contents())); + EXPECT_CALL(*mock_pwd_generation_controller, OnGenerationRequested(false)); + controller()->OnGenerationRequested(false); +} + TEST_F(PasswordAccessoryControllerTest, AddsGenerationCommandWhenAvailable) { controller()->SavePasswordsForOrigin({}, url::Origin::Create(GURL(kExampleSite))); @@ -660,8 +694,17 @@ PasswordAccessorySheetDataBuilder(passwords_empty_str(kExampleDomain)) .Build())); EXPECT_CALL(mock_manual_filling_controller_, - Hide(FillingSource::PASSWORD_FALLBACKS)); + DeactivateFillingSource(FillingSource::PASSWORD_FALLBACKS)); controller()->RefreshSuggestionsForField( FocusedFieldType::kFillableUsernameField, /*is_manual_generation_available=*/true); } + +TEST_F(PasswordAccessoryControllerTest, OnManualGenerationRequested) { + MockPasswordGenerationController* mock_pwd_generation_controller = + static_cast<MockPasswordGenerationController*>( + PasswordGenerationController::GetIfExisting(web_contents())); + EXPECT_CALL(mock_manual_filling_controller_, Hide()); + EXPECT_CALL(*mock_pwd_generation_controller, OnGenerationRequested(true)); + controller()->OnOptionSelected(AccessoryAction::GENERATE_PASSWORD_MANUAL); +}
diff --git a/chrome/browser/password_manager/password_generation_controller.h b/chrome/browser/password_manager/password_generation_controller.h index fe1c499..8383ae5f 100644 --- a/chrome/browser/password_manager/password_generation_controller.h +++ b/chrome/browser/password_manager/password_generation_controller.h
@@ -8,11 +8,14 @@ #include <memory> #include "base/memory/weak_ptr.h" +#include "components/autofill/core/common/mojom/autofill_types.mojom.h" #include "components/autofill/core/common/password_generation_util.h" #include "content/public/browser/web_contents.h" +#include "ui/gfx/geometry/rect.h" namespace password_manager { class PasswordManagerDriver; +class PasswordManagerDriver; } // namespace password_manager // Interface for the controller responsible for overseeing the UI flow for @@ -22,7 +25,7 @@ // it manages the modal dialog used to display the generated password. // // There is a single instance per WebContents that can be accessed by calling: -// PasswordAccessoryController::GetOrCreate(web_contents); +// PasswordGenerationController::GetOrCreate(web_contents); // On the first call, an instance is attached to |web_contents|, so it can be // returned by subsequent calls. class PasswordGenerationController { @@ -50,15 +53,31 @@ // Methods called by the ChromePasswordManagerClient: // -------------------------------------------------- + // Returns the driver associated with the frame that is considered active + // for generation. + virtual base::WeakPtr<password_manager::PasswordManagerDriver> + GetActiveFrameDriver() const = 0; + + // This signals that the focus has moved. |focused_field_type| tells + // the generation controller whether the focus moved to a fillable password + // field. This event sets/unsets the active frame for generation. + virtual void FocusedInputChanged( + autofill::mojom::FocusedFieldType focused_field_type, + base::WeakPtr<password_manager::PasswordManagerDriver> driver) = 0; + // Notifies the UI that automatic password generation is available. // A button should be displayed in the accessory bar. virtual void OnAutomaticGenerationAvailable( + const password_manager::PasswordManagerDriver* target_frame_driver, const autofill::password_generation::PasswordGenerationUIData& ui_data, - const base::WeakPtr<password_manager::PasswordManagerDriver>& driver) = 0; + gfx::RectF element_bounds_in_screen_space) = 0; - // Notifies the UI that the generation element lost focus so that it can - // hide the generation button if it was shown. - virtual void OnGenerationElementLostFocus() = 0; + // This is called after the user requested manual generation and the + // corresponding setup was done in the renderer. + virtual void ShowManualGenerationDialog( + const password_manager::PasswordManagerDriver* target_frame_driver, + const autofill::password_generation::PasswordGenerationUIData& + ui_data) = 0; // ------------------------- // Methods called by the UI: @@ -66,7 +85,9 @@ // Called by the UI code to signal that the user requested password // generation. This should prompt a modal dialog with the generated password. - virtual void OnGenerationRequested() = 0; + // |manual| - whether the requests originates from a an automatic + // generation flow or from a manual one. + virtual void OnGenerationRequested(bool manual) = 0; // Called from the modal dialog if the user accepted the generated password. // |driver| is used to communicate the message back to the renderer.
diff --git a/chrome/browser/password_manager/password_generation_controller_impl.cc b/chrome/browser/password_manager/password_generation_controller_impl.cc index 0e1431d..1b57601 100644 --- a/chrome/browser/password_manager/password_generation_controller_impl.cc +++ b/chrome/browser/password_manager/password_generation_controller_impl.cc
@@ -10,8 +10,10 @@ #include "base/callback.h" #include "base/metrics/histogram_macros.h" #include "chrome/browser/autofill/manual_filling_controller.h" +#include "chrome/browser/password_manager/chrome_password_manager_client.h" #include "chrome/browser/password_manager/password_accessory_controller.h" #include "chrome/browser/password_manager/password_generation_dialog_view_interface.h" +#include "components/autofill/core/common/autofill_features.h" #include "components/autofill/core/common/password_form.h" #include "components/autofill/core/common/password_generation_util.h" #include "components/autofill/core/common/signatures_util.h" @@ -19,6 +21,8 @@ #include "components/password_manager/core/browser/password_manager.h" #include "components/password_manager/core/browser/password_manager_driver.h" +using autofill::mojom::FocusedFieldType; + namespace { void RecordGenerationDialogDismissal(bool accepted) { @@ -60,6 +64,18 @@ field_signature(field_signature), max_password_length(max_password_length) {} + GenerationElementData( + const autofill::password_generation::PasswordGenerationUIData& ui_data) { + const std::string kFieldType = "password"; + + form = ui_data.password_form; + form_signature = + autofill::CalculateFormSignature(ui_data.password_form.form_data); + field_signature = autofill::CalculateFieldSignatureByNameAndType( + ui_data.generation_element, kFieldType); + max_password_length = ui_data.max_length; + } + // Form for which password generation is triggered. autofill::PasswordForm form; @@ -73,16 +89,32 @@ uint32_t max_password_length; }; +base::WeakPtr<password_manager::PasswordManagerDriver> +PasswordGenerationControllerImpl::GetActiveFrameDriver() const { + return active_frame_driver_; +} + void PasswordGenerationControllerImpl::OnAutomaticGenerationAvailable( + const password_manager::PasswordManagerDriver* target_frame_driver, const autofill::password_generation::PasswordGenerationUIData& ui_data, - const base::WeakPtr<password_manager::PasswordManagerDriver>& driver) { - target_frame_driver_ = driver; - generation_element_data_ = std::make_unique<GenerationElementData>( - ui_data.password_form, - autofill::CalculateFormSignature(ui_data.password_form.form_data), - autofill::CalculateFieldSignatureByNameAndType(ui_data.generation_element, - "password"), - ui_data.max_length); + gfx::RectF element_bounds_in_screen_space) { + if (!IsActiveFrameDriver(target_frame_driver)) + return; + DCHECK(!dialog_view_); + + active_frame_driver_->GetPasswordManager() + ->SetGenerationElementAndReasonForForm( + active_frame_driver_.get(), ui_data.password_form, + ui_data.generation_element, false /* is_manually_triggered */); + + if (!base::FeatureList::IsEnabled( + autofill::features::kAutofillKeyboardAccessory)) { + active_frame_driver_->GetPasswordAutofillManager() + ->MaybeShowPasswordSuggestions(element_bounds_in_screen_space, + ui_data.text_direction); + } + + generation_element_data_ = std::make_unique<GenerationElementData>(ui_data); if (!manual_filling_controller_) { manual_filling_controller_ = @@ -93,32 +125,30 @@ manual_filling_controller_->OnAutomaticGenerationStatusChanged(true); } -void PasswordGenerationControllerImpl::OnGenerationElementLostFocus() { - if (manual_filling_controller_ && generation_element_data_) { - manual_filling_controller_->OnAutomaticGenerationStatusChanged(false); - } - target_frame_driver_ = nullptr; - generation_element_data_.reset(); +void PasswordGenerationControllerImpl::ShowManualGenerationDialog( + const password_manager::PasswordManagerDriver* target_frame_driver, + const autofill::password_generation::PasswordGenerationUIData& ui_data) { + if (!IsActiveFrameDriver(target_frame_driver)) + return; + generation_element_data_ = std::make_unique<GenerationElementData>(ui_data); + ShowDialog(true /* manual */); } -void PasswordGenerationControllerImpl::OnGenerationRequested() { - if (!target_frame_driver_) - return; - dialog_view_ = create_dialog_factory_.Run(this); - uint32_t spec_priority = 0; - base::string16 password = - target_frame_driver_->GetPasswordGenerationHelper()->GeneratePassword( - web_contents_->GetLastCommittedURL().GetOrigin(), - generation_element_data_->form_signature, - generation_element_data_->field_signature, - generation_element_data_->max_password_length, &spec_priority); - if (target_frame_driver_ && target_frame_driver_->GetPasswordManager()) { - target_frame_driver_->GetPasswordManager() - ->ReportSpecPriorityForGeneratedPassword(generation_element_data_->form, - spec_priority); +void PasswordGenerationControllerImpl::FocusedInputChanged( + autofill::mojom::FocusedFieldType focused_field_type, + base::WeakPtr<password_manager::PasswordManagerDriver> driver) { + ResetState(); + if (focused_field_type == FocusedFieldType::kFillablePasswordField) + active_frame_driver_ = std::move(driver); +} + +void PasswordGenerationControllerImpl::OnGenerationRequested(bool manual) { + if (manual) { + ChromePasswordManagerClient::FromWebContents(web_contents_) + ->GeneratePassword(); + } else { + ShowDialog(false /* manual */); } - dialog_view_->Show(password, std::move(target_frame_driver_)); - target_frame_driver_ = nullptr; } void PasswordGenerationControllerImpl::GeneratedPasswordAccepted( @@ -128,12 +158,12 @@ return; RecordGenerationDialogDismissal(true); driver->GeneratedPasswordAccepted(password); - dialog_view_.reset(); + ResetState(); } void PasswordGenerationControllerImpl::GeneratedPasswordRejected() { RecordGenerationDialogDismissal(false); - dialog_view_.reset(); + ResetState(); } gfx::NativeWindow PasswordGenerationControllerImpl::top_level_native_window() @@ -171,4 +201,46 @@ manual_filling_controller_(std::move(manual_filling_controller_)), create_dialog_factory_(create_dialog_factory) {} +void PasswordGenerationControllerImpl::ShowDialog(bool manual) { + if (!active_frame_driver_ || dialog_view_) { + return; + } + + // TODO(crbug.com/894756): Add a test helper that sets this up correctly. + if (!generation_element_data_) { + /* This can currently happen in integration tests that are iniated from + the java side. */ + return; + } + + dialog_view_ = create_dialog_factory_.Run(this); + + uint32_t spec_priority = 0; + base::string16 password = + active_frame_driver_->GetPasswordGenerationHelper()->GeneratePassword( + web_contents_->GetLastCommittedURL().GetOrigin(), + generation_element_data_->form_signature, + generation_element_data_->field_signature, + generation_element_data_->max_password_length, &spec_priority); + active_frame_driver_->GetPasswordManager() + ->ReportSpecPriorityForGeneratedPassword(generation_element_data_->form, + spec_priority); + dialog_view_->Show(password, active_frame_driver_); +} + +bool PasswordGenerationControllerImpl::IsActiveFrameDriver( + const password_manager::PasswordManagerDriver* driver) const { + if (!active_frame_driver_) + return false; + return active_frame_driver_.get() == driver; +} + +void PasswordGenerationControllerImpl::ResetState() { + if (manual_filling_controller_) + manual_filling_controller_->OnAutomaticGenerationStatusChanged(false); + active_frame_driver_.reset(); + generation_element_data_.reset(); + dialog_view_.reset(); +} + WEB_CONTENTS_USER_DATA_KEY_IMPL(PasswordGenerationControllerImpl)
diff --git a/chrome/browser/password_manager/password_generation_controller_impl.h b/chrome/browser/password_manager/password_generation_controller_impl.h index 3a6ed7f..4da1cd0 100644 --- a/chrome/browser/password_manager/password_generation_controller_impl.h +++ b/chrome/browser/password_manager/password_generation_controller_impl.h
@@ -11,10 +11,15 @@ #include "chrome/browser/password_manager/password_generation_controller.h" #include "components/autofill/core/common/password_generation_util.h" #include "content/public/browser/web_contents_user_data.h" +#include "ui/gfx/geometry/rect.h" class ManualFillingController; class PasswordGenerationDialogViewInterface; +namespace password_manager { +class PasswordManagerDriver; +} // namespace password_manager + // In its current state, this class is not involved in the editing flow for // a generated password. // @@ -27,16 +32,23 @@ public: using CreateDialogFactory = base::RepeatingCallback<std::unique_ptr< PasswordGenerationDialogViewInterface>(PasswordGenerationController*)>; - ~PasswordGenerationControllerImpl() override; // PasswordGenerationController: + base::WeakPtr<password_manager::PasswordManagerDriver> GetActiveFrameDriver() + const override; + void FocusedInputChanged( + autofill::mojom::FocusedFieldType focused_field_type, + base::WeakPtr<password_manager::PasswordManagerDriver> driver) override; void OnAutomaticGenerationAvailable( + const password_manager::PasswordManagerDriver* target_frame_driver, const autofill::password_generation::PasswordGenerationUIData& ui_data, - const base::WeakPtr<password_manager::PasswordManagerDriver>& driver) + gfx::RectF element_bounds_in_screen_space) override; + void ShowManualGenerationDialog( + const password_manager::PasswordManagerDriver* target_frame_driver, + const autofill::password_generation::PasswordGenerationUIData& ui_data) override; - void OnGenerationElementLostFocus() override; - void OnGenerationRequested() override; + void OnGenerationRequested(bool manual) override; void GeneratedPasswordAccepted( const base::string16& password, base::WeakPtr<password_manager::PasswordManagerDriver> driver) override; @@ -51,6 +63,10 @@ base::WeakPtr<ManualFillingController> manual_filling_controller, CreateDialogFactory create_dialog_callback); + protected: + // Callable in tests. + explicit PasswordGenerationControllerImpl(content::WebContents* web_contents); + private: // Data including the form and field for which generation was requested, // their signatures and the maximum password size. @@ -58,22 +74,38 @@ friend class content::WebContentsUserData<PasswordGenerationControllerImpl>; - explicit PasswordGenerationControllerImpl(content::WebContents* web_contents); - // Constructor that allows to inject a mock or fake view. PasswordGenerationControllerImpl( content::WebContents* web_contents, base::WeakPtr<ManualFillingController> manual_filling_controller, CreateDialogFactory create_dialog_callback); + // Checks if the given PasswordManagerDriver is the same as the one + // belonging to the currently considered active frame for generation. + // The active frame is the latest focused frame that received a field focus + // event. + bool IsActiveFrameDriver( + const password_manager::PasswordManagerDriver* driver) const; + + // Called to show the generation modal dialog. |manual| - whether the + // dialog was shown for a manual or automatic generation flow. This is used + // for metrics. + void ShowDialog(bool manual); + + // Resets the current active frame driver, as well as the dialog if shown + // and the generation element data. + void ResetState(); + // The tab for which this class is scoped. content::WebContents* web_contents_; // Data for the generation element used to generate the password. std::unique_ptr<GenerationElementData> generation_element_data_; - // Password manager driver for the target frame used for password generation. - base::WeakPtr<password_manager::PasswordManagerDriver> target_frame_driver_; + // Password manager driver for the currently active frame. This is set + // when a password field focus event arrives from the renderer and unset + // whenever a focus event for a non-password field is received. + base::WeakPtr<password_manager::PasswordManagerDriver> active_frame_driver_; // The manual filling controller object to forward client requests to. base::WeakPtr<ManualFillingController> manual_filling_controller_;
diff --git a/chrome/browser/password_manager/password_generation_controller_impl_unittest.cc b/chrome/browser/password_manager/password_generation_controller_impl_unittest.cc index aec5d3f..54aed4d2 100644 --- a/chrome/browser/password_manager/password_generation_controller_impl_unittest.cc +++ b/chrome/browser/password_manager/password_generation_controller_impl_unittest.cc
@@ -12,18 +12,28 @@ #include "base/test/metrics/histogram_tester.h" #include "base/test/mock_callback.h" #include "chrome/browser/autofill/mock_manual_filling_controller.h" +#include "chrome/browser/password_manager/chrome_password_manager_client.h" #include "chrome/browser/password_manager/password_generation_dialog_view_interface.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" +#include "components/autofill/core/browser/autofill_client.h" +#include "components/autofill/core/browser/test_autofill_client.h" +#include "components/password_manager/core/browser/mock_password_store.h" +#include "components/password_manager/core/browser/password_autofill_manager.h" #include "components/password_manager/core/browser/password_generation_frame_helper.h" +#include "components/password_manager/core/browser/password_manager.h" +#include "components/password_manager/core/browser/stub_password_manager_client.h" #include "components/password_manager/core/browser/stub_password_manager_driver.h" +#include "content/public/browser/web_contents.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace { using autofill::FooterCommand; using autofill::PasswordForm; +using autofill::mojom::FocusedFieldType; using autofill::password_generation::PasswordGenerationUIData; using base::ASCIIToUTF16; +using password_manager::MockPasswordStore; using testing::_; using testing::ByMove; using testing::Eq; @@ -32,14 +42,69 @@ using testing::Return; using testing::StrictMock; +class TestPasswordManagerClient : public ChromePasswordManagerClient { + public: + static TestPasswordManagerClient* CreateForWebContents( + content::WebContents* web_contents, + autofill::AutofillClient* autofill_client); + + TestPasswordManagerClient(content::WebContents* web_contents, + autofill::AutofillClient* autofill_client); + ~TestPasswordManagerClient() override; + + bool IsSavingAndFillingEnabled(const GURL& url) const override; + password_manager::PasswordStore* GetPasswordStore() const override; + + private: + scoped_refptr<MockPasswordStore> mock_password_store_; +}; + +// static +TestPasswordManagerClient* TestPasswordManagerClient::CreateForWebContents( + content::WebContents* web_contents, + autofill::AutofillClient* autofill_client) { + if (FromWebContents(web_contents)) + ADD_FAILURE() << "Can't attatch TestPasswordManagerClient to WebContents. " + "A ChromePasswordManagerClient is already attatched to " + "the given WebContents."; + TestPasswordManagerClient* test_client = + new TestPasswordManagerClient(web_contents, autofill_client); + web_contents->SetUserData(UserDataKey(), base::WrapUnique(test_client)); + return test_client; +} + +TestPasswordManagerClient::TestPasswordManagerClient( + content::WebContents* web_contents, + autofill::AutofillClient* autofill_client) + : ChromePasswordManagerClient(web_contents, autofill_client) { + mock_password_store_ = new MockPasswordStore(); +} + +TestPasswordManagerClient::~TestPasswordManagerClient() { + mock_password_store_->ShutdownOnUIThread(); +} + +bool TestPasswordManagerClient::IsSavingAndFillingEnabled( + const GURL& url) const { + return true; +} + +password_manager::PasswordStore* TestPasswordManagerClient::GetPasswordStore() + const { + return mock_password_store_.get(); +} + class MockPasswordManagerDriver : public password_manager::StubPasswordManagerDriver { public: MockPasswordManagerDriver() = default; + MOCK_METHOD1(GeneratedPasswordAccepted, void(const base::string16&)); MOCK_METHOD0(GetPasswordGenerationHelper, password_manager::PasswordGenerationFrameHelper*()); - MOCK_METHOD1(GeneratedPasswordAccepted, void(const base::string16&)); + MOCK_METHOD0(GetPasswordManager, password_manager::PasswordManager*()); + MOCK_METHOD0(GetPasswordAutofillManager, + password_manager::PasswordAutofillManager*()); private: DISALLOW_COPY_AND_ASSIGN(MockPasswordManagerDriver); @@ -72,6 +137,9 @@ MOCK_METHOD2(Show, void(base::string16&, base::WeakPtr<password_manager::PasswordManagerDriver>)); + MOCK_METHOD0(Destroy, void()); + + virtual ~MockPasswordGenerationDialogView() { Destroy(); } private: DISALLOW_COPY_AND_ASSIGN(MockPasswordGenerationDialogView); @@ -119,14 +187,37 @@ PasswordGenerationControllerImpl::CreateForWebContentsForTesting( web_contents(), mock_manual_filling_controller_.AsWeakPtr(), mock_dialog_factory_.Get()); + test_pwd_manager_client_ = TestPasswordManagerClient::CreateForWebContents( + web_contents(), &test_autofill_client_); + password_manager_ = std::make_unique<password_manager::PasswordManager>( + test_pwd_manager_client_); mock_password_manager_driver_ = std::make_unique<NiceMock<MockPasswordManagerDriver>>(); + + // TODO(crbug.com/969051): Remove once kAutofillKeyboardAccessory is + // enabled. + password_autofill_manager_ = + std::make_unique<password_manager::PasswordAutofillManager>( + mock_password_manager_driver_.get(), &test_autofill_client_, + test_pwd_manager_client_); + + ON_CALL(*mock_password_manager_driver_, GetPasswordManager()) + .WillByDefault(Return(password_manager_.get())); + ON_CALL(*mock_password_manager_driver_, GetPasswordAutofillManager()) + .WillByDefault(Return(password_autofill_manager_.get())); + mock_generation_helper_ = std::make_unique<NiceMock<MockPasswordGenerationHelper>>( nullptr, mock_password_manager_driver_.get()); mock_dialog_ = std::make_unique<NiceMock<MockPasswordGenerationDialogView>>(); + + EXPECT_CALL(mock_manual_filling_controller_, + OnAutomaticGenerationStatusChanged(false)); + controller()->FocusedInputChanged( + FocusedFieldType::kFillablePasswordField, + base::AsWeakPtr(mock_password_manager_driver_.get())); } PasswordGenerationController* controller() { @@ -142,7 +233,10 @@ protected: // Sets up mocks needed by the generation flow and signals the // |PasswordGenerationController| that generation is available. - void InitializeGeneration(const base::string16& password); + void InitializeAutomaticGeneration(const base::string16& password); + + // Sets up mocks needed by the generation flow. + void InitializeManualGeneration(const base::string16& password); StrictMock<MockManualFillingController> mock_manual_filling_controller_; @@ -156,9 +250,14 @@ NiceMock< base::MockCallback<PasswordGenerationControllerImpl::CreateDialogFactory>> mock_dialog_factory_; + std::unique_ptr<password_manager::PasswordManager> password_manager_; + std::unique_ptr<password_manager::PasswordAutofillManager> + password_autofill_manager_; + TestPasswordManagerClient* test_pwd_manager_client_ = nullptr; + autofill::TestAutofillClient test_autofill_client_; }; -void PasswordGenerationControllerTest::InitializeGeneration( +void PasswordGenerationControllerTest::InitializeAutomaticGeneration( const base::string16& password) { ON_CALL(*mock_password_manager_driver_, GetPasswordGenerationHelper()) .WillByDefault(Return(mock_generation_helper_.get())); @@ -167,13 +266,20 @@ OnAutomaticGenerationStatusChanged(true)); controller()->OnAutomaticGenerationAvailable( - GetTestGenerationUIData1(), mock_password_manager_driver_->AsWeakPtr()); + mock_password_manager_driver_.get(), GetTestGenerationUIData1(), + gfx::RectF(100, 20)); ON_CALL(*mock_generation_helper_, GeneratePassword(_, _, _, _, _)) .WillByDefault(Return(password)); +} - ON_CALL(mock_dialog_factory(), Run) - .WillByDefault(Return(ByMove(std::move(mock_dialog_)))); +void PasswordGenerationControllerTest::InitializeManualGeneration( + const base::string16& password) { + ON_CALL(*mock_password_manager_driver_, GetPasswordGenerationHelper()) + .WillByDefault(Return(mock_generation_helper_.get())); + + ON_CALL(*mock_generation_helper_, GeneratePassword(_, _, _, _, _)) + .WillByDefault(Return(password)); } TEST_F(PasswordGenerationControllerTest, IsNotRecreatedForSameWebContents) { @@ -188,27 +294,9 @@ TEST_F(PasswordGenerationControllerTest, RelaysAutomaticGenerationAvailable) { EXPECT_CALL(mock_manual_filling_controller_, OnAutomaticGenerationStatusChanged(true)); - controller()->OnAutomaticGenerationAvailable(GetTestGenerationUIData1(), - nullptr); -} - -TEST_F(PasswordGenerationControllerTest, OnlySignalsGenerationUnavailableOnce) { - EXPECT_CALL(mock_manual_filling_controller_, - OnAutomaticGenerationStatusChanged(true)); controller()->OnAutomaticGenerationAvailable( - GetTestGenerationUIData1(), mock_password_manager_driver_->AsWeakPtr()); - EXPECT_CALL(mock_manual_filling_controller_, - OnAutomaticGenerationStatusChanged(false)); - controller()->OnGenerationElementLostFocus(); - controller()->OnGenerationElementLostFocus(); -} - -TEST_F(PasswordGenerationControllerTest, - OnlySendsGenerationUnavailableIfAvailableBefore) { - EXPECT_CALL(mock_manual_filling_controller_, - OnAutomaticGenerationStatusChanged(false)) - .Times(0); - controller()->OnGenerationElementLostFocus(); + mock_password_manager_driver_.get(), GetTestGenerationUIData1(), + gfx::RectF(100, 20)); } // Tests that if AutomaticGenerationAvailable is called for different @@ -221,10 +309,11 @@ OnAutomaticGenerationStatusChanged(true)) .Times(2); controller()->OnAutomaticGenerationAvailable( - GetTestGenerationUIData1(), mock_password_manager_driver_->AsWeakPtr()); + mock_password_manager_driver_.get(), GetTestGenerationUIData1(), + gfx::RectF(100, 20)); PasswordGenerationUIData new_ui_data = GetTestGenerationUIData2(); controller()->OnAutomaticGenerationAvailable( - new_ui_data, mock_password_manager_driver_->AsWeakPtr()); + mock_password_manager_driver_.get(), new_ui_data, gfx::RectF(100, 20)); autofill::FormSignature form_signature = autofill::CalculateFormSignature(new_ui_data.password_form.form_data); @@ -232,9 +321,9 @@ autofill::CalculateFieldSignatureByNameAndType( new_ui_data.generation_element, "password"); - MockPasswordGenerationDialogView* raw_dialog_view = mock_dialog_.get(); - base::string16 generated_password = ASCIIToUTF16("t3stp@ssw0rd"); + NiceMock<MockPasswordGenerationDialogView>* raw_dialog_view = + mock_dialog_.get(); EXPECT_CALL(mock_dialog_factory(), Run) .WillOnce(Return(ByMove(std::move(mock_dialog_)))); EXPECT_CALL(*mock_password_manager_driver_, GetPasswordGenerationHelper()) @@ -246,17 +335,22 @@ EXPECT_CALL(*raw_dialog_view, Show(generated_password, PointsToSameAddress(mock_password_manager_driver_.get()))); - controller()->OnGenerationRequested(); + controller()->OnGenerationRequested(false); } TEST_F(PasswordGenerationControllerTest, RecordsGeneratedPasswordRejected) { base::string16 test_password = ASCIIToUTF16("t3stp@ssw0rd"); - InitializeGeneration(test_password); + InitializeAutomaticGeneration(test_password); base::HistogramTester histogram_tester; - controller()->OnGenerationRequested(); + EXPECT_CALL(mock_dialog_factory(), Run) + .WillOnce(Return(ByMove(std::move(mock_dialog_)))); + controller()->OnGenerationRequested(false); + + EXPECT_CALL(mock_manual_filling_controller_, + OnAutomaticGenerationStatusChanged(false)); controller()->GeneratedPasswordRejected(); histogram_tester.ExpectUniqueSample( @@ -266,11 +360,16 @@ TEST_F(PasswordGenerationControllerTest, RecordsGeneratedPasswordAccepted) { base::string16 test_password = ASCIIToUTF16("t3stp@ssw0rd"); - InitializeGeneration(test_password); + InitializeAutomaticGeneration(test_password); base::HistogramTester histogram_tester; - controller()->OnGenerationRequested(); + EXPECT_CALL(mock_dialog_factory(), Run) + .WillOnce(Return(ByMove(std::move(mock_dialog_)))); + controller()->OnGenerationRequested(false); + + EXPECT_CALL(mock_manual_filling_controller_, + OnAutomaticGenerationStatusChanged(false)); controller()->GeneratedPasswordAccepted( test_password, mock_password_manager_driver_->AsWeakPtr()); @@ -279,22 +378,96 @@ } TEST_F(PasswordGenerationControllerTest, - RelaysGenerationAcceptedToCorrectDriver) { - base::string16 test_password = ASCIIToUTF16("t3stp@ssw0rd"); - - InitializeGeneration(test_password); - - controller()->OnGenerationRequested(); - - MockPasswordManagerDriver wrong_driver; + RejectAutomaticAvailableForNonActiveFrame) { EXPECT_CALL(mock_manual_filling_controller_, - OnAutomaticGenerationStatusChanged(true)); - controller()->OnAutomaticGenerationAvailable(GetTestGenerationUIData2(), - wrong_driver.AsWeakPtr()); + OnAutomaticGenerationStatusChanged(_)) + .Times(0); + MockPasswordManagerDriver wrong_driver; + controller()->OnAutomaticGenerationAvailable( + &wrong_driver, GetTestGenerationUIData2(), gfx::RectF(100, 20)); +} - EXPECT_CALL(*mock_password_manager_driver_, - GeneratedPasswordAccepted(test_password)); - EXPECT_CALL(wrong_driver, GeneratedPasswordAccepted(_)).Times(0); - controller()->GeneratedPasswordAccepted( - test_password, mock_password_manager_driver_->AsWeakPtr()); +TEST_F(PasswordGenerationControllerTest, + ResetStateWhenFocusChangesToNonPassword) { + EXPECT_CALL(mock_manual_filling_controller_, + OnAutomaticGenerationStatusChanged(false)); + + MockPasswordManagerDriver new_driver; + controller()->FocusedInputChanged(FocusedFieldType::kFillableUsernameField, + base::AsWeakPtr(&new_driver)); + EXPECT_FALSE(controller()->GetActiveFrameDriver()); +} + +TEST_F(PasswordGenerationControllerTest, + ResetStateWhenFocusChangesToOtherFramePassword) { + EXPECT_CALL(mock_manual_filling_controller_, + OnAutomaticGenerationStatusChanged(false)); + + MockPasswordManagerDriver new_driver; + controller()->FocusedInputChanged(FocusedFieldType::kFillablePasswordField, + base::AsWeakPtr(&new_driver)); + EXPECT_EQ(&new_driver, controller()->GetActiveFrameDriver().get()); +} + +TEST_F(PasswordGenerationControllerTest, HidesDialogWhenFocusChanges) { + base::string16 test_password = ASCIIToUTF16("t3stp@ssw0rd"); + InitializeManualGeneration(test_password); + NiceMock<MockPasswordGenerationDialogView>* raw_dialog_view = + mock_dialog_.get(); + EXPECT_CALL(mock_dialog_factory(), Run) + .WillOnce(Return(ByMove(std::move(mock_dialog_)))); + EXPECT_CALL(*raw_dialog_view, + Show(test_password, + PointsToSameAddress(mock_password_manager_driver_.get()))); + controller()->ShowManualGenerationDialog(mock_password_manager_driver_.get(), + GetTestGenerationUIData1()); + EXPECT_CALL(mock_manual_filling_controller_, + OnAutomaticGenerationStatusChanged(false)); + EXPECT_CALL(*raw_dialog_view, Destroy()); + controller()->FocusedInputChanged( + FocusedFieldType::kFillableUsernameField, + base::AsWeakPtr(mock_password_manager_driver_.get())); + Mock::VerifyAndClearExpectations(raw_dialog_view); +} + +TEST_F(PasswordGenerationControllerTest, ShowManualDialogForActiveFrame) { + base::string16 test_password = ASCIIToUTF16("t3stp@ssw0rd"); + InitializeManualGeneration(test_password); + NiceMock<MockPasswordGenerationDialogView>* raw_dialog_view = + mock_dialog_.get(); + EXPECT_CALL(mock_dialog_factory(), Run) + .WillOnce(Return(ByMove(std::move(mock_dialog_)))); + EXPECT_CALL(*raw_dialog_view, + Show(test_password, + PointsToSameAddress(mock_password_manager_driver_.get()))); + controller()->ShowManualGenerationDialog(mock_password_manager_driver_.get(), + GetTestGenerationUIData1()); +} + +TEST_F(PasswordGenerationControllerTest, + RejectShowManualDialogForNonActiveFrame) { + MockPasswordManagerDriver wrong_driver; + EXPECT_CALL(mock_dialog_factory(), Run).Times(0); + controller()->ShowManualGenerationDialog(&wrong_driver, + GetTestGenerationUIData1()); +} + +TEST_F(PasswordGenerationControllerTest, DontShowDialogIfAlreadyShown) { + base::string16 test_password = ASCIIToUTF16("t3stp@ssw0rd"); + InitializeManualGeneration(test_password); + + NiceMock<MockPasswordGenerationDialogView>* raw_dialog_view = + mock_dialog_.get(); + EXPECT_CALL(mock_dialog_factory(), Run) + .WillOnce(Return(ByMove(std::move(mock_dialog_)))); + + EXPECT_CALL(*raw_dialog_view, + Show(test_password, + PointsToSameAddress(mock_password_manager_driver_.get()))); + controller()->ShowManualGenerationDialog(mock_password_manager_driver_.get(), + GetTestGenerationUIData1()); + + EXPECT_CALL(mock_dialog_factory(), Run).Times(0); + controller()->ShowManualGenerationDialog(mock_password_manager_driver_.get(), + GetTestGenerationUIData1()); }
diff --git a/chrome/browser/password_manager/password_generation_dialog_view_interface.h b/chrome/browser/password_manager/password_generation_dialog_view_interface.h index 52b3637a7..fed9a9f 100644 --- a/chrome/browser/password_manager/password_generation_dialog_view_interface.h +++ b/chrome/browser/password_manager/password_generation_dialog_view_interface.h
@@ -18,6 +18,9 @@ virtual ~PasswordGenerationDialogViewInterface() = default; // Called to show the dialog. |password| is the generated password. + // TODO(crbug.com/835234): Don't pass in |target_frame_driver|. + // This is no longer needed since any focus change now hides the dialog, + // ensuring that it can't be interacted with if the focus changes. virtual void Show(base::string16& password, base::WeakPtr<password_manager::PasswordManagerDriver> target_frame_driver) = 0;
diff --git a/chrome/browser/prefs/pref_service_syncable_util.cc b/chrome/browser/prefs/pref_service_syncable_util.cc index 48dc2a0..befeafc 100644 --- a/chrome/browser/prefs/pref_service_syncable_util.cc +++ b/chrome/browser/prefs/pref_service_syncable_util.cc
@@ -17,12 +17,6 @@ profile->GetPrefs()); } -sync_preferences::PrefServiceSyncable* PrefServiceSyncableIncognitoFromProfile( - Profile* profile) { - return static_cast<sync_preferences::PrefServiceSyncable*>( - profile->GetOffTheRecordPrefs()); -} - std::unique_ptr<sync_preferences::PrefServiceSyncable> CreateIncognitoPrefServiceSyncable( sync_preferences::PrefServiceSyncable* pref_service,
diff --git a/chrome/browser/prefs/pref_service_syncable_util.h b/chrome/browser/prefs/pref_service_syncable_util.h index 0456814..6c000ce 100644 --- a/chrome/browser/prefs/pref_service_syncable_util.h +++ b/chrome/browser/prefs/pref_service_syncable_util.h
@@ -23,12 +23,10 @@ // // For this reason, Profile does not expose an accessor for the // sync_preferences::PrefServiceSyncable type. Instead, you can use the -// utilities below to retrieve the sync_preferences::PrefServiceSyncable (or its -// incognito version) from a Profile. +// utilities below to retrieve the sync_preferences::PrefServiceSyncable from a +// Profile. sync_preferences::PrefServiceSyncable* PrefServiceSyncableFromProfile( Profile* profile); -sync_preferences::PrefServiceSyncable* PrefServiceSyncableIncognitoFromProfile( - Profile* profile); // Creates an incognito copy of |pref_service| that shares most prefs but uses // a fresh non-persistent overlay for the user pref store and an individual
diff --git a/chrome/browser/prerender/prerender_manager.cc b/chrome/browser/prerender/prerender_manager.cc index 00ab1b0..e20cf73 100644 --- a/chrome/browser/prerender/prerender_manager.cc +++ b/chrome/browser/prerender/prerender_manager.cc
@@ -31,6 +31,7 @@ #include "base/timer/elapsed_timer.h" #include "base/values.h" #include "chrome/browser/chrome_notification_types.h" +#include "chrome/browser/content_settings/cookie_settings_factory.h" #include "chrome/browser/net/prediction_options.h" #include "chrome/browser/predictors/loading_predictor.h" #include "chrome/browser/predictors/loading_predictor_factory.h" @@ -49,8 +50,7 @@ #include "chrome/browser/ui/tab_contents/core_tab_helper.h" #include "chrome/common/chrome_features.h" #include "chrome/common/prerender_types.h" -#include "components/content_settings/core/common/pref_names.h" -#include "components/prefs/pref_service.h" +#include "components/content_settings/core/browser/cookie_settings.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/navigation_controller.h" @@ -749,7 +749,8 @@ return; } - if (profile_->GetPrefs()->GetBoolean(prefs::kBlockThirdPartyCookies)) { + auto cookie_settings = CookieSettingsFactory::GetForProfile(profile_); + if (cookie_settings->ShouldBlockThirdPartyCookies()) { return; } @@ -791,7 +792,8 @@ GURL url = url_arg; - if (profile_->GetPrefs()->GetBoolean(prefs::kBlockThirdPartyCookies)) { + auto cookie_settings = CookieSettingsFactory::GetForProfile(profile_); + if (cookie_settings->ShouldBlockThirdPartyCookies()) { SkipPrerenderContentsAndMaybePreconnect( url, origin, FINAL_STATUS_BLOCK_THIRD_PARTY_COOKIES); return nullptr;
diff --git a/chrome/browser/resources/BUILD.gn b/chrome/browser/resources/BUILD.gn index 9b4adc9..160d9ce 100644 --- a/chrome/browser/resources/BUILD.gn +++ b/chrome/browser/resources/BUILD.gn
@@ -33,7 +33,7 @@ "print_preview:closure_compile", "quota_internals:closure_compile", "settings:closure_compile", - "signin/dice_sync_confirmation:closure_compile", + "signin/sync_confirmation:closure_compile", "user_manager:closure_compile", "welcome/dice_welcome:closure_compile", "welcome/onboarding_welcome:closure_compile",
diff --git a/chrome/browser/resources/chromeos/account_manager_welcome.html b/chrome/browser/resources/chromeos/account_manager_welcome.html index 439a4625..54e41f8 100644 --- a/chrome/browser/resources/chromeos/account_manager_welcome.html +++ b/chrome/browser/resources/chromeos/account_manager_welcome.html
@@ -1,7 +1,7 @@ <!doctype html> <html dir="$i18n{textdirection}" lang="$i18n{language}"> - <head> + <title>$i18n{welcomeTitle}</title> <meta charset="utf-8"> <link rel="import" href="chrome://resources/html/polymer.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html"> @@ -26,13 +26,14 @@ <body> <div id="content"> <if expr="_google_chrome"> - <img id="google-logo" src="googleg.svg"> + <img id="google-logo" src="googleg.svg" alt=""> </if> <h1>$i18n{welcomeTitle}</h1> <p>$i18nRaw{welcomeMessage}</p> <if expr="_google_chrome"> - <img id="welcome-image" srcset="account_manager_welcome_1x.png 1x, - account_manager_welcome_2x.png 2x"> + <img id="welcome-image" alt="" + srcset="account_manager_welcome_1x.png 1x, + account_manager_welcome_2x.png 2x"> </if> <div class="button-container"> <paper-button id="ok-button" class="action-button"> @@ -41,5 +42,4 @@ </div> </div> </body> - </html>
diff --git a/chrome/browser/resources/chromeos/account_migration_welcome.html b/chrome/browser/resources/chromeos/account_migration_welcome.html index 68af205a..952623e 100644 --- a/chrome/browser/resources/chromeos/account_migration_welcome.html +++ b/chrome/browser/resources/chromeos/account_migration_welcome.html
@@ -1,6 +1,7 @@ <!doctype html> <html dir="$i18n{textdirection}" lang="$i18n{language}"> <head> + <title>$i18n{welcomePageTitle}</title> <meta charset="utf-8"> <link rel="import" href="chrome://resources/html/polymer.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html"> @@ -21,16 +22,18 @@ <script src="strings.js"></script> <script src="account_migration_welcome.js"></script> </head> + <body> <div id="content"> <if expr="_google_chrome"> - <img id="google-logo" src="googleg.svg"> + <img id="google-logo" src="googleg.svg" alt=""> </if> <h1 id="welcome-title"></h1> <p id="welcome-message"></p> <if expr="_google_chrome"> - <img id="welcome-image" srcset="account_manager_welcome_1x.png 1x, - account_manager_welcome_2x.png 2x"> + <img id="welcome-image" alt="" + srcset="account_manager_welcome_1x.png 1x, + account_manager_welcome_2x.png 2x"> </if> <div class="button-container"> <paper-button id="cancel-button" class="cancel-button">
diff --git a/chrome/browser/resources/settings/page_visibility.js b/chrome/browser/resources/settings/page_visibility.js index 330a9db..7a6bb7c 100644 --- a/chrome/browser/resources/settings/page_visibility.js +++ b/chrome/browser/resources/settings/page_visibility.js
@@ -125,9 +125,7 @@ autofill: false, people: false, onStartup: false, - reset: { - powerwash: false, - }, + reset: false, appearance: { setWallpaper: false, setTheme: false,
diff --git a/chrome/browser/resources/settings/people_page/account_manager.html b/chrome/browser/resources/settings/people_page/account_manager.html index 9efc576..b90991d 100644 --- a/chrome/browser/resources/settings/people_page/account_manager.html +++ b/chrome/browser/resources/settings/people_page/account_manager.html
@@ -139,10 +139,10 @@ <template is="dom-if" if="[[shouldShowReauthenticationButton_(item)]]"> - <cr-button class="reauth-button" - on-click="onReauthenticationTap_"> + <paper-button title="[[getAccountManagerSignedOutTitle_(item)]]" + class="reauth-button" on-click="onReauthenticationTap_"> [[getAccountManagerSignedOutLabel_(item.unmigrated)]] - </cr-button> + </paper-button> </template> <!-- If this is the Device Account, display the management status --> @@ -153,8 +153,10 @@ </template> <!-- Else, display a hamburger menu for removing the account --> <template is="dom-if" if="[[!item.isDeviceAccount]]"> - <cr-icon-button class="icon-more-vert" title="$i18n{moreActions}" - on-click="onAccountActionsMenuButtonTap_"></cr-icon-button> + <cr-icon-button class="icon-more-vert" + title="[[getMoreActionsTitle_(item)]]" + on-click="onAccountActionsMenuButtonTap_"> + </cr-icon-button> </template> </div> </template>
diff --git a/chrome/browser/resources/settings/people_page/account_manager.js b/chrome/browser/resources/settings/people_page/account_manager.js index 00248e2..8613c12 100644 --- a/chrome/browser/resources/settings/people_page/account_manager.js +++ b/chrome/browser/resources/settings/people_page/account_manager.js
@@ -133,6 +133,26 @@ : 'accountManagerReauthenticationLabel'); }, + + /** + * @param {!settings.Account} account + * @private + */ + getAccountManagerSignedOutTitle_: function(account) { + const label = account.unmigrated ? 'accountManagerMigrationTooltip' + : 'accountManagerReauthenticationTooltip'; + return loadTimeData.getStringF(label, account.email); + }, + + /** + * @param {!settings.Account} account + * @private + */ + getMoreActionsTitle_: function(account) { + return loadTimeData.getStringF('accountManagerMoreActionsTooltip', + account.email); + }, + /** * @param {!CustomEvent<!{model: !{item: !settings.Account}}>} event * @private
diff --git a/chrome/browser/resources/signin/dice_sync_confirmation/images/sync_confirmation_illustration.svg b/chrome/browser/resources/signin/dice_sync_confirmation/images/sync_confirmation_illustration.svg deleted file mode 100644 index a0f1262..0000000 --- a/chrome/browser/resources/signin/dice_sync_confirmation/images/sync_confirmation_illustration.svg +++ /dev/null
@@ -1 +0,0 @@ -<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 168"><defs><style>.cls-1{fill:#fff}.cls-3{fill:#e8e9eb}.cls-5{fill:#bdc0c5}</style></defs><path class="cls-1" d="M256 89a41 41 0 0 0-41 39.13h82A41 41 0 0 0 256 89z"/><path d="M97.76 72H103c0-10.83 2.9-19.34 8.63-25.3 9-9.37 22.15-9.41 22.28-9.41L134 32c-.62 0-15.32 0-25.84 10.91-6.79 6.99-10.4 16.78-10.4 29.09z" fill="#4285f4"/><path class="cls-3" d="M82.41 102.42A35.27 35.27 0 0 1 67 106.75V112a40.36 40.36 0 0 0 18-5c8.23-4.61 18-14.42 18-35h-5.24c0 14.48-5.16 24.71-15.35 30.42zM143.78 33.27v5.33h7.41a6.35 6.35 0 0 1-2.77 4.15 8.28 8.28 0 0 1-12.36-4.35 8.29 8.29 0 0 1 7.71-10.91 7.52 7.52 0 0 1 5.23 2.05l4-3.95a13.22 13.22 0 0 0-9.22-3.59 13.75 13.75 0 0 0-12.3 7.6 13.64 13.64 0 0 0 0 12.35 13.76 13.76 0 0 0 12.3 7.59 13.15 13.15 0 0 0 9.12-3.33 13.46 13.46 0 0 0 4.1-10.12 15.82 15.82 0 0 0-.25-2.82zM433 109h18v-8.48a11 11 0 0 0-18 8.48zM491 59.49h-30.2a5.6 5.6 0 0 0-5.59 5.59v72.36a5.6 5.6 0 0 0 5.59 5.56H491a5.6 5.6 0 0 0 5.59-5.59V65.08a5.6 5.6 0 0 0-5.59-5.59zm4.89 77.95a4.89 4.89 0 0 1-4.89 4.89h-30.2a4.89 4.89 0 0 1-4.89-4.89V65.08a4.89 4.89 0 0 1 4.89-4.89H491a4.89 4.89 0 0 1 4.89 4.89zM418.43 92.8c6.1-10.92 17.06-16.46 32.56-16.46v-5.62c-22 0-32.53 10.52-37.46 19.34a43.35 43.35 0 0 0-5.36 19.27h5.62a37.88 37.88 0 0 1 4.64-16.53zM342 50.45a9.28 9.28 0 0 1-8.17-4.86l-9.38-16.21A21.84 21.84 0 0 0 321 40.92a21 21 0 0 0 17.56 20.86l7-11.94a10.66 10.66 0 0 1-3.56.61z"/><path class="cls-3" d="M347.91 33.67a9.58 9.58 0 0 1 3.54 7.33 8.47 8.47 0 0 1-1.28 4.61L340.66 62h1.26a20.93 20.93 0 0 0 15.21-6.49h-2.81a8.64 8.64 0 0 1 7.82-8.6 20.8 20.8 0 0 0 .87-5.82 21.63 21.63 0 0 0-1.23-7.35z"/><path class="cls-3" d="M342 31.55l18.69.07a20.52 20.52 0 0 0-13.78-11A50.49 50.49 0 0 0 341 .16V0h-6c.6.9 1.14 1.79 1.62 2.67A44.81 44.81 0 0 1 341.83 20a20.87 20.87 0 0 0-15.94 7.49l6.88 12a9.47 9.47 0 0 1 9.23-7.94z"/><circle class="cls-3" cx="342" cy="41" r="7.35" transform="rotate(-89.77 342 40.997)"/><path class="cls-3" d="M258.56 166.88A37.06 37.06 0 0 1 221.77 144H226v-8.48a11 11 0 0 0-6.86-2.51v-.48a37 37 0 0 1 34.36-39.47l-.07-1a38 38 0 0 0-35.29 40.53v.45A11 11 0 0 0 208 144h12.68a38 38 0 0 0 73.21-11.35l-1-.07a37 37 0 0 1-34.33 34.3z"/><path d="M62.72 48.5H0v88.33h67.51V53.28a4.78 4.78 0 0 0-4.79-4.78z" fill="#f4f4f4"/><path class="cls-5" d="M68 53.28A5.3 5.3 0 0 0 62.72 48H0v1h62.72A4.28 4.28 0 0 1 67 53.28v83.06H0v1h68zM0 143.01h86v.99H0zM451.72 139.1V63.73a7.9 7.9 0 0 1 7.89-7.89h25.07v-.7h-25.06a8.6 8.6 0 0 0-8.6 8.59v75.37a8.6 8.6 0 0 0 8.6 8.59H472V147h-12.38a7.9 7.9 0 0 1-7.9-7.9zM495.22 55.55v.75a7.9 7.9 0 0 1 5.26 7.43v75.37a7.9 7.9 0 0 1-7.89 7.89H480.2v.7h12.39a8.6 8.6 0 0 0 8.6-8.59V63.73a8.61 8.61 0 0 0-5.97-8.18z"/><path d="M499.48 7.6c-11.6 11.7-11.6 28-11.59 28.74 0 .15 0 14.78-10 24.78-6.34 6.37-15.38 9.6-26.89 9.6v5.62c13.08 0 23.48-3.8 30.91-11.3 11.6-11.7 11.6-28 11.59-28.74 0-.15 0-14.78 10-24.78a29.73 29.73 0 0 1 8.5-5.94V0h-1.28a35.46 35.46 0 0 0-11.24 7.6z" fill="#34a751"/><path class="cls-1" d="M62.56 99.28a11.77 11.77 0 0 0-9.48 5 7.42 7.42 0 0 0-2.7-.52c-4.49 0-8.12 4-8.12 9h32.49c0-7.46-5.46-13.48-12.19-13.48z"/><path class="cls-5" d="M68 70v.53a8.35 8.35 0 0 1 8.44 7.94H68V79h9v-.26A8.88 8.88 0 0 0 68 70zM166.5 81a2 2 0 0 1 2-2h4.72v-2a2.55 2.55 0 0 1 5.11 0v2h.49v-2a3 3 0 0 0-6.09 0v1.44h-4.23A2.48 2.48 0 0 0 166 81v4.5h.49zM187 85.19h-1.43V81a2.49 2.49 0 0 0-2.57-2.52h-3.25V79H183a2 2 0 0 1 2 2v4.72h2a2.55 2.55 0 0 1 0 5.11h-2v.49h2a3 3 0 0 0 0-6.09zM185 95.52a2 2 0 0 1-2 2h-4v-1.44a3.27 3.27 0 0 0-6.54 0V98h.54v-1.92a2.78 2.78 0 0 1 5.56 0V98H183a2.49 2.49 0 0 0 2.48-2.48v-3.26H185zM166.49 95.52v-4h1.43a3.27 3.27 0 1 0 0-6.54h-.24v.49h.24a2.78 2.78 0 0 1 0 5.56H166v4.5a2.49 2.49 0 0 0 2.48 2.47h3v-.49h-3a2 2 0 0 1-1.99-1.99zM231.5 32.3v14.81h2.64V32.3zm2.15 14.32H232V32.79h1.66z"/><path class="cls-5" d="M234.61 28h-27.22a2.4 2.4 0 0 0-2.39 2.39v3.1h.49v-3.1a1.9 1.9 0 0 1 1.9-1.9h27.21a1.9 1.9 0 0 1 1.9 1.9V49a1.9 1.9 0 0 1-1.9 1.9h-27.21a1.9 1.9 0 0 1-1.9-1.9v-6.52l1.87 2.58 2.14-1.55-2.13-2.93 3.44-1.12-.81-2.51-3.43 1.11v-3.62H205v.49h1.07v3.8l3.61-1.17.51 1.57-3.62 1.17 2.24 3.08-1.34 1L205 41v8a2.4 2.4 0 0 0 2.39 2.39h27.21A2.4 2.4 0 0 0 237 49V30.39a2.4 2.4 0 0 0-2.39-2.39z"/><path class="cls-5" d="M219.68 34.44v3.62l-3.43-1.11-.82 2.51 3.44 1.12-2.13 2.93 2.14 1.55 2.12-2.92 2.12 2.92 2.14-1.55-2.13-2.93 3.44-1.12-.82-2.51-3.43 1.11v-3.62zm5.75 3.13l.51 1.57-3.61 1.17 2.24 3.08-1.34 1-2.23-3.08-2.23 3.06-1.34-1 2.24-3.08-3.62-1.17.51-1.57 3.61 1.17v-3.8h1.66v3.8zM296.75 69.86h-.5v3.75l-5.2-5.2 5.2-5.21v3.76h.5V62l-6.41 6.41 6.41 6.41v-4.96zM296.25 87.28h.5v-3.75l5.2 5.2-5.2 5.21v-3.75h-.5v4.95l6.41-6.41-6.41-6.41v4.96z"/><path class="cls-5" d="M296.5 68.07v.5a10 10 0 0 1 8.62 15.08l.43.25a10.5 10.5 0 0 0-9-15.83zM296.5 88.57a10 10 0 0 1-8.62-15.08l-.43-.25a10.5 10.5 0 0 0 9 15.83zM47 31.7V20.58H23.49v-3a2.1 2.1 0 0 1 2.09-2.11H44.4a2.11 2.11 0 0 1 2.11 2.11v2H47v-2A2.6 2.6 0 0 0 44.4 15H25.6a2.59 2.59 0 0 0-2.6 2.6v3.48h23.51V31.7a2.11 2.11 0 0 1-2.11 2.11H25.6a2.11 2.11 0 0 1-2.11-2.11v-8h22.45v-.5H23v8.5a2.6 2.6 0 0 0 2.6 2.6h18.8a2.6 2.6 0 0 0 2.6-2.6zM354 101.55a4.78 4.78 0 1 0 4.78 4.78 4.79 4.79 0 0 0-4.78-4.78zm0 9.06a4.28 4.28 0 1 1 4.28-4.28 4.28 4.28 0 0 1-4.28 4.29z"/><path class="cls-5" d="M365.9 102.27l-2.41-4.18a.88.88 0 0 0-1.05-.38l-2.88 1.16a9 9 0 0 0-1.85-1.07l-.43-3.06a.85.85 0 0 0-.85-.73h-4.84a.84.84 0 0 0-.84.73l-.43 3.06a9.33 9.33 0 0 0-1.85 1.07l-2.88-1.16a.85.85 0 0 0-1 .38l-2.42 4.19a.84.84 0 0 0 .22 1.09l2.44 1.9a7.56 7.56 0 0 0-.09 1.07 8 8 0 0 0 .07 1.07l-2.44 1.91a.88.88 0 0 0-.21 1.09l2.41 4.18a.87.87 0 0 0 1.05.38l2.88-1.16a9 9 0 0 0 1.85 1.07l.44 3.07a.87.87 0 0 0 .85.72h4.84a.83.83 0 0 0 .84-.73l.43-3.06a9.34 9.34 0 0 0 1.85-1.07l2.88 1.16a.85.85 0 0 0 1-.38l2.42-4.19a.84.84 0 0 0-.22-1.09l-2.41-1.91a9.82 9.82 0 0 0 .06-1.07 7.93 7.93 0 0 0-.07-1.07l2.44-1.91a.88.88 0 0 0 .2-1.08zm-.52.7l-2.67 2.09v.15a7.28 7.28 0 0 1 .09 1.14 9.76 9.76 0 0 1-.07 1.15v.14l2.64 2.09a.33.33 0 0 1 .08.44l-2.45 4.17a.34.34 0 0 1-.43.16l-3.14-1.26-.11.09a8.89 8.89 0 0 1-2 1.15l-.13.05-.47 3.36a.33.33 0 0 1-.34.29h-4.84a.36.36 0 0 1-.36-.3l-.47-3.34-.13-.06a8.58 8.58 0 0 1-2-1.15l-.11-.09-3.12 1.26a.36.36 0 0 1-.44-.16l-2.41-4.18a.37.37 0 0 1 .08-.45l2.67-2.09v-.15a7.4 7.4 0 0 1-.09-1.14 7.28 7.28 0 0 1 .1-1.14v-.15l-2.62-2.04a.33.33 0 0 1-.08-.44l2.44-4.23a.34.34 0 0 1 .43-.16l3.14 1.26.11-.09a8.9 8.9 0 0 1 2-1.15l.13-.05.47-3.34a.34.34 0 0 1 .34-.3h4.84a.35.35 0 0 1 .36.3l.47 3.35.13.05a8.58 8.58 0 0 1 2 1.15l.11.09 3.12-1.26a.36.36 0 0 1 .44.16l2.41 4.18a.37.37 0 0 1-.13.48zM62.56 99a12 12 0 0 0-9.56 5 7.64 7.64 0 0 0-2.62-.47c-4.62 0-8.38 4.14-8.38 9.24v.23h33v-.28C75 105.15 69.42 99 62.56 99zm11.93 13.44h-32c.13-4.66 3.61-8.4 7.87-8.4a7.19 7.19 0 0 1 2.62.5l.17.07.11-.15a11.5 11.5 0 0 1 9.28-4.9c6.52 0 11.81 5.75 11.95 12.88zM375.91 42.28a13.18 13.18 0 0 0-10.17 4.77A8.89 8.89 0 0 0 354 55.51v.27h35.1v-.27a13.24 13.24 0 0 0-13.19-13.23zm-21.33 13a8.35 8.35 0 0 1 11.15-7.61l.18.06.12-.15a12.69 12.69 0 0 1 22.56 7.7zM441 33.51a2.5 2.5 0 1 0-2.5-2.5 2.51 2.51 0 0 0 2.5 2.5zm0-4.51a2 2 0 1 1-2 2 2 2 0 0 1 2-2z"/><path class="cls-5" d="M441 38a7 7 0 0 0 6.53-4.49H452V38h5v-4.49h2v-5h-11.47A7 7 0 1 0 441 38zm0-13.48a6.48 6.48 0 0 1 6.11 4.32l.06.17h11.32v4h-2v4.49h-4V33h-5.3l-.06.17a6.48 6.48 0 1 1-6.13-8.65z"/><path d="M256 92v1a37 37 0 0 1 37 37h1a38 38 0 0 0-38-38z" fill="#f7bb2a"/><path class="cls-1" d="M411.08 121a16.81 16.81 0 0 0-13.08 6.27 11.21 11.21 0 0 0-15 10.58h44.93A16.85 16.85 0 0 0 411.08 121z"/><path class="cls-3" d="M411.08 121.7a16.17 16.17 0 0 1 16.13 15.44h-43.48a10.5 10.5 0 0 1 14-9.22l.47.17.31-.39a16.09 16.09 0 0 1 12.56-6m0-.7a16.81 16.81 0 0 0-13.07 6.27 11.21 11.21 0 0 0-15 10.58h44.93A16.85 16.85 0 0 0 411.08 121z"/></svg> \ No newline at end of file
diff --git a/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation.html b/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation.html deleted file mode 100644 index 6b02251..0000000 --- a/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!doctype html> -<html dir="$i18n{textdirection}" lang="$i18n{language}" $i18n{dark}> - <head> - <meta charset="utf-8"> - <link rel="stylesheet" href="chrome://resources/css/md_colors.css"> - <link rel="import" href="sync_confirmation_app.html"></link> - <style> - body { - margin: 0; - padding: 0; - width: 512px; - } - @media (prefers-color-scheme: dark) { - body { - background-color: var(--md-background-color); - } - } - </style> - </head> - <body> - <sync-confirmation-app></sync-confirmation-app> - </body> - <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css"> - <link rel="import" href="chrome://resources/html/cr.html"></script> - <link rel="import" href="chrome://resources/html/util.html"></script> - <script src="sync_confirmation.js"></script> - <link rel="import" href="chrome://resources/html/dark_mode.html"> -</html>
diff --git a/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation.js b/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation.js deleted file mode 100644 index 31aa325f..0000000 --- a/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation.js +++ /dev/null
@@ -1,32 +0,0 @@ -/* Copyright 2017 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. */ - -cr.define('sync.confirmation', function() { - 'use strict'; - - function initialize() { - const syncConfirmationBrowserProxy = - sync.confirmation.SyncConfirmationBrowserProxyImpl.getInstance(); - // Prefer using |document.body.offsetHeight| instead of - // |document.body.scrollHeight| as it returns the correct height of the - // even when the page zoom in Chrome is different than 100%. - syncConfirmationBrowserProxy.initializedWithSize( - [document.body.offsetHeight]); - // The web dialog size has been initialized, so reset the body width to - // auto. This makes sure that the body only takes up the viewable width, - // e.g. when there is a scrollbar. - document.body.style.width = 'auto'; - } - - function clearFocus() { - document.activeElement.blur(); - } - - return { - clearFocus: clearFocus, - initialize: initialize, - }; -}); - -document.addEventListener('DOMContentLoaded', sync.confirmation.initialize);
diff --git a/chrome/browser/resources/signin/dice_sync_confirmation/BUILD.gn b/chrome/browser/resources/signin/sync_confirmation/BUILD.gn similarity index 100% rename from chrome/browser/resources/signin/dice_sync_confirmation/BUILD.gn rename to chrome/browser/resources/signin/sync_confirmation/BUILD.gn
diff --git a/chrome/browser/resources/signin/dice_sync_confirmation/images/ic_google.png b/chrome/browser/resources/signin/sync_confirmation/images/ic_google.png similarity index 100% rename from chrome/browser/resources/signin/dice_sync_confirmation/images/ic_google.png rename to chrome/browser/resources/signin/sync_confirmation/images/ic_google.png Binary files differ
diff --git a/chrome/browser/resources/signin/dice_sync_confirmation/images/ic_google_2x.png b/chrome/browser/resources/signin/sync_confirmation/images/ic_google_2x.png similarity index 100% rename from chrome/browser/resources/signin/dice_sync_confirmation/images/ic_google_2x.png rename to chrome/browser/resources/signin/sync_confirmation/images/ic_google_2x.png Binary files differ
diff --git a/chrome/browser/resources/signin/sync_confirmation/images/sync_confirmation_illustration.svg b/chrome/browser/resources/signin/sync_confirmation/images/sync_confirmation_illustration.svg new file mode 100644 index 0000000..324434e2 --- /dev/null +++ b/chrome/browser/resources/signin/sync_confirmation/images/sync_confirmation_illustration.svg
@@ -0,0 +1 @@ +<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 168"><defs><style>.cls-1{fill:#fff}.cls-3{fill:#e8e9eb}.cls-5{fill:#bdc0c5}</style></defs><path class="cls-1" d="M256 89a41 41 0 0 0-41 39.13h82A41 41 0 0 0 256 89z"/><path d="M97.76 72H103c0-10.83 2.9-19.34 8.63-25.3 9-9.37 22.15-9.41 22.28-9.41L134 32c-.62 0-15.32 0-25.84 10.91-6.79 6.99-10.4 16.78-10.4 29.09z" fill="#4285f4"/><path class="cls-3" d="M82.41 102.42A35.27 35.27 0 0 1 67 106.75V112a40.36 40.36 0 0 0 18-5c8.23-4.61 18-14.42 18-35h-5.24c0 14.48-5.16 24.71-15.35 30.42zm61.37-69.15v5.33h7.41a6.35 6.35 0 0 1-2.77 4.15 8.28 8.28 0 0 1-12.36-4.35 8.29 8.29 0 0 1 7.71-10.91 7.52 7.52 0 0 1 5.23 2.05l4-3.95a13.22 13.22 0 0 0-9.22-3.59 13.75 13.75 0 0 0-12.3 7.6 13.64 13.64 0 0 0 0 12.35 13.76 13.76 0 0 0 12.3 7.59 13.15 13.15 0 0 0 9.12-3.33 13.46 13.46 0 0 0 4.1-10.12 15.82 15.82 0 0 0-.25-2.82zM433 109h18v-8.48a11 11 0 0 0-18 8.48zm58-49.51h-30.2a5.6 5.6 0 0 0-5.59 5.59v72.36a5.6 5.6 0 0 0 5.59 5.56H491a5.6 5.6 0 0 0 5.59-5.59V65.08a5.6 5.6 0 0 0-5.59-5.59zm4.89 77.95a4.89 4.89 0 0 1-4.89 4.89h-30.2a4.89 4.89 0 0 1-4.89-4.89V65.08a4.89 4.89 0 0 1 4.89-4.89H491a4.89 4.89 0 0 1 4.89 4.89zM418.43 92.8c6.1-10.92 17.06-16.46 32.56-16.46v-5.62c-22 0-32.53 10.52-37.46 19.34a43.35 43.35 0 0 0-5.36 19.27h5.62a37.88 37.88 0 0 1 4.64-16.53zM342 50.45a9.28 9.28 0 0 1-8.17-4.86l-9.38-16.21A21.84 21.84 0 0 0 321 40.92a21 21 0 0 0 17.56 20.86l7-11.94a10.66 10.66 0 0 1-3.56.61z"/><path class="cls-3" d="M347.91 33.67a9.58 9.58 0 0 1 3.54 7.33 8.47 8.47 0 0 1-1.28 4.61L340.66 62h1.26a20.93 20.93 0 0 0 15.21-6.49h-2.81a8.64 8.64 0 0 1 7.82-8.6 20.8 20.8 0 0 0 .87-5.82 21.63 21.63 0 0 0-1.23-7.35z"/><path class="cls-3" d="M342 31.55l18.69.07a20.52 20.52 0 0 0-13.78-11A50.49 50.49 0 0 0 341 .16V0h-6c.6.9 1.14 1.79 1.62 2.67A44.81 44.81 0 0 1 341.83 20a20.87 20.87 0 0 0-15.94 7.49l6.88 12a9.47 9.47 0 0 1 9.23-7.94z"/><circle class="cls-3" cx="342" cy="41" r="7.35" transform="rotate(-89.77 342 40.997)"/><path class="cls-3" d="M258.56 166.88A37.06 37.06 0 0 1 221.77 144H226v-8.48a11 11 0 0 0-6.86-2.51v-.48a37 37 0 0 1 34.36-39.47l-.07-1a38 38 0 0 0-35.29 40.53v.45A11 11 0 0 0 208 144h12.68a38 38 0 0 0 73.21-11.35l-1-.07a37 37 0 0 1-34.33 34.3z"/><path d="M62.72 48.5H0v88.33h67.51V53.28a4.78 4.78 0 0 0-4.79-4.78z" fill="#f4f4f4"/><path class="cls-5" d="M68 53.28A5.3 5.3 0 0 0 62.72 48H0v1h62.72A4.28 4.28 0 0 1 67 53.28v83.06H0v1h68zM0 143.01h86v.99H0zm451.72-3.91V63.73a7.9 7.9 0 0 1 7.89-7.89h25.07v-.7h-25.06a8.6 8.6 0 0 0-8.6 8.59v75.37a8.6 8.6 0 0 0 8.6 8.59H472V147h-12.38a7.9 7.9 0 0 1-7.9-7.9zm43.5-83.55v.75a7.9 7.9 0 0 1 5.26 7.43v75.37a7.9 7.9 0 0 1-7.89 7.89H480.2v.7h12.39a8.6 8.6 0 0 0 8.6-8.59V63.73a8.61 8.61 0 0 0-5.97-8.18z"/><path d="M499.48 7.6c-11.6 11.7-11.6 28-11.59 28.74 0 .15 0 14.78-10 24.78-6.34 6.37-15.38 9.6-26.89 9.6v5.62c13.08 0 23.48-3.8 30.91-11.3 11.6-11.7 11.6-28 11.59-28.74 0-.15 0-14.78 10-24.78a29.73 29.73 0 0 1 8.5-5.94V0h-1.28a35.46 35.46 0 0 0-11.24 7.6z" fill="#34a751"/><path class="cls-1" d="M62.56 99.28a11.77 11.77 0 0 0-9.48 5 7.42 7.42 0 0 0-2.7-.52c-4.49 0-8.12 4-8.12 9h32.49c0-7.46-5.46-13.48-12.19-13.48z"/><path class="cls-5" d="M68 70v.53a8.35 8.35 0 0 1 8.44 7.94H68V79h9v-.26A8.88 8.88 0 0 0 68 70zm98.5 11a2 2 0 0 1 2-2h4.72v-2a2.55 2.55 0 0 1 5.11 0v2h.49v-2a3 3 0 0 0-6.09 0v1.44h-4.23A2.48 2.48 0 0 0 166 81v4.5h.49zm20.5 4.19h-1.43V81a2.49 2.49 0 0 0-2.57-2.52h-3.25V79H183a2 2 0 0 1 2 2v4.72h2a2.55 2.55 0 0 1 0 5.11h-2v.49h2a3 3 0 0 0 0-6.09zm-2 10.33a2 2 0 0 1-2 2h-4v-1.44a3.27 3.27 0 0 0-6.54 0V98h.54v-1.92a2.78 2.78 0 0 1 5.56 0V98H183a2.49 2.49 0 0 0 2.48-2.48v-3.26H185zm-18.51 0v-4h1.43a3.27 3.27 0 1 0 0-6.54h-.24v.49h.24a2.78 2.78 0 0 1 0 5.56H166v4.5a2.49 2.49 0 0 0 2.48 2.47h3v-.49h-3a2 2 0 0 1-1.99-1.99zM231.5 32.3v14.81h2.64V32.3zm2.15 14.32H232V32.79h1.66z"/><path class="cls-5" d="M234.61 28h-27.22a2.4 2.4 0 0 0-2.39 2.39v3.1h.49v-3.1a1.9 1.9 0 0 1 1.9-1.9h27.21a1.9 1.9 0 0 1 1.9 1.9V49a1.9 1.9 0 0 1-1.9 1.9h-27.21a1.9 1.9 0 0 1-1.9-1.9v-6.52l1.87 2.58 2.14-1.55-2.13-2.93 3.44-1.12-.81-2.51-3.43 1.11v-3.62H205v.49h1.07v3.8l3.61-1.17.51 1.57-3.62 1.17 2.24 3.08-1.34 1L205 41v8a2.4 2.4 0 0 0 2.39 2.39h27.21A2.4 2.4 0 0 0 237 49V30.39a2.4 2.4 0 0 0-2.39-2.39z"/><path class="cls-5" d="M219.68 34.44v3.62l-3.43-1.11-.82 2.51 3.44 1.12-2.13 2.93 2.14 1.55 2.12-2.92 2.12 2.92 2.14-1.55-2.13-2.93 3.44-1.12-.82-2.51-3.43 1.11v-3.62zm5.75 3.13l.51 1.57-3.61 1.17 2.24 3.08-1.34 1-2.23-3.08-2.23 3.06-1.34-1 2.24-3.08-3.62-1.17.51-1.57 3.61 1.17v-3.8h1.66v3.8zm71.32 32.29h-.5v3.75l-5.2-5.2 5.2-5.21v3.76h.5V62l-6.41 6.41 6.41 6.41v-4.96zm-.5 17.42h.5v-3.75l5.2 5.2-5.2 5.21v-3.75h-.5v4.95l6.41-6.41-6.41-6.41v4.96z"/><path class="cls-5" d="M296.5 68.07v.5a10 10 0 0 1 8.62 15.08l.43.25a10.5 10.5 0 0 0-9-15.83zm0 20.5a10 10 0 0 1-8.62-15.08l-.43-.25a10.5 10.5 0 0 0 9 15.83zM47 31.7V20.58H23.49v-3a2.1 2.1 0 0 1 2.09-2.11H44.4a2.11 2.11 0 0 1 2.11 2.11v2H47v-2A2.6 2.6 0 0 0 44.4 15H25.6a2.59 2.59 0 0 0-2.6 2.6v3.48h23.51V31.7a2.11 2.11 0 0 1-2.11 2.11H25.6a2.11 2.11 0 0 1-2.11-2.11v-8h22.45v-.5H23v8.5a2.6 2.6 0 0 0 2.6 2.6h18.8a2.6 2.6 0 0 0 2.6-2.6zm307 69.85a4.78 4.78 0 1 0 4.78 4.78 4.79 4.79 0 0 0-4.78-4.78zm0 9.06a4.28 4.28 0 1 1 4.28-4.28 4.28 4.28 0 0 1-4.28 4.29z"/><path class="cls-5" d="M365.9 102.27l-2.41-4.18a.88.88 0 0 0-1.05-.38l-2.88 1.16a9 9 0 0 0-1.85-1.07l-.43-3.06a.85.85 0 0 0-.85-.73h-4.84a.84.84 0 0 0-.84.73l-.43 3.06a9.33 9.33 0 0 0-1.85 1.07l-2.88-1.16a.85.85 0 0 0-1 .38l-2.42 4.19a.84.84 0 0 0 .22 1.09l2.44 1.9a7.56 7.56 0 0 0-.09 1.07 8 8 0 0 0 .07 1.07l-2.44 1.91a.88.88 0 0 0-.21 1.09l2.41 4.18a.87.87 0 0 0 1.05.38l2.88-1.16a9 9 0 0 0 1.85 1.07l.44 3.07a.87.87 0 0 0 .85.72h4.84a.83.83 0 0 0 .84-.73l.43-3.06a9.34 9.34 0 0 0 1.85-1.07l2.88 1.16a.85.85 0 0 0 1-.38l2.42-4.19a.84.84 0 0 0-.22-1.09l-2.41-1.91a9.82 9.82 0 0 0 .06-1.07 7.93 7.93 0 0 0-.07-1.07l2.44-1.91a.88.88 0 0 0 .2-1.08zm-.52.7l-2.67 2.09v.15a7.28 7.28 0 0 1 .09 1.14 9.76 9.76 0 0 1-.07 1.15v.14l2.64 2.09a.33.33 0 0 1 .08.44l-2.45 4.17a.34.34 0 0 1-.43.16l-3.14-1.26-.11.09a8.89 8.89 0 0 1-2 1.15l-.13.05-.47 3.36a.33.33 0 0 1-.34.29h-4.84a.36.36 0 0 1-.36-.3l-.47-3.34-.13-.06a8.58 8.58 0 0 1-2-1.15l-.11-.09-3.12 1.26a.36.36 0 0 1-.44-.16l-2.41-4.18a.37.37 0 0 1 .08-.45l2.67-2.09v-.15a7.4 7.4 0 0 1-.09-1.14 7.28 7.28 0 0 1 .1-1.14v-.15l-2.62-2.04a.33.33 0 0 1-.08-.44l2.44-4.23a.34.34 0 0 1 .43-.16l3.14 1.26.11-.09a8.9 8.9 0 0 1 2-1.15l.13-.05.47-3.34a.34.34 0 0 1 .34-.3h4.84a.35.35 0 0 1 .36.3l.47 3.35.13.05a8.58 8.58 0 0 1 2 1.15l.11.09 3.12-1.26a.36.36 0 0 1 .44.16l2.41 4.18a.37.37 0 0 1-.13.48zM62.56 99a12 12 0 0 0-9.56 5 7.64 7.64 0 0 0-2.62-.47c-4.62 0-8.38 4.14-8.38 9.24v.23h33v-.28C75 105.15 69.42 99 62.56 99zm11.93 13.44h-32c.13-4.66 3.61-8.4 7.87-8.4a7.19 7.19 0 0 1 2.62.5l.17.07.11-.15a11.5 11.5 0 0 1 9.28-4.9c6.52 0 11.81 5.75 11.95 12.88zm301.42-70.16a13.18 13.18 0 0 0-10.17 4.77A8.89 8.89 0 0 0 354 55.51v.27h35.1v-.27a13.24 13.24 0 0 0-13.19-13.23zm-21.33 13a8.35 8.35 0 0 1 11.15-7.61l.18.06.12-.15a12.69 12.69 0 0 1 22.56 7.7zM441 33.51a2.5 2.5 0 1 0-2.5-2.5 2.51 2.51 0 0 0 2.5 2.5zm0-4.51a2 2 0 1 1-2 2 2 2 0 0 1 2-2z"/><path class="cls-5" d="M441 38a7 7 0 0 0 6.53-4.49H452V38h5v-4.49h2v-5h-11.47A7 7 0 1 0 441 38zm0-13.48a6.48 6.48 0 0 1 6.11 4.32l.06.17h11.32v4h-2v4.49h-4V33h-5.3l-.06.17a6.48 6.48 0 1 1-6.13-8.65z"/><path d="M256 92v1a37 37 0 0 1 37 37h1a38 38 0 0 0-38-38z" fill="#f7bb2a"/><path class="cls-1" d="M411.08 121a16.81 16.81 0 0 0-13.08 6.27 11.21 11.21 0 0 0-15 10.58h44.93A16.85 16.85 0 0 0 411.08 121z"/><path class="cls-3" d="M411.08 121.7a16.17 16.17 0 0 1 16.13 15.44h-43.48a10.5 10.5 0 0 1 14-9.22l.47.17.31-.39a16.09 16.09 0 0 1 12.56-6m0-.7a16.81 16.81 0 0 0-13.07 6.27 11.21 11.21 0 0 0-15 10.58h44.93A16.85 16.85 0 0 0 411.08 121z"/></svg> \ No newline at end of file
diff --git a/chrome/browser/resources/signin/dice_sync_confirmation/images/sync_confirmation_illustration_dark.svg b/chrome/browser/resources/signin/sync_confirmation/images/sync_confirmation_illustration_dark.svg similarity index 100% rename from chrome/browser/resources/signin/dice_sync_confirmation/images/sync_confirmation_illustration_dark.svg rename to chrome/browser/resources/signin/sync_confirmation/images/sync_confirmation_illustration_dark.svg
diff --git a/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.html b/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.html index 57db3894..6b02251 100644 --- a/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.html +++ b/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.html
@@ -3,73 +3,26 @@ <head> <meta charset="utf-8"> <link rel="stylesheet" href="chrome://resources/css/md_colors.css"> + <link rel="import" href="sync_confirmation_app.html"></link> <style> - html { - background-color: var(--md-background-color); + body { + margin: 0; + padding: 0; + width: 512px; + } + @media (prefers-color-scheme: dark) { + body { + background-color: var(--md-background-color); + } } </style> - </custom-style> - <link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html"> - <link rel="import" href="chrome://resources/html/polymer.html"> - <link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html"> - <link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html"> - <link rel="import" href="signin_shared_css.html"> - <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css"> - <custom-style> - <style include="signin-dialog-shared paper-button-style"> - .details { - padding: 0 24px; - } - #undoButton { -<if expr="is_macosx or is_linux"> - margin-inline-end: 8px; -</if> -<if expr="not is_macosx and not is_linux"> - margin-inline-start: 8px; -</if> - } - - #syncDisabledDetails { - line-height: 20px; - margin-bottom: 8px; - margin-top: 16px; - padding: 0 24px; - } - - </style> - </custom-style> </head> <body> - <!-- - Use the 'consent-description' attribute to annotate all the UI elements - that are part of the text the user reads before consenting to the Sync - data collection . Similarly, use 'consent-confirmation' on UI elements on - which user clicks to indicate consent. - --> - <div class="container"> - <div class="top-title-bar" consent-description> - $i18n{syncConfirmationTitle} - </div> - <div class="details" id="syncDisabledDetails"> - <div class="body text" consent-description> - $i18n{syncDisabledConfirmationDetails} - </div> - </div> - <div class="action-container"> - <paper-button class="action-button" id="confirmButton" - consent-confirmation> - $i18n{syncConfirmationConfirmLabel} - </paper-button> - <paper-button id="undoButton"> - $i18n{syncConfirmationUndoLabel} - </paper-button> - </div> - </div> + <sync-confirmation-app></sync-confirmation-app> </body> - <link rel="import" href="chrome://resources/html/cr.html"> - <link rel="import" href="chrome://resources/html/load_time_data.html"> - <link rel="import" href="chrome://resources/html/util.html"> + <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css"> + <link rel="import" href="chrome://resources/html/cr.html"></script> + <link rel="import" href="chrome://resources/html/util.html"></script> <script src="sync_confirmation.js"></script> - <script src="chrome://sync-confirmation/strings.js"></script> <link rel="import" href="chrome://resources/html/dark_mode.html"> </html>
diff --git a/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.js b/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.js index 12307c57..31aa325f 100644 --- a/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.js +++ b/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.js
@@ -1,77 +1,32 @@ -/* Copyright 2015 The Chromium Authors. All rights reserved. +/* 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. */ cr.define('sync.confirmation', function() { 'use strict'; - /** - * @param {!Array<!HTMLElement>} path Path of the click event. Must contain - * a consent confirmation element. - * @return {string} The text of the consent confirmation element. - * @private - */ - function getConsentConfirmation(path) { - let consentConfirmation; - for (const element of path) { - if (element.nodeType !== Node.DOCUMENT_FRAGMENT_NODE && - element.hasAttribute('consent-confirmation')) { - return element.innerHTML.trim(); - } - } - assertNotReached('No consent confirmation element found.'); - return ''; - } - - /** @return {!Array<string>} Text of the consent description elements. */ - function getConsentDescription() { - const consentDescription = - Array.from(document.querySelectorAll('[consent-description]')) - .filter(element => element.clientWidth * element.clientHeight > 0) - .map(element => element.innerHTML.trim()); - assert(consentDescription); - return consentDescription; - } - - function onConfirm(e) { - chrome.send( - 'confirm', [getConsentDescription(), getConsentConfirmation(e.path)]); - } - - function onUndo(e) { - chrome.send('undo'); - } - function initialize() { - document.addEventListener('keydown', onKeyDown); - $('confirmButton').addEventListener('click', onConfirm); - $('undoButton').addEventListener('click', onUndo); + const syncConfirmationBrowserProxy = + sync.confirmation.SyncConfirmationBrowserProxyImpl.getInstance(); // Prefer using |document.body.offsetHeight| instead of // |document.body.scrollHeight| as it returns the correct height of the // even when the page zoom in Chrome is different than 100%. - chrome.send('initializedWithSize', [document.body.offsetHeight]); + syncConfirmationBrowserProxy.initializedWithSize( + [document.body.offsetHeight]); + // The web dialog size has been initialized, so reset the body width to + // auto. This makes sure that the body only takes up the viewable width, + // e.g. when there is a scrollbar. + document.body.style.width = 'auto'; } function clearFocus() { document.activeElement.blur(); } - function onKeyDown(e) { - // If the currently focused element isn't something that performs an action - // on "enter" being pressed and the user hits "enter", perform the default - // action of the dialog, which is "OK, Got It". - if (e.key == 'Enter' && - !/^(A|PAPER-(BUTTON|CHECKBOX))$/.test(document.activeElement.tagName)) { - $('confirmButton').click(); - e.preventDefault(); - } - } - - // TODO(tangltom): clearFocus is called directly by the C++ handler. - // C++ handlers should not be calling JS functions by name anymore. They - // should be firing events with FireWebuiListener and have the page itself - // decide whether to listen or not listen to the event. - return {clearFocus: clearFocus, initialize: initialize}; + return { + clearFocus: clearFocus, + initialize: initialize, + }; }); document.addEventListener('DOMContentLoaded', sync.confirmation.initialize);
diff --git a/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_app.html b/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_app.html similarity index 100% rename from chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_app.html rename to chrome/browser/resources/signin/sync_confirmation/sync_confirmation_app.html
diff --git a/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_app.js b/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_app.js similarity index 100% rename from chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_app.js rename to chrome/browser/resources/signin/sync_confirmation/sync_confirmation_app.js
diff --git a/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_browser_proxy.html b/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_browser_proxy.html similarity index 100% rename from chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_browser_proxy.html rename to chrome/browser/resources/signin/sync_confirmation/sync_confirmation_browser_proxy.html
diff --git a/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_browser_proxy.js b/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_browser_proxy.js similarity index 96% rename from chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_browser_proxy.js rename to chrome/browser/resources/signin/sync_confirmation/sync_confirmation_browser_proxy.js index 2f8a6da..c5cb104a 100644 --- a/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_browser_proxy.js +++ b/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_browser_proxy.js
@@ -8,7 +8,6 @@ */ cr.define('sync.confirmation', function() { - /** @interface */ class SyncConfirmationBrowserProxy { /** @@ -20,7 +19,8 @@ */ confirm(description, confirmation) {} - /** Called when the user undoes the Sync confirmation. + /** + * Called when the user undoes the Sync confirmation. */ undo() {}
diff --git a/chrome/browser/resources/signin/sync_confirmation/sync_disabled_confirmation.html b/chrome/browser/resources/signin/sync_confirmation/sync_disabled_confirmation.html new file mode 100644 index 0000000..77cac079 --- /dev/null +++ b/chrome/browser/resources/signin/sync_confirmation/sync_disabled_confirmation.html
@@ -0,0 +1,75 @@ +<!doctype html> +<html dir="$i18n{textdirection}" lang="$i18n{language}" $i18n{dark}> + <head> + <meta charset="utf-8"> + <link rel="stylesheet" href="chrome://resources/css/md_colors.css"> + <style> + html { + background-color: var(--md-background-color); + } + </style> + </custom-style> + <link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html"> + <link rel="import" href="chrome://resources/html/polymer.html"> + <link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html"> + <link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html"> + <link rel="import" href="signin_shared_css.html"> + <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css"> + <custom-style> + <style include="signin-dialog-shared paper-button-style"> + .details { + padding: 0 24px; + } + #undoButton { +<if expr="is_macosx or is_linux"> + margin-inline-end: 8px; +</if> +<if expr="not is_macosx and not is_linux"> + margin-inline-start: 8px; +</if> + } + + #syncDisabledDetails { + line-height: 20px; + margin-bottom: 8px; + margin-top: 16px; + padding: 0 24px; + } + + </style> + </custom-style> + </head> + <body> + <!-- + Use the 'consent-description' attribute to annotate all the UI elements + that are part of the text the user reads before consenting to the Sync + data collection . Similarly, use 'consent-confirmation' on UI elements on + which user clicks to indicate consent. + --> + <div class="container"> + <div class="top-title-bar" consent-description> + $i18n{syncConfirmationTitle} + </div> + <div class="details" id="syncDisabledDetails"> + <div class="body text" consent-description> + $i18n{syncDisabledConfirmationDetails} + </div> + </div> + <div class="action-container"> + <paper-button class="action-button" id="confirmButton" + consent-confirmation> + $i18n{syncConfirmationConfirmLabel} + </paper-button> + <paper-button id="undoButton"> + $i18n{syncConfirmationUndoLabel} + </paper-button> + </div> + </div> + </body> + <link rel="import" href="chrome://resources/html/cr.html"> + <link rel="import" href="chrome://resources/html/load_time_data.html"> + <link rel="import" href="chrome://resources/html/util.html"> + <script src="sync_disabled_confirmation.js"></script> + <script src="chrome://sync-confirmation/strings.js"></script> + <link rel="import" href="chrome://resources/html/dark_mode.html"> +</html>
diff --git a/chrome/browser/resources/signin/sync_confirmation/sync_disabled_confirmation.js b/chrome/browser/resources/signin/sync_confirmation/sync_disabled_confirmation.js new file mode 100644 index 0000000..12307c57 --- /dev/null +++ b/chrome/browser/resources/signin/sync_confirmation/sync_disabled_confirmation.js
@@ -0,0 +1,77 @@ +/* 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. */ + +cr.define('sync.confirmation', function() { + 'use strict'; + + /** + * @param {!Array<!HTMLElement>} path Path of the click event. Must contain + * a consent confirmation element. + * @return {string} The text of the consent confirmation element. + * @private + */ + function getConsentConfirmation(path) { + let consentConfirmation; + for (const element of path) { + if (element.nodeType !== Node.DOCUMENT_FRAGMENT_NODE && + element.hasAttribute('consent-confirmation')) { + return element.innerHTML.trim(); + } + } + assertNotReached('No consent confirmation element found.'); + return ''; + } + + /** @return {!Array<string>} Text of the consent description elements. */ + function getConsentDescription() { + const consentDescription = + Array.from(document.querySelectorAll('[consent-description]')) + .filter(element => element.clientWidth * element.clientHeight > 0) + .map(element => element.innerHTML.trim()); + assert(consentDescription); + return consentDescription; + } + + function onConfirm(e) { + chrome.send( + 'confirm', [getConsentDescription(), getConsentConfirmation(e.path)]); + } + + function onUndo(e) { + chrome.send('undo'); + } + + function initialize() { + document.addEventListener('keydown', onKeyDown); + $('confirmButton').addEventListener('click', onConfirm); + $('undoButton').addEventListener('click', onUndo); + // Prefer using |document.body.offsetHeight| instead of + // |document.body.scrollHeight| as it returns the correct height of the + // even when the page zoom in Chrome is different than 100%. + chrome.send('initializedWithSize', [document.body.offsetHeight]); + } + + function clearFocus() { + document.activeElement.blur(); + } + + function onKeyDown(e) { + // If the currently focused element isn't something that performs an action + // on "enter" being pressed and the user hits "enter", perform the default + // action of the dialog, which is "OK, Got It". + if (e.key == 'Enter' && + !/^(A|PAPER-(BUTTON|CHECKBOX))$/.test(document.activeElement.tagName)) { + $('confirmButton').click(); + e.preventDefault(); + } + } + + // TODO(tangltom): clearFocus is called directly by the C++ handler. + // C++ handlers should not be calling JS functions by name anymore. They + // should be firing events with FireWebuiListener and have the page itself + // decide whether to listen or not listen to the event. + return {clearFocus: clearFocus, initialize: initialize}; +}); + +document.addEventListener('DOMContentLoaded', sync.confirmation.initialize);
diff --git a/chrome/browser/sync/test/integration/single_client_nigori_sync_test.cc b/chrome/browser/sync/test/integration/single_client_nigori_sync_test.cc index a816ac39..e3c917b 100644 --- a/chrome/browser/sync/test/integration/single_client_nigori_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_nigori_sync_test.cc
@@ -4,8 +4,11 @@ #include "base/base64.h" #include "base/macros.h" +#include "base/test/scoped_feature_list.h" #include "chrome/browser/sync/test/integration/encryption_helper.h" +#include "chrome/browser/sync/test/integration/profile_sync_service_harness.h" #include "chrome/browser/sync/test/integration/sync_test.h" +#include "components/sync/driver/sync_driver_switches.h" #include "components/sync/nigori/nigori.h" #include "testing/gmock/include/gmock/gmock.h" @@ -32,16 +35,35 @@ return encrypted_data.key_name() == nigori_name; } -class SingleClientNigoriSyncTest : public SyncTest { +class SingleClientNigoriSyncTestWithUssTests + : public SyncTest, + public testing::WithParamInterface<bool> { public: - SingleClientNigoriSyncTest() : SyncTest(SINGLE_CLIENT) {} - ~SingleClientNigoriSyncTest() override = default; + SingleClientNigoriSyncTestWithUssTests() : SyncTest(SINGLE_CLIENT) { + if (GetParam()) { + // USS Nigori requires USS implementations to be enabled for all + // datatypes. + override_features_.InitWithFeatures( + /*enabled_features=*/{switches::kSyncUSSBookmarks, + switches::kSyncUSSPasswords, + switches::kSyncUSSAutofillWalletMetadata, + switches::kSyncUSSNigori}, + /*disabled_features=*/{}); + } else { + // We test Directory Nigori with default values of USS feature flags of + // other datatypes. + override_features_.InitAndDisableFeature(switches::kSyncUSSNigori); + } + } + ~SingleClientNigoriSyncTestWithUssTests() override = default; private: - DISALLOW_COPY_AND_ASSIGN(SingleClientNigoriSyncTest); + DISALLOW_COPY_AND_ASSIGN(SingleClientNigoriSyncTestWithUssTests); + + base::test::ScopedFeatureList override_features_; }; -IN_PROC_BROWSER_TEST_F(SingleClientNigoriSyncTest, +IN_PROC_BROWSER_TEST_P(SingleClientNigoriSyncTestWithUssTests, ShouldCommitKeystoreNigoriWhenReceivedDefault) { // SetupSync() should make FakeServer send default NigoriSpecifics. ASSERT_TRUE(SetupSync()); @@ -61,4 +83,8 @@ EXPECT_TRUE(specifics.has_keystore_migration_time()); } +INSTANTIATE_TEST_SUITE_P(USS, + SingleClientNigoriSyncTestWithUssTests, + ::testing::Values(false, true)); + } // namespace
diff --git a/chrome/browser/sync/test/integration/single_client_sessions_sync_test.cc b/chrome/browser/sync/test/integration/single_client_sessions_sync_test.cc index 550ed9e..defe0a1d 100644 --- a/chrome/browser/sync/test/integration/single_client_sessions_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_sessions_sync_test.cc
@@ -458,8 +458,9 @@ ExpectNavigationChain({first_url, second_url}); } +// TODO(crbug.com/972929): The test is slow and times out often. IN_PROC_BROWSER_TEST_F(SingleClientSessionsSyncTest, - NavigationChainAlteredDestructively) { + DISABLED_NavigationChainAlteredDestructively) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; ASSERT_TRUE(CheckInitialState(0));
diff --git a/chrome/browser/sync/test/integration/two_client_wallet_sync_test.cc b/chrome/browser/sync/test/integration/two_client_wallet_sync_test.cc index c79a2b4d..eb9f3417 100644 --- a/chrome/browser/sync/test/integration/two_client_wallet_sync_test.cc +++ b/chrome/browser/sync/test/integration/two_client_wallet_sync_test.cc
@@ -467,7 +467,7 @@ // Flaky. http://crbug.com/917498 IN_PROC_BROWSER_TEST_P(TwoClientWalletSyncTest, - ServerAddressConvertsToSameLocalAddress) { + DISABLED_ServerAddressConvertsToSameLocalAddress) { GetFakeServer()->SetWalletData( {CreateSyncWalletAddress(/*name=*/"address-1", /*company=*/"Company-1"), CreateDefaultSyncPaymentsCustomerData()});
diff --git a/chrome/browser/ui/android/passwords/manual_filling_view_android.cc b/chrome/browser/ui/android/passwords/manual_filling_view_android.cc index f4ffb7c2..c7335a8 100644 --- a/chrome/browser/ui/android/passwords/manual_filling_view_android.cc +++ b/chrome/browser/ui/android/passwords/manual_filling_view_android.cc
@@ -34,7 +34,9 @@ using autofill::AccessorySheetData; using autofill::FooterCommand; +using autofill::PasswordForm; using autofill::UserInfo; +using autofill::password_generation::PasswordGenerationUIData; using base::android::ConvertJavaStringToUTF16; using base::android::ConvertUTF16ToJavaString; using base::android::JavaRef; @@ -131,12 +133,6 @@ static_cast<autofill::AccessoryAction>(selected_action)); } -void ManualFillingViewAndroid::OnGenerationRequested( - JNIEnv* env, - const base::android::JavaParamRef<jobject>& obj) { - controller_->OnGenerationRequested(); -} - void ManualFillingViewAndroid::OnImageFetched( const base::android::ScopedJavaGlobalRef<jobject>& j_callback, const gfx::Image& image) { @@ -237,11 +233,6 @@ jboolean j_available) { content::WebContents* web_contents = content::WebContents::FromJavaWebContents(j_web_contents); - if (j_available) { - // The added generation button will call back to the generation controller - // so we need to make sure one exists. - ignore_result(PasswordGenerationController::GetOrCreate(web_contents)); - } // Bypass the generation controller when sending this status to the UI to // avoid setup overhead, since its logic is currently not needed for tests.
diff --git a/chrome/browser/ui/android/passwords/manual_filling_view_android.h b/chrome/browser/ui/android/passwords/manual_filling_view_android.h index 99914e3c..960267e 100644 --- a/chrome/browser/ui/android/passwords/manual_filling_view_android.h +++ b/chrome/browser/ui/android/passwords/manual_filling_view_android.h
@@ -49,8 +49,6 @@ void OnOptionSelected(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, jint selected_action); - void OnGenerationRequested(JNIEnv* env, - const base::android::JavaParamRef<jobject>& obj); private: void OnImageFetched(
diff --git a/chrome/browser/ui/autofill/autofill_popup_controller_impl.cc b/chrome/browser/ui/autofill/autofill_popup_controller_impl.cc index e0d6cadb..e26c6b6 100644 --- a/chrome/browser/ui/autofill/autofill_popup_controller_impl.cc +++ b/chrome/browser/ui/autofill/autofill_popup_controller_impl.cc
@@ -561,7 +561,7 @@ void AutofillPopupControllerImpl::HideViewAndDie() { #if defined(OS_ANDROID) ManualFillingController::GetOrCreate(web_contents_) - ->Hide(FillingSource::AUTOFILL); + ->DeactivateFillingSource(FillingSource::AUTOFILL); #endif if (view_)
diff --git a/chrome/browser/ui/extensions/app_launch_params.cc b/chrome/browser/ui/extensions/app_launch_params.cc index 97005f8..2246589 100644 --- a/chrome/browser/ui/extensions/app_launch_params.cc +++ b/chrome/browser/ui/extensions/app_launch_params.cc
@@ -17,14 +17,12 @@ #endif using extensions::ExtensionPrefs; -using extensions::api::app_runtime::PlayStoreStatus; AppLaunchParams::AppLaunchParams(Profile* profile, const extensions::Extension* extension, extensions::LaunchContainer container, WindowOpenDisposition disposition, extensions::AppLaunchSource source, - bool set_playstore_status, int64_t display_id) : profile(profile), extension_id(extension ? extension->id() : std::string()), @@ -32,19 +30,8 @@ disposition(disposition), command_line(base::CommandLine::NO_PROGRAM), source(source), - play_store_status(PlayStoreStatus::PLAY_STORE_STATUS_UNKNOWN), display_id(display_id), opener(nullptr) { -#if defined(OS_CHROMEOS) - // TODO(b/34478891): Remove this from app launch. - if (set_playstore_status) { - if (arc::IsArcAllowedForProfile(profile)) - play_store_status = PlayStoreStatus::PLAY_STORE_STATUS_ENABLED; - else if (arc::IsArcAvailable()) - play_store_status = PlayStoreStatus::PLAY_STORE_STATUS_AVAILABLE; - // else, default to PLAY_STORE_STATUS_UNKNOWN. - } -#endif } AppLaunchParams::AppLaunchParams(const AppLaunchParams& other) = default; @@ -89,5 +76,5 @@ disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB; } return AppLaunchParams(profile, extension, container, disposition, source, - false, display_id); + display_id); }
diff --git a/chrome/browser/ui/extensions/app_launch_params.h b/chrome/browser/ui/extensions/app_launch_params.h index febd5ae..d0d41a7 100644 --- a/chrome/browser/ui/extensions/app_launch_params.h +++ b/chrome/browser/ui/extensions/app_launch_params.h
@@ -10,7 +10,6 @@ #include "base/command_line.h" #include "base/files/file_path.h" #include "chrome/common/extensions/extension_constants.h" -#include "extensions/common/api/app_runtime.h" #include "extensions/common/constants.h" #include "ui/base/window_open_disposition.h" #include "ui/display/types/display_constants.h" @@ -33,7 +32,6 @@ extensions::LaunchContainer container, WindowOpenDisposition disposition, extensions::AppLaunchSource source, - bool set_playstore_status = false, int64_t display_id = display::kInvalidDisplayId); AppLaunchParams(const AppLaunchParams& other); @@ -78,9 +76,6 @@ // Different app may have their own enumeration of sources. extensions::AppLaunchSource source; - // Status of ARC on this device. - extensions::api::app_runtime::PlayStoreStatus play_store_status; - // The id of the display from which the app is launched. // display::kInvalidDisplayId means that the display does not exist or is not // set.
diff --git a/chrome/browser/ui/extensions/application_launch.cc b/chrome/browser/ui/extensions/application_launch.cc index e90984e0..335a225b 100644 --- a/chrome/browser/ui/extensions/application_launch.cc +++ b/chrome/browser/ui/extensions/application_launch.cc
@@ -283,7 +283,7 @@ if (CanLaunchViaEvent(extension)) { apps::LaunchPlatformAppWithCommandLineAndLaunchId( params.profile, extension, params.launch_id, params.command_line, - params.current_directory, params.source, params.play_store_status); + params.current_directory, params.source); return NULL; }
diff --git a/chrome/browser/ui/extensions/hosted_app_browser_controller.cc b/chrome/browser/ui/extensions/hosted_app_browser_controller.cc index b9a45fe3..ad169b0 100644 --- a/chrome/browser/ui/extensions/hosted_app_browser_controller.cc +++ b/chrome/browser/ui/extensions/hosted_app_browser_controller.cc
@@ -325,7 +325,10 @@ if (!browser()->bounds_overridden()) return; - DCHECK(chrome::SavedBoundsAreContentBounds(browser())); + // The saved bounds will only be wrong if they are content bounds. + if (!chrome::SavedBoundsAreContentBounds(browser())) + return; + // TODO(crbug.com/964825): Correctly set the window size at creation time. // This is currently not possible because the current url is not easily known // at popup construction time.
diff --git a/chrome/browser/ui/extensions/hosted_app_browsertest.cc b/chrome/browser/ui/extensions/hosted_app_browsertest.cc index db9d7377..a8239db 100644 --- a/chrome/browser/ui/extensions/hosted_app_browsertest.cc +++ b/chrome/browser/ui/extensions/hosted_app_browsertest.cc
@@ -33,6 +33,7 @@ #include "chrome/browser/predictors/loading_predictor_config.h" #include "chrome/browser/profiles/profile_io_data.h" #include "chrome/browser/renderer_context_menu/render_view_context_menu_test_util.h" +#include "chrome/browser/sessions/tab_restore_service_factory.h" #include "chrome/browser/ssl/ssl_browsertest_util.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_dialogs.h" @@ -57,6 +58,7 @@ #include "chrome/test/base/ui_test_utils.h" #include "components/security_interstitials/content/security_interstitial_tab_helper.h" #include "components/security_interstitials/core/controller_client.h" +#include "components/sessions/core/tab_restore_service.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/interstitial_page.h" #include "content/public/browser/interstitial_page_delegate.h" @@ -332,20 +334,6 @@ LaunchApp(); } - void SetupSystemAppWithURL(const GURL& app_url) { - extensions::TestExtensionDir test_app_dir; - test_app_dir.WriteManifest( - base::StringPrintf(kAppDotComManifest, app_url.spec().c_str())); - - app_ = InstallExtensionWithSourceAndFlags( - test_app_dir.UnpackedPath(), 1, - extensions::Manifest::EXTERNAL_COMPONENT, - extensions::Extension::FROM_BOOKMARK); - ASSERT_TRUE(app_); - - LaunchApp(); - } - void LaunchApp() { // Launch app in a window. app_browser_ = LaunchAppBrowser(app_); @@ -1185,6 +1173,33 @@ EXPECT_EQ(new_browser->window()->GetBounds(), bounds); } +// Tests that desktop PWAs are reopened at the correct size. +IN_PROC_BROWSER_TEST_P(HostedAppPWAOnlyTest, + ReopenedPWASizeIsCorrectlyRestored) { + ASSERT_TRUE(https_server()->Start()); + + InstallSecurePWA(); + + EXPECT_TRUE(web_app::AppBrowserController::IsForWebAppBrowser(app_browser_)); + NavigateToURLAndWait(app_browser_, GetSecureAppURL()); + + gfx::Rect bounds = gfx::Rect(10, 10, 500, 500); + app_browser_->window()->SetBounds(bounds); + app_browser_->window()->Close(); + + content::WebContentsAddedObserver new_contents_observer; + + sessions::TabRestoreService* service = + TabRestoreServiceFactory::GetForProfile(app_browser_->profile()); + service->RestoreMostRecentEntry(nullptr); + + content::WebContents* restored_web_contents = + new_contents_observer.GetWebContents(); + Browser* restored_browser = + chrome::FindBrowserWithWebContents(restored_web_contents); + EXPECT_EQ(restored_browser->window()->GetBounds(), bounds); +} + // Tests that using window.open to create a popup window out of scope results in // a correctly sized window. IN_PROC_BROWSER_TEST_P(HostedAppPWAOnlyTest, OffScopePWAPopupsHaveCorrectSize) { @@ -1774,61 +1789,6 @@ } #endif -// Check that the toolbar is shown correctly with a System App. -IN_PROC_BROWSER_TEST_P(HostedAppPWAOnlyTest, ShouldShowToolbarForSystemApp) { - const GURL app_url(chrome::kChromeUISettingsURL); - - SetupSystemAppWithURL(app_url); - - // Navigate to the app's launch page; the toolbar should be hidden. - NavigateAndCheckForToolbar(app_browser_, app_url, false); -} - -#if (defined(OS_LINUX) || defined(OS_CHROMEOS)) && !defined(NDEBUG) -// https://crbug.com/966834. Flaky on Linux/Chrome OS debug bots. -#define MAYBE_ShouldNotShowToolbarForSystemWebAppInChrome \ - DISABLED_ShouldNotShowToolbarForSystemWebAppInChrome -#else -#define MAYBE_ShouldNotShowToolbarForSystemWebAppInChrome \ - ShouldNotShowToolbarForSystemWebAppInChrome -#endif -// Check the toolbar is not shown for system web apps for pages on the chrome:// -// scheme. -IN_PROC_BROWSER_TEST_P(HostedAppPWAOnlyTest, - MAYBE_ShouldNotShowToolbarForSystemWebAppInChrome) { - const GURL app_url(chrome::kChromeUISettingsURL); - - SetupSystemAppWithURL(app_url); - - // Navigate to the app's launch page; the toolbar should be hidden. - NavigateAndCheckForToolbar(app_browser_, app_url, false); - - // Because the first part of the url is on a different origin (settings vs. - // foo) a toolbar would normally be shown. However, because settings is a - // SystemWebApp and foo is served via chrome:// it is okay not to show the - // toolbar. - GURL out_of_scope_chrome_page(app_url.spec() + "://foo"); - LOG(ERROR) << out_of_scope_chrome_page; - NavigateAndCheckForToolbar(app_browser_, out_of_scope_chrome_page, false); -} - -// Check the toolbar is shown for system web apps on pages not on the chrome:// -// scheme. Note: We should never normally get into this scenario. -IN_PROC_BROWSER_TEST_P(HostedAppPWAOnlyTest, - ShouldShowToolbarForSystemWebAppOnInternet) { - const GURL app_url(chrome::kChromeUISettingsURL); - - SetupSystemAppWithURL(app_url); - - // Navigate to the app's launch page; the toolbar should be hidden. - NavigateAndCheckForToolbar(app_browser_, app_url, false); - - // Even though the url is secure it is not being served over chrome:// so a - // toolbar should be shown. - GURL off_scheme_page("https://example.com"); - NavigateAndCheckForToolbar(app_browser_, off_scheme_page, true); -} - // Common app manifest for HostedAppProcessModelTests. constexpr const char kHostedAppProcessModelManifest[] = R"( { "name": "Hosted App Process Model Test",
diff --git a/chrome/browser/ui/views/collected_cookies_views.cc b/chrome/browser/ui/views/collected_cookies_views.cc index aa600d5..0e88ed3 100644 --- a/chrome/browser/ui/views/collected_cookies_views.cc +++ b/chrome/browser/ui/views/collected_cookies_views.cc
@@ -27,12 +27,9 @@ #include "chrome/browser/ui/views/chrome_layout_provider.h" #include "chrome/browser/ui/views/chrome_typography.h" #include "chrome/browser/ui/views/cookie_info_view.h" -#include "chrome/common/pref_names.h" #include "chrome/grit/generated_resources.h" #include "components/constrained_window/constrained_window_views.h" #include "components/content_settings/core/browser/cookie_settings.h" -#include "components/content_settings/core/common/pref_names.h" -#include "components/prefs/pref_service.h" #include "components/strings/grit/components_strings.h" #include "components/vector_icons/vector_icons.h" #include "content/public/browser/notification_details.h" @@ -505,12 +502,12 @@ Profile* profile = Profile::FromBrowserContext(web_contents_->GetBrowserContext()); - PrefService* prefs = profile->GetPrefs(); + auto cookie_settings = CookieSettingsFactory::GetForProfile(profile); // Create the controls that go into the pane. blocked_label_ = new views::Label( l10n_util::GetStringUTF16( - prefs->GetBoolean(prefs::kBlockThirdPartyCookies) + cookie_settings->ShouldBlockThirdPartyCookies() ? IDS_COLLECTED_COOKIES_BLOCKED_THIRD_PARTY_BLOCKING_ENABLED : IDS_COLLECTED_COOKIES_BLOCKED_COOKIES_LABEL), CONTEXT_BODY_TEXT_LARGE);
diff --git a/chrome/browser/ui/views/location_bar/custom_tab_bar_view.cc b/chrome/browser/ui/views/location_bar/custom_tab_bar_view.cc index 02f95e6..ecd114d 100644 --- a/chrome/browser/ui/views/location_bar/custom_tab_bar_view.cc +++ b/chrome/browser/ui/views/location_bar/custom_tab_bar_view.cc
@@ -15,6 +15,7 @@ #include "chrome/browser/ui/views/chrome_typography.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/frame/hosted_app_button_container.h" +#include "chrome/browser/ui/web_applications/app_browser_controller.h" #include "components/security_interstitials/content/security_interstitial_tab_helper.h" #include "components/url_formatter/url_formatter.h" #include "components/vector_icons/vector_icons.h" @@ -246,13 +247,21 @@ last_title_ = title; last_location_ = location; - // Only show the close button if the current URL is not in the application - // scope (it doesn't make sense to show a 'back-to-scope' button in scope). - close_button_->SetVisible(!extensions::IsSameScope( - chrome::FindBrowserWithWebContents(contents) - ->app_controller() - ->GetAppLaunchURL(), - contents->GetVisibleURL(), contents->GetBrowserContext())); + web_app::AppBrowserController* app_controller = + chrome::FindBrowserWithWebContents(contents)->app_controller(); + const bool started_in_scope = extensions::IsSameScope( + app_controller->GetAppLaunchURL(), app_controller->initial_url(), + contents->GetBrowserContext()); + + // Only show the 'X' button if the current URL is not in the application + // scope (it doesn't make sense to show a 'back-to-scope' button in scope) + // and if the window started in scope (this is important for popup windows + // which get opened out of scope). + close_button_->SetVisible( + started_in_scope && + !extensions::IsSameScope(app_controller->GetAppLaunchURL(), + contents->GetVisibleURL(), + contents->GetBrowserContext())); Layout(); }
diff --git a/chrome/browser/ui/views/location_bar/custom_tab_bar_view_browsertest.cc b/chrome/browser/ui/views/location_bar/custom_tab_bar_view_browsertest.cc index f839194..daf59c72 100644 --- a/chrome/browser/ui/views/location_bar/custom_tab_bar_view_browsertest.cc +++ b/chrome/browser/ui/views/location_bar/custom_tab_bar_view_browsertest.cc
@@ -276,6 +276,31 @@ EXPECT_FALSE(popup_view->toolbar()->custom_tab_bar()); } +IN_PROC_BROWSER_TEST_F(CustomTabBarViewBrowserTest, + BackToAppButtonIsNotVisibleInOutOfScopePopups) { + ASSERT_TRUE(https_server()->Start()); + + const GURL& app_url = https_server()->GetURL("app.com", "/ssl/google.html"); + const GURL& out_of_scope_url = GURL("https://example.com"); + + InstallBookmark(app_url); + + BrowserView* app_view = BrowserView::GetBrowserViewForBrowser(app_browser_); + + Browser* popup_browser = + OpenPopup(app_view->GetActiveWebContents(), out_of_scope_url); + + // Out of scope, so custom tab bar should be shown. + EXPECT_TRUE(popup_browser->app_controller()->ShouldShowToolbar()); + + // As the popup was opened out of scope the close button should not be shown. + EXPECT_FALSE(BrowserView::GetBrowserViewForBrowser(popup_browser) + ->toolbar() + ->custom_tab_bar() + ->close_button_for_testing() + ->GetVisible()); +} + // Check the custom tab will be used for a Desktop PWA. IN_PROC_BROWSER_TEST_F(CustomTabBarViewBrowserTest, IsUsedForDesktopPWA) { ASSERT_TRUE(https_server()->Start());
diff --git a/chrome/browser/ui/views/omnibox/omnibox_popup_contents_view_browsertest.cc b/chrome/browser/ui/views/omnibox/omnibox_popup_contents_view_browsertest.cc index 7bd2f63..31124ee5 100644 --- a/chrome/browser/ui/views/omnibox/omnibox_popup_contents_view_browsertest.cc +++ b/chrome/browser/ui/views/omnibox/omnibox_popup_contents_view_browsertest.cc
@@ -29,6 +29,8 @@ #include "ui/base/ui_base_features.h" #include "ui/compositor/layer_animator.h" #include "ui/events/test/event_generator.h" +#include "ui/views/accessibility/ax_event_manager.h" +#include "ui/views/accessibility/ax_event_observer.h" #include "ui/views/widget/widget.h" #if defined(USE_AURA) @@ -82,6 +84,34 @@ DISALLOW_COPY_AND_ASSIGN(ThemeChangeWaiter); }; +class TestAXEventObserver : public views::AXEventObserver { + public: + TestAXEventObserver() { views::AXEventManager::Get()->AddObserver(this); } + + ~TestAXEventObserver() override { + views::AXEventManager::Get()->RemoveObserver(this); + } + + // views::AXEventObserver: + void OnViewEvent(views::View* view, ax::mojom::Event event_type) override { + ui::AXNodeData node_data; + view->GetAccessibleNodeData(&node_data); + if (event_type == ax::mojom::Event::kTextChanged && + node_data.role == ax::mojom::Role::kListBoxOption) { + text_changed_on_listboxoption_count_++; + } + } + + int text_changed_on_listboxoption_count() { + return text_changed_on_listboxoption_count_; + } + + private: + int text_changed_on_listboxoption_count_ = 0; + + DISALLOW_COPY_AND_ASSIGN(TestAXEventObserver); +}; + } // namespace class OmniboxPopupContentsViewTest : public InProcessBrowserTest { @@ -334,3 +364,17 @@ EXPECT_EQ(color_before_focus, location_bar()->background()->get_color()); EXPECT_EQ(color_before_focus, omnibox_view()->GetBackgroundColor()); } + +IN_PROC_BROWSER_TEST_F(OmniboxPopupContentsViewTest, + EmitTextChangedAccessibilityEvent) { + // Set the result to what we want and update. + TestAXEventObserver observer; + popup_view()->UpdatePopupAppearance(); + EXPECT_EQ(observer.text_changed_on_listboxoption_count(), 0); + + // Calling it again should emit the event. + edit_model()->SetUserText(base::ASCIIToUTF16("bar")); + edit_model()->StartAutocomplete(false, false); + popup_view()->UpdatePopupAppearance(); + EXPECT_EQ(observer.text_changed_on_listboxoption_count(), 1); +}
diff --git a/chrome/browser/ui/views/omnibox/omnibox_result_view.cc b/chrome/browser/ui/views/omnibox/omnibox_result_view.cc index a938d7a..0a98e388 100644 --- a/chrome/browser/ui/views/omnibox/omnibox_result_view.cc +++ b/chrome/browser/ui/views/omnibox/omnibox_result_view.cc
@@ -111,6 +111,7 @@ Invalidate(); Layout(); + EmitTextChangedAccessiblityEvent(); } void OmniboxResultView::ShowKeyword(bool show_keyword) { @@ -465,6 +466,18 @@ popup_contents_view_->model()->TryDeletingLine(model_index_); } +void OmniboxResultView::EmitTextChangedAccessiblityEvent() { + if (!popup_contents_view_->IsOpen()) + return; + + base::string16 current_name = AutocompleteMatchType::ToAccessibilityLabel( + match_, match_.contents, false); + if (accessible_name_ != current_name) { + NotifyAccessibilityEvent(ax::mojom::Event::kTextChanged, true); + accessible_name_ = current_name; + } +} + //////////////////////////////////////////////////////////////////////////////// // OmniboxResultView, private:
diff --git a/chrome/browser/ui/views/omnibox/omnibox_result_view.h b/chrome/browser/ui/views/omnibox/omnibox_result_view.h index 165c65a9..dce840e 100644 --- a/chrome/browser/ui/views/omnibox/omnibox_result_view.h +++ b/chrome/browser/ui/views/omnibox/omnibox_result_view.h
@@ -88,6 +88,9 @@ // Removes the shown |match_| from history, if possible. void RemoveSuggestion() const; + // Call when updating |match_| to possibly fire Accessiblity events. + void EmitTextChangedAccessiblityEvent(); + // views::View: void Layout() override; bool OnMousePressed(const ui::MouseEvent& event) override; @@ -141,6 +144,9 @@ // The data this class is built to display (the "Omnibox Result"). AutocompleteMatch match_; + // Accessible name (enables to emit certain events). + base::string16 accessible_name_; + // For sliding in the keyword search. std::unique_ptr<gfx::SlideAnimation> animation_;
diff --git a/chrome/browser/ui/views/payments/shipping_address_editor_view_controller.cc b/chrome/browser/ui/views/payments/shipping_address_editor_view_controller.cc index a027c65..56727e0 100644 --- a/chrome/browser/ui/views/payments/shipping_address_editor_view_controller.cc +++ b/chrome/browser/ui/views/payments/shipping_address_editor_view_controller.cc
@@ -100,13 +100,16 @@ } else { autofill::ServerFieldTypeSet all_fields; profile_to_edit_->GetSupportedTypes(&all_fields); - // Clear all the address data in |profile_to_edit_|, in anticipation of - // adding only the fields present in the editor. Prefer this method to - // copying |profile| into |profile_to_edit_|, because the latter object - // needs to retain other properties (use count, use date, guid, - // etc.). - for (autofill::ServerFieldType type : all_fields) - profile_to_edit_->SetRawInfo(type, base::string16()); + // Clear all the address data in |profile_to_edit_| except the email field, + // in anticipation of adding only the fields present in the editor. Prefer + // this method to copying |profile| into |profile_to_edit_|, because the + // latter object needs to retain other properties (use count, use date, + // guid, etc.). + for (autofill::ServerFieldType type : all_fields) { + if (type != autofill::ServerFieldType::EMAIL_ADDRESS) { + profile_to_edit_->SetRawInfo(type, base::string16()); + } + } bool success = SaveFieldsToProfile(profile_to_edit_, /*ignore_errors=*/false);
diff --git a/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.cc b/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.cc index f8925d6..78f33804 100644 --- a/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.cc +++ b/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.cc
@@ -78,6 +78,8 @@ html_source->SetJsonPath("strings.js"); // Add localized strings. + html_source->AddLocalizedString("welcomePageTitle", + IDS_ACCOUNT_MIGRATION_WELCOME_PAGE_TITLE); html_source->AddLocalizedString("welcomeTitle", IDS_ACCOUNT_MIGRATION_WELCOME_TITLE); html_source->AddLocalizedString("welcomeMessage",
diff --git a/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc b/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc index 1cf1aab..d74d55b 100644 --- a/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc +++ b/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc
@@ -1698,6 +1698,12 @@ IDS_SETTINGS_ACCOUNT_MANAGER_MIGRATION_LABEL}, {"accountManagerReauthenticationLabel", IDS_SETTINGS_ACCOUNT_MANAGER_REAUTHENTICATION_LABEL}, + {"accountManagerMigrationTooltip", + IDS_SETTINGS_ACCOUNT_MANAGER_MIGRATION_TOOLTIP}, + {"accountManagerReauthenticationTooltip", + IDS_SETTINGS_ACCOUNT_MANAGER_REAUTHENTICATION_TOOLTIP}, + {"accountManagerMoreActionsTooltip", + IDS_SETTINGS_ACCOUNT_MANAGER_MORE_ACTIONS_TOOLTIP}, {"accountManagerManagedLabel", IDS_SETTINGS_ACCOUNT_MANAGER_MANAGEMENT_STATUS_MANAGED_ACCOUNT}, {"accountManagerUnmanagedLabel",
diff --git a/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc b/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc index 31705c9..864bfb50 100644 --- a/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc +++ b/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc
@@ -42,17 +42,16 @@ int confirm_button_ids = -1; int undo_button_ids = -1; if (is_sync_allowed) { - source->SetDefaultResource(IDR_DICE_SYNC_CONFIRMATION_HTML); + source->SetDefaultResource(IDR_SYNC_CONFIRMATION_HTML); source->AddResourcePath("sync_confirmation_browser_proxy.html", - IDR_DICE_SYNC_CONFIRMATION_BROWSER_PROXY_HTML); + IDR_SYNC_CONFIRMATION_BROWSER_PROXY_HTML); source->AddResourcePath("sync_confirmation_browser_proxy.js", - IDR_DICE_SYNC_CONFIRMATION_BROWSER_PROXY_JS); + IDR_SYNC_CONFIRMATION_BROWSER_PROXY_JS); source->AddResourcePath("sync_confirmation_app.html", - IDR_DICE_SYNC_CONFIRMATION_APP_HTML); + IDR_SYNC_CONFIRMATION_APP_HTML); source->AddResourcePath("sync_confirmation_app.js", - IDR_DICE_SYNC_CONFIRMATION_APP_JS); - source->AddResourcePath("sync_confirmation.js", - IDR_DICE_SYNC_CONFIRMATION_JS); + IDR_SYNC_CONFIRMATION_APP_JS); + source->AddResourcePath("sync_confirmation.js", IDR_SYNC_CONFIRMATION_JS); AddStringResource(source, "syncConfirmationSyncInfoTitle", IDS_SYNC_CONFIRMATION_UNITY_SYNC_INFO_TITLE); @@ -87,8 +86,9 @@ undo_button_ids = IDS_CANCEL; consent_feature_ = consent_auditor::Feature::CHROME_UNIFIED_CONSENT; } else { - source->SetDefaultResource(IDR_SYNC_CONFIRMATION_HTML); - source->AddResourcePath("sync_confirmation.js", IDR_SYNC_CONFIRMATION_JS); + source->SetDefaultResource(IDR_SYNC_DISABLED_CONFIRMATION_HTML); + source->AddResourcePath("sync_disabled_confirmation.js", + IDR_SYNC_DISABLED_CONFIRMATION_JS); AddStringResource(source, "syncDisabledConfirmationDetails", IDS_SYNC_DISABLED_CONFIRMATION_DETAILS);
diff --git a/chrome/browser/web_applications/bookmark_apps/system_web_app_manager_browsertest.cc b/chrome/browser/web_applications/bookmark_apps/system_web_app_manager_browsertest.cc index b3bf82a..9018776 100644 --- a/chrome/browser/web_applications/bookmark_apps/system_web_app_manager_browsertest.cc +++ b/chrome/browser/web_applications/bookmark_apps/system_web_app_manager_browsertest.cc
@@ -20,6 +20,7 @@ #include "chrome/browser/web_applications/test/test_system_web_app_manager.h" #include "chrome/common/chrome_features.h" #include "chrome/common/extensions/manifest_handlers/app_theme_color_info.h" +#include "chrome/common/webui_url_constants.h" #include "chrome/grit/browser_resources.h" #include "chrome/grit/chrome_unscaled_resources.h" #include "content/public/browser/web_contents.h" @@ -27,6 +28,7 @@ #include "content/public/browser/web_ui_controller.h" #include "content/public/browser/web_ui_controller_factory.h" #include "content/public/browser/web_ui_data_source.h" +#include "content/public/test/browser_test_utils.h" #include "content/public/test/test_utils.h" #include "extensions/browser/extension_registry.h" #include "testing/gtest/include/gtest/gtest.h" @@ -208,4 +210,33 @@ .IsSystemWebApp(app->id())); } +// Check the toolbar is not shown for system web apps for pages on the chrome:// +// scheme but is shown off the chrome:// scheme. +IN_PROC_BROWSER_TEST_F(SystemWebAppManagerBrowserTest, + ToolbarVisibilityForSystemWebApp) { + Browser* app_browser = + WaitForSystemAppInstallAndLaunch(SystemAppType::SETTINGS); + // In scope, the toolbar should not be visible. + EXPECT_FALSE(app_browser->app_controller()->ShouldShowToolbar()); + + // Because the first part of the url is on a different origin (settings vs. + // foo) a toolbar would normally be shown. However, because settings is a + // SystemWebApp and foo is served via chrome:// it is okay not to show the + // toolbar. + GURL out_of_scope_chrome_page(content::kChromeUIScheme + + std::string("://foo")); + content::NavigateToURLBlockUntilNavigationsComplete( + app_browser->tab_strip_model()->GetActiveWebContents(), + out_of_scope_chrome_page, 1); + EXPECT_FALSE(app_browser->app_controller()->ShouldShowToolbar()); + + // Even though the url is secure it is not being served over chrome:// so a + // toolbar should be shown. + GURL off_scheme_page("https://example.com"); + content::NavigateToURLBlockUntilNavigationsComplete( + app_browser->tab_strip_model()->GetActiveWebContents(), off_scheme_page, + 1); + EXPECT_TRUE(app_browser->app_controller()->ShouldShowToolbar()); +} + } // namespace web_app
diff --git a/chrome/browser/web_applications/components/web_app_icon_generator.cc b/chrome/browser/web_applications/components/web_app_icon_generator.cc index 891010232..b365af0 100644 --- a/chrome/browser/web_applications/components/web_app_icon_generator.cc +++ b/chrome/browser/web_applications/components/web_app_icon_generator.cc
@@ -8,9 +8,11 @@ #include <string> #include <utility> +#include "base/i18n/case_conversion.h" #include "base/macros.h" #include "build/build_config.h" #include "chrome/grit/platform_locale_settings.h" +#include "components/url_formatter/url_formatter.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" #include "skia/ext/image_operations.h" #include "ui/base/l10n/l10n_util.h" @@ -31,7 +33,9 @@ // |letter| into a rounded background of |color|. class GeneratedIconImageSource : public gfx::CanvasImageSource { public: - explicit GeneratedIconImageSource(char letter, SkColor color, int output_size) + explicit GeneratedIconImageSource(base::char16 letter, + SkColor color, + int output_size) : gfx::CanvasImageSource(gfx::Size(output_size, output_size), false), letter_(letter), color_(color), @@ -64,13 +68,13 @@ // The text rect's size needs to be odd to center the text correctly. gfx::Rect text_rect(icon_inset, icon_inset, icon_size + 1, icon_size + 1); canvas->DrawStringRectWithFlags( - base::string16(1, std::toupper(letter_)), + base::string16(1, letter_), gfx::FontList(gfx::Font(font_name, font_size)), color_utils::GetColorWithMaxContrast(color_), text_rect, gfx::Canvas::TEXT_ALIGN_CENTER); } - char letter_; + base::char16 letter_; SkColor color_; @@ -86,7 +90,7 @@ void GenerateIcon(std::map<int, BitmapAndSource>* bitmaps, int output_size, SkColor color, - char letter) { + base::char16 letter) { // Do nothing if there is already an icon of |output_size|. if (bitmaps->count(output_size)) return; @@ -98,30 +102,15 @@ const GURL& app_url, SkColor generated_icon_color, std::map<int, BitmapAndSource>* bitmap_map) { - // The letter that will be painted on the generated icon. - char icon_letter = ' '; - std::string domain_and_registry( - net::registry_controlled_domains::GetDomainAndRegistry( - app_url, - net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES)); - - // TODO(crbug.com/867311): Decode the app URL or the domain before retrieving - // the first character, otherwise we generate an icon with "x" if the domain - // or app URL starts with a UTF-8 character. - if (!domain_and_registry.empty()) { - icon_letter = domain_and_registry[0]; - } else if (app_url.has_host()) { - icon_letter = app_url.host_piece()[0]; - } - // If no color has been specified, use a dark gray so it will stand out on the // black shelf. if (generated_icon_color == SK_ColorTRANSPARENT) generated_icon_color = SK_ColorDKGRAY; - for (int size : generate_sizes) { + const base::char16 icon_letter = GenerateIconLetterFromUrl(app_url); + + for (int size : generate_sizes) GenerateIcon(bitmap_map, size, generated_icon_color, icon_letter); - } } } // namespace @@ -167,7 +156,7 @@ return output_bitmaps; } -SkBitmap GenerateBitmap(int output_size, SkColor color, char letter) { +SkBitmap GenerateBitmap(int output_size, SkColor color, base::char16 letter) { gfx::ImageSkia icon_image( std::make_unique<GeneratedIconImageSource>(letter, color, output_size), gfx::Size(output_size, output_size)); @@ -179,6 +168,28 @@ return dst; } +// Returns the letter that will be painted on the generated icon. +base::char16 GenerateIconLetterFromUrl(const GURL& app_url) { + std::string app_url_part = " "; + const std::string domain_and_registry = + net::registry_controlled_domains::GetDomainAndRegistry( + app_url, + net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); + + if (!domain_and_registry.empty()) { + app_url_part = domain_and_registry; + } else if (app_url.has_host()) { + app_url_part = app_url.host(); + } + + // Translate punycode into unicode before retrieving the first letter. + const base::string16 string_for_display = + url_formatter::IDNToUnicode(app_url_part); + + base::char16 icon_letter = base::i18n::ToUpper(string_for_display)[0]; + return icon_letter; +} + std::map<int, BitmapAndSource> ResizeIconsAndGenerateMissing( const std::vector<BitmapAndSource>& icons, const std::set<int>& sizes_to_generate,
diff --git a/chrome/browser/web_applications/components/web_app_icon_generator.h b/chrome/browser/web_applications/components/web_app_icon_generator.h index 0308e447..2348438 100644 --- a/chrome/browser/web_applications/components/web_app_icon_generator.h +++ b/chrome/browser/web_applications/components/web_app_icon_generator.h
@@ -9,6 +9,7 @@ #include <set> #include <vector> +#include "base/strings/string16.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkColor.h" #include "url/gurl.h" @@ -53,7 +54,10 @@ // Generates a square container icon of |output_size| by drawing the given // |letter| into a rounded background of |color|. -SkBitmap GenerateBitmap(int output_size, SkColor color, char letter); +SkBitmap GenerateBitmap(int output_size, SkColor color, base::char16 letter); + +// Returns the letter that will be painted on the generated icon. +base::char16 GenerateIconLetterFromUrl(const GURL& app_url); // Resize icons to the accepted sizes, and generate any that are missing. // Note that |app_url| is the launch URL for the app.
diff --git a/chrome/browser/web_applications/components/web_app_icon_generator_unittest.cc b/chrome/browser/web_applications/components/web_app_icon_generator_unittest.cc index 265905a0..5b33ef64 100644 --- a/chrome/browser/web_applications/components/web_app_icon_generator_unittest.cc +++ b/chrome/browser/web_applications/components/web_app_icon_generator_unittest.cc
@@ -7,6 +7,7 @@ #include <vector> #include "base/stl_util.h" +#include "base/strings/string16.h" #include "testing/gtest/include/gtest/gtest.h" namespace web_app { @@ -337,4 +338,15 @@ TestIconGeneration(icon_size::k512, 0, 3); } +TEST(WebAppIconGeneratorTest, GenerateIconLetterFromUrl) { + // ASCII: + EXPECT_EQ('E', GenerateIconLetterFromUrl(GURL("http://example.com"))); + // Cyrillic capital letter ZHE for something like https://zhuk.rf: + EXPECT_EQ(0x0416, + GenerateIconLetterFromUrl(GURL("https://xn--f1ai0a.xn--p1ai/"))); + // Arabic: + EXPECT_EQ(0x0645, + GenerateIconLetterFromUrl(GURL("http://xn--mgbh0fb.example/"))); +} + } // namespace web_app
diff --git a/chrome/test/data/chromeos/file_manager/exif.jpg b/chrome/test/data/chromeos/file_manager/exif.jpg new file mode 100644 index 0000000..1a6cd31 --- /dev/null +++ b/chrome/test/data/chromeos/file_manager/exif.jpg Binary files differ
diff --git a/chrome/test/data/webui/BUILD.gn b/chrome/test/data/webui/BUILD.gn index 829b8be6..f8b0448 100644 --- a/chrome/test/data/webui/BUILD.gn +++ b/chrome/test/data/webui/BUILD.gn
@@ -87,7 +87,7 @@ "test_browser_proxy.js", "settings/test_password_manager_proxy.js", "settings/passwords_and_autofill_fake_data.js", - "//chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_browser_proxy.js", + "//chrome/browser/resources/signin/sync_confirmation/sync_confirmation_browser_proxy.js", "//chrome/browser/ui/webui/chromeos/account_migration_proxy_test.js", ]
diff --git a/chrome/test/data/webui/signin/signin_browsertest.js b/chrome/test/data/webui/signin/signin_browsertest.js index 6a6c899..2502d413 100644 --- a/chrome/test/data/webui/signin/signin_browsertest.js +++ b/chrome/test/data/webui/signin/signin_browsertest.js
@@ -11,7 +11,7 @@ /** * Test fixture for - * chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation.html. + * chrome/browser/resources/signin/sync_confirmation/sync_confirmation.html. * This has to be declared as a variable for TEST_F to find it correctly. */ // eslint-disable-next-line no-var @@ -36,7 +36,7 @@ return [ ...super.extraLibraries, '//chrome/test/data/webui/test_browser_proxy.js', - '//chrome/browser/resources/signin/dice_sync_confirmation/' + + '//chrome/browser/resources/signin/sync_confirmation/' + 'sync_confirmation_browser_proxy.js', 'test_sync_confirmation_browser_proxy.js', 'sync_confirmation_test.js',
diff --git a/chrome/test/media_router/telemetry/README.md b/chrome/test/media_router/telemetry/README.md index 15b9cc2..24c39eed 100644 --- a/chrome/test/media_router/telemetry/README.md +++ b/chrome/test/media_router/telemetry/README.md
@@ -16,12 +16,8 @@ ```shell ./chrome/test/media_router/telemetry/run_benchmark --browser=<browser> \ - media_router.dialog.latency.tracing --reset-results - -./chrome/test/media_router/telemetry/run_benchmark --browser=<browser> \ media_router.dialog.latency.histogram ``` The results will be in `<chromium src folder>/chrome/test/media_router/telemetry/results.html` -
diff --git a/chrome/test/media_router/telemetry/benchmarks/media_router_benchmark.py b/chrome/test/media_router/telemetry/benchmarks/media_router_benchmark.py index bf2d1f17..f2e3d85 100644 --- a/chrome/test/media_router/telemetry/benchmarks/media_router_benchmark.py +++ b/chrome/test/media_router/telemetry/benchmarks/media_router_benchmark.py
@@ -39,29 +39,6 @@ ]) -class TraceEventCastBenckmark(_BaseCastBenchmark): - """Benchmark for dialog latency from trace event.""" - - def CreateCoreTimelineBasedMeasurementOptions(self): - media_router_category = 'media_router' - category_filter = chrome_trace_category_filter.ChromeTraceCategoryFilter( - media_router_category) - category_filter.AddIncludedCategory('blink.console') - options = timeline_based_measurement.Options(category_filter) - options.SetLegacyTimelineBasedMetrics([ - media_router_timeline_metric.MediaRouterMetric()]) - return options - - @classmethod - def Name(cls): - return 'media_router.dialog.latency.tracing' - - @classmethod - def ShouldAddValue(cls, _, from_first_story_run): - """Only drops the first result.""" - return not from_first_story_run - - class HistogramCastBenckmark(_BaseCastBenchmark): """Benchmark for dialog latency from histograms."""
diff --git a/chrome/test/media_router/telemetry/benchmarks/media_router_timeline_metric.py b/chrome/test/media_router/telemetry/benchmarks/media_router_timeline_metric.py deleted file mode 100644 index 93d9c30..0000000 --- a/chrome/test/media_router/telemetry/benchmarks/media_router_timeline_metric.py +++ /dev/null
@@ -1,27 +0,0 @@ -# Copyright 2016 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -from telemetry import value -from telemetry.web_perf.metrics import timeline_based_metric - - -class MediaRouterMetric(timeline_based_metric.TimelineBasedMetric): - """Reports latency of media router dialog from trace event.""" - - def AddResults(self, model, renderer_thread, interactions, results): - browser = model.browser_process - if not browser: - return - - events = [e for e in browser.parent.IterAllEvents( - event_predicate=lambda event: event.name == 'UI')] - if len(events) > 0: - results.AddValue(value.scalar.ScalarValue( - page=results.current_page, - name='media_router_ui', - units='ms', - description=('Latency between Media Router dialog ' - 'creation call and initialization'), - value=events[0].duration, - improvement_direction=value.improvement_direction.DOWN))
diff --git a/chromeos/constants/chromeos_features.cc b/chromeos/constants/chromeos_features.cc index fec3415d..016432ca 100644 --- a/chromeos/constants/chromeos_features.cc +++ b/chromeos/constants/chromeos_features.cc
@@ -51,6 +51,11 @@ const base::Feature kEnableFileManagerFeedbackPanel{ "EnableFeedbackPanel", base::FEATURE_DISABLED_BY_DEFAULT}; +// Enables the enhanced external media formatting dialog in the file manager, +// with support for labelling and also NTFS/exFAT filesystems. +const base::Feature kEnableFileManagerFormatDialog{ + "EnableFileManagerFormatDialog", base::FEATURE_DISABLED_BY_DEFAULT}; + // Enable the piex-wasm module for raw image preview image extraction. const base::Feature kEnableFileManagerPiexWasm{ "PiexWasm", base::FEATURE_ENABLED_BY_DEFAULT};
diff --git a/chromeos/constants/chromeos_features.h b/chromeos/constants/chromeos_features.h index ab4cbb7c..138a9cd78 100644 --- a/chromeos/constants/chromeos_features.h +++ b/chromeos/constants/chromeos_features.h
@@ -35,6 +35,8 @@ COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kEnableFileManagerFeedbackPanel; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) +extern const base::Feature kEnableFileManagerFormatDialog; +COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kEnableFileManagerPiexWasm; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kEnableMessagesWebPush;
diff --git a/chromeos/network/fast_transition_observer_unittest.cc b/chromeos/network/fast_transition_observer_unittest.cc index dea7de6..ce5bd27d 100644 --- a/chromeos/network/fast_transition_observer_unittest.cc +++ b/chromeos/network/fast_transition_observer_unittest.cc
@@ -4,7 +4,7 @@ #include <memory> -#include "base/message_loop/message_loop.h" +#include "base/test/scoped_task_environment.h" #include "chromeos/constants/chromeos_pref_names.h" #include "chromeos/dbus/shill/shill_clients.h" #include "chromeos/dbus/shill/shill_manager_client.h" @@ -48,7 +48,7 @@ } private: - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; std::unique_ptr<NetworkStateHandler> network_state_handler_; std::unique_ptr<TestingPrefServiceSimple> local_state_; std::unique_ptr<FastTransitionObserver> observer_;
diff --git a/chromeos/network/managed_network_configuration_handler_unittest.cc b/chromeos/network/managed_network_configuration_handler_unittest.cc index bd31f29f..bcc71a6 100644 --- a/chromeos/network/managed_network_configuration_handler_unittest.cc +++ b/chromeos/network/managed_network_configuration_handler_unittest.cc
@@ -10,8 +10,8 @@ #include "base/bind_helpers.h" #include "base/json/json_writer.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/test/scoped_task_environment.h" #include "base/test/values_test_util.h" #include "base/values.h" #include "chromeos/dbus/shill/shill_clients.h" @@ -220,7 +220,7 @@ } protected: - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; TestNetworkPolicyObserver policy_observer_; std::unique_ptr<MockNetworkStateHandler> network_state_handler_;
diff --git a/components/BUILD.gn b/components/BUILD.gn index 72308cc..db0f8f1 100644 --- a/components/BUILD.gn +++ b/components/BUILD.gn
@@ -83,6 +83,7 @@ "//components/content_capture/common:unit_tests", "//components/content_settings/core/browser:unit_tests", "//components/content_settings/core/common:unit_tests", + "//components/crash/core/common:unit_tests", "//components/crx_file:unit_tests", "//components/device_event_log:unit_tests", "//components/dom_distiller/core:unit_tests", @@ -191,7 +192,6 @@ deps += [ "//components/autofill/ios/browser:unit_tests", "//components/autofill/ios/form_util:unit_tests", - "//components/crash/core/common:unit_tests", "//components/image_fetcher/ios:unit_tests", "//components/language/ios/browser:unit_tests", "//components/password_manager/ios:unit_tests", @@ -211,7 +211,6 @@ "//components/contextual_search/core:unit_tests", "//components/crash/content/app:unit_tests", "//components/crash/content/browser:unit_tests", - "//components/crash/core/common:unit_tests", "//components/data_reduction_proxy/content/browser:unit_tests", "//components/data_reduction_proxy/content/common:unit_tests", "//components/data_reduction_proxy/content/renderer:unit_tests",
diff --git a/components/OWNERS b/components/OWNERS index 51fa197a..c4c3e8d 100644 --- a/components/OWNERS +++ b/components/OWNERS
@@ -2,6 +2,9 @@ caitkp@chromium.org jochen@chromium.org +# For build configuration things and simple changes. +thakis@chromium.org + per-file app_modal_strings.grdp=file://components/app_modal/OWNERS per-file autofill_assistant_strings.grdp=file://components/autofill_assistant/OWNERS per-file autofill_payments_strings.grdp=file://components/autofill/core/browser/payments/OWNERS
diff --git a/components/autofill/content/renderer/autofill_agent.cc b/components/autofill/content/renderer/autofill_agent.cc index 3e8a3349..83e9a6d5 100644 --- a/components/autofill/content/renderer/autofill_agent.cc +++ b/components/autofill/content/renderer/autofill_agent.cc
@@ -844,6 +844,10 @@ WebElement focused_element; if (!doc.IsNull()) focused_element = doc.FocusedElement(); + + if (!focused_element.IsNull() && password_autofill_agent_) + password_autofill_agent_->FocusedNodeHasChanged(focused_element); + // PasswordGenerationAgent needs to know about focus changes, even if there is // no focused element. if (password_generation_agent_ && @@ -851,8 +855,6 @@ is_generation_popup_possibly_visible_ = true; is_popup_possibly_visible_ = true; } - if (!focused_element.IsNull() && password_autofill_agent_) - password_autofill_agent_->FocusedNodeHasChanged(focused_element); if (!IsKeyboardAccessoryEnabled() && focus_requires_scroll_) HandleFocusChangeComplete();
diff --git a/components/autofill/core/browser/webdata/autofill_profile_sync_bridge.cc b/components/autofill/core/browser/webdata/autofill_profile_sync_bridge.cc index 2e92677f..e1b0561f4 100644 --- a/components/autofill/core/browser/webdata/autofill_profile_sync_bridge.cc +++ b/components/autofill/core/browser/webdata/autofill_profile_sync_bridge.cc
@@ -275,9 +275,7 @@ base::Unretained(web_data_backend_)))); std::vector<std::unique_ptr<AutofillProfile>> profiles_to_upload_to_sync; - std::vector<std::string> profiles_to_delete_from_sync; - RETURN_IF_ERROR(tracker->FlushToSync(&profiles_to_upload_to_sync, - &profiles_to_delete_from_sync)); + RETURN_IF_ERROR(tracker->FlushToSync(&profiles_to_upload_to_sync)); for (const std::unique_ptr<AutofillProfile>& entry : profiles_to_upload_to_sync) { change_processor()->Put(GetStorageKeyFromAutofillProfile(*entry), @@ -287,9 +285,6 @@ // TODO(crbug.com/904390): Remove when the investigation is over. ReportAutofillProfileAddOrUpdateOrigin(origin); } - for (const std::string& storage_key : profiles_to_delete_from_sync) { - change_processor()->Delete(storage_key, metadata_change_list.get()); - } return static_cast<syncer::SyncMetadataStoreChangeList*>( metadata_change_list.get())
diff --git a/components/autofill/core/browser/webdata/autofill_profile_sync_difference_tracker.cc b/components/autofill/core/browser/webdata/autofill_profile_sync_difference_tracker.cc index 44af5e0..8f96bb8 100644 --- a/components/autofill/core/browser/webdata/autofill_profile_sync_difference_tracker.cc +++ b/components/autofill/core/browser/webdata/autofill_profile_sync_difference_tracker.cc
@@ -71,51 +71,30 @@ // Look for exact duplicates, compare only profile contents (and // ignore origin and language code in comparison). if (local.Compare(*remote) == 0) { - // We found a duplicate. We keep the version with the bigger storage key. + // We found a duplicate, we keep the new (remote) one and delete the + // local one. DVLOG(2) << "[AUTOFILL SYNC] The profile " << base::UTF16ToUTF8(local.GetRawInfo(NAME_FIRST)) << base::UTF16ToUTF8(local.GetRawInfo(NAME_LAST)) - << " already exists with a different storage key; keep the bigger key" - << std::max(remote_storage_key, local_storage_key) - << " and delete the smaller key " - << std::min(remote_storage_key, local_storage_key); - if (remote_storage_key > local_storage_key) { - // We keep the remote entity and delete the local one. - // Ensure that a verified profile can never revert back to an unverified - // one. In such a case, take over the old origin for the new entry. - if (local.IsVerified() && !remote->IsVerified()) { - remote->set_origin(local.origin()); - // Save a copy of the remote profile also to sync. - save_to_sync_.push_back(std::make_unique<AutofillProfile>(*remote)); - } - add_to_local_.push_back(std::move(remote)); - DeleteFromLocal(local_storage_key); - } else { - // We keep the local entity and delete the remote one. - // Ensure that a verified profile can never revert back to an unverified - // one. In such a case, modify the origin and re-upload. Otherwise, - // there's no need to upload it: either is was already uploaded before - // (if this is incremental sync) or we'll upload it with all the - // remaining data in GetLocalOnlyEntries (if this is an initial sync). - if (remote->IsVerified() && !local.IsVerified()) { - auto modified_local = std::make_unique<AutofillProfile>(local); - modified_local->set_origin(remote->origin()); - update_to_local_.push_back( - std::make_unique<AutofillProfile>(*modified_local)); - save_to_sync_.push_back(std::move(modified_local)); - // The local entity is already marked for upload so it is not local - // only anymore (we do not want to upload it once again while flushing - // if this is initial sync). - GetLocalOnlyEntries()->erase(local_storage_key); - } - delete_from_sync_.insert(remote_storage_key); + << " already exists with a different storage key; keep the remote key" + << remote_storage_key << " and delete the local key " + << local_storage_key; + + // Ensure that a verified profile can never revert back to an unverified + // one. In such a case, take over the local origin for the new (remote) + // entry. + if (local.IsVerified() && !remote->IsVerified()) { + remote->set_origin(local.origin()); + // Save a copy of the remote profile also to sync. + save_to_sync_.push_back(std::make_unique<AutofillProfile>(*remote)); } - return base::nullopt; + // Delete the local profile that gets replaced by |remote|. + DeleteFromLocal(local_storage_key); + break; } } - // If no duplicate was found, just add the remote profile. add_to_local_.push_back(std::move(remote)); return base::nullopt; } @@ -153,14 +132,10 @@ } Optional<ModelError> AutofillProfileSyncDifferenceTracker::FlushToSync( - std::vector<std::unique_ptr<AutofillProfile>>* profiles_to_upload_to_sync, - std::vector<std::string>* profiles_to_delete_from_sync) { + std::vector<std::unique_ptr<AutofillProfile>>* profiles_to_upload_to_sync) { for (std::unique_ptr<AutofillProfile>& entry : save_to_sync_) { profiles_to_upload_to_sync->push_back(std::move(entry)); } - for (const std::string& entry : delete_from_sync_) { - profiles_to_delete_from_sync->push_back(std::move(entry)); - } return base::nullopt; } @@ -225,11 +200,9 @@ } Optional<ModelError> AutofillProfileInitialSyncDifferenceTracker::FlushToSync( - std::vector<std::unique_ptr<AutofillProfile>>* profiles_to_upload_to_sync, - std::vector<std::string>* profiles_to_delete_from_sync) { + std::vector<std::unique_ptr<AutofillProfile>>* profiles_to_upload_to_sync) { // First, flush standard updates to sync. - AutofillProfileSyncDifferenceTracker::FlushToSync( - profiles_to_upload_to_sync, profiles_to_delete_from_sync); + AutofillProfileSyncDifferenceTracker::FlushToSync(profiles_to_upload_to_sync); // For initial sync, we additionally need to upload all local only entries. if (!GetLocalOnlyEntries()) {
diff --git a/components/autofill/core/browser/webdata/autofill_profile_sync_difference_tracker.h b/components/autofill/core/browser/webdata/autofill_profile_sync_difference_tracker.h index 437d0d37..055de2e 100644 --- a/components/autofill/core/browser/webdata/autofill_profile_sync_difference_tracker.h +++ b/components/autofill/core/browser/webdata/autofill_profile_sync_difference_tracker.h
@@ -50,12 +50,11 @@ base::OnceClosure autofill_changes_callback); // Writes into |profiles_to_upload_to_sync| all autofill profiles to be sent - // to the sync server, and into |profiles_to_delete_from_sync| the storage - // keys of all profiles to be deleted from the server. After flushing, no - // further remote changes should get incorporated. + // to the sync server. After flushing, not further remote changes should get + // incorporated. virtual base::Optional<syncer::ModelError> FlushToSync( - std::vector<std::unique_ptr<AutofillProfile>>* profiles_to_upload_to_sync, - std::vector<std::string>* profiles_to_delete_from_sync); + std::vector<std::unique_ptr<AutofillProfile>>* + profiles_to_upload_to_sync); protected: // If the entry is found, |entry| will be return, otherwise base::nullopt is @@ -99,13 +98,9 @@ std::vector<std::unique_ptr<AutofillProfile>> add_to_local_; std::vector<std::unique_ptr<AutofillProfile>> update_to_local_; - // Contains data for entries that existed on both sync and local sides + // Contains merged data for entries that existed on both sync and local sides // and need to be saved back to sync. std::vector<std::unique_ptr<AutofillProfile>> save_to_sync_; - // Contains data for entries that existed on both sync and local - // sides and need to be deleted from sync (because the conflict resolution - // preferred the local copies). - std::set<std::string> delete_from_sync_; private: DISALLOW_COPY_AND_ASSIGN(AutofillProfileSyncDifferenceTracker); @@ -121,8 +116,8 @@ const std::string& storage_key) override; base::Optional<syncer::ModelError> FlushToSync( - std::vector<std::unique_ptr<AutofillProfile>>* profiles_to_upload_to_sync, - std::vector<std::string>* profiles_to_delete_from_sync) override; + std::vector<std::unique_ptr<AutofillProfile>>* profiles_to_upload_to_sync) + override; // Performs an additional pass through remote entries incorporated from sync // to find any similarities with local entries. Should be run after all
diff --git a/components/autofill/core/browser/webdata/autofill_profile_sync_difference_tracker_unittest.cc b/components/autofill/core/browser/webdata/autofill_profile_sync_difference_tracker_unittest.cc index f4a1100..799ff003 100644 --- a/components/autofill/core/browser/webdata/autofill_profile_sync_difference_tracker_unittest.cc +++ b/components/autofill/core/browser/webdata/autofill_profile_sync_difference_tracker_unittest.cc
@@ -30,18 +30,13 @@ using testing::IsEmpty; // Some guids for testing. -const char kSmallerGuid[] = "EDC609ED-7EEE-4F27-B00C-423242A9C44A"; -const char kBiggerGuid[] = "EDC609ED-7EEE-4F27-B00C-423242A9C44B"; +const char kGuidA[] = "EDC609ED-7EEE-4F27-B00C-423242A9C44A"; +const char kGuidB[] = "EDC609ED-7EEE-4F27-B00C-423242A9C44B"; const char kHttpOrigin[] = "http://www.example.com/"; const char kHttpsOrigin[] = "https://www.example.com/"; const char kLocaleString[] = "en-US"; const base::Time kJune2017 = base::Time::FromDoubleT(1497552271); -struct UpdatesToSync { - std::vector<AutofillProfile> profiles_to_upload_to_sync; - std::vector<std::string> profiles_to_delete_from_sync; -}; - } // namespace class AutofillProfileSyncDifferenceTrackerTestBase : public testing::Test { @@ -70,26 +65,24 @@ std::make_unique<AutofillProfile>(profile))); } - UpdatesToSync FlushToSync() { + std::vector<AutofillProfile> FlushAndReturnProfilesToUploadToSync() { EXPECT_EQ(base::nullopt, tracker()->FlushToLocal( /*autofill_changes_callback=*/base::DoNothing())); - UpdatesToSync updates; std::vector<std::unique_ptr<AutofillProfile>> vector_of_unique_ptrs; EXPECT_EQ(base::nullopt, tracker()->FlushToSync( - /*profiles_to_upload_to_sync=*/&vector_of_unique_ptrs, - /*profiles_to_delete_from_sync=*/&updates - .profiles_to_delete_from_sync)); + /*profiles_to_upload_to_sync=*/&vector_of_unique_ptrs)); // Copy all the elements by value so that we have a vector that is easier to // work with in the test. + std::vector<AutofillProfile> vector_of_values; for (const std::unique_ptr<AutofillProfile>& entry : vector_of_unique_ptrs) { - updates.profiles_to_upload_to_sync.push_back(*entry); + vector_of_values.push_back(*entry); } - return updates; + return vector_of_values; } std::vector<AutofillProfile> GetAllLocalData() { @@ -137,69 +130,63 @@ TEST_F(AutofillProfileSyncDifferenceTrackerTest, IncorporateRemoteProfileShouldOverwriteProfileWithSameKey) { - AutofillProfile local = AutofillProfile(kSmallerGuid, kHttpOrigin); + AutofillProfile local = AutofillProfile(kGuidA, kHttpOrigin); local.SetRawInfo(NAME_FIRST, ASCIIToUTF16("John")); AddAutofillProfilesToTable({local}); // The remote profile is completely different but it has the same key. - AutofillProfile remote = AutofillProfile(kSmallerGuid, kHttpsOrigin); + AutofillProfile remote = AutofillProfile(kGuidA, kHttpsOrigin); remote.SetRawInfo(NAME_FIRST, ASCIIToUTF16("Tom")); IncorporateRemoteProfile(remote); // Nothing gets uploaded to sync and the remote profile wins. - UpdatesToSync updates = FlushToSync(); - EXPECT_THAT(updates.profiles_to_upload_to_sync, IsEmpty()); - EXPECT_THAT(updates.profiles_to_delete_from_sync, IsEmpty()); + EXPECT_THAT(FlushAndReturnProfilesToUploadToSync(), IsEmpty()); EXPECT_THAT(GetAllLocalData(), ElementsAre(remote)); } TEST_F(AutofillProfileSyncDifferenceTrackerTest, IncorporateRemoteProfileShouldOverwriteUnverifiedProfileByVerified) { - AutofillProfile local = AutofillProfile(kSmallerGuid, kHttpsOrigin); + AutofillProfile local = AutofillProfile(kGuidA, kHttpsOrigin); local.SetRawInfo(NAME_FIRST, ASCIIToUTF16("John")); AddAutofillProfilesToTable({local}); // The remote profile has the same key but it is not verified. - AutofillProfile remote = AutofillProfile(kSmallerGuid, kSettingsOrigin); + AutofillProfile remote = AutofillProfile(kGuidA, kSettingsOrigin); remote.SetRawInfo(NAME_FIRST, ASCIIToUTF16("Tom")); IncorporateRemoteProfile(remote); // Nothing gets uploaded to sync and the local profile wins. - UpdatesToSync updates = FlushToSync(); - EXPECT_THAT(updates.profiles_to_upload_to_sync, IsEmpty()); - EXPECT_THAT(updates.profiles_to_delete_from_sync, IsEmpty()); + EXPECT_THAT(FlushAndReturnProfilesToUploadToSync(), IsEmpty()); EXPECT_THAT(GetAllLocalData(), ElementsAre(remote)); } TEST_F(AutofillProfileSyncDifferenceTrackerTest, IncorporateRemoteProfileShouldNotOverwriteVerifiedProfileByUnverified) { - AutofillProfile local = AutofillProfile(kSmallerGuid, kSettingsOrigin); + AutofillProfile local = AutofillProfile(kGuidA, kSettingsOrigin); local.SetRawInfo(NAME_FIRST, ASCIIToUTF16("John")); AddAutofillProfilesToTable({local}); // The remote profile has the same key but it is not verified. - AutofillProfile remote = AutofillProfile(kSmallerGuid, kHttpsOrigin); + AutofillProfile remote = AutofillProfile(kGuidA, kHttpsOrigin); remote.SetRawInfo(NAME_FIRST, ASCIIToUTF16("Tom")); IncorporateRemoteProfile(remote); // Nothing gets uploaded to sync and the local profile wins. - UpdatesToSync updates = FlushToSync(); - EXPECT_THAT(updates.profiles_to_upload_to_sync, IsEmpty()); - EXPECT_THAT(updates.profiles_to_delete_from_sync, IsEmpty()); + EXPECT_THAT(FlushAndReturnProfilesToUploadToSync(), IsEmpty()); EXPECT_THAT(GetAllLocalData(), ElementsAre(local)); } TEST_F(AutofillProfileSyncDifferenceTrackerTest, IncorporateRemoteProfileShouldNotOverwriteFullNameByEmptyString) { - AutofillProfile local = AutofillProfile(kSmallerGuid, kHttpOrigin); + AutofillProfile local = AutofillProfile(kGuidA, kHttpOrigin); local.SetRawInfo(NAME_FULL, ASCIIToUTF16("John")); AddAutofillProfilesToTable({local}); // The remote profile has the same key. - AutofillProfile remote = AutofillProfile(kSmallerGuid, kHttpsOrigin); + AutofillProfile remote = AutofillProfile(kGuidA, kHttpsOrigin); remote.SetRawInfo(ADDRESS_HOME_STREET_ADDRESS, ASCIIToUTF16("2 2st st")); AutofillProfile merged(remote); @@ -209,45 +196,40 @@ // Nothing gets uploaded to sync and the remote profile wins except for the // full name. - UpdatesToSync updates = FlushToSync(); - EXPECT_THAT(updates.profiles_to_upload_to_sync, IsEmpty()); - EXPECT_THAT(updates.profiles_to_delete_from_sync, IsEmpty()); + EXPECT_THAT(FlushAndReturnProfilesToUploadToSync(), IsEmpty()); EXPECT_THAT(GetAllLocalData(), ElementsAre(merged)); } -TEST_F( - AutofillProfileSyncDifferenceTrackerTest, - IncorporateRemoteProfileShouldKeepRemoteKeyWhenMergingDuplicateProfileWithBiggerKey) { - AutofillProfile local = AutofillProfile(kSmallerGuid, kHttpOrigin); +TEST_F(AutofillProfileSyncDifferenceTrackerTest, + IncorporateRemoteProfileShouldMergeIdenticalProfilesWithDifferentKeys) { + AutofillProfile local = AutofillProfile(kGuidA, kHttpOrigin); local.SetRawInfo(NAME_FIRST, ASCIIToUTF16("John")); local.SetRawInfo(ADDRESS_HOME_STREET_ADDRESS, ASCIIToUTF16("1 1st st")); AddAutofillProfilesToTable({local}); // The remote profile is identical to the local one, except that the guids and // origins are different. - AutofillProfile remote = AutofillProfile(kBiggerGuid, kHttpsOrigin); + AutofillProfile remote = AutofillProfile(kGuidB, kHttpsOrigin); remote.SetRawInfo(NAME_FIRST, ASCIIToUTF16("John")); remote.SetRawInfo(ADDRESS_HOME_STREET_ADDRESS, ASCIIToUTF16("1 1st st")); IncorporateRemoteProfile(remote); // Nothing gets uploaded to sync and the remote profile wins. - UpdatesToSync updates = FlushToSync(); - EXPECT_THAT(updates.profiles_to_upload_to_sync, IsEmpty()); - EXPECT_THAT(updates.profiles_to_delete_from_sync, IsEmpty()); + EXPECT_THAT(FlushAndReturnProfilesToUploadToSync(), IsEmpty()); EXPECT_THAT(GetAllLocalData(), ElementsAre(remote)); } TEST_F( AutofillProfileSyncDifferenceTrackerTest, - IncorporateRemoteProfileShouldKeepRemoteKeyAndLocalOriginWhenMergingDuplicateProfileWithBiggerKey) { - AutofillProfile local = AutofillProfile(kSmallerGuid, kSettingsOrigin); + IncorporateRemoteProfileShouldMergeIdenticalProfilesWithDifferentKeysButKeepVerifiedOrigin) { + AutofillProfile local = AutofillProfile(kGuidA, kSettingsOrigin); local.SetRawInfo(NAME_FIRST, ASCIIToUTF16("John")); local.SetRawInfo(ADDRESS_HOME_STREET_ADDRESS, ASCIIToUTF16("1 1st st")); AddAutofillProfilesToTable({local}); // The remote profile has the same key. - AutofillProfile remote = AutofillProfile(kBiggerGuid, kHttpsOrigin); + AutofillProfile remote = AutofillProfile(kGuidB, kHttpsOrigin); remote.SetRawInfo(NAME_FIRST, ASCIIToUTF16("John")); remote.SetRawInfo(ADDRESS_HOME_STREET_ADDRESS, ASCIIToUTF16("1 1st st")); @@ -258,60 +240,7 @@ // Nothing gets uploaded to sync and the remote profile wins except for the // full name. - UpdatesToSync updates = FlushToSync(); - EXPECT_THAT(updates.profiles_to_upload_to_sync, ElementsAre(merged)); - EXPECT_THAT(updates.profiles_to_delete_from_sync, IsEmpty()); - EXPECT_THAT(GetAllLocalData(), ElementsAre(merged)); -} - -TEST_F( - AutofillProfileSyncDifferenceTrackerTest, - IncorporateRemoteProfileShouldKeepLocalKeyWhenMergingDuplicateProfileWithSmallerKey) { - AutofillProfile local = AutofillProfile(kBiggerGuid, kHttpOrigin); - local.SetRawInfo(NAME_FIRST, ASCIIToUTF16("John")); - local.SetRawInfo(ADDRESS_HOME_STREET_ADDRESS, ASCIIToUTF16("1 1st st")); - AddAutofillProfilesToTable({local}); - - // The remote profile is identical to the local one, except that the guids and - // origins are different. - AutofillProfile remote = AutofillProfile(kSmallerGuid, kHttpsOrigin); - remote.SetRawInfo(NAME_FIRST, ASCIIToUTF16("John")); - remote.SetRawInfo(ADDRESS_HOME_STREET_ADDRESS, ASCIIToUTF16("1 1st st")); - - IncorporateRemoteProfile(remote); - - // Nothing gets uploaded to sync and the remote profile wins. - UpdatesToSync updates = FlushToSync(); - EXPECT_THAT(updates.profiles_to_upload_to_sync, IsEmpty()); - EXPECT_THAT(updates.profiles_to_delete_from_sync, - ElementsAre(std::string(kSmallerGuid))); - EXPECT_THAT(GetAllLocalData(), ElementsAre(local)); -} - -TEST_F( - AutofillProfileSyncDifferenceTrackerTest, - IncorporateRemoteProfileShouldKeepLocalKeyAndRemoteOriginWhenMergingDuplicateProfileWithSmallerKey) { - AutofillProfile local = AutofillProfile(kBiggerGuid, kHttpsOrigin); - local.SetRawInfo(NAME_FIRST, ASCIIToUTF16("John")); - local.SetRawInfo(ADDRESS_HOME_STREET_ADDRESS, ASCIIToUTF16("1 1st st")); - AddAutofillProfilesToTable({local}); - - // The remote profile has the same key. - AutofillProfile remote = AutofillProfile(kSmallerGuid, kSettingsOrigin); - remote.SetRawInfo(NAME_FIRST, ASCIIToUTF16("John")); - remote.SetRawInfo(ADDRESS_HOME_STREET_ADDRESS, ASCIIToUTF16("1 1st st")); - - AutofillProfile merged(local); - merged.set_origin(kSettingsOrigin); - - IncorporateRemoteProfile(remote); - - // Nothing gets uploaded to sync and the remote profile wins except for the - // full name. - UpdatesToSync updates = FlushToSync(); - EXPECT_THAT(updates.profiles_to_upload_to_sync, ElementsAre(merged)); - EXPECT_THAT(updates.profiles_to_delete_from_sync, - ElementsAre(std::string(kSmallerGuid))); + EXPECT_THAT(FlushAndReturnProfilesToUploadToSync(), ElementsAre(merged)); EXPECT_THAT(GetAllLocalData(), ElementsAre(merged)); } @@ -326,10 +255,10 @@ TEST_F(AutofillProfileSyncDifferenceTrackerTest, FlushToLocalShouldCallbackWhenProfileDeleted) { - AutofillProfile local = AutofillProfile(kSmallerGuid, kSettingsOrigin); + AutofillProfile local = AutofillProfile(kGuidA, kSettingsOrigin); AddAutofillProfilesToTable({local}); - tracker()->IncorporateRemoteDelete(kSmallerGuid); + tracker()->IncorporateRemoteDelete(kGuidA); MockCallback<base::OnceClosure> autofill_changes_callback; EXPECT_CALL(autofill_changes_callback, Run()).Times(1); @@ -342,7 +271,7 @@ TEST_F(AutofillProfileSyncDifferenceTrackerTest, FlushToLocalShouldCallbackWhenProfileAdded) { - AutofillProfile remote = AutofillProfile(kSmallerGuid, kSettingsOrigin); + AutofillProfile remote = AutofillProfile(kGuidA, kSettingsOrigin); IncorporateRemoteProfile(remote); MockCallback<base::OnceClosure> autofill_changes_callback; @@ -356,10 +285,10 @@ TEST_F(AutofillProfileSyncDifferenceTrackerTest, FlushToLocalShouldCallbackWhenProfileUpdated) { - AutofillProfile local = AutofillProfile(kSmallerGuid, kHttpsOrigin); + AutofillProfile local = AutofillProfile(kGuidA, kHttpsOrigin); AddAutofillProfilesToTable({local}); - AutofillProfile remote = AutofillProfile(kSmallerGuid, kHttpsOrigin); + AutofillProfile remote = AutofillProfile(kGuidA, kHttpsOrigin); remote.SetRawInfo(ADDRESS_HOME_STREET_ADDRESS, ASCIIToUTF16("1 1st st")); IncorporateRemoteProfile(remote); @@ -368,7 +297,7 @@ EXPECT_EQ(base::nullopt, tracker()->FlushToLocal(autofill_changes_callback.Get())); - // On top of that, the profile with key kSmallerGuid should also get updated. + // On top of that, the profile with key kGuidA should also get updated. EXPECT_THAT(GetAllLocalData(), ElementsAre(remote)); } @@ -395,13 +324,13 @@ TEST_F(AutofillProfileInitialSyncDifferenceTrackerTest, MergeSimilarEntriesForInitialSyncShouldSyncUpChanges) { - AutofillProfile local = AutofillProfile(kSmallerGuid, kHttpOrigin); + AutofillProfile local = AutofillProfile(kGuidA, kHttpOrigin); local.SetRawInfo(ADDRESS_HOME_STREET_ADDRESS, ASCIIToUTF16("1 1st st")); local.set_use_count(27); AddAutofillProfilesToTable({local}); // The remote profile matches the local one (except for origin and use count). - AutofillProfile remote = AutofillProfile(kBiggerGuid, kHttpsOrigin); + AutofillProfile remote = AutofillProfile(kGuidB, kHttpsOrigin); remote.SetRawInfo(ADDRESS_HOME_STREET_ADDRESS, ASCIIToUTF16("1 1st st")); remote.SetRawInfo(COMPANY_NAME, ASCIIToUTF16("Frobbers, Inc.")); remote.set_use_count(13); @@ -417,21 +346,19 @@ MergeSimilarEntriesForInitialSync(); // The merged profile needs to get uploaded back to sync and stored locally. - UpdatesToSync updates = FlushToSync(); - EXPECT_THAT(updates.profiles_to_upload_to_sync, ElementsAre(merged)); - EXPECT_THAT(updates.profiles_to_delete_from_sync, IsEmpty()); + EXPECT_THAT(FlushAndReturnProfilesToUploadToSync(), ElementsAre(merged)); EXPECT_THAT(GetAllLocalData(), ElementsAre(merged)); } TEST_F(AutofillProfileInitialSyncDifferenceTrackerTest, MergeSimilarEntriesForInitialSyncShouldNotSyncUpWhenNotNeeded) { - AutofillProfile local = AutofillProfile(kSmallerGuid, kHttpOrigin); + AutofillProfile local = AutofillProfile(kGuidA, kHttpOrigin); local.SetRawInfo(ADDRESS_HOME_STREET_ADDRESS, ASCIIToUTF16("1 1st st")); local.set_use_count(13); AddAutofillProfilesToTable({local}); // The remote profile matches the local one and has some additional data. - AutofillProfile remote = AutofillProfile(kBiggerGuid, kHttpOrigin); + AutofillProfile remote = AutofillProfile(kGuidB, kHttpOrigin); remote.SetRawInfo(ADDRESS_HOME_STREET_ADDRESS, ASCIIToUTF16("1 1st st")); remote.SetRawInfo(COMPANY_NAME, ASCIIToUTF16("Frobbers, Inc.")); // Merging two profile takes their max use count, so use count of 27 is taken. @@ -441,21 +368,19 @@ MergeSimilarEntriesForInitialSync(); // Nothing gets uploaded to sync and the remote profile wins. - UpdatesToSync updates = FlushToSync(); - EXPECT_THAT(updates.profiles_to_upload_to_sync, IsEmpty()); - EXPECT_THAT(updates.profiles_to_delete_from_sync, IsEmpty()); + EXPECT_THAT(FlushAndReturnProfilesToUploadToSync(), IsEmpty()); EXPECT_THAT(GetAllLocalData(), ElementsAre(remote)); } TEST_F(AutofillProfileInitialSyncDifferenceTrackerTest, MergeSimilarEntriesForInitialSyncNotMatchNonsimilarEntries) { - AutofillProfile local = AutofillProfile(kSmallerGuid, kHttpOrigin); + AutofillProfile local = AutofillProfile(kGuidA, kHttpOrigin); local.SetRawInfo(ADDRESS_HOME_STREET_ADDRESS, ASCIIToUTF16("1 1st st")); local.SetRawInfo(COMPANY_NAME, ASCIIToUTF16("Frobbers, Inc.")); AddAutofillProfilesToTable({local}); // The remote profile has a different street address. - AutofillProfile remote = AutofillProfile(kBiggerGuid, kHttpOrigin); + AutofillProfile remote = AutofillProfile(kGuidB, kHttpOrigin); remote.SetRawInfo(ADDRESS_HOME_STREET_ADDRESS, ASCIIToUTF16("2 2st st")); remote.SetRawInfo(COMPANY_NAME, ASCIIToUTF16("Frobbers, Inc.")); @@ -464,21 +389,19 @@ // The local profile gets uploaded (due to initial sync) and the remote // profile gets stored locally. - UpdatesToSync updates = FlushToSync(); - EXPECT_THAT(updates.profiles_to_upload_to_sync, ElementsAre(local)); - EXPECT_THAT(updates.profiles_to_delete_from_sync, IsEmpty()); + EXPECT_THAT(FlushAndReturnProfilesToUploadToSync(), ElementsAre(local)); EXPECT_THAT(GetAllLocalData(), ElementsAre(local, remote)); } TEST_F(AutofillProfileInitialSyncDifferenceTrackerTest, MergeSimilarEntriesForInitialSyncDoesNotMatchLocalVerifiedEntry) { // The local entry is verified, should not get merged. - AutofillProfile local = AutofillProfile(kSmallerGuid, kSettingsOrigin); + AutofillProfile local = AutofillProfile(kGuidA, kSettingsOrigin); local.SetRawInfo(ADDRESS_HOME_STREET_ADDRESS, ASCIIToUTF16("1 1st st")); AddAutofillProfilesToTable({local}); // The remote profile is similar to the local one. - AutofillProfile remote = AutofillProfile(kBiggerGuid, kHttpOrigin); + AutofillProfile remote = AutofillProfile(kGuidB, kHttpOrigin); remote.SetRawInfo(ADDRESS_HOME_STREET_ADDRESS, ASCIIToUTF16("1 1st st")); remote.SetRawInfo(COMPANY_NAME, ASCIIToUTF16("Frobbers, Inc.")); @@ -487,21 +410,19 @@ // The local profile gets uploaded (due to initial sync) and the remote // profile gets stored locally. - UpdatesToSync updates = FlushToSync(); - EXPECT_THAT(updates.profiles_to_upload_to_sync, ElementsAre(local)); - EXPECT_THAT(updates.profiles_to_delete_from_sync, IsEmpty()); + EXPECT_THAT(FlushAndReturnProfilesToUploadToSync(), ElementsAre(local)); EXPECT_THAT(GetAllLocalData(), ElementsAre(local, remote)); } TEST_F(AutofillProfileInitialSyncDifferenceTrackerTest, MergeSimilarEntriesForInitialSyncDoesNotMatchRemoteVerifiedEntry) { - AutofillProfile local = AutofillProfile(kSmallerGuid, kHttpOrigin); + AutofillProfile local = AutofillProfile(kGuidA, kHttpOrigin); local.SetRawInfo(ADDRESS_HOME_STREET_ADDRESS, ASCIIToUTF16("1 1st st")); AddAutofillProfilesToTable({local}); // The remote profile is similar to the local one but is verified and thus it // should not get merged. - AutofillProfile remote = AutofillProfile(kBiggerGuid, kSettingsOrigin); + AutofillProfile remote = AutofillProfile(kGuidB, kSettingsOrigin); remote.SetRawInfo(ADDRESS_HOME_STREET_ADDRESS, ASCIIToUTF16("1 1st st")); remote.SetRawInfo(COMPANY_NAME, ASCIIToUTF16("Frobbers, Inc.")); @@ -510,9 +431,7 @@ // The local profile gets uploaded (due to initial sync) and the remote // profile gets stored locally. - UpdatesToSync updates = FlushToSync(); - EXPECT_THAT(updates.profiles_to_upload_to_sync, ElementsAre(local)); - EXPECT_THAT(updates.profiles_to_delete_from_sync, IsEmpty()); + EXPECT_THAT(FlushAndReturnProfilesToUploadToSync(), ElementsAre(local)); EXPECT_THAT(GetAllLocalData(), ElementsAre(local, remote)); }
diff --git a/components/browsing_data/core/counters/history_counter.cc b/components/browsing_data/core/counters/history_counter.cc index 99d2744..6f0e1ae 100644 --- a/components/browsing_data/core/counters/history_counter.cc +++ b/components/browsing_data/core/counters/history_counter.cc
@@ -68,8 +68,8 @@ history_service_->GetHistoryCount( GetPeriodStart(), GetPeriodEnd(), - base::Bind(&HistoryCounter::OnGetLocalHistoryCount, - weak_ptr_factory_.GetWeakPtr()), + base::BindOnce(&HistoryCounter::OnGetLocalHistoryCount, + weak_ptr_factory_.GetWeakPtr()), &cancelable_task_tracker_); // If the history sync is enabled, test if there is at least one synced item.
diff --git a/components/content_settings/core/browser/cookie_settings.cc b/components/content_settings/core/browser/cookie_settings.cc index ddc490d..2a31f93 100644 --- a/components/content_settings/core/browser/cookie_settings.cc +++ b/components/content_settings/core/browser/cookie_settings.cc
@@ -185,6 +185,8 @@ if (block_third_party_cookies_ != new_block_third_party_cookies) { base::AutoLock auto_lock(lock_); block_third_party_cookies_ = new_block_third_party_cookies; + for (Observer& obs : observers_) + obs.OnThirdPartyCookieBlockingChanged(block_third_party_cookies_); } }
diff --git a/components/content_settings/core/browser/cookie_settings.h b/components/content_settings/core/browser/cookie_settings.h index d339149c..481987c 100644 --- a/components/content_settings/core/browser/cookie_settings.h +++ b/components/content_settings/core/browser/cookie_settings.h
@@ -10,6 +10,7 @@ #include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/ref_counted.h" +#include "base/observer_list.h" #include "base/synchronization/lock.h" #include "base/threading/thread_checker.h" #include "components/content_settings/core/browser/host_content_settings_map.h" @@ -32,6 +33,12 @@ class CookieSettings : public CookieSettingsBase, public RefcountedKeyedService { public: + class Observer : public base::CheckedObserver { + public: + virtual void OnThirdPartyCookieBlockingChanged( + bool block_third_party_cookies) = 0; + }; + // Creates a new CookieSettings instance. // The caller is responsible for ensuring that |extension_scheme| is valid for // the whole lifetime of this instance. @@ -108,12 +115,17 @@ static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); + void AddObserver(Observer* obs) { observers_.AddObserver(obs); } + + void RemoveObserver(const Observer* obs) { observers_.RemoveObserver(obs); } + private: ~CookieSettings() override; void OnCookiePreferencesChanged(); base::ThreadChecker thread_checker_; + base::ObserverList<Observer> observers_; scoped_refptr<HostContentSettingsMap> host_content_settings_map_; PrefChangeRegistrar pref_change_registrar_; const char* extension_scheme_; // Weak.
diff --git a/components/crash/core/common/BUILD.gn b/components/crash/core/common/BUILD.gn index e1a5fb35..3d42df9 100644 --- a/components/crash/core/common/BUILD.gn +++ b/components/crash/core/common/BUILD.gn
@@ -153,14 +153,6 @@ sources += [ "objc_zombie_unittest.mm" ] } - # TODO(crbug.com/970280): crash_key* is failing on iOS. - if (is_ios) { - sources -= [ - "crash_key_unittest.cc", - "crash_keys_unittest.cc", - ] - } - if (!is_mac && !is_ios && !is_win && !is_fuchsia && !is_android) { include_dirs = [ "//third_party/breakpad/breakpad/src/" ] sources += [ "crash_key_breakpad_unittest.cc" ]
diff --git a/components/crash/core/common/crash_key.h b/components/crash/core/common/crash_key.h index a38e24c..2118ebd 100644 --- a/components/crash/core/common/crash_key.h +++ b/components/crash/core/common/crash_key.h
@@ -226,6 +226,10 @@ // current component. CRASH_KEY_EXPORT std::string GetCrashKeyValue(const std::string& key_name); +// Initializes the crash key subsystem with testing configuration if it is +// required. +CRASH_KEY_EXPORT void InitializeCrashKeysForTesting(); + // Resets crash key state and, depending on the platform, de-initializes // the system. CRASH_KEY_EXPORT void ResetCrashKeysForTesting();
diff --git a/components/crash/core/common/crash_key_breakpad.cc b/components/crash/core/common/crash_key_breakpad.cc index 0351e01..78f275f 100644 --- a/components/crash/core/common/crash_key_breakpad.cc +++ b/components/crash/core/common/crash_key_breakpad.cc
@@ -144,6 +144,10 @@ return std::string(); } +void InitializeCrashKeysForTesting() { + InitializeCrashKeys(); +} + void ResetCrashKeysForTesting() { internal::ResetCrashKeyStorageForTesting(); base::debug::SetCrashKeyImplementation(nullptr);
diff --git a/components/crash/core/common/crash_key_breakpad_ios.mm b/components/crash/core/common/crash_key_breakpad_ios.mm index b062517..b4099df 100644 --- a/components/crash/core/common/crash_key_breakpad_ios.mm +++ b/components/crash/core/common/crash_key_breakpad_ios.mm
@@ -95,9 +95,16 @@ return base::SysNSStringToUTF8(value); } +void InitializeCrashKeysForTesting() { + [[BreakpadController sharedInstance] updateConfiguration:@{ + @BREAKPAD_URL : @"http://breakpad.test" + }]; + [[BreakpadController sharedInstance] start:YES]; + InitializeCrashKeys(); +} + void ResetCrashKeysForTesting() { - // There's no way to do this on iOS without tearing down the - // BreakpadController. + [[BreakpadController sharedInstance] stop]; } } // namespace crash_reporter
diff --git a/components/crash/core/common/crash_key_crashpad.cc b/components/crash/core/common/crash_key_crashpad.cc index c6b07489..66fd94d 100644 --- a/components/crash/core/common/crash_key_crashpad.cc +++ b/components/crash/core/common/crash_key_crashpad.cc
@@ -35,6 +35,10 @@ return std::string(); } +void InitializeCrashKeysForTesting() { + InitializeCrashKeys(); +} + void ResetCrashKeysForTesting() { // The AnnotationList should not be deleted because the static Annotation // object data still reference the link nodes.
diff --git a/components/crash/core/common/crash_key_stubs.cc b/components/crash/core/common/crash_key_stubs.cc index 77fe36e7..c286715 100644 --- a/components/crash/core/common/crash_key_stubs.cc +++ b/components/crash/core/common/crash_key_stubs.cc
@@ -32,6 +32,8 @@ return std::string(); } +void InitializeCrashKeysForTesting() {} + void ResetCrashKeysForTesting() {} } // namespace crash_reporter
diff --git a/components/crash/core/common/crash_key_unittest.cc b/components/crash/core/common/crash_key_unittest.cc index cb9ad966..3e7f1023 100644 --- a/components/crash/core/common/crash_key_unittest.cc +++ b/components/crash/core/common/crash_key_unittest.cc
@@ -15,7 +15,9 @@ class CrashKeyStringTest : public testing::Test { public: - void SetUp() override { InitializeCrashKeys(); } + void SetUp() override { InitializeCrashKeysForTesting(); } + + void TearDown() override { ResetCrashKeysForTesting(); } }; TEST_F(CrashKeyStringTest, ScopedCrashKeyString) {
diff --git a/components/crash/core/common/crash_keys_unittest.cc b/components/crash/core/common/crash_keys_unittest.cc index 603cc36..82eb5cdd 100644 --- a/components/crash/core/common/crash_keys_unittest.cc +++ b/components/crash/core/common/crash_keys_unittest.cc
@@ -24,7 +24,7 @@ public: void SetUp() override { ResetData(); - crash_reporter::InitializeCrashKeys(); + crash_reporter::InitializeCrashKeysForTesting(); } void TearDown() override {
diff --git a/components/data_reduction_proxy/core/browser/data_reduction_proxy_service.h b/components/data_reduction_proxy/core/browser/data_reduction_proxy_service.h index 7731c93..46405a3f 100644 --- a/components/data_reduction_proxy/core/browser/data_reduction_proxy_service.h +++ b/components/data_reduction_proxy/core/browser/data_reduction_proxy_service.h
@@ -179,6 +179,10 @@ base::WeakPtr<DataReductionProxyService> GetWeakPtr(); + base::SequencedTaskRunner* GetDBTaskRunnerForTesting() const { + return db_task_runner_.get(); + } + private: FRIEND_TEST_ALL_PREFIXES(DataReductionProxySettingsTest, TestLoFiSessionStateHistograms);
diff --git a/components/history/core/browser/history_service.cc b/components/history/core/browser/history_service.cc index 851c854..d00a16cc 100644 --- a/components/history/core/browser/history_service.cc +++ b/components/history/core/browser/history_service.cc
@@ -681,44 +681,43 @@ base::CancelableTaskTracker::TaskId HistoryService::GetHistoryCount( const Time& begin_time, const Time& end_time, - const GetHistoryCountCallback& callback, + GetHistoryCountCallback callback, base::CancelableTaskTracker* tracker) { DCHECK(backend_task_runner_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); return tracker->PostTaskAndReplyWithResult( backend_task_runner_.get(), FROM_HERE, - base::Bind(&HistoryBackend::GetHistoryCount, history_backend_, begin_time, - end_time), - callback); + base::BindOnce(&HistoryBackend::GetHistoryCount, history_backend_, + begin_time, end_time), + std::move(callback)); } void HistoryService::CountUniqueHostsVisitedLastMonth( - const GetHistoryCountCallback& callback, + GetHistoryCountCallback callback, base::CancelableTaskTracker* tracker) { DCHECK(backend_task_runner_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); tracker->PostTaskAndReplyWithResult( backend_task_runner_.get(), FROM_HERE, - base::BindRepeating(&HistoryBackend::CountUniqueHostsVisitedLastMonth, - history_backend_), - callback); + base::BindOnce(&HistoryBackend::CountUniqueHostsVisitedLastMonth, + history_backend_), + std::move(callback)); } // Downloads ------------------------------------------------------------------- // Handle creation of a download by creating an entry in the history service's // 'downloads' table. -void HistoryService::CreateDownload( - const DownloadRow& create_info, - const HistoryService::DownloadCreateCallback& callback) { +void HistoryService::CreateDownload(const DownloadRow& create_info, + DownloadCreateCallback callback) { DCHECK(backend_task_runner_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); PostTaskAndReplyWithResult(backend_task_runner_.get(), FROM_HERE, - base::Bind(&HistoryBackend::CreateDownload, - history_backend_, create_info), - callback); + base::BindOnce(&HistoryBackend::CreateDownload, + history_backend_, create_info), + std::move(callback)); } void HistoryService::GetNextDownloadId(const DownloadIdCallback& callback) {
diff --git a/components/history/core/browser/history_service.h b/components/history/core/browser/history_service.h index f2494de..5f89170 100644 --- a/components/history/core/browser/history_service.h +++ b/components/history/core/browser/history_service.h
@@ -300,16 +300,16 @@ // [|begin_time|, |end_time|). Each URL is counted only once per day. For // determination of the date, timestamps are converted to dates using local // time. - typedef base::Callback<void(HistoryCountResult)> GetHistoryCountCallback; + using GetHistoryCountCallback = base::OnceCallback<void(HistoryCountResult)>; base::CancelableTaskTracker::TaskId GetHistoryCount( const base::Time& begin_time, const base::Time& end_time, - const GetHistoryCountCallback& callback, + GetHistoryCountCallback callback, base::CancelableTaskTracker* tracker); // Returns, via a callback, the number of Hosts visited in the last month. - void CountUniqueHostsVisitedLastMonth(const GetHistoryCountCallback& callback, + void CountUniqueHostsVisitedLastMonth(GetHistoryCountCallback callback, base::CancelableTaskTracker* tracker); // Database management operations -------------------------------------------- @@ -372,14 +372,13 @@ // Implemented by the caller of 'CreateDownload' below, and is called when the // history service has created a new entry for a download in the history db. - typedef base::Callback<void(bool)> DownloadCreateCallback; + using DownloadCreateCallback = base::OnceCallback<void(bool)>; // Begins a history request to create a new row for a download. 'info' // contains all the download's creation state, and 'callback' runs when the // history service request is complete. The callback is called on the thread // that calls CreateDownload(). - void CreateDownload(const DownloadRow& info, - const DownloadCreateCallback& callback); + void CreateDownload(const DownloadRow& info, DownloadCreateCallback callback); // Implemented by the caller of 'GetNextDownloadId' below, and is called with // the maximum id of all downloads records in the database plus 1.
diff --git a/components/language/core/common/language_experiments.cc b/components/language/core/common/language_experiments.cc index df4c1f7..e7cec35 100644 --- a/components/language/core/common/language_experiments.cc +++ b/components/language/core/common/language_experiments.cc
@@ -24,7 +24,7 @@ const base::Feature kUseFluentLanguageModel{"UseFluentLanguageModel", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kNotifySyncOnLanguageDetermined{ - "NotifySyncOnLanguageDetermined", base::FEATURE_ENABLED_BY_DEFAULT}; + "NotifySyncOnLanguageDetermined", base::FEATURE_DISABLED_BY_DEFAULT}; // Base feature for Translate desktop UI experiment const base::Feature kUseButtonTranslateBubbleUi{
diff --git a/components/omnibox/browser/BUILD.gn b/components/omnibox/browser/BUILD.gn index c05a311..c67055fc 100644 --- a/components/omnibox/browser/BUILD.gn +++ b/components/omnibox/browser/BUILD.gn
@@ -361,6 +361,7 @@ sources = [ "//components/test/data/omnibox/Shortcuts.no_fill_into_edit.sql", "//components/test/data/omnibox/Shortcuts.v0.sql", + "//components/test/data/omnibox/Shortcuts.v1.sql", "//components/test/data/omnibox/in_memory_url_index_test.sql", "//components/test/data/omnibox/in_memory_url_index_test_limited.sql", "//components/test/data/omnibox/on_device_head_test_model.bin",
diff --git a/components/omnibox/browser/autocomplete_result_unittest.cc b/components/omnibox/browser/autocomplete_result_unittest.cc index f5579a3..f8f441a 100644 --- a/components/omnibox/browser/autocomplete_result_unittest.cc +++ b/components/omnibox/browser/autocomplete_result_unittest.cc
@@ -690,6 +690,79 @@ result.match_at(2)->destination_url.spec()); } +TEST_F(AutocompleteResultTest, DemoteByTypeButPreserveDefaultMatchScore) { + // Add some matches. + ACMatches matches; + const AutocompleteMatchTestData data[] = { + {"http://history-url/", AutocompleteMatchType::HISTORY_URL}, + {"http://history-title/", AutocompleteMatchType::HISTORY_TITLE}, + {"http://search-what-you-typed/", + AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED}, + {"http://search-history/", AutocompleteMatchType::SEARCH_HISTORY}, + }; + PopulateAutocompleteMatchesFromTestData(data, base::size(data), &matches); + + // Make history-title and search-history the only default matches, so that + // they compete. + matches[0].allowed_to_be_default_match = false; + matches[2].allowed_to_be_default_match = false; + + // Add a rule demoting history-title. + { + std::map<std::string, std::string> params; + params[std::string(OmniboxFieldTrial::kDemoteByTypeRule) + ":*:*"] = "2:50"; + ASSERT_TRUE(variations::AssociateVariationParams( + OmniboxFieldTrial::kBundledExperimentFieldTrialName, "A", params)); + } + base::FieldTrialList::CreateFieldTrial( + OmniboxFieldTrial::kBundledExperimentFieldTrialName, "A"); + + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature(omnibox::kOmniboxPreserveDefaultMatchScore); + + { + AutocompleteInput input(base::ASCIIToUTF16("a"), + OmniboxEventProto::HOME_PAGE, + TestSchemeClassifier()); + AutocompleteResult result; + result.AppendMatches(input, matches); + result.SortAndCull(input, template_url_service_.get()); + + // Make sure history-title is the default match, despite demotion. + ASSERT_EQ(4u, result.size()); + EXPECT_EQ("http://history-title/", + result.match_at(0)->destination_url.spec()); + EXPECT_EQ("http://history-url/", + result.match_at(1)->destination_url.spec()); + EXPECT_EQ("http://search-what-you-typed/", + result.match_at(2)->destination_url.spec()); + EXPECT_EQ("http://search-history/", + result.match_at(3)->destination_url.spec()); + } + + { + // Re-sort with a page classification of fake-box, and make sure + // history-title is now demoted. + AutocompleteInput input( + base::ASCIIToUTF16("a"), + OmniboxEventProto::INSTANT_NTP_WITH_FAKEBOX_AS_STARTING_FOCUS, + TestSchemeClassifier()); + AutocompleteResult result; + result.AppendMatches(input, matches); + result.SortAndCull(input, template_url_service_.get()); + + ASSERT_EQ(4u, result.size()); + EXPECT_EQ("http://search-history/", + result.match_at(0)->destination_url.spec()); + EXPECT_EQ("http://history-url/", + result.match_at(1)->destination_url.spec()); + EXPECT_EQ("http://search-what-you-typed/", + result.match_at(2)->destination_url.spec()); + EXPECT_EQ("http://history-title/", + result.match_at(3)->destination_url.spec()); + } +} + TEST_F(AutocompleteResultTest, SortAndCullWithMatchDupsAndDemotionsByType) { // Add some matches. ACMatches matches;
diff --git a/components/omnibox/browser/omnibox_popup_model.cc b/components/omnibox/browser/omnibox_popup_model.cc index fb19717..fbaa4484 100644 --- a/components/omnibox/browser/omnibox_popup_model.cc +++ b/components/omnibox/browser/omnibox_popup_model.cc
@@ -309,7 +309,8 @@ // Get the favicon for navigational suggestions. if (base::FeatureList::IsEnabled( omnibox::kUIExperimentShowSuggestionFavicons) && - !AutocompleteMatch::IsSearchType(match.type)) { + !AutocompleteMatch::IsSearchType(match.type) && + match.type != AutocompleteMatchType::DOCUMENT_SUGGESTION) { // Because the Views UI code calls GetMatchIcon in both the layout and // painting code, we may generate multiple OnFaviconFetched callbacks, // all run one after another. This seems to be harmless as the callback
diff --git a/components/omnibox/browser/shortcuts_backend.cc b/components/omnibox/browser/shortcuts_backend.cc index 115f6daf..5201ae5 100644 --- a/components/omnibox/browser/shortcuts_backend.cc +++ b/components/omnibox/browser/shortcuts_backend.cc
@@ -171,6 +171,7 @@ return ShortcutsDatabase::Shortcut::MatchCore( normalized_match->fill_into_edit, normalized_match->destination_url, + static_cast<int>(normalized_match->document_type), normalized_match->contents, StripMatchMarkers(normalized_match->contents_class), normalized_match->description,
diff --git a/components/omnibox/browser/shortcuts_database.cc b/components/omnibox/browser/shortcuts_database.cc index 2e5a919..77c8dede 100644 --- a/components/omnibox/browser/shortcuts_database.cc +++ b/components/omnibox/browser/shortcuts_database.cc
@@ -26,7 +26,7 @@ // Current version number. We write databases at the "current" version number, // but any previous version that can read the "compatible" one can make do with // our database without *too* many bad effects. -const int kCurrentVersionNumber = 1; +const int kCurrentVersionNumber = 2; const int kCompatibleVersionNumber = 1; void BindShortcutToStatement(const ShortcutsDatabase::Shortcut& shortcut, @@ -36,15 +36,16 @@ s->BindString16(1, shortcut.text); s->BindString16(2, shortcut.match_core.fill_into_edit); s->BindString(3, shortcut.match_core.destination_url.spec()); - s->BindString16(4, shortcut.match_core.contents); - s->BindString(5, shortcut.match_core.contents_class); - s->BindString16(6, shortcut.match_core.description); - s->BindString(7, shortcut.match_core.description_class); - s->BindInt(8, shortcut.match_core.transition); - s->BindInt(9, shortcut.match_core.type); - s->BindString16(10, shortcut.match_core.keyword); - s->BindInt64(11, shortcut.last_access_time.ToInternalValue()); - s->BindInt(12, shortcut.number_of_hits); + s->BindInt(4, shortcut.match_core.document_type); + s->BindString16(5, shortcut.match_core.contents); + s->BindString(6, shortcut.match_core.contents_class); + s->BindString16(7, shortcut.match_core.description); + s->BindString(8, shortcut.match_core.description_class); + s->BindInt(9, shortcut.match_core.transition); + s->BindInt(10, shortcut.match_core.type); + s->BindString16(11, shortcut.match_core.keyword); + s->BindInt64(12, shortcut.last_access_time.ToInternalValue()); + s->BindInt(13, shortcut.number_of_hits); } bool DeleteShortcut(const char* field_name, @@ -90,6 +91,7 @@ ShortcutsDatabase::Shortcut::MatchCore::MatchCore( const base::string16& fill_into_edit, const GURL& destination_url, + int document_type, const base::string16& contents, const std::string& contents_class, const base::string16& description, @@ -99,14 +101,14 @@ const base::string16& keyword) : fill_into_edit(fill_into_edit), destination_url(destination_url), + document_type(document_type), contents(contents), contents_class(contents_class), description(description), description_class(description_class), transition(transition), type(type), - keyword(keyword) { -} + keyword(keyword) {} ShortcutsDatabase::Shortcut::MatchCore::MatchCore(const MatchCore& other) = default; @@ -130,11 +132,18 @@ } ShortcutsDatabase::Shortcut::Shortcut() - : match_core(base::string16(), GURL(), base::string16(), std::string(), - base::string16(), std::string(), 0, 0, base::string16()), + : match_core(base::string16(), + GURL(), + 0, + base::string16(), + std::string(), + base::string16(), + std::string(), + 0, + 0, + base::string16()), last_access_time(base::Time::Now()), - number_of_hits(0) { -} + number_of_hits(0) {} ShortcutsDatabase::Shortcut::Shortcut(const Shortcut& other) = default; @@ -173,9 +182,10 @@ sql::Statement s(db_.GetCachedStatement( SQL_FROM_HERE, "INSERT INTO omni_box_shortcuts (id, text, fill_into_edit, url, " - "contents, contents_class, description, description_class, " - "transition, type, keyword, last_access_time, number_of_hits) " - "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)")); + "document_type, contents, contents_class, description, " + "description_class, transition, type, keyword, last_access_time, " + "number_of_hits) " + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)")); BindShortcutToStatement(shortcut, &s); return s.Run(); } @@ -184,11 +194,11 @@ sql::Statement s(db_.GetCachedStatement( SQL_FROM_HERE, "UPDATE omni_box_shortcuts SET id=?, text=?, fill_into_edit=?, url=?, " - "contents=?, contents_class=?, description=?, description_class=?, " - "transition=?, type=?, keyword=?, last_access_time=?, " - "number_of_hits=? WHERE id=?")); + "document_type=?, contents=?, contents_class=?, description=?, " + "description_class=?, transition=?, type=?, keyword=?, " + "last_access_time=?, number_of_hits=? WHERE id=?")); BindShortcutToStatement(shortcut, &s); - s.BindString(13, shortcut.id); + s.BindString(14, shortcut.id); return s.Run(); } @@ -220,9 +230,9 @@ DCHECK(shortcuts); sql::Statement s(db_.GetCachedStatement( SQL_FROM_HERE, - "SELECT id, text, fill_into_edit, url, contents, contents_class, " - "description, description_class, transition, type, keyword, " - "last_access_time, number_of_hits FROM omni_box_shortcuts")); + "SELECT id, text, fill_into_edit, url, document_type, contents, " + "contents_class, description, description_class, transition, type, " + "keyword, last_access_time, number_of_hits FROM omni_box_shortcuts")); shortcuts->clear(); while (s.Step()) { @@ -234,16 +244,17 @@ Shortcut::MatchCore( s.ColumnString16(2), // fill_into_edit GURL(s.ColumnString(3)), // destination_url - s.ColumnString16(4), // contents - s.ColumnString(5), // contents_class - s.ColumnString16(6), // description - s.ColumnString(7), // description_class - s.ColumnInt(8), // transition - s.ColumnInt(9), // type - s.ColumnString16(10)), // keyword - base::Time::FromInternalValue(s.ColumnInt64(11)), + s.ColumnInt(4), // document_type + s.ColumnString16(5), // contents + s.ColumnString(6), // contents_class + s.ColumnString16(7), // description + s.ColumnString(8), // description_class + s.ColumnInt(9), // transition + s.ColumnInt(10), // type + s.ColumnString16(11)), // keyword + base::Time::FromInternalValue(s.ColumnInt64(12)), // last_access_time - s.ColumnInt(12)))); // number_of_hits + s.ColumnInt(13)))); // number_of_hits } } @@ -251,62 +262,110 @@ } bool ShortcutsDatabase::EnsureTable() { - if (!db_.DoesTableExist("omni_box_shortcuts")) { - return db_.Execute( - "CREATE TABLE omni_box_shortcuts (id VARCHAR PRIMARY KEY, " - "text VARCHAR, fill_into_edit VARCHAR, url VARCHAR, " - "contents VARCHAR, contents_class VARCHAR, description VARCHAR, " - "description_class VARCHAR, transition INTEGER, type INTEGER, " - "keyword VARCHAR, last_access_time INTEGER, " - "number_of_hits INTEGER)"); + if (!db_.DoesTableExist("omni_box_shortcuts")) + return DoMigration(-1); + + // The first version of the shortcuts table (pre-v0) lacked the + // fill_into_edit, transition, type, and keyword columns. + // Additionally, pre-v0 lacks a MetaTable from which to identify the version, + // thus requiring checking the existence of those columns. + if (!db_.DoesColumnExist("omni_box_shortcuts", "fill_into_edit") && + !DoMigration(0)) { + return false; } - // The first version of the shortcuts table lacked the fill_into_edit, - // transition, type, and keyword columns. - if (!db_.DoesColumnExist("omni_box_shortcuts", "fill_into_edit")) { - // Perform the upgrade in a transaction to ensure it doesn't happen - // incompletely. - sql::Transaction transaction(&db_); - if (!(transaction.Begin() && - db_.Execute("ALTER TABLE omni_box_shortcuts " - "ADD COLUMN fill_into_edit VARCHAR") && - db_.Execute("UPDATE omni_box_shortcuts SET fill_into_edit = url") && - db_.Execute("ALTER TABLE omni_box_shortcuts " - "ADD COLUMN transition INTEGER") && - db_.Execute(base::StringPrintf( - "UPDATE omni_box_shortcuts SET transition = %d", - static_cast<int>(ui::PAGE_TRANSITION_TYPED)).c_str()) && - db_.Execute("ALTER TABLE omni_box_shortcuts ADD COLUMN type INTEGER") && - db_.Execute(base::StringPrintf( - "UPDATE omni_box_shortcuts SET type = %d", - static_cast<int>(AutocompleteMatchType::HISTORY_TITLE)).c_str()) && - db_.Execute("ALTER TABLE omni_box_shortcuts " - "ADD COLUMN keyword VARCHAR") && - transaction.Commit())) { + // v0 also lacks a MetaTable. Migrating to v1 introduces the MetaTable in + // addition to other changes handled by |DoMigration|. If the MetaTable + // exists, lookup |current_version|. Otherwise, leave it at 0, and + // |DoMigration(1)| will create the MetaTable. + int current_version = 0; + if (sql::MetaTable::DoesTableExist(&db_)) { + if (!(meta_table_.Init(&db_, 1, kCompatibleVersionNumber))) return false; - } + current_version = meta_table_.GetVersionNumber(); } - if (!sql::MetaTable::DoesTableExist(&db_)) { - sql::Transaction transaction(&db_); - if (!(transaction.Begin() && - meta_table_.Init( - &db_, kCurrentVersionNumber, kCompatibleVersionNumber) && - // Migrate old SEARCH_OTHER_ENGINE values to the new type value. - db_.Execute( - "UPDATE omni_box_shortcuts SET type = 13 WHERE type = 9") && - // Migrate old EXTENSION_APP values to the new type value. - db_.Execute( - "UPDATE omni_box_shortcuts SET type = 14 WHERE type = 10") && - // Migrate old CONTACT values to the new type value. - db_.Execute( - "UPDATE omni_box_shortcuts SET type = 15 WHERE type = 11") && - // Migrate old BOOKMARK_TITLE values to the new type value. - db_.Execute( - "UPDATE omni_box_shortcuts SET type = 16 WHERE type = 12") && - transaction.Commit())) { + for (int i = current_version + 1; i <= kCurrentVersionNumber; ++i) { + if (!DoMigration(i)) return false; - } + meta_table_.SetVersionNumber(i); } + return true; } + +bool ShortcutsDatabase::DoMigration(int version) { + // Perform migrations in transactions to avoid incomplete migrations. + sql::Transaction transaction(&db_); + + switch (version) { + case -1: + // When there is no existing table, skip iterative migration; instead, + // migrate to the latest version. + return transaction.Begin() && + meta_table_.Init(&db_, kCurrentVersionNumber, + kCompatibleVersionNumber) && + db_.Execute( + "CREATE TABLE omni_box_shortcuts (id VARCHAR PRIMARY KEY, " + "text VARCHAR, fill_into_edit VARCHAR, url VARCHAR, " + "document_type INTEGER, contents VARCHAR, " + "contents_class VARCHAR, description VARCHAR, " + "description_class VARCHAR, transition INTEGER, type INTEGER, " + "keyword VARCHAR, last_access_time INTEGER, " + "number_of_hits INTEGER)") && + transaction.Commit(); + case 0: + // Version pre-0 of the shortcuts table lacked the fill_into_edit, + // transition type, and keyword columns. + return transaction.Begin() && + db_.Execute( + "ALTER TABLE omni_box_shortcuts " + "ADD COLUMN fill_into_edit VARCHAR") && + db_.Execute( + "UPDATE omni_box_shortcuts SET fill_into_edit = url") && + db_.Execute( + "ALTER TABLE omni_box_shortcuts " + "ADD COLUMN transition INTEGER") && + db_.Execute(base::StringPrintf( + "UPDATE omni_box_shortcuts SET transition = %d", + static_cast<int>(ui::PAGE_TRANSITION_TYPED)) + .c_str()) && + db_.Execute( + "ALTER TABLE omni_box_shortcuts ADD COLUMN type INTEGER") && + db_.Execute( + base::StringPrintf( + "UPDATE omni_box_shortcuts SET type = %d", + static_cast<int>(AutocompleteMatchType::HISTORY_TITLE)) + .c_str()) && + db_.Execute( + "ALTER TABLE omni_box_shortcuts " + "ADD COLUMN keyword VARCHAR") && + transaction.Commit(); + case 1: + return transaction.Begin() && + // Create the MetaTable. + meta_table_.Init(&db_, 1, kCompatibleVersionNumber) && + // Migrate old SEARCH_OTHER_ENGINE values to the new type value. + db_.Execute( + "UPDATE omni_box_shortcuts SET type = 13 WHERE type = 9") && + // Migrate old EXTENSION_APP values to the new type value. + db_.Execute( + "UPDATE omni_box_shortcuts SET type = 14 WHERE type = 10") && + // Migrate old CONTACT values to the new type value. + db_.Execute( + "UPDATE omni_box_shortcuts SET type = 15 WHERE type = 11") && + // Migrate old BOOKMARK_TITLE values to the new type value. + db_.Execute( + "UPDATE omni_box_shortcuts SET type = 16 WHERE type = 12") && + transaction.Commit(); + case 2: + // Version 1 of the shortcuts table lacked the document_type column. + return transaction.Begin() && + db_.Execute( + "ALTER TABLE omni_box_shortcuts " + "ADD COLUMN document_type INTEGER") && + transaction.Commit(); + default: + return false; + } +}
diff --git a/components/omnibox/browser/shortcuts_database.h b/components/omnibox/browser/shortcuts_database.h index f110560..fb922a3 100644 --- a/components/omnibox/browser/shortcuts_database.h +++ b/components/omnibox/browser/shortcuts_database.h
@@ -44,6 +44,7 @@ struct MatchCore { MatchCore(const base::string16& fill_into_edit, const GURL& destination_url, + int document_type, const base::string16& contents, const std::string& contents_class, const base::string16& description, @@ -56,6 +57,7 @@ base::string16 fill_into_edit; GURL destination_url; + int document_type; base::string16 contents; // For both contents_class and description_class, we strip MATCH // classifications; the ShortcutsProvider will re-mark MATCH regions based @@ -124,6 +126,11 @@ // Ensures that the table is present. bool EnsureTable(); + // Migrates table from version |version| - 1 to |version|. |version| = -1 + // indicates there is no preexisting table; |DoMigration| will migrate to the + // latest version, skipping iterative migrations. + bool DoMigration(int version); + // The sql database. Not valid until Init is called. sql::Database db_; base::FilePath database_path_;
diff --git a/components/omnibox/browser/shortcuts_database_unittest.cc b/components/omnibox/browser/shortcuts_database_unittest.cc index ec5389a..da795b0 100644 --- a/components/omnibox/browser/shortcuts_database_unittest.cc +++ b/components/omnibox/browser/shortcuts_database_unittest.cc
@@ -14,6 +14,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "build/build_config.h" +#include "components/omnibox/browser/autocomplete_match.h" #include "components/omnibox/browser/autocomplete_match_type.h" #include "components/omnibox/browser/shortcuts_constants.h" #include "sql/statement.h" @@ -33,6 +34,7 @@ std::string text; std::string fill_into_edit; std::string destination_url; + AutocompleteMatch::DocumentType document_type; std::string contents; std::string contents_class; std::string description; @@ -43,34 +45,79 @@ int days_from_now; int number_of_hits; } shortcut_test_db[] = { - { "BD85DBA2-8C29-49F9-84AE-48E1E90880DF", "goog", "www.google.com", - "http://www.google.com/", "Google", "0,1,4,0", "Google", "0,1", - ui::PAGE_TRANSITION_GENERATED, AutocompleteMatchType::SEARCH_HISTORY, - "google.com", 1, 100, }, - { "BD85DBA2-8C29-49F9-84AE-48E1E90880E0", "slash", "slashdot.org", - "http://slashdot.org/", "slashdot.org", "0,1", - "Slashdot - News for nerds, stuff that matters", "0,0", - ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_URL, "", 0, - 100}, - { "BD85DBA2-8C29-49F9-84AE-48E1E90880E1", "news", "slashdot.org", - "http://slashdot.org/", "slashdot.org", "0,1", - "Slashdot - News for nerds, stuff that matters", "0,0", - ui::PAGE_TRANSITION_LINK, AutocompleteMatchType::HISTORY_TITLE, "", 0, - 5}, + {"BD85DBA2-8C29-49F9-84AE-48E1E90880DF", "goog", "www.google.com", + "http://www.google.com/", AutocompleteMatch::DocumentType::NONE, "Google", + "0,1,4,0", "Google", "0,1", ui::PAGE_TRANSITION_GENERATED, + AutocompleteMatchType::SEARCH_HISTORY, "google.com", 1, 100}, + {"BD85DBA2-8C29-49F9-84AE-48E1E90880E0", "slash", "slashdot.org", + "http://slashdot.org/", AutocompleteMatch::DocumentType::NONE, + "slashdot.org", "0,1", "Slashdot - News for nerds, stuff that matters", + "0,0", ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_URL, "", + 0, 100}, + {"BD85DBA2-8C29-49F9-84AE-48E1E90880E1", "news", "slashdot.org", + "http://slashdot.org/", AutocompleteMatch::DocumentType::NONE, + "slashdot.org", "0,1", "Slashdot - News for nerds, stuff that matters", + "0,0", ui::PAGE_TRANSITION_LINK, AutocompleteMatchType::HISTORY_TITLE, "", + 0, 5}, }; typedef testing::Test ShortcutsDatabaseMigrationTest; -// Checks that the database at |db| has the version 2 columns iff |is_v2|. -void CheckV2ColumnExistence(const base::FilePath& db_path, bool is_v2) { +// Checks that the database at |db_path| has the version 0 columns iff |is_v0|. +void CheckV0ColumnExistence(const base::FilePath& db_path, bool is_v0) { sql::Database connection; ASSERT_TRUE(connection.Open(db_path)); - EXPECT_EQ(is_v2, + EXPECT_EQ(is_v0, connection.DoesColumnExist("omni_box_shortcuts", "fill_into_edit")); - EXPECT_EQ(is_v2, + EXPECT_EQ(is_v0, connection.DoesColumnExist("omni_box_shortcuts", "transition")); - EXPECT_EQ(is_v2, connection.DoesColumnExist("omni_box_shortcuts", "type")); - EXPECT_EQ(is_v2, connection.DoesColumnExist("omni_box_shortcuts", "keyword")); + EXPECT_EQ(is_v0, connection.DoesColumnExist("omni_box_shortcuts", "type")); + EXPECT_EQ(is_v0, connection.DoesColumnExist("omni_box_shortcuts", "keyword")); +} + +// Tests the db at |sql_path| successfully migrates to V2 when initialized. +void CheckV2Migration(base::FilePath sql_path) { + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + base::FilePath db_path(temp_dir.GetPath().AppendASCII("TestShortcuts.db")); + if (!sql_path.empty()) + ASSERT_TRUE(sql::test::CreateDatabaseFromSQL(db_path, sql_path)); + + // Check document_type column does not yet exist. + { + sql::Database connection; + ASSERT_TRUE(connection.Open(db_path)); + EXPECT_FALSE( + connection.DoesColumnExist("omni_box_shortcuts", "document_type")); + } + + // Create a ShortcutsDatabase from the test database, which will migrate the + // test database to the current version. + { + scoped_refptr<ShortcutsDatabase> db(new ShortcutsDatabase(db_path)); + db->Init(); + } + + sql::Database connection; + ASSERT_TRUE(connection.Open(db_path)); + + // Check a meta table was created. + ASSERT_TRUE(sql::MetaTable::DoesTableExist(&connection)); + + // Check document_type column exists after migration. + EXPECT_TRUE( + connection.DoesColumnExist("omni_box_shortcuts", "document_type")); + + // Check the column has the default value. + sql::Statement statement(connection.GetUniqueStatement( + "SELECT document_type FROM omni_box_shortcuts")); + ASSERT_TRUE(statement.is_valid()); + while (statement.Step()) { + EXPECT_EQ( + AutocompleteMatch::DocumentType::NONE, + static_cast<AutocompleteMatch::DocumentType>(statement.ColumnInt(0))); + } + EXPECT_TRUE(statement.Succeeded()); } const base::FilePath GetTestDataDir() { @@ -131,9 +178,10 @@ info.guid, ASCIIToUTF16(info.text), ShortcutsDatabase::Shortcut::MatchCore( ASCIIToUTF16(info.fill_into_edit), GURL(info.destination_url), - ASCIIToUTF16(info.contents), info.contents_class, - ASCIIToUTF16(info.description), info.description_class, - info.transition, info.type, ASCIIToUTF16(info.keyword)), + static_cast<int>(info.document_type), ASCIIToUTF16(info.contents), + info.contents_class, ASCIIToUTF16(info.description), + info.description_class, info.transition, info.type, + ASCIIToUTF16(info.keyword)), base::Time::Now() - base::TimeDelta::FromDays(info.days_from_now), info.number_of_hits); } @@ -224,18 +272,13 @@ TEST(ShortcutsDatabaseMigrationTest, MigrateTableAddFillIntoEdit) { // Use the pre-v0 test file to create a test database in a temp dir. - base::FilePath sql_path = GetTestDataDir().AppendASCII( -#if defined(OS_ANDROID) - "Shortcuts.v1.sql"); -#else - "Shortcuts.no_fill_into_edit.sql"); -#endif + base::FilePath sql_path = GetTestDataDir().AppendASCII("Shortcuts.no_fill_into_edit.sql"); base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); base::FilePath db_path(temp_dir.GetPath().AppendASCII("TestShortcuts.db")); ASSERT_TRUE(sql::test::CreateDatabaseFromSQL(db_path, sql_path)); - CheckV2ColumnExistence(db_path, false); + CheckV0ColumnExistence(db_path, false); // Create a ShortcutsDatabase from the test database, which will migrate the // test database to the current version. @@ -244,11 +287,15 @@ db->Init(); } - CheckV2ColumnExistence(db_path, true); + CheckV0ColumnExistence(db_path, true); - // Check the values in each of the new columns. sql::Database connection; ASSERT_TRUE(connection.Open(db_path)); + + // Check a meta table was created. + ASSERT_TRUE(sql::MetaTable::DoesTableExist(&connection)); + + // Check the values in each of the new columns. sql::Statement statement(connection.GetUniqueStatement( "SELECT fill_into_edit, url, transition, type, keyword " "FROM omni_box_shortcuts")); @@ -266,9 +313,6 @@ EXPECT_TRUE(statement.ColumnString(4).empty()); } EXPECT_TRUE(statement.Succeeded()); -#if !defined(OS_WIN) - EXPECT_TRUE(temp_dir.Delete()); -#endif } TEST(ShortcutsDatabaseMigrationTest, MigrateV0ToV1) { @@ -289,25 +333,31 @@ // Check that all the old type values got converted to new values. sql::Database connection; ASSERT_TRUE(connection.Open(db_path)); + + // Check a meta table was created. + ASSERT_TRUE(sql::MetaTable::DoesTableExist(&connection)); + sql::Statement statement(connection.GetUniqueStatement( "SELECT count(1) FROM omni_box_shortcuts WHERE type in (9, 10, 11, 12)")); ASSERT_TRUE(statement.is_valid()); while (statement.Step()) EXPECT_EQ(0, statement.ColumnInt(0)); EXPECT_TRUE(statement.Succeeded()); -#if !defined(OS_WIN) - EXPECT_TRUE(temp_dir.Delete()); -#endif +} + +TEST(ShortcutsDatabaseMigrationTest, MigrateToV2) { + // Test migrating from a database with no omni_box_shortcuts table. + base::FilePath sql_path; + CheckV2Migration(sql_path); + + CheckV2Migration(GetTestDataDir().AppendASCII("Shortcuts.no_fill_into_edit.sql")); + CheckV2Migration(GetTestDataDir().AppendASCII("Shortcuts.v0.sql")); + CheckV2Migration(GetTestDataDir().AppendASCII("Shortcuts.v1.sql")); } TEST(ShortcutsDatabaseMigrationTest, Recovery1) { -#if defined(OS_ANDROID) - char kBasename[] = "Shortcuts.v1.sql"; -#else - char kBasename[] = "Shortcuts.no_fill_into_edit.sql"; -#endif // Use the pre-v0 test file to create a test database in a temp dir. - base::FilePath sql_path = GetTestDataDir().AppendASCII(kBasename); + base::FilePath sql_path = GetTestDataDir().AppendASCII("Shortcuts.no_fill_into_edit.sql"); base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); base::FilePath db_path(temp_dir.GetPath().AppendASCII("TestShortcuts.db")); @@ -355,7 +405,7 @@ ASSERT_TRUE(expecter.SawExpectedErrors()); } - CheckV2ColumnExistence(db_path, true); + CheckV0ColumnExistence(db_path, true); // The previously-broken statement works and all of the data should have been // recovered.
diff --git a/components/omnibox/browser/shortcuts_provider.cc b/components/omnibox/browser/shortcuts_provider.cc index 028a1cf..4424f83 100644 --- a/components/omnibox/browser/shortcuts_provider.cc +++ b/components/omnibox/browser/shortcuts_provider.cc
@@ -257,6 +257,8 @@ match.fill_into_edit = shortcut.match_core.fill_into_edit; match.destination_url = shortcut.match_core.destination_url; DCHECK(match.destination_url.is_valid()); + match.document_type = static_cast<AutocompleteMatch::DocumentType>( + shortcut.match_core.document_type); match.contents = shortcut.match_core.contents; match.contents_class = AutocompleteMatch::ClassificationsFromString( shortcut.match_core.contents_class);
diff --git a/components/omnibox/browser/shortcuts_provider_test_util.cc b/components/omnibox/browser/shortcuts_provider_test_util.cc index 3ee9e2a..1622478e 100644 --- a/components/omnibox/browser/shortcuts_provider_test_util.cc +++ b/components/omnibox/browser/shortcuts_provider_test_util.cc
@@ -12,23 +12,26 @@ #include "components/omnibox/browser/test_scheme_classifier.h" #include "testing/gtest/include/gtest/gtest.h" -TestShortcutData::TestShortcutData(std::string guid, - std::string text, - std::string fill_into_edit, - std::string destination_url, - std::string contents, - std::string contents_class, - std::string description, - std::string description_class, - ui::PageTransition transition, - AutocompleteMatch::Type type, - std::string keyword, - int days_from_now, - int number_of_hits) { +TestShortcutData::TestShortcutData( + std::string guid, + std::string text, + std::string fill_into_edit, + std::string destination_url, + AutocompleteMatch::DocumentType document_type, + std::string contents, + std::string contents_class, + std::string description, + std::string description_class, + ui::PageTransition transition, + AutocompleteMatch::Type type, + std::string keyword, + int days_from_now, + int number_of_hits) { this->guid = guid; this->text = text; this->fill_into_edit = fill_into_edit; this->destination_url = destination_url; + this->document_type = document_type; this->contents = contents; this->contents_class = contents_class; this->description = description; @@ -53,6 +56,7 @@ cur.guid, base::ASCIIToUTF16(cur.text), ShortcutsDatabase::Shortcut::MatchCore( base::ASCIIToUTF16(cur.fill_into_edit), GURL(cur.destination_url), + static_cast<int>(cur.document_type), base::ASCIIToUTF16(cur.contents), cur.contents_class, base::ASCIIToUTF16(cur.description), cur.description_class, cur.transition, cur.type, base::ASCIIToUTF16(cur.keyword)),
diff --git a/components/omnibox/browser/shortcuts_provider_test_util.h b/components/omnibox/browser/shortcuts_provider_test_util.h index adb0c8a..0b9f1f7 100644 --- a/components/omnibox/browser/shortcuts_provider_test_util.h +++ b/components/omnibox/browser/shortcuts_provider_test_util.h
@@ -22,6 +22,7 @@ std::string text, std::string fill_into_edit, std::string destination_url, + AutocompleteMatch::DocumentType document_type, std::string contents, std::string contents_class, std::string description, @@ -37,6 +38,7 @@ std::string text; std::string fill_into_edit; std::string destination_url; + AutocompleteMatch::DocumentType document_type; std::string contents; std::string contents_class; std::string description;
diff --git a/components/omnibox/browser/shortcuts_provider_unittest.cc b/components/omnibox/browser/shortcuts_provider_unittest.cc index ae812c0b..845e512 100644 --- a/components/omnibox/browser/shortcuts_provider_unittest.cc +++ b/components/omnibox/browser/shortcuts_provider_unittest.cc
@@ -40,125 +40,147 @@ struct TestShortcutData shortcut_test_db[] = { {"BD85DBA2-8C29-49F9-84AE-48E1E90880E0", "goog", "www.google.com", - "http://www.google.com/", "Google", "0,1,4,0", "Google", "0,3,4,1", - ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_URL, "", 1, 100}, + "http://www.google.com/", AutocompleteMatch::DocumentType::NONE, "Google", + "0,1,4,0", "Google", "0,3,4,1", ui::PAGE_TRANSITION_TYPED, + AutocompleteMatchType::HISTORY_URL, "", 1, 100}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880E1", "slash", "slashdot.org", - "http://slashdot.org/", "slashdot.org", "0,3,5,1", - "Slashdot - News for nerds, stuff that matters", "0,2,5,0", - ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_URL, "", 0, 100}, + "http://slashdot.org/", AutocompleteMatch::DocumentType::NONE, + "slashdot.org", "0,3,5,1", "Slashdot - News for nerds, stuff that matters", + "0,2,5,0", ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_URL, + "", 0, 100}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880E2", "news", "slashdot.org", - "http://slashdot.org/", "slashdot.org", "0,1", - "Slashdot - News for nerds, stuff that matters", "0,0,11,2,15,0", - ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_TITLE, "", 0, 5}, + "http://slashdot.org/", AutocompleteMatch::DocumentType::NONE, + "slashdot.org", "0,1", "Slashdot - News for nerds, stuff that matters", + "0,0,11,2,15,0", ui::PAGE_TRANSITION_TYPED, + AutocompleteMatchType::HISTORY_TITLE, "", 0, 5}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880E3", "news", "sports.yahoo.com", - "http://sports.yahoo.com/", "sports.yahoo.com", "0,1", + "http://sports.yahoo.com/", AutocompleteMatch::DocumentType::NONE, + "sports.yahoo.com", "0,1", "Yahoo! Sports - Sports News, Scores, Rumors, Fantasy Games, and more", "0,0,23,2,27,0", ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_TITLE, "", 2, 5}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880E4", "news weather", "www.cnn.com/index.html", "http://www.cnn.com/index.html", - "www.cnn.com/index.html", "0,1", + AutocompleteMatch::DocumentType::NONE, "www.cnn.com/index.html", "0,1", "CNN.com - Breaking News, U.S., World, Weather, Entertainment & Video", "0,0,19,2,23,0,38,2,45,0", ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_TITLE, "", 1, 10}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880E5", "nhl scores", "sports.yahoo.com", - "http://sports.yahoo.com/", "sports.yahoo.com", "0,1", + "http://sports.yahoo.com/", AutocompleteMatch::DocumentType::NONE, + "sports.yahoo.com", "0,1", "Yahoo! Sports - Sports News, Scores, Rumors, Fantasy Games, and more", "0,0,29,2,35,0", ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_BODY, "", 1, 10}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880E6", "nhl scores", "www.nhl.com/scores/index.html", "http://www.nhl.com/scores/index.html", - "www.nhl.com/scores/index.html", "0,1,4,3,7,1", - "January 13, 2010 - NHL.com - Scores", "0,0,19,2,22,0,29,2,35,0", - ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_URL, "", 5, 1}, + AutocompleteMatch::DocumentType::NONE, "www.nhl.com/scores/index.html", + "0,1,4,3,7,1", "January 13, 2010 - NHL.com - Scores", + "0,0,19,2,22,0,29,2,35,0", ui::PAGE_TRANSITION_TYPED, + AutocompleteMatchType::HISTORY_URL, "", 5, 1}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880E7", "just", "www.testsite.com/a.html", - "http://www.testsite.com/a.html", "www.testsite.com/a.html", "0,1", - "Test - site - just a test", "0,0,14,2,18,0", ui::PAGE_TRANSITION_TYPED, + "http://www.testsite.com/a.html", AutocompleteMatch::DocumentType::NONE, + "www.testsite.com/a.html", "0,1", "Test - site - just a test", + "0,0,14,2,18,0", ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_TITLE, "", 5, 1}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880E8", "just", "www.testsite.com/b.html", - "http://www.testsite.com/b.html", "www.testsite.com/b.html", "0,1", - "Test - site - just a test", "0,0,14,2,18,0", ui::PAGE_TRANSITION_TYPED, + "http://www.testsite.com/b.html", AutocompleteMatch::DocumentType::NONE, + "www.testsite.com/b.html", "0,1", "Test - site - just a test", + "0,0,14,2,18,0", ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_TITLE, "", 5, 2}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880E9", "just", "www.testsite.com/c.html", - "http://www.testsite.com/c.html", "www.testsite.com/c.html", "0,1", - "Test - site - just a test", "0,0,14,2,18,0", ui::PAGE_TRANSITION_TYPED, + "http://www.testsite.com/c.html", AutocompleteMatch::DocumentType::NONE, + "www.testsite.com/c.html", "0,1", "Test - site - just a test", + "0,0,14,2,18,0", ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_TITLE, "", 8, 1}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880EA", "just a", "www.testsite.com/d.html", "http://www.testsite.com/d.html", - "www.testsite.com/d.html", "0,1", "Test - site - just a test", - "0,0,14,2,18,0", ui::PAGE_TRANSITION_TYPED, + AutocompleteMatch::DocumentType::NONE, "www.testsite.com/d.html", "0,1", + "Test - site - just a test", "0,0,14,2,18,0", ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_TITLE, "", 12, 1}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880EB", "just a t", "www.testsite.com/e.html", "http://www.testsite.com/e.html", - "www.testsite.com/e.html", "0,1", "Test - site - just a test", - "0,0,14,2,18,0", ui::PAGE_TRANSITION_TYPED, + AutocompleteMatch::DocumentType::NONE, "www.testsite.com/e.html", "0,1", + "Test - site - just a test", "0,0,14,2,18,0", ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_TITLE, "", 12, 1}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880EC", "just a te", "www.testsite.com/f.html", "http://www.testsite.com/f.html", - "www.testsite.com/f.html", "0,1", "Test - site - just a test", - "0,0,14,2,18,0", ui::PAGE_TRANSITION_TYPED, + AutocompleteMatch::DocumentType::NONE, "www.testsite.com/f.html", "0,1", + "Test - site - just a test", "0,0,14,2,18,0", ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_TITLE, "", 12, 1}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880ED", "ago", "www.daysagotest.com/a.html", "http://www.daysagotest.com/a.html", - "www.daysagotest.com/a.html", "0,1,8,3,11,1", "Test - site", "0,0", - ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_URL, "", 1, 1}, + AutocompleteMatch::DocumentType::NONE, "www.daysagotest.com/a.html", + "0,1,8,3,11,1", "Test - site", "0,0", ui::PAGE_TRANSITION_TYPED, + AutocompleteMatchType::HISTORY_URL, "", 1, 1}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880EE", "ago", "www.daysagotest.com/b.html", "http://www.daysagotest.com/b.html", - "www.daysagotest.com/b.html", "0,1,8,3,11,1", "Test - site", "0,0", - ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_URL, "", 2, 1}, + AutocompleteMatch::DocumentType::NONE, "www.daysagotest.com/b.html", + "0,1,8,3,11,1", "Test - site", "0,0", ui::PAGE_TRANSITION_TYPED, + AutocompleteMatchType::HISTORY_URL, "", 2, 1}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880EF", "ago", "www.daysagotest.com/c.html", "http://www.daysagotest.com/c.html", - "www.daysagotest.com/c.html", "0,1,8,3,11,1", "Test - site", "0,0", - ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_URL, "", 3, 1}, + AutocompleteMatch::DocumentType::NONE, "www.daysagotest.com/c.html", + "0,1,8,3,11,1", "Test - site", "0,0", ui::PAGE_TRANSITION_TYPED, + AutocompleteMatchType::HISTORY_URL, "", 3, 1}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880F0", "ago", "www.daysagotest.com/d.html", "http://www.daysagotest.com/d.html", - "www.daysagotest.com/d.html", "0,1,8,3,11,1", "Test - site", "0,0", - ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_URL, "", 4, 1}, + AutocompleteMatch::DocumentType::NONE, "www.daysagotest.com/d.html", + "0,1,8,3,11,1", "Test - site", "0,0", ui::PAGE_TRANSITION_TYPED, + AutocompleteMatchType::HISTORY_URL, "", 4, 1}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880F2", "abcdef.com", "http://abcdef.com", - "http://abcdef.com/", "Abcdef", "0,1,4,0", "Abcdef", "0,3,4,1", - ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_URL, "", 1, 100}, + "http://abcdef.com/", AutocompleteMatch::DocumentType::NONE, "Abcdef", + "0,1,4,0", "Abcdef", "0,3,4,1", ui::PAGE_TRANSITION_TYPED, + AutocompleteMatchType::HISTORY_URL, "", 1, 100}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880F3", "query", "query", - "https://www.google.com/search?q=query", "query", "0,0", "Google Search", + "https://www.google.com/search?q=query", + AutocompleteMatch::DocumentType::NONE, "query", "0,0", "Google Search", "0,4", ui::PAGE_TRANSITION_GENERATED, AutocompleteMatchType::SEARCH_HISTORY, "google.com", 1, 100}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880F4", "word", "www.word", - "https://www.google.com/search?q=www.word", "www.word", "0,0", - "Google Search", "0,4", ui::PAGE_TRANSITION_GENERATED, + "https://www.google.com/search?q=www.word", + AutocompleteMatch::DocumentType::NONE, "www.word", "0,0", "Google Search", + "0,4", ui::PAGE_TRANSITION_GENERATED, AutocompleteMatchType::SEARCH_HISTORY, "google.com", 1, 100}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880F5", "about:o", "chrome://omnibox", - "chrome://omnibox/", "about:omnibox", "0,3,10,1", "", "", - ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::NAVSUGGEST, "", 1, 100}, + "chrome://omnibox/", AutocompleteMatch::DocumentType::NONE, + "about:omnibox", "0,3,10,1", "", "", ui::PAGE_TRANSITION_TYPED, + AutocompleteMatchType::NAVSUGGEST, "", 1, 100}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880F6", "www/real sp", "http://www/real space/long-url-with-space.html", "http://www/real%20space/long-url-with-space.html", + AutocompleteMatch::DocumentType::NONE, "www/real space/long-url-with-space.html", "0,3,11,1", "Page With Space; Input with Space", "0,0", ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_URL, "", 1, 100}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880F7", "duplicate", - "http://duplicate.com", "http://duplicate.com/", "Duplicate", "0,1", - "Duplicate", "0,1", ui::PAGE_TRANSITION_TYPED, - AutocompleteMatchType::HISTORY_URL, "", 1, 100}, + "http://duplicate.com", "http://duplicate.com/", + AutocompleteMatch::DocumentType::NONE, "Duplicate", "0,1", "Duplicate", + "0,1", ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_URL, "", + 1, 100}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880F8", "dupl", "http://duplicate.com", - "http://duplicate.com/", "Duplicate", "0,1", "Duplicate", "0,1", - ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_URL, "", 1, 100}, + "http://duplicate.com/", AutocompleteMatch::DocumentType::NONE, + "Duplicate", "0,1", "Duplicate", "0,1", ui::PAGE_TRANSITION_TYPED, + AutocompleteMatchType::HISTORY_URL, "", 1, 100}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880F9", "notrailing.com/", - "http://notrailing.com", "http://notrailing.com/", "No Trailing Slash", - "0,1", "No Trailing Slash on fill_into_edit", "0,1", - ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_URL, "", 1, 100}, + "http://notrailing.com", "http://notrailing.com/", + AutocompleteMatch::DocumentType::NONE, "No Trailing Slash", "0,1", + "No Trailing Slash on fill_into_edit", "0,1", ui::PAGE_TRANSITION_TYPED, + AutocompleteMatchType::HISTORY_URL, "", 1, 100}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880FA", "http:///foo.com", - "http://foo.com", "http://foo.com/", "Foo - Typo in Input", "0,1", + "http://foo.com", "http://foo.com/", AutocompleteMatch::DocumentType::NONE, + "Foo - Typo in Input", "0,1", "Foo - Typo in Input Corrected in fill_into_edit", "0,1", ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_URL, "", 1, 100}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880FB", "trailing1 ", "http://trailing1.com", "http://trailing1.com/", - "Trailing1 - Space in Shortcut", "0,1", "Trailing1 - Space in Shortcut", - "0,1", ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_URL, "", - 1, 100}, + AutocompleteMatch::DocumentType::NONE, "Trailing1 - Space in Shortcut", + "0,1", "Trailing1 - Space in Shortcut", "0,1", ui::PAGE_TRANSITION_TYPED, + AutocompleteMatchType::HISTORY_URL, "", 1, 100}, {"BD85DBA2-8C29-49F9-84AE-48E1E90880FC", "about:trailing2 ", "chrome://trailing2blah", "chrome://trailing2blah/", - "Trailing2 - Space in Shortcut", "0,1", "Trailing2 - Space in Shortcut", - "0,1", ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_URL, "", - 1, 100}, + AutocompleteMatch::DocumentType::NONE, "Trailing2 - Space in Shortcut", + "0,1", "Trailing2 - Space in Shortcut", "0,1", ui::PAGE_TRANSITION_TYPED, + AutocompleteMatchType::HISTORY_URL, "", 1, 100}, }; } // namespace @@ -437,6 +459,7 @@ std::string(), ASCIIToUTF16("test"), ShortcutsDatabase::Shortcut::MatchCore( ASCIIToUTF16("www.test.com"), GURL("http://www.test.com"), + static_cast<int>(AutocompleteMatch::DocumentType::NONE), ASCIIToUTF16("www.test.com"), "0,1,4,3,8,1", ASCIIToUTF16("A test"), "0,0,2,2", ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_URL, base::string16()), @@ -488,21 +511,23 @@ TEST_F(ShortcutsProviderTest, DeleteMatch) { TestShortcutData shortcuts_to_test_delete[] = { {"BD85DBA2-8C29-49F9-84AE-48E1E90881F1", "delete", "www.deletetest.com/1", - "http://www.deletetest.com/1", "http://www.deletetest.com/1", "0,2", - "Erase this shortcut!", "0,0", ui::PAGE_TRANSITION_TYPED, - AutocompleteMatchType::HISTORY_URL, "", 1, 1}, + "http://www.deletetest.com/1", AutocompleteMatch::DocumentType::NONE, + "http://www.deletetest.com/1", "0,2", "Erase this shortcut!", "0,0", + ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_URL, "", 1, 1}, {"BD85DBA2-8C29-49F9-84AE-48E1E90881F2", "erase", "www.deletetest.com/1", - "http://www.deletetest.com/1", "http://www.deletetest.com/1", "0,2", - "Erase this shortcut!", "0,0", ui::PAGE_TRANSITION_TYPED, - AutocompleteMatchType::HISTORY_TITLE, "", 1, 1}, + "http://www.deletetest.com/1", AutocompleteMatch::DocumentType::NONE, + "http://www.deletetest.com/1", "0,2", "Erase this shortcut!", "0,0", + ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_TITLE, "", 1, + 1}, {"BD85DBA2-8C29-49F9-84AE-48E1E90881F3", "keep", "www.deletetest.com/1/2", - "http://www.deletetest.com/1/2", "http://www.deletetest.com/1/2", "0,2", - "Keep this shortcut!", "0,0", ui::PAGE_TRANSITION_TYPED, - AutocompleteMatchType::HISTORY_TITLE, "", 1, 1}, + "http://www.deletetest.com/1/2", AutocompleteMatch::DocumentType::NONE, + "http://www.deletetest.com/1/2", "0,2", "Keep this shortcut!", "0,0", + ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_TITLE, "", 1, + 1}, {"BD85DBA2-8C29-49F9-84AE-48E1E90881F4", "delete", "www.deletetest.com/2", - "http://www.deletetest.com/2", "http://www.deletetest.com/2", "0,2", - "Erase this shortcut!", "0,0", ui::PAGE_TRANSITION_TYPED, - AutocompleteMatchType::HISTORY_URL, "", 1, 1}, + "http://www.deletetest.com/2", AutocompleteMatch::DocumentType::NONE, + "http://www.deletetest.com/2", "0,2", "Erase this shortcut!", "0,0", + ui::PAGE_TRANSITION_TYPED, AutocompleteMatchType::HISTORY_URL, "", 1, 1}, }; scoped_refptr<ShortcutsBackend> backend = client_->GetShortcutsBackend();
diff --git a/components/remote_cocoa/DEPS b/components/remote_cocoa/DEPS index 3a1c916..646c0f5 100644 --- a/components/remote_cocoa/DEPS +++ b/components/remote_cocoa/DEPS
@@ -9,4 +9,5 @@ "+ui/display", "+ui/events", "+ui/gfx", + "+ui/strings/grit" ]
diff --git a/components/remote_cocoa/app_shim/BUILD.gn b/components/remote_cocoa/app_shim/BUILD.gn index cbbe402..912d967 100644 --- a/components/remote_cocoa/app_shim/BUILD.gn +++ b/components/remote_cocoa/app_shim/BUILD.gn
@@ -40,6 +40,8 @@ "ns_view_ids.h", "ns_view_ids.mm", "remote_cocoa_app_shim_export.h", + "select_file_dialog_bridge.h", + "select_file_dialog_bridge.mm", "views_nswindow_delegate.h", "views_nswindow_delegate.mm", "views_scrollbar_bridge.h", @@ -60,6 +62,7 @@ "//ui/base/ime:ime", "//ui/events", "//ui/gfx", + "//ui/strings:ui_strings_grit", ] libs = [ "Cocoa.framework",
diff --git a/components/remote_cocoa/app_shim/select_file_dialog_bridge.h b/components/remote_cocoa/app_shim/select_file_dialog_bridge.h new file mode 100644 index 0000000..f434102e --- /dev/null +++ b/components/remote_cocoa/app_shim/select_file_dialog_bridge.h
@@ -0,0 +1,85 @@ +// 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. + +#ifndef COMPONENTS_REMOTE_COCOA_APP_SHIM_SELECT_FILE_DIALOG_BRIDGE_H_ +#define COMPONENTS_REMOTE_COCOA_APP_SHIM_SELECT_FILE_DIALOG_BRIDGE_H_ + +#import <Cocoa/Cocoa.h> + +#include <vector> + +#include "base/callback.h" +#include "base/mac/scoped_nsobject.h" +#include "base/memory/weak_ptr.h" +#include "components/remote_cocoa/app_shim/remote_cocoa_app_shim_export.h" +#include "components/remote_cocoa/common/select_file_dialog.mojom.h" + +@class ExtensionDropdownHandler; +@class SelectFileDialogDelegate; + +namespace remote_cocoa { + +// This structure bridges from the C++ mojo SelectFileDialog to the Cocoa +// NSSavePanel. +class REMOTE_COCOA_APP_SHIM_EXPORT SelectFileDialogBridge + : public mojom::SelectFileDialog { + public: + // Callback made from the NSSavePanel's completion block. + using PanelEndedCallback = + base::OnceCallback<void(bool was_cancelled, + const std::vector<base::FilePath>& files, + int index)>; + + SelectFileDialogBridge(NSWindow* owning_window); + ~SelectFileDialogBridge() override; + + // mojom::SelectFileDialog: + void Show(mojom::SelectFileDialogType type, + const base::string16& title, + const base::FilePath& default_path, + mojom::SelectFileTypeInfoPtr file_types, + int file_type_index, + const base::FilePath::StringType& default_extension, + ShowCallback callback) override; + + // Return the most recently created NSSavePanel. There is no guarantee that + // this will be a valid pointer, and is only to be used to bridge across the + // mojo interface for testing. + static NSSavePanel* GetLastCreatedNativePanelForTesting(); + + private: + // Sets the accessory view for |dialog_| and sets + // |extension_dropdown_handler_|. + void SetAccessoryView(mojom::SelectFileTypeInfoPtr file_types, + int file_type_index, + const base::FilePath::StringType& default_extension); + + // Called when the panel completes. + void OnPanelEnded(bool did_cancel); + + // The callback to make when this dialog ends. + ShowCallback show_callback_; + + // Type type of this dialog. + mojom::SelectFileDialogType type_; + + // The NSSavePanel that |this| tracks. + base::scoped_nsobject<NSSavePanel> panel_; + + // The parent window for |panel_|. + base::scoped_nsobject<NSWindow> owning_window_; + + // The delegate for |panel|. + base::scoped_nsobject<SelectFileDialogDelegate> delegate_; + + // Extension dropdown handler corresponding to this file dialog. + base::scoped_nsobject<ExtensionDropdownHandler> extension_dropdown_handler_; + + base::WeakPtrFactory<SelectFileDialogBridge> weak_factory_; + DISALLOW_COPY_AND_ASSIGN(SelectFileDialogBridge); +}; + +} // namespace remote_cocoa + +#endif // COMPONENTS_REMOTE_COCOA_APP_SHIM_SELECT_FILE_DIALOG_BRIDGE_H_
diff --git a/components/remote_cocoa/app_shim/select_file_dialog_bridge.mm b/components/remote_cocoa/app_shim/select_file_dialog_bridge.mm new file mode 100644 index 0000000..17683b7 --- /dev/null +++ b/components/remote_cocoa/app_shim/select_file_dialog_bridge.mm
@@ -0,0 +1,413 @@ +// 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 "components/remote_cocoa/app_shim/select_file_dialog_bridge.h" + +#include <CoreServices/CoreServices.h> +#include <stddef.h> + +#include "base/files/file_util.h" +#include "base/i18n/case_conversion.h" +#include "base/mac/foundation_util.h" +#include "base/mac/scoped_cftyperef.h" +#include "base/strings/sys_string_conversions.h" +#include "base/strings/utf_string_conversions.h" +#import "ui/base/cocoa/controls/textfield_utils.h" +#include "ui/base/l10n/l10n_util_mac.h" +#include "ui/strings/grit/ui_strings.h" + +namespace { + +const int kFileTypePopupTag = 1234; + +CFStringRef CreateUTIFromExtension(const base::FilePath::StringType& ext) { + base::ScopedCFTypeRef<CFStringRef> ext_cf(base::SysUTF8ToCFStringRef(ext)); + return UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, + ext_cf.get(), NULL); +} + +NSString* GetDescriptionFromExtension(const base::FilePath::StringType& ext) { + base::ScopedCFTypeRef<CFStringRef> uti(CreateUTIFromExtension(ext)); + base::ScopedCFTypeRef<CFStringRef> description( + UTTypeCopyDescription(uti.get())); + + if (description && CFStringGetLength(description)) + return [[base::mac::CFToNSCast(description.get()) retain] autorelease]; + + // In case no description is found, create a description based on the + // unknown extension type (i.e. if the extension is .qqq, the we create + // a description "QQQ File (.qqq)"). + base::string16 ext_name = base::UTF8ToUTF16(ext); + return l10n_util::GetNSStringF(IDS_APP_SAVEAS_EXTENSION_FORMAT, + base::i18n::ToUpper(ext_name), ext_name); +} + +base::scoped_nsobject<NSView> CreateAccessoryView() { + static constexpr CGFloat kControlPadding = 2; + + base::scoped_nsobject<NSView> view( + [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 350, 60)]); + + // Create the label and center it vertically. + NSTextField* label = [TextFieldUtils + labelWithString:l10n_util::GetNSString( + IDS_SAVE_PAGE_FILE_FORMAT_PROMPT_MAC)]; + [label sizeToFit]; + NSRect label_frame = [label frame]; + label_frame.origin = + NSMakePoint(kControlPadding, NSMidY([view frame]) - NSMidY(label_frame)); + [label setFrame:label_frame]; + [view addSubview:label]; + + // Create the pop-up button, positioning it to the right of the label. + // Its X position needs to be slightly below the label's, so that the text + // baselines are aligned. + base::scoped_nsobject<NSPopUpButton> pop_up_button([[NSPopUpButton alloc] + initWithFrame:NSMakeRect(NSWidth(label_frame) + kControlPadding, + NSMinY(label_frame) - 5, 230, 25) + pullsDown:NO]); + [pop_up_button setTag:kFileTypePopupTag]; + [view addSubview:pop_up_button.get()]; + + // Resize the containing view to fit the controls. + CGFloat total_width = NSMaxX([pop_up_button frame]); + NSRect view_frame = [view frame]; + view_frame.size.width = total_width + kControlPadding; + [view setFrame:view_frame]; + + return view; +} + +NSSavePanel* g_last_created_panel_for_testing = nil; + +} // namespace + +// A bridge class to act as the modal delegate to the save/open sheet and send +// the results to the C++ class. +@interface SelectFileDialogDelegate : NSObject <NSOpenSavePanelDelegate> +@end + +// Target for NSPopupButton control in file dialog's accessory view. +@interface ExtensionDropdownHandler : NSObject { + @private + // The file dialog to which this target object corresponds. Weak reference + // since the dialog_ will stay alive longer than this object. + NSSavePanel* dialog_; + + // An array whose each item corresponds to an array of different extensions in + // an extension group. + base::scoped_nsobject<NSArray> fileTypeLists_; +} + +- (id)initWithDialog:(NSSavePanel*)dialog fileTypeLists:(NSArray*)fileTypeLists; + +- (void)popupAction:(id)sender; +@end + +@implementation SelectFileDialogDelegate + +- (BOOL)panel:(id)sender shouldEnableURL:(NSURL*)url { + return [url isFileURL]; +} + +- (BOOL)panel:(id)sender validateURL:(NSURL*)url error:(NSError**)outError { + // Refuse to accept users closing the dialog with a key repeat, since the key + // may have been first pressed while the user was looking at insecure content. + // See https://crbug.com/637098. + if ([[NSApp currentEvent] type] == NSKeyDown && + [[NSApp currentEvent] isARepeat]) { + return NO; + } + + return YES; +} + +@end + +@implementation ExtensionDropdownHandler + +- (id)initWithDialog:(NSSavePanel*)dialog + fileTypeLists:(NSArray*)fileTypeLists { + if ((self = [super init])) { + dialog_ = dialog; + fileTypeLists_.reset([fileTypeLists retain]); + } + return self; +} + +- (void)popupAction:(id)sender { + NSUInteger index = [sender indexOfSelectedItem]; + if (index < [fileTypeLists_ count]) { + // For save dialogs, this causes the first item in the allowedFileTypes + // array to be used as the extension for the save panel. + [dialog_ setAllowedFileTypes:[fileTypeLists_ objectAtIndex:index]]; + } else { + // The user selected "All files" option. + [dialog_ setAllowedFileTypes:nil]; + } +} + +@end + +namespace remote_cocoa { + +using mojom::SelectFileDialogType; +using mojom::SelectFileTypeInfoPtr; + +SelectFileDialogBridge::SelectFileDialogBridge(NSWindow* owning_window) + : owning_window_(owning_window, base::scoped_policy::RETAIN), + weak_factory_(this) {} + +SelectFileDialogBridge::~SelectFileDialogBridge() { + // If we never executed our callback, then the panel never closed. Cancel it + // now. + if (show_callback_) + [panel_ cancel:panel_]; + + // Balance the setDelegate called during Show. + [panel_ setDelegate:nil]; +} + +void SelectFileDialogBridge::Show( + SelectFileDialogType type, + const base::string16& title, + const base::FilePath& default_path, + SelectFileTypeInfoPtr file_types, + int file_type_index, + const base::FilePath::StringType& default_extension, + PanelEndedCallback initialize_callback) { + show_callback_ = std::move(initialize_callback); + type_ = type; + // Note: we need to retain the dialog as |owning_window_| can be null. + // (See http://crbug.com/29213 .) + if (type_ == SelectFileDialogType::kSaveAsFile) + panel_.reset([[NSSavePanel savePanel] retain]); + else + panel_.reset([[NSOpenPanel openPanel] retain]); + NSSavePanel* dialog = panel_.get(); + g_last_created_panel_for_testing = dialog; + + if (!title.empty()) + [dialog setMessage:base::SysUTF16ToNSString(title)]; + + NSString* default_dir = nil; + NSString* default_filename = nil; + if (!default_path.empty()) { + // The file dialog is going to do a ton of stats anyway. Not much + // point in eliminating this one. + base::ThreadRestrictions::ScopedAllowIO allow_io; + if (base::DirectoryExists(default_path)) { + default_dir = base::SysUTF8ToNSString(default_path.value()); + } else { + default_dir = base::SysUTF8ToNSString(default_path.DirName().value()); + default_filename = + base::SysUTF8ToNSString(default_path.BaseName().value()); + } + } + + if (type_ != SelectFileDialogType::kFolder && + type_ != SelectFileDialogType::kUploadFolder && + type_ != SelectFileDialogType::kExistingFolder) { + if (file_types) { + SetAccessoryView(std::move(file_types), file_type_index, + default_extension); + } else { + // If no type_ info is specified, anything goes. + [dialog setAllowsOtherFileTypes:YES]; + } + } + + if (type_ == SelectFileDialogType::kSaveAsFile) { + // When file extensions are hidden and removing the extension from + // the default filename gives one which still has an extension + // that OS X recognizes, it will get confused and think the user + // is trying to override the default extension. This happens with + // filenames like "foo.tar.gz" or "ball.of.tar.png". Work around + // this by never hiding extensions in that case. + base::FilePath::StringType penultimate_extension = + default_path.RemoveFinalExtension().FinalExtension(); + if (!penultimate_extension.empty()) { + [dialog setExtensionHidden:NO]; + } else { + [dialog setExtensionHidden:YES]; + [dialog setCanSelectHiddenExtension:YES]; + } + } else { + NSOpenPanel* open_dialog = base::mac::ObjCCastStrict<NSOpenPanel>(dialog); + + if (type_ == SelectFileDialogType::kOpenMultiFile) + [open_dialog setAllowsMultipleSelection:YES]; + else + [open_dialog setAllowsMultipleSelection:NO]; + + if (type_ == SelectFileDialogType::kFolder || + type_ == SelectFileDialogType::kUploadFolder || + type_ == SelectFileDialogType::kExistingFolder) { + [open_dialog setCanChooseFiles:NO]; + [open_dialog setCanChooseDirectories:YES]; + + if (type_ == SelectFileDialogType::kFolder) + [open_dialog setCanCreateDirectories:YES]; + else + [open_dialog setCanCreateDirectories:NO]; + + NSString* prompt = + (type_ == SelectFileDialogType::kUploadFolder) + ? l10n_util::GetNSString(IDS_SELECT_UPLOAD_FOLDER_BUTTON_TITLE) + : l10n_util::GetNSString(IDS_SELECT_FOLDER_BUTTON_TITLE); + [open_dialog setPrompt:prompt]; + } else { + [open_dialog setCanChooseFiles:YES]; + [open_dialog setCanChooseDirectories:NO]; + } + + delegate_.reset([[SelectFileDialogDelegate alloc] init]); + [open_dialog setDelegate:delegate_.get()]; + } + if (default_dir) + [dialog setDirectoryURL:[NSURL fileURLWithPath:default_dir]]; + if (default_filename) + [dialog setNameFieldStringValue:default_filename]; + + // Ensure that |callback| (rather than |this|) be retained by the block. + auto callback = base::BindRepeating(&SelectFileDialogBridge::OnPanelEnded, + weak_factory_.GetWeakPtr()); + [dialog beginSheetModalForWindow:owning_window_ + completionHandler:^(NSInteger result) { + callback.Run(result != NSFileHandlingPanelOKButton); + }]; +} + +void SelectFileDialogBridge::SetAccessoryView( + SelectFileTypeInfoPtr file_types, + int file_type_index, + const base::FilePath::StringType& default_extension) { + DCHECK(file_types); + base::scoped_nsobject<NSView> accessory_view = CreateAccessoryView(); + NSSavePanel* dialog = panel_.get(); + [dialog setAccessoryView:accessory_view.get()]; + + NSPopUpButton* popup = [accessory_view viewWithTag:kFileTypePopupTag]; + DCHECK(popup); + + // Create an array with each item corresponding to an array of different + // extensions in an extension group. + NSMutableArray* file_type_lists = [NSMutableArray array]; + int default_extension_index = -1; + for (size_t i = 0; i < file_types->extensions.size(); ++i) { + const std::vector<base::FilePath::StringType>& ext_list = + file_types->extensions[i]; + + // Generate type description for the extension group. + NSString* type_description = nil; + if (i < file_types->extension_description_overrides.size() && + !file_types->extension_description_overrides[i].empty()) { + type_description = base::SysUTF16ToNSString( + file_types->extension_description_overrides[i]); + } else { + // No description given for a list of extensions; pick the first one + // from the list (arbitrarily) and use its description. + DCHECK(!ext_list.empty()); + type_description = GetDescriptionFromExtension(ext_list[0]); + } + DCHECK_NE(0u, [type_description length]); + [popup addItemWithTitle:type_description]; + + // Populate file_type_lists. + // Set to store different extensions in the current extension group. + NSMutableSet* file_type_set = [NSMutableSet set]; + for (const base::FilePath::StringType& ext : ext_list) { + if (ext == default_extension) + default_extension_index = i; + + // Crash reports suggest that CreateUTIFromExtension may return nil. Hence + // we nil check before adding to |file_type_set|. See crbug.com/630101 and + // rdar://27490414. + base::ScopedCFTypeRef<CFStringRef> uti(CreateUTIFromExtension(ext)); + if (uti) + [file_type_set addObject:base::mac::CFToNSCast(uti.get())]; + + // Always allow the extension itself, in case the UTI doesn't map + // back to the original extension correctly. This occurs with dynamic + // UTIs on 10.7 and 10.8. + // See http://crbug.com/148840, http://openradar.me/12316273 + base::ScopedCFTypeRef<CFStringRef> ext_cf( + base::SysUTF8ToCFStringRef(ext)); + [file_type_set addObject:base::mac::CFToNSCast(ext_cf.get())]; + } + [file_type_lists addObject:[file_type_set allObjects]]; + } + + if (file_types->include_all_files || file_types->extensions.empty()) { + [popup addItemWithTitle:l10n_util::GetNSString(IDS_APP_SAVEAS_ALL_FILES)]; + [dialog setAllowsOtherFileTypes:YES]; + } + + extension_dropdown_handler_.reset([[ExtensionDropdownHandler alloc] + initWithDialog:dialog + fileTypeLists:file_type_lists]); + + // This establishes a weak reference to handler. Hence we persist it as part + // of dialog_data_list_. + [popup setTarget:extension_dropdown_handler_]; + [popup setAction:@selector(popupAction:)]; + + // file_type_index uses 1 based indexing. + if (file_type_index) { + DCHECK_LE(static_cast<size_t>(file_type_index), + file_types->extensions.size()); + DCHECK_GE(file_type_index, 1); + [popup selectItemAtIndex:file_type_index - 1]; + [extension_dropdown_handler_ popupAction:popup]; + } else if (!default_extension.empty() && default_extension_index != -1) { + [popup selectItemAtIndex:default_extension_index]; + [dialog + setAllowedFileTypes:@[ base::SysUTF8ToNSString(default_extension) ]]; + } else { + // Select the first item. + [popup selectItemAtIndex:0]; + [extension_dropdown_handler_ popupAction:popup]; + } +} + +void SelectFileDialogBridge::OnPanelEnded(bool did_cancel) { + if (!show_callback_) + return; + + int index = 0; + std::vector<base::FilePath> paths; + if (!did_cancel) { + if (type_ == SelectFileDialogType::kSaveAsFile) { + if ([[panel_ URL] isFileURL]) { + paths.push_back(base::mac::NSStringToFilePath([[panel_ URL] path])); + } + + NSView* accessoryView = [panel_ accessoryView]; + if (accessoryView) { + NSPopUpButton* popup = [accessoryView viewWithTag:kFileTypePopupTag]; + if (popup) { + // File type indexes are 1-based. + index = [popup indexOfSelectedItem] + 1; + } + } else { + index = 1; + } + } else { + CHECK([panel_ isKindOfClass:[NSOpenPanel class]]); + NSArray* urls = [static_cast<NSOpenPanel*>(panel_) URLs]; + for (NSURL* url in urls) + if ([url isFileURL]) + paths.push_back(base::FilePath(base::SysNSStringToUTF8([url path]))); + } + } + + std::move(show_callback_).Run(did_cancel, paths, index); +} + +// static +NSSavePanel* SelectFileDialogBridge::GetLastCreatedNativePanelForTesting() { + return g_last_created_panel_for_testing; +} + +} // namespace remote_cocoa
diff --git a/components/remote_cocoa/common/BUILD.gn b/components/remote_cocoa/common/BUILD.gn index 75794cc..a8da71b 100644 --- a/components/remote_cocoa/common/BUILD.gn +++ b/components/remote_cocoa/common/BUILD.gn
@@ -12,6 +12,7 @@ "application.mojom", "native_widget_ns_window.mojom", "native_widget_ns_window_host.mojom", + "select_file_dialog.mojom", "text_input_host.mojom", ]
diff --git a/components/remote_cocoa/common/select_file_dialog.mojom b/components/remote_cocoa/common/select_file_dialog.mojom new file mode 100644 index 0000000..31e9192 --- /dev/null +++ b/components/remote_cocoa/common/select_file_dialog.mojom
@@ -0,0 +1,44 @@ +// 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. + +module remote_cocoa.mojom; + +import "mojo/public/mojom/base/file_path.mojom"; +import "mojo/public/mojom/base/string16.mojom"; + +// The type of dialog to open. This corresponds to the subset of +// ui::SelectFileDialog::Type that is used on macOS. +enum SelectFileDialogType { + kFolder, + kUploadFolder, + kExistingFolder, + kOpenFile, + kOpenMultiFile, + kSaveAsFile +}; + +// Information about the file extensions to be shown in the dialog. +struct SelectFileTypeInfo { + // The list of allowed extensions. + array<array<string>> extensions; + + // Override of system descriptions of specified extensions. + array<mojo_base.mojom.String16> extension_description_overrides; + + // Specifies whether or not there is be a filter added for all files. + bool include_all_files; +}; + +// The interface to a file selection (Save As, Upload, etc) dialog. +interface SelectFileDialog { + // Show the dialog, and issue a callback when it has completed. + Show(SelectFileDialogType type, + mojo_base.mojom.String16 title, + mojo_base.mojom.FilePath file_path, + SelectFileTypeInfo? file_types, + int32 file_type_index, + string default_extension) => (bool was_cancelled, + array<mojo_base.mojom.FilePath> files, + int32 index); +};
diff --git a/components/signin/core/browser/account_fetcher_service.h b/components/signin/core/browser/account_fetcher_service.h index 82b8cd4..047b19f 100644 --- a/components/signin/core/browser/account_fetcher_service.h +++ b/components/signin/core/browser/account_fetcher_service.h
@@ -39,7 +39,7 @@ class ImageFetcherImpl; } // namespace image_fetcher -class AccountFetcherService : public OAuth2TokenService::Observer { +class AccountFetcherService : public OAuth2TokenServiceObserver { public: // Name of the preference that tracks the int64_t representation of the last // time the AccountTrackerService was updated. @@ -91,7 +91,7 @@ void SetIsChildAccount(const std::string& account_id, bool is_child_account); #endif - // OAuth2TokenService::Observer implementation. + // OAuth2TokenServiceObserver implementation. void OnRefreshTokenAvailable(const CoreAccountId& account_id) override; void OnRefreshTokenRevoked(const CoreAccountId& account_id) override; void OnRefreshTokensLoaded() override;
diff --git a/components/signin/core/browser/account_reconcilor.cc b/components/signin/core/browser/account_reconcilor.cc index 32fa9709..8ba2bb3 100644 --- a/components/signin/core/browser/account_reconcilor.cc +++ b/components/signin/core/browser/account_reconcilor.cc
@@ -854,16 +854,7 @@ } bool AccountReconcilor::IsIdentityManagerReady() { -#if defined(OS_CHROMEOS) - // TODO(droger): ChromeOS should use the same logic as other platforms. See - // https://crbug.com/749535 - // On ChromeOS, there are cases where the IdentityManager is never fully - // initialized and AreAllCredentialsLoaded() always return false. - return identity_manager_->AreRefreshTokensLoaded() || - (identity_manager_->GetAccountsWithRefreshTokens().size() > 0); -#else return identity_manager_->AreRefreshTokensLoaded(); -#endif } void AccountReconcilor::OnSetAccountsInCookieCompleted(
diff --git a/components/signin/core/browser/account_reconcilor_unittest.cc b/components/signin/core/browser/account_reconcilor_unittest.cc index 64509b2c..8c2f1ea 100644 --- a/components/signin/core/browser/account_reconcilor_unittest.cc +++ b/components/signin/core/browser/account_reconcilor_unittest.cc
@@ -1957,13 +1957,10 @@ AccountReconcilor* reconcilor = GetMockReconcilor(); reconcilor->StartReconcile(); -#if !defined(OS_CHROMEOS) - // No reconcile when tokens are not loaded, except on ChromeOS where reconcile - // can start as long as the token service is not empty. + // No reconcile when tokens are not loaded. ASSERT_FALSE(reconcilor->is_reconcile_started_); // When tokens are loaded, reconcile starts automatically. identity_test_env()->ReloadAccountsFromDisk(); -#endif if (!IsMultiloginEnabled()) { EXPECT_CALL(*GetMockReconcilor(), PerformMergeAction(account_id));
diff --git a/components/signin/core/browser/account_tracker_service_unittest.cc b/components/signin/core/browser/account_tracker_service_unittest.cc index 46eac21d..7b97724 100644 --- a/components/signin/core/browser/account_tracker_service_unittest.cc +++ b/components/signin/core/browser/account_tracker_service_unittest.cc
@@ -240,6 +240,7 @@ AccountTrackerService::RegisterPrefs(pref_service_.registry()); AccountFetcherService::RegisterPrefs(pref_service_.registry()); + ProfileOAuth2TokenService::RegisterProfilePrefs(pref_service_.registry()); } ~AccountTrackerServiceTest() override {} @@ -247,6 +248,7 @@ void SetUp() override { testing::Test::SetUp(); CreateAccountTracker(base::FilePath(), /*network_enabled=*/true); + fake_oauth2_token_service_.LoadCredentials(""); observer_.Clear(); }
diff --git a/components/signin/core/browser/mutable_profile_oauth2_token_service_delegate_unittest.cc b/components/signin/core/browser/mutable_profile_oauth2_token_service_delegate_unittest.cc index 29c92e4..9ece20e 100644 --- a/components/signin/core/browser/mutable_profile_oauth2_token_service_delegate_unittest.cc +++ b/components/signin/core/browser/mutable_profile_oauth2_token_service_delegate_unittest.cc
@@ -81,7 +81,7 @@ class MutableProfileOAuth2TokenServiceDelegateTest : public testing::Test, public OAuth2AccessTokenConsumer, - public OAuth2TokenService::Observer, + public OAuth2TokenServiceObserver, public OAuth2TokenService::DiagnosticsObserver, public WebDataServiceConsumer { public: @@ -187,7 +187,7 @@ access_token_failure_ = error; } - // OAuth2TokenService::Observer implementation. + // OAuth2TokenServiceObserver implementation. void OnRefreshTokenAvailable(const CoreAccountId& account_id) override { ++token_available_count_; } @@ -858,7 +858,7 @@ TEST_F(MutableProfileOAuth2TokenServiceDelegateTest, InvalidateTokensForMultilogin) { - class TokenServiceErrorObserver : public OAuth2TokenService::Observer { + class TokenServiceErrorObserver : public OAuth2TokenServiceObserver { public: MOCK_METHOD2(OnAuthErrorChanged, void(const CoreAccountId&, const GoogleServiceAuthError&)); @@ -1304,7 +1304,7 @@ // Checks that OnAuthErrorChanged() is called during UpdateCredentials(), and // that RefreshTokenIsAvailable() can be used at this time. TEST_F(MutableProfileOAuth2TokenServiceDelegateTest, OnAuthErrorChanged) { - class TokenServiceErrorObserver : public OAuth2TokenService::Observer { + class TokenServiceErrorObserver : public OAuth2TokenServiceObserver { public: explicit TokenServiceErrorObserver( MutableProfileOAuth2TokenServiceDelegate* delegate) @@ -1376,7 +1376,7 @@ // Regression test for https://crbug.com/824791. TEST_F(MutableProfileOAuth2TokenServiceDelegateTest, InvalidTokenObserverCallsOrdering) { - class TokenServiceErrorObserver : public OAuth2TokenService::Observer { + class TokenServiceErrorObserver : public OAuth2TokenServiceObserver { public: explicit TokenServiceErrorObserver( MutableProfileOAuth2TokenServiceDelegate* delegate)
diff --git a/components/signin/core/browser/oauth2_token_service_delegate_android_unittest.cc b/components/signin/core/browser/oauth2_token_service_delegate_android_unittest.cc index ea03519..884abc32 100644 --- a/components/signin/core/browser/oauth2_token_service_delegate_android_unittest.cc +++ b/components/signin/core/browser/oauth2_token_service_delegate_android_unittest.cc
@@ -27,7 +27,7 @@ MOCK_METHOD1(SetAccounts, void(const std::vector<CoreAccountId>&)); }; -class TestObserver : public OAuth2TokenService::Observer { +class TestObserver : public OAuth2TokenServiceObserver { public: MOCK_METHOD1(OnRefreshTokenAvailable, void(const CoreAccountId&)); MOCK_METHOD1(OnRefreshTokenRevoked, void(const CoreAccountId&));
diff --git a/components/signin/core/browser/primary_account_manager.h b/components/signin/core/browser/primary_account_manager.h index 2596c7b2..5056924 100644 --- a/components/signin/core/browser/primary_account_manager.h +++ b/components/signin/core/browser/primary_account_manager.h
@@ -40,7 +40,7 @@ class ProfileOAuth2TokenService; class SigninClient; -class PrimaryAccountManager : public OAuth2TokenService::Observer { +class PrimaryAccountManager : public OAuth2TokenServiceObserver { public: class Observer { public: @@ -218,7 +218,7 @@ // Send all observers |GoogleSignedOut| notifications. void FireGoogleSignedOut(const AccountInfo& account_info); - // OAuth2TokenService::Observer: + // OAuth2TokenServiceObserver: void OnRefreshTokensLoaded() override; #endif
diff --git a/components/signin/core/browser/profile_oauth2_token_service.cc b/components/signin/core/browser/profile_oauth2_token_service.cc index 3d218a3f..f1be157 100644 --- a/components/signin/core/browser/profile_oauth2_token_service.cc +++ b/components/signin/core/browser/profile_oauth2_token_service.cc
@@ -61,15 +61,11 @@ ProfileOAuth2TokenService::ProfileOAuth2TokenService( PrefService* user_prefs, std::unique_ptr<OAuth2TokenServiceDelegate> delegate) - : OAuth2TokenService(std::move(delegate)), - user_prefs_(user_prefs), - all_credentials_loaded_(false) { + : OAuth2TokenService(std::move(delegate)), user_prefs_(user_prefs) { DCHECK(user_prefs_); - AddObserver(this); } ProfileOAuth2TokenService::~ProfileOAuth2TokenService() { - RemoveObserver(this); } // static @@ -98,10 +94,6 @@ GetDelegate()->LoadCredentials(primary_account_id); } -bool ProfileOAuth2TokenService::AreAllCredentialsLoaded() { - return all_credentials_loaded_; -} - void ProfileOAuth2TokenService::UpdateCredentials( const std::string& account_id, const std::string& refresh_token, @@ -145,6 +137,8 @@ void ProfileOAuth2TokenService::OnRefreshTokenAvailable( const CoreAccountId& account_id) { + OAuth2TokenService::OnRefreshTokenAvailable(account_id); + // Check if the newly-updated token is valid (invalid tokens are inserted when // the user signs out on the web with DICE enabled). bool is_valid = true; @@ -170,6 +164,8 @@ void ProfileOAuth2TokenService::OnRefreshTokenRevoked( const CoreAccountId& account_id) { + OAuth2TokenService::OnRefreshTokenRevoked(account_id); + // If this was the last token, recreate the device ID. RecreateDeviceIdIfNeeded(); @@ -186,13 +182,13 @@ } void ProfileOAuth2TokenService::OnRefreshTokensLoaded() { + OAuth2TokenService::OnRefreshTokensLoaded(); + DCHECK_NE(OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_NOT_STARTED, GetDelegate()->load_credentials_state()); DCHECK_NE(OAuth2TokenServiceDelegate::LOAD_CREDENTIALS_IN_PROGRESS, GetDelegate()->load_credentials_state()); - all_credentials_loaded_ = true; - // Reset the state for update refresh token operations to Unknown as this // was the original state before LoadCredentials was called. update_refresh_token_source_ = SourceForRefreshTokenOperation::kUnknown;
diff --git a/components/signin/core/browser/profile_oauth2_token_service.h b/components/signin/core/browser/profile_oauth2_token_service.h index 3ab7b7e7..6961b06 100644 --- a/components/signin/core/browser/profile_oauth2_token_service.h +++ b/components/signin/core/browser/profile_oauth2_token_service.h
@@ -39,8 +39,7 @@ // // Note: requests should be started from the UI thread. To start a // request from other thread, please use OAuth2TokenServiceRequest. -class ProfileOAuth2TokenService : public OAuth2TokenService, - public OAuth2TokenService::Observer { +class ProfileOAuth2TokenService : public OAuth2TokenService { public: ProfileOAuth2TokenService( PrefService* user_prefs, @@ -61,9 +60,6 @@ // For a supervised user, the id comes from SupervisedUserService. void LoadCredentials(const std::string& primary_account_id); - // Returns true iff all credentials have been loaded from disk. - bool AreAllCredentialsLoaded(); - // Returns true if LoadCredentials finished with no errors. bool HasLoadCredentialsFinishedWithNoErrors(); @@ -98,10 +94,6 @@ const std::string& account_id); #endif - void set_all_credentials_loaded_for_testing(bool loaded) { - all_credentials_loaded_ = loaded; - } - // Exposes the ability to update auth errors to tests. void UpdateAuthErrorForTesting(const std::string& account_id, const GoogleServiceAuthError& error) { @@ -111,7 +103,7 @@ private: friend class identity::IdentityManager; - // OAuth2TokenService::Observer implementation. + // OAuth2TokenServiceObserver implementation. void OnRefreshTokenAvailable(const CoreAccountId& account_id) override; void OnRefreshTokenRevoked(const CoreAccountId& account_id) override; void OnRefreshTokensLoaded() override; @@ -122,9 +114,6 @@ PrefService* user_prefs_; - // Whether all credentials have been loaded. - bool all_credentials_loaded_; - signin_metrics::SourceForRefreshTokenOperation update_refresh_token_source_ = signin_metrics::SourceForRefreshTokenOperation::kUnknown;
diff --git a/components/signin/core/browser/profile_oauth2_token_service_delegate_chromeos.cc b/components/signin/core/browser/profile_oauth2_token_service_delegate_chromeos.cc index 5ff73d7..230d6b9 100644 --- a/components/signin/core/browser/profile_oauth2_token_service_delegate_chromeos.cc +++ b/components/signin/core/browser/profile_oauth2_token_service_delegate_chromeos.cc
@@ -290,7 +290,7 @@ DCHECK_EQ(LOAD_CREDENTIALS_IN_PROGRESS, load_credentials_state()); set_load_credentials_state(LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS); - // The typical order of |OAuth2TokenService::Observer| callbacks is: + // The typical order of |OAuth2TokenServiceObserver| callbacks is: // 1. OnRefreshTokenAvailable // 2. OnEndBatchChanges // 3. OnRefreshTokensLoaded @@ -341,7 +341,7 @@ ScopedBatchChange batch(this); FireRefreshTokenAvailable(account_id); - // See |OAuth2TokenService::Observer::OnAuthErrorChanged|. + // See |OAuth2TokenServiceObserver::OnAuthErrorChanged|. // |OnAuthErrorChanged| must be always called after // |OnRefreshTokenAvailable|, when refresh token is updated. FireAuthErrorChanged(account_id, error);
diff --git a/components/signin/core/browser/profile_oauth2_token_service_delegate_chromeos_unittest.cc b/components/signin/core/browser/profile_oauth2_token_service_delegate_chromeos_unittest.cc index 8b83f53b..84224fc 100644 --- a/components/signin/core/browser/profile_oauth2_token_service_delegate_chromeos_unittest.cc +++ b/components/signin/core/browser/profile_oauth2_token_service_delegate_chromeos_unittest.cc
@@ -59,16 +59,18 @@ DISALLOW_COPY_AND_ASSIGN(AccessTokenConsumer); }; -class TokenServiceObserver : public OAuth2TokenService::Observer { +class TestOAuth2TokenServiceObserver : public OAuth2TokenServiceObserver { public: // |delegate| is a non-owning pointer to an |OAuth2TokenServiceDelegate| that // MUST outlive |this| instance. - explicit TokenServiceObserver(OAuth2TokenServiceDelegate* delegate) + explicit TestOAuth2TokenServiceObserver(OAuth2TokenServiceDelegate* delegate) : delegate_(delegate) { delegate_->AddObserver(this); } - ~TokenServiceObserver() override { delegate_->RemoveObserver(this); } + ~TestOAuth2TokenServiceObserver() override { + delegate_->RemoveObserver(this); + } void StartBatchChanges() { EXPECT_FALSE(is_inside_batch_); @@ -229,7 +231,7 @@ &account_tracker_service_, network::TestNetworkConnectionTracker::GetInstance(), &account_manager, false /* is_regular_profile */); - TokenServiceObserver observer(delegate.get()); + TestOAuth2TokenServiceObserver observer(delegate.get()); // Test that LoadCredentials works as expected. EXPECT_FALSE(observer.refresh_tokens_loaded_); @@ -276,7 +278,7 @@ } TEST_F(CrOSOAuthDelegateTest, ObserversAreNotifiedOnAuthErrorChange) { - TokenServiceObserver observer(delegate_.get()); + TestOAuth2TokenServiceObserver observer(delegate_.get()); auto error = GoogleServiceAuthError(GoogleServiceAuthError::State::SERVICE_ERROR); @@ -287,7 +289,7 @@ } TEST_F(CrOSOAuthDelegateTest, ObserversAreNotifiedOnCredentialsInsertion) { - TokenServiceObserver observer(delegate_.get()); + TestOAuth2TokenServiceObserver observer(delegate_.get()); delegate_->UpdateCredentials(account_info_.account_id, kGaiaToken); EXPECT_EQ(1UL, observer.account_ids_.size()); @@ -298,7 +300,7 @@ TEST_F(CrOSOAuthDelegateTest, ObserversDoNotSeeCachedErrorsOnCredentialsUpdate) { - TokenServiceObserver observer(delegate_.get()); + TestOAuth2TokenServiceObserver observer(delegate_.get()); auto error = GoogleServiceAuthError(GoogleServiceAuthError::State::SERVICE_ERROR); delegate_->UpdateCredentials(account_info_.account_id, kGaiaToken); @@ -310,7 +312,7 @@ } TEST_F(CrOSOAuthDelegateTest, DummyTokensArePreEmptivelyRejected) { - TokenServiceObserver observer(delegate_.get()); + TestOAuth2TokenServiceObserver observer(delegate_.get()); delegate_->UpdateCredentials(account_info_.account_id, chromeos::AccountManager::kInvalidToken); @@ -328,7 +330,7 @@ } TEST_F(CrOSOAuthDelegateTest, ObserversAreNotifiedOnCredentialsUpdate) { - TokenServiceObserver observer(delegate_.get()); + TestOAuth2TokenServiceObserver observer(delegate_.get()); delegate_->UpdateCredentials(account_info_.account_id, kGaiaToken); EXPECT_EQ(1UL, observer.account_ids_.size()); @@ -339,7 +341,7 @@ TEST_F(CrOSOAuthDelegateTest, ObserversAreNotNotifiedIfCredentialsAreNotUpdated) { - TokenServiceObserver observer(delegate_.get()); + TestOAuth2TokenServiceObserver observer(delegate_.get()); delegate_->UpdateCredentials(account_info_.account_id, kGaiaToken); observer.account_ids_.clear(); @@ -352,7 +354,7 @@ TEST_F(CrOSOAuthDelegateTest, BatchChangeObserversAreNotifiedOnCredentialsUpdate) { - TokenServiceObserver observer(delegate_.get()); + TestOAuth2TokenServiceObserver observer(delegate_.get()); delegate_->UpdateCredentials(account_info_.account_id, kGaiaToken); EXPECT_EQ(1UL, observer.batch_change_records_.size()); @@ -393,7 +395,7 @@ network::TestNetworkConnectionTracker::GetInstance(), &account_manager, true /* is_regular_profile */); delegate->LoadCredentials(account1.account_id /* primary_account_id */); - TokenServiceObserver observer(delegate.get()); + TestOAuth2TokenServiceObserver observer(delegate.get()); // Wait until chromeos::AccountManager is fully initialized. task_environment_.RunUntilIdle(); @@ -497,7 +499,7 @@ TEST_F(CrOSOAuthDelegateTest, ObserversAreNotifiedOnAccountRemoval) { delegate_->UpdateCredentials(account_info_.account_id, kGaiaToken); - TokenServiceObserver observer(delegate_.get()); + TestOAuth2TokenServiceObserver observer(delegate_.get()); account_manager_.RemoveAccount(gaia_account_key_); EXPECT_EQ(1UL, observer.batch_change_records_.size());
diff --git a/components/signin/ios/browser/profile_oauth2_token_service_ios_delegate_unittest.mm b/components/signin/ios/browser/profile_oauth2_token_service_ios_delegate_unittest.mm index b9627c1..4ac4d661 100644 --- a/components/signin/ios/browser/profile_oauth2_token_service_ios_delegate_unittest.mm +++ b/components/signin/ios/browser/profile_oauth2_token_service_ios_delegate_unittest.mm
@@ -29,7 +29,7 @@ class ProfileOAuth2TokenServiceIOSDelegateTest : public testing::Test, public OAuth2AccessTokenConsumer, - public OAuth2TokenService::Observer { + public OAuth2TokenServiceObserver { public: ProfileOAuth2TokenServiceIOSDelegateTest() : factory_(NULL), @@ -75,7 +75,7 @@ last_access_token_error_ = error; } - // OAuth2TokenService::Observer implementation. + // OAuth2TokenServiceObserver implementation. void OnRefreshTokenAvailable(const CoreAccountId& account_id) override { ++token_available_count_; }
diff --git a/components/test/data/omnibox/Shortcuts.v1.sql b/components/test/data/omnibox/Shortcuts.v1.sql index 0c96e554..8b51c93a 100644 --- a/components/test/data/omnibox/Shortcuts.v1.sql +++ b/components/test/data/omnibox/Shortcuts.v1.sql
@@ -1,9 +1,11 @@ PRAGMA foreign_keys=OFF; BEGIN TRANSACTION; -CREATE TABLE omni_box_shortcuts ( id VARCHAR PRIMARY KEY, text VARCHAR, url VARCHAR, contents VARCHAR, contents_class VARCHAR, description VARCHAR, description_class VARCHAR, last_access_time INTEGER, number_of_hits INTEGER); -INSERT INTO "omni_box_shortcuts" VALUES('34A7401D-0DC5-4A8F-A6B5-3FA4FF786C42','sha','http://shacknews.com/','shacknews.com','0,1','Video Game News and Features - Video Game News, Videos, and File Downloads for PC and Console Games at Shacknews.com','0,0',13024194201806179,3); -INSERT INTO "omni_box_shortcuts" VALUES('9EA31BB8-8528-4AE0-A6B1-FD06458DFC31','shacknews','http://shacknews.com/','shacknews.com','0,1','Video Game News and Features - Video Game News, Videos, and File Downloads for PC and Console Games at Shacknews.com','0,0',13024456716613368,4); -INSERT INTO "omni_box_shortcuts" VALUES('CD853DC4-7C4E-4E64-903D-A4BBCAA410F9','shacknews.com','http://shacknews.com/','shacknews.com','0,1','Video Game News and Features - Video Game News, Videos, and File Downloads for PC and Console Games at Shacknews.com','0,0',13024196901413541,1); -INSERT INTO "omni_box_shortcuts" VALUES('377314F7-E3AB-4264-8F3F-3404BE48DADB','echo echo','chrome-extension://cedabbhfglmiikkmdgcpjdkocfcmbkee/?q=echo','Run Echo command: echo','0,0','Echo','0,4',13025401559133998,2); -INSERT INTO "omni_box_shortcuts" VALUES('BCE200CA-01E9-4A2F-B5EC-2D561DDFBE41','echo','chrome-extension://cedabbhfglmiikkmdgcpjdkocfcmbkee/?q=frobber','Run Echo command: frobber','0,0','Echo','0,4',13025413423801769,2); +CREATE TABLE omni_box_shortcuts ( id VARCHAR PRIMARY KEY, text VARCHAR, url VARCHAR, contents VARCHAR, contents_class VARCHAR, description VARCHAR, description_class VARCHAR, last_access_time INTEGER, number_of_hits INTEGER, fill_into_edit VARCHAR, transition INTEGER, type INTEGER, keyword VARCHAR); +INSERT INTO "omni_box_shortcuts" VALUES('34A7401D-0DC5-4A8F-A6B5-3FA4FF786C42','sha','http://shacknews.com/','shacknews.com','0,1','Video Game News and Features - Video Game News, Videos, and File Downloads for PC and Console Games at Shacknews.com','0,0',13024194201806179,3,'http://shacknews.com',1,2,NULL); +INSERT INTO "omni_box_shortcuts" VALUES('9EA31BB8-8528-4AE0-A6B1-FD06458DFC31','shacknews','http://shacknews.com/','shacknews.com','0,1','Video Game News and Features - Video Game News, Videos, and File Downloads for PC and Console Games at Shacknews.com','0,0',13024456716613368,4,'http://shacknews.com',1,2,NULL); +INSERT INTO "omni_box_shortcuts" VALUES('CD853DC4-7C4E-4E64-903D-A4BBCAA410F9','shacknews.com','http://shacknews.com/','shacknews.com','0,1','Video Game News and Features - Video Game News, Videos, and File Downloads for PC and Console Games at Shacknews.com','0,0',13024196901413541,1,'http://shacknews.com',1,2,NULL); +INSERT INTO "omni_box_shortcuts" VALUES('377314F7-E3AB-4264-8F3F-3404BE48DADB','echo echo','chrome-extension://cedabbhfglmiikkmdgcpjdkocfcmbkee/?q=echo','Run Echo command: echo','0,0','Echo','0,4',13025401559133998,2,'http://shacknews.com',1,2,NULL); +INSERT INTO "omni_box_shortcuts" VALUES('BCE200CA-01E9-4A2F-B5EC-2D561DDFBE41','echo','chrome-extension://cedabbhfglmiikkmdgcpjdkocfcmbkee/?q=frobber','Run Echo command: frobber','0,0','Echo','0,4',13025413423801769,2,'http://shacknews.com',1,2,NULL); +INSERT INTO "omni_box_shortcuts" VALUES('B07F4744-F008-3C87-37E4-9D284AD9A697','yahoo.com other keyword','http://search.yahoo.com/search?ei=UTF-8&fr=crmas&p=other+keyword','other keyword','0,0','Yahoo! Search','0,4',13036572535614255,1,'yahoo.com other keyword',9,13,'yahoo.com'); +INSERT INTO "omni_box_shortcuts" VALUES('9CBB669D-B7F0-5AFF-D808-EFFF7028B159','rdt','http://www.reddit.com/','www.reddit.com/','0,1','rdt','0,0',13036574229966419,1,'www.reddit.com/',1,16,''); COMMIT;
diff --git a/components/viz/host/layered_window_updater_impl.cc b/components/viz/host/layered_window_updater_impl.cc index d3a49ed8..65c26e2 100644 --- a/components/viz/host/layered_window_updater_impl.cc +++ b/components/viz/host/layered_window_updater_impl.cc
@@ -4,7 +4,6 @@ #include "components/viz/host/layered_window_updater_impl.h" -#include "base/memory/shared_memory.h" #include "components/viz/common/resources/resource_format.h" #include "components/viz/common/resources/resource_sizes.h" #include "mojo/public/cpp/system/platform_handle.h" @@ -23,9 +22,12 @@ void LayeredWindowUpdaterImpl::OnAllocatedSharedMemory( const gfx::Size& pixel_size, - mojo::ScopedSharedBufferHandle scoped_buffer_handle) { + base::UnsafeSharedMemoryRegion region) { canvas_.reset(); + if (!region.IsValid()) + return; + // Make sure |pixel_size| is sane. size_t expected_bytes; bool size_result = ResourceSizes::MaybeSizeInBytes( @@ -33,18 +35,12 @@ if (!size_result) return; - base::SharedMemoryHandle shm_handle; - MojoResult unwrap_result = mojo::UnwrapSharedMemoryHandle( - std::move(scoped_buffer_handle), &shm_handle, nullptr, nullptr); - if (unwrap_result != MOJO_RESULT_OK) - return; - // The SkCanvas maps shared memory on creation and unmaps on destruction. canvas_ = skia::CreatePlatformCanvasWithSharedSection( - pixel_size.width(), pixel_size.height(), true, shm_handle.GetHandle(), + pixel_size.width(), pixel_size.height(), true, region.GetPlatformHandle(), skia::RETURN_NULL_ON_FAILURE); - shm_handle.Close(); + // |region|'s handle will close when it goes out of scope. } void LayeredWindowUpdaterImpl::Draw(DrawCallback draw_callback) {
diff --git a/components/viz/host/layered_window_updater_impl.h b/components/viz/host/layered_window_updater_impl.h index 93c52d2b..d9a9730 100644 --- a/components/viz/host/layered_window_updater_impl.h +++ b/components/viz/host/layered_window_updater_impl.h
@@ -10,6 +10,7 @@ #include <memory> #include "base/macros.h" +#include "base/memory/unsafe_shared_memory_region.h" #include "components/viz/host/viz_host_export.h" #include "mojo/public/cpp/bindings/binding.h" #include "services/viz/privileged/interfaces/compositing/layered_window_updater.mojom.h" @@ -30,9 +31,8 @@ ~LayeredWindowUpdaterImpl() override; // mojom::LayeredWindowUpdater implementation. - void OnAllocatedSharedMemory( - const gfx::Size& pixel_size, - mojo::ScopedSharedBufferHandle scoped_buffer_handle) override; + void OnAllocatedSharedMemory(const gfx::Size& pixel_size, + base::UnsafeSharedMemoryRegion region) override; void Draw(DrawCallback draw_callback) override; private:
diff --git a/components/viz/service/display_embedder/output_device_backing.cc b/components/viz/service/display_embedder/output_device_backing.cc index f261cf0..f3ee9aff 100644 --- a/components/viz/service/display_embedder/output_device_backing.cc +++ b/components/viz/service/display_embedder/output_device_backing.cc
@@ -44,12 +44,12 @@ if (GetMaxViewportBytes() == created_shm_bytes_) return; - // Otherwise we need to allocate a new SharedMemory segment and clients + // Otherwise we need to allocate a new shared memory region and clients // should re-request it. for (auto* client : clients_) client->ReleaseCanvas(); - shm_.reset(); + region_ = {}; created_shm_bytes_ = 0; } @@ -63,7 +63,7 @@ ClientResized(); } -base::SharedMemory* OutputDeviceBacking::GetSharedMemory( +base::UnsafeSharedMemoryRegion* OutputDeviceBacking::GetSharedMemoryRegion( const gfx::Size& viewport_size) { // If |viewport_size| is empty or too big don't try to allocate SharedMemory. size_t viewport_bytes; @@ -71,20 +71,20 @@ return nullptr; // Allocate a new SharedMemory segment that can fit the largest viewport. - if (!shm_) { + if (!region_.IsValid()) { size_t max_viewport_bytes = GetMaxViewportBytes(); DCHECK_LE(viewport_bytes, max_viewport_bytes); - shm_ = std::make_unique<base::SharedMemory>(); base::debug::Alias(&max_viewport_bytes); - CHECK(shm_->CreateAnonymous(max_viewport_bytes)); + region_ = base::UnsafeSharedMemoryRegion::Create(max_viewport_bytes); + CHECK(region_.IsValid()); created_shm_bytes_ = max_viewport_bytes; } else { // Clients must call Resize() for new |viewport_size|. DCHECK_LE(viewport_bytes, created_shm_bytes_); } - return shm_.get(); + return ®ion_; } size_t OutputDeviceBacking::GetMaxViewportBytes() {
diff --git a/components/viz/service/display_embedder/output_device_backing.h b/components/viz/service/display_embedder/output_device_backing.h index b3a9b1c..a21a712 100644 --- a/components/viz/service/display_embedder/output_device_backing.h +++ b/components/viz/service/display_embedder/output_device_backing.h
@@ -9,6 +9,7 @@ #include <vector> #include "base/macros.h" +#include "base/memory/unsafe_shared_memory_region.h" #include "components/viz/service/viz_service_export.h" #include "ui/gfx/geometry/size.h" @@ -44,9 +45,10 @@ void ClientResized(); // Requests a SharedMemory segment large enough to fit |viewport_size|. Will - // return null if |viewport_size| is too large to safely allocate SharedMemory - // for. - base::SharedMemory* GetSharedMemory(const gfx::Size& viewport_size); + // return null if |viewport_size| is too large to safely allocate + // a shared memory region. + base::UnsafeSharedMemoryRegion* GetSharedMemoryRegion( + const gfx::Size& viewport_size); // Returns the maximum size in bytes needed for the largest viewport from // registered clients. @@ -54,7 +56,7 @@ private: std::vector<Client*> clients_; - std::unique_ptr<base::SharedMemory> shm_; + base::UnsafeSharedMemoryRegion region_; size_t created_shm_bytes_ = 0; DISALLOW_COPY_AND_ASSIGN(OutputDeviceBacking);
diff --git a/components/viz/service/display_embedder/output_device_backing_unittest.cc b/components/viz/service/display_embedder/output_device_backing_unittest.cc index 91657333..2ea317c 100644 --- a/components/viz/service/display_embedder/output_device_backing_unittest.cc +++ b/components/viz/service/display_embedder/output_device_backing_unittest.cc
@@ -27,7 +27,7 @@ : backing_(backing), viewport_size_(viewport_size) { backing_->RegisterClient(this); backing_->ClientResized(); - backing_->GetSharedMemory(viewport_size_); + backing_->GetSharedMemoryRegion(viewport_size_); } ~TestBackingClient() override { backing_->UnregisterClient(this); } @@ -96,17 +96,17 @@ OutputDeviceBacking backing; // The viewport is bigger than |kMaxBitmapSizeBytes| and OutputDeviceBacking - // won't try to create SharedMemory for it. + // won't try to create a shared memory region for it. TestBackingClient client_a(&backing, gfx::Size(16385, 8193)); - EXPECT_EQ(nullptr, backing.GetSharedMemory(client_a.viewport_size())); + EXPECT_EQ(nullptr, backing.GetSharedMemoryRegion(client_a.viewport_size())); - // This should cause SharedMemory to get allocated. + // This should cause a region to get allocated. TestBackingClient client_b(&backing, gfx::Size(1024, 768)); - EXPECT_NE(nullptr, backing.GetSharedMemory(client_b.viewport_size())); + EXPECT_NE(nullptr, backing.GetSharedMemoryRegion(client_b.viewport_size())); // Even though SharedMemory was allocated to fit |client_b|, it will be too - // small for |client_a| and GetSharedMemory() should still return null. - EXPECT_EQ(nullptr, backing.GetSharedMemory(client_a.viewport_size())); + // small for |client_a| and GetSharedMemoryRegion() should still return null. + EXPECT_EQ(nullptr, backing.GetSharedMemoryRegion(client_a.viewport_size())); } } // namespace viz
diff --git a/components/viz/service/display_embedder/software_output_device_win.cc b/components/viz/service/display_embedder/software_output_device_win.cc index 4e3f0255..73ea198 100644 --- a/components/viz/service/display_embedder/software_output_device_win.cc +++ b/components/viz/service/display_embedder/software_output_device_win.cc
@@ -5,7 +5,7 @@ #include "components/viz/service/display_embedder/software_output_device_win.h" #include "base/bind.h" -#include "base/memory/shared_memory.h" +#include "base/memory/unsafe_shared_memory_region.h" #include "base/threading/thread_checker.h" #include "base/win/windows_version.h" #include "components/viz/common/display/use_layered_window.h" @@ -144,12 +144,12 @@ if (!canvas_) { // Share pixel backing with other SoftwareOutputDeviceWinDirect instances. // All work happens on the same thread so this is safe. - base::SharedMemory* memory = - backing_->GetSharedMemory(viewport_pixel_size_); - if (memory) { + base::UnsafeSharedMemoryRegion* region = + backing_->GetSharedMemoryRegion(viewport_pixel_size_); + if (region && region->IsValid()) { canvas_ = skia::CreatePlatformCanvasWithSharedSection( viewport_pixel_size_.width(), viewport_pixel_size_.height(), true, - memory->handle().GetHandle(), skia::CRASH_ON_FAILURE); + region->GetPlatformHandle(), skia::CRASH_ON_FAILURE); } } return canvas_.get(); @@ -173,8 +173,8 @@ // SoftwareOutputDevice implementation that uses layered window API to draw // indirectly. Since UpdateLayeredWindow() is blocked by the GPU sandbox an // implementation of mojom::LayeredWindowUpdater in the browser process handles -// calling UpdateLayeredWindow. Pixel backing is in SharedMemory so no copying -// between processes is required. +// calling UpdateLayeredWindow. Pixel backing is in a SharedMemoryRegion so no +// copying between processes is required. class SoftwareOutputDeviceWinProxy : public SoftwareOutputDeviceWinBase { public: SoftwareOutputDeviceWinProxy( @@ -237,8 +237,9 @@ return; } - base::SharedMemory shm; - if (!shm.CreateAnonymous(required_bytes)) { + base::UnsafeSharedMemoryRegion region = + base::UnsafeSharedMemoryRegion::Create(required_bytes); + if (!region.IsValid()) { DLOG(ERROR) << "Failed to allocate " << required_bytes << " bytes"; return; } @@ -246,15 +247,11 @@ // The SkCanvas maps shared memory on creation and unmaps on destruction. canvas_ = skia::CreatePlatformCanvasWithSharedSection( viewport_pixel_size_.width(), viewport_pixel_size_.height(), true, - shm.handle().GetHandle(), skia::CRASH_ON_FAILURE); + region.GetPlatformHandle(), skia::CRASH_ON_FAILURE); - // Transfer handle ownership to the browser process. - mojo::ScopedSharedBufferHandle scoped_handle = mojo::WrapSharedMemoryHandle( - shm.TakeHandle(), required_bytes, - mojo::UnwrappedSharedMemoryHandleProtection::kReadWrite); - + // Transfer region ownership to the browser process. layered_window_updater_->OnAllocatedSharedMemory(viewport_pixel_size_, - std::move(scoped_handle)); + std::move(region)); } SkCanvas* SoftwareOutputDeviceWinProxy::BeginPaintDelegated() {
diff --git a/content/browser/browser_child_process_host_impl.cc b/content/browser/browser_child_process_host_impl.cc index ff5e049..481c063 100644 --- a/content/browser/browser_child_process_host_impl.cc +++ b/content/browser/browser_child_process_host_impl.cc
@@ -568,13 +568,6 @@ break; default: - // Report new processes. "Custom" ones are renumbered to 1000+ so that - // they won't conflict with any standard ones in the future. - int process_type = data_.process_type; - if (process_type >= PROCESS_TYPE_CONTENT_END) - process_type += 1000 - PROCESS_TYPE_CONTENT_END; - base::UmaHistogramSparse( - "UMA.SubprocessMetricsProvider.UntrackedProcesses", process_type); return; }
diff --git a/content/browser/compositor/surface_utils.cc b/content/browser/compositor/surface_utils.cc index 6e928608..ed52592 100644 --- a/content/browser/compositor/surface_utils.cc +++ b/content/browser/compositor/surface_utils.cc
@@ -19,7 +19,7 @@ viz::FrameSinkId AllocateFrameSinkId() { #if defined(OS_ANDROID) - return CompositorDependencies::Get().AllocateFrameSinkId(); + return CompositorDependenciesAndroid::Get().AllocateFrameSinkId(); #else ImageTransportFactory* factory = ImageTransportFactory::GetInstance(); return factory->GetContextFactoryPrivate()->AllocateFrameSinkId(); @@ -28,7 +28,7 @@ viz::FrameSinkManagerImpl* GetFrameSinkManager() { #if defined(OS_ANDROID) - return CompositorDependencies::Get().frame_sink_manager_impl(); + return CompositorDependenciesAndroid::Get().frame_sink_manager_impl(); #else ImageTransportFactory* factory = ImageTransportFactory::GetInstance(); if (!factory) @@ -39,7 +39,7 @@ viz::HostFrameSinkManager* GetHostFrameSinkManager() { #if defined(OS_ANDROID) - return CompositorDependencies::Get().host_frame_sink_manager(); + return CompositorDependenciesAndroid::Get().host_frame_sink_manager(); #else ImageTransportFactory* factory = ImageTransportFactory::GetInstance(); if (!factory)
diff --git a/content/browser/frame_host/render_frame_host_impl.cc b/content/browser/frame_host/render_frame_host_impl.cc index 25cb7dcf..c7245425 100644 --- a/content/browser/frame_host/render_frame_host_impl.cc +++ b/content/browser/frame_host/render_frame_host_impl.cc
@@ -6594,25 +6594,18 @@ // same-document navigations. is_commit_allowed_to_proceed |= is_same_document_navigation; - // 3) This was a navigation to a subframe in an MHTML archive. - is_commit_allowed_to_proceed |= - GetParent() && frame_tree_node_->frame_tree() - ->root() - ->current_frame_host() - ->is_mhtml_document(); - - // 4) Transient interstitial page commits will not have a matching + // 3) Transient interstitial page commits will not have a matching // NavigationRequest. // TODO(clamy): Enforce having a NavigationRequest for data URLs when // committed interstitials have launched or interstitials create // NavigationRequests. is_commit_allowed_to_proceed |= !!delegate_->GetAsInterstitialPage(); - // 5) Error pages implementations in Chrome can commit twice. + // 4) Error pages implementations in Chrome can commit twice. // TODO(clamy): Fix this. is_commit_allowed_to_proceed |= validated_params->url_is_unreachable; - // 6) Special case for DOMSerializerBrowsertests which are implemented + // 5) Special case for DOMSerializerBrowsertests which are implemented // entirely renderer-side and unlike normal RenderView based tests load // file URLs instead of data URLs. // TODO(clamy): Rework the tests to remove this exception.
diff --git a/content/browser/navigation_mhtml_browsertest.cc b/content/browser/navigation_mhtml_browsertest.cc index 27d561d..a9722a9 100644 --- a/content/browser/navigation_mhtml_browsertest.cc +++ b/content/browser/navigation_mhtml_browsertest.cc
@@ -409,4 +409,31 @@ EXPECT_FALSE(iframe_navigation.is_error()); } +// Tests Content-Security-Policy: frame-ancestors enforcement in MHTML +// subframes. It isn't enforced currently. +// See https://crbug.com/969711. +IN_PROC_BROWSER_TEST_F(NavigationMhtmlBrowserTest, CspFrameAncestor) { + MhtmlArchive mhtml_archive; + mhtml_archive.AddHtmlDocument( + GURL("http://example.com/main"), + "<iframe src=\"http://example.com/subframe\"></iframe>"); + mhtml_archive.AddHtmlDocument( + GURL("http://example.com/subframe"), + "Content-Security-Policy: frame-ancestors 'none'\n", "<iframe></iframe>"); + GURL mhtml_url = mhtml_archive.Write("index.mhtml"); + + EXPECT_TRUE(NavigateToURL(shell(), mhtml_url)); + + RenderFrameHostImpl* main_frame = main_frame_host(); + ASSERT_EQ(1u, main_frame->child_count()); + RenderFrameHostImpl* sub_frame = + main_frame->child_at(0)->current_frame_host(); + + // Currently, frame-ancestors is not enforced. See https://crbug.com/969711. + // Check that the iframe is properly loaded. EvalJs("document.body.innerHTML") + // can't be used, because javascript is disabled. Instead, check it was able + // to load an iframe. + ASSERT_EQ(1u, sub_frame->child_count()); +} + } // namespace content
diff --git a/content/browser/renderer_host/compositor_dependencies_android.cc b/content/browser/renderer_host/compositor_dependencies_android.cc index 4cb2f96..47123b1 100644 --- a/content/browser/renderer_host/compositor_dependencies_android.cc +++ b/content/browser/renderer_host/compositor_dependencies_android.cc
@@ -70,12 +70,12 @@ } // namespace // static -CompositorDependencies& CompositorDependencies::Get() { - static base::NoDestructor<CompositorDependencies> instance; +CompositorDependenciesAndroid& CompositorDependenciesAndroid::Get() { + static base::NoDestructor<CompositorDependenciesAndroid> instance; return *instance; } -CompositorDependencies::CompositorDependencies() +CompositorDependenciesAndroid::CompositorDependenciesAndroid() : frame_sink_id_allocator_(kDefaultClientId) { DCHECK_CURRENTLY_ON(BrowserThread::UI); @@ -92,9 +92,9 @@ } } -CompositorDependencies::~CompositorDependencies() = default; +CompositorDependenciesAndroid::~CompositorDependenciesAndroid() = default; -void CompositorDependencies::CreateVizFrameSinkManager() { +void CompositorDependenciesAndroid::CreateVizFrameSinkManager() { viz::mojom::FrameSinkManagerPtr frame_sink_manager; viz::mojom::FrameSinkManagerRequest frame_sink_manager_request = mojo::MakeRequest(&frame_sink_manager); @@ -109,28 +109,29 @@ // Set up a callback to automatically re-connect if we lose our // connection. - host_frame_sink_manager_.SetConnectionLostCallback(base::BindRepeating( - []() { CompositorDependencies::Get().CreateVizFrameSinkManager(); })); + host_frame_sink_manager_.SetConnectionLostCallback(base::BindRepeating([]() { + CompositorDependenciesAndroid::Get().CreateVizFrameSinkManager(); + })); // Set up a pending request which will be run once we've successfully // connected to the GPU process. pending_connect_viz_on_io_thread_ = base::BindOnce( - &CompositorDependencies::ConnectVizFrameSinkManagerOnIOThread, + &CompositorDependenciesAndroid::ConnectVizFrameSinkManagerOnIOThread, std::move(frame_sink_manager_request), frame_sink_manager_client.PassInterface()); } -cc::TaskGraphRunner* CompositorDependencies::GetTaskGraphRunner() { +cc::TaskGraphRunner* CompositorDependenciesAndroid::GetTaskGraphRunner() { if (!task_graph_runner_) task_graph_runner_ = std::make_unique<SingleThreadTaskGraphRunner>(); return task_graph_runner_.get(); } -viz::FrameSinkId CompositorDependencies::AllocateFrameSinkId() { +viz::FrameSinkId CompositorDependenciesAndroid::AllocateFrameSinkId() { return frame_sink_id_allocator_.NextFrameSinkId(); } -void CompositorDependencies::TryEstablishVizConnectionIfNeeded() { +void CompositorDependenciesAndroid::TryEstablishVizConnectionIfNeeded() { if (!pending_connect_viz_on_io_thread_) return; base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, @@ -142,7 +143,7 @@ // established and lost. In this case the ConnectionLost callback will be // re-run when the request is deleted (goes out of scope). // static -void CompositorDependencies::ConnectVizFrameSinkManagerOnIOThread( +void CompositorDependenciesAndroid::ConnectVizFrameSinkManagerOnIOThread( viz::mojom::FrameSinkManagerRequest request, viz::mojom::FrameSinkManagerClientPtrInfo client) { auto* gpu_process_host = GpuProcessHost::Get(); @@ -152,18 +153,18 @@ std::move(client)); } -void CompositorDependencies::EnqueueLowEndBackgroundCleanup() { +void CompositorDependenciesAndroid::EnqueueLowEndBackgroundCleanup() { if (base::SysInfo::IsLowEndDevice()) { - low_end_background_cleanup_task_.Reset( - base::BindOnce(&CompositorDependencies::DoLowEndBackgroundCleanup, - base::Unretained(this))); + low_end_background_cleanup_task_.Reset(base::BindOnce( + &CompositorDependenciesAndroid::DoLowEndBackgroundCleanup, + base::Unretained(this))); base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, low_end_background_cleanup_task_.callback(), base::TimeDelta::FromSeconds(5)); } } -void CompositorDependencies::DoLowEndBackgroundCleanup() { +void CompositorDependenciesAndroid::DoLowEndBackgroundCleanup() { // When we become visible, we immediately cancel the callback that runs this // code. First, evict all unlocked frames, allowing resources to be // reclaimed. @@ -180,14 +181,16 @@ })); } -void CompositorDependencies::OnCompositorVisible(CompositorImpl* compositor) { +void CompositorDependenciesAndroid::OnCompositorVisible( + CompositorImpl* compositor) { bool element_inserted = visible_compositors_.insert(compositor).second; DCHECK(element_inserted); if (visible_compositors_.size() == 1) OnVisibilityChanged(); } -void CompositorDependencies::OnCompositorHidden(CompositorImpl* compositor) { +void CompositorDependenciesAndroid::OnCompositorHidden( + CompositorImpl* compositor) { size_t elements_removed = visible_compositors_.erase(compositor); DCHECK_EQ(1u, elements_removed); if (visible_compositors_.size() == 0) @@ -196,7 +199,7 @@ // This function runs when our first CompositorImpl becomes visible or when // our last Compositormpl is hidden. -void CompositorDependencies::OnVisibilityChanged() { +void CompositorDependenciesAndroid::OnVisibilityChanged() { if (visible_compositors_.size() > 0) { GpuDataManagerImpl::GetInstance()->SetApplicationVisible(true); BrowserGpuChannelHostFactorySetApplicationVisible(true);
diff --git a/content/browser/renderer_host/compositor_dependencies_android.h b/content/browser/renderer_host/compositor_dependencies_android.h index dc131a2..fc85dd44 100644 --- a/content/browser/renderer_host/compositor_dependencies_android.h +++ b/content/browser/renderer_host/compositor_dependencies_android.h
@@ -27,9 +27,9 @@ class CompositorImpl; -class CompositorDependencies { +class CompositorDependenciesAndroid { public: - static CompositorDependencies& Get(); + static CompositorDependenciesAndroid& Get(); cc::TaskGraphRunner* GetTaskGraphRunner(); @@ -47,14 +47,14 @@ void OnCompositorHidden(CompositorImpl* compositor); private: - friend class base::NoDestructor<CompositorDependencies>; + friend class base::NoDestructor<CompositorDependenciesAndroid>; static void ConnectVizFrameSinkManagerOnIOThread( viz::mojom::FrameSinkManagerRequest request, viz::mojom::FrameSinkManagerClientPtrInfo client); - CompositorDependencies(); - ~CompositorDependencies(); + CompositorDependenciesAndroid(); + ~CompositorDependenciesAndroid(); void CreateVizFrameSinkManager(); void EnqueueLowEndBackgroundCleanup(); @@ -84,7 +84,7 @@ std::unique_ptr<cc::TaskGraphRunner> task_graph_runner_; - DISALLOW_COPY_AND_ASSIGN(CompositorDependencies); + DISALLOW_COPY_AND_ASSIGN(CompositorDependenciesAndroid); }; } // namespace content
diff --git a/content/browser/renderer_host/compositor_impl_android.cc b/content/browser/renderer_host/compositor_impl_android.cc index 69e1a82..b21ad69 100644 --- a/content/browser/renderer_host/compositor_impl_android.cc +++ b/content/browser/renderer_host/compositor_impl_android.cc
@@ -571,7 +571,8 @@ cc::LayerTreeHost::InitParams params; params.client = this; - params.task_graph_runner = CompositorDependencies::Get().GetTaskGraphRunner(); + params.task_graph_runner = + CompositorDependenciesAndroid::Get().GetTaskGraphRunner(); params.main_task_runner = base::ThreadTaskRunnerHandle::Get(); params.settings = &settings; params.mutator_host = animation_host_.get(); @@ -598,12 +599,13 @@ has_layer_tree_frame_sink_ = false; pending_frames_ = 0; - // Notify CompositorDependencies of visibility changes last, to ensure that - // we don't disable the GPU watchdog until sync IPCs above are completed. - CompositorDependencies::Get().OnCompositorHidden(this); + // Notify CompositorDependenciesAndroid of visibility changes last, to + // ensure that we don't disable the GPU watchdog until sync IPCs above are + // completed. + CompositorDependenciesAndroid::Get().OnCompositorHidden(this); } else { DCHECK(!host_->IsVisible()); - CompositorDependencies::Get().OnCompositorVisible(this); + CompositorDependenciesAndroid::Get().OnCompositorVisible(this); RegisterRootFrameSink(); host_->SetVisible(true); has_submitted_frame_since_became_visible_ = false; @@ -748,7 +750,7 @@ scoped_refptr<gpu::GpuChannelHost> gpu_channel_host) { // At this point we know we have a valid GPU process, establish our viz // connection if needed. - CompositorDependencies::Get().TryEstablishVizConnectionIfNeeded(); + CompositorDependenciesAndroid::Get().TryEstablishVizConnectionIfNeeded(); // We might end up queing multiple GpuChannel requests for the same // LayerTreeFrameSink request as the visibility of the compositor changes, so
diff --git a/content/browser/serial/serial_service.h b/content/browser/serial/serial_service.h index 12378db..ccfa95c 100644 --- a/content/browser/serial/serial_service.h +++ b/content/browser/serial/serial_service.h
@@ -42,6 +42,8 @@ void OnWatcherConnectionError(); void DecrementActiveFrameCount(); + // This raw pointer is safe because instances of this class are owned by + // RenderFrameHostImpl. RenderFrameHost* const render_frame_host_; mojo::BindingSet<blink::mojom::SerialService> bindings_;
diff --git a/content/common/throttling_url_loader.cc b/content/common/throttling_url_loader.cc index ecdedf3..5c22dc5 100644 --- a/content/common/throttling_url_loader.cc +++ b/content/common/throttling_url_loader.cc
@@ -394,9 +394,27 @@ network::ResourceResponseHead response_head; std::string header_string = base::StringPrintf( "HTTP/1.1 %i Internal Redirect\n" - "Location: %s\n", + "Location: %s", net::HTTP_TEMPORARY_REDIRECT, throttle_will_start_redirect_url_.spec().c_str()); + + // This is only needed when CORS is running in the renderer. + if (!network::features::ShouldEnableOutOfBlinkCors()) { + std::string http_origin; + if (start_info_->url_request.headers.GetHeader("Origin", &http_origin)) { + // If this redirect is used in a cross-origin request, add CORS headers + // to make sure that the redirect gets through. Note that the + // destination URL is still subject to the usual CORS policy, i.e. the + // resource will only be available to web pages if the server serves the + // response with the required CORS response headers. + header_string += base::StringPrintf( + "\n" + "Access-Control-Allow-Origin: %s\n" + "Access-Control-Allow-Credentials: true", + http_origin.c_str()); + } + } + response_head.headers = base::MakeRefCounted<net::HttpResponseHeaders>( net::HttpUtil::AssembleRawHeaders(header_string)); response_head.encoded_data_length = header_string.size();
diff --git a/content/public/android/java/src/org/chromium/content/browser/GestureListenerManagerImpl.java b/content/public/android/java/src/org/chromium/content/browser/GestureListenerManagerImpl.java index fb898d6..074a342 100644 --- a/content/public/android/java/src/org/chromium/content/browser/GestureListenerManagerImpl.java +++ b/content/public/android/java/src/org/chromium/content/browser/GestureListenerManagerImpl.java
@@ -328,9 +328,10 @@ private void setTouchScrollInProgress(boolean touchScrollInProgress) { mIsTouchScrollInProgress = touchScrollInProgress; - // Use the active touch scroll signal for hiding. The animation movement - // by fling will naturally hide the ActionMode by invalidating its content rect. - getSelectionPopupController().setScrollInProgress(touchScrollInProgress); + // Use the active touch scroll and fling scroll signal for hiding. + // The animation movement by fling will naturally hide the ActionMode + // by invalidating its content rect. + getSelectionPopupController().setScrollInProgress(isScrollInProgress()); } /**
diff --git a/content/renderer/BUILD.gn b/content/renderer/BUILD.gn index c9744c9..c489bd6 100644 --- a/content/renderer/BUILD.gn +++ b/content/renderer/BUILD.gn
@@ -211,8 +211,6 @@ "media/stream/audio_service_audio_processor_proxy.h", "media/stream/local_media_stream_audio_source.cc", "media/stream/local_media_stream_audio_source.h", - "media/stream/media_stream_audio_level_calculator.cc", - "media/stream/media_stream_audio_level_calculator.h", "media/stream/media_stream_audio_processor.cc", "media/stream/media_stream_audio_processor.h", "media/stream/media_stream_center.cc", @@ -223,7 +221,6 @@ "media/stream/media_stream_constraints_util_video_content.h", "media/stream/media_stream_device_observer.cc", "media/stream/media_stream_device_observer.h", - "media/stream/media_stream_dispatcher_eventhandler.h", "media/stream/media_stream_renderer_factory_impl.cc", "media/stream/media_stream_renderer_factory_impl.h", "media/stream/processed_local_audio_source.cc", @@ -603,6 +600,7 @@ "//third_party/webrtc/api/video:video_bitrate_allocation", "//third_party/webrtc/api/video:video_frame", "//third_party/webrtc/api/video:video_frame_i420", + "//third_party/webrtc/api/video:video_rtp_headers", "//third_party/webrtc/api/video_codecs:rtc_software_fallback_wrappers", "//third_party/webrtc/api/video_codecs:video_codecs_api", "//third_party/webrtc/common_video:common_video",
diff --git a/content/renderer/loader/resource_dispatcher.cc b/content/renderer/loader/resource_dispatcher.cc index 4548a42..2438d65b 100644 --- a/content/renderer/loader/resource_dispatcher.cc +++ b/content/renderer/loader/resource_dispatcher.cc
@@ -25,6 +25,7 @@ #include "content/common/navigation_params.h" #include "content/common/throttling_url_loader.h" #include "content/public/common/navigation_policy.h" +#include "content/public/common/origin_util.h" #include "content/public/common/resource_type.h" #include "content/public/common/url_utils.h" #include "content/public/renderer/request_peer.h" @@ -64,7 +65,7 @@ net::URLRequest:: CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE) && request.referrer.SchemeIsCryptographic() && - !request.url.SchemeIsCryptographic()) { + !IsOriginSecure(request.url)) { LOG(FATAL) << "Trying to send secure referrer for insecure request " << "without an appropriate referrer policy.\n" << "URL = " << request.url << "\n"
diff --git a/content/renderer/media/stream/media_stream_device_observer.cc b/content/renderer/media/stream/media_stream_device_observer.cc index d32589d..5432f5c 100644 --- a/content/renderer/media/stream/media_stream_device_observer.cc +++ b/content/renderer/media/stream/media_stream_device_observer.cc
@@ -14,7 +14,7 @@ #include "content/child/child_thread_impl.h" #include "content/public/common/service_names.mojom.h" #include "content/public/renderer/render_frame.h" -#include "content/renderer/media/stream/media_stream_dispatcher_eventhandler.h" +#include "third_party/blink/public/platform/modules/mediastream/media_stream_dispatcher_eventhandler.h" #include "url/origin.h" namespace content { @@ -38,7 +38,7 @@ struct MediaStreamDeviceObserver::Stream { Stream() {} ~Stream() {} - base::WeakPtr<MediaStreamDispatcherEventHandler> handler; + base::WeakPtr<blink::MediaStreamDispatcherEventHandler> handler; blink::MediaStreamDevices audio_devices; blink::MediaStreamDevices video_devices; }; @@ -150,7 +150,8 @@ const std::string& label, const blink::MediaStreamDevices& audio_devices, const blink::MediaStreamDevices& video_devices, - const base::WeakPtr<MediaStreamDispatcherEventHandler>& event_handler) { + const base::WeakPtr<blink::MediaStreamDispatcherEventHandler>& + event_handler) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); Stream stream;
diff --git a/content/renderer/media/stream/media_stream_device_observer.h b/content/renderer/media/stream/media_stream_device_observer.h index 3d38bd1..66feb84 100644 --- a/content/renderer/media/stream/media_stream_device_observer.h +++ b/content/renderer/media/stream/media_stream_device_observer.h
@@ -22,12 +22,14 @@ #include "third_party/blink/public/common/mediastream/media_stream_request.h" #include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h" +namespace blink { +class MediaStreamDispatcherEventHandler; +} + namespace content { -class MediaStreamDispatcherEventHandler; - // This class implements a Mojo object that receives device stopped -// notifications and forwards them to MediaStreamDispatcherEventHandler. +// notifications and forwards them to blink::MediaStreamDispatcherEventHandler. class CONTENT_EXPORT MediaStreamDeviceObserver : public RenderFrameObserver, public blink::mojom::MediaStreamDeviceObserver { @@ -40,11 +42,11 @@ // being shown to the user. blink::MediaStreamDevices GetNonScreenCaptureDevices(); - void AddStream( - const std::string& label, - const blink::MediaStreamDevices& audio_devices, - const blink::MediaStreamDevices& video_devices, - const base::WeakPtr<MediaStreamDispatcherEventHandler>& event_handler); + void AddStream(const std::string& label, + const blink::MediaStreamDevices& audio_devices, + const blink::MediaStreamDevices& video_devices, + const base::WeakPtr<blink::MediaStreamDispatcherEventHandler>& + event_handler); void AddStream(const std::string& label, const blink::MediaStreamDevice& device); bool RemoveStream(const std::string& label); @@ -96,4 +98,4 @@ } // namespace content -#endif // CONTENT_RENDERER_MEDIA_STREAM_MEDIA_STREAM_DEVICE_OBSERVER_H_ \ No newline at end of file +#endif // CONTENT_RENDERER_MEDIA_STREAM_MEDIA_STREAM_DEVICE_OBSERVER_H_
diff --git a/content/renderer/media/stream/media_stream_dispatcher_eventhandler.h b/content/renderer/media/stream/media_stream_dispatcher_eventhandler.h deleted file mode 100644 index 85055f17..0000000 --- a/content/renderer/media/stream/media_stream_dispatcher_eventhandler.h +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_RENDERER_MEDIA_STREAM_MEDIA_STREAM_DISPATCHER_EVENTHANDLER_H_ -#define CONTENT_RENDERER_MEDIA_STREAM_MEDIA_STREAM_DISPATCHER_EVENTHANDLER_H_ - -#include <string> - -#include "content/common/content_export.h" -#include "third_party/blink/public/common/mediastream/media_stream_request.h" - -namespace content { - -class CONTENT_EXPORT MediaStreamDispatcherEventHandler { - public: - // A device has been stopped in the browser process. - virtual void OnDeviceStopped(const blink::MediaStreamDevice& device) = 0; - - // Switch to the new device within the working session. - virtual void OnDeviceChanged(const blink::MediaStreamDevice& old_device, - const blink::MediaStreamDevice& new_device) = 0; - - protected: - virtual ~MediaStreamDispatcherEventHandler() {} -}; - -} // namespace content - -#endif // CONTENT_RENDERER_MEDIA_STREAM_MEDIA_STREAM_DISPATCHER_EVENTHANDLER_H_
diff --git a/content/renderer/media/stream/processed_local_audio_source.h b/content/renderer/media/stream/processed_local_audio_source.h index 7f0e908b..8757b7a 100644 --- a/content/renderer/media/stream/processed_local_audio_source.h +++ b/content/renderer/media/stream/processed_local_audio_source.h
@@ -12,10 +12,10 @@ #include "base/memory/ref_counted.h" #include "base/synchronization/lock.h" #include "content/renderer/media/stream/audio_service_audio_processor_proxy.h" -#include "content/renderer/media/stream/media_stream_audio_level_calculator.h" #include "content/renderer/media/stream/media_stream_audio_processor.h" #include "media/base/audio_capturer_source.h" #include "media/webrtc/audio_processor_controls.h" +#include "third_party/blink/public/platform/modules/mediastream/media_stream_audio_level_calculator.h" #include "third_party/blink/public/platform/modules/mediastream/media_stream_audio_source.h" #include "third_party/blink/public/platform/web_media_constraints.h" @@ -83,8 +83,8 @@ (audio_processor_ && audio_processor_->has_audio_processing()); } - const scoped_refptr<MediaStreamAudioLevelCalculator::Level>& audio_level() - const { + const scoped_refptr<blink::MediaStreamAudioLevelCalculator::Level>& + audio_level() const { return level_calculator_.level(); } @@ -152,7 +152,7 @@ base::subtle::Atomic32 volume_; // Used to calculate the signal level that shows in the UI. - MediaStreamAudioLevelCalculator level_calculator_; + blink::MediaStreamAudioLevelCalculator level_calculator_; bool allow_invalid_render_frame_id_for_testing_;
diff --git a/content/renderer/media/stream/user_media_processor.h b/content/renderer/media/stream/user_media_processor.h index 51ac1b66..1eeb2f8 100644 --- a/content/renderer/media/stream/user_media_processor.h +++ b/content/renderer/media/stream/user_media_processor.h
@@ -16,9 +16,9 @@ #include "base/memory/weak_ptr.h" #include "base/sequence_checker.h" #include "content/common/content_export.h" -#include "content/renderer/media/stream/media_stream_dispatcher_eventhandler.h" #include "third_party/blink/public/mojom/mediastream/media_devices.mojom.h" #include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h" +#include "third_party/blink/public/platform/modules/mediastream/media_stream_dispatcher_eventhandler.h" #include "third_party/blink/public/platform/modules/mediastream/web_platform_media_stream_source.h" #include "third_party/blink/public/platform/web_vector.h" #include "third_party/blink/public/web/web_user_media_request.h" @@ -63,7 +63,7 @@ // UserMediaProcessor must be created, called and destroyed on the main render // thread. There should be only one UserMediaProcessor per frame. class CONTENT_EXPORT UserMediaProcessor - : public MediaStreamDispatcherEventHandler { + : public blink::MediaStreamDispatcherEventHandler { public: using MediaDevicesDispatcherCallback = base::RepeatingCallback< const blink::mojom::MediaDevicesDispatcherHostPtr&()>; @@ -108,7 +108,7 @@ bool HasActiveSources() const; - // MediaStreamDispatcherEventHandler implementation. + // blink::MediaStreamDispatcherEventHandler implementation. void OnDeviceStopped(const blink::MediaStreamDevice& device) override; void OnDeviceChanged(const blink::MediaStreamDevice& old_device, const blink::MediaStreamDevice& new_device) override;
diff --git a/content/renderer/media/webrtc/rtc_peer_connection_handler.cc b/content/renderer/media/webrtc/rtc_peer_connection_handler.cc index c5a8fd2..67f0cf99 100644 --- a/content/renderer/media/webrtc/rtc_peer_connection_handler.cc +++ b/content/renderer/media/webrtc/rtc_peer_connection_handler.cc
@@ -2321,8 +2321,7 @@ for (const auto& content : sdesc->description()->contents()) { if (content.type == cricket::MediaProtocolType::kRtp) { - const auto* mdesc = - static_cast<cricket::MediaContentDescription*>(content.description); + const auto* mdesc = content.media_description(); audio = audio || (mdesc->type() == cricket::MEDIA_TYPE_AUDIO); video = video || (mdesc->type() == cricket::MEDIA_TYPE_VIDEO); rtcp_mux = rtcp_mux || mdesc->rtcp_mux();
diff --git a/content/renderer/media/webrtc/webrtc_audio_sink.cc b/content/renderer/media/webrtc/webrtc_audio_sink.cc index 2a4e5d2..e26cb3a 100644 --- a/content/renderer/media/webrtc/webrtc_audio_sink.cc +++ b/content/renderer/media/webrtc/webrtc_audio_sink.cc
@@ -44,7 +44,7 @@ } void WebRtcAudioSink::SetLevel( - scoped_refptr<MediaStreamAudioLevelCalculator::Level> level) { + scoped_refptr<blink::MediaStreamAudioLevelCalculator::Level> level) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(level.get()); adapter_->set_level(std::move(level));
diff --git a/content/renderer/media/webrtc/webrtc_audio_sink.h b/content/renderer/media/webrtc/webrtc_audio_sink.h index 99a1179..4bcb258b 100644 --- a/content/renderer/media/webrtc/webrtc_audio_sink.h +++ b/content/renderer/media/webrtc/webrtc_audio_sink.h
@@ -17,10 +17,10 @@ #include "base/single_thread_task_runner.h" #include "base/synchronization/lock.h" #include "content/common/content_export.h" -#include "content/renderer/media/stream/media_stream_audio_level_calculator.h" #include "content/renderer/media/stream/media_stream_audio_processor.h" #include "media/base/audio_parameters.h" #include "media/base/audio_push_fifo.h" +#include "third_party/blink/public/platform/modules/mediastream/media_stream_audio_level_calculator.h" #include "third_party/blink/public/platform/modules/mediastream/web_media_stream_audio_sink.h" #include "third_party/webrtc/api/media_stream_interface.h" #include "third_party/webrtc/pc/media_stream_track.h" @@ -54,7 +54,8 @@ // level. This is passed via the Adapter to libjingle. This method may only // be called once, before the audio data flow starts, and before any calls to // Adapter::GetSignalLevel() might be made. - void SetLevel(scoped_refptr<MediaStreamAudioLevelCalculator::Level> level); + void SetLevel( + scoped_refptr<blink::MediaStreamAudioLevelCalculator::Level> level); // Set the processor that applies signal processing on the data from the // source. This is passed via the Adapter to libjingle. This method may only @@ -88,7 +89,7 @@ audio_processor_ = std::move(processor); } void set_level( - scoped_refptr<MediaStreamAudioLevelCalculator::Level> level) { + scoped_refptr<blink::MediaStreamAudioLevelCalculator::Level> level) { level_ = std::move(level); } @@ -135,7 +136,7 @@ // Thread-safe accessor to current audio signal level. This may be null, if // not applicable to the current use case. This must be set before calls to // GetSignalLevel() are made. - scoped_refptr<MediaStreamAudioLevelCalculator::Level> level_; + scoped_refptr<blink::MediaStreamAudioLevelCalculator::Level> level_; // Lock that protects concurrent access to the |sinks_| list. base::Lock lock_;
diff --git a/content/shell/tools/breakpad_integration_test.py b/content/shell/tools/breakpad_integration_test.py index 2e09b13..310d8af 100755 --- a/content/shell/tools/breakpad_integration_test.py +++ b/content/shell/tools/breakpad_integration_test.py
@@ -55,13 +55,16 @@ return GetDevice.device -def clear_android_dumps(device): +def clear_android_dumps(options, device): try: + print '# Deleting stale crash dumps' pending = ANDROID_CRASH_DIR + '/pending/' files = device.RunShellCommand(['ls', pending], as_root=True) for f in files: - device.RunShellCommand(['rm', pending + f], check_return=True, - as_root=True) + if f.endswith('.dmp'): + if options.verbose: + print ' deleting %s' % f + device.RunShellCommand(['rm', f], check_return=True, as_root=True) except: print 'Failed to delete android crash dir %s' % ANDROID_CRASH_DIR @@ -101,7 +104,7 @@ device = GetDevice() failure = None - clear_android_dumps(device) + clear_android_dumps(options, device) apk_path = os.path.join(options.build_dir, 'apks', 'ContentShell.apk') apk = apk_helper.ApkHelper(apk_path) @@ -260,7 +263,6 @@ print '# Install ContentShell.apk' apk_path = os.path.join(options.build_dir, 'apks', 'ContentShell.apk') device.Install(apk_path, reinstall=False, allow_downgrade=True) - #device.RunShellCommand(['mkdir', ANDROID_CRASH_DIR], check_return=True) if options.platform != 'win32': print '# Generate symbols.' @@ -310,7 +312,7 @@ except: print 'Failed to delete temp directory "%s".' % crash_dir if options.platform == 'android': - clear_android_dumps(GetDevice()) + clear_android_dumps(options, GetDevice()) if '__main__' == __name__:
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index 60b3107c..0190f31de 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -701,6 +701,14 @@ "//ui/gfx:test_support", "//ui/gfx/geometry", "//v8", + + # This is required to ensure content/shell/common/web_test.mojom.h is + # generated before attempting to build this target. The file is included + # through content/shell/renderer/web_test/blink_test_runner.h. However + # adding a dependency on //content/shell:content_shell_lib as that would + # cause a circular dependency. Instead add this dependency directly to + # fix a flaky build (see https://crbug.com/971978 for more details). + "//content/shell:mojo_bindings", ] } @@ -2041,6 +2049,7 @@ "//third_party/webrtc/api/task_queue:task_queue_test", "//third_party/webrtc/api/video:video_frame", "//third_party/webrtc/api/video:video_frame_i420", + "//third_party/webrtc/api/video:video_rtp_headers", "//third_party/webrtc/api/video_codecs:video_codecs_api", "//third_party/webrtc/media:rtc_media", "//third_party/webrtc/media:rtc_vp9_profile",
diff --git a/extensions/common/api/app_runtime.idl b/extensions/common/api/app_runtime.idl index e67a080..09c1f84 100644 --- a/extensions/common/api/app_runtime.idl +++ b/extensions/common/api/app_runtime.idl
@@ -55,16 +55,6 @@ new_note }; - // Status of the play store. - [nodoc] enum PlayStoreStatus { - // Indicates that the play store is enabled. It also implies available. - enabled, - // Indicates that the play store is available but not enabled. - available, - // Indicates that the play store status is unknown. - unknown - }; - // Optional data that includes action-specific launch information. dictionary ActionData { ActionType actionType; @@ -129,9 +119,6 @@ // launched with. This is null if the app was not launched with a specific // action intent. ActionData? actionData; - - // Internal fields used to indicate ARC status on the device. - [nodoc] PlayStoreStatus? playStoreStatus; }; // This object specifies details and operations to perform on the embedding
diff --git a/extensions/common/extension.cc b/extensions/common/extension.cc index 463f92a1..33448207 100644 --- a/extensions/common/extension.cc +++ b/extensions/common/extension.cc
@@ -219,13 +219,13 @@ } ExtensionResource Extension::GetResource( - const std::string& relative_path) const { - std::string new_path = relative_path; + base::StringPiece relative_path) const { // We have some legacy data where resources have leading slashes. // See: http://crbug.com/121164 - if (!new_path.empty() && new_path.at(0) == '/') - new_path.erase(0, 1); - base::FilePath relative_file_path = base::FilePath::FromUTF8Unsafe(new_path); + if (!relative_path.empty() && relative_path[0] == '/') + relative_path.remove_prefix(1); + base::FilePath relative_file_path = + base::FilePath::FromUTF8Unsafe(relative_path); if (ContainsReservedCharacters(relative_file_path)) return ExtensionResource(); ExtensionResource r(id(), path(), relative_file_path);
diff --git a/extensions/common/extension.h b/extensions/common/extension.h index bcc4fed..d28ea9d 100644 --- a/extensions/common/extension.h +++ b/extensions/common/extension.h
@@ -193,7 +193,7 @@ // Returns an extension resource object. |relative_path| should be UTF8 // encoded. - ExtensionResource GetResource(const std::string& relative_path) const; + ExtensionResource GetResource(base::StringPiece relative_path) const; // As above, but with |relative_path| following the file system's encoding. ExtensionResource GetResource(const base::FilePath& relative_path) const;
diff --git a/google_apis/BUILD.gn b/google_apis/BUILD.gn index 3c605a4..e343daf 100644 --- a/google_apis/BUILD.gn +++ b/google_apis/BUILD.gn
@@ -120,6 +120,7 @@ "gaia/oauth2_token_service.h", "gaia/oauth2_token_service_delegate.cc", "gaia/oauth2_token_service_delegate.h", + "gaia/oauth2_token_service_observer.h", "gaia/oauth2_token_service_request.cc", "gaia/oauth2_token_service_request.h", "gaia/oauth_multilogin_result.cc",
diff --git a/google_apis/gaia/oauth2_token_service.cc b/google_apis/gaia/oauth2_token_service.cc index 5fdc3b9..7a7a8702 100644 --- a/google_apis/gaia/oauth2_token_service.cc +++ b/google_apis/gaia/oauth2_token_service.cc
@@ -390,14 +390,16 @@ OAuth2TokenService::OAuth2TokenService( std::unique_ptr<OAuth2TokenServiceDelegate> delegate) - : delegate_(std::move(delegate)) { + : delegate_(std::move(delegate)), all_credentials_loaded_(false) { DCHECK(delegate_); + AddObserver(this); } OAuth2TokenService::~OAuth2TokenService() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Release all the pending fetchers. pending_fetchers_.clear(); + RemoveObserver(this); } OAuth2TokenServiceDelegate* OAuth2TokenService::GetDelegate() { @@ -408,11 +410,11 @@ return delegate_.get(); } -void OAuth2TokenService::AddObserver(Observer* observer) { +void OAuth2TokenService::AddObserver(OAuth2TokenServiceObserver* observer) { delegate_->AddObserver(observer); } -void OAuth2TokenService::RemoveObserver(Observer* observer) { +void OAuth2TokenService::RemoveObserver(OAuth2TokenServiceObserver* observer) { delegate_->RemoveObserver(observer); } @@ -585,7 +587,14 @@ *cache_token_response)); } +bool OAuth2TokenService::AreAllCredentialsLoaded() const { + return all_credentials_loaded_; +} + std::vector<std::string> OAuth2TokenService::GetAccounts() const { + if (!AreAllCredentialsLoaded()) + return std::vector<std::string>(); + return delegate_->GetAccounts(); } @@ -735,6 +744,11 @@ } return false; } + +void OAuth2TokenService::OnRefreshTokensLoaded() { + all_credentials_loaded_ = true; +} + void OAuth2TokenService::UpdateAuthError(const CoreAccountId& account_id, const GoogleServiceAuthError& error) { delegate_->UpdateAuthError(account_id, error);
diff --git a/google_apis/gaia/oauth2_token_service.h b/google_apis/gaia/oauth2_token_service.h index 56239fbb..e51f108 100644 --- a/google_apis/gaia/oauth2_token_service.h +++ b/google_apis/gaia/oauth2_token_service.h
@@ -24,6 +24,7 @@ #include "google_apis/gaia/google_service_auth_error.h" #include "google_apis/gaia/oauth2_access_token_consumer.h" #include "google_apis/gaia/oauth2_access_token_fetcher.h" +#include "google_apis/gaia/oauth2_token_service_observer.h" namespace network { class SharedURLLoaderFactory; @@ -60,7 +61,7 @@ // // The caller of StartRequest() owns the returned request and is responsible to // delete the request even once the callback has been invoked. -class OAuth2TokenService { +class OAuth2TokenService : public OAuth2TokenServiceObserver { public: // A set of scopes in OAuth2 authentication. typedef std::set<std::string> ScopeSet; @@ -94,37 +95,6 @@ std::string id_; }; - // Classes that want to listen for refresh token availability should - // implement this interface and register with the AddObserver() call. - class Observer { - public: - // Called whenever a new login-scoped refresh token is available for - // account |account_id|. Once available, access tokens can be retrieved for - // this account. This is called during initial startup for each token - // loaded (and any time later when, e.g., credentials change). When called, - // any pending token request is cancelled and needs to be retried. Such a - // pending request can easily occur on Android, where refresh tokens are - // held by the OS and are thus often available on startup even before - // OnRefreshTokenAvailable() is called. - virtual void OnRefreshTokenAvailable(const CoreAccountId& account_id) {} - // Called whenever the login-scoped refresh token becomes unavailable for - // account |account_id|. - virtual void OnRefreshTokenRevoked(const CoreAccountId& account_id) {} - // Called after all refresh tokens are loaded during OAuth2TokenService - // startup. - virtual void OnRefreshTokensLoaded() {} - // Sent after a batch of refresh token changes is done. - virtual void OnEndBatchChanges() {} - // Called when the authentication error state for |account_id| has changed. - // Note: It is always called after |OnRefreshTokenAvailable| when refresh - // token is updated. It is not called when the refresh token is revoked. - virtual void OnAuthErrorChanged(const CoreAccountId& account_id, - const GoogleServiceAuthError& auth_error) {} - - protected: - virtual ~Observer() {} - }; - // Classes that want to monitor status of access token and access token // request should implement this interface and register with the // AddDiagnosticsObserver() call. @@ -162,11 +132,11 @@ explicit OAuth2TokenService( std::unique_ptr<OAuth2TokenServiceDelegate> delegate); - virtual ~OAuth2TokenService(); + ~OAuth2TokenService() override; // Add or remove observers of this token service. - void AddObserver(Observer* observer); - void RemoveObserver(Observer* observer); + void AddObserver(OAuth2TokenServiceObserver* observer); + void RemoveObserver(OAuth2TokenServiceObserver* observer); // Add or remove observers of this token service. void AddDiagnosticsObserver(DiagnosticsObserver* observer); @@ -209,6 +179,13 @@ const ScopeSet& scopes, Consumer* consumer); + // Returns true iff all credentials have been loaded from disk. + bool AreAllCredentialsLoaded() const; + + void set_all_credentials_loaded_for_testing(bool loaded) { + all_credentials_loaded_ = loaded; + } + // Lists account IDs of all accounts with a refresh token maintained by this // instance. // Note: For each account returned by |GetAccounts|, |RefreshTokenIsAvailable| @@ -291,6 +268,9 @@ SEQUENCE_CHECKER(sequence_checker_); }; + // OAuth2TokenServiceObserver: + void OnRefreshTokensLoaded() override; + // Implement it in delegates if they want to report errors to the user. void UpdateAuthError(const CoreAccountId& account_id, const GoogleServiceAuthError& error); @@ -428,6 +408,9 @@ // The depth of batch changes. int batch_change_depth_; + // Whether all credentials have been loaded. + bool all_credentials_loaded_; + // Maximum number of retries in fetching an OAuth2 access token. static int max_fetch_retry_num_;
diff --git a/google_apis/gaia/oauth2_token_service_delegate.cc b/google_apis/gaia/oauth2_token_service_delegate.cc index d4a4409..6c775f6 100644 --- a/google_apis/gaia/oauth2_token_service_delegate.cc +++ b/google_apis/gaia/oauth2_token_service_delegate.cc
@@ -23,8 +23,7 @@ } OAuth2TokenServiceDelegate::OAuth2TokenServiceDelegate() - : batch_change_depth_(0) { -} + : batch_change_depth_(0) {} OAuth2TokenServiceDelegate::~OAuth2TokenServiceDelegate() { } @@ -47,12 +46,12 @@ } void OAuth2TokenServiceDelegate::AddObserver( - OAuth2TokenService::Observer* observer) { + OAuth2TokenServiceObserver* observer) { observer_list_.AddObserver(observer); } void OAuth2TokenServiceDelegate::RemoveObserver( - OAuth2TokenService::Observer* observer) { + OAuth2TokenServiceObserver* observer) { observer_list_.RemoveObserver(observer); }
diff --git a/google_apis/gaia/oauth2_token_service_delegate.h b/google_apis/gaia/oauth2_token_service_delegate.h index 771dc1a..e19c2281 100644 --- a/google_apis/gaia/oauth2_token_service_delegate.h +++ b/google_apis/gaia/oauth2_token_service_delegate.h
@@ -93,8 +93,8 @@ bool ValidateAccountId(const std::string& account_id) const; // Add or remove observers of this token service. - void AddObserver(OAuth2TokenService::Observer* observer); - void RemoveObserver(OAuth2TokenService::Observer* observer); + void AddObserver(OAuth2TokenServiceObserver* observer); + void RemoveObserver(OAuth2TokenServiceObserver* observer); // Returns a pointer to its instance of net::BackoffEntry if it has one, or // a nullptr otherwise. @@ -171,7 +171,7 @@ private: // List of observers to notify when refresh token availability changes. // Makes sure list is empty on destruction. - base::ObserverList<OAuth2TokenService::Observer, true>::Unchecked + base::ObserverList<OAuth2TokenServiceObserver, true>::Unchecked observer_list_; // The state of the load credentials operation.
diff --git a/google_apis/gaia/oauth2_token_service_delegate_unittest.cc b/google_apis/gaia/oauth2_token_service_delegate_unittest.cc index fdb969f..ca3e65e 100644 --- a/google_apis/gaia/oauth2_token_service_delegate_unittest.cc +++ b/google_apis/gaia/oauth2_token_service_delegate_unittest.cc
@@ -21,7 +21,7 @@ // where refresh tokens are not accessible. This test checks that refresh tokens // are not affected on INVALID_TOKENS Multilogin error. TEST(OAuth2TokenServiceDelegateTest, InvalidateTokensForMultilogin) { - class TokenServiceObserver : public OAuth2TokenService::Observer { + class TestOAuth2TokenServiceObserver : public OAuth2TokenServiceObserver { public: MOCK_METHOD2(OnAuthErrorChanged, void(const CoreAccountId&, const GoogleServiceAuthError&)); @@ -29,7 +29,7 @@ FakeOAuth2TokenServiceDelegate delegate; - TokenServiceObserver observer; + TestOAuth2TokenServiceObserver observer; delegate.AddObserver(&observer); // Check that OnAuthErrorChanged is not fired from // InvalidateTokensForMultilogin and refresh tokens are not set in error.
diff --git a/google_apis/gaia/oauth2_token_service_observer.h b/google_apis/gaia/oauth2_token_service_observer.h new file mode 100644 index 0000000..bbbd196 --- /dev/null +++ b/google_apis/gaia/oauth2_token_service_observer.h
@@ -0,0 +1,43 @@ +// 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. + +#ifndef GOOGLE_APIS_GAIA_OAUTH2_TOKEN_SERVICE_OBSERVER_H_ +#define GOOGLE_APIS_GAIA_OAUTH2_TOKEN_SERVICE_OBSERVER_H_ + +#include "google_apis/gaia/core_account_id.h" +#include "google_apis/gaia/google_service_auth_error.h" + +// Classes that want to listen for refresh token availability should +// implement this interface and register with the OAuth2TokenService:: +// AddObserver() call. +class OAuth2TokenServiceObserver { + public: + // Called whenever a new login-scoped refresh token is available for + // account |account_id|. Once available, access tokens can be retrieved for + // this account. This is called during initial startup for each token + // loaded (and any time later when, e.g., credentials change). When called, + // any pending token request is cancelled and needs to be retried. Such a + // pending request can easily occur on Android, where refresh tokens are + // held by the OS and are thus often available on startup even before + // OnRefreshTokenAvailable() is called. + virtual void OnRefreshTokenAvailable(const CoreAccountId& account_id) {} + // Called whenever the login-scoped refresh token becomes unavailable for + // account |account_id|. + virtual void OnRefreshTokenRevoked(const CoreAccountId& account_id) {} + // Called after all refresh tokens are loaded during OAuth2TokenService + // startup. + virtual void OnRefreshTokensLoaded() {} + // Sent after a batch of refresh token changes is done. + virtual void OnEndBatchChanges() {} + // Called when the authentication error state for |account_id| has changed. + // Note: It is always called after |OnRefreshTokenAvailable| when refresh + // token is updated. It is not called when the refresh token is revoked. + virtual void OnAuthErrorChanged(const CoreAccountId& account_id, + const GoogleServiceAuthError& auth_error) {} + + protected: + virtual ~OAuth2TokenServiceObserver() {} +}; + +#endif // GOOGLE_APIS_GAIA_OAUTH2_TOKEN_SERVICE_OBSERVER_H_
diff --git a/google_apis/gaia/oauth2_token_service_unittest.cc b/google_apis/gaia/oauth2_token_service_unittest.cc index 3545a2b2..ff24655 100644 --- a/google_apis/gaia/oauth2_token_service_unittest.cc +++ b/google_apis/gaia/oauth2_token_service_unittest.cc
@@ -53,7 +53,7 @@ std::unique_ptr<OAuth2TokenService::Request> request_; }; -class FakeOAuth2TokenServiceObserver : public OAuth2TokenService::Observer { +class FakeOAuth2TokenServiceObserver : public OAuth2TokenServiceObserver { public: MOCK_METHOD2(OnAuthErrorChanged, void(const CoreAccountId&, const GoogleServiceAuthError&)); @@ -149,6 +149,28 @@ EXPECT_EQ(1, consumer_.number_of_errors_); } +TEST_F(OAuth2TokenServiceTest, GetAccounts) { + // Accounts should start off empty. + auto accounts = oauth2_service_->GetAccounts(); + EXPECT_TRUE(accounts.empty()); + + // Add an account. + oauth2_service_->GetFakeOAuth2TokenServiceDelegate()->UpdateCredentials( + account_id_, "refreshToken"); + + // Accounts should still be empty as tokens have not yet been loaded from + // disk. + accounts = oauth2_service_->GetAccounts(); + EXPECT_TRUE(accounts.empty()); + + // Load tokens from disk. + oauth2_service_->GetDelegate()->LoadCredentials(""); + + // |account_id_| should now be visible in the accounts. + accounts = oauth2_service_->GetAccounts(); + EXPECT_THAT(accounts, testing::ElementsAre(account_id_)); +} + TEST_F(OAuth2TokenServiceTest, FailureShouldNotRetry) { oauth2_service_->GetFakeOAuth2TokenServiceDelegate()->UpdateCredentials( account_id_, "refreshToken");
diff --git a/gpu/command_buffer/service/texture_manager.h b/gpu/command_buffer/service/texture_manager.h index 27df199..d149cf5 100644 --- a/gpu/command_buffer/service/texture_manager.h +++ b/gpu/command_buffer/service/texture_manager.h
@@ -51,6 +51,7 @@ class SharedImageRepresentationGLTextureIOSurface; class SharedImageRepresentationSkiaIOSurface; class SharedImageBackingDXGISwapChain; +class StreamTexture; class SwapChainFactoryDXGI; namespace gles2 { @@ -417,6 +418,7 @@ friend class gpu::SwapChainFactoryDXGI; friend class gpu::SharedImageRepresentationGLTextureIOSurface; friend class gpu::SharedImageRepresentationSkiaIOSurface; + friend class gpu::StreamTexture; friend class AbstractTextureImplOnSharedContext; friend class TextureDefinition; friend class TextureManager;
diff --git a/gpu/ipc/common/struct_traits_unittest.cc b/gpu/ipc/common/struct_traits_unittest.cc index e67bce0..21146bf 100644 --- a/gpu/ipc/common/struct_traits_unittest.cc +++ b/gpu/ipc/common/struct_traits_unittest.cc
@@ -5,7 +5,7 @@ #include <algorithm> #include <string> -#include "base/message_loop/message_loop.h" +#include "base/test/scoped_task_environment.h" #include "build/build_config.h" #include "gpu/config/gpu_feature_type.h" #include "gpu/ipc/common/gpu_feature_info.mojom.h" @@ -82,7 +82,7 @@ std::move(callback).Run(prefs); } - base::MessageLoop loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; mojo::BindingSet<TraitsTestService> traits_test_bindings_; DISALLOW_COPY_AND_ASSIGN(StructTraitsTest);
diff --git a/gpu/ipc/service/stream_texture_android.cc b/gpu/ipc/service/stream_texture_android.cc index 1b66ba80..8d6d9f6 100644 --- a/gpu/ipc/service/stream_texture_android.cc +++ b/gpu/ipc/service/stream_texture_android.cc
@@ -223,6 +223,30 @@ surface_owner_.get()); } +void StreamTexture::OnSetSize(const gfx::Size& size) { + size_ = size; + if (!owner_stub_ || !surface_owner_.get()) + return; + + gles2::ContextGroup* context_group = + owner_stub_->decoder_context()->GetContextGroup(); + DCHECK(context_group); + TextureManager* texture_manager = context_group->texture_manager(); + gles2::Texture* texture = + texture_manager->GetTextureForServiceId(texture_id_); + if (texture) { + // SetLevelInfo will reset the image / stream texture image, which may be + // the last reference to |this|, so keep a reference around, and make sure + // to reset the stream texture image. + scoped_refptr<StreamTexture> self(this); + texture->SetLevelInfo(GL_TEXTURE_EXTERNAL_OES, 0, GL_RGBA, size.width(), + size.height(), 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, + gfx::Rect(size)); + texture->SetLevelStreamTextureImage(GL_TEXTURE_EXTERNAL_OES, 0, this, + gles2::Texture::UNBOUND, 0); + } +} + StreamTexture::BindOrCopy StreamTexture::ShouldBindOrCopy() { return COPY; }
diff --git a/gpu/ipc/service/stream_texture_android.h b/gpu/ipc/service/stream_texture_android.h index 0fbac37..aabd38f9 100644 --- a/gpu/ipc/service/stream_texture_android.h +++ b/gpu/ipc/service/stream_texture_android.h
@@ -90,7 +90,7 @@ // IPC message handlers: void OnStartListening(); void OnForwardForSurfaceRequest(const base::UnguessableToken& request_token); - void OnSetSize(const gfx::Size& size) { size_ = size; } + void OnSetSize(const gfx::Size& size); std::unique_ptr<SurfaceOwner> surface_owner_;
diff --git a/infra/config/OWNERS b/infra/config/OWNERS index 31a321e3..a966cffd 100644 --- a/infra/config/OWNERS +++ b/infra/config/OWNERS
@@ -1,5 +1,4 @@ # For build parallelism configs. -per-file cr-buildbucket.cfg=shinyak@chromium.org per-file cr-buildbucket.cfg=sque@chromium.org per-file cr-buildbucket.cfg=tikuta@chromium.org per-file cr-buildbucket.cfg=ukai@chromium.org
diff --git a/infra/config/cr-buildbucket.cfg b/infra/config/cr-buildbucket.cfg index 9c958ba..dd84f5e 100644 --- a/infra/config/cr-buildbucket.cfg +++ b/infra/config/cr-buildbucket.cfg
@@ -926,7 +926,8 @@ builders { name: "Android ASAN (dbg)" mixins: "android-ci" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { @@ -1098,49 +1099,57 @@ builders { name: "android-cronet-arm-dbg" mixins: "android-ci" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { name: "android-cronet-arm-rel" mixins: "android-ci" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { name: "android-cronet-arm64-dbg" mixins: "android-ci" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { name: "android-cronet-arm64-rel" mixins: "android-ci" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { name: "android-cronet-asan-arm-rel" mixins: "android-ci" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { name: "android-cronet-kitkat-arm-rel" mixins: "android-ci" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { name: "android-cronet-lollipop-arm-rel" mixins: "android-ci" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { name: "android-cronet-marshmallow-arm64-rel" mixins: "android-ci" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { @@ -1158,25 +1167,29 @@ builders { name: "android-cronet-x86-dbg" mixins: "android-ci" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { name: "android-cronet-x86-rel" mixins: "android-ci" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { name: "android-incremental-dbg" mixins: "android-ci" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { name: "android-jumbo-rel" mixins: "android-ci" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { @@ -1195,71 +1208,84 @@ builders { name: "android-mojo-webview-rel" - dimensions: "os:Ubuntu-14.04" mixins: "fyi-ci" + mixins: "linux-xenial" + mixins: "builderless" } builders { name: "Cast Android (dbg)" mixins: "android-ci" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { name: "Deterministic Android" mixins: "deterministic" mixins: "android-ci-goma-rbe-prod" + mixins: "linux-xenial" + mixins: "builderless" } builders { name: "Deterministic Android (dbg)" mixins: "deterministic" mixins: "android-ci-goma-rbe-prod" + mixins: "linux-xenial" + mixins: "builderless" } builders { name: "KitKat Phone Tester (dbg)" mixins: "android-ci" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { name: "KitKat Tablet Tester" mixins: "android-ci" mixins: "android-tablet-ci" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { name: "Lollipop Phone Tester" mixins: "android-ci" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { name: "Lollipop Tablet Tester" mixins: "android-ci" mixins: "android-tablet-ci" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { name: "Marshmallow 64 bit Tester" mixins: "android-ci" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { name: "Marshmallow Tablet Tester" mixins: "android-ci" mixins: "android-tablet-ci" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { name: "Nougat Phone Tester" mixins: "android-ci" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } # ChromeOS bots. @@ -1401,6 +1427,8 @@ builders { name: "Cast Linux" mixins: "linux-ci" + mixins: "linux-xenial" + mixins: "builderless" recipe { properties_j: "$build/goma:{\"jobs\": 50}" } @@ -1517,6 +1545,8 @@ builders { name: "linux-jumbo-rel" mixins: "linux-ci" + mixins: "linux-xenial" + mixins: "builderless" } builders { @@ -2495,13 +2525,15 @@ } builders { name: "Oreo Phone Tester" - dimensions: "os:Ubuntu-14.04" mixins: "android-ci" + mixins: "linux-xenial" + mixins: "builderless" } builders { name: "android-pie-arm64-dbg" - dimensions: "os:Ubuntu-14.04" mixins: "android-ci" + mixins: "linux-xenial" + mixins: "builderless" } builders { @@ -3499,19 +3531,22 @@ builders { mixins: "android-try" name: "android-oreo-arm64-cts-networkservice-dbg" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { mixins: "android-try" mixins: "goma-j300" name: "android_arm64_dbg_recipe" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { name: "android-binary-size" mixins: "android-try" mixins: "goma-j150" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" recipe { name: "binary_size_trybot" } @@ -3519,34 +3554,40 @@ builders { mixins: "android-try" name: "android_blink_rel" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { mixins: "android-try" mixins: "goma-j300" name: "android_clang_dbg_recipe" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { mixins: "android-try" mixins: "goma-j150" name: "android_compile_dbg" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { mixins: "android-try" name: "android_cronet" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { mixins: "android-try" name: "android_n5x_swarming_dbg" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { mixins: "android-try" name: "cast_shell_android" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { mixins: "android-optional-gpu-try" name: "android_optional_gpu_tests_rel" } builders { @@ -3630,18 +3671,22 @@ mixins: "deterministic" mixins: "goma-rbe-prod" name: "android-deterministic-rel" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { mixins: "android-try" mixins: "deterministic" mixins: "goma-rbe-prod" name: "android-deterministic-dbg" - dimensions: "os:Ubuntu-14.04" + mixins: "linux-xenial" + mixins: "builderless" } builders { mixins: "android-try" name: "try-nougat-phone-tester" + mixins: "linux-xenial" + mixins: "builderless" } builders { mixins: "chromeos-try" name: "chromeos-amd64-generic-cfi-thin-lto-rel" } @@ -3680,7 +3725,12 @@ } builders { mixins: "linux-try" name: "cast_shell_audio_linux" } - builders { mixins: "linux-try" name: "cast_shell_linux" } + builders { + mixins: "linux-try" + name: "cast_shell_linux" + mixins: "linux-xenial" + mixins: "builderless" + } builders { mixins: "linux-try" name: "chromium_devtools" } builders { mixins: "linux-try" @@ -3812,7 +3862,12 @@ name: "linux-goma-rbe-staging-rel" } builders { mixins: "linux-try" name: "linux-gcc-rel" } - builders { mixins: "linux-try" name: "linux-jumbo-rel" } + builders { + mixins: "linux-try" + name: "linux-jumbo-rel" + mixins: "linux-xenial" + mixins: "builderless" + } builders { name: "linux-libfuzzer-asan-rel" mixins: "linux-try" @@ -4203,9 +4258,10 @@ builders { name: "android_compile_x86_dbg" - dimensions: "os:Ubuntu-14.04" mixins: "android-try" mixins: "goma-rbe-prod" + mixins: "linux-xenial" + mixins: "builderless" } builders { name: "linux-annotator-rel" @@ -4230,14 +4286,16 @@ } builders { name: "android_compile_x64_dbg" - dimensions: "os:Ubuntu-14.04" mixins: "android-try" mixins: "goma-rbe-prod" + mixins: "linux-xenial" + mixins: "builderless" } builders { name: "android_archive_rel_ng" - dimensions: "os:Ubuntu-14.04" mixins: "android-try" + mixins: "linux-xenial" + mixins: "builderless" } builders { name: "layout_test_leak_detection" @@ -4254,9 +4312,10 @@ } builders { name: "android_mojo" - dimensions: "os:Ubuntu-14.04" mixins: "android-try" mixins: "goma-rbe-prod" + mixins: "linux-xenial" + mixins: "builderless" } # Blink try builders.
diff --git a/ios/chrome/browser/ui/alert_view_controller/alert_view_controller.mm b/ios/chrome/browser/ui/alert_view_controller/alert_view_controller.mm index 871b5b1..dea6873 100644 --- a/ios/chrome/browser/ui/alert_view_controller/alert_view_controller.mm +++ b/ios/chrome/browser/ui/alert_view_controller/alert_view_controller.mm
@@ -225,6 +225,7 @@ if (self.title.length) { UILabel* titleLabel = [[UILabel alloc] init]; + titleLabel.numberOfLines = 0; titleLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline]; titleLabel.adjustsFontForContentSizeCategory = YES;
diff --git a/ios/chrome/browser/ui/overlays/web_content_area/java_script_dialogs/java_script_dialog_overlay_coordinator.mm b/ios/chrome/browser/ui/overlays/web_content_area/java_script_dialogs/java_script_dialog_overlay_coordinator.mm index c54536c5..6fd279f 100644 --- a/ios/chrome/browser/ui/overlays/web_content_area/java_script_dialogs/java_script_dialog_overlay_coordinator.mm +++ b/ios/chrome/browser/ui/overlays/web_content_area/java_script_dialogs/java_script_dialog_overlay_coordinator.mm
@@ -19,7 +19,8 @@ #error "This file requires ARC support." #endif -@interface JavaScriptDialogOverlayCoordinator () +@interface JavaScriptDialogOverlayCoordinator () < + JavaScriptDialogOverlayMediatorDelegate> // Whether the coordinator has been started. @property(nonatomic, getter=isStarted) BOOL started; // The alert view controller. @@ -30,6 +31,23 @@ @implementation JavaScriptDialogOverlayCoordinator +#pragma mark - Accessors + +- (void)setMediator:(JavaScriptDialogOverlayMediator*)mediator { + if (_mediator == mediator) + return; + _mediator.delegate = nil; + _mediator = mediator; + _mediator.delegate = self; +} + +#pragma mark - JavaScriptDialogOverlayMediatorDelegate + +- (void)stopDialogForMediator:(JavaScriptDialogOverlayMediator*)mediator { + DCHECK_EQ(self.mediator, mediator); + [self stopAnimated:YES]; +} + #pragma mark - OverlayCoordinator + (BOOL)supportsRequest:(OverlayRequest*)request {
diff --git a/ios/chrome/browser/ui/toolbar/primary_toolbar_view.mm b/ios/chrome/browser/ui/toolbar/primary_toolbar_view.mm index e7f949d..d22304e 100644 --- a/ios/chrome/browser/ui/toolbar/primary_toolbar_view.mm +++ b/ios/chrome/browser/ui/toolbar/primary_toolbar_view.mm
@@ -157,6 +157,11 @@ [self setUpSeparator]; [self setUpConstraints]; + + // Make sure that the trait collection is taken into account. + if (@available(iOS 13, *)) { + [self updateLayoutForPreviousTraitCollection:nil]; + } } - (void)addFakeOmniboxTarget { @@ -181,14 +186,7 @@ - (void)traitCollectionDidChange:(UITraitCollection*)previousTraitCollection { [super traitCollectionDidChange:previousTraitCollection]; - if (IsRegularXRegularSizeClass(self)) { - self.backgroundColor = - self.buttonFactory.toolbarConfiguration.backgroundColor; - self.blur.alpha = 0; - } else { - self.backgroundColor = [UIColor clearColor]; - self.blur.alpha = 1; - } + [self updateLayoutForPreviousTraitCollection:previousTraitCollection]; } #pragma mark - Setup @@ -473,4 +471,18 @@ return nil; } +#pragma mark - Private + +- (void)updateLayoutForPreviousTraitCollection: + (UITraitCollection*)previousTraitCollection { + if (IsRegularXRegularSizeClass(self)) { + self.backgroundColor = + self.buttonFactory.toolbarConfiguration.backgroundColor; + self.blur.alpha = 0; + } else { + self.backgroundColor = [UIColor clearColor]; + self.blur.alpha = 1; + } +} + @end
diff --git a/ios/chrome/browser/ui/toolbar/primary_toolbar_view_controller.mm b/ios/chrome/browser/ui/toolbar/primary_toolbar_view_controller.mm index 452ca96..4064b41a 100644 --- a/ios/chrome/browser/ui/toolbar/primary_toolbar_view_controller.mm +++ b/ios/chrome/browser/ui/toolbar/primary_toolbar_view_controller.mm
@@ -137,6 +137,13 @@ } } +- (void)viewDidLoad { + [super viewDidLoad]; + if (@available(iOS 13, *)) { + [self updateLayoutForPreviousTraitCollection:nil]; + } +} + - (void)didMoveToParentViewController:(UIViewController*)parent { [super didMoveToParentViewController:parent]; UIView* omniboxView = self.view.locationBarContainer; @@ -146,24 +153,7 @@ - (void)traitCollectionDidChange:(UITraitCollection*)previousTraitCollection { [super traitCollectionDidChange:previousTraitCollection]; - [self.delegate - viewControllerTraitCollectionDidChange:previousTraitCollection]; - if (IsCompactHeight(self)) { - self.view.locationBarExtraBottomPadding.constant = - kAdaptiveLocationBarExtraVerticalMargin; - } else { - self.view.locationBarExtraBottomPadding.constant = 0; - } - self.view.locationBarBottomConstraint.constant = - [self verticalMarginForLocationBarForFullscreenProgress: - self.previousFullscreenProgress]; - if (previousTraitCollection.preferredContentSizeCategory != - self.traitCollection.preferredContentSizeCategory) { - self.view.locationBarHeight.constant = [self - locationBarHeightForFullscreenProgress:self.previousFullscreenProgress]; - self.view.locationBarContainer.layer.cornerRadius = - self.view.locationBarHeight.constant / 2; - } + [self updateLayoutForPreviousTraitCollection:previousTraitCollection]; } #pragma mark - Property accessors @@ -266,6 +256,28 @@ #pragma mark - Private +- (void)updateLayoutForPreviousTraitCollection: + (UITraitCollection*)previousTraitCollection { + [self.delegate + viewControllerTraitCollectionDidChange:previousTraitCollection]; + if (IsCompactHeight(self)) { + self.view.locationBarExtraBottomPadding.constant = + kAdaptiveLocationBarExtraVerticalMargin; + } else { + self.view.locationBarExtraBottomPadding.constant = 0; + } + self.view.locationBarBottomConstraint.constant = + [self verticalMarginForLocationBarForFullscreenProgress: + self.previousFullscreenProgress]; + if (previousTraitCollection.preferredContentSizeCategory != + self.traitCollection.preferredContentSizeCategory) { + self.view.locationBarHeight.constant = [self + locationBarHeightForFullscreenProgress:self.previousFullscreenProgress]; + self.view.locationBarContainer.layer.cornerRadius = + self.view.locationBarHeight.constant / 2; + } +} + - (CGFloat)clampedFontSizeMultiplier { return ToolbarClampedFontSizeMultiplier( self.traitCollection.preferredContentSizeCategory);
diff --git a/ios/web/BUILD.gn b/ios/web/BUILD.gn index 0c467c8..f6afc02b 100644 --- a/ios/web/BUILD.gn +++ b/ios/web/BUILD.gn
@@ -508,7 +508,6 @@ "//ios/web/test:test_support", "//ios/web/web_state:context_menu", "//ios/web/web_state/js", - "//ios/web/web_state/ui:crw_wk_script_message_router", "//net:test_support", "//services/service_manager/public/cpp", "//testing/gmock", @@ -555,7 +554,6 @@ "//ios/web/web_state:context_menu", "//ios/web/web_state/js", "//ios/web/web_state/ui:crw_context_menu_controller", - "//ios/web/web_state/ui:crw_wk_script_message_router", "//ios/web/web_state/ui:favicon_util", "//net:test_support", "//services/service_manager/public/cpp", @@ -570,7 +568,6 @@ "web_state/ui/crw_web_view_content_view_unittest.mm", "web_state/ui/crw_web_view_proxy_impl_unittest.mm", "web_state/ui/crw_web_view_scroll_view_proxy_unittest.mm", - "web_state/ui/crw_wk_script_message_router_unittest.mm", "web_state/ui/favicon_util_unittest.mm", "web_state/ui/html_element_fetch_request_unittest.mm", "web_state/ui/web_view_js_utils_unittest.mm",
diff --git a/ios/web/js_messaging/BUILD.gn b/ios/web/js_messaging/BUILD.gn index 7339ed9..a86c192d 100644 --- a/ios/web/js_messaging/BUILD.gn +++ b/ios/web/js_messaging/BUILD.gn
@@ -9,6 +9,7 @@ deps = [ "//base", "//crypto", + "//ios/web/navigation:wk_navigation_util", "//ios/web/public", "//ios/web/public/deprecated", "//ios/web/public/js_messaging", @@ -21,6 +22,8 @@ "crw_js_injector.mm", "crw_js_window_id_manager.h", "crw_js_window_id_manager.mm", + "crw_wk_script_message_router.h", + "crw_wk_script_message_router.mm", "page_script_util.h", "page_script_util.mm", "web_frame_impl.h", @@ -45,10 +48,12 @@ "//ios/web/public/test", "//ios/web/public/test/fakes", "//testing/gtest", + "//third_party/ocmock", ] sources = [ "crw_js_window_id_manager_unittest.mm", + "crw_wk_script_message_router_unittest.mm", "page_script_util_unittest.mm", "web_frame_impl_unittest.mm", "web_frame_util_unittest.mm",
diff --git a/ios/web/web_state/ui/crw_wk_script_message_router.h b/ios/web/js_messaging/crw_wk_script_message_router.h similarity index 89% rename from ios/web/web_state/ui/crw_wk_script_message_router.h rename to ios/web/js_messaging/crw_wk_script_message_router.h index c24a25f0..595ecec 100644 --- a/ios/web/web_state/ui/crw_wk_script_message_router.h +++ b/ios/web/js_messaging/crw_wk_script_message_router.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef IOS_WEB_WEB_STATE_UI_CRW_WK_SCRIPT_MESSAGE_ROUTER_H_ -#define IOS_WEB_WEB_STATE_UI_CRW_WK_SCRIPT_MESSAGE_ROUTER_H_ +#ifndef IOS_WEB_JS_MESSAGING_CRW_WK_SCRIPT_MESSAGE_ROUTER_H_ +#define IOS_WEB_JS_MESSAGING_CRW_WK_SCRIPT_MESSAGE_ROUTER_H_ #import <WebKit/WebKit.h> @@ -41,4 +41,4 @@ @end -#endif // IOS_WEB_WEB_STATE_UI_CRW_WK_SCRIPT_MESSAGE_ROUTER_H_ +#endif // IOS_WEB_JS_MESSAGING_CRW_WK_SCRIPT_MESSAGE_ROUTER_H_
diff --git a/ios/web/web_state/ui/crw_wk_script_message_router.mm b/ios/web/js_messaging/crw_wk_script_message_router.mm similarity index 96% rename from ios/web/web_state/ui/crw_wk_script_message_router.mm rename to ios/web/js_messaging/crw_wk_script_message_router.mm index d501501..99dc4a5 100644 --- a/ios/web/web_state/ui/crw_wk_script_message_router.mm +++ b/ios/web/js_messaging/crw_wk_script_message_router.mm
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#import "ios/web/web_state/ui/crw_wk_script_message_router.h" +#import "ios/web/js_messaging/crw_wk_script_message_router.h" #include "base/logging.h" #include "ios/web/navigation/wk_navigation_util.h" @@ -12,7 +12,7 @@ #error "This file requires ARC support." #endif -@interface CRWWKScriptMessageRouter ()<WKScriptMessageHandler> +@interface CRWWKScriptMessageRouter () <WKScriptMessageHandler> // Removes a specific message handler. Does nothing if handler does not exist. - (void)tryRemoveScriptMessageHandlerForName:(NSString*)messageName
diff --git a/ios/web/web_state/ui/crw_wk_script_message_router_unittest.mm b/ios/web/js_messaging/crw_wk_script_message_router_unittest.mm similarity index 98% rename from ios/web/web_state/ui/crw_wk_script_message_router_unittest.mm rename to ios/web/js_messaging/crw_wk_script_message_router_unittest.mm index de8d4b65..8a609dd8 100644 --- a/ios/web/web_state/ui/crw_wk_script_message_router_unittest.mm +++ b/ios/web/js_messaging/crw_wk_script_message_router_unittest.mm
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#import "ios/web/web_state/ui/crw_wk_script_message_router.h" +#import "ios/web/js_messaging/crw_wk_script_message_router.h" #include "base/mac/scoped_block.h" #include "base/memory/ptr_util.h"
diff --git a/ios/web/navigation/crw_web_view_navigation_observer.mm b/ios/web/navigation/crw_web_view_navigation_observer.mm index 696990a0..1a0ca1c28 100644 --- a/ios/web/navigation/crw_web_view_navigation_observer.mm +++ b/ios/web/navigation/crw_web_view_navigation_observer.mm
@@ -75,7 +75,8 @@ @"estimatedProgress" : @"webViewEstimatedProgressDidChange", @"loading" : @"webViewLoadingStateDidChange", @"canGoForward" : @"webViewBackForwardStateDidChange", - @"canGoBack" : @"webViewBackForwardStateDidChange" + @"canGoBack" : @"webViewBackForwardStateDidChange", + @"URL" : @"webViewURLDidChange", }; } @@ -182,8 +183,7 @@ // signal page change explicitly. DCHECK_EQ(self.documentURL.GetOrigin(), webViewURL.GetOrigin()); BOOL isSameDocumentNavigation = - [self.delegate navigationObserver:self - isURLChangeSameDocumentNavigation:webViewURL]; + [self isKVOChangePotentialSameDocumentNavigationToURL:webViewURL]; [self.delegate navigationObserver:self didChangeDocumentURL:webViewURL @@ -221,4 +221,186 @@ self.webStateImpl->OnBackForwardStateChanged(); } +// Called when WKWebView URL has been changed. +- (void)webViewURLDidChange { + // TODO(crbug.com/966412): Determine if there are any cases where this still + // happens, and if so whether anything should be done when it does. + if (!self.webView.URL) { + DVLOG(1) << "Received nil URL callback"; + return; + } + GURL URL(net::GURLWithNSURL(self.webView.URL)); + // URL changes happen at four points: + // 1) When a load starts; at this point, the load is provisional, and + // it should be ignored until it's committed, since the document/window + // objects haven't changed yet. + // 2) When a non-document-changing URL change happens (hash change, + // history.pushState, etc.). This URL change happens instantly, so should + // be reported. + // 3) When a navigation error occurs after provisional navigation starts, + // the URL reverts to the previous URL without triggering a new navigation. + // 4) When a SafeBrowsing warning is displayed after + // decidePolicyForNavigationAction but before a provisional navigation + // starts, and the user clicks the "Go Back" link on the warning page. + // + // If |isLoading| is NO, then it must be case 2, 3, or 4. If the last + // committed URL (_documentURL) matches the current URL, assume that it is + // case 4 if a SafeBrowsing warning is currently displayed and case 3 + // otherwise. If the URL does not match, assume it is a non-document-changing + // URL change, and handle accordingly. + // + // If |isLoading| is YES, then it could either be case 1, or it could be case + // 2 on a page that hasn't finished loading yet. If it's possible that it + // could be a same-page navigation (in which case there may not be any other + // callback about the URL having changed), then check the actual page URL via + // JavaScript. If the origin of the new URL matches the last committed URL, + // then check window.location.href, and if it matches, trust it. The origin + // check ensures that if a site somehow corrupts window.location.href it can't + // do a redirect to a slow-loading target page while it is still loading to + // spoof the origin. On a document-changing URL change, the + // window.location.href will match the previous URL at this stage, not the web + // view's current URL. + if (!self.webView.loading) { + if (self.documentURL == URL) { + if (!web::IsSafeBrowsingWarningDisplayedInWebView(self.webView)) + return; + + self.navigationManagerImpl->DiscardNonCommittedItems(); + self.webStateImpl->SetIsLoading(false); + self.navigationHandler.pendingNavigationInfo = nil; + if (web::GetWebClient()->IsSlimNavigationManagerEnabled()) { + // Right after a history navigation that gets cancelled by a tap on + // "Go Back", WKWebView's current back/forward list item will still be + // for the unsafe page; updating this is the responsibility of the + // WebProcess, so only happens after an IPC round-trip to and from the + // WebProcess with no notification to the embedder. This means that + // WKBasedNavigationManagerImpl::WKWebViewCache::GetCurrentItemIndex() + // will be the index of the unsafe page's item. To get back into a + // consistent state, force a reload. + [self.webView reload]; + } else { + // Tapping "Go Back" on a SafeBrowsing interstitial can change whether + // there are any forward or back items, e.g., by returning to or + // moving away from the forward-most or back-most item. + self.webStateImpl->OnBackForwardStateChanged(); + } + return; + } + + // At this point, self.webView, self.webView.backForwardList.currentItem and + // its associated NavigationItem should all have the same URL, except in two + // edge cases: + // 1. location.replace that only changes hash: WebKit updates + // self.webView.URL + // and currentItem.URL, and NavigationItem URL must be synced. + // 2. location.replace to about: URL: a WebKit bug causes only + // self.webView.URL, + // but not currentItem.URL to be updated. NavigationItem URL should be + // synced to self.webView.URL. + // This needs to be done before |URLDidChangeWithoutDocumentChange| so any + // WebStateObserver callbacks will see the updated URL. + // TODO(crbug.com/809287) use currentItem.URL instead of self.webView.URL to + // update NavigationItem URL. + if (web::GetWebClient()->IsSlimNavigationManagerEnabled()) { + const GURL webViewURL = net::GURLWithNSURL(self.webView.URL); + web::NavigationItem* currentItem = nullptr; + if (self.webView.backForwardList.currentItem) { + currentItem = [[CRWNavigationItemHolder + holderForBackForwardListItem:self.webView.backForwardList + .currentItem] navigationItem]; + } else { + // WKBackForwardList.currentItem may be nil in a corner case when + // location.replace is called with about:blank#hash in an empty window + // open tab. See crbug.com/866142. + DCHECK(self.webStateImpl->HasOpener()); + DCHECK(!self.navigationManagerImpl->GetTransientItem()); + DCHECK(!self.navigationManagerImpl->GetPendingItem()); + currentItem = self.navigationManagerImpl->GetLastCommittedItem(); + } + if (currentItem && webViewURL != currentItem->GetURL()) + currentItem->SetURL(webViewURL); + } + + [self.delegate navigationObserver:self + URLDidChangeWithoutDocumentChange:URL]; + } else if ([self isKVOChangePotentialSameDocumentNavigationToURL:URL]) { + WKNavigation* navigation = + [self.navigationHandler.navigationStates lastAddedNavigation]; + [self.webView + evaluateJavaScript:@"window.location.href" + completionHandler:^(id result, NSError* error) { + // If the web view has gone away, or the location + // couldn't be retrieved, abort. + if (!self.webView || ![result isKindOfClass:[NSString class]]) { + return; + } + GURL JSURL(base::SysNSStringToUTF8(result)); + // Check that window.location matches the new URL. If + // it does not, this is a document-changing URL change as + // the window location would not have changed to the new + // URL when the script was called. + BOOL windowLocationMatchesNewURL = JSURL == URL; + // Re-check origin in case navigaton has occurred since + // start of JavaScript evaluation. + BOOL newURLOriginMatchesDocumentURLOrigin = + self.documentURL.GetOrigin() == URL.GetOrigin(); + // Check that the web view URL still matches the new URL. + // TODO(crbug.com/563568): webViewURLMatchesNewURL check + // may drop same document URL changes if pending URL + // change occurs immediately after. Revisit heuristics to + // prevent this. + BOOL webViewURLMatchesNewURL = + net::GURLWithNSURL(self.webView.URL) == URL; + // Check that the new URL is different from the current + // document URL. If not, URL change should not be reported. + BOOL URLDidChangeFromDocumentURL = URL != self.documentURL; + // Check if a new different document navigation started before the JS + // completion block fires. Check WKNavigationState to make sure this + // navigation has started in WKWebView. If so, don't run the block to + // avoid clobbering global states. See crbug.com/788452. + // TODO(crbug.com/788465): simplify hisgtory state handling to avoid + // this hack. + WKNavigation* last_added_navigation = + [self.navigationHandler.navigationStates lastAddedNavigation]; + BOOL differentDocumentNavigationStarted = + navigation != last_added_navigation && + [self.navigationHandler.navigationStates + stateForNavigation:last_added_navigation] >= + web::WKNavigationState::STARTED; + if (windowLocationMatchesNewURL && + newURLOriginMatchesDocumentURLOrigin && + webViewURLMatchesNewURL && URLDidChangeFromDocumentURL && + !differentDocumentNavigationStarted) { + [self.delegate navigationObserver:self + URLDidChangeWithoutDocumentChange:URL]; + } + }]; + } +} + +#pragma mark - Private + +// Returns YES if a KVO change to |newURL| could be a 'navigation' within the +// document (hash change, pushState/replaceState, etc.). This should only be +// used in the context of a URL KVO callback firing, and only if |isLoading| is +// YES for the web view (since if it's not, no guesswork is needed). +- (BOOL)isKVOChangePotentialSameDocumentNavigationToURL:(const GURL&)newURL { + // If the origin changes, it can't be same-document. + if (self.documentURL.GetOrigin().is_empty() || + self.documentURL.GetOrigin() != newURL.GetOrigin()) { + return NO; + } + if (self.navigationHandler.navigationState == + web::WKNavigationState::REQUESTED) { + // Normally LOAD_REQUESTED indicates that this is a regular, pending + // navigation, but it can also happen during a fast-back navigation across + // a hash change, so that case is potentially a same-document navigation. + return web::GURLByRemovingRefFromGURL(newURL) == + web::GURLByRemovingRefFromGURL(self.documentURL); + } + // If it passes all the checks above, it might be (but there's no guarantee + // that it is). + return YES; +} + @end
diff --git a/ios/web/navigation/crw_web_view_navigation_observer_delegate.h b/ios/web/navigation/crw_web_view_navigation_observer_delegate.h index 1ffd9f7..2577345 100644 --- a/ios/web/navigation/crw_web_view_navigation_observer_delegate.h +++ b/ios/web/navigation/crw_web_view_navigation_observer_delegate.h
@@ -59,9 +59,9 @@ didLoadNewURL:(const GURL&)webViewURL forSameDocumentNavigation:(BOOL)isSameDocumentNavigation; -// Returns whether the navigation to |URL| is a navigation in the same document. -- (BOOL)navigationObserver:(CRWWebViewNavigationObserver*)navigationObserver - isURLChangeSameDocumentNavigation:(const GURL&)URL; +// Notifies the delegate that a non-document-changing URL change occurs. +- (void)navigationObserver:(CRWWebViewNavigationObserver*)navigationObserver + URLDidChangeWithoutDocumentChange:(const GURL&)newURL; @end
diff --git a/ios/web/navigation/crw_wk_navigation_handler.mm b/ios/web/navigation/crw_wk_navigation_handler.mm index 3d7b6d78..ac03ac5 100644 --- a/ios/web/navigation/crw_wk_navigation_handler.mm +++ b/ios/web/navigation/crw_wk_navigation_handler.mm
@@ -256,7 +256,6 @@ // Invalid URLs should not be loaded. if (!requestURL.is_valid()) { - decisionHandler(WKNavigationActionPolicyCancel); // The HTML5 spec indicates that window.open with an invalid URL should open // about:blank. BOOL isFirstLoadInOpenedWindow = @@ -264,13 +263,13 @@ !self.webStateImpl->GetNavigationManager()->GetLastCommittedItem(); BOOL isMainFrame = action.targetFrame.mainFrame; if (isFirstLoadInOpenedWindow && isMainFrame) { + decisionHandler(WKNavigationActionPolicyCancel); GURL aboutBlankURL(url::kAboutBlankURL); web::NavigationManager::WebLoadParams loadParams(aboutBlankURL); loadParams.referrer = self.currentReferrer; self.webStateImpl->GetNavigationManager()->LoadURLWithParams(loadParams); } - return; } // First check if the navigation action should be blocked by the controller @@ -363,11 +362,15 @@ } else { if (action.targetFrame.mainFrame) { [self.pendingNavigationInfo setCancelled:YES]; - // Discard the pending item to ensure that the current URL is not - // different from what is displayed on the view. Discard only happens - // if the last item was not a native view, to avoid ugly animation of - // inserting the webview. - [self discardNonCommittedItemsIfLastCommittedWasNotNativeView]; + if (!web::features::StorePendingItemInContext() || + self.navigationManagerImpl->GetPendingItemIndex() == -1) { + // Discard the new pending item to ensure that the current URL is not + // different from what is displayed on the view. Discard only happens + // if the last item was not a native view, to avoid ugly animation of + // inserting the webview. There is no need to reset pending item index + // for a different pending back-forward navigation. + [self discardNonCommittedItemsIfLastCommittedWasNotNativeView]; + } web::NavigationContextImpl* context = [self contextForPendingMainFrameNavigationWithURL:requestURL]; @@ -1783,6 +1786,19 @@ self.webStateImpl->SetIsLoading(false); return; } + + if (error.code == web::kWebKitErrorCannotShowUrl) { + if (!navigationContext->GetUrl().is_valid()) { + // It won't be possible to load an error page for invalid URL, because + // WKWebView will revert the url to about:blank. Simply discard pending + // item and fail the navigation. + navigationContext->ReleaseItem(); + self.webStateImpl->OnNavigationFinished(navigationContext); + self.webStateImpl->SetIsLoading(false); + self.webStateImpl->OnPageLoaded(navigationContext->GetUrl(), false); + return; + } + } } web::NavigationManager* navManager =
diff --git a/ios/web/web_state/ui/BUILD.gn b/ios/web/web_state/ui/BUILD.gn index fb5781d6..55dcb4bc 100644 --- a/ios/web/web_state/ui/BUILD.gn +++ b/ios/web/web_state/ui/BUILD.gn
@@ -8,7 +8,6 @@ deps = [ ":crw_context_menu_controller", ":crw_web_view_navigation_proxy", - ":crw_wk_script_message_router", ":favicon_util", "//base", "//ios/net", @@ -69,24 +68,6 @@ configs += [ "//build/config/compiler:enable_arc" ] } -source_set("crw_wk_script_message_router") { - deps = [ - "//base", - "//ios/web/navigation:core", - "//ios/web/navigation:wk_navigation_util", - "//net", - ] - - sources = [ - "crw_wk_script_message_router.h", - "crw_wk_script_message_router.mm", - ] - - libs = [ "WebKit.framework" ] - - configs += [ "//build/config/compiler:enable_arc" ] -} - source_set("crw_web_view_navigation_proxy") { sources = [ "crw_web_view_navigation_proxy.h", @@ -100,10 +81,10 @@ source_set("crw_context_menu_controller") { deps = [ "//base", + "//ios/web/js_messaging", "//ios/web/public", "//ios/web/public/deprecated", "//ios/web/web_state:context_menu", - "//ios/web/web_state/ui:crw_wk_script_message_router", "//ios/web/web_state/ui:wk_web_view_configuration_provider", ] @@ -119,7 +100,6 @@ source_set("wk_web_view_configuration_provider") { deps = [ - ":crw_wk_script_message_router", "//base", "//ios/web/common", "//ios/web/js_messaging",
diff --git a/ios/web/web_state/ui/crw_context_menu_controller.mm b/ios/web/web_state/ui/crw_context_menu_controller.mm index 4e2f31b..84f8b12 100644 --- a/ios/web/web_state/ui/crw_context_menu_controller.mm +++ b/ios/web/web_state/ui/crw_context_menu_controller.mm
@@ -13,11 +13,11 @@ #include "base/metrics/histogram_macros.h" #include "base/strings/sys_string_conversions.h" #include "base/unguessable_token.h" +#import "ios/web/js_messaging/crw_wk_script_message_router.h" #import "ios/web/public/deprecated/crw_context_menu_delegate.h" #import "ios/web/public/web_state/context_menu_params.h" #import "ios/web/web_state/context_menu_constants.h" #import "ios/web/web_state/context_menu_params_utils.h" -#import "ios/web/web_state/ui/crw_wk_script_message_router.h" #import "ios/web/web_state/ui/html_element_fetch_request.h" #import "ios/web/web_state/ui/wk_web_view_configuration_provider.h"
diff --git a/ios/web/web_state/ui/crw_web_controller.mm b/ios/web/web_state/ui/crw_web_controller.mm index de9a7561..d9271c83c 100644 --- a/ios/web/web_state/ui/crw_web_controller.mm +++ b/ios/web/web_state/ui/crw_web_controller.mm
@@ -51,6 +51,7 @@ #import "ios/web/find_in_page/find_in_page_manager_impl.h" #include "ios/web/history_state_util.h" #import "ios/web/js_messaging/crw_js_injector.h" +#import "ios/web/js_messaging/crw_wk_script_message_router.h" #import "ios/web/js_messaging/web_frame_impl.h" #import "ios/web/js_messaging/web_frames_manager_impl.h" #import "ios/web/navigation/crw_navigation_item_holder.h" @@ -107,7 +108,6 @@ #import "ios/web/web_state/ui/crw_web_controller_container_view.h" #import "ios/web/web_state/ui/crw_web_view_navigation_proxy.h" #import "ios/web/web_state/ui/crw_web_view_proxy_impl.h" -#import "ios/web/web_state/ui/crw_wk_script_message_router.h" #import "ios/web/web_state/ui/crw_wk_ui_handler.h" #import "ios/web/web_state/ui/crw_wk_ui_handler_delegate.h" #import "ios/web/web_state/ui/favicon_util.h" @@ -638,7 +638,6 @@ @"serverTrust" : @"webViewSecurityFeaturesDidChange", @"hasOnlySecureContent" : @"webViewSecurityFeaturesDidChange", @"title" : @"webViewTitleDidChange", - @"URL" : @"webViewURLDidChange", }; } @@ -3179,189 +3178,74 @@ } } -// Called when WKWebView URL has been changed. -- (void)webViewURLDidChange { - // TODO(stuartmorgan): Determine if there are any cases where this still - // happens, and if so whether anything should be done when it does. - if (!self.webView.URL) { - DVLOG(1) << "Received nil URL callback"; - return; - } - GURL URL(net::GURLWithNSURL(self.webView.URL)); - // URL changes happen at four points: - // 1) When a load starts; at this point, the load is provisional, and - // it should be ignored until it's committed, since the document/window - // objects haven't changed yet. - // 2) When a non-document-changing URL change happens (hash change, - // history.pushState, etc.). This URL change happens instantly, so should - // be reported. - // 3) When a navigation error occurs after provisional navigation starts, - // the URL reverts to the previous URL without triggering a new navigation. - // 4) When a SafeBrowsing warning is displayed after - // decidePolicyForNavigationAction but before a provisional navigation - // starts, and the user clicks the "Go Back" link on the warning page. - // - // If |isLoading| is NO, then it must be case 2, 3, or 4. If the last - // committed URL (_documentURL) matches the current URL, assume that it is - // case 4 if a SafeBrowsing warning is currently displayed and case 3 - // otherwise. If the URL does not match, assume it is a non-document-changing - // URL change, and handle accordingly. - // - // If |isLoading| is YES, then it could either be case 1, or it could be case - // 2 on a page that hasn't finished loading yet. If it's possible that it - // could be a same-page navigation (in which case there may not be any other - // callback about the URL having changed), then check the actual page URL via - // JavaScript. If the origin of the new URL matches the last committed URL, - // then check window.location.href, and if it matches, trust it. The origin - // check ensures that if a site somehow corrupts window.location.href it can't - // do a redirect to a slow-loading target page while it is still loading to - // spoof the origin. On a document-changing URL change, the - // window.location.href will match the previous URL at this stage, not the web - // view's current URL. - if (!self.webView.loading) { - if (_documentURL == URL) { - if (!web::IsSafeBrowsingWarningDisplayedInWebView(self.webView)) - return; +#pragma mark - CRWWebViewNavigationObserverDelegate - self.navigationManagerImpl->DiscardNonCommittedItems(); - self.webStateImpl->SetIsLoading(false); - self.navigationHandler.pendingNavigationInfo = nil; - if (web::GetWebClient()->IsSlimNavigationManagerEnabled()) { - // Right after a history navigation that gets cancelled by a tap on - // "Go Back", WKWebView's current back/forward list item will still be - // for the unsafe page; updating this is the responsibility of the - // WebProcess, so only happens after an IPC round-trip to and from the - // WebProcess with no notification to the embedder. This means that - // WKBasedNavigationManagerImpl::WKWebViewCache::GetCurrentItemIndex() - // will be the index of the unsafe page's item. To get back into a - // consistent state, force a reload. - [self.webView reload]; - } else { - // Tapping "Go Back" on a SafeBrowsing interstitial can change whether - // there are any forward or back items, e.g., by returning to or - // moving away from the forward-most or back-most item. - self.webStateImpl->OnBackForwardStateChanged(); - } - return; - } +- (BOOL)webViewIsBeingDestroyed: + (CRWWebViewNavigationObserver*)navigationObserver { + return _isBeingDestroyed; +} - // At this point, self.webView, self.webView.backForwardList.currentItem and - // its associated NavigationItem should all have the same URL, except in two - // edge cases: - // 1. location.replace that only changes hash: WebKit updates - // self.webView.URL - // and currentItem.URL, and NavigationItem URL must be synced. - // 2. location.replace to about: URL: a WebKit bug causes only - // self.webView.URL, - // but not currentItem.URL to be updated. NavigationItem URL should be - // synced to self.webView.URL. - // This needs to be done before |URLDidChangeWithoutDocumentChange| so any - // WebStateObserver callbacks will see the updated URL. - // TODO(crbug.com/809287) use currentItem.URL instead of self.webView.URL to - // update NavigationItem URL. - if (web::GetWebClient()->IsSlimNavigationManagerEnabled()) { - const GURL webViewURL = net::GURLWithNSURL(self.webView.URL); - web::NavigationItem* currentItem = nullptr; - if (self.webView.backForwardList.currentItem) { - currentItem = [[CRWNavigationItemHolder - holderForBackForwardListItem:self.webView.backForwardList - .currentItem] navigationItem]; - } else { - // WKBackForwardList.currentItem may be nil in a corner case when - // location.replace is called with about:blank#hash in an empty window - // open tab. See crbug.com/866142. - DCHECK(self.webStateImpl->HasOpener()); - DCHECK(!self.navigationManagerImpl->GetTransientItem()); - DCHECK(!self.navigationManagerImpl->GetPendingItem()); - currentItem = self.navigationManagerImpl->GetLastCommittedItem(); - } - if (currentItem && webViewURL != currentItem->GetURL()) - currentItem->SetURL(webViewURL); - } +- (web::WebStateImpl*)webStateImplForNavigationObserver: + (CRWWebViewNavigationObserver*)navigationObserver { + return self.webStateImpl; +} - [self URLDidChangeWithoutDocumentChange:URL]; - } else if ([self isKVOChangePotentialSameDocumentNavigationToURL:URL]) { - WKNavigation* navigation = - [self.navigationHandler.navigationStates lastAddedNavigation]; - [self.webView - evaluateJavaScript:@"window.location.href" - completionHandler:^(id result, NSError* error) { - // If the web view has gone away, or the location - // couldn't be retrieved, abort. - if (!self.webView || ![result isKindOfClass:[NSString class]]) { - return; - } - GURL JSURL(base::SysNSStringToUTF8(result)); - // Check that window.location matches the new URL. If - // it does not, this is a document-changing URL change as - // the window location would not have changed to the new - // URL when the script was called. - BOOL windowLocationMatchesNewURL = JSURL == URL; - // Re-check origin in case navigaton has occurred since - // start of JavaScript evaluation. - BOOL newURLOriginMatchesDocumentURLOrigin = - _documentURL.GetOrigin() == URL.GetOrigin(); - // Check that the web view URL still matches the new URL. - // TODO(crbug.com/563568): webViewURLMatchesNewURL check - // may drop same document URL changes if pending URL - // change occurs immediately after. Revisit heuristics to - // prevent this. - BOOL webViewURLMatchesNewURL = - net::GURLWithNSURL(self.webView.URL) == URL; - // Check that the new URL is different from the current - // document URL. If not, URL change should not be reported. - BOOL URLDidChangeFromDocumentURL = URL != _documentURL; - // Check if a new different document navigation started before the JS - // completion block fires. Check WKNavigationState to make sure this - // navigation has started in WKWebView. If so, don't run the block to - // avoid clobbering global states. See crbug.com/788452. - // TODO(crbug.com/788465): simplify hisgtory state handling to avoid - // this hack. - WKNavigation* last_added_navigation = - [self.navigationHandler.navigationStates lastAddedNavigation]; - BOOL differentDocumentNavigationStarted = - navigation != last_added_navigation && - [self.navigationHandler.navigationStates - stateForNavigation:last_added_navigation] >= - web::WKNavigationState::STARTED; - if (windowLocationMatchesNewURL && - newURLOriginMatchesDocumentURLOrigin && - webViewURLMatchesNewURL && URLDidChangeFromDocumentURL && - !differentDocumentNavigationStarted) { - [self URLDidChangeWithoutDocumentChange:URL]; - } - }]; +- (CRWWKNavigationHandler*)navigationHandlerForNavigationObserver: + (CRWWebViewNavigationObserver*)navigationObserver { + return self.navigationHandler; +} + +- (const GURL&)documentURLForNavigationObserver: + (CRWWebViewNavigationObserver*)navigationObserver { + return _documentURL; +} + +- (void)navigationObserverDidChangeSSLStatus: + (CRWWebViewNavigationObserver*)navigationObserver { + [self updateSSLStatusForCurrentNavigationItem]; +} + +- (void)navigationObserver:(CRWWebViewNavigationObserver*)navigationObserver + didFinishNavigation:(web::NavigationContextImpl*)context { + [self didFinishNavigation:context]; +} + +- (void)navigationObserver:(CRWWebViewNavigationObserver*)navigationObserver + didChangeDocumentURL:(const GURL&)documentURL + forContext:(web::NavigationContextImpl*)context { + [self setDocumentURL:documentURL context:context]; +} + +- (void)navigationObserver:(CRWWebViewNavigationObserver*)navigationObserver + didChangePageWithContext:(web::NavigationContextImpl*)context { + [self.navigationHandler webPageChangedWithContext:context + webView:self.webView]; +} + +- (void)navigationObserver:(CRWWebViewNavigationObserver*)navigationObserver + didLoadNewURL:(const GURL&)webViewURL + forSameDocumentNavigation:(BOOL)isSameDocumentNavigation { + std::unique_ptr<web::NavigationContextImpl> newContext = + [self registerLoadRequestForURL:webViewURL + sameDocumentNavigation:isSameDocumentNavigation + hasUserGesture:NO + rendererInitiated:YES + placeholderNavigation:IsPlaceholderUrl(webViewURL)]; + [self.navigationHandler webPageChangedWithContext:newContext.get() + webView:self.webView]; + newContext->SetHasCommitted(!isSameDocumentNavigation); + self.webStateImpl->OnNavigationFinished(newContext.get()); + // TODO(crbug.com/792515): It is OK, but very brittle, to call + // |didFinishNavigation:| here because the gating condition is mutually + // exclusive with the condition below. Refactor this method after + // deprecating self.navigationHandler.pendingNavigationInfo. + if (newContext->GetWKNavigationType() == WKNavigationTypeBackForward) { + [self didFinishNavigation:newContext.get()]; } } -#pragma mark - KVO Helpers - -// Returns YES if a KVO change to |newURL| could be a 'navigation' within the -// document (hash change, pushState/replaceState, etc.). This should only be -// used in the context of a URL KVO callback firing, and only if |isLoading| is -// YES for the web view (since if it's not, no guesswork is needed). -- (BOOL)isKVOChangePotentialSameDocumentNavigationToURL:(const GURL&)newURL { - // If the origin changes, it can't be same-document. - if (_documentURL.GetOrigin().is_empty() || - _documentURL.GetOrigin() != newURL.GetOrigin()) { - return NO; - } - if (self.navigationHandler.navigationState == - web::WKNavigationState::REQUESTED) { - // Normally LOAD_REQUESTED indicates that this is a regular, pending - // navigation, but it can also happen during a fast-back navigation across - // a hash change, so that case is potentially a same-document navigation. - return web::GURLByRemovingRefFromGURL(newURL) == - web::GURLByRemovingRefFromGURL(_documentURL); - } - // If it passes all the checks above, it might be (but there's no guarantee - // that it is). - return YES; -} - -// Called when a non-document-changing URL change occurs. Updates the -// _documentURL, and informs the superclass of the change. -- (void)URLDidChangeWithoutDocumentChange:(const GURL&)newURL { +- (void)navigationObserver:(CRWWebViewNavigationObserver*)navigationObserver + URLDidChangeWithoutDocumentChange:(const GURL&)newURL { DCHECK(newURL == net::GURLWithNSURL(self.webView.URL)); if (base::FeatureList::IsEnabled( @@ -3453,77 +3337,6 @@ } } -#pragma mark - CRWWebViewNavigationObserverDelegate - -- (BOOL)webViewIsBeingDestroyed: - (CRWWebViewNavigationObserver*)navigationObserver { - return _isBeingDestroyed; -} - -- (web::WebStateImpl*)webStateImplForNavigationObserver: - (CRWWebViewNavigationObserver*)navigationObserver { - return self.webStateImpl; -} - -- (CRWWKNavigationHandler*)navigationHandlerForNavigationObserver: - (CRWWebViewNavigationObserver*)navigationObserver { - return self.navigationHandler; -} - -- (const GURL&)documentURLForNavigationObserver: - (CRWWebViewNavigationObserver*)navigationObserver { - return _documentURL; -} - -- (void)navigationObserverDidChangeSSLStatus: - (CRWWebViewNavigationObserver*)navigationObserver { - [self updateSSLStatusForCurrentNavigationItem]; -} - -- (void)navigationObserver:(CRWWebViewNavigationObserver*)navigationObserver - didFinishNavigation:(web::NavigationContextImpl*)context { - [self didFinishNavigation:context]; -} - -- (void)navigationObserver:(CRWWebViewNavigationObserver*)navigationObserver - didChangeDocumentURL:(const GURL&)documentURL - forContext:(web::NavigationContextImpl*)context { - [self setDocumentURL:documentURL context:context]; -} - -- (void)navigationObserver:(CRWWebViewNavigationObserver*)navigationObserver - didChangePageWithContext:(web::NavigationContextImpl*)context { - [self.navigationHandler webPageChangedWithContext:context - webView:self.webView]; -} - -- (void)navigationObserver:(CRWWebViewNavigationObserver*)navigationObserver - didLoadNewURL:(const GURL&)webViewURL - forSameDocumentNavigation:(BOOL)isSameDocumentNavigation { - std::unique_ptr<web::NavigationContextImpl> newContext = - [self registerLoadRequestForURL:webViewURL - sameDocumentNavigation:isSameDocumentNavigation - hasUserGesture:NO - rendererInitiated:YES - placeholderNavigation:IsPlaceholderUrl(webViewURL)]; - [self.navigationHandler webPageChangedWithContext:newContext.get() - webView:self.webView]; - newContext->SetHasCommitted(!isSameDocumentNavigation); - self.webStateImpl->OnNavigationFinished(newContext.get()); - // TODO(crbug.com/792515): It is OK, but very brittle, to call - // |didFinishNavigation:| here because the gating condition is mutually - // exclusive with the condition below. Refactor this method after - // deprecating self.navigationHandler.pendingNavigationInfo. - if (newContext->GetWKNavigationType() == WKNavigationTypeBackForward) { - [self didFinishNavigation:newContext.get()]; - } -} - -- (BOOL)navigationObserver:(CRWWebViewNavigationObserver*)navigationObserver - isURLChangeSameDocumentNavigation:(const GURL&)URL { - return [self isKVOChangePotentialSameDocumentNavigationToURL:URL]; -} - #pragma mark - CRWWKNavigationHandlerDelegate - (BOOL)navigationHandlerWebViewBeingDestroyed:
diff --git a/ios/web/web_state/ui/wk_web_view_configuration_provider.mm b/ios/web/web_state/ui/wk_web_view_configuration_provider.mm index e60a18f..f2a451f 100644 --- a/ios/web/web_state/ui/wk_web_view_configuration_provider.mm +++ b/ios/web/web_state/ui/wk_web_view_configuration_provider.mm
@@ -12,10 +12,10 @@ #include "base/memory/ptr_util.h" #include "base/strings/sys_string_conversions.h" #include "ios/web/common/features.h" +#import "ios/web/js_messaging/crw_wk_script_message_router.h" #import "ios/web/js_messaging/page_script_util.h" #include "ios/web/public/browser_state.h" #include "ios/web/public/web_client.h" -#import "ios/web/web_state/ui/crw_wk_script_message_router.h" #import "ios/web/web_state/ui/wk_web_view_configuration_provider_observer.h" #import "ios/web/webui/crw_web_ui_scheme_handler.h"
diff --git a/ios/web/web_state/ui/wk_web_view_configuration_provider_unittest.mm b/ios/web/web_state/ui/wk_web_view_configuration_provider_unittest.mm index 6d2da2ef..66cbead 100644 --- a/ios/web/web_state/ui/wk_web_view_configuration_provider_unittest.mm +++ b/ios/web/web_state/ui/wk_web_view_configuration_provider_unittest.mm
@@ -7,12 +7,12 @@ #import <WebKit/WebKit.h> #include "base/memory/ptr_util.h" +#import "ios/web/js_messaging/crw_wk_script_message_router.h" #import "ios/web/js_messaging/page_script_util.h" #include "ios/web/public/test/fakes/test_browser_state.h" #include "ios/web/public/test/scoped_testing_web_client.h" #import "ios/web/public/web_client.h" #import "ios/web/test/fakes/fake_wk_configuration_provider_observer.h" -#import "ios/web/web_state/ui/crw_wk_script_message_router.h" #include "testing/gtest/include/gtest/gtest.h" #import "testing/gtest_mac.h" #include "testing/platform_test.h"
diff --git a/ios/web/web_state/web_state_observer_inttest.mm b/ios/web/web_state/web_state_observer_inttest.mm index e1fad7c..02ead8e 100644 --- a/ios/web/web_state/web_state_observer_inttest.mm +++ b/ios/web/web_state/web_state_observer_inttest.mm
@@ -329,11 +329,12 @@ // Verifies correctness of |NavigationContext| (|arg1|) for failed navigation // passed to |DidFinishNavigation|. Asserts that |NavigationContext| the same as // |context|. -ACTION_P5(VerifyErrorFinishedContext, +ACTION_P6(VerifyErrorFinishedContext, web_state, url, context, nav_id, + committed, error_code) { ASSERT_EQ(*context, arg1); EXPECT_EQ(web_state, arg0); @@ -346,7 +347,7 @@ PageTransitionCoreTypeIs(ui::PageTransition::PAGE_TRANSITION_TYPED, (*context)->GetPageTransition())); EXPECT_FALSE((*context)->IsSameDocument()); - EXPECT_TRUE((*context)->HasCommitted()); + EXPECT_EQ(committed, (*context)->HasCommitted()); EXPECT_FALSE((*context)->IsDownload()); EXPECT_FALSE((*context)->IsPost()); // The error code will be different on bots and for local runs. Allow both. @@ -358,8 +359,13 @@ ASSERT_FALSE(web_state->ContentIsHTML()); NavigationManager* navigation_manager = web_state->GetNavigationManager(); NavigationItem* item = navigation_manager->GetLastCommittedItem(); - EXPECT_FALSE(item->GetTimestamp().is_null()); - EXPECT_EQ(url, item->GetURL()); + if (committed) { + ASSERT_TRUE(item); + EXPECT_FALSE(item->GetTimestamp().is_null()); + EXPECT_EQ(url, item->GetURL()); + } else { + EXPECT_FALSE(item); + } } // Verifies correctness of |NavigationContext| (|arg1|) passed to @@ -1054,6 +1060,7 @@ &nav_id)); EXPECT_CALL(observer_, DidFinishNavigation(web_state(), _)) .WillOnce(VerifyErrorFinishedContext(web_state(), url, &context, &nav_id, + /*committed=*/true, NSURLErrorNetworkConnectionLost)); EXPECT_CALL(observer_, DidStopLoading(web_state())); EXPECT_CALL(observer_, @@ -1069,6 +1076,44 @@ DCHECK_EQ(item->GetTitle(), base::UTF8ToUTF16(kFailedTitle)); } +// Tests failed navigation because of invalid URL. +TEST_P(WebStateObserverTest, InvalidUrlNavigation) { + const std::string kBadSuffix = "/..;"; + GURL url = test_server_->GetURL(kBadSuffix); + + // WebKit rewrites invalid URLs. + std::string webkit_rewritten_url_spec = url.spec(); + webkit_rewritten_url_spec.replace(url.spec().size() - kBadSuffix.size(), + kBadSuffix.size(), ";/"); + + // Perform a navigation to an ivalid url, which will fail. + NavigationContext* context = nullptr; + int32_t nav_id = 0; + EXPECT_CALL(observer_, DidStartLoading(web_state())); + WebStatePolicyDecider::RequestInfo expected_request_info( + // Can't match NavigationContext and determine navigation type + ui::PageTransition::PAGE_TRANSITION_CLIENT_REDIRECT, + /*target_main_frame=*/true, /*has_user_gesture=*/false); + EXPECT_CALL(*decider_, + ShouldAllowRequest(_, RequestInfoMatch(expected_request_info))) + .WillOnce(Return(true)); + EXPECT_CALL(observer_, DidStartNavigation(web_state(), _)) + .WillOnce(VerifyPageStartedContext( + web_state(), GURL(webkit_rewritten_url_spec), + ui::PageTransition::PAGE_TRANSITION_TYPED, &context, &nav_id)); + + EXPECT_CALL(observer_, DidFinishNavigation(web_state(), _)) + .WillOnce(VerifyErrorFinishedContext( + web_state(), GURL(webkit_rewritten_url_spec), &context, &nav_id, + /*committed=*/false, kWebKitErrorCannotShowUrl)); + EXPECT_CALL(observer_, DidStopLoading(web_state())); + EXPECT_CALL(observer_, + PageLoaded(web_state(), PageLoadCompletionStatus::FAILURE)); + test::LoadUrl(web_state(), url); + ASSERT_TRUE(test::WaitForPageToFinishLoading(web_state())); + EXPECT_EQ("", web_state()->GetVisibleURL()); +} + // Tests failed navigation because URL scheme is not supported by WKWebView. TEST_P(WebStateObserverTest, WebViewUnsupportedSchemeNavigation) { GURL url(url::SchemeHostPort(kTestAppSpecificScheme, "foo", 0).Serialize()); @@ -1089,6 +1134,7 @@ &nav_id)); EXPECT_CALL(observer_, DidFinishNavigation(web_state(), _)) .WillOnce(VerifyErrorFinishedContext(web_state(), url, &context, &nav_id, + /*committed=*/true, NSURLErrorUnsupportedURL)); EXPECT_CALL(observer_, DidStopLoading(web_state())); EXPECT_CALL(observer_, @@ -1118,6 +1164,7 @@ &nav_id)); EXPECT_CALL(observer_, DidFinishNavigation(web_state(), _)) .WillOnce(VerifyErrorFinishedContext(web_state(), url, &context, &nav_id, + /*committed=*/true, web::kWebKitErrorCannotShowUrl)); EXPECT_CALL(observer_, DidStopLoading(web_state())); EXPECT_CALL(observer_,
diff --git a/jingle/glue/fake_ssl_client_socket_unittest.cc b/jingle/glue/fake_ssl_client_socket_unittest.cc index cacd246..89ea3fa 100644 --- a/jingle/glue/fake_ssl_client_socket_unittest.cc +++ b/jingle/glue/fake_ssl_client_socket_unittest.cc
@@ -13,8 +13,8 @@ #include <vector> #include "base/memory/ref_counted.h" -#include "base/message_loop/message_loop.h" #include "base/stl_util.h" +#include "base/test/scoped_task_environment.h" #include "net/base/completion_once_callback.h" #include "net/base/completion_repeating_callback.h" #include "net/base/io_buffer.h" @@ -275,7 +275,7 @@ } // MockTCPClientSocket needs a message loop. - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; net::MockClientSocketFactory mock_client_socket_factory_; std::unique_ptr<net::StaticSocketDataProvider> static_socket_data_provider_;
diff --git a/jingle/glue/network_service_async_socket_unittest.cc b/jingle/glue/network_service_async_socket_unittest.cc index bb66f19..a4fe932 100644 --- a/jingle/glue/network_service_async_socket_unittest.cc +++ b/jingle/glue/network_service_async_socket_unittest.cc
@@ -14,12 +14,12 @@ #include "base/containers/circular_deque.h" #include "base/logging.h" #include "base/memory/ptr_util.h" -#include "base/message_loop/message_loop.h" #include "base/message_loop/message_pump_default.h" #include "base/run_loop.h" #include "base/stl_util.h" #include "base/strings/strcat.h" #include "base/strings/string_number_conversions.h" +#include "base/test/scoped_task_environment.h" #include "mojo/public/cpp/bindings/binding.h" #include "mojo/public/cpp/system/data_pipe_utils.h" #include "net/base/address_list.h" @@ -553,7 +553,7 @@ } // Need a message loop for both the socket and Mojo. - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; AsyncSocketDataProvider async_socket_data_provider_; net::SSLSocketDataProvider ssl_socket_data_provider_;
diff --git a/jingle/glue/task_pump_unittest.cc b/jingle/glue/task_pump_unittest.cc index fa40017..5b00b856 100644 --- a/jingle/glue/task_pump_unittest.cc +++ b/jingle/glue/task_pump_unittest.cc
@@ -4,8 +4,8 @@ #include "jingle/glue/task_pump.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/test/scoped_task_environment.h" #include "jingle/glue/mock_task.h" #include "testing/gtest/include/gtest/gtest.h" @@ -17,7 +17,7 @@ class TaskPumpTest : public testing::Test { private: - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; }; TEST_F(TaskPumpTest, Basic) {
diff --git a/jingle/glue/thread_wrapper_unittest.cc b/jingle/glue/thread_wrapper_unittest.cc index 72ffddf..5653e2a9 100644 --- a/jingle/glue/thread_wrapper_unittest.cc +++ b/jingle/glue/thread_wrapper_unittest.cc
@@ -6,9 +6,9 @@ #include "base/bind.h" #include "base/compiler_specific.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" +#include "base/test/scoped_task_environment.h" #include "base/threading/thread.h" #include "jingle/glue/thread_wrapper.h" #include "testing/gmock/include/gmock/gmock.h" @@ -90,7 +90,7 @@ } // ThreadWrapper destroyes itself when |message_loop_| is destroyed. - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; rtc::Thread* thread_; MockMessageHandler handler1_; MockMessageHandler handler2_; @@ -156,7 +156,7 @@ .WillOnce(DeleteMessageData()); base::RunLoop run_loop; - message_loop_.task_runner()->PostDelayedTask( + scoped_task_environment_.GetMainThreadTaskRunner()->PostDelayedTask( FROM_HERE, run_loop.QuitClosure(), base::TimeDelta::FromMilliseconds(kMaxTestDelay)); run_loop.Run(); @@ -212,7 +212,7 @@ .WillOnce(DeleteMessageData()); base::RunLoop run_loop; - message_loop_.task_runner()->PostDelayedTask( + scoped_task_environment_.GetMainThreadTaskRunner()->PostDelayedTask( FROM_HERE, run_loop.QuitClosure(), base::TimeDelta::FromMilliseconds(kMaxTestDelay)); run_loop.Run();
diff --git a/jingle/notifier/base/weak_xmpp_client_unittest.cc b/jingle/notifier/base/weak_xmpp_client_unittest.cc index 455698b..fa8a2b4 100644 --- a/jingle/notifier/base/weak_xmpp_client_unittest.cc +++ b/jingle/notifier/base/weak_xmpp_client_unittest.cc
@@ -7,8 +7,8 @@ #include <memory> #include "base/memory/weak_ptr.h" -#include "base/message_loop/message_loop.h" #include "base/stl_util.h" +#include "base/test/scoped_task_environment.h" #include "jingle/glue/task_pump.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -61,7 +61,7 @@ } // Needed by TaskPump. - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; std::unique_ptr<jingle_glue::TaskPump> task_pump_; MockXmppDelegate mock_xmpp_delegate_;
diff --git a/jingle/notifier/base/xmpp_connection_unittest.cc b/jingle/notifier/base/xmpp_connection_unittest.cc index 23d6d90..77dbffe 100644 --- a/jingle/notifier/base/xmpp_connection_unittest.cc +++ b/jingle/notifier/base/xmpp_connection_unittest.cc
@@ -10,9 +10,9 @@ #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" -#include "base/message_loop/message_loop.h" #include "base/message_loop/message_pump_default.h" #include "base/run_loop.h" +#include "base/test/scoped_task_environment.h" #include "jingle/glue/mock_task.h" #include "jingle/glue/network_service_config_test_util.h" #include "jingle/glue/task_pump.h" @@ -79,7 +79,7 @@ : mock_pre_xmpp_auth_(new MockPreXmppAuth()), net_config_helper_( base::MakeRefCounted<net::TestURLRequestContextGetter>( - message_loop_.task_runner())) { + scoped_task_environment_.GetMainThreadTaskRunner())) { // GTest death tests by default execute in a fork()ed but not exec()ed // process. On macOS, a CoreFoundation-backed MessageLoop will exit with a // __THE_PROCESS_HAS_FORKED_AND_YOU_CANNOT_USE_THIS_COREFOUNDATION_FUNCTIONALITY___YOU_MUST_EXEC__ @@ -95,7 +95,7 @@ } // Needed by XmppConnection. - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; MockXmppConnectionDelegate mock_xmpp_connection_delegate_; std::unique_ptr<MockPreXmppAuth> mock_pre_xmpp_auth_; jingle_glue::NetworkServiceConfigTestUtil net_config_helper_;
diff --git a/jingle/notifier/communicator/single_login_attempt_unittest.cc b/jingle/notifier/communicator/single_login_attempt_unittest.cc index 1ae95d7..00d63ff 100644 --- a/jingle/notifier/communicator/single_login_attempt_unittest.cc +++ b/jingle/notifier/communicator/single_login_attempt_unittest.cc
@@ -8,8 +8,8 @@ #include <memory> #include "base/compiler_specific.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/test/scoped_task_environment.h" #include "base/threading/thread_task_runner_handle.h" #include "jingle/glue/network_service_config_test_util.h" #include "jingle/notifier/base/const_communicator.h" @@ -111,7 +111,7 @@ } private: - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; jingle_glue::NetworkServiceConfigTestUtil net_config_helper_; const LoginSettings login_settings_;
diff --git a/jingle/notifier/listener/non_blocking_push_client_unittest.cc b/jingle/notifier/listener/non_blocking_push_client_unittest.cc index 8ec10395..1ed9b17 100644 --- a/jingle/notifier/listener/non_blocking_push_client_unittest.cc +++ b/jingle/notifier/listener/non_blocking_push_client_unittest.cc
@@ -9,8 +9,8 @@ #include "base/bind.h" #include "base/compiler_specific.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/test/scoped_task_environment.h" #include "base/threading/thread_task_runner_handle.h" #include "jingle/notifier/base/fake_base_task.h" #include "jingle/notifier/listener/fake_push_client.h" @@ -60,7 +60,7 @@ return std::unique_ptr<PushClient>(fake_push_client_); } - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; FakePushClientObserver fake_observer_; std::unique_ptr<NonBlockingPushClient> push_client_; // Owned by |push_client_|.
diff --git a/media/capture/video/chromeos/camera_device_delegate.cc b/media/capture/video/chromeos/camera_device_delegate.cc index d352f7f3..74804484 100644 --- a/media/capture/video/chromeos/camera_device_delegate.cc +++ b/media/capture/video/chromeos/camera_device_delegate.cc
@@ -545,6 +545,7 @@ chrome_capture_params_.requested_format.frame_size.height(); preview_stream->format = cros::mojom::HalPixelFormat::HAL_PIXEL_FORMAT_YCbCr_420_888; + preview_stream->usage = cros::mojom::GRALLOC_USAGE_HW_COMPOSER; preview_stream->data_space = 0; preview_stream->rotation = cros::mojom::Camera3StreamRotation::CAMERA3_STREAM_ROTATION_0;
diff --git a/media/capture/video/chromeos/mojo/camera3.mojom b/media/capture/video/chromeos/mojo/camera3.mojom index 1ce2e11..3d103348 100644 --- a/media/capture/video/chromeos/mojo/camera3.mojom +++ b/media/capture/video/chromeos/mojo/camera3.mojom
@@ -8,6 +8,17 @@ import "media/capture/video/chromeos/mojo/camera_metadata.mojom"; +// These usages flags are defined in gralloc.h. They determine the nature of +// the buffers allocated by gralloc. Read more on: +// https://source.android.com/devices/graphics/arch-bq-gralloc#gralloc_HAL +const uint32 GRALLOC_USAGE_SW_READ_NEVER = 0x00000000; +const uint32 GRALLOC_USAGE_SW_READ_OFTEN = 0x00000003; +const uint32 GRALLOC_USAGE_SW_WRITE_NEVER = 0x00000000; +const uint32 GRALLOC_USAGE_SW_WRITE_OFTEN = 0x00000030; +const uint32 GRALLOC_USAGE_HW_COMPOSER = 0x00000800; +const uint32 GRALLOC_USAGE_HW_CAMERA_WRITE = 0x00020000; +const uint32 GRALLOC_USAGE_HW_CAMERA_READ = 0x00040000; + [Extensible] enum HalPixelFormat { HAL_PIXEL_FORMAT_RGBA_8888 = 0x1, @@ -56,6 +67,10 @@ uint32 width; uint32 height; HalPixelFormat format; + // usage stores the gralloc usage flags for this stream and determines the + // nature of it. The value is used by Chrome VCD, Android framework and camera + // HAL. Read more on: + // https://source.android.com/devices/graphics/arch-bq-gralloc#gralloc_HAL uint32 usage; uint32 max_buffers; uint32 data_space;
diff --git a/media/capture/video/chromeos/request_manager.cc b/media/capture/video/chromeos/request_manager.cc index 4dc8634..8d7d403 100644 --- a/media/capture/video/chromeos/request_manager.cc +++ b/media/capture/video/chromeos/request_manager.cc
@@ -597,8 +597,7 @@ // buffer will be reused in SubmitCaptureResult. warning_msg = std::string( - "An error occurred while filling output buffer of stream ") + - StreamTypeToString(stream_type) + std::string(" in frame ") + + "An error occurred while filling output buffer for frame ") + std::to_string(frame_number); break; @@ -607,7 +606,7 @@ break; } - LOG(WARNING) << warning_msg << stream_type; + LOG(WARNING) << warning_msg << " with type = " << stream_type; device_context_->LogToClient(warning_msg); // If the buffer is already returned by the HAL, submit it and we're done.
diff --git a/media/capture/video/chromeos/request_manager_unittest.cc b/media/capture/video/chromeos/request_manager_unittest.cc index 893dd2fc..687f2b3 100644 --- a/media/capture/video/chromeos/request_manager_unittest.cc +++ b/media/capture/video/chromeos/request_manager_unittest.cc
@@ -3,8 +3,6 @@ // found in the LICENSE file. #include "media/capture/video/chromeos/request_manager.h" -#include "media/capture/video/chromeos/reprocess_manager.h" -#include "media/capture/video/chromeos/stream_buffer_manager.h" #include <map> #include <memory> @@ -16,15 +14,16 @@ #include "base/test/scoped_task_environment.h" #include "base/threading/thread.h" #include "base/threading/thread_task_runner_handle.h" +#include "media/capture/video/blob_utils.h" #include "media/capture/video/chromeos/camera_buffer_factory.h" #include "media/capture/video/chromeos/camera_device_context.h" #include "media/capture/video/chromeos/camera_device_delegate.h" #include "media/capture/video/chromeos/mock_video_capture_client.h" +#include "media/capture/video/chromeos/reprocess_manager.h" +#include "media/capture/video/chromeos/stream_buffer_manager.h" #include "media/capture/video/mock_gpu_memory_buffer_manager.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" - -#include "media/capture/video/blob_utils.h" using testing::_; using testing::A; using testing::AtLeast; @@ -279,7 +278,7 @@ &RequestManagerTest::QuitCaptureLoop, base::Unretained(this))); EXPECT_CALL(*GetMockCaptureInterface(), DoProcessCaptureRequest(_, _)) .Times(AtLeast(1)) - .WillOnce(Invoke(this, &RequestManagerTest::ProcessCaptureRequest)); + .WillRepeatedly(Invoke(this, &RequestManagerTest::ProcessCaptureRequest)); request_manager_->SetUpStreamsAndBuffers( kDefaultCaptureFormat, @@ -306,22 +305,23 @@ base::Unretained(this))); EXPECT_CALL(*GetMockCaptureInterface(), DoProcessCaptureRequest(_, _)) .Times(AtLeast(1)) - .WillOnce(Invoke([this](cros::mojom::Camera3CaptureRequestPtr& request, - base::OnceCallback<void(int32_t)>& callback) { - std::move(callback).Run(0); - mock_callback_ops_->Notify(PrepareShutterNotifyMessage( - request->frame_number, - (base::TimeTicks::Now() - base::TimeTicks()).InMicroseconds())); - mock_callback_ops_->ProcessCaptureResult(PrepareCapturedResult( - request->frame_number, cros::mojom::CameraMetadata::New(), 1, - std::move(request->output_buffers))); - mock_callback_ops_->ProcessCaptureResult(PrepareCapturedResult( - request->frame_number, cros::mojom::CameraMetadata::New(), 2, - std::vector<cros::mojom::Camera3StreamBufferPtr>())); - mock_callback_ops_->ProcessCaptureResult(PrepareCapturedResult( - request->frame_number, cros::mojom::CameraMetadata::New(), 3, - std::vector<cros::mojom::Camera3StreamBufferPtr>())); - })); + .WillRepeatedly( + Invoke([this](cros::mojom::Camera3CaptureRequestPtr& request, + base::OnceCallback<void(int32_t)>& callback) { + std::move(callback).Run(0); + mock_callback_ops_->Notify(PrepareShutterNotifyMessage( + request->frame_number, + (base::TimeTicks::Now() - base::TimeTicks()).InMicroseconds())); + mock_callback_ops_->ProcessCaptureResult(PrepareCapturedResult( + request->frame_number, cros::mojom::CameraMetadata::New(), 1, + std::move(request->output_buffers))); + mock_callback_ops_->ProcessCaptureResult(PrepareCapturedResult( + request->frame_number, cros::mojom::CameraMetadata::New(), 2, + std::vector<cros::mojom::Camera3StreamBufferPtr>())); + mock_callback_ops_->ProcessCaptureResult(PrepareCapturedResult( + request->frame_number, cros::mojom::CameraMetadata::New(), 3, + std::vector<cros::mojom::Camera3StreamBufferPtr>())); + })); request_manager_->SetUpStreamsAndBuffers( kDefaultCaptureFormat, @@ -393,7 +393,7 @@ request->frame_number, cros::mojom::CameraMetadata::New(), 1, std::move(request->output_buffers))); })) - .WillOnce(Invoke(this, &RequestManagerTest::ProcessCaptureRequest)); + .WillRepeatedly(Invoke(this, &RequestManagerTest::ProcessCaptureRequest)); request_manager_->SetUpStreamsAndBuffers( kDefaultCaptureFormat, @@ -434,7 +434,7 @@ request->frame_number, cros::mojom::Camera3ErrorMsgCode::CAMERA3_MSG_ERROR_RESULT)); })) - .WillOnce(Invoke(this, &RequestManagerTest::ProcessCaptureRequest)); + .WillRepeatedly(Invoke(this, &RequestManagerTest::ProcessCaptureRequest)); request_manager_->SetUpStreamsAndBuffers( kDefaultCaptureFormat, @@ -477,7 +477,7 @@ request->frame_number, cros::mojom::CameraMetadata::New(), 1, std::move(request->output_buffers))); })) - .WillOnce(Invoke(this, &RequestManagerTest::ProcessCaptureRequest)); + .WillRepeatedly(Invoke(this, &RequestManagerTest::ProcessCaptureRequest)); request_manager_->SetUpStreamsAndBuffers( kDefaultCaptureFormat,
diff --git a/media/gpu/v4l2/v4l2_image_processor.cc b/media/gpu/v4l2/v4l2_image_processor.cc index f56b3e3..6907d86 100644 --- a/media/gpu/v4l2/v4l2_image_processor.cc +++ b/media/gpu/v4l2/v4l2_image_processor.cc
@@ -485,7 +485,8 @@ memset(&control, 0, sizeof(control)); control.id = V4L2_CID_ALPHA_COMPONENT; control.value = 255; - IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_S_CTRL, &control); + if (device_->Ioctl(VIDIOC_S_CTRL, &control) != 0) + DVLOGF(4) << "V4L2_CID_ALPHA_COMPONENT is not supported"; struct v4l2_rect visible_rect; visible_rect.left = 0;
diff --git a/media/gpu/v4l2/v4l2_slice_video_decode_accelerator.cc b/media/gpu/v4l2/v4l2_slice_video_decode_accelerator.cc index cead850..2fdc917 100644 --- a/media/gpu/v4l2/v4l2_slice_video_decode_accelerator.cc +++ b/media/gpu/v4l2/v4l2_slice_video_decode_accelerator.cc
@@ -508,28 +508,16 @@ DCHECK_GT(num_pictures, 0u); DCHECK(!pic_size.IsEmpty()); - // Set the frame size on the OUTPUT queue struct v4l2_format format; memset(&format, 0, sizeof(format)); - format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; - if (device_->Ioctl(VIDIOC_G_FMT, &format) != 0) { - VPLOGF(1) << "Failed getting format of output queue"; - NOTIFY_ERROR(PLATFORM_FAILURE); - return false; - } + format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; + format.fmt.pix_mp.pixelformat = output_format_fourcc_; format.fmt.pix_mp.width = pic_size.width(); format.fmt.pix_mp.height = pic_size.height(); - if (device_->Ioctl(VIDIOC_S_FMT, &format) != 0) { - VPLOGF(1) << "Failed changing resolution of output queue"; - NOTIFY_ERROR(PLATFORM_FAILURE); - return false; - } + format.fmt.pix_mp.num_planes = output_planes_count_; - // Get the coded size from the CAPTURE queue - memset(&format, 0, sizeof(format)); - format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; - if (device_->Ioctl(VIDIOC_G_FMT, &format) != 0) { - VPLOGF(1) << "Failed getting format of capture queue"; + if (device_->Ioctl(VIDIOC_S_FMT, &format) != 0) { + VPLOGF(1) << "Failed setting format to: " << output_format_fourcc_; NOTIFY_ERROR(PLATFORM_FAILURE); return false; }
diff --git a/media/webrtc/audio_processor.cc b/media/webrtc/audio_processor.cc index f095b15..be4a916c 100644 --- a/media/webrtc/audio_processor.cc +++ b/media/webrtc/audio_processor.cc
@@ -10,6 +10,7 @@ #include "base/bind.h" #include "base/command_line.h" #include "base/feature_list.h" +#include "base/files/file_util.h" #include "base/memory/ptr_util.h" #include "base/metrics/field_trial.h" #include "base/metrics/field_trial_params.h" @@ -159,13 +160,13 @@ DCHECK(file.IsValid()); - base::PlatformFile stream = file.TakePlatformFile(); if (!worker_queue_) { worker_queue_ = std::make_unique<rtc::TaskQueue>( CreateWebRtcTaskQueue(rtc::TaskQueue::Priority::LOW)); } auto aec_dump = webrtc::AecDumpFactory::Create( - stream, -1 /* max_log_size_bytes */, worker_queue_.get()); + FileToFILE(std::move(file), "wb"), -1 /* max_log_size_bytes */, + worker_queue_.get()); if (!aec_dump) { // AecDumpFactory::Create takes ownership of stream even if it fails, so we // don't need to close it.
diff --git a/ppapi/host/resource_message_filter_unittest.cc b/ppapi/host/resource_message_filter_unittest.cc index d0688b5..c0abd5f 100644 --- a/ppapi/host/resource_message_filter_unittest.cc +++ b/ppapi/host/resource_message_filter_unittest.cc
@@ -10,6 +10,7 @@ #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/synchronization/waitable_event.h" +#include "base/test/scoped_task_environment.h" #include "base/threading/thread.h" #include "base/threading/thread_task_runner_handle.h" #include "ipc/ipc_message.h" @@ -211,11 +212,11 @@ // ResourceMessageFilter instances need to be created on a thread with message // loop. Therefore, we create a message loop and run the testing logic as a // task on it. - base::MessageLoop main_message_loop; + base::test::ScopedTaskEnvironment scoped_task_environment; // It should be safe to use base::Unretained() because the object won't be // destroyed before the task is run. - main_message_loop.task_runner()->PostTask( + scoped_task_environment.GetMainThreadTaskRunner()->PostTask( FROM_HERE, base::BindOnce(&ResourceMessageFilterTest::TestHandleMessageImpl, base::Unretained(this)));
diff --git a/ppapi/shared_impl/proxy_lock_unittest.cc b/ppapi/shared_impl/proxy_lock_unittest.cc index 02a8d4b..980bfe4 100644 --- a/ppapi/shared_impl/proxy_lock_unittest.cc +++ b/ppapi/shared_impl/proxy_lock_unittest.cc
@@ -10,7 +10,7 @@ #include "base/logging.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/message_loop/message_loop.h" +#include "base/test/scoped_task_environment.h" #include "ppapi/shared_impl/proxy_lock.h" #include "ppapi/shared_impl/test_globals.h" #include "testing/gtest/include/gtest/gtest.h" @@ -68,7 +68,8 @@ } // namespace class PpapiProxyLockTest : public testing::Test { - base::MessageLoop message_loop_; // Required to receive callbacks. + base::test::ScopedTaskEnvironment + scoped_task_environment_; // Required to receive callbacks. }; TEST_F(PpapiProxyLockTest, Locking) {
diff --git a/ppapi/shared_impl/resource_tracker_unittest.cc b/ppapi/shared_impl/resource_tracker_unittest.cc index c57b32d2..4044882 100644 --- a/ppapi/shared_impl/resource_tracker_unittest.cc +++ b/ppapi/shared_impl/resource_tracker_unittest.cc
@@ -5,7 +5,7 @@ #include "testing/gtest/include/gtest/gtest.h" #include "base/compiler_specific.h" -#include "base/message_loop/message_loop.h" +#include "base/test/scoped_task_environment.h" #include "ppapi/shared_impl/proxy_lock.h" #include "ppapi/shared_impl/resource.h" #include "ppapi/shared_impl/resource_tracker.h" @@ -49,7 +49,8 @@ ResourceTracker& resource_tracker() { return *globals_.GetResourceTracker(); } private: - base::MessageLoop message_loop_; // Required to receive callbacks. + base::test::ScopedTaskEnvironment + scoped_task_environment_; // Required to receive callbacks. TestGlobals globals_; };
diff --git a/ppapi/shared_impl/var_tracker_unittest.cc b/ppapi/shared_impl/var_tracker_unittest.cc index f0408e7..a31053f3 100644 --- a/ppapi/shared_impl/var_tracker_unittest.cc +++ b/ppapi/shared_impl/var_tracker_unittest.cc
@@ -5,11 +5,11 @@ #include "testing/gtest/include/gtest/gtest.h" #include "base/compiler_specific.h" -#include "base/message_loop/message_loop.h" +#include "base/test/scoped_task_environment.h" #include "ppapi/shared_impl/proxy_lock.h" +#include "ppapi/shared_impl/test_globals.h" #include "ppapi/shared_impl/var.h" #include "ppapi/shared_impl/var_tracker.h" -#include "ppapi/shared_impl/test_globals.h" namespace ppapi { @@ -49,7 +49,8 @@ VarTracker& var_tracker() { return *globals_.GetVarTracker(); } private: - base::MessageLoop message_loop_; // Required to receive callbacks. + base::test::ScopedTaskEnvironment + scoped_task_environment_; // Required to receive callbacks. TestGlobals globals_; };
diff --git a/services/identity/public/cpp/access_token_fetcher.h b/services/identity/public/cpp/access_token_fetcher.h index 41bfa34..8ed681d 100644 --- a/services/identity/public/cpp/access_token_fetcher.h +++ b/services/identity/public/cpp/access_token_fetcher.h
@@ -25,7 +25,7 @@ // Helper class to ease the task of obtaining an OAuth2 access token for a // given account. // May only be used on the UI thread. -class AccessTokenFetcher : public OAuth2TokenService::Observer, +class AccessTokenFetcher : public OAuth2TokenServiceObserver, public OAuth2TokenService::Consumer { public: // Specifies how this instance should behave: @@ -103,7 +103,7 @@ void StartAccessTokenRequest(); - // OAuth2TokenService::Observer implementation. + // OAuth2TokenServiceObserver implementation. void OnRefreshTokenAvailable(const CoreAccountId& account_id) override; // OAuth2TokenService::Consumer implementation.
diff --git a/services/identity/public/cpp/identity_manager.cc b/services/identity/public/cpp/identity_manager.cc index 62c1b43..c0c84d9b 100644 --- a/services/identity/public/cpp/identity_manager.cc +++ b/services/identity/public/cpp/identity_manager.cc
@@ -98,6 +98,14 @@ account_tracker_service_->RemoveObserver(this); } +void IdentityManager::AddObserver(Observer* observer) { + observer_list_.AddObserver(observer); +} + +void IdentityManager::RemoveObserver(Observer* observer) { + observer_list_.RemoveObserver(observer); +} + // TODO(862619) change return type to base::Optional<CoreAccountInfo> CoreAccountInfo IdentityManager::GetPrimaryAccountInfo() const { DCHECK_EQ(primary_account_.has_value(), @@ -127,6 +135,52 @@ return primary_account_.has_value(); } +std::unique_ptr<AccessTokenFetcher> +IdentityManager::CreateAccessTokenFetcherForAccount( + const CoreAccountId& account_id, + const std::string& oauth_consumer_name, + const identity::ScopeSet& scopes, + AccessTokenFetcher::TokenCallback callback, + AccessTokenFetcher::Mode mode) { + return std::make_unique<AccessTokenFetcher>(account_id, oauth_consumer_name, + token_service_.get(), scopes, + std::move(callback), mode); +} + +std::unique_ptr<AccessTokenFetcher> +IdentityManager::CreateAccessTokenFetcherForAccount( + const CoreAccountId& account_id, + const std::string& oauth_consumer_name, + scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, + const identity::ScopeSet& scopes, + AccessTokenFetcher::TokenCallback callback, + AccessTokenFetcher::Mode mode) { + return std::make_unique<AccessTokenFetcher>( + account_id, oauth_consumer_name, token_service_.get(), url_loader_factory, + scopes, std::move(callback), mode); +} + +std::unique_ptr<AccessTokenFetcher> +IdentityManager::CreateAccessTokenFetcherForClient( + const CoreAccountId& account_id, + const std::string& client_id, + const std::string& client_secret, + const std::string& oauth_consumer_name, + const identity::ScopeSet& scopes, + AccessTokenFetcher::TokenCallback callback, + AccessTokenFetcher::Mode mode) { + return std::make_unique<AccessTokenFetcher>( + account_id, client_id, client_secret, oauth_consumer_name, + token_service_.get(), scopes, std::move(callback), mode); +} + +void IdentityManager::RemoveAccessTokenFromCache( + const CoreAccountId& account_id, + const identity::ScopeSet& scopes, + const std::string& access_token) { + token_service_->InvalidateAccessToken(account_id, scopes, access_token); +} + std::vector<CoreAccountInfo> IdentityManager::GetAccountsWithRefreshTokens() const { std::vector<std::string> account_ids_with_tokens = @@ -159,14 +213,8 @@ return accounts; } -AccountsInCookieJarInfo IdentityManager::GetAccountsInCookieJar() const { - std::vector<gaia::ListedAccount> signed_in_accounts; - std::vector<gaia::ListedAccount> signed_out_accounts; - bool accounts_are_fresh = gaia_cookie_manager_service_->ListAccounts( - &signed_in_accounts, &signed_out_accounts); - - return AccountsInCookieJarInfo(accounts_are_fresh, signed_in_accounts, - signed_out_accounts); +bool IdentityManager::HasPrimaryAccountWithRefreshToken() const { + return HasAccountWithRefreshToken(GetPrimaryAccountId()); } bool IdentityManager::HasAccountWithRefreshToken( @@ -174,6 +222,10 @@ return token_service_->RefreshTokenIsAvailable(account_id); } +bool IdentityManager::AreRefreshTokensLoaded() const { + return token_service_->AreAllCredentialsLoaded(); +} + bool IdentityManager::HasAccountWithRefreshTokenInPersistentErrorState( const CoreAccountId& account_id) const { return GetErrorStateOfRefreshTokenForAccount(account_id).IsPersistentError(); @@ -184,14 +236,6 @@ return token_service_->GetAuthError(account_id); } -bool IdentityManager::HasPrimaryAccountWithRefreshToken() const { - return HasAccountWithRefreshToken(GetPrimaryAccountId()); -} - -bool IdentityManager::AreRefreshTokensLoaded() const { - return token_service_->AreAllCredentialsLoaded(); -} - base::Optional<AccountInfo> IdentityManager::FindExtendedAccountInfoForAccount( const CoreAccountInfo& account_info) const { AccountInfo extended_account_info = @@ -251,52 +295,6 @@ return GetAccountInfoForAccountWithRefreshToken(account_info.account_id); } -std::unique_ptr<AccessTokenFetcher> -IdentityManager::CreateAccessTokenFetcherForAccount( - const CoreAccountId& account_id, - const std::string& oauth_consumer_name, - const identity::ScopeSet& scopes, - AccessTokenFetcher::TokenCallback callback, - AccessTokenFetcher::Mode mode) { - return std::make_unique<AccessTokenFetcher>(account_id, oauth_consumer_name, - token_service_.get(), scopes, - std::move(callback), mode); -} - -std::unique_ptr<AccessTokenFetcher> -IdentityManager::CreateAccessTokenFetcherForAccount( - const CoreAccountId& account_id, - const std::string& oauth_consumer_name, - scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - const identity::ScopeSet& scopes, - AccessTokenFetcher::TokenCallback callback, - AccessTokenFetcher::Mode mode) { - return std::make_unique<AccessTokenFetcher>( - account_id, oauth_consumer_name, token_service_.get(), url_loader_factory, - scopes, std::move(callback), mode); -} - -std::unique_ptr<AccessTokenFetcher> -IdentityManager::CreateAccessTokenFetcherForClient( - const CoreAccountId& account_id, - const std::string& client_id, - const std::string& client_secret, - const std::string& oauth_consumer_name, - const identity::ScopeSet& scopes, - AccessTokenFetcher::TokenCallback callback, - AccessTokenFetcher::Mode mode) { - return std::make_unique<AccessTokenFetcher>( - account_id, client_id, client_secret, oauth_consumer_name, - token_service_.get(), scopes, std::move(callback), mode); -} - -void IdentityManager::RemoveAccessTokenFromCache( - const CoreAccountId& account_id, - const identity::ScopeSet& scopes, - const std::string& access_token) { - token_service_->InvalidateAccessToken(account_id, scopes, access_token); -} - std::unique_ptr<signin::UbertokenFetcher> IdentityManager::CreateUbertokenFetcherForAccount( const CoreAccountId& account_id, @@ -309,6 +307,41 @@ url_loader_factory, bount_to_channel_id); } +AccountsInCookieJarInfo IdentityManager::GetAccountsInCookieJar() const { + std::vector<gaia::ListedAccount> signed_in_accounts; + std::vector<gaia::ListedAccount> signed_out_accounts; + bool accounts_are_fresh = gaia_cookie_manager_service_->ListAccounts( + &signed_in_accounts, &signed_out_accounts); + + return AccountsInCookieJarInfo(accounts_are_fresh, signed_in_accounts, + signed_out_accounts); +} + +PrimaryAccountMutator* IdentityManager::GetPrimaryAccountMutator() { + return primary_account_mutator_.get(); +} + +AccountsMutator* IdentityManager::GetAccountsMutator() { + return accounts_mutator_.get(); +} + +AccountsCookieMutator* IdentityManager::GetAccountsCookieMutator() { + return accounts_cookie_mutator_.get(); +} + +void IdentityManager::AddDiagnosticsObserver(DiagnosticsObserver* observer) { + diagnostics_observer_list_.AddObserver(observer); +} + +void IdentityManager::RemoveDiagnosticsObserver(DiagnosticsObserver* observer) { + diagnostics_observer_list_.RemoveObserver(observer); +} + +void IdentityManager::OnNetworkInitialized() { + gaia_cookie_manager_service_->InitCookieListener(); + account_fetcher_service_->OnNetworkInitialized(); +} + // static bool IdentityManager::IsAccountIdMigrationSupported() { return AccountTrackerService::IsMigrationSupported(); @@ -342,23 +375,6 @@ account_tracker_service_->GetMigrationState()); } -PrimaryAccountMutator* IdentityManager::GetPrimaryAccountMutator() { - return primary_account_mutator_.get(); -} - -AccountsMutator* IdentityManager::GetAccountsMutator() { - return accounts_mutator_.get(); -} - -AccountsCookieMutator* IdentityManager::GetAccountsCookieMutator() { - return accounts_cookie_mutator_.get(); -} - -void IdentityManager::OnNetworkInitialized() { - gaia_cookie_manager_service_->InitCookieListener(); - account_fetcher_service_->OnNetworkInitialized(); -} - #if !defined(OS_IOS) && !defined(OS_ANDROID) void IdentityManager::DeprecatedLoadCredentialsForSupervisedUser( const std::string& primary_account_id) { @@ -425,22 +441,6 @@ } #endif -void IdentityManager::AddObserver(Observer* observer) { - observer_list_.AddObserver(observer); -} - -void IdentityManager::RemoveObserver(Observer* observer) { - observer_list_.RemoveObserver(observer); -} - -void IdentityManager::AddDiagnosticsObserver(DiagnosticsObserver* observer) { - diagnostics_observer_list_.AddObserver(observer); -} - -void IdentityManager::RemoveDiagnosticsObserver(DiagnosticsObserver* observer) { - diagnostics_observer_list_.RemoveObserver(observer); -} - PrimaryAccountManager* IdentityManager::GetPrimaryAccountManager() { return primary_account_manager_.get(); }
diff --git a/services/identity/public/cpp/identity_manager.h b/services/identity/public/cpp/identity_manager.h index a5803ad25..a341ae0 100644 --- a/services/identity/public/cpp/identity_manager.h +++ b/services/identity/public/cpp/identity_manager.h
@@ -52,7 +52,7 @@ // ./README.md for detailed documentation. class IdentityManager : public PrimaryAccountManager::Observer, public OAuth2TokenService::DiagnosticsObserver, - public OAuth2TokenService::Observer, + public OAuth2TokenServiceObserver, public AccountTrackerService::Observer { public: class Observer { @@ -136,6 +136,155 @@ virtual void OnExtendedAccountInfoRemoved(const AccountInfo& info) {} }; + // Methods to register or remove observers. + void AddObserver(Observer* observer); + void RemoveObserver(Observer* observer); + + // Provides access to the core information of the user's primary account. + // Returns an empty struct if no such info is available, either because there + // is no primary account yet or because the user signed out. + CoreAccountInfo GetPrimaryAccountInfo() const; + + // Provides access to the account ID of the user's primary account. Simple + // convenience wrapper over GetPrimaryAccountInfo().account_id. + CoreAccountId GetPrimaryAccountId() const; + + // Returns whether the user's primary account is available. + bool HasPrimaryAccount() const; + + // Creates an AccessTokenFetcher given the passed-in information. + std::unique_ptr<AccessTokenFetcher> CreateAccessTokenFetcherForAccount( + const CoreAccountId& account_id, + const std::string& oauth_consumer_name, + const identity::ScopeSet& scopes, + AccessTokenFetcher::TokenCallback callback, + AccessTokenFetcher::Mode mode); + + // Creates an AccessTokenFetcher given the passed-in information, allowing + // to specify a custom |url_loader_factory| as well. + std::unique_ptr<AccessTokenFetcher> CreateAccessTokenFetcherForAccount( + const CoreAccountId& account_id, + const std::string& oauth_consumer_name, + scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, + const identity::ScopeSet& scopes, + AccessTokenFetcher::TokenCallback callback, + AccessTokenFetcher::Mode mode); + + // Creates an AccessTokenFetcher given the passed-in information, allowing to + // specify custom |client_id| and |client_secret| to identify the OAuth client + // app. + std::unique_ptr<AccessTokenFetcher> CreateAccessTokenFetcherForClient( + const CoreAccountId& account_id, + const std::string& client_id, + const std::string& client_secret, + const std::string& oauth_consumer_name, + const identity::ScopeSet& scopes, + AccessTokenFetcher::TokenCallback callback, + AccessTokenFetcher::Mode mode); + + // If an entry exists in the cache of access tokens corresponding to the + // given information, removes that entry; in this case, the next access token + // request for |account_id| and |scopes| will fetch a new token from the + // network. Otherwise, is a no-op. + void RemoveAccessTokenFromCache(const CoreAccountId& account_id, + const identity::ScopeSet& scopes, + const std::string& access_token); + + // Provides the information of all accounts that have refresh tokens. + // NOTE: The accounts should not be assumed to be in any particular order; in + // particular, they are not guaranteed to be in the order in which the + // refresh tokens were added. + std::vector<CoreAccountInfo> GetAccountsWithRefreshTokens() const; + + // Same functionality as GetAccountsWithRefreshTokens() but returning the + // extended account information. + std::vector<AccountInfo> GetExtendedAccountInfoForAccountsWithRefreshToken() + const; + + // Returns true if (a) the primary account exists, and (b) a refresh token + // exists for the primary account. + bool HasPrimaryAccountWithRefreshToken() const; + + // Returns true if a refresh token exists for |account_id|. + bool HasAccountWithRefreshToken(const CoreAccountId& account_id) const; + + // Returns true if all refresh tokens have been loaded from disk. + bool AreRefreshTokensLoaded() const; + + // Returns true if (a) a refresh token exists for |account_id|, and (b) the + // refresh token is in a persistent error state (defined as + // GoogleServiceAuthError::IsPersistentError() returning true for the error + // returned by GetErrorStateOfRefreshTokenForAccount(account_id)). + bool HasAccountWithRefreshTokenInPersistentErrorState( + const CoreAccountId& account_id) const; + + // Returns the error state of the refresh token associated with |account_id|. + // In particular: Returns GoogleServiceAuthError::AuthErrorNone() if either + // (a) no refresh token exists for |account_id|, or (b) the refresh token is + // not in a persistent error state. Otherwise, returns the last persistent + // error that was detected when using the refresh token. + GoogleServiceAuthError GetErrorStateOfRefreshTokenForAccount( + const CoreAccountId& account_id) const; + + // Returns extended information for account identified by |account_info|. + // The information will be returned if the information is available and + // refresh token is available for account. + base::Optional<AccountInfo> FindExtendedAccountInfoForAccount( + const CoreAccountInfo& account_info) const; + + // Looks up and returns information for account with given |account_id|. If + // the account cannot be found, return an empty optional. This is equivalent + // to searching on the vector returned by GetAccountsWithRefreshTokens() but + // without allocating memory for the vector. + base::Optional<AccountInfo> + FindAccountInfoForAccountWithRefreshTokenByAccountId( + const CoreAccountId& account_id) const; + + // Looks up and returns information for account with given |email_address|. If + // the account cannot be found, return an empty optional. This is equivalent + // to searching on the vector returned by GetAccountsWithRefreshTokens() but + // without allocating memory for the vector. + base::Optional<AccountInfo> + FindAccountInfoForAccountWithRefreshTokenByEmailAddress( + const std::string& email_address) const; + + // Looks up and returns information for account with given |gaia_id|. If the + // account cannot be found, return an empty optional. This is equivalent to + // searching on the vector returned by GetAccountsWithRefreshTokens() but + // without allocating memory for the vector. + base::Optional<AccountInfo> FindAccountInfoForAccountWithRefreshTokenByGaiaId( + const std::string& gaia_id) const; + + // Creates an UbertokenFetcher given the passed-in information, allowing + // to specify a custom |url_loader_factory| as well. + std::unique_ptr<signin::UbertokenFetcher> CreateUbertokenFetcherForAccount( + const CoreAccountId& account_id, + signin::UbertokenFetcher::CompletionCallback callback, + gaia::GaiaSource source, + scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, + bool bound_to_channel_id = true); + + // Provides the information of all accounts that are present in the Gaia + // cookie in the cookie jar, ordered by their order in the cookie. + // If the returned accounts are not fresh, an internal update will be + // triggered and there will be a subsequent invocation of + // IdentityManager::Observer::OnAccountsInCookieJarChanged(). + AccountsInCookieJarInfo GetAccountsInCookieJar() const; + + // Returns pointer to the object used to change the signed-in state of the + // primary account, if supported on the current platform. Otherwise, returns + // null. + PrimaryAccountMutator* GetPrimaryAccountMutator(); + + // Returns pointer to the object used to seed accounts and mutate state of + // accounts' refresh tokens, if supported on the current platform. Otherwise, + // returns null. + AccountsMutator* GetAccountsMutator(); + + // Returns pointer to the object used to manipulate the cookies stored and the + // accounts associated with them. Guaranteed to be non-null. + AccountsCookieMutator* GetAccountsCookieMutator(); + // Observer interface for classes that want to monitor status of various // requests. Mostly useful in tests and debugging contexts (e.g., WebUI). class DiagnosticsObserver { @@ -177,14 +326,14 @@ const std::string& source) {} }; - // Possible values for the account ID migration state, needs to be kept in - // sync with AccountTrackerService::AccountIdMigrationState. - enum AccountIdMigrationState { - MIGRATION_NOT_STARTED = 0, - MIGRATION_IN_PROGRESS = 1, - MIGRATION_DONE = 2, - NUM_MIGRATION_STATES - }; + void AddDiagnosticsObserver(DiagnosticsObserver* observer); + void RemoveDiagnosticsObserver(DiagnosticsObserver* observer); + + // ************************************************************************** + // NOTE: All public methods methods below are either intended to be used only + // by signin code, or are slated for deletion. Most IdentityManager consumers + // should not need to interact with any methods below this line. + // ************************************************************************** IdentityManager( std::unique_ptr<AccountTrackerService> account_tracker_service, @@ -198,136 +347,9 @@ std::unique_ptr<DiagnosticsProvider> diagnostics_provider); ~IdentityManager() override; - // Provides access to the core information of the user's primary account. - // Returns an empty struct if no such info is available, either because there - // is no primary account yet or because the user signed out. - CoreAccountInfo GetPrimaryAccountInfo() const; - - // Provides access to the account ID of the user's primary account. Simple - // convenience wrapper over GetPrimaryAccountInfo().account_id. - CoreAccountId GetPrimaryAccountId() const; - - // Returns whether the user's primary account is available. - bool HasPrimaryAccount() const; - - // Provides the information of all accounts that have refresh tokens. - // NOTE: The accounts should not be assumed to be in any particular order; in - // particular, they are not guaranteed to be in the order in which the - // refresh tokens were added. - std::vector<CoreAccountInfo> GetAccountsWithRefreshTokens() const; - - // Same functionality as GetAccountsWithRefreshTokens() but returning the - // extended account information. - std::vector<AccountInfo> GetExtendedAccountInfoForAccountsWithRefreshToken() - const; - - // Provides the information of all accounts that are present in the Gaia - // cookie in the cookie jar, ordered by their order in the cookie. - // If the returned accounts are not fresh, an internal update will be - // triggered and there will be a subsequent invocation of - // IdentityManager::Observer::OnAccountsInCookieJarChanged(). - AccountsInCookieJarInfo GetAccountsInCookieJar() const; - - // Returns true if a refresh token exists for |account_id|. - bool HasAccountWithRefreshToken(const CoreAccountId& account_id) const; - - // Returns true if (a) a refresh token exists for |account_id|, and (b) the - // refresh token is in a persistent error state (defined as - // GoogleServiceAuthError::IsPersistentError() returning true for the error - // returned by GetErrorStateOfRefreshTokenForAccount(account_id)). - bool HasAccountWithRefreshTokenInPersistentErrorState( - const CoreAccountId& account_id) const; - - // Returns the error state of the refresh token associated with |account_id|. - // In particular: Returns GoogleServiceAuthError::AuthErrorNone() if either - // (a) no refresh token exists for |account_id|, or (b) the refresh token is - // not in a persistent error state. Otherwise, returns the last persistent - // error that was detected when using the refresh token. - GoogleServiceAuthError GetErrorStateOfRefreshTokenForAccount( - const CoreAccountId& account_id) const; - - // Returns true if (a) the primary account exists, and (b) a refresh token - // exists for the primary account. - bool HasPrimaryAccountWithRefreshToken() const; - - // Returns true if all refresh tokens have been loaded from disk. - bool AreRefreshTokensLoaded() const; - - // Returns extended information for account identified by |account_info|. - // The information will be returned if the information is available and - // refresh token is available for account. - base::Optional<AccountInfo> FindExtendedAccountInfoForAccount( - const CoreAccountInfo& account_info) const; - - // Looks up and returns information for account with given |account_id|. If - // the account cannot be found, return an empty optional. This is equivalent - // to searching on the vector returned by GetAccountsWithRefreshTokens() but - // without allocating memory for the vector. - base::Optional<AccountInfo> - FindAccountInfoForAccountWithRefreshTokenByAccountId( - const CoreAccountId& account_id) const; - - // Looks up and returns information for account with given |email_address|. If - // the account cannot be found, return an empty optional. This is equivalent - // to searching on the vector returned by GetAccountsWithRefreshTokens() but - // without allocating memory for the vector. - base::Optional<AccountInfo> - FindAccountInfoForAccountWithRefreshTokenByEmailAddress( - const std::string& email_address) const; - - // Looks up and returns information for account with given |gaia_id|. If the - // account cannot be found, return an empty optional. This is equivalent to - // searching on the vector returned by GetAccountsWithRefreshTokens() but - // without allocating memory for the vector. - base::Optional<AccountInfo> FindAccountInfoForAccountWithRefreshTokenByGaiaId( - const std::string& gaia_id) const; - - // Creates an AccessTokenFetcher given the passed-in information. - std::unique_ptr<AccessTokenFetcher> CreateAccessTokenFetcherForAccount( - const CoreAccountId& account_id, - const std::string& oauth_consumer_name, - const identity::ScopeSet& scopes, - AccessTokenFetcher::TokenCallback callback, - AccessTokenFetcher::Mode mode); - - // Creates an AccessTokenFetcher given the passed-in information, allowing - // to specify a custom |url_loader_factory| as well. - std::unique_ptr<AccessTokenFetcher> CreateAccessTokenFetcherForAccount( - const CoreAccountId& account_id, - const std::string& oauth_consumer_name, - scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - const identity::ScopeSet& scopes, - AccessTokenFetcher::TokenCallback callback, - AccessTokenFetcher::Mode mode); - - // Creates an AccessTokenFetcher given the passed-in information, allowing to - // specify custom |client_id| and |client_secret| to identify the OAuth client - // app. - std::unique_ptr<AccessTokenFetcher> CreateAccessTokenFetcherForClient( - const CoreAccountId& account_id, - const std::string& client_id, - const std::string& client_secret, - const std::string& oauth_consumer_name, - const identity::ScopeSet& scopes, - AccessTokenFetcher::TokenCallback callback, - AccessTokenFetcher::Mode mode); - - // If an entry exists in the cache of access tokens corresponding to the - // given information, removes that entry; in this case, the next access token - // request for |account_id| and |scopes| will fetch a new token from the - // network. Otherwise, is a no-op. - void RemoveAccessTokenFromCache(const CoreAccountId& account_id, - const identity::ScopeSet& scopes, - const std::string& access_token); - - // Creates an UbertokenFetcher given the passed-in information, allowing - // to specify a custom |url_loader_factory| as well. - std::unique_ptr<signin::UbertokenFetcher> CreateUbertokenFetcherForAccount( - const CoreAccountId& account_id, - signin::UbertokenFetcher::CompletionCallback callback, - gaia::GaiaSource source, - scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - bool bound_to_channel_id = true); + // Performs initialization that is dependent on the network being + // initialized. + void OnNetworkInitialized(); // Returns |true| if migration of the account ID from normalized email is // supported for the current platform. @@ -346,26 +368,18 @@ CoreAccountId PickAccountIdForAccount(const std::string& gaia, const std::string& email) const; + // Possible values for the account ID migration state, needs to be kept in + // sync with AccountTrackerService::AccountIdMigrationState. + enum AccountIdMigrationState { + MIGRATION_NOT_STARTED = 0, + MIGRATION_IN_PROGRESS = 1, + MIGRATION_DONE = 2, + NUM_MIGRATION_STATES + }; + // Returns the currently saved state for the migration of accounts IDs. AccountIdMigrationState GetAccountIdMigrationState() const; - // Returns pointer to the object used to change the signed-in state of the - // primary account, if supported on the current platform. Otherwise, returns - // null. - PrimaryAccountMutator* GetPrimaryAccountMutator(); - - // Returns pointer to the object used to seed accounts and mutate state of - // accounts' refresh tokens, if supported on the current platform. Otherwise, - // returns null. - AccountsMutator* GetAccountsMutator(); - - // Returns pointer to the object used to manipulate the cookies stored and the - // accounts associated with them. Guaranteed to be non-null. - AccountsCookieMutator* GetAccountsCookieMutator(); - - // Performs initalization that is dependent on the network being initialized. - void OnNetworkInitialized(); - #if !defined(OS_IOS) && !defined(OS_ANDROID) // Explicitly triggers the loading of accounts in the context of supervised // users. @@ -443,12 +457,6 @@ void ForceRefreshOfExtendedAccountInfo(const CoreAccountId& account_id); #endif - // Methods to register or remove observers. - void AddObserver(Observer* observer); - void RemoveObserver(Observer* observer); - void AddDiagnosticsObserver(DiagnosticsObserver* observer); - void RemoveDiagnosticsObserver(DiagnosticsObserver* observer); - private: // These test helpers need to use some of the private methods below. friend CoreAccountInfo SetPrimaryAccount(IdentityManager* identity_manager, @@ -588,7 +596,7 @@ void AuthenticatedAccountSet(const AccountInfo& account_info) override; void AuthenticatedAccountCleared() override; - // OAuth2TokenService::Observer: + // OAuth2TokenServiceObserver: void OnRefreshTokenAvailable(const CoreAccountId& account_id) override; void OnRefreshTokenRevoked(const CoreAccountId& account_id) override; void OnRefreshTokensLoaded() override;
diff --git a/services/viz/privileged/interfaces/compositing/layered_window_updater.mojom b/services/viz/privileged/interfaces/compositing/layered_window_updater.mojom index 360cab3..58a7e22 100644 --- a/services/viz/privileged/interfaces/compositing/layered_window_updater.mojom +++ b/services/viz/privileged/interfaces/compositing/layered_window_updater.mojom
@@ -4,6 +4,7 @@ module viz.mojom; +import "mojo/public/mojom/base/shared_memory.mojom"; import "ui/gfx/geometry/mojo/geometry.mojom"; // The syscalls needed to update a layered window are blocked by the GPU @@ -13,10 +14,13 @@ // A new shared memory buffer has been allocated for |pixel_size|. The shared // memory buffer must be at least big enough to contain |pixel_size| in // RGBA_8888. The shared memory buffer will be used with subsequent calls to - // Draw(). + // Draw(). The shared memory is used with + // skia::CreatePlatformCanvasWithSharedSection() on both ends to create a + // canvas and therefore must be writable (and Unsafe) on both ends. + OnAllocatedSharedMemory( gfx.mojom.Size pixel_size, - handle<shared_buffer> scoped_buffer_handle + mojo_base.mojom.UnsafeSharedMemoryRegion region ); // Draws to the HWND by copying pixels from shared memory. Callback must be
diff --git a/testing/buildbot/chromium.linux.json b/testing/buildbot/chromium.linux.json index aaea37c..5c3aba9f 100644 --- a/testing/buildbot/chromium.linux.json +++ b/testing/buildbot/chromium.linux.json
@@ -788,7 +788,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -803,7 +803,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -818,7 +818,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -833,7 +833,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -848,7 +848,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -863,7 +863,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -879,7 +879,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -894,7 +894,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -909,7 +909,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -924,7 +924,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -942,7 +942,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -957,7 +957,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -972,7 +972,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -987,7 +987,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1002,7 +1002,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1017,7 +1017,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1048,7 +1048,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1063,7 +1063,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1078,7 +1078,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1093,7 +1093,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1111,7 +1111,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ], "shards": 6 @@ -1132,7 +1132,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1147,7 +1147,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1162,7 +1162,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1177,7 +1177,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1192,7 +1192,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1207,7 +1207,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1222,7 +1222,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1237,7 +1237,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1252,7 +1252,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1267,7 +1267,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1282,7 +1282,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1297,7 +1297,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1312,7 +1312,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1327,7 +1327,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1342,7 +1342,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1357,7 +1357,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1372,7 +1372,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1387,7 +1387,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1402,7 +1402,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1417,7 +1417,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1432,7 +1432,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1447,7 +1447,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1462,7 +1462,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1477,7 +1477,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1492,7 +1492,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1507,7 +1507,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1522,7 +1522,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1537,7 +1537,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1552,7 +1552,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -1567,7 +1567,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -3833,7 +3833,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -3848,7 +3848,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -3863,7 +3863,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -3878,7 +3878,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -3893,7 +3893,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -3908,7 +3908,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -3923,7 +3923,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -3938,7 +3938,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -3953,7 +3953,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -3968,7 +3968,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -3984,7 +3984,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -3999,7 +3999,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4014,7 +4014,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4029,7 +4029,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ], "shards": 10 @@ -4050,7 +4050,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4065,7 +4065,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4083,7 +4083,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4098,7 +4098,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4113,7 +4113,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4128,7 +4128,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4143,7 +4143,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4158,7 +4158,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4173,7 +4173,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4188,7 +4188,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4203,7 +4203,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ], "shards": 6 @@ -4224,7 +4224,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4244,7 +4244,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4259,7 +4259,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4274,7 +4274,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4289,7 +4289,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4304,7 +4304,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4319,7 +4319,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4334,7 +4334,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4349,7 +4349,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4364,7 +4364,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4379,7 +4379,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4394,7 +4394,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4409,7 +4409,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4424,7 +4424,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4439,7 +4439,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4454,7 +4454,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4469,7 +4469,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4484,7 +4484,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4499,7 +4499,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4514,7 +4514,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4529,7 +4529,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ], "shards": 3 @@ -4550,7 +4550,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4565,7 +4565,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4580,7 +4580,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4595,7 +4595,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4610,7 +4610,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4625,7 +4625,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4640,7 +4640,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4655,7 +4655,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4670,7 +4670,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4685,7 +4685,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4700,7 +4700,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4715,7 +4715,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4730,7 +4730,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4745,7 +4745,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4760,7 +4760,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4775,7 +4775,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4790,7 +4790,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ], "shards": 2 @@ -4806,7 +4806,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4821,7 +4821,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4836,7 +4836,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4851,7 +4851,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4866,7 +4866,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4881,7 +4881,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4896,7 +4896,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4911,7 +4911,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4926,7 +4926,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4941,7 +4941,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4956,7 +4956,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4971,7 +4971,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -4986,7 +4986,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -5001,7 +5001,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -5016,7 +5016,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -5031,7 +5031,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -5046,7 +5046,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -5061,7 +5061,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -5076,7 +5076,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -5091,7 +5091,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -5106,7 +5106,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -5121,7 +5121,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -5136,7 +5136,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -5151,7 +5151,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -5166,7 +5166,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -5182,7 +5182,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] }, @@ -5201,7 +5201,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] } @@ -5217,7 +5217,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] } @@ -5233,7 +5233,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] } @@ -5249,7 +5249,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] } @@ -5265,7 +5265,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] } @@ -5281,7 +5281,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] } @@ -5297,7 +5297,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] } @@ -5321,7 +5321,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ], "shards": 20 @@ -5338,7 +5338,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ], "idempotent": false @@ -5359,7 +5359,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ], "idempotent": false, @@ -5381,7 +5381,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ], "idempotent": false, @@ -5404,7 +5404,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] } @@ -5420,7 +5420,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ] } @@ -5443,7 +5443,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-16.04" + "os": "Ubuntu-14.04" } ], "shards": 20
diff --git a/testing/buildbot/waterfalls.pyl b/testing/buildbot/waterfalls.pyl index bb56c876..69ffa35 100644 --- a/testing/buildbot/waterfalls.pyl +++ b/testing/buildbot/waterfalls.pyl
@@ -3310,7 +3310,7 @@ }, 'Cast Linux': { 'mixins': [ - 'linux-trusty', + 'linux-xenial', ], 'additional_compile_targets': [ 'cast_shell', @@ -3400,7 +3400,8 @@ }, 'Linux Tests (dbg)(1)': { 'mixins': [ - 'linux-xenial', + # TODO(tikuta): investigate browser_tests failure on xenial crbug.com/954450 . + 'linux-trusty', ], 'test_suites': { 'gtest_tests': 'chromium_linux_gtests',
diff --git a/third_party/blink/public/BUILD.gn b/third_party/blink/public/BUILD.gn index 62d3bea4..457bf09 100644 --- a/third_party/blink/public/BUILD.gn +++ b/third_party/blink/public/BUILD.gn
@@ -143,9 +143,11 @@ "platform/modules/media_capabilities/web_media_decoding_configuration.h", "platform/modules/media_capabilities/web_video_configuration.h", "platform/modules/mediastream/media_stream_audio_deliverer.h", + "platform/modules/mediastream/media_stream_audio_level_calculator.h", "platform/modules/mediastream/media_stream_audio_processor_options.h", "platform/modules/mediastream/media_stream_audio_source.h", "platform/modules/mediastream/media_stream_audio_track.h", + "platform/modules/mediastream/media_stream_dispatcher_eventhandler.h", "platform/modules/mediastream/media_stream_types.h", "platform/modules/mediastream/secure_display_link_tracker.h", "platform/modules/mediastream/web_media_stream_audio_renderer.h",
diff --git a/third_party/blink/public/common/BUILD.gn b/third_party/blink/public/common/BUILD.gn index 550c28f..020ac79 100644 --- a/third_party/blink/public/common/BUILD.gn +++ b/third_party/blink/public/common/BUILD.gn
@@ -132,6 +132,7 @@ "//media", "//media/capture:capture_base", "//media/capture:capture_lib", + "//media/mojo/interfaces:interfaces", ] }
diff --git a/content/renderer/media/stream/media_stream_audio_level_calculator.h b/third_party/blink/public/platform/modules/mediastream/media_stream_audio_level_calculator.h similarity index 70% rename from content/renderer/media/stream/media_stream_audio_level_calculator.h rename to third_party/blink/public/platform/modules/mediastream/media_stream_audio_level_calculator.h index 4d8f9bb2..dc4f0824 100644 --- a/content/renderer/media/stream/media_stream_audio_level_calculator.h +++ b/third_party/blink/public/platform/modules/mediastream/media_stream_audio_level_calculator.h
@@ -2,18 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CONTENT_RENDERER_MEDIA_STREAM_MEDIA_STREAM_AUDIO_LEVEL_CALCULATOR_H_ -#define CONTENT_RENDERER_MEDIA_STREAM_MEDIA_STREAM_AUDIO_LEVEL_CALCULATOR_H_ +#ifndef THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_MEDIASTREAM_MEDIA_STREAM_AUDIO_LEVEL_CALCULATOR_H_ +#define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_MEDIASTREAM_MEDIA_STREAM_AUDIO_LEVEL_CALCULATOR_H_ #include "base/memory/ref_counted.h" #include "base/synchronization/lock.h" -#include "content/common/content_export.h" +#include "third_party/blink/public/platform/web_common.h" namespace media { class AudioBus; } -namespace content { +namespace blink { // This class is used by the WebRtcAudioCapturer to calculate the level of the // audio signal. And the audio level will be eventually used by the volume @@ -21,12 +21,16 @@ // // The algorithm used by this class is the same as how it is done in // third_party/webrtc/voice_engine/level_indicator.cc. -class CONTENT_EXPORT MediaStreamAudioLevelCalculator { +// +// TODO(crbug.com/704136): Move this class out of the Blink exposed API +// when all users of it have been Onion souped. +// +class BLINK_PLATFORM_EXPORT MediaStreamAudioLevelCalculator { public: // Provides thread-safe access to the current signal level. This object is // intended to be passed to modules running on other threads that poll for the // current signal level. - class CONTENT_EXPORT Level : public base::RefCountedThreadSafe<Level> { + class BLINK_PLATFORM_EXPORT Level : public base::RefCountedThreadSafe<Level> { public: float GetCurrent() const; @@ -60,6 +64,6 @@ const scoped_refptr<Level> level_; }; -} // namespace content +} // namespace blink -#endif // CONTENT_RENDERER_MEDIA_STREAM_MEDIA_STREAM_AUDIO_LEVEL_CALCULATOR_H_ +#endif // THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_MEDIASTREAM_MEDIA_STREAM_AUDIO_LEVEL_CALCULATOR_H_
diff --git a/third_party/blink/public/platform/modules/mediastream/media_stream_dispatcher_eventhandler.h b/third_party/blink/public/platform/modules/mediastream/media_stream_dispatcher_eventhandler.h new file mode 100644 index 0000000..9d57df92 --- /dev/null +++ b/third_party/blink/public/platform/modules/mediastream/media_stream_dispatcher_eventhandler.h
@@ -0,0 +1,32 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_MEDIASTREAM_MEDIA_STREAM_DISPATCHER_EVENTHANDLER_H_ +#define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_MEDIASTREAM_MEDIA_STREAM_DISPATCHER_EVENTHANDLER_H_ + +#include <string> + +#include "third_party/blink/public/common/mediastream/media_stream_request.h" +#include "third_party/blink/public/platform/web_common.h" + +namespace blink { + +// TODO(crbug.com/704136): Move this class out of the Blink exposed API +// when all users of it have been Onion souped. +class BLINK_PLATFORM_EXPORT MediaStreamDispatcherEventHandler { + public: + // A device has been stopped in the browser process. + virtual void OnDeviceStopped(const blink::MediaStreamDevice& device) = 0; + + // Switch to the new device within the working session. + virtual void OnDeviceChanged(const blink::MediaStreamDevice& old_device, + const blink::MediaStreamDevice& new_device) = 0; + + protected: + virtual ~MediaStreamDispatcherEventHandler() {} +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_MEDIASTREAM_MEDIA_STREAM_DISPATCHER_EVENTHANDLER_H_
diff --git a/third_party/blink/renderer/bindings/core/v8/binding_security_test.cc b/third_party/blink/renderer/bindings/core/v8/binding_security_test.cc index d39e7446..067d1fc 100644 --- a/third_party/blink/renderer/bindings/core/v8/binding_security_test.cc +++ b/third_party/blink/renderer/bindings/core/v8/binding_security_test.cc
@@ -75,7 +75,7 @@ which_origin == OriginDisposition::SameOriginDomain ? "document.domain = 'example.com';" : "", - property.Utf8().data(), target_url); + property.Utf8().c_str(), target_url); LoadURL(kMainFrame); main.Complete(document); @@ -119,7 +119,7 @@ which_origin == OriginDisposition::SameOriginDomain ? "document.domain = 'example.com';" : "", - property.Utf8().data(), target_url); + property.Utf8().c_str(), target_url); LoadURL(kMainFrame); main.Complete(document);
diff --git a/third_party/blink/renderer/bindings/core/v8/script_controller.cc b/third_party/blink/renderer/bindings/core/v8/script_controller.cc index 3aa9813..512b5c6 100644 --- a/third_party/blink/renderer/bindings/core/v8/script_controller.cc +++ b/third_party/blink/renderer/bindings/core/v8/script_controller.cc
@@ -68,6 +68,7 @@ #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" #include "third_party/blink/renderer/platform/wtf/text/cstring.h" #include "third_party/blink/renderer/platform/wtf/text/string_builder.h" +#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h" #include "third_party/blink/renderer/platform/wtf/time.h" namespace blink { @@ -273,9 +274,8 @@ params->url = GetFrame()->GetDocument()->Url(); String result = ToCoreString(v8::Local<v8::String>::Cast(v8_result)); - WebNavigationParams::FillStaticResponse( - params.get(), "text/html", "UTF-8", - base::make_span(result.Utf8().data(), result.Utf8().length())); + WebNavigationParams::FillStaticResponse(params.get(), "text/html", "UTF-8", + StringUTF8Adaptor(result)); GetFrame()->Loader().CommitNavigation(std::move(params), nullptr, true); }
diff --git a/third_party/blink/renderer/bindings/core/v8/script_promise_property_test.cc b/third_party/blink/renderer/bindings/core/v8/script_promise_property_test.cc index 251c4549..5ab7eba 100644 --- a/third_party/blink/renderer/bindings/core/v8/script_promise_property_test.cc +++ b/third_party/blink/renderer/bindings/core/v8/script_promise_property_test.cc
@@ -220,8 +220,8 @@ } if (expected != actual) { ADD_FAILURE_AT(file, line) - << "toV8 returns an incorrect value.\n Actual: " - << actual.Utf8().data() << "\nExpected: " << expected; + << "toV8 returns an incorrect value.\n Actual: " << actual.Utf8() + << "\nExpected: " << expected; return; } }
diff --git a/third_party/blink/renderer/bindings/core/v8/to_v8_test.cc b/third_party/blink/renderer/bindings/core/v8/to_v8_test.cc index 0f74638..2e01968 100644 --- a/third_party/blink/renderer/bindings/core/v8/to_v8_test.cc +++ b/third_party/blink/renderer/bindings/core/v8/to_v8_test.cc
@@ -37,7 +37,7 @@ if (String(expected) != actual_string) { ADD_FAILURE_AT(path, line_number) << "toV8 returns an incorrect value.\n Actual: " - << actual_string.Utf8().data() << "\nExpected: " << expected; + << actual_string.Utf8() << "\nExpected: " << expected; return; } }
diff --git a/third_party/blink/renderer/bindings/core/v8/v8_extras_test_utils.cc b/third_party/blink/renderer/bindings/core/v8/v8_extras_test_utils.cc index 0f291416..7623ed70 100644 --- a/third_party/blink/renderer/bindings/core/v8/v8_extras_test_utils.cc +++ b/third_party/blink/renderer/bindings/core/v8/v8_extras_test_utils.cc
@@ -40,11 +40,8 @@ v8::TryCatch block(scope->GetIsolate()); ScriptValue r = Eval(scope, script); if (block.HasCaught()) { - ADD_FAILURE() << ToCoreString(block.Exception() - ->ToString(scope->GetContext()) - .ToLocalChecked()) - .Utf8() - .data(); + ADD_FAILURE() << ToCoreString( + block.Exception()->ToString(scope->GetContext()).ToLocalChecked()); block.ReThrow(); } return r;
diff --git a/third_party/blink/renderer/bindings/core/v8/v8_script_runner_test.cc b/third_party/blink/renderer/bindings/core/v8/v8_script_runner_test.cc index 3d09d3c..021d7ca 100644 --- a/third_party/blink/renderer/bindings/core/v8/v8_script_runner_test.cc +++ b/third_party/blink/renderer/bindings/core/v8/v8_script_runner_test.cc
@@ -15,6 +15,7 @@ #include "third_party/blink/renderer/platform/loader/fetch/cached_metadata.h" #include "third_party/blink/renderer/platform/loader/fetch/cached_metadata_handler.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" +#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h" #include "third_party/blink/renderer/platform/wtf/text/text_encoding.h" #include "v8/include/v8.h" @@ -104,7 +105,8 @@ ResourceResponse response(Url()); response.SetHttpStatusCode(200); resource->SetResponse(response); - resource->AppendData(code.Utf8().data(), code.Utf8().length()); + StringUTF8Adaptor code_utf8(code); + resource->AppendData(code_utf8.data(), code_utf8.size()); resource->FinishForTest(); return resource; }
diff --git a/third_party/blink/renderer/bindings/templates/interface.cc.tmpl b/third_party/blink/renderer/bindings/templates/interface.cc.tmpl index a9a54a18..c58e9a81 100644 --- a/third_party/blink/renderer/bindings/templates/interface.cc.tmpl +++ b/third_party/blink/renderer/bindings/templates/interface.cc.tmpl
@@ -402,12 +402,12 @@ static void NamedPropertyGetter(const AtomicString& name, const v8::PropertyCallbackInfo<v8::Value>& info) { {% if getter.is_raises_exception %} - const CString& name_in_utf8 = name.Utf8(); + const std::string& name_in_utf8 = name.Utf8(); ExceptionState exception_state( info.GetIsolate(), ExceptionState::kGetterContext, "{{interface_name}}", - name_in_utf8.data()); + name_in_utf8.c_str()); {% endif %} {% if getter.is_call_with_script_state %} ScriptState* script_state = ScriptState::ForRelevantRealm(info); @@ -461,12 +461,12 @@ v8::Local<v8::Value> v8_value, const v8::PropertyCallbackInfo<v8::Value>& info) { {% if setter.has_exception_state %} - const CString& name_in_utf8 = name.Utf8(); + const std::string& name_in_utf8 = name.Utf8(); ExceptionState exception_state( info.GetIsolate(), ExceptionState::kSetterContext, "{{interface_name}}", - name_in_utf8.data()); + name_in_utf8.c_str()); {% endif %} {% if setter.is_ce_reactions %} CEReactionsScope ce_reactions_scope; @@ -539,12 +539,12 @@ static void NamedPropertyDeleter( const AtomicString& name, const v8::PropertyCallbackInfo<v8::Boolean>& info) { {% if deleter.is_raises_exception %} - const CString& name_in_utf8 = name.Utf8(); + const std::string& name_in_utf8 = name.Utf8(); ExceptionState exception_state( info.GetIsolate(), ExceptionState::kDeletionContext, "{{interface_name}}", - name_in_utf8.data()); + name_in_utf8.c_str()); {% endif %} {% if deleter.is_ce_reactions %} CEReactionsScope ce_reactions_scope; @@ -619,12 +619,12 @@ static void NamedPropertyQuery( const AtomicString& name, const v8::PropertyCallbackInfo<T>& info) { {% endif %} - const CString& name_in_utf8 = name.Utf8(); + const std::string& name_in_utf8 = name.Utf8(); ExceptionState exception_state( info.GetIsolate(), ExceptionState::kGetterContext, "{{interface_name}}", - name_in_utf8.data()); + name_in_utf8.c_str()); {% if getter.is_call_with_script_state %} ScriptState* script_state = ScriptState::ForRelevantRealm(info); {% endif %}
diff --git a/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface.cc b/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface.cc index 56cbf88..c158598 100644 --- a/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface.cc +++ b/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface.cc
@@ -2418,12 +2418,12 @@ static void NamedPropertyQuery( const AtomicString& name, const v8::PropertyCallbackInfo<v8::Integer>& info) { - const CString& name_in_utf8 = name.Utf8(); + const std::string& name_in_utf8 = name.Utf8(); ExceptionState exception_state( info.GetIsolate(), ExceptionState::kGetterContext, "TestInterface", - name_in_utf8.data()); + name_in_utf8.c_str()); TestInterfaceImplementation* impl = V8TestInterface::ToImpl(info.Holder());
diff --git a/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface_2.cc b/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface_2.cc index fb6be871..372a02fa 100644 --- a/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface_2.cc +++ b/third_party/blink/renderer/bindings/tests/results/core/v8_test_interface_2.cc
@@ -365,12 +365,12 @@ static void NamedPropertyGetter(const AtomicString& name, const v8::PropertyCallbackInfo<v8::Value>& info) { - const CString& name_in_utf8 = name.Utf8(); + const std::string& name_in_utf8 = name.Utf8(); ExceptionState exception_state( info.GetIsolate(), ExceptionState::kGetterContext, "TestInterface2", - name_in_utf8.data()); + name_in_utf8.c_str()); TestInterface2* impl = V8TestInterface2::ToImpl(info.Holder()); TestInterfaceEmpty* result = impl->namedItem(name, exception_state); @@ -383,12 +383,12 @@ const AtomicString& name, v8::Local<v8::Value> v8_value, const v8::PropertyCallbackInfo<v8::Value>& info) { - const CString& name_in_utf8 = name.Utf8(); + const std::string& name_in_utf8 = name.Utf8(); ExceptionState exception_state( info.GetIsolate(), ExceptionState::kSetterContext, "TestInterface2", - name_in_utf8.data()); + name_in_utf8.c_str()); TestInterface2* impl = V8TestInterface2::ToImpl(info.Holder()); TestInterfaceEmpty* property_value = V8TestInterfaceEmpty::ToImplWithTypeCheck(info.GetIsolate(), v8_value); @@ -407,12 +407,12 @@ static void NamedPropertyDeleter( const AtomicString& name, const v8::PropertyCallbackInfo<v8::Boolean>& info) { - const CString& name_in_utf8 = name.Utf8(); + const std::string& name_in_utf8 = name.Utf8(); ExceptionState exception_state( info.GetIsolate(), ExceptionState::kDeletionContext, "TestInterface2", - name_in_utf8.data()); + name_in_utf8.c_str()); TestInterface2* impl = V8TestInterface2::ToImpl(info.Holder()); @@ -426,12 +426,12 @@ static void NamedPropertyQuery( const AtomicString& name, const v8::PropertyCallbackInfo<v8::Integer>& info) { - const CString& name_in_utf8 = name.Utf8(); + const std::string& name_in_utf8 = name.Utf8(); ExceptionState exception_state( info.GetIsolate(), ExceptionState::kGetterContext, "TestInterface2", - name_in_utf8.data()); + name_in_utf8.c_str()); TestInterface2* impl = V8TestInterface2::ToImpl(info.Holder());
diff --git a/third_party/blink/renderer/bindings/tests/results/core/v8_test_object.cc b/third_party/blink/renderer/bindings/tests/results/core/v8_test_object.cc index b069acbd..12d12e29 100644 --- a/third_party/blink/renderer/bindings/tests/results/core/v8_test_object.cc +++ b/third_party/blink/renderer/bindings/tests/results/core/v8_test_object.cc
@@ -9176,12 +9176,12 @@ static void NamedPropertyQuery( const AtomicString& name, const v8::PropertyCallbackInfo<v8::Integer>& info) { - const CString& name_in_utf8 = name.Utf8(); + const std::string& name_in_utf8 = name.Utf8(); ExceptionState exception_state( info.GetIsolate(), ExceptionState::kGetterContext, "TestObject", - name_in_utf8.data()); + name_in_utf8.c_str()); ScriptState* script_state = ScriptState::ForRelevantRealm(info); TestObject* impl = V8TestObject::ToImpl(info.Holder());
diff --git a/third_party/blink/renderer/bindings/tests/results/core/v8_test_special_operations.cc b/third_party/blink/renderer/bindings/tests/results/core/v8_test_special_operations.cc index a2fabbc3..cc42ef9 100644 --- a/third_party/blink/renderer/bindings/tests/results/core/v8_test_special_operations.cc +++ b/third_party/blink/renderer/bindings/tests/results/core/v8_test_special_operations.cc
@@ -120,12 +120,12 @@ template <typename T> static void NamedPropertyQuery( const AtomicString& name, const v8::PropertyCallbackInfo<T>& info) { - const CString& name_in_utf8 = name.Utf8(); + const std::string& name_in_utf8 = name.Utf8(); ExceptionState exception_state( info.GetIsolate(), ExceptionState::kGetterContext, "TestSpecialOperations", - name_in_utf8.data()); + name_in_utf8.c_str()); TestSpecialOperations* impl = V8TestSpecialOperations::ToImpl(info.Holder());
diff --git a/third_party/blink/renderer/bindings/tests/results/core/v8_test_special_operations_not_enumerable.cc b/third_party/blink/renderer/bindings/tests/results/core/v8_test_special_operations_not_enumerable.cc index 4981915a..199e77d 100644 --- a/third_party/blink/renderer/bindings/tests/results/core/v8_test_special_operations_not_enumerable.cc +++ b/third_party/blink/renderer/bindings/tests/results/core/v8_test_special_operations_not_enumerable.cc
@@ -76,12 +76,12 @@ static void NamedPropertyQuery( const AtomicString& name, const v8::PropertyCallbackInfo<v8::Integer>& info) { - const CString& name_in_utf8 = name.Utf8(); + const std::string& name_in_utf8 = name.Utf8(); ExceptionState exception_state( info.GetIsolate(), ExceptionState::kGetterContext, "TestSpecialOperationsNotEnumerable", - name_in_utf8.data()); + name_in_utf8.c_str()); TestSpecialOperationsNotEnumerable* impl = V8TestSpecialOperationsNotEnumerable::ToImpl(info.Holder());
diff --git a/third_party/blink/renderer/bindings/tests/results/modules/v8_test_inherited_legacy_unenumerable_named_properties.cc b/third_party/blink/renderer/bindings/tests/results/modules/v8_test_inherited_legacy_unenumerable_named_properties.cc index 87c851f7..72a8c71 100644 --- a/third_party/blink/renderer/bindings/tests/results/modules/v8_test_inherited_legacy_unenumerable_named_properties.cc +++ b/third_party/blink/renderer/bindings/tests/results/modules/v8_test_inherited_legacy_unenumerable_named_properties.cc
@@ -86,12 +86,12 @@ template <typename T> static void NamedPropertyQuery( const AtomicString& name, const v8::PropertyCallbackInfo<T>& info) { - const CString& name_in_utf8 = name.Utf8(); + const std::string& name_in_utf8 = name.Utf8(); ExceptionState exception_state( info.GetIsolate(), ExceptionState::kGetterContext, "TestInheritedLegacyUnenumerableNamedProperties", - name_in_utf8.data()); + name_in_utf8.c_str()); TestInheritedLegacyUnenumerableNamedProperties* impl = V8TestInheritedLegacyUnenumerableNamedProperties::ToImpl(info.Holder());
diff --git a/third_party/blink/renderer/bindings/tests/results/modules/v8_test_interface_5.cc b/third_party/blink/renderer/bindings/tests/results/modules/v8_test_interface_5.cc index 00236e4..a95030c 100644 --- a/third_party/blink/renderer/bindings/tests/results/modules/v8_test_interface_5.cc +++ b/third_party/blink/renderer/bindings/tests/results/modules/v8_test_interface_5.cc
@@ -528,12 +528,12 @@ static void NamedPropertyQuery( const AtomicString& name, const v8::PropertyCallbackInfo<v8::Integer>& info) { - const CString& name_in_utf8 = name.Utf8(); + const std::string& name_in_utf8 = name.Utf8(); ExceptionState exception_state( info.GetIsolate(), ExceptionState::kGetterContext, "TestInterface5", - name_in_utf8.data()); + name_in_utf8.c_str()); TestInterface5Implementation* impl = V8TestInterface5::ToImpl(info.Holder());
diff --git a/third_party/blink/renderer/core/BUILD.gn b/third_party/blink/renderer/core/BUILD.gn index 2aebd6a..93259ed 100644 --- a/third_party/blink/renderer/core/BUILD.gn +++ b/third_party/blink/renderer/core/BUILD.gn
@@ -2115,6 +2115,7 @@ "streams/readable_stream_test.cc", "streams/stream_promise_resolver_test.cc", "streams/test_underlying_source.h", + "streams/transferable_streams_test.cc", "streams/transform_stream_test.cc", "streams/writable_stream_test.cc", "style/border_value_test.cc",
diff --git a/third_party/blink/renderer/core/animation/compositor_animations_test.cc b/third_party/blink/renderer/core/animation/compositor_animations_test.cc index f38984d..2a1d764 100644 --- a/third_party/blink/renderer/core/animation/compositor_animations_test.cc +++ b/third_party/blink/renderer/core/animation/compositor_animations_test.cc
@@ -177,12 +177,6 @@ void GetAnimationOnCompositor( Timing& timing, StringKeyframeEffectModel& effect, - Vector<std::unique_ptr<CompositorKeyframeModel>>& keyframe_models) { - GetAnimationOnCompositor(timing, effect, keyframe_models, 1); - } - void GetAnimationOnCompositor( - Timing& timing, - StringKeyframeEffectModel& effect, Vector<std::unique_ptr<CompositorKeyframeModel>>& keyframe_models, double animation_playback_rate) { CompositorAnimations::GetAnimationOnCompositor(
diff --git a/third_party/blink/renderer/core/css/css_font_face_source_test.cc b/third_party/blink/renderer/core/css/css_font_face_source_test.cc index 62ffbf43..9ef1fca 100644 --- a/third_party/blink/renderer/core/css/css_font_face_source_test.cc +++ b/third_party/blink/renderer/core/css/css_font_face_source_test.cc
@@ -18,8 +18,8 @@ scoped_refptr<SimpleFontData> CreateFontData( const FontDescription&, const FontSelectionCapabilities&) override { - return SimpleFontData::Create(FontPlatformData(SkTypeface::MakeDefault(), - CString(), 0, false, false)); + return SimpleFontData::Create(FontPlatformData( + SkTypeface::MakeDefault(), std::string(), 0, false, false)); } DummyFontFaceSource() = default;
diff --git a/third_party/blink/renderer/core/css/resolver/style_resolver.cc b/third_party/blink/renderer/core/css/resolver/style_resolver.cc index b1fb500..c685cb2 100644 --- a/third_party/blink/renderer/core/css/resolver/style_resolver.cc +++ b/third_party/blink/renderer/core/css/resolver/style_resolver.cc
@@ -982,8 +982,8 @@ return state.TakeStyle(); } -scoped_refptr<ComputedStyle> StyleResolver::StyleForPage(int page_index) { - scoped_refptr<ComputedStyle> initial_style = +scoped_refptr<const ComputedStyle> StyleResolver::StyleForPage(int page_index) { + scoped_refptr<const ComputedStyle> initial_style = InitialStyleForElement(GetDocument()); StyleResolverState state(GetDocument(), GetDocument().documentElement(), nullptr /* pseudo_element */, initial_style.get(),
diff --git a/third_party/blink/renderer/core/css/resolver/style_resolver.h b/third_party/blink/renderer/core/css/resolver/style_resolver.h index b5c9f07..1de2c23d 100644 --- a/third_party/blink/renderer/core/css/resolver/style_resolver.h +++ b/third_party/blink/renderer/core/css/resolver/style_resolver.h
@@ -88,7 +88,7 @@ const ComputedStyle* parent_style, const ComputedStyle* layout_parent_style); - scoped_refptr<ComputedStyle> StyleForPage(int page_index); + scoped_refptr<const ComputedStyle> StyleForPage(int page_index); scoped_refptr<const ComputedStyle> StyleForText(Text*); static scoped_refptr<ComputedStyle> StyleForViewport(Document&);
diff --git a/third_party/blink/renderer/core/dom/document.cc b/third_party/blink/renderer/core/dom/document.cc index 0e6aa51..a2d09a03 100644 --- a/third_party/blink/renderer/core/dom/document.cc +++ b/third_party/blink/renderer/core/dom/document.cc
@@ -2574,7 +2574,7 @@ focused_element_->blur(); } -scoped_refptr<ComputedStyle> Document::StyleForPage(int page_index) { +scoped_refptr<const ComputedStyle> Document::StyleForPage(int page_index) { UpdateDistributionForUnknownReasons(); return EnsureStyleResolver().StyleForPage(page_index); } @@ -2620,7 +2620,7 @@ int& margin_right, int& margin_bottom, int& margin_left) { - scoped_refptr<ComputedStyle> style = StyleForPage(page_index); + scoped_refptr<const ComputedStyle> style = StyleForPage(page_index); double width = page_size.Width(); double height = page_size.Height(); @@ -8166,8 +8166,9 @@ void showLiveDocumentInstances() { WeakDocumentSet& set = liveDocumentSet(); fprintf(stderr, "There are %u documents currently alive:\n", set.size()); - for (blink::Document* document : set) + for (blink::Document* document : set) { fprintf(stderr, "- Document %p URL: %s\n", document, - document->Url().GetString().Utf8().data()); + document->Url().GetString().Utf8().c_str()); + } } #endif
diff --git a/third_party/blink/renderer/core/dom/document.h b/third_party/blink/renderer/core/dom/document.h index 2f8079e..6f289c8 100644 --- a/third_party/blink/renderer/core/dom/document.h +++ b/third_party/blink/renderer/core/dom/document.h
@@ -529,7 +529,7 @@ kRunPostLayoutTasksSynchronously, }; void UpdateStyleAndLayoutForNode(const Node*); - scoped_refptr<ComputedStyle> StyleForPage(int page_index); + scoped_refptr<const ComputedStyle> StyleForPage(int page_index); // Ensures that location-based data will be valid for a given node. //
diff --git a/third_party/blink/renderer/core/dom/events/event_target.cc b/third_party/blink/renderer/core/dom/events/event_target.cc index cecc5c3..3dbe4ae 100644 --- a/third_party/blink/renderer/core/dom/events/event_target.cc +++ b/third_party/blink/renderer/core/dom/events/event_target.cc
@@ -138,7 +138,7 @@ " ms due to main thread being busy. " "Consider marking event handler as 'passive' to make the page more " "responsive.", - event.type().GetString().Utf8().data(), delayed.InMilliseconds()); + event.type().GetString().Utf8().c_str(), delayed.InMilliseconds()); PerformanceMonitor::ReportGenericViolation( target.GetExecutionContext(), PerformanceMonitor::kBlockedEvent, message_text, delayed, listener->GetSourceLocation(target)); @@ -377,7 +377,7 @@ "Consider marking event handler as 'passive' to make the page more " "responsive. See " "https://www.chromestatus.com/feature/5745543795965952", - event_type.GetString().Utf8().data()); + event_type.GetString().Utf8().c_str()); PerformanceMonitor::ReportGenericViolation( GetExecutionContext(), PerformanceMonitor::kDiscouragedAPIUse, @@ -501,7 +501,7 @@ String message_text = String::Format( "Added synchronous DOM mutation listener to a '%s' event. " "Consider using MutationObserver to make the page more responsive.", - event_type.GetString().Utf8().data()); + event_type.GetString().Utf8().c_str()); PerformanceMonitor::ReportGenericViolation( context, PerformanceMonitor::kDiscouragedAPIUse, message_text, base::TimeDelta(), nullptr);
diff --git a/third_party/blink/renderer/core/dom/node.cc b/third_party/blink/renderer/core/dom/node.cc index ae893ca..f6f42fe 100644 --- a/third_party/blink/renderer/core/dom/node.cc +++ b/third_party/blink/renderer/core/dom/node.cc
@@ -2046,7 +2046,7 @@ } std::ostream& operator<<(std::ostream& ostream, const Node& node) { - return ostream << node.ToString().Utf8().data(); + return ostream << node.ToString().Utf8(); } std::ostream& operator<<(std::ostream& ostream, const Node* node) { @@ -2112,7 +2112,7 @@ switch (node->getNodeType()) { case kElementNode: { - stream << "/" << node->nodeName().Utf8().data(); + stream << "/" << node->nodeName().Utf8(); const auto* element = To<Element>(node); const AtomicString& idattr = element->GetIdAttribute(); @@ -2126,12 +2126,12 @@ } } if (has_id_attr) - stream << "[@id=\"" << idattr.Utf8().data() + stream << "[@id=\"" << idattr.Utf8() << "\" and position()=" << count << "]"; else stream << "[" << count << "]"; } else if (has_id_attr) { - stream << "[@id=\"" << idattr.Utf8().data() << "\"]"; + stream << "[@id=\"" << idattr.Utf8() << "\"]"; } break; } @@ -2139,7 +2139,7 @@ stream << "/text()"; break; case kAttributeNode: - stream << "/@" << node->nodeName().Utf8().data(); + stream << "/@" << node->nodeName().Utf8(); break; default: break; @@ -2264,7 +2264,7 @@ std::ostream& stream) { if (node == marked_node) stream << "*"; - stream << indent.Utf8().data() << *node << "\n"; + stream << indent.Utf8() << *node << "\n"; if (auto* frame_owner_element = DynamicTo<HTMLFrameOwnerElement>(node)) { PrintSubTreeAcrossFrame(frame_owner_element->contentDocument(), marked_node, indent + "\t", stream); @@ -3074,7 +3074,7 @@ void showTree(const blink::Node* node) { if (node) - LOG(INFO) << "\n" << node->ToTreeStringForThis().Utf8().data(); + LOG(INFO) << "\n" << node->ToTreeStringForThis().Utf8(); else LOG(INFO) << "Cannot showTree for <null>"; }
diff --git a/third_party/blink/renderer/core/dom/range.cc b/third_party/blink/renderer/core/dom/range.cc index 7deffbd..e6b942d4 100644 --- a/third_party/blink/renderer/core/dom/range.cc +++ b/third_party/blink/renderer/core/dom/range.cc
@@ -1818,7 +1818,6 @@ ->ToMarkedTreeString(range->startContainer(), "S", range->endContainer(), "E") .Utf8() - .data() << "start offset: " << range->startOffset() << ", end offset: " << range->endOffset(); } else {
diff --git a/third_party/blink/renderer/core/editing/ephemeral_range.cc b/third_party/blink/renderer/core/editing/ephemeral_range.cc index 6af4259..081263d7 100644 --- a/third_party/blink/renderer/core/editing/ephemeral_range.cc +++ b/third_party/blink/renderer/core/editing/ephemeral_range.cc
@@ -175,12 +175,9 @@ ->ToMarkedTreeString(StartPosition().AnchorNode(), "S", EndPosition().AnchorNode(), "E") .Utf8() - .data() - << "start: " - << StartPosition().ToAnchorTypeAndOffsetString().Utf8().data() + << "start: " << StartPosition().ToAnchorTypeAndOffsetString().Utf8() << std::endl - << "end: " - << EndPosition().ToAnchorTypeAndOffsetString().Utf8().data(); + << "end: " << EndPosition().ToAnchorTypeAndOffsetString().Utf8(); } #endif
diff --git a/third_party/blink/renderer/core/editing/ime/input_method_controller_test.cc b/third_party/blink/renderer/core/editing/ime/input_method_controller_test.cc index f8a7334f..9706813c 100644 --- a/third_party/blink/renderer/core/editing/ime/input_method_controller_test.cc +++ b/third_party/blink/renderer/core/editing/ime/input_method_controller_test.cc
@@ -136,7 +136,7 @@ String::FromUTF8("foo\xE2\x98\x85")); // U+2605 == "black star" GetDocument().UpdateStyleAndLayout(); Controller().SetEditableSelectionOffsets(PlainTextRange(4, 4)); - EXPECT_STREQ("foo\xE2\x98\x85", input->value().Utf8().data()); + EXPECT_EQ("foo\xE2\x98\x85", input->value().Utf8()); Controller().ExtendSelectionAndDelete(1, 0); EXPECT_EQ("foo", input->value()); @@ -144,7 +144,7 @@ String::FromUTF8("foo\xF0\x9F\x8F\x86")); // U+1F3C6 == "trophy" GetDocument().UpdateStyleAndLayout(); Controller().SetEditableSelectionOffsets(PlainTextRange(4, 4)); - EXPECT_STREQ("foo\xF0\x9F\x8F\x86", input->value().Utf8().data()); + EXPECT_EQ("foo\xF0\x9F\x8F\x86", input->value().Utf8()); Controller().ExtendSelectionAndDelete(1, 0); EXPECT_EQ("foo", input->value()); @@ -152,7 +152,7 @@ input->setValue(String::FromUTF8("foo\xE0\xB8\x81\xE0\xB9\x89")); GetDocument().UpdateStyleAndLayout(); Controller().SetEditableSelectionOffsets(PlainTextRange(4, 4)); - EXPECT_STREQ("foo\xE0\xB8\x81\xE0\xB9\x89", input->value().Utf8().data()); + EXPECT_EQ("foo\xE0\xB8\x81\xE0\xB9\x89", input->value().Utf8()); Controller().ExtendSelectionAndDelete(1, 0); EXPECT_EQ("foo", input->value()); @@ -207,10 +207,10 @@ .ComputeOffsetInContainerNode()); Controller().SetComposition(String("a"), ime_text_spans, 1, 1); - EXPECT_STREQ("\xF0\x9F\x8F\x86\x61", div->innerText().Utf8().data()); + EXPECT_EQ("\xF0\x9F\x8F\x86\x61", div->innerText().Utf8()); Controller().SetComposition(String("ab"), ime_text_spans, 2, 2); - EXPECT_STREQ("\xF0\x9F\x8F\x86\x61\x62", div->innerText().Utf8().data()); + EXPECT_EQ("\xF0\x9F\x8F\x86\x61\x62", div->innerText().Utf8()); } TEST_F(InputMethodControllerTest, SetCompositionWithGraphemeCluster) { @@ -258,18 +258,18 @@ ime_text_spans, 1); Controller().CommitText("\nab ", ime_text_spans, 1); Controller().SetComposition(String("c"), ime_text_spans, 1, 1); - EXPECT_STREQ( + EXPECT_EQ( "\xE0\xA4\xB9\xE0\xA5\x87\xE0\xA4\xB2\xE0\xA5\x8D\xE0\xA4\xB2\xE0\xA5" "\x8B\nab c", - div->innerText().Utf8().data()); + div->innerText().Utf8()); EXPECT_EQ(11u, Controller().GetSelectionOffsets().Start()); EXPECT_EQ(11u, Controller().GetSelectionOffsets().End()); Controller().SetComposition(String("cd"), ime_text_spans, 2, 2); - EXPECT_STREQ( + EXPECT_EQ( "\xE0\xA4\xB9\xE0\xA5\x87\xE0\xA4\xB2\xE0\xA5\x8D\xE0\xA4\xB2\xE0\xA5" "\x8B\nab cd", - div->innerText().Utf8().data()); + div->innerText().Utf8()); EXPECT_EQ(12u, Controller().GetSelectionOffsets().Start()); EXPECT_EQ(12u, Controller().GetSelectionOffsets().End()); } @@ -288,22 +288,22 @@ // Subtract a character. Controller().SetComposition(String("12345789"), ime_text_spans, 8, 8); - EXPECT_STREQ("abc1<b>2</b>3457<b>8</b>9d<b>e</b>f", - div->InnerHTMLAsString().Utf8().data()); + EXPECT_EQ("abc1<b>2</b>3457<b>8</b>9d<b>e</b>f", + div->InnerHTMLAsString().Utf8()); EXPECT_EQ(11u, Controller().GetSelectionOffsets().Start()); EXPECT_EQ(11u, Controller().GetSelectionOffsets().End()); // Append a character. Controller().SetComposition(String("123456789"), ime_text_spans, 9, 9); - EXPECT_STREQ("abc1<b>2</b>34567<b>8</b>9d<b>e</b>f", - div->InnerHTMLAsString().Utf8().data()); + EXPECT_EQ("abc1<b>2</b>34567<b>8</b>9d<b>e</b>f", + div->InnerHTMLAsString().Utf8()); EXPECT_EQ(12u, Controller().GetSelectionOffsets().Start()); EXPECT_EQ(12u, Controller().GetSelectionOffsets().End()); // Subtract and append characters. Controller().SetComposition(String("123hello789"), ime_text_spans, 11, 11); - EXPECT_STREQ("abc1<b>2</b>3hello7<b>8</b>9d<b>e</b>f", - div->InnerHTMLAsString().Utf8().data()); + EXPECT_EQ("abc1<b>2</b>3hello7<b>8</b>9d<b>e</b>f", + div->InnerHTMLAsString().Utf8()); } TEST_F(InputMethodControllerTest, SetCompositionWithEmojiKeepingStyle) { @@ -322,13 +322,11 @@ // surrogate pair to the previous one. Controller().SetComposition(String::FromUTF8("\xF0\x9F\x8F\xAB"), ime_text_spans, 2, 2); - EXPECT_STREQ("<b>\xF0\x9F\x8F\xAB</b>", - div->InnerHTMLAsString().Utf8().data()); + EXPECT_EQ("<b>\xF0\x9F\x8F\xAB</b>", div->InnerHTMLAsString().Utf8()); Controller().SetComposition(String::FromUTF8("\xF0\x9F\x8F\xA0"), ime_text_spans, 2, 2); - EXPECT_STREQ("<b>\xF0\x9F\x8F\xA0</b>", - div->InnerHTMLAsString().Utf8().data()); + EXPECT_EQ("<b>\xF0\x9F\x8F\xA0</b>", div->InnerHTMLAsString().Utf8()); } TEST_F(InputMethodControllerTest, @@ -349,12 +347,11 @@ // 1 grapheme cluster. Controller().SetComposition(String::FromUTF8("\xE0\xB0\x83\xE0\xB0\x83"), ime_text_spans, 2, 2); - EXPECT_STREQ("<b>\xE0\xB0\x83\xE0\xB0\x83</b>", - div->InnerHTMLAsString().Utf8().data()); + EXPECT_EQ("<b>\xE0\xB0\x83\xE0\xB0\x83</b>", div->InnerHTMLAsString().Utf8()); Controller().SetComposition(String::FromUTF8("\xE0\xB0\x83"), ime_text_spans, 1, 1); - EXPECT_STREQ("<b>\xE0\xB0\x83</b>", div->InnerHTMLAsString().Utf8().data()); + EXPECT_EQ("<b>\xE0\xB0\x83</b>", div->InnerHTMLAsString().Utf8()); } TEST_F(InputMethodControllerTest, FinishComposingTextKeepingStyle) { @@ -664,7 +661,7 @@ input->setValue(String::FromUTF8("foo\xE2\x98\x85")); GetDocument().UpdateStyleAndLayout(); Controller().SetEditableSelectionOffsets(PlainTextRange(4, 4)); - EXPECT_STREQ("foo\xE2\x98\x85", input->value().Utf8().data()); + EXPECT_EQ("foo\xE2\x98\x85", input->value().Utf8()); Controller().DeleteSurroundingText(1, 0); EXPECT_EQ("foo", input->value()); @@ -672,7 +669,7 @@ input->setValue(String::FromUTF8("foo\xF0\x9F\x8F\x86")); GetDocument().UpdateStyleAndLayout(); Controller().SetEditableSelectionOffsets(PlainTextRange(5, 5)); - EXPECT_STREQ("foo\xF0\x9F\x8F\x86", input->value().Utf8().data()); + EXPECT_EQ("foo\xF0\x9F\x8F\x86", input->value().Utf8()); Controller().DeleteSurroundingText(1, 0); EXPECT_EQ("foo", input->value()); @@ -680,7 +677,7 @@ input->setValue(String::FromUTF8("foo\xE0\xB8\x81\xE0\xB9\x89")); GetDocument().UpdateStyleAndLayout(); Controller().SetEditableSelectionOffsets(PlainTextRange(5, 5)); - EXPECT_STREQ("foo\xE0\xB8\x81\xE0\xB9\x89", input->value().Utf8().data()); + EXPECT_EQ("foo\xE0\xB8\x81\xE0\xB9\x89", input->value().Utf8()); Controller().DeleteSurroundingText(1, 0); EXPECT_EQ("foo", input->value()); @@ -688,17 +685,15 @@ input->setValue(String::FromUTF8("foo\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86")); GetDocument().UpdateStyleAndLayout(); Controller().SetEditableSelectionOffsets(PlainTextRange(7, 7)); - EXPECT_STREQ("foo\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86", - input->value().Utf8().data()); + EXPECT_EQ("foo\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86", input->value().Utf8()); Controller().DeleteSurroundingText(2, 0); - EXPECT_STREQ("foo\xF0\x9F\x8F\x86", input->value().Utf8().data()); + EXPECT_EQ("foo\xF0\x9F\x8F\x86", input->value().Utf8()); // "trophy" + "trophy". input->setValue(String::FromUTF8("foo\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86")); GetDocument().UpdateStyleAndLayout(); Controller().SetEditableSelectionOffsets(PlainTextRange(7, 7)); - EXPECT_STREQ("foo\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86", - input->value().Utf8().data()); + EXPECT_EQ("foo\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86", input->value().Utf8()); Controller().DeleteSurroundingText(3, 0); EXPECT_EQ("foo", input->value()); @@ -706,8 +701,7 @@ input->setValue(String::FromUTF8("foo\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86")); GetDocument().UpdateStyleAndLayout(); Controller().SetEditableSelectionOffsets(PlainTextRange(7, 7)); - EXPECT_STREQ("foo\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86", - input->value().Utf8().data()); + EXPECT_EQ("foo\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86", input->value().Utf8()); Controller().DeleteSurroundingText(4, 0); EXPECT_EQ("foo", input->value()); @@ -715,8 +709,7 @@ input->setValue(String::FromUTF8("foo\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86")); GetDocument().UpdateStyleAndLayout(); Controller().SetEditableSelectionOffsets(PlainTextRange(7, 7)); - EXPECT_STREQ("foo\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86", - input->value().Utf8().data()); + EXPECT_EQ("foo\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86", input->value().Utf8()); Controller().DeleteSurroundingText(5, 0); EXPECT_EQ("fo", input->value()); } @@ -730,7 +723,7 @@ input->setValue(String::FromUTF8("\xE2\x98\x85 foo")); GetDocument().UpdateStyleAndLayout(); Controller().SetEditableSelectionOffsets(PlainTextRange(0, 0)); - EXPECT_STREQ("\xE2\x98\x85 foo", input->value().Utf8().data()); + EXPECT_EQ("\xE2\x98\x85 foo", input->value().Utf8()); Controller().DeleteSurroundingText(0, 1); EXPECT_EQ(" foo", input->value()); @@ -738,7 +731,7 @@ input->setValue(String::FromUTF8("\xF0\x9F\x8F\x86 foo")); GetDocument().UpdateStyleAndLayout(); Controller().SetEditableSelectionOffsets(PlainTextRange(0, 0)); - EXPECT_STREQ("\xF0\x9F\x8F\x86 foo", input->value().Utf8().data()); + EXPECT_EQ("\xF0\x9F\x8F\x86 foo", input->value().Utf8()); Controller().DeleteSurroundingText(0, 1); EXPECT_EQ(" foo", input->value()); @@ -746,7 +739,7 @@ input->setValue(String::FromUTF8("\xE0\xB8\x81\xE0\xB9\x89 foo")); GetDocument().UpdateStyleAndLayout(); Controller().SetEditableSelectionOffsets(PlainTextRange(0, 0)); - EXPECT_STREQ("\xE0\xB8\x81\xE0\xB9\x89 foo", input->value().Utf8().data()); + EXPECT_EQ("\xE0\xB8\x81\xE0\xB9\x89 foo", input->value().Utf8()); Controller().DeleteSurroundingText(0, 1); EXPECT_EQ(" foo", input->value()); @@ -754,17 +747,15 @@ input->setValue(String::FromUTF8("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86 foo")); GetDocument().UpdateStyleAndLayout(); Controller().SetEditableSelectionOffsets(PlainTextRange(0, 0)); - EXPECT_STREQ("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86 foo", - input->value().Utf8().data()); + EXPECT_EQ("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86 foo", input->value().Utf8()); Controller().DeleteSurroundingText(0, 2); - EXPECT_STREQ("\xF0\x9F\x8F\x86 foo", input->value().Utf8().data()); + EXPECT_EQ("\xF0\x9F\x8F\x86 foo", input->value().Utf8()); // "trophy" + "trophy". input->setValue(String::FromUTF8("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86 foo")); GetDocument().UpdateStyleAndLayout(); Controller().SetEditableSelectionOffsets(PlainTextRange(0, 0)); - EXPECT_STREQ("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86 foo", - input->value().Utf8().data()); + EXPECT_EQ("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86 foo", input->value().Utf8()); Controller().DeleteSurroundingText(0, 3); EXPECT_EQ(" foo", input->value()); @@ -772,8 +763,7 @@ input->setValue(String::FromUTF8("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86 foo")); GetDocument().UpdateStyleAndLayout(); Controller().SetEditableSelectionOffsets(PlainTextRange(0, 0)); - EXPECT_STREQ("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86 foo", - input->value().Utf8().data()); + EXPECT_EQ("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86 foo", input->value().Utf8()); Controller().DeleteSurroundingText(0, 4); EXPECT_EQ(" foo", input->value()); @@ -781,8 +771,7 @@ input->setValue(String::FromUTF8("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86 foo")); GetDocument().UpdateStyleAndLayout(); Controller().SetEditableSelectionOffsets(PlainTextRange(0, 0)); - EXPECT_STREQ("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86 foo", - input->value().Utf8().data()); + EXPECT_EQ("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86 foo", input->value().Utf8()); Controller().DeleteSurroundingText(0, 5); EXPECT_EQ("foo", input->value()); } @@ -796,8 +785,7 @@ input->setValue(String::FromUTF8("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86")); GetDocument().UpdateStyleAndLayout(); Controller().SetEditableSelectionOffsets(PlainTextRange(2, 2)); - EXPECT_STREQ("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86", - input->value().Utf8().data()); + EXPECT_EQ("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86", input->value().Utf8()); Controller().DeleteSurroundingText(1, 1); EXPECT_EQ("", input->value()); } @@ -850,7 +838,7 @@ Controller().SetEditableSelectionOffsets(PlainTextRange(8, 8)); Controller().DeleteSurroundingTextInCodePoints(2, 0); - EXPECT_STREQ("a\xE2\x98\x85 \xF0\x9F\x8F\x86 ", input->value().Utf8().data()); + EXPECT_EQ("a\xE2\x98\x85 \xF0\x9F\x8F\x86 ", input->value().Utf8()); Controller().DeleteSurroundingTextInCodePoints(4, 0); EXPECT_EQ("a", input->value()); @@ -865,7 +853,7 @@ // grapheme cluster (2 code points). The root cause is that we adjust the // selection by grapheme cluster in deleteSurroundingText(). Controller().DeleteSurroundingTextInCodePoints(1, 0); - EXPECT_STREQ("a\xE2\x98\x85 \xF0\x9F\x8F\x86 ", input->value().Utf8().data()); + EXPECT_EQ("a\xE2\x98\x85 \xF0\x9F\x8F\x86 ", input->value().Utf8()); } TEST_F(InputMethodControllerTest, @@ -880,7 +868,7 @@ Controller().SetEditableSelectionOffsets(PlainTextRange(0, 0)); Controller().DeleteSurroundingTextInCodePoints(0, 5); - EXPECT_STREQ("\xE0\xB8\x81\xE0\xB9\x89", input->value().Utf8().data()); + EXPECT_EQ("\xE0\xB8\x81\xE0\xB9\x89", input->value().Utf8()); Controller().DeleteSurroundingTextInCodePoints(0, 1); // TODO(yabinh): Same here. We should only delete 1 code point. @@ -898,7 +886,7 @@ GetDocument().UpdateStyleAndLayout(); Controller().SetEditableSelectionOffsets(PlainTextRange(3, 3)); Controller().DeleteSurroundingTextInCodePoints(2, 2); - EXPECT_STREQ("a\xE0\xB8\x81\xE0\xB9\x89", input->value().Utf8().data()); + EXPECT_EQ("a\xE0\xB8\x81\xE0\xB9\x89", input->value().Utf8()); } TEST_F(InputMethodControllerTest, DeleteSurroundingTextInCodePointsWithImage) { @@ -928,28 +916,23 @@ GetDocument().UpdateStyleAndLayout(); // The invalid high surrogate is encoded as '\xED\xA0\xBC', and invalid low // surrogate is encoded as '\xED\xBF\x86'. - EXPECT_STREQ("a\xED\xA0\xBC\xE2\x98\x85\xED\xBF\x86 ", - input->value().Utf8().data()); + EXPECT_EQ("a\xED\xA0\xBC\xE2\x98\x85\xED\xBF\x86 ", input->value().Utf8()); Controller().SetEditableSelectionOffsets(PlainTextRange(5, 5)); // Delete a SPACE. Controller().DeleteSurroundingTextInCodePoints(1, 0); - EXPECT_STREQ("a\xED\xA0\xBC\xE2\x98\x85\xED\xBF\x86", - input->value().Utf8().data()); + EXPECT_EQ("a\xED\xA0\xBC\xE2\x98\x85\xED\xBF\x86", input->value().Utf8()); // Do nothing since there is an invalid surrogate in the requested range. Controller().DeleteSurroundingTextInCodePoints(2, 0); - EXPECT_STREQ("a\xED\xA0\xBC\xE2\x98\x85\xED\xBF\x86", - input->value().Utf8().data()); + EXPECT_EQ("a\xED\xA0\xBC\xE2\x98\x85\xED\xBF\x86", input->value().Utf8()); Controller().SetEditableSelectionOffsets(PlainTextRange(0, 0)); // Delete 'a'. Controller().DeleteSurroundingTextInCodePoints(0, 1); - EXPECT_STREQ("\xED\xA0\xBC\xE2\x98\x85\xED\xBF\x86", - input->value().Utf8().data()); + EXPECT_EQ("\xED\xA0\xBC\xE2\x98\x85\xED\xBF\x86", input->value().Utf8()); // Do nothing since there is an invalid surrogate in the requested range. Controller().DeleteSurroundingTextInCodePoints(0, 2); - EXPECT_STREQ("\xED\xA0\xBC\xE2\x98\x85\xED\xBF\x86", - input->value().Utf8().data()); + EXPECT_EQ("\xED\xA0\xBC\xE2\x98\x85\xED\xBF\x86", input->value().Utf8()); } TEST_F(InputMethodControllerTest, SetCompositionForInputWithNewCaretPositions) { @@ -1317,7 +1300,7 @@ GetDocument().setTitle(g_empty_string); GetDocument().UpdateStyleAndLayout(); Controller().CommitText("", ime_text_spans, 0); - EXPECT_STREQ("", GetDocument().title().Utf8().data()); + EXPECT_EQ("", GetDocument().title().Utf8()); GetDocument().setTitle(g_empty_string); Controller().SetComposition("n", ime_text_spans, 1, 1); @@ -1643,10 +1626,9 @@ // Check that the marker is still attached to " text" and includes the space // before "text" but not the space after EXPECT_EQ(1u, GetDocument().Markers().Markers().size()); - ASSERT_STREQ("\xC2\xA0text", - GetMarkedText(GetDocument().Markers(), div->firstChild(), 0) - .Utf8() - .data()); + ASSERT_EQ( + "\xC2\xA0text", + GetMarkedText(GetDocument().Markers(), div->firstChild(), 0).Utf8()); } TEST_F(InputMethodControllerTest, @@ -1671,10 +1653,9 @@ // Check that the marker is still attached to "text " and includes the space // after "text" but not the space before EXPECT_EQ(1u, GetDocument().Markers().Markers().size()); - ASSERT_STREQ("text\xC2\xA0", - GetMarkedText(GetDocument().Markers(), div->firstChild(), 0) - .Utf8() - .data()); + ASSERT_EQ( + "text\xC2\xA0", + GetMarkedText(GetDocument().Markers(), div->firstChild(), 0).Utf8()); } TEST_F( @@ -1701,10 +1682,9 @@ // Check that the marker is still attached to " text " and includes both the // space before "text" and the space after EXPECT_EQ(1u, GetDocument().Markers().Markers().size()); - ASSERT_STREQ("\xC2\xA0text\xC2\xA0", - GetMarkedText(GetDocument().Markers(), div->firstChild(), 0) - .Utf8() - .data()); + ASSERT_EQ( + "\xC2\xA0text\xC2\xA0", + GetMarkedText(GetDocument().Markers(), div->firstChild(), 0).Utf8()); } TEST_F(InputMethodControllerTest, ContentDependentMarker_ReplaceStartOfMarker) { @@ -1742,10 +1722,9 @@ // Verify marker is under "Original text" EXPECT_EQ(1u, GetDocument().Markers().Markers().size()); - ASSERT_STREQ("Original text", - GetMarkedText(GetDocument().Markers(), div->firstChild(), 0) - .Utf8() - .data()); + ASSERT_EQ( + "Original text", + GetMarkedText(GetDocument().Markers(), div->firstChild(), 0).Utf8()); } TEST_F(InputMethodControllerTest, @@ -1824,10 +1803,9 @@ // Verify marker is under "Initial string" EXPECT_EQ(1u, GetDocument().Markers().Markers().size()); - ASSERT_STREQ("Initial string", - GetMarkedText(GetDocument().Markers(), div->firstChild(), 0) - .Utf8() - .data()); + ASSERT_EQ( + "Initial string", + GetMarkedText(GetDocument().Markers(), div->firstChild(), 0).Utf8()); } TEST_F(InputMethodControllerTest, @@ -1911,10 +1889,9 @@ // Verify marker is under "string" EXPECT_EQ(1u, GetDocument().Markers().Markers().size()); - ASSERT_STREQ("string", - GetMarkedText(GetDocument().Markers(), div->firstChild(), 0) - .Utf8() - .data()); + ASSERT_EQ( + "string", + GetMarkedText(GetDocument().Markers(), div->firstChild(), 0).Utf8()); } TEST_F(InputMethodControllerTest, @@ -2555,8 +2532,7 @@ EXPECT_EQ(1u, div->CountChildren()); auto* text = To<Text>(div->firstChild()); - EXPECT_STREQ("\xE0\xAE\x9A\xE0\xAF\x8D\xE0\xAE\x9A", - text->data().Utf8().data()); + EXPECT_EQ("\xE0\xAE\x9A\xE0\xAF\x8D\xE0\xAE\x9A", text->data().Utf8()); Range* range = GetCompositionRange(); EXPECT_EQ(2u, range->startOffset());
diff --git a/third_party/blink/renderer/core/editing/iterators/simplified_backwards_text_iterator_test.cc b/third_party/blink/renderer/core/editing/iterators/simplified_backwards_text_iterator_test.cc index 58ae10e..cf442f18 100644 --- a/third_party/blink/renderer/core/editing/iterators/simplified_backwards_text_iterator_test.cc +++ b/third_party/blink/renderer/core/editing/iterators/simplified_backwards_text_iterator_test.cc
@@ -35,8 +35,7 @@ is_first = false; builder.Append(iterator.GetTextState().GetTextForTesting()); } - CString utf8 = builder.ToString().Utf8(); - return std::string(utf8.data(), utf8.length()); + return builder.ToString().Utf8(); } };
diff --git a/third_party/blink/renderer/core/editing/iterators/text_iterator_test.cc b/third_party/blink/renderer/core/editing/iterators/text_iterator_test.cc index 2add728..004aeee 100644 --- a/third_party/blink/renderer/core/editing/iterators/text_iterator_test.cc +++ b/third_party/blink/renderer/core/editing/iterators/text_iterator_test.cc
@@ -148,7 +148,7 @@ text_chunks.Append(iterator.GetText().GetTextForTesting()); text_chunks.Append(']'); } - return std::string(text_chunks.ToString().Utf8().data()); + return text_chunks.ToString().Utf8(); } Range* TextIteratorTest::GetBodyRange() const {
diff --git a/third_party/blink/renderer/core/editing/iterators/text_searcher_icu.cc b/third_party/blink/renderer/core/editing/iterators/text_searcher_icu.cc index ccb0531..355ba77 100644 --- a/third_party/blink/renderer/core/editing/iterators/text_searcher_icu.cc +++ b/third_party/blink/renderer/core/editing/iterators/text_searcher_icu.cc
@@ -50,7 +50,7 @@ CurrentSearchLocaleID() + String("@collation=search"); UStringSearch* searcher = usearch_open(&kNewlineCharacter, 1, &kNewlineCharacter, 1, - search_collator_name.Utf8().data(), nullptr, &status); + search_collator_name.Utf8().c_str(), nullptr, &status); DCHECK(status == U_ZERO_ERROR || status == U_USING_FALLBACK_WARNING || status == U_USING_DEFAULT_WARNING) << status;
diff --git a/third_party/blink/renderer/core/editing/keyboard_test.cc b/third_party/blink/renderer/core/editing/keyboard_test.cc index d216985..356c435 100644 --- a/third_party/blink/renderer/core/editing/keyboard_test.cc +++ b/third_party/blink/renderer/core/editing/keyboard_test.cc
@@ -66,9 +66,7 @@ WebInputEvent::GetStaticTimeStampForTests()); event.text[0] = key_code; event.windows_key_code = key_code; - CString key_utf8 = key.Utf8(); - event.dom_key = ui::KeycodeConverter::KeyStringToDomKey( - std::string(key_utf8.data(), key_utf8.length())); + event.dom_key = ui::KeycodeConverter::KeyStringToDomKey(key.Utf8()); return event; }
diff --git a/third_party/blink/renderer/core/editing/layout_selection.cc b/third_party/blink/renderer/core/editing/layout_selection.cc index 9405b0e..ea77044e 100644 --- a/third_party/blink/renderer/core/editing/layout_selection.cc +++ b/third_party/blink/renderer/core/editing/layout_selection.cc
@@ -911,7 +911,7 @@ if (node.IsTextNode()) ostream << "#text"; else if (const Element* element = ToElementOrNull(node)) - ostream << element->tagName().Utf8().data(); + ostream << element->tagName().Utf8(); LayoutObject* layout_object = node.GetLayoutObject(); if (!layout_object) { ostream << " <null LayoutObject>";
diff --git a/third_party/blink/renderer/core/editing/layout_selection_test.cc b/third_party/blink/renderer/core/editing/layout_selection_test.cc index 31b9910..c8fbb486 100644 --- a/third_party/blink/renderer/core/editing/layout_selection_test.cc +++ b/third_party/blink/renderer/core/editing/layout_selection_test.cc
@@ -33,7 +33,7 @@ class LayoutSelectionTestBase : public EditingTestBase { protected: static void PrintText(std::ostream& ostream, const Text& text) { - ostream << "'" << text.data().Utf8().data() << "'"; + ostream << "'" << text.data().Utf8() << "'"; } static void PrintLayoutTextInfo(const FrameSelection& selection, @@ -84,7 +84,7 @@ if (const Text* text = DynamicTo<Text>(node)) PrintText(ostream, *text); else if (const Element* element = ToElementOrNull(node)) - ostream << element->tagName().Utf8().data(); + ostream << element->tagName().Utf8(); else ostream << node; @@ -96,7 +96,7 @@ PrintLayoutObjectInfo(selection, ostream, layout_object); if (LayoutTextFragment* first_letter = FirstLetterPartFor(layout_object)) { ostream << std::endl - << RepeatString(" ", depth + 1).Utf8().data() << ":first-letter"; + << RepeatString(" ", depth + 1).Utf8() << ":first-letter"; PrintLayoutObjectInfo(selection, ostream, first_letter); } } @@ -105,14 +105,14 @@ std::ostream& ostream, const Node& node, wtf_size_t depth) { - ostream << RepeatString(" ", depth).Utf8().data(); + ostream << RepeatString(" ", depth).Utf8(); if (IsHTMLStyleElement(node)) { ostream << "<style> "; return; } PrintSelectionInfo(selection, ostream, node, depth); if (ShadowRoot* shadow_root = node.GetShadowRoot()) { - ostream << std::endl << RepeatString(" ", depth + 1).Utf8().data(); + ostream << std::endl << RepeatString(" ", depth + 1).Utf8(); ostream << "#shadow-root "; for (Node* child = shadow_root->firstChild(); child; child = child->nextSibling()) {
diff --git a/third_party/blink/renderer/core/editing/markers/document_marker_controller.cc b/third_party/blink/renderer/core/editing/markers/document_marker_controller.cc index 0ccaf7f..023cfc5 100644 --- a/third_party/blink/renderer/core/editing/markers/document_marker_controller.cc +++ b/third_party/blink/renderer/core/editing/markers/document_marker_controller.cc
@@ -985,7 +985,7 @@ builder.Append("\n"); } LOG(INFO) << markers_.size() << " nodes have markers:\n" - << builder.ToString().Utf8().data(); + << builder.ToString().Utf8(); } #endif
diff --git a/third_party/blink/renderer/core/editing/position.cc b/third_party/blink/renderer/core/editing/position.cc index 7e6855c..f2c5a94e 100644 --- a/third_party/blink/renderer/core/editing/position.cc +++ b/third_party/blink/renderer/core/editing/position.cc
@@ -710,8 +710,8 @@ return; } LOG(INFO) << "\n" - << AnchorNode()->ToTreeStringForThis().Utf8().data() - << ToAnchorTypeAndOffsetString().Utf8().data(); + << AnchorNode()->ToTreeStringForThis().Utf8() + << ToAnchorTypeAndOffsetString().Utf8(); } template <typename Strategy> @@ -721,8 +721,8 @@ return; } LOG(INFO) << "\n" - << AnchorNode()->ToFlatTreeStringForThis().Utf8().data() - << ToAnchorTypeAndOffsetString().Utf8().data(); + << AnchorNode()->ToFlatTreeStringForThis().Utf8() + << ToAnchorTypeAndOffsetString().Utf8(); } #endif // DCHECK_IS_ON() @@ -733,7 +733,7 @@ if (position.IsNull()) return ostream << "null"; return ostream << position.AnchorNode() << "@" - << position.ToAnchorTypeAndOffsetString().Utf8().data(); + << position.ToAnchorTypeAndOffsetString().Utf8(); } std::ostream& operator<<(std::ostream& ostream,
diff --git a/third_party/blink/renderer/core/editing/selection_template.cc b/third_party/blink/renderer/core/editing/selection_template.cc index ed84f0c..8a6a042 100644 --- a/third_party/blink/renderer/core/editing/selection_template.cc +++ b/third_party/blink/renderer/core/editing/selection_template.cc
@@ -133,11 +133,8 @@ ->ToMarkedTreeString(base_.AnchorNode(), "B", extent_.AnchorNode(), "E") .Utf8() - .data() - << "base: " << base_.ToAnchorTypeAndOffsetString().Utf8().data() - << "\n" - << "extent: " - << extent_.ToAnchorTypeAndOffsetString().Utf8().data(); + << "base: " << base_.ToAnchorTypeAndOffsetString().Utf8() << "\n" + << "extent: " << extent_.ToAnchorTypeAndOffsetString().Utf8(); } #endif
diff --git a/third_party/blink/renderer/core/editing/serializers/markup_formatter.cc b/third_party/blink/renderer/core/editing/serializers/markup_formatter.cc index 0c4b114..8332061 100644 --- a/third_party/blink/renderer/core/editing/serializers/markup_formatter.cc +++ b/third_party/blink/renderer/core/editing/serializers/markup_formatter.cc
@@ -51,7 +51,7 @@ struct EntityDescription { UChar entity; - const CString& reference; + const std::string& reference; EntityMask mask; }; @@ -71,8 +71,8 @@ entity_maps[entity_index].mask & entity_mask) { result.Append(text + position_after_last_entity, i - position_after_last_entity); - const CString& replacement = entity_maps[entity_index].reference; - result.Append(replacement.data(), replacement.length()); + const std::string& replacement = entity_maps[entity_index].reference; + result.Append(replacement.c_str(), replacement.length()); position_after_last_entity = i + 1; break; } @@ -88,14 +88,14 @@ unsigned offset, unsigned length, EntityMask entity_mask) { - DEFINE_STATIC_LOCAL(const CString, amp_reference, ("&")); - DEFINE_STATIC_LOCAL(const CString, lt_reference, ("<")); - DEFINE_STATIC_LOCAL(const CString, gt_reference, (">")); - DEFINE_STATIC_LOCAL(const CString, quot_reference, (""")); - DEFINE_STATIC_LOCAL(const CString, nbsp_reference, (" ")); - DEFINE_STATIC_LOCAL(const CString, tab_reference, ("	")); - DEFINE_STATIC_LOCAL(const CString, line_feed_reference, (" ")); - DEFINE_STATIC_LOCAL(const CString, carriage_return_reference, (" ")); + DEFINE_STATIC_LOCAL(const std::string, amp_reference, ("&")); + DEFINE_STATIC_LOCAL(const std::string, lt_reference, ("<")); + DEFINE_STATIC_LOCAL(const std::string, gt_reference, (">")); + DEFINE_STATIC_LOCAL(const std::string, quot_reference, (""")); + DEFINE_STATIC_LOCAL(const std::string, nbsp_reference, (" ")); + DEFINE_STATIC_LOCAL(const std::string, tab_reference, ("	")); + DEFINE_STATIC_LOCAL(const std::string, line_feed_reference, (" ")); + DEFINE_STATIC_LOCAL(const std::string, carriage_return_reference, (" ")); static const EntityDescription kEntityMaps[] = { {'&', amp_reference, kEntityAmp},
diff --git a/third_party/blink/renderer/core/editing/serializers/styled_markup_serializer_test.cc b/third_party/blink/renderer/core/editing/serializers/styled_markup_serializer_test.cc index 9179f50..2ad2264 100644 --- a/third_party/blink/renderer/core/editing/serializers/styled_markup_serializer_test.cc +++ b/third_party/blink/renderer/core/editing/serializers/styled_markup_serializer_test.cc
@@ -41,7 +41,7 @@ GetDocument().body(), PositionAnchorType::kBeforeChildren); PositionTemplate<Strategy> end = PositionTemplate<Strategy>( GetDocument().body(), PositionAnchorType::kAfterChildren); - return CreateMarkup(start, end, should_annotate).Utf8().data(); + return CreateMarkup(start, end, should_annotate).Utf8(); } template <typename Strategy> @@ -49,7 +49,7 @@ const PositionTemplate<Strategy>& start, const PositionTemplate<Strategy>& end, AnnotateForInterchange should_annotate) { - return CreateMarkup(start, end, should_annotate).Utf8().data(); + return CreateMarkup(start, end, should_annotate).Utf8(); } TEST_F(StyledMarkupSerializerTest, TextOnly) {
diff --git a/third_party/blink/renderer/core/editing/testing/selection_sample.cc b/third_party/blink/renderer/core/editing/testing/selection_sample.cc index 7b1ebd71..156603e 100644 --- a/third_party/blink/renderer/core/editing/testing/selection_sample.cc +++ b/third_party/blink/renderer/core/editing/testing/selection_sample.cc
@@ -17,6 +17,7 @@ #include "third_party/blink/renderer/core/html/html_collection.h" #include "third_party/blink/renderer/core/html/html_template_element.h" #include "third_party/blink/renderer/platform/wtf/text/string_builder.h" +#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h" namespace blink { @@ -178,7 +179,7 @@ std::string Serialize(const ContainerNode& root) { SerializeChildren(root); - return builder_.ToString().Utf8().data(); + return builder_.ToString().Utf8(); } private:
diff --git a/third_party/blink/renderer/core/editing/text_offset_mapping_test.cc b/third_party/blink/renderer/core/editing/text_offset_mapping_test.cc index fc7dd060..e6db282d 100644 --- a/third_party/blink/renderer/core/editing/text_offset_mapping_test.cc +++ b/third_party/blink/renderer/core/editing/text_offset_mapping_test.cc
@@ -12,6 +12,7 @@ #include "third_party/blink/renderer/core/layout/layout_block_flow.h" #include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h" #include "third_party/blink/renderer/platform/wtf/text/string_builder.h" +#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink { @@ -33,8 +34,7 @@ builder.Append(text.Left(offset)); builder.Append('|'); builder.Append(text.Substring(offset)); - const CString result8 = builder.ToString().Utf8(); - return std::string(result8.data(), result8.length()); + return builder.ToString().Utf8(); } std::string GetRange(const std::string& selection_text) {
diff --git a/third_party/blink/renderer/core/editing/visible_selection.cc b/third_party/blink/renderer/core/editing/visible_selection.cc index 991cb00..48384ba6 100644 --- a/third_party/blink/renderer/core/editing/visible_selection.cc +++ b/third_party/blink/renderer/core/editing/visible_selection.cc
@@ -381,10 +381,8 @@ ->ToMarkedTreeString(Start().AnchorNode(), "S", End().AnchorNode(), "E") .Utf8() - .data() - << "start: " << Start().ToAnchorTypeAndOffsetString().Utf8().data() - << "\n" - << "end: " << End().ToAnchorTypeAndOffsetString().Utf8().data(); + << "start: " << Start().ToAnchorTypeAndOffsetString().Utf8() << "\n" + << "end: " << End().ToAnchorTypeAndOffsetString().Utf8(); } #endif
diff --git a/third_party/blink/renderer/core/exported/local_frame_client_impl_test.cc b/third_party/blink/renderer/core/exported/local_frame_client_impl_test.cc index 381c93e..e3449dc 100644 --- a/third_party/blink/renderer/core/exported/local_frame_client_impl_test.cc +++ b/third_party/blink/renderer/core/exported/local_frame_client_impl_test.cc
@@ -76,8 +76,8 @@ WebString UserAgent() { // The test always returns the same user agent . - WTF::CString user_agent = GetLocalFrameClient().UserAgent().Utf8(); - return WebString::FromUTF8(user_agent.data(), user_agent.length()); + std::string user_agent = GetLocalFrameClient().UserAgent().Utf8(); + return WebString::FromUTF8(user_agent.c_str(), user_agent.length()); } WebLocalFrameImpl* MainFrame() { return helper_.LocalMainFrame(); }
diff --git a/third_party/blink/renderer/core/exported/web_application_cache_host_impl.cc b/third_party/blink/renderer/core/exported/web_application_cache_host_impl.cc index ad8c3b1..7fa4d90 100644 --- a/third_party/blink/renderer/core/exported/web_application_cache_host_impl.cc +++ b/third_party/blink/renderer/core/exported/web_application_cache_host_impl.cc
@@ -152,7 +152,7 @@ // deleted within the script event handler. const char kFormatString[] = "Application Cache Progress event (%d of %d) %s"; String message = String::Format(kFormatString, num_complete, num_total, - url.GetString().Utf8().data()); + url.GetString().Utf8().c_str()); LogMessage(mojom::blink::ConsoleMessageLevel::kInfo, message); status_ = mojom::blink::AppCacheStatus::APPCACHE_STATUS_DOWNLOADING; client_->NotifyProgressEventListener(url, num_total, num_complete); @@ -164,7 +164,7 @@ // deleted within the script event handler. const char kFormatString[] = "Application Cache Error event: %s"; String full_message = - String::Format(kFormatString, details->message.Utf8().data()); + String::Format(kFormatString, details->message.Utf8().c_str()); LogMessage(mojom::blink::ConsoleMessageLevel::kError, full_message); status_ = cache_info_.is_complete
diff --git a/third_party/blink/renderer/core/exported/web_associated_url_loader_impl_test.cc b/third_party/blink/renderer/core/exported/web_associated_url_loader_impl_test.cc index 25c68a09..78995f4 100644 --- a/third_party/blink/renderer/core/exported/web_associated_url_loader_impl_test.cc +++ b/third_party/blink/renderer/core/exported/web_associated_url_loader_impl_test.cc
@@ -78,9 +78,9 @@ const WTF::String& filename) { WebURLResponse response; response.SetMimeType("text/html"); - KURL url = ToKURL(url_root + filename.Utf8().data()); + KURL url = ToKURL(url_root + filename.Utf8()); Platform::Current()->GetURLLoaderMockFactory()->RegisterURL( - url, response, test::CoreTestDataPath(filename.Utf8().data())); + url, response, test::CoreTestDataPath(filename.Utf8().c_str())); return url; } @@ -97,7 +97,7 @@ RegisterMockedUrl(url_root, iframe_support_files[i]); } - frame_test_helpers::LoadFrame(MainFrame(), url.GetString().Utf8().data()); + frame_test_helpers::LoadFrame(MainFrame(), url.GetString().Utf8().c_str()); Platform::Current()->GetURLLoaderMockFactory()->UnregisterURL(url); }
diff --git a/third_party/blink/renderer/core/exported/web_frame_serializer_sanitization_test.cc b/third_party/blink/renderer/core/exported/web_frame_serializer_sanitization_test.cc index e03d3cc3..b9f8791 100644 --- a/third_party/blink/renderer/core/exported/web_frame_serializer_sanitization_test.cc +++ b/third_party/blink/renderer/core/exported/web_frame_serializer_sanitization_test.cc
@@ -112,7 +112,7 @@ KURL parsed_url(url); String file_path("frameserialization/" + file_name); RegisterMockedFileURLLoad(parsed_url, file_path, mime_type); - frame_test_helpers::LoadFrame(MainFrameImpl(), url.Utf8().data()); + frame_test_helpers::LoadFrame(MainFrameImpl(), url.Utf8().c_str()); MainFrameImpl()->GetFrame()->View()->UpdateAllLifecyclePhases( DocumentLifecycle::LifecycleUpdateReason::kTest); } @@ -181,7 +181,7 @@ const String& file_path, const String& mime_type = "image/png") { url_test_helpers::RegisterMockedURLLoad( - url, test::CoreTestDataPath(file_path.Utf8().data()), mime_type); + url, test::CoreTestDataPath(file_path.Utf8().c_str()), mime_type); } WebViewImpl* WebView() { return helper_.GetWebView(); }
diff --git a/third_party/blink/renderer/core/exported/web_frame_serializer_test.cc b/third_party/blink/renderer/core/exported/web_frame_serializer_test.cc index 74e129b..5acb60a 100644 --- a/third_party/blink/renderer/core/exported/web_frame_serializer_test.cc +++ b/third_party/blink/renderer/core/exported/web_frame_serializer_test.cc
@@ -77,7 +77,7 @@ void RegisterMockedImageURLLoad(const String& url) { // Image resources need to be mocked, but irrelevant here what image they // map to. - RegisterMockedFileURLLoad(url_test_helpers::ToKURL(url.Utf8().data()), + RegisterMockedFileURLLoad(url_test_helpers::ToKURL(url.Utf8().c_str()), "frameserialization/awesome.png"); } @@ -85,7 +85,7 @@ const String& file_path, const String& mime_type = "image/png") { url_test_helpers::RegisterMockedURLLoad( - url, test::CoreTestDataPath(file_path.Utf8().data()), mime_type); + url, test::CoreTestDataPath(file_path.Utf8().c_str()), mime_type); } class SingleLinkRewritingDelegate @@ -118,7 +118,7 @@ KURL parsed_url(url); String file_path("frameserialization/" + file_name); RegisterMockedFileURLLoad(parsed_url, file_path, "text/html"); - frame_test_helpers::LoadFrame(MainFrameImpl(), url.Utf8().data()); + frame_test_helpers::LoadFrame(MainFrameImpl(), url.Utf8().c_str()); SingleLinkRewritingDelegate delegate(parsed_url, WebString("local")); SimpleWebFrameSerializerClient serializer_client; WebFrameSerializer::Serialize(MainFrameImpl(), &serializer_client,
diff --git a/third_party/blink/renderer/core/exported/web_page_popup_impl.cc b/third_party/blink/renderer/core/exported/web_page_popup_impl.cc index cbded07..d32feb6b 100644 --- a/third_party/blink/renderer/core/exported/web_page_popup_impl.cc +++ b/third_party/blink/renderer/core/exported/web_page_popup_impl.cc
@@ -118,7 +118,7 @@ const String&) override { #ifndef NDEBUG fprintf(stderr, "CONSOLE MESSSAGE:%u: %s\n", line_number, - message.Utf8().data()); + message.Utf8().c_str()); #endif }
diff --git a/third_party/blink/renderer/core/exported/web_surrounding_text_test.cc b/third_party/blink/renderer/core/exported/web_surrounding_text_test.cc index 713231cf8..4a087bc0 100644 --- a/third_party/blink/renderer/core/exported/web_surrounding_text_test.cc +++ b/third_party/blink/renderer/core/exported/web_surrounding_text_test.cc
@@ -384,9 +384,8 @@ EphemeralRange selection = Select(0); WebSurroundingText surrounding_text(selection, 100); - EXPECT_STREQ( - "\xEF\xBF\xBC\n57th Street and Lake Shore Drive\nChicago IL 60637", - surrounding_text.TextContent().Utf8().data()); + EXPECT_EQ("\xEF\xBF\xBC\n57th Street and Lake Shore Drive\nChicago IL 60637", + surrounding_text.TextContent().Utf8()); EXPECT_EQ(43u, surrounding_text.StartOffsetInTextContent()); EXPECT_EQ(43u, surrounding_text.EndOffsetInTextContent()); }
diff --git a/third_party/blink/renderer/core/exported/web_view_impl.cc b/third_party/blink/renderer/core/exported/web_view_impl.cc index 50e55b2..91651c8 100644 --- a/third_party/blink/renderer/core/exported/web_view_impl.cc +++ b/third_party/blink/renderer/core/exported/web_view_impl.cc
@@ -2674,7 +2674,13 @@ void WebViewImpl::SetTextAutosizePageInfo( const WebTextAutosizerPageInfo& page_info) { + Frame* root_frame = GetPage()->MainFrame(); + DCHECK(root_frame->IsRemoteFrame()); + if (page_info == GetPage()->TextAutosizerPageInfo()) + return; + GetPage()->SetTextAutosizePageInfo(page_info); + TextAutosizer::UpdatePageInfoInAllFrames(root_frame); } void WebViewImpl::UpdateMainFrameLayoutSize() {
diff --git a/third_party/blink/renderer/core/exported/web_view_test.cc b/third_party/blink/renderer/core/exported/web_view_test.cc index e1e5b4a0..b46460cd 100644 --- a/third_party/blink/renderer/core/exported/web_view_test.cc +++ b/third_party/blink/renderer/core/exported/web_view_test.cc
@@ -1168,7 +1168,7 @@ WebRange(), 3, 3); WebTextInputInfo info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("hello", std::string(info.value.Utf8().data())); + EXPECT_EQ("hello", info.value.Utf8()); EXPECT_EQ(3, info.selection_start); EXPECT_EQ(3, info.selection_end); EXPECT_EQ(0, info.composition_start); @@ -1186,7 +1186,7 @@ WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans, WebRange(), 3, 3); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("helhellolo", std::string(info.value.Utf8().data())); + EXPECT_EQ("helhellolo", info.value.Utf8()); EXPECT_EQ(6, info.selection_start); EXPECT_EQ(6, info.selection_end); EXPECT_EQ(3, info.composition_start); @@ -1219,7 +1219,7 @@ WebRange(), -5); WebTextInputInfo info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("helloworld", std::string(info.value.Utf8().data())); + EXPECT_EQ("helloworld", info.value.Utf8()); EXPECT_EQ(5, info.selection_start); EXPECT_EQ(5, info.selection_end); EXPECT_EQ(-1, info.composition_start); @@ -1233,7 +1233,7 @@ WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans, WebRange(), 0, 0); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("helloABCworld", std::string(info.value.Utf8().data())); + EXPECT_EQ("helloABCworld", info.value.Utf8()); EXPECT_EQ(5, info.selection_start); EXPECT_EQ(5, info.selection_end); EXPECT_EQ(5, info.composition_start); @@ -1244,7 +1244,7 @@ WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans, WebRange(), 3, 3); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("helloABCworld", std::string(info.value.Utf8().data())); + EXPECT_EQ("helloABCworld", info.value.Utf8()); EXPECT_EQ(8, info.selection_start); EXPECT_EQ(8, info.selection_end); EXPECT_EQ(5, info.composition_start); @@ -1255,7 +1255,7 @@ WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans, WebRange(), -2, -2); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("helloABCworld", std::string(info.value.Utf8().data())); + EXPECT_EQ("helloABCworld", info.value.Utf8()); EXPECT_EQ(3, info.selection_start); EXPECT_EQ(3, info.selection_end); EXPECT_EQ(5, info.composition_start); @@ -1266,7 +1266,7 @@ WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans, WebRange(), 5, 5); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("helloABCworld", std::string(info.value.Utf8().data())); + EXPECT_EQ("helloABCworld", info.value.Utf8()); EXPECT_EQ(10, info.selection_start); EXPECT_EQ(10, info.selection_end); EXPECT_EQ(5, info.composition_start); @@ -1277,7 +1277,7 @@ WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans, WebRange(), -5, -5); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("helloABCworld", std::string(info.value.Utf8().data())); + EXPECT_EQ("helloABCworld", info.value.Utf8()); EXPECT_EQ(0, info.selection_start); EXPECT_EQ(0, info.selection_end); EXPECT_EQ(5, info.composition_start); @@ -1288,7 +1288,7 @@ WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans, WebRange(), 8, 8); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("helloABCworld", std::string(info.value.Utf8().data())); + EXPECT_EQ("helloABCworld", info.value.Utf8()); EXPECT_EQ(13, info.selection_start); EXPECT_EQ(13, info.selection_end); EXPECT_EQ(5, info.composition_start); @@ -1299,7 +1299,7 @@ WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans, WebRange(), -100, -100); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("helloABCworld", std::string(info.value.Utf8().data())); + EXPECT_EQ("helloABCworld", info.value.Utf8()); EXPECT_EQ(0, info.selection_start); EXPECT_EQ(0, info.selection_end); EXPECT_EQ(5, info.composition_start); @@ -1310,7 +1310,7 @@ WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans, WebRange(), 100, 100); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("helloABCworld", std::string(info.value.Utf8().data())); + EXPECT_EQ("helloABCworld", info.value.Utf8()); EXPECT_EQ(13, info.selection_start); EXPECT_EQ(13, info.selection_end); EXPECT_EQ(5, info.composition_start); @@ -1333,7 +1333,7 @@ WebRange(), 0); WebTextInputInfo info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("hello", std::string(info.value.Utf8().data())); + EXPECT_EQ("hello", info.value.Utf8()); EXPECT_EQ(5, info.selection_start); EXPECT_EQ(5, info.selection_end); EXPECT_EQ(-1, info.composition_start); @@ -1342,7 +1342,7 @@ active_input_method_controller->SetComposition( WebString::FromUTF8(""), empty_ime_text_spans, WebRange(), 0, 0); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("hello", std::string(info.value.Utf8().data())); + EXPECT_EQ("hello", info.value.Utf8()); EXPECT_EQ(5, info.selection_start); EXPECT_EQ(5, info.selection_end); EXPECT_EQ(-1, info.composition_start); @@ -1351,7 +1351,7 @@ active_input_method_controller->SetComposition( WebString::FromUTF8(""), empty_ime_text_spans, WebRange(), -2, -2); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("hello", std::string(info.value.Utf8().data())); + EXPECT_EQ("hello", info.value.Utf8()); EXPECT_EQ(3, info.selection_start); EXPECT_EQ(3, info.selection_end); EXPECT_EQ(-1, info.composition_start); @@ -1374,7 +1374,7 @@ active_input_method_controller->CommitText("ab", empty_ime_text_spans, WebRange(), -2); WebTextInputInfo info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("ab", std::string(info.value.Utf8().data())); + EXPECT_EQ("ab", info.value.Utf8()); EXPECT_EQ(0, info.selection_start); EXPECT_EQ(0, info.selection_end); EXPECT_EQ(-1, info.composition_start); @@ -1384,7 +1384,7 @@ active_input_method_controller->CommitText("c", empty_ime_text_spans, WebRange(), 1); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("cab", std::string(info.value.Utf8().data())); + EXPECT_EQ("cab", info.value.Utf8()); EXPECT_EQ(2, info.selection_start); EXPECT_EQ(2, info.selection_end); EXPECT_EQ(-1, info.composition_start); @@ -1394,7 +1394,7 @@ active_input_method_controller->CommitText("def", empty_ime_text_spans, WebRange(), -5); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("cadefb", std::string(info.value.Utf8().data())); + EXPECT_EQ("cadefb", info.value.Utf8()); EXPECT_EQ(0, info.selection_start); EXPECT_EQ(0, info.selection_end); EXPECT_EQ(-1, info.composition_start); @@ -1404,7 +1404,7 @@ active_input_method_controller->CommitText("g", empty_ime_text_spans, WebRange(), 6); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("gcadefb", std::string(info.value.Utf8().data())); + EXPECT_EQ("gcadefb", info.value.Utf8()); EXPECT_EQ(7, info.selection_start); EXPECT_EQ(7, info.selection_end); EXPECT_EQ(-1, info.composition_start); @@ -1414,7 +1414,7 @@ active_input_method_controller->CommitText("hi", empty_ime_text_spans, WebRange(), -100); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("gcadefbhi", std::string(info.value.Utf8().data())); + EXPECT_EQ("gcadefbhi", info.value.Utf8()); EXPECT_EQ(0, info.selection_start); EXPECT_EQ(0, info.selection_end); EXPECT_EQ(-1, info.composition_start); @@ -1424,7 +1424,7 @@ active_input_method_controller->CommitText("jk", empty_ime_text_spans, WebRange(), 100); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("jkgcadefbhi", std::string(info.value.Utf8().data())); + EXPECT_EQ("jkgcadefbhi", info.value.Utf8()); EXPECT_EQ(11, info.selection_start); EXPECT_EQ(11, info.selection_end); EXPECT_EQ(-1, info.composition_start); @@ -1445,7 +1445,7 @@ active_input_method_controller->SetComposition( WebString::FromUTF8("abc"), empty_ime_text_spans, WebRange(), 0, 0); WebTextInputInfo info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("abc", std::string(info.value.Utf8().data())); + EXPECT_EQ("abc", info.value.Utf8()); EXPECT_EQ(0, info.selection_start); EXPECT_EQ(0, info.selection_end); EXPECT_EQ(0, info.composition_start); @@ -1456,7 +1456,7 @@ active_input_method_controller->CommitText("hello", empty_ime_text_spans, WebRange(), -2); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("hello", std::string(info.value.Utf8().data())); + EXPECT_EQ("hello", info.value.Utf8()); EXPECT_EQ(3, info.selection_start); EXPECT_EQ(3, info.selection_end); EXPECT_EQ(-1, info.composition_start); @@ -1465,7 +1465,7 @@ active_input_method_controller->SetComposition( WebString::FromUTF8("abc"), empty_ime_text_spans, WebRange(), 0, 0); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("helabclo", std::string(info.value.Utf8().data())); + EXPECT_EQ("helabclo", info.value.Utf8()); EXPECT_EQ(3, info.selection_start); EXPECT_EQ(3, info.selection_end); EXPECT_EQ(3, info.composition_start); @@ -1475,7 +1475,7 @@ active_input_method_controller->CommitText("", empty_ime_text_spans, WebRange(), 2); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("hello", std::string(info.value.Utf8().data())); + EXPECT_EQ("hello", info.value.Utf8()); EXPECT_EQ(5, info.selection_start); EXPECT_EQ(5, info.selection_end); EXPECT_EQ(-1, info.composition_start); @@ -1485,7 +1485,7 @@ active_input_method_controller->CommitText("world", empty_ime_text_spans, WebRange(), -5); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("helloworld", std::string(info.value.Utf8().data())); + EXPECT_EQ("helloworld", info.value.Utf8()); EXPECT_EQ(5, info.selection_start); EXPECT_EQ(5, info.selection_end); EXPECT_EQ(-1, info.composition_start); @@ -1495,7 +1495,7 @@ active_input_method_controller->CommitText("", empty_ime_text_spans, WebRange(), 5); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("helloworld", std::string(info.value.Utf8().data())); + EXPECT_EQ("helloworld", info.value.Utf8()); EXPECT_EQ(10, info.selection_start); EXPECT_EQ(10, info.selection_end); EXPECT_EQ(-1, info.composition_start); @@ -1526,7 +1526,7 @@ EXPECT_LT(0, offset_height); WebTextInputInfo info = frame->GetInputMethodController()->TextInputInfo(); - EXPECT_EQ("hello", std::string(info.value.Utf8().data())); + EXPECT_EQ("hello", info.value.Utf8()); // Verify that the input field is not scrolled back into the viewport. frame->FrameWidget() @@ -1551,8 +1551,7 @@ frame->SetCompositionFromExistingText(8, 12, empty_ime_text_spans); WebTextInputInfo info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("0123456789abcdefghijklmnopqrstuvwxyz", - std::string(info.value.Utf8().data())); + EXPECT_EQ("0123456789abcdefghijklmnopqrstuvwxyz", info.value.Utf8()); EXPECT_EQ(4, info.selection_start); EXPECT_EQ(4, info.selection_end); EXPECT_EQ(8, info.composition_start); @@ -1575,8 +1574,7 @@ EXPECT_EQ(5, info.selection_end); EXPECT_EQ(-1, info.composition_start); EXPECT_EQ(-1, info.composition_end); - EXPECT_EQ("0123\n456789abcdefghijklmnopqrstuvwxyz", - std::string(info.value.Utf8().data())); + EXPECT_EQ("0123\n456789abcdefghijklmnopqrstuvwxyz", info.value.Utf8()); } TEST_F(WebViewTest, ExtendSelectionAndDelete) { @@ -1590,12 +1588,12 @@ WebInputMethodController* active_input_method_controller = frame->GetInputMethodController(); WebTextInputInfo info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("01234ijklmnopqrstuvwxyz", std::string(info.value.Utf8().data())); + EXPECT_EQ("01234ijklmnopqrstuvwxyz", info.value.Utf8()); EXPECT_EQ(5, info.selection_start); EXPECT_EQ(5, info.selection_end); frame->ExtendSelectionAndDelete(10, 0); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("ijklmnopqrstuvwxyz", std::string(info.value.Utf8().data())); + EXPECT_EQ("ijklmnopqrstuvwxyz", info.value.Utf8()); } TEST_F(WebViewTest, DeleteSurroundingText) { @@ -1610,33 +1608,33 @@ frame->SetEditableSelectionOffsets(10, 10); frame->DeleteSurroundingText(5, 8); WebTextInputInfo info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("01234ijklmnopqrstuvwxyz", std::string(info.value.Utf8().data())); + EXPECT_EQ("01234ijklmnopqrstuvwxyz", info.value.Utf8()); EXPECT_EQ(5, info.selection_start); EXPECT_EQ(5, info.selection_end); frame->SetEditableSelectionOffsets(5, 10); frame->DeleteSurroundingText(3, 5); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("01ijklmstuvwxyz", std::string(info.value.Utf8().data())); + EXPECT_EQ("01ijklmstuvwxyz", info.value.Utf8()); EXPECT_EQ(2, info.selection_start); EXPECT_EQ(7, info.selection_end); frame->SetEditableSelectionOffsets(5, 5); frame->DeleteSurroundingText(10, 0); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("lmstuvwxyz", std::string(info.value.Utf8().data())); + EXPECT_EQ("lmstuvwxyz", info.value.Utf8()); EXPECT_EQ(0, info.selection_start); EXPECT_EQ(0, info.selection_end); frame->DeleteSurroundingText(0, 20); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("", std::string(info.value.Utf8().data())); + EXPECT_EQ("", info.value.Utf8()); EXPECT_EQ(0, info.selection_start); EXPECT_EQ(0, info.selection_end); frame->DeleteSurroundingText(10, 10); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("", std::string(info.value.Utf8().data())); + EXPECT_EQ("", info.value.Utf8()); EXPECT_EQ(0, info.selection_start); EXPECT_EQ(0, info.selection_end); } @@ -1686,14 +1684,12 @@ WebString::FromUTF8(new_line_text.c_str()), empty_ime_text_spans, WebRange(), 0); WebTextInputInfo info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("0123456789abcdefghijklmnopq\nrstuvwxyz", - std::string(info.value.Utf8().data())); + EXPECT_EQ("0123456789abcdefghijklmnopq\nrstuvwxyz", info.value.Utf8()); frame->SetEditableSelectionOffsets(31, 31); frame->SetCompositionFromExistingText(30, 34, ime_text_spans); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("0123456789abcdefghijklmnopq\nrstuvwxyz", - std::string(info.value.Utf8().data())); + EXPECT_EQ("0123456789abcdefghijklmnopq\nrstuvwxyz", info.value.Utf8()); EXPECT_EQ(31, info.selection_start); EXPECT_EQ(31, info.selection_end); EXPECT_EQ(30, info.composition_start); @@ -1704,8 +1700,7 @@ WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans, WebRange(), 0); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("0123456789abcdefghijklmnopq\nrsyoloxyz", - std::string(info.value.Utf8().data())); + EXPECT_EQ("0123456789abcdefghijklmnopq\nrsyoloxyz", info.value.Utf8()); EXPECT_EQ(34, info.selection_start); EXPECT_EQ(34, info.selection_end); EXPECT_EQ(-1, info.composition_start); @@ -1749,7 +1744,7 @@ empty_ime_text_spans, WebRange(), 5, 5); WebTextInputInfo info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("hello world", std::string(info.value.Utf8().data())); + EXPECT_EQ("hello world", info.value.Utf8()); EXPECT_EQ(11, info.selection_start); EXPECT_EQ(11, info.selection_end); EXPECT_EQ(6, info.composition_start); @@ -1758,7 +1753,7 @@ WebLocalFrameImpl* frame = web_view->MainFrameImpl(); frame->SetEditableSelectionOffsets(6, 6); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("hello world", std::string(info.value.Utf8().data())); + EXPECT_EQ("hello world", info.value.Utf8()); EXPECT_EQ(6, info.selection_start); EXPECT_EQ(6, info.selection_end); EXPECT_EQ(6, info.composition_start); @@ -1766,7 +1761,7 @@ frame->SetEditableSelectionOffsets(8, 8); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("hello world", std::string(info.value.Utf8().data())); + EXPECT_EQ("hello world", info.value.Utf8()); EXPECT_EQ(8, info.selection_start); EXPECT_EQ(8, info.selection_end); EXPECT_EQ(6, info.composition_start); @@ -1774,7 +1769,7 @@ frame->SetEditableSelectionOffsets(11, 11); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("hello world", std::string(info.value.Utf8().data())); + EXPECT_EQ("hello world", info.value.Utf8()); EXPECT_EQ(11, info.selection_start); EXPECT_EQ(11, info.selection_end); EXPECT_EQ(6, info.composition_start); @@ -1782,7 +1777,7 @@ frame->SetEditableSelectionOffsets(6, 11); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("hello world", std::string(info.value.Utf8().data())); + EXPECT_EQ("hello world", info.value.Utf8()); EXPECT_EQ(6, info.selection_start); EXPECT_EQ(11, info.selection_end); EXPECT_EQ(6, info.composition_start); @@ -1790,7 +1785,7 @@ frame->SetEditableSelectionOffsets(2, 2); info = active_input_method_controller->TextInputInfo(); - EXPECT_EQ("hello world", std::string(info.value.Utf8().data())); + EXPECT_EQ("hello world", info.value.Utf8()); EXPECT_EQ(2, info.selection_start); EXPECT_EQ(2, info.selection_end); // Composition range should be reset by browser process or keyboard apps. @@ -2944,9 +2939,9 @@ EXPECT_TRUE( TapElementById(WebInputEvent::kGestureLongPress, onselectstartfalse)); - EXPECT_EQ("", std::string(frame->SelectionAsText().Utf8().data())); + EXPECT_EQ("", frame->SelectionAsText().Utf8()); EXPECT_TRUE(TapElementById(WebInputEvent::kGestureLongPress, target)); - EXPECT_EQ("testword", std::string(frame->SelectionAsText().Utf8().data())); + EXPECT_EQ("testword", frame->SelectionAsText().Utf8()); } TEST_F(WebViewTest, FinishComposingTextDoesNotDismissHandles) { @@ -2968,13 +2963,12 @@ EXPECT_TRUE(active_input_method_controller->SetComposition( "12345", empty_ime_text_spans, WebRange(), 8, 13)); EXPECT_TRUE(frame->GetFrame()->GetInputMethodController().HasComposition()); - EXPECT_EQ("", std::string(frame->SelectionAsText().Utf8().data())); + EXPECT_EQ("", frame->SelectionAsText().Utf8()); EXPECT_FALSE(frame->GetFrame()->Selection().IsHandleVisible()); EXPECT_TRUE(frame->GetFrame()->GetInputMethodController().HasComposition()); EXPECT_TRUE(TapElementById(WebInputEvent::kGestureLongPress, target)); - EXPECT_EQ("testword12345", - std::string(frame->SelectionAsText().Utf8().data())); + EXPECT_EQ("testword12345", frame->SelectionAsText().Utf8()); EXPECT_TRUE(frame->GetFrame()->Selection().IsHandleVisible()); EXPECT_TRUE(frame->GetFrame()->GetInputMethodController().HasComposition()); @@ -3111,7 +3105,7 @@ std::string test_word = "This text should be selected."; WebLocalFrameImpl* frame = web_view->MainFrameImpl(); - EXPECT_EQ(test_word, std::string(frame->SelectionAsText().Utf8().data())); + EXPECT_EQ(test_word, frame->SelectionAsText().Utf8()); WebRange range = web_view->MainFrameImpl() ->GetInputMethodController() @@ -3533,8 +3527,7 @@ frame->SetCompositionFromExistingText(8, 12, empty_ime_text_spans); WebTextInputInfo info = frame->GetInputMethodController()->TextInputInfo(); - EXPECT_EQ("0123456789abcdefghijklmnopqrstuvwxyz", - std::string(info.value.Utf8().data())); + EXPECT_EQ("0123456789abcdefghijklmnopqrstuvwxyz", info.value.Utf8()); EXPECT_EQ(8, info.composition_start); EXPECT_EQ(12, info.composition_end);
diff --git a/third_party/blink/renderer/core/exported/worker_shadow_page.cc b/third_party/blink/renderer/core/exported/worker_shadow_page.cc index 1f2993c..3e31eb2 100644 --- a/third_party/blink/renderer/core/exported/worker_shadow_page.cc +++ b/third_party/blink/renderer/core/exported/worker_shadow_page.cc
@@ -64,10 +64,10 @@ // Construct substitute data source. We only need it to have same origin as // the worker so the loading checks work correctly. - CString content(""); + std::string content(""); main_frame_->GetFrame()->Loader().CommitNavigation( WebNavigationParams::CreateWithHTMLBuffer( - SharedBuffer::Create(content.data(), content.length()), script_url), + SharedBuffer::Create(content.c_str(), content.length()), script_url), nullptr /* extra_data */); }
diff --git a/third_party/blink/renderer/core/feature_policy/layout_animations_policy.cc b/third_party/blink/renderer/core/feature_policy/layout_animations_policy.cc index 3b08064..53c870b 100644 --- a/third_party/blink/renderer/core/feature_policy/layout_animations_policy.cc +++ b/third_party/blink/renderer/core/feature_policy/layout_animations_policy.cc
@@ -15,10 +15,10 @@ return String::Format( "Feature policy violation: CSS property '%s' violates feature policy " "'%s' which is disabled in this document", - property.GetPropertyNameString().Utf8().data(), + property.GetPropertyNameString().Utf8().c_str(), GetNameForFeature(mojom::FeaturePolicyFeature::kLayoutAnimations) .Utf8() - .data()); + .c_str()); } } // namespace
diff --git a/third_party/blink/renderer/core/fetch/body_stream_buffer_test.cc b/third_party/blink/renderer/core/fetch/body_stream_buffer_test.cc index ca286e1f..4c795238 100644 --- a/third_party/blink/renderer/core/fetch/body_stream_buffer_test.cc +++ b/third_party/blink/renderer/core/fetch/body_stream_buffer_test.cc
@@ -68,8 +68,7 @@ ADD_FAILURE() << ToCoreString(block.Exception() ->ToString(script_state->GetContext()) .ToLocalChecked()) - .Utf8() - .data(); + .Utf8(); block.ReThrow(); } return r;
diff --git a/third_party/blink/renderer/core/fetch/fetch_data_loader.cc b/third_party/blink/renderer/core/fetch/fetch_data_loader.cc index 3bcde6d..6a04dd97 100644 --- a/third_party/blink/renderer/core/fetch/fetch_data_loader.cc +++ b/third_party/blink/renderer/core/fetch/fetch_data_loader.cc
@@ -21,6 +21,7 @@ #include "third_party/blink/renderer/platform/wtf/functional.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" #include "third_party/blink/renderer/platform/wtf/text/string_builder.h" +#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink { @@ -333,10 +334,11 @@ DCHECK(!form_data_); DCHECK(!multipart_parser_); - const CString multipart_boundary_utf8 = multipart_boundary_.Utf8(); + StringUTF8Adaptor multipart_boundary_utf8(multipart_boundary_); Vector<char> multipart_boundary_vector; - multipart_boundary_vector.Append(multipart_boundary_utf8.data(), - multipart_boundary_utf8.length()); + multipart_boundary_vector.Append( + multipart_boundary_utf8.data(), + multipart_boundary_utf8.size()); client_ = client; form_data_ = MakeGarbageCollected<FormData>();
diff --git a/third_party/blink/renderer/core/fetch/testing/worker_internals_fetch.cc b/third_party/blink/renderer/core/fetch/testing/worker_internals_fetch.cc index d1e38a9..9f0007b 100644 --- a/third_party/blink/renderer/core/fetch/testing/worker_internals_fetch.cc +++ b/third_party/blink/renderer/core/fetch/testing/worker_internals_fetch.cc
@@ -34,7 +34,7 @@ ScriptPromiseResolver* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); ScriptPromise promise = resolver->Promise(); - KURL resource_url = url_test_helpers::ToKURL(url.Utf8().data()); + KURL resource_url = url_test_helpers::ToKURL(url.Utf8()); DCHECK(worker_global); auto callback = WTF::Bind(&WorkerInternalsFetch::ResolveResourcePriority,
diff --git a/third_party/blink/renderer/core/fileapi/file_reader.cc b/third_party/blink/renderer/core/fileapi/file_reader.cc index 3d7893f..597edc7a 100644 --- a/third_party/blink/renderer/core/fileapi/file_reader.cc +++ b/third_party/blink/renderer/core/fileapi/file_reader.cc
@@ -52,11 +52,11 @@ namespace { -const CString Utf8BlobUUID(Blob* blob) { +const std::string Utf8BlobUUID(Blob* blob) { return blob->Uuid().Utf8(); } -const CString Utf8FilePath(Blob* blob) { +const std::string Utf8FilePath(Blob* blob) { return blob->HasBackingFile() ? To<File>(blob)->GetPath().Utf8() : ""; }
diff --git a/third_party/blink/renderer/core/frame/csp/csp_directive_list.cc b/third_party/blink/renderer/core/frame/csp/csp_directive_list.cc index 26b99c8..9e40791 100644 --- a/third_party/blink/renderer/core/frame/csp/csp_directive_list.cc +++ b/third_party/blink/renderer/core/frame/csp/csp_directive_list.cc
@@ -859,8 +859,8 @@ "Refused to create a TrustedTypePolicy named '%s' because " "it violates the following Content Security Policy directive: " "\"%s\".", - policy_name.Utf8().data(), - trusted_types_.Get()->GetText().Utf8().data()), + policy_name.Utf8().c_str(), + trusted_types_.Get()->GetText().Utf8().c_str()), KURL(), RedirectStatus::kNoRedirect); return DenyIfEnforcingPolicy();
diff --git a/third_party/blink/renderer/core/frame/frame.cc b/third_party/blink/renderer/core/frame/frame.cc index 2260fc9..1e9b9e4 100644 --- a/third_party/blink/renderer/core/frame/frame.cc +++ b/third_party/blink/renderer/core/frame/frame.cc
@@ -261,10 +261,10 @@ } } -const CString& Frame::ToTraceValue() { +const std::string& Frame::ToTraceValue() { // token's ToString() is latin1. if (!trace_value_) - trace_value_ = CString(devtools_frame_token_.ToString().c_str()); + trace_value_ = devtools_frame_token_.ToString(); return trace_value_.value(); }
diff --git a/third_party/blink/renderer/core/frame/frame.h b/third_party/blink/renderer/core/frame/frame.h index b404b59c..8fc80a8 100644 --- a/third_party/blink/renderer/core/frame/frame.h +++ b/third_party/blink/renderer/core/frame/frame.h
@@ -206,7 +206,7 @@ const base::UnguessableToken& GetDevToolsFrameToken() const { return devtools_frame_token_; } - const CString& ToTraceValue(); + const std::string& ToTraceValue(); // TODO(dcheng): temporary for debugging https://crbug.com/838348. const base::debug::StackTrace& CreateStackForDebugging() { @@ -304,7 +304,7 @@ // TODO(sashab): Investigate if this can be represented with m_lifecycle. bool is_loading_; base::UnguessableToken devtools_frame_token_; - base::Optional<CString> trace_value_; + base::Optional<std::string> trace_value_; base::debug::StackTrace create_stack_; base::debug::StackTrace detach_stack_; @@ -330,8 +330,8 @@ // in a TRACE_EVENT_XXX macro. Example: // // TRACE_EVENT1("category", "event_name", "frame", ToTraceValue(GetFrame())); -static inline CString ToTraceValue(Frame* frame) { - return frame ? frame->ToTraceValue() : CString(); +static inline std::string ToTraceValue(Frame* frame) { + return frame ? frame->ToTraceValue() : std::string(); } } // namespace blink
diff --git a/third_party/blink/renderer/core/frame/frame_serializer.cc b/third_party/blink/renderer/core/frame/frame_serializer.cc index e29d000..fb7a716 100644 --- a/third_party/blink/renderer/core/frame/frame_serializer.cc +++ b/third_party/blink/renderer/core/frame/frame_serializer.cc
@@ -279,11 +279,11 @@ String text = accumulator.SerializeNodes<EditingStrategy>(document, kIncludeNode); - CString frame_html = + std::string frame_html = document.Encoding().Encode(text, WTF::kEntitiesForUnencodables); resources_->push_back(SerializedResource( url, document.SuggestedMIMEType(), - SharedBuffer::Create(frame_html.data(), frame_html.length()))); + SharedBuffer::Create(frame_html.c_str(), frame_html.length()))); } should_collect_problem_metric_ = @@ -401,11 +401,11 @@ WTF::TextEncoding text_encoding(style_sheet.Contents()->Charset()); DCHECK(text_encoding.IsValid()); String text_string = css_text.ToString(); - CString text = text_encoding.Encode( + std::string text = text_encoding.Encode( text_string, WTF::kCSSEncodedEntitiesForUnencodables); resources_->push_back( SerializedResource(url, String("text/css"), - SharedBuffer::Create(text.data(), text.length()))); + SharedBuffer::Create(text.c_str(), text.length()))); } // Sub resources need to be serialized even if the CSS definition doesn't
diff --git a/third_party/blink/renderer/core/frame/frame_serializer_test.cc b/third_party/blink/renderer/core/frame/frame_serializer_test.cc index 922200b..c8728b4a 100644 --- a/third_party/blink/renderer/core/frame/frame_serializer_test.cc +++ b/third_party/blink/renderer/core/frame/frame_serializer_test.cc
@@ -114,7 +114,7 @@ void Serialize(const char* url) { frame_test_helpers::LoadFrame( helper_.GetWebView()->MainFrameImpl(), - KURL(base_url_, url).GetString().Utf8().data()); + KURL(base_url_, url).GetString().Utf8().c_str()); // Sometimes we have iframes created in "onload" handler - wait for them to // load. frame_test_helpers::PumpPendingRequestsForFrameToLoad(
diff --git a/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.cc b/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.cc index 6e039e9..6b9c43b0 100644 --- a/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.cc +++ b/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.cc
@@ -93,7 +93,7 @@ uma_name.Append(uma_postscript); if (metric_data.has_uma) { absolute_record.uma_counter.reset(new CustomCountHistogram( - uma_name.ToString().Utf8().data(), 0, 10000000, 50)); + uma_name.ToString().Utf8().c_str(), 0, 10000000, 50)); } // Percentage records report the ratio of each metric to the primary metric, @@ -109,7 +109,7 @@ uma_percentage_name.Append(bucket_substring); percentage_record.uma_counters_per_bucket.push_back( std::make_unique<CustomCountHistogram>( - uma_percentage_name.ToString().Utf8().data(), 0, 10000000, 50)); + uma_percentage_name.ToString().Utf8().c_str(), 0, 10000000, 50)); } } }
diff --git a/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator_test.cc b/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator_test.cc index 1693053..f4826968 100644 --- a/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator_test.cc +++ b/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator_test.cc
@@ -36,19 +36,15 @@ void ResetAggregator() { aggregator_.reset(); } std::string GetPrimaryMetricName() { - return std::string( - LocalFrameUkmAggregator::primary_metric_name().Utf8().data()); + return LocalFrameUkmAggregator::primary_metric_name().Utf8(); } std::string GetMetricName(int index) { - return std::string( - LocalFrameUkmAggregator::metrics_data()[index].name.Utf8().data()); + return LocalFrameUkmAggregator::metrics_data()[index].name.Utf8(); } std::string GetPercentageMetricName(int index) { - return std::string(LocalFrameUkmAggregator::metrics_data()[index] - .name.Utf8() - .data()) + + return LocalFrameUkmAggregator::metrics_data()[index].name.Utf8() + "Percentage"; }
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 fb158280..e42a041a9 100644 --- a/third_party/blink/renderer/core/frame/local_frame_view.cc +++ b/third_party/blink/renderer/core/frame/local_frame_view.cc
@@ -856,7 +856,7 @@ if (frame_->IsMainFrame()) { if (auto* text_autosizer = frame_->GetDocument()->GetTextAutosizer()) { if (text_autosizer->HasLayoutInlineSizeChanged()) - text_autosizer->UpdatePageInfoInAllFrames(); + text_autosizer->UpdatePageInfoInAllFrames(frame_); } } @@ -2065,6 +2065,7 @@ } void LocalFrameView::NotifyResizeObservers() { + TRACE_EVENT0("blink,benchmark", "LocalFrameView::NotifyResizeObservers"); // Controller exists only if ResizeObserver was created. if (!GetFrame().GetDocument()->GetResizeObserverController()) return; @@ -3510,11 +3511,8 @@ return; layout_size_ = size; - if (frame_->IsMainFrame() && frame_->GetDocument()) { - if (TextAutosizer* text_autosizer = - frame_->GetDocument()->GetTextAutosizer()) - text_autosizer->UpdatePageInfoInAllFrames(); - } + if (frame_->IsMainFrame() && frame_->GetDocument()) + TextAutosizer::UpdatePageInfoInAllFrames(frame_); SetNeedsLayout(); }
diff --git a/third_party/blink/renderer/core/frame/performance_monitor.cc b/third_party/blink/renderer/core/frame/performance_monitor.cc index 383568d..938bad3 100644 --- a/third_party/blink/renderer/core/frame/performance_monitor.cc +++ b/third_party/blink/renderer/core/frame/performance_monitor.cc
@@ -239,7 +239,7 @@ String name = user_callback->name ? String(user_callback->name) : String(user_callback->atomic_name); String text = String::Format("'%s' handler took %" PRId64 "ms", - name.Utf8().data(), duration.InMilliseconds()); + name.Utf8().c_str(), duration.InMilliseconds()); InnerReportGenericViolation(probe.context, handler_type, text, duration, SourceLocation::FromFunction(probe.function)); } @@ -267,7 +267,7 @@ auto sub_task_attribution = std::make_unique<SubTaskAttribution>( AtomicString("script-compile"), - String::Format("%s(%d, %d)", probe.file_name.Utf8().data(), probe.line, + String::Format("%s(%d, %d)", probe.file_name.Utf8().c_str(), probe.line, probe.column), v8_compile_start_time_, v8_compile_duration); sub_task_attributions_.push_back(std::move(sub_task_attribution));
diff --git a/third_party/blink/renderer/core/frame/web_frame_serializer_impl.cc b/third_party/blink/renderer/core/frame/web_frame_serializer_impl.cc index d7a974d..529c941 100644 --- a/third_party/blink/renderer/core/frame/web_frame_serializer_impl.cc +++ b/third_party/blink/renderer/core/frame/web_frame_serializer_impl.cc
@@ -277,12 +277,12 @@ String content = data_buffer_.ToString(); data_buffer_.Clear(); - CString encoded_content = + std::string encoded_content = param->text_encoding.Encode(content, WTF::kEntitiesForUnencodables); // Send result to the client. client_->DidSerializeDataForFrame( - WebVector<char>(encoded_content.data(), encoded_content.length()), + WebVector<char>(encoded_content.c_str(), encoded_content.length()), status); }
diff --git a/third_party/blink/renderer/core/frame/web_local_frame_impl.cc b/third_party/blink/renderer/core/frame/web_local_frame_impl.cc index 3b7e586..6813dcb 100644 --- a/third_party/blink/renderer/core/frame/web_local_frame_impl.cc +++ b/third_party/blink/renderer/core/frame/web_local_frame_impl.cc
@@ -1561,7 +1561,7 @@ WebString WebLocalFrameImpl::PageProperty(const WebString& property_name, int page_index) { DCHECK(print_context_); - return print_context_->PageProperty(GetFrame(), property_name.Utf8().data(), + return print_context_->PageProperty(GetFrame(), property_name.Utf8().c_str(), page_index); }
diff --git a/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_import_step.cc b/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_import_step.cc index 43450d1..f4025118 100644 --- a/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_import_step.cc +++ b/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_import_step.cc
@@ -80,7 +80,7 @@ void V0CustomElementMicrotaskImportStep::Show(unsigned indent) { fprintf(stderr, "%*sImport(wait=%d sync=%d, url=%s)\n", indent, "", ShouldWaitForImport(), import_ && import_->IsSync(), - import_ ? import_->Url().GetString().Utf8().data() : "null"); + import_ ? import_->Url().GetString().Utf8().c_str() : "null"); queue_->Show(indent + 1); } #endif
diff --git a/third_party/blink/renderer/core/html/forms/external_popup_menu_test.cc b/third_party/blink/renderer/core/html/forms/external_popup_menu_test.cc index de158f5..b1fda914 100644 --- a/third_party/blink/renderer/core/html/forms/external_popup_menu_test.cc +++ b/third_party/blink/renderer/core/html/forms/external_popup_menu_test.cc
@@ -182,7 +182,7 @@ static_cast<ExternalPopupMenu*>(select->Popup()); client->DidAcceptIndex(2); EXPECT_FALSE(select->PopupIsVisible()); - ASSERT_STREQ("2", menu_list->GetText().Utf8().data()); + ASSERT_EQ("2", menu_list->GetText().Utf8()); EXPECT_EQ(2, select->selectedIndex()); }
diff --git a/third_party/blink/renderer/core/html/forms/form_data.cc b/third_party/blink/renderer/core/html/forms/form_data.cc index 550a6d1..f550517e 100644 --- a/third_party/blink/renderer/core/html/forms/form_data.cc +++ b/third_party/blink/renderer/core/html/forms/form_data.cc
@@ -226,7 +226,7 @@ MakeGarbageCollected<Entry>(Normalize(name), Normalize(value))); } -CString FormData::Encode(const String& string) const { +std::string FormData::Encode(const String& string) const { return encoding_.Encode(string, WTF::kEntitiesForUnencodables); } @@ -307,8 +307,8 @@ entry->GetBlob()->GetBlobDataHandle()); } } else { - CString encoded_value = Encode(entry->Value()); - form_data->AppendData(encoded_value.data(), encoded_value.length()); + std::string encoded_value = Encode(entry->Value()); + form_data->AppendData(encoded_value.c_str(), encoded_value.length()); } form_data->AppendData("\r\n", 2); }
diff --git a/third_party/blink/renderer/core/html/forms/form_data.h b/third_party/blink/renderer/core/html/forms/form_data.h index 48670d9..5e9eb52 100644 --- a/third_party/blink/renderer/core/html/forms/form_data.h +++ b/third_party/blink/renderer/core/html/forms/form_data.h
@@ -84,7 +84,7 @@ // Internal functions. const WTF::TextEncoding& Encoding() const { return encoding_; } - CString Encode(const String& key) const; + std::string Encode(const String& key) const; class Entry; const HeapVector<Member<const Entry>>& Entries() const { return entries_; } size_t size() const { return entries_.size(); }
diff --git a/third_party/blink/renderer/core/html/forms/input_type.cc b/third_party/blink/renderer/core/html/forms/input_type.cc index b684227..ec9b2091 100644 --- a/third_party/blink/renderer/core/html/forms/input_type.cc +++ b/third_party/blink/renderer/core/html/forms/input_type.cc
@@ -972,7 +972,7 @@ mojom::ConsoleMessageSource::kRendering, mojom::ConsoleMessageLevel::kWarning, String::Format(message_format, - JSONValue::QuoteString(value).Utf8().data()))); + JSONValue::QuoteString(value).Utf8().c_str()))); } } // namespace blink
diff --git a/third_party/blink/renderer/core/html/html_iframe_element.cc b/third_party/blink/renderer/core/html/html_iframe_element.cc index 5feb7292..8167726 100644 --- a/third_party/blink/renderer/core/html/html_iframe_element.cc +++ b/third_party/blink/renderer/core/html/html_iframe_element.cc
@@ -300,7 +300,7 @@ messages->push_back(String::Format( "Allow and Sandbox attributes both mention '%s'. Allow will take " "precedence.", - GetNameForFeature(pair.second).Utf8().data())); + GetNameForFeature(pair.second).Utf8().c_str())); } } }
diff --git a/third_party/blink/renderer/core/html/link_rel_attribute_test.cc b/third_party/blink/renderer/core/html/link_rel_attribute_test.cc index a62fca0..4ed754fd 100644 --- a/third_party/blink/renderer/core/html/link_rel_attribute_test.cc +++ b/third_party/blink/renderer/core/html/link_rel_attribute_test.cc
@@ -45,7 +45,7 @@ bool is_import = false, bool is_preconnect = false, bool is_canonical = false) { - SCOPED_TRACE(value.Utf8().data()); + SCOPED_TRACE(value.Utf8()); LinkRelAttribute link_rel_attribute(value); ASSERT_EQ(is_style_sheet, link_rel_attribute.IsStyleSheet()); ASSERT_EQ(icon_type, link_rel_attribute.GetIconType());
diff --git a/third_party/blink/renderer/core/html/media/html_audio_element.idl b/third_party/blink/renderer/core/html/media/html_audio_element.idl index f2eb3fa..698f97b6 100644 --- a/third_party/blink/renderer/core/html/media/html_audio_element.idl +++ b/third_party/blink/renderer/core/html/media/html_audio_element.idl
@@ -26,6 +26,7 @@ // https://html.spec.whatwg.org/C/#the-audio-element [ + Exposed=Window, HTMLConstructor, NamedConstructor=Audio(optional DOMString src), ConstructorCallWith=Document
diff --git a/third_party/blink/renderer/core/html/media/html_media_element.cc b/third_party/blink/renderer/core/html/media/html_media_element.cc index e5b795a4..19ae6fa 100644 --- a/third_party/blink/renderer/core/html/media/html_media_element.cc +++ b/third_party/blink/renderer/core/html/media/html_media_element.cc
@@ -385,7 +385,7 @@ base::debug::AllocateCrashKeyString("media_content_type", base::debug::CrashKeySize::Size256); base::debug::ScopedCrashKeyString scoped_crash_key( - content_type_crash_key, content_type.Raw().Utf8().data()); + content_type_crash_key, content_type.Raw().Utf8().c_str()); String type = content_type.GetType().DeprecatedLower(); // The codecs string is not lower-cased because MP4 values are case sensitive
diff --git a/third_party/blink/renderer/core/html/media/media_error.idl b/third_party/blink/renderer/core/html/media/media_error.idl index fbf1a23..7bdfc0b 100644 --- a/third_party/blink/renderer/core/html/media/media_error.idl +++ b/third_party/blink/renderer/core/html/media/media_error.idl
@@ -25,6 +25,7 @@ // https://html.spec.whatwg.org/C/#error-codes +[Exposed=Window] interface MediaError { const unsigned short MEDIA_ERR_ABORTED = 1; const unsigned short MEDIA_ERR_NETWORK = 2;
diff --git a/third_party/blink/renderer/core/html/media/media_fragment_uri_parser.cc b/third_party/blink/renderer/core/html/media/media_fragment_uri_parser.cc index 1bdbeef..efb81e3 100644 --- a/third_party/blink/renderer/core/html/media/media_fragment_uri_parser.cc +++ b/third_party/blink/renderer/core/html/media/media_fragment_uri_parser.cc
@@ -128,15 +128,15 @@ // UTF-8. If either name or value are not valid UTF-8 strings, then // remove the name-value pair from the list. bool valid_utf8 = true; - CString utf8_name; + std::string utf8_name; if (!name.IsEmpty()) { utf8_name = name.Utf8(kStrictUTF8Conversion); - valid_utf8 = !utf8_name.IsNull(); + valid_utf8 = !utf8_name.empty(); } - CString utf8_value; + std::string utf8_value; if (valid_utf8 && !value.IsEmpty()) { utf8_value = value.Utf8(kStrictUTF8Conversion); - valid_utf8 = !utf8_value.IsNull(); + valid_utf8 = !utf8_value.empty(); } if (valid_utf8)
diff --git a/third_party/blink/renderer/core/html/media/media_fragment_uri_parser.h b/third_party/blink/renderer/core/html/media/media_fragment_uri_parser.h index 7956260..bf245513 100644 --- a/third_party/blink/renderer/core/html/media/media_fragment_uri_parser.h +++ b/third_party/blink/renderer/core/html/media/media_fragment_uri_parser.h
@@ -68,7 +68,7 @@ TimeFormat time_format_; double start_time_; double end_time_; - Vector<std::pair<CString, CString>> fragments_; + Vector<std::pair<std::string, std::string>> fragments_; }; } // namespace blink
diff --git a/third_party/blink/renderer/core/html/parser/atomic_html_token.cc b/third_party/blink/renderer/core/html/parser/atomic_html_token.cc index 419fbf3f..8adbeba 100644 --- a/third_party/blink/renderer/core/html/parser/atomic_html_token.cc +++ b/third_party/blink/renderer/core/html/parser/atomic_html_token.cc
@@ -47,11 +47,11 @@ printf(" selfclosing"); FALLTHROUGH; case HTMLToken::DOCTYPE: - printf(" name \"%s\"", name_.GetString().Utf8().data()); + printf(" name \"%s\"", name_.GetString().Utf8().c_str()); break; case HTMLToken::kComment: case HTMLToken::kCharacter: - printf(" data \"%s\"", data_.Utf8().data()); + printf(" data \"%s\"", data_.Utf8().c_str()); break; default: break;
diff --git a/third_party/blink/renderer/core/html/parser/xss_auditor_delegate.cc b/third_party/blink/renderer/core/html/parser/xss_auditor_delegate.cc index 7cb79f5..dcd28b8 100644 --- a/third_party/blink/renderer/core/html/parser/xss_auditor_delegate.cc +++ b/third_party/blink/renderer/core/html/parser/xss_auditor_delegate.cc
@@ -38,6 +38,7 @@ #include "third_party/blink/renderer/platform/network/encoded_form_data.h" #include "third_party/blink/renderer/platform/weborigin/security_origin.h" #include "third_party/blink/renderer/platform/wtf/text/string_builder.h" +#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h" namespace blink { @@ -94,7 +95,8 @@ auto report_object = std::make_unique<JSONObject>(); report_object->SetObject("xss-report", std::move(report_details)); - return EncodedFormData::Create(report_object->ToJSONString().Utf8().data()); + return EncodedFormData::Create( + StringUTF8Adaptor(report_object->ToJSONString())); } void XSSAuditorDelegate::DidBlockScript(const XSSInfo& xss_info) {
diff --git a/third_party/blink/renderer/core/html/track/vtt/vtt_cue.cc b/third_party/blink/renderer/core/html/track/vtt/vtt_cue.cc index d21f5a2a..f3140d13 100644 --- a/third_party/blink/renderer/core/html/track/vtt/vtt_cue.cc +++ b/third_party/blink/renderer/core/html/track/vtt/vtt_cue.cc
@@ -258,8 +258,8 @@ #ifndef NDEBUG String VTTCue::ToString() const { return String::Format("%p id=%s interval=%f-->%f cue=%s)", this, - id().Utf8().data(), startTime(), endTime(), - text().Utf8().data()); + id().Utf8().c_str(), startTime(), endTime(), + text().Utf8().c_str()); } #endif
diff --git a/third_party/blink/renderer/core/input/touch_action_test.cc b/third_party/blink/renderer/core/input/touch_action_test.cc index b4097820..d84a16c 100644 --- a/third_party/blink/renderer/core/input/touch_action_test.cc +++ b/third_party/blink/renderer/core/input/touch_action_test.cc
@@ -327,9 +327,7 @@ .data() << "\"" << std::endl << "Document render tree:" << std::endl - << ExternalRepresentation(root->GetDocument().GetFrame()) - .Utf8() - .data(); + << ExternalRepresentation(root->GetDocument().GetFrame()).Utf8(); // Now send the touch event and check any touch action result. SendTouchEvent(web_view, WebInputEvent::kPointerDown, window_point);
diff --git a/third_party/blink/renderer/core/inspector/inspector_css_agent.cc b/third_party/blink/renderer/core/inspector/inspector_css_agent.cc index 1789bcd..75570e8 100644 --- a/third_party/blink/renderer/core/inspector/inspector_css_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_css_agent.cc
@@ -408,7 +408,7 @@ String MergeId() override { return String::Format("SetStyleSheetText %s", - style_sheet_->Id().Utf8().data()); + style_sheet_->Id().Utf8().c_str()); } void Merge(Action* action) override { @@ -525,7 +525,7 @@ String MergeId() override { return String::Format("ModifyRuleAction:%d %s:%d", type_, - style_sheet_->Id().Utf8().data(), old_range_.start); + style_sheet_->Id().Utf8().c_str(), old_range_.start); } bool IsNoop() override { return old_text_ == new_text_; } @@ -579,7 +579,7 @@ String MergeId() override { return String::Format("SetElementStyleAction:%s", - style_sheet_->Id().Utf8().data()); + style_sheet_->Id().Utf8().c_str()); } std::unique_ptr<protocol::CSS::CSSStyle> TakeSerializedStyle() override {
diff --git a/third_party/blink/renderer/core/inspector/inspector_dom_snapshot_agent.cc b/third_party/blink/renderer/core/inspector/inspector_dom_snapshot_agent.cc index 5cdf35d..9ba75c8 100644 --- a/third_party/blink/renderer/core/inspector/inspector_dom_snapshot_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_dom_snapshot_agent.cc
@@ -472,9 +472,9 @@ value->setDocumentURL(InspectorDOMAgent::DocumentURLString(document)); value->setBaseURL(InspectorDOMAgent::DocumentBaseURLString(document)); if (document->ContentLanguage()) - value->setContentLanguage(document->ContentLanguage().Utf8().data()); + value->setContentLanguage(document->ContentLanguage().Utf8().c_str()); if (document->EncodingName()) - value->setDocumentEncoding(document->EncodingName().Utf8().data()); + value->setDocumentEncoding(document->EncodingName().Utf8().c_str()); value->setFrameId(IdentifiersFactory::FrameId(document->GetFrame())); if (document->View() && document->View()->LayoutViewport()) { auto offset = document->View()->LayoutViewport()->GetScrollOffset();
diff --git a/third_party/blink/renderer/core/inspector/inspector_page_agent.cc b/third_party/blink/renderer/core/inspector/inspector_page_agent.cc index a7008e7..339598b5 100644 --- a/third_party/blink/renderer/core/inspector/inspector_page_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_page_agent.cc
@@ -241,8 +241,7 @@ wtf_size_t buffer_size, String* result, bool* base64_encoded) { - if (!text_content.IsNull() && - !text_content.Utf8(WTF::kStrictUTF8Conversion).IsNull()) { + if (!text_content.IsNull()) { *result = text_content; *base64_encoded = false; } else if (buffer_data) {
diff --git a/third_party/blink/renderer/core/inspector/thread_debugger.cc b/third_party/blink/renderer/core/inspector/thread_debugger.cc index e247b37..e50cda9 100644 --- a/third_party/blink/renderer/core/inspector/thread_debugger.cc +++ b/third_party/blink/renderer/core/inspector/thread_debugger.cc
@@ -460,14 +460,14 @@ // TODO(dgozman): we can save on a copy here if trace macro would take a // pointer with length. TRACE_EVENT_COPY_ASYNC_BEGIN0("blink.console", - ToCoreString(title).Utf8().data(), this); + ToCoreString(title).Utf8().c_str(), this); } void ThreadDebugger::consoleTimeEnd(const v8_inspector::StringView& title) { // TODO(dgozman): we can save on a copy here if trace macro would take a // pointer with length. TRACE_EVENT_COPY_ASYNC_END0("blink.console", - ToCoreString(title).Utf8().data(), this); + ToCoreString(title).Utf8().c_str(), this); } void ThreadDebugger::consoleTimeStamp(const v8_inspector::StringView& title) {
diff --git a/third_party/blink/renderer/core/layout/layout_block_flow.cc b/third_party/blink/renderer/core/layout/layout_block_flow.cc index 1ca9ecc..cf996c0 100644 --- a/third_party/blink/renderer/core/layout/layout_block_flow.cc +++ b/third_party/blink/renderer/core/layout/layout_block_flow.cc
@@ -4781,7 +4781,7 @@ root->DumpLineTreeAndMark(string_blockflow, marked_box1, marked_label1, marked_box2, marked_label2, obj, 1); } - DLOG(INFO) << "\n" << string_blockflow.ToString().Utf8().data(); + DLOG(INFO) << "\n" << string_blockflow.ToString().Utf8(); } #endif
diff --git a/third_party/blink/renderer/core/layout/layout_object.cc b/third_party/blink/renderer/core/layout/layout_object.cc index 45a2cad4..254caa0 100644 --- a/third_party/blink/renderer/core/layout/layout_object.cc +++ b/third_party/blink/renderer/core/layout/layout_object.cc
@@ -1730,7 +1730,7 @@ #else info = object.DebugName(); #endif - return out << static_cast<const void*>(&object) << ":" << info.Utf8().data(); + return out << static_cast<const void*>(&object) << ":" << info.Utf8(); } std::ostream& operator<<(std::ostream& out, const LayoutObject* object) { @@ -1763,7 +1763,7 @@ void LayoutObject::ShowLayoutObject() const { StringBuilder string_builder; DumpLayoutObject(string_builder, true, kShowTreeCharacterOffset); - DLOG(INFO) << "\n" << string_builder.ToString().Utf8().data(); + DLOG(INFO) << "\n" << string_builder.ToString().Utf8(); } void LayoutObject::DumpLayoutObject(StringBuilder& string_builder, @@ -4119,7 +4119,7 @@ StringBuilder string_builder; root->DumpLayoutTreeAndMark(string_builder, object1, "*", object2, "-", 0); - DLOG(INFO) << "\n" << string_builder.ToString().Utf8().data(); + DLOG(INFO) << "\n" << string_builder.ToString().Utf8(); } } else { DLOG(INFO) << "Cannot showLayoutTree. Root is (nil)";
diff --git a/third_party/blink/renderer/core/layout/layout_object_test.cc b/third_party/blink/renderer/core/layout/layout_object_test.cc index 9a29a32b..28a54ec 100644 --- a/third_party/blink/renderer/core/layout/layout_object_test.cc +++ b/third_party/blink/renderer/core/layout/layout_object_test.cc
@@ -740,7 +740,7 @@ StringBuilder result; block->DumpLayoutObject(result, false, 0); - EXPECT_THAT(result.ToString().Utf8().data(), + EXPECT_THAT(result.ToString().Utf8(), MatchesRegex("LayoutN?G?BlockFlow\tDIV id=\"block\" " "style=\"background:\\\\nlime\""));
diff --git a/third_party/blink/renderer/core/layout/layout_quote.cc b/third_party/blink/renderer/core/layout/layout_quote.cc index f61b8cf..5e0f03d5 100644 --- a/third_party/blink/renderer/core/layout/layout_quote.cc +++ b/third_party/blink/renderer/core/layout/layout_quote.cc
@@ -235,8 +235,8 @@ // This could be just a hash table, but doing that adds 200k to LayoutQuote.o Language* languages_end = g_languages + base::size(g_languages); - CString lowercase_lang = lang.DeprecatedLower().Utf8(); - Language key = {lowercase_lang.data(), 0, 0, 0, 0, nullptr}; + std::string lowercase_lang = lang.DeprecatedLower().Utf8(); + Language key = {lowercase_lang.c_str(), 0, 0, 0, 0, nullptr}; Language* match = std::lower_bound(g_languages, languages_end, key); if (match == languages_end || strcmp(match->lang, key.lang)) return nullptr;
diff --git a/third_party/blink/renderer/core/layout/line/inline_text_box.cc b/third_party/blink/renderer/core/layout/line/inline_text_box.cc index d7bba44a..75b321e 100644 --- a/third_party/blink/renderer/core/layout/line/inline_text_box.cc +++ b/third_party/blink/renderer/core/layout/line/inline_text_box.cc
@@ -710,7 +710,7 @@ while (string_inlinetextbox.length() < kLayoutObjectCharacterOffset) string_inlinetextbox.Append(' '); string_inlinetextbox.AppendFormat("(%d,%d) \"%s\"", Start(), Start() + Len(), - value.Utf8().data()); + value.Utf8().c_str()); } #endif
diff --git a/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node_test.cc b/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node_test.cc index 6f31c49..cd49b3cc 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node_test.cc +++ b/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node_test.cc
@@ -35,7 +35,7 @@ public: using NGInlineNode::NGInlineNode; - std::string Text() const { return Data().text_content.Utf8().data(); } + std::string Text() const { return Data().text_content.Utf8(); } Vector<NGInlineItem>& Items() { return MutableData()->items; } static Vector<NGInlineItem>& Items(NGInlineNodeData& data) { return data.items;
diff --git a/third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment_test.cc b/third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment_test.cc index 1867897..00a6fd0 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment_test.cc +++ b/third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment_test.cc
@@ -38,7 +38,7 @@ } static std::string GetText(const NGPhysicalTextFragment& fragment) { - return fragment.Text().ToString().Utf8().data(); + return fragment.Text().ToString().Utf8(); } };
diff --git a/third_party/blink/renderer/core/layout/ng/ng_break_token.cc b/third_party/blink/renderer/core/layout/ng/ng_break_token.cc index 3d272e1..a810bfe 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_break_token.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_break_token.cc
@@ -60,7 +60,7 @@ StringBuilder string_builder; string_builder.Append(".:: LayoutNG Break Token Tree ::.\n"); AppendBreakTokenToString(this, &string_builder); - fprintf(stderr, "%s\n", string_builder.ToString().Utf8().data()); + fprintf(stderr, "%s\n", string_builder.ToString().Utf8().c_str()); } #endif // DCHECK_IS_ON()
diff --git a/third_party/blink/renderer/core/layout/ng/ng_layout_input_node.cc b/third_party/blink/renderer/core/layout/ng/ng_layout_input_node.cc index c6cc985..b848caa 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_layout_input_node.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_layout_input_node.cc
@@ -139,7 +139,7 @@ StringBuilder string_builder; string_builder.Append(".:: LayoutNG Node Tree ::.\n"); AppendNodeToString(*this, &string_builder); - fprintf(stderr, "%s\n", string_builder.ToString().Utf8().data()); + fprintf(stderr, "%s\n", string_builder.ToString().Utf8().c_str()); } #endif
diff --git a/third_party/blink/renderer/core/layout/ng/ng_physical_fragment.cc b/third_party/blink/renderer/core/layout/ng/ng_physical_fragment.cc index 606cbace..6cb1590 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_physical_fragment.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_physical_fragment.cc
@@ -509,7 +509,7 @@ #if DCHECK_IS_ON() void NGPhysicalFragment::ShowFragmentTree() const { DumpFlags dump_flags = DumpAll; - LOG(INFO) << "\n" << DumpFragmentTree(dump_flags).Utf8().data(); + LOG(INFO) << "\n" << DumpFragmentTree(dump_flags).Utf8(); } #endif
diff --git a/third_party/blink/renderer/core/layout/svg/svg_resources.cc b/third_party/blink/renderer/core/layout/svg/svg_resources.cc index c2933d40..32620578 100644 --- a/third_party/blink/renderer/core/layout/svg/svg_resources.cc +++ b/third_party/blink/renderer/core/layout/svg/svg_resources.cc
@@ -565,7 +565,8 @@ fprintf(stderr, "-> this=%p, SVGResources(layoutObject=%p, node=%p)\n", this, object, object->GetNode()); fprintf(stderr, " | DOM Tree:\n"); - fprintf(stderr, "%s", object->GetNode()->ToTreeStringForThis().Utf8().data()); + fprintf(stderr, "%s", + object->GetNode()->ToTreeStringForThis().Utf8().c_str()); fprintf(stderr, "\n | List of resources:\n"); if (clipper_filter_masker_data_) {
diff --git a/third_party/blink/renderer/core/layout/text_autosizer.cc b/third_party/blink/renderer/core/layout/text_autosizer.cc index f0212e4c..04e5f903 100644 --- a/third_party/blink/renderer/core/layout/text_autosizer.cc +++ b/third_party/blink/renderer/core/layout/text_autosizer.cc
@@ -569,11 +569,10 @@ return new_inline_size != page_info_.shared_info_.main_frame_layout_width; } -void TextAutosizer::UpdatePageInfoInAllFrames() { - DCHECK(!document_->GetFrame() || document_->GetFrame()->IsMainFrame()); - - for (Frame* frame = document_->GetFrame(); frame; - frame = frame->Tree().TraverseNext()) { +// Static. +void TextAutosizer::UpdatePageInfoInAllFrames(Frame* main_frame) { + DCHECK(main_frame && main_frame == main_frame->Tree().Top()); + for (Frame* frame = main_frame; frame; frame = frame->Tree().TraverseNext()) { auto* local_frame = DynamicTo<LocalFrame>(frame); if (!local_frame) continue; @@ -586,17 +585,18 @@ text_autosizer->UpdatePageInfo(); // Share the page information from the local mainframe with remote ones. + // TODO(wjmaclean): Refactor this code into a non-static class function + // called UpdateWebTextAutosizerPageInfoIfNecessary(). if (frame->IsMainFrame()) { + const PageInfo& page_info = text_autosizer->page_info_; const WebTextAutosizerPageInfo& old_page_info = - document_->GetPage()->TextAutosizerPageInfo(); - if (page_info_.shared_info_ != old_page_info) { - document_->GetPage() - ->GetChromeClient() - .DidUpdateTextAutosizerPageInfo(page_info_.shared_info_); + document->GetPage()->TextAutosizerPageInfo(); + if (page_info.shared_info_ != old_page_info) { + document->GetPage()->GetChromeClient().DidUpdateTextAutosizerPageInfo( + page_info.shared_info_); // Remember the RemotePageSettings in the mainframe's renderer so we // know when they change. - document_->GetPage()->SetTextAutosizePageInfo( - page_info_.shared_info_); + document->GetPage()->SetTextAutosizePageInfo(page_info.shared_info_); } } } @@ -619,41 +619,41 @@ bool horizontal_writing_mode = IsHorizontalWritingMode(layout_view->StyleRef().GetWritingMode()); - // FIXME: With out-of-process iframes, the top frame can be remote and - // doesn't have sizing information. Just return if this is the case. Frame& frame = document_->GetFrame()->Tree().Top(); - if (frame.IsRemoteFrame()) - return; + if (frame.IsRemoteFrame()) { + // When the frame is remote, the local main frame is responsible for + // computing shared_info_ and passing them down to the OOPIF renderers. + page_info_.shared_info_ = document_->GetPage()->TextAutosizerPageInfo(); + } else { + LocalFrame& main_frame = To<LocalFrame>(frame); + IntSize frame_size = + document_->GetSettings()->TextAutosizingWindowSizeOverride(); + if (frame_size.IsEmpty()) + frame_size = WindowSize(); - LocalFrame& main_frame = To<LocalFrame>(frame); - IntSize frame_size = - document_->GetSettings()->TextAutosizingWindowSizeOverride(); - if (frame_size.IsEmpty()) - frame_size = WindowSize(); + page_info_.shared_info_.main_frame_width = + horizontal_writing_mode ? frame_size.Width() : frame_size.Height(); - page_info_.shared_info_.main_frame_width = - horizontal_writing_mode ? frame_size.Width() : frame_size.Height(); + page_info_.shared_info_.main_frame_layout_width = + GetLayoutInlineSize(*document_, *main_frame.View()); - page_info_.shared_info_.main_frame_layout_width = - GetLayoutInlineSize(*document_, *main_frame.View()); - - // TODO(pdr): Accessibility should be moved out of the text autosizer. See: - // crbug.com/645717. + // If the page has a meta viewport or @viewport, don't apply the device + // scale adjustment. + if (!main_frame.GetDocument() + ->GetViewportData() + .GetViewportDescription() + .IsSpecifiedByAuthor()) { + page_info_.shared_info_.device_scale_adjustment = + document_->GetSettings()->GetDeviceScaleAdjustment(); + } else { + page_info_.shared_info_.device_scale_adjustment = 1.0f; + } + } + // TODO(pdr): Accessibility should be moved out of the text autosizer. + // See: crbug.com/645717. page_info_.accessibility_font_scale_factor_ = document_->GetSettings()->GetAccessibilityFontScaleFactor(); - // If the page has a meta viewport or @viewport, don't apply the device - // scale adjustment. - if (!main_frame.GetDocument() - ->GetViewportData() - .GetViewportDescription() - .IsSpecifiedByAuthor()) { - page_info_.shared_info_.device_scale_adjustment = - document_->GetSettings()->GetDeviceScaleAdjustment(); - } else { - page_info_.shared_info_.device_scale_adjustment = 1.0f; - } - // TODO(pdr): pageNeedsAutosizing should take into account whether // text-size-adjust is used anywhere on the page because that also needs to // trigger autosizing. See: crbug.com/646237. @@ -1423,6 +1423,10 @@ TextAutosizer::DeferUpdatePageInfo::DeferUpdatePageInfo(Page* page) : main_frame_(page->DeprecatedLocalMainFrame()) { + // TODO(wjmaclean): see if we need to try and extend deferred updates to + // renderers for remote main frames or not. For now, it's safe to assume + // main_frame_ will be local, see WebViewImpl::ResizeViewWhileAnchored(). + DCHECK(main_frame_); if (TextAutosizer* text_autosizer = main_frame_->GetDocument()->GetTextAutosizer()) { DCHECK(!text_autosizer->update_page_info_deferred_); @@ -1464,7 +1468,7 @@ main_frame_->GetDocument()->GetTextAutosizer()) { DCHECK(text_autosizer->update_page_info_deferred_); text_autosizer->update_page_info_deferred_ = false; - text_autosizer->UpdatePageInfoInAllFrames(); + TextAutosizer::UpdatePageInfoInAllFrames(main_frame_); } }
diff --git a/third_party/blink/renderer/core/layout/text_autosizer.h b/third_party/blink/renderer/core/layout/text_autosizer.h index 53172afd..92ad9de 100644 --- a/third_party/blink/renderer/core/layout/text_autosizer.h +++ b/third_party/blink/renderer/core/layout/text_autosizer.h
@@ -44,6 +44,7 @@ namespace blink { class Document; +class Frame; class IntSize; class LayoutBlock; class LayoutObject; @@ -67,9 +68,12 @@ static float ComputeAutosizedFontSize(float computed_size, float multiplier, float effective_zoom); + // Static to allow starting updates from the frame tree root when it's a + // remote frame, though this function is called for all main frames, local + // or remote. + static void UpdatePageInfoInAllFrames(Frame* root_frame); bool HasLayoutInlineSizeChanged() const; - void UpdatePageInfoInAllFrames(); void UpdatePageInfo(); void Record(LayoutBlock*); void Record(LayoutText*);
diff --git a/third_party/blink/renderer/core/loader/frame_loader.cc b/third_party/blink/renderer/core/loader/frame_loader.cc index d8c357c5..8f729e2 100644 --- a/third_party/blink/renderer/core/loader/frame_loader.cc +++ b/third_party/blink/renderer/core/loader/frame_loader.cc
@@ -112,6 +112,7 @@ #include "third_party/blink/renderer/platform/weborigin/security_policy.h" #include "third_party/blink/renderer/platform/wtf/assertions.h" #include "third_party/blink/renderer/platform/wtf/text/cstring.h" +#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink { @@ -776,20 +777,18 @@ // - use it here instead of re-reading from the owner. // This way we will get rid of extra dependency between starting and // committing navigation. - CString encoded_srcdoc; + String srcdoc; HTMLFrameOwnerElement* owner_element = frame->DeprecatedLocalOwner(); if (!IsHTMLIFrameElement(owner_element) || !owner_element->FastHasAttribute(html_names::kSrcdocAttr)) { // Cannot retrieve srcdoc content anymore (perhaps, the attribute was // cleared) - load empty instead. } else { - String srcdoc = owner_element->FastGetAttribute(html_names::kSrcdocAttr); + srcdoc = owner_element->FastGetAttribute(html_names::kSrcdocAttr); DCHECK(!srcdoc.IsNull()); - encoded_srcdoc = srcdoc.Utf8(); } - WebNavigationParams::FillStaticResponse( - params, "text/html", "UTF-8", - base::make_span(encoded_srcdoc.data(), encoded_srcdoc.length())); + WebNavigationParams::FillStaticResponse(params, "text/html", "UTF-8", + StringUTF8Adaptor(srcdoc)); return; }
diff --git a/third_party/blink/renderer/core/loader/http_equiv.cc b/third_party/blink/renderer/core/loader/http_equiv.cc index 21b759c..855add6 100644 --- a/third_party/blink/renderer/core/loader/http_equiv.cc +++ b/third_party/blink/renderer/core/loader/http_equiv.cc
@@ -211,7 +211,7 @@ mojom::ConsoleMessageSource::kSecurity, mojom::ConsoleMessageLevel::kError, String::Format("Blocked setting the `%s` cookie from a `<meta>` tag.", - content.Utf8().data()))); + content.Utf8().c_str()))); } } // namespace blink
diff --git a/third_party/blink/renderer/core/loader/mixed_content_checker.cc b/third_party/blink/renderer/core/loader/mixed_content_checker.cc index 2dde925..fd4c72d 100644 --- a/third_party/blink/renderer/core/loader/mixed_content_checker.cc +++ b/third_party/blink/renderer/core/loader/mixed_content_checker.cc
@@ -300,8 +300,8 @@ String message = String::Format( "Mixed Content: The page at '%s' was loaded over HTTPS, but requested an " "insecure %s '%s'. %s", - main_resource_url.ElidedString().Utf8().data(), - RequestContextName(request_context), url.ElidedString().Utf8().data(), + main_resource_url.ElidedString().Utf8().c_str(), + RequestContextName(request_context), url.ElidedString().Utf8().c_str(), allowed ? "This content should also be served over HTTPS." : "This request has been blocked; the content must be served " "over HTTPS."); @@ -549,8 +549,8 @@ String message = String::Format( "Mixed Content: The page at '%s' was loaded over HTTPS, but attempted to " "connect to the insecure WebSocket endpoint '%s'. %s", - main_resource_url.ElidedString().Utf8().data(), - url.ElidedString().Utf8().data(), + main_resource_url.ElidedString().Utf8().c_str(), + url.ElidedString().Utf8().c_str(), allowed ? "This endpoint should be available via WSS. Insecure access is " "deprecated." : "This request has been blocked; this endpoint must be " @@ -656,8 +656,8 @@ "Mixed Content: The page at '%s' was loaded over a secure connection, " "but contains a form that targets an insecure endpoint '%s'. This " "endpoint should be made available over a secure connection.", - MainResourceUrlForFrame(mixed_frame).ElidedString().Utf8().data(), - url.ElidedString().Utf8().data()); + MainResourceUrlForFrame(mixed_frame).ElidedString().Utf8().c_str(), + url.ElidedString().Utf8().c_str()); frame->GetDocument()->AddConsoleMessage( ConsoleMessage::Create(mojom::ConsoleMessageSource::kSecurity, mojom::ConsoleMessageLevel::kWarning, message)); @@ -774,8 +774,8 @@ "automatically upgraded to HTTPS, For more information see " "https://chromium.googlesource.com/chromium/src/+/master/docs/security/" "autoupgrade-mixed.md", - main_resource_url.ElidedString().Utf8().data(), - mixed_content_url.ElidedString().Utf8().data()); + main_resource_url.ElidedString().Utf8().c_str(), + mixed_content_url.ElidedString().Utf8().c_str()); return ConsoleMessage::Create(mojom::ConsoleMessageSource::kSecurity, mojom::ConsoleMessageLevel::kWarning, message); } @@ -792,8 +792,8 @@ "information see " "https://chromium.googlesource.com/chromium/src/+/master/docs/security/" "autoupgrade-mixed.md", - main_resource_url.ElidedString().Utf8().data(), - mixed_content_url.ElidedString().Utf8().data()); + main_resource_url.ElidedString().Utf8().c_str(), + mixed_content_url.ElidedString().Utf8().c_str()); return ConsoleMessage::Create(mojom::ConsoleMessageSource::kSecurity, mojom::ConsoleMessageLevel::kWarning, message); }
diff --git a/third_party/blink/renderer/core/page/frame_tree.cc b/third_party/blink/renderer/core/page/frame_tree.cc index 86974eb..6ddc6d4 100644 --- a/third_party/blink/renderer/core/page/frame_tree.cc +++ b/third_party/blink/renderer/core/page/frame_tree.cc
@@ -377,7 +377,7 @@ printIndent(indent); printf(" uri=%s\n\n", local_frame - ? local_frame->GetDocument()->Url().GetString().Utf8().data() + ? local_frame->GetDocument()->Url().GetString().Utf8().c_str() : nullptr); for (blink::Frame* child = frame->Tree().FirstChild(); child;
diff --git a/third_party/blink/renderer/core/page/page.cc b/third_party/blink/renderer/core/page/page.cc index 819ce53..d3f15ac 100644 --- a/third_party/blink/renderer/core/page/page.cc +++ b/third_party/blink/renderer/core/page/page.cc
@@ -590,10 +590,11 @@ ->GetDocument() ->GetViewportData() .UpdateViewportDescription(); - // The text autosizer has dependencies on the viewport. - if (TextAutosizer* text_autosizer = - DeprecatedLocalMainFrame()->GetDocument()->GetTextAutosizer()) - text_autosizer->UpdatePageInfoInAllFrames(); + // The text autosizer has dependencies on the viewport. Viewport + // description only applies to the main frame. On a viewport description + // change; any changes will be calculated starting from the local main + // frame renderer and propagated to the OOPIF renderers. + TextAutosizer::UpdatePageInfoInAllFrames(MainFrame()); } break; case SettingsDelegate::kViewportScrollbarChange: @@ -618,11 +619,11 @@ } break; case SettingsDelegate::kTextAutosizingChange: - if (!MainFrame() || !MainFrame()->IsLocalFrame()) + if (!MainFrame()) break; - if (TextAutosizer* text_autosizer = - DeprecatedLocalMainFrame()->GetDocument()->GetTextAutosizer()) - text_autosizer->UpdatePageInfoInAllFrames(); + // We need to update even for remote main frames since this setting + // could be changed via InternalSettings. + TextAutosizer::UpdatePageInfoInAllFrames(MainFrame()); break; case SettingsDelegate::kFontFamilyChange: for (Frame* frame = MainFrame(); frame;
diff --git a/third_party/blink/renderer/core/page/page_popup_client.h b/third_party/blink/renderer/core/page/page_popup_client.h index 0d46cf3..62822b6 100644 --- a/third_party/blink/renderer/core/page/page_popup_client.h +++ b/third_party/blink/renderer/core/page/page_popup_client.h
@@ -35,6 +35,7 @@ #include "third_party/blink/renderer/platform/geometry/int_rect.h" #include "third_party/blink/renderer/platform/shared_buffer.h" #include "third_party/blink/renderer/platform/wtf/text/cstring.h" +#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink { @@ -94,8 +95,8 @@ }; inline void PagePopupClient::AddString(const String& str, SharedBuffer* data) { - CString str8 = str.Utf8(); - data->Append(str8.data(), str8.length()); + StringUTF8Adaptor utf8(str); + data->Append(utf8.data(), utf8.size()); } } // namespace blink
diff --git a/third_party/blink/renderer/core/page/print_context.cc b/third_party/blink/renderer/core/page/print_context.cc index 358bebb..32be554f 100644 --- a/third_party/blink/renderer/core/page/print_context.cc +++ b/third_party/blink/renderer/core/page/print_context.cc
@@ -251,7 +251,8 @@ // want to collect @page rules and figure out what declarations apply on a // given page (that may or may not exist). print_context->BeginPrintMode(800, 1000); - scoped_refptr<ComputedStyle> style = document->StyleForPage(page_number); + scoped_refptr<const ComputedStyle> style = + document->StyleForPage(page_number); // Implement formatters for properties we care about. if (!strcmp(property_name, "margin-left")) {
diff --git a/third_party/blink/renderer/core/paint/compositing/graphics_layer_tree_as_text.cc b/third_party/blink/renderer/core/paint/compositing/graphics_layer_tree_as_text.cc index ae4a430..1edca85 100644 --- a/third_party/blink/renderer/core/paint/compositing/graphics_layer_tree_as_text.cc +++ b/third_party/blink/renderer/core/paint/compositing/graphics_layer_tree_as_text.cc
@@ -369,7 +369,7 @@ String new_tree = GraphicsLayerTreeAsTextForTesting(root, flags); auto it = s_previous_trees.find(root); if (it == s_previous_trees.end() || it->value != new_tree) { - VLOG(2) << "GraphicsLayer tree:\n" << new_tree.Utf8().data(); + VLOG(2) << "GraphicsLayer tree:\n" << new_tree.Utf8(); s_previous_trees.Set(root, new_tree); // For simplification, we don't remove deleted GraphicsLayers from the map. } @@ -386,7 +386,7 @@ } String output = blink::GraphicsLayerTreeAsTextForTesting(layer, 0xffffffff); - LOG(ERROR) << output.Utf8().data(); + LOG(ERROR) << output.Utf8(); } void showGraphicsLayers(const blink::GraphicsLayer* layer) { @@ -397,6 +397,6 @@ String output = blink::GraphicsLayerTreeAsTextForTesting( layer, 0xffffffff & ~blink::kOutputAsLayerTree); - LOG(ERROR) << output.Utf8().data(); + LOG(ERROR) << output.Utf8(); } #endif
diff --git a/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h b/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h index 7317732a..9829e3a 100644 --- a/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h +++ b/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h
@@ -38,6 +38,8 @@ // placeholders for displaying them. class CORE_EXPORT NGPaintFragment : public RefCounted<NGPaintFragment>, public DisplayItemClient { + USING_FAST_MALLOC(NGPaintFragment); + public: NGPaintFragment(scoped_refptr<const NGPhysicalFragment>, PhysicalOffset offset,
diff --git a/third_party/blink/renderer/core/paint/paint_layer.cc b/third_party/blink/renderer/core/paint/paint_layer.cc index 51a098b..2a746f4 100644 --- a/third_party/blink/renderer/core/paint/paint_layer.cc +++ b/third_party/blink/renderer/core/paint/paint_layer.cc
@@ -3543,7 +3543,7 @@ blink::kLayoutAsTextShowLayoutState | blink::kLayoutAsTextShowPaintProperties, layer); - LOG(ERROR) << output.Utf8().data(); + LOG(ERROR) << output.Utf8(); } }
diff --git a/third_party/blink/renderer/core/paint/paint_property_tree_printer.cc b/third_party/blink/renderer/core/paint/paint_property_tree_printer.cc index 6b0ee86..057f90e 100644 --- a/third_party/blink/renderer/core/paint/paint_property_tree_printer.cc +++ b/third_party/blink/renderer/core/paint/paint_property_tree_printer.cc
@@ -229,22 +229,21 @@ void showTransformPropertyTree(const blink::LocalFrameView& rootFrame) { LOG(ERROR) << "Transform tree:\n" - << transformPropertyTreeAsString(rootFrame).Utf8().data(); + << transformPropertyTreeAsString(rootFrame).Utf8(); } void showClipPropertyTree(const blink::LocalFrameView& rootFrame) { - LOG(ERROR) << "Clip tree:\n" - << clipPropertyTreeAsString(rootFrame).Utf8().data(); + LOG(ERROR) << "Clip tree:\n" << clipPropertyTreeAsString(rootFrame).Utf8(); } void showEffectPropertyTree(const blink::LocalFrameView& rootFrame) { LOG(ERROR) << "Effect tree:\n" - << effectPropertyTreeAsString(rootFrame).Utf8().data(); + << effectPropertyTreeAsString(rootFrame).Utf8(); } void showScrollPropertyTree(const blink::LocalFrameView& rootFrame) { LOG(ERROR) << "Scroll tree:\n" - << scrollPropertyTreeAsString(rootFrame).Utf8().data(); + << scrollPropertyTreeAsString(rootFrame).Utf8(); } String transformPropertyTreeAsString(const blink::LocalFrameView& rootFrame) {
diff --git a/third_party/blink/renderer/core/script/document_write_intervention.cc b/third_party/blink/renderer/core/script/document_write_intervention.cc index fbe4bfc3..c2df36e 100644 --- a/third_party/blink/renderer/core/script/document_write_intervention.cc +++ b/third_party/blink/renderer/core/script/document_write_intervention.cc
@@ -34,7 +34,7 @@ document.AddConsoleMessage( ConsoleMessage::Create(mojom::ConsoleMessageSource::kJavaScript, mojom::ConsoleMessageLevel::kWarning, message)); - DVLOG(1) << message.Utf8().data(); + DVLOG(1) << message.Utf8(); } void EmitWarningNotBlocked(const String& url, Document& document) {
diff --git a/third_party/blink/renderer/core/streams/BUILD.gn b/third_party/blink/renderer/core/streams/BUILD.gn index 24a5a05..d8c60b6 100644 --- a/third_party/blink/renderer/core/streams/BUILD.gn +++ b/third_party/blink/renderer/core/streams/BUILD.gn
@@ -30,6 +30,8 @@ "stream_algorithms.h", "stream_promise_resolver.cc", "stream_promise_resolver.h", + "transferable_streams.cc", + "transferable_streams.h", "transform_stream.cc", "transform_stream.h", "transform_stream_default_controller.cc",
diff --git a/third_party/blink/renderer/core/streams/README.md b/third_party/blink/renderer/core/streams/README.md index 6856924..1b845c20 100644 --- a/third_party/blink/renderer/core/streams/README.md +++ b/third_party/blink/renderer/core/streams/README.md
@@ -26,6 +26,8 @@ writable_stream_default_writer.idl writable_stream_native.cc writable_stream_native.h + transferable_streams.cc + transferable_streams.h transform_stream_default_controller.cc transform_stream_default_controller.h transform_stream_native.cc
diff --git a/third_party/blink/renderer/core/streams/miscellaneous_operations_test.cc b/third_party/blink/renderer/core/streams/miscellaneous_operations_test.cc index c21a934..9a8e28b 100644 --- a/third_party/blink/renderer/core/streams/miscellaneous_operations_test.cc +++ b/third_party/blink/renderer/core/streams/miscellaneous_operations_test.cc
@@ -97,7 +97,8 @@ int argc = 0, v8::Local<v8::Value> argv[] = nullptr) { String js = String("({start: ") + function_definition + "})" + '\0'; - ScriptValue underlying_value = EvalWithPrintingError(scope, js.Utf8().data()); + ScriptValue underlying_value = + EvalWithPrintingError(scope, js.Utf8().c_str()); auto underlying_object = underlying_value.V8Value().As<v8::Object>(); auto* algo = CreateAlgorithmFromUnderlyingMethod( scope->GetScriptState(), underlying_object, "start",
diff --git a/third_party/blink/renderer/core/streams/readable_stream.cc b/third_party/blink/renderer/core/streams/readable_stream.cc index 8b787d6..e1088481 100644 --- a/third_party/blink/renderer/core/streams/readable_stream.cc +++ b/third_party/blink/renderer/core/streams/readable_stream.cc
@@ -60,11 +60,9 @@ ReadableStream* ReadableStream::Deserialize(ScriptState* script_state, MessagePort* port, ExceptionState& exception_state) { - // TODO(ricea): Implementation serialization for the native implementation. if (RuntimeEnabledFeatures::StreamsNativeEnabled()) { - exception_state.ThrowTypeError( - "serialization disabled because StreamsNative feature is enabled"); - return nullptr; + return ReadableStreamNative::Deserialize(script_state, port, + exception_state); } return ReadableStreamWrapper::Deserialize(script_state, port,
diff --git a/third_party/blink/renderer/core/streams/readable_stream_native.cc b/third_party/blink/renderer/core/streams/readable_stream_native.cc index d957c75..1828317 100644 --- a/third_party/blink/renderer/core/streams/readable_stream_native.cc +++ b/third_party/blink/renderer/core/streams/readable_stream_native.cc
@@ -15,6 +15,7 @@ #include "third_party/blink/renderer/core/streams/readable_stream_reader.h" #include "third_party/blink/renderer/core/streams/stream_algorithms.h" #include "third_party/blink/renderer/core/streams/stream_promise_resolver.h" +#include "third_party/blink/renderer/core/streams/transferable_streams.h" #include "third_party/blink/renderer/core/streams/underlying_source_base.h" #include "third_party/blink/renderer/core/streams/writable_stream_default_controller.h" #include "third_party/blink/renderer/core/streams/writable_stream_default_writer.h" @@ -30,13 +31,6 @@ namespace blink { -struct ReadableStreamNative::PipeOptions { - PipeOptions() = default; - bool prevent_close = false; - bool prevent_abort = false; - bool prevent_cancel = false; -}; - // PipeToEngine implements PipeTo(). All standard steps in this class come from // https://streams.spec.whatwg.org/#readable-stream-pipe-to // @@ -1394,7 +1388,43 @@ void ReadableStreamNative::Serialize(ScriptState* script_state, MessagePort* port, ExceptionState& exception_state) { - // TODO(ricea): Implement this. + if (IsLocked(this)) { + exception_state.ThrowTypeError("Cannot transfer a locked stream"); + return; + } + + auto* writable = + CreateCrossRealmTransformWritable(script_state, port, exception_state); + if (exception_state.HadException()) { + return; + } + + auto promise = PipeTo(script_state, this, writable, PipeOptions()); + promise.MarkAsHandled(); +} + +ReadableStreamNative* ReadableStreamNative::Deserialize( + ScriptState* script_state, + MessagePort* port, + ExceptionState& exception_state) { + // We need to execute JavaScript to call "Then" on v8::Promises. We will not + // run author code. + v8::Isolate::AllowJavascriptExecutionScope allow_js( + script_state->GetIsolate()); + auto* readable = + CreateCrossRealmTransformReadable(script_state, port, exception_state); + if (exception_state.HadException()) { + return nullptr; + } + return readable; +} + +ScriptPromise ReadableStreamNative::PipeTo(ScriptState* script_state, + ReadableStreamNative* readable, + WritableStreamNative* destination, + PipeOptions pipe_options) { + auto* engine = MakeGarbageCollected<PipeToEngine>(script_state, pipe_options); + return engine->Start(readable, destination); } v8::Local<v8::Value> ReadableStreamNative::GetStoredError( @@ -1409,14 +1439,6 @@ ReadableStream::Trace(visitor); } -ScriptPromise ReadableStreamNative::PipeTo(ScriptState* script_state, - ReadableStreamNative* readable, - WritableStreamNative* destination, - PipeOptions pipe_options) { - auto* engine = MakeGarbageCollected<PipeToEngine>(script_state, pipe_options); - return engine->Start(readable, destination); -} - // // Abstract Operations Used By Controllers //
diff --git a/third_party/blink/renderer/core/streams/readable_stream_native.h b/third_party/blink/renderer/core/streams/readable_stream_native.h index b2af17d4..9cd1fea 100644 --- a/third_party/blink/renderer/core/streams/readable_stream_native.h +++ b/third_party/blink/renderer/core/streams/readable_stream_native.h
@@ -30,6 +30,13 @@ // See https://streams.spec.whatwg.org/#rs-model for background. class ReadableStreamNative : public ReadableStream { public: + struct PipeOptions { + PipeOptions() = default; + bool prevent_close = false; + bool prevent_abort = false; + bool prevent_cancel = false; + }; + enum State : uint8_t { kReadable, kClosed, kErrored }; // Implements ReadableStream::Create() when this implementation is enabled. @@ -146,6 +153,10 @@ void Serialize(ScriptState*, MessagePort* port, ExceptionState&) override; + static ReadableStreamNative* Deserialize(ScriptState*, + MessagePort* port, + ExceptionState&); + bool IsBroken() const override { return false; } // @@ -162,6 +173,12 @@ return stream->reader_; } + // https://streams.spec.whatwg.org/#readable-stream-pipe-to + static ScriptPromise PipeTo(ScriptState*, + ReadableStreamNative*, + WritableStreamNative*, + PipeOptions); + // // Functions exported for use by TransformStream. Not part of the standard. // @@ -190,7 +207,6 @@ friend class ReadableStreamDefaultController; friend class ReadableStreamReader; - struct PipeOptions; class PipeToEngine; class ReadHandleImpl; class TeeEngine; @@ -204,12 +220,6 @@ bool for_author_code, ExceptionState&); - // https://streams.spec.whatwg.org/#readable-stream-pipe-to - static ScriptPromise PipeTo(ScriptState*, - ReadableStreamNative*, - WritableStreamNative*, - PipeOptions); - // https://streams.spec.whatwg.org/#readable-stream-add-read-request static StreamPromiseResolver* AddReadRequest(ScriptState*, ReadableStreamNative*);
diff --git a/third_party/blink/renderer/core/streams/readable_stream_reader.h b/third_party/blink/renderer/core/streams/readable_stream_reader.h index 3d5f8d3..6099dca 100644 --- a/third_party/blink/renderer/core/streams/readable_stream_reader.h +++ b/third_party/blink/renderer/core/streams/readable_stream_reader.h
@@ -6,6 +6,7 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_READABLE_STREAM_READER_H_ #include "third_party/blink/renderer/bindings/core/v8/script_value.h" +#include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "v8/include/v8.h" @@ -25,7 +26,7 @@ // with the standard, ReadableStreamDefaultReader is implemented by the // ReadableStreamReader class. // TODO(ricea): Refactor this when implementing ReadableStreamBYOBReader. -class ReadableStreamReader : public ScriptWrappable { +class CORE_EXPORT ReadableStreamReader : public ScriptWrappable { DEFINE_WRAPPERTYPEINFO(); public:
diff --git a/third_party/blink/renderer/core/streams/readable_stream_test.cc b/third_party/blink/renderer/core/streams/readable_stream_test.cc index 656da9d..2217f82 100644 --- a/third_party/blink/renderer/core/streams/readable_stream_test.cc +++ b/third_party/blink/renderer/core/streams/readable_stream_test.cc
@@ -410,11 +410,6 @@ } TEST_P(ReadableStreamTest, Serialize) { - if (GetParam()) { - // Serialize() is not yet supported in the C++ implementation. - return; - } - ScopedTransferableStreamsForTest enabled(true); V8TestingScope scope;
diff --git a/third_party/blink/renderer/core/streams/transferable_streams.cc b/third_party/blink/renderer/core/streams/transferable_streams.cc new file mode 100644 index 0000000..82efecb --- /dev/null +++ b/third_party/blink/renderer/core/streams/transferable_streams.cc
@@ -0,0 +1,878 @@ +// 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. + +// Functions for transferable streams. See design doc +// https://docs.google.com/document/d/1_KuZzg5c3pncLJPFa8SuVm23AP4tft6mzPCL5at3I9M/edit + +#include "third_party/blink/renderer/core/streams/transferable_streams.h" + +#include "base/stl_util.h" +#include "third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h" +#include "third_party/blink/renderer/bindings/core/v8/v8_dom_exception.h" +#include "third_party/blink/renderer/core/dom/dom_exception.h" +#include "third_party/blink/renderer/core/dom/events/native_event_listener.h" +#include "third_party/blink/renderer/core/events/message_event.h" +#include "third_party/blink/renderer/core/messaging/message_port.h" +#include "third_party/blink/renderer/core/messaging/post_message_options.h" +#include "third_party/blink/renderer/core/streams/miscellaneous_operations.h" +#include "third_party/blink/renderer/core/streams/promise_handler.h" +#include "third_party/blink/renderer/core/streams/readable_stream_default_controller.h" +#include "third_party/blink/renderer/core/streams/readable_stream_native.h" +#include "third_party/blink/renderer/core/streams/stream_algorithms.h" +#include "third_party/blink/renderer/core/streams/stream_promise_resolver.h" +#include "third_party/blink/renderer/core/streams/writable_stream_default_controller.h" +#include "third_party/blink/renderer/core/streams/writable_stream_native.h" +#include "third_party/blink/renderer/platform/bindings/exception_state.h" +#include "third_party/blink/renderer/platform/bindings/script_state.h" +#include "third_party/blink/renderer/platform/bindings/v8_binding.h" +#include "third_party/blink/renderer/platform/heap/heap.h" +#include "third_party/blink/renderer/platform/heap/visitor.h" +#include "third_party/blink/renderer/platform/wtf/assertions.h" +#include "v8/include/v8.h" + +// See the design doc at +// https://docs.google.com/document/d/1_KuZzg5c3pncLJPFa8SuVm23AP4tft6mzPCL5at3I9M/edit +// for explanation of how transferable streams are constructed from the "cross +// realm identity transform" implemented in this file. + +// The peer (the other end of the MessagePort) is untrusted as it may be +// compromised. This means we have to be very careful in unpacking the messages +// from the peer. LOG(WARNING) is used for cases where a message from the peer +// appears to be invalid. If this appears during ordinary testing it indicates a +// bug. +// +// The -vmodule=transferable_streams=3 command-line argument can be used for +// debugging of the protocol. + +namespace blink { + +namespace { + +// These are the types of messages that are sent between peers. +enum class MessageType { kPull, kCancel, kChunk, kClose, kAbort, kError }; + +// These are the different ways an error reason can be encoded. +enum class ErrorType { kTypeError, kJson, kDomException, kUndefined }; + +bool IsATypeError(ScriptState* script_state, v8::Local<v8::Object> object) { + // There isn't a 100% reliable way to identify a TypeError. + return object->IsNativeError() && + object->GetConstructorName() + ->Equals(script_state->GetContext(), + V8AtomicString(script_state->GetIsolate(), "TypeError")) + .ToChecked(); +} + +bool IsADOMException(v8::Isolate* isolate, v8::Local<v8::Object> object) { + return V8DOMException::HasInstance(object, isolate); +} + +// Creates a JavaScript object with a null prototype structured like {key1: +// value2, key2: value2}. This is used to create objects to be serialized by +// postMessage. +v8::Local<v8::Object> CreateKeyValueObject(v8::Isolate* isolate, + const char* key1, + v8::Local<v8::Value> value1, + const char* key2, + v8::Local<v8::Value> value2) { + v8::Local<v8::Name> names[] = {V8AtomicString(isolate, key1), + V8AtomicString(isolate, key2)}; + v8::Local<v8::Value> values[] = {value1, value2}; + static_assert(base::size(names) == base::size(values), + "names and values arrays must be the same size"); + return v8::Object::New(isolate, v8::Null(isolate), names, values, + base::size(names)); +} + +// Unpacks an object created by CreateKeyValueObject(). |value1| and |value2| +// are out parameters. Returns false on failure. +bool UnpackKeyValueObject(ScriptState* script_state, + v8::Local<v8::Object> object, + const char* key1, + v8::Local<v8::Value>* value1, + const char* key2, + v8::Local<v8::Value>* value2) { + auto* isolate = script_state->GetIsolate(); + v8::TryCatch try_catch(isolate); + auto context = script_state->GetContext(); + if (!object->Get(context, V8AtomicString(isolate, key1)).ToLocal(value1)) { + DLOG(WARNING) << "Error reading key: '" << key1 << "'"; + return false; + } + if (!object->Get(context, V8AtomicString(isolate, key2)).ToLocal(value2)) { + DLOG(WARNING) << "Error reading key: '" << key2 << "'"; + return false; + } + return true; +} + +// Send a message with type |type| and contents |value| over |port|. The type +// will be packed as a number with key "t", and the value will be packed with +// key "v". +void PackAndPostMessage(ScriptState* script_state, + MessagePort* port, + MessageType type, + v8::Local<v8::Value> value, + ExceptionState& exception_state) { + DVLOG(3) << "PackAndPostMessage sending message type " + << static_cast<int>(type); + auto* isolate = script_state->GetIsolate(); + v8::Local<v8::Object> packed = CreateKeyValueObject( + isolate, "t", v8::Number::New(isolate, static_cast<int>(type)), "v", + value); + port->postMessage(script_state, ScriptValue(script_state, packed), + PostMessageOptions::Create(), exception_state); +} + +// Packs an error into an {e: number, s: string} object for transmission by +// postMessage. Serializing the resulting object should never fail. +v8::Local<v8::Object> PackErrorType(v8::Isolate* isolate, + ErrorType type, + v8::Local<v8::String> string) { + auto error_as_number = v8::Number::New(isolate, static_cast<int>(type)); + return CreateKeyValueObject(isolate, "e", error_as_number, "s", string); +} + +// Overload for the common case where |string| is a compile-time constant. +v8::Local<v8::Object> PackErrorType(v8::Isolate* isolate, + ErrorType type, + const char* string) { + return PackErrorType(isolate, type, V8String(isolate, string)); +} + +// We'd like to able to transfer TypeError exceptions, but we can't, so we hack +// around it. PackReason() is guaranteed to succeed and the object produced is +// guaranteed to be serializable by postMessage(), however data may be lost. It +// is not very efficient, and has fairly arbitrary semantics. +// TODO(ricea): Replace once Errors are serializable. +v8::Local<v8::Value> PackReason(ScriptState* script_state, + v8::Local<v8::Value> reason) { + auto* isolate = script_state->GetIsolate(); + auto context = script_state->GetContext(); + if (reason->IsString() || reason->IsNumber() || reason->IsBoolean()) { + v8::TryCatch try_catch(isolate); + v8::Local<v8::String> stringified; + if (!v8::JSON::Stringify(context, reason).ToLocal(&stringified)) { + return PackErrorType(isolate, ErrorType::kTypeError, + "Cannot transfer message"); + } + + return PackErrorType(isolate, ErrorType::kJson, stringified); + } + + if (reason->IsNull()) { + return PackErrorType(isolate, ErrorType::kJson, "null"); + } + + if (reason->IsFunction() || reason->IsSymbol() || !reason->IsObject()) { + // Squash to undefined + return PackErrorType(isolate, ErrorType::kUndefined, ""); + } + + if (IsATypeError(script_state, reason.As<v8::Object>())) { + v8::TryCatch try_catch(isolate); + // "message" on TypeError is a normal property, meaning that if it + // is set, it is set on the object itself. We can take advantage of + // this to avoid executing user JavaScript in the case when the + // TypeError was generated internally. + v8::Local<v8::Value> descriptor; + if (!reason.As<v8::Object>() + ->GetOwnPropertyDescriptor(context, + V8AtomicString(isolate, "message")) + .ToLocal(&descriptor)) { + return PackErrorType(isolate, ErrorType::kTypeError, + "Cannot transfer message"); + } + if (descriptor->IsUndefined()) { + return PackErrorType(isolate, ErrorType::kTypeError, ""); + } + v8::Local<v8::Value> message; + CHECK(descriptor->IsObject()); + if (!descriptor.As<v8::Object>() + ->Get(context, V8AtomicString(isolate, "value")) + .ToLocal(&message)) { + message = V8String(isolate, "Cannot transfer message"); + } else if (!message->IsString()) { + message = V8String(isolate, ""); + } + return PackErrorType(isolate, ErrorType::kTypeError, + message.As<v8::String>()); + } + + if (IsADOMException(isolate, reason.As<v8::Object>())) { + DOMException* dom_exception = + V8DOMException::ToImpl(reason.As<v8::Object>()); + String message = dom_exception->message(); + String name = dom_exception->name(); + v8::Local<v8::Value> packed = CreateKeyValueObject( + isolate, "m", V8String(isolate, message), "n", V8String(isolate, name)); + // It should be impossible for this to fail, except for out-of-memory. + v8::Local<v8::String> packed_string = + v8::JSON::Stringify(context, packed).ToLocalChecked(); + return PackErrorType(isolate, ErrorType::kDomException, packed_string); + } + + v8::TryCatch try_catch(isolate); + v8::Local<v8::Value> json; + if (!v8::JSON::Stringify(context, reason).ToLocal(&json)) { + return PackErrorType(isolate, ErrorType::kTypeError, + "Cannot transfer message"); + } + + return PackErrorType(isolate, ErrorType::kJson, json.As<v8::String>()); +} + +// Converts an object created by PackReason() back into a clone of the original +// object, minus any data that was discarded by PackReason(). +bool UnpackReason(ScriptState* script_state, + v8::Local<v8::Value> packed_reason, + v8::Local<v8::Value>* reason) { + // We need to be robust against malformed input because it could come from a + // compromised renderer. + if (!packed_reason->IsObject()) { + DLOG(WARNING) << "packed_reason is not an object"; + return false; + } + + v8::Local<v8::Value> encoder_value; + v8::Local<v8::Value> string_value; + if (!UnpackKeyValueObject(script_state, packed_reason.As<v8::Object>(), "e", + &encoder_value, "s", &string_value)) { + return false; + } + + if (!encoder_value->IsNumber()) { + DLOG(WARNING) << "encoder_value is not a number"; + return false; + } + + int encoder = encoder_value.As<v8::Number>()->Value(); + if (!string_value->IsString()) { + DLOG(WARNING) << "string_value is not a string"; + return false; + } + + v8::Local<v8::String> string = string_value.As<v8::String>(); + auto* isolate = script_state->GetIsolate(); + auto context = script_state->GetContext(); + switch (static_cast<ErrorType>(encoder)) { + case ErrorType::kJson: { + v8::TryCatch try_catch(isolate); + if (!v8::JSON::Parse(context, string).ToLocal(reason)) { + DLOG(WARNING) << "JSON Parse failed. Content: " << ToCoreString(string); + return false; + } + return true; + } + + case ErrorType::kTypeError: + *reason = v8::Exception::TypeError(string); + return true; + + case ErrorType::kDomException: { + v8::TryCatch try_catch(isolate); + v8::Local<v8::Value> packed_exception; + if (!v8::JSON::Parse(context, string).ToLocal(&packed_exception)) { + DLOG(WARNING) << "Packed DOMException JSON parse failed"; + return false; + } + + if (!packed_exception->IsObject()) { + DLOG(WARNING) << "Packed DOMException is not an object"; + return false; + } + + v8::Local<v8::Value> message; + v8::Local<v8::Value> name; + if (!UnpackKeyValueObject(script_state, packed_exception.As<v8::Object>(), + "m", &message, "n", &name)) { + DLOG(WARNING) << "Failed unpacking packed DOMException"; + return false; + } + + if (!message->IsString()) { + DLOG(WARNING) << "DOMException message is not a string"; + return false; + } + + if (!name->IsString()) { + DLOG(WARNING) << "DOMException name is not a string"; + return false; + } + + auto ToBlink = [](v8::Local<v8::Value> value) { + return ToBlinkString<String>(value.As<v8::String>(), kDoNotExternalize); + }; + *reason = ToV8(DOMException::Create(ToBlink(message), ToBlink(name)), + script_state); + return true; + } + + case ErrorType::kUndefined: + *reason = v8::Undefined(isolate); + return true; + + default: + DLOG(WARNING) << "Invalid ErrorType: " << encoder; + return false; + } +} + +// Base class for CrossRealmTransformWritable and CrossRealmTransformReadable. +// Contains common methods that are used when handling MessagePort events. +class CrossRealmTransformStream + : public GarbageCollected<CrossRealmTransformStream> { + public: + // Neither of the subclasses require finalization, so no destructor. + + virtual ScriptState* GetScriptState() const = 0; + virtual MessagePort* GetMessagePort() const = 0; + + // HandleMessage() is called by CrossRealmTransformMessageListener to handle + // an incoming message from the MessagePort. + virtual void HandleMessage(MessageType type, v8::Local<v8::Value> value) = 0; + + // HandleError() is called by CrossRealmTransformErrorListener when an error + // event is fired on the message port. It should error the stream. + virtual void HandleError(v8::Local<v8::Value> error) = 0; + + virtual void Trace(Visitor*) {} +}; + +// Handles MessageEvents from the MessagePort. +class CrossRealmTransformMessageListener final : public NativeEventListener { + public: + explicit CrossRealmTransformMessageListener(CrossRealmTransformStream* target) + : target_(target) {} + + void Invoke(ExecutionContext*, Event* event) override { + // TODO(ricea): Find a way to guarantee this cast is safe. + MessageEvent* message = static_cast<MessageEvent*>(event); + ScriptState* script_state = target_->GetScriptState(); + // The deserializer code called by message->data() looks up the ScriptState + // from the current context, so we need to make sure it is set. + ScriptState::Scope scope(script_state); + v8::Local<v8::Value> data = message->data(script_state).V8Value(); + if (!data->IsObject()) { + DLOG(WARNING) << "Invalid message from peer ignored (not object)"; + return; + } + + v8::Local<v8::Value> type; + v8::Local<v8::Value> value; + if (!UnpackKeyValueObject(script_state, data.As<v8::Object>(), "t", &type, + "v", &value)) { + DLOG(WARNING) << "Invalid message from peer ignored"; + return; + } + + if (!type->IsNumber()) { + DLOG(WARNING) << "Invalid message from peer ignored (type is not number)"; + return; + } + + int type_value = type.As<v8::Number>()->Value(); + DVLOG(3) << "MessageListener saw message type " << type_value; + target_->HandleMessage(static_cast<MessageType>(type_value), value); + } + + void Trace(Visitor* visitor) override { + visitor->Trace(target_); + NativeEventListener::Trace(visitor); + } + + private: + const Member<CrossRealmTransformStream> target_; +}; + +// Handles "error" events from the MessagePort. +class CrossRealmTransformErrorListener final : public NativeEventListener { + public: + explicit CrossRealmTransformErrorListener(CrossRealmTransformStream* target) + : target_(target) {} + + void Invoke(ExecutionContext*, Event*) override { + ScriptState* script_state = target_->GetScriptState(); + const auto* error = + DOMException::Create("chunk could not be cloned", "DataCloneError"); + auto* message_port = target_->GetMessagePort(); + v8::Local<v8::Value> error_value = ToV8(error, script_state); + ExceptionState exception_state(script_state->GetIsolate(), + ExceptionState::kUnknownContext, "", ""); + + PackAndPostMessage(script_state, message_port, MessageType::kError, + PackReason(script_state, error_value), exception_state); + if (exception_state.HadException()) { + DLOG(WARNING) << "Ignoring postMessage failure in error listener"; + exception_state.ClearException(); + } + + message_port->close(); + target_->HandleError(error_value); + } + + void Trace(Visitor* visitor) override { + visitor->Trace(target_); + NativeEventListener::Trace(visitor); + } + + private: + const Member<CrossRealmTransformStream> target_; +}; + +// Class for data associated with the writable side of the cross realm transform +// stream. +class CrossRealmTransformWritable final : public CrossRealmTransformStream { + public: + CrossRealmTransformWritable(ScriptState* script_state, MessagePort* port) + : script_state_(script_state), + message_port_(port), + backpressure_promise_( + MakeGarbageCollected<StreamPromiseResolver>(script_state)) {} + + WritableStreamNative* CreateWritableStream(ExceptionState&); + + ScriptState* GetScriptState() const override { return script_state_; } + MessagePort* GetMessagePort() const override { return message_port_; } + void HandleMessage(MessageType type, v8::Local<v8::Value> value) override; + void HandleError(v8::Local<v8::Value> error) override; + + void Trace(Visitor* visitor) override { + visitor->Trace(script_state_); + visitor->Trace(message_port_); + visitor->Trace(backpressure_promise_); + visitor->Trace(controller_); + CrossRealmTransformStream::Trace(visitor); + } + + private: + class WriteAlgorithm; + class CloseAlgorithm; + class AbortAlgorithm; + + const Member<ScriptState> script_state_; + const Member<MessagePort> message_port_; + Member<StreamPromiseResolver> backpressure_promise_; + Member<WritableStreamDefaultController> controller_; +}; + +class CrossRealmTransformWritable::WriteAlgorithm final + : public StreamAlgorithm { + public: + explicit WriteAlgorithm(CrossRealmTransformWritable* writable) + : writable_(writable) {} + + // Sends the chunk to the readable side, possibly after waiting for + // backpressure. + v8::Local<v8::Promise> Run(ScriptState* script_state, + int argc, + v8::Local<v8::Value> argv[]) override { + DCHECK_EQ(argc, 1); + auto chunk = argv[0]; + + if (!writable_->backpressure_promise_) { + return DoWrite(script_state, chunk); + } + + auto* isolate = script_state->GetIsolate(); + return StreamThenPromise( + script_state->GetContext(), + writable_->backpressure_promise_->V8Promise(isolate), + MakeGarbageCollected<DoWriteOnResolve>(script_state, chunk, this)); + } + + void Trace(Visitor* visitor) override { + visitor->Trace(writable_); + StreamAlgorithm::Trace(visitor); + } + + private: + // A promise handler which calls DoWrite() when the promise resolves. + class DoWriteOnResolve final : public PromiseHandlerWithValue { + public: + DoWriteOnResolve(ScriptState* script_state, + v8::Local<v8::Value> chunk, + WriteAlgorithm* target) + : PromiseHandlerWithValue(script_state), + chunk_(script_state->GetIsolate(), chunk), + target_(target) {} + + v8::Local<v8::Value> CallWithLocal(v8::Local<v8::Value>) override { + ScriptState* script_state = GetScriptState(); + return target_->DoWrite(script_state, + chunk_.NewLocal(script_state->GetIsolate())); + } + + void Trace(Visitor* visitor) override { + visitor->Trace(chunk_); + visitor->Trace(target_); + PromiseHandlerWithValue::Trace(visitor); + } + + private: + const TraceWrapperV8Reference<v8::Value> chunk_; + const Member<WriteAlgorithm> target_; + }; + + // Sends a chunk over the message port to the readable side. + v8::Local<v8::Promise> DoWrite(ScriptState* script_state, + v8::Local<v8::Value> chunk) { + writable_->backpressure_promise_ = + MakeGarbageCollected<StreamPromiseResolver>(script_state); + ExceptionState exception_state(script_state->GetIsolate(), + ExceptionState::kUnknownContext, "", ""); + PackAndPostMessage(script_state, writable_->message_port_, + MessageType::kChunk, chunk, exception_state); + if (exception_state.HadException()) { + auto exception = exception_state.GetException(); + exception_state.ClearException(); + + PackAndPostMessage( + script_state, writable_->message_port_, MessageType::kError, + PackReason(writable_->script_state_, exception), exception_state); + if (exception_state.HadException()) { + DLOG(WARNING) << "Disregarding exception while sending error"; + exception_state.ClearException(); + } + + writable_->message_port_->close(); + return PromiseReject(script_state, exception); + } + + return PromiseResolveWithUndefined(script_state); + } + + const Member<CrossRealmTransformWritable> writable_; +}; + +class CrossRealmTransformWritable::CloseAlgorithm final + : public StreamAlgorithm { + public: + explicit CloseAlgorithm(CrossRealmTransformWritable* writable) + : writable_(writable) {} + + // Sends a close message to the readable side and closes the message port. + v8::Local<v8::Promise> Run(ScriptState* script_state, + int argc, + v8::Local<v8::Value> argv[]) override { + DCHECK_EQ(argc, 0); + ExceptionState exception_state(script_state->GetIsolate(), + ExceptionState::kUnknownContext, "", ""); + PackAndPostMessage( + script_state, writable_->message_port_, MessageType::kClose, + v8::Undefined(script_state->GetIsolate()), exception_state); + if (exception_state.HadException()) { + DLOG(WARNING) << "Ignoring exception from PackAndPostMessage kClose"; + exception_state.ClearException(); + } + + writable_->message_port_->close(); + return PromiseResolveWithUndefined(script_state); + } + + void Trace(Visitor* visitor) override { + visitor->Trace(writable_); + StreamAlgorithm::Trace(visitor); + } + + private: + const Member<CrossRealmTransformWritable> writable_; +}; + +class CrossRealmTransformWritable::AbortAlgorithm final + : public StreamAlgorithm { + public: + explicit AbortAlgorithm(CrossRealmTransformWritable* writable) + : writable_(writable) {} + + // Sends an abort message to the readable side and closes the message port. + v8::Local<v8::Promise> Run(ScriptState* script_state, + int argc, + v8::Local<v8::Value> argv[]) override { + DCHECK_EQ(argc, 1); + auto reason = argv[0]; + ExceptionState exception_state(script_state->GetIsolate(), + ExceptionState::kUnknownContext, "", ""); + PackAndPostMessage( + script_state, writable_->message_port_, MessageType::kAbort, + PackReason(writable_->script_state_, reason), exception_state); + if (exception_state.HadException()) { + DLOG(WARNING) << "Ignoring exception from PackAndPostMessage kAbort"; + exception_state.ClearException(); + } + writable_->message_port_->close(); + return PromiseResolveWithUndefined(script_state); + } + + void Trace(Visitor* visitor) override { + visitor->Trace(writable_); + StreamAlgorithm::Trace(visitor); + } + + private: + const Member<CrossRealmTransformWritable> writable_; +}; + +WritableStreamNative* CrossRealmTransformWritable::CreateWritableStream( + ExceptionState& exception_state) { + DCHECK(!controller_) << "CreateWritableStream() can only be called once"; + + message_port_->setOnmessage( + MakeGarbageCollected<CrossRealmTransformMessageListener>(this)); + message_port_->setOnmessageerror( + MakeGarbageCollected<CrossRealmTransformErrorListener>(this)); + + auto* stream = WritableStreamNative::Create( + script_state_, CreateTrivialStartAlgorithm(), + MakeGarbageCollected<WriteAlgorithm>(this), + MakeGarbageCollected<CloseAlgorithm>(this), + MakeGarbageCollected<AbortAlgorithm>(this), 1, + CreateDefaultSizeAlgorithm(), exception_state); + + if (exception_state.HadException()) { + return nullptr; + } + + controller_ = stream->Controller(); + return stream; +} + +void CrossRealmTransformWritable::HandleMessage(MessageType type, + v8::Local<v8::Value> value) { + switch (type) { + case MessageType::kPull: + DCHECK(backpressure_promise_); + backpressure_promise_->ResolveWithUndefined(script_state_); + backpressure_promise_ = nullptr; + return; + + case MessageType::kCancel: + case MessageType::kError: { + v8::Local<v8::Value> reason; + if (!UnpackReason(script_state_, value, &reason)) { + DLOG(WARNING) + << "Invalid message from peer ignored (unable to unpack value)"; + return; + } + WritableStreamDefaultController::ErrorIfNeeded(script_state_, controller_, + reason); + if (backpressure_promise_) { + backpressure_promise_->ResolveWithUndefined(script_state_); + backpressure_promise_ = nullptr; + } + return; + } + + default: + DLOG(WARNING) << "Invalid message from peer ignored (invalid type): " + << static_cast<int>(type); + return; + } +} + +void CrossRealmTransformWritable::HandleError(v8::Local<v8::Value> error) { + WritableStreamDefaultController::ErrorIfNeeded(script_state_, controller_, + error); +} + +// Class for data associated with the readable side of the cross realm transform +// stream. +class CrossRealmTransformReadable final : public CrossRealmTransformStream { + public: + CrossRealmTransformReadable(ScriptState* script_state, MessagePort* port) + : script_state_(script_state), + message_port_(port), + backpressure_promise_( + MakeGarbageCollected<StreamPromiseResolver>(script_state)) {} + + ReadableStreamNative* CreateReadableStream(ExceptionState&); + + ScriptState* GetScriptState() const override { return script_state_; } + MessagePort* GetMessagePort() const override { return message_port_; } + void HandleMessage(MessageType type, v8::Local<v8::Value> value) override; + void HandleError(v8::Local<v8::Value> error) override; + + void Trace(Visitor* visitor) override { + visitor->Trace(script_state_); + visitor->Trace(message_port_); + visitor->Trace(backpressure_promise_); + visitor->Trace(controller_); + CrossRealmTransformStream::Trace(visitor); + } + + private: + class PullAlgorithm; + class CancelAlgorithm; + + const Member<ScriptState> script_state_; + const Member<MessagePort> message_port_; + Member<StreamPromiseResolver> backpressure_promise_; + Member<ReadableStreamDefaultController> controller_; + bool finished_ = false; +}; + +class CrossRealmTransformReadable::PullAlgorithm final + : public StreamAlgorithm { + public: + explicit PullAlgorithm(CrossRealmTransformReadable* readable) + : readable_(readable) {} + + // Sends a pull message to the writable side and then waits for backpressure + // to clear. + v8::Local<v8::Promise> Run(ScriptState* script_state, + int argc, + v8::Local<v8::Value> argv[]) override { + DCHECK_EQ(argc, 0); + auto* isolate = script_state->GetIsolate(); + ExceptionState exception_state(isolate, ExceptionState::kUnknownContext, "", + ""); + + PackAndPostMessage( + script_state, readable_->message_port_, MessageType::kPull, + v8::Undefined(script_state->GetIsolate()), exception_state); + if (exception_state.HadException()) { + DLOG(WARNING) << "Ignoring exception from PackAndPostMessage kClose"; + exception_state.ClearException(); + } + + return readable_->backpressure_promise_->V8Promise(isolate); + } + + void Trace(Visitor* visitor) override { + visitor->Trace(readable_); + StreamAlgorithm::Trace(visitor); + } + + private: + const Member<CrossRealmTransformReadable> readable_; +}; + +class CrossRealmTransformReadable::CancelAlgorithm final + : public StreamAlgorithm { + public: + explicit CancelAlgorithm(CrossRealmTransformReadable* readable) + : readable_(readable) {} + + // Sends a cancel message to the writable side and closes the message port. + v8::Local<v8::Promise> Run(ScriptState* script_state, + int argc, + v8::Local<v8::Value> argv[]) override { + DCHECK_EQ(argc, 1); + auto reason = argv[0]; + readable_->finished_ = true; + ExceptionState exception_state(script_state->GetIsolate(), + ExceptionState::kUnknownContext, "", ""); + + PackAndPostMessage(script_state, readable_->message_port_, + MessageType::kCancel, PackReason(script_state, reason), + exception_state); + if (exception_state.HadException()) { + DLOG(WARNING) << "Ignoring exception from PackAndPostMessage kClose"; + exception_state.ClearException(); + } + + readable_->message_port_->close(); + return PromiseResolveWithUndefined(script_state); + } + + void Trace(Visitor* visitor) override { + visitor->Trace(readable_); + StreamAlgorithm::Trace(visitor); + } + + private: + const Member<CrossRealmTransformReadable> readable_; +}; + +ReadableStreamNative* CrossRealmTransformReadable::CreateReadableStream( + ExceptionState& exception_state) { + DCHECK(!controller_) << "CreateReadableStream can only be called once"; + + message_port_->setOnmessage( + MakeGarbageCollected<CrossRealmTransformMessageListener>(this)); + message_port_->setOnmessageerror( + MakeGarbageCollected<CrossRealmTransformErrorListener>(this)); + + auto* stream = ReadableStreamNative::Create( + script_state_, CreateTrivialStartAlgorithm(), + MakeGarbageCollected<PullAlgorithm>(this), + MakeGarbageCollected<CancelAlgorithm>(this), + /* highWaterMark = */ 0, CreateDefaultSizeAlgorithm(), exception_state); + + if (exception_state.HadException()) { + return nullptr; + } + + controller_ = stream->GetController(); + return stream; +} + +void CrossRealmTransformReadable::HandleMessage(MessageType type, + v8::Local<v8::Value> value) { + switch (type) { + case MessageType::kChunk: { + // This can't throw because we always use the default strategy size + // algorithm, which doesn't throw, and always returns a valid value of + // 1.0. + ReadableStreamDefaultController::Enqueue(script_state_, controller_, + value, ASSERT_NO_EXCEPTION); + + backpressure_promise_->ResolveWithUndefined(script_state_); + backpressure_promise_ = + MakeGarbageCollected<StreamPromiseResolver>(script_state_); + return; + } + + case MessageType::kClose: + finished_ = true; + ReadableStreamDefaultController::Close(script_state_, controller_); + message_port_->close(); + return; + + case MessageType::kAbort: + case MessageType::kError: { + finished_ = true; + v8::Local<v8::Value> reason; + if (!UnpackReason(script_state_, value, &reason)) { + DLOG(WARNING) + << "Invalid message from peer ignored (unable to unpack value)"; + return; + } + + ReadableStreamDefaultController::Error(script_state_, controller_, + reason); + message_port_->close(); + return; + } + + default: + DLOG(WARNING) << "Invalid message from peer ignored (invalid type): " + << static_cast<int>(type); + return; + } +} + +void CrossRealmTransformReadable::HandleError(v8::Local<v8::Value> error) { + ReadableStreamDefaultController::Error(script_state_, controller_, error); +} + +} // namespace + +CORE_EXPORT WritableStreamNative* CreateCrossRealmTransformWritable( + ScriptState* script_state, + MessagePort* port, + ExceptionState& exception_state) { + return MakeGarbageCollected<CrossRealmTransformWritable>(script_state, port) + ->CreateWritableStream(exception_state); +} + +CORE_EXPORT ReadableStreamNative* CreateCrossRealmTransformReadable( + ScriptState* script_state, + MessagePort* port, + ExceptionState& exception_state) { + return MakeGarbageCollected<CrossRealmTransformReadable>(script_state, port) + ->CreateReadableStream(exception_state); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/core/streams/transferable_streams.h b/third_party/blink/renderer/core/streams/transferable_streams.h new file mode 100644 index 0000000..62883f1 --- /dev/null +++ b/third_party/blink/renderer/core/streams/transferable_streams.h
@@ -0,0 +1,37 @@ +// 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. + +// Functions used to build transferable streams. + +#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_TRANSFERABLE_STREAMS_H_ +#define THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_TRANSFERABLE_STREAMS_H_ + +#include "third_party/blink/renderer/core/core_export.h" + +namespace blink { + +class ExceptionState; +class MessagePort; +class ReadableStreamNative; +class ScriptState; +class WritableStreamNative; + +// Creates the writable side of a cross-realm identity transform stream, using +// |port| for communication. |port| must be entangled with another MessagePort +// which is passed to CreateCrossRealmTransformReadable(). +CORE_EXPORT WritableStreamNative* CreateCrossRealmTransformWritable( + ScriptState*, + MessagePort* port, + ExceptionState&); + +// Creates the readable side of a cross-realm identity transform stream. |port| +// is used symmetrically with CreateCrossRealmTransformWritable(). +CORE_EXPORT ReadableStreamNative* CreateCrossRealmTransformReadable( + ScriptState*, + MessagePort* port, + ExceptionState&); + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_TRANSFERABLE_STREAMS_H_
diff --git a/third_party/blink/renderer/core/streams/transferable_streams_test.cc b/third_party/blink/renderer/core/streams/transferable_streams_test.cc new file mode 100644 index 0000000..3811b05 --- /dev/null +++ b/third_party/blink/renderer/core/streams/transferable_streams_test.cc
@@ -0,0 +1,129 @@ +// 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 "third_party/blink/renderer/core/streams/transferable_streams.h" + +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/renderer/bindings/core/v8/script_function.h" +#include "third_party/blink/renderer/bindings/core/v8/script_promise.h" +#include "third_party/blink/renderer/bindings/core/v8/script_value.h" +#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h" +#include "third_party/blink/renderer/bindings/core/v8/v8_iterator_result_value.h" +#include "third_party/blink/renderer/bindings/core/v8/v8_readable_stream_default_reader.h" +#include "third_party/blink/renderer/bindings/core/v8/v8_writable_stream_default_writer.h" +#include "third_party/blink/renderer/core/messaging/message_channel.h" +#include "third_party/blink/renderer/core/streams/readable_stream_default_reader.h" +#include "third_party/blink/renderer/core/streams/readable_stream_native.h" +#include "third_party/blink/renderer/core/streams/writable_stream_default_writer.h" +#include "third_party/blink/renderer/core/streams/writable_stream_native.h" +#include "third_party/blink/renderer/platform/bindings/exception_state.h" +#include "third_party/blink/renderer/platform/heap/heap.h" +#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h" + +namespace blink { + +namespace { + +// We only do minimal testing here. The functionality of transferable streams is +// tested in the layout tests. +TEST(TransferableStreamsTest, SmokeTest) { + V8TestingScope scope; + + auto* channel = + MakeGarbageCollected<MessageChannel>(scope.GetExecutionContext()); + auto* script_state = scope.GetScriptState(); + auto* writable = CreateCrossRealmTransformWritable( + script_state, channel->port1(), ASSERT_NO_EXCEPTION); + ASSERT_TRUE(writable); + auto* readable = CreateCrossRealmTransformReadable( + script_state, channel->port2(), ASSERT_NO_EXCEPTION); + ASSERT_TRUE(readable); + + auto* writer = V8WritableStreamDefaultWriter::ToImpl( + writable->getWriter(script_state, ASSERT_NO_EXCEPTION) + .V8Value() + .As<v8::Object>()); + auto* reader = V8ReadableStreamDefaultReader::ToImpl( + readable->getReader(script_state, ASSERT_NO_EXCEPTION) + .V8Value() + .As<v8::Object>()); + + writer->write(script_state, ScriptValue::CreateNull(script_state)); + + class ExpectNullResponse : public ScriptFunction { + public: + static v8::Local<v8::Function> Create(ScriptState* script_state, + bool* got_response) { + auto* self = + MakeGarbageCollected<ExpectNullResponse>(script_state, got_response); + return self->BindToV8Function(); + } + + ExpectNullResponse(ScriptState* script_state, bool* got_response) + : ScriptFunction(script_state), got_response_(got_response) {} + + private: + ScriptValue Call(ScriptValue value) override { + *got_response_ = true; + if (!value.IsObject()) { + ADD_FAILURE() << "iterator must be an object"; + return ScriptValue(); + } + bool done = false; + auto* script_state = GetScriptState(); + auto chunk_maybe = + V8UnpackIteratorResult(script_state, + value.V8Value() + ->ToObject(script_state->GetContext()) + .ToLocalChecked(), + &done); + EXPECT_FALSE(done); + v8::Local<v8::Value> chunk; + if (!chunk_maybe.ToLocal(&chunk)) { + ADD_FAILURE() << "V8UnpackIteratorResult failed"; + return ScriptValue(); + } + EXPECT_TRUE(chunk->IsNull()); + return ScriptValue(); + } + + bool* got_response_; + }; + + // TODO(ricea): This is copy-and-pasted from transform_stream_test.cc. Put it + // in a shared location. + class ExpectNotReached : public ScriptFunction { + public: + static v8::Local<v8::Function> Create(ScriptState* script_state) { + auto* self = MakeGarbageCollected<ExpectNotReached>(script_state); + return self->BindToV8Function(); + } + + explicit ExpectNotReached(ScriptState* script_state) + : ScriptFunction(script_state) {} + + private: + ScriptValue Call(ScriptValue) override { + ADD_FAILURE() << "ExpectNotReached was reached"; + return ScriptValue(); + } + }; + + bool got_response = false; + reader->read(script_state) + .Then(ExpectNullResponse::Create(script_state, &got_response), + ExpectNotReached::Create(script_state)); + + // Need to run the event loop to pass messages through the MessagePort. + test::RunPendingTasks(); + + // Resolve promises. + v8::MicrotasksScope::PerformCheckpoint(scope.GetIsolate()); + + EXPECT_TRUE(got_response); +} + +} // namespace + +} // namespace blink
diff --git a/third_party/blink/renderer/core/streams/writable_stream.cc b/third_party/blink/renderer/core/streams/writable_stream.cc index da3db6e..3d6f944 100644 --- a/third_party/blink/renderer/core/streams/writable_stream.cc +++ b/third_party/blink/renderer/core/streams/writable_stream.cc
@@ -57,7 +57,10 @@ WritableStream* WritableStream::Deserialize(ScriptState* script_state, MessagePort* port, ExceptionState& exception_state) { - // TODO(ricea): Switch on Blink feature. + if (RuntimeEnabledFeatures::StreamsNativeEnabled()) { + return WritableStreamNative::Deserialize(script_state, port, + exception_state); + } return WritableStreamWrapper::Deserialize(script_state, port, exception_state); }
diff --git a/third_party/blink/renderer/core/streams/writable_stream_default_writer.h b/third_party/blink/renderer/core/streams/writable_stream_default_writer.h index 1bb5bea..fbe239e 100644 --- a/third_party/blink/renderer/core/streams/writable_stream_default_writer.h +++ b/third_party/blink/renderer/core/streams/writable_stream_default_writer.h
@@ -6,6 +6,7 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_WRITABLE_STREAM_DEFAULT_WRITER_H_ #include "base/optional.h" +#include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "v8/include/v8.h" @@ -21,7 +22,7 @@ class WritableStreamNative; // https://streams.spec.whatwg.org/#default-writer-class -class WritableStreamDefaultWriter final : public ScriptWrappable { +class CORE_EXPORT WritableStreamDefaultWriter final : public ScriptWrappable { DEFINE_WRAPPERTYPEINFO(); public:
diff --git a/third_party/blink/renderer/core/streams/writable_stream_native.cc b/third_party/blink/renderer/core/streams/writable_stream_native.cc index 262a9833..c0ee787 100644 --- a/third_party/blink/renderer/core/streams/writable_stream_native.cc +++ b/third_party/blink/renderer/core/streams/writable_stream_native.cc
@@ -7,7 +7,9 @@ #include "third_party/blink/renderer/bindings/core/v8/script_value.h" #include "third_party/blink/renderer/core/streams/miscellaneous_operations.h" #include "third_party/blink/renderer/core/streams/promise_handler.h" +#include "third_party/blink/renderer/core/streams/readable_stream_native.h" #include "third_party/blink/renderer/core/streams/stream_promise_resolver.h" +#include "third_party/blink/renderer/core/streams/transferable_streams.h" #include "third_party/blink/renderer/core/streams/writable_stream_default_controller.h" #include "third_party/blink/renderer/core/streams/writable_stream_default_writer.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" @@ -215,6 +217,41 @@ return stream; } +void WritableStreamNative::Serialize(ScriptState* script_state, + MessagePort* port, + ExceptionState& exception_state) { + if (IsLocked(this)) { + exception_state.ThrowTypeError("Cannot transfer a locked stream"); + return; + } + + auto* readable = + CreateCrossRealmTransformReadable(script_state, port, exception_state); + if (exception_state.HadException()) { + return; + } + + auto promise = ReadableStreamNative::PipeTo( + script_state, readable, this, ReadableStreamNative::PipeOptions()); + promise.MarkAsHandled(); +} + +WritableStreamNative* WritableStreamNative::Deserialize( + ScriptState* script_state, + MessagePort* port, + ExceptionState& exception_state) { + // We need to execute JavaScript to call "Then" on v8::Promises. We will not + // run author code. + v8::Isolate::AllowJavascriptExecutionScope allow_js( + script_state->GetIsolate()); + auto* writable = + CreateCrossRealmTransformWritable(script_state, port, exception_state); + if (exception_state.HadException()) { + return nullptr; + } + return writable; +} + WritableStreamDefaultWriter* WritableStreamNative::AcquireDefaultWriter( ScriptState* script_state, WritableStreamNative* stream,
diff --git a/third_party/blink/renderer/core/streams/writable_stream_native.h b/third_party/blink/renderer/core/streams/writable_stream_native.h index 64f80fc2..e1848c6 100644 --- a/third_party/blink/renderer/core/streams/writable_stream_native.h +++ b/third_party/blink/renderer/core/streams/writable_stream_native.h
@@ -83,9 +83,11 @@ return stream->writer_; } - void Serialize(ScriptState*, MessagePort*, ExceptionState&) override { - // TODO(ricea): Implement this. - } + void Serialize(ScriptState*, MessagePort*, ExceptionState&) override; + + static WritableStreamNative* Deserialize(ScriptState*, + MessagePort*, + ExceptionState&); // // Methods used by ReadableStreamNative::PipeTo
diff --git a/third_party/blink/renderer/core/streams/writable_stream_test.cc b/third_party/blink/renderer/core/streams/writable_stream_test.cc index 5401cc7..e87946d1 100644 --- a/third_party/blink/renderer/core/streams/writable_stream_test.cc +++ b/third_party/blink/renderer/core/streams/writable_stream_test.cc
@@ -60,12 +60,6 @@ } TEST_P(WritableStreamTest, Serialize) { - // Disable the test when StreamsNative is enabled as WritableStreamNative - // doesn't support serialization yet. - // TODO(ricea): Re-enable this test when serialization is supported. - if (GetParam()) - return; - ScopedTransferableStreamsForTest enable_transferable_streams(true); V8TestingScope scope;
diff --git a/third_party/blink/renderer/core/svg/unsafe_svg_attribute_sanitization_test.cc b/third_party/blink/renderer/core/svg/unsafe_svg_attribute_sanitization_test.cc index b49eeeb7..20a4843 100644 --- a/third_party/blink/renderer/core/svg/unsafe_svg_attribute_sanitization_test.cc +++ b/third_party/blink/renderer/core/svg/unsafe_svg_attribute_sanitization_test.cc
@@ -95,11 +95,11 @@ EXPECT_TRUE(sanitized_content.Contains("</a>")) << "We should have pasted *something*; the document is: " - << sanitized_content.Utf8().data(); + << sanitized_content.Utf8(); EXPECT_FALSE(sanitized_content.Contains(":alert()")) << "The JavaScript URL is unsafe and should have been stripped; " "instead: " - << sanitized_content.Utf8().data(); + << sanitized_content.Utf8(); } TEST(UnsafeSVGAttributeSanitizationTest, @@ -116,11 +116,11 @@ EXPECT_TRUE(sanitized_content.Contains("</a>")) << "We should have pasted *something*; the document is: " - << sanitized_content.Utf8().data(); + << sanitized_content.Utf8(); EXPECT_FALSE(sanitized_content.Contains(":alert()")) << "The JavaScript URL is unsafe and should have been stripped; " "instead: " - << sanitized_content.Utf8().data(); + << sanitized_content.Utf8(); } TEST(UnsafeSVGAttributeSanitizationTest, @@ -136,11 +136,11 @@ EXPECT_TRUE(sanitized_content.Contains("</a>")) << "We should have pasted *something*; the document is: " - << sanitized_content.Utf8().data(); + << sanitized_content.Utf8(); EXPECT_FALSE(sanitized_content.Contains(":alert()")) << "The JavaScript URL is unsafe and should have been stripped; " "instead: " - << sanitized_content.Utf8().data(); + << sanitized_content.Utf8(); } TEST(UnsafeSVGAttributeSanitizationTest, @@ -157,11 +157,11 @@ EXPECT_TRUE(sanitized_content.Contains("</a>")) << "We should have pasted *something*; the document is: " - << sanitized_content.Utf8().data(); + << sanitized_content.Utf8(); EXPECT_FALSE(sanitized_content.Contains(":alert()")) << "The JavaScript URL is unsafe and should have been stripped; " "instead: " - << sanitized_content.Utf8().data(); + << sanitized_content.Utf8(); } TEST(UnsafeSVGAttributeSanitizationTest, @@ -177,11 +177,11 @@ EXPECT_TRUE(sanitized_content.Contains("</a>")) << "We should have pasted *something*; the document is: " - << sanitized_content.Utf8().data(); + << sanitized_content.Utf8(); EXPECT_FALSE(sanitized_content.Contains(":alert()")) << "The JavaScript URL is unsafe and should have been stripped; " "instead: " - << sanitized_content.Utf8().data(); + << sanitized_content.Utf8(); } TEST( @@ -199,11 +199,11 @@ EXPECT_TRUE(sanitized_content.Contains("</a>")) << "We should have pasted *something*; the document is: " - << sanitized_content.Utf8().data(); + << sanitized_content.Utf8(); EXPECT_FALSE(sanitized_content.Contains(":alert()")) << "The JavaScript URL is unsafe and should have been stripped; " "instead: " - << sanitized_content.Utf8().data(); + << sanitized_content.Utf8(); } // Other sanitization integration tests are web tests that use @@ -226,11 +226,11 @@ EXPECT_TRUE(sanitized_content.Contains("<a href=\"https://www.goo")) << "We should have pasted *something*; the document is: " - << sanitized_content.Utf8().data(); + << sanitized_content.Utf8(); EXPECT_FALSE(sanitized_content.Contains(":alert()")) << "The JavaScript URL is unsafe and should have been stripped; " "instead: " - << sanitized_content.Utf8().data(); + << sanitized_content.Utf8(); } TEST( @@ -252,11 +252,11 @@ EXPECT_TRUE(sanitized_content.Contains("<a xlink:href=\"https://www.goo")) << "We should have pasted *something*; the document is: " - << sanitized_content.Utf8().data(); + << sanitized_content.Utf8(); EXPECT_FALSE(sanitized_content.Contains(":alert()")) << "The JavaScript URL is unsafe and should have been stripped; " "instead: " - << sanitized_content.Utf8().data(); + << sanitized_content.Utf8(); } // Unit tests
diff --git a/third_party/blink/renderer/core/testing/internals.cc b/third_party/blink/renderer/core/testing/internals.cc index 6f5c9c28..841073f 100644 --- a/third_party/blink/renderer/core/testing/internals.cc +++ b/third_party/blink/renderer/core/testing/internals.cc
@@ -486,7 +486,7 @@ ScriptPromiseResolver* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); ScriptPromise promise = resolver->Promise(); - KURL resource_url = url_test_helpers::ToKURL(url.Utf8().data()); + KURL resource_url = url_test_helpers::ToKURL(url.Utf8()); DCHECK(document); auto callback = WTF::Bind(&Internals::ResolveResourcePriority, @@ -513,10 +513,10 @@ if (!document) return String(); Resource* resource = document->Fetcher()->AllResources().at( - url_test_helpers::ToKURL(url.Utf8().data())); + url_test_helpers::ToKURL(url.Utf8())); if (!resource) return String(); - return resource->GetResourceRequest().HttpHeaderField(header.Utf8().data()); + return resource->GetResourceRequest().HttpHeaderField(AtomicString(header)); } bool Internals::isValidContentSelect(Element* insertion_point, @@ -2317,7 +2317,7 @@ return String(); } - return PrintContext::PageProperty(GetFrame(), property_name.Utf8().data(), + return PrintContext::PageProperty(GetFrame(), property_name.Utf8().c_str(), page_number); }
diff --git a/third_party/blink/renderer/core/testing/page_test_base.cc b/third_party/blink/renderer/core/testing/page_test_base.cc index f2ab10fb..cd8f8ff6 100644 --- a/third_party/blink/renderer/core/testing/page_test_base.cc +++ b/third_party/blink/renderer/core/testing/page_test_base.cc
@@ -105,12 +105,12 @@ } void PageTestBase::SetBodyContent(const std::string& body_content) { - SetBodyInnerHTML(String::FromUTF8(body_content.c_str())); + SetBodyInnerHTML(String::FromUTF8(body_content)); } void PageTestBase::SetHtmlInnerHTML(const std::string& html_content) { GetDocument().documentElement()->SetInnerHTMLFromString( - String::FromUTF8(html_content.c_str())); + String::FromUTF8(html_content)); UpdateAllLifecyclePhasesForTest(); }
diff --git a/third_party/blink/renderer/core/testing/sim/sim_request.cc b/third_party/blink/renderer/core/testing/sim/sim_request.cc index 41d6bc0e..c1b021d 100644 --- a/third_party/blink/renderer/core/testing/sim/sim_request.cc +++ b/third_party/blink/renderer/core/testing/sim/sim_request.cc
@@ -9,6 +9,7 @@ #include "third_party/blink/renderer/core/testing/sim/sim_network.h" #include "third_party/blink/renderer/platform/loader/static_data_navigation_body_loader.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" +#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h" namespace blink { @@ -65,18 +66,14 @@ } void SimRequestBase::Write(const String& data) { - if (!started_) - ServePending(); - DCHECK(started_); - DCHECK(!error_); - total_encoded_data_length_ += data.length(); - if (navigation_body_loader_) - navigation_body_loader_->Write(data.Utf8().data(), data.length()); - else - client_->DidReceiveData(data.Utf8().data(), data.length()); + WriteInternal(StringUTF8Adaptor(data)); } void SimRequestBase::Write(const Vector<char>& data) { + WriteInternal(data); +} + +void SimRequestBase::WriteInternal(base::span<const char> data) { if (!started_) ServePending(); DCHECK(started_);
diff --git a/third_party/blink/renderer/core/testing/sim/sim_request.h b/third_party/blink/renderer/core/testing/sim/sim_request.h index f1c116c..cd208356 100644 --- a/third_party/blink/renderer/core/testing/sim/sim_request.h +++ b/third_party/blink/renderer/core/testing/sim/sim_request.h
@@ -67,6 +67,9 @@ void Reset(); + // Internal function to write a chunk of the response body + void WriteInternal(base::span<const char>); + // Used by SimNetwork. void DidReceiveResponse(WebURLLoaderClient*, const WebURLResponse&); void DidFail(const WebURLError&);
diff --git a/third_party/blink/renderer/core/timing/performance_user_timing.cc b/third_party/blink/renderer/core/timing/performance_user_timing.cc index c1da450..3f76f57 100644 --- a/third_party/blink/renderer/core/timing/performance_user_timing.cc +++ b/third_party/blink/renderer/core/timing/performance_user_timing.cc
@@ -135,11 +135,11 @@ void UserTiming::AddMarkToPerformanceTimeline(PerformanceMark& mark) { if (performance_->timing()) { - TRACE_EVENT_COPY_MARK1("blink.user_timing", mark.name().Utf8().data(), + TRACE_EVENT_COPY_MARK1("blink.user_timing", mark.name().Utf8().c_str(), "data", performance_->timing()->GetNavigationTracingData()); } else { - TRACE_EVENT_COPY_MARK("blink.user_timing", mark.name().Utf8().data()); + TRACE_EVENT_COPY_MARK("blink.user_timing", mark.name().Utf8().c_str()); } InsertPerformanceEntry(marks_map_, mark); DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, @@ -228,10 +228,10 @@ WTF::AddFloatToHash(hash, end_time); TRACE_EVENT_COPY_NESTABLE_ASYNC_BEGIN_WITH_TIMESTAMP0( - "blink.user_timing", measure_name.Utf8().data(), hash, + "blink.user_timing", measure_name.Utf8().c_str(), hash, trace_event::ToTraceTimestamp(start_time_monotonic)); TRACE_EVENT_COPY_NESTABLE_ASYNC_END_WITH_TIMESTAMP0( - "blink.user_timing", measure_name.Utf8().data(), hash, + "blink.user_timing", measure_name.Utf8().c_str(), hash, trace_event::ToTraceTimestamp(end_time_monotonic)); auto* measure = MakeGarbageCollected<PerformanceMeasure>(
diff --git a/third_party/blink/renderer/core/xml/parser/xml_document_parser.cc b/third_party/blink/renderer/core/xml/parser/xml_document_parser.cc index 15e3060..6e16c58 100644 --- a/third_party/blink/renderer/core/xml/parser/xml_document_parser.cc +++ b/third_party/blink/renderer/core/xml/parser/xml_document_parser.cc
@@ -684,12 +684,12 @@ scoped_refptr<XMLParserContext> XMLParserContext::CreateMemoryParser( xmlSAXHandlerPtr handlers, void* user_data, - const CString& chunk) { + const std::string& chunk) { InitializeLibXMLIfNecessary(); // appendFragmentSource() checks that the length doesn't overflow an int. xmlParserCtxtPtr parser = - xmlCreateMemoryParserCtxt(chunk.data(), chunk.length()); + xmlCreateMemoryParserCtxt(chunk.c_str(), chunk.length()); if (!parser) return nullptr; @@ -1491,7 +1491,7 @@ // http://bugs.webkit.org/show_bug.cgi?id=5792 } -void XMLDocumentParser::InitializeParserContext(const CString& chunk) { +void XMLDocumentParser::InitializeParserContext(const std::string& chunk) { xmlSAXHandler sax; memset(&sax, 0, sizeof(sax)); @@ -1525,7 +1525,6 @@ if (parsing_fragment_) { context_ = XMLParserContext::CreateMemoryParser(&sax, this, chunk); } else { - DCHECK(!chunk.data()); context_ = XMLParserContext::CreateStringParser(&sax, this); } } @@ -1630,7 +1629,7 @@ DCHECK(!context_); DCHECK(parsing_fragment_); - CString chunk_as_utf8 = chunk.Utf8(); + std::string chunk_as_utf8 = chunk.Utf8(); // libxml2 takes an int for a length, and therefore can't handle XML chunks // larger than 2 GiB.
diff --git a/third_party/blink/renderer/core/xml/parser/xml_document_parser.h b/third_party/blink/renderer/core/xml/parser/xml_document_parser.h index aaf355cb..e202fa6 100644 --- a/third_party/blink/renderer/core/xml/parser/xml_document_parser.h +++ b/third_party/blink/renderer/core/xml/parser/xml_document_parser.h
@@ -55,8 +55,10 @@ USING_FAST_MALLOC(XMLParserContext); public: - static scoped_refptr<XMLParserContext> - CreateMemoryParser(xmlSAXHandlerPtr, void* user_data, const CString& chunk); + static scoped_refptr<XMLParserContext> CreateMemoryParser( + xmlSAXHandlerPtr, + void* user_data, + const std::string& chunk); static scoped_refptr<XMLParserContext> CreateStringParser(xmlSAXHandlerPtr, void* user_data); ~XMLParserContext(); @@ -158,7 +160,7 @@ void EndDocument(); private: - void InitializeParserContext(const CString& chunk = CString()); + void InitializeParserContext(const std::string& chunk = std::string()); void PushCurrentNode(ContainerNode*); void PopCurrentNode();
diff --git a/third_party/blink/renderer/core/xml/xsl_style_sheet_libxslt.cc b/third_party/blink/renderer/core/xml/xsl_style_sheet_libxslt.cc index b97d69c..13dffcdc 100644 --- a/third_party/blink/renderer/core/xml/xsl_style_sheet_libxslt.cc +++ b/third_party/blink/renderer/core/xml/xsl_style_sheet_libxslt.cc
@@ -143,7 +143,7 @@ stylesheet_doc_ = xmlCtxtReadMemory(ctxt, input.Data(), input.size(), - final_url_.GetString().Utf8().data(), input.Encoding(), + final_url_.GetString().Utf8().c_str(), input.Encoding(), XML_PARSE_NOENT | XML_PARSE_DTDATTR | XML_PARSE_NOWARNING | XML_PARSE_NOCDATA); @@ -167,7 +167,7 @@ // We have to locate (by ID) the appropriate embedded stylesheet // element, so that we can walk the import/include list. xmlAttrPtr id_node = xmlGetID( - GetDocument(), (const xmlChar*)(final_url_.GetString().Utf8().data())); + GetDocument(), (const xmlChar*)(final_url_.GetString().Utf8().c_str())); if (!id_node) return; stylesheet_root = id_node->parent; @@ -287,10 +287,10 @@ // In order to ensure that libxml canonicalized both URLs, we get // the original href string from the import rule and canonicalize it // using libxml before comparing it with the URI argument. - CString import_href = child->href().Utf8(); + std::string import_href = child->href().Utf8(); xmlChar* base = xmlNodeGetBase(parent_doc, (xmlNodePtr)parent_doc); xmlChar* child_uri = - xmlBuildURI((const xmlChar*)import_href.data(), base); + xmlBuildURI((const xmlChar*)import_href.c_str(), base); bool equal_ur_is = xmlStrEqual(uri, child_uri); xmlFree(base); xmlFree(child_uri);
diff --git a/third_party/blink/renderer/core/xml/xslt_processor_libxslt.cc b/third_party/blink/renderer/core/xml/xslt_processor_libxslt.cc index eb1bdd3..7f5a4dd 100644 --- a/third_party/blink/renderer/core/xml/xslt_processor_libxslt.cc +++ b/third_party/blink/renderer/core/xml/xslt_processor_libxslt.cc
@@ -247,9 +247,9 @@ unsigned index = 0; for (auto& parameter : parameters) { parameter_array[index++] = - AllocateParameterArray(parameter.key.Utf8().data()); + AllocateParameterArray(parameter.key.Utf8().c_str()); parameter_array[index++] = - AllocateParameterArray(parameter.value.Utf8().data()); + AllocateParameterArray(parameter.value.Utf8().c_str()); } parameter_array[index] = nullptr;
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object.cc b/third_party/blink/renderer/modules/accessibility/ax_object.cc index 4b09f5a7..a1743d2 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_object.cc
@@ -3435,7 +3435,7 @@ } std::ostream& operator<<(std::ostream& stream, const AXObject& obj) { - return stream << obj.ToString().Utf8().data(); + return stream << obj.ToString().Utf8(); } void AXObject::Trace(blink::Visitor* visitor) {
diff --git a/third_party/blink/renderer/modules/accessibility/ax_position.cc b/third_party/blink/renderer/modules/accessibility/ax_position.cc index f90b106..27464e9 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_position.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_position.cc
@@ -900,7 +900,7 @@ } std::ostream& operator<<(std::ostream& ostream, const AXPosition& position) { - return ostream << position.ToString().Utf8().data(); + return ostream << position.ToString().Utf8(); } } // namespace blink
diff --git a/third_party/blink/renderer/modules/accessibility/ax_range.cc b/third_party/blink/renderer/modules/accessibility/ax_range.cc index 650e566a..6f6ab24 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_range.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_range.cc
@@ -86,7 +86,7 @@ } std::ostream& operator<<(std::ostream& ostream, const AXRange& range) { - return ostream << range.ToString().Utf8().data(); + return ostream << range.ToString().Utf8(); } } // namespace blink
diff --git a/third_party/blink/renderer/modules/accessibility/ax_selection.cc b/third_party/blink/renderer/modules/accessibility/ax_selection.cc index 3700f25..bdf3283 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_selection.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_selection.cc
@@ -441,7 +441,7 @@ } std::ostream& operator<<(std::ostream& ostream, const AXSelection& selection) { - return ostream << selection.ToString().Utf8().data(); + return ostream << selection.ToString().Utf8(); } } // namespace blink
diff --git a/third_party/blink/renderer/modules/accessibility/testing/accessibility_selection_test.cc b/third_party/blink/renderer/modules/accessibility/testing/accessibility_selection_test.cc index 7223a88..6e22068 100644 --- a/third_party/blink/renderer/modules/accessibility/testing/accessibility_selection_test.cc +++ b/third_party/blink/renderer/modules/accessibility/testing/accessibility_selection_test.cc
@@ -52,7 +52,7 @@ return {}; SerializeSubtree(subtree); DCHECK_EQ(tree_level_, 0); - return builder_.ToString().Utf8().data(); + return builder_.ToString().Utf8(); } private: @@ -163,8 +163,7 @@ const auto position = AXPosition::CreatePositionBeforeObject(*child); HandleSelection(position); ++tree_level_; - builder_.Append( - String::FromUTF8(std::string(tree_level_ * 2, '+').c_str())); + builder_.Append(String::FromUTF8(std::string(tree_level_ * 2, '+'))); if (position.IsTextPosition()) { HandleTextObject(*child); } else { @@ -207,7 +206,7 @@ // parts of the tree indicated by the selection markers in the snippet. const Vector<AXSelection> Deserialize(const std::string& html_snippet, HTMLElement& element) { - element.SetInnerHTMLFromString(String::FromUTF8(html_snippet.c_str())); + element.SetInnerHTMLFromString(String::FromUTF8(html_snippet)); element.GetDocument().View()->UpdateAllLifecyclePhases( DocumentLifecycle::LifecycleUpdateReason::kTest); AXObject* root = ax_object_cache_->GetOrCreate(&element); @@ -395,7 +394,7 @@ const std::string& test_name) const { static const std::string separator_line = '\n' + std::string(80, '=') + '\n'; const String relative_path = String::FromUTF8(kSelectionTestsRelativePath) + - String::FromUTF8(test_name.c_str()); + String::FromUTF8(test_name); const String test_path = AccessibilityTestDataPath(relative_path); const String test_file = test_path + String::FromUTF8(kTestFileSuffix); @@ -406,7 +405,7 @@ std::back_inserter(test_file_contents)); ASSERT_FALSE(test_file_contents.empty()) << "Test file cannot be empty.\n" - << test_file.Utf8().data() + << test_file.Utf8() << "\nDid you forget to add a data dependency to the BUILD file?"; const String ax_file = test_path + String::FromUTF8(kAXTestExpectationSuffix); @@ -417,7 +416,7 @@ std::back_inserter(ax_file_contents)); ASSERT_FALSE(ax_file_contents.empty()) << "Expectations file cannot be empty.\n" - << ax_file.Utf8().data() + << ax_file.Utf8() << "\nDid you forget to add a data dependency to the BUILD file?"; HTMLElement* body = GetDocument().body(); @@ -430,7 +429,7 @@ for (auto& ax_selection : ax_selections) { ax_selection.Select(); actual_ax_file_contents += separator_line; - actual_ax_file_contents += ax_selection.ToString().Utf8().data(); + actual_ax_file_contents += ax_selection.ToString().Utf8(); actual_ax_file_contents += separator_line; actual_ax_file_contents += GetCurrentSelectionText(); }
diff --git a/third_party/blink/renderer/modules/animationworklet/worklet_animation.cc b/third_party/blink/renderer/modules/animationworklet/worklet_animation.cc index 5d24a8d..ba0b6ed 100644 --- a/third_party/blink/renderer/modules/animationworklet/worklet_animation.cc +++ b/third_party/blink/renderer/modules/animationworklet/worklet_animation.cc
@@ -801,8 +801,8 @@ double current_time_ms = current_time.value().InMillisecondsF(); if (!was_active && is_active) { - input_state->Add({id_, std::string(animator_name_.Utf8().data()), - current_time_ms, CloneOptions(), CloneEffectTimings()}); + input_state->Add({id_, animator_name_.Utf8(), current_time_ms, + CloneOptions(), CloneEffectTimings()}); } else if (was_active && is_active) { // Skip if the input time is not changed. if (did_time_change)
diff --git a/third_party/blink/renderer/modules/cache_storage/inspector_cache_storage_agent.cc b/third_party/blink/renderer/modules/cache_storage/inspector_cache_storage_agent.cc index 524e127..01fdfd1 100644 --- a/third_party/blink/renderer/modules/cache_storage/inspector_cache_storage_agent.cc +++ b/third_party/blink/renderer/modules/cache_storage/inspector_cache_storage_agent.cc
@@ -343,7 +343,7 @@ void SendFailure(const mojom::blink::CacheStorageError& error) { callback_->sendFailure(ProtocolResponse::Error( String::Format("Error requesting responses for cache %s : %s", - params_.cache_name.Utf8().data(), + params_.cache_name.Utf8().c_str(), CacheStorageErrorString(error).data()))); } @@ -396,7 +396,7 @@ self->callback_->sendFailure( ProtocolResponse::Error(String::Format( "Error requesting requests for cache %s: %s", - params.cache_name.Utf8().data(), + params.cache_name.Utf8().c_str(), CacheStorageErrorString(result->get_status()).data()))); } else { if (result->get_keys().IsEmpty()) { @@ -575,7 +575,7 @@ if (result->is_status()) { callback->sendFailure(ProtocolResponse::Error(String::Format( "Error requesting cache %s: %s", - params.cache_name.Utf8().data(), + params.cache_name.Utf8().c_str(), CacheStorageErrorString(result->get_status()).data()))); } else { auto request = std::make_unique<GetCacheKeysForRequestData>( @@ -644,7 +644,7 @@ mojom::blink::OpenResultPtr result) { if (result->is_status()) { callback->sendFailure(ProtocolResponse::Error(String::Format( - "Error requesting cache %s: %s", cache_name.Utf8().data(), + "Error requesting cache %s: %s", cache_name.Utf8().c_str(), CacheStorageErrorString(result->get_status()).data()))); } else { Vector<mojom::blink::BatchOperationPtr> batch_operations;
diff --git a/third_party/blink/renderer/modules/clipboard/clipboard_reader.cc b/third_party/blink/renderer/modules/clipboard/clipboard_reader.cc index b2f3e95..ef4542d3 100644 --- a/third_party/blink/renderer/modules/clipboard/clipboard_reader.cc +++ b/third_party/blink/renderer/modules/clipboard/clipboard_reader.cc
@@ -10,6 +10,7 @@ #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/imagebitmap/image_bitmap.h" #include "third_party/blink/renderer/platform/image-encoders/image_encoder.h" +#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h" #include "third_party/blink/renderer/platform/wtf/wtf.h" namespace blink { @@ -50,10 +51,9 @@ mojom::ClipboardBuffer::kStandard); // Encode WTF String to UTF-8, the standard text format for blobs. - CString utf_text = plain_text.Utf8(); - + StringUTF8Adaptor utf_text(plain_text); return Blob::Create(reinterpret_cast<const uint8_t*>(utf_text.data()), - utf_text.length(), kMimeTypeTextPlain); + utf_text.size(), kMimeTypeTextPlain); } };
diff --git a/third_party/blink/renderer/modules/credentialmanager/password_credential_test.cc b/third_party/blink/renderer/modules/credentialmanager/password_credential_test.cc index b6283d1..a915b71 100644 --- a/third_party/blink/renderer/modules/credentialmanager/password_credential_test.cc +++ b/third_party/blink/renderer/modules/credentialmanager/password_credential_test.cc
@@ -28,7 +28,7 @@ b.Append("'>"); b.Append(html); b.Append("</form></body></html>"); - SetHtmlInnerHTML(b.ToString().Utf8().data()); + SetHtmlInnerHTML(b.ToString().Utf8()); HTMLFormElement* form = ToHTMLFormElement(GetElementById("theForm")); EXPECT_NE(nullptr, form); return form;
diff --git a/third_party/blink/renderer/modules/crypto/subtle_crypto.cc b/third_party/blink/renderer/modules/crypto/subtle_crypto.cc index 6dbc3f4..4e6de702 100644 --- a/third_party/blink/renderer/modules/crypto/subtle_crypto.cc +++ b/third_party/blink/renderer/modules/crypto/subtle_crypto.cc
@@ -154,7 +154,7 @@ CopyStringProperty(kPropertyNames[i], dict, json_object.get()); String json = json_object->ToJSONString(); - json_utf8 = WebVector<uint8_t>(json.Utf8().data(), json.Utf8().length()); + json_utf8 = WebVector<uint8_t>(json.Utf8().c_str(), json.Utf8().length()); return true; }
diff --git a/third_party/blink/renderer/modules/encoding/text_encoder.cc b/third_party/blink/renderer/modules/encoding/text_encoder.cc index 66978bb..548289c 100644 --- a/third_party/blink/renderer/modules/encoding/text_encoder.cc +++ b/third_party/blink/renderer/modules/encoding/text_encoder.cc
@@ -60,7 +60,7 @@ } NotShared<DOMUint8Array> TextEncoder::encode(const String& input) { - CString result; + std::string result; // Note that the UnencodableHandling here is never used since the // only possible encoding is UTF-8, which will use // U+FFFD-replacement rather than ASCII fallback substitution when @@ -74,12 +74,12 @@ WTF::kNoUnencodables); } - const char* buffer = result.data(); + const char* buffer = result.c_str(); const unsigned char* unsigned_buffer = reinterpret_cast<const unsigned char*>(buffer); - return NotShared<DOMUint8Array>( - DOMUint8Array::Create(unsigned_buffer, result.length())); + return NotShared<DOMUint8Array>(DOMUint8Array::Create( + unsigned_buffer, static_cast<unsigned>(result.length()))); } TextEncoderEncodeIntoResult* TextEncoder::encodeInto(
diff --git a/third_party/blink/renderer/modules/encoding/text_encoder_stream.cc b/third_party/blink/renderer/modules/encoding/text_encoder_stream.cc index 373f318..380115f 100644 --- a/third_party/blink/renderer/modules/encoding/text_encoder_stream.cc +++ b/third_party/blink/renderer/modules/encoding/text_encoder_stream.cc
@@ -47,8 +47,8 @@ const base::Optional<UChar> high_surrogate = pending_high_surrogate_; pending_high_surrogate_ = base::nullopt; - CString prefix; - CString result; + std::string prefix; + std::string result; if (input.Is8Bit()) { if (high_surrogate.has_value()) { // An 8-bit code unit can never be part of an astral character, so no @@ -75,13 +75,14 @@ if (!pending_high_surrogate_.has_value()) return; - const CString replacement_character = ReplacementCharacterInUtf8(); + const std::string replacement_character = ReplacementCharacterInUtf8(); const uint8_t* u8buffer = - reinterpret_cast<const uint8_t*>(replacement_character.data()); - controller->Enqueue( - ToV8(DOMUint8Array::Create(u8buffer, replacement_character.length()), - script_state_), - exception_state); + reinterpret_cast<const uint8_t*>(replacement_character.c_str()); + controller->Enqueue(ToV8(DOMUint8Array::Create( + u8buffer, static_cast<unsigned int>( + replacement_character.length())), + script_state_), + exception_state); } ScriptState* GetScriptState() override { return script_state_; } @@ -92,21 +93,21 @@ } private: - static CString ReplacementCharacterInUtf8() { + static std::string ReplacementCharacterInUtf8() { constexpr char kRawBytes[] = {0xEF, 0xBF, 0xBD}; - return CString(kRawBytes, sizeof(kRawBytes)); + return std::string(kRawBytes, sizeof(kRawBytes)); } static DOMUint8Array* CreateDOMUint8ArrayFromTwoCStringsConcatenated( - const CString& string1, - const CString& string2) { - const wtf_size_t length1 = string1.length(); - const wtf_size_t length2 = string2.length(); + const std::string& string1, + const std::string& string2) { + const wtf_size_t length1 = static_cast<wtf_size_t>(string1.length()); + const wtf_size_t length2 = static_cast<wtf_size_t>(string2.length()); DOMUint8Array* const array = DOMUint8Array::Create(length1 + length2); if (length1 > 0) - memcpy(array->Data(), string1.data(), length1); + memcpy(array->Data(), string1.c_str(), length1); if (length2 > 0) - memcpy(array->Data() + length1, string2.data(), length2); + memcpy(array->Data() + length1, string2.c_str(), length2); return array; } @@ -114,8 +115,8 @@ // value. bool Encode16BitString(const String& input, base::Optional<UChar> high_surrogate, - CString* prefix, - CString* result) { + std::string* prefix, + std::string* result) { const UChar* begin = input.Characters16(); const UChar* end = input.Characters16() + input.length(); DCHECK_GT(end, begin);
diff --git a/third_party/blink/renderer/modules/eventsource/event_source.cc b/third_party/blink/renderer/modules/eventsource/event_source.cc index e5aa0bc9..ce08a98 100644 --- a/third_party/blink/renderer/modules/eventsource/event_source.cc +++ b/third_party/blink/renderer/modules/eventsource/event_source.cc
@@ -142,10 +142,10 @@ // encoded as UTF-8. // TODO(davidben): This should be captured in the type of // setHTTPHeaderField's arguments. - CString last_event_id_utf8 = parser_->LastEventId().Utf8(); + std::string last_event_id_utf8 = parser_->LastEventId().Utf8(); request.SetHttpHeaderField( http_names::kLastEventID, - AtomicString(reinterpret_cast<const LChar*>(last_event_id_utf8.data()), + AtomicString(reinterpret_cast<const LChar*>(last_event_id_utf8.c_str()), last_event_id_utf8.length())); }
diff --git a/third_party/blink/renderer/modules/indexeddb/inspector_indexed_db_agent.cc b/third_party/blink/renderer/modules/indexeddb/inspector_indexed_db_agent.cc index 3c4bf94..0bbfd6f4f 100644 --- a/third_party/blink/renderer/modules/indexeddb/inspector_indexed_db_agent.cc +++ b/third_party/blink/renderer/modules/indexeddb/inspector_indexed_db_agent.cc
@@ -903,7 +903,7 @@ ExceptionCode ec = exception_state.Code(); request_callback_->sendFailure(Response::Error( String::Format("Could not count entries in object store '%s': %d", - object_store_name_.Utf8().data(), ec))); + object_store_name_.Utf8().c_str(), ec))); return; } GetMetadataListener* listener_get_entries_count = @@ -1108,7 +1108,7 @@ ExceptionCode ec = exception_state.Code(); request_callback_->sendFailure(Response::Error( String::Format("Could not clear object store '%s': %d", - object_store_name_.Utf8().data(), ec))); + object_store_name_.Utf8().c_str(), ec))); return; } idb_transaction->addEventListener(
diff --git a/third_party/blink/renderer/modules/mediastream/media_stream_video_renderer_sink.cc b/third_party/blink/renderer/modules/mediastream/media_stream_video_renderer_sink.cc index 4af12d7..906681ff 100644 --- a/third_party/blink/renderer/modules/mediastream/media_stream_video_renderer_sink.cc +++ b/third_party/blink/renderer/modules/mediastream/media_stream_video_renderer_sink.cc
@@ -28,12 +28,12 @@ public: FrameDeliverer( const RepaintCB& repaint_cb, - base::RepeatingCallback<void(media::VideoCaptureFrameDropReason)> - frame_dropped_cb, + base::WeakPtr<MediaStreamVideoRendererSink> + media_stream_video_renderer_sink, scoped_refptr<base::SingleThreadTaskRunner> main_render_task_runner) : main_render_task_runner_(std::move(main_render_task_runner)), repaint_cb_(repaint_cb), - frame_dropped_cb_(std::move(frame_dropped_cb)), + media_stream_video_renderer_sink_(media_stream_video_renderer_sink), state_(STOPPED), frame_size_(kMinFrameSize, kMinFrameSize), emit_frame_drop_events_(true) { @@ -60,7 +60,8 @@ emit_frame_drop_events_ = false; PostCrossThreadTask( *main_render_task_runner_, FROM_HERE, - CrossThreadBind(frame_dropped_cb_, + CrossThreadBind(&MediaStreamVideoRendererSink::OnFrameDropped, + media_stream_video_renderer_sink_, media::VideoCaptureFrameDropReason:: kRendererSinkFrameDelivererIsNotStarted)); } @@ -117,8 +118,7 @@ const scoped_refptr<base::SingleThreadTaskRunner> main_render_task_runner_; const RepaintCB repaint_cb_; - const base::RepeatingCallback<void(media::VideoCaptureFrameDropReason)> - frame_dropped_cb_; + base::WeakPtr<MediaStreamVideoRendererSink> media_stream_video_renderer_sink_; State state_; gfx::Size frame_size_; bool emit_frame_drop_events_; @@ -148,10 +148,7 @@ DCHECK_CALLED_ON_VALID_THREAD(main_thread_checker_); frame_deliverer_.reset(new MediaStreamVideoRendererSink::FrameDeliverer( - repaint_cb_, - ConvertToBaseCallback(CrossThreadBind( - &MediaStreamVideoSink::OnFrameDropped, weak_factory_.GetWeakPtr())), - main_render_task_runner_)); + repaint_cb_, weak_factory_.GetWeakPtr(), main_render_task_runner_)); PostCrossThreadTask( *io_task_runner_, FROM_HERE, CrossThreadBindOnce(&FrameDeliverer::Start,
diff --git a/third_party/blink/renderer/modules/nfc/nfc.cc b/third_party/blink/renderer/modules/nfc/nfc.cc index 447befc..32080b0 100644 --- a/third_party/blink/renderer/modules/nfc/nfc.cc +++ b/third_party/blink/renderer/modules/nfc/nfc.cc
@@ -23,6 +23,7 @@ #include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/mojo/mojo_helper.h" #include "third_party/blink/renderer/platform/weborigin/security_origin.h" +#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h" namespace { const char kJsonMimePostfix[] = "+json"; @@ -131,9 +132,9 @@ template <> struct TypeConverter<Vector<uint8_t>, String> { static Vector<uint8_t> Convert(const String& string) { - CString utf8String = string.Utf8(); + StringUTF8Adaptor utf8_string(string); Vector<uint8_t> array; - array.Append(utf8String.data(), utf8String.length()); + array.Append(utf8_string.data(), utf8_string.size()); return array; } };
diff --git a/third_party/blink/renderer/modules/notifications/notification_image_loader.cc b/third_party/blink/renderer/modules/notifications/notification_image_loader.cc index 65f6fd9..da43cc2 100644 --- a/third_party/blink/renderer/modules/notifications/notification_image_loader.cc +++ b/third_party/blink/renderer/modules/notifications/notification_image_loader.cc
@@ -53,51 +53,6 @@ NotificationImageLoader::~NotificationImageLoader() = default; -// static -SkBitmap NotificationImageLoader::ScaleDownIfNeeded(const SkBitmap& image, - Type type) { - int max_width_px = 0, max_height_px = 0; - switch (type) { - case Type::kImage: - max_width_px = kWebNotificationMaxImageWidthPx; - max_height_px = kWebNotificationMaxImageHeightPx; - break; - case Type::kIcon: - max_width_px = kWebNotificationMaxIconSizePx; - max_height_px = kWebNotificationMaxIconSizePx; - break; - case Type::kBadge: - max_width_px = kWebNotificationMaxBadgeSizePx; - max_height_px = kWebNotificationMaxBadgeSizePx; - break; - case Type::kActionIcon: - max_width_px = kWebNotificationMaxActionIconSizePx; - max_height_px = kWebNotificationMaxActionIconSizePx; - break; - } - DCHECK_GT(max_width_px, 0); - DCHECK_GT(max_height_px, 0); - // TODO(peter): Explore doing the scaling on a background thread. - if (image.width() > max_width_px || image.height() > max_height_px) { - double scale = - std::min(static_cast<double>(max_width_px) / image.width(), - static_cast<double>(max_height_px) / image.height()); - TimeTicks start_time = CurrentTimeTicks(); - // TODO(peter): Try using RESIZE_BETTER for large images. - SkBitmap scaled_image = skia::ImageOperations::Resize( - image, skia::ImageOperations::RESIZE_BEST, - static_cast<int>(std::lround(scale * image.width())), - static_cast<int>(std::lround(scale * image.height()))); - NOTIFICATION_HISTOGRAM_COUNTS( - LoadScaleDownTime, type, - base::saturated_cast<base::HistogramBase::Sample>( - (CurrentTimeTicks() - start_time).InMilliseconds()), - 1000 * 10 /* 10 seconds max */); - return scaled_image; - } - return image; -} - void NotificationImageLoader::Start(ExecutionContext* context, const KURL& url, ImageCallback image_callback) { @@ -167,7 +122,8 @@ // The |ImageFrame*| is owned by the decoder. ImageFrame* image_frame = decoder->DecodeFrameBufferAtIndex(0); if (image_frame) { - std::move(image_callback_).Run(image_frame->Bitmap()); + std::move(image_callback_) + .Run(ScaleDownIfNeeded(image_frame->Bitmap())); return; } } @@ -198,4 +154,47 @@ std::move(image_callback_).Run(SkBitmap()); } +SkBitmap NotificationImageLoader::ScaleDownIfNeeded(const SkBitmap& image) { + int max_width_px = 0, max_height_px = 0; + switch (type_) { + case Type::kImage: + max_width_px = kWebNotificationMaxImageWidthPx; + max_height_px = kWebNotificationMaxImageHeightPx; + break; + case Type::kIcon: + max_width_px = kWebNotificationMaxIconSizePx; + max_height_px = kWebNotificationMaxIconSizePx; + break; + case Type::kBadge: + max_width_px = kWebNotificationMaxBadgeSizePx; + max_height_px = kWebNotificationMaxBadgeSizePx; + break; + case Type::kActionIcon: + max_width_px = kWebNotificationMaxActionIconSizePx; + max_height_px = kWebNotificationMaxActionIconSizePx; + break; + } + DCHECK_GT(max_width_px, 0); + DCHECK_GT(max_height_px, 0); + // TODO(peter): Explore doing the scaling on a background thread. + if (image.width() > max_width_px || image.height() > max_height_px) { + double scale = + std::min(static_cast<double>(max_width_px) / image.width(), + static_cast<double>(max_height_px) / image.height()); + TimeTicks start_time = CurrentTimeTicks(); + // TODO(peter): Try using RESIZE_BETTER for large images. + SkBitmap scaled_image = skia::ImageOperations::Resize( + image, skia::ImageOperations::RESIZE_BEST, + static_cast<int>(std::lround(scale * image.width())), + static_cast<int>(std::lround(scale * image.height()))); + NOTIFICATION_HISTOGRAM_COUNTS( + LoadScaleDownTime, type_, + base::saturated_cast<base::HistogramBase::Sample>( + (CurrentTimeTicks() - start_time).InMilliseconds()), + 1000 * 10 /* 10 seconds max */); + return scaled_image; + } + return image; +} + } // namespace blink
diff --git a/third_party/blink/renderer/modules/notifications/notification_image_loader.h b/third_party/blink/renderer/modules/notifications/notification_image_loader.h index e29a9e2..f59ef9a 100644 --- a/third_party/blink/renderer/modules/notifications/notification_image_loader.h +++ b/third_party/blink/renderer/modules/notifications/notification_image_loader.h
@@ -40,10 +40,6 @@ explicit NotificationImageLoader(Type type); ~NotificationImageLoader() override; - // Scales down |image| according to its type and returns result. If it is - // already small enough, |image| is returned unchanged. - static SkBitmap ScaleDownIfNeeded(const SkBitmap& image, Type type); - // Asynchronously downloads an image from the given url, decodes the loaded // data, and passes the bitmap to the callback. Times out if the load takes // too long and ImageCallback is invoked with an empty bitmap. @@ -67,6 +63,10 @@ } private: + // Scales down |image| according to its |type_| and returns result. If it is + // already small enough, |image| is returned unchanged. + SkBitmap ScaleDownIfNeeded(const SkBitmap& image); + void RunCallbackWithEmptyBitmap(); Type type_;
diff --git a/third_party/blink/renderer/modules/notifications/notification_resources_loader.cc b/third_party/blink/renderer/modules/notifications/notification_resources_loader.cc index 5adbcc2f..4fba768 100644 --- a/third_party/blink/renderer/modules/notifications/notification_resources_loader.cc +++ b/third_party/blink/renderer/modules/notifications/notification_resources_loader.cc
@@ -93,20 +93,17 @@ } void NotificationResourcesLoader::DidLoadImage(const SkBitmap& image) { - image_ = NotificationImageLoader::ScaleDownIfNeeded( - image, NotificationImageLoader::Type::kImage); + image_ = image; DidFinishRequest(); } void NotificationResourcesLoader::DidLoadIcon(const SkBitmap& image) { - icon_ = NotificationImageLoader::ScaleDownIfNeeded( - image, NotificationImageLoader::Type::kIcon); + icon_ = image; DidFinishRequest(); } void NotificationResourcesLoader::DidLoadBadge(const SkBitmap& image) { - badge_ = NotificationImageLoader::ScaleDownIfNeeded( - image, NotificationImageLoader::Type::kBadge); + badge_ = image; DidFinishRequest(); } @@ -114,8 +111,7 @@ const SkBitmap& image) { DCHECK_LT(action_index, action_icons_.size()); - action_icons_[action_index] = NotificationImageLoader::ScaleDownIfNeeded( - image, NotificationImageLoader::Type::kActionIcon); + action_icons_[action_index] = image; DidFinishRequest(); }
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_certificate.cc b/third_party/blink/renderer/modules/peerconnection/rtc_certificate.cc index c07ad33..f6c27c5 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_certificate.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_certificate.cc
@@ -54,11 +54,10 @@ first_certificate_stats.get(); certificate_stats; certificate_stats = certificate_stats->issuer.get()) { RTCDtlsFingerprint* fingerprint = RTCDtlsFingerprint::Create(); - fingerprint->setAlgorithm(WTF::String::FromUTF8( - certificate_stats->fingerprint_algorithm.c_str())); + fingerprint->setAlgorithm( + WTF::String::FromUTF8(certificate_stats->fingerprint_algorithm)); fingerprint->setValue( - WTF::String::FromUTF8(certificate_stats->fingerprint.c_str()) - .LowerASCII()); + WTF::String::FromUTF8(certificate_stats->fingerprint).LowerASCII()); fingerprints.push_back(fingerprint); }
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_test.cc b/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_test.cc index c377f06..3eea9f50 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_test.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_test.cc
@@ -265,9 +265,8 @@ EXPECT_EQ(4U, channel->bufferedAmount()); channel->OnBufferedAmountChange(4); ASSERT_EQ(1U, channel->scheduled_events_.size()); - EXPECT_EQ( - "bufferedamountlow", - std::string(channel->scheduled_events_.back()->type().Utf8().data())); + EXPECT_EQ("bufferedamountlow", + channel->scheduled_events_.back()->type().Utf8()); } TEST_F(RTCDataChannelTest, Open) { @@ -280,9 +279,7 @@ pc.get()); channel->OnStateChange(webrtc::DataChannelInterface::kOpen); ASSERT_EQ(1U, channel->scheduled_events_.size()); - EXPECT_EQ( - "open", - std::string(channel->scheduled_events_.back()->type().Utf8().data())); + EXPECT_EQ("open", channel->scheduled_events_.back()->type().Utf8()); } TEST_F(RTCDataChannelTest, Close) { @@ -295,9 +292,7 @@ pc.get()); channel->OnStateChange(webrtc::DataChannelInterface::kClosed); ASSERT_EQ(1U, channel->scheduled_events_.size()); - EXPECT_EQ( - "close", - std::string(channel->scheduled_events_.back()->type().Utf8().data())); + EXPECT_EQ("close", channel->scheduled_events_.back()->type().Utf8()); } TEST_F(RTCDataChannelTest, Message) { @@ -312,9 +307,7 @@ std::unique_ptr<webrtc::DataBuffer> message(new webrtc::DataBuffer("A")); channel->OnMessage(std::move(message)); ASSERT_EQ(1U, channel->scheduled_events_.size()); - EXPECT_EQ( - "message", - std::string(channel->scheduled_events_.back()->type().Utf8().data())); + EXPECT_EQ("message", channel->scheduled_events_.back()->type().Utf8()); } TEST_F(RTCDataChannelTest, SendAfterContextDestroyed) {
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc index 8c77147..9b455f0 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc
@@ -528,7 +528,7 @@ base::Optional<SdpFormat> DeduceSdpFormat(const String& type, const String& sdp) { std::unique_ptr<webrtc::SessionDescriptionInterface> session_description( - webrtc::CreateSessionDescription(type.Utf8().data(), sdp.Utf8().data(), + webrtc::CreateSessionDescription(type.Utf8().c_str(), sdp.Utf8().c_str(), nullptr)); if (!session_description) return base::nullopt;
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_test.cc b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_test.cc index 61df391..8b74078 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_test.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_test.cc
@@ -400,9 +400,8 @@ std::string GetExceptionMessage(V8TestingScope& scope) { ExceptionState& exception_state = scope.GetExceptionState(); - return exception_state.HadException() - ? exception_state.Message().Utf8().data() - : ""; + return exception_state.HadException() ? exception_state.Message().Utf8() + : ""; } void AddStream(V8TestingScope& scope,
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_rtp_sender.cc b/third_party/blink/renderer/modules/peerconnection/rtc_rtp_sender.cc index c0686e4c..41c0703 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_rtp_sender.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_rtp_sender.cc
@@ -295,7 +295,7 @@ const webrtc::RtpCodecParameters& webrtc_codec) { RTCRtpCodecParameters* codec = RTCRtpCodecParameters::Create(); codec->setPayloadType(webrtc_codec.payload_type); - codec->setMimeType(WTF::String::FromUTF8(webrtc_codec.mime_type().c_str())); + codec->setMimeType(WTF::String::FromUTF8(webrtc_codec.mime_type())); if (webrtc_codec.clock_rate) codec->setClockRate(webrtc_codec.clock_rate.value()); if (webrtc_codec.num_channels) @@ -564,7 +564,7 @@ SafeCast<wtf_size_t>(rtc_capabilities->codecs.size())); for (const auto& rtc_codec : rtc_capabilities->codecs) { auto* codec = RTCRtpCodecCapability::Create(); - codec->setMimeType(WTF::String::FromUTF8(rtc_codec.mime_type().c_str())); + codec->setMimeType(WTF::String::FromUTF8(rtc_codec.mime_type())); if (rtc_codec.clock_rate) codec->setClockRate(rtc_codec.clock_rate.value()); if (rtc_codec.num_channels) @@ -587,8 +587,7 @@ SafeCast<wtf_size_t>(rtc_capabilities->header_extensions.size())); for (const auto& rtc_header_extension : rtc_capabilities->header_extensions) { auto* header_extension = RTCRtpHeaderExtensionCapability::Create(); - header_extension->setUri( - WTF::String::FromUTF8(rtc_header_extension.uri.c_str())); + header_extension->setUri(WTF::String::FromUTF8(rtc_header_extension.uri)); header_extensions.push_back(header_extension); } capabilities->setHeaderExtensions(header_extensions);
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_rtp_transceiver.cc b/third_party/blink/renderer/modules/peerconnection/rtc_rtp_transceiver.cc index 9e2e179..619d443 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_rtp_transceiver.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_rtp_transceiver.cc
@@ -76,7 +76,7 @@ } DCHECK(init->hasStreams()); for (const auto& stream : init->streams()) { - webrtc_init.stream_ids.push_back(stream->id().Utf8().data()); + webrtc_init.stream_ids.push_back(stream->id().Utf8()); } DCHECK(init->hasSendEncodings()); for (const auto& encoding : init->sendEncodings()) {
diff --git a/third_party/blink/renderer/modules/push_messaging/push_message_data.cc b/third_party/blink/renderer/modules/push_messaging/push_message_data.cc index ec7a9e58..28e48e6 100644 --- a/third_party/blink/renderer/modules/push_messaging/push_message_data.cc +++ b/third_party/blink/renderer/modules/push_messaging/push_message_data.cc
@@ -42,10 +42,10 @@ } if (message_data.IsUSVString()) { - CString encoded_string = UTF8Encoding().Encode( + std::string encoded_string = UTF8Encoding().Encode( message_data.GetAsUSVString(), WTF::kNoUnencodables); - return MakeGarbageCollected<PushMessageData>(encoded_string.data(), - encoded_string.length()); + return MakeGarbageCollected<PushMessageData>( + encoded_string.c_str(), static_cast<unsigned>(encoded_string.length())); } DCHECK(message_data.IsNull());
diff --git a/third_party/blink/renderer/modules/push_messaging/push_message_data_test.cc b/third_party/blink/renderer/modules/push_messaging/push_message_data_test.cc index c6eaf5e..792a0742 100644 --- a/third_party/blink/renderer/modules/push_messaging/push_message_data_test.cc +++ b/third_party/blink/renderer/modules/push_messaging/push_message_data_test.cc
@@ -29,7 +29,7 @@ PushMessageData* data = PushMessageData::Create(s); ASSERT_NE(data, nullptr); - EXPECT_STREQ("", data->text().Utf8().data()); + EXPECT_EQ("", data->text().Utf8()); } TEST(PushMessageDataTest, NullPayload) {
diff --git a/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.cc b/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.cc index a0c63be2..7d7b48e5 100644 --- a/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.cc +++ b/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.cc
@@ -708,7 +708,7 @@ String message = String::Format( "Event handler of '%s' event must be added on the initial evaluation " "of worker script.", - event_type.Utf8().data()); + event_type.Utf8().c_str()); AddConsoleMessage( ConsoleMessage::Create(mojom::ConsoleMessageSource::kJavaScript, mojom::ConsoleMessageLevel::kWarning, message));
diff --git a/third_party/blink/renderer/modules/storage/cached_storage_area.cc b/third_party/blink/renderer/modules/storage/cached_storage_area.cc index 6a3a371..b6fc8729 100644 --- a/third_party/blink/renderer/modules/storage/cached_storage_area.cc +++ b/third_party/blink/renderer/modules/storage/cached_storage_area.cc
@@ -17,6 +17,7 @@ #include "third_party/blink/renderer/platform/weborigin/kurl.h" #include "third_party/blink/renderer/platform/wtf/functional.h" #include "third_party/blink/renderer/platform/wtf/text/string_buffer.h" +#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h" #include "third_party/blink/renderer/platform/wtf/text/unicode.h" #include "third_party/blink/renderer/platform/wtf/text/utf8.h" @@ -368,12 +369,11 @@ "site_storage/%s/0x%" PRIXPTR "/cache_size", IsSessionStorage() ? "session_storage" : "local_storage", reinterpret_cast<uintptr_t>(this)); - MemoryAllocatorDump* dump = pmd->CreateAllocatorDump(dump_name.Utf8().data()); + MemoryAllocatorDump* dump = pmd->CreateAllocatorDump(dump_name.Utf8()); dump->AddScalar(MemoryAllocatorDump::kNameSize, MemoryAllocatorDump::kUnitsBytes, memory_used()); - pmd->AddSuballocation( - dump->guid(), - String(WTF::Partitions::kAllocatedObjectPoolName).Utf8().data()); + pmd->AddSuballocation(dump->guid(), + WTF::Partitions::kAllocatedObjectPoolName); return true; } @@ -651,10 +651,10 @@ // TODO(dmurph): Figure out how to avoid a copy here. // TODO(dmurph): Handle invalid UTF16 better. https://crbug.com/873280. - CString utf8 = input.Utf8( - WTF::kStrictUTF8ConversionReplacingUnpairedSurrogatesWithFFFD); - Vector<uint8_t> result(utf8.length()); - std::memcpy(result.data(), utf8.data(), utf8.length()); + StringUTF8Adaptor utf8( + input, WTF::kStrictUTF8ConversionReplacingUnpairedSurrogatesWithFFFD); + Vector<uint8_t> result(utf8.size()); + std::memcpy(result.data(), utf8.data(), utf8.size()); return result; } case FormatOption::kLocalStorageDetectFormat: {
diff --git a/third_party/blink/renderer/modules/webdatabase/sqlite/sandboxed_vfs.cc b/third_party/blink/renderer/modules/webdatabase/sqlite/sandboxed_vfs.cc index c15c2e931..04a20ad 100644 --- a/third_party/blink/renderer/modules/webdatabase/sqlite/sandboxed_vfs.cc +++ b/third_party/blink/renderer/modules/webdatabase/sqlite/sandboxed_vfs.cc
@@ -160,7 +160,7 @@ sqlite3* connection; constexpr int open_flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_PRIVATECACHE; - int status = sqlite3_open_v2(filename.Utf8().data(), &connection, open_flags, + int status = sqlite3_open_v2(filename.Utf8().c_str(), &connection, open_flags, kSqliteVfsName); if (status != SQLITE_OK) { // SQLite creates a connection handle in most cases where open fails.
diff --git a/third_party/blink/renderer/modules/webdatabase/sqlite/sqlite_statement.cc b/third_party/blink/renderer/modules/webdatabase/sqlite/sqlite_statement.cc index 3e8725e..10e4689 100644 --- a/third_party/blink/renderer/modules/webdatabase/sqlite/sqlite_statement.cc +++ b/third_party/blink/renderer/modules/webdatabase/sqlite/sqlite_statement.cc
@@ -88,7 +88,7 @@ DCHECK(!is_prepared_); #endif - CString query = query_.StripWhiteSpace().Utf8(); + std::string query = query_.StripWhiteSpace().Utf8(); // Need to pass non-stack |const char*| and |sqlite3_stmt*| to avoid race // with Oilpan stack scanning. @@ -98,13 +98,14 @@ *statement = nullptr; int error; { - SQL_DVLOG(1) << "SQL - prepare - " << query.data(); + SQL_DVLOG(1) << "SQL - prepare - " << query; // Pass the length of the string including the null character to // sqlite3_prepare_v3(); this lets SQLite avoid an extra string copy. - wtf_size_t length_including_null_character = query.length() + 1; + wtf_size_t length_including_null_character = + static_cast<wtf_size_t>(query.length()) + 1; - error = sqlite3_prepare_v3(database_.Sqlite3Handle(), query.data(), + error = sqlite3_prepare_v3(database_.Sqlite3Handle(), query.c_str(), length_including_null_character, /* prepFlags= */ 0, statement.get(), tail.get()); } @@ -112,7 +113,7 @@ if (error != SQLITE_OK) { SQL_DVLOG(1) << "sqlite3_prepare_v3 failed (" << error << ")\n" - << query.data() << "\n" + << query << "\n" << sqlite3_errmsg(database_.Sqlite3Handle()); } else if (*tail && **tail) { error = SQLITE_ERROR;
diff --git a/third_party/blink/renderer/modules/webgl/webgl2_compute_rendering_context_base.cc b/third_party/blink/renderer/modules/webgl/webgl2_compute_rendering_context_base.cc index 9e4fcd5b..ebfc60d 100644 --- a/third_party/blink/renderer/modules/webgl/webgl2_compute_rendering_context_base.cc +++ b/third_party/blink/renderer/modules/webgl/webgl2_compute_rendering_context_base.cc
@@ -93,7 +93,7 @@ return 0; return ContextGL()->GetProgramResourceIndex( - ObjectOrZero(program), program_interface, name.Utf8().data()); + ObjectOrZero(program), program_interface, name.Utf8().c_str()); } String WebGL2ComputeRenderingContextBase::getProgramResourceName( @@ -282,7 +282,7 @@ return WrapLocation(script_state, -1, program, program_interface); GLint location = ContextGL()->GetProgramResourceLocation( - ObjectOrZero(program), program_interface, name.Utf8().data()); + ObjectOrZero(program), program_interface, name.Utf8().c_str()); return WrapLocation(script_state, location, program, program_interface); }
diff --git a/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.cc b/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.cc index 0a2e104..b37f9c3 100644 --- a/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.cc +++ b/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.cc
@@ -2430,7 +2430,7 @@ return -1; return ContextGL()->GetFragDataLocation(ObjectOrZero(program), - name.Utf8().data()); + name.Utf8().c_str()); } void WebGL2RenderingContextBase::uniform1ui( @@ -4783,7 +4783,7 @@ return 0; return ContextGL()->GetUniformBlockIndex(ObjectOrZero(program), - uniform_block_name.Utf8().data()); + uniform_block_name.Utf8().c_str()); } bool WebGL2RenderingContextBase::ValidateUniformBlockIndex(
diff --git a/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc b/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc index 4629ea6..18dead5 100644 --- a/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc +++ b/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc
@@ -603,9 +603,9 @@ builder); FormatWebGLStatusString( "Reset notification strategy", - String::Format("0x%04x", info.reset_notification_strategy).Utf8().data(), + String::Format("0x%04x", info.reset_notification_strategy).Utf8().c_str(), builder); - FormatWebGLStatusString("ErrorMessage", info.error_message.Utf8().data(), + FormatWebGLStatusString("ErrorMessage", info.error_message.Utf8().c_str(), builder); builder.Append('.'); return builder.ToString(); @@ -1764,7 +1764,7 @@ return; } ContextGL()->BindAttribLocation(ObjectOrZero(program), index, - name.Utf8().data()); + name.Utf8().c_str()); } bool WebGLRenderingContextBase::ValidateAndUpdateBufferBindTarget( @@ -2893,7 +2893,7 @@ return 0; } return ContextGL()->GetAttribLocation(ObjectOrZero(program), - name.Utf8().data()); + name.Utf8().c_str()); } bool WebGLRenderingContextBase::ValidateBufferTarget(const char* function_name, @@ -3727,7 +3727,7 @@ } // Now need to look this up by name again to find its location GLint loc = ContextGL()->GetUniformLocation( - ObjectOrZero(program), name_builder.ToString().Utf8().data()); + ObjectOrZero(program), name_builder.ToString().Utf8().c_str()); if (loc == location) { // Found it. Use the type in the ActiveInfo to determine the return // type. @@ -3966,7 +3966,7 @@ return nullptr; } GLint uniform_location = ContextGL()->GetUniformLocation( - ObjectOrZero(program), name.Utf8().data()); + ObjectOrZero(program), name.Utf8().c_str()); if (uniform_location == -1) return nullptr; return WebGLUniformLocation::Create(program, uniform_location);
diff --git a/third_party/blink/renderer/modules/websockets/dom_websocket.cc b/third_party/blink/renderer/modules/websockets/dom_websocket.cc index 9671c6c..a3da2cf 100644 --- a/third_party/blink/renderer/modules/websockets/dom_websocket.cc +++ b/third_party/blink/renderer/modules/websockets/dom_websocket.cc
@@ -68,6 +68,7 @@ #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" #include "third_party/blink/renderer/platform/wtf/text/cstring.h" #include "third_party/blink/renderer/platform/wtf/text/string_builder.h" +#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h" #include "third_party/blink/renderer/platform/wtf/wtf_size_t.h" static const size_t kMaxByteSizeForHistogram = 100 * 1000 * 1000; @@ -460,8 +461,6 @@ void DOMWebSocket::send(const String& message, ExceptionState& exception_state) { - CString encoded_message = message.Utf8(); - NETWORK_DVLOG(1) << "WebSocket " << this << " send() Sending String " << message; if (state_ == kConnecting) { @@ -470,6 +469,7 @@ } // No exception is raised if the connection was once established but has // subsequently been closed. + std::string encoded_message = message.Utf8(); if (state_ == kClosing || state_ == kClosed) { UpdateBufferedAmountAfterClose(encoded_message.length()); return; @@ -593,8 +593,8 @@ } // Bindings specify USVString, so unpaired surrogates are already replaced // with U+FFFD. - CString utf8 = reason.Utf8(); - if (utf8.length() > kMaxReasonSizeInBytes) { + StringUTF8Adaptor utf8(reason); + if (utf8.size() > kMaxReasonSizeInBytes) { exception_state.ThrowDOMException( DOMExceptionCode::kSyntaxError, "The message must not be greater than " + @@ -602,10 +602,10 @@ return; } if (!reason.IsEmpty() && !reason.Is8Bit()) { - DCHECK_GT(utf8.length(), 0u); + DCHECK_GT(utf8.size(), 0u); // reason might contain unpaired surrogates. Reconstruct it from // utf8. - cleansed_reason = String::FromUTF8(utf8.data(), utf8.length()); + cleansed_reason = String::FromUTF8(utf8.data(), utf8.size()); } }
diff --git a/third_party/blink/renderer/modules/websockets/dom_websocket_test.cc b/third_party/blink/renderer/modules/websockets/dom_websocket_test.cc index c7a6c143..41bf413 100644 --- a/third_party/blink/renderer/modules/websockets/dom_websocket_test.cc +++ b/third_party/blink/renderer/modules/websockets/dom_websocket_test.cc
@@ -50,7 +50,7 @@ ~MockWebSocketChannel() override = default; MOCK_METHOD2(Connect, bool(const KURL&, const String&)); - MOCK_METHOD1(Send, void(const CString&)); + MOCK_METHOD1(Send, void(const std::string&)); MOCK_METHOD3(Send, void(const DOMArrayBuffer&, unsigned, unsigned)); MOCK_METHOD1(SendMock, void(BlobDataHandle*)); void Send(scoped_refptr<BlobDataHandle> handle) override { @@ -714,7 +714,7 @@ EXPECT_CALL(websocket_scope.Channel(), Connect(KURL("ws://example.com/"), String())) .WillOnce(Return(true)); - EXPECT_CALL(websocket_scope.Channel(), Send(CString("hello"))); + EXPECT_CALL(websocket_scope.Channel(), Send(std::string("hello"))); } websocket_scope.Socket().Connect("ws://example.com/", Vector<String>(), scope.GetExceptionState()); @@ -737,7 +737,7 @@ Connect(KURL("ws://example.com/"), String())) .WillOnce(Return(true)); EXPECT_CALL(websocket_scope.Channel(), - Send(CString("\xe7\x8b\x90\xe0\xa4\x94"))); + Send(std::string("\xe7\x8b\x90\xe0\xa4\x94"))); } websocket_scope.Socket().Connect("ws://example.com/", Vector<String>(), scope.GetExceptionState()); @@ -863,8 +863,8 @@ EXPECT_CALL(websocket_scope.Channel(), Connect(KURL("ws://example.com/"), String())) .WillOnce(Return(true)); - EXPECT_CALL(websocket_scope.Channel(), Send(CString("hello"))); - EXPECT_CALL(websocket_scope.Channel(), Send(CString("world"))); + EXPECT_CALL(websocket_scope.Channel(), Send(std::string("hello"))); + EXPECT_CALL(websocket_scope.Channel(), Send(std::string("world"))); } websocket_scope.Socket().Connect("ws://example.com/", Vector<String>(), scope.GetExceptionState()); @@ -893,7 +893,7 @@ EXPECT_CALL(websocket_scope.Channel(), Connect(KURL("ws://example.com/"), String())) .WillOnce(Return(true)); - EXPECT_CALL(websocket_scope.Channel(), Send(CString("hello"))); + EXPECT_CALL(websocket_scope.Channel(), Send(std::string("hello"))); } websocket_scope.Socket().Connect("ws://example.com/", Vector<String>(), scope.GetExceptionState());
diff --git a/third_party/blink/renderer/modules/websockets/web_pepper_socket_impl.cc b/third_party/blink/renderer/modules/websockets/web_pepper_socket_impl.cc index 745ada6e..2339e11 100644 --- a/third_party/blink/renderer/modules/websockets/web_pepper_socket_impl.cc +++ b/third_party/blink/renderer/modules/websockets/web_pepper_socket_impl.cc
@@ -82,7 +82,7 @@ bool WebPepperSocketImpl::SendText(const WebString& message) { String core_message = message; - CString encoded_message = core_message.Utf8(); + std::string encoded_message = core_message.Utf8(); size_t size = encoded_message.length(); buffered_amount_ += size; if (is_closing_or_closed_)
diff --git a/third_party/blink/renderer/modules/websockets/websocket_channel.h b/third_party/blink/renderer/modules/websockets/websocket_channel.h index 31c006a7..546e4aa 100644 --- a/third_party/blink/renderer/modules/websockets/websocket_channel.h +++ b/third_party/blink/renderer/modules/websockets/websocket_channel.h
@@ -70,7 +70,7 @@ }; virtual bool Connect(const KURL&, const String& protocol) = 0; - virtual void Send(const CString&) = 0; + virtual void Send(const std::string&) = 0; virtual void Send(const DOMArrayBuffer&, unsigned byte_offset, unsigned byte_length) = 0;
diff --git a/third_party/blink/renderer/modules/websockets/websocket_channel_impl.cc b/third_party/blink/renderer/modules/websockets/websocket_channel_impl.cc index 492980a..0942ce9 100644 --- a/third_party/blink/renderer/modules/websockets/websocket_channel_impl.cc +++ b/third_party/blink/renderer/modules/websockets/websocket_channel_impl.cc
@@ -103,7 +103,7 @@ class WebSocketChannelImpl::Message : public GarbageCollectedFinalized<WebSocketChannelImpl::Message> { public: - explicit Message(const CString&); + explicit Message(const std::string&); explicit Message(scoped_refptr<BlobDataHandle>); explicit Message(DOMArrayBuffer*); // For WorkerWebSocketChannel @@ -115,7 +115,7 @@ MessageType type; - CString text; + std::string text; scoped_refptr<BlobDataHandle> blob_data_handle; Member<DOMArrayBuffer> array_buffer; std::unique_ptr<Vector<char>> vector_data; @@ -294,11 +294,11 @@ return Connect(url, protocol, std::move(socket_ptr)); } -void WebSocketChannelImpl::Send(const CString& message) { +void WebSocketChannelImpl::Send(const std::string& message) { NETWORK_DVLOG(1) << this << " Send(" << message << ") (CString argument)"; probe::DidSendWebSocketMessage(execution_context_, identifier_, WebSocketOpCode::kOpCodeText, true, - message.data(), message.length()); + message.c_str(), message.length()); messages_.push_back(MakeGarbageCollected<Message>(message)); ProcessSendQueue(); } @@ -415,7 +415,7 @@ identifier_ = 0; } -WebSocketChannelImpl::Message::Message(const CString& text) +WebSocketChannelImpl::Message::Message(const std::string& text) : type(kMessageTypeText), text(text) {} WebSocketChannelImpl::Message::Message( @@ -476,7 +476,8 @@ switch (message->type) { case kMessageTypeText: SendInternal(WebSocketHandle::kMessageTypeText, message->text.data(), - message->text.length(), &consumed_buffered_amount); + static_cast<wtf_size_t>(message->text.length()), + &consumed_buffered_amount); break; case kMessageTypeBlob: CHECK(!blob_loader_);
diff --git a/third_party/blink/renderer/modules/websockets/websocket_channel_impl.h b/third_party/blink/renderer/modules/websockets/websocket_channel_impl.h index 317ba3b..fd35395ad 100644 --- a/third_party/blink/renderer/modules/websockets/websocket_channel_impl.h +++ b/third_party/blink/renderer/modules/websockets/websocket_channel_impl.h
@@ -92,7 +92,7 @@ // WebSocketChannel functions. bool Connect(const KURL&, const String& protocol) override; - void Send(const CString& message) override; + void Send(const std::string& message) override; void Send(const DOMArrayBuffer&, unsigned byte_offset, unsigned byte_length) override;
diff --git a/third_party/blink/renderer/modules/websockets/websocket_channel_impl_test.cc b/third_party/blink/renderer/modules/websockets/websocket_channel_impl_test.cc index c7989347..007cee33 100644 --- a/third_party/blink/renderer/modules/websockets/websocket_channel_impl_test.cc +++ b/third_party/blink/renderer/modules/websockets/websocket_channel_impl_test.cc
@@ -192,7 +192,7 @@ std::string(negation ? "doesn't equal" : "equals") + " to \"" + url_string + "\"") { const KURL url(NullURL(), url_string); - *result_listener << "where the url is \"" << arg.GetString().Utf8().data() + *result_listener << "where the url is \"" << arg.GetString().Utf8().c_str() << "\""; return arg == url; }
diff --git a/third_party/blink/renderer/platform/BUILD.gn b/third_party/blink/renderer/platform/BUILD.gn index c8a9070..a29cdced 100644 --- a/third_party/blink/renderer/platform/BUILD.gn +++ b/third_party/blink/renderer/platform/BUILD.gn
@@ -469,6 +469,7 @@ "date_components.h", "exported/file_path_conversion.cc", "exported/interface_registry.cc", + "exported/mediastream/media_stream_audio_level_calculator.cc", "exported/mediastream/media_stream_audio_processor_options.cc", "exported/mediastream/media_stream_audio_source.cc", "exported/mediastream/media_stream_audio_track.cc",
diff --git a/third_party/blink/renderer/platform/animation/compositor_animation.cc b/third_party/blink/renderer/platform/animation/compositor_animation.cc index 759903e..d7f6df2 100644 --- a/third_party/blink/renderer/platform/animation/compositor_animation.cc +++ b/third_party/blink/renderer/platform/animation/compositor_animation.cc
@@ -27,7 +27,7 @@ std::unique_ptr<cc::AnimationOptions> options, std::unique_ptr<cc::AnimationEffectTimings> effect_timings) { return std::make_unique<CompositorAnimation>(cc::WorkletAnimation::Create( - worklet_animation_id, std::string(name.Utf8().data()), playback_rate, + worklet_animation_id, name.Utf8(), playback_rate, std::move(scroll_timeline), std::move(options), std::move(effect_timings))); }
diff --git a/third_party/blink/renderer/platform/audio/hrtf_elevation.cc b/third_party/blink/renderer/platform/audio/hrtf_elevation.cc index b8fc130..ca1afacb 100644 --- a/third_party/blink/renderer/platform/audio/hrtf_elevation.cc +++ b/third_party/blink/renderer/platform/audio/hrtf_elevation.cc
@@ -78,7 +78,7 @@ AudioBusMap::iterator iterator = audio_bus_map.find(subject_name); if (iterator == audio_bus_map.end()) { scoped_refptr<AudioBus> concatenated_impulse_responses( - AudioBus::GetDataResource(subject_name.Utf8().data(), + AudioBus::GetDataResource(subject_name.Utf8().c_str(), kResponseSampleRate)); DCHECK(concatenated_impulse_responses); if (!concatenated_impulse_responses)
diff --git a/third_party/blink/renderer/platform/bindings/runtime_call_stats.cc b/third_party/blink/renderer/platform/bindings/runtime_call_stats.cc index f9dcbd94..69883bb 100644 --- a/third_party/blink/renderer/platform/bindings/runtime_call_stats.cc +++ b/third_party/blink/renderer/platform/bindings/runtime_call_stats.cc
@@ -17,9 +17,8 @@ // Wrapper function defined in WebKit.h void LogRuntimeCallStats() { - LOG(INFO) - << "\n" - << RuntimeCallStats::From(MainThreadIsolate())->ToString().Utf8().data(); + LOG(INFO) << "\n" + << RuntimeCallStats::From(MainThreadIsolate())->ToString().Utf8(); } namespace {
diff --git a/third_party/blink/renderer/platform/blob/blob_data.cc b/third_party/blink/renderer/platform/blob/blob_data.cc index cf420a5..70275114 100644 --- a/third_party/blink/renderer/platform/blob/blob_data.cc +++ b/third_party/blink/renderer/platform/blob/blob_data.cc
@@ -221,7 +221,7 @@ bool do_normalize_line_endings_to_native) { DCHECK_EQ(file_composition_, FileCompositionStatus::NO_UNKNOWN_SIZE_FILES) << "Blobs with a unknown-size file cannot have other items."; - CString utf8_text = UTF8Encoding().Encode(text, WTF::kNoUnencodables); + std::string utf8_text = UTF8Encoding().Encode(text, WTF::kNoUnencodables); if (do_normalize_line_endings_to_native) { if (utf8_text.length() >
diff --git a/third_party/blink/renderer/platform/exported/file_path_conversion_test.cc b/third_party/blink/renderer/platform/exported/file_path_conversion_test.cc index 81ac9b31..842f965 100644 --- a/third_party/blink/renderer/platform/exported/file_path_conversion_test.cc +++ b/third_party/blink/renderer/platform/exported/file_path_conversion_test.cc
@@ -43,10 +43,8 @@ EXPECT_EQ("path", FilePathToWebString(base::FilePath(FILE_PATH_LITERAL("path")))); - EXPECT_STREQ(test8bit_latin1.Utf8().data(), - FilePathToWebString(path_latin1).Utf8().data()); - EXPECT_STREQ(test16bit_utf16.Utf8().data(), - FilePathToWebString(path_utf16).Utf8().data()); + EXPECT_EQ(test8bit_latin1.Utf8(), FilePathToWebString(path_latin1).Utf8()); + EXPECT_EQ(test16bit_utf16.Utf8(), FilePathToWebString(path_utf16).Utf8()); } } // namespace blink
diff --git a/content/renderer/media/stream/media_stream_audio_level_calculator.cc b/third_party/blink/renderer/platform/exported/mediastream/media_stream_audio_level_calculator.cc similarity index 93% rename from content/renderer/media/stream/media_stream_audio_level_calculator.cc rename to third_party/blink/renderer/platform/exported/mediastream/media_stream_audio_level_calculator.cc index cd5bd64..369b07b0d 100644 --- a/content/renderer/media/stream/media_stream_audio_level_calculator.cc +++ b/third_party/blink/renderer/platform/exported/mediastream/media_stream_audio_level_calculator.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "content/renderer/media/stream/media_stream_audio_level_calculator.h" +#include "third_party/blink/public/platform/modules/mediastream/media_stream_audio_level_calculator.h" #include <cmath> #include <limits> @@ -11,7 +11,7 @@ #include "base/stl_util.h" #include "media/base/audio_bus.h" -namespace content { +namespace blink { namespace { @@ -79,4 +79,4 @@ } } -} // namespace content +} // namespace blink
diff --git a/third_party/blink/renderer/platform/fonts/android/font_unique_name_lookup_android.cc b/third_party/blink/renderer/platform/fonts/android/font_unique_name_lookup_android.cc index 166fe77..1f426a0 100644 --- a/third_party/blink/renderer/platform/fonts/android/font_unique_name_lookup_android.cc +++ b/third_party/blink/renderer/platform/fonts/android/font_unique_name_lookup_android.cc
@@ -17,7 +17,7 @@ if (!EnsureMatchingServiceConnected()) return nullptr; base::Optional<FontTableMatcher::MatchResult> match_result = - font_table_matcher_->MatchName(font_unique_name.Utf8().data()); + font_table_matcher_->MatchName(font_unique_name.Utf8().c_str()); if (!match_result) return nullptr; return SkTypeface::MakeFromFile(match_result->font_path.c_str(),
diff --git a/third_party/blink/renderer/platform/fonts/font_cache.cc b/third_party/blink/renderer/platform/fonts/font_cache.cc index 32f740f..17e6db2 100644 --- a/third_party/blink/renderer/platform/fonts/font_cache.cc +++ b/third_party/blink/renderer/platform/fonts/font_cache.cc
@@ -281,7 +281,7 @@ // only from grd/xtb and all ASCII, and b) at most only a few times per // setting change/script. return String::FromUTF8( - gfx::FontList::FirstAvailableOrFirst(families.Utf8().data()).c_str()); + gfx::FontList::FirstAvailableOrFirst(families.Utf8().c_str())); } SimpleFontData* FontCache::GetNonRetainedLastResortFallbackFont( @@ -457,8 +457,7 @@ } sk_sp<SkTypeface> FontCache::CreateTypefaceFromUniqueName( - const FontFaceCreationParams& creation_params, - CString& name) { + const FontFaceCreationParams& creation_params) { FontUniqueNameLookup* unique_name_lookup = FontGlobalContext::Get()->GetFontUniqueNameLookup(); DCHECK(unique_name_lookup);
diff --git a/third_party/blink/renderer/platform/fonts/font_cache.h b/third_party/blink/renderer/platform/fonts/font_cache.h index 9afa2d4..886405d 100644 --- a/third_party/blink/renderer/platform/fonts/font_cache.h +++ b/third_party/blink/renderer/platform/fonts/font_cache.h
@@ -257,8 +257,7 @@ const SimpleFontData* font_data_to_substitute, FontFallbackPriority = FontFallbackPriority::kText); sk_sp<SkTypeface> CreateTypefaceFromUniqueName( - const FontFaceCreationParams& creation_params, - CString& name); + const FontFaceCreationParams& creation_params); static Bcp47Vector GetBcp47LocaleForRequest( const FontDescription& font_description, @@ -299,7 +298,7 @@ sk_sp<SkTypeface> CreateTypeface(const FontDescription&, const FontFaceCreationParams&, - CString& name); + std::string& name); #if defined(OS_ANDROID) || defined(OS_LINUX) static AtomicString GetFamilyNameForCharacter(SkFontMgr*,
diff --git a/third_party/blink/renderer/platform/fonts/font_custom_platform_data.cc b/third_party/blink/renderer/platform/fonts/font_custom_platform_data.cc index 51edd9d..225e850 100644 --- a/third_party/blink/renderer/platform/fonts/font_custom_platform_data.cc +++ b/third_party/blink/renderer/platform/fonts/font_custom_platform_data.cc
@@ -132,7 +132,7 @@ } } - return FontPlatformData(std::move(return_typeface), CString(), size, + return FontPlatformData(std::move(return_typeface), std::string(), size, bold && !base_typeface_->isBold(), italic && !base_typeface_->isItalic(), orientation); }
diff --git a/third_party/blink/renderer/platform/fonts/font_platform_data.cc b/third_party/blink/renderer/platform/fonts/font_platform_data.cc index b3b02d3..d7d3dc3a 100644 --- a/third_party/blink/renderer/platform/fonts/font_platform_data.cc +++ b/third_party/blink/renderer/platform/fonts/font_platform_data.cc
@@ -114,7 +114,7 @@ #if !defined(OS_WIN) && !defined(OS_MACOSX) src.family_.data(), #else - CString(), + std::string(), #endif text_size, src.synthetic_bold_, @@ -123,7 +123,7 @@ } FontPlatformData::FontPlatformData(sk_sp<SkTypeface> typeface, - const CString& family, + const std::string& family, float text_size, bool synthetic_bold, bool synthetic_italic, @@ -285,7 +285,7 @@ #if !defined(OS_MACOSX) && !defined(OS_WIN) // static WebFontRenderStyle FontPlatformData::QuerySystemRenderStyle( - const CString& family, + const std::string& family, float text_size, SkFontStyle font_style) { WebFontRenderStyle result;
diff --git a/third_party/blink/renderer/platform/fonts/font_platform_data.h b/third_party/blink/renderer/platform/fonts/font_platform_data.h index 6e4bf97a..8e5f1b2 100644 --- a/third_party/blink/renderer/platform/fonts/font_platform_data.h +++ b/third_party/blink/renderer/platform/fonts/font_platform_data.h
@@ -79,7 +79,7 @@ FontOrientation = FontOrientation::kHorizontal); FontPlatformData(const FontPlatformData& src, float text_size); FontPlatformData(const sk_sp<SkTypeface>, - const CString& name, + const std::string& name, float text_size, bool synthetic_bold, bool synthetic_italic, @@ -145,7 +145,7 @@ private: #if !defined(OS_WIN) && !defined(OS_MACOSX) - WebFontRenderStyle QuerySystemRenderStyle(const CString& family, + WebFontRenderStyle QuerySystemRenderStyle(const std::string& family, float text_size, SkFontStyle); #endif @@ -157,7 +157,7 @@ sk_sp<SkTypeface> typeface_; #if !defined(OS_WIN) && !defined(OS_MACOSX) - CString family_; + std::string family_; #endif public:
diff --git a/third_party/blink/renderer/platform/fonts/fuchsia/font_cache_fuchsia.cc b/third_party/blink/renderer/platform/fonts/fuchsia/font_cache_fuchsia.cc index cff0f61..4ce9d60 100644 --- a/third_party/blink/renderer/platform/fonts/fuchsia/font_cache_fuchsia.cc +++ b/third_party/blink/renderer/platform/fonts/fuchsia/font_cache_fuchsia.cc
@@ -50,11 +50,11 @@ const SimpleFontData* font_data_to_substitute, FontFallbackPriority fallback_priority) { sk_sp<SkFontMgr> font_mgr(SkFontMgr::RefDefault()); - CString family_name = font_description.Family().Family().Utf8(); + std::string family_name = font_description.Family().Family().Utf8(); Bcp47Vector locales = GetBcp47LocaleForRequest(font_description, fallback_priority); sk_sp<SkTypeface> typeface(font_mgr->matchFamilyStyleCharacter( - family_name.data(), font_description.SkiaFontStyle(), locales.data(), + family_name.c_str(), font_description.SkiaFontStyle(), locales.data(), locales.size(), character)); if (!typeface) return nullptr; @@ -65,7 +65,7 @@ font_description.IsSyntheticItalic() && !typeface->isItalic(); auto font_data = std::make_unique<FontPlatformData>( - std::move(typeface), CString(), font_description.EffectiveFontSize(), + std::move(typeface), std::string(), font_description.EffectiveFontSize(), synthetic_bold, synthetic_italic, font_description.Orientation()); return FontDataFromFontPlatformData(font_data.get(), kDoNotRetain);
diff --git a/third_party/blink/renderer/platform/fonts/linux/font_unique_name_lookup_linux.cc b/third_party/blink/renderer/platform/fonts/linux/font_unique_name_lookup_linux.cc index c8837198..1c3b8d04 100644 --- a/third_party/blink/renderer/platform/fonts/linux/font_unique_name_lookup_linux.cc +++ b/third_party/blink/renderer/platform/fonts/linux/font_unique_name_lookup_linux.cc
@@ -25,7 +25,7 @@ Platform::Current() ->GetSandboxSupport() ->MatchFontByPostscriptNameOrFullFontName( - font_unique_name.Utf8(WTF::kStrictUTF8Conversion).data(), + font_unique_name.Utf8(WTF::kStrictUTF8Conversion).c_str(), &uniquely_matched_font); if (!uniquely_matched_font.filename.size()) return nullptr;
diff --git a/third_party/blink/renderer/platform/fonts/mac/font_platform_data_mac.mm b/third_party/blink/renderer/platform/fonts/mac/font_platform_data_mac.mm index e42f3193..16bcce4 100644 --- a/third_party/blink/renderer/platform/fonts/mac/font_platform_data_mac.mm +++ b/third_party/blink/renderer/platform/fonts/mac/font_platform_data_mac.mm
@@ -146,8 +146,8 @@ return std::make_unique<FontPlatformData>( std::move(typeface), - CString(), // family_ doesn't exist on Mac, this avoids conversion from - // NSString which requires including a //base header + std::string(), // family_ doesn't exist on Mac, this avoids conversion + // from NSString which requires including a //base header size, synthetic_bold, synthetic_italic, orientation); }
diff --git a/third_party/blink/renderer/platform/fonts/shaping/shape_result_bloberizer_test.cc b/third_party/blink/renderer/platform/fonts/shaping/shape_result_bloberizer_test.cc index 2d14ed37..17be9da 100644 --- a/third_party/blink/renderer/platform/fonts/shaping/shape_result_bloberizer_test.cc +++ b/third_party/blink/renderer/platform/fonts/shaping/shape_result_bloberizer_test.cc
@@ -24,7 +24,7 @@ static scoped_refptr<SimpleFontData> CreateTestSimpleFontData( bool force_rotation = false) { FontPlatformData platform_data( - SkTypeface::MakeDefault(), CString(), 10, false, false, + SkTypeface::MakeDefault(), std::string(), 10, false, false, force_rotation ? FontOrientation::kVerticalUpright : FontOrientation::kHorizontal); return SimpleFontData::Create(platform_data, nullptr);
diff --git a/third_party/blink/renderer/platform/fonts/shaping/shape_result_inline_headers.h b/third_party/blink/renderer/platform/fonts/shaping/shape_result_inline_headers.h index 76ee6091..c14d3a0 100644 --- a/third_party/blink/renderer/platform/fonts/shaping/shape_result_inline_headers.h +++ b/third_party/blink/renderer/platform/fonts/shaping/shape_result_inline_headers.h
@@ -251,37 +251,6 @@ template <bool has_non_zero_glyph_offsets> struct iterator final {}; - // For non-zero glyph offset array - template <> - struct iterator<true> final { - // The constructor for ShapeResult - explicit iterator(const GlyphOffsetArray& array) - : pointer(array.storage_.get()) { - DCHECK(pointer); - } - - // The constructor for ShapeResultView - explicit iterator(const GlyphDataRange& range) : pointer(range.offsets) { - DCHECK(pointer); - } - - GlyphOffset operator*() const { return *pointer; } - void operator++() { ++pointer; } - - const GlyphOffset* pointer; - }; - - // For zero glyph offset array - template <> - struct iterator<false> final { - explicit iterator(const GlyphOffsetArray& array) { - DCHECK(!array.HasStorage()); - } - explicit iterator(const GlyphDataRange& range) { DCHECK(!range.offsets); } - GlyphOffset operator*() const { return GlyphOffset(); } - void operator++() {} - }; - template <bool has_non_zero_glyph_offsets> iterator<has_non_zero_glyph_offsets> GetIterator() const { return iterator<has_non_zero_glyph_offsets>(*this); @@ -495,6 +464,37 @@ float width_; }; +// For non-zero glyph offset array +template <> +struct ShapeResult::RunInfo::GlyphOffsetArray::iterator<true> final { + // The constructor for ShapeResult + explicit iterator(const GlyphOffsetArray& array) + : pointer(array.storage_.get()) { + DCHECK(pointer); + } + + // The constructor for ShapeResultView + explicit iterator(const GlyphDataRange& range) : pointer(range.offsets) { + DCHECK(pointer); + } + + GlyphOffset operator*() const { return *pointer; } + void operator++() { ++pointer; } + + const GlyphOffset* pointer; +}; + +// For zero glyph offset array +template <> +struct ShapeResult::RunInfo::GlyphOffsetArray::iterator<false> final { + explicit iterator(const GlyphOffsetArray& array) { + DCHECK(!array.HasStorage()); + } + explicit iterator(const GlyphDataRange& range) { DCHECK(!range.offsets); } + GlyphOffset operator*() const { return GlyphOffset(); } + void operator++() {} +}; + // Find the range of HarfBuzzRunGlyphData for the specified character index // range. This function uses binary search twice, hence O(2 log n). inline ShapeResult::RunInfo::GlyphDataRange
diff --git a/third_party/blink/renderer/platform/fonts/skia/font_cache_skia.cc b/third_party/blink/renderer/platform/fonts/skia/font_cache_skia.cc index b81c71c..2ce9881f 100644 --- a/third_party/blink/renderer/platform/fonts/skia/font_cache_skia.cc +++ b/third_party/blink/renderer/platform/fonts/skia/font_cache_skia.cc
@@ -193,7 +193,7 @@ sk_sp<SkTypeface> FontCache::CreateTypeface( const FontDescription& font_description, const FontFaceCreationParams& creation_params, - CString& name) { + std::string& name) { #if !defined(OS_WIN) && !defined(OS_ANDROID) && !defined(OS_FUCHSIA) // TODO(fuchsia): Revisit this and other font code for Fuchsia. @@ -222,7 +222,7 @@ // TODO(vmpstr): Deal with paint typeface here. if (sideloaded_fonts_) { HashMap<String, sk_sp<SkTypeface>, CaseFoldingHash>::iterator - sideloaded_font = sideloaded_fonts_->find(name.data()); + sideloaded_font = sideloaded_fonts_->find(name.c_str()); if (sideloaded_font != sideloaded_fonts_->end()) return sideloaded_font->value; } @@ -235,7 +235,7 @@ // Manager. On Windows the font manager is always present. if (font_manager_) { auto tf = sk_sp<SkTypeface>(font_manager_->matchFamilyStyle( - name.data(), font_description.SkiaFontStyle())); + name.c_str(), font_description.SkiaFontStyle())); return tf; } #endif @@ -243,7 +243,7 @@ // FIXME: Use m_fontManager, matchFamilyStyle instead of // legacyCreateTypeface on all platforms. return SkTypeface_Factory::FromFamilyNameAndFontStyle( - name.data(), font_description.SkiaFontStyle()); + name.c_str(), font_description.SkiaFontStyle()); } #if !defined(OS_WIN) @@ -252,13 +252,13 @@ const FontFaceCreationParams& creation_params, float font_size, AlternateFontName alternate_name) { - CString name; + std::string name; sk_sp<SkTypeface> typeface; #if defined(OS_ANDROID) || defined(OS_LINUX) if (alternate_name == AlternateFontName::kLocalUniqueFace && RuntimeEnabledFeatures::FontSrcLocalMatchingEnabled()) { - typeface = CreateTypefaceFromUniqueName(creation_params, name); + typeface = CreateTypefaceFromUniqueName(creation_params); } else { typeface = CreateTypeface(font_description, creation_params, name); }
diff --git a/third_party/blink/renderer/platform/fonts/win/font_cache_skia_win.cc b/third_party/blink/renderer/platform/fonts/win/font_cache_skia_win.cc index 65cb248..7c2d603 100644 --- a/third_party/blink/renderer/platform/fonts/win/font_cache_skia_win.cc +++ b/third_party/blink/renderer/platform/fonts/win/font_cache_skia_win.cc
@@ -197,11 +197,11 @@ } if (use_skia_font_fallback_) { - CString family_name = font_description.Family().Family().Utf8(); + std::string family_name = font_description.Family().Family().Utf8(); Bcp47Vector locales = GetBcp47LocaleForRequest(font_description, fallback_priority); SkTypeface* typeface = font_manager_->matchFamilyStyleCharacter( - family_name.data(), font_description.SkiaFontStyle(), locales.data(), + family_name.c_str(), font_description.SkiaFontStyle(), locales.data(), locales.size(), character); if (typeface) { SkString skia_family; @@ -394,11 +394,11 @@ DCHECK_EQ(creation_params.CreationType(), kCreateFontByFamily); sk_sp<SkTypeface> typeface; - CString name; + std::string name; if (alternate_font_name == AlternateFontName::kLocalUniqueFace && RuntimeEnabledFeatures::FontSrcLocalMatchingEnabled()) { - typeface = CreateTypefaceFromUniqueName(creation_params, name); + typeface = CreateTypefaceFromUniqueName(creation_params); if (!typeface && sideloaded_fonts_) { typeface = FindUniqueFontNameFromSideloadedFonts(creation_params.Family(),
diff --git a/third_party/blink/renderer/platform/fonts/win/font_fallback_win.cc b/third_party/blink/renderer/platform/fonts/win/font_fallback_win.cc index 1c4ad7c..9ce036a 100644 --- a/third_party/blink/renderer/platform/fonts/win/font_fallback_win.cc +++ b/third_party/blink/renderer/platform/fonts/win/font_fallback_win.cc
@@ -51,7 +51,7 @@ SkFontMgr* font_manager) { String family = font_name; sk_sp<SkTypeface> tf( - font_manager->matchFamilyStyle(family.Utf8().data(), SkFontStyle())); + font_manager->matchFamilyStyle(family.Utf8().c_str(), SkFontStyle())); if (!tf) return false;
diff --git a/third_party/blink/renderer/platform/fonts/win/font_unique_name_lookup_win.cc b/third_party/blink/renderer/platform/fonts/win/font_unique_name_lookup_win.cc index ee12b3df..5b6bacd 100644 --- a/third_party/blink/renderer/platform/fonts/win/font_unique_name_lookup_win.cc +++ b/third_party/blink/renderer/platform/fonts/win/font_unique_name_lookup_win.cc
@@ -66,7 +66,7 @@ return nullptr; base::Optional<FontTableMatcher::MatchResult> match_result = - font_table_matcher_->MatchName(font_unique_name.Utf8().data()); + font_table_matcher_->MatchName(font_unique_name.Utf8()); if (!match_result) return nullptr;
diff --git a/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.cc b/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.cc index db269ac6..800a2f9 100644 --- a/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.cc +++ b/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.cc
@@ -1025,7 +1025,7 @@ if (new_output != s_previous_output) { LOG(ERROR) << "PaintArtifactCompositor::Update() done\n" << "Composited layers:\n" - << new_output.Utf8().data(); + << new_output.Utf8(); s_previous_output = new_output; } } @@ -1181,8 +1181,7 @@ LOG(ERROR) << LayersAsJSON(kLayerTreeIncludesDebugInfo | kLayerTreeIncludesPaintInvalidations) ->ToPrettyJSONString() - .Utf8() - .data(); + .Utf8(); } #endif
diff --git a/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.cc b/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.cc index fb00041..f0708a2 100644 --- a/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.cc +++ b/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.cc
@@ -343,9 +343,8 @@ #if DCHECK_IS_ON() DLOG(ERROR) << "Error: Chunk has a clip that escaped its layer's or " << "effect's clip.\ntarget_clip:\n" - << target_clip.ToTreeString().Utf8().data() - << "current_clip_:\n" - << current_clip_->ToTreeString().Utf8().data(); + << target_clip.ToTreeString().Utf8() << "current_clip_:\n" + << current_clip_->ToTreeString().Utf8(); #endif if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) NOTREACHED(); @@ -463,9 +462,8 @@ #if DCHECK_IS_ON() DLOG(ERROR) << "Error: Chunk has an effect that escapes layer's effect.\n" << "target_effect:\n" - << target_effect.ToTreeString().Utf8().data() - << "current_effect_:\n" - << current_effect_->ToTreeString().Utf8().data(); + << target_effect.ToTreeString().Utf8() << "current_effect_:\n" + << current_effect_->ToTreeString().Utf8(); has_pre_cap_effect_hierarchy_issue = true; #endif if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled())
diff --git a/third_party/blink/renderer/platform/graphics/graphics_context.cc b/third_party/blink/renderer/platform/graphics/graphics_context.cc index 8af7eff..41fe251 100644 --- a/third_party/blink/renderer/platform/graphics/graphics_context.cc +++ b/third_party/blink/renderer/platform/graphics/graphics_context.cc
@@ -1327,7 +1327,7 @@ return; DCHECK(canvas_); - sk_sp<SkData> url(SkData::MakeWithCString(link.GetString().Utf8().data())); + sk_sp<SkData> url(SkData::MakeWithCString(link.GetString().Utf8().c_str())); canvas_->Annotate(cc::PaintCanvas::AnnotationType::URL, dest_rect, std::move(url)); } @@ -1338,7 +1338,7 @@ return; DCHECK(canvas_); - sk_sp<SkData> sk_dest_name(SkData::MakeWithCString(dest_name.Utf8().data())); + sk_sp<SkData> sk_dest_name(SkData::MakeWithCString(dest_name.Utf8().c_str())); canvas_->Annotate(cc::PaintCanvas::AnnotationType::LINK_TO_DESTINATION, rect, std::move(sk_dest_name)); } @@ -1350,7 +1350,7 @@ DCHECK(canvas_); SkRect rect = SkRect::MakeXYWH(location.X(), location.Y(), 0, 0); - sk_sp<SkData> sk_name(SkData::MakeWithCString(name.Utf8().data())); + sk_sp<SkData> sk_name(SkData::MakeWithCString(name.Utf8().c_str())); canvas_->Annotate(cc::PaintCanvas::AnnotationType::NAMED_DESTINATION, rect, std::move(sk_name)); }
diff --git a/third_party/blink/renderer/platform/graphics/logging_canvas.cc b/third_party/blink/renderer/platform/graphics/logging_canvas.cc index c51983e..79dbd08 100644 --- a/third_party/blink/renderer/platform/graphics/logging_canvas.cc +++ b/third_party/blink/renderer/platform/graphics/logging_canvas.cc
@@ -745,7 +745,7 @@ } void ShowPaintRecord(const PaintRecord& record) { - DLOG(INFO) << RecordAsDebugString(record).Utf8().data(); + DLOG(INFO) << RecordAsDebugString(record).Utf8(); } std::unique_ptr<JSONArray> SkPictureAsJSON(const SkPicture& picture) { @@ -759,7 +759,7 @@ } void ShowSkPicture(const SkPicture& picture) { - DLOG(INFO) << SkPictureAsDebugString(picture).Utf8().data(); + DLOG(INFO) << SkPictureAsDebugString(picture).Utf8(); } } // namespace blink
diff --git a/third_party/blink/renderer/platform/graphics/paint/display_item.cc b/third_party/blink/renderer/platform/graphics/paint/display_item.cc index 721c500..8a46ce1 100644 --- a/third_party/blink/renderer/platform/graphics/paint/display_item.cc +++ b/third_party/blink/renderer/platform/graphics/paint/display_item.cc
@@ -179,8 +179,8 @@ String DisplayItem::Id::ToString() const { #if DCHECK_IS_ON() - return String::Format("%s:%s:%d", client.ToString().Utf8().data(), - DisplayItem::TypeAsDebugString(type).Utf8().data(), + return String::Format("%s:%s:%d", client.ToString().Utf8().c_str(), + DisplayItem::TypeAsDebugString(type).Utf8().c_str(), fragment); #else return String::Format("%p:%d:%d", &client, static_cast<int>(type), fragment); @@ -189,19 +189,19 @@ std::ostream& operator<<(std::ostream& os, DisplayItem::Type type) { #if DCHECK_IS_ON() - return os << DisplayItem::TypeAsDebugString(type).Utf8().data(); + return os << DisplayItem::TypeAsDebugString(type).Utf8(); #else return os << static_cast<int>(type); #endif } std::ostream& operator<<(std::ostream& os, const DisplayItem::Id& id) { - return os << id.ToString().Utf8().data(); + return os << id.ToString().Utf8(); } std::ostream& operator<<(std::ostream& os, const DisplayItem& item) { #if DCHECK_IS_ON() - return os << item.AsDebugString().Utf8().data(); + return os << item.AsDebugString().Utf8(); #else return os << "{\"id\": " << item.GetId() << "}"; #endif
diff --git a/third_party/blink/renderer/platform/graphics/paint/display_item_client.cc b/third_party/blink/renderer/platform/graphics/paint/display_item_client.cc index 3888b08..5560ac3d 100644 --- a/third_party/blink/renderer/platform/graphics/paint/display_item_client.cc +++ b/third_party/blink/renderer/platform/graphics/paint/display_item_client.cc
@@ -49,7 +49,7 @@ String DisplayItemClient::ToString() const { #if DCHECK_IS_ON() - return String::Format("%p:%s", this, SafeDebugName().Utf8().data()); + return String::Format("%p:%s", this, SafeDebugName().Utf8().c_str()); #else return String::Format("%p", this); #endif
diff --git a/third_party/blink/renderer/platform/graphics/paint/hit_test_data.cc b/third_party/blink/renderer/platform/graphics/paint/hit_test_data.cc index 2bd6a07..2e3570b1 100644 --- a/third_party/blink/renderer/platform/graphics/paint/hit_test_data.cc +++ b/third_party/blink/renderer/platform/graphics/paint/hit_test_data.cc
@@ -58,7 +58,7 @@ } std::ostream& operator<<(std::ostream& os, const HitTestData& data) { - return os << data.ToString().Utf8().data(); + return os << data.ToString().Utf8(); } } // namespace blink
diff --git a/third_party/blink/renderer/platform/graphics/paint/paint_chunk.cc b/third_party/blink/renderer/platform/graphics/paint/paint_chunk.cc index 0ace1ef1..c5926d2f 100644 --- a/third_party/blink/renderer/platform/graphics/paint/paint_chunk.cc +++ b/third_party/blink/renderer/platform/graphics/paint/paint_chunk.cc
@@ -29,8 +29,8 @@ sb.AppendFormat( "PaintChunk(begin=%zu, end=%zu, id=%s cacheable=%d props=(%s) bounds=%s " "known_to_be_opaque=%d", - begin_index, end_index, id.ToString().Utf8().data(), is_cacheable, - properties.ToString().Utf8().data(), bounds.ToString().Utf8().data(), + begin_index, end_index, id.ToString().Utf8().c_str(), is_cacheable, + properties.ToString().Utf8().c_str(), bounds.ToString().Utf8().c_str(), known_to_be_opaque); if (hit_test_data) { sb.Append(", hit_test_data="); @@ -41,7 +41,7 @@ } std::ostream& operator<<(std::ostream& os, const PaintChunk& chunk) { - return os << chunk.ToString().Utf8().data() << "\n"; + return os << chunk.ToString().Utf8() << "\n"; } } // namespace blink
diff --git a/third_party/blink/renderer/platform/graphics/paint/paint_controller.cc b/third_party/blink/renderer/platform/graphics/paint/paint_controller.cc index e3c410c6..de524d2 100644 --- a/third_party/blink/renderer/platform/graphics/paint/paint_controller.cc +++ b/third_party/blink/renderer/platform/graphics/paint/paint_controller.cc
@@ -225,11 +225,10 @@ new_display_item_list_); if (index != kNotFound) { ShowDebugData(); - NOTREACHED() - << "DisplayItem " << display_item.AsDebugString().Utf8().data() - << " has duplicated id with previous " - << new_display_item_list_[index].AsDebugString().Utf8().data() - << " (index=" << index << ")"; + NOTREACHED() << "DisplayItem " << display_item.AsDebugString().Utf8() + << " has duplicated id with previous " + << new_display_item_list_[index].AsDebugString().Utf8() + << " (index=" << index << ")"; } AddToIndicesByClientMap(display_item.Client(), new_display_item_list_.size() - 1, @@ -626,11 +625,9 @@ .get(); } LOG(INFO) << "new record:\n" - << (new_record ? RecordAsDebugString(*new_record).Utf8().data() - : "None"); + << (new_record ? RecordAsDebugString(*new_record).Utf8() : "None"); LOG(INFO) << "old record:\n" - << (old_record ? RecordAsDebugString(*old_record).Utf8().data() - : "None"); + << (old_record ? RecordAsDebugString(*old_record).Utf8() : "None"); ShowDebugData(); #else
diff --git a/third_party/blink/renderer/platform/graphics/paint/paint_controller_debug_data.cc b/third_party/blink/renderer/platform/graphics/paint/paint_controller_debug_data.cc index 31a2ec73..938214c8 100644 --- a/third_party/blink/renderer/platform/graphics/paint/paint_controller_debug_data.cc +++ b/third_party/blink/renderer/platform/graphics/paint/paint_controller_debug_data.cc
@@ -161,8 +161,7 @@ current_cached_subsequences_, current_paint_artifact_->PaintChunks(), current_list_flags) .ToString() - .Utf8() - .data(); + .Utf8(); LOG(ERROR) << "new display item list: " << DisplayItemListAsJSON( @@ -171,8 +170,7 @@ // The clients in new_display_item_list_ are all alive. flags | DisplayItemList::kClientKnownToBeAlive) .ToString() - .Utf8() - .data(); + .Utf8(); } void PaintController::ShowCompactDebugData() const {
diff --git a/third_party/blink/renderer/platform/graphics/paint/paint_property_node.h b/third_party/blink/renderer/platform/graphics/paint/paint_property_node.h index 4e4b92f..d5cccda 100644 --- a/third_party/blink/renderer/platform/graphics/paint/paint_property_node.h +++ b/third_party/blink/renderer/platform/graphics/paint/paint_property_node.h
@@ -271,7 +271,7 @@ template <typename NodeType> std::ostream& operator<<(std::ostream& os, const PaintPropertyNode<NodeType>& node) { - return os << static_cast<const NodeType&>(node).ToString().Utf8().data(); + return os << static_cast<const NodeType&>(node).ToString().Utf8(); } PLATFORM_EXPORT const char* PaintPropertyChangeTypeToString(
diff --git a/third_party/blink/renderer/platform/graphics/paint/property_tree_state.cc b/third_party/blink/renderer/platform/graphics/paint/property_tree_state.cc index 3be0d74..690447f4 100644 --- a/third_party/blink/renderer/platform/graphics/paint/property_tree_state.cc +++ b/third_party/blink/renderer/platform/graphics/paint/property_tree_state.cc
@@ -55,7 +55,7 @@ } std::ostream& operator<<(std::ostream& os, const PropertyTreeState& state) { - return os << state.ToString().Utf8().data(); + return os << state.ToString().Utf8(); } } // namespace blink
diff --git a/third_party/blink/renderer/platform/heap/blink_gc_memory_dump_provider.cc b/third_party/blink/renderer/platform/heap/blink_gc_memory_dump_provider.cc index 47ac816..2692c45 100644 --- a/third_party/blink/renderer/platform/heap/blink_gc_memory_dump_provider.cc +++ b/third_party/blink/renderer/platform/heap/blink_gc_memory_dump_provider.cc
@@ -66,7 +66,7 @@ const String& absolute_name) { // TODO(bashi): Change type name of |absoluteName|. return current_process_memory_dump_->CreateAllocatorDump( - absolute_name.Utf8().data()); + absolute_name.Utf8()); } void BlinkGCMemoryDumpProvider::ClearProcessDumpForCurrentGC() {
diff --git a/third_party/blink/renderer/platform/instrumentation/tracing/trace_event.cc b/third_party/blink/renderer/platform/instrumentation/tracing/trace_event.cc index 3f6c59c..4597bae1 100644 --- a/third_party/blink/renderer/platform/instrumentation/tracing/trace_event.cc +++ b/third_party/blink/renderer/platform/instrumentation/tracing/trace_event.cc
@@ -11,7 +11,7 @@ void EnableTracing(const String& category_filter) { base::trace_event::TraceLog::GetInstance()->SetEnabled( - base::trace_event::TraceConfig(category_filter.Utf8().data(), ""), + base::trace_event::TraceConfig(category_filter.Utf8(), ""), base::trace_event::TraceLog::RECORDING_MODE); }
diff --git a/third_party/blink/renderer/platform/instrumentation/tracing/traced_value_test.cc b/third_party/blink/renderer/platform/instrumentation/tracing/traced_value_test.cc index 6616955..ee380f8 100644 --- a/third_party/blink/renderer/platform/instrumentation/tracing/traced_value_test.cc +++ b/third_party/blink/renderer/platform/instrumentation/tracing/traced_value_test.cc
@@ -14,8 +14,7 @@ std::unique_ptr<base::Value> ParseTracedValue( std::unique_ptr<TracedValue> value) { base::JSONReader reader; - CString utf8 = value->ToString().Utf8(); - return reader.ReadDeprecated(utf8.data()); + return reader.ReadDeprecated(value->ToString().Utf8()); } TEST(TracedValueTest, FlatDictionary) {
diff --git a/third_party/blink/renderer/platform/json/json_parser.cc b/third_party/blink/renderer/platform/json/json_parser.cc index bef74f5..54e15fa 100644 --- a/third_party/blink/renderer/platform/json/json_parser.cc +++ b/third_party/blink/renderer/platform/json/json_parser.cc
@@ -442,7 +442,7 @@ *output = buffer.ToString(); // Validate constructed utf16 string. - if (output->Utf8(kStrictUTF8Conversion).IsNull()) { + if (output->Utf8(kStrictUTF8Conversion).empty()) { cursor->pos = string_start; return Error::kUnsupportedEncoding; }
diff --git a/third_party/blink/renderer/platform/loader/fetch/data_pipe_bytes_consumer_test.cc b/third_party/blink/renderer/platform/loader/fetch/data_pipe_bytes_consumer_test.cc index 1e55531..21bd571 100644 --- a/third_party/blink/renderer/platform/loader/fetch/data_pipe_bytes_consumer_test.cc +++ b/third_party/blink/renderer/platform/loader/fetch/data_pipe_bytes_consumer_test.cc
@@ -44,8 +44,7 @@ auto result = MakeGarbageCollected<BytesConsumerTestReader>(consumer)->Run( task_runner_.get()); EXPECT_EQ(Result::kDone, result.first); - EXPECT_EQ(kData, - String(result.second.data(), result.second.size()).Utf8().data()); + EXPECT_EQ(kData, String(result.second.data(), result.second.size()).Utf8()); } TEST_F(DataPipeBytesConsumerTest, TwoPhaseRead_SignalError) {
diff --git a/third_party/blink/renderer/platform/loader/static_data_navigation_body_loader_test.cc b/third_party/blink/renderer/platform/loader/static_data_navigation_body_loader_test.cc index 52a1c521..8282506 100644 --- a/third_party/blink/renderer/platform/loader/static_data_navigation_body_loader_test.cc +++ b/third_party/blink/renderer/platform/loader/static_data_navigation_body_loader_test.cc
@@ -18,8 +18,8 @@ } void Write(const String& buffer) { - CString cstring = buffer.Utf8(); - loader_->Write(cstring.data(), cstring.length()); + std::string string = buffer.Utf8(); + loader_->Write(string.c_str(), string.length()); } void BodyCodeCacheReceived(base::span<const uint8_t>) override {}
diff --git a/third_party/blink/renderer/platform/mhtml/mhtml_archive.cc b/third_party/blink/renderer/platform/mhtml/mhtml_archive.cc index 89a9da5..280de7ea 100644 --- a/third_party/blink/renderer/platform/mhtml/mhtml_archive.cc +++ b/third_party/blink/renderer/platform/mhtml/mhtml_archive.cc
@@ -190,9 +190,9 @@ // as: =?utf-8?Q?encoded_text?= // where, "utf-8" is the chosen charset to represent the text and "Q" is the // Quoted-Printable format to convert to 7-bit printable ASCII characters. - CString utf8_text = text.Utf8(); + std::string utf8_text = text.Utf8(); Vector<char> encoded_text; - QuotedPrintableEncode(utf8_text.data(), utf8_text.length(), + QuotedPrintableEncode(utf8_text.c_str(), utf8_text.length(), true /* is_header */, encoded_text); return String(encoded_text.data(), encoded_text.size()); } @@ -330,9 +330,9 @@ // We use utf8() below instead of ascii() as ascii() replaces CRLFs with ?? // (we still only have put ASCII characters in it). DCHECK(string_builder.ToString().ContainsOnlyASCIIOrEmpty()); - CString ascii_string = string_builder.ToString().Utf8(); + std::string utf8_string = string_builder.ToString().Utf8(); - output_buffer.Append(ascii_string.data(), ascii_string.length()); + output_buffer.Append(utf8_string.c_str(), utf8_string.length()); } void MHTMLArchive::GenerateMHTMLPart(const String& boundary, @@ -381,8 +381,8 @@ string_builder.Append("\r\n"); - CString ascii_string = string_builder.ToString().Utf8(); - output_buffer.Append(ascii_string.data(), ascii_string.length()); + std::string utf8_string = string_builder.ToString().Utf8(); + output_buffer.Append(utf8_string.data(), utf8_string.length()); if (!strcmp(content_encoding, kBinary)) { for (const auto& span : *resource.data) @@ -419,8 +419,8 @@ void MHTMLArchive::GenerateMHTMLFooterForTesting(const String& boundary, Vector<char>& output_buffer) { DCHECK(!boundary.IsEmpty()); - CString ascii_string = String("\r\n--" + boundary + "--\r\n").Utf8(); - output_buffer.Append(ascii_string.data(), ascii_string.length()); + std::string utf8_string = String("\r\n--" + boundary + "--\r\n").Utf8(); + output_buffer.Append(utf8_string.c_str(), utf8_string.length()); } void MHTMLArchive::SetMainResource(ArchiveResource* main_resource) {
diff --git a/third_party/blink/renderer/platform/mhtml/mhtml_parser.cc b/third_party/blink/renderer/platform/mhtml/mhtml_parser.cc index 12cc160..41ede87 100644 --- a/third_party/blink/renderer/platform/mhtml/mhtml_parser.cc +++ b/third_party/blink/renderer/platform/mhtml/mhtml_parser.cc
@@ -224,7 +224,7 @@ WTF::Time parsed_time; // Behave like //net and parse time-valued headers with a default time zone // of UTC. - if (WTF::Time::FromUTCString(mime_parameters_iterator->value.Utf8().data(), + if (WTF::Time::FromUTCString(mime_parameters_iterator->value.Utf8().c_str(), &parsed_time)) mime_header->date_ = parsed_time; } @@ -363,7 +363,7 @@ // read the part content till reaching the boundary without CRLF. So the // part content may contain CRLF at the end, which will be stripped off // later. - line_reader_.SetSeparator(end_of_part_boundary.Utf8().data()); + line_reader_.SetSeparator(end_of_part_boundary.Utf8().c_str()); if (!line_reader_.NextChunk(content)) { DVLOG(1) << "Binary contents requires end of part"; return nullptr; @@ -412,7 +412,7 @@ } // Note that we use line.utf8() and not line.ascii() as ascii turns // special characters (such as tab, line-feed...) into '?'. - content.Append(line.Utf8().data(), line.length()); + content.Append(line.Utf8().c_str(), line.length()); if (content_transfer_encoding == MIMEHeader::Encoding::kQuotedPrintable) { // The line reader removes the \r\n, but we need them for the content in // this case as the QuotedPrintable decoder expects CR-LF terminated
diff --git a/third_party/blink/renderer/platform/mojo/security_origin_struct_traits.h b/third_party/blink/renderer/platform/mojo/security_origin_struct_traits.h index 76daaee..cab3d8de 100644 --- a/third_party/blink/renderer/platform/mojo/security_origin_struct_traits.h +++ b/third_party/blink/renderer/platform/mojo/security_origin_struct_traits.h
@@ -23,8 +23,8 @@ scoped_refptr<blink::SecurityOrigin> tuple_origin; if (!tuple.IsInvalid()) { tuple_origin = blink::SecurityOrigin::Create( - String::FromUTF8(tuple.scheme().c_str()), - String::FromUTF8(tuple.host().c_str()), tuple.port()); + String::FromUTF8(tuple.scheme()), String::FromUTF8(tuple.host()), + tuple.port()); } if (nonce_if_opaque) {
diff --git a/third_party/blink/renderer/platform/network/encoded_form_data.cc b/third_party/blink/renderer/platform/network/encoded_form_data.cc index f4315e851..5ea53af 100644 --- a/third_party/blink/renderer/platform/network/encoded_form_data.cc +++ b/third_party/blink/renderer/platform/network/encoded_form_data.cc
@@ -109,9 +109,10 @@ return result; } -scoped_refptr<EncodedFormData> EncodedFormData::Create(const CString& string) { +scoped_refptr<EncodedFormData> EncodedFormData::Create( + base::span<const char> string) { scoped_refptr<EncodedFormData> result = Create(); - result->AppendData(string.data(), string.length()); + result->AppendData(string.data(), string.size()); return result; }
diff --git a/third_party/blink/renderer/platform/network/encoded_form_data.h b/third_party/blink/renderer/platform/network/encoded_form_data.h index e51137d..53323997 100644 --- a/third_party/blink/renderer/platform/network/encoded_form_data.h +++ b/third_party/blink/renderer/platform/network/encoded_form_data.h
@@ -103,7 +103,7 @@ static scoped_refptr<EncodedFormData> Create(); static scoped_refptr<EncodedFormData> Create(const void*, wtf_size_t); - static scoped_refptr<EncodedFormData> Create(const CString&); + static scoped_refptr<EncodedFormData> Create(base::span<const char>); static scoped_refptr<EncodedFormData> Create(const Vector<char>&); scoped_refptr<EncodedFormData> Copy() const; scoped_refptr<EncodedFormData> DeepCopy() const;
diff --git a/third_party/blink/renderer/platform/network/encoded_form_data_mojom_traits.cc b/third_party/blink/renderer/platform/network/encoded_form_data_mojom_traits.cc index d82395f..ab4901e 100644 --- a/third_party/blink/renderer/platform/network/encoded_form_data_mojom_traits.cc +++ b/third_party/blink/renderer/platform/network/encoded_form_data_mojom_traits.cc
@@ -63,8 +63,7 @@ base::FilePath StructTraits<network::mojom::DataElementDataView, blink::FormDataElement>::path( const blink::FormDataElement& data) { - return base::FilePath::FromUTF8Unsafe( - std::string(data.filename_.Utf8().data())); + return base::FilePath::FromUTF8Unsafe(data.filename_.Utf8()); } // static
diff --git a/third_party/blink/renderer/platform/network/form_data_encoder.cc b/third_party/blink/renderer/platform/network/form_data_encoder.cc index b2cf324..0954362 100644 --- a/third_party/blink/renderer/platform/network/form_data_encoder.cc +++ b/third_party/blink/renderer/platform/network/form_data_encoder.cc
@@ -41,7 +41,7 @@ buffer.Append(string, static_cast<wtf_size_t>(strlen(string))); } -static inline void Append(Vector<char>& buffer, const CString& string) { +static inline void Append(Vector<char>& buffer, const std::string& string) { buffer.Append(string.data(), string.length()); } @@ -51,7 +51,8 @@ buffer.Append(tmp, sizeof(tmp)); } -static void AppendQuotedString(Vector<char>& buffer, const CString& string) { +static void AppendQuotedString(Vector<char>& buffer, + const std::string& string) { // Append a string as a quoted value, escaping quotes and line breaks. // FIXME: Is it correct to use percent escaping here? Other browsers do not // encode these characters yet, so we should test popular servers to find out @@ -132,8 +133,8 @@ } void FormDataEncoder::BeginMultiPartHeader(Vector<char>& buffer, - const CString& boundary, - const CString& name) { + const std::string& boundary, + const std::string& name) { AddBoundaryToMultiPartHeader(buffer, boundary); // FIXME: This loses data irreversibly if the input name includes characters @@ -144,7 +145,7 @@ } void FormDataEncoder::AddBoundaryToMultiPartHeader(Vector<char>& buffer, - const CString& boundary, + const std::string& boundary, bool is_last_boundary) { Append(buffer, "--"); Append(buffer, boundary); @@ -204,8 +205,8 @@ void FormDataEncoder::AddKeyValuePairAsFormData( Vector<char>& buffer, - const CString& key, - const CString& value, + const std::string& key, + const std::string& value, EncodedFormData::EncodingType encoding_type, Mode mode) { if (encoding_type == EncodedFormData::kTextPlain) { @@ -223,7 +224,7 @@ } void FormDataEncoder::EncodeStringAsFormData(Vector<char>& buffer, - const CString& string, + const std::string& string, Mode mode) { // Same safe characters as Netscape for compatibility. static const char kSafeCharacters[] = "-._*";
diff --git a/third_party/blink/renderer/platform/network/form_data_encoder.h b/third_party/blink/renderer/platform/network/form_data_encoder.h index 173e94e..43e7e5e8 100644 --- a/third_party/blink/renderer/platform/network/form_data_encoder.h +++ b/third_party/blink/renderer/platform/network/form_data_encoder.h
@@ -49,10 +49,10 @@ // Helper functions used by HTMLFormElement for multi-part form data static Vector<char> GenerateUniqueBoundaryString(); static void BeginMultiPartHeader(Vector<char>&, - const CString& boundary, - const CString& name); + const std::string& boundary, + const std::string& name); static void AddBoundaryToMultiPartHeader(Vector<char>&, - const CString& boundary, + const std::string& boundary, bool is_last_boundary = false); static void AddFilenameToMultiPartHeader(Vector<char>&, const WTF::TextEncoding&, @@ -65,11 +65,11 @@ // argument is not used for TextPlain type. static void AddKeyValuePairAsFormData( Vector<char>&, - const CString& key, - const CString& value, + const std::string& key, + const std::string& value, EncodedFormData::EncodingType = EncodedFormData::kFormURLEncoded, Mode = kNormalizeCRLF); - static void EncodeStringAsFormData(Vector<char>&, const CString&, Mode); + static void EncodeStringAsFormData(Vector<char>&, const std::string&, Mode); }; } // namespace blink
diff --git a/third_party/blink/renderer/platform/network/http_parsers.cc b/third_party/blink/renderer/platform/network/http_parsers.cc index cfeefad..c722063e 100644 --- a/third_party/blink/renderer/platform/network/http_parsers.cc +++ b/third_party/blink/renderer/platform/network/http_parsers.cc
@@ -141,9 +141,8 @@ } bool IsContentDispositionAttachment(const String& content_disposition) { - CString cstring(content_disposition.Utf8()); - std::string string(cstring.data(), cstring.length()); - return net::HttpContentDisposition(string, std::string()).is_attachment(); + return net::HttpContentDisposition(content_disposition.Utf8(), std::string()) + .is_attachment(); } // https://html.spec.whatwg.org/C/#attr-meta-http-equiv-refresh @@ -214,7 +213,7 @@ } double ParseDate(const String& value) { - return ParseDateFromNullTerminatedCharacters(value.Utf8().data()); + return ParseDateFromNullTerminatedCharacters(value.Utf8().c_str()); } AtomicString ExtractMIMETypeFromMediaType(const AtomicString& media_type) {
diff --git a/third_party/blink/renderer/platform/network/network_utils.cc b/third_party/blink/renderer/platform/network/network_utils.cc index 80b95977..fed70f72 100644 --- a/third_party/blink/renderer/platform/network/network_utils.cc +++ b/third_party/blink/renderer/platform/network/network_utils.cc
@@ -118,21 +118,18 @@ } String GenerateAcceptLanguageHeader(const String& lang) { - CString cstring(lang.Utf8()); - std::string string(cstring.data(), cstring.length()); return WebString::FromUTF8( - net::HttpUtil::GenerateAcceptLanguageHeader(string)); + net::HttpUtil::GenerateAcceptLanguageHeader(lang.Utf8())); } Vector<char> ParseMultipartBoundary(const AtomicString& content_type_header) { - CString cstring(content_type_header.Utf8()); - std::string string(cstring.data(), cstring.length()); + std::string utf8_string = content_type_header.Utf8(); std::string mime_type; std::string charset; bool had_charset = false; std::string boundary; - net::HttpUtil::ParseContentType(string, &mime_type, &charset, &had_charset, - &boundary); + net::HttpUtil::ParseContentType(utf8_string, &mime_type, &charset, + &had_charset, &boundary); base::TrimString(boundary, " \"", &boundary); Vector<char> result; result.Append(boundary.data(), boundary.size());
diff --git a/third_party/blink/renderer/platform/scheduler/common/tracing_helper.h b/third_party/blink/renderer/platform/scheduler/common/tracing_helper.h index acbced1..fe98ae89 100644 --- a/third_party/blink/renderer/platform/scheduler/common/tracing_helper.h +++ b/third_party/blink/renderer/platform/scheduler/common/tracing_helper.h
@@ -105,7 +105,7 @@ // String will be copied before leaving this function. void TraceString(const String& state) { - TraceImpl(state.Utf8().data(), true); + TraceImpl(state.Utf8().c_str(), true); } // Trace compile-time defined const string, so no copy needed.
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.cc b/third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.cc index 23af8563..fd1d531 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.cc +++ b/third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.cc
@@ -342,7 +342,7 @@ } void PageSchedulerImpl::ReportIntervention(const std::string& message) { - delegate_->ReportIntervention(String::FromUTF8(message.c_str())); + delegate_->ReportIntervention(String::FromUTF8(message)); } base::TimeTicks PageSchedulerImpl::EnableVirtualTime() { @@ -553,7 +553,7 @@ "for more details", throttling_duration.InSecondsF()); - delegate_->ReportIntervention(String::FromUTF8(message.c_str())); + delegate_->ReportIntervention(String::FromUTF8(message)); } void PageSchedulerImpl::UpdateBackgroundSchedulingLifecycleState(
diff --git a/third_party/blink/renderer/platform/testing/url_test_helpers.cc b/third_party/blink/renderer/platform/testing/url_test_helpers.cc index a4e4ae8..ff8c9dd 100644 --- a/third_party/blink/renderer/platform/testing/url_test_helpers.cc +++ b/third_party/blink/renderer/platform/testing/url_test_helpers.cc
@@ -50,8 +50,7 @@ const WebString& file_name, const WebString& mime_type) { // fullURL = baseURL + fileName. - std::string full_url = std::string(base_url.Utf8().data()) + - std::string(file_name.Utf8().data()); + std::string full_url = base_url.Utf8() + file_name.Utf8(); // filePath = basePath + ("/" +) fileName. base::FilePath file_path =
diff --git a/third_party/blink/renderer/platform/text/layout_locale.cc b/third_party/blink/renderer/platform/text/layout_locale.cc index 8e705279..576cb6cb 100644 --- a/third_party/blink/renderer/platform/text/layout_locale.cc +++ b/third_party/blink/renderer/platform/text/layout_locale.cc
@@ -214,9 +214,9 @@ if (string_.Contains('@')) return string_; - CString utf8_locale = string_.Utf8(); + std::string utf8_locale = string_.Utf8(); Vector<char> buffer(utf8_locale.length() + 11, 0); - memcpy(buffer.data(), utf8_locale.data(), utf8_locale.length()); + memcpy(buffer.data(), utf8_locale.c_str(), utf8_locale.length()); const char* keyword_value = nullptr; switch (mode) {
diff --git a/third_party/blink/renderer/platform/text/locale_icu.cc b/third_party/blink/renderer/platform/text/locale_icu.cc index 9d2a1789..1550e54 100644 --- a/third_party/blink/renderer/platform/text/locale_icu.cc +++ b/third_party/blink/renderer/platform/text/locale_icu.cc
@@ -45,10 +45,10 @@ namespace blink { std::unique_ptr<Locale> Locale::Create(const String& locale) { - return std::make_unique<LocaleICU>(locale.Utf8().data()); + return std::make_unique<LocaleICU>(locale.Utf8()); } -LocaleICU::LocaleICU(const char* locale) +LocaleICU::LocaleICU(const std::string& locale) : locale_(locale), number_format_(nullptr), short_date_format_(nullptr), @@ -105,7 +105,7 @@ did_create_decimal_format_ = true; UErrorCode status = U_ZERO_ERROR; number_format_ = - unum_open(UNUM_DECIMAL, nullptr, 0, locale_.data(), nullptr, &status); + unum_open(UNUM_DECIMAL, nullptr, 0, locale_.c_str(), nullptr, &status); if (!U_SUCCESS(status)) return; @@ -141,7 +141,7 @@ UDateFormatStyle date_style) const { const UChar kGmtTimezone[3] = {'G', 'M', 'T'}; UErrorCode status = U_ZERO_ERROR; - return udat_open(time_style, date_style, locale_.data(), kGmtTimezone, + return udat_open(time_style, date_style, locale_.c_str(), kGmtTimezone, base::size(kGmtTimezone), nullptr, -1, &status); } @@ -155,7 +155,7 @@ const UChar kMonthPattern[4] = {'L', 'L', 'L', 'L'}; UErrorCode status = U_ZERO_ERROR; UDateFormat* formatter = - udat_open(UDAT_PATTERN, UDAT_PATTERN, locale_.data(), nullptr, -1, + udat_open(UDAT_PATTERN, UDAT_PATTERN, locale_.c_str(), nullptr, -1, kMonthPattern, is_short ? 3 : 4, &status); udat_setContext(formatter, UDISPCTX_CAPITALIZATION_FOR_STANDALONE, &status); DCHECK(U_SUCCESS(status)); @@ -287,7 +287,7 @@ bool LocaleICU::IsRTL() { UErrorCode status = U_ZERO_ERROR; - return uloc_getCharacterOrientation(locale_.data(), &status) == + return uloc_getCharacterOrientation(locale_.c_str(), &status) == ULOC_LAYOUT_RTL; } @@ -372,14 +372,14 @@ return month_format_; // Gets a format for "MMMM" because Windows API always provides formats for // "MMMM" in some locales. - month_format_ = GetFormatForSkeleton(locale_.data(), "yyyyMMMM"); + month_format_ = GetFormatForSkeleton(locale_.c_str(), "yyyyMMMM"); return month_format_; } String LocaleICU::ShortMonthFormat() { if (!short_month_format_.IsNull()) return short_month_format_; - short_month_format_ = GetFormatForSkeleton(locale_.data(), "yyyyMMM"); + short_month_format_ = GetFormatForSkeleton(locale_.c_str(), "yyyyMMM"); return short_month_format_; }
diff --git a/third_party/blink/renderer/platform/text/locale_icu.h b/third_party/blink/renderer/platform/text/locale_icu.h index 568b11db..1798a60 100644 --- a/third_party/blink/renderer/platform/text/locale_icu.h +++ b/third_party/blink/renderer/platform/text/locale_icu.h
@@ -46,7 +46,7 @@ // LocalizedDateICU.cpp, and LocalizedNumberICUTest.cpp. class PLATFORM_EXPORT LocaleICU : public Locale { public: - explicit LocaleICU(const char*); + explicit LocaleICU(const std::string&); ~LocaleICU() override; const Vector<String>& WeekDayShortLabels() override; @@ -89,7 +89,7 @@ int32_t size); void InitializeDateTimeFormat(); - CString locale_; + std::string locale_; UNumberFormat* number_format_; UDateFormat* short_date_format_; bool did_create_decimal_format_;
diff --git a/third_party/blink/renderer/platform/text/locale_icu_test.cc b/third_party/blink/renderer/platform/text/locale_icu_test.cc index 0a241ff..a65a8b16 100644 --- a/third_party/blink/renderer/platform/text/locale_icu_test.cc +++ b/third_party/blink/renderer/platform/text/locale_icu_test.cc
@@ -137,8 +137,7 @@ TEST_F(LocaleICUTest, monthFormat) { EXPECT_EQ("MMMM yyyy", MonthFormat("en_US")); EXPECT_EQ("MMMM yyyy", MonthFormat("fr")); - EXPECT_STREQ("yyyy\xE5\xB9\xB4M\xE6\x9C\x88", - MonthFormat("ja").Utf8().data()); + EXPECT_EQ("yyyy\xE5\xB9\xB4M\xE6\x9C\x88", MonthFormat("ja").Utf8()); } TEST_F(LocaleICUTest, localizedDateFormatText) { @@ -162,10 +161,10 @@ #if U_ICU_VERSION_MAJOR_NUM >= 54 EXPECT_EQ("Janvier", StandAloneMonthLabel("fr_FR", 0)); EXPECT_EQ("Juin", StandAloneMonthLabel("fr_FR", 5)); - EXPECT_STREQ( + EXPECT_EQ( "D\xC3\xA9" "cembre", - StandAloneMonthLabel("fr_FR", 11).Utf8().data()); + StandAloneMonthLabel("fr_FR", 11).Utf8()); #else EXPECT_EQ("janvier", standAloneMonthLabel("fr_FR", 0)); EXPECT_EQ("juin", standAloneMonthLabel("fr_FR", 5)); @@ -175,15 +174,14 @@ standAloneMonthLabel("fr_FR", 11)); #endif - EXPECT_STREQ("1\xE6\x9C\x88", StandAloneMonthLabel("ja_JP", 0).Utf8().data()); - EXPECT_STREQ("6\xE6\x9C\x88", StandAloneMonthLabel("ja_JP", 5).Utf8().data()); - EXPECT_STREQ("12\xE6\x9C\x88", - StandAloneMonthLabel("ja_JP", 11).Utf8().data()); + EXPECT_EQ("1\xE6\x9C\x88", StandAloneMonthLabel("ja_JP", 0).Utf8()); + EXPECT_EQ("6\xE6\x9C\x88", StandAloneMonthLabel("ja_JP", 5).Utf8()); + EXPECT_EQ("12\xE6\x9C\x88", StandAloneMonthLabel("ja_JP", 11).Utf8()); - EXPECT_STREQ("\xD0\x9C\xD0\xB0\xD1\x80\xD1\x82", - StandAloneMonthLabel("ru_RU", 2).Utf8().data()); - EXPECT_STREQ("\xD0\x9C\xD0\xB0\xD0\xB9", - StandAloneMonthLabel("ru_RU", 4).Utf8().data()); + EXPECT_EQ("\xD0\x9C\xD0\xB0\xD1\x80\xD1\x82", + StandAloneMonthLabel("ru_RU", 2).Utf8()); + EXPECT_EQ("\xD0\x9C\xD0\xB0\xD0\xB9", + StandAloneMonthLabel("ru_RU", 4).Utf8()); } TEST_F(LocaleICUTest, shortMonthLabels) { @@ -195,14 +193,14 @@ #if U_ICU_VERSION_MAJOR_NUM >= 54 EXPECT_EQ("janv.", ShortMonthLabel("fr_FR", 0)); EXPECT_EQ("Janv.", ShortStandAloneMonthLabel("fr_FR", 0)); - EXPECT_STREQ( + EXPECT_EQ( "d\xC3\xA9" "c.", - ShortMonthLabel("fr_FR", 11).Utf8().data()); - EXPECT_STREQ( + ShortMonthLabel("fr_FR", 11).Utf8()); + EXPECT_EQ( "D\xC3\xA9" "c.", - ShortStandAloneMonthLabel("fr_FR", 11).Utf8().data()); + ShortStandAloneMonthLabel("fr_FR", 11).Utf8()); #else EXPECT_EQ("janv.", shortMonthLabel("fr_FR", 0)); EXPECT_EQ("janv.", shortStandAloneMonthLabel("fr_FR", 0)); @@ -216,21 +214,17 @@ shortStandAloneMonthLabel("fr_FR", 11)); #endif - EXPECT_STREQ("1\xE6\x9C\x88", ShortMonthLabel("ja_JP", 0).Utf8().data()); - EXPECT_STREQ("1\xE6\x9C\x88", - ShortStandAloneMonthLabel("ja_JP", 0).Utf8().data()); - EXPECT_STREQ("12\xE6\x9C\x88", ShortMonthLabel("ja_JP", 11).Utf8().data()); - EXPECT_STREQ("12\xE6\x9C\x88", - ShortStandAloneMonthLabel("ja_JP", 11).Utf8().data()); + EXPECT_EQ("1\xE6\x9C\x88", ShortMonthLabel("ja_JP", 0).Utf8()); + EXPECT_EQ("1\xE6\x9C\x88", ShortStandAloneMonthLabel("ja_JP", 0).Utf8()); + EXPECT_EQ("12\xE6\x9C\x88", ShortMonthLabel("ja_JP", 11).Utf8()); + EXPECT_EQ("12\xE6\x9C\x88", ShortStandAloneMonthLabel("ja_JP", 11).Utf8()); - EXPECT_STREQ("\xD0\xBC\xD0\xB0\xD1\x80.", - ShortMonthLabel("ru_RU", 2).Utf8().data()); - EXPECT_STREQ("\xD0\x9C\xD0\xB0\xD1\x80\xD1\x82", - ShortStandAloneMonthLabel("ru_RU", 2).Utf8().data()); - EXPECT_STREQ("\xD0\xBC\xD0\xB0\xD1\x8F", - ShortMonthLabel("ru_RU", 4).Utf8().data()); - EXPECT_STREQ("\xD0\x9C\xD0\xB0\xD0\xB9", - ShortStandAloneMonthLabel("ru_RU", 4).Utf8().data()); + EXPECT_EQ("\xD0\xBC\xD0\xB0\xD1\x80.", ShortMonthLabel("ru_RU", 2).Utf8()); + EXPECT_EQ("\xD0\x9C\xD0\xB0\xD1\x80\xD1\x82", + ShortStandAloneMonthLabel("ru_RU", 2).Utf8()); + EXPECT_EQ("\xD0\xBC\xD0\xB0\xD1\x8F", ShortMonthLabel("ru_RU", 4).Utf8()); + EXPECT_EQ("\xD0\x9C\xD0\xB0\xD0\xB9", + ShortStandAloneMonthLabel("ru_RU", 4).Utf8()); } TEST_F(LocaleICUTest, timeAMPMLabels) {
diff --git a/third_party/blink/renderer/platform/text/locale_mac_test.mm b/third_party/blink/renderer/platform/text/locale_mac_test.mm index 1d40a9b..1418c101 100644 --- a/third_party/blink/renderer/platform/text/locale_mac_test.mm +++ b/third_party/blink/renderer/platform/text/locale_mac_test.mm
@@ -201,15 +201,15 @@ TEST_F(LocaleMacTest, formatMonth) { EXPECT_EQ("April 2005", FormatMonth("en_US", "2005-04", false)); EXPECT_EQ("avril 2005", FormatMonth("fr_FR", "2005-04", false)); - EXPECT_STREQ("2005\xE5\xB9\xB4" - "04\xE6\x9C\x88", - FormatMonth("ja_JP", "2005-04", false).Utf8().data()); + EXPECT_EQ("2005\xE5\xB9\xB4" + "04\xE6\x9C\x88", + FormatMonth("ja_JP", "2005-04", false).Utf8()); EXPECT_EQ("Apr 2005", FormatMonth("en_US", "2005-04", true)); EXPECT_EQ("avr. 2005", FormatMonth("fr_FR", "2005-04", true)); - EXPECT_STREQ("2005\xE5\xB9\xB4" - "04\xE6\x9C\x88", - FormatMonth("ja_JP", "2005-04", true).Utf8().data()); + EXPECT_EQ("2005\xE5\xB9\xB4" + "04\xE6\x9C\x88", + FormatMonth("ja_JP", "2005-04", true).Utf8()); } TEST_F(LocaleMacTest, formatDate) { @@ -229,44 +229,44 @@ EXPECT_EQ("13:23", FormatTime("fr_FR", 13, 23, 00, 000, true)); EXPECT_EQ("13:23", FormatTime("ja_JP", 13, 23, 00, 000, true)); if (expect_ar_nbsp) { - EXPECT_STREQ("\xD9\xA1:\xD9\xA2\xD9\xA3\xC2\xA0\xD9\x85", - FormatTime("ar", 13, 23, 00, 000, true).Utf8().data()); + EXPECT_EQ("\xD9\xA1:\xD9\xA2\xD9\xA3\xC2\xA0\xD9\x85", + FormatTime("ar", 13, 23, 00, 000, true).Utf8()); } else { - EXPECT_STREQ("\xD9\xA1:\xD9\xA2\xD9\xA3 \xD9\x85", - FormatTime("ar", 13, 23, 00, 000, true).Utf8().data()); + EXPECT_EQ("\xD9\xA1:\xD9\xA2\xD9\xA3 \xD9\x85", + FormatTime("ar", 13, 23, 00, 000, true).Utf8()); } - EXPECT_STREQ("\xDB\xB1\xDB\xB3:\xDB\xB2\xDB\xB3", - FormatTime("fa", 13, 23, 00, 000, true).Utf8().data()); + EXPECT_EQ("\xDB\xB1\xDB\xB3:\xDB\xB2\xDB\xB3", + FormatTime("fa", 13, 23, 00, 000, true).Utf8()); EXPECT_EQ("12:00 AM", FormatTime("en_US", 00, 00, 00, 000, true)); EXPECT_EQ("00:00", FormatTime("fr_FR", 00, 00, 00, 000, true)); EXPECT_EQ("0:00", FormatTime("ja_JP", 00, 00, 00, 000, true)); if (expect_ar_nbsp) { - EXPECT_STREQ("\xD9\xA1\xD9\xA2:\xD9\xA0\xD9\xA0\xC2\xA0\xD8\xB5", - FormatTime("ar", 00, 00, 00, 000, true).Utf8().data()); + EXPECT_EQ("\xD9\xA1\xD9\xA2:\xD9\xA0\xD9\xA0\xC2\xA0\xD8\xB5", + FormatTime("ar", 00, 00, 00, 000, true).Utf8()); } else { - EXPECT_STREQ("\xD9\xA1\xD9\xA2:\xD9\xA0\xD9\xA0 \xD8\xB5", - FormatTime("ar", 00, 00, 00, 000, true).Utf8().data()); + EXPECT_EQ("\xD9\xA1\xD9\xA2:\xD9\xA0\xD9\xA0 \xD8\xB5", + FormatTime("ar", 00, 00, 00, 000, true).Utf8()); } - EXPECT_STREQ("\xDB\xB0:\xDB\xB0\xDB\xB0", - FormatTime("fa", 00, 00, 00, 000, true).Utf8().data()); + EXPECT_EQ("\xDB\xB0:\xDB\xB0\xDB\xB0", + FormatTime("fa", 00, 00, 00, 000, true).Utf8()); EXPECT_EQ("7:07:07.007 AM", FormatTime("en_US", 07, 07, 07, 007, false)); EXPECT_EQ("07:07:07,007", FormatTime("fr_FR", 07, 07, 07, 007, false)); EXPECT_EQ("7:07:07.007", FormatTime("ja_JP", 07, 07, 07, 007, false)); if (expect_ar_nbsp) { - EXPECT_STREQ( + EXPECT_EQ( "\xD9\xA7:\xD9\xA0\xD9\xA7:" "\xD9\xA0\xD9\xA7\xD9\xAB\xD9\xA0\xD9\xA0\xD9\xA7\xC2\xA0\xD8\xB5", - FormatTime("ar", 07, 07, 07, 007, false).Utf8().data()); + FormatTime("ar", 07, 07, 07, 007, false).Utf8()); } else { - EXPECT_STREQ("\xD9\xA7:\xD9\xA0\xD9\xA7:" - "\xD9\xA0\xD9\xA7\xD9\xAB\xD9\xA0\xD9\xA0\xD9\xA7 \xD8\xB5", - FormatTime("ar", 07, 07, 07, 007, false).Utf8().data()); + EXPECT_EQ("\xD9\xA7:\xD9\xA0\xD9\xA7:" + "\xD9\xA0\xD9\xA7\xD9\xAB\xD9\xA0\xD9\xA0\xD9\xA7 \xD8\xB5", + FormatTime("ar", 07, 07, 07, 007, false).Utf8()); } - EXPECT_STREQ("\xDB\xB7:\xDB\xB0\xDB\xB7:" - "\xDB\xB0\xDB\xB7\xD9\xAB\xDB\xB0\xDB\xB0\xDB\xB7", - FormatTime("fa", 07, 07, 07, 007, false).Utf8().data()); + EXPECT_EQ("\xDB\xB7:\xDB\xB0\xDB\xB7:" + "\xDB\xB0\xDB\xB7\xD9\xAB\xDB\xB0\xDB\xB0\xDB\xB7", + FormatTime("fa", 07, 07, 07, 007, false).Utf8()); } TEST_F(LocaleMacTest, firstDayOfWeek) { @@ -282,13 +282,13 @@ EXPECT_EQ("janvier", MonthLabel("fr_FR", kJanuary)); EXPECT_EQ("juin", MonthLabel("fr_FR", kJune)); - EXPECT_STREQ("d\xC3\xA9" - "cembre", - MonthLabel("fr_FR", kDecember).Utf8().data()); + EXPECT_EQ("d\xC3\xA9" + "cembre", + MonthLabel("fr_FR", kDecember).Utf8()); - EXPECT_STREQ("1\xE6\x9C\x88", MonthLabel("ja_JP", kJanuary).Utf8().data()); - EXPECT_STREQ("6\xE6\x9C\x88", MonthLabel("ja_JP", kJune).Utf8().data()); - EXPECT_STREQ("12\xE6\x9C\x88", MonthLabel("ja_JP", kDecember).Utf8().data()); + EXPECT_EQ("1\xE6\x9C\x88", MonthLabel("ja_JP", kJanuary).Utf8()); + EXPECT_EQ("6\xE6\x9C\x88", MonthLabel("ja_JP", kJune).Utf8()); + EXPECT_EQ("12\xE6\x9C\x88", MonthLabel("ja_JP", kDecember).Utf8()); } TEST_F(LocaleMacTest, weekDayShortLabels) { @@ -300,12 +300,9 @@ EXPECT_EQ("mer.", WeekDayShortLabel("fr_FR", kWednesday)); EXPECT_EQ("sam.", WeekDayShortLabel("fr_FR", kSaturday)); - EXPECT_STREQ("\xE6\x97\xA5", - WeekDayShortLabel("ja_JP", kSunday).Utf8().data()); - EXPECT_STREQ("\xE6\xB0\xB4", - WeekDayShortLabel("ja_JP", kWednesday).Utf8().data()); - EXPECT_STREQ("\xE5\x9C\x9F", - WeekDayShortLabel("ja_JP", kSaturday).Utf8().data()); + EXPECT_EQ("\xE6\x97\xA5", WeekDayShortLabel("ja_JP", kSunday).Utf8()); + EXPECT_EQ("\xE6\xB0\xB4", WeekDayShortLabel("ja_JP", kWednesday).Utf8()); + EXPECT_EQ("\xE5\x9C\x9F", WeekDayShortLabel("ja_JP", kSaturday).Utf8()); } TEST_F(LocaleMacTest, isRTL) { @@ -317,8 +314,7 @@ TEST_F(LocaleMacTest, monthFormat) { EXPECT_EQ("MMMM yyyy", MonthFormat("en_US")); - EXPECT_STREQ("yyyy\xE5\xB9\xB4M\xE6\x9C\x88", - MonthFormat("ja_JP").Utf8().data()); + EXPECT_EQ("yyyy\xE5\xB9\xB4M\xE6\x9C\x88", MonthFormat("ja_JP").Utf8()); // fr_FR and ru return different results on OS versions. // "MMM yyyy" "LLL yyyy" on 10.6 and 10.7 @@ -344,16 +340,13 @@ EXPECT_EQ("janvier", StandAloneMonthLabel("fr_FR", kJanuary)); EXPECT_EQ("juin", StandAloneMonthLabel("fr_FR", kJune)); - EXPECT_STREQ("d\xC3\xA9" - "cembre", - StandAloneMonthLabel("fr_FR", kDecember).Utf8().data()); + EXPECT_EQ("d\xC3\xA9" + "cembre", + StandAloneMonthLabel("fr_FR", kDecember).Utf8()); - EXPECT_STREQ("1\xE6\x9C\x88", - StandAloneMonthLabel("ja_JP", kJanuary).Utf8().data()); - EXPECT_STREQ("6\xE6\x9C\x88", - StandAloneMonthLabel("ja_JP", kJune).Utf8().data()); - EXPECT_STREQ("12\xE6\x9C\x88", - StandAloneMonthLabel("ja_JP", kDecember).Utf8().data()); + EXPECT_EQ("1\xE6\x9C\x88", StandAloneMonthLabel("ja_JP", kJanuary).Utf8()); + EXPECT_EQ("6\xE6\x9C\x88", StandAloneMonthLabel("ja_JP", kJune).Utf8()); + EXPECT_EQ("12\xE6\x9C\x88", StandAloneMonthLabel("ja_JP", kDecember).Utf8()); } TEST_F(LocaleMacTest, shortMonthLabels) { @@ -364,24 +357,21 @@ EXPECT_EQ("janv.", ShortMonthLabel("fr_FR", 0)); EXPECT_EQ("janv.", ShortStandAloneMonthLabel("fr_FR", 0)); - EXPECT_STREQ("d\xC3\xA9" - "c.", - ShortMonthLabel("fr_FR", 11).Utf8().data()); - EXPECT_STREQ("d\xC3\xA9" - "c.", - ShortStandAloneMonthLabel("fr_FR", 11).Utf8().data()); + EXPECT_EQ("d\xC3\xA9" + "c.", + ShortMonthLabel("fr_FR", 11).Utf8()); + EXPECT_EQ("d\xC3\xA9" + "c.", + ShortStandAloneMonthLabel("fr_FR", 11).Utf8()); - EXPECT_STREQ("1\xE6\x9C\x88", ShortMonthLabel("ja_JP", 0).Utf8().data()); - EXPECT_STREQ("1\xE6\x9C\x88", - ShortStandAloneMonthLabel("ja_JP", 0).Utf8().data()); - EXPECT_STREQ("12\xE6\x9C\x88", ShortMonthLabel("ja_JP", 11).Utf8().data()); - EXPECT_STREQ("12\xE6\x9C\x88", - ShortStandAloneMonthLabel("ja_JP", 11).Utf8().data()); + EXPECT_EQ("1\xE6\x9C\x88", ShortMonthLabel("ja_JP", 0).Utf8()); + EXPECT_EQ("1\xE6\x9C\x88", ShortStandAloneMonthLabel("ja_JP", 0).Utf8()); + EXPECT_EQ("12\xE6\x9C\x88", ShortMonthLabel("ja_JP", 11).Utf8()); + EXPECT_EQ("12\xE6\x9C\x88", ShortStandAloneMonthLabel("ja_JP", 11).Utf8()); - EXPECT_STREQ("\xD0\xBC\xD0\xB0\xD1\x80\xD1\x82\xD0\xB0", - ShortMonthLabel("ru_RU", 2).Utf8().data()); - EXPECT_STREQ("\xD0\xBC\xD0\xB0\xD1\x8F", - ShortMonthLabel("ru_RU", 4).Utf8().data()); + EXPECT_EQ("\xD0\xBC\xD0\xB0\xD1\x80\xD1\x82\xD0\xB0", + ShortMonthLabel("ru_RU", 2).Utf8()); + EXPECT_EQ("\xD0\xBC\xD0\xB0\xD1\x8F", ShortMonthLabel("ru_RU", 4).Utf8()); // The ru_RU locale returns different stand-alone month labels on OS versions. // "\xD0\xBC\xD0\xB0\xD1\x80\xD1\x82" "\xD0\xBC\xD0\xB0\xD0\xB9" on 10.7 // "\xD0\x9C\xD0\xB0\xD1\x80\xD1\x82" "\xD0\x9C\xD0\xB0\xD0\xB9" on 10.8 @@ -394,10 +384,8 @@ EXPECT_EQ("AM", TimeAMPMLabel("fr_FR", 0)); EXPECT_EQ("PM", TimeAMPMLabel("fr_FR", 1)); - EXPECT_STREQ("\xE5\x8D\x88\xE5\x89\x8D", - TimeAMPMLabel("ja_JP", 0).Utf8().data()); - EXPECT_STREQ("\xE5\x8D\x88\xE5\xBE\x8C", - TimeAMPMLabel("ja_JP", 1).Utf8().data()); + EXPECT_EQ("\xE5\x8D\x88\xE5\x89\x8D", TimeAMPMLabel("ja_JP", 0).Utf8()); + EXPECT_EQ("\xE5\x8D\x88\xE5\xBE\x8C", TimeAMPMLabel("ja_JP", 1).Utf8()); } TEST_F(LocaleMacTest, decimalSeparator) {
diff --git a/third_party/blink/renderer/platform/text/locale_win_test.cc b/third_party/blink/renderer/platform/text/locale_win_test.cc index 1bd59aa..341fe53e 100644 --- a/third_party/blink/renderer/platform/text/locale_win_test.cc +++ b/third_party/blink/renderer/platform/text/locale_win_test.cc
@@ -178,16 +178,14 @@ EXPECT_EQ("janvier", MonthLabel(kFrenchFR, kJanuary)); EXPECT_EQ("juin", MonthLabel(kFrenchFR, kJune)); - EXPECT_STREQ( + EXPECT_EQ( "d\xC3\xA9" "cembre", - MonthLabel(kFrenchFR, kDecember).Utf8().data()); + MonthLabel(kFrenchFR, kDecember).Utf8()); - EXPECT_STREQ("1\xE6\x9C\x88", - MonthLabel(kJapaneseJP, kJanuary).Utf8().data()); - EXPECT_STREQ("6\xE6\x9C\x88", MonthLabel(kJapaneseJP, kJune).Utf8().data()); - EXPECT_STREQ("12\xE6\x9C\x88", - MonthLabel(kJapaneseJP, kDecember).Utf8().data()); + EXPECT_EQ("1\xE6\x9C\x88", MonthLabel(kJapaneseJP, kJanuary).Utf8()); + EXPECT_EQ("6\xE6\x9C\x88", MonthLabel(kJapaneseJP, kJune).Utf8()); + EXPECT_EQ("12\xE6\x9C\x88", MonthLabel(kJapaneseJP, kDecember).Utf8()); } TEST_F(LocaleWinTest, weekDayShortLabels) { @@ -199,12 +197,9 @@ EXPECT_EQ("mer.", WeekDayShortLabel(kFrenchFR, kWednesday)); EXPECT_EQ("sam.", WeekDayShortLabel(kFrenchFR, kSaturday)); - EXPECT_STREQ("\xE6\x97\xA5", - WeekDayShortLabel(kJapaneseJP, kSunday).Utf8().data()); - EXPECT_STREQ("\xE6\xB0\xB4", - WeekDayShortLabel(kJapaneseJP, kWednesday).Utf8().data()); - EXPECT_STREQ("\xE5\x9C\x9F", - WeekDayShortLabel(kJapaneseJP, kSaturday).Utf8().data()); + EXPECT_EQ("\xE6\x97\xA5", WeekDayShortLabel(kJapaneseJP, kSunday).Utf8()); + EXPECT_EQ("\xE6\xB0\xB4", WeekDayShortLabel(kJapaneseJP, kWednesday).Utf8()); + EXPECT_EQ("\xE5\x9C\x9F", WeekDayShortLabel(kJapaneseJP, kSaturday).Utf8()); } TEST_F(LocaleWinTest, isRTL) { @@ -226,8 +221,7 @@ // "MMMM yyyy" on Window 8 or later. EXPECT_EQ("MMMM yyyy", MonthFormat(kEnglishUS).Replace(',', "")); EXPECT_EQ("MMMM yyyy", MonthFormat(kFrenchFR)); - EXPECT_STREQ("yyyy\xE5\xB9\xB4M\xE6\x9C\x88", - MonthFormat(kJapaneseJP).Utf8().data()); + EXPECT_EQ("yyyy\xE5\xB9\xB4M\xE6\x9C\x88", MonthFormat(kJapaneseJP).Utf8()); } TEST_F(LocaleWinTest, timeFormat) { @@ -246,10 +240,10 @@ EXPECT_EQ("Jan", ShortMonthLabel(kEnglishUS, 0)); EXPECT_EQ("Dec", ShortMonthLabel(kEnglishUS, 11)); EXPECT_EQ("janv.", ShortMonthLabel(kFrenchFR, 0)); - EXPECT_STREQ( + EXPECT_EQ( "d\xC3\xA9" "c.", - ShortMonthLabel(kFrenchFR, 11).Utf8().data()); + ShortMonthLabel(kFrenchFR, 11).Utf8()); EXPECT_EQ("1", ShortMonthLabel(kJapaneseJP, 0)); EXPECT_EQ("12", ShortMonthLabel(kJapaneseJP, 11)); } @@ -258,13 +252,11 @@ EXPECT_EQ("AM", TimeAMPMLabel(kEnglishUS, 0)); EXPECT_EQ("PM", TimeAMPMLabel(kEnglishUS, 1)); - EXPECT_STREQ("", TimeAMPMLabel(kFrenchFR, 0).Utf8().data()); - EXPECT_STREQ("", TimeAMPMLabel(kFrenchFR, 1).Utf8().data()); + EXPECT_EQ("", TimeAMPMLabel(kFrenchFR, 0).Utf8()); + EXPECT_EQ("", TimeAMPMLabel(kFrenchFR, 1).Utf8()); - EXPECT_STREQ("\xE5\x8D\x88\xE5\x89\x8D", - TimeAMPMLabel(kJapaneseJP, 0).Utf8().data()); - EXPECT_STREQ("\xE5\x8D\x88\xE5\xBE\x8C", - TimeAMPMLabel(kJapaneseJP, 1).Utf8().data()); + EXPECT_EQ("\xE5\x8D\x88\xE5\x89\x8D", TimeAMPMLabel(kJapaneseJP, 0).Utf8()); + EXPECT_EQ("\xE5\x8D\x88\xE5\xBE\x8C", TimeAMPMLabel(kJapaneseJP, 1).Utf8()); } TEST_F(LocaleWinTest, decimalSeparator) {
diff --git a/third_party/blink/renderer/platform/text/text_boundaries_test.cc b/third_party/blink/renderer/platform/text/text_boundaries_test.cc index 5a97a71..82fca82 100644 --- a/third_party/blink/renderer/platform/text/text_boundaries_test.cc +++ b/third_party/blink/renderer/platform/text/text_boundaries_test.cc
@@ -45,8 +45,7 @@ builder.Append('|'); } builder.Append(text.Substring(end)); - const CString result8 = builder.ToString().Utf8(); - return std::string(result8.data(), result8.length()); + return builder.ToString().Utf8(); } // Returns word boundray with start(^) and end(|) markes from text with
diff --git a/third_party/blink/renderer/platform/text/text_break_iterator_icu.cc b/third_party/blink/renderer/platform/text/text_break_iterator_icu.cc index 7f94979..a257cd7 100644 --- a/third_party/blink/renderer/platform/text/text_break_iterator_icu.cc +++ b/third_party/blink/renderer/platform/text/text_break_iterator_icu.cc
@@ -68,7 +68,7 @@ bool locale_is_empty = locale.IsEmpty(); iterator = icu::BreakIterator::createLineInstance( locale_is_empty ? icu::Locale(CurrentTextBreakLocaleID()) - : icu::Locale(locale.Utf8().data()), + : icu::Locale(locale.Utf8().c_str()), open_status); // locale comes from a web page and it can be invalid, leading ICU // to fail, in which case we fall back to the default locale.
diff --git a/third_party/blink/renderer/platform/weborigin/kurl.cc b/third_party/blink/renderer/platform/weborigin/kurl.cc index 8d66e1c..d90bd58e 100644 --- a/third_party/blink/renderer/platform/weborigin/kurl.cc +++ b/third_party/blink/renderer/platform/weborigin/kurl.cc
@@ -101,9 +101,9 @@ void ConvertFromUTF16(const base::char16* input, int input_length, url::CanonOutput* output) override { - CString encoded = encoding_->Encode( + std::string encoded = encoding_->Encode( String(input, input_length), WTF::kURLEncodedEntitiesForUnencodables); - output->Append(encoded.data(), static_cast<int>(encoded.length())); + output->Append(encoded.c_str(), static_cast<int>(encoded.length())); } private: @@ -630,7 +630,7 @@ } String EncodeWithURLEscapeSequences(const String& not_encoded_string) { - CString utf8 = + std::string utf8 = UTF8Encoding().Encode(not_encoded_string, WTF::kNoUnencodables); url::RawCanonOutputT<char> buffer; @@ -638,7 +638,7 @@ if (buffer.capacity() < input_length * 3) buffer.Resize(input_length * 3); - url::EncodeURIComponent(utf8.data(), input_length, &buffer); + url::EncodeURIComponent(utf8.c_str(), input_length, &buffer); String escaped(buffer.data(), static_cast<unsigned>(buffer.length())); // Unescape '/'; it's safe and much prettier. escaped.Replace("%2F", "/");
diff --git a/third_party/blink/renderer/platform/weborigin/kurl_test.cc b/third_party/blink/renderer/platform/weborigin/kurl_test.cc index d272885..fc97171 100644 --- a/third_party/blink/renderer/platform/weborigin/kurl_test.cc +++ b/third_party/blink/renderer/platform/weborigin/kurl_test.cc
@@ -181,25 +181,25 @@ KURL kurl(cases[i].url); kurl.SetProtocol(cases[i].protocol); - EXPECT_STREQ(cases[i].expected_protocol, kurl.GetString().Utf8().data()); + EXPECT_EQ(cases[i].expected_protocol, kurl.GetString().Utf8()); kurl.SetHost(cases[i].host); - EXPECT_STREQ(cases[i].expected_host, kurl.GetString().Utf8().data()); + EXPECT_EQ(cases[i].expected_host, kurl.GetString().Utf8()); kurl.SetPort(cases[i].port); - EXPECT_STREQ(cases[i].expected_port, kurl.GetString().Utf8().data()); + EXPECT_EQ(cases[i].expected_port, kurl.GetString().Utf8()); kurl.SetUser(cases[i].user); - EXPECT_STREQ(cases[i].expected_user, kurl.GetString().Utf8().data()); + EXPECT_EQ(cases[i].expected_user, kurl.GetString().Utf8()); kurl.SetPass(cases[i].pass); - EXPECT_STREQ(cases[i].expected_pass, kurl.GetString().Utf8().data()); + EXPECT_EQ(cases[i].expected_pass, kurl.GetString().Utf8()); kurl.SetPath(cases[i].path); - EXPECT_STREQ(cases[i].expected_path, kurl.GetString().Utf8().data()); + EXPECT_EQ(cases[i].expected_path, kurl.GetString().Utf8()); kurl.SetQuery(cases[i].query); - EXPECT_STREQ(cases[i].expected_query, kurl.GetString().Utf8().data()); + EXPECT_EQ(cases[i].expected_query, kurl.GetString().Utf8()); // Refs are tested below. On the Safari 3.1 branch, we don't match their // KURL since we integrated a fix from their trunk. @@ -237,13 +237,13 @@ String input(decode_cases[i].input); String str = DecodeURLEscapeSequences(input, DecodeURLMode::kUTF8OrIsomorphic); - EXPECT_STREQ(decode_cases[i].output, str.Utf8().data()); + EXPECT_EQ(decode_cases[i].output, str.Utf8()); } // Our decode should decode %00 String zero = DecodeURLEscapeSequences("%00", DecodeURLMode::kUTF8OrIsomorphic); - EXPECT_STRNE("%00", zero.Utf8().data()); + EXPECT_NE("%00", zero.Utf8()); // Decode UTF-8. String decoded = DecodeURLEscapeSequences("%e6%bc%a2%e5%ad%97", @@ -473,7 +473,7 @@ EXPECT_FALSE(kurl.IsValid()); EXPECT_TRUE(kurl.IsEmpty()); - EXPECT_STREQ("", kurl.GetString().Utf8().data()); + EXPECT_EQ("", kurl.GetString().Utf8()); kurl.SetProtocol("http"); // GKURL will say that a URL with just a scheme is invalid, KURL will not. @@ -870,8 +870,7 @@ for (size_t i = 0; i < base::size(referrer_cases); i++) { const KURL kurl(referrer_cases[i].input); - String referrer = kurl.StrippedForUseAsReferrer(); - EXPECT_STREQ(referrer_cases[i].output, referrer.Utf8().data()); + EXPECT_EQ(referrer_cases[i].output, kurl.StrippedForUseAsReferrer().Utf8()); } }
diff --git a/third_party/blink/renderer/platform/weborigin/security_origin.cc b/third_party/blink/renderer/platform/weborigin/security_origin.cc index db34a13..9c5f809 100644 --- a/third_party/blink/renderer/platform/weborigin/security_origin.cc +++ b/third_party/blink/renderer/platform/weborigin/security_origin.cc
@@ -219,13 +219,13 @@ scoped_refptr<SecurityOrigin> SecurityOrigin::CreateFromUrlOrigin( const url::Origin& origin) { const url::SchemeHostPort& tuple = origin.GetTupleOrPrecursorTupleIfOpaque(); - DCHECK(String::FromUTF8(tuple.scheme().c_str()).ContainsOnlyASCIIOrEmpty()); - DCHECK(String::FromUTF8(tuple.host().c_str()).ContainsOnlyASCIIOrEmpty()); + DCHECK(String::FromUTF8(tuple.scheme()).ContainsOnlyASCIIOrEmpty()); + DCHECK(String::FromUTF8(tuple.host()).ContainsOnlyASCIIOrEmpty()); scoped_refptr<SecurityOrigin> tuple_origin; if (!tuple.IsInvalid()) { - String scheme = String::FromUTF8(tuple.scheme().c_str()); - String host = String::FromUTF8(tuple.host().c_str()); + String scheme = String::FromUTF8(tuple.scheme()); + String host = String::FromUTF8(tuple.host()); uint16_t port = tuple.port(); // url::Origin is percent encoded and SecurityOrigin is percent decoded.
diff --git a/third_party/blink/renderer/platform/weborigin/security_policy_test.cc b/third_party/blink/renderer/platform/weborigin/security_policy_test.cc index f01956c64..baea980 100644 --- a/third_party/blink/renderer/platform/weborigin/security_policy_test.cc +++ b/third_party/blink/renderer/platform/weborigin/security_policy_test.cc
@@ -242,11 +242,11 @@ EXPECT_EQ(String::FromUTF8(test.expected), result.referrer) << "'" << test.referrer << "' to '" << test.destination << "' should have been '" << test.expected << "': was '" - << result.referrer.Utf8().data() << "'."; + << result.referrer.Utf8() << "'."; } else { EXPECT_TRUE(result.referrer.IsEmpty()) << "'" << test.referrer << "' to '" << test.destination - << "' should have been empty: was '" << result.referrer.Utf8().data() + << "' should have been empty: was '" << result.referrer.Utf8() << "'."; } EXPECT_EQ(test.policy == network::mojom::ReferrerPolicy::kDefault
diff --git a/third_party/blink/renderer/platform/wtf/text/atomic_string.h b/third_party/blink/renderer/platform/wtf/text/atomic_string.h index 1b517531..a1da6c9 100644 --- a/third_party/blink/renderer/platform/wtf/text/atomic_string.h +++ b/third_party/blink/renderer/platform/wtf/text/atomic_string.h
@@ -216,7 +216,7 @@ std::string Ascii() const { return string_.Ascii(); } std::string Latin1() const { return string_.Latin1(); } - CString Utf8(UTF8ConversionMode mode = kLenientUTF8Conversion) const { + std::string Utf8(UTF8ConversionMode mode = kLenientUTF8Conversion) const { return string_.Utf8(mode); }
diff --git a/third_party/blink/renderer/platform/wtf/text/line_ending.cc b/third_party/blink/renderer/platform/wtf/text/line_ending.cc index 0693652..f2e2826a 100644 --- a/third_party/blink/renderer/platform/wtf/text/line_ending.cc +++ b/third_party/blink/renderer/platform/wtf/text/line_ending.cc
@@ -88,34 +88,34 @@ } #if defined(OS_WIN) -void InternalNormalizeLineEndingsToCRLF(const CString& from, +void InternalNormalizeLineEndingsToCRLF(const std::string& from, Vector<char>& buffer) { - size_t new_len = RequiredSizeForCRLF(from.data(), from.length()); + size_t new_len = RequiredSizeForCRLF(from.c_str(), from.length()); if (new_len < from.length()) return; if (new_len == from.length()) { - buffer.Append(from.data(), from.length()); + buffer.Append(from.c_str(), from.length()); return; } wtf_size_t old_buffer_size = buffer.size(); buffer.Grow(old_buffer_size + new_len); char* write_position = buffer.data() + old_buffer_size; - NormalizeToCRLF(from.data(), from.length(), write_position); + NormalizeToCRLF(from.c_str(), from.length(), write_position); } #endif // defined(OS_WIN) } // namespace -void NormalizeLineEndingsToLF(const CString& from, Vector<char>& result) { +void NormalizeLineEndingsToLF(const std::string& from, Vector<char>& result) { // Compute the new length. wtf_size_t new_len = 0; bool need_fix = false; - const char* p = from.data(); + const char* p = from.c_str(); char from_ending_char = '\r'; char to_ending_char = '\n'; - while (p < from.data() + from.length()) { + while (p < from.c_str() + from.length()) { char c = *p++; if (c == '\r' && *p == '\n') { // Turn CRLF into CR or LF. @@ -129,7 +129,7 @@ } // Grow the result buffer. - p = from.data(); + p = from.c_str(); wtf_size_t old_result_size = result.size(); result.Grow(old_result_size + new_len); char* q = result.data() + old_result_size; @@ -141,7 +141,7 @@ } // Make a copy of the string. - while (p < from.data() + from.length()) { + while (p < from.c_str() + from.length()) { char c = *p++; if (c == '\r' && *p == '\n') { // Turn CRLF or CR into CR or LF. @@ -177,7 +177,8 @@ return String::Adopt(buffer); } -void NormalizeLineEndingsToNative(const CString& from, Vector<char>& result) { +void NormalizeLineEndingsToNative(const std::string& from, + Vector<char>& result) { #if defined(OS_WIN) InternalNormalizeLineEndingsToCRLF(from, result); #else
diff --git a/third_party/blink/renderer/platform/wtf/text/line_ending.h b/third_party/blink/renderer/platform/wtf/text/line_ending.h index 83abb227..b3719a7 100644 --- a/third_party/blink/renderer/platform/wtf/text/line_ending.h +++ b/third_party/blink/renderer/platform/wtf/text/line_ending.h
@@ -43,13 +43,13 @@ // Normalize all line-endings in the given string to LF and append the result to // the given buffer. -WTF_EXPORT void NormalizeLineEndingsToLF(const CString& from, +WTF_EXPORT void NormalizeLineEndingsToLF(const std::string& from, Vector<char>& result); // Normalize all line-endings in the given string to the native line-endings and // append the result to the given buffer. // (Normalize to CRLF on Windows and normalize to LF on all other platforms.) -WTF_EXPORT void NormalizeLineEndingsToNative(const CString& from, +WTF_EXPORT void NormalizeLineEndingsToNative(const std::string& from, Vector<char>& result); } // namespace WTF
diff --git a/third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.cc b/third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.cc index 9ead0694..4ae7cc0 100644 --- a/third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.cc +++ b/third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.cc
@@ -19,7 +19,7 @@ size_ = string.length(); } else { utf8_buffer_ = string.Utf8(mode); - data_ = utf8_buffer_.data(); + data_ = utf8_buffer_.c_str(); size_ = utf8_buffer_.length(); } }
diff --git a/third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h b/third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h index 76b9df3..c2f2c75c 100644 --- a/third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h +++ b/third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h
@@ -64,7 +64,7 @@ } private: - CString utf8_buffer_; + std::string utf8_buffer_; const char* data_ = nullptr; wtf_size_t size_ = 0; };
diff --git a/third_party/blink/renderer/platform/wtf/text/text_codec.h b/third_party/blink/renderer/platform/wtf/text/text_codec.h index 5a9c4f6..b692617 100644 --- a/third_party/blink/renderer/platform/wtf/text/text_codec.h +++ b/third_party/blink/renderer/platform/wtf/text/text_codec.h
@@ -97,12 +97,12 @@ FlushBehavior, bool stop_on_error, bool& saw_error) = 0; - virtual CString Encode(const UChar*, - wtf_size_t length, - UnencodableHandling) = 0; - virtual CString Encode(const LChar*, - wtf_size_t length, - UnencodableHandling) = 0; + virtual std::string Encode(const UChar*, + wtf_size_t length, + UnencodableHandling) = 0; + virtual std::string Encode(const LChar*, + wtf_size_t length, + UnencodableHandling) = 0; // EncodeInto is meant only to encode UTF8 bytes into an unsigned char* // buffer; therefore this method is only usefully overridden by TextCodecUTF8. virtual EncodeIntoResult EncodeInto(const LChar*,
diff --git a/third_party/blink/renderer/platform/wtf/text/text_codec_icu.cc b/third_party/blink/renderer/platform/wtf/text/text_codec_icu.cc index f161a8b..c5f037c 100644 --- a/third_party/blink/renderer/platform/wtf/text/text_codec_icu.cc +++ b/third_party/blink/renderer/platform/wtf/text/text_codec_icu.cc
@@ -653,8 +653,8 @@ Vector<UChar> buffer_; }; -CString TextCodecICU::EncodeInternal(const TextCodecInput& input, - UnencodableHandling handling) { +std::string TextCodecICU::EncodeInternal(const TextCodecInput& input, + UnencodableHandling handling) { const UChar* source = input.begin(); const UChar* end = input.end(); @@ -705,7 +705,7 @@ DCHECK(U_SUCCESS(err)); if (U_FAILURE(err)) - return CString(); + return std::string(); Vector<char> result; wtf_size_t size = 0; @@ -722,34 +722,34 @@ size += count; } while (err == U_BUFFER_OVERFLOW_ERROR); - return CString(result.data(), size); + return std::string(result.data(), size); } template <typename CharType> -CString TextCodecICU::EncodeCommon(const CharType* characters, - wtf_size_t length, - UnencodableHandling handling) { +std::string TextCodecICU::EncodeCommon(const CharType* characters, + wtf_size_t length, + UnencodableHandling handling) { if (!length) return ""; if (!converter_icu_) CreateICUConverter(); if (!converter_icu_) - return CString(); + return std::string(); TextCodecInput input(encoding_, characters, length); return EncodeInternal(input, handling); } -CString TextCodecICU::Encode(const UChar* characters, - wtf_size_t length, - UnencodableHandling handling) { +std::string TextCodecICU::Encode(const UChar* characters, + wtf_size_t length, + UnencodableHandling handling) { return EncodeCommon(characters, length, handling); } -CString TextCodecICU::Encode(const LChar* characters, - wtf_size_t length, - UnencodableHandling handling) { +std::string TextCodecICU::Encode(const LChar* characters, + wtf_size_t length, + UnencodableHandling handling) { return EncodeCommon(characters, length, handling); }
diff --git a/third_party/blink/renderer/platform/wtf/text/text_codec_icu.h b/third_party/blink/renderer/platform/wtf/text/text_codec_icu.h index b6cbdd8..c2202380 100644 --- a/third_party/blink/renderer/platform/wtf/text/text_codec_icu.h +++ b/third_party/blink/renderer/platform/wtf/text/text_codec_icu.h
@@ -57,12 +57,18 @@ FlushBehavior, bool stop_on_error, bool& saw_error) override; - CString Encode(const UChar*, wtf_size_t length, UnencodableHandling) override; - CString Encode(const LChar*, wtf_size_t length, UnencodableHandling) override; + std::string Encode(const UChar*, + wtf_size_t length, + UnencodableHandling) override; + std::string Encode(const LChar*, + wtf_size_t length, + UnencodableHandling) override; template <typename CharType> - CString EncodeCommon(const CharType*, wtf_size_t length, UnencodableHandling); - CString EncodeInternal(const TextCodecInput&, UnencodableHandling); + std::string EncodeCommon(const CharType*, + wtf_size_t length, + UnencodableHandling); + std::string EncodeInternal(const TextCodecInput&, UnencodableHandling); void CreateICUConverter() const; void ReleaseICUConverter() const;
diff --git a/third_party/blink/renderer/platform/wtf/text/text_codec_icu_test.cc b/third_party/blink/renderer/platform/wtf/text/text_codec_icu_test.cc index 1208102..a1d2e1a 100644 --- a/third_party/blink/renderer/platform/wtf/text/text_codec_icu_test.cc +++ b/third_party/blink/renderer/platform/wtf/text/text_codec_icu_test.cc
@@ -16,21 +16,21 @@ Vector<UChar> source; source.push_back('a'); source.push_back(kZeroWidthJoinerCharacter); - CString encoded = + std::string encoded = codec->Encode(source.data(), source.size(), kEntitiesForUnencodables); - EXPECT_STREQ("a‍", encoded.data()); + EXPECT_EQ("a‍", encoded); const String source2(u"ABC~¤•★星🌟星★•¤~XYZ"); - const CString encoded2(codec->Encode(source2.GetCharacters<UChar>(), - source2.length(), - kEntitiesForUnencodables)); + const std::string encoded2(codec->Encode(source2.GetCharacters<UChar>(), + source2.length(), + kEntitiesForUnencodables)); const String source3(u"ABC~¤•★星🌟星★•¤~XYZ"); - const CString encoded3(codec->Encode(source3.GetCharacters<UChar>(), - source3.length(), - kEntitiesForUnencodables)); - EXPECT_STREQ(encoded3.data(), encoded2.data()); - EXPECT_STREQ( + const std::string encoded3(codec->Encode(source3.GetCharacters<UChar>(), + source3.length(), + kEntitiesForUnencodables)); + EXPECT_EQ(encoded3, encoded2); + EXPECT_EQ( "ABC~¤•\x1B$B!z@1\x1B(B🌟\x1B$B@1!z\x1B(B•¤~" "XYZ", - encoded2.data()); + encoded2); } }
diff --git a/third_party/blink/renderer/platform/wtf/text/text_codec_latin1.cc b/third_party/blink/renderer/platform/wtf/text/text_codec_latin1.cc index 609f25e..4299686 100644 --- a/third_party/blink/renderer/platform/wtf/text/text_codec_latin1.cc +++ b/third_party/blink/renderer/platform/wtf/text/text_codec_latin1.cc
@@ -203,9 +203,9 @@ } template <typename CharType> -static CString EncodeComplexWindowsLatin1(const CharType* characters, - wtf_size_t length, - UnencodableHandling handling) { +static std::string EncodeComplexWindowsLatin1(const CharType* characters, + wtf_size_t length, + UnencodableHandling handling) { DCHECK_NE(handling, kNoUnencodables); wtf_size_t target_length = length; Vector<char> result(target_length); @@ -249,43 +249,40 @@ bytes[result_length++] = b; } - return CString(bytes, result_length); + return std::string(bytes, result_length); } template <typename CharType> -CString TextCodecLatin1::EncodeCommon(const CharType* characters, - wtf_size_t length, - UnencodableHandling handling) { - { - char* bytes; - CString string = CString::CreateUninitialized(length, bytes); +std::string TextCodecLatin1::EncodeCommon(const CharType* characters, + wtf_size_t length, + UnencodableHandling handling) { + std::string string(length, '\0'); - // Convert the string a fast way and simultaneously do an efficient check to - // see if it's all ASCII. - UChar ored = 0; - for (wtf_size_t i = 0; i < length; ++i) { - UChar c = characters[i]; - bytes[i] = static_cast<char>(c); - ored |= c; - } - - if (!(ored & 0xFF80)) - return string; + // Convert the string a fast way and simultaneously do an efficient check to + // see if it's all ASCII. + UChar ored = 0; + for (wtf_size_t i = 0; i < length; ++i) { + UChar c = characters[i]; + string[i] = static_cast<char>(c); + ored |= c; } + if (!(ored & 0xFF80)) + return string; + // If it wasn't all ASCII, call the function that handles more-complex cases. return EncodeComplexWindowsLatin1(characters, length, handling); } -CString TextCodecLatin1::Encode(const UChar* characters, - wtf_size_t length, - UnencodableHandling handling) { +std::string TextCodecLatin1::Encode(const UChar* characters, + wtf_size_t length, + UnencodableHandling handling) { return EncodeCommon(characters, length, handling); } -CString TextCodecLatin1::Encode(const LChar* characters, - wtf_size_t length, - UnencodableHandling handling) { +std::string TextCodecLatin1::Encode(const LChar* characters, + wtf_size_t length, + UnencodableHandling handling) { return EncodeCommon(characters, length, handling); }
diff --git a/third_party/blink/renderer/platform/wtf/text/text_codec_latin1.h b/third_party/blink/renderer/platform/wtf/text/text_codec_latin1.h index 4840c4b4..708ebab 100644 --- a/third_party/blink/renderer/platform/wtf/text/text_codec_latin1.h +++ b/third_party/blink/renderer/platform/wtf/text/text_codec_latin1.h
@@ -41,11 +41,17 @@ FlushBehavior, bool stop_on_error, bool& saw_error) override; - CString Encode(const UChar*, wtf_size_t length, UnencodableHandling) override; - CString Encode(const LChar*, wtf_size_t length, UnencodableHandling) override; + std::string Encode(const UChar*, + wtf_size_t length, + UnencodableHandling) override; + std::string Encode(const LChar*, + wtf_size_t length, + UnencodableHandling) override; template <typename CharType> - CString EncodeCommon(const CharType*, wtf_size_t length, UnencodableHandling); + std::string EncodeCommon(const CharType*, + wtf_size_t length, + UnencodableHandling); }; } // namespace WTF
diff --git a/third_party/blink/renderer/platform/wtf/text/text_codec_replacement_test.cc b/third_party/blink/renderer/platform/wtf/text/text_codec_replacement_test.cc index 449e39b3..99c93dc 100644 --- a/third_party/blink/renderer/platform/wtf/text/text_codec_replacement_test.cc +++ b/third_party/blink/renderer/platform/wtf/text/text_codec_replacement_test.cc
@@ -52,10 +52,10 @@ // "Kanji" in Chinese characters. const UChar kTestCase[] = {0x6F22, 0x5B57}; wtf_size_t test_case_size = base::size(kTestCase); - CString result = + std::string result = codec->Encode(kTestCase, test_case_size, kEntitiesForUnencodables); - EXPECT_STREQ("\xE6\xBC\xA2\xE5\xAD\x97", result.data()); + EXPECT_EQ("\xE6\xBC\xA2\xE5\xAD\x97", result); } } // namespace
diff --git a/third_party/blink/renderer/platform/wtf/text/text_codec_user_defined.cc b/third_party/blink/renderer/platform/wtf/text/text_codec_user_defined.cc index f52b94c3..2e7cbf9 100644 --- a/third_party/blink/renderer/platform/wtf/text/text_codec_user_defined.cc +++ b/third_party/blink/renderer/platform/wtf/text/text_codec_user_defined.cc
@@ -66,9 +66,9 @@ } template <typename CharType> -static CString EncodeComplexUserDefined(const CharType* characters, - wtf_size_t length, - UnencodableHandling handling) { +static std::string EncodeComplexUserDefined(const CharType* characters, + wtf_size_t length, + UnencodableHandling handling) { DCHECK_NE(handling, kNoUnencodables); wtf_size_t target_length = length; Vector<char> result(target_length); @@ -104,22 +104,21 @@ } } - return CString(bytes, result_length); + return std::string(bytes, result_length); } template <typename CharType> -CString TextCodecUserDefined::EncodeCommon(const CharType* characters, - wtf_size_t length, - UnencodableHandling handling) { - char* bytes; - CString result = CString::CreateUninitialized(length, bytes); +std::string TextCodecUserDefined::EncodeCommon(const CharType* characters, + wtf_size_t length, + UnencodableHandling handling) { + std::string result(length, '\0'); // Convert the string a fast way and simultaneously do an efficient check to // see if it's all ASCII. UChar ored = 0; for (wtf_size_t i = 0; i < length; ++i) { UChar c = characters[i]; - bytes[i] = static_cast<char>(c); + result[i] = static_cast<char>(c); ored |= c; } @@ -130,15 +129,15 @@ return EncodeComplexUserDefined(characters, length, handling); } -CString TextCodecUserDefined::Encode(const UChar* characters, - wtf_size_t length, - UnencodableHandling handling) { +std::string TextCodecUserDefined::Encode(const UChar* characters, + wtf_size_t length, + UnencodableHandling handling) { return EncodeCommon(characters, length, handling); } -CString TextCodecUserDefined::Encode(const LChar* characters, - wtf_size_t length, - UnencodableHandling handling) { +std::string TextCodecUserDefined::Encode(const LChar* characters, + wtf_size_t length, + UnencodableHandling handling) { return EncodeCommon(characters, length, handling); }
diff --git a/third_party/blink/renderer/platform/wtf/text/text_codec_user_defined.h b/third_party/blink/renderer/platform/wtf/text/text_codec_user_defined.h index 1dd2455..a0167d4 100644 --- a/third_party/blink/renderer/platform/wtf/text/text_codec_user_defined.h +++ b/third_party/blink/renderer/platform/wtf/text/text_codec_user_defined.h
@@ -41,11 +41,17 @@ FlushBehavior, bool stop_on_error, bool& saw_error) override; - CString Encode(const UChar*, wtf_size_t length, UnencodableHandling) override; - CString Encode(const LChar*, wtf_size_t length, UnencodableHandling) override; + std::string Encode(const UChar*, + wtf_size_t length, + UnencodableHandling) override; + std::string Encode(const LChar*, + wtf_size_t length, + UnencodableHandling) override; template <typename CharType> - CString EncodeCommon(const CharType*, wtf_size_t length, UnencodableHandling); + std::string EncodeCommon(const CharType*, + wtf_size_t length, + UnencodableHandling); }; } // namespace WTF
diff --git a/third_party/blink/renderer/platform/wtf/text/text_codec_utf16.cc b/third_party/blink/renderer/platform/wtf/text/text_codec_utf16.cc index 0cafd95..4d12afff 100644 --- a/third_party/blink/renderer/platform/wtf/text/text_codec_utf16.cc +++ b/third_party/blink/renderer/platform/wtf/text/text_codec_utf16.cc
@@ -150,9 +150,9 @@ return String::Adopt(buffer); } -CString TextCodecUTF16::Encode(const UChar* characters, - wtf_size_t length, - UnencodableHandling) { +std::string TextCodecUTF16::Encode(const UChar* characters, + wtf_size_t length, + UnencodableHandling) { // We need to be sure we can double the length without overflowing. // Since the passed-in length is the length of an actual existing // character buffer, each character is two bytes, and we know @@ -161,8 +161,7 @@ // and there's no need for a runtime check. DCHECK_LE(length, std::numeric_limits<wtf_size_t>::max() / 2); - char* bytes; - CString result = CString::CreateUninitialized(length * 2, bytes); + std::string result(length * 2, '\0'); // FIXME: CString is not a reasonable data structure for encoded UTF-16, which // will have null characters inside it. Perhaps the result of encode should @@ -170,38 +169,37 @@ if (little_endian_) { for (wtf_size_t i = 0; i < length; ++i) { UChar c = characters[i]; - bytes[i * 2] = static_cast<char>(c); - bytes[i * 2 + 1] = c >> 8; + result[i * 2] = static_cast<char>(c); + result[i * 2 + 1] = c >> 8; } } else { for (wtf_size_t i = 0; i < length; ++i) { UChar c = characters[i]; - bytes[i * 2] = c >> 8; - bytes[i * 2 + 1] = static_cast<char>(c); + result[i * 2] = c >> 8; + result[i * 2 + 1] = static_cast<char>(c); } } return result; } -CString TextCodecUTF16::Encode(const LChar* characters, - wtf_size_t length, - UnencodableHandling) { +std::string TextCodecUTF16::Encode(const LChar* characters, + wtf_size_t length, + UnencodableHandling) { // In the LChar case, we do actually need to perform this check in release. :) CHECK_LE(length, std::numeric_limits<wtf_size_t>::max() / 2); - char* bytes; - CString result = CString::CreateUninitialized(length * 2, bytes); + std::string result(length * 2, '\0'); if (little_endian_) { for (wtf_size_t i = 0; i < length; ++i) { - bytes[i * 2] = characters[i]; - bytes[i * 2 + 1] = 0; + result[i * 2] = characters[i]; + result[i * 2 + 1] = 0; } } else { for (wtf_size_t i = 0; i < length; ++i) { - bytes[i * 2] = 0; - bytes[i * 2 + 1] = characters[i]; + result[i * 2] = 0; + result[i * 2 + 1] = characters[i]; } }
diff --git a/third_party/blink/renderer/platform/wtf/text/text_codec_utf16.h b/third_party/blink/renderer/platform/wtf/text/text_codec_utf16.h index 5a28b40..4fa2cdfa 100644 --- a/third_party/blink/renderer/platform/wtf/text/text_codec_utf16.h +++ b/third_party/blink/renderer/platform/wtf/text/text_codec_utf16.h
@@ -42,8 +42,12 @@ FlushBehavior, bool stop_on_error, bool& saw_error) override; - CString Encode(const UChar*, wtf_size_t length, UnencodableHandling) override; - CString Encode(const LChar*, wtf_size_t length, UnencodableHandling) override; + std::string Encode(const UChar*, + wtf_size_t length, + UnencodableHandling) override; + std::string Encode(const LChar*, + wtf_size_t length, + UnencodableHandling) override; private: bool little_endian_;
diff --git a/third_party/blink/renderer/platform/wtf/text/text_codec_utf8.cc b/third_party/blink/renderer/platform/wtf/text/text_codec_utf8.cc index 7a465ed..54ac1ed 100644 --- a/third_party/blink/renderer/platform/wtf/text/text_codec_utf8.cc +++ b/third_party/blink/renderer/platform/wtf/text/text_codec_utf8.cc
@@ -467,8 +467,8 @@ } template <typename CharType> -CString TextCodecUTF8::EncodeCommon(const CharType* characters, - wtf_size_t length) { +std::string TextCodecUTF8::EncodeCommon(const CharType* characters, + wtf_size_t length) { // The maximum number of UTF-8 bytes needed per UTF-16 code unit is 3. // BMP characters take only one UTF-16 code unit and can take up to 3 bytes // (3x). @@ -490,7 +490,7 @@ U8_APPEND_UNSAFE(bytes.data(), bytes_written, character); } - return CString(reinterpret_cast<char*>(bytes.data()), bytes_written); + return std::string(reinterpret_cast<char*>(bytes.data()), bytes_written); } template <typename CharType> @@ -529,15 +529,15 @@ return encode_into_result; } -CString TextCodecUTF8::Encode(const UChar* characters, - wtf_size_t length, - UnencodableHandling) { +std::string TextCodecUTF8::Encode(const UChar* characters, + wtf_size_t length, + UnencodableHandling) { return EncodeCommon(characters, length); } -CString TextCodecUTF8::Encode(const LChar* characters, - wtf_size_t length, - UnencodableHandling) { +std::string TextCodecUTF8::Encode(const LChar* characters, + wtf_size_t length, + UnencodableHandling) { return EncodeCommon(characters, length); }
diff --git a/third_party/blink/renderer/platform/wtf/text/text_codec_utf8.h b/third_party/blink/renderer/platform/wtf/text/text_codec_utf8.h index 28efb92..688a404 100644 --- a/third_party/blink/renderer/platform/wtf/text/text_codec_utf8.h +++ b/third_party/blink/renderer/platform/wtf/text/text_codec_utf8.h
@@ -47,8 +47,12 @@ FlushBehavior, bool stop_on_error, bool& saw_error) override; - CString Encode(const UChar*, wtf_size_t length, UnencodableHandling) override; - CString Encode(const LChar*, wtf_size_t length, UnencodableHandling) override; + std::string Encode(const UChar*, + wtf_size_t length, + UnencodableHandling) override; + std::string Encode(const LChar*, + wtf_size_t length, + UnencodableHandling) override; // See comment above TextCodec::EncodeInto for more information. // This implementation writes as many code points to |destination| as will @@ -65,7 +69,7 @@ wtf_size_t capacity) override; template <typename CharType> - CString EncodeCommon(const CharType* characters, wtf_size_t length); + std::string EncodeCommon(const CharType* characters, wtf_size_t length); template <typename CharType> EncodeIntoResult EncodeIntoCommon(const CharType* characters, wtf_size_t length,
diff --git a/third_party/blink/renderer/platform/wtf/text/text_encoding.cc b/third_party/blink/renderer/platform/wtf/text/text_encoding.cc index 3008ee47..b7ecbf0 100644 --- a/third_party/blink/renderer/platform/wtf/text/text_encoding.cc +++ b/third_party/blink/renderer/platform/wtf/text/text_encoding.cc
@@ -55,16 +55,16 @@ stop_on_error, saw_error); } -CString TextEncoding::Encode(const String& string, - UnencodableHandling handling) const { +std::string TextEncoding::Encode(const String& string, + UnencodableHandling handling) const { if (!name_) - return CString(); + return std::string(); if (string.IsEmpty()) - return ""; + return std::string(); std::unique_ptr<TextCodec> text_codec = NewTextCodec(*this); - CString encoded_string; + std::string encoded_string; if (string.Is8Bit()) encoded_string = text_codec->Encode(string.Characters8(), string.length(), handling);
diff --git a/third_party/blink/renderer/platform/wtf/text/text_encoding.h b/third_party/blink/renderer/platform/wtf/text/text_encoding.h index dc229d9..9b87be2 100644 --- a/third_party/blink/renderer/platform/wtf/text/text_encoding.h +++ b/third_party/blink/renderer/platform/wtf/text/text_encoding.h
@@ -58,7 +58,7 @@ bool stop_on_error, bool& saw_error) const; - CString Encode(const String&, UnencodableHandling) const; + std::string Encode(const String&, UnencodableHandling) const; bool IsNonByteBasedEncoding() const;
diff --git a/third_party/blink/renderer/platform/wtf/text/wtf_string.cc b/third_party/blink/renderer/platform/wtf/text/wtf_string.cc index 4add9193..bfe5020 100644 --- a/third_party/blink/renderer/platform/wtf/text/wtf_string.cc +++ b/third_party/blink/renderer/platform/wtf/text/wtf_string.cc
@@ -463,11 +463,11 @@ *buffer++ = static_cast<char>((ch & 0x3F) | 0x80); } -CString String::Utf8(UTF8ConversionMode mode) const { +std::string String::Utf8(UTF8ConversionMode mode) const { unsigned length = this->length(); if (!length) - return CString("", 0); + return std::string(); // Allocate a buffer big enough to hold all the characters // (an individual UTF-16 UChar can only expand to 3 UTF-8 bytes). @@ -480,7 +480,7 @@ // have a good chance of being able to write the string into the // buffer without reallocing (say, 1.5 x length). if (length > std::numeric_limits<unsigned>::max() / 3) - return CString(); + return std::string(); Vector<char, 1024> buffer_vector(length * 3); char* buffer = buffer_vector.data(); @@ -528,13 +528,13 @@ // Only produced from strict conversion. if (result == unicode::kSourceIllegal) { DCHECK(strict); - return CString(); + return std::string(); } // Check for an unconverted high surrogate. if (result == unicode::kSourceExhausted) { if (strict) - return CString(); + return std::string(); // This should be one unpaired high surrogate. Treat it the same // was as an unpaired high surrogate would have been handled in // the middle of a string with non-strict conversion - which is @@ -550,7 +550,7 @@ } } - return CString(buffer_vector.data(), buffer - buffer_vector.data()); + return std::string(buffer_vector.data(), buffer - buffer_vector.data()); } String String::Make8BitFrom16BitSource(const UChar* source, wtf_size_t length) { @@ -616,6 +616,10 @@ return FromUTF8(s.data()); } +String String::FromUTF8(base::StringPiece s) { + return FromUTF8(reinterpret_cast<const LChar*>(s.data()), s.size()); +} + String String::FromUTF8WithLatin1Fallback(const LChar* string, size_t size) { String utf8 = FromUTF8(string, size); if (!utf8) @@ -624,7 +628,7 @@ } std::ostream& operator<<(std::ostream& out, const String& string) { - return out << string.EncodeForDebugging().Utf8().data(); + return out << string.EncodeForDebugging().Utf8(); } #ifndef NDEBUG
diff --git a/third_party/blink/renderer/platform/wtf/text/wtf_string.h b/third_party/blink/renderer/platform/wtf/text/wtf_string.h index c8207f3c..7cfc8cc5 100644 --- a/third_party/blink/renderer/platform/wtf/text/wtf_string.h +++ b/third_party/blink/renderer/platform/wtf/text/wtf_string.h
@@ -169,7 +169,7 @@ std::string Ascii() const WARN_UNUSED_RESULT; std::string Latin1() const WARN_UNUSED_RESULT; - CString Utf8(UTF8ConversionMode = kLenientUTF8Conversion) const + std::string Utf8(UTF8ConversionMode = kLenientUTF8Conversion) const WARN_UNUSED_RESULT; UChar operator[](unsigned index) const { @@ -520,6 +520,7 @@ return FromUTF8(reinterpret_cast<const LChar*>(s)); } static String FromUTF8(const CString&) WARN_UNUSED_RESULT; + static String FromUTF8(base::StringPiece) WARN_UNUSED_RESULT; // Tries to convert the passed in string to UTF-8, but will fall back to // Latin-1 if the string is not valid UTF-8.
diff --git a/third_party/blink/renderer/platform/wtf/text/wtf_string_test.cc b/third_party/blink/renderer/platform/wtf/text/wtf_string_test.cc index d69bb4a..6722593 100644 --- a/third_party/blink/renderer/platform/wtf/text/wtf_string_test.cc +++ b/third_party/blink/renderer/platform/wtf/text/wtf_string_test.cc
@@ -140,7 +140,7 @@ test_string = String::FromUTF8("r\xC3\xA9sum\xC3\xA9"); EXPECT_FALSE(test_string.Is8Bit()); test_string.Replace('3', "NotFound"); - EXPECT_STREQ("r\xC3\xA9sum\xC3\xA9", test_string.Utf8().data()); + EXPECT_EQ("r\xC3\xA9sum\xC3\xA9", test_string.Utf8()); } TEST(StringTest, ComparisonOfSameStringVectors) { @@ -271,7 +271,7 @@ String source = String::FromUTF8(test_data_list[i].source); for (size_t j = 0; j < test_data_list[i].locale_list_length; ++j) { const char* locale = test_data_list[i].locale_list[j]; - EXPECT_STREQ(expected, source.UpperUnicode(locale).Utf8().data()) + EXPECT_EQ(expected, source.UpperUnicode(locale).Utf8()) << test_data_list[i].source_description << "; locale=" << locale; } } @@ -331,7 +331,7 @@ String source = String::FromUTF8(test_data_list[i].source); for (size_t j = 0; j < test_data_list[i].locale_list_length; ++j) { const char* locale = test_data_list[i].locale_list[j]; - EXPECT_STREQ(expected, source.LowerUnicode(locale).Utf8().data()) + EXPECT_EQ(expected, source.LowerUnicode(locale).Utf8()) << test_data_list[i].source_description << "; locale=" << locale; } } @@ -421,9 +421,9 @@ EXPECT_EQ("lin\xE1k", String("lIn\xC1k").DeprecatedLower().Latin1()); // U+212A -> k - EXPECT_STREQ( + EXPECT_EQ( "link", - String::FromUTF8("LIN\xE2\x84\xAA").DeprecatedLower().Utf8().data()); + String::FromUTF8("LIN\xE2\x84\xAA").DeprecatedLower().Utf8()); } TEST(StringTest, Ensure16Bit) {
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 393f36ae..d766871 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -64,13 +64,6 @@ crbug.com/771003 http/tests/security/mixedContent/insecure-iframe-in-main-frame.html [ Failure ] crbug.com/771003 virtual/blink-cors/http/tests/security/mixedContent/insecure-iframe-in-main-frame.html [ Failure ] -# Tests temporarily disabled with Site Isolation - known differences in product -# behavior (either accepted for the long-term, or for the short-term): -# TODO(lukasza, alexmos): Burn down this list. -# Text auto-sizing: -crbug.com/393285 http/tests/text-autosizing/narrow-iframe.html [ Failure Crash ] -crbug.com/393285 http/tests/text-autosizing/wide-iframe.html [ Failure Crash ] - # Tests temporarily disabled with Site Isolation - uninvestigated bugs: # TODO(lukasza, alexmos): Burn down this list. crbug.com/608015 http/tests/inspector-protocol/access-inspected-object.js [ Failure Timeout ] @@ -5334,12 +5327,6 @@ crbug.com/919272 external/wpt/resource-timing/resource-timing.html [ Skip ] -### virtual/streams-native/http/tests/streams/transferable/ -crbug.com/902633 virtual/streams-native/http/tests/streams/transferable/writable-stream.html [ Timeout ] -crbug.com/902633 virtual/streams-native/http/tests/streams/transferable/shared-worker.html [ Pass Failure ] -crbug.com/902633 virtual/streams-native/http/tests/streams/transferable/worker.html [ Pass Failure ] - - # Sheriff 2019-01-03 crbug.com/918905 external/wpt/css/vendor-imports/mozilla/mozilla-central-reftests/sizing/block-size-with-min-or-max-content-table-1b.html [ Pass Failure ]
diff --git a/third_party/blink/web_tests/external/wpt/css/css-logical/parsing/margin-block-inline-invalid.html b/third_party/blink/web_tests/external/wpt/css/css-logical/parsing/margin-block-inline-invalid.html new file mode 100644 index 0000000..a1e0cbf3 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-logical/parsing/margin-block-inline-invalid.html
@@ -0,0 +1,25 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="utf-8"> +<title>CSS Logical Properties and Values: parsing margin-block and margin-inline with invalid values</title> +<link rel="help" href="https://drafts.csswg.org/css-logical/#propdef-margin-block"> +<meta name="assert" content="margin-block, margin-inline support only the grammar '<'margin-top'>{1,2}'."> +<meta name="assert" content="margin-block, margin-inline longhands support only the grammar '<'margin-top'>'."> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/parsing-testcommon.js"></script> +</head> +<body> +<script> +test_invalid_value("margin-block-start", "none"); +test_invalid_value("margin-block-end", "10"); +test_invalid_value("margin-inline-start", "20% calc(10px - 0.5em)"); +test_invalid_value("margin-inline-end", "10px, auto"); + +test_invalid_value("margin-block", "none"); +test_invalid_value("margin-block", "20%, calc(10px - 0.5em)"); +test_invalid_value("margin-inline", "10px auto 20px"); +</script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-logical/parsing/margin-block-inline-valid.html b/third_party/blink/web_tests/external/wpt/css/css-logical/parsing/margin-block-inline-valid.html new file mode 100644 index 0000000..4a278f90 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-logical/parsing/margin-block-inline-valid.html
@@ -0,0 +1,32 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="utf-8"> +<title>CSS Logical Properties and Values: parsing margin-block and margin-inline with valid values</title> +<link rel="help" href="https://drafts.csswg.org/css-logical/#propdef-margin-block"> +<meta name="assert" content="margin-block, margin-inline support the full grammar '<'margin-top'>{1,2}'."> +<meta name="assert" content="margin-block, margin-inline longhands support the full grammar '<'margin-top'>'."> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/parsing-testcommon.js"></script> +</head> +<body> +<script> +test_valid_value("margin-block-start", "calc(20% + 10px)"); +test_valid_value("margin-block-start", "auto"); +test_valid_value("margin-block-end", "-10px"); +test_valid_value("margin-inline-start", "-20%"); +test_valid_value("margin-inline-end", "calc(2em + 3ex)"); + +test_valid_value("margin-block", "auto"); +test_valid_value("margin-block", "-10px"); +test_valid_value("margin-block", "calc(2em + 3ex) -20%"); +test_valid_value("margin-block", "auto auto", "auto"); +test_valid_value("margin-block", "-20% calc(20% + 10px)"); +test_valid_value("margin-inline", "20%"); +test_valid_value("margin-inline", "calc(2em + 3ex)"); +test_valid_value("margin-inline", "-10px auto"); +test_valid_value("margin-inline", "auto calc(2em + 3ex)"); +</script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-logical/parsing/padding-block-inline-invalid.html b/third_party/blink/web_tests/external/wpt/css/css-logical/parsing/padding-block-inline-invalid.html new file mode 100644 index 0000000..56c2adb --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-logical/parsing/padding-block-inline-invalid.html
@@ -0,0 +1,35 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="utf-8"> +<title>CSS Logical Properties and Values: parsing padding-block and padding-inline with invalid values</title> +<link rel="help" href="https://drafts.csswg.org/css-logical/#propdef-padding-block"> +<meta name="assert" content="padding-block, padding-inline support only the grammar '<'padding-top'>{1,2}'."> +<meta name="assert" content="padding-block, padding-inline longhands support only the grammar '<'padding-top'>'."> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/parsing-testcommon.js"></script> +</head> +<body> +<script> +test_invalid_value("padding-block-start", "none"); +test_invalid_value("padding-block-start", "-10px"); +test_invalid_value("padding-block-end", "1px 2px"); +test_invalid_value("padding-block-end", "auto"); +test_invalid_value("padding-block-end", "10"); +test_invalid_value("padding-block-end", "1px, 2px"); +test_invalid_value("padding-inline-start", "20% calc(10px - 0.5em)"); +test_invalid_value("padding-inline-start", "2px auto"); +test_invalid_value("padding-inline-end", "-20%"); +test_invalid_value("padding-inline-end", "10px, auto"); + +test_invalid_value("padding-block", "none"); +test_invalid_value("padding-block", "20% -10px"); +test_invalid_value("padding-block", "auto, -10px"); +test_invalid_value("padding-block", "20%, calc(10px - 0.5em)"); +test_invalid_value("padding-inline", "10px auto 20px"); +test_invalid_value("padding-inline", "1px 2px 3px"); +test_invalid_value("padding-inline", "-20% calc(20% + 10px)"); +</script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-logical/parsing/padding-block-inline-valid.html b/third_party/blink/web_tests/external/wpt/css/css-logical/parsing/padding-block-inline-valid.html new file mode 100644 index 0000000..1f3be17 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-logical/parsing/padding-block-inline-valid.html
@@ -0,0 +1,27 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="utf-8"> +<title>CSS Logical Properties and Values: parsing padding-block and padding-inline with valid values</title> +<link rel="help" href="https://drafts.csswg.org/css-logical/#propdef-padding-block"> +<meta name="assert" content="padding-block, padding-inline support the full grammar '<'padding-top'>{1,2}'."> +<meta name="assert" content="padding-block, padding-inline longhands support the full grammar '<'padding-top'>'."> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/parsing-testcommon.js"></script> +</head> +<body> +<script> +test_valid_value("padding-block-start", "0", "0px"); +test_valid_value("padding-block-start", "calc(20% + 10px)"); +test_valid_value("padding-block-end", "10px"); +test_valid_value("padding-inline-start", "20%"); +test_valid_value("padding-inline-end", "calc(2em + 2ex)"); + +test_valid_value("padding-block", "10px"); +test_valid_value("padding-block", "10px 20%"); +test_valid_value("padding-inline", "20%"); +test_valid_value("padding-inline", "20% calc(20% + 10px)"); +</script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-text-decor/parsing/text-decoration-color-computed.html b/third_party/blink/web_tests/external/wpt/css/css-text-decor/parsing/text-decoration-color-computed.html new file mode 100644 index 0000000..deb1563a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-text-decor/parsing/text-decoration-color-computed.html
@@ -0,0 +1,31 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="utf-8"> +<title>CSS Text Decoration Test: getComputedValue().textDecorationColor</title> +<link rel="help" href="https://drafts.csswg.org/css-text-decor-3/#text-decoration-color-property"> +<meta name="assert" content="Computed text-decoration-color is the computed color."> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/computed-testcommon.js"></script> +<style> + #container { + color: rgb(255, 0, 0); + text-decoration-color: currentcolor; + } + #target { + color: rgb(0, 255, 0); + } +</style> +</head> +<body> +<div id="container"> + <div id="target"></div> +</div> +<script> +test_computed_value("text-decoration-color", "rgb(0, 0, 255)"); +test_computed_value("text-decoration-color", "currentcolor", "rgb(0, 255, 0)"); +test_computed_value("text-decoration-color", "inherit", "rgb(0, 255, 0)"); // currentcolor +</script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-text-decor/parsing/text-decoration-color-invalid.html b/third_party/blink/web_tests/external/wpt/css/css-text-decor/parsing/text-decoration-color-invalid.html new file mode 100644 index 0000000..24364d8 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-text-decor/parsing/text-decoration-color-invalid.html
@@ -0,0 +1,15 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>CSS Text Decoration Test: Parsing text-decoration-color with invalid values</title> +<link rel="help" href="https://drafts.csswg.org/css-text-decor-3/#text-decoration-color-property"> +<meta name="assert" content="text-decoration-color supports only the grammar '<color>'."> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/parsing-testcommon.js"></script> +<script> +test_invalid_value("text-decoration-color", "auto"); +test_invalid_value("text-decoration-color", "invert"); +test_invalid_value("text-decoration-color", "50%"); +test_invalid_value("text-decoration-color", "red green"); +</script> +
diff --git a/third_party/blink/web_tests/external/wpt/css/css-text-decor/parsing/text-decoration-color-valid.html b/third_party/blink/web_tests/external/wpt/css/css-text-decor/parsing/text-decoration-color-valid.html new file mode 100644 index 0000000..f1998f0 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-text-decor/parsing/text-decoration-color-valid.html
@@ -0,0 +1,14 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>CSS Text Decoration Test: Parsing text-decoration-color with valid values</title> +<link rel="help" href="https://drafts.csswg.org/css-text-decor-3/#text-decoration-color-property"> +<meta name="assert" content="text-decoration-color supports the full grammar '<color>'."> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/parsing-testcommon.js"></script> +<script> +test_valid_value("text-decoration-color", "currentcolor"); +test_valid_value("text-decoration-color", "red"); +test_valid_value("text-decoration-color", "rgba(10, 20, 30, 0.4)"); +</script> +
diff --git a/third_party/blink/web_tests/external/wpt/css/css-text-decor/parsing/text-decoration-computed.html b/third_party/blink/web_tests/external/wpt/css/css-text-decor/parsing/text-decoration-computed.html new file mode 100644 index 0000000..109d475d --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-text-decor/parsing/text-decoration-computed.html
@@ -0,0 +1,32 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="utf-8"> +<title>CSS Text Decoration Test: getComputedValue().textDecoration</title> +<link rel="help" href="https://drafts.csswg.org/css-text-decor-4/#text-decoration-line-property"> +<meta name="assert" content="text-decoration computed value is as specified."> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/computed-testcommon.js"></script> +<style> + #target { + color: blue; + } +</style> +</head> +<body> +<div id="target"></div> +<script> +'use strict'; +const currentColor = "rgb(0, 0, 255)"; +test_computed_value("text-decoration", "none", "none solid " + currentColor); +test_computed_value("text-decoration", "line-through", "line-through solid " + currentColor); +test_computed_value("text-decoration", "solid", "none solid " + currentColor); +test_computed_value("text-decoration", "currentcolor", "none solid " + currentColor); + +test_computed_value("text-decoration", "double overline underline", "underline overline double " + currentColor); +test_computed_value("text-decoration", "underline overline line-through red", "underline overline line-through solid rgb(255, 0, 0)"); +test_computed_value("text-decoration", "rgba(10, 20, 30, 0.4) dotted", "none dotted rgba(10, 20, 30, 0.4)"); + +test_computed_value("text-decoration", "underline dashed rgb(0, 255, 0)"); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-text-decor/parsing/text-decoration-invalid.html b/third_party/blink/web_tests/external/wpt/css/css-text-decor/parsing/text-decoration-invalid.html new file mode 100644 index 0000000..90095c0 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-text-decor/parsing/text-decoration-invalid.html
@@ -0,0 +1,16 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>CSS Text Decoration Test: Parsing text-decoration with invalid values</title> +<link rel="help" href="https://drafts.csswg.org/css-text-decor-3/#propdef-text-decoration"> +<meta name="assert" content="text-decoration supports only the grammar '<‘text-decoration-line’> || <‘text-decoration-style’> || <‘text-decoration-color’>'."> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/parsing-testcommon.js"></script> +<script> +test_invalid_value("text-decoration", "auto"); +test_invalid_value("text-decoration", "1px"); + +test_invalid_value("text-decoration", "double overline underline dotted"); +test_invalid_value("text-decoration", "red line-through green"); +test_invalid_value("text-decoration", "overline blue underline"); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-text-decor/parsing/text-decoration-line-computed-expected.txt b/third_party/blink/web_tests/external/wpt/css/css-text-decor/parsing/text-decoration-line-computed-expected.txt new file mode 100644 index 0000000..965acb3 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-text-decor/parsing/text-decoration-line-computed-expected.txt
@@ -0,0 +1,21 @@ +This is a testharness.js-based test. +PASS Property text-decoration-line value 'none' computes to 'none' +PASS Property text-decoration-line value 'underline' computes to 'underline' +PASS Property text-decoration-line value 'overline' computes to 'overline' +PASS Property text-decoration-line value 'line-through' computes to 'line-through' +FAIL Property text-decoration-line value 'blink' computes to 'blink' assert_equals: expected "blink" but got "none" +PASS Property text-decoration-line value 'underline overline' computes to 'underline overline' +PASS Property text-decoration-line value 'underline line-through' computes to 'underline line-through' +FAIL Property text-decoration-line value 'underline blink' computes to 'underline blink' assert_equals: expected "underline blink" but got "underline" +PASS Property text-decoration-line value 'overline line-through' computes to 'overline line-through' +FAIL Property text-decoration-line value 'overline blink' computes to 'overline blink' assert_equals: expected "overline blink" but got "overline" +FAIL Property text-decoration-line value 'line-through blink' computes to 'line-through blink' assert_equals: expected "line-through blink" but got "line-through" +PASS Property text-decoration-line value 'underline overline line-through' computes to 'underline overline line-through' +FAIL Property text-decoration-line value 'underline overline blink' computes to 'underline overline blink' assert_equals: expected "underline overline blink" but got "underline overline" +FAIL Property text-decoration-line value 'underline line-through blink' computes to 'underline line-through blink' assert_equals: expected "underline line-through blink" but got "underline line-through" +FAIL Property text-decoration-line value 'overline line-through blink' computes to 'overline line-through blink' assert_equals: expected "overline line-through blink" but got "overline line-through" +FAIL Property text-decoration-line value 'underline overline line-through blink' computes to 'underline overline line-through blink' assert_equals: expected "underline overline line-through blink" but got "underline overline line-through" +FAIL Property text-decoration-line value 'spelling-error' computes to 'spelling-error' assert_equals: expected "spelling-error" but got "none" +FAIL Property text-decoration-line value 'grammar-error' computes to 'grammar-error' assert_equals: expected "grammar-error" but got "none" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/css/css-text-decor/parsing/text-decoration-line-computed.html b/third_party/blink/web_tests/external/wpt/css/css-text-decor/parsing/text-decoration-line-computed.html new file mode 100644 index 0000000..d27a6dde --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-text-decor/parsing/text-decoration-line-computed.html
@@ -0,0 +1,41 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="utf-8"> +<title>CSS Text Decoration Test: getComputedValue().textDecorationLine</title> +<link rel="help" href="https://drafts.csswg.org/css-text-decor-4/#text-decoration-line-property"> +<meta name="assert" content="text-decoration-line computed value is specified keyword(s)."> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/computed-testcommon.js"></script> +</head> +<body> +<div id="target"></div> +<script> +// none +test_computed_value("text-decoration-line", "none"); + +// underline || overline || line-through || blink +test_computed_value("text-decoration-line", "underline"); +test_computed_value("text-decoration-line", "overline"); +test_computed_value("text-decoration-line", "line-through"); +test_computed_value("text-decoration-line", "blink"); +test_computed_value("text-decoration-line", "underline overline"); +test_computed_value("text-decoration-line", "underline line-through"); +test_computed_value("text-decoration-line", "underline blink"); +test_computed_value("text-decoration-line", "overline line-through"); +test_computed_value("text-decoration-line", "overline blink"); +test_computed_value("text-decoration-line", "line-through blink"); +test_computed_value("text-decoration-line", "underline overline line-through"); +test_computed_value("text-decoration-line", "underline overline blink"); +test_computed_value("text-decoration-line", "underline line-through blink"); +test_computed_value("text-decoration-line", "overline line-through blink"); +test_computed_value("text-decoration-line", "underline overline line-through blink"); + +// spelling-error +test_computed_value("text-decoration-line", "spelling-error"); + +// grammar-error +test_computed_value("text-decoration-line", "grammar-error"); + +</script>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-text-decor/parsing/text-decoration-valid.html b/third_party/blink/web_tests/external/wpt/css/css-text-decor/parsing/text-decoration-valid.html new file mode 100644 index 0000000..1c1aef3 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-text-decor/parsing/text-decoration-valid.html
@@ -0,0 +1,20 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>CSS Text Decoration Test: Parsing text-decoration with valid values</title> +<link rel="help" href="https://drafts.csswg.org/css-text-decor-3/#propdef-text-decoration"> +<meta name="assert" content="text-decoration supports the full grammar '<‘text-decoration-line’> || <‘text-decoration-style’> || <‘text-decoration-color’>'."> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/parsing-testcommon.js"></script> +<script> +test_valid_value("text-decoration", "none"); +test_valid_value("text-decoration", "line-through"); +test_valid_value("text-decoration", "solid"); +test_valid_value("text-decoration", "currentcolor"); + +test_valid_value("text-decoration", "double overline underline", "underline overline double"); +test_valid_value("text-decoration", "underline overline line-through red"); +test_valid_value("text-decoration", "rgba(10, 20, 30, 0.4) dotted", "dotted rgba(10, 20, 30, 0.4)"); + +test_valid_value("text-decoration", "underline dashed green"); +</script>
diff --git a/third_party/blink/web_tests/http/tests/text-autosizing/narrow-iframe-expected.html b/third_party/blink/web_tests/http/tests/text-autosizing/narrow-iframe-expected.html index df3c5bd..def47433 100644 --- a/third_party/blink/web_tests/http/tests/text-autosizing/narrow-iframe-expected.html +++ b/third_party/blink/web_tests/http/tests/text-autosizing/narrow-iframe-expected.html
@@ -7,10 +7,6 @@ </style> </head> <body> -<iframe style="width: 100%; height: 300px; border: 0" src='data:text/html, -<html style="font-size: 16px"><body style="margin: 0; overflow-y: hidden"><div style="width: 400px; font-size: 1.25rem"> -This text should be autosized to just 20px computed font size, i.e. scaled up by 1.25x, since although this block is in an 800px wide iframe, it is in a 400px block and 400 / 320 = 1.25.<br> -Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. -</div></body></html>'> +<iframe style="width: 100%; height: 300px; border: 0" src='http://localhost:8000/text-autosizing/resources/narrow-iframe-expected.html'> </body> </html>
diff --git a/third_party/blink/web_tests/http/tests/text-autosizing/resources/narrow-iframe-expected.html b/third_party/blink/web_tests/http/tests/text-autosizing/resources/narrow-iframe-expected.html new file mode 100644 index 0000000..6b3b167 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/text-autosizing/resources/narrow-iframe-expected.html
@@ -0,0 +1,4 @@ +<html style="font-size: 16px"><body style="margin: 0; overflow-y: hidden"><div style="width: 400px; font-size: 1.25rem"> +This text should be autosized to just 20px computed font size, i.e. scaled up by 1.25x, since although this block is in an 800px wide iframe, it is in a 400px block and 400 / 320 = 1.25.<br> +Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. +</div></body></html>
diff --git a/third_party/blink/web_tests/http/tests/text-autosizing/resources/narrow-iframe.html b/third_party/blink/web_tests/http/tests/text-autosizing/resources/narrow-iframe.html index d821e82..c73e3616 100644 --- a/third_party/blink/web_tests/http/tests/text-autosizing/resources/narrow-iframe.html +++ b/third_party/blink/web_tests/http/tests/text-autosizing/resources/narrow-iframe.html
@@ -1,5 +1,12 @@ <!DOCTYPE html> -<html style="font-size: 16px"><body style="margin: 0; overflow-y: hidden"><div style="width: 400px"> +<html style="font-size: 16px"> +<head> +<script> + if (window.internals) + internals.settings.setTextAutosizingEnabled(true); +</script> +</head> +<body style="margin: 0; overflow-y: hidden"><div style="width: 400px"> This text should be autosized to just 20px computed font size, i.e. scaled up by 1.25x, since although this block is in an 800px wide iframe, it is in a 400px block and 400 / 320 = 1.25.<br> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </div></body></html>
diff --git a/third_party/blink/web_tests/http/tests/text-autosizing/resources/wide-iframe-expected.html b/third_party/blink/web_tests/http/tests/text-autosizing/resources/wide-iframe-expected.html new file mode 100644 index 0000000..ea64733 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/text-autosizing/resources/wide-iframe-expected.html
@@ -0,0 +1,4 @@ +<html style="font-size: 16px"><body style="margin: 0; overflow-y: hidden"><div style="width: 1600px; font-size: 2.5rem"> +This text should be autosized to just 40px computed font size, i.e. scaled up by 2.5x, since although this block is 1600px wide and is in a 3200px wide iframe, the top level frame is only 800px wide, and min(1600, 3200, 800) / 320 = 2.5.<br> +Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. +</div></body></html>
diff --git a/third_party/blink/web_tests/http/tests/text-autosizing/resources/wide-iframe.html b/third_party/blink/web_tests/http/tests/text-autosizing/resources/wide-iframe.html index 189f317..46042f9 100644 --- a/third_party/blink/web_tests/http/tests/text-autosizing/resources/wide-iframe.html +++ b/third_party/blink/web_tests/http/tests/text-autosizing/resources/wide-iframe.html
@@ -1,5 +1,12 @@ <!DOCTYPE html> -<html style="font-size: 16px"><body style="margin: 0; overflow-y: hidden"><div style="width: 1600px"> +<html style="font-size: 16px"> +<head> +<script> + if (window.internals) + internals.settings.setTextAutosizingEnabled(true); +</script> +</head> +<body style="margin: 0; overflow-y: hidden"><div style="width: 1600px"> This text should be autosized to just 40px computed font size, i.e. scaled up by 2.5x, since although this block is 1600px wide and is in a 3200px wide iframe, the top level frame is only 800px wide, and min(1600, 3200, 800) / 320 = 2.5.<br> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </div></body></html>
diff --git a/third_party/blink/web_tests/http/tests/text-autosizing/wide-iframe-expected.html b/third_party/blink/web_tests/http/tests/text-autosizing/wide-iframe-expected.html index 1a71c0b..86bfc41 100644 --- a/third_party/blink/web_tests/http/tests/text-autosizing/wide-iframe-expected.html +++ b/third_party/blink/web_tests/http/tests/text-autosizing/wide-iframe-expected.html
@@ -10,11 +10,7 @@ </head> <body> -<iframe style="width: 3200px; height: 50%; border: 0" src='data:text/html, -<html style="font-size: 16px"><body style="margin: 0; overflow-y: hidden"><div style="width: 1600px; font-size: 2.5rem"> -This text should be autosized to just 40px computed font size, i.e. scaled up by 2.5x, since although this block is 1600px wide and is in a 3200px wide iframe, the top level frame is only 800px wide, and min(1600, 3200, 800) / 320 = 2.5.<br> -Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. -</div></body></html>'> +<iframe style="width: 3200px; height: 50%; border: 0" src='http://localhost:8000/text-autosizing/resources/wide-iframe-expected.html'> </body> </html>
diff --git a/third_party/blink/web_tests/virtual/streams-native/http/tests/streams/transferable/readable-stream-expected.txt b/third_party/blink/web_tests/virtual/streams-native/http/tests/streams/transferable/readable-stream-expected.txt deleted file mode 100644 index a398705f..0000000 --- a/third_party/blink/web_tests/virtual/streams-native/http/tests/streams/transferable/readable-stream-expected.txt +++ /dev/null
@@ -1,19 +0,0 @@ -This is a testharness.js-based test. -FAIL sending one chunk through a transferred stream should work promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL sending ten chunks through a transferred stream should work promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL sending ten chunks one at a time should work promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL sending ten chunks on demand should work promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL transferring a stream should relieve backpressure assert_array_equals: pull() should have been called lengths differ, expected 1 got 0 -FAIL transferring a stream should add one chunk to the queue size promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL the extra queue from transferring is counted in chunks promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL cancel should be propagated to the original promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL cancel should abort a pending read() promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL stream cancel should not wait for underlying source cancel promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL serialization should not happen until the value is read promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL transferring a non-serializable chunk should error both sides promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL errors should be passed through promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL race between cancel() and error() should leave sides in different states promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL race between cancel() and close() should be benign promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL race between cancel() and enqueue() should be benign promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/virtual/streams-native/http/tests/streams/transferable/reason-expected.txt b/third_party/blink/web_tests/virtual/streams-native/http/tests/streams/transferable/reason-expected.txt deleted file mode 100644 index e381006..0000000 --- a/third_party/blink/web_tests/virtual/streams-native/http/tests/streams/transferable/reason-expected.txt +++ /dev/null
@@ -1,25 +0,0 @@ -This is a testharness.js-based test. -FAIL reason with a simple value of 'hi' should be preserved promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL reason with a simple value of ' \r -' should be preserved promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL reason with a simple value of '7' should be preserved promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL reason with a simple value of '3' should be preserved promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL reason with a simple value of 'undefined' should be preserved promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL reason with a simple value of 'null' should be preserved promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL reason with a simple value of 'true' should be preserved promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL reason with a simple value of 'false' should be preserved promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL reason with a type of 'symbol' should be squished to undefined promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL reason with a type of 'function' should be squished to undefined promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL number with a value of 'NaN' should be squished to null promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL number with a value of 'Infinity' should be squished to null promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL objects that can be completely expressed in JSON should be preserved promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL objects that cannot be expressed in JSON should result in a TypeError promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL the type and message of a TypeError should be preserved promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL other attributes of a TypeError should not be preserved promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL a TypeError message should not be preserved if it is not a string promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL a TypeError message should not be preserved if it is a getter promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL a TypeError message should not be preserved if it is inherited promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL DOMException errors should be preserved promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -FAIL RangeErrors should not be preserved promise_test: Unhandled rejection with value: object "Error: what is this thing: "null"?" -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/virtual/streams-native/http/tests/streams/transferable/service-worker-expected.txt b/third_party/blink/web_tests/virtual/streams-native/http/tests/streams/transferable/service-worker-expected.txt deleted file mode 100644 index d487631..0000000 --- a/third_party/blink/web_tests/virtual/streams-native/http/tests/streams/transferable/service-worker-expected.txt +++ /dev/null
@@ -1,6 +0,0 @@ -This is a testharness.js-based test. -PASS service-worker -FAIL serviceWorker.controller.postMessage should be able to transfer a ReadableStream assert_true: the original stream should be locked expected true got false -FAIL postMessage in a service worker should be able to transfer ReadableStream promise_test: Unhandled rejection with value: "BAD: TypeError: Cannot read property 'constructor' of null" -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/virtual/streams-native/http/tests/streams/transferable/shared-worker-expected.txt b/third_party/blink/web_tests/virtual/streams-native/http/tests/streams/transferable/shared-worker-expected.txt deleted file mode 100644 index a61ccf35..0000000 --- a/third_party/blink/web_tests/virtual/streams-native/http/tests/streams/transferable/shared-worker-expected.txt +++ /dev/null
@@ -1,5 +0,0 @@ -This is a testharness.js-based test. -FAIL worker.postMessage should be able to transfer a ReadableStream assert_true: the original stream should be locked expected true got false -FAIL postMessage in a worker should be able to transfer a ReadableStream promise_test: Unhandled rejection with value: object "TypeError: Cannot read property 'constructor' of null" -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/virtual/streams-native/http/tests/streams/transferable/transform-stream-expected.txt b/third_party/blink/web_tests/virtual/streams-native/http/tests/streams/transferable/transform-stream-expected.txt deleted file mode 100644 index fddd996..0000000 --- a/third_party/blink/web_tests/virtual/streams-native/http/tests/streams/transferable/transform-stream-expected.txt +++ /dev/null
@@ -1,8 +0,0 @@ -This is a testharness.js-based test. -FAIL window.postMessage should be able to transfer a TransformStream assert_true: the readable side should be locked expected true got false -PASS a TransformStream with a locked writable should not be transferable -PASS a TransformStream with a locked readable should not be transferable -PASS a TransformStream with both sides locked should not be transferable -FAIL piping through transferred transforms should work Cannot read property 'source' of null -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/virtual/streams-native/http/tests/streams/transferable/window-expected.txt b/third_party/blink/web_tests/virtual/streams-native/http/tests/streams/transferable/window-expected.txt deleted file mode 100644 index 8e6fa50..0000000 --- a/third_party/blink/web_tests/virtual/streams-native/http/tests/streams/transferable/window-expected.txt +++ /dev/null
@@ -1,13 +0,0 @@ -CONSOLE ERROR: line 23: Uncaught TypeError: Cannot read property 'start' of null -CONSOLE ERROR: line 17: Uncaught (in promise) TypeError: Cannot read property 'constructor' of null -CONSOLE ERROR: line 41: Uncaught (in promise) TypeError: Cannot read property 'addEventListener' of null -CONSOLE ERROR: line 45: Uncaught (in promise) Error: assert_array_equals: there should be no ports in the event lengths differ, expected 0 got 1 -CONSOLE ERROR: line 5: Uncaught TypeError: Failed to execute 'postMessage' on 'Window': Value at index 0 is an untransferable 'null' value. -This is a testharness.js-based test. -Harness Error. harness_status.status = 1 , harness_status.message = assert_array_equals: there should be no ports in the event lengths differ, expected 0 got 1 -FAIL window.postMessage should be able to transfer a ReadableStream assert_true: the original stream should be locked expected true got false -FAIL port.postMessage should be able to transfer a ReadableStream assert_true: the original stream should be locked expected true got false -FAIL the same ReadableStream posted multiple times should arrive together object null is not iterable (cannot read property Symbol(Symbol.iterator)) -FAIL transfer to and from an iframe should work assert_array_equals: there should be no ports in the event lengths differ, expected 0 got 1 -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/virtual/streams-native/http/tests/streams/transferable/worker-expected.txt b/third_party/blink/web_tests/virtual/streams-native/http/tests/streams/transferable/worker-expected.txt deleted file mode 100644 index d3ca9a3..0000000 --- a/third_party/blink/web_tests/virtual/streams-native/http/tests/streams/transferable/worker-expected.txt +++ /dev/null
@@ -1,8 +0,0 @@ -CONSOLE ERROR: line 2: Uncaught TypeError: Failed to execute 'postMessage' on 'DedicatedWorkerGlobalScope': Value at index 0 is an untransferable 'null' value. -CONSOLE ERROR: line 2: Uncaught TypeError: Failed to execute 'postMessage' on 'DedicatedWorkerGlobalScope': Value at index 0 is an untransferable 'null' value. -This is a testharness.js-based test. -FAIL worker.postMessage should be able to transfer a ReadableStream assert_true: the original stream should be locked expected true got false -FAIL postMessage in a worker should be able to transfer a ReadableStream promise_test: Unhandled rejection with value: object "TypeError: Cannot read property 'constructor' of null" -FAIL terminating a worker should not error the stream promise_test: Unhandled rejection with value: "error in worker" -Harness: the test ran to completion. -
diff --git a/third_party/freetype/README.chromium b/third_party/freetype/README.chromium index 2b8faca..3ebbfe0d 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-10-0-57-g7fde521bd -Revision: 7fde521bd918d2299cce80c306ecc2cac9f51303 +Version: VER-2-10-0-59-g78c02bc11 +Revision: 78c02bc110b6a605c41487d8c26ae18960df251b License: Custom license "inspired by the BSD, Artistic, and IJG (Independent JPEG Group) licenses" License File: src/docs/FTL.TXT
diff --git a/tools/binary_size/diagnose_bloat.py b/tools/binary_size/diagnose_bloat.py index c4cb3a3cb..3ff8c7a 100755 --- a/tools/binary_size/diagnose_bloat.py +++ b/tools/binary_size/diagnose_bloat.py
@@ -337,7 +337,6 @@ def _GenGnCmd(self): gn_args = 'is_official_build=true' gn_args += ' android_channel="stable"' - gn_args += ' enable_chrome_language_splits=true' # Variables often become unused when experimenting with macros to reduce # size, so don't fail on warnings. gn_args += ' treat_warnings_as_errors=false'
diff --git a/tools/flags/list-flags.py b/tools/flags/list-flags.py index 799be77e9..b91b74a6 100755 --- a/tools/flags/list-flags.py +++ b/tools/flags/list-flags.py
@@ -24,19 +24,6 @@ return json5.load(open(flags_path)) -def keep_unowned(flags): - """Filter flags to contain only flags with no owners entry. - - >>> keep_unowned([{'name': 'foo'}]) - [{'name': 'foo'}] - >>> keep_unowned([{'name': 'bar', 'owners': ['f']}]) - [] - >>> keep_unowned([{'name': 'foo'}, {'name': 'bar', 'owners': ['f']}]) - [{'name': 'foo'}] - """ - return [f for f in flags if not f.get('owners')] - - def keep_expired_by(flags, mstone): """Filter flags to contain only flags that expire by mstone. @@ -69,7 +56,7 @@ prints just the name. >>> f1 = {'name': 'foo', 'expiry_milestone': 73, 'owners': ['bar', 'baz']} - >>> f2 = {'name': 'bar', 'expiry_milestone': 74} + >>> f2 = {'name': 'bar', 'expiry_milestone': 74, 'owners': ['//quxx/OWNERS']} >>> print_flags([f1], False) foo >>> print_flags([f1], True) @@ -77,12 +64,12 @@ >>> print_flags([f2], False) bar >>> print_flags([f2], True) - bar expires 74 owners (none) + bar expires 74 owners //quxx/OWNERS """ for f in flags: if verbose: print '%s expires %d owners %s' % (f['name'], f['expiry_milestone'], - ', '.join(f.get('owners', ['(none)']))) + ', '.join(f['owners'])) else: print f['name'] @@ -92,7 +79,6 @@ doctest.testmod() parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('-u', '--unowned', action='store_true') group = parser.add_mutually_exclusive_group() group.add_argument('-n', '--never-expires', action='store_true') group.add_argument('-e', '--expired-by', type=int) @@ -100,8 +86,6 @@ args = parser.parse_args() flags = load_metadata() - if args.unowned: - flags = keep_unowned(flags) if args.expired_by: flags = keep_expired_by(flags, args.expired_by) if args.never_expires:
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 85c8afd6..445e8cf7 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -33460,6 +33460,7 @@ <int value="-1839874877" label="WebXROrientationSensorDevice:enabled"/> <int value="-1839496458" label="disable-file-manager-touch-mode"/> <int value="-1838482444" label="disable-settings-window"/> + <int value="-1837401779" label="EnableFileManagerFormatDialog:enabled"/> <int value="-1837329460" label="NewEncodeCpuLoadEstimator:enabled"/> <int value="-1835975804" label="disable-offline-auto-reload"/> <int value="-1833149810" label="enable-accessibility-tab-switcher"/> @@ -34817,6 +34818,7 @@ <int value="151022756" label="ArcAvailableForChildAccount:disabled"/> <int value="151101719" label="HtmlBaseUsernameDetector:enabled"/> <int value="153347646" label="SmartDimModelV3:disabled"/> + <int value="155977192" label="EnableFileManagerFormatDialog:disabled"/> <int value="157217034" label="enable-tab-for-desktop-share"/> <int value="157318016" label="AutomaticTabDiscarding:enabled"/> <int value="160838658" label="SmartDimModelV3:enabled"/>
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 2dbf1acb..dd0b8cc 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -71115,7 +71115,7 @@ </histogram> <histogram name="Net.QuicSession.CloseAllSessionsError" enum="NetErrorCodes" - expires_after="M77"> + expires_after="M80"> <owner>rch@chromium.org</owner> <summary> The network error code which resulted in all sessions being closed. @@ -71428,7 +71428,7 @@ </histogram> <histogram name="Net.QuicSession.HandshakeStatusOnConnectionMigration" - enum="BooleanConfirmed" expires_after="M77"> + enum="BooleanConfirmed" expires_after="M80"> <owner>zhongyi@chromium.org</owner> <summary> The handshake status when when the session attempts to migrate the @@ -71437,7 +71437,7 @@ </histogram> <histogram name="Net.QuicSession.HandshakeTimeout.PathDegradingDetected" - enum="BooleanDetected" expires_after="M77"> + enum="BooleanDetected" expires_after="M80"> <owner>zhongyi@chromium.org</owner> <summary> Whether path degrading has been detected by the time a QUIC connection is @@ -135774,6 +135774,9 @@ <histogram name="UMA.SubprocessMetricsProvider.UntrackedProcesses" enum="SubprocessType" expires_after="M77"> + <obsolete> + Removed 2019/06 after not reporting anything in years. + </obsolete> <owner>asvitkine@chromium.org</owner> <owner>bcwhite@chromium.org</owner> <summary>
diff --git a/tools/perf/benchmarks/startup_mobile.py b/tools/perf/benchmarks/startup_mobile.py index 9751ced..189e9ca 100644 --- a/tools/perf/benchmarks/startup_mobile.py +++ b/tools/perf/benchmarks/startup_mobile.py
@@ -190,8 +190,7 @@ self._current_story = None self._possible_browser.CleanUpEnvironment() - def DumpStateUponFailure(self, story, results): - del story + def DumpStateUponStoryRunFailure(self, results): del results # Note: Dumping state of objects upon errors, e.g. of the browser, is # handled individually by the context managers that handle their lifetime.
diff --git a/tools/perf/page_sets/dual_browser_story.py b/tools/perf/page_sets/dual_browser_story.py index ac1c84e..2577121 100644 --- a/tools/perf/page_sets/dual_browser_story.py +++ b/tools/perf/page_sets/dual_browser_story.py
@@ -213,7 +213,8 @@ self.platform.network_controller.Close() self._CloseAllBrowsers() - def DumpStateUponFailure(self, unused_story, unused_results): + def DumpStateUponStoryRunFailure(self, results): + del results # Unused. if self._browsers: for browser_type, browser in self._browsers.iteritems(): if browser is not None:
diff --git a/ui/accessibility/platform/ax_platform_node_auralinux.cc b/ui/accessibility/platform/ax_platform_node_auralinux.cc index 701ec8b..586123f 100644 --- a/ui/accessibility/platform/ax_platform_node_auralinux.cc +++ b/ui/accessibility/platform/ax_platform_node_auralinux.cc
@@ -3039,8 +3039,6 @@ } void AXPlatformNodeAuraLinux::OnNameChanged() { - std::string name = GetStringAttribute(ax::mojom::StringAttribute::kName); - std::string previous_accessible_name = accessible_name_; // Calling atk_object_get_name will update the value of accessible_name_. if (!g_strcmp0(atk_object_get_name(atk_object_), @@ -3128,6 +3126,9 @@ case ax::mojom::Event::kSelectedChildrenChanged: OnSelectedChildrenChanged(); break; + case ax::mojom::Event::kTextChanged: + OnNameChanged(); + break; case ax::mojom::Event::kTextSelectionChanged: OnTextSelectionChanged(); break;
diff --git a/ui/file_manager/file_manager/foreground/js/metadata/BUILD.gn b/ui/file_manager/file_manager/foreground/js/metadata/BUILD.gn index 52e0a3c6..65c11c4 100644 --- a/ui/file_manager/file_manager/foreground/js/metadata/BUILD.gn +++ b/ui/file_manager/file_manager/foreground/js/metadata/BUILD.gn
@@ -287,4 +287,5 @@ ":multi_metadata_provider_unittest", ":thumbnail_model_unittest", ] + mocks = [ "metadata_dispatcher_mock_deps.js" ] }
diff --git a/ui/file_manager/file_manager/foreground/js/metadata/exif_parser.js b/ui/file_manager/file_manager/foreground/js/metadata/exif_parser.js index 4dcc94b..48ae4af 100644 --- a/ui/file_manager/file_manager/foreground/js/metadata/exif_parser.js +++ b/ui/file_manager/file_manager/foreground/js/metadata/exif_parser.js
@@ -2,25 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// When running this code in unit tests, `importScripts` is not defined, but -// that doesn't really matter since the dependent file is already included by -// the build system. -if (typeof importScripts !== 'undefined') { - /** - * Protocol + host parts of extension URL. - * - * The __FILE_NAME suffix is because the same string constant is used in - * multiple JS files, and JavaScript doesn't have C's #define mechanism (which - * only affects the file its in). Without the suffix, we'd have "constant - * FILE_MANAGER_HOST assigned a value more than once" compiler warnings. - */ - const FILE_MANAGER_HOST__EXIF_PARSER = - 'chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj'; - - importScripts( - FILE_MANAGER_HOST__EXIF_PARSER + - '/foreground/js/metadata/exif_constants.js'); -} +importScripts( + 'chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj/foreground/js/metadata/exif_constants.js'); /** @final */ class ExifParser extends ImageParser {
diff --git a/ui/file_manager/file_manager/foreground/js/metadata/id3_parser.js b/ui/file_manager/file_manager/foreground/js/metadata/id3_parser.js index 4a797f7..1e46966c 100644 --- a/ui/file_manager/file_manager/foreground/js/metadata/id3_parser.js +++ b/ui/file_manager/file_manager/foreground/js/metadata/id3_parser.js
@@ -2,26 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/** - * Protocol + host parts of extension URL. - * - * The __FILE_NAME suffix is because the same string constant is used in - * multiple JS files, and JavaScript doesn't have C's #define mechanism (which - * only affects the file its in). Without the suffix, we'd have "constant - * FILE_MANAGER_HOST assigned a value more than once" compiler warnings. - * - * @type {string} - * @const - */ -const FILE_MANAGER_HOST__ID3_PARSER = - 'chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj'; - importScripts( - FILE_MANAGER_HOST__ID3_PARSER + - '/foreground/js/metadata/function_sequence.js'); + 'chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj/foreground/js/metadata/function_sequence.js'); importScripts( - FILE_MANAGER_HOST__ID3_PARSER + - '/foreground/js/metadata/function_parallel.js'); + 'chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj/foreground/js/metadata/function_parallel.js'); /** * ID3 parser.
diff --git a/ui/file_manager/file_manager/foreground/js/metadata/metadata_dispatcher.js b/ui/file_manager/file_manager/foreground/js/metadata/metadata_dispatcher.js index 90d344f..6836fc7 100644 --- a/ui/file_manager/file_manager/foreground/js/metadata/metadata_dispatcher.js +++ b/ui/file_manager/file_manager/foreground/js/metadata/metadata_dispatcher.js
@@ -2,43 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/** - * Protocol + host parts of extension URL. - * - * The __FILE_NAME suffix is because the same string constant is used in - * multiple JS files, and JavaScript doesn't have C's #define mechanism (which - * only affects the file its in). Without the suffix, we'd have "constant - * FILE_MANAGER_HOST assigned a value more than once" compiler warnings. - * - * @type {string} - * @const - */ -const FILE_MANAGER_HOST__METADATA_DISPATCHER = - 'chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj'; - // All of these scripts could be imported with a single call to importScripts, // but then load and compile time errors would all be reported from the same -// line. +// line. Note: update component_extension_resources.grd when adding new parsers. importScripts( - FILE_MANAGER_HOST__METADATA_DISPATCHER + - '/foreground/js/metadata/metadata_parser.js'); + 'chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj/foreground/js/metadata/metadata_parser.js'); importScripts( - FILE_MANAGER_HOST__METADATA_DISPATCHER + - '/foreground/js/metadata/byte_reader.js'); - -// Note: update component_extension_resources.grd when adding new parsers. + 'chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj/foreground/js/metadata/byte_reader.js'); importScripts( - FILE_MANAGER_HOST__METADATA_DISPATCHER + - '/foreground/js/metadata/exif_parser.js'); + 'chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj/foreground/js/metadata/exif_parser.js'); importScripts( - FILE_MANAGER_HOST__METADATA_DISPATCHER + - '/foreground/js/metadata/image_parsers.js'); + 'chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj/foreground/js/metadata/image_parsers.js'); importScripts( - FILE_MANAGER_HOST__METADATA_DISPATCHER + - '/foreground/js/metadata/mpeg_parser.js'); + 'chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj/foreground/js/metadata/mpeg_parser.js'); importScripts( - FILE_MANAGER_HOST__METADATA_DISPATCHER + - '/foreground/js/metadata/id3_parser.js'); + 'chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj/foreground/js/metadata/id3_parser.js'); /** * Dispatches metadata requests to the correct parser. @@ -257,4 +235,3 @@ // Non-shared worker. new MetadataDispatcher(global); } -
diff --git a/ui/file_manager/integration_tests/test_util.js b/ui/file_manager/integration_tests/test_util.js index b173cc2..06a2a98 100644 --- a/ui/file_manager/integration_tests/test_util.js +++ b/ui/file_manager/integration_tests/test_util.js
@@ -574,11 +574,10 @@ typeText: 'PNG image' }), - // An image file without an extension, to confirm that file type detection - // using mime types works fine. image2: new TestEntryInfo({ type: EntryType.FILE, sourceFileName: 'image2.png', + // No file extension. targetPath: 'image2', mimeType: 'image/png', lastModifiedTime: 'Jan 18, 2038, 1:02 AM', @@ -609,11 +608,21 @@ typeText: 'JPEG image' }), - // An ogg file without a mime type, to confirm that file type detection using - // file extensions works fine. + exifImage: new TestEntryInfo({ + type: EntryType.FILE, + sourceFileName: 'exif.jpg', + // No mime type. + targetPath: 'exif.jpg', + lastModifiedTime: 'Jan 18, 2038, 1:02 AM', + nameText: 'exif.jpg', + sizeText: '31 KB', + typeText: 'JPEG image' + }), + beautiful: new TestEntryInfo({ type: EntryType.FILE, sourceFileName: 'music.ogg', + // No mime type. targetPath: 'Beautiful Song.ogg', lastModifiedTime: 'Nov 12, 2086, 12:00 PM', nameText: 'Beautiful Song.ogg', @@ -673,10 +682,10 @@ typeText: 'Plain text', }), - // Note, no MIME type here, this is used for testing file content sniffing. plainText: new TestEntryInfo({ type: EntryType.FILE, sourceFileName: 'plaintext', + // No mime type, no file extension. targetPath: 'plaintext', lastModifiedTime: 'Sep 4, 1998, 12:34 PM', nameText: 'plaintext',
diff --git a/ui/shell_dialogs/BUILD.gn b/ui/shell_dialogs/BUILD.gn index 429d75c5..872767c 100644 --- a/ui/shell_dialogs/BUILD.gn +++ b/ui/shell_dialogs/BUILD.gn
@@ -75,7 +75,11 @@ "Foundation.framework", "AppKit.framework", ] - deps += [ "//components/remote_cocoa/browser" ] + deps += [ + "//components/remote_cocoa/app_shim", + "//components/remote_cocoa/browser", + "//components/remote_cocoa/common:mojo", + ] } if (is_fuchsia) { @@ -97,9 +101,14 @@ ":shell_dialogs", "//base", "//base/test:test_support", + "//mojo/core/embedder", "//testing/gtest", "//ui/base", "//ui/resources:ui_test_pak_data", "//ui/strings", ] + + if (is_mac) { + deps += [ "//components/remote_cocoa/app_shim" ] + } }
diff --git a/ui/shell_dialogs/DEPS b/ui/shell_dialogs/DEPS index eda7619..11d09a31a 100644 --- a/ui/shell_dialogs/DEPS +++ b/ui/shell_dialogs/DEPS
@@ -1,6 +1,8 @@ include_rules = [ "+jni", - "+components/remote_cocoa/browser/window.h", + "+components/remote_cocoa", + "+mojo/core/embedder", + "+mojo/public/cpp/bindings", "+ui/android/window_android.h", "+ui/aura", "+ui/base",
diff --git a/ui/shell_dialogs/run_all_unittests.cc b/ui/shell_dialogs/run_all_unittests.cc index e3c12ce5..c390b5cf 100644 --- a/ui/shell_dialogs/run_all_unittests.cc +++ b/ui/shell_dialogs/run_all_unittests.cc
@@ -8,6 +8,7 @@ #include "base/test/launcher/unit_test_launcher.h" #include "base/test/test_suite.h" #include "build/build_config.h" +#include "mojo/core/embedder/embedder.h" #include "ui/base/material_design/material_design_controller.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/ui_base_paths.h" @@ -61,6 +62,8 @@ int main(int argc, char** argv) { ShellDialogsTestSuite test_suite(argc, argv); + mojo::core::Init(); + return base::LaunchUnitTests(argc, argv, base::BindOnce(&ShellDialogsTestSuite::Run, base::Unretained(&test_suite)));
diff --git a/ui/shell_dialogs/select_file_dialog_mac.h b/ui/shell_dialogs/select_file_dialog_mac.h index 7f1d8c83..cf69dc9 100644 --- a/ui/shell_dialogs/select_file_dialog_mac.h +++ b/ui/shell_dialogs/select_file_dialog_mac.h
@@ -5,81 +5,23 @@ #ifndef UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_MAC_H_ #define UI_SHELL_DIALOGS_SELECT_FILE_DIALOG_MAC_H_ -#import <Cocoa/Cocoa.h> - #include <list> #include <memory> #include <vector> -#include "base/callback.h" -#import "base/mac/scoped_nsobject.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" +#include "components/remote_cocoa/common/select_file_dialog.mojom.h" #include "ui/gfx/native_widget_types.h" #include "ui/shell_dialogs/select_file_dialog.h" #include "ui/shell_dialogs/shell_dialogs_export.h" -@class ExtensionDropdownHandler; -@class SelectFileDialogDelegate; - namespace ui { namespace test { class SelectFileDialogMacTest; } // namespace test -// TODO(https://crbug.com/913303): Move this structure to -// components/remote_cocoa. This structure provides a C++ (or mojo) interface -// for creating a NSSavePanel. -class SavePanelBridge { - public: - // Callback made from the NSSavePanel's completion block. - using PanelEndedCallback = - base::OnceCallback<void(bool was_cancelled, - const std::vector<base::FilePath>& files, - int index)>; - - SavePanelBridge(PanelEndedCallback callback); - ~SavePanelBridge(); - - void Initialize(SelectFileDialog::Type type, - NSWindow* owning_window, - const base::string16& title, - const base::FilePath& default_path, - const SelectFileDialog::FileTypeInfo* file_types, - int file_type_index, - const base::FilePath::StringType& default_extension); - NSSavePanel* GetNativePanelForTesting() { return panel_.get(); } - - private: - // Sets the accessory view for |dialog_| and sets - // |extension_dropdown_handler_|. - void SetAccessoryView(const SelectFileDialog::FileTypeInfo* file_types, - int file_type_index, - const base::FilePath::StringType& default_extension); - - // Called when the panel completes. - void OnPanelEnded(bool did_cancel); - - // The callback to make when this dialog ends. - PanelEndedCallback callback_; - - // Type type of this dialog. - SelectFileDialog::Type type_; - - // The NSSavePanel that |this| tracks. - base::scoped_nsobject<NSSavePanel> panel_; - - // The delegate for |panel|. - base::scoped_nsobject<SelectFileDialogDelegate> delegate_; - - // Extension dropdown handler corresponding to this file dialog. - base::scoped_nsobject<ExtensionDropdownHandler> extension_dropdown_handler_; - - base::WeakPtrFactory<SavePanelBridge> weak_factory_; - DISALLOW_COPY_AND_ASSIGN(SavePanelBridge); -}; - // Implementation of SelectFileDialog that shows Cocoa dialogs for choosing a // file or folder. // Exported for unit tests. @@ -119,7 +61,7 @@ void* params; // Bridge to the Cocoa NSSavePanel. - std::unique_ptr<SavePanelBridge> save_panel_bridge; + remote_cocoa::mojom::SelectFileDialogPtr select_file_dialog; private: DISALLOW_COPY_AND_ASSIGN(DialogData);
diff --git a/ui/shell_dialogs/select_file_dialog_mac.mm b/ui/shell_dialogs/select_file_dialog_mac.mm index 77d05b4..01a4148 100644 --- a/ui/shell_dialogs/select_file_dialog_mac.mm +++ b/ui/shell_dialogs/select_file_dialog_mac.mm
@@ -4,130 +4,24 @@ #include "ui/shell_dialogs/select_file_dialog_mac.h" -#include <CoreServices/CoreServices.h> -#include <stddef.h> - -#include <vector> - #include "base/bind.h" -#include "base/files/file_util.h" -#include "base/i18n/case_conversion.h" #include "base/logging.h" -#include "base/mac/foundation_util.h" -#include "base/mac/scoped_cftyperef.h" -#include "base/strings/sys_string_conversions.h" -#include "base/strings/utf_string_conversions.h" #include "base/threading/thread_restrictions.h" +#include "components/remote_cocoa/app_shim/select_file_dialog_bridge.h" #include "components/remote_cocoa/browser/window.h" -#import "ui/base/cocoa/controls/textfield_utils.h" -#include "ui/base/l10n/l10n_util_mac.h" +#include "mojo/public/cpp/bindings/interface_request.h" +#include "mojo/public/cpp/bindings/strong_binding.h" #include "ui/shell_dialogs/select_file_policy.h" -#include "ui/strings/grit/ui_strings.h" -namespace { - -const int kFileTypePopupTag = 1234; - -CFStringRef CreateUTIFromExtension(const base::FilePath::StringType& ext) { - base::ScopedCFTypeRef<CFStringRef> ext_cf(base::SysUTF8ToCFStringRef(ext)); - return UTTypeCreatePreferredIdentifierForTag( - kUTTagClassFilenameExtension, ext_cf.get(), NULL); -} - -NSString* GetDescriptionFromExtension(const base::FilePath::StringType& ext) { - base::ScopedCFTypeRef<CFStringRef> uti(CreateUTIFromExtension(ext)); - base::ScopedCFTypeRef<CFStringRef> description( - UTTypeCopyDescription(uti.get())); - - if (description && CFStringGetLength(description)) - return [[base::mac::CFToNSCast(description.get()) retain] autorelease]; - - // In case no description is found, create a description based on the - // unknown extension type (i.e. if the extension is .qqq, the we create - // a description "QQQ File (.qqq)"). - base::string16 ext_name = base::UTF8ToUTF16(ext); - return l10n_util::GetNSStringF(IDS_APP_SAVEAS_EXTENSION_FORMAT, - base::i18n::ToUpper(ext_name), ext_name); -} - -base::scoped_nsobject<NSView> CreateAccessoryView() { - static constexpr CGFloat kControlPadding = 2; - - base::scoped_nsobject<NSView> view( - [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 350, 60)]); - - // Create the label and center it vertically. - NSTextField* label = [TextFieldUtils - labelWithString:l10n_util::GetNSString( - IDS_SAVE_PAGE_FILE_FORMAT_PROMPT_MAC)]; - [label sizeToFit]; - NSRect label_frame = [label frame]; - label_frame.origin = - NSMakePoint(kControlPadding, NSMidY([view frame]) - NSMidY(label_frame)); - [label setFrame:label_frame]; - [view addSubview:label]; - - // Create the pop-up button, positioning it to the right of the label. - // Its X position needs to be slightly below the label's, so that the text - // baselines are aligned. - base::scoped_nsobject<NSPopUpButton> pop_up_button([[NSPopUpButton alloc] - initWithFrame:NSMakeRect(NSWidth(label_frame) + kControlPadding, - NSMinY(label_frame) - 5, 230, 25) - pullsDown:NO]); - [pop_up_button setTag:kFileTypePopupTag]; - [view addSubview:pop_up_button.get()]; - - // Resize the containing view to fit the controls. - CGFloat total_width = NSMaxX([pop_up_button frame]); - NSRect view_frame = [view frame]; - view_frame.size.width = total_width + kControlPadding; - [view setFrame:view_frame]; - - return view; -} - -} // namespace - -// A bridge class to act as the modal delegate to the save/open sheet and send -// the results to the C++ class. -@interface SelectFileDialogDelegate : NSObject <NSOpenSavePanelDelegate> -@end - -// Target for NSPopupButton control in file dialog's accessory view. -@interface ExtensionDropdownHandler : NSObject { - @private - // The file dialog to which this target object corresponds. Weak reference - // since the dialog_ will stay alive longer than this object. - NSSavePanel* dialog_; - - // An array whose each item corresponds to an array of different extensions in - // an extension group. - base::scoped_nsobject<NSArray> fileTypeLists_; -} - -- (id)initWithDialog:(NSSavePanel*)dialog fileTypeLists:(NSArray*)fileTypeLists; - -- (void)popupAction:(id)sender; -@end +using remote_cocoa::mojom::SelectFileDialogType; +using remote_cocoa::mojom::SelectFileTypeInfo; +using remote_cocoa::mojom::SelectFileTypeInfoPtr; namespace ui { using Type = SelectFileDialog::Type; using FileTypeInfo = SelectFileDialog::FileTypeInfo; -SavePanelBridge::SavePanelBridge(PanelEndedCallback callback) - : callback_(std::move(callback)), weak_factory_(this) {} - -SavePanelBridge::~SavePanelBridge() { - // If we never executed our callback, then the panel never closed. Cancel it - // now. - if (callback_) - [panel_ cancel:panel_]; - - // Balance the setDelegate called during Initialize. - [panel_ setDelegate:nil]; -} - SelectFileDialogImpl::SelectFileDialogImpl( Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy) @@ -197,127 +91,60 @@ hasMultipleFileTypeChoices_ = file_types ? file_types->extensions.size() > 1 : true; - // Add a new DialogData to the list. + // Add a new DialogData to the list. Note that it is safe to pass + // |dialog_data| by a pointer because it will only be removed from the list + // when the callback is made or after the callback has been cancelled by + // |weak_factory_|. dialog_data_list_.emplace_back(owning_window, params); DialogData& dialog_data = dialog_data_list_.back(); - // Create a NSSavePanel for it. Note that it is safe to pass |dialog_data| by - // a pointer because it will only be removed from the list when the callback - // is made or after the callback has been cancelled by |weak_factory_|. - dialog_data.save_panel_bridge = - std::make_unique<SavePanelBridge>(base::BindOnce( - &SelectFileDialogImpl::FileWasSelected, weak_factory_.GetWeakPtr(), - &dialog_data, type == SELECT_OPEN_MULTI_FILE)); - dialog_data.save_panel_bridge->Initialize(type, owning_window, title, - default_path, file_types, - file_type_index, default_extension); -} + // Create a NSSavePanel for it. + mojo::MakeStrongBinding( + std::make_unique<remote_cocoa::SelectFileDialogBridge>(owning_window), + mojo::MakeRequest(&dialog_data.select_file_dialog)); -void SavePanelBridge::Initialize( - Type type, - NSWindow* owning_window, - const base::string16& title, - const base::FilePath& default_path, - const FileTypeInfo* file_types, - int file_type_index, - const base::FilePath::StringType& default_extension) { - type_ = type; - // Note: we need to retain the dialog as |owning_window| can be null. - // (See http://crbug.com/29213 .) - if (type_ == SelectFileDialog::SELECT_SAVEAS_FILE) - panel_.reset([[NSSavePanel savePanel] retain]); - else - panel_.reset([[NSOpenPanel openPanel] retain]); - NSSavePanel* dialog = panel_.get(); - - if (!title.empty()) - [dialog setMessage:base::SysUTF16ToNSString(title)]; - - NSString* default_dir = nil; - NSString* default_filename = nil; - if (!default_path.empty()) { - // The file dialog is going to do a ton of stats anyway. Not much - // point in eliminating this one. - base::ThreadRestrictions::ScopedAllowIO allow_io; - if (base::DirectoryExists(default_path)) { - default_dir = base::SysUTF8ToNSString(default_path.value()); - } else { - default_dir = base::SysUTF8ToNSString(default_path.DirName().value()); - default_filename = - base::SysUTF8ToNSString(default_path.BaseName().value()); - } + // Show the panel. + SelectFileDialogType mojo_type = SelectFileDialogType::kFolder; + switch (type) { + case SELECT_FOLDER: + mojo_type = SelectFileDialogType::kFolder; + break; + case SELECT_UPLOAD_FOLDER: + mojo_type = SelectFileDialogType::kUploadFolder; + break; + case SELECT_EXISTING_FOLDER: + mojo_type = SelectFileDialogType::kExistingFolder; + break; + case SELECT_OPEN_FILE: + mojo_type = SelectFileDialogType::kOpenFile; + break; + case SELECT_OPEN_MULTI_FILE: + mojo_type = SelectFileDialogType::kOpenMultiFile; + break; + case SELECT_SAVEAS_FILE: + mojo_type = SelectFileDialogType::kSaveAsFile; + break; + default: + NOTREACHED(); + break; } - if (type_ != SelectFileDialog::SELECT_FOLDER && - type_ != SelectFileDialog::SELECT_UPLOAD_FOLDER && - type_ != SelectFileDialog::SELECT_EXISTING_FOLDER) { - if (file_types) { - SetAccessoryView(file_types, file_type_index, default_extension); - } else { - // If no type_ info is specified, anything goes. - [dialog setAllowsOtherFileTypes:YES]; - } + SelectFileTypeInfoPtr mojo_file_types; + if (file_types) { + mojo_file_types = SelectFileTypeInfo::New(); + mojo_file_types->extensions = file_types->extensions; + mojo_file_types->extension_description_overrides = + file_types->extension_description_overrides; + mojo_file_types->include_all_files = file_types->include_all_files; } - if (type_ == SelectFileDialog::SELECT_SAVEAS_FILE) { - // When file extensions are hidden and removing the extension from - // the default filename gives one which still has an extension - // that OS X recognizes, it will get confused and think the user - // is trying to override the default extension. This happens with - // filenames like "foo.tar.gz" or "ball.of.tar.png". Work around - // this by never hiding extensions in that case. - base::FilePath::StringType penultimate_extension = - default_path.RemoveFinalExtension().FinalExtension(); - if (!penultimate_extension.empty()) { - [dialog setExtensionHidden:NO]; - } else { - [dialog setExtensionHidden:YES]; - [dialog setCanSelectHiddenExtension:YES]; - } - } else { - NSOpenPanel* open_dialog = base::mac::ObjCCastStrict<NSOpenPanel>(dialog); + auto callback = base::BindOnce(&SelectFileDialogImpl::FileWasSelected, + weak_factory_.GetWeakPtr(), &dialog_data, + type == SELECT_OPEN_MULTI_FILE); - if (type_ == SelectFileDialog::SELECT_OPEN_MULTI_FILE) - [open_dialog setAllowsMultipleSelection:YES]; - else - [open_dialog setAllowsMultipleSelection:NO]; - - if (type_ == SelectFileDialog::SELECT_FOLDER || - type_ == SelectFileDialog::SELECT_UPLOAD_FOLDER || - type_ == SelectFileDialog::SELECT_EXISTING_FOLDER) { - [open_dialog setCanChooseFiles:NO]; - [open_dialog setCanChooseDirectories:YES]; - - if (type_ == SelectFileDialog::SELECT_FOLDER) - [open_dialog setCanCreateDirectories:YES]; - else - [open_dialog setCanCreateDirectories:NO]; - - NSString* prompt = - (type_ == SelectFileDialog::SELECT_UPLOAD_FOLDER) - ? l10n_util::GetNSString(IDS_SELECT_UPLOAD_FOLDER_BUTTON_TITLE) - : l10n_util::GetNSString(IDS_SELECT_FOLDER_BUTTON_TITLE); - [open_dialog setPrompt:prompt]; - } else { - [open_dialog setCanChooseFiles:YES]; - [open_dialog setCanChooseDirectories:NO]; - } - - delegate_.reset([[SelectFileDialogDelegate alloc] init]); - [open_dialog setDelegate:delegate_.get()]; - } - if (default_dir) - [dialog setDirectoryURL:[NSURL fileURLWithPath:default_dir]]; - if (default_filename) - [dialog setNameFieldStringValue:default_filename]; - - // Ensure that |callback| (rather than |this|) be retained by the block. - auto callback = base::BindRepeating(&SavePanelBridge::OnPanelEnded, - weak_factory_.GetWeakPtr()); - [dialog beginSheetModalForWindow:owning_window - completionHandler:^(NSInteger result) { - callback.Run(result != NSFileHandlingPanelOKButton); - }]; + dialog_data.select_file_dialog->Show( + mojo_type, title, default_path, std::move(mojo_file_types), + file_type_index, default_extension, std::move(callback)); } SelectFileDialogImpl::DialogData::DialogData(gfx::NativeWindow parent_window_, @@ -342,98 +169,6 @@ dialog_data_list_.clear(); } -void SavePanelBridge::SetAccessoryView( - const FileTypeInfo* file_types, - int file_type_index, - const base::FilePath::StringType& default_extension) { - DCHECK(file_types); - base::scoped_nsobject<NSView> accessory_view = CreateAccessoryView(); - NSSavePanel* dialog = panel_.get(); - [dialog setAccessoryView:accessory_view.get()]; - - NSPopUpButton* popup = [accessory_view viewWithTag:kFileTypePopupTag]; - DCHECK(popup); - - // Create an array with each item corresponding to an array of different - // extensions in an extension group. - NSMutableArray* file_type_lists = [NSMutableArray array]; - int default_extension_index = -1; - for (size_t i = 0; i < file_types->extensions.size(); ++i) { - const std::vector<base::FilePath::StringType>& ext_list = - file_types->extensions[i]; - - // Generate type description for the extension group. - NSString* type_description = nil; - if (i < file_types->extension_description_overrides.size() && - !file_types->extension_description_overrides[i].empty()) { - type_description = base::SysUTF16ToNSString( - file_types->extension_description_overrides[i]); - } else { - // No description given for a list of extensions; pick the first one - // from the list (arbitrarily) and use its description. - DCHECK(!ext_list.empty()); - type_description = GetDescriptionFromExtension(ext_list[0]); - } - DCHECK_NE(0u, [type_description length]); - [popup addItemWithTitle:type_description]; - - // Populate file_type_lists. - // Set to store different extensions in the current extension group. - NSMutableSet* file_type_set = [NSMutableSet set]; - for (const base::FilePath::StringType& ext : ext_list) { - if (ext == default_extension) - default_extension_index = i; - - // Crash reports suggest that CreateUTIFromExtension may return nil. Hence - // we nil check before adding to |file_type_set|. See crbug.com/630101 and - // rdar://27490414. - base::ScopedCFTypeRef<CFStringRef> uti(CreateUTIFromExtension(ext)); - if (uti) - [file_type_set addObject:base::mac::CFToNSCast(uti.get())]; - - // Always allow the extension itself, in case the UTI doesn't map - // back to the original extension correctly. This occurs with dynamic - // UTIs on 10.7 and 10.8. - // See http://crbug.com/148840, http://openradar.me/12316273 - base::ScopedCFTypeRef<CFStringRef> ext_cf( - base::SysUTF8ToCFStringRef(ext)); - [file_type_set addObject:base::mac::CFToNSCast(ext_cf.get())]; - } - [file_type_lists addObject:[file_type_set allObjects]]; - } - - if (file_types->include_all_files || file_types->extensions.empty()) { - [popup addItemWithTitle:l10n_util::GetNSString(IDS_APP_SAVEAS_ALL_FILES)]; - [dialog setAllowsOtherFileTypes:YES]; - } - - extension_dropdown_handler_.reset([[ExtensionDropdownHandler alloc] - initWithDialog:dialog - fileTypeLists:file_type_lists]); - - // This establishes a weak reference to handler. Hence we persist it as part - // of dialog_data_list_. - [popup setTarget:extension_dropdown_handler_]; - [popup setAction:@selector(popupAction:)]; - - // file_type_index uses 1 based indexing. - if (file_type_index) { - DCHECK_LE(static_cast<size_t>(file_type_index), - file_types->extensions.size()); - DCHECK_GE(file_type_index, 1); - [popup selectItemAtIndex:file_type_index - 1]; - [extension_dropdown_handler_ popupAction:popup]; - } else if (!default_extension.empty() && default_extension_index != -1) { - [popup selectItemAtIndex:default_extension_index]; - [dialog - setAllowedFileTypes:@[ base::SysUTF8ToNSString(default_extension) ]]; - } else { - // Select the first item. - [popup selectItemAtIndex:0]; - [extension_dropdown_handler_ popupAction:popup]; - } -} - bool SelectFileDialogImpl::HasMultipleFileTypeChoicesImpl() { return hasMultipleFileTypeChoices_; } @@ -444,83 +179,4 @@ return new SelectFileDialogImpl(listener, std::move(policy)); } -void SavePanelBridge::OnPanelEnded(bool did_cancel) { - if (!callback_) - return; - - int index = 0; - std::vector<base::FilePath> paths; - if (!did_cancel) { - if (type_ == SelectFileDialog::SELECT_SAVEAS_FILE) { - if ([[panel_ URL] isFileURL]) { - paths.push_back(base::mac::NSStringToFilePath([[panel_ URL] path])); - } - - NSView* accessoryView = [panel_ accessoryView]; - if (accessoryView) { - NSPopUpButton* popup = [accessoryView viewWithTag:kFileTypePopupTag]; - if (popup) { - // File type indexes are 1-based. - index = [popup indexOfSelectedItem] + 1; - } - } else { - index = 1; - } - } else { - CHECK([panel_ isKindOfClass:[NSOpenPanel class]]); - NSArray* urls = [static_cast<NSOpenPanel*>(panel_) URLs]; - for (NSURL* url in urls) - if ([url isFileURL]) - paths.push_back(base::FilePath(base::SysNSStringToUTF8([url path]))); - } - } - - std::move(callback_).Run(did_cancel, paths, index); -} - } // namespace ui - -@implementation SelectFileDialogDelegate - -- (BOOL)panel:(id)sender shouldEnableURL:(NSURL *)url { - return [url isFileURL]; -} - -- (BOOL)panel:(id)sender validateURL:(NSURL*)url error:(NSError**)outError { - // Refuse to accept users closing the dialog with a key repeat, since the key - // may have been first pressed while the user was looking at insecure content. - // See https://crbug.com/637098. - if ([[NSApp currentEvent] type] == NSKeyDown && - [[NSApp currentEvent] isARepeat]) { - return NO; - } - - return YES; -} - -@end - -@implementation ExtensionDropdownHandler - -- (id)initWithDialog:(NSSavePanel*)dialog - fileTypeLists:(NSArray*)fileTypeLists { - if ((self = [super init])) { - dialog_ = dialog; - fileTypeLists_.reset([fileTypeLists retain]); - } - return self; -} - -- (void)popupAction:(id)sender { - NSUInteger index = [sender indexOfSelectedItem]; - if (index < [fileTypeLists_ count]) { - // For save dialogs, this causes the first item in the allowedFileTypes - // array to be used as the extension for the save panel. - [dialog_ setAllowedFileTypes:[fileTypeLists_ objectAtIndex:index]]; - } else { - // The user selected "All files" option. - [dialog_ setAllowedFileTypes:nil]; - } -} - -@end
diff --git a/ui/shell_dialogs/select_file_dialog_mac_unittest.mm b/ui/shell_dialogs/select_file_dialog_mac_unittest.mm index 8249888f..e3185db 100644 --- a/ui/shell_dialogs/select_file_dialog_mac_unittest.mm +++ b/ui/shell_dialogs/select_file_dialog_mac_unittest.mm
@@ -4,16 +4,17 @@ #import "ui/shell_dialogs/select_file_dialog_mac.h" -#include <vector> - #include "base/files/file_util.h" #import "base/mac/foundation_util.h" #include "base/mac/mac_util.h" #include "base/memory/ref_counted.h" +#include "base/run_loop.h" #include "base/stl_util.h" #include "base/strings/stringprintf.h" #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/scoped_task_environment.h" +#include "components/remote_cocoa/app_shim/select_file_dialog_bridge.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/shell_dialogs/select_file_policy.h" @@ -92,12 +93,15 @@ void* params) override {} protected: + base::test::ScopedTaskEnvironment task_environment_; + // Helper method to launch a dialog with the given |args|. void SelectFileWithParams(FileDialogArguments args) { dialog_->SelectFile(args.type, args.title, args.default_path, args.file_types, args.file_type_index, args.default_extension, args.owning_window, args.params); + base::RunLoop().RunUntilIdle(); } // Returns the number of panels currently active. @@ -105,16 +109,17 @@ return dialog_->dialog_data_list_.size(); } - // Returns one of the created NSSavePanel. If multiple SelectFile calls were - // made on the same |dialog_| object, any of the created NSSavePanel will be - // returned. + // Returns the most recently created NSSavePanel. NSSavePanel* GetPanel() const { DCHECK_GE(GetActivePanelCount(), 1lu); - return dialog_->dialog_data_list_.begin() - ->save_panel_bridge->GetNativePanelForTesting(); + return remote_cocoa::SelectFileDialogBridge:: + GetLastCreatedNativePanelForTesting(); } - void ResetDialog() { dialog_ = new SelectFileDialogImpl(this, nullptr); } + void ResetDialog() { + dialog_ = new SelectFileDialogImpl(this, nullptr); + base::RunLoop().RunUntilIdle(); + } private: scoped_refptr<SelectFileDialogImpl> dialog_; @@ -429,16 +434,18 @@ FileDialogArguments args(GetDefaultArguments()); SelectFileWithParams(args); + NSSavePanel* panel1 = GetPanel(); SelectFileWithParams(args); + NSSavePanel* panel2 = GetPanel(); EXPECT_EQ(2lu, GetActivePanelCount()); // Verify closing the panel decreases the panel count. - NSSavePanel* panel = GetPanel(); - [panel cancel:panel]; + [panel1 cancel:panel1]; + base::RunLoop().RunUntilIdle(); EXPECT_EQ(1lu, GetActivePanelCount()); - panel = GetPanel(); - [panel ok:panel]; + [panel2 ok:panel2]; + base::RunLoop().RunUntilIdle(); EXPECT_EQ(0lu, GetActivePanelCount()); }
diff --git a/url/mojom/url_gurl_mojom_traits_unittest.cc b/url/mojom/url_gurl_mojom_traits_unittest.cc index d0f50a0..1e44fc64 100644 --- a/url/mojom/url_gurl_mojom_traits_unittest.cc +++ b/url/mojom/url_gurl_mojom_traits_unittest.cc
@@ -5,8 +5,8 @@ #include <utility> #include "base/logging.h" -#include "base/message_loop/message_loop.h" #include "base/stl_util.h" +#include "base/test/scoped_task_environment.h" #include "mojo/public/cpp/bindings/binding.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/mojom/url_test.mojom.h" @@ -33,7 +33,7 @@ // Mojo version of chrome IPC test in url/ipc/url_param_traits_unittest.cc. TEST(MojoGURLStructTraitsTest, Basic) { - base::MessageLoop message_loop; + base::test::ScopedTaskEnvironment scoped_task_environment; mojom::UrlTestPtr proxy; UrlTestImpl impl(MakeRequest(&proxy));