diff --git a/DEPS b/DEPS index a09ff2c..59eaa14 100644 --- a/DEPS +++ b/DEPS
@@ -79,11 +79,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': '4125b6165d4314c6c64ce12d31b2565d52c6fad3', + 'skia_revision': 'ba7b7abda177c4b4ebcab0f32f18816495018062', # 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': '5c0ec61e5061683382c0d5953b1af43b4419f88b', + 'v8_revision': '09e7152ea60732cac61120982ae63b4630a1fb9f', # 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. @@ -91,7 +91,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': 'd429ac569e9772c25b16c09d6b90228064adf63b', + 'angle_revision': 'b2c60b1a195049ede3f3d28a81cb1ff35929f88b', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling build tools # and whatever else without interference from each other. @@ -103,7 +103,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. - 'pdfium_revision': '2e6405c333d8daae4e3edaa6b48f5ac5a8d7675b', + 'pdfium_revision': '765d1ebe41defa659a703a2f0ff5284c0da96a95', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling openmax_dl # and whatever else without interference from each other. @@ -320,7 +320,7 @@ # Build tools for Chrome OS. Note: This depends on third_party/pyelftools. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'b84994071091a2287443fa0d893a9450c926e48c', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '6ea47f17c992f586b1ca0ae632d11b2fef15d48c', 'condition': 'checkout_linux', }, @@ -345,7 +345,7 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '0b89935ad6fee0109212969cbaccdce822a7632c', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + 'ba51bb3c1274f5e8f7fef0ff6706d0e46e33864f', 'src/third_party/devtools-node-modules': Var('chromium_git') + '/external/github.com/ChromeDevTools/devtools-node-modules' + '@' + Var('devtools_node_modules_revision'), @@ -369,7 +369,7 @@ }, 'src/third_party/ffmpeg': - Var('chromium_git') + '/chromium/third_party/ffmpeg.git' + '@' + '02ec9ce5a9bc14a5e245fdfce30770d2e878bb24', + Var('chromium_git') + '/chromium/third_party/ffmpeg.git' + '@' + '5baad932589a94969782df630db02ec0293d920f', 'src/third_party/flac': Var('chromium_git') + '/chromium/deps/flac.git' + '@' + '7d0f5b3a173ffe98db08057d1f52b7787569e0a6', @@ -687,7 +687,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@ceb1b20c43132851bb4cd489b9c772e10e85e355', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@ca08cc1b0773392396de7e96cdcdc555149b6dcc', 'condition': 'checkout_src_internal', },
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index 9f40aad..7d49901 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -114,9 +114,8 @@ "display/ash_display_controller.h", "display/cursor_window_controller.cc", "display/cursor_window_controller.h", + "display/display_animator.cc", "display/display_animator.h", - "display/display_animator_chromeos.cc", - "display/display_animator_chromeos.h", "display/display_color_manager.cc", "display/display_color_manager.h", "display/display_configuration_controller.cc", @@ -1256,7 +1255,7 @@ "//ui/events", "//ui/gfx", "//ui/gfx/geometry", - "//ui/keyboard:keyboard_with_content", + "//ui/keyboard", "//ui/resources", "//ui/strings", "//ui/views",
diff --git a/ash/app_list/model/search/search_result.cc b/ash/app_list/model/search/search_result.cc index 14d1715ed..287e45d 100644 --- a/ash/app_list/model/search/search_result.cc +++ b/ash/app_list/model/search/search_result.cc
@@ -12,23 +12,6 @@ namespace app_list { -SearchResult::Action::Action(const gfx::ImageSkia& base_image, - const gfx::ImageSkia& hover_image, - const gfx::ImageSkia& pressed_image, - const base::string16& tooltip_text) - : base_image(base_image), - hover_image(hover_image), - pressed_image(pressed_image), - tooltip_text(tooltip_text) {} - -SearchResult::Action::Action(const base::string16& label_text, - const base::string16& tooltip_text) - : tooltip_text(tooltip_text), label_text(label_text) {} - -SearchResult::Action::Action(const Action& other) = default; - -SearchResult::Action::~Action() = default; - SearchResult::SearchResult() = default; SearchResult::~SearchResult() {
diff --git a/ash/app_list/model/search/search_result.h b/ash/app_list/model/search/search_result.h index fde39797..e8aa2fbb 100644 --- a/ash/app_list/model/search/search_result.h +++ b/ash/app_list/model/search/search_result.h
@@ -12,6 +12,7 @@ #include <vector> #include "ash/app_list/model/app_list_model_export.h" +#include "ash/public/cpp/app_list/app_list_types.h" #include "base/macros.h" #include "base/observer_list.h" #include "base/strings/string16.h" @@ -34,71 +35,12 @@ // default style. class APP_LIST_MODEL_EXPORT SearchResult { public: - // How the result should be displayed. Do not change the order of these as - // they are used for metrics. - enum DisplayType { - DISPLAY_NONE = 0, - DISPLAY_LIST, - DISPLAY_TILE, - DISPLAY_RECOMMENDATION, - DISPLAY_CARD, - // Add new values here. - - DISPLAY_TYPE_LAST, - }; - - // Type of the search result. This should be set in corresponding subclass's - // constructor. - enum ResultType { - RESULT_UNKNOWN, // Unknown type. - RESULT_INSTALLED_APP, // Installed apps. - RESULT_PLAYSTORE_APP, // Uninstalled apps from playstore. - RESULT_INSTANT_APP, // Instant apps. - // Add new values here. - }; - - // A tagged range in search result text. - struct APP_LIST_MODEL_EXPORT Tag { - // Similar to ACMatchClassification::Style, the style values are not - // mutually exclusive. - enum Style { - NONE = 0, - URL = 1 << 0, - MATCH = 1 << 1, - DIM = 1 << 2, - }; - - Tag(int styles, size_t start, size_t end) - : styles(styles), - range(static_cast<uint32_t>(start), static_cast<uint32_t>(end)) {} - - int styles; - gfx::Range range; - }; - typedef std::vector<Tag> Tags; - - // Data representing an action that can be performed on this search result. - // An action could be represented as an icon set or as a blue button with - // a label. Icon set is chosen if label text is empty. Otherwise, a blue - // button with the label text will be used. - struct APP_LIST_MODEL_EXPORT Action { - Action(const gfx::ImageSkia& base_image, - const gfx::ImageSkia& hover_image, - const gfx::ImageSkia& pressed_image, - const base::string16& tooltip_text); - Action(const base::string16& label_text, - const base::string16& tooltip_text); - Action(const Action& other); - ~Action(); - - gfx::ImageSkia base_image; - gfx::ImageSkia hover_image; - gfx::ImageSkia pressed_image; - - base::string16 tooltip_text; - base::string16 label_text; - }; - typedef std::vector<Action> Actions; + using ResultType = ash::SearchResultType; + using DisplayType = ash::SearchResultDisplayType; + using Tag = ash::SearchResultTag; + using Tags = ash::SearchResultTags; + using Action = ash::SearchResultAction; + using Actions = ash::SearchResultActions; SearchResult(); virtual ~SearchResult(); @@ -238,9 +180,9 @@ // duplicates. May be empty, in which case |id_| will be used for comparison. std::string comparable_id_; double relevance_ = 0; - DisplayType display_type_ = DISPLAY_LIST; + DisplayType display_type_ = ash::SearchResultDisplayType::kList; - ResultType result_type_ = RESULT_UNKNOWN; + ResultType result_type_ = ash::SearchResultType::kUnknown; // The Manhattan distance from the origin of all search results to this // result. This is logged for UMA.
diff --git a/ash/components/shortcut_viewer/keyboard_shortcut_viewer_metadata.cc b/ash/components/shortcut_viewer/keyboard_shortcut_viewer_metadata.cc index d4e8a74..826de80 100644 --- a/ash/components/shortcut_viewer/keyboard_shortcut_viewer_metadata.cc +++ b/ash/components/shortcut_viewer/keyboard_shortcut_viewer_metadata.cc
@@ -725,7 +725,7 @@ // |accelerator_ids| {}, // |shortcut_key_codes| - {ui::VKEY_LWIN, ui::VKEY_COMMAND, ui::VKEY_UNKNOWN, ui::VKEY_DOWN}}, + {ui::VKEY_LMENU, ui::VKEY_COMMAND, ui::VKEY_UNKNOWN, ui::VKEY_DOWN}}, {// |categories| {ShortcutCategory::kPageAndBrowser},
diff --git a/ash/content/shell_content_state.cc b/ash/content/shell_content_state.cc index bcdd817..7ce49db 100644 --- a/ash/content/shell_content_state.cc +++ b/ash/content/shell_content_state.cc
@@ -5,7 +5,7 @@ #include "ash/content/shell_content_state.h" #include "base/logging.h" -#include "ui/keyboard/content/keyboard.h" +#include "ui/keyboard/keyboard_resource_util.h" namespace ash { @@ -34,7 +34,7 @@ ShellContentState::ShellContentState() { // The keyboard system must be initialized before the RootWindowController is // created. - keyboard::InitializeKeyboard(); + keyboard::InitializeKeyboardResources(); } ShellContentState::~ShellContentState() = default;
diff --git a/ash/display/display_animator_chromeos.cc b/ash/display/display_animator.cc similarity index 91% rename from ash/display/display_animator_chromeos.cc rename to ash/display/display_animator.cc index 8c4ac26..9de3874 100644 --- a/ash/display/display_animator_chromeos.cc +++ b/ash/display/display_animator.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/display/display_animator_chromeos.h" +#include "ash/display/display_animator.h" #include <memory> @@ -94,16 +94,16 @@ } // namespace -DisplayAnimatorChromeOS::DisplayAnimatorChromeOS() : weak_ptr_factory_(this) { +DisplayAnimator::DisplayAnimator() : weak_ptr_factory_(this) { Shell::Get()->display_configurator()->AddObserver(this); } -DisplayAnimatorChromeOS::~DisplayAnimatorChromeOS() { +DisplayAnimator::~DisplayAnimator() { Shell::Get()->display_configurator()->RemoveObserver(this); ClearHidingLayers(); } -void DisplayAnimatorChromeOS::StartFadeOutAnimation(base::Closure callback) { +void DisplayAnimator::StartFadeOutAnimation(base::Closure callback) { CallbackRunningObserver* observer = new CallbackRunningObserver(callback); ClearHidingLayers(); @@ -138,17 +138,16 @@ timer_.reset(new base::OneShotTimer()); timer_->Start(FROM_HERE, base::TimeDelta::FromSeconds(kFadingTimeoutDurationInSeconds), - this, &DisplayAnimatorChromeOS::ClearHidingLayers); + this, &DisplayAnimator::ClearHidingLayers); } -void DisplayAnimatorChromeOS::StartFadeInAnimation() { +void DisplayAnimator::StartFadeInAnimation() { // We want to make sure clearing all of hiding layers after the animation // finished. Note that this callback can be canceled, but the cancel only // happens when the next animation is scheduled. Thus the hiding layers // should be deleted eventually. - CallbackRunningObserver* observer = new CallbackRunningObserver( - base::Bind(&DisplayAnimatorChromeOS::ClearHidingLayers, - weak_ptr_factory_.GetWeakPtr())); + CallbackRunningObserver* observer = new CallbackRunningObserver(base::Bind( + &DisplayAnimator::ClearHidingLayers, weak_ptr_factory_.GetWeakPtr())); // Ensure that layers are not animating. for (auto& e : hiding_layers_) { @@ -191,20 +190,20 @@ } } -void DisplayAnimatorChromeOS::OnDisplayModeChanged( +void DisplayAnimator::OnDisplayModeChanged( const display::DisplayConfigurator::DisplayStateList& displays) { if (!hiding_layers_.empty()) StartFadeInAnimation(); } -void DisplayAnimatorChromeOS::OnDisplayModeChangeFailed( +void DisplayAnimator::OnDisplayModeChangeFailed( const display::DisplayConfigurator::DisplayStateList& displays, display::MultipleDisplayState failed_new_state) { if (!hiding_layers_.empty()) StartFadeInAnimation(); } -void DisplayAnimatorChromeOS::ClearHidingLayers() { +void DisplayAnimator::ClearHidingLayers() { if (timer_) { timer_->Stop(); timer_.reset();
diff --git a/ash/display/display_animator.h b/ash/display/display_animator.h index 527b0f5..f32ddb82 100644 --- a/ash/display/display_animator.h +++ b/ash/display/display_animator.h
@@ -6,27 +6,57 @@ #define ASH_DISPLAY_DISPLAY_ANIMATOR_H_ #include <map> +#include <memory> #include "ash/ash_export.h" +#include "ash/display/display_animator.h" #include "base/callback.h" +#include "base/macros.h" +#include "base/memory/weak_ptr.h" +#include "base/timer/timer.h" +#include "ui/display/manager/chromeos/display_configurator.h" + +namespace aura { +class Window; +} // namespace aura + +namespace ui { +class Layer; +} // namespace ui namespace ash { -// Interface class for animating display changes. -class ASH_EXPORT DisplayAnimator { +// DisplayAnimator provides the visual effects for +// display::DisplayConfigurator, such like fade-out/in during changing +// the display mode. +class ASH_EXPORT DisplayAnimator + : public display::DisplayConfigurator::Observer { public: - virtual ~DisplayAnimator() {} + DisplayAnimator(); + ~DisplayAnimator() override; - // Starts the fade-out animation for the all root windows. It will - // call |callback| once all of the animations have finished. - virtual void StartFadeOutAnimation(base::Closure callback) = 0; + void StartFadeOutAnimation(base::Closure callback); + void StartFadeInAnimation(); - // Starts the animation to clear the fade-out animation effect - // for the all root windows. - virtual void StartFadeInAnimation() = 0; + protected: + // display::DisplayConfigurator::Observer overrides: + void OnDisplayModeChanged( + const display::DisplayConfigurator::DisplayStateList& outputs) override; + void OnDisplayModeChangeFailed( + const display::DisplayConfigurator::DisplayStateList& displays, + display::MultipleDisplayState failed_new_state) override; private: - DISALLOW_ASSIGN(DisplayAnimator); + // Clears all hiding layers. Note that in case that this method is called + // during an animation, the method call will cancel all of the animations + // and *not* call the registered callback. + void ClearHidingLayers(); + + std::map<aura::Window*, std::unique_ptr<ui::Layer>> hiding_layers_; + std::unique_ptr<base::OneShotTimer> timer_; + base::WeakPtrFactory<DisplayAnimator> weak_ptr_factory_; + + DISALLOW_COPY_AND_ASSIGN(DisplayAnimator); }; } // namespace ash
diff --git a/ash/display/display_animator_chromeos.h b/ash/display/display_animator_chromeos.h deleted file mode 100644 index 333d03d6..0000000 --- a/ash/display/display_animator_chromeos.h +++ /dev/null
@@ -1,66 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef ASH_DISPLAY_DISPLAY_ANIMATOR_CHROMEOS_H_ -#define ASH_DISPLAY_DISPLAY_ANIMATOR_CHROMEOS_H_ - -#include <map> -#include <memory> - -#include "ash/ash_export.h" -#include "ash/display/display_animator.h" -#include "base/callback.h" -#include "base/macros.h" -#include "base/memory/weak_ptr.h" -#include "base/timer/timer.h" -#include "ui/display/manager/chromeos/display_configurator.h" - -namespace aura { -class Window; -} // namespace aura - -namespace ui { -class Layer; -} // namespace ui - -namespace ash { - -// DisplayAnimatorChromeOS provides the visual effects for -// display::DisplayConfigurator, such like fade-out/in during changing -// the display mode. -class ASH_EXPORT DisplayAnimatorChromeOS - : public DisplayAnimator, - public display::DisplayConfigurator::Observer { - public: - DisplayAnimatorChromeOS(); - ~DisplayAnimatorChromeOS() override; - - // DisplayAnimator - void StartFadeOutAnimation(base::Closure callback) override; - void StartFadeInAnimation() override; - - protected: - // display::DisplayConfigurator::Observer overrides: - void OnDisplayModeChanged( - const display::DisplayConfigurator::DisplayStateList& outputs) override; - void OnDisplayModeChangeFailed( - const display::DisplayConfigurator::DisplayStateList& displays, - display::MultipleDisplayState failed_new_state) override; - - private: - // Clears all hiding layers. Note that in case that this method is called - // during an animation, the method call will cancel all of the animations - // and *not* call the registered callback. - void ClearHidingLayers(); - - std::map<aura::Window*, std::unique_ptr<ui::Layer>> hiding_layers_; - std::unique_ptr<base::OneShotTimer> timer_; - base::WeakPtrFactory<DisplayAnimatorChromeOS> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(DisplayAnimatorChromeOS); -}; - -} // namespace ash - -#endif // ASH_DISPLAY_DISPLAY_ANIMATOR_CHROMEOS_H_
diff --git a/ash/display/display_configuration_controller.cc b/ash/display/display_configuration_controller.cc index 8630140..3cb9f6b 100644 --- a/ash/display/display_configuration_controller.cc +++ b/ash/display/display_configuration_controller.cc
@@ -5,7 +5,6 @@ #include "ash/display/display_configuration_controller.h" #include "ash/display/display_animator.h" -#include "ash/display/display_animator_chromeos.h" #include "ash/display/display_util.h" #include "ash/display/window_tree_host_manager.h" #include "ash/rotator/screen_rotation_animator.h" @@ -68,7 +67,7 @@ window_tree_host_manager_->AddObserver(this); if (chromeos::IsRunningAsSystemCompositor()) limiter_.reset(new DisplayChangeLimiter); - display_animator_.reset(new DisplayAnimatorChromeOS()); + display_animator_.reset(new DisplayAnimator()); } DisplayConfigurationController::~DisplayConfigurationController() {
diff --git a/ash/public/cpp/BUILD.gn b/ash/public/cpp/BUILD.gn index 3b8e588b..3cb3527 100644 --- a/ash/public/cpp/BUILD.gn +++ b/ash/public/cpp/BUILD.gn
@@ -8,6 +8,7 @@ component("cpp") { sources = [ "accessibility_types.h", + "app_list/app_list_types.cc", "app_list/app_list_types.h", "app_list/term_break_iterator.cc", "app_list/term_break_iterator.h",
diff --git a/ash/public/cpp/app_list/app_list_struct_traits.cc b/ash/public/cpp/app_list/app_list_struct_traits.cc new file mode 100644 index 0000000..ba8972d --- /dev/null +++ b/ash/public/cpp/app_list/app_list_struct_traits.cc
@@ -0,0 +1,80 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ash/public/cpp/app_list/app_list_struct_traits.h" + +#include "mojo/public/cpp/base/string16_mojom_traits.h" +#include "ui/gfx/image/mojo/image_skia_struct_traits.h" +#include "ui/gfx/range/mojo/range_struct_traits.h" + +namespace mojo { + +//////////////////////////////////////////////////////////////////////////////// +// SearchResultTag: + +// static +bool StructTraits<ash::mojom::SearchResultTagDataView, ash::SearchResultTag>:: + Read(ash::mojom::SearchResultTagDataView data, ash::SearchResultTag* out) { + if (!data.ReadRange(&out->range)) + return false; + out->styles = data.styles(); + return true; +} + +//////////////////////////////////////////////////////////////////////////////// +// SearchResultActionLabel: + +// static +ash::mojom::SearchResultActionLabelDataView::Tag UnionTraits< + ash::mojom::SearchResultActionLabelDataView, + ash::SearchResultAction>::GetTag(const ash::SearchResultAction& action) { + if (action.label_text.empty()) + return ash::mojom::SearchResultActionLabelDataView::Tag::IMAGE_LABEL; + else + return ash::mojom::SearchResultActionLabelDataView::Tag::TEXT_LABEL; +} + +// static +bool UnionTraits<ash::mojom::SearchResultActionLabelDataView, + ash::SearchResultAction>:: + Read(ash::mojom::SearchResultActionLabelDataView data, + ash::SearchResultAction* out) { + switch (data.tag()) { + case ash::mojom::SearchResultActionLabelDataView::Tag::IMAGE_LABEL: { + ash::mojom::SearchResultActionImageLabelDataView image_label_data_view; + data.GetImageLabelDataView(&image_label_data_view); + if (!image_label_data_view.ReadBaseImage(&out->base_image)) + return false; + if (!image_label_data_view.ReadHoverImage(&out->hover_image)) + return false; + if (!image_label_data_view.ReadPressedImage(&out->pressed_image)) + return false; + return true; + } + case ash::mojom::SearchResultActionLabelDataView::Tag::TEXT_LABEL: { + if (!data.ReadTextLabel(&out->label_text)) + return false; + return true; + } + } + NOTREACHED(); + return false; +} + +//////////////////////////////////////////////////////////////////////////////// +// SearchResultAction: + +// static +bool StructTraits< + ash::mojom::SearchResultActionDataView, + ash::SearchResultAction>::Read(ash::mojom::SearchResultActionDataView data, + ash::SearchResultAction* out) { + if (!data.ReadTooltipText(&out->tooltip_text)) + return false; + if (!data.ReadLabel(out)) + return false; + return true; +} + +} // namespace mojo
diff --git a/ash/public/cpp/app_list/app_list_struct_traits.h b/ash/public/cpp/app_list/app_list_struct_traits.h index de33e17e..7d165685 100644 --- a/ash/public/cpp/app_list/app_list_struct_traits.h +++ b/ash/public/cpp/app_list/app_list_struct_traits.h
@@ -8,9 +8,13 @@ #include "ash/public/cpp/app_list/app_list_types.h" #include "ash/public/cpp/ash_public_export.h" #include "ash/public/interfaces/app_list.mojom-shared.h" +#include "base/strings/string16.h" namespace mojo { +//////////////////////////////////////////////////////////////////////////////// +// AppListState: + template <> struct EnumTraits<ash::mojom::AppListState, ash::AppListState> { static ash::mojom::AppListState ToMojom(ash::AppListState input) { @@ -47,6 +51,9 @@ } }; +//////////////////////////////////////////////////////////////////////////////// +// AppListModelStatus: + template <> struct EnumTraits<ash::mojom::AppListModelStatus, ash::AppListModelStatus> { static ash::mojom::AppListModelStatus ToMojom(ash::AppListModelStatus input) { @@ -75,6 +82,140 @@ } }; +//////////////////////////////////////////////////////////////////////////////// +// SearchResultType: + +template <> +struct EnumTraits<ash::mojom::SearchResultType, ash::SearchResultType> { + static ash::mojom::SearchResultType ToMojom(ash::SearchResultType input) { + switch (input) { + case ash::SearchResultType::kInstalledApp: + return ash::mojom::SearchResultType::kInstalledApp; + case ash::SearchResultType::kPlayStoreApp: + return ash::mojom::SearchResultType::kPlayStoreApp; + case ash::SearchResultType::kInstantApp: + return ash::mojom::SearchResultType::kInstantApp; + case ash::SearchResultType::kUnknown: + break; + } + NOTREACHED(); + return ash::mojom::SearchResultType::kInstalledApp; + } + + static bool FromMojom(ash::mojom::SearchResultType input, + ash::SearchResultType* out) { + switch (input) { + case ash::mojom::SearchResultType::kInstalledApp: + *out = ash::SearchResultType::kInstalledApp; + return true; + case ash::mojom::SearchResultType::kPlayStoreApp: + *out = ash::SearchResultType::kPlayStoreApp; + return true; + case ash::mojom::SearchResultType::kInstantApp: + *out = ash::SearchResultType::kInstantApp; + return true; + } + NOTREACHED(); + return false; + } +}; + +//////////////////////////////////////////////////////////////////////////////// +// SearchResultDisplayType: + +template <> +struct EnumTraits<ash::mojom::SearchResultDisplayType, + ash::SearchResultDisplayType> { + static ash::mojom::SearchResultDisplayType ToMojom( + ash::SearchResultDisplayType input) { + switch (input) { + case ash::SearchResultDisplayType::kNone: + return ash::mojom::SearchResultDisplayType::kNone; + case ash::SearchResultDisplayType::kList: + return ash::mojom::SearchResultDisplayType::kList; + case ash::SearchResultDisplayType::kTile: + return ash::mojom::SearchResultDisplayType::kTile; + case ash::SearchResultDisplayType::kRecommendation: + return ash::mojom::SearchResultDisplayType::kRecommendation; + case ash::SearchResultDisplayType::kCard: + return ash::mojom::SearchResultDisplayType::kCard; + case ash::SearchResultDisplayType::kLast: + break; + } + NOTREACHED(); + return ash::mojom::SearchResultDisplayType::kNone; + } + + static bool FromMojom(ash::mojom::SearchResultDisplayType input, + ash::SearchResultDisplayType* out) { + switch (input) { + case ash::mojom::SearchResultDisplayType::kNone: + *out = ash::SearchResultDisplayType::kNone; + return true; + case ash::mojom::SearchResultDisplayType::kList: + *out = ash::SearchResultDisplayType::kList; + return true; + case ash::mojom::SearchResultDisplayType::kTile: + *out = ash::SearchResultDisplayType::kTile; + return true; + case ash::mojom::SearchResultDisplayType::kRecommendation: + *out = ash::SearchResultDisplayType::kRecommendation; + return true; + case ash::mojom::SearchResultDisplayType::kCard: + *out = ash::SearchResultDisplayType::kCard; + return true; + } + NOTREACHED(); + return false; + } +}; + +//////////////////////////////////////////////////////////////////////////////// +// SearchResultTag: + +template <> +struct StructTraits<ash::mojom::SearchResultTagDataView, ash::SearchResultTag> { + static int styles(const ash::SearchResultTag& tag) { return tag.styles; } + static const gfx::Range& range(const ash::SearchResultTag& tag) { + return tag.range; + } + static bool Read(ash::mojom::SearchResultTagDataView data, + ash::SearchResultTag* out); +}; + +//////////////////////////////////////////////////////////////////////////////// +// SearchResultActionLabel: + +template <> +struct UnionTraits<ash::mojom::SearchResultActionLabelDataView, + ash::SearchResultAction> { + static ash::mojom::SearchResultActionLabelDataView::Tag GetTag( + const ash::SearchResultAction& action); + + static bool Read(ash::mojom::SearchResultActionLabelDataView data, + ash::SearchResultAction* out); +}; + +//////////////////////////////////////////////////////////////////////////////// +// SearchResultAction: + +template <> +struct StructTraits<ash::mojom::SearchResultActionDataView, + ash::SearchResultAction> { + static bool Read(ash::mojom::SearchResultActionDataView data, + ash::SearchResultAction* out); + + static const base::string16& tooltip_text( + const ash::SearchResultAction& action) { + return action.tooltip_text; + } + + static const ash::SearchResultAction& label( + const ash::SearchResultAction& action) { + return action; + } +}; + } // namespace mojo #endif // ASH_PUBLIC_CPP_APP_LIST_APP_LIST_STRUCT_TRAITS_H_
diff --git a/ash/public/cpp/app_list/app_list_types.cc b/ash/public/cpp/app_list/app_list_types.cc new file mode 100644 index 0000000..6db9acc --- /dev/null +++ b/ash/public/cpp/app_list/app_list_types.cc
@@ -0,0 +1,40 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ash/public/cpp/app_list/app_list_types.h" + +namespace ash { + +//////////////////////////////////////////////////////////////////////////////// +// SearchResultTag: + +SearchResultTag::SearchResultTag() = default; + +SearchResultTag::SearchResultTag(int styles, uint32_t start, uint32_t end) + : styles(styles), range(start, end) {} + +//////////////////////////////////////////////////////////////////////////////// +// SearchResultAction: + +SearchResultAction::SearchResultAction() {} + +SearchResultAction::SearchResultAction(const gfx::ImageSkia& base_image, + const gfx::ImageSkia& hover_image, + const gfx::ImageSkia& pressed_image, + const base::string16& tooltip_text) + : base_image(base_image), + hover_image(hover_image), + pressed_image(pressed_image), + tooltip_text(tooltip_text) {} + +SearchResultAction::SearchResultAction(const base::string16& label_text, + const base::string16& tooltip_text) + : tooltip_text(tooltip_text), label_text(label_text) {} + +SearchResultAction::SearchResultAction(const SearchResultAction& other) = + default; + +SearchResultAction::~SearchResultAction() = default; + +} // namespace ash
diff --git a/ash/public/cpp/app_list/app_list_types.h b/ash/public/cpp/app_list/app_list_types.h index 8919c57..43999c0 100644 --- a/ash/public/cpp/app_list/app_list_types.h +++ b/ash/public/cpp/app_list/app_list_types.h
@@ -5,13 +5,17 @@ #ifndef ASH_PUBLIC_CPP_APP_LIST_APP_LIST_TYPES_H_ #define ASH_PUBLIC_CPP_APP_LIST_APP_LIST_TYPES_H_ +#include <vector> + #include "ash/public/cpp/ash_public_export.h" +#include "ui/gfx/image/image_skia.h" +#include "ui/gfx/range/range.h" namespace ash { // All possible states of the app list. // Note: Do not change the order of these as they are used for metrics. -enum class ASH_PUBLIC_EXPORT AppListState { +enum class AppListState { kStateApps = 0, kStateSearchResults, kStateStart, @@ -23,11 +27,75 @@ }; // The status of the app list model. -enum class ASH_PUBLIC_EXPORT AppListModelStatus { +enum class AppListModelStatus { kStatusNormal, kStatusSyncing, // Syncing apps or installing synced apps. }; +// Type of the search result, which is set in Chrome. +enum class SearchResultType { + kUnknown, // Unknown type. Don't use over IPC + kInstalledApp, // Installed apps. + kPlayStoreApp, // Uninstalled apps from playstore. + kInstantApp, // Instant apps. + // Add new values here. +}; + +// How the result should be displayed. Do not change the order of these as +// they are used for metrics. +enum SearchResultDisplayType { + kNone = 0, + kList, + kTile, + kRecommendation, + kCard, + // Add new values here. + + kLast, // Don't use over IPC +}; + +// A tagged range in search result text. +struct ASH_PUBLIC_EXPORT SearchResultTag { + // Similar to ACMatchClassification::Style, the style values are not + // mutually exclusive. + enum Style { + NONE = 0, + URL = 1 << 0, + MATCH = 1 << 1, + DIM = 1 << 2, + }; + + SearchResultTag(); + SearchResultTag(int styles, uint32_t start, uint32_t end); + + int styles; + gfx::Range range; +}; +using SearchResultTags = std::vector<SearchResultTag>; + +// Data representing an action that can be performed on this search result. +// An action could be represented as an icon set or as a blue button with +// a label. Icon set is chosen if label text is empty. Otherwise, a blue +// button with the label text will be used. +struct ASH_PUBLIC_EXPORT SearchResultAction { + SearchResultAction(); + SearchResultAction(const gfx::ImageSkia& base_image, + const gfx::ImageSkia& hover_image, + const gfx::ImageSkia& pressed_image, + const base::string16& tooltip_text); + SearchResultAction(const base::string16& label_text, + const base::string16& tooltip_text); + SearchResultAction(const SearchResultAction& other); + ~SearchResultAction(); + + gfx::ImageSkia base_image; + gfx::ImageSkia hover_image; + gfx::ImageSkia pressed_image; + base::string16 tooltip_text; + base::string16 label_text; +}; +using SearchResultActions = std::vector<SearchResultAction>; + } // namespace ash #endif // ASH_PUBLIC_CPP_APP_LIST_APP_LIST_TYPES_H_
diff --git a/ash/public/interfaces/BUILD.gn b/ash/public/interfaces/BUILD.gn index e08fa45..78e5bbe 100644 --- a/ash/public/interfaces/BUILD.gn +++ b/ash/public/interfaces/BUILD.gn
@@ -68,6 +68,7 @@ "//ui/events/mojo:interfaces", "//ui/gfx/geometry/mojo", "//ui/gfx/image/mojo:interfaces", + "//ui/gfx/range/mojo", "//ui/message_center/public/mojo:mojo", "//url/mojom:url_mojom_gurl", ]
diff --git a/ash/public/interfaces/app_list.mojom b/ash/public/interfaces/app_list.mojom index 92726f48..7e951dcf 100644 --- a/ash/public/interfaces/app_list.mojom +++ b/ash/public/interfaces/app_list.mojom
@@ -9,6 +9,7 @@ import "mojo/public/mojom/base/string16.mojom"; import "ui/gfx/geometry/mojo/geometry.mojom"; import "ui/gfx/image/mojo/image.mojom"; +import "ui/gfx/range/mojo/range.mojom"; // A structure holding the common information of AppListItem and // ChromeAppListItem, which is sent between ash and chrome representing @@ -39,6 +40,51 @@ kStatusSyncing, // Syncing apps or installing synced apps. }; +// How the result should be displayed. Do not change the order of these as +// they are used for metrics. +enum SearchResultDisplayType { + kNone = 0, + kList, + kTile, + kRecommendation, + kCard, + // Add new values here. +}; + +// Type of the search result, which is set in Chrome. +enum SearchResultType { + kInstalledApp, // Installed apps. + kPlayStoreApp, // Uninstalled apps from playstore. + kInstantApp, // Instant apps. + // Add new values here. +}; + +// A tagged range in search result text. +struct SearchResultTag { + // Similar to ACMatchClassification::Style, the style values are not + // mutually exclusive. + int16 styles; + gfx.mojom.Range range; +}; + +// Data representing an action that can be performed on a search result. +// An action could be represented as an icon set or as a blue button with +// a label. Icon set is chosen if label text is empty. Otherwise, a blue +// button with the label text will be used. +struct SearchResultActionImageLabel { + gfx.mojom.ImageSkia base_image; + gfx.mojom.ImageSkia hover_image; + gfx.mojom.ImageSkia pressed_Image; +}; +union SearchResultActionLabel { + SearchResultActionImageLabel image_label; + mojo_base.mojom.String16 text_label; +}; +struct SearchResultAction { + mojo_base.mojom.String16 tooltip_text; + SearchResultActionLabel label; +}; + // The Chrome app list (aka Launcher), is the place where user can find and // organize all installed apps, or search for various types of information. //
diff --git a/ash/public/interfaces/app_list.typemap b/ash/public/interfaces/app_list.typemap index 6b66c5e1..66f8326e 100644 --- a/ash/public/interfaces/app_list.typemap +++ b/ash/public/interfaces/app_list.typemap
@@ -5,7 +5,17 @@ mojom = "//ash/public/interfaces/app_list.mojom" public_headers = [ "//ash/public/cpp/app_list/app_list_types.h" ] traits_headers = [ "//ash/public/cpp/app_list/app_list_struct_traits.h" ] +sources = [ + "//ash/public/cpp/app_list/app_list_struct_traits.cc", +] +deps = [ + "//ui/gfx/range/mojo:struct_traits", +] type_mappings = [ "ash.mojom.AppListState=ash::AppListState", "ash.mojom.AppListModelStatus=ash::AppListModelStatus", + "ash.mojom.SearchResultType=ash::SearchResultType", + "ash.mojom.SearchResultDisplayType=ash::SearchResultDisplayType", + "ash.mojom.SearchResultTag=ash::SearchResultTag", + "ash.mojom.SearchResultAction=ash::SearchResultAction", ]
diff --git a/base/BUILD.gn b/base/BUILD.gn index 6450041..f6f871e 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -3002,3 +3002,21 @@ "//base", ] } + +fuzzer_test("string_number_conversions_fuzzer") { + sources = [ + "strings/string_number_conversions_fuzzer.cc", + ] + deps = [ + "//base", + ] +} + +fuzzer_test("string_tokenizer_fuzzer") { + sources = [ + "strings/string_tokenizer_fuzzer.cc", + ] + deps = [ + "//base", + ] +}
diff --git a/testing/libfuzzer/fuzzers/string_to_int_fuzzer.cc b/base/strings/string_number_conversions_fuzzer.cc similarity index 61% rename from testing/libfuzzer/fuzzers/string_to_int_fuzzer.cc rename to base/strings/string_number_conversions_fuzzer.cc index 59aff298..2fed7de 100644 --- a/testing/libfuzzer/fuzzers/string_to_int_fuzzer.cc +++ b/base/strings/string_number_conversions_fuzzer.cc
@@ -27,6 +27,18 @@ size_t out_size; base::StringToSizeT(string_piece_input, &out_size); + // Test for StringPiece16 if size is even. + if (size % 2 == 0) { + base::StringPiece16 string_piece_input16( + reinterpret_cast<const base::char16*>(data), size / 2); + + base::StringToInt(string_piece_input16, &out_int); + base::StringToUint(string_piece_input16, &out_uint); + base::StringToInt64(string_piece_input16, &out_int64); + base::StringToUint64(string_piece_input16, &out_uint64); + base::StringToSizeT(string_piece_input16, &out_size); + } + double out_double; base::StringToDouble(string_input, &out_double); @@ -38,5 +50,18 @@ base::HexStringToBytes(string_piece_input, &out_bytes); base::HexEncode(data, size); + + // Convert the numbers back to strings. + base::NumberToString(out_int); + base::NumberToString16(out_int); + base::NumberToString(out_uint); + base::NumberToString16(out_uint); + base::NumberToString(out_int64); + base::NumberToString16(out_int64); + base::NumberToString(out_uint64); + base::NumberToString16(out_uint64); + base::NumberToString(out_double); + base::NumberToString16(out_double); + return 0; }
diff --git a/testing/libfuzzer/fuzzers/string_tokenizer_fuzzer.cc b/base/strings/string_tokenizer_fuzzer.cc similarity index 85% rename from testing/libfuzzer/fuzzers/string_tokenizer_fuzzer.cc rename to base/strings/string_tokenizer_fuzzer.cc index c41b8ae..00d6cb0 100644 --- a/testing/libfuzzer/fuzzers/string_tokenizer_fuzzer.cc +++ b/base/strings/string_tokenizer_fuzzer.cc
@@ -30,13 +30,10 @@ return 0; } - std::string pattern(reinterpret_cast<const char*>(data + 1), - pattern_size); + std::string pattern(reinterpret_cast<const char*>(data + 1), pattern_size); - std::string input( - reinterpret_cast<const char*>(data + 1 + pattern_size), - size - pattern_size - 1); - + std::string input(reinterpret_cast<const char*>(data + 1 + pattern_size), + size - pattern_size - 1); base::StringTokenizer t(input, pattern); GetAllTokens(t); @@ -49,7 +46,6 @@ t_options.set_options(base::StringTokenizer::RETURN_DELIMS); GetAllTokens(t_options); - base::StringTokenizer t_quote_and_options(input, pattern); t_quote_and_options.set_quote_chars("\""); t_quote_and_options.set_options(base::StringTokenizer::RETURN_DELIMS);
diff --git a/build/android/gyp/compile_resources.py b/build/android/gyp/compile_resources.py deleted file mode 100755 index 377d1143..0000000 --- a/build/android/gyp/compile_resources.py +++ /dev/null
@@ -1,561 +0,0 @@ -#!/usr/bin/env python -# -# 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. - -"""Compile Android resources into an intermediate APK. - -This can also generate an R.txt, and an .srcjar file containing the proper -final R.java class for all resource packages the APK depends on. - -This will crunch images with aapt2. -""" - -import argparse -import collections -import multiprocessing.pool -import os -import re -import shutil -import subprocess -import sys -import zipfile -from xml.etree import ElementTree - - -from util import build_utils -from util import resource_utils - -_SOURCE_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname( - __file__)))) -# Import jinja2 from third_party/jinja2 -sys.path.insert(1, os.path.join(_SOURCE_ROOT, 'third_party')) -from jinja2 import Template # pylint: disable=F0401 - -# A variation of this lists also exists in: -# //base/android/java/src/org/chromium/base/LocaleUtils.java -_CHROME_TO_ANDROID_LOCALE_MAP = { - 'en-GB': 'en-rGB', - 'en-US': 'en-rUS', - 'es-419': 'es-rUS', - 'fil': 'tl', - 'he': 'iw', - 'id': 'in', - 'pt-PT': 'pt-rPT', - 'pt-BR': 'pt-rBR', - 'yi': 'ji', - 'zh-CN': 'zh-rCN', - 'zh-TW': 'zh-rTW', -} - -# Pngs that we shouldn't convert to webp. Please add rationale when updating. -_PNG_WEBP_BLACKLIST_PATTERN = re.compile('|'.join([ - # Crashes on Galaxy S5 running L (https://crbug.com/807059). - r'.*star_gray\.png', - # Android requires pngs for 9-patch images. - r'.*\.9\.png', - # Daydream (*.dd) requires pngs for icon files. - r'.*\.dd\.png'])) - - -def _ParseArgs(args): - """Parses command line options. - - Returns: - An options object as from argparse.ArgumentParser.parse_args() - """ - parser, input_opts, output_opts = resource_utils.ResourceArgsParser() - - input_opts.add_argument('--android-manifest', required=True, - help='AndroidManifest.xml path') - - input_opts.add_argument( - '--shared-resources', - action='store_true', - help='Make all resources in R.java non-final and allow the resource IDs ' - 'to be reset to a different package index when the apk is loaded by ' - 'another application at runtime.') - - input_opts.add_argument( - '--shared-resources-whitelist', - help='An R.txt file acting as a whitelist for resources that should be ' - 'non-final and have their package ID changed at runtime in R.java. ' - 'Implies and overrides --shared-resources.') - - input_opts.add_argument('--support-zh-hk', action='store_true', - help='Use zh-rTW resources for zh-rHK.') - - input_opts.add_argument('--debuggable', - action='store_true', - help='Whether to add android:debuggable="true"') - - input_opts.add_argument('--version-code', help='Version code for apk.') - input_opts.add_argument('--version-name', help='Version name for apk.') - - input_opts.add_argument( - '--no-compress', - help='disables compression for the given comma-separated list of ' - 'extensions') - - input_opts.add_argument( - '--locale-whitelist', - default='[]', - help='GN list of languages to include. All other language configs will ' - 'be stripped out. List may include a combination of Android locales ' - 'or Chrome locales.') - - input_opts.add_argument('--exclude-xxxhdpi', action='store_true', - help='Do not include xxxhdpi drawables.') - - input_opts.add_argument( - '--xxxhdpi-whitelist', - default='[]', - help='GN list of globs that say which xxxhdpi images to include even ' - 'when --exclude-xxxhdpi is set.') - - input_opts.add_argument('--png-to-webp', action='store_true', - help='Convert png files to webp format.') - - input_opts.add_argument('--webp-binary', default='', - help='Path to the cwebp binary.') - - input_opts.add_argument('--no-xml-namespaces', - action='store_true', - help='Whether to strip xml namespaces from processed ' - 'xml resources') - - output_opts.add_argument('--apk-path', required=True, - help='Path to output (partial) apk.') - - output_opts.add_argument('--srcjar-out', - help='Path to srcjar to contain generated R.java.') - - output_opts.add_argument('--r-text-out', - help='Path to store the generated R.txt file.') - - output_opts.add_argument('--proguard-file', - help='Path to proguard.txt generated file') - - output_opts.add_argument( - '--proguard-file-main-dex', - help='Path to proguard.txt generated file for main dex') - - options = parser.parse_args(args) - - resource_utils.HandleCommonOptions(options) - - options.locale_whitelist = build_utils.ParseGnList(options.locale_whitelist) - options.xxxhdpi_whitelist = build_utils.ParseGnList(options.xxxhdpi_whitelist) - - return options - - -def _SortZip(original_path, sorted_path): - """Generate new zip archive by sorting all files in the original by name.""" - with zipfile.ZipFile(sorted_path, 'w') as sorted_zip, \ - zipfile.ZipFile(original_path, 'r') as original_zip: - for info in sorted(original_zip.infolist(), key=lambda i: i.filename): - sorted_zip.writestr(info, original_zip.read(info)) - - -def _DuplicateZhResources(resource_dirs): - """Duplicate Taiwanese resources into Hong-Kong specific directory.""" - for resource_dir in resource_dirs: - # We use zh-TW resources for zh-HK (if we have zh-TW resources). - for path in build_utils.IterFiles(resource_dir): - if 'zh-rTW' in path: - hk_path = path.replace('zh-rTW', 'zh-rHK') - build_utils.MakeDirectory(os.path.dirname(hk_path)) - shutil.copyfile(path, hk_path) - - -def _ToAaptLocales(locale_whitelist, support_zh_hk): - """Converts the list of Chrome locales to aapt config locales.""" - ret = set() - for locale in locale_whitelist: - locale = _CHROME_TO_ANDROID_LOCALE_MAP.get(locale, locale) - if locale is None or ('-' in locale and '-r' not in locale): - raise Exception('_CHROME_TO_ANDROID_LOCALE_MAP needs updating.' - ' Found: %s' % locale) - ret.add(locale) - # Always keep non-regional fall-backs. - language = locale.split('-')[0] - ret.add(language) - - # We don't actually support zh-HK in Chrome on Android, but we mimic the - # native side behavior where we use zh-TW resources when the locale is set to - # zh-HK. See https://crbug.com/780847. - if support_zh_hk: - assert not any('HK' in l for l in locale_whitelist), ( - 'Remove special logic if zh-HK is now supported (crbug.com/780847).') - ret.add('zh-rHK') - return sorted(ret) - - -def _MoveImagesToNonMdpiFolders(res_root): - """Move images from drawable-*-mdpi-* folders to drawable-* folders. - - Why? http://crbug.com/289843 - """ - for src_dir_name in os.listdir(res_root): - src_components = src_dir_name.split('-') - if src_components[0] != 'drawable' or 'mdpi' not in src_components: - continue - src_dir = os.path.join(res_root, src_dir_name) - if not os.path.isdir(src_dir): - continue - dst_components = [c for c in src_components if c != 'mdpi'] - assert dst_components != src_components - dst_dir_name = '-'.join(dst_components) - dst_dir = os.path.join(res_root, dst_dir_name) - build_utils.MakeDirectory(dst_dir) - for src_file_name in os.listdir(src_dir): - if not os.path.splitext(src_file_name)[1] in ('.png', '.webp'): - continue - src_file = os.path.join(src_dir, src_file_name) - dst_file = os.path.join(dst_dir, src_file_name) - assert not os.path.lexists(dst_file) - shutil.move(src_file, dst_file) - - -def _CreateLinkApkArgs(options): - """Create command-line arguments list to invoke 'aapt2 link'. - - Args: - options: The command-line options tuple. - Returns: - A list of strings corresponding to the command-line invokation for - the command, matching the arguments from |options|. - """ - link_command = [ - options.aapt_path + '2', - 'link', - '--version-code', options.version_code, - '--version-name', options.version_name, - '--auto-add-overlay', - '--no-version-vectors', - '-I', options.android_sdk_jar, - '-o', options.apk_path, - ] - - if options.proguard_file: - link_command += ['--proguard', options.proguard_file] - if options.proguard_file_main_dex: - link_command += ['--proguard-main-dex', options.proguard_file_main_dex] - - if options.no_compress: - for ext in options.no_compress.split(','): - link_command += ['-0', ext] - - if options.shared_resources: - link_command.append('--shared-lib') - - if options.locale_whitelist: - aapt_locales = _ToAaptLocales( - options.locale_whitelist, options.support_zh_hk) - link_command += ['-c', ','.join(aapt_locales)] - - if options.no_xml_namespaces: - link_command.append('--no-xml-namespaces') - - return link_command - - -def _ExtractVersionFromSdk(aapt_path, sdk_path): - """Extract version code and name from Android SDK .jar file. - - Args: - aapt_path: Path to 'aapt' build tool. - sdk_path: Path to SDK-specific android.jar file. - Returns: - A (version_code, version_name) pair of strings. - """ - output = subprocess.check_output([aapt_path, 'dump', 'badging', sdk_path]) - version_code = re.search(r"versionCode='(.*?)'", output).group(1) - version_name = re.search(r"versionName='(.*?)'", output).group(1) - return version_code, version_name, - - -def _FixManifest(options, temp_dir): - """Fix the APK's AndroidManifest.xml. - - This adds any missing namespaces for 'android' and 'tools', and - sets certains elements like 'platformBuildVersionCode' or - 'android:debuggable' depending on the content of |options|. - - Args: - options: The command-line arguments tuple. - temp_dir: A temporary directory where the fixed manifest will be written to. - Returns: - Path to the fixed manifest within |temp_dir|. - """ - debug_manifest_path = os.path.join(temp_dir, 'AndroidManifest.xml') - _ANDROID_NAMESPACE = 'http://schemas.android.com/apk/res/android' - _TOOLS_NAMESPACE = 'http://schemas.android.com/tools' - ElementTree.register_namespace('android', _ANDROID_NAMESPACE) - ElementTree.register_namespace('tools', _TOOLS_NAMESPACE) - original_manifest = ElementTree.parse(options.android_manifest) - - version_code, version_name = _ExtractVersionFromSdk( - options.aapt_path, options.android_sdk_jar) - - # ElementTree.find does not work if the required tag is the root. - if original_manifest.getroot().tag == 'manifest': - manifest_node = original_manifest.getroot() - else: - manifest_node = original_manifest.find('manifest') - - manifest_node.set('platformBuildVersionCode', version_code) - manifest_node.set('platformBuildVersionName', version_name) - - if options.debuggable: - app_node = original_manifest.find('application') - app_node.set('{%s}%s' % (_ANDROID_NAMESPACE, 'debuggable'), 'true') - - with open(debug_manifest_path, 'w') as debug_manifest: - debug_manifest.write(ElementTree.tostring( - original_manifest.getroot(), encoding='UTF-8')) - - return debug_manifest_path - - -def _ResourceNameFromPath(path): - return os.path.splitext(os.path.basename(path))[0] - - -def _CreateKeepPredicate(resource_dirs, exclude_xxxhdpi, xxxhdpi_whitelist): - """Return a predicate lambda to determine which resource files to keep.""" - if not exclude_xxxhdpi: - # Do not extract dotfiles (e.g. ".gitkeep"). aapt ignores them anyways. - return lambda path: os.path.basename(path)[0] != '.' - - # Returns False only for xxxhdpi non-mipmap, non-whitelisted drawables. - naive_predicate = lambda path: ( - not re.search(r'[/-]xxxhdpi[/-]', path) or - re.search(r'[/-]mipmap[/-]', path) or - build_utils.MatchesGlob(path, xxxhdpi_whitelist)) - - # Build a set of all non-xxxhdpi drawables to ensure that we never exclude any - # xxxhdpi drawable that does not exist in other densities. - non_xxxhdpi_drawables = set() - for resource_dir in resource_dirs: - for path in build_utils.IterFiles(resource_dir): - if re.search(r'[/-]drawable[/-]', path) and naive_predicate(path): - non_xxxhdpi_drawables.add(_ResourceNameFromPath(path)) - - return lambda path: (naive_predicate(path) or - _ResourceNameFromPath(path) not in non_xxxhdpi_drawables) - - -def _ConvertToWebP(webp_binary, png_files): - pool = multiprocessing.pool.ThreadPool(10) - def convert_image(png_path): - root = os.path.splitext(png_path)[0] - webp_path = root + '.webp' - args = [webp_binary, png_path, '-mt', '-quiet', '-m', '6', '-q', '100', - '-lossless', '-o', webp_path] - subprocess.check_call(args) - os.remove(png_path) - - pool.map(convert_image, [f for f in png_files - if not _PNG_WEBP_BLACKLIST_PATTERN.match(f)]) - pool.close() - pool.join() - - -def _CompileDeps(aapt_path, dep_subdirs, temp_dir): - partials_dir = os.path.join(temp_dir, 'partials') - build_utils.MakeDirectory(partials_dir) - partial_compile_command = [ - aapt_path + '2', - 'compile', - # TODO(wnwen): Turn this on once aapt2 forces 9-patch to be crunched. - # '--no-crunch', - ] - pool = multiprocessing.pool.ThreadPool(10) - def compile_partial(directory): - dirname = os.path.basename(directory) - partial_path = os.path.join(partials_dir, dirname + '.zip') - compile_command = (partial_compile_command + - ['--dir', directory, '-o', partial_path]) - build_utils.CheckOutput(compile_command) - - # Sorting the files in the partial ensures deterministic output from the - # aapt2 link step which uses order of files in the partial. - sorted_partial_path = os.path.join(partials_dir, dirname + '.sorted.zip') - _SortZip(partial_path, sorted_partial_path) - - return sorted_partial_path - - partials = pool.map(compile_partial, dep_subdirs) - pool.close() - pool.join() - return partials - - -def _PackageApk(options, dep_subdirs, temp_dir, gen_dir, r_txt_path): - """Compile resources with aapt2 and generate intermediate .ap_ file. - - Args: - options: The command-line options tuple. E.g. the generated apk - will be written to |options.apk_path|. - dep_subdirs: The list of directories where dependency resource zips - were extracted (its content will be altered by this function). - temp_dir: A temporary directory. - gen_dir: Another temp directory where some intermediate files are - generated. - r_txt_path: The path where the R.txt file will written to. - """ - _DuplicateZhResources(dep_subdirs) - - keep_predicate = _CreateKeepPredicate( - dep_subdirs, options.exclude_xxxhdpi, options.xxxhdpi_whitelist) - png_paths = [] - for directory in dep_subdirs: - for f in build_utils.IterFiles(directory): - if not keep_predicate(f): - os.remove(f) - elif f.endswith('.png'): - png_paths.append(f) - if png_paths and options.png_to_webp: - _ConvertToWebP(options.webp_binary, png_paths) - for directory in dep_subdirs: - _MoveImagesToNonMdpiFolders(directory) - - link_command = _CreateLinkApkArgs(options) - link_command += ['--output-text-symbols', r_txt_path] - # TODO(digit): Is this below actually required for R.txt generation? - link_command += ['--java', gen_dir] - - fixed_manifest = _FixManifest(options, temp_dir) - link_command += ['--manifest', fixed_manifest] - - partials = _CompileDeps(options.aapt_path, dep_subdirs, temp_dir) - for partial in partials: - link_command += ['-R', partial] - - # Creates a .zip with AndroidManifest.xml, resources.arsc, res/* - # Also creates R.txt - build_utils.CheckOutput( - link_command, print_stdout=False, print_stderr=False) - - -def _WriteFinalRTxtFile(options, aapt_r_txt_path): - """Determine final R.txt and return its location. - - This handles --r-text-in and --r-text-out options at the same time. - - Args: - options: The command-line options tuple. - aapt_r_txt_path: The path to the R.txt generated by aapt. - Returns: - Path to the final R.txt file. - """ - if options.r_text_in: - r_txt_file = options.r_text_in - else: - # When an empty res/ directory is passed, aapt does not write an R.txt. - r_txt_file = aapt_r_txt_path - if not os.path.exists(r_txt_file): - build_utils.Touch(r_txt_file) - - if options.r_text_out: - shutil.copyfile(r_txt_file, options.r_text_out) - - return r_txt_file - - -def _OnStaleMd5(options): - with resource_utils.BuildContext() as build: - dep_subdirs = resource_utils.ExtractDeps(options.dependencies_res_zips, - build.deps_dir) - - _PackageApk(options, dep_subdirs, build.temp_dir, build.gen_dir, - build.r_txt_path) - - r_txt_path = _WriteFinalRTxtFile(options, build.r_txt_path) - - package = resource_utils.ExtractPackageFromManifest( - options.android_manifest) - - # If --shared-resources-whitelist is used, the all resources listed in - # the corresponding R.txt file will be non-final, and an onResourcesLoaded() - # will be generated to adjust them at runtime. - # - # Otherwise, if --shared-resources is used, the all resources will be - # non-final, and an onResourcesLoaded() method will be generated too. - # - # Otherwise, all resources will be final, and no method will be generated. - # - rjava_build_options = resource_utils.RJavaBuildOptions() - if options.shared_resources_whitelist: - rjava_build_options.ExportSomeResources( - options.shared_resources_whitelist) - rjava_build_options.GenerateOnResourcesLoaded() - elif options.shared_resources: - rjava_build_options.ExportAllResources() - rjava_build_options.GenerateOnResourcesLoaded() - - resource_utils.CreateRJavaFiles( - build.srcjar_dir, package, r_txt_path, - options.extra_res_packages, - options.extra_r_text_files, - rjava_build_options) - - if options.srcjar_out: - build_utils.ZipDir(options.srcjar_out, build.srcjar_dir) - - -def main(args): - args = build_utils.ExpandFileArgs(args) - options = _ParseArgs(args) - - # Order of these must match order specified in GN so that the correct one - # appears first in the depfile. - possible_output_paths = [ - options.apk_path, - options.r_text_out, - options.srcjar_out, - options.proguard_file, - options.proguard_file_main_dex, - ] - output_paths = [x for x in possible_output_paths if x] - - # List python deps in input_strings rather than input_paths since the contents - # of them does not change what gets written to the depsfile. - input_strings = options.extra_res_packages + [ - options.shared_resources, - options.exclude_xxxhdpi, - options.xxxhdpi_whitelist, - str(options.debuggable), - str(options.png_to_webp), - str(options.support_zh_hk), - str(options.no_xml_namespaces), - ] - - input_strings.extend(_CreateLinkApkArgs(options)) - - possible_input_paths = [ - options.aapt_path, - options.android_manifest, - options.android_sdk_jar, - options.shared_resources_whitelist, - ] - input_paths = [x for x in possible_input_paths if x] - input_paths.extend(options.dependencies_res_zips) - input_paths.extend(options.extra_r_text_files) - - if options.webp_binary: - input_paths.append(options.webp_binary) - - build_utils.CallAndWriteDepfileIfStale( - lambda: _OnStaleMd5(options), - options, - input_paths=input_paths, - input_strings=input_strings, - output_paths=output_paths) - - -if __name__ == '__main__': - main(sys.argv[1:])
diff --git a/build/android/gyp/prepare_resources.py b/build/android/gyp/prepare_resources.py deleted file mode 100755 index fee7932..0000000 --- a/build/android/gyp/prepare_resources.py +++ /dev/null
@@ -1,285 +0,0 @@ -#!/usr/bin/env python -# -# 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. - -"""Process Android resource directories to generate .resources.zip, R.txt and -.srcjar files.""" - -import argparse -import collections -import os -import re -import shutil -import sys - -import generate_v14_compatible_resources - -from util import build_utils -from util import resource_utils - - -def _ParseArgs(args): - """Parses command line options. - - Returns: - An options object as from argparse.ArgumentParser.parse_args() - """ - parser, input_opts, output_opts = resource_utils.ResourceArgsParser() - - input_opts.add_argument('--resource-dirs', - default='[]', - help='A list of input directories containing resources ' - 'for this target.') - - input_opts.add_argument( - '--shared-resources', - action='store_true', - help='Make resources shareable by generating an onResourcesLoaded() ' - 'method in the R.java source file.') - - input_opts.add_argument('--custom-package', - help='Optional Java package for main R.java.') - - input_opts.add_argument( - '--android-manifest', - help='Optional AndroidManifest.xml path. Only used to extract a package ' - 'name for R.java if a --custom-package is not provided.') - - output_opts.add_argument( - '--resource-zip-out', - help='Path to a zip archive containing all resources from ' - '--resource-dirs, merged into a single directory tree. This will ' - 'also include auto-generated v14-compatible resources unless ' - '--v14-skip is used.') - - output_opts.add_argument('--srcjar-out', - help='Path to .srcjar to contain the generated R.java.') - - output_opts.add_argument('--r-text-out', - help='Path to store the generated R.txt file.') - - input_opts.add_argument( - '--v14-skip', - action="store_true", - help='Do not generate nor verify v14 resources.') - - options = parser.parse_args(args) - - resource_utils.HandleCommonOptions(options) - - options.resource_dirs = build_utils.ParseGnList(options.resource_dirs) - - return options - - -def _GenerateGlobs(pattern): - # This function processes the aapt ignore assets pattern into a list of globs - # to be used to exclude files on the python side. It removes the '!', which is - # used by aapt to mean 'not chatty' so it does not output if the file is - # ignored (we dont output anyways, so it is not required). This function does - # not handle the <dir> and <file> prefixes used by aapt and are assumed not to - # be included in the pattern string. - return pattern.replace('!', '').split(':') - - -def _ZipResources(resource_dirs, zip_path, ignore_pattern): - # Python zipfile does not provide a way to replace a file (it just writes - # another file with the same name). So, first collect all the files to put - # in the zip (with proper overriding), and then zip them. - # ignore_pattern is a string of ':' delimited list of globs used to ignore - # files that should not be part of the final resource zip. - files_to_zip = dict() - globs = _GenerateGlobs(ignore_pattern) - for d in resource_dirs: - for root, _, files in os.walk(d): - for f in files: - archive_path = f - parent_dir = os.path.relpath(root, d) - if parent_dir != '.': - archive_path = os.path.join(parent_dir, f) - path = os.path.join(root, f) - if build_utils.MatchesGlob(archive_path, globs): - continue - files_to_zip[archive_path] = path - build_utils.DoZip(files_to_zip.iteritems(), zip_path) - - -def _GenerateRTxt(options, dep_subdirs, gen_dir): - """Generate R.txt file. - - Args: - options: The command-line options tuple. - dep_subdirs: List of directories containing extracted dependency resources. - gen_dir: Locates where the aapt-generated files will go. In particular - the output file is always generated as |{gen_dir}/R.txt|. - """ - # NOTE: This uses aapt rather than aapt2 because 'aapt2 compile' does not - # support the --output-text-symbols option yet (https://crbug.com/820460). - package_command = [options.aapt_path, - 'package', - '-m', - '-M', resource_utils.EMPTY_ANDROID_MANIFEST_PATH, - '--no-crunch', - '--auto-add-overlay', - '--no-version-vectors', - '-I', options.android_sdk_jar, - '--output-text-symbols', gen_dir, - '-J', gen_dir, # Required for R.txt generation. - '--ignore-assets', build_utils.AAPT_IGNORE_PATTERN] - - # Adding all dependencies as sources is necessary for @type/foo references - # to symbols within dependencies to resolve. However, it has the side-effect - # that all Java symbols from dependencies are copied into the new R.java. - # E.g.: It enables an arguably incorrect usage of - # "mypackage.R.id.lib_symbol" where "libpackage.R.id.lib_symbol" would be - # more correct. This is just how Android works. - for d in dep_subdirs: - package_command += ['-S', d] - - for d in options.resource_dirs: - package_command += ['-S', d] - - # Only creates an R.txt - build_utils.CheckOutput( - package_command, print_stdout=False, print_stderr=False) - - -def _GenerateResourcesZip(output_resource_zip, input_resource_dirs, - v14_skip, temp_dir): - """Generate a .resources.zip file fron a list of input resource dirs. - - Args: - output_resource_zip: Path to the output .resources.zip file. - input_resource_dirs: A list of input resource directories. - v14_skip: If False, then v14-compatible resource will also be - generated in |{temp_dir}/v14| and added to the final zip. - temp_dir: Path to temporary directory. - """ - if not v14_skip: - # Generate v14-compatible resources in temp_dir. - v14_dir = os.path.join(temp_dir, 'v14') - build_utils.MakeDirectory(v14_dir) - - for resource_dir in input_resource_dirs: - generate_v14_compatible_resources.GenerateV14Resources( - resource_dir, - v14_dir) - - input_resource_dirs.append(v14_dir) - - _ZipResources(input_resource_dirs, output_resource_zip, - build_utils.AAPT_IGNORE_PATTERN) - - -def _OnStaleMd5(options): - with resource_utils.BuildContext() as build: - if options.r_text_in: - r_txt_path = options.r_text_in - else: - # Extract dependencies to resolve @foo/type references into - # dependent packages. - dep_subdirs = resource_utils.ExtractDeps(options.dependencies_res_zips, - build.deps_dir) - - _GenerateRTxt(options, dep_subdirs, build.gen_dir) - r_txt_path = build.r_txt_path - - # 'aapt' doesn't generate any R.txt file if res/ was empty. - if not os.path.exists(r_txt_path): - build_utils.Touch(r_txt_path) - - if options.r_text_out: - shutil.copyfile(r_txt_path, options.r_text_out) - - if options.srcjar_out: - package = options.custom_package - if not package and options.android_manifest: - package = resource_utils.ExtractPackageFromManifest( - options.android_manifest) - - # Don't create a .java file for the current resource target when no - # package name was provided (either by manifest or build rules). - if package: - # All resource IDs should be non-final here, but the - # onResourcesLoaded() method should only be generated if - # --shared-resources is used. - rjava_build_options = resource_utils.RJavaBuildOptions() - rjava_build_options.ExportAllResources() - rjava_build_options.ExportAllStyleables() - if options.shared_resources: - rjava_build_options.GenerateOnResourcesLoaded() - - resource_utils.CreateRJavaFiles( - build.srcjar_dir, package, r_txt_path, - options.extra_res_packages, - options.extra_r_text_files, - rjava_build_options) - - build_utils.ZipDir(options.srcjar_out, build.srcjar_dir) - - if options.resource_zip_out: - _GenerateResourcesZip(options.resource_zip_out, options.resource_dirs, - options.v14_skip, build.temp_dir) - - -def main(args): - args = build_utils.ExpandFileArgs(args) - options = _ParseArgs(args) - - # Order of these must match order specified in GN so that the correct one - # appears first in the depfile. - possible_output_paths = [ - options.resource_zip_out, - options.r_text_out, - options.srcjar_out, - ] - output_paths = [x for x in possible_output_paths if x] - - # List python deps in input_strings rather than input_paths since the contents - # of them does not change what gets written to the depsfile. - input_strings = options.extra_res_packages + [ - options.custom_package, - options.shared_resources, - options.v14_skip, - ] - - possible_input_paths = [ - options.aapt_path, - options.android_manifest, - options.android_sdk_jar, - ] - input_paths = [x for x in possible_input_paths if x] - input_paths.extend(options.dependencies_res_zips) - input_paths.extend(options.extra_r_text_files) - - # Resource files aren't explicitly listed in GN. Listing them in the depfile - # ensures the target will be marked stale when resource files are removed. - depfile_deps = [] - resource_names = [] - for resource_dir in options.resource_dirs: - for resource_file in build_utils.FindInDirectory(resource_dir, '*'): - # Don't list the empty .keep file in depfile. Since it doesn't end up - # included in the .zip, it can lead to -w 'dupbuild=err' ninja errors - # if ever moved. - if not resource_file.endswith(os.path.join('empty', '.keep')): - input_paths.append(resource_file) - depfile_deps.append(resource_file) - resource_names.append(os.path.relpath(resource_file, resource_dir)) - - # Resource filenames matter to the output, so add them to strings as well. - # This matters if a file is renamed but not changed (http://crbug.com/597126). - input_strings.extend(sorted(resource_names)) - - build_utils.CallAndWriteDepfileIfStale( - lambda: _OnStaleMd5(options), - options, - input_paths=input_paths, - input_strings=input_strings, - output_paths=output_paths, - depfile_deps=depfile_deps) - - -if __name__ == '__main__': - main(sys.argv[1:])
diff --git a/build/android/gyp/process_resources.py b/build/android/gyp/process_resources.py new file mode 100755 index 0000000..a038a60 --- /dev/null +++ b/build/android/gyp/process_resources.py
@@ -0,0 +1,884 @@ +#!/usr/bin/env python +# +# 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. + +"""Process Android resources to generate R.java, and prepare for packaging. + +This will crunch images with aapt2 and generate v14 compatible resources +(see generate_v14_compatible_resources.py). +""" + +import codecs +import collections +import multiprocessing.pool +import optparse +import os +import re +import shutil +import subprocess +import sys +import zipfile +from xml.etree import ElementTree + + +import generate_v14_compatible_resources + +from util import build_utils + +_SOURCE_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname( + __file__)))) +# Import jinja2 from third_party/jinja2 +sys.path.insert(1, os.path.join(_SOURCE_ROOT, 'third_party')) +from jinja2 import Template # pylint: disable=F0401 + + +_EMPTY_ANDROID_MANIFEST_PATH = os.path.join( + _SOURCE_ROOT, 'build', 'android', 'AndroidManifest.xml') + + +# Represents a line from a R.txt file. +TextSymbolsEntry = collections.namedtuple('RTextEntry', + ('java_type', 'resource_type', 'name', 'value')) + + +# A variation of this lists also exists in: +# //base/android/java/src/org/chromium/base/LocaleUtils.java +_CHROME_TO_ANDROID_LOCALE_MAP = { + 'en-GB': 'en-rGB', + 'en-US': 'en-rUS', + 'es-419': 'es-rUS', + 'fil': 'tl', + 'he': 'iw', + 'id': 'in', + 'pt-PT': 'pt-rPT', + 'pt-BR': 'pt-rBR', + 'yi': 'ji', + 'zh-CN': 'zh-rCN', + 'zh-TW': 'zh-rTW', +} + +# Pngs that we shouldn't convert to webp. Please add rationale when updating. +_PNG_WEBP_BLACKLIST_PATTERN = re.compile('|'.join([ + # Crashes on Galaxy S5 running L (https://crbug.com/807059). + r'.*star_gray\.png', + # Android requires pngs for 9-patch images. + r'.*\.9\.png', + # Daydream (*.dd) requires pngs for icon files. + r'.*\.dd\.png'])) + + +class _ResourceWhitelist(object): + def __init__(self, entries=None): + self._entries = None + if entries: + self._entries = set(self._Key(x) for x in entries) + + def __contains__(self, entry): + return self._entries is None or self._Key(entry) in self._entries + + @staticmethod + def _Key(entry): + # Whitelists should only care about the name of the resource rather than the + # resource ID (since the whitelist is from another compilation unit, the + # resource IDs may not match). + return (entry.java_type, entry.resource_type, entry.name) + + +def _ParseArgs(args): + """Parses command line options. + + Returns: + An options object as from optparse.OptionsParser.parse_args() + """ + parser = optparse.OptionParser() + build_utils.AddDepfileOption(parser) + + parser.add_option('--android-sdk-jar', + help='the path to android jar file.') + parser.add_option('--aapt-path', + help='path to the Android aapt tool') + parser.add_option('--non-constant-id', action='store_true') + + parser.add_option('--android-manifest', help='AndroidManifest.xml path') + parser.add_option('--custom-package', help='Java package for R.java') + parser.add_option( + '--shared-resources', + action='store_true', + help='Make a resource package that can be loaded by a different' + 'application at runtime to access the package\'s resources.') + parser.add_option( + '--app-as-shared-lib', + action='store_true', + help='Make a resource package that can be loaded as shared library.') + parser.add_option( + '--shared-resources-whitelist', + help='An R.txt file acting as a whitelist for resources that should be ' + 'non-final and have their package ID changed at runtime in R.java. If no ' + 'whitelist is provided, then everything is whitelisted.') + + parser.add_option('--resource-dirs', + default='[]', + help='Directories containing resources of this target.') + parser.add_option('--dependencies-res-zips', + help='Resources from dependents.') + + parser.add_option('--resource-zip-out', + help='Path for output zipped resources.') + + parser.add_option('--srcjar-out', + help='Path to srcjar to contain generated R.java.') + parser.add_option('--r-text-out', + help='Path to store the generated R.txt file.') + parser.add_option('--r-text-in', + help='Path to pre-existing R.txt for these resources. ' + 'Resource names from it will be used to generate R.java ' + 'instead of aapt-generated R.txt.') + + parser.add_option('--proguard-file', + help='Path to proguard.txt generated file') + parser.add_option('--proguard-file-main-dex', + help='Path to proguard.txt generated file for main dex') + + parser.add_option( + '--v14-skip', + action="store_true", + help='Do not generate nor verify v14 resources') + + parser.add_option( + '--extra-res-packages', + help='Additional package names to generate R.java files for') + parser.add_option( + '--extra-r-text-files', + help='For each additional package, the R.txt file should contain a ' + 'list of resources to be included in the R.java file in the format ' + 'generated by aapt') + + parser.add_option('--support-zh-hk', action='store_true', + help='Use zh-rTW resources for zh-rHK.') + + parser.add_option('--stamp', help='File to touch on success') + + parser.add_option('--debuggable', + action='store_true', + help='Whether to add android:debuggable="true"') + parser.add_option('--version-code', help='Version code for apk.') + parser.add_option('--version-name', help='Version name for apk.') + parser.add_option('--no-compress', help='disables compression for the ' + 'given comma separated list of extensions') + parser.add_option('--locale-whitelist', + default='[]', + help='GN list of languages to include. All other language ' + 'configs will be stripped out. List may include ' + 'a combination of Android locales or Chrome locales.') + parser.add_option('--apk-path', + help='Path to output (partial) apk.') + parser.add_option('--exclude-xxxhdpi', action='store_true', + help='Do not include xxxhdpi drawables.') + parser.add_option('--xxxhdpi-whitelist', + default='[]', + help='GN list of globs that say which xxxhdpi images to ' + 'include even when --exclude-xxxhdpi is set.') + parser.add_option('--png-to-webp', action='store_true', + help='Convert png files to webp format.') + parser.add_option('--webp-binary', default='', + help='Path to the cwebp binary.') + parser.add_option('--no-xml-namespaces', + action='store_true', + help='Whether to strip xml namespaces from processed xml ' + 'resources') + + options, positional_args = parser.parse_args(args) + + if positional_args: + parser.error('No positional arguments should be given.') + + # Check that required options have been provided. + required_options = ( + 'android_sdk_jar', + 'aapt_path', + 'dependencies_res_zips', + ) + build_utils.CheckOptions(options, parser, required=required_options) + + options.resource_dirs = build_utils.ParseGnList(options.resource_dirs) + options.dependencies_res_zips = ( + build_utils.ParseGnList(options.dependencies_res_zips)) + + options.locale_whitelist = build_utils.ParseGnList(options.locale_whitelist) + options.xxxhdpi_whitelist = build_utils.ParseGnList(options.xxxhdpi_whitelist) + + # Don't use [] as default value since some script explicitly pass "". + if options.extra_res_packages: + options.extra_res_packages = ( + build_utils.ParseGnList(options.extra_res_packages)) + else: + options.extra_res_packages = [] + + if options.extra_r_text_files: + options.extra_r_text_files = ( + build_utils.ParseGnList(options.extra_r_text_files)) + else: + options.extra_r_text_files = [] + + return options + + +def _CreateRJavaFiles(srcjar_dir, main_r_txt_file, packages, r_txt_files, + shared_resources, non_constant_id, whitelist_r_txt_file, is_apk): + assert len(packages) == len(r_txt_files), 'Need one R.txt file per package' + + # Map of (resource_type, name) -> Entry. + # Contains the correct values for resources. + all_resources = {} + for entry in _ParseTextSymbolsFile(main_r_txt_file): + entry = entry._replace(value=_FixPackageIds(entry.value)) + all_resources[(entry.resource_type, entry.name)] = entry + + if whitelist_r_txt_file: + whitelisted_resources = _ResourceWhitelist( + _ParseTextSymbolsFile(whitelist_r_txt_file)) + else: + whitelisted_resources = _ResourceWhitelist() + + # Map of package_name->resource_type->entry + resources_by_package = ( + collections.defaultdict(lambda: collections.defaultdict(list))) + # Build the R.java files using each package's R.txt file, but replacing + # each entry's placeholder value with correct values from all_resources. + for package, r_txt_file in zip(packages, r_txt_files): + if package in resources_by_package: + raise Exception(('Package name "%s" appeared twice. All ' + 'android_resources() targets must use unique package ' + 'names, or no package name at all.') % package) + resources_by_type = resources_by_package[package] + # The sub-R.txt files have the wrong values at this point. Read them to + # figure out which entries belong to them, but use the values from the + # main R.txt file. + for entry in _ParseTextSymbolsFile(r_txt_file): + entry = all_resources.get((entry.resource_type, entry.name)) + # For most cases missing entry here is an error. It means that some + # library claims to have or depend on a resource that isn't included into + # the APK. There is one notable exception: Google Play Services (GMS). + # GMS is shipped as a bunch of AARs. One of them - basement - contains + # R.txt with ids of all resources, but most of the resources are in the + # other AARs. However, all other AARs reference their resources via + # basement's R.java so the latter must contain all ids that are in its + # R.txt. Most targets depend on only a subset of GMS AARs so some + # resources are missing, which is okay because the code that references + # them is missing too. We can't get an id for a resource that isn't here + # so the only solution is to skip the resource entry entirely. + # + # We can verify that all entries referenced in the code were generated + # correctly by running Proguard on the APK: it will report missing + # fields. + if entry: + resources_by_type[entry.resource_type].append(entry) + + for package, resources_by_type in resources_by_package.iteritems(): + package_r_java_dir = os.path.join(srcjar_dir, *package.split('.')) + build_utils.MakeDirectory(package_r_java_dir) + package_r_java_path = os.path.join(package_r_java_dir, 'R.java') + java_file_contents = _CreateRJavaFile(package, resources_by_type, + shared_resources, non_constant_id, whitelisted_resources, is_apk) + with open(package_r_java_path, 'w') as f: + f.write(java_file_contents) + + +def _ParseTextSymbolsFile(path): + """Given an R.txt file, returns a list of TextSymbolsEntry.""" + ret = [] + with open(path) as f: + for line in f: + m = re.match(r'(int(?:\[\])?) (\w+) (\w+) (.+)$', line) + if not m: + raise Exception('Unexpected line in R.txt: %s' % line) + java_type, resource_type, name, value = m.groups() + ret.append(TextSymbolsEntry(java_type, resource_type, name, value)) + return ret + + +def _FixPackageIds(resource_value): + # Resource IDs for resources belonging to regular APKs have their first byte + # as 0x7f (package id). However with webview, since it is not a regular apk + # but used as a shared library, aapt is passed the --shared-resources flag + # which changes some of the package ids to 0x02 and 0x00. This function just + # normalises all package ids to 0x7f, which the generated code in R.java + # changes to the correct package id at runtime. + # resource_value is a string with either, a single value '0x12345678', or an + # array of values like '{ 0xfedcba98, 0x01234567, 0x56789abc }' + return re.sub(r'0x(?!01)\d\d', r'0x7f', resource_value) + + +def _CreateRJavaFile(package, resources_by_type, shared_resources, + non_constant_id, whitelisted_resources, is_apk): + """Generates the contents of a R.java file.""" + final_resources_by_type = collections.defaultdict(list) + non_final_resources_by_type = collections.defaultdict(list) + if shared_resources or non_constant_id: + for res_type, resources in resources_by_type.iteritems(): + for entry in resources: + # Entries in stylable that are not int[] are not actually resource ids + # but constants. If we are creating an apk there is no reason for them + # to be non-final. However for libraries, they may be clobbered later on + # and thus should remain non-final. This is regardless of the + # whitelisting rules (since they are not actually resources). + if entry.resource_type == 'styleable' and entry.java_type != 'int[]': + if is_apk: + final_resources_by_type[res_type].append(entry) + else: + non_final_resources_by_type[res_type].append(entry) + elif entry in whitelisted_resources: + non_final_resources_by_type[res_type].append(entry) + else: + final_resources_by_type[res_type].append(entry) + else: + final_resources_by_type = resources_by_type + + # Keep these assignments all on one line to make diffing against regular + # aapt-generated files easier. + create_id = ('{{ e.resource_type }}.{{ e.name }} ^= packageIdTransform;') + # Here we diverge from what aapt does. Because we have so many + # resources, the onResourcesLoaded method was exceeding the 64KB limit that + # Java imposes. For this reason we split onResourcesLoaded into different + # methods for each resource type. + template = Template("""/* AUTO-GENERATED FILE. DO NOT MODIFY. */ + +package {{ package }}; + +public final class R { + private static boolean sResourcesDidLoad; + {% for resource_type in resource_types %} + public static final class {{ resource_type }} { + {% for e in final_resources[resource_type] %} + public static final {{ e.java_type }} {{ e.name }} = {{ e.value }}; + {% endfor %} + {% for e in non_final_resources[resource_type] %} + public static {{ e.java_type }} {{ e.name }} = {{ e.value }}; + {% endfor %} + } + {% endfor %} + {% if shared_resources %} + public static void transfromArray(int[] array, int packageIdTransform) { + for (int i=0; i < array.length; i++) { + if ((array[i] >>> 24) == 0x7f) { + array[i] ^= packageIdTransform; + } + } + } + public static void onResourcesLoaded(int packageId) { + assert !sResourcesDidLoad; + sResourcesDidLoad = true; + int packageIdTransform = (packageId ^ 0x7f) << 24; + {% for resource_type in resource_types %} + onResourcesLoaded{{ resource_type|title }}(packageIdTransform); + {% for e in non_final_resources[resource_type] %} + {% if e.java_type == 'int[]' %} + transfromArray({{ e.resource_type }}.{{ e.name }}, packageIdTransform); + {% endif %} + {% endfor %} + {% endfor %} + } + {% for res_type in resource_types %} + private static void onResourcesLoaded{{ res_type|title }} ( + int packageIdTransform) { + {% for e in non_final_resources[res_type] %} + {% if res_type != 'styleable' and e.java_type != 'int[]' %} + """ + create_id + """ + {% endif %} + {% endfor %} + } + {% endfor %} + {% endif %} +} +""", trim_blocks=True, lstrip_blocks=True) + + return template.render(package=package, + resource_types=sorted(resources_by_type), + shared_resources=shared_resources, + final_resources=final_resources_by_type, + non_final_resources=non_final_resources_by_type) + + +def _GenerateGlobs(pattern): + # This function processes the aapt ignore assets pattern into a list of globs + # to be used to exclude files on the python side. It removes the '!', which is + # used by aapt to mean 'not chatty' so it does not output if the file is + # ignored (we dont output anyways, so it is not required). This function does + # not handle the <dir> and <file> prefixes used by aapt and are assumed not to + # be included in the pattern string. + return pattern.replace('!', '').split(':') + + +def _ZipResources(resource_dirs, zip_path, ignore_pattern): + # Python zipfile does not provide a way to replace a file (it just writes + # another file with the same name). So, first collect all the files to put + # in the zip (with proper overriding), and then zip them. + # ignore_pattern is a string of ':' delimited list of globs used to ignore + # files that should not be part of the final resource zip. + files_to_zip = dict() + globs = _GenerateGlobs(ignore_pattern) + for d in resource_dirs: + for root, _, files in os.walk(d): + for f in files: + archive_path = f + parent_dir = os.path.relpath(root, d) + if parent_dir != '.': + archive_path = os.path.join(parent_dir, f) + path = os.path.join(root, f) + if build_utils.MatchesGlob(archive_path, globs): + continue + files_to_zip[archive_path] = path + build_utils.DoZip(files_to_zip.iteritems(), zip_path) + +def _SortZip(original_path, sorted_path): + with zipfile.ZipFile(sorted_path, 'w') as sorted_zip, \ + zipfile.ZipFile(original_path, 'r') as original_zip: + for info in sorted(original_zip.infolist(), key=lambda i: i.filename): + sorted_zip.writestr(info, original_zip.read(info)) + + + +def _DuplicateZhResources(resource_dirs): + for resource_dir in resource_dirs: + # We use zh-TW resources for zh-HK (if we have zh-TW resources). + for path in build_utils.IterFiles(resource_dir): + if 'zh-rTW' in path: + hk_path = path.replace('zh-rTW', 'zh-rHK') + build_utils.MakeDirectory(os.path.dirname(hk_path)) + shutil.copyfile(path, hk_path) + +def _ExtractPackageFromManifest(manifest_path): + doc = ElementTree.parse(manifest_path) + return doc.getroot().get('package') + + +def _ToAaptLocales(locale_whitelist, support_zh_hk): + """Converts the list of Chrome locales to aapt config locales.""" + ret = set() + for locale in locale_whitelist: + locale = _CHROME_TO_ANDROID_LOCALE_MAP.get(locale, locale) + if locale is None or ('-' in locale and '-r' not in locale): + raise Exception('_CHROME_TO_ANDROID_LOCALE_MAP needs updating.' + ' Found: %s' % locale) + ret.add(locale) + # Always keep non-regional fall-backs. + language = locale.split('-')[0] + ret.add(language) + + # We don't actually support zh-HK in Chrome on Android, but we mimic the + # native side behavior where we use zh-TW resources when the locale is set to + # zh-HK. See https://crbug.com/780847. + if support_zh_hk: + assert not any('HK' in l for l in locale_whitelist), ( + 'Remove special logic if zh-HK is now supported (crbug.com/780847).') + ret.add('zh-rHK') + return sorted(ret) + + +def _MoveImagesToNonMdpiFolders(res_root): + """Move images from drawable-*-mdpi-* folders to drawable-* folders. + + Why? http://crbug.com/289843 + """ + for src_dir_name in os.listdir(res_root): + src_components = src_dir_name.split('-') + if src_components[0] != 'drawable' or 'mdpi' not in src_components: + continue + src_dir = os.path.join(res_root, src_dir_name) + if not os.path.isdir(src_dir): + continue + dst_components = [c for c in src_components if c != 'mdpi'] + assert dst_components != src_components + dst_dir_name = '-'.join(dst_components) + dst_dir = os.path.join(res_root, dst_dir_name) + build_utils.MakeDirectory(dst_dir) + for src_file_name in os.listdir(src_dir): + if not os.path.splitext(src_file_name)[1] in ('.png', '.webp'): + continue + src_file = os.path.join(src_dir, src_file_name) + dst_file = os.path.join(dst_dir, src_file_name) + assert not os.path.lexists(dst_file) + shutil.move(src_file, dst_file) + + +def _CreateLinkApkArgs(options): + link_command = [ + options.aapt_path + '2', + 'link', + '--version-code', options.version_code, + '--version-name', options.version_name, + '--auto-add-overlay', + '--no-version-vectors', + '-I', options.android_sdk_jar, + '-o', options.apk_path, + ] + + if options.proguard_file: + link_command += ['--proguard', options.proguard_file] + if options.proguard_file_main_dex: + link_command += ['--proguard-main-dex', options.proguard_file_main_dex] + + if options.no_compress: + for ext in options.no_compress.split(','): + link_command += ['-0', ext] + + if options.shared_resources: + link_command.append('--shared-lib') + + if options.locale_whitelist: + aapt_locales = _ToAaptLocales( + options.locale_whitelist, options.support_zh_hk) + link_command += ['-c', ','.join(aapt_locales)] + + if options.no_xml_namespaces: + link_command.append('--no-xml-namespaces') + + return link_command + + +def _ExtractVersionFromSdk(aapt_path, sdk_path): + output = subprocess.check_output([aapt_path, 'dump', 'badging', sdk_path]) + version_code = re.search(r"versionCode='(.*?)'", output).group(1) + version_name = re.search(r"versionName='(.*?)'", output).group(1) + return version_code, version_name, + + +def _FixManifest(options, temp_dir): + debug_manifest_path = os.path.join(temp_dir, 'AndroidManifest.xml') + _ANDROID_NAMESPACE = 'http://schemas.android.com/apk/res/android' + _TOOLS_NAMESPACE = 'http://schemas.android.com/tools' + ElementTree.register_namespace('android', _ANDROID_NAMESPACE) + ElementTree.register_namespace('tools', _TOOLS_NAMESPACE) + original_manifest = ElementTree.parse(options.android_manifest) + + version_code, version_name = _ExtractVersionFromSdk( + options.aapt_path, options.android_sdk_jar) + + # ElementTree.find does not work if the required tag is the root. + if original_manifest.getroot().tag == 'manifest': + manifest_node = original_manifest.getroot() + else: + manifest_node = original_manifest.find('manifest') + + manifest_node.set('platformBuildVersionCode', version_code) + manifest_node.set('platformBuildVersionName', version_name) + + if options.debuggable: + app_node = original_manifest.find('application') + app_node.set('{%s}%s' % (_ANDROID_NAMESPACE, 'debuggable'), 'true') + + with open(debug_manifest_path, 'w') as debug_manifest: + debug_manifest.write(ElementTree.tostring( + original_manifest.getroot(), encoding='UTF-8')) + + return debug_manifest_path + + +def _ResourceNameFromPath(path): + return os.path.splitext(os.path.basename(path))[0] + + +def _CreateKeepPredicate(resource_dirs, exclude_xxxhdpi, xxxhdpi_whitelist): + if not exclude_xxxhdpi: + # Do not extract dotfiles (e.g. ".gitkeep"). aapt ignores them anyways. + return lambda path: os.path.basename(path)[0] != '.' + + # Returns False only for xxxhdpi non-mipmap, non-whitelisted drawables. + naive_predicate = lambda path: ( + not re.search(r'[/-]xxxhdpi[/-]', path) or + re.search(r'[/-]mipmap[/-]', path) or + build_utils.MatchesGlob(path, xxxhdpi_whitelist)) + + # Build a set of all non-xxxhdpi drawables to ensure that we never exclude any + # xxxhdpi drawable that does not exist in other densities. + non_xxxhdpi_drawables = set() + for resource_dir in resource_dirs: + for path in build_utils.IterFiles(resource_dir): + if re.search(r'[/-]drawable[/-]', path) and naive_predicate(path): + non_xxxhdpi_drawables.add(_ResourceNameFromPath(path)) + + return lambda path: (naive_predicate(path) or + _ResourceNameFromPath(path) not in non_xxxhdpi_drawables) + + +def _ConvertToWebP(webp_binary, png_files): + pool = multiprocessing.pool.ThreadPool(10) + def convert_image(png_path): + root = os.path.splitext(png_path)[0] + webp_path = root + '.webp' + args = [webp_binary, png_path, '-mt', '-quiet', '-m', '6', '-q', '100', + '-lossless', '-o', webp_path] + subprocess.check_call(args) + os.remove(png_path) + + pool.map(convert_image, [f for f in png_files + if not _PNG_WEBP_BLACKLIST_PATTERN.match(f)]) + pool.close() + pool.join() + + +def _CompileDeps(aapt_path, dep_subdirs, temp_dir): + partials_dir = os.path.join(temp_dir, 'partials') + build_utils.MakeDirectory(partials_dir) + partial_compile_command = [ + aapt_path + '2', + 'compile', + # TODO(wnwen): Turn this on once aapt2 forces 9-patch to be crunched. + # '--no-crunch', + ] + pool = multiprocessing.pool.ThreadPool(10) + def compile_partial(directory): + dirname = os.path.basename(directory) + partial_path = os.path.join(partials_dir, dirname + '.zip') + compile_command = (partial_compile_command + + ['--dir', directory, '-o', partial_path]) + build_utils.CheckOutput(compile_command) + + # Sorting the files in the partial ensures deterministic output from the + # aapt2 link step which uses order of files in the partial. + sorted_partial_path = os.path.join(partials_dir, dirname + '.sorted.zip') + _SortZip(partial_path, sorted_partial_path) + + return sorted_partial_path + + partials = pool.map(compile_partial, dep_subdirs) + pool.close() + pool.join() + return partials + + +def _PackageApk(options, dep_subdirs, temp_dir, gen_dir, r_txt_path): + _DuplicateZhResources(dep_subdirs) + + keep_predicate = _CreateKeepPredicate( + dep_subdirs, options.exclude_xxxhdpi, options.xxxhdpi_whitelist) + png_paths = [] + for directory in dep_subdirs: + for f in build_utils.IterFiles(directory): + if not keep_predicate(f): + os.remove(f) + elif f.endswith('.png'): + png_paths.append(f) + if png_paths and options.png_to_webp: + _ConvertToWebP(options.webp_binary, png_paths) + for directory in dep_subdirs: + _MoveImagesToNonMdpiFolders(directory) + + link_command = _CreateLinkApkArgs(options) + link_command += ['--output-text-symbols', r_txt_path] + link_command += ['--java', gen_dir] + + fixed_manifest = _FixManifest(options, temp_dir) + link_command += ['--manifest', fixed_manifest] + + partials = _CompileDeps(options.aapt_path, dep_subdirs, temp_dir) + for partial in partials: + link_command += ['-R', partial] + + # Creates a .zip with AndroidManifest.xml, resources.arsc, res/* + # Also creates R.txt + build_utils.CheckOutput( + link_command, print_stdout=False, print_stderr=False) + + +# _PackageLibrary uses aapt rather than aapt2 because aapt2 compile does not +# support outputting an R.txt file. +def _PackageLibrary(options, dep_subdirs, temp_dir, gen_dir): + v14_dir = os.path.join(temp_dir, 'v14') + build_utils.MakeDirectory(v14_dir) + + # Generate R.java. This R.java contains non-final constants and is used only + # while compiling the library jar (e.g. chromium_content.jar). When building + # an apk, a new R.java file with the correct resource -> ID mappings will be + # generated by merging the resources from all libraries and the main apk + # project. + package_command = [options.aapt_path, + 'package', + '-m', + '-M', _EMPTY_ANDROID_MANIFEST_PATH, + '--no-crunch', + '--auto-add-overlay', + '--no-version-vectors', + '-I', options.android_sdk_jar, + '--output-text-symbols', gen_dir, + '-J', gen_dir, # Required for R.txt generation. + '--ignore-assets', build_utils.AAPT_IGNORE_PATTERN] + + # Adding all dependencies as sources is necessary for @type/foo references + # to symbols within dependencies to resolve. However, it has the side-effect + # that all Java symbols from dependencies are copied into the new R.java. + # E.g.: It enables an arguably incorrect usage of + # "mypackage.R.id.lib_symbol" where "libpackage.R.id.lib_symbol" would be + # more correct. This is just how Android works. + for d in dep_subdirs: + package_command += ['-S', d] + + input_resource_dirs = options.resource_dirs + + for d in input_resource_dirs: + package_command += ['-S', d] + + if not options.v14_skip: + for resource_dir in input_resource_dirs: + generate_v14_compatible_resources.GenerateV14Resources( + resource_dir, + v14_dir) + + # This is the list of directories with resources to put in the final .zip + zip_resource_dirs = input_resource_dirs + [v14_dir] + + if options.resource_zip_out: + _ZipResources(zip_resource_dirs, options.resource_zip_out, + build_utils.AAPT_IGNORE_PATTERN) + + # Only creates an R.txt + build_utils.CheckOutput( + package_command, print_stdout=False, print_stderr=False) + + +def _CreateRTxtAndSrcJar(options, r_txt_path, srcjar_dir): + # When an empty res/ directory is passed, aapt does not write an R.txt. + if not os.path.exists(r_txt_path): + build_utils.Touch(r_txt_path) + + if options.r_text_in: + r_txt_path = options.r_text_in + + packages = list(options.extra_res_packages) + r_txt_files = list(options.extra_r_text_files) + + cur_package = options.custom_package + if not options.custom_package and options.android_manifest: + cur_package = _ExtractPackageFromManifest(options.android_manifest) + + # Don't create a .java file for the current resource target when: + # - no package name was provided (either by manifest or build rules), + # - there was already a dependent android_resources() with the same + # package (occurs mostly when an apk target and resources target share + # an AndroidManifest.xml) + if cur_package and cur_package not in packages: + packages.append(cur_package) + r_txt_files.append(r_txt_path) + + if packages: + shared_resources = options.shared_resources or options.app_as_shared_lib + _CreateRJavaFiles(srcjar_dir, r_txt_path, packages, r_txt_files, + shared_resources, options.non_constant_id, + options.shared_resources_whitelist, bool(options.apk_path)) + + if options.srcjar_out: + build_utils.ZipDir(options.srcjar_out, srcjar_dir) + + if options.r_text_out: + shutil.copyfile(r_txt_path, options.r_text_out) + + +def _ExtractDeps(dep_zips, deps_dir): + dep_subdirs = [] + for z in dep_zips: + subdir = os.path.join(deps_dir, os.path.basename(z)) + if os.path.exists(subdir): + raise Exception('Resource zip name conflict: ' + os.path.basename(z)) + build_utils.ExtractAll(z, path=subdir) + dep_subdirs.append(subdir) + return dep_subdirs + + +def _OnStaleMd5(options): + with build_utils.TempDir() as temp_dir: + deps_dir = os.path.join(temp_dir, 'deps') + build_utils.MakeDirectory(deps_dir) + gen_dir = os.path.join(temp_dir, 'gen') + build_utils.MakeDirectory(gen_dir) + r_txt_path = os.path.join(gen_dir, 'R.txt') + srcjar_dir = os.path.join(temp_dir, 'java') + + dep_subdirs = _ExtractDeps(options.dependencies_res_zips, deps_dir) + + if options.apk_path: + _PackageApk(options, dep_subdirs, temp_dir, gen_dir, r_txt_path) + else: + _PackageLibrary(options, dep_subdirs, temp_dir, gen_dir) + + _CreateRTxtAndSrcJar(options, r_txt_path, srcjar_dir) + + +def main(args): + args = build_utils.ExpandFileArgs(args) + options = _ParseArgs(args) + + # Order of these must match order specified in GN so that the correct one + # appears first in the depfile. + possible_output_paths = [ + options.apk_path, + options.resource_zip_out, + options.r_text_out, + options.srcjar_out, + options.proguard_file, + options.proguard_file_main_dex, + ] + output_paths = [x for x in possible_output_paths if x] + + # List python deps in input_strings rather than input_paths since the contents + # of them does not change what gets written to the depsfile. + input_strings = options.extra_res_packages + [ + options.app_as_shared_lib, + options.custom_package, + options.non_constant_id, + options.shared_resources, + options.v14_skip, + options.exclude_xxxhdpi, + options.xxxhdpi_whitelist, + str(options.debuggable), + str(options.png_to_webp), + str(options.support_zh_hk), + str(options.no_xml_namespaces), + ] + + if options.apk_path: + input_strings.extend(_CreateLinkApkArgs(options)) + + possible_input_paths = [ + options.aapt_path, + options.android_manifest, + options.android_sdk_jar, + options.shared_resources_whitelist, + ] + input_paths = [x for x in possible_input_paths if x] + input_paths.extend(options.dependencies_res_zips) + input_paths.extend(options.extra_r_text_files) + + if options.webp_binary: + input_paths.append(options.webp_binary) + + # Resource files aren't explicitly listed in GN. Listing them in the depfile + # ensures the target will be marked stale when resource files are removed. + depfile_deps = [] + resource_names = [] + for resource_dir in options.resource_dirs: + for resource_file in build_utils.FindInDirectory(resource_dir, '*'): + # Don't list the empty .keep file in depfile. Since it doesn't end up + # included in the .zip, it can lead to -w 'dupbuild=err' ninja errors + # if ever moved. + if not resource_file.endswith(os.path.join('empty', '.keep')): + input_paths.append(resource_file) + depfile_deps.append(resource_file) + resource_names.append(os.path.relpath(resource_file, resource_dir)) + + # Resource filenames matter to the output, so add them to strings as well. + # This matters if a file is renamed but not changed (http://crbug.com/597126). + input_strings.extend(sorted(resource_names)) + + build_utils.CallAndWriteDepfileIfStale( + lambda: _OnStaleMd5(options), + options, + input_paths=input_paths, + input_strings=input_strings, + output_paths=output_paths, + depfile_deps=depfile_deps) + + +if __name__ == '__main__': + main(sys.argv[1:])
diff --git a/build/android/gyp/util/resource_utils.py b/build/android/gyp/util/resource_utils.py deleted file mode 100644 index 1c0b7c5..0000000 --- a/build/android/gyp/util/resource_utils.py +++ /dev/null
@@ -1,453 +0,0 @@ -# Copyright 2018 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import argparse -import collections -import contextlib -import os -import re -import shutil -import sys -import tempfile -from xml.etree import ElementTree - -import util.build_utils as build_utils - -_SOURCE_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname( - os.path.dirname(__file__))))) -# Import jinja2 from third_party/jinja2 -sys.path.insert(1, os.path.join(_SOURCE_ROOT, 'third_party')) -from jinja2 import Template # pylint: disable=F0401 - - -EMPTY_ANDROID_MANIFEST_PATH = os.path.join( - _SOURCE_ROOT, 'build', 'android', 'AndroidManifest.xml') - - -# Represents a line from a R.txt file. -_TextSymbolEntry = collections.namedtuple('RTextEntry', - ('java_type', 'resource_type', 'name', 'value')) - - -def _ParseTextSymbolsFile(path, fix_package_ids=False): - """Given an R.txt file, returns a list of _TextSymbolEntry. - - Args: - path: Input file path. - fix_package_ids: if True, all packaged IDs read from the file - will be fixed to 0x7f. - Returns: - A list of _TextSymbolEntry instances. - Raises: - Exception: An unexpected line was detected in the input. - """ - ret = [] - with open(path) as f: - for line in f: - m = re.match(r'(int(?:\[\])?) (\w+) (\w+) (.+)$', line) - if not m: - raise Exception('Unexpected line in R.txt: %s' % line) - java_type, resource_type, name, value = m.groups() - if fix_package_ids: - value = _FixPackageIds(value) - ret.append(_TextSymbolEntry(java_type, resource_type, name, value)) - return ret - - -def _FixPackageIds(resource_value): - # Resource IDs for resources belonging to regular APKs have their first byte - # as 0x7f (package id). However with webview, since it is not a regular apk - # but used as a shared library, aapt is passed the --shared-resources flag - # which changes some of the package ids to 0x02 and 0x00. This function just - # normalises all package ids to 0x7f, which the generated code in R.java - # changes to the correct package id at runtime. - # resource_value is a string with either, a single value '0x12345678', or an - # array of values like '{ 0xfedcba98, 0x01234567, 0x56789abc }' - return re.sub(r'0x(?!01)\d\d', r'0x7f', resource_value) - - -def _GetRTxtResourceNames(r_txt_path): - """Parse an R.txt file and extract the set of resource names from it.""" - result = set() - for entry in _ParseTextSymbolsFile(r_txt_path): - result.add(entry.name) - return result - - -class RJavaBuildOptions: - """A class used to model the various ways to build an R.java file. - - This is used to control which resource ID variables will be final or - non-final, and whether an onResourcesLoaded() method will be generated - to adjust the non-final ones, when the corresponding library is loaded - at runtime. - - Note that by default, all resources are final, and there is no - method generated, which corresponds to calling ExportNoResources(). - """ - def __init__(self): - self.has_constant_ids = True - self.resources_whitelist = None - self.has_on_resources_loaded = False - self.export_const_styleable = False - - def ExportNoResources(self): - """Make all resource IDs final, and don't generate a method.""" - self.has_constant_ids = True - self.resources_whitelist = None - self.has_on_resources_loaded = False - self.export_const_styleable = False - - def ExportAllResources(self): - """Make all resource IDs non-final in the R.java file.""" - self.has_constant_ids = False - self.resources_whitelist = None - - def ExportSomeResources(self, r_txt_file_path): - """Only select specific resource IDs to be non-final. - - Args: - r_txt_file_path: The path to an R.txt file. All resources named - int it will be non-final in the generated R.java file, all others - will be final. - """ - self.has_constant_ids = True - self.resources_whitelist = _GetRTxtResourceNames(r_txt_file_path) - - def ExportAllStyleables(self): - """Make all styleable constants non-final, even non-resources ones. - - Resources that are styleable but not of int[] type are not actually - resource IDs but constants. By default they are always final. Call this - method to make them non-final anyway in the final R.java file. - """ - self.export_const_styleable = True - - def GenerateOnResourcesLoaded(self): - """Generate an onResourcesLoaded() method. - - This Java method will be called at runtime by the framework when - the corresponding library (which includes the R.java source file) - will be loaded at runtime. This corresponds to the --shared-resources - or --app-as-shared-lib flags of 'aapt package'. - """ - self.has_on_resources_loaded = True - - def _IsResourceFinal(self, entry): - """Determines whether a resource should be final or not. - - Args: - entry: A _TextSymbolEntry instance. - Returns: - True iff the corresponding entry should be final. - """ - if entry.resource_type == 'styleable' and entry.java_type != 'int[]': - # A styleable constant may be exported as non-final after all. - return not self.export_const_styleable - elif not self.has_constant_ids: - # Every resource is non-final - return False - elif not self.resources_whitelist: - # No whitelist means all IDs are non-final. - return True - else: - # Otherwise, only those in the - return entry.name not in self.resources_whitelist - - -def CreateRJavaFiles(srcjar_dir, package, main_r_txt_file, - extra_res_packages, extra_r_txt_files, - rjava_build_options): - """Create all R.java files for a set of packages and R.txt files. - - Args: - srcjar_dir: The top-level output directory for the generated files. - package: Top-level package name. - main_r_txt_file: The main R.txt file containing the valid values - of _all_ resource IDs. - extra_res_packages: A list of extra package names. - extra_r_txt_files: A list of extra R.txt files. One per item in - |extra_res_packages|. Note that all resource IDs in them will be ignored, - |and replaced by the values extracted from |main_r_txt_file|. - rjava_build_options: An RJavaBuildOptions instance that controls how - exactly the R.java file is generated. - Raises: - Exception if a package name appears several times in |extra_res_packages| - """ - assert len(extra_res_packages) == len(extra_r_txt_files), \ - 'Need one R.txt file per package' - - packages = list(extra_res_packages) - r_txt_files = list(extra_r_txt_files) - - if package not in packages: - # Sometimes, an apk target and a resources target share the same - # AndroidManifest.xml and thus |package| will already be in |packages|. - packages.append(package) - r_txt_files.append(main_r_txt_file) - - # Map of (resource_type, name) -> Entry. - # Contains the correct values for resources. - all_resources = {} - for entry in _ParseTextSymbolsFile(main_r_txt_file, fix_package_ids=True): - all_resources[(entry.resource_type, entry.name)] = entry - - # Map of package_name->resource_type->entry - resources_by_package = ( - collections.defaultdict(lambda: collections.defaultdict(list))) - # Build the R.java files using each package's R.txt file, but replacing - # each entry's placeholder value with correct values from all_resources. - for package, r_txt_file in zip(packages, r_txt_files): - if package in resources_by_package: - raise Exception(('Package name "%s" appeared twice. All ' - 'android_resources() targets must use unique package ' - 'names, or no package name at all.') % package) - resources_by_type = resources_by_package[package] - # The sub-R.txt files have the wrong values at this point. Read them to - # figure out which entries belong to them, but use the values from the - # main R.txt file. - for entry in _ParseTextSymbolsFile(r_txt_file): - entry = all_resources.get((entry.resource_type, entry.name)) - # For most cases missing entry here is an error. It means that some - # library claims to have or depend on a resource that isn't included into - # the APK. There is one notable exception: Google Play Services (GMS). - # GMS is shipped as a bunch of AARs. One of them - basement - contains - # R.txt with ids of all resources, but most of the resources are in the - # other AARs. However, all other AARs reference their resources via - # basement's R.java so the latter must contain all ids that are in its - # R.txt. Most targets depend on only a subset of GMS AARs so some - # resources are missing, which is okay because the code that references - # them is missing too. We can't get an id for a resource that isn't here - # so the only solution is to skip the resource entry entirely. - # - # We can verify that all entries referenced in the code were generated - # correctly by running Proguard on the APK: it will report missing - # fields. - if entry: - resources_by_type[entry.resource_type].append(entry) - - for package, resources_by_type in resources_by_package.iteritems(): - _CreateRJavaSourceFile(srcjar_dir, package, resources_by_type, - rjava_build_options) - - -def _CreateRJavaSourceFile(srcjar_dir, package, resources_by_type, - rjava_build_options): - """Generates an R.java source file.""" - package_r_java_dir = os.path.join(srcjar_dir, *package.split('.')) - build_utils.MakeDirectory(package_r_java_dir) - package_r_java_path = os.path.join(package_r_java_dir, 'R.java') - java_file_contents = _RenderRJavaSource(package, resources_by_type, - rjava_build_options) - with open(package_r_java_path, 'w') as f: - f.write(java_file_contents) - - -def _RenderRJavaSource(package, resources_by_type, rjava_build_options): - """Render an R.java source file. See _CreateRJaveSourceFile for args info.""" - final_resources_by_type = collections.defaultdict(list) - non_final_resources_by_type = collections.defaultdict(list) - for res_type, resources in resources_by_type.iteritems(): - for entry in resources: - # Entries in stylable that are not int[] are not actually resource ids - # but constants. - if rjava_build_options._IsResourceFinal(entry): - final_resources_by_type[res_type].append(entry) - else: - non_final_resources_by_type[res_type].append(entry) - - # Keep these assignments all on one line to make diffing against regular - # aapt-generated files easier. - create_id = ('{{ e.resource_type }}.{{ e.name }} ^= packageIdTransform;') - # Here we diverge from what aapt does. Because we have so many - # resources, the onResourcesLoaded method was exceeding the 64KB limit that - # Java imposes. For this reason we split onResourcesLoaded into different - # methods for each resource type. - template = Template("""/* AUTO-GENERATED FILE. DO NOT MODIFY. */ - -package {{ package }}; - -public final class R { - private static boolean sResourcesDidLoad; - {% for resource_type in resource_types %} - public static final class {{ resource_type }} { - {% for e in final_resources[resource_type] %} - public static final {{ e.java_type }} {{ e.name }} = {{ e.value }}; - {% endfor %} - {% for e in non_final_resources[resource_type] %} - public static {{ e.java_type }} {{ e.name }} = {{ e.value }}; - {% endfor %} - } - {% endfor %} - {% if has_on_resources_loaded %} - public static void transfromArray(int[] array, int packageIdTransform) { - for (int i=0; i < array.length; i++) { - if ((array[i] >>> 24) == 0x7f) { - array[i] ^= packageIdTransform; - } - } - } - public static void onResourcesLoaded(int packageId) { - assert !sResourcesDidLoad; - sResourcesDidLoad = true; - int packageIdTransform = (packageId ^ 0x7f) << 24; - {% for resource_type in resource_types %} - onResourcesLoaded{{ resource_type|title }}(packageIdTransform); - {% for e in non_final_resources[resource_type] %} - {% if e.java_type == 'int[]' %} - transfromArray({{ e.resource_type }}.{{ e.name }}, packageIdTransform); - {% endif %} - {% endfor %} - {% endfor %} - } - {% for res_type in resource_types %} - private static void onResourcesLoaded{{ res_type|title }} ( - int packageIdTransform) { - {% for e in non_final_resources[res_type] %} - {% if res_type != 'styleable' and e.java_type != 'int[]' %} - """ + create_id + """ - {% endif %} - {% endfor %} - } - {% endfor %} - {% endif %} -} -""", trim_blocks=True, lstrip_blocks=True) - - return template.render( - package=package, - resource_types=sorted(resources_by_type), - has_on_resources_loaded=rjava_build_options.has_on_resources_loaded, - final_resources=final_resources_by_type, - non_final_resources=non_final_resources_by_type) - - -def ExtractPackageFromManifest(manifest_path): - """Extract package name from Android manifest file.""" - doc = ElementTree.parse(manifest_path) - return doc.getroot().get('package') - - -def ExtractDeps(dep_zips, deps_dir): - """Extract a list of resource dependency zip files. - - Args: - dep_zips: A list of zip file paths, each one will be extracted to - a subdirectory of |deps_dir|, named after the zip file (e.g. - '/some/path/foo.zip' -> '{deps_dir}/foo/'). - deps_dir: Top-level extraction directory. - Returns: - The list of all sub-directory paths, relative to |deps_dir|. - Raises: - Exception: If a sub-directory already exists with the same name before - extraction. - """ - dep_subdirs = [] - for z in dep_zips: - subdir = os.path.join(deps_dir, os.path.basename(z)) - if os.path.exists(subdir): - raise Exception('Resource zip name conflict: ' + os.path.basename(z)) - build_utils.ExtractAll(z, path=subdir) - dep_subdirs.append(subdir) - return dep_subdirs - - -class _ResourceBuildContext(object): - """A temporary directory for packaging and compiling Android resources.""" - def __init__(self): - """Initialized the context.""" - # The top-level temporary directory. - self.temp_dir = tempfile.mkdtemp() - # A location to store resources extracted form dependency zip files. - self.deps_dir = os.path.join(self.temp_dir, 'deps') - os.mkdir(self.deps_dir) - # A location to place aapt-generated files. - self.gen_dir = os.path.join(self.temp_dir, 'gen') - os.mkdir(self.gen_dir) - # Location of the generated R.txt file. - self.r_txt_path = os.path.join(self.gen_dir, 'R.txt') - # A location to place generated R.java files. - self.srcjar_dir = os.path.join(self.temp_dir, 'java') - os.mkdir(self.srcjar_dir) - - def Close(self): - """Close the context and destroy all temporary files.""" - shutil.rmtree(self.temp_dir) - - -@contextlib.contextmanager -def BuildContext(): - """Generator for a _ResourceBuildContext instance.""" - try: - context = _ResourceBuildContext() - yield context - finally: - context.Close() - - -def ResourceArgsParser(): - """Create an argparse.ArgumentParser instance with common argument groups. - - Returns: - A tuple of (parser, in_group, out_group) corresponding to the parser - instance, and the input and output argument groups for it, respectively. - """ - parser = argparse.ArgumentParser(description=__doc__) - - input_opts = parser.add_argument_group('Input options') - output_opts = parser.add_argument_group('Output options') - - build_utils.AddDepfileOption(output_opts) - - input_opts.add_argument('--android-sdk-jar', required=True, - help='Path to the android.jar file.') - - input_opts.add_argument('--aapt-path', required=True, - help='Path to the Android aapt tool') - - input_opts.add_argument('--dependencies-res-zips', required=True, - help='Resources zip archives from dependents. Required to ' - 'resolve @type/foo references into dependent ' - 'libraries.') - - input_opts.add_argument( - '--r-text-in', - help='Path to pre-existing R.txt. Its resource IDs override those found ' - 'in the aapt-generated R.txt when generating R.java.') - - input_opts.add_argument( - '--extra-res-packages', - help='Additional package names to generate R.java files for.') - - input_opts.add_argument( - '--extra-r-text-files', - help='For each additional package, the R.txt file should contain a ' - 'list of resources to be included in the R.java file in the format ' - 'generated by aapt.') - - return (parser, input_opts, output_opts) - - -def HandleCommonOptions(options): - """Handle common command-line options after parsing. - - Args: - options: the result of parse_args() on the parser returned by - ResourceArgsParser(). This function updates a few common fields. - """ - options.dependencies_res_zips = ( - build_utils.ParseGnList(options.dependencies_res_zips)) - - # Don't use [] as default value since some script explicitly pass "". - if options.extra_res_packages: - options.extra_res_packages = ( - build_utils.ParseGnList(options.extra_res_packages)) - else: - options.extra_res_packages = [] - - if options.extra_r_text_files: - options.extra_r_text_files = ( - build_utils.ParseGnList(options.extra_r_text_files)) - else: - options.extra_r_text_files = []
diff --git a/build/config/android/internal_rules.gni b/build/config/android/internal_rules.gni index 452afa4..81c502bd 100644 --- a/build/config/android/internal_rules.gni +++ b/build/config/android/internal_rules.gni
@@ -1449,65 +1449,22 @@ } } - # This template is used to parse a set of resource directories and - # create the R.txt, .srcjar and .resources.zip for it. - # - # Input variables: - # deps: Specifies the input dependencies for this target. - # - # build_config: Path to the .build_config file corresponding to the target. - # - # resource_dirs: - # List of directories containing Android resources, layout should be - # similar to what aapt -S <dir> expects. - # - # generated_resource_dirs: (optional) - # List of directories containing generated resources. - # - # generated_resource_files: (optional) - # If generated_resources_dirs is not empty, must list all the files - # within these directories (the directory must appear at the start of - # the file path). - # - # custom_package: (optional) - # Package name for the generated R.java source file. Optional if - # android_manifest is not provided. - # - # android_manifest: (optional) - # If custom_package is not provided, path to an AndroidManifest.xml file - # that is only used to extract a package name out of it. - # - # r_text_in_path: (optional) - # Path to an input R.txt file to use to generate the R.java file. - # The default is to use 'aapt' to generate the file from the content - # of the resource directories. - # - # alternative_android_sdk_jar: Alternative android.jar to use. - # TODO(digit): Not sure this is needed here. - # - # shared_resources: (optional) - # If true, generate an R.java file that uses non-final resource ID - # variables and an onResourcesLoaded() method. - # - # v14_skip: (optional) - # If true, skip generation of v14 compatible resources. - # (see generate_v14_compatible_resources.py for details). - # - # Output variables: - # zip_path: (optional) - # Path to a .resources.zip that will simply contain all the - # input resources, collected in a single archive. - # - # r_text_out_path: (optional): Path for the generated R.txt file. - # - # srcjar_path: (optional) Path to a generated .srcjar containing the - # generated R.java source file. - # - template("prepare_resources") { + template("process_resources") { + _process_resources_target_name = target_name if (defined(invoker.srcjar_path)) { _srcjar_path = invoker.srcjar_path } - action(target_name) { + if (defined(invoker.output)) { + _packaged_resources_path = invoker.output + } + if (defined(invoker.post_process_script)) { + _process_resources_target_name = "${target_name}__intermediate" + _packaged_resources_path = + get_path_info(_packaged_resources_path, "dir") + "/" + + get_path_info(_packaged_resources_path, "name") + ".intermediate.ap_" + _srcjar_path = "${_srcjar_path}.intermediate.srcjar" + } + action(_process_resources_target_name) { set_sources_assignment_filter([]) forward_variables_from(invoker, [ @@ -1515,9 +1472,9 @@ "testonly", "visibility", ]) - script = "//build/android/gyp/prepare_resources.py" + script = "//build/android/gyp/process_resources.py" - depfile = "$target_gen_dir/${invoker.target_name}.d" + depfile = "$target_gen_dir/${invoker.target_name}_1.d" outputs = [] _all_resource_dirs = [] sources = [] @@ -1550,6 +1507,7 @@ } inputs = [ + android_default_aapt_path, invoker.build_config, _android_aapt_path, _android_sdk_jar, @@ -1583,6 +1541,44 @@ args += [ "--resource-dirs=$_rebased_all_resource_dirs" ] } + if (defined(invoker.shared_resources_whitelist)) { + inputs += [ invoker.shared_resources_whitelist ] + args += [ + "--shared-resources-whitelist", + rebase_path(invoker.shared_resources_whitelist, root_build_dir), + ] + } + + if (defined(invoker.no_xml_namespaces) && invoker.no_xml_namespaces) { + args += [ "--no-xml-namespaces" ] + } + + if (defined(invoker.version_code)) { + args += [ + "--version-code", + invoker.version_code, + ] + } + if (defined(invoker.version_name)) { + args += [ + "--version-name", + invoker.version_name, + ] + } + if (defined(_packaged_resources_path)) { + outputs += [ _packaged_resources_path ] + args += [ + "--apk-path", + rebase_path(_packaged_resources_path, root_build_dir), + ] + } + + # Useful to have android:debuggable in the manifest even for Release + # builds. Just omit it for officai + if (debuggable_apks) { + args += [ "--debuggable" ] + } + if (defined(invoker.zip_path)) { outputs += [ invoker.zip_path ] args += [ @@ -1616,6 +1612,11 @@ ] } + if (!defined(invoker.generate_constant_ids) || + !invoker.generate_constant_ids) { + args += [ "--non-constant-id" ] + } + if (defined(invoker.custom_package)) { args += [ "--custom-package", @@ -1623,209 +1624,18 @@ ] } - if (defined(invoker.shared_resources) && invoker.shared_resources) { - args += [ "--shared-resources" ] - } - if (defined(invoker.v14_skip) && invoker.v14_skip) { args += [ "--v14-skip" ] } - } - } - - # A template that is used to compile all resources needed by a binary - # (e.g. an android_apk or a junit_binary) into an intermediate .ar_ - # archive. It can also generate an associated .srcjar that contains the - # final R.java sources for all resource packages the binary depends on. - # - # Input variables: - # deps: Specifies the input dependencies for this target. - # - # build_config: Path to the .build_config file corresponding to the target. - # - # android_manifest: Path to root manifest for the binary. - # - # version_code: (optional) - # - # version_name: (optional) - # - # alternative_android_sdk_jar: Alternative system android.jar to use. - # - # shared_resources: (optional) - # If true, make all variables in each generated R.java file non-final, - # and provide an onResourcesLoaded() method that can be used to reset - # their package index at load time. Useful when the APK corresponds to - # a library that is loaded at runtime, like system_webview_apk or - # monochrome_apk. - # - # shared_resources_whitelist: (optional) - # Path to an R.txt file. If provided, acts similar to shared_resources - # except that it restricts the list of non-final resource variables - # to the list from the input R.txt file. Overrides shared_resources - # when both are specified. - # - # support_zh_hk: (optional) - # If true, support zh-HK in Chrome on Android by using the resources - # from zh-TW. See https://crbug.com/780847. - # - # aapt_locale_whitelist: (optional) - # Restrict compiled locale-dependent resources to a specific whitelist. - # NOTE: This is a list of Chromium locale names, not Android ones. - # - # exclude_xxxhdpi: (optional) - # - # xxxhdpi_whitelist: (optional) - # - # no_xml_namespaces: (optional) - # - # png_to_webp: (optional) - # If true, convert all PNG resources (except 9-patch files) to WebP. - # - # post_process_script: (optional) - # - # - # Output variables: - # output: Path to a zip file containing the compiled resources. - # - # r_text_out_path: (optional): - # Path for the corresponding generated R.txt file. - # - # srcjar_path: (optional) - # Path to a generated .srcjar containing the generated R.java sources - # for all dependent resource libraries. - # - # proguard_file: (optional) - # Path to proguard configuration file for this apk target. - # - # proguard_file_main_dex: (optional) - # - # - template("compile_resources") { - _compile_resources_target_name = target_name - _compiled_resources_path = invoker.output - - if (defined(invoker.srcjar_path)) { - _srcjar_path = invoker.srcjar_path - } - if (defined(invoker.post_process_script)) { - _compile_resources_target_name = "${target_name}__intermediate" - _compiled_resources_path = - get_path_info(_compiled_resources_path, "dir") + "/" + - get_path_info(_compiled_resources_path, "name") + ".intermediate.ap_" - _srcjar_path = "${_srcjar_path}.intermediate.srcjar" - } - - action(_compile_resources_target_name) { - set_sources_assignment_filter([]) - forward_variables_from(invoker, - [ - "deps", - "testonly", - "visibility", - ]) - script = "//build/android/gyp/compile_resources.py" - - depfile = "$target_gen_dir/${invoker.target_name}_1.d" - outputs = [] - - _android_aapt_path = android_default_aapt_path - - _android_sdk_jar = android_sdk_jar - if (defined(invoker.alternative_android_sdk_jar)) { - _android_sdk_jar = invoker.alternative_android_sdk_jar - } - - inputs = [ - invoker.build_config, - _android_aapt_path, - _android_sdk_jar, - ] - - _rebased_build_config = rebase_path(invoker.build_config, root_build_dir) - - args = [ - "--depfile", - rebase_path(depfile, root_build_dir), - "--android-sdk-jar", - rebase_path(_android_sdk_jar, root_build_dir), - "--aapt-path", - rebase_path(_android_aapt_path, root_build_dir), - "--dependencies-res-zips=@FileArg($_rebased_build_config:resources:dependency_zips)", - "--extra-res-packages=@FileArg($_rebased_build_config:resources:extra_package_names)", - "--extra-r-text-files=@FileArg($_rebased_build_config:resources:extra_r_text_files)", - ] - - inputs += [ invoker.android_manifest ] - args += [ - "--android-manifest", - rebase_path(invoker.android_manifest, root_build_dir), - ] - - if (defined(invoker.shared_resources_whitelist)) { - inputs += [ invoker.shared_resources_whitelist ] - args += [ - "--shared-resources-whitelist", - rebase_path(invoker.shared_resources_whitelist, root_build_dir), - ] - } - - if (defined(invoker.no_xml_namespaces) && invoker.no_xml_namespaces) { - args += [ "--no-xml-namespaces" ] - } - - if (defined(invoker.version_code)) { - args += [ - "--version-code", - invoker.version_code, - ] - } - if (defined(invoker.version_name)) { - args += [ - "--version-name", - invoker.version_name, - ] - } - if (defined(_compiled_resources_path)) { - outputs += [ _compiled_resources_path ] - args += [ - "--apk-path", - rebase_path(_compiled_resources_path, root_build_dir), - ] - } - - # Useful to have android:debuggable in the manifest even for Release - # builds. Just omit it for officai - if (debuggable_apks) { - args += [ "--debuggable" ] - } - - if (defined(invoker.r_text_out_path)) { - outputs += [ invoker.r_text_out_path ] - args += [ - "--r-text-out", - rebase_path(invoker.r_text_out_path, root_build_dir), - ] - } - - if (defined(_srcjar_path)) { - outputs += [ _srcjar_path ] - args += [ - "--srcjar-out", - rebase_path(_srcjar_path, root_build_dir), - ] - } - - if (defined(invoker.custom_package)) { - args += [ - "--custom-package", - invoker.custom_package, - ] - } if (defined(invoker.shared_resources) && invoker.shared_resources) { args += [ "--shared-resources" ] } + if (defined(invoker.app_as_shared_lib) && invoker.app_as_shared_lib) { + args += [ "--app-as-shared-lib" ] + } + if (defined(invoker.proguard_file)) { outputs += [ invoker.proguard_file ] args += [ @@ -1880,7 +1690,7 @@ "--depfile", rebase_path(depfile, root_build_dir), "--apk-path", - rebase_path(_compiled_resources_path, root_build_dir), + rebase_path(_packaged_resources_path, root_build_dir), "--output", rebase_path(invoker.output, root_build_dir), "--srcjar-in", @@ -1898,14 +1708,14 @@ } inputs = [ _srcjar_path, - _compiled_resources_path, + _packaged_resources_path, ] outputs = [ invoker.output, invoker.srcjar_path, ] public_deps = [ - ":${_compile_resources_target_name}", + ":${_process_resources_target_name}", ] } } @@ -1954,14 +1764,14 @@ invoker.output_apk_path, ] - _rebased_compiled_resources_path = + _rebased_packaged_resources_path = rebase_path(invoker.packaged_resources_path, root_build_dir) _rebased_packaged_apk_path = rebase_path(invoker.output_apk_path, root_build_dir) args = [ "--depfile", rebase_path(depfile, root_build_dir), - "--resource-apk=$_rebased_compiled_resources_path", + "--resource-apk=$_rebased_packaged_resources_path", "--output-apk=$_rebased_packaged_apk_path", ] if (defined(invoker.assets_build_config)) { @@ -2126,23 +1936,27 @@ invoker.native_libs_even_when_incremental } - _incremental_compiled_resources_path = "${_base_path}_incremental.ap_" + _incremental_packaged_resources_path = "${_base_path}_incremental.ap_" _packaged_apk_path = "${_base_path}_unsigned.apk" _incremental_packaged_apk_path = "${_base_path}_incremental_unsigned.apk" _shared_resources = defined(invoker.shared_resources) && invoker.shared_resources assert(_shared_resources || true) # Mark as used. + _app_as_shared_lib = + defined(invoker.app_as_shared_lib) && invoker.app_as_shared_lib + assert(_app_as_shared_lib || true) # Mark as used. + assert(!(_shared_resources && _app_as_shared_lib)) _keystore_path = invoker.keystore_path _keystore_name = invoker.keystore_name _keystore_password = invoker.keystore_password - _incremental_compile_resources_target_name = - "${target_name}_incremental__compile_resources" + _incremental_package_resources_target_name = + "${target_name}_incremental__package_resources" _incremental_android_manifest = - get_label_info(_incremental_compile_resources_target_name, + get_label_info(_incremental_package_resources_target_name, "target_gen_dir") + "/AndroidManifest.xml" - action(_incremental_compile_resources_target_name) { + action(_incremental_package_resources_target_name) { deps = _incremental_deps script = "//build/android/incremental_install/generate_android_manifest.py" @@ -2156,7 +1970,7 @@ # Output the non-compiled manifest for easy debugging (as opposed to # generating to a temp file). _incremental_android_manifest, - _incremental_compiled_resources_path, + _incremental_packaged_resources_path, ] _android_sdk_jar = android_sdk_jar @@ -2171,7 +1985,7 @@ "--in-apk", rebase_path(invoker.packaged_resources_path, root_build_dir), "--out-apk", - rebase_path(_incremental_compiled_resources_path, root_build_dir), + rebase_path(_incremental_packaged_resources_path, root_build_dir), "--aapt-path", rebase_path(android_default_aapt_path, root_build_dir), "--android-sdk-jar", @@ -2222,7 +2036,7 @@ } _dex_target = "//build/android/incremental_install:bootstrap_java__dex" deps = _incremental_deps + [ - ":${_incremental_compile_resources_target_name}", + ":${_incremental_package_resources_target_name}", _dex_target, ] @@ -2241,7 +2055,7 @@ } output_apk_path = _incremental_packaged_apk_path - packaged_resources_path = _incremental_compiled_resources_path + packaged_resources_path = _incremental_packaged_resources_path } finalize_apk(target_name) {
diff --git a/build/config/android/rules.gni b/build/config/android/rules.gni index 154a985..6db38cf 100644 --- a/build/config/android/rules.gni +++ b/build/config/android/rules.gni
@@ -723,6 +723,8 @@ # false. (see build/android/gyp/generate_v14_compatible_resources.py) # shared_resources: If true make a resource package that can be loaded by a # different application at runtime to access the package's resources. + # app_as_shared_lib: If true make a resource package that can be loaded as + # both shared_resources and normal application. # r_text_file: (optional) path to pre-generated R.txt to be used when # generating R.java instead of resource-based aapt-generated one. # create_srcjar: If false, does not create an R.java file. Needed only for @@ -790,15 +792,17 @@ } } - prepare_resources(target_name) { + process_resources(target_name) { forward_variables_from(invoker, [ + "app_as_shared_lib", "android_manifest", "custom_package", "deps", "generated_resource_dirs", "generated_resource_files", "resource_dirs", + "shared_resources", "v14_skip", ]) if (!defined(deps)) { @@ -1147,8 +1151,8 @@ _deps += invoker.deps } - _prepare_resources_target = "${target_name}__prepare_resources" - prepare_resources(_prepare_resources_target) { + _process_resources_target = "${target_name}__process_resources" + process_resources(_process_resources_target) { deps = _deps + [ ":$_build_config_target_name" ] build_config = _build_config srcjar_path = "${target_gen_dir}/${target_name}.srcjar" @@ -1178,7 +1182,7 @@ srcjar_deps = [] } srcjar_deps += [ - ":$_prepare_resources_target", + ":$_process_resources_target", # This dep is required for any targets that depend on //base:base_java. "//base:base_build_config_gen", @@ -2010,11 +2014,12 @@ "$_base_path.resources.main-dex-proguard.txt" } _generated_proguard_config = "$_base_path.resources.proguard.txt" - _compile_resources_target = "${_template_name}__compile_resources" - compile_resources(_compile_resources_target) { + _process_resources_target = "${_template_name}__process_resources" + process_resources(_process_resources_target) { forward_variables_from(invoker, [ "alternative_android_sdk_jar", + "app_as_shared_lib", "shared_resources", "support_zh_hk", "aapt_locale_whitelist", @@ -2031,6 +2036,7 @@ } srcjar_path = "${target_gen_dir}/${target_name}.srcjar" r_text_out_path = "${target_gen_dir}/${target_name}_R.txt" + generate_constant_ids = true proguard_file = _generated_proguard_config if (_enable_multidex) { proguard_file_main_dex = _generated_proguard_main_dex_config @@ -2050,13 +2056,13 @@ get_label_info(invoker.shared_resources_whitelist_target, "name") shared_resources_whitelist = "${_whitelist_gen_dir}/${_whitelist_target_name}" + - "__compile_resources_R.txt" + "__process_resources_R.txt" deps += [ - "${invoker.shared_resources_whitelist_target}__compile_resources", + "${invoker.shared_resources_whitelist_target}__process_resources", ] } } - _srcjar_deps += [ ":$_compile_resources_target" ] + _srcjar_deps += [ ":$_process_resources_target" ] if (_native_libs_deps != []) { _enable_chromium_linker_tests = false @@ -2234,7 +2240,7 @@ ]) deps = _deps + [ ":$_build_config_target", - ":$_compile_resources_target", + ":$_process_resources_target", ":$_java_target", ] inputs = [ @@ -2292,7 +2298,7 @@ if (_enable_multidex) { extra_main_dex_proguard_config = _generated_proguard_main_dex_config - deps += [ ":$_compile_resources_target" ] + deps += [ ":$_process_resources_target" ] } # All deps are already included in _dex_sources when proguard is used. @@ -2420,7 +2426,7 @@ incremental_deps = _deps + [ ":$_merge_manifest_target", ":$_build_config_target", - ":$_compile_resources_target", + ":$_process_resources_target", ] # This target generates the input file _all_resources_zip_path. @@ -2428,7 +2434,7 @@ ":$_merge_manifest_target", ":$_build_config_target", ":$_final_dex_target_name", - ":$_compile_resources_target", + ":$_process_resources_target", ] if (_native_libs_deps != [] ||
diff --git a/cc/BUILD.gn b/cc/BUILD.gn index 6cc7ef6c..ed0afe6f 100644 --- a/cc/BUILD.gn +++ b/cc/BUILD.gn
@@ -616,6 +616,7 @@ "paint/display_item_list_unittest.cc", "paint/filter_operations_unittest.cc", "paint/oop_pixeltest.cc", + "paint/paint_filter_unittest.cc", "paint/paint_image_unittest.cc", "paint/paint_op_buffer_unittest.cc", "paint/paint_op_helper_unittest.cc",
diff --git a/cc/PRESUBMIT.py b/cc/PRESUBMIT.py index 26909c0b..3ddbde8 100644 --- a/cc/PRESUBMIT.py +++ b/cc/PRESUBMIT.py
@@ -318,6 +318,6 @@ cl, [ 'master.tryserver.blink:linux_trusty_blink_rel', - 'master.tryserver.chromium.android:android_optional_gpu_tests_rel', + 'luci.chromium.try:android_optional_gpu_tests_rel', ], 'Automatically added Blink and Android GPU trybots for CQ.')
diff --git a/cc/paint/BUILD.gn b/cc/paint/BUILD.gn index 7d72ee55..535acba 100644 --- a/cc/paint/BUILD.gn +++ b/cc/paint/BUILD.gn
@@ -24,6 +24,7 @@ "filter_operation.h", "filter_operations.cc", "filter_operations.h", + "image_analysis_state.h", "image_animation_count.h", "image_id.h", "image_provider.cc",
diff --git a/cc/paint/decode_stashing_image_provider.cc b/cc/paint/decode_stashing_image_provider.cc index e995f51..f8b4f94 100644 --- a/cc/paint/decode_stashing_image_provider.cc +++ b/cc/paint/decode_stashing_image_provider.cc
@@ -15,8 +15,8 @@ ImageProvider::ScopedDecodedDrawImage DecodeStashingImageProvider::GetDecodedDrawImage(const DrawImage& draw_image) { auto decode = source_provider_->GetDecodedDrawImage(draw_image); - if (!decode) - return ScopedDecodedDrawImage(); + if (!decode.needs_unlock()) + return decode; // No need to add any destruction callback to the returned image. The images // decoded here match the lifetime of this provider.
diff --git a/cc/paint/discardable_image_map.cc b/cc/paint/discardable_image_map.cc index e963a14..e27659a 100644 --- a/cc/paint/discardable_image_map.cc +++ b/cc/paint/discardable_image_map.cc
@@ -14,6 +14,7 @@ #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/trace_event/trace_event.h" +#include "cc/paint/paint_filter.h" #include "cc/paint/paint_op_buffer.h" #include "third_party/skia/include/utils/SkNoDrawCanvas.h" #include "ui/gfx/geometry/rect_conversions.h" @@ -124,6 +125,26 @@ } private: + class ImageGatheringProvider : public ImageProvider { + public: + ImageGatheringProvider(DiscardableImageGenerator* generator, + const gfx::Rect& op_rect) + : generator_(generator), op_rect_(op_rect) {} + ~ImageGatheringProvider() override = default; + + ScopedDecodedDrawImage GetDecodedDrawImage( + const DrawImage& draw_image) override { + generator_->AddImage(draw_image.paint_image(), + SkRect::Make(draw_image.src_rect()), op_rect_, + SkMatrix::I(), draw_image.filter_quality()); + return ScopedDecodedDrawImage(); + } + + private: + DiscardableImageGenerator* generator_; + gfx::Rect op_rect_; + }; + // Adds discardable images from |buffer| to the set of images tracked by // this generator. If |buffer| is being used in a DrawOp that requires // rasterization of the buffer as a pre-processing step for execution of the @@ -144,12 +165,13 @@ // TODO(khushalsagar): Optimize out save/restore blocks if there are no // images in the draw ops between them. for (auto* op : PaintOpBuffer::Iterator(buffer)) { - if (!op->IsDrawOp()) { + // We need to play non-draw ops on the SkCanvas since they can affect the + // transform/clip state. + if (!op->IsDrawOp()) op->Raster(canvas, params); + + if (!PaintOp::OpHasDiscardableImages(op)) continue; - } else if (!PaintOp::OpHasDiscardableImages(op)) { - continue; - } gfx::Rect op_rect; base::Optional<gfx::Rect> local_op_rect; @@ -202,9 +224,10 @@ gfx::Rect transformed_rect; SkRect op_rect; - if (!PaintOp::GetBounds(op, &op_rect)) { + if (!op->IsDrawOp() || !PaintOp::GetBounds(op, &op_rect)) { // If we can't provide a conservative bounding rect for the op, assume it // covers the complete current clip. + // TODO(khushalsagar): See if we can do something better for non-draw ops. transformed_rect = gfx::ToEnclosingRect(gfx::SkRectToRectF(clip_rect)); } else { const PaintFlags* flags = @@ -247,34 +270,48 @@ void AddImageFromFlags(const gfx::Rect& op_rect, const PaintFlags& flags, const SkMatrix& ctm) { - if (!flags.getShader()) + AddImageFromShader(op_rect, flags.getShader(), ctm, + flags.getFilterQuality()); + AddImageFromFilter(op_rect, flags.getImageFilter().get()); + } + + void AddImageFromShader(const gfx::Rect& op_rect, + const PaintShader* shader, + const SkMatrix& ctm, + SkFilterQuality filter_quality) { + if (!shader || !shader->has_discardable_images()) return; - if (flags.getShader()->shader_type() == PaintShader::Type::kImage) { - const PaintImage& paint_image = flags.getShader()->paint_image(); + if (shader->shader_type() == PaintShader::Type::kImage) { + const PaintImage& paint_image = shader->paint_image(); SkMatrix matrix = ctm; - matrix.postConcat(flags.getShader()->GetLocalMatrix()); + matrix.postConcat(shader->GetLocalMatrix()); AddImage(paint_image, SkRect::MakeWH(paint_image.width(), paint_image.height()), - op_rect, matrix, flags.getFilterQuality()); - } else if (flags.getShader()->shader_type() == - PaintShader::Type::kPaintRecord && - flags.getShader()->paint_record()->HasDiscardableImages()) { + op_rect, matrix, filter_quality); + return; + } + + if (shader->shader_type() == PaintShader::Type::kPaintRecord) { + // For record backed shaders, only analyze them if they have animated + // images. + if (shader->image_analysis_state() == + ImageAnalysisState::kNoAnimatedImages) { + return; + } + SkRect scaled_tile_rect; - if (!flags.getShader()->GetRasterizationTileRect(ctm, - &scaled_tile_rect)) { + if (!shader->GetRasterizationTileRect(ctm, &scaled_tile_rect)) { return; } PaintTrackingCanvas canvas(scaled_tile_rect.width(), scaled_tile_rect.height()); - canvas.setMatrix(SkMatrix::MakeRectToRect(flags.getShader()->tile(), - scaled_tile_rect, - SkMatrix::kFill_ScaleToFit)); - base::AutoReset<bool> auto_reset(&iterating_record_shaders_, true); + canvas.setMatrix(SkMatrix::MakeRectToRect( + shader->tile(), scaled_tile_rect, SkMatrix::kFill_ScaleToFit)); + base::AutoReset<bool> auto_reset(&only_gather_animated_images_, true); size_t prev_image_set_size = image_set_.size(); - GatherDiscardableImages(flags.getShader()->paint_record().get(), &op_rect, - &canvas); + GatherDiscardableImages(shader->paint_record().get(), &op_rect, &canvas); // We only track animated images for PaintShaders. If we added any entry // to the |image_set_|, this shader any has animated images. @@ -282,11 +319,31 @@ // PaintShader here since the analysis is done on the main thread, before // the PaintOpBuffer is used for rasterization. DCHECK_GE(image_set_.size(), prev_image_set_size); - if (image_set_.size() > prev_image_set_size) - const_cast<PaintShader*>(flags.getShader())->set_has_animated_images(); + const bool has_animated_images = image_set_.size() > prev_image_set_size; + const_cast<PaintShader*>(shader)->set_has_animated_images( + has_animated_images); } } + void AddImageFromFilter(const gfx::Rect& op_rect, const PaintFilter* filter) { + // Only analyze filters if they have animated images. + if (!filter || !filter->has_discardable_images() || + filter->image_analysis_state() == + ImageAnalysisState::kNoAnimatedImages) { + return; + } + + base::AutoReset<bool> auto_reset(&only_gather_animated_images_, true); + size_t prev_image_set_size = image_set_.size(); + ImageGatheringProvider image_provider(this, op_rect); + filter->SnapshotWithImages(&image_provider); + + DCHECK_GE(image_set_.size(), prev_image_set_size); + const bool has_animated_images = image_set_.size() > prev_image_set_size; + const_cast<PaintFilter*>(filter)->set_has_animated_images( + has_animated_images); + } + void AddImage(PaintImage paint_image, const SkRect& src_rect, const gfx::Rect& image_rect, @@ -335,7 +392,8 @@ // are animated. We defer decoding of images in record shaders to skia, but // we still need to track animated images to invalidate and advance the // animation in cc. - bool add_image = !iterating_record_shaders_ || paint_image.ShouldAnimate(); + bool add_image = + !only_gather_animated_images_ || paint_image.ShouldAnimate(); if (add_image) { image_set_.emplace_back( DrawImage(std::move(paint_image), src_irect, filter_quality, matrix), @@ -348,7 +406,7 @@ std::vector<DiscardableImageMap::AnimatedImageMetadata> animated_images_metadata_; base::flat_map<PaintImage::Id, PaintImage::DecodingMode> decoding_mode_map_; - bool iterating_record_shaders_ = false; + bool only_gather_animated_images_ = false; // Statistics about the number of images and pixels that will require color // conversion if the target color space is not sRGB.
diff --git a/cc/paint/discardable_image_map_unittest.cc b/cc/paint/discardable_image_map_unittest.cc index 72906af..72d608b 100644 --- a/cc/paint/discardable_image_map_unittest.cc +++ b/cc/paint/discardable_image_map_unittest.cc
@@ -756,9 +756,11 @@ display_list->EndPaintOfUnpaired(visible_rect); display_list->Finalize(); - EXPECT_FALSE(flags.getShader()->has_animated_images()); + EXPECT_EQ(flags.getShader()->image_analysis_state(), + ImageAnalysisState::kNoAnalysis); display_list->GenerateDiscardableImagesMetadata(); - EXPECT_TRUE(flags.getShader()->has_animated_images()); + EXPECT_EQ(flags.getShader()->image_analysis_state(), + ImageAnalysisState::kAnimatedImages); const auto& image_map = display_list->discardable_image_map(); // The image rect is set to the rect for the DrawRectOp, and only animated @@ -776,6 +778,75 @@ EXPECT_EQ(SkSize::Make(4.f, 4.f), draw_images[0].scale); } +TEST_F(DiscardableImageMapTest, CapturesImagesInPaintFilters) { + // Create the record to use in the filter. + auto filter_record = sk_make_sp<PaintOpBuffer>(); + + PaintImage static_image = CreateDiscardablePaintImage(gfx::Size(100, 100)); + filter_record->push<DrawImageOp>(static_image, 0.f, 0.f, nullptr); + + std::vector<FrameMetadata> frames = { + FrameMetadata(true, base::TimeDelta::FromMilliseconds(1)), + FrameMetadata(true, base::TimeDelta::FromMilliseconds(1))}; + PaintImage animated_image = CreateAnimatedImage(gfx::Size(100, 100), frames); + filter_record->push<DrawImageOp>(animated_image, 0.f, 0.f, nullptr); + + gfx::Rect visible_rect(500, 500); + scoped_refptr<DisplayItemList> display_list = new DisplayItemList(); + display_list->StartPaint(); + PaintFlags flags; + flags.setImageFilter(sk_make_sp<RecordPaintFilter>( + filter_record, SkRect::MakeWH(100.f, 100.f))); + display_list->push<DrawRectOp>(SkRect::MakeWH(200, 200), flags); + display_list->EndPaintOfUnpaired(visible_rect); + display_list->Finalize(); + + EXPECT_EQ(flags.getImageFilter()->image_analysis_state(), + ImageAnalysisState::kNoAnalysis); + display_list->GenerateDiscardableImagesMetadata(); + EXPECT_EQ(flags.getImageFilter()->image_analysis_state(), + ImageAnalysisState::kAnimatedImages); + const auto& image_map = display_list->discardable_image_map(); + + // The image rect is set to the rect for the DrawRectOp, and only animated + // images in a filter are tracked. + std::vector<PositionScaleDrawImage> draw_images = + GetDiscardableImagesInRect(image_map, visible_rect); + std::vector<gfx::Rect> inset_rects = InsetImageRects(draw_images); + ASSERT_EQ(draw_images.size(), 1u); + EXPECT_EQ(draw_images[0].image, animated_image); + // The position of the image is the position of the DrawRectOp that uses the + // filter. + EXPECT_EQ(gfx::Rect(200, 200), inset_rects[0]); + // Images in a filter are decoded at the original size. + EXPECT_EQ(SkSize::Make(1.f, 1.f), draw_images[0].scale); +} + +TEST_F(DiscardableImageMapTest, CapturesImagesInSaveLayers) { + PaintFlags flags; + PaintImage image = CreateDiscardablePaintImage(gfx::Size(100, 100)); + flags.setShader(PaintShader::MakeImage(image, SkShader::kClamp_TileMode, + SkShader::kClamp_TileMode, nullptr)); + + gfx::Rect visible_rect(500, 500); + scoped_refptr<DisplayItemList> display_list = new DisplayItemList(); + display_list->StartPaint(); + display_list->push<SaveLayerOp>(nullptr, &flags); + display_list->push<DrawColorOp>(SK_ColorBLUE, SkBlendMode::kSrc); + display_list->EndPaintOfUnpaired(visible_rect); + display_list->Finalize(); + + display_list->GenerateDiscardableImagesMetadata(); + const auto& image_map = display_list->discardable_image_map(); + std::vector<PositionScaleDrawImage> draw_images = + GetDiscardableImagesInRect(image_map, visible_rect); + std::vector<gfx::Rect> inset_rects = InsetImageRects(draw_images); + ASSERT_EQ(draw_images.size(), 1u); + EXPECT_EQ(draw_images[0].image, image); + EXPECT_EQ(gfx::Rect(500, 500), inset_rects[0]); + EXPECT_EQ(SkSize::Make(1.f, 1.f), draw_images[0].scale); +} + TEST_F(DiscardableImageMapTest, EmbeddedShaderWithAnimatedImages) { // Create the record with animated image to use in the shader. SkRect tile = SkRect::MakeWH(100, 100); @@ -806,8 +877,10 @@ display_list->EndPaintOfUnpaired(visible_rect); display_list->Finalize(); display_list->GenerateDiscardableImagesMetadata(); - EXPECT_TRUE(shader_with_image->has_animated_images()); - EXPECT_TRUE(shader_with_shader_with_image->has_animated_images()); + EXPECT_EQ(shader_with_image->image_analysis_state(), + ImageAnalysisState::kAnimatedImages); + EXPECT_EQ(shader_with_shader_with_image->image_analysis_state(), + ImageAnalysisState::kAnimatedImages); } TEST_F(DiscardableImageMapTest, DecodingModeHintsBasic) {
diff --git a/cc/paint/image_analysis_state.h b/cc/paint/image_analysis_state.h new file mode 100644 index 0000000..ebf085dc --- /dev/null +++ b/cc/paint/image_analysis_state.h
@@ -0,0 +1,18 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CC_PAINT_IMAGE_ANALYSIS_STATE_H_ +#define CC_PAINT_IMAGE_ANALYSIS_STATE_H_ + +namespace cc { + +enum class ImageAnalysisState { + kNoAnalysis, + kAnimatedImages, + kNoAnimatedImages, +}; + +} // namespace cc + +#endif // CC_PAINT_IMAGE_ANALYSIS_STATE_H_
diff --git a/cc/paint/paint_filter.cc b/cc/paint/paint_filter.cc index 514fb3e..947973c 100644 --- a/cc/paint/paint_filter.cc +++ b/cc/paint/paint_filter.cc
@@ -5,6 +5,7 @@ #include "cc/paint/paint_filter.h" #include "cc/paint/filter_operations.h" +#include "cc/paint/paint_image_builder.h" #include "cc/paint/paint_op_writer.h" #include "cc/paint/paint_record.h" #include "third_party/skia/include/core/SkColorFilter.h" @@ -26,6 +27,8 @@ namespace cc { namespace { +const bool kHasNoDiscardableImages = false; + bool AreFiltersEqual(const PaintFilter* one, const PaintFilter* two) { if (!one || !two) return !one && !two; @@ -36,9 +39,31 @@ return PaintOp::AreEqualEvenIfNaN(one, two); } +bool HasDiscardableImages(const sk_sp<PaintFilter>& filter) { + return filter ? filter->has_discardable_images() : false; +} + +bool HasDiscardableImages(const sk_sp<PaintFilter>* const filters, int count) { + for (int i = 0; i < count; ++i) { + if (filters[i] && filters[i]->has_discardable_images()) + return true; + } + return false; +} + +sk_sp<PaintFilter> Snapshot(const sk_sp<PaintFilter>& filter, + ImageProvider* image_provider) { + if (!filter) + return nullptr; + return filter->SnapshotWithImages(image_provider); +} + } // namespace -PaintFilter::PaintFilter(Type type, const CropRect* crop_rect) : type_(type) { +PaintFilter::PaintFilter(Type type, + const CropRect* crop_rect, + bool has_discardable_images) + : type_(type), has_discardable_images_(has_discardable_images) { if (crop_rect) crop_rect_.emplace(*crop_rect); } @@ -120,6 +145,13 @@ return total_size; } +sk_sp<PaintFilter> PaintFilter::SnapshotWithImages( + ImageProvider* image_provider) const { + if (!has_discardable_images_) + return sk_ref_sp<PaintFilter>(this); + return SnapshotWithImagesInternal(image_provider); +} + bool PaintFilter::operator==(const PaintFilter& other) const { if (type_ != other.type_) return false; @@ -211,7 +243,7 @@ sk_sp<SkColorFilter> color_filter, sk_sp<PaintFilter> input, const CropRect* crop_rect) - : PaintFilter(kType, crop_rect), + : PaintFilter(kType, crop_rect, HasDiscardableImages(input)), color_filter_(std::move(color_filter)), input_(std::move(input)) { DCHECK(color_filter_); @@ -229,6 +261,12 @@ return total_size.ValueOrDefault(0u); } +sk_sp<PaintFilter> ColorFilterPaintFilter::SnapshotWithImagesInternal( + ImageProvider* image_provider) const { + return sk_make_sp<ColorFilterPaintFilter>( + color_filter_, Snapshot(input_, image_provider), crop_rect()); +} + bool ColorFilterPaintFilter::operator==( const ColorFilterPaintFilter& other) const { return PaintOp::AreSkFlattenablesEqual(color_filter_.get(), @@ -241,7 +279,7 @@ TileMode tile_mode, sk_sp<PaintFilter> input, const CropRect* crop_rect) - : PaintFilter(kType, crop_rect), + : PaintFilter(kType, crop_rect, HasDiscardableImages(input)), sigma_x_(sigma_x), sigma_y_(sigma_y), tile_mode_(tile_mode), @@ -260,6 +298,13 @@ return total_size.ValueOrDefault(0u); } +sk_sp<PaintFilter> BlurPaintFilter::SnapshotWithImagesInternal( + ImageProvider* image_provider) const { + return sk_make_sp<BlurPaintFilter>(sigma_x_, sigma_y_, tile_mode_, + Snapshot(input_, image_provider), + crop_rect()); +} + bool BlurPaintFilter::operator==(const BlurPaintFilter& other) const { return PaintOp::AreEqualEvenIfNaN(sigma_x_, other.sigma_x_) && PaintOp::AreEqualEvenIfNaN(sigma_y_, other.sigma_y_) && @@ -275,7 +320,7 @@ ShadowMode shadow_mode, sk_sp<PaintFilter> input, const CropRect* crop_rect) - : PaintFilter(kType, crop_rect), + : PaintFilter(kType, crop_rect, HasDiscardableImages(input)), dx_(dx), dy_(dy), sigma_x_(sigma_x), @@ -298,6 +343,13 @@ return total_size.ValueOrDefault(0u); } +sk_sp<PaintFilter> DropShadowPaintFilter::SnapshotWithImagesInternal( + ImageProvider* image_provider) const { + return sk_make_sp<DropShadowPaintFilter>( + dx_, dy_, sigma_x_, sigma_y_, color_, shadow_mode_, + Snapshot(input_, image_provider), crop_rect()); +} + bool DropShadowPaintFilter::operator==( const DropShadowPaintFilter& other) const { return PaintOp::AreEqualEvenIfNaN(dx_, other.dx_) && @@ -312,7 +364,7 @@ SkScalar inset, sk_sp<PaintFilter> input, const CropRect* crop_rect) - : PaintFilter(kType, crop_rect), + : PaintFilter(kType, crop_rect, HasDiscardableImages(input)), src_rect_(src_rect), inset_(inset), input_(std::move(input)) { @@ -329,6 +381,12 @@ return total_size.ValueOrDefault(0u); } +sk_sp<PaintFilter> MagnifierPaintFilter::SnapshotWithImagesInternal( + ImageProvider* image_provider) const { + return sk_make_sp<MagnifierPaintFilter>( + src_rect_, inset_, Snapshot(input_, image_provider), crop_rect()); +} + bool MagnifierPaintFilter::operator==(const MagnifierPaintFilter& other) const { return PaintOp::AreSkRectsEqual(src_rect_, other.src_rect_) && PaintOp::AreEqualEvenIfNaN(inset_, other.inset_) && @@ -337,7 +395,9 @@ ComposePaintFilter::ComposePaintFilter(sk_sp<PaintFilter> outer, sk_sp<PaintFilter> inner) - : PaintFilter(Type::kCompose, nullptr), + : PaintFilter(Type::kCompose, + nullptr, + HasDiscardableImages(outer) || HasDiscardableImages(inner)), outer_(std::move(outer)), inner_(std::move(inner)) { cached_sk_filter_ = SkComposeImageFilter::Make(GetSkFilter(outer_.get()), @@ -353,6 +413,12 @@ return total_size.ValueOrDefault(0u); } +sk_sp<PaintFilter> ComposePaintFilter::SnapshotWithImagesInternal( + ImageProvider* image_provider) const { + return sk_make_sp<ComposePaintFilter>(Snapshot(outer_, image_provider), + Snapshot(inner_, image_provider)); +} + bool ComposePaintFilter::operator==(const ComposePaintFilter& other) const { return AreFiltersEqual(outer_.get(), other.outer_.get()) && AreFiltersEqual(inner_.get(), other.inner_.get()); @@ -363,7 +429,7 @@ SkScalar outer_max, sk_sp<PaintFilter> input, const CropRect* crop_rect) - : PaintFilter(kType, crop_rect), + : PaintFilter(kType, crop_rect, HasDiscardableImages(input)), region_(region), inner_min_(inner_min), outer_max_(outer_max), @@ -383,6 +449,13 @@ return total_size.ValueOrDefault(0u); } +sk_sp<PaintFilter> AlphaThresholdPaintFilter::SnapshotWithImagesInternal( + ImageProvider* image_provider) const { + return sk_make_sp<AlphaThresholdPaintFilter>(region_, inner_min_, outer_max_, + Snapshot(input_, image_provider), + crop_rect()); +} + bool AlphaThresholdPaintFilter::operator==( const AlphaThresholdPaintFilter& other) const { return region_ == other.region_ && @@ -395,7 +468,10 @@ sk_sp<PaintFilter> background, sk_sp<PaintFilter> foreground, const CropRect* crop_rect) - : PaintFilter(kType, crop_rect), + : PaintFilter( + kType, + crop_rect, + HasDiscardableImages(background) || HasDiscardableImages(foreground)), blend_mode_(blend_mode), background_(std::move(background)), foreground_(std::move(foreground)) { @@ -414,6 +490,13 @@ return total_size.ValueOrDefault(0u); } +sk_sp<PaintFilter> XfermodePaintFilter::SnapshotWithImagesInternal( + ImageProvider* image_provider) const { + return sk_make_sp<XfermodePaintFilter>( + blend_mode_, Snapshot(background_, image_provider), + Snapshot(foreground_, image_provider), crop_rect()); +} + bool XfermodePaintFilter::operator==(const XfermodePaintFilter& other) const { return blend_mode_ == other.blend_mode_ && AreFiltersEqual(background_.get(), other.background_.get()) && @@ -428,7 +511,10 @@ sk_sp<PaintFilter> background, sk_sp<PaintFilter> foreground, const CropRect* crop_rect) - : PaintFilter(kType, crop_rect), + : PaintFilter( + kType, + crop_rect, + HasDiscardableImages(background) || HasDiscardableImages(foreground)), k1_(k1), k2_(k2), k3_(k3), @@ -452,6 +538,14 @@ return total_size.ValueOrDefault(0u); } +sk_sp<PaintFilter> ArithmeticPaintFilter::SnapshotWithImagesInternal( + ImageProvider* image_provider) const { + return sk_make_sp<ArithmeticPaintFilter>( + k1_, k2_, k3_, k4_, enforce_pm_color_, + Snapshot(background_, image_provider), + Snapshot(foreground_, image_provider), crop_rect()); +} + bool ArithmeticPaintFilter::operator==( const ArithmeticPaintFilter& other) const { return PaintOp::AreEqualEvenIfNaN(k1_, other.k1_) && @@ -473,7 +567,7 @@ bool convolve_alpha, sk_sp<PaintFilter> input, const CropRect* crop_rect) - : PaintFilter(kType, crop_rect), + : PaintFilter(kType, crop_rect, HasDiscardableImages(input)), kernel_size_(kernel_size), gain_(gain), bias_(bias), @@ -503,6 +597,13 @@ return total_size.ValueOrDefault(0u); } +sk_sp<PaintFilter> MatrixConvolutionPaintFilter::SnapshotWithImagesInternal( + ImageProvider* image_provider) const { + return sk_make_sp<MatrixConvolutionPaintFilter>( + kernel_size_, &kernel_[0], gain_, bias_, kernel_offset_, tile_mode_, + convolve_alpha_, Snapshot(input_, image_provider), crop_rect()); +} + bool MatrixConvolutionPaintFilter::operator==( const MatrixConvolutionPaintFilter& other) const { return kernel_size_ == other.kernel_size_ && @@ -523,7 +624,10 @@ sk_sp<PaintFilter> displacement, sk_sp<PaintFilter> color, const CropRect* crop_rect) - : PaintFilter(kType, crop_rect), + : PaintFilter( + kType, + crop_rect, + HasDiscardableImages(displacement) || HasDiscardableImages(color)), channel_x_(channel_x), channel_y_(channel_y), scale_(scale), @@ -545,6 +649,13 @@ return total_size.ValueOrDefault(0u); } +sk_sp<PaintFilter> DisplacementMapEffectPaintFilter::SnapshotWithImagesInternal( + ImageProvider* image_provider) const { + return sk_make_sp<DisplacementMapEffectPaintFilter>( + channel_x_, channel_y_, scale_, Snapshot(displacement_, image_provider), + Snapshot(color_, image_provider), crop_rect()); +} + bool DisplacementMapEffectPaintFilter::operator==( const DisplacementMapEffectPaintFilter& other) const { return channel_x_ == other.channel_x_ && channel_y_ == other.channel_y_ && @@ -557,7 +668,7 @@ const SkRect& src_rect, const SkRect& dst_rect, SkFilterQuality filter_quality) - : PaintFilter(kType, nullptr), + : PaintFilter(kType, nullptr, image.IsLazyGenerated()), image_(std::move(image)), src_rect_(src_rect), dst_rect_(dst_rect), @@ -576,6 +687,26 @@ return total_size.ValueOrDefault(0u); } +sk_sp<PaintFilter> ImagePaintFilter::SnapshotWithImagesInternal( + ImageProvider* image_provider) const { + DrawImage draw_image(image_, SkIRect::MakeWH(image_.width(), image_.height()), + filter_quality_, SkMatrix::I()); + auto scoped_decoded_image = image_provider->GetDecodedDrawImage(draw_image); + if (!scoped_decoded_image) + return nullptr; + + auto decoded_sk_image = sk_ref_sp<SkImage>( + const_cast<SkImage*>(scoped_decoded_image.decoded_image().image().get())); + PaintImage decoded_paint_image = + PaintImageBuilder::WithDefault() + .set_id(image_.stable_id()) + .set_image(decoded_sk_image, PaintImage::GetNextContentId()) + .TakePaintImage(); + + return sk_make_sp<ImagePaintFilter>(std::move(decoded_paint_image), src_rect_, + dst_rect_, filter_quality_); +} + bool ImagePaintFilter::operator==(const ImagePaintFilter& other) const { return !!image_ == !!other.image_ && PaintOp::AreSkRectsEqual(src_rect_, other.src_rect_) && @@ -585,11 +716,16 @@ RecordPaintFilter::RecordPaintFilter(sk_sp<PaintRecord> record, const SkRect& record_bounds) - : PaintFilter(kType, nullptr), + : RecordPaintFilter(std::move(record), record_bounds, nullptr) {} + +RecordPaintFilter::RecordPaintFilter(sk_sp<PaintRecord> record, + const SkRect& record_bounds, + ImageProvider* image_provider) + : PaintFilter(kType, nullptr, record->HasDiscardableImages()), record_(std::move(record)), record_bounds_(record_bounds) { - cached_sk_filter_ = - SkPictureImageFilter::Make(ToSkPicture(record_, record_bounds_)); + cached_sk_filter_ = SkPictureImageFilter::Make( + ToSkPicture(record_, record_bounds_, image_provider)); } RecordPaintFilter::~RecordPaintFilter() = default; @@ -601,21 +737,35 @@ return total_size.ValueOrDefault(0u); } +sk_sp<PaintFilter> RecordPaintFilter::SnapshotWithImagesInternal( + ImageProvider* image_provider) const { + return sk_sp<RecordPaintFilter>( + new RecordPaintFilter(record_, record_bounds_, image_provider)); +} + bool RecordPaintFilter::operator==(const RecordPaintFilter& other) const { return !!record_ == !!other.record_ && PaintOp::AreSkRectsEqual(record_bounds_, other.record_bounds_); } -MergePaintFilter::MergePaintFilter(sk_sp<PaintFilter>* const filters, +MergePaintFilter::MergePaintFilter(const sk_sp<PaintFilter>* const filters, int count, const CropRect* crop_rect) - : PaintFilter(kType, crop_rect) { + : MergePaintFilter(filters, count, crop_rect, nullptr) {} + +MergePaintFilter::MergePaintFilter(const sk_sp<PaintFilter>* const filters, + int count, + const CropRect* crop_rect, + ImageProvider* image_provider) + : PaintFilter(kType, crop_rect, HasDiscardableImages(filters, count)) { std::vector<sk_sp<SkImageFilter>> sk_filters; sk_filters.reserve(count); for (int i = 0; i < count; ++i) { - inputs_->push_back(filters[i]); - sk_filters.push_back(GetSkFilter(filters[i].get())); + auto filter = + image_provider ? Snapshot(filters[i], image_provider) : filters[i]; + inputs_->push_back(std::move(filter)); + sk_filters.push_back(GetSkFilter(inputs_->back().get())); } cached_sk_filter_ = SkMergeImageFilter::Make( @@ -633,6 +783,12 @@ return total_size.ValueOrDefault(0u); } +sk_sp<PaintFilter> MergePaintFilter::SnapshotWithImagesInternal( + ImageProvider* image_provider) const { + return sk_sp<MergePaintFilter>(new MergePaintFilter( + &inputs_[0], inputs_->size(), crop_rect(), image_provider)); +} + bool MergePaintFilter::operator==(const MergePaintFilter& other) const { if (inputs_->size() != other.inputs_->size()) return false; @@ -648,7 +804,7 @@ int radius_y, sk_sp<PaintFilter> input, const CropRect* crop_rect) - : PaintFilter(kType, crop_rect), + : PaintFilter(kType, crop_rect, HasDiscardableImages(input)), morph_type_(morph_type), radius_x_(radius_x), radius_y_(radius_y), @@ -675,6 +831,13 @@ return total_size.ValueOrDefault(0u); } +sk_sp<PaintFilter> MorphologyPaintFilter::SnapshotWithImagesInternal( + ImageProvider* image_provider) const { + return sk_make_sp<MorphologyPaintFilter>(morph_type_, radius_x_, radius_y_, + Snapshot(input_, image_provider), + crop_rect()); +} + bool MorphologyPaintFilter::operator==( const MorphologyPaintFilter& other) const { return morph_type_ == other.morph_type_ && radius_x_ == other.radius_x_ && @@ -686,7 +849,7 @@ SkScalar dy, sk_sp<PaintFilter> input, const CropRect* crop_rect) - : PaintFilter(kType, crop_rect), + : PaintFilter(kType, crop_rect, HasDiscardableImages(input)), dx_(dx), dy_(dy), input_(std::move(input)) { @@ -703,6 +866,12 @@ return total_size.ValueOrDefault(0u); } +sk_sp<PaintFilter> OffsetPaintFilter::SnapshotWithImagesInternal( + ImageProvider* image_provider) const { + return sk_make_sp<OffsetPaintFilter>( + dx_, dy_, Snapshot(input_, image_provider), crop_rect()); +} + bool OffsetPaintFilter::operator==(const OffsetPaintFilter& other) const { return PaintOp::AreEqualEvenIfNaN(dx_, other.dx_) && PaintOp::AreEqualEvenIfNaN(dy_, other.dy_) && @@ -712,7 +881,7 @@ TilePaintFilter::TilePaintFilter(const SkRect& src, const SkRect& dst, sk_sp<PaintFilter> input) - : PaintFilter(kType, nullptr), + : PaintFilter(kType, nullptr, HasDiscardableImages(input)), src_(src), dst_(dst), input_(std::move(input)) { @@ -729,6 +898,12 @@ return total_size.ValueOrDefault(0u); } +sk_sp<PaintFilter> TilePaintFilter::SnapshotWithImagesInternal( + ImageProvider* image_provider) const { + return sk_make_sp<TilePaintFilter>(src_, dst_, + Snapshot(input_, image_provider)); +} + bool TilePaintFilter::operator==(const TilePaintFilter& other) const { return PaintOp::AreSkRectsEqual(src_, other.src_) && PaintOp::AreSkRectsEqual(dst_, other.dst_) && @@ -742,7 +917,7 @@ SkScalar seed, const SkISize* tile_size, const CropRect* crop_rect) - : PaintFilter(kType, crop_rect), + : PaintFilter(kType, crop_rect, kHasNoDiscardableImages), turbulence_type_(turbulence_type), base_frequency_x_(base_frequency_x), base_frequency_y_(base_frequency_y), @@ -776,6 +951,13 @@ sizeof(num_octaves_) + sizeof(seed_) + sizeof(tile_size_); } +sk_sp<PaintFilter> TurbulencePaintFilter::SnapshotWithImagesInternal( + ImageProvider* image_provider) const { + return sk_make_sp<TurbulencePaintFilter>(turbulence_type_, base_frequency_x_, + base_frequency_y_, num_octaves_, + seed_, &tile_size_, crop_rect()); +} + bool TurbulencePaintFilter::operator==( const TurbulencePaintFilter& other) const { return turbulence_type_ == other.turbulence_type_ && @@ -790,8 +972,20 @@ PaintFlagsPaintFilter::PaintFlagsPaintFilter(PaintFlags flags, const CropRect* crop_rect) - : PaintFilter(kType, crop_rect), flags_(std::move(flags)) { - cached_sk_filter_ = SkPaintImageFilter::Make(flags_.ToSkPaint(), crop_rect); + : PaintFlagsPaintFilter(std::move(flags), nullptr, crop_rect) {} + +PaintFlagsPaintFilter::PaintFlagsPaintFilter(PaintFlags flags, + ImageProvider* image_provider, + const CropRect* crop_rect) + : PaintFilter(kType, crop_rect, flags.HasDiscardableImages()), + flags_(std::move(flags)) { + if (image_provider) { + raster_flags_.emplace(&flags_, image_provider, SkMatrix::I(), 255u, + true /* create_skia_shaders */); + } + cached_sk_filter_ = SkPaintImageFilter::Make( + raster_flags_ ? raster_flags_->flags()->ToSkPaint() : flags_.ToSkPaint(), + crop_rect); } PaintFlagsPaintFilter::~PaintFlagsPaintFilter() = default; @@ -802,6 +996,12 @@ return total_size.ValueOrDefault(0u); } +sk_sp<PaintFilter> PaintFlagsPaintFilter::SnapshotWithImagesInternal( + ImageProvider* image_provider) const { + return sk_sp<PaintFilter>( + new PaintFlagsPaintFilter(flags_, image_provider, crop_rect())); +} + bool PaintFlagsPaintFilter::operator==( const PaintFlagsPaintFilter& other) const { return flags_ == other.flags_; @@ -810,7 +1010,7 @@ MatrixPaintFilter::MatrixPaintFilter(const SkMatrix& matrix, SkFilterQuality filter_quality, sk_sp<PaintFilter> input) - : PaintFilter(Type::kMatrix, nullptr), + : PaintFilter(Type::kMatrix, nullptr, HasDiscardableImages(input)), matrix_(matrix), filter_quality_(filter_quality), input_(std::move(input)) { @@ -827,6 +1027,12 @@ return total_size.ValueOrDefault(0u); } +sk_sp<PaintFilter> MatrixPaintFilter::SnapshotWithImagesInternal( + ImageProvider* image_provider) const { + return sk_make_sp<MatrixPaintFilter>(matrix_, filter_quality_, + Snapshot(input_, image_provider)); +} + bool MatrixPaintFilter::operator==(const MatrixPaintFilter& other) const { return PaintOp::AreSkMatricesEqual(matrix_, other.matrix_) && filter_quality_ == other.filter_quality_ && @@ -842,7 +1048,7 @@ SkScalar shininess, sk_sp<PaintFilter> input, const CropRect* crop_rect) - : PaintFilter(kType, crop_rect), + : PaintFilter(kType, crop_rect, HasDiscardableImages(input)), lighting_type_(lighting_type), direction_(direction), light_color_(light_color), @@ -875,6 +1081,13 @@ return total_size.ValueOrDefault(0u); } +sk_sp<PaintFilter> LightingDistantPaintFilter::SnapshotWithImagesInternal( + ImageProvider* image_provider) const { + return sk_make_sp<LightingDistantPaintFilter>( + lighting_type_, direction_, light_color_, surface_scale_, kconstant_, + shininess_, Snapshot(input_, image_provider), crop_rect()); +} + bool LightingDistantPaintFilter::operator==( const LightingDistantPaintFilter& other) const { return lighting_type_ == other.lighting_type_ && @@ -894,7 +1107,7 @@ SkScalar shininess, sk_sp<PaintFilter> input, const CropRect* crop_rect) - : PaintFilter(kType, crop_rect), + : PaintFilter(kType, crop_rect, HasDiscardableImages(input)), lighting_type_(lighting_type), location_(location), light_color_(light_color), @@ -927,6 +1140,13 @@ return total_size.ValueOrDefault(0u); } +sk_sp<PaintFilter> LightingPointPaintFilter::SnapshotWithImagesInternal( + ImageProvider* image_provider) const { + return sk_make_sp<LightingPointPaintFilter>( + lighting_type_, location_, light_color_, surface_scale_, kconstant_, + shininess_, Snapshot(input_, image_provider), crop_rect()); +} + bool LightingPointPaintFilter::operator==( const LightingPointPaintFilter& other) const { return lighting_type_ == other.lighting_type_ && @@ -949,7 +1169,7 @@ SkScalar shininess, sk_sp<PaintFilter> input, const CropRect* crop_rect) - : PaintFilter(kType, crop_rect), + : PaintFilter(kType, crop_rect, HasDiscardableImages(input)), lighting_type_(lighting_type), location_(location), target_(target), @@ -987,6 +1207,14 @@ return total_size.ValueOrDefault(0u); } +sk_sp<PaintFilter> LightingSpotPaintFilter::SnapshotWithImagesInternal( + ImageProvider* image_provider) const { + return sk_make_sp<LightingSpotPaintFilter>( + lighting_type_, location_, target_, specular_exponent_, cutoff_angle_, + light_color_, surface_scale_, kconstant_, shininess_, + Snapshot(input_, image_provider), crop_rect()); +} + bool LightingSpotPaintFilter::operator==( const LightingSpotPaintFilter& other) const { return lighting_type_ == other.lighting_type_ &&
diff --git a/cc/paint/paint_filter.h b/cc/paint/paint_filter.h index 12e3a54..57897f5 100644 --- a/cc/paint/paint_filter.h +++ b/cc/paint/paint_filter.h
@@ -12,6 +12,7 @@ #include "cc/paint/paint_export.h" #include "cc/paint/paint_flags.h" #include "cc/paint/paint_image.h" +#include "cc/paint/scoped_raster_flags.h" #include "third_party/skia/include/core/SkBlendMode.h" #include "third_party/skia/include/core/SkImageFilter.h" #include "third_party/skia/include/core/SkPoint3.h" @@ -27,6 +28,7 @@ } // namespace viz namespace cc { +class ImageProvider; class CC_PAINT_EXPORT PaintFilter : public SkRefCnt { public: @@ -102,8 +104,23 @@ return base::OptionalOrNullptr(crop_rect_); } + bool has_discardable_images() const { return has_discardable_images_; } + ImageAnalysisState image_analysis_state() const { + return image_analysis_state_; + } + void set_has_animated_images(bool has_animated_images) { + image_analysis_state_ = has_animated_images + ? ImageAnalysisState::kAnimatedImages + : ImageAnalysisState::kNoAnimatedImages; + } + virtual size_t SerializedSize() const = 0; + // Returns a snaphot of the PaintFilter with images replaced using + // |image_provider|. Note that this may return the same filter if the filter + // has no images. + sk_sp<PaintFilter> SnapshotWithImages(ImageProvider* image_provider) const; + // Note that this operation is potentially slow. It also only compares things // that are easy to compare. As an example, it doesn't compare equality of // images, rather only its existence. This is meant to be used only by tests @@ -114,7 +131,9 @@ bool operator!=(const PaintFilter& other) const { return !(*this == other); } protected: - PaintFilter(Type type, const CropRect* crop_rect); + PaintFilter(Type type, + const CropRect* crop_rect, + bool has_discardable_images); static sk_sp<SkImageFilter> GetSkFilter(const PaintFilter* paint_filter) { return paint_filter ? paint_filter->cached_sk_filter_ : nullptr; @@ -124,6 +143,8 @@ } size_t BaseSerializedSize() const; + virtual sk_sp<PaintFilter> SnapshotWithImagesInternal( + ImageProvider* image_provider) const = 0; // This should be created by each sub-class at construction time, to ensure // that subsequent access to the filter is thread-safe. @@ -138,6 +159,9 @@ const Type type_; base::Optional<CropRect> crop_rect_; + const bool has_discardable_images_; + + ImageAnalysisState image_analysis_state_ = ImageAnalysisState::kNoAnalysis; DISALLOW_COPY_AND_ASSIGN(PaintFilter); }; @@ -156,6 +180,10 @@ size_t SerializedSize() const override; bool operator==(const ColorFilterPaintFilter& other) const; + protected: + sk_sp<PaintFilter> SnapshotWithImagesInternal( + ImageProvider* image_provider) const override; + private: sk_sp<SkColorFilter> color_filter_; sk_sp<PaintFilter> input_; @@ -181,6 +209,10 @@ size_t SerializedSize() const override; bool operator==(const BlurPaintFilter& other) const; + protected: + sk_sp<PaintFilter> SnapshotWithImagesInternal( + ImageProvider* image_provider) const override; + private: SkScalar sigma_x_; SkScalar sigma_y_; @@ -213,6 +245,10 @@ size_t SerializedSize() const override; bool operator==(const DropShadowPaintFilter& other) const; + protected: + sk_sp<PaintFilter> SnapshotWithImagesInternal( + ImageProvider* image_provider) const override; + private: SkScalar dx_; SkScalar dy_; @@ -239,6 +275,10 @@ size_t SerializedSize() const override; bool operator==(const MagnifierPaintFilter& other) const; + protected: + sk_sp<PaintFilter> SnapshotWithImagesInternal( + ImageProvider* image_provider) const override; + private: SkRect src_rect_; SkScalar inset_; @@ -257,6 +297,10 @@ size_t SerializedSize() const override; bool operator==(const ComposePaintFilter& other) const; + protected: + sk_sp<PaintFilter> SnapshotWithImagesInternal( + ImageProvider* image_provider) const override; + private: sk_sp<PaintFilter> outer_; sk_sp<PaintFilter> inner_; @@ -280,6 +324,10 @@ size_t SerializedSize() const override; bool operator==(const AlphaThresholdPaintFilter& other) const; + protected: + sk_sp<PaintFilter> SnapshotWithImagesInternal( + ImageProvider* image_provider) const override; + private: SkRegion region_; SkScalar inner_min_; @@ -303,6 +351,10 @@ size_t SerializedSize() const override; bool operator==(const XfermodePaintFilter& other) const; + protected: + sk_sp<PaintFilter> SnapshotWithImagesInternal( + ImageProvider* image_provider) const override; + private: SkBlendMode blend_mode_; sk_sp<PaintFilter> background_; @@ -333,6 +385,10 @@ size_t SerializedSize() const override; bool operator==(const ArithmeticPaintFilter& other) const; + protected: + sk_sp<PaintFilter> SnapshotWithImagesInternal( + ImageProvider* image_provider) const override; + private: float k1_; float k2_; @@ -370,6 +426,10 @@ size_t SerializedSize() const override; bool operator==(const MatrixConvolutionPaintFilter& other) const; + protected: + sk_sp<PaintFilter> SnapshotWithImagesInternal( + ImageProvider* image_provider) const override; + private: SkISize kernel_size_; base::StackVector<SkScalar, 3> kernel_; @@ -403,6 +463,10 @@ size_t SerializedSize() const override; bool operator==(const DisplacementMapEffectPaintFilter& other) const; + protected: + sk_sp<PaintFilter> SnapshotWithImagesInternal( + ImageProvider* image_provider) const override; + private: ChannelSelectorType channel_x_; ChannelSelectorType channel_y_; @@ -428,6 +492,10 @@ size_t SerializedSize() const override; bool operator==(const ImagePaintFilter& other) const; + protected: + sk_sp<PaintFilter> SnapshotWithImagesInternal( + ImageProvider* image_provider) const override; + private: PaintImage image_; SkRect src_rect_; @@ -447,7 +515,15 @@ size_t SerializedSize() const override; bool operator==(const RecordPaintFilter& other) const; + protected: + sk_sp<PaintFilter> SnapshotWithImagesInternal( + ImageProvider* image_provider) const override; + private: + RecordPaintFilter(sk_sp<PaintRecord> record, + const SkRect& record_bounds, + ImageProvider* image_provider); + sk_sp<PaintRecord> record_; SkRect record_bounds_; }; @@ -455,7 +531,7 @@ class CC_PAINT_EXPORT MergePaintFilter final : public PaintFilter { public: static constexpr Type kType = Type::kMerge; - MergePaintFilter(sk_sp<PaintFilter>* const filters, + MergePaintFilter(const sk_sp<PaintFilter>* const filters, int count, const CropRect* crop_rect = nullptr); ~MergePaintFilter() override; @@ -469,7 +545,15 @@ size_t SerializedSize() const override; bool operator==(const MergePaintFilter& other) const; + protected: + sk_sp<PaintFilter> SnapshotWithImagesInternal( + ImageProvider* image_provider) const override; + private: + MergePaintFilter(const sk_sp<PaintFilter>* const filters, + int count, + const CropRect* crop_rect, + ImageProvider* image_provider); base::StackVector<sk_sp<PaintFilter>, 2> inputs_; }; @@ -492,6 +576,10 @@ size_t SerializedSize() const override; bool operator==(const MorphologyPaintFilter& other) const; + protected: + sk_sp<PaintFilter> SnapshotWithImagesInternal( + ImageProvider* image_provider) const override; + private: MorphType morph_type_; int radius_x_; @@ -515,6 +603,10 @@ size_t SerializedSize() const override; bool operator==(const OffsetPaintFilter& other) const; + protected: + sk_sp<PaintFilter> SnapshotWithImagesInternal( + ImageProvider* image_provider) const override; + private: SkScalar dx_; SkScalar dy_; @@ -536,6 +628,10 @@ size_t SerializedSize() const override; bool operator==(const TilePaintFilter& other) const; + protected: + sk_sp<PaintFilter> SnapshotWithImagesInternal( + ImageProvider* image_provider) const override; + private: SkRect src_; SkRect dst_; @@ -569,6 +665,10 @@ size_t SerializedSize() const override; bool operator==(const TurbulencePaintFilter& other) const; + protected: + sk_sp<PaintFilter> SnapshotWithImagesInternal( + ImageProvider* image_provider) const override; + private: TurbulenceType turbulence_type_; SkScalar base_frequency_x_; @@ -590,8 +690,17 @@ size_t SerializedSize() const override; bool operator==(const PaintFlagsPaintFilter& other) const; + protected: + sk_sp<PaintFilter> SnapshotWithImagesInternal( + ImageProvider* image_provider) const override; + private: + PaintFlagsPaintFilter(PaintFlags flags, + ImageProvider* image_provider, + const CropRect* crop_rect); + PaintFlags flags_; + base::Optional<ScopedRasterFlags> raster_flags_; }; class CC_PAINT_EXPORT MatrixPaintFilter final : public PaintFilter { @@ -609,6 +718,10 @@ size_t SerializedSize() const override; bool operator==(const MatrixPaintFilter& other) const; + protected: + sk_sp<PaintFilter> SnapshotWithImagesInternal( + ImageProvider* image_provider) const override; + private: SkMatrix matrix_; SkFilterQuality filter_quality_; @@ -642,6 +755,10 @@ size_t SerializedSize() const override; bool operator==(const LightingDistantPaintFilter& other) const; + protected: + sk_sp<PaintFilter> SnapshotWithImagesInternal( + ImageProvider* image_provider) const override; + private: LightingType lighting_type_; SkPoint3 direction_; @@ -679,6 +796,10 @@ size_t SerializedSize() const override; bool operator==(const LightingPointPaintFilter& other) const; + protected: + sk_sp<PaintFilter> SnapshotWithImagesInternal( + ImageProvider* image_provider) const override; + private: LightingType lighting_type_; SkPoint3 location_; @@ -722,6 +843,10 @@ size_t SerializedSize() const override; bool operator==(const LightingSpotPaintFilter& other) const; + protected: + sk_sp<PaintFilter> SnapshotWithImagesInternal( + ImageProvider* image_provider) const override; + private: LightingType lighting_type_; SkPoint3 location_;
diff --git a/cc/paint/paint_filter_unittest.cc b/cc/paint/paint_filter_unittest.cc new file mode 100644 index 0000000..de1ea451 --- /dev/null +++ b/cc/paint/paint_filter_unittest.cc
@@ -0,0 +1,197 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "cc/paint/paint_filter.h" + +#include "cc/paint/paint_op_buffer.h" +#include "cc/test/skia_common.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/skia/include/effects/SkLumaColorFilter.h" + +namespace cc { +namespace { + +class MockImageProvider : public ImageProvider { + public: + MockImageProvider() = default; + ~MockImageProvider() override = default; + + ScopedDecodedDrawImage GetDecodedDrawImage( + const DrawImage& draw_image) override { + image_count_++; + return ScopedDecodedDrawImage(DecodedDrawImage( + CreateBitmapImage(gfx::Size(10, 10)).GetSkImage(), SkSize::MakeEmpty(), + SkSize::Make(1.0f, 1.0f), draw_image.filter_quality(), true)); + } + int image_count_ = 0; +}; + +sk_sp<PaintFilter> CreateTestFilter(PaintFilter::Type filter_type, + bool has_discardable_images) { + PaintImage image; + if (has_discardable_images) + image = CreateDiscardablePaintImage(gfx::Size(100, 100)); + else + image = CreateBitmapImage(gfx::Size(100, 100)); + + auto image_filter = sk_make_sp<ImagePaintFilter>( + image, SkRect::MakeWH(100.f, 100.f), SkRect::MakeWH(100.f, 100.f), + kNone_SkFilterQuality); + auto record = sk_make_sp<PaintOpBuffer>(); + record->push<DrawImageOp>(image, 0.f, 0.f, nullptr); + auto record_filter = + sk_make_sp<RecordPaintFilter>(record, SkRect::MakeWH(100.f, 100.f)); + + SkImageFilter::CropRect crop_rect(SkRect::MakeWH(100.f, 100.f)); + + switch (filter_type) { + case PaintFilter::Type::kNullFilter: + NOTREACHED(); + return nullptr; + case PaintFilter::Type::kColorFilter: + return sk_make_sp<ColorFilterPaintFilter>(SkLumaColorFilter::Make(), + image_filter, &crop_rect); + case PaintFilter::Type::kBlur: + return sk_make_sp<BlurPaintFilter>(0.1f, 0.2f, + SkBlurImageFilter::kClamp_TileMode, + record_filter, &crop_rect); + case PaintFilter::Type::kDropShadow: + return sk_make_sp<DropShadowPaintFilter>( + 0.1, 0.2f, 0.3f, 0.4f, SK_ColorWHITE, + SkDropShadowImageFilter::kDrawShadowOnly_ShadowMode, image_filter, + &crop_rect); + case PaintFilter::Type::kMagnifier: + return sk_make_sp<MagnifierPaintFilter>(SkRect::MakeWH(100.f, 100.f), + 0.1f, record_filter, &crop_rect); + case PaintFilter::Type::kCompose: + return sk_make_sp<ComposePaintFilter>(image_filter, record_filter); + case PaintFilter::Type::kAlphaThreshold: + return sk_make_sp<AlphaThresholdPaintFilter>( + SkRegion(SkIRect::MakeWH(100, 100)), 0.1f, 0.2f, image_filter, + &crop_rect); + case PaintFilter::Type::kXfermode: + return sk_make_sp<XfermodePaintFilter>(SkBlendMode::kSrc, image_filter, + record_filter, &crop_rect); + case PaintFilter::Type::kArithmetic: + return sk_make_sp<ArithmeticPaintFilter>(0.1f, 0.2f, 0.3f, 0.4f, true, + image_filter, record_filter, + &crop_rect); + case PaintFilter::Type::kMatrixConvolution: { + SkScalar scalars[9] = {1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f, 9.f}; + return sk_make_sp<MatrixConvolutionPaintFilter>( + SkISize::Make(3, 3), scalars, 0.1f, 0.2f, SkIPoint::Make(2, 2), + SkMatrixConvolutionImageFilter::TileMode::kRepeat_TileMode, false, + image_filter, &crop_rect); + } + case PaintFilter::Type::kDisplacementMapEffect: + return sk_make_sp<DisplacementMapEffectPaintFilter>( + SkDisplacementMapEffect::ChannelSelectorType::kR_ChannelSelectorType, + SkDisplacementMapEffect::ChannelSelectorType::kR_ChannelSelectorType, + 0.1f, image_filter, record_filter, &crop_rect); + case PaintFilter::Type::kImage: + return image_filter; + case PaintFilter::Type::kPaintRecord: + return record_filter; + case PaintFilter::Type::kMerge: { + sk_sp<PaintFilter> filters[2] = {image_filter, record_filter}; + return sk_make_sp<MergePaintFilter>(filters, 2, &crop_rect); + } + case PaintFilter::Type::kMorphology: + return sk_make_sp<MorphologyPaintFilter>( + MorphologyPaintFilter::MorphType::kDilate, 1, 2, image_filter, + &crop_rect); + case PaintFilter::Type::kOffset: + return sk_make_sp<OffsetPaintFilter>(0.1f, 0.2f, image_filter, + &crop_rect); + case PaintFilter::Type::kTile: + return sk_make_sp<TilePaintFilter>(SkRect::MakeWH(100.f, 100.f), + SkRect::MakeWH(200.f, 200.f), + record_filter); + case PaintFilter::Type::kTurbulence: + return sk_make_sp<TurbulencePaintFilter>( + TurbulencePaintFilter::TurbulenceType::kTurbulence, 0.1f, 0.2f, 2, + 0.3f, nullptr, &crop_rect); + case PaintFilter::Type::kPaintFlags: { + PaintFlags flags; + flags.setShader(PaintShader::MakeImage(image, SkShader::kClamp_TileMode, + SkShader::kClamp_TileMode, + nullptr)); + return sk_make_sp<PaintFlagsPaintFilter>(flags, &crop_rect); + } + case PaintFilter::Type::kMatrix: + return sk_make_sp<MatrixPaintFilter>(SkMatrix::I(), kNone_SkFilterQuality, + record_filter); + case PaintFilter::Type::kLightingDistant: + return sk_make_sp<LightingDistantPaintFilter>( + PaintFilter::LightingType::kDiffuse, SkPoint3::Make(0.1f, 0.2f, 0.3f), + SK_ColorWHITE, 0.1f, 0.2f, 0.3f, image_filter, &crop_rect); + case PaintFilter::Type::kLightingPoint: + return sk_make_sp<LightingPointPaintFilter>( + PaintFilter::LightingType::kDiffuse, SkPoint3::Make(0.1f, 0.2f, 0.3f), + SK_ColorWHITE, 0.1f, 0.2f, 0.3f, record_filter, &crop_rect); + case PaintFilter::Type::kLightingSpot: + return sk_make_sp<LightingSpotPaintFilter>( + PaintFilter::LightingType::kDiffuse, SkPoint3::Make(0.1f, 0.2f, 0.3f), + SkPoint3::Make(0.4f, 0.5f, 0.6f), 0.1f, 0.2f, SK_ColorWHITE, 0.4f, + 0.5f, 0.6f, image_filter, &crop_rect); + } + NOTREACHED(); + return nullptr; +} + +} // namespace + +class PaintFilterTest : public ::testing::TestWithParam<uint8_t> { + public: + PaintFilter::Type GetParamType() const { + return static_cast<PaintFilter::Type>(GetParam()); + } +}; + +INSTANTIATE_TEST_CASE_P( + P, + PaintFilterTest, + ::testing::Range(static_cast<uint8_t>(PaintFilter::Type::kColorFilter), + static_cast<uint8_t>(PaintFilter::Type::kMaxFilterType))); + +TEST_P(PaintFilterTest, HasDiscardableImagesYes) { + // TurbulencePaintFilter can not embed images. + if (GetParamType() == PaintFilter::Type::kTurbulence) + return; + + EXPECT_TRUE(CreateTestFilter(GetParamType(), true)->has_discardable_images()) + << PaintFilter::TypeToString(GetParamType()); +} + +TEST_P(PaintFilterTest, HasDiscardableImagesNo) { + EXPECT_FALSE( + CreateTestFilter(GetParamType(), false)->has_discardable_images()) + << PaintFilter::TypeToString(GetParamType()); +} + +TEST_P(PaintFilterTest, SnapshotWithImages) { + auto filter = CreateTestFilter(GetParamType(), true); + MockImageProvider image_provider; + auto snapshot_filter = filter->SnapshotWithImages(&image_provider); + if (GetParamType() != PaintFilter::Type::kTurbulence) { + // TurbulencePaintFilter can not embed images. + EXPECT_GT(image_provider.image_count_, 0) + << PaintFilter::TypeToString(GetParamType()); + } + EXPECT_EQ(*filter, *snapshot_filter) + << PaintFilter::TypeToString(GetParamType()); +} + +TEST(PaintFilterTest, ImageAnalysisState) { + auto filter = CreateTestFilter(PaintFilter::Type::kImage, true); + EXPECT_EQ(filter->image_analysis_state(), ImageAnalysisState::kNoAnalysis); + filter->set_has_animated_images(true); + EXPECT_EQ(filter->image_analysis_state(), + ImageAnalysisState::kAnimatedImages); + filter->set_has_animated_images(false); + EXPECT_EQ(filter->image_analysis_state(), + ImageAnalysisState::kNoAnimatedImages); +} + +} // namespace cc
diff --git a/cc/paint/paint_flags.cc b/cc/paint/paint_flags.cc index 3a75c09f..e194750 100644 --- a/cc/paint/paint_flags.cc +++ b/cc/paint/paint_flags.cc
@@ -199,13 +199,8 @@ } bool PaintFlags::HasDiscardableImages() const { - if (!shader_) - return false; - else if (shader_->shader_type() == PaintShader::Type::kImage) - return shader_->paint_image().IsLazyGenerated(); - else if (shader_->shader_type() == PaintShader::Type::kPaintRecord) - return shader_->paint_record()->HasDiscardableImages(); - return false; + return (shader_ && shader_->has_discardable_images()) || + (image_filter_ && image_filter_->has_discardable_images()); } size_t PaintFlags::GetSerializedSize() const {
diff --git a/cc/paint/paint_op_buffer.cc b/cc/paint/paint_op_buffer.cc index 3ec40ab..e5ca5c1 100644 --- a/cc/paint/paint_op_buffer.cc +++ b/cc/paint/paint_op_buffer.cc
@@ -1893,7 +1893,8 @@ // static bool PaintOp::QuickRejectDraw(const PaintOp* op, const SkCanvas* canvas) { - DCHECK(op->IsDrawOp()); + if (!op->IsDrawOp()) + return false; SkRect rect; if (!PaintOp::GetBounds(op, &rect)) @@ -1937,7 +1938,7 @@ } bool PaintOpWithFlags::HasDiscardableImagesFromFlags() const { - return IsDrawOp() && flags.HasDiscardableImages(); + return flags.HasDiscardableImages(); } void PaintOpWithFlags::RasterWithFlags(SkCanvas* canvas,
diff --git a/cc/paint/paint_op_buffer_unittest.cc b/cc/paint/paint_op_buffer_unittest.cc index 520b354..7c6ce78 100644 --- a/cc/paint/paint_op_buffer_unittest.cc +++ b/cc/paint/paint_op_buffer_unittest.cc
@@ -3101,7 +3101,7 @@ record_buffer, SkRect::MakeWH(10.f, 10.f), SkShader::TileMode::kRepeat_TileMode, SkShader::TileMode::kRepeat_TileMode, nullptr); - shader->set_has_animated_images(); + shader->set_has_animated_images(true); auto buffer = sk_make_sp<PaintOpBuffer>(); buffer->push<ScaleOp>(0.5f, 0.8f); PaintFlags flags;
diff --git a/cc/paint/paint_record.cc b/cc/paint/paint_record.cc index 9593bbb..6609e82 100644 --- a/cc/paint/paint_record.cc +++ b/cc/paint/paint_record.cc
@@ -9,18 +9,23 @@ namespace cc { -sk_sp<SkPicture> ToSkPicture(sk_sp<PaintRecord> record, const SkRect& bounds) { +sk_sp<SkPicture> ToSkPicture(sk_sp<PaintRecord> record, + const SkRect& bounds, + ImageProvider* image_provider) { SkPictureRecorder recorder; SkCanvas* canvas = recorder.beginRecording(bounds); - record->Playback(canvas); + PlaybackParams params(image_provider); + record->Playback(canvas, params); return recorder.finishRecordingAsPicture(); } sk_sp<const SkPicture> ToSkPicture(sk_sp<const PaintRecord> record, - const SkRect& bounds) { + const SkRect& bounds, + ImageProvider* image_provider) { SkPictureRecorder recorder; SkCanvas* canvas = recorder.beginRecording(bounds); - record->Playback(canvas); + PlaybackParams params(image_provider); + record->Playback(canvas, params); return recorder.finishRecordingAsPicture(); }
diff --git a/cc/paint/paint_record.h b/cc/paint/paint_record.h index 1509bac..6e0c1d7 100644 --- a/cc/paint/paint_record.h +++ b/cc/paint/paint_record.h
@@ -10,6 +10,7 @@ #include "third_party/skia/include/core/SkPicture.h" namespace cc { +class ImageProvider; // TODO(enne): Don't want to rename the world for this. Using these as the // same types for now prevents an extra allocation. Probably PaintRecord @@ -17,12 +18,15 @@ using PaintRecord = PaintOpBuffer; // TODO(enne): Remove these if possible, they are really expensive. -CC_PAINT_EXPORT sk_sp<SkPicture> ToSkPicture(sk_sp<PaintRecord> record, - const SkRect& bounds); +CC_PAINT_EXPORT sk_sp<SkPicture> ToSkPicture( + sk_sp<PaintRecord> record, + const SkRect& bounds, + ImageProvider* image_provider = nullptr); CC_PAINT_EXPORT sk_sp<const SkPicture> ToSkPicture( sk_sp<const PaintRecord> record, - const SkRect& bounds); + const SkRect& bounds, + ImageProvider* image_provider = nullptr); } // namespace cc
diff --git a/cc/paint/paint_shader.cc b/cc/paint/paint_shader.cc index dccf2ca3..a53c6ed 100644 --- a/cc/paint/paint_shader.cc +++ b/cc/paint/paint_shader.cc
@@ -186,6 +186,11 @@ PaintShader::PaintShader(Type type) : shader_type_(type) {} PaintShader::~PaintShader() = default; +bool PaintShader::has_discardable_images() const { + return (image_ && image_.IsLazyGenerated()) || + (record_ && record_->HasDiscardableImages()); +} + bool PaintShader::GetRasterizationTileRect(const SkMatrix& ctm, SkRect* tile_rect) const { DCHECK_EQ(shader_type_, Type::kPaintRecord);
diff --git a/cc/paint/paint_shader.h b/cc/paint/paint_shader.h index 4fffd255..6c197b7 100644 --- a/cc/paint/paint_shader.h +++ b/cc/paint/paint_shader.h
@@ -10,6 +10,7 @@ #include "base/optional.h" #include "base/stl_util.h" +#include "cc/paint/image_analysis_state.h" #include "cc/paint/paint_export.h" #include "cc/paint/paint_image.h" #include "third_party/skia/include/core/SkImage.h" @@ -106,8 +107,16 @@ ~PaintShader() override; - void set_has_animated_images() { has_animated_images_ = true; } - bool has_animated_images() const { return has_animated_images_; } + void set_has_animated_images(bool has_animated_images) { + image_analysis_state_ = has_animated_images + ? ImageAnalysisState::kAnimatedImages + : ImageAnalysisState::kNoAnimatedImages; + } + ImageAnalysisState image_analysis_state() const { + return image_analysis_state_; + } + + bool has_discardable_images() const; SkMatrix GetLocalMatrix() const { return local_matrix_ ? *local_matrix_ : SkMatrix::I(); @@ -200,7 +209,7 @@ // accesses to it are thread-safe. sk_sp<SkShader> cached_shader_; - bool has_animated_images_ = false; + ImageAnalysisState image_analysis_state_ = ImageAnalysisState::kNoAnalysis; DISALLOW_COPY_AND_ASSIGN(PaintShader); };
diff --git a/cc/paint/paint_shader_unittest.cc b/cc/paint/paint_shader_unittest.cc index 55ce7c5..ac6f9e0 100644 --- a/cc/paint/paint_shader_unittest.cc +++ b/cc/paint/paint_shader_unittest.cc
@@ -84,7 +84,7 @@ auto record_shader = PaintShader::MakePaintRecord( record, SkRect::MakeWH(100, 100), SkShader::TileMode::kClamp_TileMode, SkShader::TileMode::kClamp_TileMode, &local_matrix); - record_shader->set_has_animated_images(); + record_shader->set_has_animated_images(true); PaintOpBuffer buffer; PaintFlags flags;
diff --git a/cc/paint/scoped_raster_flags.cc b/cc/paint/scoped_raster_flags.cc index 6e45512..e8590ac 100644 --- a/cc/paint/scoped_raster_flags.cc +++ b/cc/paint/scoped_raster_flags.cc
@@ -5,6 +5,7 @@ #include "cc/paint/scoped_raster_flags.h" #include "cc/paint/image_provider.h" +#include "cc/paint/paint_filter.h" #include "cc/paint/paint_image_builder.h" namespace cc { @@ -15,20 +16,13 @@ bool create_skia_shader) : original_flags_(flags) { if (flags->HasDiscardableImages() && image_provider) { - DCHECK(flags->HasShader()); - // TODO(khushalsagar): The decoding of images in PaintFlags here is a bit of // a mess. We decode image shaders at the correct scale but ignore that // during serialization and just use the original image. decode_stashing_image_provider_.emplace(image_provider); - if (flags->getShader()->shader_type() == PaintShader::Type::kImage) { - DecodeImageShader(ctm); - } else if (flags->getShader()->shader_type() == - PaintShader::Type::kPaintRecord) { - DecodeRecordShader(ctm, create_skia_shader); - } else { - NOTREACHED(); - } + DecodeImageShader(ctm); + DecodeRecordShader(ctm, create_skia_shader); + DecodeFilter(); // We skip the op if any images fail to decode. if (decode_failed_) @@ -46,6 +40,10 @@ ScopedRasterFlags::~ScopedRasterFlags() = default; void ScopedRasterFlags::DecodeImageShader(const SkMatrix& ctm) { + if (!flags()->HasShader() || + flags()->getShader()->shader_type() != PaintShader::Type::kImage) + return; + const PaintImage& paint_image = flags()->getShader()->paint_image(); SkMatrix matrix = flags()->getShader()->GetLocalMatrix(); @@ -100,9 +98,14 @@ void ScopedRasterFlags::DecodeRecordShader(const SkMatrix& ctm, bool create_skia_shader) { + if (!flags()->HasShader() || + flags()->getShader()->shader_type() != PaintShader::Type::kPaintRecord) + return; + // TODO(khushalsagar): For OOP, we have to decode everything during // serialization. This will force us to use original sized decodes. - if (!flags()->getShader()->has_animated_images()) + if (flags()->getShader()->image_analysis_state() != + ImageAnalysisState::kAnimatedImages) return; auto decoded_shader = flags()->getShader()->CreateDecodedPaintRecord( @@ -117,6 +120,18 @@ MutableFlags()->setShader(std::move(decoded_shader)); } +void ScopedRasterFlags::DecodeFilter() { + if (!flags()->getImageFilter() || + !flags()->getImageFilter()->has_discardable_images() || + flags()->getImageFilter()->image_analysis_state() != + ImageAnalysisState::kAnimatedImages) { + return; + } + + MutableFlags()->setImageFilter(flags()->getImageFilter()->SnapshotWithImages( + &*decode_stashing_image_provider_)); +} + void ScopedRasterFlags::AdjustStrokeIfNeeded(const SkMatrix& ctm) { // With anti-aliasing turned off, strokes with a device space width in (0, 1) // may not raster at all. To avoid this, we have two options:
diff --git a/cc/paint/scoped_raster_flags.h b/cc/paint/scoped_raster_flags.h index 5b2f859..5b8185b1 100644 --- a/cc/paint/scoped_raster_flags.h +++ b/cc/paint/scoped_raster_flags.h
@@ -37,6 +37,7 @@ private: void DecodeImageShader(const SkMatrix& ctm); void DecodeRecordShader(const SkMatrix& ctm, bool create_skia_shader); + void DecodeFilter(); void AdjustStrokeIfNeeded(const SkMatrix& ctm); PaintFlags* MutableFlags() {
diff --git a/cc/paint/scoped_raster_flags_unittest.cc b/cc/paint/scoped_raster_flags_unittest.cc index c912d07..b0ac265 100644 --- a/cc/paint/scoped_raster_flags_unittest.cc +++ b/cc/paint/scoped_raster_flags_unittest.cc
@@ -54,7 +54,7 @@ auto record_shader = PaintShader::MakePaintRecord( record, SkRect::MakeWH(100, 100), SkShader::TileMode::kClamp_TileMode, SkShader::TileMode::kClamp_TileMode, &SkMatrix::I()); - record_shader->set_has_animated_images(); + record_shader->set_has_animated_images(true); MockImageProvider provider; PaintFlags flags;
diff --git a/cc/trees/layer_tree_host_unittest.cc b/cc/trees/layer_tree_host_unittest.cc index 6a436bf1..8e7da40a 100644 --- a/cc/trees/layer_tree_host_unittest.cc +++ b/cc/trees/layer_tree_host_unittest.cc
@@ -8594,6 +8594,20 @@ MULTI_THREAD_TEST_F(LayerTreeHostTestImageAnimationDrawRecordShader); +class LayerTreeHostTestImageAnimationPaintFilter + : public LayerTreeHostTestImageAnimation { + void AddImageOp(const PaintImage& image) override { + auto record = sk_make_sp<PaintOpBuffer>(); + record->push<DrawImageOp>(image, 0.f, 0.f, nullptr); + PaintFlags flags; + flags.setImageFilter( + sk_make_sp<RecordPaintFilter>(record, SkRect::MakeWH(500, 500))); + content_layer_client_.add_draw_rect(gfx::Rect(500, 500), flags); + } +}; + +MULTI_THREAD_TEST_F(LayerTreeHostTestImageAnimationPaintFilter); + class LayerTreeHostTestImageAnimationSynchronousScheduling : public LayerTreeHostTestImageAnimationDrawImage { public:
diff --git a/chrome/VERSION b/chrome/VERSION index a4261225..cf09b30 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=67 MINOR=0 -BUILD=3377 +BUILD=3378 PATCH=0
diff --git a/chrome/android/chrome_public_apk_tmpl.gni b/chrome/android/chrome_public_apk_tmpl.gni index a63ae884..cd5bb69d 100644 --- a/chrome/android/chrome_public_apk_tmpl.gni +++ b/chrome/android/chrome_public_apk_tmpl.gni
@@ -112,7 +112,7 @@ } alternative_android_sdk_jar = webview_framework_jar - shared_resources = true + app_as_shared_lib = true use_chromium_linker = false requires_sdk_api_level_23 = true
diff --git a/chrome/android/java/res/layout/new_tab_page_snippets_expandable_header.xml b/chrome/android/java/res/layout/new_tab_page_snippets_expandable_header.xml index affa7d1..a7d2180 100644 --- a/chrome/android/java/res/layout/new_tab_page_snippets_expandable_header.xml +++ b/chrome/android/java/res/layout/new_tab_page_snippets_expandable_header.xml
@@ -17,6 +17,7 @@ android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" + android:textAlignment="viewStart" android:textAppearance="@style/BlackCaption" /> <org.chromium.chrome.browser.widget.TintedImageView
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/IntentHandler.java b/chrome/android/java/src/org/chromium/chrome/browser/IntentHandler.java index dfc463b9..f6318a5 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/IntentHandler.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/IntentHandler.java
@@ -14,6 +14,7 @@ import android.content.Context; import android.content.Intent; import android.net.Uri; +import android.os.Build; import android.os.Bundle; import android.os.SystemClock; import android.provider.Browser; @@ -412,6 +413,7 @@ String referrerUrl = getReferrerUrlIncludingExtraHeaders(intent); String extraHeaders = getExtraHeadersFromIntent(intent); + extraHeaders = maybeAddAdditionalExtraHeaders(intent, url, extraHeaders); // TODO(joth): Presumably this should check the action too. mDelegate.processUrlViewIntent(url, referrerUrl, extraHeaders, tabOpenType, @@ -677,6 +679,8 @@ String key = keys.next(); String value = bundleExtraHeaders.getString(key); if ("referer".equals(key.toLowerCase(Locale.US))) continue; + // Strip the custom header that can only be added by ourselves. + if ("x-chrome-intent-type".equals(key.toLowerCase(Locale.US))) continue; if (extraHeaders.length() != 0) extraHeaders.append("\n"); extraHeaders.append(key); extraHeaders.append(": "); @@ -1008,6 +1012,30 @@ ? data.getQuery() : null; } + @VisibleForTesting + static String maybeAddAdditionalExtraHeaders(Intent intent, String url, String extraHeaders) { + // On Oreo, ContentResolver.getType(contentUri) returns "application/octet-stream", instead + // of the registered MIME type when opening a document from Downloads. To work around this, + // we pass the intent type in extra headers such that content request job can get it. + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return extraHeaders; + if (intent == null || url == null) return extraHeaders; + + String scheme = getSanitizedUrlScheme(url); + if (!TextUtils.equals(scheme, UrlConstants.CONTENT_SCHEME)) return extraHeaders; + + Uri uri = Uri.parse(url); + if (uri == null + || !"com.android.providers.downloads.documents".equals(uri.getAuthority())) { + return extraHeaders; + } + + String type = intent.getType(); + if (type == null || type.isEmpty()) return extraHeaders; + + String typeHeader = "X-Chrome-intent-type: " + type; + return (extraHeaders == null) ? typeHeader : (extraHeaders + "\n" + typeHeader); + } + /** * Adjusts the URL to account for the googlechrome:// scheme. * Currently, its only use is to handle navigations, only http and https URL is allowed.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/phone/StackLayoutBase.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/phone/StackLayoutBase.java index 1c1464cd..3d02c6b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/phone/StackLayoutBase.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/phone/StackLayoutBase.java
@@ -818,15 +818,20 @@ float switchDelta = getOrientation() == Orientation.PORTRAIT ? relativeX : relativeY; // In LTR portrait mode, the first stack can be swiped to the left to switch to the second - // stack, and the second stack can be swiped to the right to switch to the first stack. We + // stack, and the last stack can be swiped to the right to switch to the first stack. We // reverse the check for RTL portrait mode because increasing the stack index corresponds - // to a negative switchDelta. + // to a negative switchDelta. If there are more than two stacks, we do not currently support + // swiping to close on any of the stacks in the middle // // Landscape mode is like LTR portrait mode (increasing the stack index corresponds to a // positive switchDelta). final boolean isRtlPortraitMode = (getOrientation() == Orientation.PORTRAIT && LocalizationUtils.isLayoutRtl()); - if ((currentIndex == 0) ^ (switchDelta > 0) ^ isRtlPortraitMode) { + final boolean onLeftmostStack = (currentIndex == 0 && !isRtlPortraitMode) + || (currentIndex == mStacks.size() - 1 && isRtlPortraitMode); + final boolean onRightmostStack = (currentIndex == 0 && isRtlPortraitMode) + || (currentIndex == mStacks.size() - 1 && !isRtlPortraitMode); + if ((onLeftmostStack && switchDelta < 0) || (onRightmostStack && switchDelta > 0)) { // Dragging in a direction the stack cannot switch. Pass the drag to the Stack, which // will treat it as intending to discard a tab. return SWIPE_MODE_SEND_TO_STACK;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/service/DownloadBackgroundTask.java b/chrome/android/java/src/org/chromium/chrome/browser/download/service/DownloadBackgroundTask.java index dffab18..1f6457b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/service/DownloadBackgroundTask.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/service/DownloadBackgroundTask.java
@@ -65,6 +65,8 @@ Callback<Boolean> wrappedCallback = new Callback<Boolean>() { @Override public void onResult(Boolean needsReschedule) { + if (mPendingTaskCounters.get(taskType) == null) return; + boolean noPendingCallbacks = decrementPendingCallbackCount(taskType, needsReschedule); if (noPendingCallbacks) {
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/IntentHandlerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/IntentHandlerTest.java index 3f862a745..42cb3bf 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/IntentHandlerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/IntentHandlerTest.java
@@ -7,6 +7,7 @@ import android.content.Context; import android.content.Intent; import android.net.Uri; +import android.os.Build; import android.os.Bundle; import android.os.SystemClock; import android.provider.Browser; @@ -345,4 +346,59 @@ String referrer = IntentHandler.constructValidReferrerForAuthority(packageName).getUrl(); Assert.assertEquals("android-app://" + packageName, referrer); } + + @Test + @SmallTest + @UiThreadTest + @Feature({"Android-AppBase"}) + public void testRemoveChromeCustomHeaderFromExtraIntentHeaders() throws Throwable { + Bundle bundle = new Bundle(); + bundle.putString("X-Chrome-intent-type", "X-custom-value"); + Intent headersIntent = new Intent(Intent.ACTION_VIEW); + headersIntent.putExtra(Browser.EXTRA_HEADERS, bundle); + Assert.assertNull(IntentHandler.getExtraHeadersFromIntent(headersIntent)); + } + + @Test + @SmallTest + @Feature({"Android-AppBase"}) + public void testMaybeAddAdditionalExtraHeaders() { + String downloadContentUrl = + "content://com.android.providers.downloads.documents/document/1"; + String otherContentUrl = "content://com.example.org/document/1"; + Intent intent = new Intent(); + + Assert.assertNull(IntentHandler.maybeAddAdditionalExtraHeaders(null, null, null)); + // Null URL. + Assert.assertNull(IntentHandler.maybeAddAdditionalExtraHeaders(intent, null, null)); + // Null intent. + Assert.assertNull( + IntentHandler.maybeAddAdditionalExtraHeaders(null, downloadContentUrl, null)); + // Non-download authority. + Assert.assertNull( + IntentHandler.maybeAddAdditionalExtraHeaders(intent, otherContentUrl, null)); + // Null type. + Assert.assertNull( + IntentHandler.maybeAddAdditionalExtraHeaders(intent, downloadContentUrl, null)); + // Empty type. + intent.setType(""); + Assert.assertNull( + IntentHandler.maybeAddAdditionalExtraHeaders(intent, downloadContentUrl, null)); + + intent.setType("text/plain"); + + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { + Assert.assertNull( + IntentHandler.maybeAddAdditionalExtraHeaders(intent, downloadContentUrl, null)); + Assert.assertEquals("Foo: bar", + IntentHandler.maybeAddAdditionalExtraHeaders( + intent, downloadContentUrl, "Foo: bar")); + } else { + Assert.assertEquals("X-Chrome-intent-type: text/plain", + IntentHandler.maybeAddAdditionalExtraHeaders(intent, downloadContentUrl, null)); + Assert.assertEquals("Foo: bar\nX-Chrome-intent-type: text/plain", + IntentHandler.maybeAddAdditionalExtraHeaders( + intent, downloadContentUrl, "Foo: bar")); + } + } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/WebVrInputTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/WebVrInputTest.java index c723b29..db16e93 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/WebVrInputTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/WebVrInputTest.java
@@ -33,7 +33,6 @@ import org.chromium.base.test.params.ParameterizedRunner; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.DisableIf; -import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.MinAndroidSdkLevel; import org.chromium.base.test.util.Restriction; import org.chromium.base.test.util.RetryOnFailure; @@ -162,7 +161,6 @@ @MediumTest @Restriction(RESTRICTION_TYPE_VIEWER_DAYDREAM) @VrActivityRestriction({VrActivityRestriction.SupportedActivity.ALL}) - @DisabledTest(message = "https://crbug.com/808524") public void testControllerClicksRegisteredOnDaydream() throws InterruptedException { EmulatedVrController controller = new EmulatedVrController(mTestRule.getActivity()); mVrTestFramework.loadUrlAndAwaitInitialization( @@ -202,6 +200,58 @@ } /** + * Tests that Daydream controller clicks are registered as XR input in an exclusive session. + */ + @Test + @MediumTest + @Restriction(RESTRICTION_TYPE_VIEWER_DAYDREAM) + @CommandLineFlags.Remove({"enable-webvr"}) + @CommandLineFlags.Add({"enable-features=WebXR"}) + @VrActivityRestriction({VrActivityRestriction.SupportedActivity.ALL}) + public void testControllerClicksRegisteredOnDaydream_WebXr() throws InterruptedException { + EmulatedVrController controller = new EmulatedVrController(mTestRule.getActivity()); + mXrTestFramework.loadUrlAndAwaitInitialization( + XrTestFramework.getHtmlTestFile("test_webxr_input"), PAGE_LOAD_TIMEOUT_S); + TransitionUtils.enterPresentationOrFail(mXrTestFramework); + int numIterations = 10; + XrTestFramework.runJavaScriptOrFail( + "stepSetupListeners(" + String.valueOf(numIterations) + ")", POLL_TIMEOUT_SHORT_MS, + mXrTestFramework.getFirstTabWebContents()); + + // Click the touchpad a bunch of times and make sure they're all registered. + for (int i = 0; i < numIterations; i++) { + controller.sendClickButtonToggleEvent(); + controller.sendClickButtonToggleEvent(); + } + + XrTestFramework.waitOnJavaScriptStep(mXrTestFramework.getFirstTabWebContents()); + XrTestFramework.endTest(mXrTestFramework.getFirstTabWebContents()); + } + + private long sendScreenTouchDown(final View view, final int x, final int y) { + long downTime = SystemClock.uptimeMillis(); + ThreadUtils.runOnUiThreadBlocking(new Runnable() { + @Override + public void run() { + view.dispatchTouchEvent( + MotionEvent.obtain(downTime, downTime, MotionEvent.ACTION_DOWN, x, y, 0)); + } + }); + return downTime; + } + + private void sendScreenTouchUp(final View view, final int x, final int y, final long downTime) { + ThreadUtils.runOnUiThreadBlocking(new Runnable() { + @Override + public void run() { + long now = SystemClock.uptimeMillis(); + view.dispatchTouchEvent( + MotionEvent.obtain(downTime, now, MotionEvent.ACTION_UP, x, y, 0)); + } + }); + } + + /** * Tests that screen touches are still registered when the viewer is Cardboard. */ @Test @@ -220,33 +270,60 @@ mVrTestFramework.getFirstTabCvc(), mVrTestFramework.getFirstTabWebContents()); int x = mVrTestFramework.getFirstTabContentView().getWidth() / 2; int y = mVrTestFramework.getFirstTabContentView().getHeight() / 2; - // TODO(mthiesse, crbug.com/758374): Injecting touch events into the root GvrLayout + // TODO(mthiesse, https://crbug.com/758374): Injecting touch events into the root GvrLayout // (VrShellImpl) is flaky. Sometimes the events just don't get routed to the presentation // view for no apparent reason. We should figure out why this is and see if it's fixable. final View presentationView = ((VrShellImpl) TestVrShellDelegate.getVrShellForTesting()) .getPresentationViewForTesting(); - long downTime = SystemClock.uptimeMillis(); - ThreadUtils.runOnUiThreadBlocking(new Runnable() { - @Override - public void run() { - presentationView.dispatchTouchEvent( - MotionEvent.obtain(downTime, downTime, MotionEvent.ACTION_DOWN, x, y, 0)); - } - }); + long downTime = sendScreenTouchDown(presentationView, x, y); VrTestFramework.waitOnJavaScriptStep(mVrTestFramework.getFirstTabWebContents()); - ThreadUtils.runOnUiThreadBlocking(new Runnable() { - @Override - public void run() { - long now = SystemClock.uptimeMillis(); - presentationView.dispatchTouchEvent( - MotionEvent.obtain(downTime, now, MotionEvent.ACTION_UP, x, y, 0)); - } - }); + sendScreenTouchUp(presentationView, x, y, downTime); VrTestFramework.waitOnJavaScriptStep(mVrTestFramework.getFirstTabWebContents()); VrTestFramework.endTest(mVrTestFramework.getFirstTabWebContents()); } /** + * Tests that screen touches are registered as XR input when the viewer is Cardboard. + */ + @Test + @MediumTest + @Restriction(RESTRICTION_TYPE_VIEWER_NON_DAYDREAM) + @CommandLineFlags.Remove({"enable-webvr"}) + @CommandLineFlags.Add({"enable-features=WebXR"}) + @VrActivityRestriction({VrActivityRestriction.SupportedActivity.ALL}) + public void testScreenTapsRegisteredOnCardboard_WebXr() throws InterruptedException { + EmulatedVrController controller = new EmulatedVrController(mTestRule.getActivity()); + mXrTestFramework.loadUrlAndAwaitInitialization( + XrTestFramework.getHtmlTestFile("test_webxr_input"), PAGE_LOAD_TIMEOUT_S); + TransitionUtils.enterPresentationOrFail(mXrTestFramework); + int numIterations = 10; + XrTestFramework.runJavaScriptOrFail( + "stepSetupListeners(" + String.valueOf(numIterations) + ")", POLL_TIMEOUT_SHORT_MS, + mXrTestFramework.getFirstTabWebContents()); + + int x = mXrTestFramework.getFirstTabContentView().getWidth() / 2; + int y = mXrTestFramework.getFirstTabContentView().getHeight() / 2; + // TODO(mthiesse, https://crbug.com/758374): Injecting touch events into the root GvrLayout + // (VrShellImpl) is flaky. Sometimes the events just don't get routed to the presentation + // view for no apparent reason. We should figure out why this is and see if it's fixable. + final View presentationView = ((VrShellImpl) TestVrShellDelegate.getVrShellForTesting()) + .getPresentationViewForTesting(); + + // Tap the screen a bunch of times and make sure that they're all registered. + // Android doesn't seem to like sending touch events too quickly, so have a short delay + // between events. + for (int i = 0; i < numIterations; i++) { + long downTime = sendScreenTouchDown(presentationView, x, y); + SystemClock.sleep(100); + sendScreenTouchUp(presentationView, x, y, downTime); + SystemClock.sleep(100); + } + + XrTestFramework.waitOnJavaScriptStep(mXrTestFramework.getFirstTabWebContents()); + XrTestFramework.endTest(mXrTestFramework.getFirstTabWebContents()); + } + + /** * Tests that focus is locked to the presenting display for purposes of VR input. */ @Test
diff --git a/chrome/app/settings_strings.grdp b/chrome/app/settings_strings.grdp index 077e7ba2..2ce25524 100644 --- a/chrome/app/settings_strings.grdp +++ b/chrome/app/settings_strings.grdp
@@ -518,6 +518,9 @@ <message name="IDS_SETTINGS_GOOGLE_PAYMENTS" desc="Label used to differentiate when an address or credit card entry comes from Google Pay. This should follow the casing of the 'Google Pay' brand. 'Google Pay' should not be translated as it is the product name."> Google Pay </message> + <message name="IDS_SETTINGS_AUTOFILL_TOGGLE_LABEL" desc="Label for a toggle that allows users to control whether forms should be autofilled with data such as addresses and credit cards, but not passwords."> + Autofill forms + </message> <message name="IDS_SETTINGS_AUTOFILL_ADDRESSES_HEADING" desc="Title for the list of addresses that chrome has saved for use in filling in forms."> Addresses </message> @@ -581,6 +584,9 @@ <message name="IDS_SETTINGS_PASSWORDS" desc="Name for the password section and toggle"> Manage passwords </message> + <message name="IDS_SETTINGS_PASSWORDS_SAVE_PASSWORDS_TOGGLE_LABEL" desc="Label for a toggle that allows users to be prompted if they want to save their passwords when logging into webpages."> + Offer to save passwords + </message> <message name="IDS_SETTINGS_PASSWORDS_AUTOSIGNIN_CHECKBOX_LABEL" desc="Label for a checkbox that allows users to sign in automatically to websites when their credentials are already saved."> Auto Sign-in </message>
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 695cc5b8..af8f692 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -3544,6 +3544,11 @@ flag_descriptions::kStopLoadingInBackgroundDescription, kOsAndroid, FEATURE_VALUE_TYPE(features::kStopLoadingInBackground)}, + {"stop-non-timers-in-background", + flag_descriptions::kStopNonTimersInBackgroundName, + flag_descriptions::kStopNonTimersInBackgroundDescription, kOsAndroid, + FEATURE_VALUE_TYPE(features::kStopNonTimersInBackground)}, + {"stop-in-background", flag_descriptions::kStopInBackgroundName, flag_descriptions::kStopInBackgroundDescription, kOsAll, FEATURE_VALUE_TYPE(features::kStopInBackground)},
diff --git a/chrome/browser/android/ntp/content_suggestions_notifier_service_unittest.cc b/chrome/browser/android/ntp/content_suggestions_notifier_service_unittest.cc index c0b54fb..5cb97e2 100644 --- a/chrome/browser/android/ntp/content_suggestions_notifier_service_unittest.cc +++ b/chrome/browser/android/ntp/content_suggestions_notifier_service_unittest.cc
@@ -65,7 +65,7 @@ public: FakeContentSuggestionsService(PrefService* prefs, base::Clock* clock) : ContentSuggestionsService( - ContentSuggestionsService::ENABLED, + ContentSuggestionsService::State::ENABLED, /*identity_manager=*/nullptr, /*history_service=*/nullptr, /*large_icon_cache=*/nullptr,
diff --git a/chrome/browser/android/vr/android_ui_gesture_target.cc b/chrome/browser/android/vr/android_ui_gesture_target.cc index 32510cac..3558f62 100644 --- a/chrome/browser/android/vr/android_ui_gesture_target.cc +++ b/chrome/browser/android/vr/android_ui_gesture_target.cc
@@ -45,7 +45,7 @@ DCHECK(gesture->data.scroll_begin.delta_hint_units == blink::WebGestureEvent::ScrollUnits::kPrecisePixels); - SetPointer(gesture->x, gesture->y); + SetPointer(gesture->PositionInWidget().x, gesture->PositionInWidget().y); Inject(content::MOTION_EVENT_ACTION_START, event_time_ms); float xdiff = gesture->data.scroll_begin.delta_x_hint; @@ -59,8 +59,8 @@ ydiff *= touch_slop_ / dist; } - float xtarget = xdiff * scroll_ratio_ + gesture->x; - float ytarget = ydiff * scroll_ratio_ + gesture->y; + float xtarget = xdiff * scroll_ratio_ + gesture->PositionInWidget().x; + float ytarget = ydiff * scroll_ratio_ + gesture->PositionInWidget().y; scroll_x_ = xtarget > 0 ? std::ceil(xtarget) : std::floor(xtarget); scroll_y_ = ytarget > 0 ? std::ceil(ytarget) : std::floor(ytarget); @@ -80,7 +80,7 @@ Inject(content::MOTION_EVENT_ACTION_MOVE, event_time_ms); break; case blink::WebGestureEvent::kGestureTapDown: - SetPointer(gesture->x, gesture->y); + SetPointer(gesture->PositionInWidget().x, gesture->PositionInWidget().y); Inject(content::MOTION_EVENT_ACTION_START, event_time_ms); Inject(content::MOTION_EVENT_ACTION_END, event_time_ms); break;
diff --git a/chrome/browser/android/vr/vr_controller.cc b/chrome/browser/android/vr/vr_controller.cc index eb6a07a..0601b6dc 100644 --- a/chrome/browser/android/vr/vr_controller.cc +++ b/chrome/browser/android/vr/vr_controller.cc
@@ -368,7 +368,7 @@ UpdateOverallVelocity(); UpdateGestureFromTouchInfo(gesture.get()); - gesture->source_device = blink::kWebGestureDeviceTouchpad; + gesture->SetSourceDevice(blink::kWebGestureDeviceTouchpad); gesture_list->push_back(std::move(gesture)); if (gesture_list->back()->GetType() ==
diff --git a/chrome/browser/apps/guest_view/web_view_browsertest.cc b/chrome/browser/apps/guest_view/web_view_browsertest.cc index f988ff1..1587a1c0 100644 --- a/chrome/browser/apps/guest_view/web_view_browsertest.cc +++ b/chrome/browser/apps/guest_view/web_view_browsertest.cc
@@ -4090,21 +4090,19 @@ ASSERT_EQ(gfx::Vector2dF(), guest_host_view->GetLastScrollOffset()); ASSERT_EQ(gfx::Vector2dF(), embedder_host_view->GetLastScrollOffset()); - gfx::Point guest_scroll_location(1, 1); - gfx::Point guest_scroll_location_in_root = - guest_host_view->TransformPointToRootCoordSpace(guest_scroll_location); + gfx::PointF guest_scroll_location(1, 1); + gfx::PointF guest_scroll_location_in_root = + guest_host_view->TransformPointToRootCoordSpaceF(guest_scroll_location); // When the guest is already scrolled to the top, scroll up so that we bubble // scroll. blink::WebGestureEvent scroll_begin( blink::WebGestureEvent::kGestureScrollBegin, blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::GetStaticTimeStampForTests()); - scroll_begin.source_device = blink::kWebGestureDeviceTouchpad; - scroll_begin.x = guest_scroll_location.x(); - scroll_begin.y = guest_scroll_location.y(); - scroll_begin.global_x = guest_scroll_location_in_root.x(); - scroll_begin.global_y = guest_scroll_location_in_root.y(); + blink::WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchpad); + scroll_begin.SetPositionInWidget(guest_scroll_location); + scroll_begin.SetPositionInScreen(guest_scroll_location_in_root); scroll_begin.data.scroll_begin.delta_x_hint = 0; scroll_begin.data.scroll_begin.delta_y_hint = 5; content::SimulateGestureEvent(guest_contents, scroll_begin, @@ -4123,12 +4121,10 @@ blink::WebGestureEvent scroll_update( blink::WebGestureEvent::kGestureScrollUpdate, blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::GetStaticTimeStampForTests()); - scroll_update.source_device = scroll_begin.source_device; - scroll_update.x = scroll_begin.x; - scroll_update.y = scroll_begin.y; - scroll_update.global_x = scroll_begin.global_x; - scroll_update.global_y = scroll_begin.global_y; + blink::WebInputEvent::GetStaticTimeStampForTests(), + scroll_begin.SourceDevice()); + scroll_update.SetPositionInWidget(scroll_begin.PositionInWidget()); + scroll_update.SetPositionInScreen(scroll_begin.PositionInScreen()); scroll_update.data.scroll_update.delta_x = scroll_begin.data.scroll_begin.delta_x_hint; scroll_update.data.scroll_update.delta_y =
diff --git a/chrome/browser/banners/app_banner_manager_browsertest.cc b/chrome/browser/banners/app_banner_manager_browsertest.cc index ca1e76f..74eed70 100644 --- a/chrome/browser/banners/app_banner_manager_browsertest.cc +++ b/chrome/browser/banners/app_banner_manager_browsertest.cc
@@ -154,7 +154,8 @@ class AppBannerManagerBrowserTest : public InProcessBrowserTest { public: void SetUpOnMainThread() override { - feature_list_.InitAndDisableFeature(features::kExperimentalAppBanners); + feature_list_.InitWithFeatures({}, {features::kExperimentalAppBanners, + features::kDesktopPWAWindowing}); AppBannerSettingsHelper::SetTotalEngagementToTrigger(10); SiteEngagementScore::SetParamValuesForTesting(); ASSERT_TRUE(embedded_test_server()->Start());
diff --git a/chrome/browser/chrome_content_browser_client.cc b/chrome/browser/chrome_content_browser_client.cc index 571970b..4aa708e 100644 --- a/chrome/browser/chrome_content_browser_client.cc +++ b/chrome/browser/chrome_content_browser_client.cc
@@ -927,11 +927,6 @@ registry->RegisterBooleanPref(prefs::kSitePerProcess, false); registry->RegisterBooleanPref(prefs::kWebDriverOverridesIncompatiblePolicies, false); -#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) - // TODO(chrisha): Move this to chrome/browser/conflicts as we build the - // logic that responds to this pref. - registry->RegisterBooleanPref(prefs::kThirdPartyBlockingEnabled, true); -#endif } // static
diff --git a/chrome/browser/chrome_site_per_process_browsertest.cc b/chrome/browser/chrome_site_per_process_browsertest.cc index a615c5c9..3a821ee7 100644 --- a/chrome/browser/chrome_site_per_process_browsertest.cc +++ b/chrome/browser/chrome_site_per_process_browsertest.cc
@@ -1065,19 +1065,17 @@ // open. ContextMenuWaiter menu_waiter(content::NotificationService::AllSources()); - gfx::Point child_location(1, 1); - gfx::Point child_location_in_root = - child_rwhv->TransformPointToRootCoordSpace(child_location); + gfx::PointF child_location(1, 1); + gfx::PointF child_location_in_root = + child_rwhv->TransformPointToRootCoordSpaceF(child_location); blink::WebGestureEvent event( blink::WebInputEvent::kGestureTwoFingerTap, blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::GetStaticTimeStampForTests()); - event.source_device = blink::kWebGestureDeviceTouchscreen; - event.x = child_location.x(); - event.y = child_location.y(); - event.global_x = child_location_in_root.x(); - event.global_y = child_location_in_root.y(); + blink::WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(child_location); + event.SetPositionInScreen(child_location_in_root); event.data.two_finger_tap.first_finger_width = 10; event.data.two_finger_tap.first_finger_height = 10;
diff --git a/chrome/browser/chromeos/assistant/assistant_client.cc b/chrome/browser/chromeos/assistant/assistant_client.cc index 4f71fb97..0c404f1 100644 --- a/chrome/browser/chromeos/assistant/assistant_client.cc +++ b/chrome/browser/chromeos/assistant/assistant_client.cc
@@ -23,7 +23,8 @@ return g_instance; } -AssistantClient::AssistantClient() : audio_input_binding_(&audio_input_) { +AssistantClient::AssistantClient() + : client_binding_(this), audio_input_binding_(&audio_input_) { DCHECK_EQ(nullptr, g_instance); g_instance = this; } @@ -38,7 +39,15 @@ mojom::AudioInputPtr audio_input_ptr; audio_input_binding_.Bind(mojo::MakeRequest(&audio_input_ptr)); - assistant_connection_->Init(std::move(audio_input_ptr)); + mojom::ClientPtr client_ptr; + client_binding_.Bind(mojo::MakeRequest(&client_ptr)); + + assistant_connection_->Init(std::move(client_ptr), + std::move(audio_input_ptr)); +} + +void AssistantClient::OnAssistantStatusChanged(bool running) { + running_ = running; } } // namespace assistant
diff --git a/chrome/browser/chromeos/assistant/assistant_client.h b/chrome/browser/chromeos/assistant/assistant_client.h index e8ed6c5..623f53c 100644 --- a/chrome/browser/chromeos/assistant/assistant_client.h +++ b/chrome/browser/chromeos/assistant/assistant_client.h
@@ -18,20 +18,26 @@ namespace assistant { // Class to handle all assistant in-browser-process functionalities. -class AssistantClient { +class AssistantClient : mojom::Client { public: static AssistantClient* Get(); AssistantClient(); - ~AssistantClient(); + ~AssistantClient() override; void Start(service_manager::Connector* connector); + // assistant::mojom::Client overrides: + void OnAssistantStatusChanged(bool running) override; + private: + mojo::Binding<mojom::Client> client_binding_; + mojom::AssistantPlatformPtr assistant_connection_; mojo::Binding<mojom::AudioInput> audio_input_binding_; PlatformAudioInputHost audio_input_; + bool running_ = false; DISALLOW_COPY_AND_ASSIGN(AssistantClient); };
diff --git a/chrome/browser/chromeos/chrome_browser_main_chromeos.cc b/chrome/browser/chromeos/chrome_browser_main_chromeos.cc index 0b392c9e..a1219e74 100644 --- a/chrome/browser/chromeos/chrome_browser_main_chromeos.cc +++ b/chrome/browser/chromeos/chrome_browser_main_chromeos.cc
@@ -183,7 +183,7 @@ #include "ui/chromeos/events/event_rewriter_chromeos.h" #include "ui/chromeos/events/pref_names.h" #include "ui/events/event_utils.h" -#include "ui/keyboard/content/keyboard.h" +#include "ui/keyboard/keyboard_resource_util.h" #if BUILDFLAG(ENABLE_RLZ) #include "components/rlz/rlz_tracker.h" @@ -824,7 +824,7 @@ // Initialize the keyboard before any session state changes (i.e. before // loading the default profile). - keyboard::InitializeKeyboard(); + keyboard::InitializeKeyboardResources(); if (lock_screen_apps::StateController::IsEnabled()) { lock_screen_apps_state_controller_ =
diff --git a/chrome/browser/chromeos/input_method/input_method_manager_impl.cc b/chrome/browser/chromeos/input_method/input_method_manager_impl.cc index 4c7f949..14bd6cfa 100644 --- a/chrome/browser/chromeos/input_method/input_method_manager_impl.cc +++ b/chrome/browser/chromeos/input_method/input_method_manager_impl.cc
@@ -49,7 +49,6 @@ #include "ui/base/ime/ime_bridge.h" #include "ui/chromeos/ime/input_method_menu_item.h" #include "ui/chromeos/ime/input_method_menu_manager.h" -#include "ui/keyboard/content/keyboard_constants.h" #include "ui/keyboard/keyboard_controller.h" namespace chromeos {
diff --git a/chrome/browser/chromeos/login/screens/sync_consent_screen.cc b/chrome/browser/chromeos/login/screens/sync_consent_screen.cc index adf1d2a0..3e5fb58 100644 --- a/chrome/browser/chromeos/login/screens/sync_consent_screen.cc +++ b/chrome/browser/chromeos/login/screens/sync_consent_screen.cc
@@ -9,7 +9,9 @@ #include "base/logging.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/sync/profile_sync_service_factory.h" +#include "chrome/common/pref_names.h" #include "components/browser_sync/profile_sync_service.h" +#include "components/prefs/pref_service.h" #include "components/user_manager/user_manager.h" namespace chromeos { @@ -57,6 +59,8 @@ void SyncConsentScreen::OnUserAction(const std::string& action_id) { if (action_id == kUserActionConinueAndReview) { + profile_->GetPrefs()->SetBoolean(prefs::kShowSyncSettingsOnSessionStart, + true); Finish(ScreenExitCode::SYNC_CONSENT_FINISHED); return; }
diff --git a/chrome/browser/chromeos/login/session/user_session_manager.cc b/chrome/browser/chromeos/login/session/user_session_manager.cc index 8c84312..26f0bbf 100644 --- a/chrome/browser/chromeos/login/session/user_session_manager.cc +++ b/chrome/browser/chromeos/login/session/user_session_manager.cc
@@ -82,6 +82,7 @@ #include "chrome/browser/supervised_user/child_accounts/child_account_service.h" #include "chrome/browser/supervised_user/child_accounts/child_account_service_factory.h" #include "chrome/browser/ui/app_list/app_list_service.h" +#include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/startup/startup_browser_creator.h" #include "chrome/common/channel_info.h" #include "chrome/common/chrome_switches.h" @@ -1954,6 +1955,12 @@ // Show the one-time notification and update the relevant pref about the // completion of the file system migration necessary for ARC, when needed. arc::ShowArcMigrationSuccessNotificationIfNeeded(profile); + + if (should_launch_browser_ && + profile->GetPrefs()->GetBoolean(prefs::kShowSyncSettingsOnSessionStart)) { + profile->GetPrefs()->ClearPref(prefs::kShowSyncSettingsOnSessionStart); + chrome::ShowSettingsSubPageForProfile(profile, "syncSetup"); + } } void UserSessionManager::RespectLocalePreferenceWrapper(
diff --git a/chrome/browser/chromeos/login/wizard_controller.cc b/chrome/browser/chromeos/login/wizard_controller.cc index 8a79db8c..5867c27 100644 --- a/chrome/browser/chromeos/login/wizard_controller.cc +++ b/chrome/browser/chromeos/login/wizard_controller.cc
@@ -74,6 +74,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/ash/ash_util.h" +#include "chrome/browser/ui/ash/tablet_mode_client.h" #include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h" #include "chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h" #include "chrome/browser/ui/webui/help/help_utils_chromeos.h" @@ -130,10 +131,12 @@ chromeos::OobeScreen::SCREEN_ARC_TERMS_OF_SERVICE, chromeos::OobeScreen::SCREEN_AUTO_ENROLLMENT_CHECK}; -// Checks flag for HID-detection screen show. +// Checks if device is in tablet mode, and that HID-detection screen is not +// disabled by flag. bool CanShowHIDDetectionScreen() { - return !base::CommandLine::ForCurrentProcess()->HasSwitch( - chromeos::switches::kDisableHIDDetectionOnOOBE); + return !TabletModeClient::Get()->tablet_mode_enabled() && + !base::CommandLine::ForCurrentProcess()->HasSwitch( + chromeos::switches::kDisableHIDDetectionOnOOBE); } bool IsResumableScreen(chromeos::OobeScreen screen) {
diff --git a/chrome/browser/chromeos/preferences.cc b/chrome/browser/chromeos/preferences.cc index 48d8dec..0e0a4f92 100644 --- a/chrome/browser/chromeos/preferences.cc +++ b/chrome/browser/chromeos/preferences.cc
@@ -408,6 +408,7 @@ update_engine::EndOfLifeStatus::kSupported); registry->RegisterBooleanPref(prefs::kCastReceiverEnabled, false); + registry->RegisterBooleanPref(prefs::kShowSyncSettingsOnSessionStart, false); } void Preferences::InitUserPrefs(sync_preferences::PrefServiceSyncable* prefs) {
diff --git a/chrome/browser/chromeos/printing/printers_sync_bridge.cc b/chrome/browser/chromeos/printing/printers_sync_bridge.cc index 0a2a9db..67a40d4 100644 --- a/chrome/browser/chromeos/printing/printers_sync_bridge.cc +++ b/chrome/browser/chromeos/printing/printers_sync_bridge.cc
@@ -19,6 +19,7 @@ #include "components/sync/model/model_type_change_processor.h" #include "components/sync/model/model_type_store.h" #include "components/sync/model/mutable_data_batch.h" +#include "components/sync/model_impl/client_tag_based_model_type_processor.h" #include "components/sync/protocol/model_type_state.pb.h" #include "components/sync/protocol/sync.pb.h" @@ -26,13 +27,14 @@ namespace { +using syncer::ClientTagBasedModelTypeProcessor; using syncer::ConflictResolution; using syncer::EntityChange; using syncer::EntityChangeList; using syncer::EntityData; +using syncer::MetadataChangeList; using syncer::ModelTypeChangeProcessor; using syncer::ModelTypeStore; -using syncer::MetadataChangeList; std::unique_ptr<EntityData> CopyToEntityData( const sync_pb::PrinterSpecifics& specifics) { @@ -137,7 +139,8 @@ return; } - owner_->change_processor()->ModelReadyToSync(std::move(metadata_batch)); + owner_->change_processor()->ModelReadyToSync(owner_, + std::move(metadata_batch)); } PrintersSyncBridge* owner_; @@ -149,9 +152,9 @@ PrintersSyncBridge::PrintersSyncBridge( syncer::OnceModelTypeStoreFactory callback, const base::RepeatingClosure& error_callback) - : ModelTypeSyncBridge(base::BindRepeating(&ModelTypeChangeProcessor::Create, - error_callback), - syncer::PRINTERS), + : ModelTypeSyncBridge( + std::make_unique<ClientTagBasedModelTypeProcessor>(syncer::PRINTERS, + error_callback)), store_delegate_(std::make_unique<StoreProxy>(this, std::move(callback))), observers_(new base::ObserverListThreadSafe<Observer>()) {}
diff --git a/chrome/browser/client_hints/client_hints.cc b/chrome/browser/client_hints/client_hints.cc index 3eacd2f0..7f7bfe1 100644 --- a/chrome/browser/client_hints/client_hints.cc +++ b/chrome/browser/client_hints/client_hints.cc
@@ -141,14 +141,16 @@ if (web_client_hints.IsEnabled( blink::mojom::WebClientHintsType::kViewportWidth)) { -// TODO: https://crbug.com/821974: Viewport width client hint should be sent -// on non-Android main frame navigations as well. + // The default value on Android. See + // https://cs.chromium.org/chromium/src/third_party/WebKit/Source/core/css/viewportAndroid.css. + double viewport_width = 980; #if !defined(OS_ANDROID) - double viewport_width = (display::Screen::GetScreen() - ->GetPrimaryDisplay() - .GetSizeInPixel() - .width()) / - GetZoomFactor(context, url); + viewport_width = (display::Screen::GetScreen() + ->GetPrimaryDisplay() + .GetSizeInPixel() + .width()) / + GetZoomFactor(context, url); +#endif // !OS_ANDROID DCHECK_LT(0, viewport_width); if (viewport_width > 0) { additional_headers->SetHeader( @@ -156,11 +158,10 @@ blink::mojom::WebClientHintsType::kViewportWidth)], base::NumberToString(std::round(viewport_width))); } -#endif // !OS_ANDROID } - // Static assert that triggers if a new client hint header is added. If a new - // client hint header is added, the following assertion should be updated. + // Static assert that triggers if a new client hint header is added. If a + // new client hint header is added, the following assertion should be updated. // If possible, logic should be added above so that the request headers for // the newly added client hint can be added to the request. static_assert(
diff --git a/chrome/browser/client_hints/client_hints_browsertest.cc b/chrome/browser/client_hints/client_hints_browsertest.cc index 328a729..75e5a35 100644 --- a/chrome/browser/client_hints/client_hints_browsertest.cc +++ b/chrome/browser/client_hints/client_hints_browsertest.cc
@@ -261,14 +261,8 @@ base::ContainsKey(request.headers, "device-memory")); EXPECT_EQ(expect_client_hints_on_main_frame_, base::ContainsKey(request.headers, "dpr")); -// Sending of viewport-width is not enabled on main frame navigations for -// Android. -#if defined(OS_ANDROID) - EXPECT_FALSE(base::ContainsKey(request.headers, "viewport-width")); -#else EXPECT_EQ(expect_client_hints_on_main_frame_, base::ContainsKey(request.headers, "viewport-width")); -#endif if (expect_client_hints_on_main_frame_) { double value = 0.0; EXPECT_TRUE(base::StringToDouble( @@ -278,11 +272,12 @@ EXPECT_TRUE( base::StringToDouble(request.headers.find("dpr")->second, &value)); EXPECT_LT(0.0, value); - -#if !defined(OS_ANDROID) EXPECT_TRUE(base::StringToDouble( request.headers.find("viewport-width")->second, &value)); +#if !defined(OS_ANDROID) EXPECT_LT(0.0, value); +#else + EXPECT_EQ(980, value); #endif } } @@ -307,7 +302,11 @@ EXPECT_TRUE(base::StringToDouble( request.headers.find("viewport-width")->second, &value)); +#if !defined(OS_ANDROID) EXPECT_LT(0.0, value); +#else + EXPECT_EQ(980, value); +#endif } } @@ -410,14 +409,9 @@ content::FetchHistogramsFromChildProcesses(); SubprocessMetricsProvider::MergeHistogramDeltasForTesting(); -// Two client hints are attached to the image request, and the device-memory -// and dpr headers are attached to the main frame request. -// On desktop, viewport-width is also attached to the main frame request. -#if defined(OS_ANDROID) - EXPECT_EQ(4u, count_client_hints_headers_seen()); -#else + // Three client hints are attached to the image request, and three to the main + // frame request. EXPECT_EQ(6u, count_client_hints_headers_seen()); -#endif // Navigating to without_accept_ch_without_lifetime_img_foo_com() should not // attach client hints to the image subresouce contained in that page since @@ -510,14 +504,9 @@ ui_test_utils::NavigateToURL(browser(), without_accept_ch_without_lifetime_local_url()); -// Two client hints are attached to the image request, and the device-memory -// header is attached to the main frame request. -// On desktop, viewport-width is also attached to the main frame request. -#if defined(OS_ANDROID) - EXPECT_EQ(4u, count_client_hints_headers_seen()); -#else + // Three client hints are attached to the image request, and three to the main + // frame request. EXPECT_EQ(6u, count_client_hints_headers_seen()); -#endif } // Loads a webpage that does not request persisting of client hints. @@ -574,14 +563,9 @@ ui_test_utils::NavigateToURL(browser(), without_accept_ch_without_lifetime_url()); -// Two client hints are attached to the image request, and the device-memory -// and dpr headers are attached to the main frame request. -// On desktop, viewport-width is also attached to the main frame request. -#if defined(OS_ANDROID) - EXPECT_EQ(4u, count_client_hints_headers_seen()); -#else + // Three client hints are attached to the image request, and three to the main + // frame request. EXPECT_EQ(6u, count_client_hints_headers_seen()); -#endif } // Ensure that when cookies are blocked, client hint preferences are not @@ -674,14 +658,10 @@ SetClientHintExpectationsOnSubresources(true); ui_test_utils::NavigateToURL(browser(), without_accept_ch_without_lifetime_url()); -// Two client hints are attached to the image request, and the device-memory -// header is attached to the main frame request. -// On desktop, viewport-width is also attached to the main frame request. -#if defined(OS_ANDROID) - EXPECT_EQ(4u, count_client_hints_headers_seen()); -#else + + // Three client hints are attached to the image request, and three to the main + // frame request. EXPECT_EQ(6u, count_client_hints_headers_seen()); -#endif // Clear settings. HostContentSettingsMapFactory::GetForProfile(browser()->profile()) @@ -780,14 +760,10 @@ SetClientHintExpectationsOnSubresources(true); ui_test_utils::NavigateToURL(browser(), without_accept_ch_without_lifetime_url()); -// Two client hints are attached to the image request, and the device-memory -// and dpr headers are attached to the main frame request. -// On desktop, viewport-width is also attached to the main frame request. -#if defined(OS_ANDROID) - EXPECT_EQ(4u, count_client_hints_headers_seen()); -#else + + // Three client hints are attached to the image request, and three to the main + // frame request. EXPECT_EQ(6u, count_client_hints_headers_seen()); -#endif // Clear settings. HostContentSettingsMapFactory::GetForProfile(browser()->profile())
diff --git a/chrome/browser/component_updater/third_party_module_list_component_installer_win.cc b/chrome/browser/component_updater/third_party_module_list_component_installer_win.cc index 0741121..bd1dc33d 100644 --- a/chrome/browser/component_updater/third_party_module_list_component_installer_win.cc +++ b/chrome/browser/component_updater/third_party_module_list_component_installer_win.cc
@@ -19,6 +19,7 @@ #include "base/values.h" #include "base/version.h" #include "chrome/browser/conflicts/module_database_win.h" +#include "chrome/browser/conflicts/third_party_conflicts_manager_win.h" #include "components/component_updater/component_updater_paths.h" #include "content/public/browser/browser_thread.h"
diff --git a/chrome/browser/conflicts/module_database_win.cc b/chrome/browser/conflicts/module_database_win.cc index 6ad367cb..c66a219 100644 --- a/chrome/browser/conflicts/module_database_win.cc +++ b/chrome/browser/conflicts/module_database_win.cc
@@ -13,6 +13,16 @@ #include "base/win/windows_version.h" #include "chrome/browser/conflicts/module_database_observer_win.h" +#if defined(GOOGLE_CHROME_BUILD) +#include "base/feature_list.h" +#include "chrome/browser/browser_process.h" +#include "chrome/browser/conflicts/third_party_conflicts_manager_win.h" +#include "chrome/common/chrome_features.h" +#include "chrome/common/pref_names.h" +#include "components/prefs/pref_registry_simple.h" +#include "components/prefs/pref_service.h" +#endif + namespace { // Document the assumptions made on the ProcessType enum in order to convert @@ -49,11 +59,7 @@ AddObserver(&third_party_metrics_); #if defined(GOOGLE_CHROME_BUILD) - if (base::win::GetVersion() >= base::win::VERSION_WIN10) { - third_party_conflicts_manager_ = - std::make_unique<ThirdPartyConflictsManager>(this); - AddObserver(third_party_conflicts_manager_.get()); - } + MaybeInitializeThirdPartyConflictsManager(); #endif } @@ -172,6 +178,15 @@ module_inspector_.IncreaseInspectionPriority(); } +#if defined(GOOGLE_CHROME_BUILD) +// static +void ModuleDatabase::RegisterLocalStatePrefs(PrefRegistrySimple* registry) { + // Register the pref used to disable the Incompatible Applications warning + // using group policy. + registry->RegisterBooleanPref(prefs::kThirdPartyBlockingEnabled, true); +} +#endif + // static uint32_t ModuleDatabase::ProcessTypeToBit(content::ProcessType process_type) { uint32_t bit_index = @@ -258,3 +273,23 @@ observer->OnNewModuleFound(module.first, module.second); } } + +#if defined(GOOGLE_CHROME_BUILD) +void ModuleDatabase::MaybeInitializeThirdPartyConflictsManager() { + // Early exit if disabled via group policy. + const PrefService::Preference* third_party_blocking_enabled_pref = + g_browser_process->local_state()->FindPreference( + prefs::kThirdPartyBlockingEnabled); + if (third_party_blocking_enabled_pref->IsManaged() && + !third_party_blocking_enabled_pref->GetValue()->GetBool()) + return; + + if (base::FeatureList::IsEnabled( + features::kIncompatibleApplicationsWarning) && + base::win::GetVersion() >= base::win::VERSION_WIN10) { + third_party_conflicts_manager_ = + std::make_unique<ThirdPartyConflictsManager>(this); + AddObserver(third_party_conflicts_manager_.get()); + } +} +#endif
diff --git a/chrome/browser/conflicts/module_database_win.h b/chrome/browser/conflicts/module_database_win.h index e9583721..80bb624 100644 --- a/chrome/browser/conflicts/module_database_win.h +++ b/chrome/browser/conflicts/module_database_win.h
@@ -19,12 +19,13 @@ #include "chrome/browser/conflicts/third_party_metrics_recorder_win.h" #include "content/public/common/process_type.h" -#if defined(GOOGLE_CHROME_BUILD) -#include "chrome/browser/conflicts/third_party_conflicts_manager_win.h" -#endif - class ModuleDatabaseObserver; +#if defined(GOOGLE_CHROME_BUILD) +class PrefRegistrySimple; +class ThirdPartyConflictsManager; +#endif + namespace base { class FilePath; } @@ -115,9 +116,11 @@ void IncreaseInspectionPriority(); #if defined(GOOGLE_CHROME_BUILD) + static void RegisterLocalStatePrefs(PrefRegistrySimple* registry); + // Accessor for the third party conflicts manager. This is exposed so that the // manager can be wired up to the ThirdPartyModuleListComponentInstaller. - // Returns returns null on Windows 8.1 and lower. + // Returns null if the tracking of incompatible applications is disabled. ThirdPartyConflictsManager* third_party_conflicts_manager() { return third_party_conflicts_manager_.get(); } @@ -170,6 +173,15 @@ // OnNewModuleFound(). void NotifyLoadedModules(ModuleDatabaseObserver* observer); +#if defined(GOOGLE_CHROME_BUILD) + // Initializes the ThirdPartyConflictsManager, which controls the warning of + // incompatible applications that injects into Chrome. + // The manager is not initialized if it is disabled via a base::Feature or a + // group policy. Note that it is also not initialized on Windows version + // 8.1 and less. + void MaybeInitializeThirdPartyConflictsManager(); +#endif + // The task runner to which this object is bound. scoped_refptr<base::SequencedTaskRunner> task_runner_;
diff --git a/chrome/browser/conflicts/module_event_sink_impl_win_unittest.cc b/chrome/browser/conflicts/module_event_sink_impl_win_unittest.cc index a4880258..e90c718 100644 --- a/chrome/browser/conflicts/module_event_sink_impl_win_unittest.cc +++ b/chrome/browser/conflicts/module_event_sink_impl_win_unittest.cc
@@ -11,6 +11,8 @@ #include "base/threading/sequenced_task_runner_handle.h" #include "chrome/browser/conflicts/module_database_win.h" #include "chrome/common/conflicts/module_watcher_win.h" +#include "chrome/test/base/scoped_testing_local_state.h" +#include "chrome/test/base/testing_browser_process.h" #include "testing/gtest/include/gtest/gtest.h" #include <windows.h> @@ -29,7 +31,8 @@ class ModuleEventSinkImplTest : public testing::Test { protected: ModuleEventSinkImplTest() - : module_database_(std::make_unique<ModuleDatabase>( + : scoped_testing_local_state_(TestingBrowserProcess::GetGlobal()), + module_database_(std::make_unique<ModuleDatabase>( base::SequencedTaskRunnerHandle::Get())) {} void CreateModuleSinkImpl() { @@ -44,6 +47,7 @@ // Must be before |module_database_|. base::test::ScopedTaskEnvironment scoped_task_environment_; + ScopedTestingLocalState scoped_testing_local_state_; std::unique_ptr<ModuleDatabase> module_database_; std::unique_ptr<ModuleEventSinkImpl> module_event_sink_impl_;
diff --git a/chrome/browser/conflicts/problematic_programs_updater_win.cc b/chrome/browser/conflicts/problematic_programs_updater_win.cc index 07fa38b..805b2413 100644 --- a/chrome/browser/conflicts/problematic_programs_updater_win.cc +++ b/chrome/browser/conflicts/problematic_programs_updater_win.cc
@@ -19,6 +19,7 @@ #include "chrome/browser/conflicts/third_party_metrics_recorder_win.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_registry_simple.h" +#include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "content/public/browser/browser_thread.h" @@ -139,9 +140,6 @@ } // namespace -const base::Feature kIncompatibleApplicationsWarning{ - "IncompatibleApplicationsWarning", base::FEATURE_DISABLED_BY_DEFAULT}; - // ProblematicProgram ---------------------------------------------------------- ProblematicProgramsUpdater::ProblematicProgram::ProblematicProgram( @@ -160,6 +158,14 @@ // ProblematicProgramsUpdater -------------------------------------------------- +ProblematicProgramsUpdater::ProblematicProgramsUpdater( + const ModuleListFilter& module_list_filter, + const InstalledPrograms& installed_programs) + : module_list_filter_(module_list_filter), + installed_programs_(installed_programs) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); +} + ProblematicProgramsUpdater::~ProblematicProgramsUpdater() = default; // static @@ -169,37 +175,16 @@ } // static -std::unique_ptr<ProblematicProgramsUpdater> -ProblematicProgramsUpdater::MaybeCreate( - const ModuleListFilter& module_list_filter, - const InstalledPrograms& installed_programs) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - std::unique_ptr<ProblematicProgramsUpdater> instance; - - if (base::FeatureList::IsEnabled(kIncompatibleApplicationsWarning)) { - instance.reset( - new ProblematicProgramsUpdater(module_list_filter, installed_programs)); - } - - return instance; +bool ProblematicProgramsUpdater::IsIncompatibleApplicationsWarningEnabled() { + return ModuleDatabase::GetInstance() && + ModuleDatabase::GetInstance()->third_party_conflicts_manager(); } // static bool ProblematicProgramsUpdater::HasCachedPrograms() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (!base::FeatureList::IsEnabled(kIncompatibleApplicationsWarning)) - return false; - - std::vector<ProblematicProgram> programs = ConvertToProblematicProgramsVector( - *g_browser_process->local_state() - ->FindPreference(prefs::kProblematicPrograms) - ->GetValue()); - - RemoveStaleEntriesAndUpdateCache(&programs); - - return !programs.empty(); + return !GetCachedPrograms().empty(); } // static @@ -207,12 +192,7 @@ ProblematicProgramsUpdater::GetCachedPrograms() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - std::vector<ProblematicProgram> programs; - - if (!base::FeatureList::IsEnabled(kIncompatibleApplicationsWarning)) - return programs; - - programs = ConvertToProblematicProgramsVector( + std::vector<ProblematicProgram> programs = ConvertToProblematicProgramsVector( *g_browser_process->local_state() ->FindPreference(prefs::kProblematicPrograms) ->GetValue()); @@ -294,9 +274,3 @@ std::move(element.second)); } } - -ProblematicProgramsUpdater::ProblematicProgramsUpdater( - const ModuleListFilter& module_list_filter, - const InstalledPrograms& installed_programs) - : module_list_filter_(module_list_filter), - installed_programs_(installed_programs) {}
diff --git a/chrome/browser/conflicts/problematic_programs_updater_win.h b/chrome/browser/conflicts/problematic_programs_updater_win.h index 90ffabe3..f0f579a 100644 --- a/chrome/browser/conflicts/problematic_programs_updater_win.h +++ b/chrome/browser/conflicts/problematic_programs_updater_win.h
@@ -8,28 +8,19 @@ #include <memory> #include <vector> -#include "base/feature_list.h" #include "base/macros.h" #include "chrome/browser/conflicts/installed_programs_win.h" #include "chrome/browser/conflicts/module_database_observer_win.h" #include "chrome/browser/conflicts/proto/module_list.pb.h" -#include "url/gurl.h" class ModuleListFilter; class PrefRegistrySimple; -// A feature that controls whether Chrome warns about incompatible applications. -extern const base::Feature kIncompatibleApplicationsWarning; - // Maintains a list of problematic programs that are installed on the machine. // These programs cause unwanted DLLs to be loaded into Chrome. // // Because the list is expensive to build, it is cached into the Local State // file so that it is available at startup. -// -// When kIncompatibleApplicationsWarning is disabled, this class always behaves -// as-if there are no problematic programs on the computer. This makes it safe -// to use all of the class' static functions unconditionally. class ProblematicProgramsUpdater : public ModuleDatabaseObserver { public: struct ProblematicProgram { @@ -46,22 +37,24 @@ std::unique_ptr<chrome::conflicts::BlacklistAction> blacklist_action; }; + // Creates an instance of the updater. |module_list_filter| and + // |installed_programs| must outlive the lifetime of this class. + ProblematicProgramsUpdater(const ModuleListFilter& module_list_filter, + const InstalledPrograms& installed_programs); ~ProblematicProgramsUpdater() override; static void RegisterLocalStatePrefs(PrefRegistrySimple* registry); - // Creates an instance of the updater. Returns nullptr if the - // kIncompatibleApplicationsWarning experiment is disabled. - // - // |installed_programs| must outlive the lifetime of this class. - static std::unique_ptr<ProblematicProgramsUpdater> MaybeCreate( - const ModuleListFilter& module_list_filter, - const InstalledPrograms& installed_programs); + // Returns true if the tracking of incompatible applications is enabled. The + // return value will not change throughout the lifetime of the process. + static bool IsIncompatibleApplicationsWarningEnabled(); // Returns true if the cache contains at least one problematic program. + // Only call this if IsIncompatibleApplicationsWarningEnabled() returns true. static bool HasCachedPrograms(); // Returns all the cached problematic programs. + // Only call this if IsIncompatibleApplicationsWarningEnabled() returns true. static std::vector<ProblematicProgram> GetCachedPrograms(); // ModuleDatabaseObserver: @@ -70,9 +63,6 @@ void OnModuleDatabaseIdle() override; private: - ProblematicProgramsUpdater(const ModuleListFilter& module_list_filter, - const InstalledPrograms& installed_programs); - const ModuleListFilter& module_list_filter_; const InstalledPrograms& installed_programs_;
diff --git a/chrome/browser/conflicts/problematic_programs_updater_win_unittest.cc b/chrome/browser/conflicts/problematic_programs_updater_win_unittest.cc index faa57f8..719aeaf3 100644 --- a/chrome/browser/conflicts/problematic_programs_updater_win_unittest.cc +++ b/chrome/browser/conflicts/problematic_programs_updater_win_unittest.cc
@@ -10,7 +10,6 @@ #include "base/logging.h" #include "base/strings/stringprintf.h" -#include "base/test/scoped_feature_list.h" #include "base/test/test_reg_util_win.h" #include "base/win/registry.h" #include "chrome/browser/conflicts/module_info_win.h" @@ -96,7 +95,6 @@ void SetUp() override { ASSERT_NO_FATAL_FAILURE( registry_override_manager_.OverrideRegistry(HKEY_CURRENT_USER)); - scoped_feature_list_.InitAndEnableFeature(kIncompatibleApplicationsWarning); } enum class Option { @@ -130,15 +128,10 @@ private: content::TestBrowserThreadBundle test_browser_thread_bundle_; - - base::test::ScopedFeatureList scoped_feature_list_; - ScopedTestingLocalState scoped_testing_local_state_; - registry_util::RegistryOverrideManager registry_override_manager_; MockModuleListFilter module_list_filter_; - MockInstalledPrograms installed_programs_; DISALLOW_COPY_AND_ASSIGN(ProblematicProgramsUpdaterTest); @@ -154,8 +147,9 @@ // ProblematicProgramsUpdater doesn't do anything when there is no registered // installed programs. TEST_F(ProblematicProgramsUpdaterTest, NoProblematicPrograms) { - auto problematic_programs_updater = ProblematicProgramsUpdater::MaybeCreate( - module_list_filter(), installed_programs()); + auto problematic_programs_updater = + std::make_unique<ProblematicProgramsUpdater>(module_list_filter(), + installed_programs()); // Simulate some arbitrary module loading into the process. problematic_programs_updater->OnNewModuleFound(ModuleInfoKey(dll1_, 0, 0, 0), @@ -169,8 +163,9 @@ TEST_F(ProblematicProgramsUpdaterTest, OneConflict) { AddProblematicProgram(dll1_, L"Foo", Option::ADD_REGISTRY_ENTRY); - auto problematic_programs_updater = ProblematicProgramsUpdater::MaybeCreate( - module_list_filter(), installed_programs()); + auto problematic_programs_updater = + std::make_unique<ProblematicProgramsUpdater>(module_list_filter(), + installed_programs()); // Simulate the module loading into the process. problematic_programs_updater->OnNewModuleFound(ModuleInfoKey(dll1_, 0, 0, 0), @@ -187,8 +182,9 @@ AddProblematicProgram(dll1_, L"Foo", Option::ADD_REGISTRY_ENTRY); AddProblematicProgram(dll2_, L"Bar", Option::ADD_REGISTRY_ENTRY); - auto problematic_programs_updater = ProblematicProgramsUpdater::MaybeCreate( - module_list_filter(), installed_programs()); + auto problematic_programs_updater = + std::make_unique<ProblematicProgramsUpdater>(module_list_filter(), + installed_programs()); // Simulate the module loading into the process. problematic_programs_updater->OnNewModuleFound(ModuleInfoKey(dll1_, 0, 0, 0), @@ -214,8 +210,9 @@ TEST_F(ProblematicProgramsUpdaterTest, PersistsThroughRestarts) { AddProblematicProgram(dll1_, L"Foo", Option::ADD_REGISTRY_ENTRY); - auto problematic_programs_updater = ProblematicProgramsUpdater::MaybeCreate( - module_list_filter(), installed_programs()); + auto problematic_programs_updater = + std::make_unique<ProblematicProgramsUpdater>(module_list_filter(), + installed_programs()); // Simulate the module loading into the process. problematic_programs_updater->OnNewModuleFound(ModuleInfoKey(dll1_, 0, 0, 0), @@ -235,8 +232,9 @@ AddProblematicProgram(dll1_, L"Foo", Option::ADD_REGISTRY_ENTRY); AddProblematicProgram(dll2_, L"Bar", Option::NO_REGISTRY_ENTRY); - auto problematic_programs_updater = ProblematicProgramsUpdater::MaybeCreate( - module_list_filter(), installed_programs()); + auto problematic_programs_updater = + std::make_unique<ProblematicProgramsUpdater>(module_list_filter(), + installed_programs()); // Simulate the modules loading into the process. problematic_programs_updater->OnNewModuleFound(ModuleInfoKey(dll1_, 0, 0, 0),
diff --git a/chrome/browser/conflicts/third_party_conflicts_manager_win.cc b/chrome/browser/conflicts/third_party_conflicts_manager_win.cc index 0f1e100..08b85293 100644 --- a/chrome/browser/conflicts/third_party_conflicts_manager_win.cc +++ b/chrome/browser/conflicts/third_party_conflicts_manager_win.cc
@@ -97,8 +97,8 @@ void ThirdPartyConflictsManager::InitializeProblematicProgramsUpdater() { DCHECK(module_list_filter_); DCHECK(installed_programs_); - problematic_programs_updater_ = ProblematicProgramsUpdater::MaybeCreate( + + problematic_programs_updater_ = std::make_unique<ProblematicProgramsUpdater>( *module_list_filter_, *installed_programs_); - if (problematic_programs_updater_) - module_database_->AddObserver(problematic_programs_updater_.get()); + module_database_->AddObserver(problematic_programs_updater_.get()); }
diff --git a/chrome/browser/devtools/devtools_targets_ui.cc b/chrome/browser/devtools/devtools_targets_ui.cc index a5b599c..499d7aa 100644 --- a/chrome/browser/devtools/devtools_targets_ui.cc +++ b/chrome/browser/devtools/devtools_targets_ui.cc
@@ -85,7 +85,7 @@ class LocalTargetsUIHandler : public DevToolsTargetsUIHandler, public content::DevToolsAgentHostObserver { public: - explicit LocalTargetsUIHandler(const Callback& callback); + LocalTargetsUIHandler(const Callback& callback, Profile* profile); ~LocalTargetsUIHandler() override; // DevToolsTargetsUIHandler overrides. @@ -99,15 +99,16 @@ void ScheduleUpdate(); void UpdateTargets(); - void SendTargets(const DevToolsAgentHost::List& targets); + Profile* profile_; std::unique_ptr<CancelableTimer> timer_; base::WeakPtrFactory<LocalTargetsUIHandler> weak_factory_; }; -LocalTargetsUIHandler::LocalTargetsUIHandler( - const Callback& callback) +LocalTargetsUIHandler::LocalTargetsUIHandler(const Callback& callback, + Profile* profile) : DevToolsTargetsUIHandler(kTargetSourceLocal, callback), + profile_(profile), weak_factory_(this) { DevToolsAgentHost::AddObserver(this); UpdateTargets(); @@ -143,16 +144,15 @@ } void LocalTargetsUIHandler::UpdateTargets() { - SendTargets(DevToolsAgentHost::GetOrCreateAll()); -} + content::DevToolsAgentHost::List targets = + DevToolsAgentHost::GetOrCreateAll(); -void LocalTargetsUIHandler::SendTargets( - const content::DevToolsAgentHost::List& targets) { std::vector<HostDescriptionNode> hosts; hosts.reserve(targets.size()); - targets_.clear(); for (const scoped_refptr<DevToolsAgentHost>& host : targets) { + if (Profile::FromBrowserContext(host->GetBrowserContext()) != profile_) + continue; targets_[host->GetId()] = host; hosts.push_back({host->GetId(), host->GetParentId(), std::move(*Serialize(host.get()))}); @@ -305,9 +305,10 @@ // static std::unique_ptr<DevToolsTargetsUIHandler> DevToolsTargetsUIHandler::CreateForLocal( - const DevToolsTargetsUIHandler::Callback& callback) { + const DevToolsTargetsUIHandler::Callback& callback, + Profile* profile) { return std::unique_ptr<DevToolsTargetsUIHandler>( - new LocalTargetsUIHandler(callback)); + new LocalTargetsUIHandler(callback, profile)); } // static
diff --git a/chrome/browser/devtools/devtools_targets_ui.h b/chrome/browser/devtools/devtools_targets_ui.h index 245cc33..613d707 100644 --- a/chrome/browser/devtools/devtools_targets_ui.h +++ b/chrome/browser/devtools/devtools_targets_ui.h
@@ -32,7 +32,8 @@ std::string source_id() const { return source_id_; } static std::unique_ptr<DevToolsTargetsUIHandler> CreateForLocal( - const Callback& callback); + const Callback& callback, + Profile* profile); static std::unique_ptr<DevToolsTargetsUIHandler> CreateForAdb( const Callback& callback,
diff --git a/chrome/browser/devtools/devtools_window.cc b/chrome/browser/devtools/devtools_window.cc index 4f6c33a..29fbdeb 100644 --- a/chrome/browser/devtools/devtools_window.cc +++ b/chrome/browser/devtools/devtools_window.cc
@@ -1034,8 +1034,15 @@ const std::string& panel, bool has_other_clients) { std::string url; + +// Modules are always bundled in CrOS. +#if defined(OS_CHROMEOS) + std::string remote_base = "?"; +#else std::string remote_base = "?remoteBase=" + DevToolsUI::GetRemoteBaseURL().spec(); +#endif + // remoteFrontend is here for backwards compatibility only. std::string remote_frontend = frontend_url + ((frontend_url.find("?") == std::string::npos)
diff --git a/chrome/browser/extensions/BUILD.gn b/chrome/browser/extensions/BUILD.gn index 33b7c04..9f5dd3df 100644 --- a/chrome/browser/extensions/BUILD.gn +++ b/chrome/browser/extensions/BUILD.gn
@@ -1143,7 +1143,6 @@ deps += [ "//ui/aura", "//ui/keyboard", - "//ui/keyboard:keyboard_with_content", "//ui/keyboard:resources", ] }
diff --git a/chrome/browser/extensions/api/identity/identity_apitest.cc b/chrome/browser/extensions/api/identity/identity_apitest.cc index 373c808..57203683 100644 --- a/chrome/browser/extensions/api/identity/identity_apitest.cc +++ b/chrome/browser/extensions/api/identity/identity_apitest.cc
@@ -2346,13 +2346,14 @@ EXPECT_FALSE(HasExpectedEvent()); } -// Test that an event is fired for changes to a secondary account when there is -// a primary account available. -IN_PROC_BROWSER_TEST_F(OnSignInChangedEventTest, - FireForSecondaryAccountWhenPrimaryAccountExists) { +// Test that an event is fired for changes to a secondary account. +IN_PROC_BROWSER_TEST_F(OnSignInChangedEventTest, FireForSecondaryAccount) { id_api()->SetAccountStateForTesting("primary", false); id_api()->SetAccountStateForTesting("secondary", false); + // NOTE: The current implementation requires that the primary account be + // present for an event to fire for secondary accounts. This is not actually + // part of the semantics of chrome.identity.OnSignInEventChanged, however. SignIn("primary", "primary"); api::identity::AccountInfo account_info; @@ -2372,75 +2373,6 @@ EXPECT_FALSE(HasExpectedEvent()); } -// Test that an event is not fired for changes to a secondary account when -// there is no primary account available. -IN_PROC_BROWSER_TEST_F(OnSignInChangedEventTest, - DontFireForSecondaryAccountWhenNoPrimaryAccountExists) { - // Add an expected event to be able to verify that no event is fired. - api::identity::AccountInfo account_info; - account_info.id = "secondary"; - AddExpectedEvent(api::identity::OnSignInChanged::Create(account_info, true)); - - // Check not firing on addition of secondary account. - AddAccount("secondary", "secondary"); - EXPECT_TRUE(HasExpectedEvent()); - - // Check not firing on token revocation of secondary account. - token_service_->RevokeCredentials("primary"); - EXPECT_TRUE(HasExpectedEvent()); -} - -// The below tests involve elements that aren't relevant on ChromeOS: -// - Signin of secondary accounts before the primary account signs in. On -// ChromeOS, this isn't possible. -// - Signout of the primary account. On ChromeOS, this isn't possible. -#if !defined(OS_CHROMEOS) -// Test that signin events are fired for all known accounts when the primary -// account signs in and there is a secondary account already present. Note that -// the order in which the events fire is undefined. -IN_PROC_BROWSER_TEST_F(OnSignInChangedEventTest, - FireForAllAccountsOnPrimaryAccountSignIn) { - id_api()->SetAccountStateForTesting("primary", false); - id_api()->SetAccountStateForTesting("secondary", false); - - api::identity::AccountInfo account_info; - account_info.id = "secondary"; - AddExpectedEvent(api::identity::OnSignInChanged::Create(account_info, true)); - - // Add the secondary account, and verify that no event is yet fired for it. - AddAccount("secondary", "secondary"); - EXPECT_TRUE(HasExpectedEvent()); - - // Add an event for the primary account in preparation for signing in. - account_info.id = "primary"; - AddExpectedEvent(api::identity::OnSignInChanged::Create(account_info, true)); - - // Sign in with the primary account, and verify that both events are fired. - SignIn("primary", "primary"); - EXPECT_FALSE(HasExpectedEvent()); -} - -// Test that signout events are fired for all known accounts when the primary -// account signs out. Note that the order in which the events fire is undefined. -IN_PROC_BROWSER_TEST_F(OnSignInChangedEventTest, - FireForAllAccountsOnPrimaryAccountSignOut) { - id_api()->SetAccountStateForTesting("primary", true); - id_api()->SetAccountStateForTesting("secondary", true); - - api::identity::AccountInfo account_info; - account_info.id = "primary"; - AddExpectedEvent(api::identity::OnSignInChanged::Create(account_info, false)); - - account_info.id = "secondary"; - AddExpectedEvent(api::identity::OnSignInChanged::Create(account_info, false)); - - // Sign out and verify that both events fire. - signin_manager_->ForceSignOut(); - - EXPECT_FALSE(HasExpectedEvent()); -} -#endif // !defined(OS_CHROMEOS) - } // namespace extensions // Tests the chrome.identity API implemented by custom JS bindings .
diff --git a/chrome/browser/extensions/api/management/management_browsertest.cc b/chrome/browser/extensions/api/management/management_browsertest.cc index b539137c..69c58730 100644 --- a/chrome/browser/extensions/api/management/management_browsertest.cc +++ b/chrome/browser/extensions/api/management/management_browsertest.cc
@@ -122,15 +122,28 @@ // Tests that installing the same version overwrites. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_InstallSameVersion) { - const Extension* extension = InstallExtension( - test_data_dir_.AppendASCII("install/install.crx"), 1); + base::ScopedAllowBlockingForTesting allow_blocking; + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + + base::FilePath root_path = test_data_dir_.AppendASCII("install"); + base::FilePath pem_path = root_path.AppendASCII("install.pem"); + base::FilePath first_path = + PackExtensionWithOptions(root_path.AppendASCII("install"), + temp_dir.GetPath().AppendASCII("install.crx"), + pem_path, base::FilePath()); + base::FilePath second_path = PackExtensionWithOptions( + root_path.AppendASCII("install_same_version"), + temp_dir.GetPath().AppendASCII("install_same_version.crx"), pem_path, + base::FilePath()); + + const Extension* extension = InstallExtension(first_path, 1); ASSERT_TRUE(extension); base::FilePath old_path = extension->path(); // Install an extension with the same version. The previous install should be // overwritten. - extension = InstallExtension( - test_data_dir_.AppendASCII("install/install_same_version.crx"), 0); + extension = InstallExtension(second_path, 0); ASSERT_TRUE(extension); base::FilePath new_path = extension->path(); @@ -139,22 +152,48 @@ } IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallOlderVersion) { - const Extension* extension = InstallExtension( - test_data_dir_.AppendASCII("install/install.crx"), 1); + base::ScopedAllowBlockingForTesting allow_blocking; + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + + base::FilePath root_path = test_data_dir_.AppendASCII("install"); + base::FilePath pem_path = root_path.AppendASCII("install.pem"); + base::FilePath modern_path = + PackExtensionWithOptions(root_path.AppendASCII("install"), + temp_dir.GetPath().AppendASCII("install.crx"), + pem_path, base::FilePath()); + base::FilePath older_path = PackExtensionWithOptions( + root_path.AppendASCII("install_older_version"), + temp_dir.GetPath().AppendASCII("install_older_version.crx"), pem_path, + base::FilePath()); + + const Extension* extension = InstallExtension(modern_path, 1); ASSERT_TRUE(extension); - ASSERT_FALSE(InstallExtension( - test_data_dir_.AppendASCII("install/install_older_version.crx"), 0)); + ASSERT_FALSE(InstallExtension(older_path, 0)); EXPECT_TRUE(IsExtensionAtVersion(extension, "1.0")); } IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallThenCancel) { - const Extension* extension = InstallExtension( - test_data_dir_.AppendASCII("install/install.crx"), 1); + base::ScopedAllowBlockingForTesting allow_blocking; + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + + base::FilePath root_path = test_data_dir_.AppendASCII("install"); + base::FilePath pem_path = root_path.AppendASCII("install.pem"); + base::FilePath v1_path = + PackExtensionWithOptions(root_path.AppendASCII("install"), + temp_dir.GetPath().AppendASCII("install.crx"), + pem_path, base::FilePath()); + base::FilePath v2_path = + PackExtensionWithOptions(root_path.AppendASCII("install_v2"), + temp_dir.GetPath().AppendASCII("install_v2.crx"), + pem_path, base::FilePath()); + + const Extension* extension = InstallExtension(v1_path, 1); ASSERT_TRUE(extension); // Cancel this install. - ASSERT_FALSE(StartInstallButCancel( - test_data_dir_.AppendASCII("install/install_v2.crx"))); + ASSERT_FALSE(StartInstallButCancel(v2_path)); EXPECT_TRUE(IsExtensionAtVersion(extension, "1.0")); } @@ -288,8 +327,20 @@ // Tests extension autoupdate. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_AutoUpdate) { - NotificationListener notification_listener; + base::ScopedAllowBlockingForTesting allow_blocking; + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + base::FilePath basedir = test_data_dir_.AppendASCII("autoupdate"); + NotificationListener notification_listener; + + base::FilePath pem_path = basedir.AppendASCII("key.pem"); + base::FilePath v1_path = PackExtensionWithOptions( + basedir.AppendASCII("v1"), temp_dir.GetPath().AppendASCII("v1.crx"), + pem_path, base::FilePath()); + base::FilePath v2_path = PackExtensionWithOptions( + basedir.AppendASCII("v2"), temp_dir.GetPath().AppendASCII("v2.crx"), + pem_path, base::FilePath()); // Note: This interceptor gets requests on the IO thread. net::LocalHostTestURLRequestInterceptor interceptor( @@ -302,7 +353,7 @@ GURL("http://localhost/autoupdate/manifest"), basedir.AppendASCII("manifest_v2.xml")); interceptor.SetResponseIgnoreQuery(GURL("http://localhost/autoupdate/v2.crx"), - basedir.AppendASCII("v2.crx")); + v2_path); // Install version 1 of the extension. ExtensionTestMessageListener listener1("v1 installed", false); @@ -311,8 +362,7 @@ ExtensionRegistry* registry = ExtensionRegistry::Get(browser()->profile()); const size_t size_before = registry->enabled_extensions().size(); ASSERT_TRUE(registry->disabled_extensions().is_empty()); - const Extension* extension = - InstallExtension(basedir.AppendASCII("v1.crx"), 1); + const Extension* extension = InstallExtension(v1_path, 1); ASSERT_TRUE(extension); listener1.WaitUntilSatisfied(); ASSERT_EQ(size_before + 1, registry->enabled_extensions().size()); @@ -379,8 +429,20 @@ // Tests extension autoupdate. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_AutoUpdateDisabledExtensions) { - NotificationListener notification_listener; + base::ScopedAllowBlockingForTesting allow_blocking; + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + base::FilePath basedir = test_data_dir_.AppendASCII("autoupdate"); + NotificationListener notification_listener; + + base::FilePath pem_path = basedir.AppendASCII("key.pem"); + base::FilePath v1_path = PackExtensionWithOptions( + basedir.AppendASCII("v1"), temp_dir.GetPath().AppendASCII("v1.crx"), + pem_path, base::FilePath()); + base::FilePath v2_path = PackExtensionWithOptions( + basedir.AppendASCII("v2"), temp_dir.GetPath().AppendASCII("v2.crx"), + pem_path, base::FilePath()); // Note: This interceptor gets requests on the IO thread. net::LocalHostTestURLRequestInterceptor interceptor( @@ -393,7 +455,7 @@ GURL("http://localhost/autoupdate/manifest"), basedir.AppendASCII("manifest_v2.xml")); interceptor.SetResponseIgnoreQuery(GURL("http://localhost/autoupdate/v2.crx"), - basedir.AppendASCII("v2.crx")); + v2_path); // Install version 1 of the extension. ExtensionTestMessageListener listener1("v1 installed", false); @@ -402,8 +464,7 @@ ExtensionRegistry* registry = ExtensionRegistry::Get(browser()->profile()); const size_t enabled_size_before = registry->enabled_extensions().size(); const size_t disabled_size_before = registry->disabled_extensions().size(); - const Extension* extension = - InstallExtension(basedir.AppendASCII("v1.crx"), 1); + const Extension* extension = InstallExtension(v1_path, 1); ASSERT_TRUE(extension); listener1.WaitUntilSatisfied(); DisableExtension(extension->id()); @@ -450,7 +511,15 @@ const char kExtensionId[] = "ogjcoiohnmldgjemafoockdghcjciccf"; extensions::ExtensionUpdater::CheckParams params; + base::ScopedAllowBlockingForTesting allow_blocking; + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + base::FilePath basedir = test_data_dir_.AppendASCII("autoupdate"); + base::FilePath pem_path = basedir.AppendASCII("key.pem"); + base::FilePath v2_path = PackExtensionWithOptions( + basedir.AppendASCII("v2"), temp_dir.GetPath().AppendASCII("v2.crx"), + pem_path, base::FilePath()); // Note: This interceptor gets requests on the IO thread. net::LocalHostTestURLRequestInterceptor interceptor( @@ -463,7 +532,7 @@ GURL("http://localhost/autoupdate/manifest"), basedir.AppendASCII("manifest_v2.xml")); interceptor.SetResponseIgnoreQuery(GURL("http://localhost/autoupdate/v2.crx"), - basedir.AppendASCII("v2.crx")); + v2_path); ExtensionRegistry* registry = ExtensionRegistry::Get(browser()->profile()); const size_t size_before = registry->enabled_extensions().size(); @@ -519,7 +588,7 @@ << "External reinstall of a killed extension should leave it killed."; // Installing from non-external source. - ASSERT_TRUE(InstallExtension(basedir.AppendASCII("v2.crx"), 1)); + ASSERT_TRUE(InstallExtension(v2_path, 1)); EXPECT_FALSE(extension_prefs->IsExternalExtensionUninstalled(kExtensionId)) << "Reinstalling should clear the kill bit."; @@ -547,7 +616,15 @@ browser()->profile())->extension_service(); const char kExtensionId[] = "ogjcoiohnmldgjemafoockdghcjciccf"; + base::ScopedAllowBlockingForTesting allow_blocking; + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + base::FilePath basedir = test_data_dir_.AppendASCII("autoupdate"); + base::FilePath pem_path = basedir.AppendASCII("key.pem"); + base::FilePath v2_path = PackExtensionWithOptions( + basedir.AppendASCII("v2"), temp_dir.GetPath().AppendASCII("v2.crx"), + pem_path, base::FilePath()); // Note: This interceptor gets requests on the IO thread. net::LocalHostTestURLRequestInterceptor interceptor( @@ -560,7 +637,7 @@ GURL("http://localhost/autoupdate/manifest"), basedir.AppendASCII("manifest_v2.xml")); interceptor.SetResponseIgnoreQuery(GURL("http://localhost/autoupdate/v2.crx"), - basedir.AppendASCII("v2.crx")); + v2_path); ExtensionRegistry* registry = ExtensionRegistry::Get(browser()->profile()); const size_t size_before = registry->enabled_extensions().size(); @@ -631,6 +708,15 @@ base::FilePath basedir = test_data_dir_.AppendASCII("autoupdate"); ASSERT_TRUE(registry->disabled_extensions().is_empty()); + base::ScopedAllowBlockingForTesting allow_blocking; + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + + base::FilePath pem_path = basedir.AppendASCII("key.pem"); + base::FilePath v2_path = PackExtensionWithOptions( + basedir.AppendASCII("v2"), temp_dir.GetPath().AppendASCII("v2.crx"), + pem_path, base::FilePath()); + // Note: This interceptor gets requests on the IO thread. net::LocalHostTestURLRequestInterceptor interceptor( BrowserThread::GetTaskRunnerForThread(BrowserThread::IO), @@ -642,7 +728,7 @@ GURL("http://localhost/autoupdate/manifest"), basedir.AppendASCII("manifest_v2.xml")); interceptor.SetResponseIgnoreQuery(GURL("http://localhost/autoupdate/v2.crx"), - basedir.AppendASCII("v2.crx")); + v2_path); // Check that the policy is initially empty. ASSERT_TRUE(extensions::ExtensionManagementFactory::GetForBrowserContext( @@ -652,7 +738,7 @@ << kForceInstallNotEmptyHelp; // User install of the extension. - ASSERT_TRUE(InstallExtension(basedir.AppendASCII("v2.crx"), 1)); + ASSERT_TRUE(InstallExtension(v2_path, 1)); ASSERT_EQ(size_before + 1, registry->enabled_extensions().size()); const Extension* extension = service->GetExtensionById(kExtensionId, false); ASSERT_TRUE(extension); @@ -689,7 +775,7 @@ EXPECT_FALSE(extension); // User install again, but have it disabled too before setting the policy. - ASSERT_TRUE(InstallExtension(basedir.AppendASCII("v2.crx"), 1)); + ASSERT_TRUE(InstallExtension(v2_path, 1)); ASSERT_EQ(size_before + 1, registry->enabled_extensions().size()); extension = service->GetExtensionById(kExtensionId, false); ASSERT_TRUE(extension);
diff --git a/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate_unittest.cc b/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate_unittest.cc index f005de4ad..76caa25 100644 --- a/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate_unittest.cc +++ b/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate_unittest.cc
@@ -250,8 +250,16 @@ }; TEST_F(ChromeRuntimeAPIDelegateTest, RequestUpdateCheck) { - base::FilePath v1_path = data_dir().AppendASCII("autoupdate/v1.crx"); - base::FilePath v2_path = data_dir().AppendASCII("autoupdate/v2.crx"); + base::ScopedAllowBlockingForTesting allow_blocking; + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + + base::FilePath root_dir = data_dir().AppendASCII("autoupdate"); + base::FilePath pem_path = root_dir.AppendASCII("key.pem"); + base::FilePath v1_path = temp_dir.GetPath().AppendASCII("v1.crx"); + base::FilePath v2_path = temp_dir.GetPath().AppendASCII("v2.crx"); + PackCRX(root_dir.AppendASCII("v1"), pem_path, v1_path); + PackCRX(root_dir.AppendASCII("v2"), pem_path, v2_path); // Start by installing version 1. scoped_refptr<const Extension> v1(InstallCRX(v1_path, INSTALL_NEW));
diff --git a/chrome/browser/extensions/api/tabs/app_base_window.cc b/chrome/browser/extensions/api/tabs/app_base_window.cc index 438c839..324756e 100644 --- a/chrome/browser/extensions/api/tabs/app_base_window.cc +++ b/chrome/browser/extensions/api/tabs/app_base_window.cc
@@ -53,6 +53,10 @@ GetBaseWindow()->Hide(); } +bool AppBaseWindow::IsVisible() const { + return GetBaseWindow()->IsVisible(); +} + void AppBaseWindow::ShowInactive() { GetBaseWindow()->ShowInactive(); }
diff --git a/chrome/browser/extensions/api/tabs/app_base_window.h b/chrome/browser/extensions/api/tabs/app_base_window.h index f606100..d9ccfb5 100644 --- a/chrome/browser/extensions/api/tabs/app_base_window.h +++ b/chrome/browser/extensions/api/tabs/app_base_window.h
@@ -35,6 +35,7 @@ gfx::Rect GetBounds() const override; void Show() override; void Hide() override; + bool IsVisible() const override; void ShowInactive() override; void Close() override; void Activate() override;
diff --git a/chrome/browser/extensions/bookmark_app_helper.cc b/chrome/browser/extensions/bookmark_app_helper.cc index 726c354..b5f2cf6f 100644 --- a/chrome/browser/extensions/bookmark_app_helper.cc +++ b/chrome/browser/extensions/bookmark_app_helper.cc
@@ -592,6 +592,7 @@ weak_factory_.GetWeakPtr())); } } else { + installable_ = INSTALLABLE_NO; OnIconsDownloaded(true, std::map<GURL, std::vector<SkBitmap>>()); } }
diff --git a/chrome/browser/extensions/bookmark_app_helper_unittest.cc b/chrome/browser/extensions/bookmark_app_helper_unittest.cc index 73e013a..82a0904 100644 --- a/chrome/browser/extensions/bookmark_app_helper_unittest.cc +++ b/chrome/browser/extensions/bookmark_app_helper_unittest.cc
@@ -346,6 +346,8 @@ helper.Create(base::Bind(&TestBookmarkAppHelper::CreationComplete, base::Unretained(&helper))); + helper.CompleteInstallableCheck(kManifestUrl, content::Manifest(), false); + std::map<GURL, std::vector<SkBitmap> > icon_map; icon_map[GURL(kAppUrl)].push_back( CreateSquareBitmapWithColor(kIconSizeSmall, SK_ColorRED));
diff --git a/chrome/browser/extensions/chrome_component_extension_resource_manager.cc b/chrome/browser/extensions/chrome_component_extension_resource_manager.cc index f93958a..0205bb2 100644 --- a/chrome/browser/extensions/chrome_component_extension_resource_manager.cc +++ b/chrome/browser/extensions/chrome_component_extension_resource_manager.cc
@@ -17,10 +17,7 @@ #include "components/chrome_apps/chrome_apps_resource_util.h" #include "ui/file_manager/file_manager_resource_util.h" #include "ui/file_manager/grit/file_manager_resources.h" -#endif - -#if defined(USE_AURA) -#include "ui/keyboard/content/keyboard_content_util.h" +#include "ui/keyboard/keyboard_resource_util.h" #endif namespace extensions {
diff --git a/chrome/browser/extensions/extension_resource_request_policy_apitest.cc b/chrome/browser/extensions/extension_resource_request_policy_apitest.cc index 5352af40..e46ff5b3 100644 --- a/chrome/browser/extensions/extension_resource_request_policy_apitest.cc +++ b/chrome/browser/extensions/extension_resource_request_policy_apitest.cc
@@ -41,11 +41,9 @@ // extension_resource_request_policy.*, but we have it as a browser test so that // can make sure it works end-to-end. IN_PROC_BROWSER_TEST_F(ExtensionResourceRequestPolicyTest, OriginPrivileges) { - ASSERT_TRUE(LoadExtensionWithFlags(test_data_dir_ - .AppendASCII("extension_resource_request_policy") - .AppendASCII("extension"), - // Tests manifest_version 1 behavior, so warnings are expected. - ExtensionBrowserTest::kFlagIgnoreManifestWarnings)); + ASSERT_TRUE(LoadExtension( + test_data_dir_.AppendASCII("extension_resource_request_policy") + .AppendASCII("extension"))); GURL web_resource(embedded_test_server()->GetURL( "/extensions/api_test/extension_resource_request_policy/" @@ -98,11 +96,9 @@ // A different extension. Legacy (manifest_version 1) extensions should always // be able to load each other's resources. - ASSERT_TRUE(LoadExtensionWithFlags(test_data_dir_ - .AppendASCII("extension_resource_request_policy") - .AppendASCII("extension2"), - // Tests manifest_version 1 behavior, so warnings are expected. - ExtensionBrowserTest::kFlagIgnoreManifestWarnings)); + ASSERT_TRUE(LoadExtension( + test_data_dir_.AppendASCII("extension_resource_request_policy") + .AppendASCII("extension2"))); ui_test_utils::NavigateToURL( browser(), GURL("chrome-extension://pbkkcbgdkliohhfaeefcijaghglkahja/index.html")); @@ -115,25 +111,20 @@ IN_PROC_BROWSER_TEST_F(ExtensionResourceRequestPolicyTest, ExtensionCanLoadHostedAppIcons) { - ASSERT_TRUE(LoadExtensionWithFlags(test_data_dir_ - .AppendASCII("extension_resource_request_policy") - .AppendASCII("extension"), - // Tests manifest_version 1 behavior, so warnings are expected. - ExtensionBrowserTest::kFlagIgnoreManifestWarnings)); + ASSERT_TRUE(LoadExtension( + test_data_dir_.AppendASCII("extension_resource_request_policy") + .AppendASCII("hosted_app"))); - ASSERT_TRUE(RunExtensionSubtest( - "extension_resource_request_policy/extension2/", - "can_load_icons_from_hosted_apps.html", - // Tests manifest_version 1 behavior, so warnings are expected. - ExtensionApiTest::kFlagIgnoreManifestWarnings)) << message_; + ASSERT_TRUE( + RunExtensionSubtest("extension_resource_request_policy/extension2/", + "can_load_icons_from_hosted_apps.html")) + << message_; } IN_PROC_BROWSER_TEST_F(ExtensionResourceRequestPolicyTest, Audio) { EXPECT_TRUE(RunExtensionSubtest( - "extension_resource_request_policy/extension2", - "audio.html", - // Tests manifest_version 1 behavior, so warnings are expected. - ExtensionApiTest::kFlagIgnoreManifestWarnings)) << message_; + "extension_resource_request_policy/extension2", "audio.html")) + << message_; } #if defined(OS_MACOSX) || defined(OS_WIN) @@ -145,10 +136,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionResourceRequestPolicyTest, MAYBE_Video) { EXPECT_TRUE(RunExtensionSubtest( - "extension_resource_request_policy/extension2", - "video.html", - // Tests manifest_version 1 behavior, so warnings are expected. - ExtensionApiTest::kFlagIgnoreManifestWarnings)) << message_; + "extension_resource_request_policy/extension2", "video.html")) + << message_; } // This test times out regularly on win_rel trybots. See http://crbug.com/122154
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index a6128bc..8eacebd 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -1474,13 +1474,19 @@ const char kStopInBackgroundName[] = "Stop in background"; const char kStopInBackgroundDescription[] = "Stop scheduler task queues, in the background, " - " after certain grace time."; + " after a grace period."; const char kStopLoadingInBackgroundName[] = "Stop loading in background"; const char kStopLoadingInBackgroundDescription[] = "Stop loading tasks and loading " "resources, in the background, after certain grace time."; +const char kStopNonTimersInBackgroundName[] = + "Stop non-timer task queues background"; +const char kStopNonTimersInBackgroundDescription[] = + "Stop non-timer task queues, in the background, " + "after a grace period."; + const char kSuggestionsWithSubStringMatchName[] = "Substring matching for Autofill suggestions"; const char kSuggestionsWithSubStringMatchDescription[] =
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 035cee2..1320c28 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -903,6 +903,9 @@ extern const char kStopLoadingInBackgroundName[]; extern const char kStopLoadingInBackgroundDescription[]; +extern const char kStopNonTimersInBackgroundName[]; +extern const char kStopNonTimersInBackgroundDescription[]; + extern const char kTLS13VariantName[]; extern const char kTLS13VariantDescription[]; extern const char kTLS13VariantDisabled[];
diff --git a/chrome/browser/pdf/pdf_extension_test.cc b/chrome/browser/pdf/pdf_extension_test.cc index b5bb3376..c8c995d 100644 --- a/chrome/browser/pdf/pdf_extension_test.cc +++ b/chrome/browser/pdf/pdf_extension_test.cc
@@ -1533,8 +1533,8 @@ blink::WebGestureEvent smart_zoom_event( blink::WebInputEvent::kGestureDoubleTap, blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::GetStaticTimeStampForTests()); - smart_zoom_event.source_device = blink::kWebGestureDeviceTouchpad; + blink::WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchpad); smart_zoom_event.data.tap.tap_count = 1; EXPECT_TRUE(browser()->PreHandleGestureEvent(GetActiveWebContents(),
diff --git a/chrome/browser/prefs/browser_prefs.cc b/chrome/browser/prefs/browser_prefs.cc index a1bb49f..91b4eb6 100644 --- a/chrome/browser/prefs/browser_prefs.cc +++ b/chrome/browser/prefs/browser_prefs.cc
@@ -272,6 +272,7 @@ #include "chrome/browser/apps/app_launch_for_metro_restart_win.h" #include "chrome/browser/component_updater/sw_reporter_installer_win.h" #if defined(GOOGLE_CHROME_BUILD) +#include "chrome/browser/conflicts/module_database_win.h" #include "chrome/browser/conflicts/problematic_programs_updater_win.h" #endif // defined(GOOGLE_CHROME_BUILD) #include "chrome/browser/safe_browsing/chrome_cleaner/settings_resetter_win.h" @@ -466,6 +467,7 @@ desktop_ios_promotion::RegisterLocalPrefs(registry); password_manager::PasswordManager::RegisterLocalPrefs(registry); #if defined(GOOGLE_CHROME_BUILD) + ModuleDatabase::RegisterLocalStatePrefs(registry); ProblematicProgramsUpdater::RegisterLocalStatePrefs(registry); #endif // defined(GOOGLE_CHROME_BUILD) #endif
diff --git a/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc b/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc index 79222de..04a7fa43 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc +++ b/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc
@@ -323,10 +323,13 @@ IN_PROC_BROWSER_TEST_F(ContextMenuBrowserTest, OpenInAppAbsentForURLsInScopeWhenDesktopPWAsDisabled) { - auto feature_list = std::make_unique<base::test::ScopedFeatureList>(); - feature_list->InitAndEnableFeature(features::kDesktopPWAWindowing); - InstallTestBookmarkApp(GURL(kAppUrl1)); - feature_list.reset(); + { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature(features::kDesktopPWAWindowing); + InstallTestBookmarkApp(GURL(kAppUrl1)); + } + base::test::ScopedFeatureList feature_list; + feature_list.InitAndDisableFeature(features::kDesktopPWAWindowing); std::unique_ptr<TestRenderViewContextMenu> menu = CreateContextMenuMediaTypeNone(GURL(kAppUrl1), GURL(kAppUrl1));
diff --git a/chrome/browser/renderer_context_menu/render_view_context_menu_unittest.cc b/chrome/browser/renderer_context_menu/render_view_context_menu_unittest.cc index 085556b..c59cb50e 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu_unittest.cc +++ b/chrome/browser/renderer_context_menu/render_view_context_menu_unittest.cc
@@ -7,6 +7,7 @@ #include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/scoped_feature_list.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/custom_handlers/protocol_handler_registry.h" @@ -18,6 +19,7 @@ #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings_factory.h" #include "chrome/browser/prefs/incognito_mode_prefs.h" #include "chrome/browser/renderer_context_menu/render_view_context_menu_test_util.h" +#include "chrome/common/chrome_features.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "chrome/test/base/testing_profile.h" @@ -100,13 +102,19 @@ class RenderViewContextMenuTest : public testing::Test { protected: - RenderViewContextMenuTest() = default; + RenderViewContextMenuTest() + : RenderViewContextMenuTest( + std::unique_ptr<extensions::TestExtensionEnvironment>()) {} + // If the test uses a TestExtensionEnvironment, which provides a MessageLoop, // it needs to be passed to the constructor so that it exists before the // RenderViewHostTestEnabler which needs to use the MessageLoop. explicit RenderViewContextMenuTest( std::unique_ptr<extensions::TestExtensionEnvironment> env) - : environment_(std::move(env)) {} + : environment_(std::move(env)) { + // TODO(mgiuca): Add tests with DesktopPWAs enabled. + feature_list_.InitAndDisableFeature(features::kDesktopPWAWindowing); + } // Proxy defined here to minimize friend classes in RenderViewContextMenu static bool ExtensionContextAndPatternMatch( @@ -135,6 +143,7 @@ private: content::RenderViewHostTestEnabler rvh_test_enabler_; + base::test::ScopedFeatureList feature_list_; DISALLOW_COPY_AND_ASSIGN(RenderViewContextMenuTest); }; @@ -375,6 +384,8 @@ RenderViewContextMenuPrefsTest() = default; void SetUp() override { + // TODO(mgiuca): Add tests with DesktopPWAs enabled. + feature_list_.InitAndDisableFeature(features::kDesktopPWAWindowing); ChromeRenderViewHostTestHarness::SetUp(); registry_ = std::make_unique<ProtocolHandlerRegistry>(profile(), nullptr); } @@ -448,6 +459,7 @@ private: std::unique_ptr<ProtocolHandlerRegistry> registry_; + base::test::ScopedFeatureList feature_list_; DISALLOW_COPY_AND_ASSIGN(RenderViewContextMenuPrefsTest); };
diff --git a/chrome/browser/resources/chromeos/login/oobe_eula.html b/chrome/browser/resources/chromeos/login/oobe_eula.html index 48fc992..533c8b8 100644 --- a/chrome/browser/resources/chromeos/login/oobe_eula.html +++ b/chrome/browser/resources/chromeos/login/oobe_eula.html
@@ -72,10 +72,10 @@ </a> <div id="logging" class="layout horizontal"> <paper-checkbox id="usageStats" checked="{{usageStatsChecked}}" - on-change="onUsageChanged_"> + on-change="onUsageChanged_" aria-labelledby="usageStatsLabel"> </paper-checkbox> <div id="usageStatsLabelContainer"> - <span i18n-content="checkboxLogging"></span> + <span id="usageStatsLabel" i18n-content="checkboxLogging"></span> <a id="" href="#" i18n-content="learnMore" on-tap="onUsageStatsHelpLinkClicked_"> </a>
diff --git a/chrome/browser/resources/hangout_services/manifest.json b/chrome/browser/resources/hangout_services/manifest.json index 712e83a8..8ad88fea 100644 --- a/chrome/browser/resources/hangout_services/manifest.json +++ b/chrome/browser/resources/hangout_services/manifest.json
@@ -9,9 +9,7 @@ "manifest_version": 2, "externally_connectable": { "matches": [ - "https://*.google.com/*", - // For tests. - "*://localhost/*" + "https://*.google.com/*" ] }, "background": {
diff --git a/chrome/browser/resources/settings/passwords_and_forms_page/autofill_section.html b/chrome/browser/resources/settings/passwords_and_forms_page/autofill_section.html index 4490ec4..f454436 100644 --- a/chrome/browser/resources/settings/passwords_and_forms_page/autofill_section.html +++ b/chrome/browser/resources/settings/passwords_and_forms_page/autofill_section.html
@@ -65,9 +65,9 @@ } </style> <settings-toggle-button id="autofillToggle" - class="first primary-toggle" + class="first" aria-label="$i18n{autofill}" no-extension-indicator - label="[[getOnOffLabel_(prefs.autofill.enabled.value)]]" + label="$i18n{autofillFormsLabel}" pref="{{prefs.autofill.enabled}}"> </settings-toggle-button> <template is="dom-if" if="[[prefs.autofill.enabled.extensionId]]">
diff --git a/chrome/browser/resources/settings/passwords_and_forms_page/passwords_section.html b/chrome/browser/resources/settings/passwords_and_forms_page/passwords_section.html index 8eb81a0..147f3ecf 100644 --- a/chrome/browser/resources/settings/passwords_and_forms_page/passwords_section.html +++ b/chrome/browser/resources/settings/passwords_and_forms_page/passwords_section.html
@@ -55,9 +55,9 @@ } </style> <settings-toggle-button id="passwordToggle" - class="first primary-toggle" + class="first" aria-label="$i18n{passwords}" no-extension-indicator - label="[[getOnOffLabel_(prefs.credentials_enable_service.value)]]" + label="$i18n{passwordsSavePasswordsLabel}" pref="{{prefs.credentials_enable_service}}"> </settings-toggle-button> <template is="dom-if"
diff --git a/chrome/browser/ssl/ssl_browsertest.cc b/chrome/browser/ssl/ssl_browsertest.cc index 50deb04..a674fbc 100644 --- a/chrome/browser/ssl/ssl_browsertest.cc +++ b/chrome/browser/ssl/ssl_browsertest.cc
@@ -171,6 +171,8 @@ using security_interstitials::SecurityInterstitialControllerClient; using web_modal::WebContentsModalDialogManager; +namespace { + const base::FilePath::CharType kDocRoot[] = FILE_PATH_LITERAL("chrome/test/data"); @@ -178,8 +180,6 @@ const char kHstsTestHostName[] = "hsts-example.test"; -namespace { - enum ProceedDecision { SSL_INTERSTITIAL_PROCEED, SSL_INTERSTITIAL_DO_NOT_PROCEED
diff --git a/chrome/browser/subresource_filter/subresource_filter_browser_test_harness.cc b/chrome/browser/subresource_filter/subresource_filter_browser_test_harness.cc index 03b6ac84..9557f511 100644 --- a/chrome/browser/subresource_filter/subresource_filter_browser_test_harness.cc +++ b/chrome/browser/subresource_filter/subresource_filter_browser_test_harness.cc
@@ -39,10 +39,7 @@ namespace subresource_filter { SubresourceFilterBrowserTest::SubresourceFilterBrowserTest() { - scoped_feature_list_.InitWithFeatures( - {kSafeBrowsingSubresourceFilter, - kSafeBrowsingSubresourceFilterExperimentalUI, kAbusiveExperienceEnforce}, - {}); + scoped_feature_list_.InitAndEnableFeature(kAdTagging); } SubresourceFilterBrowserTest::~SubresourceFilterBrowserTest() {}
diff --git a/chrome/browser/subresource_filter/subresource_filter_browsertest.cc b/chrome/browser/subresource_filter/subresource_filter_browsertest.cc index c658e2f..45969d7 100644 --- a/chrome/browser/subresource_filter/subresource_filter_browsertest.cc +++ b/chrome/browser/subresource_filter/subresource_filter_browsertest.cc
@@ -710,7 +710,10 @@ } IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTest, LazyRulesetValidation) { - // The ruleset shouldn't be validated until it's used. + // The ruleset shouldn't be validated until it's used, unless ad tagging is + // enabled. + base::test::ScopedFeatureList feature_list; + feature_list.InitAndDisableFeature(subresource_filter::kAdTagging); SetRulesetToDisallowURLsWithPathSuffix("included_script.js"); RulesetVerificationStatus dealer_status = GetRulesetVerification(); EXPECT_EQ(RulesetVerificationStatus::NOT_VERIFIED, dealer_status);
diff --git a/chrome/browser/sync/test/integration/two_client_uss_sync_test.cc b/chrome/browser/sync/test/integration/two_client_uss_sync_test.cc index e000b2b..e869f6a 100644 --- a/chrome/browser/sync/test/integration/two_client_uss_sync_test.cc +++ b/chrome/browser/sync/test/integration/two_client_uss_sync_test.cc
@@ -19,10 +19,12 @@ #include "components/sync/model/metadata_change_list.h" #include "components/sync/model/model_error.h" #include "components/sync/model/model_type_change_processor.h" +#include "components/sync/model_impl/client_tag_based_model_type_processor.h" #include "net/base/network_change_notifier.h" using browser_sync::ChromeSyncClient; using browser_sync::ProfileSyncComponentsFactoryImpl; +using syncer::ClientTagBasedModelTypeProcessor; using syncer::ConflictResolution; using syncer::FakeModelTypeSyncBridge; using syncer::ModelTypeChangeProcessor; @@ -66,9 +68,11 @@ }; TestModelTypeSyncBridge() - : FakeModelTypeSyncBridge(base::Bind(&ModelTypeChangeProcessor::Create, - base::RepeatingClosure())) { - change_processor()->ModelReadyToSync(db().CreateMetadataBatch()); + : FakeModelTypeSyncBridge( + std::make_unique<ClientTagBasedModelTypeProcessor>( + syncer::PREFERENCES, + /*dump_stack=*/base::RepeatingClosure())) { + change_processor()->ModelReadyToSync(this, db().CreateMetadataBatch()); } base::Optional<syncer::ModelError> ApplySyncChanges(
diff --git a/chrome/browser/sync/user_event_service_factory.cc b/chrome/browser/sync/user_event_service_factory.cc index d5e40f1..a0e6a4a8 100644 --- a/chrome/browser/sync/user_event_service_factory.cc +++ b/chrome/browser/sync/user_event_service_factory.cc
@@ -15,6 +15,7 @@ #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/sync/base/model_type.h" #include "components/sync/base/report_unrecoverable_error.h" +#include "components/sync/model_impl/client_tag_based_model_type_processor.h" #include "components/sync/user_events/no_op_user_event_service.h" #include "components/sync/user_events/user_event_service_impl.h" #include "components/sync/user_events/user_event_sync_bridge.h" @@ -53,12 +54,13 @@ syncer::OnceModelTypeStoreFactory store_factory = browser_sync::ProfileSyncService::GetModelTypeStoreFactory( profile->GetPath()); - syncer::ModelTypeSyncBridge::ChangeProcessorFactory processor_factory = - base::BindRepeating(&syncer::ModelTypeChangeProcessor::Create, - base::BindRepeating(&syncer::ReportUnrecoverableError, - chrome::GetChannel())); + auto change_processor = + std::make_unique<syncer::ClientTagBasedModelTypeProcessor>( + syncer::USER_EVENTS, + base::BindRepeating(&syncer::ReportUnrecoverableError, + chrome::GetChannel())); auto bridge = std::make_unique<syncer::UserEventSyncBridge>( - std::move(store_factory), std::move(processor_factory), + std::move(store_factory), std::move(change_processor), sync_service->GetGlobalIdMapper()); return new syncer::UserEventServiceImpl(sync_service, std::move(bridge)); }
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index 452ba8c..22bc6fa0 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -3410,7 +3410,6 @@ deps += [ "//ui/aura", "//ui/keyboard", - "//ui/keyboard:keyboard_with_content", "//ui/keyboard:resources", "//ui/wm", ]
diff --git a/chrome/browser/ui/app_list/chrome_app_list_model_updater.cc b/chrome/browser/ui/app_list/chrome_app_list_model_updater.cc index 2232123..0a0b3f99 100644 --- a/chrome/browser/ui/app_list/chrome_app_list_model_updater.cc +++ b/chrome/browser/ui/app_list/chrome_app_list_model_updater.cc
@@ -351,9 +351,9 @@ // have an attribute to do this when we refactor SearchResult. for (const auto& result : *search_model_->results()) { if (result->title() == target_title && - result->result_type() == app_list::SearchResult::RESULT_INSTALLED_APP && + result->result_type() == ash::SearchResultType::kInstalledApp && result->display_type() != - app_list::SearchResult::DISPLAY_RECOMMENDATION) { + ash::SearchResultDisplayType::kRecommendation) { return result.get(); } }
diff --git a/chrome/browser/ui/app_list/search/answer_card/answer_card_result.cc b/chrome/browser/ui/app_list/search/answer_card/answer_card_result.cc index fe92a0e..aa070fb 100644 --- a/chrome/browser/ui/app_list/search/answer_card/answer_card_result.cc +++ b/chrome/browser/ui/app_list/search/answer_card/answer_card_result.cc
@@ -21,7 +21,7 @@ list_controller_(list_controller), contents_(contents) { DCHECK(!stripped_result_url.empty()); - set_display_type(DISPLAY_CARD); + set_display_type(ash::SearchResultDisplayType::kCard); set_id(result_url); set_comparable_id(stripped_result_url); set_relevance(1);
diff --git a/chrome/browser/ui/app_list/search/answer_card/answer_card_result_unittest.cc b/chrome/browser/ui/app_list/search/answer_card/answer_card_result_unittest.cc index 7a179d9..67144e4 100644 --- a/chrome/browser/ui/app_list/search/answer_card/answer_card_result_unittest.cc +++ b/chrome/browser/ui/app_list/search/answer_card/answer_card_result_unittest.cc
@@ -86,7 +86,7 @@ EXPECT_EQ(kResultUrl, result->id()); EXPECT_EQ(base::ASCIIToUTF16(kResultTitle), result->title()); - EXPECT_EQ(SearchResult::DISPLAY_CARD, result->display_type()); + EXPECT_EQ(ash::SearchResultDisplayType::kCard, result->display_type()); EXPECT_EQ(1, result->relevance()); EXPECT_EQ(GetToken(), result->answer_card_contents_token()); @@ -97,7 +97,7 @@ EXPECT_EQ(kResultUrl, result1->id()); EXPECT_EQ(base::ASCIIToUTF16(kResultTitle), result1->title()); - EXPECT_EQ(SearchResult::DISPLAY_CARD, result1->display_type()); + EXPECT_EQ(ash::SearchResultDisplayType::kCard, result1->display_type()); EXPECT_EQ(1, result1->relevance()); EXPECT_EQ(GetToken(), result1->answer_card_contents_token()); }
diff --git a/chrome/browser/ui/app_list/search/answer_card/answer_card_search_provider_unittest.cc b/chrome/browser/ui/app_list/search/answer_card/answer_card_search_provider_unittest.cc index 3f2b813..a005206 100644 --- a/chrome/browser/ui/app_list/search/answer_card/answer_card_search_provider_unittest.cc +++ b/chrome/browser/ui/app_list/search/answer_card/answer_card_search_provider_unittest.cc
@@ -109,7 +109,7 @@ EXPECT_EQ(1UL, results().size()); SearchResult* result = results()[0].get(); - EXPECT_EQ(SearchResult::DISPLAY_CARD, result->display_type()); + EXPECT_EQ(ash::SearchResultDisplayType::kCard, result->display_type()); EXPECT_EQ(id, result->id()); EXPECT_EQ(1, result->relevance()); EXPECT_EQ(token, result->answer_card_contents_token());
diff --git a/chrome/browser/ui/app_list/search/app_result.cc b/chrome/browser/ui/app_list/search/app_result.cc index bb74ecd2..6ad8b9b 100644 --- a/chrome/browser/ui/app_list/search/app_result.cc +++ b/chrome/browser/ui/app_list/search/app_result.cc
@@ -16,8 +16,10 @@ : profile_(profile), app_id_(app_id), controller_(controller) { - set_display_type(is_recommendation ? DISPLAY_RECOMMENDATION : DISPLAY_TILE); - set_result_type(RESULT_INSTALLED_APP); + set_display_type(is_recommendation + ? ash::SearchResultDisplayType::kRecommendation + : ash::SearchResultDisplayType::kTile); + set_result_type(ash::SearchResultType::kInstalledApp); } AppResult::~AppResult() {
diff --git a/chrome/browser/ui/app_list/search/arc/arc_app_data_search_provider_unittest.cc b/chrome/browser/ui/app_list/search/arc/arc_app_data_search_provider_unittest.cc index d02252b..bcb7742 100644 --- a/chrome/browser/ui/app_list/search/arc/arc_app_data_search_provider_unittest.cc +++ b/chrome/browser/ui/app_list/search/arc/arc_app_data_search_provider_unittest.cc
@@ -64,7 +64,7 @@ SCOPED_TRACE(base::StringPrintf("Testing result %zu", i)); EXPECT_EQ(base::UTF16ToUTF8(results[i]->title()), base::StringPrintf("Label %s %zu", kQuery, i)); - EXPECT_EQ(SearchResult::DISPLAY_TILE, results[i]->display_type()); + EXPECT_EQ(ash::SearchResultDisplayType::kTile, results[i]->display_type()); } }
diff --git a/chrome/browser/ui/app_list/search/arc/arc_app_data_search_result.cc b/chrome/browser/ui/app_list/search/arc/arc_app_data_search_result.cc index e732c93..113c218 100644 --- a/chrome/browser/ui/app_list/search/arc/arc_app_data_search_result.cc +++ b/chrome/browser/ui/app_list/search/arc/arc_app_data_search_result.cc
@@ -83,7 +83,7 @@ weak_ptr_factory_(this) { set_title(base::UTF8ToUTF16(label())); set_id(kAppDataSearchPrefix + launch_intent_uri()); - set_display_type(DISPLAY_TILE); + set_display_type(ash::SearchResultDisplayType::kTile); icon_decode_request_ = std::make_unique<IconDecodeRequest>( base::BindOnce(&ArcAppDataSearchResult::SetIconToAvatarIcon,
diff --git a/chrome/browser/ui/app_list/search/arc/arc_playstore_search_provider_unittest.cc b/chrome/browser/ui/app_list/search/arc/arc_playstore_search_provider_unittest.cc index 4a369bfa..1096b29 100644 --- a/chrome/browser/ui/app_list/search/arc/arc_playstore_search_provider_unittest.cc +++ b/chrome/browser/ui/app_list/search/arc/arc_playstore_search_provider_unittest.cc
@@ -92,14 +92,14 @@ SCOPED_TRACE(base::StringPrintf("Testing result %zu", i)); EXPECT_EQ(base::UTF16ToUTF8(results[i]->title()), base::StringPrintf("%s %zu", kQuery, i)); - EXPECT_EQ(results[i]->display_type(), SearchResult::DISPLAY_TILE); + EXPECT_EQ(results[i]->display_type(), ash::SearchResultDisplayType::kTile); EXPECT_EQ(base::UTF16ToUTF8(results[i]->formatted_price()), base::StringPrintf("$%zu.22", i)); EXPECT_EQ(results[i]->rating(), i); const bool is_instant_app = i % 2 == 0; EXPECT_EQ(results[i]->result_type(), - is_instant_app ? SearchResult::RESULT_INSTANT_APP - : SearchResult::RESULT_PLAYSTORE_APP); + is_instant_app ? ash::SearchResultType::kInstantApp + : ash::SearchResultType::kPlayStoreApp); } }
diff --git a/chrome/browser/ui/app_list/search/arc/arc_playstore_search_result.cc b/chrome/browser/ui/app_list/search/arc/arc_playstore_search_result.cc index cc23468..d4d8fdd 100644 --- a/chrome/browser/ui/app_list/search/arc/arc_playstore_search_result.cc +++ b/chrome/browser/ui/app_list/search/arc/arc_playstore_search_result.cc
@@ -66,13 +66,14 @@ set_title(base::UTF8ToUTF16(label().value())); set_id(kPlayAppPrefix + crx_file::id_util::GenerateId(install_intent_uri().value())); - set_display_type(DISPLAY_TILE); + set_display_type(ash::SearchResultDisplayType::kTile); SetBadgeIcon(gfx::CreateVectorIcon( is_instant_app() ? kIcBadgeInstantIcon : kIcBadgePlayIcon, kAppBadgeIconSize, kBadgeColor)); SetFormattedPrice(base::UTF8ToUTF16(formatted_price().value())); SetRating(review_score()); - set_result_type(is_instant_app() ? RESULT_INSTANT_APP : RESULT_PLAYSTORE_APP); + set_result_type(is_instant_app() ? ash::SearchResultType::kInstantApp + : ash::SearchResultType::kPlayStoreApp); icon_decode_request_ = std::make_unique<IconDecodeRequest>(base::BindOnce( &ArcPlayStoreSearchResult::SetIcon, weak_ptr_factory_.GetWeakPtr()));
diff --git a/chrome/browser/ui/app_list/search/arc_app_result.cc b/chrome/browser/ui/app_list/search/arc_app_result.cc index d80e419..8eccac2 100644 --- a/chrome/browser/ui/app_list/search/arc_app_result.cc +++ b/chrome/browser/ui/app_list/search/arc_app_result.cc
@@ -45,7 +45,7 @@ void ArcAppResult::Open(int event_flags) { // Record the search metric if the result is not a suggested app. - if (display_type() != DISPLAY_RECOMMENDATION) + if (display_type() != ash::SearchResultDisplayType::kRecommendation) RecordHistogram(APP_SEARCH_RESULT); if (!arc::LaunchApp(profile(), app_id(), event_flags, @@ -59,9 +59,9 @@ } std::unique_ptr<SearchResult> ArcAppResult::Duplicate() const { - std::unique_ptr<SearchResult> copy = - std::make_unique<ArcAppResult>(profile(), app_id(), controller(), - display_type() == DISPLAY_RECOMMENDATION); + std::unique_ptr<SearchResult> copy = std::make_unique<ArcAppResult>( + profile(), app_id(), controller(), + display_type() == ash::SearchResultDisplayType::kRecommendation); copy->set_title(title()); copy->set_title_tags(title_tags()); copy->set_relevance(relevance());
diff --git a/chrome/browser/ui/app_list/search/extension_app_result.cc b/chrome/browser/ui/app_list/search/extension_app_result.cc index 8514f8d..1d254887 100644 --- a/chrome/browser/ui/app_list/search/extension_app_result.cc +++ b/chrome/browser/ui/app_list/search/extension_app_result.cc
@@ -66,7 +66,7 @@ return; // Record the search metrics if the SearchResult is not a suggested app. - if (display_type() != DISPLAY_RECOMMENDATION) { + if (display_type() != ash::SearchResultDisplayType::kRecommendation) { RecordHistogram(APP_SEARCH_RESULT); extensions::RecordAppListSearchLaunch(extension); } @@ -81,7 +81,7 @@ std::unique_ptr<SearchResult> ExtensionAppResult::Duplicate() const { std::unique_ptr<SearchResult> copy = std::make_unique<ExtensionAppResult>( profile(), app_id(), controller(), - display_type() == DISPLAY_RECOMMENDATION); + display_type() == ash::SearchResultDisplayType::kRecommendation); copy->set_title(title()); copy->set_title_tags(title_tags()); copy->set_relevance(relevance());
diff --git a/chrome/browser/ui/app_list/search/mixer.cc b/chrome/browser/ui/app_list/search/mixer.cc index dbe84ca..e439f3b 100644 --- a/chrome/browser/ui/app_list/search/mixer.cc +++ b/chrome/browser/ui/app_list/search/mixer.cc
@@ -72,7 +72,8 @@ // become dominated by previously clicked results. This happens // because the recommendation query is the empty string and the // clicked results get forever boosted. - if (result->display_type() != SearchResult::DISPLAY_RECOMMENDATION) { + if (result->display_type() != + ash::SearchResultDisplayType::kRecommendation) { KnownResults::const_iterator known_it = known_results.find(result->id()); if (known_it != known_results.end()) {
diff --git a/chrome/browser/ui/app_list/search/search_controller.cc b/chrome/browser/ui/app_list/search/search_controller.cc index dd377fd..d90715b 100644 --- a/chrome/browser/ui/app_list/search/search_controller.cc +++ b/chrome/browser/ui/app_list/search/search_controller.cc
@@ -52,10 +52,10 @@ UMA_HISTOGRAM_ENUMERATION(kSearchResultOpenDisplayTypeHistogram, result->display_type(), - SearchResult::DISPLAY_TYPE_LAST); + ash::SearchResultDisplayType::kLast); // Record the search metric if the SearchResult is not a suggested app. - if (result->display_type() != SearchResult::DISPLAY_RECOMMENDATION) { + if (result->display_type() != ash::SearchResultDisplayType::kRecommendation) { // Count AppList.Search here because it is composed of search + action. base::RecordAction(base::UserMetricsAction("AppList_OpenSearchResult"));
diff --git a/chrome/browser/ui/app_list/search/tests/mixer_unittest.cc b/chrome/browser/ui/app_list/search/tests/mixer_unittest.cc index 0224a5a..39313dd 100644 --- a/chrome/browser/ui/app_list/search/tests/mixer_unittest.cc +++ b/chrome/browser/ui/app_list/search/tests/mixer_unittest.cc
@@ -74,7 +74,7 @@ : prefix_(prefix), count_(0), bad_relevance_range_(false), - display_type_(SearchResult::DISPLAY_LIST) {} + display_type_(ash::SearchResultDisplayType::kList) {} ~TestSearchProvider() override {} // SearchProvider overrides: @@ -283,7 +283,8 @@ TEST_F(MixerTest, KnownResultsIgnoredForRecommendations) { // This gives omnibox 0 -- 5. omnibox_provider()->set_count(6); - omnibox_provider()->set_display_type(SearchResult::DISPLAY_RECOMMENDATION); + omnibox_provider()->set_display_type( + ash::SearchResultDisplayType::kRecommendation); // omnibox 1 -- 4 are "known results". AddKnownResult("omnibox1", PREFIX_SECONDARY);
diff --git a/chrome/browser/ui/ash/chrome_keyboard_ui.cc b/chrome/browser/ui/ash/chrome_keyboard_ui.cc index b64c179..b5d94c29 100644 --- a/chrome/browser/ui/ash/chrome_keyboard_ui.cc +++ b/chrome/browser/ui/ash/chrome_keyboard_ui.cc
@@ -44,9 +44,9 @@ #include "ui/base/ime/text_input_client.h" #include "ui/compositor/scoped_layer_animation_settings.h" #include "ui/gfx/geometry/insets.h" -#include "ui/keyboard/content/keyboard_constants.h" #include "ui/keyboard/keyboard_controller.h" #include "ui/keyboard/keyboard_controller_observer.h" +#include "ui/keyboard/keyboard_resource_util.h" #include "ui/keyboard/keyboard_switches.h" #include "ui/keyboard/keyboard_util.h" #include "ui/wm/core/shadow.h"
diff --git a/chrome/browser/ui/ash/keyboard_controller_browsertest.cc b/chrome/browser/ui/ash/keyboard_controller_browsertest.cc index 30dbfd00..1d9cdf8 100644 --- a/chrome/browser/ui/ash/keyboard_controller_browsertest.cc +++ b/chrome/browser/ui/ash/keyboard_controller_browsertest.cc
@@ -19,8 +19,8 @@ #include "ui/base/ime/dummy_text_input_client.h" #include "ui/base/ime/input_method.h" #include "ui/base/ime/input_method_factory.h" -#include "ui/keyboard/content/keyboard_constants.h" #include "ui/keyboard/keyboard_controller.h" +#include "ui/keyboard/keyboard_resource_util.h" #include "ui/keyboard/keyboard_switches.h" #include "ui/keyboard/keyboard_test_util.h" #include "ui/keyboard/keyboard_ui.h"
diff --git a/chrome/browser/ui/ash/keyboard_end_to_end_browsertest.cc b/chrome/browser/ui/ash/keyboard_end_to_end_browsertest.cc index ef5f305..9d15e7e 100644 --- a/chrome/browser/ui/ash/keyboard_end_to_end_browsertest.cc +++ b/chrome/browser/ui/ash/keyboard_end_to_end_browsertest.cc
@@ -12,8 +12,8 @@ #include "chrome/test/base/ui_test_utils.h" #include "content/public/test/browser_test_utils.h" #include "ui/aura/window_tree_host.h" -#include "ui/keyboard/content/keyboard_constants.h" #include "ui/keyboard/keyboard_controller.h" +#include "ui/keyboard/keyboard_resource_util.h" #include "ui/keyboard/keyboard_switches.h" #include "ui/keyboard/keyboard_test_util.h" #include "ui/keyboard/keyboard_util.h"
diff --git a/chrome/browser/ui/ash/launcher/arc_app_window.cc b/chrome/browser/ui/ash/launcher/arc_app_window.cc index d3e8158d8..819a330 100644 --- a/chrome/browser/ui/ash/launcher/arc_app_window.cc +++ b/chrome/browser/ui/ash/launcher/arc_app_window.cc
@@ -115,6 +115,11 @@ NOTREACHED(); } +bool ArcAppWindow::IsVisible() const { + NOTREACHED(); + return true; +} + void ArcAppWindow::Close() { arc::CloseTask(task_id_); }
diff --git a/chrome/browser/ui/ash/launcher/arc_app_window.h b/chrome/browser/ui/ash/launcher/arc_app_window.h index cc452196..23a5fbc 100644 --- a/chrome/browser/ui/ash/launcher/arc_app_window.h +++ b/chrome/browser/ui/ash/launcher/arc_app_window.h
@@ -77,6 +77,7 @@ void Show() override; void ShowInactive() override; void Hide() override; + bool IsVisible() const override; void Close() override; void Activate() override; void Deactivate() override;
diff --git a/chrome/browser/ui/cocoa/apps/native_app_window_cocoa.h b/chrome/browser/ui/cocoa/apps/native_app_window_cocoa.h index a3a729aa..f82d3b88 100644 --- a/chrome/browser/ui/cocoa/apps/native_app_window_cocoa.h +++ b/chrome/browser/ui/cocoa/apps/native_app_window_cocoa.h
@@ -67,6 +67,7 @@ void Show() override; void ShowInactive() override; void Hide() override; + bool IsVisible() const override; void Close() override; void Activate() override; void Deactivate() override;
diff --git a/chrome/browser/ui/cocoa/apps/native_app_window_cocoa.mm b/chrome/browser/ui/cocoa/apps/native_app_window_cocoa.mm index ae8dece3..ed108dd2 100644 --- a/chrome/browser/ui/cocoa/apps/native_app_window_cocoa.mm +++ b/chrome/browser/ui/cocoa/apps/native_app_window_cocoa.mm
@@ -470,6 +470,10 @@ HideWithoutMarkingHidden(); } +bool NativeAppWindowCocoa::IsVisible() const { + return [window() isVisible]; +} + void NativeAppWindowCocoa::Close() { [window() close]; }
diff --git a/chrome/browser/ui/cocoa/browser_window_cocoa.h b/chrome/browser/ui/cocoa/browser_window_cocoa.h index 1bacb0f..c5e4eda 100644 --- a/chrome/browser/ui/cocoa/browser_window_cocoa.h +++ b/chrome/browser/ui/cocoa/browser_window_cocoa.h
@@ -44,6 +44,7 @@ void Show() override; void ShowInactive() override; void Hide() override; + bool IsVisible() const override; void SetBounds(const gfx::Rect& bounds) override; void Close() override; void Activate() override;
diff --git a/chrome/browser/ui/cocoa/browser_window_cocoa.mm b/chrome/browser/ui/cocoa/browser_window_cocoa.mm index fc053dc..542f68a 100644 --- a/chrome/browser/ui/cocoa/browser_window_cocoa.mm +++ b/chrome/browser/ui/cocoa/browser_window_cocoa.mm
@@ -156,6 +156,10 @@ [window() orderOut:controller_]; } +bool BrowserWindowCocoa::IsVisible() const { + return [window() isVisible]; +} + void BrowserWindowCocoa::SetBounds(const gfx::Rect& bounds) { gfx::Rect real_bounds = [controller_ enforceMinWindowSize:bounds];
diff --git a/chrome/browser/ui/extensions/hosted_app_browser_controller.cc b/chrome/browser/ui/extensions/hosted_app_browser_controller.cc index c614ab4..4d6184d3 100644 --- a/chrome/browser/ui/extensions/hosted_app_browser_controller.cc +++ b/chrome/browser/ui/extensions/hosted_app_browser_controller.cc
@@ -67,6 +67,9 @@ // static bool HostedAppBrowserController::IsForHostedApp(const Browser* browser) { + if (!browser) + return false; + const std::string extension_id = web_app::GetExtensionIdFromApplicationName(browser->app_name()); const Extension* extension =
diff --git a/chrome/browser/ui/startup/startup_browser_creator_impl.cc b/chrome/browser/ui/startup/startup_browser_creator_impl.cc index fe6b7334..c146cdf7 100644 --- a/chrome/browser/ui/startup/startup_browser_creator_impl.cc +++ b/chrome/browser/ui/startup/startup_browser_creator_impl.cc
@@ -679,6 +679,8 @@ // Check if there are any incompatible applications cached from the last // Chrome run. has_incompatible_applications = + ProblematicProgramsUpdater:: + IsIncompatibleApplicationsWarningEnabled() && ProblematicProgramsUpdater::HasCachedPrograms(); } #endif
diff --git a/chrome/browser/ui/views/frame/browser_view.cc b/chrome/browser/ui/views/frame/browser_view.cc index 707ed6b..c86f056 100644 --- a/chrome/browser/ui/views/frame/browser_view.cc +++ b/chrome/browser/ui/views/frame/browser_view.cc
@@ -630,6 +630,10 @@ // Not implemented. } +bool BrowserView::IsVisible() const { + return frame_->IsVisible(); +} + void BrowserView::SetBounds(const gfx::Rect& bounds) { ExitFullscreen(); GetWidget()->SetBounds(bounds);
diff --git a/chrome/browser/ui/views/frame/browser_view.h b/chrome/browser/ui/views/frame/browser_view.h index a61dbe8..ccdf8bf 100644 --- a/chrome/browser/ui/views/frame/browser_view.h +++ b/chrome/browser/ui/views/frame/browser_view.h
@@ -270,6 +270,7 @@ void Show() override; void ShowInactive() override; void Hide() override; + bool IsVisible() const override; void SetBounds(const gfx::Rect& bounds) override; void Close() override; void Activate() override;
diff --git a/chrome/browser/ui/views/hover_button.cc b/chrome/browser/ui/views/hover_button.cc index 3ded50b3..77b1692 100644 --- a/chrome/browser/ui/views/hover_button.cc +++ b/chrome/browser/ui/views/hover_button.cc
@@ -209,6 +209,14 @@ HoverButton::~HoverButton() {} +bool HoverButton::OnKeyPressed(const ui::KeyEvent& event) { + // Unlike MenuButton, HoverButton should not be activated when the up or down + // arrow key is pressed. + if (event.key_code() == ui::VKEY_UP || event.key_code() == ui::VKEY_DOWN) + return false; + return MenuButton::OnKeyPressed(event); +} + void HoverButton::SetBorder(std::unique_ptr<views::Border> b) { MenuButton::SetBorder(std::move(b)); // Make sure the minimum size is correct according to the layout (if any). @@ -220,6 +228,16 @@ Button::GetAccessibleNodeData(node_data); } +bool HoverButton::IsTriggerableEventType(const ui::Event& event) { + // HoverButton should only be triggered on mouse released, like normal + // buttons. To make sure that the button listener is only notified when the + // mouse was released, the event type must be explicitly checked here, since + // Button::IsTriggerableEvent() returns true even it was just a press. + if (event.IsMouseEvent()) + return event.type() == ui::ET_MOUSE_RELEASED; + return Button::IsTriggerableEvent(event); +} + void HoverButton::SetSubtitleElideBehavior(gfx::ElideBehavior elide_behavior) { if (subtitle_ && !subtitle_->text().empty()) subtitle_->SetElideBehavior(elide_behavior);
diff --git a/chrome/browser/ui/views/hover_button.h b/chrome/browser/ui/views/hover_button.h index bd35b0c0..da31701 100644 --- a/chrome/browser/ui/views/hover_button.h +++ b/chrome/browser/ui/views/hover_button.h
@@ -49,8 +49,10 @@ ~HoverButton() override; // views::MenuButton: + bool OnKeyPressed(const ui::KeyEvent& event) override; void SetBorder(std::unique_ptr<views::Border> b) override; void GetAccessibleNodeData(ui::AXNodeData* node_data) override; + bool IsTriggerableEventType(const ui::Event& event) override; // Updates the title text, and applies the secondary style to the text // specified by |range|. If |range| is invalid, no style is applied. This
diff --git a/chrome/browser/ui/views/profiles/forced_reauthentication_dialog_view.cc b/chrome/browser/ui/views/profiles/forced_reauthentication_dialog_view.cc index 9ac7391..889c25d 100644 --- a/chrome/browser/ui/views/profiles/forced_reauthentication_dialog_view.cc +++ b/chrome/browser/ui/views/profiles/forced_reauthentication_dialog_view.cc
@@ -52,8 +52,7 @@ bool IsMatchingBrowser(Browser* browser, Profile* profile) { return browser->profile()->GetOriginalProfile() == profile->GetOriginalProfile() && - !browser->tab_strip_model()->empty() && - BrowserView::GetBrowserViewForBrowser(browser)->frame()->IsVisible(); + !browser->tab_strip_model()->empty() && browser->window()->IsVisible(); } // Find a browser that is associated with |profile| to show the dialog for
diff --git a/chrome/browser/ui/webui/inspect_ui.cc b/chrome/browser/ui/webui/inspect_ui.cc index ab19c4d..65d8f55 100644 --- a/chrome/browser/ui/webui/inspect_ui.cc +++ b/chrome/browser/ui/webui/inspect_ui.cc
@@ -478,7 +478,7 @@ PopulateAdditionalTargets(additional_targets); AddTargetUIHandler( - DevToolsTargetsUIHandler::CreateForLocal(callback)); + DevToolsTargetsUIHandler::CreateForLocal(callback, profile)); if (profile->IsOffTheRecord()) { ShowIncognitoWarning(); } else {
diff --git a/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc b/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc index f5036ca..4425a0d 100644 --- a/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc +++ b/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc
@@ -1319,6 +1319,7 @@ {"autofill", IDS_SETTINGS_AUTOFILL}, {"googlePayments", IDS_SETTINGS_GOOGLE_PAYMENTS}, {"googlePaymentsCached", IDS_SETTINGS_GOOGLE_PAYMENTS_CACHED}, + {"autofillFormsLabel", IDS_SETTINGS_AUTOFILL_TOGGLE_LABEL}, {"addresses", IDS_SETTINGS_AUTOFILL_ADDRESSES_HEADING}, {"addAddressTitle", IDS_SETTINGS_AUTOFILL_ADDRESSES_ADD_TITLE}, {"editAddressTitle", IDS_SETTINGS_AUTOFILL_ADDRESSES_EDIT_TITLE}, @@ -1340,6 +1341,8 @@ {"addCreditCardTitle", IDS_SETTINGS_ADD_CREDIT_CARD_TITLE}, {"autofillDetail", IDS_SETTINGS_AUTOFILL_DETAIL}, {"passwords", IDS_SETTINGS_PASSWORDS}, + {"passwordsSavePasswordsLabel", + IDS_SETTINGS_PASSWORDS_SAVE_PASSWORDS_TOGGLE_LABEL}, {"passwordsAutosigninLabel", IDS_SETTINGS_PASSWORDS_AUTOSIGNIN_CHECKBOX_LABEL}, {"passwordsAutosigninDescription",
diff --git a/chrome/browser/ui/webui/settings/md_settings_ui.cc b/chrome/browser/ui/webui/settings/md_settings_ui.cc index 2475c9d..c3d1a1d2 100644 --- a/chrome/browser/ui/webui/settings/md_settings_ui.cc +++ b/chrome/browser/ui/webui/settings/md_settings_ui.cc
@@ -230,6 +230,7 @@ #if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) bool has_incompatible_applications = + ProblematicProgramsUpdater::IsIncompatibleApplicationsWarningEnabled() && ProblematicProgramsUpdater::HasCachedPrograms(); html_source->AddBoolean("showIncompatibleApplications", has_incompatible_applications);
diff --git a/chrome/browser/ui/webui/settings/people_handler.cc b/chrome/browser/ui/webui/settings/people_handler.cc index 80d282a..ec8213d 100644 --- a/chrome/browser/ui/webui/settings/people_handler.cc +++ b/chrome/browser/ui/webui/settings/people_handler.cc
@@ -381,8 +381,9 @@ } void PeopleHandler::OnDidClosePage(const base::ListValue* args) { - // Don't mark setup as complete if "didAbort" is true. - if (!args->GetList()[0].GetBool()) { + // Don't mark setup as complete if "didAbort" is true, or if authentication + // is still needed. + if (!args->GetList()[0].GetBool() && !IsProfileAuthNeeded()) { MarkFirstSetupComplete(); } @@ -616,7 +617,8 @@ void PeopleHandler::HandleShowSetupUI(const base::ListValue* args) { AllowJavascript(); - if (!GetSyncService()) { + ProfileSyncService* service = GetSyncService(); + if (!service) { CloseUI(); return; } @@ -632,7 +634,38 @@ return; } - OpenSyncSetup(); + // Notify services that login UI is now active. + GetLoginUIService()->SetLoginUI(this); + + if (!sync_blocker_) + sync_blocker_ = service->GetSetupInProgressHandle(); + + // Early exit if there is already a preferences push pending sync startup. + if (sync_startup_tracker_) + return; + + if (!service->IsEngineInitialized()) { + // Requesting the sync service to start may trigger call to PushSyncPrefs. + // Setting up the startup tracker beforehand correctly signals the + // re-entrant call to early exit. + sync_startup_tracker_.reset(new SyncStartupTracker(profile_, this)); + service->RequestStart(); + + // See if it's even possible to bring up the sync engine - if not + // (unrecoverable error?), don't bother displaying a spinner that will be + // immediately closed because this leads to some ugly infinite UI loop (see + // http://crbug.com/244769). + if (SyncStartupTracker::GetSyncServiceState(profile_) != + SyncStartupTracker::SYNC_STARTUP_ERROR) { + DisplaySpinner(); + } + return; + } + + // User is already logged in. They must have brought up the config wizard + // via the "Advanced..." button or through One-Click signin (cases 4-6), or + // they are re-enabling sync after having disabled it (case 7). + PushSyncPrefs(); } #if defined(OS_CHROMEOS) @@ -750,42 +783,6 @@ configuring_sync_ = false; } -void PeopleHandler::OpenSyncSetup() { - // Notify services that login UI is now active. - GetLoginUIService()->SetLoginUI(this); - - ProfileSyncService* service = GetSyncService(); - if (service && !sync_blocker_) - sync_blocker_ = service->GetSetupInProgressHandle(); - - // Early exit if there is already a preferences push pending sync startup. - if (sync_startup_tracker_) - return; - - if (!service->IsEngineInitialized()) { - // Requesting the sync service to start may trigger call to PushSyncPrefs. - // Setting up the startup tracker beforehand correctly signals the - // re-entrant call to early exit. - sync_startup_tracker_.reset(new SyncStartupTracker(profile_, this)); - service->RequestStart(); - - // See if it's even possible to bring up the sync engine - if not - // (unrecoverable error?), don't bother displaying a spinner that will be - // immediately closed because this leads to some ugly infinite UI loop (see - // http://crbug.com/244769). - if (SyncStartupTracker::GetSyncServiceState(profile_) != - SyncStartupTracker::SYNC_STARTUP_ERROR) { - DisplaySpinner(); - } - return; - } - - // User is already logged in. They must have brought up the config wizard - // via the "Advanced..." button or through One-Click signin (cases 4-6), or - // they are re-enabling sync after having disabled it (case 7). - PushSyncPrefs(); -} - void PeopleHandler::InitializeSyncBlocker() { if (!web_ui()) return;
diff --git a/chrome/browser/ui/webui/settings/people_handler.h b/chrome/browser/ui/webui/settings/people_handler.h index 4c462354..c02178f 100644 --- a/chrome/browser/ui/webui/settings/people_handler.h +++ b/chrome/browser/ui/webui/settings/people_handler.h
@@ -68,9 +68,6 @@ explicit PeopleHandler(Profile* profile); ~PeopleHandler() override; - // Initializes the sync setup flow and shows the setup UI. - void OpenSyncSetup(); - // Terminates the sync setup flow. void CloseSyncSetup(); @@ -83,9 +80,26 @@ DisplayConfigureWithEngineDisabledAndCancel); FRIEND_TEST_ALL_PREFIXES( PeopleHandlerTest, + DisplayConfigureWithEngineDisabledAndCancelAfterSigninSuccess); + FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, + DisplayConfigureWithEngineDisabledAndSigninFailed); + FRIEND_TEST_ALL_PREFIXES( + PeopleHandlerTest, DisplayConfigureWithEngineDisabledAndSyncStartupCompleted); FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, HandleSetupUIWhenSyncDisabled); FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, SelectCustomEncryption); + FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, + ShowSetupCustomPassphraseRequired); + FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, ShowSetupEncryptAll); + FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, ShowSetupEncryptAllDisallowed); + FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, ShowSetupManuallySyncAll); + FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, + ShowSetupOldGaiaPassphraseRequired); + FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, ShowSetupSyncEverything); + FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, + ShowSetupSyncForAllTypesIndividually); + FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, ShowSigninOnAuthError); + FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, ShowSyncSetup); FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, ShowSyncSetupWhenNotSignedIn); FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, SuccessfullySetPassphrase); FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, TestSyncEverything);
diff --git a/chrome/browser/ui/webui/settings/people_handler_unittest.cc b/chrome/browser/ui/webui/settings/people_handler_unittest.cc index 1331211..8964c907 100644 --- a/chrome/browser/ui/webui/settings/people_handler_unittest.cc +++ b/chrome/browser/ui/webui/settings/people_handler_unittest.cc
@@ -358,7 +358,7 @@ TEST_F(PeopleHandlerTest, ShowSyncSetupWhenNotSignedIn) { EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(false)); EXPECT_CALL(*mock_pss_, IsFirstSetupComplete()).WillRepeatedly(Return(false)); - handler_->HandleShowSetupUI(NULL); + handler_->HandleShowSetupUI(nullptr); ExpectPageStatusChanged(PeopleHandler::kDonePageStatus); @@ -373,7 +373,7 @@ // sync is disabled. TEST_F(PeopleHandlerTest, HandleSetupUIWhenSyncDisabled) { EXPECT_CALL(*mock_pss_, IsManaged()).WillRepeatedly(Return(true)); - handler_->HandleShowSetupUI(NULL); + handler_->HandleShowSetupUI(nullptr); // Sync setup is closed when sync is disabled. EXPECT_EQ( @@ -396,7 +396,7 @@ // engine will try to download control data types (e.g encryption info), but // that won't finish for this test as we're simulating cancelling while the // spinner is showing. - handler_->HandleShowSetupUI(NULL); + handler_->HandleShowSetupUI(nullptr); EXPECT_EQ( handler_.get(), @@ -417,7 +417,7 @@ EXPECT_CALL(*mock_pss_, RequestStart()); SetDefaultExpectationsForConfigPage(); - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); EXPECT_EQ(1U, web_ui_.call_data().size()); ExpectPageStatusChanged(PeopleHandler::kSpinnerPageStatus); @@ -454,7 +454,7 @@ .WillRepeatedly(Return(true)); EXPECT_CALL(*mock_pss_, RequestStart()); SetDefaultExpectationsForConfigPage(); - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); // It's important to tell sync the user cancelled the setup flow before we // tell it we're through with the setup progress. @@ -475,7 +475,7 @@ EXPECT_CALL(*mock_pss_, IsEngineInitialized()).WillRepeatedly(Return(false)); EXPECT_CALL(*mock_pss_, RequestStart()); - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); ExpectPageStatusChanged(PeopleHandler::kSpinnerPageStatus); Mock::VerifyAndClearExpectations(mock_pss_); error_ = GoogleServiceAuthError( @@ -532,7 +532,7 @@ .WillRepeatedly(Return(false)); EXPECT_CALL(*mock_pss_, IsFirstSetupComplete()).WillRepeatedly(Return(false)); // Open the web UI. - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); ASSERT_FALSE(handler_->is_configuring_sync()); } @@ -542,7 +542,7 @@ EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(false)); EXPECT_CALL(*mock_pss_, IsFirstSetupComplete()).WillRepeatedly(Return(false)); // Open the web UI. - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); ASSERT_FALSE(handler_->is_configuring_sync()); } @@ -551,7 +551,7 @@ EXPECT_CALL(*mock_pss_, CanSyncStart()).WillRepeatedly(Return(false)); EXPECT_CALL(*mock_pss_, IsFirstSetupComplete()).WillRepeatedly(Return(false)); // Open the web UI. - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); ASSERT_FALSE(handler_->is_configuring_sync()); } @@ -751,7 +751,7 @@ SetupInitializedProfileSyncService(); // This should display the sync setup dialog (not login). SetDefaultExpectationsForConfigPage(); - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); ExpectSyncPrefsChanged(); } @@ -787,7 +787,7 @@ // On ChromeOS, this should display the spinner while we try to startup the // sync engine, and on desktop this displays the login dialog. - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); // Sync setup is closed when re-auth is in progress. EXPECT_EQ( @@ -806,7 +806,7 @@ SetupInitializedProfileSyncService(); SetDefaultExpectationsForConfigPage(); // This should display the sync setup dialog (not login). - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); const base::DictionaryValue* dictionary = ExpectSyncPrefsChanged(); CheckBool(dictionary, "syncAllDataTypes", true); @@ -836,7 +836,7 @@ sync_prefs.SetKeepEverythingSynced(false); SetDefaultExpectationsForConfigPage(); // This should display the sync setup dialog (not login). - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); const base::DictionaryValue* dictionary = ExpectSyncPrefsChanged(); CheckConfigDataTypeArguments(dictionary, CHOOSE_WHAT_TO_SYNC, GetAllTypes()); @@ -860,7 +860,7 @@ WillRepeatedly(Return(types)); // This should display the sync setup dialog (not login). - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); // Close the config overlay. LoginUIServiceFactory::GetForProfile(profile())->LoginUIClosed( @@ -884,7 +884,7 @@ SetDefaultExpectationsForConfigPage(); // This should display the sync setup dialog (not login). - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); const base::DictionaryValue* dictionary = ExpectSyncPrefsChanged(); CheckBool(dictionary, "passphraseRequired", true); @@ -900,7 +900,7 @@ SetDefaultExpectationsForConfigPage(); // This should display the sync setup dialog (not login). - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); const base::DictionaryValue* dictionary = ExpectSyncPrefsChanged(); CheckBool(dictionary, "passphraseRequired", true); @@ -918,7 +918,7 @@ .WillRepeatedly(Return(true)); // This should display the sync setup dialog (not login). - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); const base::DictionaryValue* dictionary = ExpectSyncPrefsChanged(); CheckBool(dictionary, "encryptAllData", true); @@ -935,7 +935,7 @@ .WillRepeatedly(Return(false)); // This should display the sync setup dialog (not login). - handler_->OpenSyncSetup(); + handler_->HandleShowSetupUI(nullptr); const base::DictionaryValue* dictionary = ExpectSyncPrefsChanged(); CheckBool(dictionary, "encryptAllData", false);
diff --git a/chrome/browser/vr/PRESUBMIT.py b/chrome/browser/vr/PRESUBMIT.py index c3aa1c2..16887ec 100644 --- a/chrome/browser/vr/PRESUBMIT.py +++ b/chrome/browser/vr/PRESUBMIT.py
@@ -60,7 +60,7 @@ 'luci.chromium.try:linux_optional_gpu_tests_rel', 'luci.chromium.try:mac_optional_gpu_tests_rel', 'master.tryserver.chromium.win:win_optional_gpu_tests_rel', - 'master.tryserver.chromium.android:android_optional_gpu_tests_rel', + 'luci.chromium.try:android_optional_gpu_tests_rel', 'master.tryserver.chromium.linux:linux_vr', ], 'Automatically added optional GPU tests to run on CQ.')
diff --git a/chrome/browser/vr/content_input_delegate.cc b/chrome/browser/vr/content_input_delegate.cc index 674d774d6..6c149db 100644 --- a/chrome/browser/vr/content_input_delegate.cc +++ b/chrome/browser/vr/content_input_delegate.cc
@@ -118,8 +118,9 @@ void ContentInputDelegate::UpdateGesture( const gfx::PointF& normalized_content_hit_point, blink::WebGestureEvent& gesture) { - gesture.x = content_tex_css_width_ * normalized_content_hit_point.x(); - gesture.y = content_tex_css_height_ * normalized_content_hit_point.y(); + gesture.SetPositionInWidget(ScalePoint(normalized_content_hit_point, + content_tex_css_width_, + content_tex_css_height_)); } void ContentInputDelegate::SendGestureToContent(
diff --git a/chrome/common/BUILD.gn b/chrome/common/BUILD.gn index d55b449..0a7569b 100644 --- a/chrome/common/BUILD.gn +++ b/chrome/common/BUILD.gn
@@ -388,7 +388,7 @@ } if (use_aura) { # This dependency is for a header used only by extensions code. - public_deps += [ "//ui/keyboard:keyboard_with_content" ] + public_deps += [ "//ui/keyboard:keyboard" ] } }
diff --git a/chrome/common/chrome_features.cc b/chrome/common/chrome_features.cc index 5682b22..66135ea 100644 --- a/chrome/common/chrome_features.cc +++ b/chrome/common/chrome_features.cc
@@ -182,8 +182,14 @@ #endif // Enables or disables windowing related features for desktop PWAs. -const base::Feature kDesktopPWAWindowing{"DesktopPWAWindowing", - base::FEATURE_DISABLED_BY_DEFAULT}; +const base::Feature kDesktopPWAWindowing { + "DesktopPWAWindowing", +#if defined(OS_CHROMEOS) + base::FEATURE_ENABLED_BY_DEFAULT +#else + base::FEATURE_DISABLED_BY_DEFAULT +#endif +}; // Enables or disables Desktop PWAs capturing links. const base::Feature kDesktopPWAsLinkCapturing{ @@ -314,6 +320,12 @@ const base::Feature kImprovedRecoveryComponent{ "ImprovedRecoveryComponent", base::FEATURE_DISABLED_BY_DEFAULT}; +#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +// A feature that controls whether Chrome warns about incompatible applications. +const base::Feature kIncompatibleApplicationsWarning{ + "IncompatibleApplicationsWarning", base::FEATURE_DISABLED_BY_DEFAULT}; +#endif + #if !defined(OS_ANDROID) // Enables Casting a Presentation API-enabled website to a secondary display. const base::Feature kLocalScreenCasting{"LocalScreenCasting", @@ -398,9 +410,10 @@ #endif // Enables the use of native notification centers instead of using the Message -// Center for displaying the toasts. Note that OS_LINUX includes Chrome OS. +// Center for displaying the toasts. #if BUILDFLAG(ENABLE_NATIVE_NOTIFICATIONS) -#if defined(OS_MACOSX) || defined(OS_ANDROID) || defined(OS_LINUX) +#if defined(OS_MACOSX) || defined(OS_ANDROID) || \ + (defined(OS_LINUX) && !defined(OS_CHROMEOS)) const base::Feature kNativeNotifications{"NativeNotifications", base::FEATURE_ENABLED_BY_DEFAULT}; #else
diff --git a/chrome/common/chrome_features.h b/chrome/common/chrome_features.h index b64e64dc..f86990b 100644 --- a/chrome/common/chrome_features.h +++ b/chrome/common/chrome_features.h
@@ -172,6 +172,10 @@ extern const base::Feature kImprovedRecoveryComponent; +#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) +extern const base::Feature kIncompatibleApplicationsWarning; +#endif + #if !defined(OS_ANDROID) extern const base::Feature kLocalScreenCasting; #endif
diff --git a/chrome/common/extensions/chrome_manifest_url_handlers.cc b/chrome/common/extensions/chrome_manifest_url_handlers.cc index 59238d8..02df04a 100644 --- a/chrome/common/extensions/chrome_manifest_url_handlers.cc +++ b/chrome/common/extensions/chrome_manifest_url_handlers.cc
@@ -25,7 +25,7 @@ #include "extensions/common/permissions/api_permission.h" #if defined(USE_AURA) -#include "ui/keyboard/content/keyboard_constants.h" // nogncheck +#include "ui/keyboard/keyboard_resource_util.h" // nogncheck #endif namespace extensions {
diff --git a/chrome/common/pref_names.cc b/chrome/common/pref_names.cc index 3dbe0464..9d1b909 100644 --- a/chrome/common/pref_names.cc +++ b/chrome/common/pref_names.cc
@@ -908,6 +908,11 @@ // be applied. See base::Version for exact string format. const char kMinimumAllowedChromeVersion[] = "minimum_req.version"; +// Boolean preference that triggers chrome://settings/syncSetup to be opened +// on user session start. +const char kShowSyncSettingsOnSessionStart[] = + "start_sync_settings_on_session_start"; + #endif // defined(OS_CHROMEOS) // A boolean pref set to true if a Home button to open the Home pages should be
diff --git a/chrome/common/pref_names.h b/chrome/common/pref_names.h index d624baf..9fabc5b 100644 --- a/chrome/common/pref_names.h +++ b/chrome/common/pref_names.h
@@ -300,6 +300,7 @@ extern const char kInstantTetheringBleAdvertisingSupported[]; extern const char kCastReceiverEnabled[]; extern const char kMinimumAllowedChromeVersion[]; +extern const char kShowSyncSettingsOnSessionStart[]; #endif // defined(OS_CHROMEOS) extern const char kShowHomeButton[]; extern const char kSpeechRecognitionFilterProfanities[];
diff --git a/chrome/test/base/test_browser_window.cc b/chrome/test/base/test_browser_window.cc index cd2334bc..6adc340 100644 --- a/chrome/test/base/test_browser_window.cc +++ b/chrome/test/base/test_browser_window.cc
@@ -108,6 +108,10 @@ return false; } +bool TestBrowserWindow::IsVisible() const { + return true; +} + LocationBar* TestBrowserWindow::GetLocationBar() const { return const_cast<TestLocationBar*>(&location_bar_); }
diff --git a/chrome/test/base/test_browser_window.h b/chrome/test/base/test_browser_window.h index 6614ad7..75060ad 100644 --- a/chrome/test/base/test_browser_window.h +++ b/chrome/test/base/test_browser_window.h
@@ -38,6 +38,7 @@ void Show() override {} void ShowInactive() override {} void Hide() override {} + bool IsVisible() const override; void SetBounds(const gfx::Rect& bounds) override {} void Close() override {} void Activate() override {}
diff --git a/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension/manifest.json b/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension/manifest.json index 588a679..9a7b415a 100644 --- a/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension/manifest.json +++ b/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension/manifest.json
@@ -1,5 +1,7 @@ { "description": "Extension 1", + "manifest_version": 2, + "web_accessible_resources": ["test.png"], "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDPOziAf8MbTjdUo6DysZ4nAU/2f/kwYnftyKkxI1GyTlbStprGy+Y2ek4/59QbE3xEE+dIIuYeObM4QTptpcFMg956ZLFoeDg41Pg3tzUrbltgG8hXTbBxN852FJx2kdaqa/MKUUsJKGSD5hkUmvZRADGGWhMWzvz64ao1h02xJQIDAQAB", "name": "test", "permissions": [ "http://a.com/*" ],
diff --git a/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/audio.html b/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/audio.html index 8ef69f4..e9290a2 100644 --- a/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/audio.html +++ b/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/audio.html
@@ -1 +1,5 @@ -<audio src="bear.wav" oncanplay="chrome.test.notifyPass()"> +<!doctype html> +<html> + <body></body> + <script src="audio.js"></script> +</html>
diff --git a/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/audio.js b/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/audio.js new file mode 100644 index 0000000..9af3705 --- /dev/null +++ b/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/audio.js
@@ -0,0 +1,8 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +let audio = document.createElement('audio'); +audio.oncanplay = () => { chrome.test.notifyPass(); }; +audio.src = chrome.runtime.getURL('bear.wav'); +document.body.appendChild(audio);
diff --git a/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/can_load_icons_from_hosted_apps.html b/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/can_load_icons_from_hosted_apps.html index 5504375..11840de 100644 --- a/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/can_load_icons_from_hosted_apps.html +++ b/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/can_load_icons_from_hosted_apps.html
@@ -1,3 +1,5 @@ -<img src="chrome-extension://fnbdbepgnidhjejikpionpfohdjjogpm/test.png" - onload="chrome.test.notifyPass()" - onerror="chrome.test.notifyFail('Should not have loaded')"> +<!doctype html> +<html> + <body></body> + <script src="can_load_icons_from_hosted_apps.js"></script> +</html>
diff --git a/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/can_load_icons_from_hosted_apps.js b/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/can_load_icons_from_hosted_apps.js new file mode 100644 index 0000000..d0ab9da --- /dev/null +++ b/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/can_load_icons_from_hosted_apps.js
@@ -0,0 +1,9 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +let image = document.createElement('img'); +image.onload = () => { chrome.test.notifyPass(); }; +image.onerror = () => { chrome.test.notifyFail('Image should have loaded'); }; +image.src = 'chrome-extension://ggmldgjhdenlnjjjmehkomheglpmijnf/test.png'; +document.body.appendChild(image);
diff --git a/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/index.html b/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/index.html index 4183769..da3eab8 100644 --- a/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/index.html +++ b/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/index.html
@@ -1,3 +1,6 @@ -<title>Unmodified</title> - -<img onload="document.title='Loaded'" onerror="document.title='Image failed to load'" src="chrome-extension://fnbdbepgnidhjejikpionpfohdjjogpm/test.png"> \ No newline at end of file +<!doctype html> +<html> + <title>Unmodified</title> + <body></body> + <script src="index.js"></script> +</html>
diff --git a/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/index.js b/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/index.js new file mode 100644 index 0000000..9ef45cf --- /dev/null +++ b/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/index.js
@@ -0,0 +1,9 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +let image = document.createElement('img'); +image.onload = () => { document.title = 'Loaded'; }; +image.onerror = () => { document.title = 'Image failed to load'; }; +image.src = 'chrome-extension://fnbdbepgnidhjejikpionpfohdjjogpm/test.png'; +document.body.appendChild(image);
diff --git a/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/manifest.json b/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/manifest.json index 042ee4e8..ee700ca 100644 --- a/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/manifest.json +++ b/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/manifest.json
@@ -1,5 +1,6 @@ { "description": "Extension 2", + "manifest_version": 2, "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDPOziAf8MbTjdUo6DysZ4nAU/2f/kwYnftyKkxI1GyTlbStprGy+Y2ek4/59QbE3xEE+dIIuYeObM4QTptpcFMg956ZLFoeDg41Pg3tzUrbltgG8hXTbBxN852FJx2kdaqa/MKUUsJKGSD5hkUmvZRADGGWhMWzvz64ao1h02xJQIDAQAC", "name": "test", "version": "0.1"
diff --git a/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/video.html b/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/video.html index dfa951c..812dcb7 100644 --- a/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/video.html +++ b/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/video.html
@@ -1,3 +1,5 @@ -<!-- The display:none is a workaround for crbug.com/71905 --> -<video src="bear.webm" oncanplay="chrome.test.notifyPass()" - style="display:none"> +<!doctype html> +<html> + <body></body> + <script src="video.js"></script> +</html>
diff --git a/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/video.js b/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/video.js new file mode 100644 index 0000000..aaba323 --- /dev/null +++ b/chrome/test/data/extensions/api_test/extension_resource_request_policy/extension2/video.js
@@ -0,0 +1,8 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +let video = document.createElement('video'); +video.oncanplay = () => { chrome.test.notifyPass(); } +video.src = chrome.runtime.getURL('bear.webm'); +document.body.appendChild(video);
diff --git a/chrome/test/data/extensions/api_test/extension_resource_request_policy/hosted_app/manifest.json b/chrome/test/data/extensions/api_test/extension_resource_request_policy/hosted_app/manifest.json index d5cf47e..bff8c0f3 100644 --- a/chrome/test/data/extensions/api_test/extension_resource_request_policy/hosted_app/manifest.json +++ b/chrome/test/data/extensions/api_test/extension_resource_request_policy/hosted_app/manifest.json
@@ -1,6 +1,7 @@ { "description": "Hosted app", "manifest_version": 2, + "web_accessible_resources": ["test.png"], "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDPOziAf8MbTjdUo6DysZ4nAU/2f/kwYnftyKkxI1GyTlbStprGy+Y2ek4/59QbE3xEE+dIIuYeObM4QTptpcFMg956ZLFoeDg41Pg3tzUrbltgG8hXTbBxN852FJx2kdaqa/MKUUsJKGSD5hkUmvZRADGGWhMWzvz64ao1h02xJQIDAQAD", "name": "test", "version": "0.1",
diff --git a/chrome/test/data/extensions/autoupdate/v1.crx b/chrome/test/data/extensions/autoupdate/v1.crx deleted file mode 100644 index 09cb670..0000000 --- a/chrome/test/data/extensions/autoupdate/v1.crx +++ /dev/null Binary files differ
diff --git a/chrome/test/data/extensions/autoupdate/v1/background.js b/chrome/test/data/extensions/autoupdate/v1/background.js new file mode 100644 index 0000000..dfc8769 --- /dev/null +++ b/chrome/test/data/extensions/autoupdate/v1/background.js
@@ -0,0 +1,7 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +window.onload = function() { + chrome.test.sendMessage('v1 installed'); +};
diff --git a/chrome/test/data/extensions/autoupdate/v1/manifest.json b/chrome/test/data/extensions/autoupdate/v1/manifest.json index 8ea5d35..abda194 100644 --- a/chrome/test/data/extensions/autoupdate/v1/manifest.json +++ b/chrome/test/data/extensions/autoupdate/v1/manifest.json
@@ -4,7 +4,7 @@ "name": "Auto-Update Test", "version": "1.0", "background": { - "page": "background.html" + "scripts": ["background.js"] }, "update_url": "http://localhost/autoupdate/manifest" }
diff --git a/chrome/test/data/extensions/autoupdate/v1/toolstrip.html b/chrome/test/data/extensions/autoupdate/v1/toolstrip.html deleted file mode 100644 index 3f884b2..0000000 --- a/chrome/test/data/extensions/autoupdate/v1/toolstrip.html +++ /dev/null
@@ -1,6 +0,0 @@ -<script> -function version() { - return 1; -} -</script> -Version 1
diff --git a/chrome/test/data/extensions/autoupdate/v2.crx b/chrome/test/data/extensions/autoupdate/v2.crx deleted file mode 100644 index d95930d..0000000 --- a/chrome/test/data/extensions/autoupdate/v2.crx +++ /dev/null Binary files differ
diff --git a/chrome/test/data/extensions/autoupdate/v2/background.js b/chrome/test/data/extensions/autoupdate/v2/background.js new file mode 100644 index 0000000..56e28da --- /dev/null +++ b/chrome/test/data/extensions/autoupdate/v2/background.js
@@ -0,0 +1,7 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +window.onload = function() { + chrome.test.sendMessage('v2 installed'); +};
diff --git a/chrome/test/data/extensions/autoupdate/v2/manifest.json b/chrome/test/data/extensions/autoupdate/v2/manifest.json index b86c856..748aacfb 100644 --- a/chrome/test/data/extensions/autoupdate/v2/manifest.json +++ b/chrome/test/data/extensions/autoupdate/v2/manifest.json
@@ -4,7 +4,7 @@ "name": "Auto-Update Test", "version": "2.0", "background": { - "page": "background.html" + "scripts": ["background.js"] }, "update_url": "http://localhost/autoupdate/manifest" }
diff --git a/chrome/test/data/extensions/autoupdate/v2/toolstrip.html b/chrome/test/data/extensions/autoupdate/v2/toolstrip.html deleted file mode 100644 index 890be73c..0000000 --- a/chrome/test/data/extensions/autoupdate/v2/toolstrip.html +++ /dev/null
@@ -1,6 +0,0 @@ -<script> -function version() { - return 2; -} -</script> -Version 2
diff --git a/chrome/test/data/extensions/autoupdate/v3/toolstrip.html b/chrome/test/data/extensions/autoupdate/v3/toolstrip.html deleted file mode 100644 index 94e9296f0..0000000 --- a/chrome/test/data/extensions/autoupdate/v3/toolstrip.html +++ /dev/null
@@ -1,6 +0,0 @@ -<script> -function version() { - return 3; -} -</script> -Version 3
diff --git a/chrome/test/data/extensions/install/install.crx b/chrome/test/data/extensions/install/install.crx deleted file mode 100644 index 1755b68..0000000 --- a/chrome/test/data/extensions/install/install.crx +++ /dev/null Binary files differ
diff --git a/chrome/test/data/extensions/install/install/bg.html b/chrome/test/data/extensions/install/install/bg.html deleted file mode 100644 index a184f3a..0000000 --- a/chrome/test/data/extensions/install/install/bg.html +++ /dev/null
@@ -1,6 +0,0 @@ -<!-- - * Copyright (c) 2011 The Chromium Authors. All rights reserved. Use of this - * source code is governed by a BSD-style license that can be found in the - * LICENSE file. ---> -<script src="bg.js"></script>
diff --git a/chrome/test/data/extensions/install/install/manifest.json b/chrome/test/data/extensions/install/install/manifest.json index 3598092..5eb6190b 100644 --- a/chrome/test/data/extensions/install/install/manifest.json +++ b/chrome/test/data/extensions/install/install/manifest.json
@@ -3,6 +3,6 @@ "version": "1.0", "manifest_version": 2, "background": { - "page": "bg.html" + "scripts": ["bg.js"] } }
diff --git a/chrome/test/data/extensions/install/install_older_version.crx b/chrome/test/data/extensions/install/install_older_version.crx deleted file mode 100644 index 3684e8b..0000000 --- a/chrome/test/data/extensions/install/install_older_version.crx +++ /dev/null Binary files differ
diff --git a/chrome/test/data/extensions/install/install_older_version/bg.html b/chrome/test/data/extensions/install/install_older_version/bg.html deleted file mode 100644 index 6f73232..0000000 --- a/chrome/test/data/extensions/install/install_older_version/bg.html +++ /dev/null
@@ -1,5 +0,0 @@ -<script> -function version() { - window.domAutomationController.send("0.9"); -} -</script>
diff --git a/chrome/test/data/extensions/install/install_older_version/bg.js b/chrome/test/data/extensions/install/install_older_version/bg.js new file mode 100644 index 0000000..02e09335 --- /dev/null +++ b/chrome/test/data/extensions/install/install_older_version/bg.js
@@ -0,0 +1,7 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +function version() { + window.domAutomationController.send('0.9'); +}
diff --git a/chrome/test/data/extensions/install/install_older_version/manifest.json b/chrome/test/data/extensions/install/install_older_version/manifest.json index 1370ada..21c6b0c8 100644 --- a/chrome/test/data/extensions/install/install_older_version/manifest.json +++ b/chrome/test/data/extensions/install/install_older_version/manifest.json
@@ -3,6 +3,6 @@ "manifest_version": 2, "version": "0.9", "background": { - "page": "bg.html" + "scripts": ["bg.js"] } }
diff --git a/chrome/test/data/extensions/install/install_same_version.crx b/chrome/test/data/extensions/install/install_same_version.crx deleted file mode 100644 index a343cf6e..0000000 --- a/chrome/test/data/extensions/install/install_same_version.crx +++ /dev/null Binary files differ
diff --git a/chrome/test/data/extensions/install/install_same_version/bg.html b/chrome/test/data/extensions/install/install_same_version/bg.html deleted file mode 100644 index 9a6c1ce..0000000 --- a/chrome/test/data/extensions/install/install_same_version/bg.html +++ /dev/null
@@ -1,5 +0,0 @@ -<script> -function version() { - window.domAutomationController.send("1 again"); -} -</script>
diff --git a/chrome/test/data/extensions/install/install_same_version/bg.js b/chrome/test/data/extensions/install/install_same_version/bg.js new file mode 100644 index 0000000..0587d637 --- /dev/null +++ b/chrome/test/data/extensions/install/install_same_version/bg.js
@@ -0,0 +1,7 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +function version() { + window.domAutomationController.send('1 again'); +}
diff --git a/chrome/test/data/extensions/install/install_same_version/manifest.json b/chrome/test/data/extensions/install/install_same_version/manifest.json index f89416295..1d23d17 100644 --- a/chrome/test/data/extensions/install/install_same_version/manifest.json +++ b/chrome/test/data/extensions/install/install_same_version/manifest.json
@@ -3,6 +3,6 @@ "manifest_version": 2, "version": "1.0", "background": { - "page": "bg.html" + "scripts": ["bg.js"] } }
diff --git a/chrome/test/data/extensions/install/install_v2.crx b/chrome/test/data/extensions/install/install_v2.crx deleted file mode 100644 index 5b97ebb..0000000 --- a/chrome/test/data/extensions/install/install_v2.crx +++ /dev/null Binary files differ
diff --git a/chrome/test/data/extensions/install/install_v2/bg.html b/chrome/test/data/extensions/install/install_v2/bg.html deleted file mode 100644 index 807f390..0000000 --- a/chrome/test/data/extensions/install/install_v2/bg.html +++ /dev/null
@@ -1,5 +0,0 @@ -<script> -function version() { - window.domAutomationController.send("2.0"); -} -</script>
diff --git a/chrome/test/data/extensions/install/install_v2/bg.js b/chrome/test/data/extensions/install/install_v2/bg.js new file mode 100644 index 0000000..9c88ed7 --- /dev/null +++ b/chrome/test/data/extensions/install/install_v2/bg.js
@@ -0,0 +1,7 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +function version() { + window.domAutomationController.send('2.0'); +}
diff --git a/chrome/test/data/extensions/install/install_v2/manifest.json b/chrome/test/data/extensions/install/install_v2/manifest.json index 8bbe432..b007292 100644 --- a/chrome/test/data/extensions/install/install_v2/manifest.json +++ b/chrome/test/data/extensions/install/install_v2/manifest.json
@@ -3,6 +3,6 @@ "manifest_version": 2, "version": "2.0", "background": { - "page": "bg.html" + "scripts": ["bg.js"] } }
diff --git a/chrome/test/data/vr/e2e_test_files/html/test_webxr_input.html b/chrome/test/data/vr/e2e_test_files/html/test_webxr_input.html new file mode 100644 index 0000000..9b32648 --- /dev/null +++ b/chrome/test/data/vr/e2e_test_files/html/test_webxr_input.html
@@ -0,0 +1,63 @@ +<!doctype html> +<!-- +Tests that screen taps when using Cardboard are translated into WebXR input, and +that Daydream controller input is registered when using Daydream View. +--> +<html> + <head> + <link rel="stylesheet" type="text/css" href="../resources/webxr_e2e.css"> + </head> + <body> + <canvas id="webgl-canvas"></canvas> + <script src="../../../../../../third_party/WebKit/LayoutTests/resources/testharness.js"></script> + <script src="../resources/webxr_e2e.js"></script> + <script src="../resources/webxr_boilerplate.js"></script> + <script> + var t = async_test("Screen taps/clicks registered as input when in WebXR exclusive session"); + + var selectStartCount = 0; + var selectEndCount = 0; + var selectCount = 0; + var iterations; + var currentIteration = 0; + + function onSelectStart() { + // selectstart should always be fired first, so check that + t.step( () => { + assert_true(selectStartCount == selectEndCount); + assert_true(selectStartCount == selectCount); + }); + selectStartCount++; + } + + function onSelectEnd() { + // selectend should always be fired between selectstart and select + t.step( () => { + assert_true(selectEndCount + 1 == selectStartCount); + assert_true(selectEndCount == selectCount); + }); + selectEndCount++; + } + + function onSelect() { + // select should always be fired last + selectCount++; + t.step( () => { + assert_true(selectCount == selectStartCount); + assert_true(selectCount == selectEndCount); + }); + currentIteration++; + if (currentIteration == iterations) { + t.done(); + } + } + + function stepSetupListeners(numIterations) { + iterations = numIterations; + exclusiveSession.addEventListener('selectstart', onSelectStart, false); + exclusiveSession.addEventListener('selectend', onSelectEnd, false); + exclusiveSession.addEventListener('select', onSelect, false); + } + </script> + </body> +</html>
diff --git a/chromeos/assistant/OWNERS b/chromeos/assistant/OWNERS index 237ac6f..62402b1 100644 --- a/chromeos/assistant/OWNERS +++ b/chromeos/assistant/OWNERS
@@ -1 +1,2 @@ xiaohuic@chromium.org +muyuanli@chromium.org
diff --git a/chromeos/services/assistant/OWNERS b/chromeos/services/assistant/OWNERS index 1f4b0556..5e49b1bb 100644 --- a/chromeos/services/assistant/OWNERS +++ b/chromeos/services/assistant/OWNERS
@@ -1,4 +1,5 @@ xiaohuic@chromium.org +muyuanli@chromium.org per-file manifest.json=set noparent per-file manifest.json=file://ipc/SECURITY_OWNERS
diff --git a/chromeos/services/assistant/public/mojom/assistant.mojom b/chromeos/services/assistant/public/mojom/assistant.mojom index 5e65d3f..f1f559a 100644 --- a/chromeos/services/assistant/public/mojom/assistant.mojom +++ b/chromeos/services/assistant/public/mojom/assistant.mojom
@@ -34,7 +34,13 @@ interface AssistantPlatform { // Initiates assistant and provides interfaces for assistant to call into the // browser. - Init(AudioInput audio_input_interface); + Init(Client assistant_client_interface, AudioInput audio_input_interface); +}; + +// Interface for assistant to call into client. +interface Client { + // Notifies assistant client that assistant running status has changed. + OnAssistantStatusChanged(bool running); }; // Interface for assistant to call into browser for audio input related
diff --git a/chromeos/services/assistant/service.cc b/chromeos/services/assistant/service.cc index f2bc7e3c..667c0c8 100644 --- a/chromeos/services/assistant/service.cc +++ b/chromeos/services/assistant/service.cc
@@ -83,6 +83,8 @@ } void Service::OnSessionActivated(bool activated) { + DCHECK(client_); + client_->OnAssistantStatusChanged(activated); assistant_manager_service_->EnableListening(activated); } @@ -99,7 +101,8 @@ return identity_manager_.get(); } -void Service::Init(mojom::AudioInputPtr audio_input) { +void Service::Init(mojom::ClientPtr client, mojom::AudioInputPtr audio_input) { + client_ = std::move(client); #if BUILDFLAG(ENABLE_CROS_LIBASSISTANT) assistant_manager_service_ = std::make_unique<AssistantManagerServiceImpl>(std::move(audio_input)); @@ -141,6 +144,7 @@ AddAshSessionObserver(); registry_.AddInterface<mojom::Assistant>(base::BindRepeating( &Service::BindAssistantConnection, base::Unretained(this))); + client_->OnAssistantStatusChanged(true); DVLOG(1) << "Assistant started"; } else { assistant_manager_service_->SetAccessToken(token.value());
diff --git a/chromeos/services/assistant/service.h b/chromeos/services/assistant/service.h index 640ef1e3..ae121174 100644 --- a/chromeos/services/assistant/service.h +++ b/chromeos/services/assistant/service.h
@@ -59,7 +59,7 @@ void BindAssistantPlatformConnection(mojom::AssistantPlatformRequest request); // mojom::AssistantPlatform overrides: - void Init(mojom::AudioInputPtr audio_input) override; + void Init(mojom::ClientPtr client, mojom::AudioInputPtr audio_input) override; // ash::mojom::SessionActivationObserver overrides: void OnSessionActivated(bool activated) override; @@ -84,6 +84,7 @@ mojo::Binding<mojom::AssistantPlatform> platform_binding_; mojo::Binding<ash::mojom::SessionActivationObserver> session_observer_binding_; + mojom::ClientPtr client_; identity::mojom::IdentityManagerPtr identity_manager_;
diff --git a/components/autofill/core/browser/webdata/autocomplete_sync_bridge.cc b/components/autofill/core/browser/webdata/autocomplete_sync_bridge.cc index bcdcc18..22c7866 100644 --- a/components/autofill/core/browser/webdata/autocomplete_sync_bridge.cc +++ b/components/autofill/core/browser/webdata/autocomplete_sync_bridge.cc
@@ -20,12 +20,14 @@ #include "components/sync/model/entity_data.h" #include "components/sync/model/model_type_change_processor.h" #include "components/sync/model/mutable_data_batch.h" +#include "components/sync/model_impl/client_tag_based_model_type_processor.h" #include "components/sync/model_impl/sync_metadata_store_change_list.h" #include "net/base/escape.h" using base::Optional; using base::Time; using sync_pb::AutofillSpecifics; +using syncer::ClientTagBasedModelTypeProcessor; using syncer::EntityChange; using syncer::EntityChangeList; using syncer::EntityData; @@ -281,10 +283,11 @@ AutofillWebDataService* web_data_service, AutofillWebDataBackend* web_data_backend) { web_data_service->GetDBUserData()->SetUserData( - UserDataKey(), std::make_unique<AutocompleteSyncBridge>( - web_data_backend, - base::BindRepeating(&ModelTypeChangeProcessor::Create, - base::RepeatingClosure()))); + UserDataKey(), + std::make_unique<AutocompleteSyncBridge>( + web_data_backend, + std::make_unique<ClientTagBasedModelTypeProcessor>( + syncer::AUTOFILL, /*dump_stack=*/base::RepeatingClosure()))); } // static @@ -297,8 +300,8 @@ AutocompleteSyncBridge::AutocompleteSyncBridge( AutofillWebDataBackend* backend, - const ChangeProcessorFactory& change_processor_factory) - : ModelTypeSyncBridge(change_processor_factory, syncer::AUTOFILL), + std::unique_ptr<ModelTypeChangeProcessor> change_processor) + : ModelTypeSyncBridge(std::move(change_processor)), web_data_backend_(backend), scoped_observer_(this) { DCHECK(web_data_backend_); @@ -456,7 +459,7 @@ {FROM_HERE, "Failed reading autofill metadata from WebDatabase."}); return; } - change_processor()->ModelReadyToSync(std::move(batch)); + change_processor()->ModelReadyToSync(this, std::move(batch)); } std::string AutocompleteSyncBridge::GetClientTag(
diff --git a/components/autofill/core/browser/webdata/autocomplete_sync_bridge.h b/components/autofill/core/browser/webdata/autocomplete_sync_bridge.h index ee568fb..2b53c23 100644 --- a/components/autofill/core/browser/webdata/autocomplete_sync_bridge.h +++ b/components/autofill/core/browser/webdata/autocomplete_sync_bridge.h
@@ -17,6 +17,7 @@ #include "components/autofill/core/browser/webdata/autofill_webdata_service_observer.h" #include "components/sync/model/metadata_change_list.h" #include "components/sync/model/model_error.h" +#include "components/sync/model/model_type_change_processor.h" #include "components/sync/model/model_type_sync_bridge.h" namespace autofill { @@ -33,7 +34,7 @@ AutocompleteSyncBridge(); AutocompleteSyncBridge( AutofillWebDataBackend* backend, - const ChangeProcessorFactory& change_processor_factory); + std::unique_ptr<syncer::ModelTypeChangeProcessor> change_processor); ~AutocompleteSyncBridge() override; static void CreateForWebDataServiceAndBackend(
diff --git a/components/autofill/core/browser/webdata/autocomplete_sync_bridge_unittest.cc b/components/autofill/core/browser/webdata/autocomplete_sync_bridge_unittest.cc index f073558..55a40c4f 100644 --- a/components/autofill/core/browser/webdata/autocomplete_sync_bridge_unittest.cc +++ b/components/autofill/core/browser/webdata/autocomplete_sync_bridge_unittest.cc
@@ -144,8 +144,9 @@ void ResetBridge(bool expect_error = false) { bridge_.reset(new AutocompleteSyncBridge( - &backend_, RecordingModelTypeChangeProcessor::FactoryForBridgeTest( - &processor_, expect_error))); + &backend_, + RecordingModelTypeChangeProcessor::CreateProcessorAndAssignRawPointer( + &processor_, expect_error))); } void SaveSpecificsToTable(
diff --git a/components/browser_sync/profile_sync_service.cc b/components/browser_sync/profile_sync_service.cc index 6d14e41..f085b8b2 100644 --- a/components/browser_sync/profile_sync_service.cc +++ b/components/browser_sync/profile_sync_service.cc
@@ -66,6 +66,7 @@ #include "components/sync/model/change_processor.h" #include "components/sync/model/model_type_change_processor.h" #include "components/sync/model/sync_error.h" +#include "components/sync/model_impl/client_tag_based_model_type_processor.h" #include "components/sync/protocol/sync.pb.h" #include "components/sync/syncable/directory.h" #include "components/sync/syncable/sync_db_util.h" @@ -86,6 +87,7 @@ using sync_sessions::SessionsSyncManager; using syncer::BackendMigrator; using syncer::ChangeProcessor; +using syncer::ClientTagBasedModelTypeProcessor; using syncer::DataTypeController; using syncer::DataTypeManager; using syncer::DataTypeStatusTable; @@ -236,9 +238,10 @@ device_info_sync_bridge_ = std::make_unique<DeviceInfoSyncBridge>( local_device_.get(), model_type_store_factory_, - base::BindRepeating( - &ModelTypeChangeProcessor::Create, - base::BindRepeating(&syncer::ReportUnrecoverableError, channel_))); + std::make_unique<ClientTagBasedModelTypeProcessor>( + syncer::DEVICE_INFO, + /*dump_stack=*/base::BindRepeating(&syncer::ReportUnrecoverableError, + channel_))); syncer::SyncApiComponentFactory::RegisterDataTypesMethod register_platform_types_callback =
diff --git a/components/download/downloader/in_progress/BUILD.gn b/components/download/downloader/in_progress/BUILD.gn index e29d519..30abd02 100644 --- a/components/download/downloader/in_progress/BUILD.gn +++ b/components/download/downloader/in_progress/BUILD.gn
@@ -22,6 +22,7 @@ "//base", "//components/download/downloader/in_progress/proto", "//components/download/public/common:public", + "//net", "//services/metrics/public/cpp:metrics_cpp", ] }
diff --git a/components/download/downloader/in_progress/download_entry.cc b/components/download/downloader/in_progress/download_entry.cc index 38b0dd5e..7bf35cb 100644 --- a/components/download/downloader/in_progress/download_entry.cc +++ b/components/download/downloader/in_progress/download_entry.cc
@@ -10,21 +10,19 @@ DownloadEntry::DownloadEntry(const DownloadEntry& other) = default; -DownloadEntry::DownloadEntry(const std::string& guid, - DownloadSource download_source, - int64_t ukm_download_id) - : guid(guid), - download_source(download_source), - ukm_download_id(ukm_download_id) {} - -DownloadEntry::DownloadEntry(const std::string& guid, - const std::string& request_origin, - DownloadSource download_source, - int64_t ukm_download_id) +DownloadEntry::DownloadEntry( + const std::string& guid, + const std::string& request_origin, + DownloadSource download_source, + bool fetch_error_body, + const DownloadUrlParameters::RequestHeadersType& request_headers, + int64_t ukm_download_id) : guid(guid), request_origin(request_origin), download_source(download_source), - ukm_download_id(ukm_download_id) {} + ukm_download_id(ukm_download_id), + fetch_error_body(fetch_error_body), + request_headers(request_headers) {} DownloadEntry::~DownloadEntry() = default; @@ -32,7 +30,9 @@ return guid == other.guid && request_origin == other.request_origin && download_source == other.download_source && ukm_download_id == other.ukm_download_id && - bytes_wasted == other.bytes_wasted; + bytes_wasted == other.bytes_wasted && + fetch_error_body == other.fetch_error_body && + request_headers == other.request_headers; } bool DownloadEntry::operator!=(const DownloadEntry& other) const {
diff --git a/components/download/downloader/in_progress/download_entry.h b/components/download/downloader/in_progress/download_entry.h index 554b1381..4881ae8 100644 --- a/components/download/downloader/in_progress/download_entry.h +++ b/components/download/downloader/in_progress/download_entry.h
@@ -8,6 +8,7 @@ #include <string> #include "components/download/public/common/download_source.h" +#include "components/download/public/common/download_url_parameters.h" #include "services/metrics/public/cpp/ukm_source_id.h" namespace download { @@ -17,13 +18,13 @@ public: DownloadEntry(); DownloadEntry(const DownloadEntry& other); - DownloadEntry(const std::string& guid, - DownloadSource download_source, - int64_t ukm_id); - DownloadEntry(const std::string& guid, - const std::string& request_origin, - DownloadSource download_source, - int64_t ukm_id); + DownloadEntry( + const std::string& guid, + const std::string& request_origin, + DownloadSource download_source, + bool fetch_error_body, + const DownloadUrlParameters::RequestHeadersType& request_headers, + int64_t ukm_id); ~DownloadEntry(); bool operator==(const DownloadEntry& other) const; @@ -45,6 +46,14 @@ // Count for how many (extra) bytes were used (including resumption). int64_t bytes_wasted = 0; + + // If the entity body of unsuccessful HTTP response, like HTTP 404, will be + // downloaded. + bool fetch_error_body = false; + + // Request header key/value pairs that will be added to the download HTTP + // request. + DownloadUrlParameters::RequestHeadersType request_headers; }; } // namespace download
diff --git a/components/download/downloader/in_progress/in_progress_cache_impl.cc b/components/download/downloader/in_progress/in_progress_cache_impl.cc index 34fd266b..5640de21a 100644 --- a/components/download/downloader/in_progress/in_progress_cache_impl.cc +++ b/components/download/downloader/in_progress/in_progress_cache_impl.cc
@@ -81,15 +81,14 @@ } // Read and parse file. - const int64_t size = base::saturated_cast<int64_t>(info.size); - if (size > INT_MAX || size < 0) { + if (info.size < 0) { LOG(ERROR) << "Could not read download entries from file " << "because the file size was unexpected."; return std::vector<char>(); } - auto file_data = std::vector<char>(size); - if (entries_file.Read(0, file_data.data(), size) <= 0) { + auto file_data = std::vector<char>(info.size); + if (entries_file.Read(0, file_data.data(), info.size) < 0) { LOG(ERROR) << "Could not read download entries from file " << "because there was a read failure."; return std::vector<char>(); @@ -149,8 +148,8 @@ } } -void InProgressCacheImpl::OnInitialized(std::vector<char> entries) { - if (entries.empty()) { +void InProgressCacheImpl::OnInitialized(const std::vector<char>& entries) { + if (!entries.empty()) { if (!entries_.ParseFromArray(entries.data(), entries.size())) { // TODO(crbug.com/778425): Get UMA for errors. LOG(ERROR) << "Could not read download entries from file "
diff --git a/components/download/downloader/in_progress/in_progress_cache_impl.h b/components/download/downloader/in_progress/in_progress_cache_impl.h index 833fd24f..6dd5fce 100644 --- a/components/download/downloader/in_progress/in_progress_cache_impl.h +++ b/components/download/downloader/in_progress/in_progress_cache_impl.h
@@ -44,7 +44,7 @@ }; // Steps to execute after initialization is complete. - void OnInitialized(std::vector<char> entries); + void OnInitialized(const std::vector<char>& entries); metadata_pb::DownloadEntries entries_; base::FilePath file_path_;
diff --git a/components/download/downloader/in_progress/in_progress_cache_impl_unittest.cc b/components/download/downloader/in_progress/in_progress_cache_impl_unittest.cc index d3f6b4b..12012af 100644 --- a/components/download/downloader/in_progress/in_progress_cache_impl_unittest.cc +++ b/components/download/downloader/in_progress/in_progress_cache_impl_unittest.cc
@@ -12,6 +12,7 @@ #include "base/task_runner.h" #include "base/task_scheduler/post_task.h" #include "base/test/scoped_task_environment.h" +#include "components/download/public/common/download_url_parameters.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -23,6 +24,12 @@ const base::FilePath::CharType kInProgressCachePath[] = FILE_PATH_LITERAL("/test/in_progress_cache"); +DownloadEntry CreateEntry(const std::string& guid) { + DownloadEntry entry; + entry.guid = guid; + return entry; +} + class InProgressCacheImplTest : public testing::Test { public: InProgressCacheImplTest() @@ -68,7 +75,7 @@ // Add entry. std::string guid1("guid"); - DownloadEntry entry1(guid1, "request origin", DownloadSource::UNKNOWN, 999); + DownloadEntry entry1 = CreateEntry(guid1); cache_->AddOrReplaceEntry(entry1); base::Optional<DownloadEntry> retrieved_entry1 = cache_->RetrieveEntry(guid1); @@ -78,17 +85,27 @@ // Replace entry. std::string new_request_origin("new request origin"); entry1.request_origin = new_request_origin; + entry1.fetch_error_body = true; + entry1.ukm_download_id = 999u; + entry1.download_source = DownloadSource::DRAG_AND_DROP; + + DownloadUrlParameters::RequestHeadersType request_headers = { + std::make_pair("key_1", "value_1"), std::make_pair("key_2", "value_2")}; + entry1.request_headers = request_headers; cache_->AddOrReplaceEntry(entry1); base::Optional<DownloadEntry> replaced_entry1 = cache_->RetrieveEntry(guid1); EXPECT_TRUE(replaced_entry1.has_value()); EXPECT_EQ(entry1, replaced_entry1.value()); - EXPECT_EQ(new_request_origin, replaced_entry1.value().request_origin); + EXPECT_EQ(new_request_origin, replaced_entry1->request_origin); + EXPECT_EQ(true, replaced_entry1->fetch_error_body); + EXPECT_EQ(999u, replaced_entry1->ukm_download_id); + EXPECT_EQ(DownloadSource::DRAG_AND_DROP, replaced_entry1->download_source); + EXPECT_EQ(request_headers, replaced_entry1->request_headers); // Add another entry. std::string guid2("guid2"); - DownloadEntry entry2(guid2, "other request origin", DownloadSource::UNKNOWN, - 888); + DownloadEntry entry2 = CreateEntry(guid2); cache_->AddOrReplaceEntry(entry2); base::Optional<DownloadEntry> retrieved_entry2 = cache_->RetrieveEntry(guid2);
diff --git a/components/download/downloader/in_progress/in_progress_conversions.cc b/components/download/downloader/in_progress/in_progress_conversions.cc index aa97cde..a5e3c8d 100644 --- a/components/download/downloader/in_progress/in_progress_conversions.cc +++ b/components/download/downloader/in_progress/in_progress_conversions.cc
@@ -17,6 +17,10 @@ entry.download_source = DownloadSourceFromProto(proto.download_source()); entry.ukm_download_id = proto.ukm_download_id(); entry.bytes_wasted = proto.bytes_wasted(); + entry.fetch_error_body = proto.fetch_error_body(); + for (const auto& header : proto.request_headers()) { + entry.request_headers.emplace_back(HttpRequestHeaderFromProto(header)); + } return entry; } @@ -28,6 +32,12 @@ proto.set_download_source(DownloadSourceToProto(entry.download_source)); proto.set_ukm_download_id(entry.ukm_download_id); proto.set_bytes_wasted(entry.bytes_wasted); + proto.set_fetch_error_body(entry.fetch_error_body); + for (const auto& header : entry.request_headers) { + auto* proto_header = proto.add_request_headers(); + *proto_header = HttpRequestHeaderToProto(header); + } + return proto; } @@ -107,4 +117,26 @@ return proto; } +// static +metadata_pb::HttpRequestHeader InProgressConversions::HttpRequestHeaderToProto( + const std::pair<std::string, std::string>& header) { + metadata_pb::HttpRequestHeader proto; + if (header.first.empty()) + return proto; + + proto.set_key(header.first); + proto.set_value(header.second); + return proto; +} + +// static +std::pair<std::string, std::string> +InProgressConversions::HttpRequestHeaderFromProto( + const metadata_pb::HttpRequestHeader& proto) { + if (proto.key().empty()) + return std::pair<std::string, std::string>(); + + return std::make_pair(proto.key(), proto.value()); +} + } // namespace download
diff --git a/components/download/downloader/in_progress/in_progress_conversions.h b/components/download/downloader/in_progress/in_progress_conversions.h index 0aa53f0..d5b97cc 100644 --- a/components/download/downloader/in_progress/in_progress_conversions.h +++ b/components/download/downloader/in_progress/in_progress_conversions.h
@@ -31,6 +31,12 @@ static metadata_pb::DownloadEntries DownloadEntriesToProto( const std::vector<DownloadEntry>& entries); + + static metadata_pb::HttpRequestHeader HttpRequestHeaderToProto( + const std::pair<std::string, std::string>& header); + + static std::pair<std::string, std::string> HttpRequestHeaderFromProto( + const metadata_pb::HttpRequestHeader& proto); }; } // namespace download
diff --git a/components/download/downloader/in_progress/in_progress_conversions_unittest.cc b/components/download/downloader/in_progress/in_progress_conversions_unittest.cc index 6456b65..4fcda352 100644 --- a/components/download/downloader/in_progress/in_progress_conversions_unittest.cc +++ b/components/download/downloader/in_progress/in_progress_conversions_unittest.cc
@@ -3,6 +3,8 @@ // found in the LICENSE file. #include "components/download/downloader/in_progress/in_progress_conversions.h" + +#include "components/download/public/common/download_url_parameters.h" #include "testing/gtest/include/gtest/gtest.h" namespace download { @@ -16,6 +18,8 @@ TEST_F(InProgressConversionsTest, DownloadEntry) { // Entry with no fields. DownloadEntry entry; + EXPECT_EQ(false, entry.fetch_error_body); + EXPECT_TRUE(entry.request_headers.empty()); EXPECT_EQ(entry, DownloadEntryFromProto(DownloadEntryToProto(entry))); // Entry with guid, request origin and download source. @@ -24,6 +28,11 @@ entry.download_source = DownloadSource::DRAG_AND_DROP; entry.ukm_download_id = 123; entry.bytes_wasted = 1234; + entry.fetch_error_body = true; + entry.request_headers.emplace_back( + std::make_pair<std::string, std::string>("123", "456")); + entry.request_headers.emplace_back( + std::make_pair<std::string, std::string>("ABC", "def")); EXPECT_EQ(entry, DownloadEntryFromProto(DownloadEntryToProto(entry))); } @@ -33,13 +42,18 @@ EXPECT_EQ(entries, DownloadEntriesFromProto(DownloadEntriesToProto(entries))); // Entries vector with one entry. - entries.push_back( - DownloadEntry("guid", "request origin", DownloadSource::UNKNOWN, 123)); + DownloadUrlParameters::RequestHeadersType request_headers; + entries.push_back(DownloadEntry("guid", "request origin", + DownloadSource::UNKNOWN, false, + request_headers, 123)); EXPECT_EQ(entries, DownloadEntriesFromProto(DownloadEntriesToProto(entries))); // Entries vector with multiple entries. - entries.push_back( - DownloadEntry("guid2", "request origin", DownloadSource::UNKNOWN, 456)); + request_headers.emplace_back( + DownloadUrlParameters::RequestHeadersNameValuePair("key", "value")); + entries.push_back(DownloadEntry("guid2", "request origin", + DownloadSource::UNKNOWN, true, + request_headers, 456)); EXPECT_EQ(entries, DownloadEntriesFromProto(DownloadEntriesToProto(entries))); } @@ -56,4 +70,13 @@ } } +TEST_F(InProgressConversionsTest, HttpRequestHeaders) { + std::pair<std::string, std::string> header; + EXPECT_EQ(header, + HttpRequestHeaderFromProto(HttpRequestHeaderToProto(header))); + header = std::make_pair("123", "456"); + EXPECT_EQ(header, + HttpRequestHeaderFromProto(HttpRequestHeaderToProto(header))); +} + } // namespace download
diff --git a/components/download/downloader/in_progress/proto/download_entry.proto b/components/download/downloader/in_progress/proto/download_entry.proto index 8d86791..776b006 100644 --- a/components/download/downloader/in_progress/proto/download_entry.proto +++ b/components/download/downloader/in_progress/proto/download_entry.proto
@@ -10,6 +10,11 @@ import "download_source.proto"; +message HttpRequestHeader { + optional string key = 1; + optional string value = 2; +} + // Stores various in-progress metadata related to a download. message DownloadEntry { optional string guid = 1; @@ -17,6 +22,8 @@ optional DownloadSource download_source = 3; optional int64 ukm_download_id = 4; optional int64 bytes_wasted = 5; + optional bool fetch_error_body = 6; + repeated HttpRequestHeader request_headers = 7; } // Contains a list of entries.
diff --git a/components/download/internal/common/download_response_handler.cc b/components/download/internal/common/download_response_handler.cc index 957fd3e..8e285f1 100644 --- a/components/download/internal/common/download_response_handler.cc +++ b/components/download/internal/common/download_response_handler.cc
@@ -53,6 +53,7 @@ bool is_parallel_request, bool is_transient, bool fetch_error_body, + const DownloadUrlParameters::RequestHeadersType& request_headers, const std::string& request_origin, DownloadSource download_source, std::vector<GURL> url_chain) @@ -64,6 +65,7 @@ referrer_(resource_request->referrer), is_transient_(is_transient), fetch_error_body_(fetch_error_body), + request_headers_(request_headers), request_origin_(request_origin), download_source_(download_source), has_strong_validators_(false), @@ -136,6 +138,7 @@ create_info->offset = create_info->save_info->offset; create_info->mime_type = head.mime_type; create_info->fetch_error_body = fetch_error_body_; + create_info->request_headers = request_headers_; create_info->request_origin = request_origin_; create_info->download_source = download_source_;
diff --git a/components/download/internal/common/resource_downloader.cc b/components/download/internal/common/resource_downloader.cc index 6f1d74a..98e6fea1 100644 --- a/components/download/internal/common/resource_downloader.cc +++ b/components/download/internal/common/resource_downloader.cc
@@ -141,6 +141,7 @@ download_url_parameters->GetSaveInfo()), is_parallel_request, download_url_parameters->is_transient(), download_url_parameters->fetch_error_body(), + download_url_parameters->request_headers(), download_url_parameters->request_origin(), download_url_parameters->download_source(), std::vector<GURL>(1, resource_request_->url)); @@ -178,8 +179,13 @@ if (suggested_filename.has_value()) save_info->suggested_name = base::UTF8ToUTF16(suggested_filename.value()); url_loader_client_ = std::make_unique<DownloadResponseHandler>( - resource_request_.get(), this, std::move(save_info), false, false, false, - std::string(), DownloadSource::NAVIGATION, std::move(url_chain)); + resource_request_.get(), this, std::move(save_info), + false, /* is_parallel_request */ + false, /* is_transient */ + false, /* fetch_error_body */ + download::DownloadUrlParameters::RequestHeadersType(), + std::string(), /* request_origin */ + download::DownloadSource::NAVIGATION, std::move(url_chain)); // Simulate on the new URLLoaderClient calls that happened on the old client. net::SSLInfo info;
diff --git a/components/download/public/common/download_create_info.h b/components/download/public/common/download_create_info.h index c17299f..70ea821d 100644 --- a/components/download/public/common/download_create_info.h +++ b/components/download/public/common/download_create_info.h
@@ -21,6 +21,7 @@ #include "components/download/public/common/download_request_handle_interface.h" #include "components/download/public/common/download_save_info.h" #include "components/download/public/common/download_source.h" +#include "components/download/public/common/download_url_parameters.h" #include "net/http/http_response_info.h" #include "services/metrics/public/cpp/ukm_source_id.h" #include "ui/base/page_transition_types.h" @@ -151,6 +152,9 @@ // response. bool fetch_error_body = false; + // The request headers that has been sent in the download request. + DownloadUrlParameters::RequestHeadersType request_headers; + // Source ID generated for UKM. ukm::SourceId ukm_source_id;
diff --git a/components/download/public/common/download_response_handler.h b/components/download/public/common/download_response_handler.h index 415ee15..a100d0a 100644 --- a/components/download/public/common/download_response_handler.h +++ b/components/download/public/common/download_response_handler.h
@@ -5,12 +5,14 @@ #ifndef COMPONENTS_DOWNLOAD_PUBLIC_COMMON_DOWNLOAD_RESPONSE_HANDLER_H_ #define COMPONENTS_DOWNLOAD_PUBLIC_COMMON_DOWNLOAD_RESPONSE_HANDLER_H_ +#include <string> #include <vector> #include "components/download/public/common/download_create_info.h" #include "components/download/public/common/download_export.h" #include "components/download/public/common/download_source.h" #include "components/download/public/common/download_stream.mojom.h" +#include "components/download/public/common/download_url_parameters.h" #include "net/cert/cert_status_flags.h" #include "services/network/public/cpp/resource_response.h" #include "services/network/public/mojom/url_loader.mojom.h" @@ -33,15 +35,17 @@ virtual void OnReceiveRedirect() = 0; }; - DownloadResponseHandler(network::ResourceRequest* resource_request, - Delegate* delegate, - std::unique_ptr<DownloadSaveInfo> save_info, - bool is_parallel_request, - bool is_transient, - bool fetch_error_body, - const std::string& request_origin, - DownloadSource download_source, - std::vector<GURL> url_chain); + DownloadResponseHandler( + network::ResourceRequest* resource_request, + Delegate* delegate, + std::unique_ptr<DownloadSaveInfo> save_info, + bool is_parallel_request, + bool is_transient, + bool fetch_error_body, + const DownloadUrlParameters::RequestHeadersType& request_headers, + const std::string& request_origin, + DownloadSource download_source, + std::vector<GURL> url_chain); ~DownloadResponseHandler() override; // network::mojom::URLLoaderClient @@ -81,6 +85,7 @@ GURL referrer_; bool is_transient_; bool fetch_error_body_; + DownloadUrlParameters::RequestHeadersType request_headers_; std::string request_origin_; DownloadSource download_source_; net::CertStatus cert_status_;
diff --git a/components/history/core/browser/history_backend.cc b/components/history/core/browser/history_backend.cc index edb7134d..851bf1c 100644 --- a/components/history/core/browser/history_backend.cc +++ b/components/history/core/browser/history_backend.cc
@@ -40,6 +40,7 @@ #include "components/history/core/browser/keyword_search_term.h" #include "components/history/core/browser/page_usage_data.h" #include "components/history/core/browser/url_utils.h" +#include "components/sync/model_impl/client_tag_based_model_type_processor.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" #include "sql/error_delegate_util.h" #include "third_party/skia/include/core/SkBitmap.h" @@ -54,7 +55,7 @@ using base::Time; using base::TimeDelta; using base::TimeTicks; -using syncer::ModelTypeChangeProcessor; +using syncer::ClientTagBasedModelTypeProcessor; /* The HistoryBackend consists of two components: @@ -218,8 +219,8 @@ typed_url_sync_bridge_ = std::make_unique<TypedURLSyncBridge>( this, db_.get(), - base::BindRepeating(&ModelTypeChangeProcessor::Create, - base::RepeatingClosure())); + std::make_unique<ClientTagBasedModelTypeProcessor>( + syncer::TYPED_URLS, /*dump_stack=*/base::RepeatingClosure())); typed_url_sync_bridge_->Init(); memory_pressure_listener_.reset(new base::MemoryPressureListener(
diff --git a/components/history/core/browser/typed_url_sync_bridge.cc b/components/history/core/browser/typed_url_sync_bridge.cc index 84610a3..230ac721 100644 --- a/components/history/core/browser/typed_url_sync_bridge.cc +++ b/components/history/core/browser/typed_url_sync_bridge.cc
@@ -21,6 +21,7 @@ using syncer::EntityData; using syncer::MetadataChangeList; using syncer::ModelError; +using syncer::ModelTypeChangeProcessor; using syncer::MutableDataBatch; namespace history { @@ -81,8 +82,8 @@ TypedURLSyncBridge::TypedURLSyncBridge( HistoryBackend* history_backend, TypedURLSyncMetadataDatabase* sync_metadata_database, - const ChangeProcessorFactory& change_processor_factory) - : ModelTypeSyncBridge(change_processor_factory, syncer::TYPED_URLS), + std::unique_ptr<ModelTypeChangeProcessor> change_processor) + : ModelTypeSyncBridge(std::move(change_processor)), history_backend_(history_backend), processing_syncer_changes_(false), sync_metadata_database_(sync_metadata_database), @@ -739,7 +740,7 @@ "TypedURLSyncMetadataDatabase."}); return; } - change_processor()->ModelReadyToSync(std::move(batch)); + change_processor()->ModelReadyToSync(this, std::move(batch)); } void TypedURLSyncBridge::ClearErrorStats() {
diff --git a/components/history/core/browser/typed_url_sync_bridge.h b/components/history/core/browser/typed_url_sync_bridge.h index e8a166b..b136b91 100644 --- a/components/history/core/browser/typed_url_sync_bridge.h +++ b/components/history/core/browser/typed_url_sync_bridge.h
@@ -9,6 +9,7 @@ #include "components/history/core/browser/history_backend_observer.h" #include "components/history/core/browser/typed_url_sync_metadata_database.h" #include "components/sync/model/metadata_change_list.h" +#include "components/sync/model/model_type_change_processor.h" #include "components/sync/model/model_type_sync_bridge.h" #include "components/sync/model/sync_error.h" @@ -19,9 +20,10 @@ public: // |sync_metadata_store| is owned by |history_backend|, and must outlive // TypedURLSyncBridge. - TypedURLSyncBridge(HistoryBackend* history_backend, - TypedURLSyncMetadataDatabase* sync_metadata_store, - const ChangeProcessorFactory& change_processor_factory); + TypedURLSyncBridge( + HistoryBackend* history_backend, + TypedURLSyncMetadataDatabase* sync_metadata_store, + std::unique_ptr<syncer::ModelTypeChangeProcessor> change_processor); ~TypedURLSyncBridge() override; // syncer::ModelTypeSyncBridge implementation.
diff --git a/components/history/core/browser/typed_url_sync_bridge_unittest.cc b/components/history/core/browser/typed_url_sync_bridge_unittest.cc index c60962f..d96c38b 100644 --- a/components/history/core/browser/typed_url_sync_bridge_unittest.cc +++ b/components/history/core/browser/typed_url_sync_bridge_unittest.cc
@@ -238,11 +238,11 @@ ASSERT_TRUE(test_dir_.CreateUniqueTempDir()); fake_history_backend_->Init( false, TestHistoryDatabaseParamsForPath(test_dir_.GetPath())); - std::unique_ptr<TypedURLSyncBridge> bridge = - std::make_unique<TypedURLSyncBridge>( - fake_history_backend_.get(), fake_history_backend_->db(), - RecordingModelTypeChangeProcessor::FactoryForBridgeTest(&processor_, - false)); + std::unique_ptr<TypedURLSyncBridge> bridge = std::make_unique< + TypedURLSyncBridge>( + fake_history_backend_.get(), fake_history_backend_->db(), + RecordingModelTypeChangeProcessor::CreateProcessorAndAssignRawPointer( + &processor_)); typed_url_sync_bridge_ = bridge.get(); typed_url_sync_bridge_->Init(); typed_url_sync_bridge_->history_backend_observer_.RemoveAll();
diff --git a/components/ntp_snippets/breaking_news/breaking_news_gcm_app_handler_unittest.cc b/components/ntp_snippets/breaking_news/breaking_news_gcm_app_handler_unittest.cc index c56f3fc..7c2b68a 100644 --- a/components/ntp_snippets/breaking_news/breaking_news_gcm_app_handler_unittest.cc +++ b/components/ntp_snippets/breaking_news/breaking_news_gcm_app_handler_unittest.cc
@@ -927,7 +927,8 @@ histogram_tester.GetAllSamples( "NewTabPage.ContentSuggestions.BreakingNews.ReceivedMessageAction"), ElementsAre(base::Bucket( - /*min=*/metrics::ReceivedMessageAction::NO_ACTION, /*count=*/1))); + /*min=*/static_cast<int>(metrics::ReceivedMessageAction::NO_ACTION), + /*count=*/1))); } TEST_F(BreakingNewsGCMAppHandlerTest, ShouldReportInvalidAction) { @@ -953,7 +954,8 @@ histogram_tester.GetAllSamples( "NewTabPage.ContentSuggestions.BreakingNews.ReceivedMessageAction"), ElementsAre( - base::Bucket(/*min=*/metrics::ReceivedMessageAction::INVALID_ACTION, + base::Bucket(/*min=*/static_cast<int>( + metrics::ReceivedMessageAction::INVALID_ACTION), /*count=*/1))); } @@ -980,7 +982,8 @@ histogram_tester.GetAllSamples( "NewTabPage.ContentSuggestions.BreakingNews.ReceivedMessageAction"), ElementsAre( - base::Bucket(/*min=*/metrics::ReceivedMessageAction::PUSH_TO_REFRESH, + base::Bucket(/*min=*/static_cast<int>( + metrics::ReceivedMessageAction::PUSH_TO_REFRESH), /*count=*/1))); } @@ -1008,7 +1011,9 @@ histogram_tester.GetAllSamples( "NewTabPage.ContentSuggestions.BreakingNews.ReceivedMessageAction"), ElementsAre(base::Bucket( - /*min=*/metrics::ReceivedMessageAction::PUSH_BY_VALUE, /*count=*/1))); + /*min=*/static_cast<int>( + metrics::ReceivedMessageAction::PUSH_BY_VALUE), + /*count=*/1))); } TEST_F(BreakingNewsGCMAppHandlerTest,
diff --git a/components/ntp_snippets/breaking_news/breaking_news_metrics.h b/components/ntp_snippets/breaking_news/breaking_news_metrics.h index 1b787ed..a80e78ae 100644 --- a/components/ntp_snippets/breaking_news/breaking_news_metrics.h +++ b/components/ntp_snippets/breaking_news/breaking_news_metrics.h
@@ -20,7 +20,7 @@ // don't remove or reorder elements, only add new ones at the end (before // COUNT), and keep in sync with ContentSuggestionsBreakingNewsMessageAction in // enums.xml. -enum ReceivedMessageAction { +enum class ReceivedMessageAction { NO_ACTION = 0, INVALID_ACTION = 1, PUSH_BY_VALUE = 2,
diff --git a/components/ntp_snippets/content_suggestions_metrics.cc b/components/ntp_snippets/content_suggestions_metrics.cc index feec62e7..5c6746c 100644 --- a/components/ntp_snippets/content_suggestions_metrics.cc +++ b/components/ntp_snippets/content_suggestions_metrics.cc
@@ -79,7 +79,7 @@ // and contains exactly the values to be recorded in UMA. Don't remove or // reorder elements, only add new ones at the end (before COUNT), and keep in // sync with ContentSuggestionsCategory in histograms.xml. -enum HistogramCategories { +enum class HistogramCategories { EXPERIMENTAL, RECENT_TABS, DOWNLOADS,
diff --git a/components/ntp_snippets/content_suggestions_service.h b/components/ntp_snippets/content_suggestions_service.h index 34718c34..6cc866c 100644 --- a/components/ntp_snippets/content_suggestions_service.h +++ b/components/ntp_snippets/content_suggestions_service.h
@@ -92,7 +92,7 @@ virtual ~Observer() = default; }; - enum State { + enum class State { ENABLED, DISABLED, };
diff --git a/components/ntp_snippets/remote/cached_image_fetcher_unittest.cc b/components/ntp_snippets/remote/cached_image_fetcher_unittest.cc index 2c809c3..64dc9e19 100644 --- a/components/ntp_snippets/remote/cached_image_fetcher_unittest.cc +++ b/components/ntp_snippets/remote/cached_image_fetcher_unittest.cc
@@ -63,7 +63,7 @@ bool enabled_ = true; }; -enum TestType { +enum class TestType { kImageCallback, kImageDataCallback, kBothCallbacks, @@ -103,11 +103,12 @@ } void Fetch(std::string expected_image_data, bool expect_image) { - fake_image_decoder()->SetEnabled(GetParam() != kImageDataCallback); + fake_image_decoder()->SetEnabled(GetParam() != + TestType::kImageDataCallback); base::MockCallback<ImageFetchedCallback> image_callback; base::MockCallback<ImageDataFetchedCallback> image_data_callback; switch (GetParam()) { - case kImageCallback: { + case TestType::kImageCallback: { EXPECT_CALL(image_callback, Run(Property(&gfx::Image::IsEmpty, Eq(!expect_image)))); cached_image_fetcher()->FetchSuggestionImage( @@ -115,13 +116,13 @@ image_callback.Get()); } break; - case kImageDataCallback: { + case TestType::kImageDataCallback: { EXPECT_CALL(image_data_callback, Run(expected_image_data)); cached_image_fetcher()->FetchSuggestionImage( kSuggestionID, GURL(kImageURL), image_data_callback.Get(), ImageFetchedCallback()); } break; - case kBothCallbacks: { + case TestType::kBothCallbacks: { EXPECT_CALL(image_data_callback, Run(expected_image_data)); EXPECT_CALL(image_callback, Run(Property(&gfx::Image::IsEmpty, Eq(!expect_image)))); @@ -193,8 +194,8 @@ INSTANTIATE_TEST_CASE_P(, CachedImageFetcherTest, - testing::Values(kImageCallback, - kImageDataCallback, - kBothCallbacks)); + testing::Values(TestType::kImageCallback, + TestType::kImageDataCallback, + TestType::kBothCallbacks)); } // namespace ntp_snippets
diff --git a/components/ntp_snippets/remote/remote_suggestion.h b/components/ntp_snippets/remote/remote_suggestion.h index 7aef0b6..9da686d 100644 --- a/components/ntp_snippets/remote/remote_suggestion.h +++ b/components/ntp_snippets/remote/remote_suggestion.h
@@ -32,7 +32,7 @@ public: using PtrVector = std::vector<std::unique_ptr<RemoteSuggestion>>; - enum ContentType { UNKNOWN, VIDEO }; + enum class ContentType { UNKNOWN, VIDEO }; ~RemoteSuggestion();
diff --git a/components/reading_list/core/reading_list_model_storage.cc b/components/reading_list/core/reading_list_model_storage.cc index ee7c4ab..87d0f5ccd 100644 --- a/components/reading_list/core/reading_list_model_storage.cc +++ b/components/reading_list/core/reading_list_model_storage.cc
@@ -5,8 +5,7 @@ #include "components/reading_list/core/reading_list_model_storage.h" ReadingListModelStorage::ReadingListModelStorage( - const ChangeProcessorFactory& change_processor_factory, - syncer::ModelType type) - : ModelTypeSyncBridge(change_processor_factory, type) {} + std::unique_ptr<syncer::ModelTypeChangeProcessor> change_processor) + : ModelTypeSyncBridge(std::move(change_processor)) {} ReadingListModelStorage::~ReadingListModelStorage() {}
diff --git a/components/reading_list/core/reading_list_model_storage.h b/components/reading_list/core/reading_list_model_storage.h index 9e29547..4726d858 100644 --- a/components/reading_list/core/reading_list_model_storage.h +++ b/components/reading_list/core/reading_list_model_storage.h
@@ -21,7 +21,7 @@ } namespace syncer { -class ModelTypeSyncBridge; +class ModelTypeChangeProcessor; } // Interface for a persistence layer for reading list. @@ -31,8 +31,7 @@ class ScopedBatchUpdate; ReadingListModelStorage( - const ChangeProcessorFactory& change_processor_factory, - syncer::ModelType type); + std::unique_ptr<syncer::ModelTypeChangeProcessor> change_processor); ~ReadingListModelStorage() override; // Sets the model the Storage is backing.
diff --git a/components/reading_list/core/reading_list_model_unittest.cc b/components/reading_list/core/reading_list_model_unittest.cc index bcfa7d8..0f8597f 100644 --- a/components/reading_list/core/reading_list_model_unittest.cc +++ b/components/reading_list/core/reading_list_model_unittest.cc
@@ -11,6 +11,7 @@ #include "components/reading_list/core/reading_list_store_delegate.h" #include "components/sync/model/metadata_change_list.h" #include "components/sync/model/model_error.h" +#include "components/sync/model_impl/client_tag_based_model_type_processor.h" #include "testing/gtest/include/gtest/gtest.h" namespace { @@ -34,9 +35,10 @@ TestReadingListStorage(TestReadingListStorageObserver* observer, base::SimpleTestClock* clock) : ReadingListModelStorage( - base::Bind(&syncer::ModelTypeChangeProcessor::Create, - base::RepeatingClosure()), - syncer::READING_LIST), + // TODO(crbug.com/823380): Consider using mock/fake here. + std::make_unique<syncer::ClientTagBasedModelTypeProcessor>( + syncer::READING_LIST, + /*dump_stack=*/base::RepeatingClosure())), entries_(new ReadingListStoreDelegate::ReadingListEntries()), observer_(observer), clock_(clock) {}
diff --git a/components/reading_list/core/reading_list_store.cc b/components/reading_list/core/reading_list_store.cc index 7d3321d..91a6666 100644 --- a/components/reading_list/core/reading_list_store.cc +++ b/components/reading_list/core/reading_list_store.cc
@@ -22,8 +22,8 @@ ReadingListStore::ReadingListStore( syncer::OnceModelTypeStoreFactory create_store_callback, - const ChangeProcessorFactory& change_processor_factory) - : ReadingListModelStorage(change_processor_factory, syncer::READING_LIST), + std::unique_ptr<syncer::ModelTypeChangeProcessor> change_processor) + : ReadingListModelStorage(std::move(change_processor)), create_store_callback_(std::move(create_store_callback)), pending_transaction_count_(0) {} @@ -156,7 +156,7 @@ if (error) { change_processor()->ReportError({FROM_HERE, "Failed to read metadata."}); } else { - change_processor()->ModelReadyToSync(std::move(metadata_batch)); + change_processor()->ModelReadyToSync(this, std::move(metadata_batch)); } }
diff --git a/components/reading_list/core/reading_list_store.h b/components/reading_list/core/reading_list_store.h index 71813505a..aae2383 100644 --- a/components/reading_list/core/reading_list_store.h +++ b/components/reading_list/core/reading_list_store.h
@@ -23,8 +23,9 @@ // A ReadingListModelStorage storing and syncing data in protobufs. class ReadingListStore : public ReadingListModelStorage { public: - ReadingListStore(syncer::OnceModelTypeStoreFactory create_store_callback, - const ChangeProcessorFactory& change_processor_factory); + ReadingListStore( + syncer::OnceModelTypeStoreFactory create_store_callback, + std::unique_ptr<syncer::ModelTypeChangeProcessor> change_processor); ~ReadingListStore() override; std::unique_ptr<ScopedBatchUpdate> EnsureBatchCreated() override;
diff --git a/components/reading_list/core/reading_list_store_unittest.cc b/components/reading_list/core/reading_list_store_unittest.cc index 7282617..911f9e8 100644 --- a/components/reading_list/core/reading_list_store_unittest.cc +++ b/components/reading_list/core/reading_list_store_unittest.cc
@@ -94,8 +94,7 @@ reading_list_store_ = std::make_unique<ReadingListStore>( base::BindOnce(&syncer::ModelTypeStoreTestUtil::MoveStoreToCallback, std::move(store_)), - base::Bind(&ReadingListStoreTest::CreateModelTypeChangeProcessor, - base::Unretained(this))); + CreateModelTypeChangeProcessor()); auto clock = std::make_unique<base::SimpleTestClock>(); clock_ = clock.get(); model_ = std::make_unique<ReadingListModelImpl>(nullptr, nullptr, @@ -106,11 +105,10 @@ } std::unique_ptr<syncer::ModelTypeChangeProcessor> - CreateModelTypeChangeProcessor(syncer::ModelType type, - syncer::ModelTypeSyncBridge* service) { + CreateModelTypeChangeProcessor() { auto processor = std::make_unique<TestModelTypeChangeProcessor>(); processor->SetObserver(this); - return std::move(processor); + return processor; } void Put(const std::string& storage_key,
diff --git a/components/sync/device_info/device_info_sync_bridge.cc b/components/sync/device_info/device_info_sync_bridge.cc index 69253794..6b75c66d 100644 --- a/components/sync/device_info/device_info_sync_bridge.cc +++ b/components/sync/device_info/device_info_sync_bridge.cc
@@ -85,8 +85,8 @@ DeviceInfoSyncBridge::DeviceInfoSyncBridge( LocalDeviceInfoProvider* local_device_info_provider, OnceModelTypeStoreFactory store_factory, - const ChangeProcessorFactory& change_processor_factory) - : ModelTypeSyncBridge(change_processor_factory, DEVICE_INFO), + std::unique_ptr<ModelTypeChangeProcessor> change_processor) + : ModelTypeSyncBridge(std::move(change_processor)), local_device_info_provider_(local_device_info_provider) { DCHECK(local_device_info_provider); @@ -390,7 +390,7 @@ return; } - change_processor()->ModelReadyToSync(std::move(metadata_batch)); + change_processor()->ModelReadyToSync(this, std::move(metadata_batch)); ReconcileLocalAndStored(); }
diff --git a/components/sync/device_info/device_info_sync_bridge.h b/components/sync/device_info/device_info_sync_bridge.h index f5abfb7..4ff3941e 100644 --- a/components/sync/device_info/device_info_sync_bridge.h +++ b/components/sync/device_info/device_info_sync_bridge.h
@@ -34,9 +34,10 @@ class DeviceInfoSyncBridge : public ModelTypeSyncBridge, public DeviceInfoTracker { public: - DeviceInfoSyncBridge(LocalDeviceInfoProvider* local_device_info_provider, - OnceModelTypeStoreFactory store_factory, - const ChangeProcessorFactory& change_processor_factory); + DeviceInfoSyncBridge( + LocalDeviceInfoProvider* local_device_info_provider, + OnceModelTypeStoreFactory store_factory, + std::unique_ptr<ModelTypeChangeProcessor> change_processor); ~DeviceInfoSyncBridge() override; // ModelTypeSyncBridge implementation.
diff --git a/components/sync/device_info/device_info_sync_bridge_unittest.cc b/components/sync/device_info/device_info_sync_bridge_unittest.cc index 5ed23eb..3c44f43 100644 --- a/components/sync/device_info/device_info_sync_bridge_unittest.cc +++ b/components/sync/device_info/device_info_sync_bridge_unittest.cc
@@ -207,7 +207,7 @@ provider_.get(), base::BindOnce(&ModelTypeStoreTestUtil::MoveStoreToCallback, std::move(store_)), - mock_processor_.FactoryForBridgeTest()); + mock_processor_.CreateForwardingProcessor()); bridge_->AddObserver(this); } @@ -374,12 +374,12 @@ // Metadata shouldn't be loaded before the provider is initialized. TEST_F(DeviceInfoSyncBridgeTest, LocalProviderInitRace) { - EXPECT_CALL(*processor(), DoModelReadyToSync(_)).Times(0); + EXPECT_CALL(*processor(), DoModelReadyToSync(_, _)).Times(0); set_provider(std::make_unique<LocalDeviceInfoProviderMock>()); InitializeAndPump(); EXPECT_EQ(0u, bridge()->GetAllDeviceInfo().size()); - EXPECT_CALL(*processor(), DoModelReadyToSync(_)); + EXPECT_CALL(*processor(), DoModelReadyToSync(_, _)); local_device()->Initialize(CreateModel(1)); base::RunLoop().RunUntilIdle(); @@ -443,8 +443,9 @@ ModelTypeState state = StateWithEncryption("ekn"); WriteToStore({specifics}, state); - EXPECT_CALL(*processor(), DoModelReadyToSync(MetadataHasEncryptionKeyName( - state.encryption_key_name()))); + EXPECT_CALL(*processor(), + DoModelReadyToSync(_, MetadataHasEncryptionKeyName( + state.encryption_key_name()))); InitializeAndPump(); ASSERT_EQ(2u, bridge()->GetAllDeviceInfo().size()); @@ -543,8 +544,9 @@ EXPECT_FALSE(error); EXPECT_EQ(2, change_count()); - EXPECT_CALL(*processor(), DoModelReadyToSync(MetadataHasEncryptionKeyName( - state.encryption_key_name()))); + EXPECT_CALL(*processor(), + DoModelReadyToSync(_, MetadataHasEncryptionKeyName( + state.encryption_key_name()))); RestartBridge(); std::unique_ptr<DeviceInfo> info = @@ -667,8 +669,9 @@ EXPECT_THAT(*bridge()->GetDeviceInfo(conflict_guid), ModelEqualsSpecifics(conflict_remote)); - EXPECT_CALL(*processor(), DoModelReadyToSync(MetadataHasEncryptionKeyName( - state.encryption_key_name()))); + EXPECT_CALL(*processor(), + DoModelReadyToSync(_, MetadataHasEncryptionKeyName( + state.encryption_key_name()))); RestartBridge(); } @@ -753,17 +756,17 @@ } TEST_F(DeviceInfoSyncBridgeTest, MultipleOnProviderInitialized) { - EXPECT_CALL(*processor(), DoModelReadyToSync(_)).Times(0); + EXPECT_CALL(*processor(), DoModelReadyToSync(_, _)).Times(0); set_provider(std::make_unique<LocalDeviceInfoProviderMock>()); InitializeAndPump(); // Verify the processor is given metadata. - EXPECT_CALL(*processor(), DoModelReadyToSync(NotNull())); + EXPECT_CALL(*processor(), DoModelReadyToSync(_, NotNull())); local_device()->Initialize(CreateModel(0)); base::RunLoop().RunUntilIdle(); // Initializing the provider again shouldn't trigger ModelReadyToSync() again. - EXPECT_CALL(*processor(), DoModelReadyToSync(_)).Times(0); + EXPECT_CALL(*processor(), DoModelReadyToSync(_, _)).Times(0); local_device()->Initialize(CreateModel(0)); base::RunLoop().RunUntilIdle(); }
diff --git a/components/sync/driver/model_type_controller_unittest.cc b/components/sync/driver/model_type_controller_unittest.cc index e55720d..83c7f34c 100644 --- a/components/sync/driver/model_type_controller_unittest.cc +++ b/components/sync/driver/model_type_controller_unittest.cc
@@ -235,9 +235,7 @@ association_callback_called_ = true; } - std::unique_ptr<ModelTypeChangeProcessor> CreateProcessor( - ModelType type, - ModelTypeSyncBridge* bridge) { + std::unique_ptr<ModelTypeChangeProcessor> CreateProcessor() { std::unique_ptr<TestModelTypeProcessor> processor = std::make_unique<TestModelTypeProcessor>(&disable_sync_call_count_); processor_ = processor.get(); @@ -246,8 +244,7 @@ void InitializeModelTypeSyncBridge() { if (model_thread_.task_runner()->BelongsToCurrentThread()) { - bridge_ = std::make_unique<StubModelTypeSyncBridge>(base::Bind( - &ModelTypeControllerTest::CreateProcessor, base::Unretained(this))); + bridge_ = std::make_unique<StubModelTypeSyncBridge>(CreateProcessor()); } else { model_thread_.task_runner()->PostTask( FROM_HERE,
diff --git a/components/sync/model/fake_model_type_change_processor.cc b/components/sync/model/fake_model_type_change_processor.cc index 67e3054..69a5a47 100644 --- a/components/sync/model/fake_model_type_change_processor.cc +++ b/components/sync/model/fake_model_type_change_processor.cc
@@ -14,8 +14,7 @@ // static std::unique_ptr<ModelTypeChangeProcessor> FakeModelTypeChangeProcessor::Create( - ModelType type, - ModelTypeSyncBridge* bridge) { + ModelType type) { return base::WrapUnique(new FakeModelTypeChangeProcessor()); } @@ -44,6 +43,7 @@ const EntityData& entity_data) {} void FakeModelTypeChangeProcessor::ModelReadyToSync( + ModelTypeSyncBridge* bridge, std::unique_ptr<MetadataBatch> batch) {} void FakeModelTypeChangeProcessor::OnSyncStarting(
diff --git a/components/sync/model/fake_model_type_change_processor.h b/components/sync/model/fake_model_type_change_processor.h index 5f868c0..5eac2f8 100644 --- a/components/sync/model/fake_model_type_change_processor.h +++ b/components/sync/model/fake_model_type_change_processor.h
@@ -20,9 +20,7 @@ // A ModelTypeChangeProcessor implementation for tests. class FakeModelTypeChangeProcessor : public ModelTypeChangeProcessor { public: - static std::unique_ptr<ModelTypeChangeProcessor> Create( - ModelType type, - ModelTypeSyncBridge* bridge); + static std::unique_ptr<ModelTypeChangeProcessor> Create(ModelType type); FakeModelTypeChangeProcessor(); ~FakeModelTypeChangeProcessor() override; @@ -37,7 +35,8 @@ const std::string& storage_key, MetadataChangeList* metadata_change_list) override; void UntrackEntity(const EntityData& entity_data) override; - void ModelReadyToSync(std::unique_ptr<MetadataBatch> batch) override; + void ModelReadyToSync(ModelTypeSyncBridge* bridge, + std::unique_ptr<MetadataBatch> batch) override; void OnSyncStarting(const ModelErrorHandler& error_handler, const StartCallback& callback) override; void DisableSync() override;
diff --git a/components/sync/model/fake_model_type_sync_bridge.cc b/components/sync/model/fake_model_type_sync_bridge.cc index 79accb2..a77e330 100644 --- a/components/sync/model/fake_model_type_sync_bridge.cc +++ b/components/sync/model/fake_model_type_sync_bridge.cc
@@ -157,8 +157,8 @@ } FakeModelTypeSyncBridge::FakeModelTypeSyncBridge( - const ChangeProcessorFactory& change_processor_factory) - : ModelTypeSyncBridge(change_processor_factory, PREFERENCES), + std::unique_ptr<ModelTypeChangeProcessor> change_processor) + : ModelTypeSyncBridge(std::move(change_processor)), db_(std::make_unique<Store>()) {} FakeModelTypeSyncBridge::~FakeModelTypeSyncBridge() {
diff --git a/components/sync/model/fake_model_type_sync_bridge.h b/components/sync/model/fake_model_type_sync_bridge.h index bdc6959..0f762d9 100644 --- a/components/sync/model/fake_model_type_sync_bridge.h +++ b/components/sync/model/fake_model_type_sync_bridge.h
@@ -15,6 +15,7 @@ #include "components/sync/model/entity_data.h" #include "components/sync/model/metadata_batch.h" #include "components/sync/model/model_error.h" +#include "components/sync/model/model_type_change_processor.h" #include "components/sync/model/model_type_sync_bridge.h" #include "components/sync/protocol/entity_metadata.pb.h" #include "components/sync/protocol/model_type_state.pb.h" @@ -89,7 +90,7 @@ }; explicit FakeModelTypeSyncBridge( - const ChangeProcessorFactory& change_processor_factory); + std::unique_ptr<ModelTypeChangeProcessor> change_processor); ~FakeModelTypeSyncBridge() override; // Local data modification. Emulates signals from the model thread.
diff --git a/components/sync/model/mock_model_type_change_processor.cc b/components/sync/model/mock_model_type_change_processor.cc index fdf7d4e..2e052f1 100644 --- a/components/sync/model/mock_model_type_change_processor.cc +++ b/components/sync/model/mock_model_type_change_processor.cc
@@ -41,8 +41,9 @@ other_->UntrackEntity(entity_data); } - void ModelReadyToSync(std::unique_ptr<MetadataBatch> batch) override { - other_->ModelReadyToSync(std::move(batch)); + void ModelReadyToSync(ModelTypeSyncBridge* bridge, + std::unique_ptr<MetadataBatch> batch) override { + other_->ModelReadyToSync(bridge, std::move(batch)); } void OnSyncStarting(const ModelErrorHandler& error_handler, @@ -76,18 +77,15 @@ } void MockModelTypeChangeProcessor::ModelReadyToSync( + ModelTypeSyncBridge* bridge, std::unique_ptr<MetadataBatch> batch) { - DoModelReadyToSync(batch.get()); + DoModelReadyToSync(bridge, batch.get()); } -ModelTypeSyncBridge::ChangeProcessorFactory -MockModelTypeChangeProcessor::FactoryForBridgeTest() { - return base::BindRepeating( - [](ModelTypeChangeProcessor* processor, ModelType, ModelTypeSyncBridge*) { - return base::WrapUnique<ModelTypeChangeProcessor>( - new ForwardingModelTypeChangeProcessor(processor)); - }, - base::Unretained(this)); +std::unique_ptr<ModelTypeChangeProcessor> +MockModelTypeChangeProcessor::CreateForwardingProcessor() { + return base::WrapUnique<ModelTypeChangeProcessor>( + new ForwardingModelTypeChangeProcessor(this)); } } // namespace syncer
diff --git a/components/sync/model/mock_model_type_change_processor.h b/components/sync/model/mock_model_type_change_processor.h index 289886b2..6988e7c6 100644 --- a/components/sync/model/mock_model_type_change_processor.h +++ b/components/sync/model/mock_model_type_change_processor.h
@@ -36,10 +36,12 @@ const std::string& storage_key, MetadataChangeList* metadata_change_list)); MOCK_METHOD1(UntrackEntity, void(const EntityData& entity_data)); - // TODO(crbug.com/729950): Use unique_ptr here direclty once move-only + // TODO(crbug.com/729950): Use unique_ptr here directly once move-only // arguments are supported in gMock. - MOCK_METHOD1(DoModelReadyToSync, void(MetadataBatch* batch)); - void ModelReadyToSync(std::unique_ptr<MetadataBatch> batch) override; + MOCK_METHOD2(DoModelReadyToSync, + void(ModelTypeSyncBridge* bridge, MetadataBatch* batch)); + void ModelReadyToSync(ModelTypeSyncBridge* bridge, + std::unique_ptr<MetadataBatch> batch) override; MOCK_METHOD2(OnSyncStarting, void(const ModelErrorHandler& error_handler, const StartCallback& callback)); @@ -47,9 +49,9 @@ MOCK_METHOD0(IsTrackingMetadata, bool()); MOCK_METHOD1(ReportError, void(const ModelError& error)); - // Returns a callback that constructs a processor that forwards all calls to - // |this|. |*this| must outlive the returned factory. - ModelTypeSyncBridge::ChangeProcessorFactory FactoryForBridgeTest(); + // Returns a processor that forwards all calls to + // |this|. |*this| must outlive the returned processor. + std::unique_ptr<ModelTypeChangeProcessor> CreateForwardingProcessor(); }; } // namespace syncer
diff --git a/components/sync/model/model_type_change_processor.cc b/components/sync/model/model_type_change_processor.cc index 9af3d15b..6cb0f5ff 100644 --- a/components/sync/model/model_type_change_processor.cc +++ b/components/sync/model/model_type_change_processor.cc
@@ -8,15 +8,6 @@ namespace syncer { -// static -std::unique_ptr<ModelTypeChangeProcessor> ModelTypeChangeProcessor::Create( - const base::RepeatingClosure& dump_stack, - ModelType type, - ModelTypeSyncBridge* bridge) { - return std::make_unique<ClientTagBasedModelTypeProcessor>( - type, bridge, dump_stack, CommitOnlyTypes().Has(type)); -} - ModelTypeChangeProcessor::ModelTypeChangeProcessor() {} ModelTypeChangeProcessor::~ModelTypeChangeProcessor() {}
diff --git a/components/sync/model/model_type_change_processor.h b/components/sync/model/model_type_change_processor.h index ef090989..3008ad3 100644 --- a/components/sync/model/model_type_change_processor.h +++ b/components/sync/model/model_type_change_processor.h
@@ -27,12 +27,6 @@ using StartCallback = base::Callback<void(std::unique_ptr<ActivationContext>)>; - // A factory function to make an implementation of ModelTypeChangeProcessor. - static std::unique_ptr<ModelTypeChangeProcessor> Create( - const base::RepeatingClosure& dump_stack, - ModelType type, - ModelTypeSyncBridge* bridge); - ModelTypeChangeProcessor(); virtual ~ModelTypeChangeProcessor(); @@ -66,13 +60,15 @@ // change_processor()->Delete() instead. virtual void UntrackEntity(const EntityData& entity_data) = 0; - // The bridge is expected to call this exactly once unless it encounters an + // The |bridge| is expected to call this exactly once unless it encounters an // error. Ideally ModelReadyToSync() is called as soon as possible during // initialization, and must be called before invoking either Put() or // Delete(). The bridge needs to be able to synchronously handle // MergeSyncData() and ApplySyncChanges() after calling ModelReadyToSync(). If // an error is encountered, calling ReportError() instead is sufficient. - virtual void ModelReadyToSync(std::unique_ptr<MetadataBatch> batch) = 0; + // |bridge| must not be nullptr and must outlive this object. + virtual void ModelReadyToSync(ModelTypeSyncBridge* bridge, + std::unique_ptr<MetadataBatch> batch) = 0; // Indicates that sync wants to connect a sync worker to this processor. Once // the processor has metadata from the bridge, it will pass the info needed
diff --git a/components/sync/model/model_type_sync_bridge.cc b/components/sync/model/model_type_sync_bridge.cc index 7d66eb2..b3963ee8 100644 --- a/components/sync/model/model_type_sync_bridge.cc +++ b/components/sync/model/model_type_sync_bridge.cc
@@ -12,11 +12,10 @@ namespace syncer { ModelTypeSyncBridge::ModelTypeSyncBridge( - const ChangeProcessorFactory& change_processor_factory, - ModelType type) - : type_(type), - change_processor_factory_(change_processor_factory), - change_processor_(change_processor_factory_.Run(type_, this)) {} + std::unique_ptr<ModelTypeChangeProcessor> change_processor) + : change_processor_(std::move(change_processor)) { + DCHECK(change_processor_); +} ModelTypeSyncBridge::~ModelTypeSyncBridge() {} @@ -41,13 +40,9 @@ } void ModelTypeSyncBridge::DisableSync() { - DCHECK(change_processor_); - const bool model_ready_to_sync = change_processor_->IsTrackingMetadata(); + // The processor resets its internal state and clears the metadata (by calling + // ApplyDisableSyncChanges() of this bridge). change_processor_->DisableSync(); - change_processor_ = change_processor_factory_.Run(type_, this); - if (model_ready_to_sync) { - change_processor_->ModelReadyToSync(std::make_unique<MetadataBatch>()); - } } void ModelTypeSyncBridge::ApplyDisableSyncChanges(
diff --git a/components/sync/model/model_type_sync_bridge.h b/components/sync/model/model_type_sync_bridge.h index 090c85cd..d91ac06c 100644 --- a/components/sync/model/model_type_sync_bridge.h +++ b/components/sync/model/model_type_sync_bridge.h
@@ -36,11 +36,9 @@ public: using DataCallback = base::OnceCallback<void(std::unique_ptr<DataBatch>)>; using StorageKeyList = std::vector<std::string>; - using ChangeProcessorFactory = base::RepeatingCallback<std::unique_ptr< - ModelTypeChangeProcessor>(ModelType type, ModelTypeSyncBridge* bridge)>; - ModelTypeSyncBridge(const ChangeProcessorFactory& change_processor_factory, - ModelType type); + ModelTypeSyncBridge( + std::unique_ptr<ModelTypeChangeProcessor> change_processor); virtual ~ModelTypeSyncBridge(); @@ -150,10 +148,6 @@ ModelTypeChangeProcessor* change_processor() const; private: - const ModelType type_; - - const ChangeProcessorFactory change_processor_factory_; - std::unique_ptr<ModelTypeChangeProcessor> change_processor_; };
diff --git a/components/sync/model/model_type_sync_bridge_unittest.cc b/components/sync/model/model_type_sync_bridge_unittest.cc index 8297a25..f268f07 100644 --- a/components/sync/model/model_type_sync_bridge_unittest.cc +++ b/components/sync/model/model_type_sync_bridge_unittest.cc
@@ -21,16 +21,10 @@ using testing::Return; using testing::_; -MATCHER(IsEmptyMetadataBatch, "") { - return arg != nullptr && - sync_pb::ModelTypeState().SerializeAsString() == - arg->GetModelTypeState().SerializeAsString() && - arg->TakeAllMetadata().empty(); -} - class ModelTypeSyncBridgeTest : public ::testing::Test { public: - ModelTypeSyncBridgeTest() : bridge_(mock_processor_.FactoryForBridgeTest()) {} + ModelTypeSyncBridgeTest() + : bridge_(mock_processor_.CreateForwardingProcessor()) {} ~ModelTypeSyncBridgeTest() override {} void OnSyncStarting() { @@ -57,19 +51,6 @@ bridge()->DisableSync(); } -// DisableSync should propagate the model readiness (IsTrackingMetadata()). -TEST_F(ModelTypeSyncBridgeTest, PropagateModelReadyToSyncInDisableSync) { - // Model is not ready to sync, so it should remain so after DisableSync(). - ON_CALL(*processor(), IsTrackingMetadata()).WillByDefault(Return(false)); - EXPECT_CALL(*processor(), DoModelReadyToSync(_)).Times(0); - bridge()->DisableSync(); - - // If the Model is ready to sync, so it should remain so after DisableSync(). - ON_CALL(*processor(), IsTrackingMetadata()).WillByDefault(Return(true)); - EXPECT_CALL(*processor(), DoModelReadyToSync(IsEmptyMetadataBatch())); - bridge()->DisableSync(); -} - // ResolveConflicts should return USE_REMOTE unless the remote data is deleted. TEST_F(ModelTypeSyncBridgeTest, DefaultConflictResolution) { EntityData local_data;
diff --git a/components/sync/model/recording_model_type_change_processor.cc b/components/sync/model/recording_model_type_change_processor.cc index fe0ee41..92c8012 100644 --- a/components/sync/model/recording_model_type_change_processor.cc +++ b/components/sync/model/recording_model_type_change_processor.cc
@@ -13,24 +13,6 @@ namespace syncer { -namespace { - -std::unique_ptr<ModelTypeChangeProcessor> CreateAndAssignProcessor( - RecordingModelTypeChangeProcessor** processor_address, - bool expect_error, - ModelType type, - ModelTypeSyncBridge* bridge) { - auto processor = std::make_unique<RecordingModelTypeChangeProcessor>(); - *processor_address = processor.get(); - if (expect_error) - processor->ExpectError(); - // Not all compilers are smart enough to up cast during copy elision, so we - // explicitly create a correctly typed unique_ptr. - return base::WrapUnique(processor.release()); -} - -} // namespace - RecordingModelTypeChangeProcessor::RecordingModelTypeChangeProcessor() {} RecordingModelTypeChangeProcessor::~RecordingModelTypeChangeProcessor() {} @@ -62,6 +44,7 @@ } void RecordingModelTypeChangeProcessor::ModelReadyToSync( + ModelTypeSyncBridge* bridge, std::unique_ptr<MetadataBatch> batch) { std::swap(metadata_, batch); } @@ -76,12 +59,17 @@ } // static -ModelTypeSyncBridge::ChangeProcessorFactory -RecordingModelTypeChangeProcessor::FactoryForBridgeTest( +std::unique_ptr<ModelTypeChangeProcessor> +RecordingModelTypeChangeProcessor::CreateProcessorAndAssignRawPointer( RecordingModelTypeChangeProcessor** processor_address, bool expect_error) { - return base::Bind(&CreateAndAssignProcessor, - base::Unretained(processor_address), expect_error); + auto processor = std::make_unique<RecordingModelTypeChangeProcessor>(); + *processor_address = processor.get(); + if (expect_error) + processor->ExpectError(); + // Not all compilers are smart enough to up cast during copy elision, so we + // explicitly create a correctly typed unique_ptr. + return base::WrapUnique(processor.release()); } } // namespace syncer
diff --git a/components/sync/model/recording_model_type_change_processor.h b/components/sync/model/recording_model_type_change_processor.h index a749277d..cf69d4b8 100644 --- a/components/sync/model/recording_model_type_change_processor.h +++ b/components/sync/model/recording_model_type_change_processor.h
@@ -32,7 +32,8 @@ const std::string& storage_key, MetadataChangeList* metadata_change_list) override; void UntrackEntity(const EntityData& entity_data) override; - void ModelReadyToSync(std::unique_ptr<MetadataBatch> batch) override; + void ModelReadyToSync(ModelTypeSyncBridge* bridge, + std::unique_ptr<MetadataBatch> batch) override; bool IsTrackingMetadata() override; void SetIsTrackingMetadata(bool is_tracking); @@ -55,12 +56,11 @@ MetadataBatch* metadata() const { return metadata_.get(); } - // Returns a callback that constructs a processor and assigns a raw pointer to - // the given address. The caller must ensure that the address passed in is - // still valid whenever the callback is run. This can be useful for tests that - // want to verify the RecordingModelTypeChangeProcessor was given data by the - // bridge they are testing. - static ModelTypeSyncBridge::ChangeProcessorFactory FactoryForBridgeTest( + // Constructs the processor and assigns its raw pointer to the given address. + // This way, the tests can keep the raw pointer for verifying expectations + // while the unique pointer is owned by the bridge being tested. + static std::unique_ptr<ModelTypeChangeProcessor> + CreateProcessorAndAssignRawPointer( RecordingModelTypeChangeProcessor** processor_address, bool expect_error = false);
diff --git a/components/sync/model/stub_model_type_sync_bridge.cc b/components/sync/model/stub_model_type_sync_bridge.cc index 33382a9..b0d370f 100644 --- a/components/sync/model/stub_model_type_sync_bridge.cc +++ b/components/sync/model/stub_model_type_sync_bridge.cc
@@ -4,6 +4,8 @@ #include "components/sync/model/stub_model_type_sync_bridge.h" +#include <utility> + #include "base/bind.h" #include "components/sync/model/fake_model_type_change_processor.h" @@ -11,11 +13,11 @@ StubModelTypeSyncBridge::StubModelTypeSyncBridge() : StubModelTypeSyncBridge( - base::Bind(&FakeModelTypeChangeProcessor::Create)) {} + FakeModelTypeChangeProcessor::Create(PREFERENCES)) {} StubModelTypeSyncBridge::StubModelTypeSyncBridge( - const ChangeProcessorFactory& change_processor_factory) - : ModelTypeSyncBridge(change_processor_factory, PREFERENCES) {} + std::unique_ptr<ModelTypeChangeProcessor> change_processor) + : ModelTypeSyncBridge(std::move(change_processor)) {} StubModelTypeSyncBridge::~StubModelTypeSyncBridge() {}
diff --git a/components/sync/model/stub_model_type_sync_bridge.h b/components/sync/model/stub_model_type_sync_bridge.h index 7ccfd97..4ba9f88 100644 --- a/components/sync/model/stub_model_type_sync_bridge.h +++ b/components/sync/model/stub_model_type_sync_bridge.h
@@ -19,7 +19,7 @@ public: StubModelTypeSyncBridge(); explicit StubModelTypeSyncBridge( - const ChangeProcessorFactory& change_processor_factory); + std::unique_ptr<ModelTypeChangeProcessor> change_processor); ~StubModelTypeSyncBridge() override; std::unique_ptr<MetadataChangeList> CreateMetadataChangeList() override;
diff --git a/components/sync/model_impl/client_tag_based_model_type_processor.cc b/components/sync/model_impl/client_tag_based_model_type_processor.cc index e110f1ae..8c79778 100644 --- a/components/sync/model_impl/client_tag_based_model_type_processor.cc +++ b/components/sync/model_impl/client_tag_based_model_type_processor.cc
@@ -46,17 +46,21 @@ ClientTagBasedModelTypeProcessor::ClientTagBasedModelTypeProcessor( ModelType type, - ModelTypeSyncBridge* bridge, + const base::RepeatingClosure& dump_stack) + : ClientTagBasedModelTypeProcessor(type, + dump_stack, + CommitOnlyTypes().Has(type)) {} + +ClientTagBasedModelTypeProcessor::ClientTagBasedModelTypeProcessor( + ModelType type, const base::RepeatingClosure& dump_stack, bool commit_only) : type_(type), - bridge_(bridge), + bridge_(nullptr), dump_stack_(dump_stack), commit_only_(commit_only), - cached_gc_directive_version_(0), - cached_gc_directive_aged_out_day_(base::Time::FromDoubleT(0)), weak_ptr_factory_(this) { - DCHECK(bridge); + ResetState(); } ClientTagBasedModelTypeProcessor::~ClientTagBasedModelTypeProcessor() { @@ -78,17 +82,18 @@ } void ClientTagBasedModelTypeProcessor::ModelReadyToSync( + ModelTypeSyncBridge* bridge, std::unique_ptr<MetadataBatch> batch) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(waiting_for_metadata_); DCHECK(entities_.empty()); + DCHECK(bridge); + + bridge_ = bridge; // The model already experienced an error; abort; if (model_error_) return; - waiting_for_metadata_ = false; - if (batch->GetModelTypeState().initial_sync_done()) { EntityMetadataMap metadata_map(batch->TakeAllMetadata()); std::vector<std::string> entities_to_commit; @@ -126,7 +131,7 @@ } bool ClientTagBasedModelTypeProcessor::IsModelReadyOrError() const { - return model_error_ || (!waiting_for_metadata_ && !waiting_for_pending_data_); + return model_error_ || (bridge_ && !waiting_for_pending_data_); } void ClientTagBasedModelTypeProcessor::ConnectIfReady() { @@ -151,7 +156,7 @@ bool ClientTagBasedModelTypeProcessor::IsAllowingChanges() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Changes can be handled correctly even before pending data is loaded. - return !waiting_for_metadata_; + return bridge_ != nullptr; } bool ClientTagBasedModelTypeProcessor::IsConnected() const { @@ -161,6 +166,9 @@ void ClientTagBasedModelTypeProcessor::DisableSync() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + // Disabling sync for a type never happens before the model is ready to sync. + DCHECK(bridge_); + std::unique_ptr<MetadataChangeList> change_list = bridge_->CreateMetadataChangeList(); for (const auto& kv : entities_) { @@ -168,6 +176,13 @@ } change_list->ClearModelTypeState(); bridge_->ApplyDisableSyncChanges(std::move(change_list)); + + // Reset all the internal state of the processor. + ResetState(); + + // The model is still ready to sync (with the same |bridge_|) - replay the + // initialization. + ModelReadyToSync(bridge_, std::make_unique<MetadataBatch>()); } bool ClientTagBasedModelTypeProcessor::IsTrackingMetadata() { @@ -947,4 +962,22 @@ entities_.erase(entity->metadata().client_tag_hash()); } +void ClientTagBasedModelTypeProcessor::ResetState() { + // This should reset all mutable fields (except for |bridge_| that is not + // const only because the pointer cannot be passed in the ctor). + worker_.reset(); + model_error_.reset(); + entities_.clear(); + storage_key_to_tag_hash_.clear(); + model_type_state_ = sync_pb::ModelTypeState(); + start_callback_ = StartCallback(); + error_handler_ = ModelErrorHandler(); + waiting_for_pending_data_ = false; + cached_gc_directive_version_ = 0; + cached_gc_directive_aged_out_day_ = base::Time::FromDoubleT(0); + + // Do not let any delayed callbacks to be called. + weak_ptr_factory_.InvalidateWeakPtrs(); +} + } // namespace syncer
diff --git a/components/sync/model_impl/client_tag_based_model_type_processor.h b/components/sync/model_impl/client_tag_based_model_type_processor.h index 4c0a80c..1b7153a 100644 --- a/components/sync/model_impl/client_tag_based_model_type_processor.h +++ b/components/sync/model_impl/client_tag_based_model_type_processor.h
@@ -41,7 +41,9 @@ public ModelTypeChangeProcessor { public: ClientTagBasedModelTypeProcessor(ModelType type, - ModelTypeSyncBridge* bridge, + const base::RepeatingClosure& dump_stack); + // Used only for unit-tests. + ClientTagBasedModelTypeProcessor(ModelType type, const base::RepeatingClosure& dump_stack, bool commit_only); ~ClientTagBasedModelTypeProcessor() override; @@ -63,7 +65,8 @@ const std::string& storage_key, MetadataChangeList* metadata_change_list) override; void UntrackEntity(const EntityData& entity_data) override; - void ModelReadyToSync(std::unique_ptr<MetadataBatch> batch) override; + void ModelReadyToSync(ModelTypeSyncBridge* bridge, + std::unique_ptr<MetadataBatch> batch) override; void OnSyncStarting(const ModelErrorHandler& error_handler, const StartCallback& callback) override; void DisableSync() override; @@ -181,6 +184,13 @@ void RemoveEntity(ProcessorEntityTracker* entity, MetadataChangeList* metadata_change_list); + // Resets the internal state of the processor to the one right after calling + // the ctor (with the exception of |bridge_| which remains intact). + // TODO(jkrcal): Replace the helper function by grouping the state naturally + // into a few structs / nested classes so that the state can be reset by + // resetting these structs. + void ResetState(); + ///////////////////// // Processor state // ///////////////////// @@ -193,7 +203,7 @@ // ModelTypeSyncBridge linked to this processor. The bridge owns this // processor instance so the pointer should never become invalid. - ModelTypeSyncBridge* const bridge_; + ModelTypeSyncBridge* bridge_; // Function to capture and upload a stack trace when an error occurs. const base::RepeatingClosure dump_stack_; @@ -206,9 +216,6 @@ // and so it can be passed to sync if it happened prior to sync being ready. base::Optional<ModelError> model_error_; - // Whether we're waiting for the model to provide metadata. - bool waiting_for_metadata_ = true; - // Whether we're waiting for the model to provide initial commit data. Starts // as false but will be set to true if we detect it's necessary to load data. bool waiting_for_pending_data_ = false; @@ -255,7 +262,7 @@ // model types. For this processor, being commit only means that on commit // confirmation, we should delete local data, because the model side never // intends to read it. This includes both data and metadata. - bool commit_only_; + const bool commit_only_; // The version which processor already ran garbage collection against on. // Cache this value is for saving resource purpose(ex. cpu, battery), so
diff --git a/components/sync/model_impl/client_tag_based_model_type_processor_unittest.cc b/components/sync/model_impl/client_tag_based_model_type_processor_unittest.cc index a36ee5a..80439fd 100644 --- a/components/sync/model_impl/client_tag_based_model_type_processor_unittest.cc +++ b/components/sync/model_impl/client_tag_based_model_type_processor_unittest.cc
@@ -56,12 +56,6 @@ return FakeModelTypeSyncBridge::GenerateEntityData(key, value); } -std::unique_ptr<ModelTypeChangeProcessor> -CreateProcessor(bool commit_only, ModelType type, ModelTypeSyncBridge* bridge) { - return std::make_unique<ClientTagBasedModelTypeProcessor>( - type, bridge, base::RepeatingClosure(), commit_only); -} - void CaptureCommitRequest(CommitRequestDataList* dst, CommitRequestDataList&& src) { *dst = std::move(src); @@ -70,7 +64,11 @@ class TestModelTypeSyncBridge : public FakeModelTypeSyncBridge { public: explicit TestModelTypeSyncBridge(bool commit_only) - : FakeModelTypeSyncBridge(base::Bind(&CreateProcessor, commit_only)) {} + : FakeModelTypeSyncBridge( + std::make_unique<ClientTagBasedModelTypeProcessor>( + PREFERENCES, + /*dump_stack=*/base::RepeatingClosure(), + commit_only)) {} TestModelTypeSyncBridge(std::unique_ptr<TestModelTypeSyncBridge> other, bool commit_only) @@ -179,11 +177,13 @@ // metadata in storage on the bridge side. class ClientTagBasedModelTypeProcessorTest : public ::testing::Test { public: - ClientTagBasedModelTypeProcessorTest() - : bridge_(std::make_unique<TestModelTypeSyncBridge>(false)) {} - + ClientTagBasedModelTypeProcessorTest() {} ~ClientTagBasedModelTypeProcessorTest() override { CheckPostConditions(); } + void SetUp() override { + bridge_ = std::make_unique<TestModelTypeSyncBridge>(IsCommitOnly()); + } + void InitializeToMetadataLoaded() { bridge()->SetInitialSyncDone(true); ModelReadyToSync(); @@ -197,7 +197,7 @@ } void ModelReadyToSync() { - type_processor()->ModelReadyToSync(db().CreateMetadataBatch()); + type_processor()->ModelReadyToSync(bridge(), db().CreateMetadataBatch()); } void OnPendingCommitDataLoaded() { bridge()->OnPendingCommitDataLoaded(); } @@ -237,14 +237,17 @@ return; } - void ResetState(bool keep_db, bool commit_only = false) { - bridge_ = keep_db ? std::make_unique<TestModelTypeSyncBridge>( - std::move(bridge_), commit_only) - : std::make_unique<TestModelTypeSyncBridge>(commit_only); + void ResetState(bool keep_db) { + bridge_ = keep_db + ? std::make_unique<TestModelTypeSyncBridge>( + std::move(bridge_), IsCommitOnly()) + : std::make_unique<TestModelTypeSyncBridge>(IsCommitOnly()); worker_ = nullptr; CheckPostConditions(); } + virtual bool IsCommitOnly() { return false; } + // Wipes existing DB and simulates a pending update of a server-known item. EntitySpecifics ResetStateWriteItem(const std::string& name, const std::string& value) { @@ -292,7 +295,7 @@ bridge()->change_processor()); } - private: + protected: void CheckPostConditions() { EXPECT_FALSE(expect_error_); } void OnReadyToConnect(std::unique_ptr<ActivationContext> context) { @@ -311,6 +314,7 @@ expect_error_ = false; } + private: std::unique_ptr<TestModelTypeSyncBridge> bridge_; // This sets ThreadTaskRunnerHandle on the current thread, which the type @@ -709,51 +713,6 @@ EXPECT_EQ(1, acked_metadata.server_version()); } -// Test that commit only types are deleted after commit response. -TEST_F(ClientTagBasedModelTypeProcessorTest, CommitOnlySimple) { - ResetState(false, true); - InitializeToReadyState(); - EXPECT_TRUE(db().model_type_state().initial_sync_done()); - - bridge()->WriteItem(kKey1, kValue1); - worker()->VerifyPendingCommits({kHash1}); - EXPECT_EQ(1U, db().data_count()); - EXPECT_EQ(1U, db().metadata_count()); - - worker()->AckOnePendingCommit(); - EXPECT_EQ(0U, db().data_count()); - EXPECT_EQ(0U, db().metadata_count()); -} - -// Test that commit only types maintain tracking of entities while unsynced -// changes exist. -TEST_F(ClientTagBasedModelTypeProcessorTest, CommitOnlyUnsyncedChanges) { - ResetState(false, true); - InitializeToReadyState(); - - bridge()->WriteItem(kKey1, kValue1); - worker()->VerifyPendingCommits({kHash1}); - EXPECT_EQ(1U, db().data_count()); - EXPECT_EQ(1U, db().metadata_count()); - - bridge()->WriteItem(kKey1, kValue2); - worker()->VerifyPendingCommits({kHash1, kHash1}); - EXPECT_EQ(1U, db().data_count()); - EXPECT_EQ(1U, db().metadata_count()); - - worker()->AckOnePendingCommit(); - worker()->VerifyPendingCommits({kHash1}); - EXPECT_EQ(1U, db().data_count()); - EXPECT_EQ(1U, db().metadata_count()); - - // The version field isn't meaningful on commit only types, so force a value - // that isn't incremented to verify everything still works. - worker()->AckOnePendingCommit(0 /* version_offset */); - worker()->VerifyPendingCommits({}); - EXPECT_EQ(0U, db().data_count()); - EXPECT_EQ(0U, db().metadata_count()); -} - // Test that an error applying metadata changes from a commit response is // propagated to the error handler. TEST_F(ClientTagBasedModelTypeProcessorTest, ErrorApplyingAck) { @@ -1693,4 +1652,53 @@ EXPECT_EQ(0U, worker()->GetNumPendingCommits()); } +class CommitOnlyClientTagBasedModelTypeProcessorTest + : public ClientTagBasedModelTypeProcessorTest { + protected: + bool IsCommitOnly() override { return true; } +}; + +// Test that commit only types are deleted after commit response. +TEST_F(CommitOnlyClientTagBasedModelTypeProcessorTest, Simple) { + InitializeToReadyState(); + EXPECT_TRUE(db().model_type_state().initial_sync_done()); + + bridge()->WriteItem(kKey1, kValue1); + worker()->VerifyPendingCommits({kHash1}); + EXPECT_EQ(1U, db().data_count()); + EXPECT_EQ(1U, db().metadata_count()); + + worker()->AckOnePendingCommit(); + EXPECT_EQ(0U, db().data_count()); + EXPECT_EQ(0U, db().metadata_count()); +} + +// Test that commit only types maintain tracking of entities while unsynced +// changes exist. +TEST_F(CommitOnlyClientTagBasedModelTypeProcessorTest, UnsyncedChanges) { + InitializeToReadyState(); + + bridge()->WriteItem(kKey1, kValue1); + worker()->VerifyPendingCommits({kHash1}); + EXPECT_EQ(1U, db().data_count()); + EXPECT_EQ(1U, db().metadata_count()); + + bridge()->WriteItem(kKey1, kValue2); + worker()->VerifyPendingCommits({kHash1, kHash1}); + EXPECT_EQ(1U, db().data_count()); + EXPECT_EQ(1U, db().metadata_count()); + + worker()->AckOnePendingCommit(); + worker()->VerifyPendingCommits({kHash1}); + EXPECT_EQ(1U, db().data_count()); + EXPECT_EQ(1U, db().metadata_count()); + + // The version field isn't meaningful on commit only types, so force a value + // that isn't incremented to verify everything still works. + worker()->AckOnePendingCommit(0 /* version_offset */); + worker()->VerifyPendingCommits({}); + EXPECT_EQ(0U, db().data_count()); + EXPECT_EQ(0U, db().metadata_count()); +} + } // namespace syncer
diff --git a/components/sync/user_events/user_event_service_impl_unittest.cc b/components/sync/user_events/user_event_service_impl_unittest.cc index 98808f00..55257af 100644 --- a/components/sync/user_events/user_event_service_impl_unittest.cc +++ b/components/sync/user_events/user_event_service_impl_unittest.cc
@@ -99,7 +99,8 @@ std::unique_ptr<UserEventSyncBridge> MakeBridge() { return std::make_unique<UserEventSyncBridge>( ModelTypeStoreTestUtil::FactoryForInMemoryStoreForTest(), - RecordingModelTypeChangeProcessor::FactoryForBridgeTest(&processor_), + RecordingModelTypeChangeProcessor::CreateProcessorAndAssignRawPointer( + &processor_), &mapper_); }
diff --git a/components/sync/user_events/user_event_sync_bridge.cc b/components/sync/user_events/user_event_sync_bridge.cc index f0f5cefd..30933e2 100644 --- a/components/sync/user_events/user_event_sync_bridge.cc +++ b/components/sync/user_events/user_event_sync_bridge.cc
@@ -69,9 +69,9 @@ UserEventSyncBridge::UserEventSyncBridge( OnceModelTypeStoreFactory store_factory, - const ChangeProcessorFactory& change_processor_factory, + std::unique_ptr<ModelTypeChangeProcessor> change_processor, GlobalIdMapper* global_id_mapper) - : ModelTypeSyncBridge(change_processor_factory, USER_EVENTS), + : ModelTypeSyncBridge(std::move(change_processor)), global_id_mapper_(global_id_mapper) { DCHECK(global_id_mapper_); std::move(store_factory) @@ -214,7 +214,7 @@ if (error) { change_processor()->ReportError(*error); } else { - change_processor()->ModelReadyToSync(std::move(metadata_batch)); + change_processor()->ModelReadyToSync(this, std::move(metadata_batch)); } }
diff --git a/components/sync/user_events/user_event_sync_bridge.h b/components/sync/user_events/user_event_sync_bridge.h index 7dc217c..4a5a2f0d 100644 --- a/components/sync/user_events/user_event_sync_bridge.h +++ b/components/sync/user_events/user_event_sync_bridge.h
@@ -13,6 +13,7 @@ #include "base/macros.h" #include "base/optional.h" +#include "components/sync/model/model_type_change_processor.h" #include "components/sync/model/model_type_store.h" #include "components/sync/model/model_type_sync_bridge.h" #include "components/sync/user_events/global_id_mapper.h" @@ -21,9 +22,10 @@ class UserEventSyncBridge : public ModelTypeSyncBridge { public: - UserEventSyncBridge(OnceModelTypeStoreFactory store_factory, - const ChangeProcessorFactory& change_processor_factory, - GlobalIdMapper* global_id_mapper); + UserEventSyncBridge( + OnceModelTypeStoreFactory store_factory, + std::unique_ptr<ModelTypeChangeProcessor> change_processor, + GlobalIdMapper* global_id_mapper); ~UserEventSyncBridge() override; // ModelTypeSyncBridge implementation.
diff --git a/components/sync/user_events/user_event_sync_bridge_unittest.cc b/components/sync/user_events/user_event_sync_bridge_unittest.cc index 62c8d39..0f2f032 100644 --- a/components/sync/user_events/user_event_sync_bridge_unittest.cc +++ b/components/sync/user_events/user_event_sync_bridge_unittest.cc
@@ -97,7 +97,7 @@ UserEventSyncBridgeTest() { bridge_ = std::make_unique<UserEventSyncBridge>( ModelTypeStoreTestUtil::FactoryForInMemoryStoreForTest(), - mock_processor_.FactoryForBridgeTest(), &test_global_id_mapper_); + mock_processor_.CreateForwardingProcessor(), &test_global_id_mapper_); ON_CALL(*processor(), IsTrackingMetadata()).WillByDefault(Return(true)); ON_CALL(*processor(), DisableSync()).WillByDefault(Invoke([this]() { bridge_->ApplyDisableSyncChanges({}); @@ -171,7 +171,7 @@ }; TEST_F(UserEventSyncBridgeTest, MetadataIsInitialized) { - EXPECT_CALL(*processor(), DoModelReadyToSync(NotNull())); + EXPECT_CALL(*processor(), DoModelReadyToSync(_, NotNull())); base::RunLoop().RunUntilIdle(); }
diff --git a/components/update_client/update_engine.cc b/components/update_client/update_engine.cc index 794639e..1f33635 100644 --- a/components/update_client/update_engine.cc +++ b/components/update_client/update_engine.cc
@@ -86,18 +86,15 @@ return; } - const auto result = - update_contexts_.insert(base::MakeRefCounted<UpdateContext>( - config_, is_foreground, ids, std::move(crx_data_callback), - notify_observers_callback_, std::move(callback), - crx_downloader_factory_)); - - DCHECK(result.second); - - const auto update_context = *result.first; - DCHECK(update_context); + const auto update_context = base::MakeRefCounted<UpdateContext>( + config_, is_foreground, ids, std::move(crx_data_callback), + notify_observers_callback_, std::move(callback), crx_downloader_factory_); DCHECK(!update_context->session_id.empty()); + const auto result = update_contexts_.insert( + std::make_pair(update_context->session_id, update_context)); + DCHECK(result.second); + // Calls out to get the corresponding CrxComponent data for the CRXs in this // update context. DCHECK_EQ(ids.size(), update_context->ids.size()); @@ -304,24 +301,20 @@ DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(update_context); + const auto num_erased = update_contexts_.erase(update_context->session_id); + DCHECK_EQ(1u, num_erased); + base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(update_context->callback), error)); - - const auto it = - std::find_if(update_contexts_.begin(), update_contexts_.end(), - [update_context](scoped_refptr<UpdateContext> other) { - return update_context->session_id == other->session_id; - }); - DCHECK(it != update_contexts_.end()); - update_contexts_.erase(it); } bool UpdateEngine::GetUpdateState(const std::string& id, CrxUpdateItem* update_item) { DCHECK(thread_checker_.CalledOnValidThread()); for (const auto& context : update_contexts_) { - const auto it = context->components.find(id); - if (it != context->components.end()) { + const auto& components = context.second->components; + const auto it = components.find(id); + if (it != components.end()) { *update_item = it->second->GetCrxUpdateItem(); return true; } @@ -349,15 +342,16 @@ Callback callback) { DCHECK(thread_checker_.CalledOnValidThread()); - const auto result = - update_contexts_.insert(base::MakeRefCounted<UpdateContext>( - config_, false, std::vector<std::string>{id}, - UpdateClient::CrxDataCallback(), - UpdateEngine::NotifyObserversCallback(), std::move(callback), - nullptr)); + const auto update_context = base::MakeRefCounted<UpdateContext>( + config_, false, std::vector<std::string>{id}, + UpdateClient::CrxDataCallback(), UpdateEngine::NotifyObserversCallback(), + std::move(callback), nullptr); + DCHECK(!update_context->session_id.empty()); + const auto result = update_contexts_.insert( + std::make_pair(update_context->session_id, update_context)); DCHECK(result.second); - const auto update_context = *result.first; + DCHECK(update_context); DCHECK_EQ(1u, update_context->ids.size()); DCHECK_EQ(1u, update_context->components.count(id));
diff --git a/components/update_client/update_engine.h b/components/update_client/update_engine.h index 067f015..3bc8f38 100644 --- a/components/update_client/update_engine.h +++ b/components/update_client/update_engine.h
@@ -8,7 +8,6 @@ #include <list> #include <map> #include <memory> -#include <set> #include <string> #include <vector> @@ -51,6 +50,9 @@ scoped_refptr<PingManager> ping_manager, const NotifyObserversCallback& notify_observers_callback); + // Returns true and the state of the component identified by |id|, if the + // component is found in any update context. Returns false if the component + // is not found. bool GetUpdateState(const std::string& id, CrxUpdateItem* update_state); void Update(bool is_foreground, @@ -67,7 +69,7 @@ friend class base::RefCounted<UpdateEngine>; ~UpdateEngine(); - using UpdateContexts = std::set<scoped_refptr<UpdateContext>>; + using UpdateContexts = std::map<std::string, scoped_refptr<UpdateContext>>; void UpdateComplete(scoped_refptr<UpdateContext> update_context, Error error); @@ -168,7 +170,9 @@ // is handling the next component in the queue. base::TimeDelta next_update_delay; - // The session id this context is associated with. + // The unique session id of this context. The session id is serialized in + // every protocol request. It is also used as a key in various data stuctures + // to uniquely identify an update context. const std::string session_id; private:
diff --git a/components/viz/PRESUBMIT.py b/components/viz/PRESUBMIT.py index 6cf77b9..c18ec999 100644 --- a/components/viz/PRESUBMIT.py +++ b/components/viz/PRESUBMIT.py
@@ -29,6 +29,6 @@ return output_api.EnsureCQIncludeTrybotsAreAdded( cl, [ - 'master.tryserver.chromium.android:android_optional_gpu_tests_rel', + 'luci.chromium.try:android_optional_gpu_tests_rel', ], 'Automatically added optional GPU tests to run on CQ.')
diff --git a/components/viz/service/frame_sinks/compositor_frame_sink_support_unittest.cc b/components/viz/service/frame_sinks/compositor_frame_sink_support_unittest.cc index e54b5db..361e524 100644 --- a/components/viz/service/frame_sinks/compositor_frame_sink_support_unittest.cc +++ b/components/viz/service/frame_sinks/compositor_frame_sink_support_unittest.cc
@@ -19,7 +19,6 @@ #include "components/viz/test/fake_external_begin_frame_source.h" #include "components/viz/test/fake_surface_observer.h" #include "components/viz/test/mock_compositor_frame_sink_client.h" -#include "components/viz/test/test_frame_sink_manager_client.h" #include "services/viz/privileged/interfaces/compositing/frame_sink_manager.mojom.h" #include "services/viz/public/interfaces/compositing/compositor_frame_sink.mojom.h" #include "testing/gmock/include/gmock/gmock.h" @@ -47,6 +46,11 @@ const base::UnguessableToken kArbitrarySourceId2 = base::UnguessableToken::Deserialize(0xdead, 0xbee0); +// Matches a SurfaceInfo for |surface_id|. +MATCHER_P(SurfaceInfoWithId, surface_id, "") { + return arg.id() == surface_id; +} + void StubResultCallback(std::unique_ptr<CopyOutputResult> result) {} gpu::SyncToken GenTestSyncToken(int id) { @@ -56,11 +60,35 @@ return token; } +class MockFrameSinkManagerClient : public mojom::FrameSinkManagerClient { + public: + MockFrameSinkManagerClient() = default; + ~MockFrameSinkManagerClient() override = default; + + // mojom::FrameSinkManagerClient: + MOCK_METHOD1(OnSurfaceCreated, void(const SurfaceId&)); + MOCK_METHOD1(OnFirstSurfaceActivation, void(const SurfaceInfo&)); + void OnClientConnectionClosed(const FrameSinkId& frame_sink_id) override {} + void OnAggregatedHitTestRegionListUpdated( + const FrameSinkId& frame_sink_id, + mojo::ScopedSharedBufferHandle active_handle, + uint32_t active_handle_size, + mojo::ScopedSharedBufferHandle idle_handle, + uint32_t idle_handle_sizes) override {} + void SwitchActiveAggregatedHitTestRegionList( + const FrameSinkId& frame_sink_id, + uint8_t active_handle_index) override {} + void OnFrameTokenChanged(const FrameSinkId& frame_sink_id, + uint32_t frame_token) override {} + + private: + DISALLOW_COPY_AND_ASSIGN(MockFrameSinkManagerClient); +}; + class CompositorFrameSinkSupportTest : public testing::Test { public: CompositorFrameSinkSupportTest() - : frame_sink_manager_client_(&manager_), - begin_frame_source_(0.f, false), + : begin_frame_source_(0.f, false), local_surface_id_(3, kArbitraryToken), frame_sync_token_(GenTestSyncToken(4)), consumer_sync_token_(GenTestSyncToken(5)) { @@ -71,6 +99,12 @@ &fake_support_client_, &manager_, kArbitraryFrameSinkId, kIsRoot, kNeedsSyncPoints); support_->SetBeginFrameSource(&begin_frame_source_); + + // By default drop temporary references. + ON_CALL(frame_sink_manager_client_, OnSurfaceCreated(_)) + .WillByDefault(Invoke([this](const SurfaceId& surface_id) { + manager_.DropTemporaryReference(surface_id); + })); } ~CompositorFrameSinkSupportTest() override { manager_.InvalidateFrameSinkId(kArbitraryFrameSinkId); @@ -152,12 +186,9 @@ support_->RefResources(surface->GetActiveFrame().resource_list); } - // testing::Test implementation: - void TearDown() override { frame_sink_manager_client_.Reset(); } - protected: FrameSinkManagerImpl manager_; - TestFrameSinkManagerClient frame_sink_manager_client_; + MockFrameSinkManagerClient frame_sink_manager_client_; FakeCompositorFrameSinkClient fake_support_client_; std::unique_ptr<CompositorFrameSinkSupport> support_; FakeExternalBeginFrameSource begin_frame_source_; @@ -587,19 +618,62 @@ manager_.InvalidateFrameSinkId(kAnotherArbitraryFrameSinkId); } +// This test checks the case where a client submits a CompositorFrame for a +// SurfaceId that has been evicted. The CompositorFrame resurrects the evicted +// Surface and notifies the browser which immediately evicts the Surface again +// because it's not needed. +TEST_F(CompositorFrameSinkSupportTest, ResurectAndImmediatelyEvict) { + LocalSurfaceId local_surface_id(1, kArbitraryToken); + SurfaceId surface_id(kArbitraryFrameSinkId, local_surface_id); + + auto frame = CompositorFrameBuilder().AddDefaultRenderPass().Build(); + support_->SubmitCompositorFrame(local_surface_id, std::move(frame)); + + // The surface should be activated now. + EXPECT_EQ(support_->last_activated_surface_id(), surface_id); + + // Evict the surface. Make surface CompositorFrameSinkSupport reflects this. + manager_.EvictSurfaces({surface_id}); + EXPECT_FALSE(support_->last_activated_surface_id().is_valid()); + + // We don't garbage collect the evicted surface yet because either garbage + // collection hasn't run or something still has a reference to it. + + // Call FrameSinkManagerImpl::EvictSurfaces() for |surface_id| in the same + // callstack as OnFirstSurfaceActivation() as that's what DelegatedFrameHost + // will do. + EXPECT_CALL(frame_sink_manager_client_, + OnFirstSurfaceActivation(SurfaceInfoWithId(surface_id))) + .WillOnce(Invoke([this](const SurfaceInfo& surface_info) { + manager_.EvictSurfaces({surface_info.id()}); + })); + + // Submit the late CompositorFrame which will resurrect the Surface and + // trigger another eviction. + frame = CompositorFrameBuilder().AddDefaultRenderPass().Build(); + support_->SubmitCompositorFrame(local_surface_id, std::move(frame)); + + // The Surface should be evicted again immediately after it's submitted. + EXPECT_FALSE(support_->last_activated_surface_id().is_valid()); +} + // Verify that a temporary reference blocks surface eviction and that when the // temporary reference is removed due to frame sink invalidation the surface // is deleted. TEST_F(CompositorFrameSinkSupportTest, EvictSurfaceWithTemporaryReference) { constexpr FrameSinkId parent_frame_sink_id(1234, 5678); - frame_sink_manager_client_.SetFrameSinkHierarchy(parent_frame_sink_id, - support_->frame_sink_id()); manager_.RegisterFrameSinkId(parent_frame_sink_id); const LocalSurfaceId local_surface_id(5, kArbitraryToken); const SurfaceId surface_id(support_->frame_sink_id(), local_surface_id); + EXPECT_CALL(frame_sink_manager_client_, OnSurfaceCreated(surface_id)) + .WillOnce( + Invoke([this, &parent_frame_sink_id](const SurfaceId& surface_id) { + manager_.AssignTemporaryReference(surface_id, parent_frame_sink_id); + })); + // When CompositorFrame is submitted, a temporary reference will be created // and |parent_frame_sink_id| will be assigned as the owner. support_->SubmitCompositorFrame(local_surface_id,
diff --git a/components/viz/service/surfaces/surface.cc b/components/viz/service/surfaces/surface.cc index d46aa31..ecf8cd2 100644 --- a/components/viz/service/surfaces/surface.cc +++ b/components/viz/service/surfaces/surface.cc
@@ -321,14 +321,17 @@ UnrefFrameResourcesAndRunCallbacks(std::move(previous_frame_data)); + // This should happen before calling SurfaceManager::FirstSurfaceActivation(), + // as that notifies observers which may have side effects for + // |surface_client_|. See https://crbug.com/821855. + if (surface_client_) + surface_client_->OnSurfaceActivated(this); + if (!seen_first_frame_activation_) { seen_first_frame_activation_ = true; surface_manager_->FirstSurfaceActivation(surface_info_); } - if (surface_client_) - surface_client_->OnSurfaceActivated(this); - surface_manager_->SurfaceActivated(this, duration); }
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index 7c509fff..bed80f9f 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -2203,6 +2203,9 @@ "IOSurface.framework", ] sources += [ + "renderer_host/render_widget_host_ns_view_bridge.h", + "renderer_host/render_widget_host_ns_view_bridge.mm", + "renderer_host/render_widget_host_ns_view_client.h", "renderer_host/render_widget_host_view_cocoa.h", "renderer_host/render_widget_host_view_cocoa.mm", ]
diff --git a/content/browser/android/content_feature_list.cc b/content/browser/android/content_feature_list.cc index 9cdddbefc..2cff631 100644 --- a/content/browser/android/content_feature_list.cc +++ b/content/browser/android/content_feature_list.cc
@@ -22,7 +22,7 @@ // this array may either refer to features defined in the header of this file or // in other locations in the code base (e.g. content_features.h). const base::Feature* kFeaturesExposedToJava[] = { - &kEnhancedSelectionInsertionHandle, &kRequestUnbufferedDispatch, + &kEnhancedSelectionInsertionHandle, }; const base::Feature* FindFeatureExposedToJava(const std::string& feature_name) {
diff --git a/content/browser/android/content_view_core.cc b/content/browser/android/content_view_core.cc index 8f8793f..d0ccd7e 100644 --- a/content/browser/android/content_view_core.cc +++ b/content/browser/android/content_view_core.cc
@@ -371,12 +371,6 @@ static_cast<WebContentsImpl*>(web_contents())->OnScreenOrientationChange(); } -jboolean ContentViewCore::UsingSynchronousCompositing( - JNIEnv* env, - const base::android::JavaParamRef<jobject>& obj) { - return content::GetContentClient()->UsingSynchronousCompositing(); -} - // This is called for each ContentView. jlong JNI_ContentViewCoreImpl_Init( JNIEnv* env,
diff --git a/content/browser/android/content_view_core.h b/content/browser/android/content_view_core.h index 48984d0e12..64c8564 100644 --- a/content/browser/android/content_view_core.h +++ b/content/browser/android/content_view_core.h
@@ -106,10 +106,6 @@ const base::android::JavaParamRef<jstring>& textTrackTextShadow, const base::android::JavaParamRef<jstring>& textTrackTextSize); - jboolean UsingSynchronousCompositing( - JNIEnv* env, - const base::android::JavaParamRef<jobject>& obj); - // -------------------------------------------------------------------------- // Methods called from native code // --------------------------------------------------------------------------
diff --git a/content/browser/android/gesture_listener_manager.cc b/content/browser/android/gesture_listener_manager.cc index 1a3e086..abd3413 100644 --- a/content/browser/android/gesture_listener_manager.cc +++ b/content/browser/android/gesture_listener_manager.cc
@@ -167,7 +167,8 @@ int gesture_type = ToGestureEventType(event.GetType()); float dip_scale = web_contents_->GetNativeView()->GetDipScale(); return Java_GestureListenerManagerImpl_filterTapOrPressEvent( - env, j_obj, gesture_type, gesture.x * dip_scale, gesture.y * dip_scale); + env, j_obj, gesture_type, gesture.PositionInWidget().x * dip_scale, + gesture.PositionInWidget().y * dip_scale); } // All positions and sizes (except |top_shown_pix|) are in CSS pixels.
diff --git a/content/browser/android/url_request_content_job.cc b/content/browser/android/url_request_content_job.cc index baf9483f..fb7f3c47 100644 --- a/content/browser/android/url_request_content_job.cc +++ b/content/browser/android/url_request_content_job.cc
@@ -9,6 +9,8 @@ #include "base/files/file_util.h" #include "base/message_loop/message_loop.h" #include "base/task_runner.h" +#include "content/public/browser/resource_request_info.h" +#include "content/public/common/resource_type.h" #include "net/base/file_stream.h" #include "net/base/io_buffer.h" #include "net/http/http_util.h" @@ -87,6 +89,10 @@ bool URLRequestContentJob::GetMimeType(std::string* mime_type) const { DCHECK(request_); + if (!mime_type_from_intent_.empty()) { + *mime_type = mime_type_from_intent_; + return true; + } if (!meta_info_.mime_type.empty()) { *mime_type = meta_info_.mime_type; return true; @@ -96,6 +102,15 @@ void URLRequestContentJob::SetExtraRequestHeaders( const net::HttpRequestHeaders& headers) { + const content::ResourceRequestInfo* resource_request_info = + content::ResourceRequestInfo::ForRequest(request()); + if (resource_request_info && resource_request_info->GetResourceType() == + content::RESOURCE_TYPE_MAIN_FRAME) { + std::string intent_type_header; + if (headers.GetHeader("X-Chrome-intent-type", &intent_type_header)) + mime_type_from_intent_ = intent_type_header; + } + std::string range_header; if (!headers.GetHeader(net::HttpRequestHeaders::kRange, &range_header)) return;
diff --git a/content/browser/android/url_request_content_job.h b/content/browser/android/url_request_content_job.h index f36f904c..9f6b379 100644 --- a/content/browser/android/url_request_content_job.h +++ b/content/browser/android/url_request_content_job.h
@@ -86,6 +86,7 @@ std::unique_ptr<net::FileStream> stream_; ContentMetaInfo meta_info_; + std::string mime_type_from_intent_; const scoped_refptr<base::TaskRunner> content_task_runner_; net::HttpByteRange byte_range_;
diff --git a/content/browser/android/url_request_content_job_unittest.cc b/content/browser/android/url_request_content_job_unittest.cc index 1e96893..8815dc8 100644 --- a/content/browser/android/url_request_content_job_unittest.cc +++ b/content/browser/android/url_request_content_job_unittest.cc
@@ -15,6 +15,7 @@ #include "base/test/scoped_task_environment.h" #include "base/test/test_file_util.h" #include "base/threading/thread_task_runner_handle.h" +#include "content/public/browser/resource_request_info.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" @@ -115,7 +116,7 @@ // contents out of it. If a Range is provided, this function will add the // appropriate Range http header to the request and verify the bytes // retrieved. - void RunRequest(const Range* range); + void RunRequest(const Range* range, const char* intent_type); base::test::ScopedTaskEnvironment scoped_task_environment_; JobObserverImpl observer_; @@ -125,7 +126,8 @@ URLRequestContentJobTest::URLRequestContentJobTest() {} -void URLRequestContentJobTest::RunRequest(const Range* range) { +void URLRequestContentJobTest::RunRequest(const Range* range, + const char* intent_type) { base::FilePath test_dir; PathService::Get(base::DIR_SOURCE_ROOT, &test_dir); test_dir = test_dir.AppendASCII("content"); @@ -148,6 +150,19 @@ std::unique_ptr<net::URLRequest> request(context_.CreateRequest( GURL(path.value()), net::DEFAULT_PRIORITY, &delegate_)); + + ResourceRequestInfo::AllocateForTesting(request.get(), + RESOURCE_TYPE_MAIN_FRAME, + nullptr, // context + 0, // render_process_id + 0, // render_view_id + 0, // render_frame_id + true, // is_main_frame + false, // allow_download + true, // is_async + PREVIEWS_OFF, // previews_state + nullptr); // navigation_ui_data + int expected_length = file_size; if (range) { ASSERT_GE(range->start, 0); @@ -164,6 +179,12 @@ expected_length = 0; } } + std::string expected_mime_type("image/png"); + if (intent_type) { + request->SetExtraRequestHeaderByName("X-Chrome-intent-type", intent_type, + true /*overwrite*/); + expected_mime_type = intent_type; + } request->Start(); base::RunLoop loop; @@ -172,29 +193,37 @@ EXPECT_FALSE(delegate_.request_failed()); ASSERT_EQ(1, observer_.num_jobs_created()); EXPECT_EQ(expected_length, delegate_.bytes_received()); + + std::string mime_type; + request->GetMimeType(&mime_type); + EXPECT_EQ(expected_mime_type, mime_type); } // Disabled: http://crbug.com/807045. TEST_F(URLRequestContentJobTest, DISABLED_ContentURIWithoutRange) { - RunRequest(NULL); + RunRequest(NULL, NULL); } // Disabled: http://crbug.com/807045. TEST_F(URLRequestContentJobTest, DISABLED_ContentURIWithSmallRange) { Range range(1, 10); - RunRequest(&range); + RunRequest(&range, NULL); } // Disabled: http://crbug.com/807045. TEST_F(URLRequestContentJobTest, DISABLED_ContentURIWithLargeRange) { Range range(1, 100000); - RunRequest(&range); + RunRequest(&range, NULL); } // Disabled: http://crbug.com/807045. TEST_F(URLRequestContentJobTest, DISABLED_ContentURIWithZeroRange) { Range range(0, 0); - RunRequest(&range); + RunRequest(&range, NULL); +} + +TEST_F(URLRequestContentJobTest, ContentURIWithIntentTypeHeader) { + RunRequest(NULL, "text/html"); } } // namespace
diff --git a/content/browser/browser_plugin/browser_plugin_guest.cc b/content/browser/browser_plugin/browser_plugin_guest.cc index fee9702..5eaa8006 100644 --- a/content/browser/browser_plugin/browser_plugin_guest.cc +++ b/content/browser/browser_plugin/browser_plugin_guest.cc
@@ -439,8 +439,8 @@ if (event.GetType() == blink::WebInputEvent::kGestureScrollUpdate) { blink::WebGestureEvent resent_gesture_event; memcpy(&resent_gesture_event, &event, sizeof(blink::WebGestureEvent)); - resent_gesture_event.x += offset_from_embedder.x(); - resent_gesture_event.y += offset_from_embedder.y(); + resent_gesture_event.SetPositionInWidget( + resent_gesture_event.PositionInWidget() + offset_from_embedder); // Mark the resend source with the browser plugin's instance id, so the // correct browser_plugin will know to ignore the event. resent_gesture_event.resending_plugin_id = browser_plugin_instance_id_;
diff --git a/content/browser/download/download_browsertest.cc b/content/browser/download/download_browsertest.cc index a3f6524..eadc06c 100644 --- a/content/browser/download/download_browsertest.cc +++ b/content/browser/download/download_browsertest.cc
@@ -3334,6 +3334,7 @@ // Verify the case that the first response is HTTP 200, and then interrupted, // and the second response is HTTP 404, the response body of 404 should be // fetched. +// Also verify the request header is correctly piped to download item. IN_PROC_BROWSER_TEST_F(DownloadContentTest, FetchErrorResponseBodyResumption) { SetupErrorInjectionDownloads(); GURL url = TestDownloadHttpResponse::GetNextURLForDownload(); @@ -3348,6 +3349,8 @@ DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( shell()->web_contents(), server_url, TRAFFIC_ANNOTATION_FOR_TESTS)); download_parameters->set_fetch_error_body(true); + download_parameters->add_request_header("header_key", "header_value"); + DownloadManager* download_manager = DownloadManagerForShell(shell()); std::unique_ptr<DownloadTestObserver> observer; @@ -3378,6 +3381,14 @@ base::ReadFileToString(items[0]->GetTargetFilePath(), &file_content)); EXPECT_EQ(std::string(), file_content); } + + // Additional request header should be sent. + test_response_handler()->WaitUntilCompletion(2u); + const auto& request = test_response_handler()->completed_requests().back(); + auto it = request->http_request.headers.find("header_key"); + EXPECT_TRUE(it != request->http_request.headers.end()); + EXPECT_EQ(request->http_request.headers["header_key"], + std::string("header_value")); } IN_PROC_BROWSER_TEST_F(DownloadContentTest, ForceDownloadMultipartRelatedPage) {
diff --git a/content/browser/download/download_item_impl.cc b/content/browser/download/download_item_impl.cc index 349a4c9..3f0847d 100644 --- a/content/browser/download/download_item_impl.cc +++ b/content/browser/download/download_item_impl.cc
@@ -393,6 +393,7 @@ etag_(info.etag), is_updating_observers_(false), fetch_error_body_(info.fetch_error_body), + request_headers_(info.request_headers), download_source_(info.download_source), weak_ptr_factory_(this) { delegate_->Attach(); @@ -1401,8 +1402,11 @@ // Read data from in-progress cache. auto in_progress_entry = GetInProgressEntry(guid_, GetBrowserContext()); - if (in_progress_entry) + if (in_progress_entry) { download_source_ = in_progress_entry->download_source; + fetch_error_body_ = in_progress_entry->fetch_error_body; + request_headers_ = in_progress_entry->request_headers; + } } DVLOG(20) << __func__ << "() " << DebugString(true); @@ -2403,11 +2407,18 @@ download_params->set_etag(GetETag()); download_params->set_hash_of_partial_file(GetHash()); download_params->set_hash_state(std::move(hash_state_)); + + // TODO(xingliu): Read |fetch_error_body| and |request_headers_| from the + // cache, and don't copy them into DownloadItemImpl. download_params->set_fetch_error_body(fetch_error_body_); + for (const auto& header : request_headers_) { + download_params->add_request_header(header.first, header.second); + } auto entry = GetInProgressEntry(GetGuid(), GetBrowserContext()); - if (entry) + if (entry) { download_params->set_request_origin(entry.value().request_origin); + } // Note that resumed downloads disallow redirects. Hence the referrer URL // (which is the contents of the Referer header for the last download request)
diff --git a/content/browser/download/download_item_impl.h b/content/browser/download/download_item_impl.h index fed8e50..6a46ad5 100644 --- a/content/browser/download/download_item_impl.h +++ b/content/browser/download/download_item_impl.h
@@ -22,6 +22,7 @@ #include "components/download/public/common/download_interrupt_reasons.h" #include "components/download/public/common/download_item.h" #include "components/download/public/common/download_request_handle_interface.h" +#include "components/download/public/common/download_url_parameters.h" #include "components/download/public/common/resume_mode.h" #include "content/common/content_export.h" #include "url/gurl.h" @@ -767,6 +768,10 @@ // response. bool fetch_error_body_ = false; + // Request header key/value pairs that will be added to the download HTTP + // request. + download::DownloadUrlParameters::RequestHeadersType request_headers_; + // Source of the download, used in metrics. download::DownloadSource download_source_ = download::DownloadSource::UNKNOWN;
diff --git a/content/browser/download/download_manager_impl.cc b/content/browser/download/download_manager_impl.cc index 1e178877..2cc16fe 100644 --- a/content/browser/download/download_manager_impl.cc +++ b/content/browser/download/download_manager_impl.cc
@@ -139,16 +139,16 @@ return download_id; } -download::DownloadEntry CreateDownloadEntryFromItemImpl( - const DownloadItemImpl& item) { - return download::DownloadEntry(item.GetGuid(), item.download_source(), - GetUniqueDownloadId()); -} - download::DownloadEntry CreateDownloadEntryFromItem( - const download::DownloadItem& item) { - return download::DownloadEntry( - item.GetGuid(), download::DownloadSource::UNKNOWN, GetUniqueDownloadId()); + const download::DownloadItem& item, + const std::string& request_origin, + download::DownloadSource download_source, + bool fetch_error_body, + const download::DownloadUrlParameters::RequestHeadersType& + request_headers) { + return download::DownloadEntry(item.GetGuid(), request_origin, + download_source, fetch_error_body, + request_headers, GetUniqueDownloadId()); } void BeginDownload(std::unique_ptr<download::DownloadUrlParameters> params, @@ -370,7 +370,10 @@ in_progress_cache_->RetrieveEntry(download->GetGuid()); download::DownloadEntry entry; if (!entry_opt.has_value()) { - entry = CreateDownloadEntryFromItem(*download); + entry = CreateDownloadEntryFromItem( + *download, std::string(), /* request_origin */ + download::DownloadSource::UNKNOWN, false, /* fetch_error_body */ + download::DownloadUrlParameters::RequestHeadersType()); in_progress_cache_->AddOrReplaceEntry(entry); break; } @@ -657,8 +660,9 @@ base::Optional<download::DownloadEntry> entry_opt = in_progress_cache->RetrieveEntry(download->GetGuid()); if (!entry_opt.has_value()) { - in_progress_cache->AddOrReplaceEntry( - CreateDownloadEntryFromItemImpl(*download)); + in_progress_cache->AddOrReplaceEntry(CreateDownloadEntryFromItem( + *download, info->request_origin, info->download_source, + info->fetch_error_body, info->request_headers)); } } @@ -790,8 +794,10 @@ base::Optional<download::DownloadEntry> entry_opt = in_progress_cache->RetrieveEntry(download_item->GetGuid()); if (!entry_opt.has_value()) { - in_progress_cache->AddOrReplaceEntry( - CreateDownloadEntryFromItemImpl(*download_item)); + in_progress_cache->AddOrReplaceEntry(CreateDownloadEntryFromItem( + *download_item, std::string(), /* request_origin */ + download::DownloadSource::UNKNOWN, false, /* fetch_error_body */ + download::DownloadUrlParameters::RequestHeadersType())); } } }
diff --git a/content/browser/download/download_request_core.cc b/content/browser/download/download_request_core.cc index ac42757..bc89894 100644 --- a/content/browser/download/download_request_core.cc +++ b/content/browser/download/download_request_core.cc
@@ -68,6 +68,10 @@ std::string guid() const { return guid_; } bool is_transient() const { return transient_; } bool fetch_error_body() const { return fetch_error_body_; } + const download::DownloadUrlParameters::RequestHeadersType& request_headers() + const { + return request_headers_; + } const download::DownloadUrlParameters::OnStartedCallback& callback() const { return on_started_callback_; } @@ -80,6 +84,7 @@ uint32_t download_id_ = download::DownloadItem::kInvalidId; std::string guid_; bool fetch_error_body_ = false; + download::DownloadUrlParameters::RequestHeadersType request_headers_; bool transient_ = false; download::DownloadUrlParameters::OnStartedCallback on_started_callback_; std::string request_origin_; @@ -98,6 +103,7 @@ request_data->download_id_ = download_id; request_data->guid_ = parameters->guid(); request_data->fetch_error_body_ = parameters->fetch_error_body(); + request_data->request_headers_ = parameters->request_headers(); request_data->transient_ = parameters->is_transient(); request_data->on_started_callback_ = parameters->callback(); request_data->request_origin_ = parameters->request_origin(); @@ -191,6 +197,7 @@ download_id_ = request_data->download_id(); guid_ = request_data->guid(); fetch_error_body_ = request_data->fetch_error_body(); + request_headers_ = request_data->request_headers(); transient_ = request_data->is_transient(); on_started_callback_ = request_data->callback(); DownloadRequestData::Detach(request_); @@ -235,6 +242,7 @@ create_info->response_headers = request()->response_headers(); create_info->offset = create_info->save_info->offset; create_info->fetch_error_body = fetch_error_body_; + create_info->request_headers = request_headers_; create_info->request_origin = request_origin_; create_info->download_source = download_source_; return create_info;
diff --git a/content/browser/download/download_request_core.h b/content/browser/download/download_request_core.h index 30575437..409e3e3 100644 --- a/content/browser/download/download_request_core.h +++ b/content/browser/download/download_request_core.h
@@ -132,6 +132,7 @@ uint32_t download_id_; std::string guid_; bool fetch_error_body_; + download::DownloadUrlParameters::RequestHeadersType request_headers_; bool transient_; download::DownloadUrlParameters::OnStartedCallback on_started_callback_;
diff --git a/content/browser/frame_host/cross_process_frame_connector.cc b/content/browser/frame_host/cross_process_frame_connector.cc index af4fa3c..0428388d 100644 --- a/content/browser/frame_host/cross_process_frame_connector.cc +++ b/content/browser/frame_host/cross_process_frame_connector.cc
@@ -216,8 +216,8 @@ blink::WebGestureEvent resent_gesture_event(event); // TODO(kenrb, wjmaclean): Do we need to account for transforms here? // See https://crbug.com/626020. - resent_gesture_event.x += offset_from_parent.x(); - resent_gesture_event.y += offset_from_parent.y(); + resent_gesture_event.SetPositionInWidget( + resent_gesture_event.PositionInWidget() + offset_from_parent); if (view_->wheel_scroll_latching_enabled()) { if (event.GetType() == blink::WebInputEvent::kGestureScrollBegin) {
diff --git a/content/browser/frame_host/render_frame_host_impl.cc b/content/browser/frame_host/render_frame_host_impl.cc index b44fe8c3..eb3fa27 100644 --- a/content/browser/frame_host/render_frame_host_impl.cc +++ b/content/browser/frame_host/render_frame_host_impl.cc
@@ -1531,9 +1531,6 @@ "frame_tree_node", frame_tree_node_->frame_tree_node_id(), "url", validated_params->url.possibly_invalid_spec()); - if (navigation_request_) - was_discarded_ = navigation_request_->request_params().was_discarded; - // Notify the resource scheduler of the navigation committing. NotifyResourceSchedulerOfNavigation(process->GetID(), *validated_params); @@ -4770,6 +4767,9 @@ pending_commit_ = false; } + if (navigation_request_) + was_discarded_ = navigation_request_->request_params().was_discarded; + // Find the appropriate NavigationHandle for this navigation. std::unique_ptr<NavigationHandleImpl> navigation_handle;
diff --git a/content/browser/frame_host/render_widget_host_view_guest.cc b/content/browser/frame_host/render_widget_host_view_guest.cc index c0d75f3..507b5d0c 100644 --- a/content/browser/frame_host/render_widget_host_view_guest.cc +++ b/content/browser/frame_host/render_widget_host_view_guest.cc
@@ -622,12 +622,11 @@ blink::WebGestureEvent gesture_tap_event( blink::WebGestureEvent::kGestureTapDown, blink::WebInputEvent::kNoModifiers, - ui::EventTimeStampToSeconds(ui::EventTimeForNow())); - gesture_tap_event.source_device = blink::kWebGestureDeviceTouchscreen; - gesture_tap_event.x = position.x + offset.x(); - gesture_tap_event.y = position.y + offset.y(); - gesture_tap_event.global_x = screenPosition.x; - gesture_tap_event.global_y = screenPosition.y; + ui::EventTimeStampToSeconds(ui::EventTimeForNow()), + blink::kWebGestureDeviceTouchscreen); + gesture_tap_event.SetPositionInWidget( + blink::WebFloatPoint(position.x + offset.x(), position.y + offset.y())); + gesture_tap_event.SetPositionInScreen(screenPosition); GetOwnerRenderWidgetHostView()->ProcessGestureEvent( gesture_tap_event, ui::LatencyInfo(ui::SourceEventType::TOUCH));
diff --git a/content/browser/renderer_host/input/fling_controller.cc b/content/browser/renderer_host/input/fling_controller.cc index 6670aad6..3c6c797 100644 --- a/content/browser/renderer_host/input/fling_controller.cc +++ b/content/browser/renderer_host/input/fling_controller.cc
@@ -68,10 +68,10 @@ const GestureEventWithLatencyInfo& gesture_event) { switch (gesture_event.event.GetType()) { case WebInputEvent::kGestureFlingCancel: - if (gesture_event.event.source_device == + if (gesture_event.event.SourceDevice() == blink::kWebGestureDeviceTouchscreen) { touchscreen_tap_suppression_controller_.GestureFlingCancel(); - } else if (gesture_event.event.source_device == + } else if (gesture_event.event.SourceDevice() == blink::kWebGestureDeviceTouchpad) { touchpad_tap_suppression_controller_.GestureFlingCancel(); } @@ -85,7 +85,7 @@ case WebInputEvent::kGestureLongPress: case WebInputEvent::kGestureLongTap: case WebInputEvent::kGestureTwoFingerTap: - if (gesture_event.event.source_device == + if (gesture_event.event.SourceDevice() == blink::kWebGestureDeviceTouchscreen) { return !touchscreen_tap_suppression_controller_.FilterTapEvent( gesture_event); @@ -105,7 +105,7 @@ // touchscreen fling is implemented, move the fling_controller_ from // GestureEventQueue to RednerWidgetHostImpl. This will gaurantee proper // gesture scroll event order in RednerWidgetHostImpl while boosting. - if (gesture_event.event.source_device == blink::kWebGestureDeviceTouchpad) + if (gesture_event.event.SourceDevice() == blink::kWebGestureDeviceTouchpad) return false; bool cancel_current_fling; @@ -137,7 +137,7 @@ bool processed = (INPUT_EVENT_ACK_STATE_CONSUMED == ack_result); switch (acked_event.event.GetType()) { case WebInputEvent::kGestureFlingCancel: { - blink::WebGestureDevice source_device = acked_event.event.source_device; + blink::WebGestureDevice source_device = acked_event.event.SourceDevice(); if (source_device == blink::kWebGestureDeviceTouchscreen) { touchscreen_tap_suppression_controller_.GestureFlingCancelAck( processed); @@ -257,11 +257,9 @@ synthetic_wheel.event.has_precise_scrolling_deltas = true; synthetic_wheel.event.momentum_phase = phase; synthetic_wheel.event.has_synthetic_phase = true; - synthetic_wheel.event.SetPositionInWidget( - current_fling_parameters_.point.x(), current_fling_parameters_.point.y()); + synthetic_wheel.event.SetPositionInWidget(current_fling_parameters_.point); synthetic_wheel.event.SetPositionInScreen( - current_fling_parameters_.global_point.x(), - current_fling_parameters_.global_point.y()); + current_fling_parameters_.global_point); // Send wheel end events nonblocking since they have zero delta and are not // sent to JS. if (phase == blink::WebMouseWheelEvent::kPhaseEnded) { @@ -327,12 +325,10 @@ } current_fling_parameters_.velocity = velocity; - current_fling_parameters_.point = - gfx::Vector2d(fling_start_event.x, fling_start_event.y); - current_fling_parameters_.global_point = - gfx::Vector2d(fling_start_event.global_x, fling_start_event.global_y); + current_fling_parameters_.point = fling_start_event.PositionInWidget(); + current_fling_parameters_.global_point = fling_start_event.PositionInScreen(); current_fling_parameters_.modifiers = fling_start_event.GetModifiers(); - current_fling_parameters_.source_device = fling_start_event.source_device; + current_fling_parameters_.source_device = fling_start_event.SourceDevice(); current_fling_parameters_.start_time = base::TimeTicks() + base::TimeDelta::FromSecondsD(fling_start_event.TimeStampSeconds());
diff --git a/content/browser/renderer_host/input/fling_controller.h b/content/browser/renderer_host/input/fling_controller.h index 3fc6840c..07a176c3 100644 --- a/content/browser/renderer_host/input/fling_controller.h +++ b/content/browser/renderer_host/input/fling_controller.h
@@ -46,8 +46,8 @@ struct ActiveFlingParameters { gfx::Vector2dF velocity; - gfx::Vector2d point; - gfx::Vector2d global_point; + gfx::PointF point; + gfx::PointF global_point; int modifiers; blink::WebGestureDevice source_device; base::TimeTicks start_time;
diff --git a/content/browser/renderer_host/input/fling_controller_unittest.cc b/content/browser/renderer_host/input/fling_controller_unittest.cc index ec1f772b..2e8310ff 100644 --- a/content/browser/renderer_host/input/fling_controller_unittest.cc +++ b/content/browser/renderer_host/input/fling_controller_unittest.cc
@@ -80,8 +80,7 @@ scheduled_next_fling_progress_ = false; WebGestureEvent fling_start( WebInputEvent::kGestureFlingStart, 0, - ui::EventTimeStampToSeconds(base::TimeTicks::Now())); - fling_start.source_device = source_device; + ui::EventTimeStampToSeconds(base::TimeTicks::Now()), source_device); fling_start.data.fling_start.velocity_x = velocity.x(); fling_start.data.fling_start.velocity_y = velocity.y(); GestureEventWithLatencyInfo fling_start_with_latency(fling_start); @@ -92,8 +91,7 @@ void SimulateFlingCancel(blink::WebGestureDevice source_device) { WebGestureEvent fling_cancel( WebInputEvent::kGestureFlingCancel, 0, - ui::EventTimeStampToSeconds(base::TimeTicks::Now())); - fling_cancel.source_device = source_device; + ui::EventTimeStampToSeconds(base::TimeTicks::Now()), source_device); GestureEventWithLatencyInfo fling_cancel_with_latency(fling_cancel); last_fling_cancel_filtered_ = fling_controller_->FilterGestureEvent(fling_cancel_with_latency);
diff --git a/content/browser/renderer_host/input/gesture_event_queue.cc b/content/browser/renderer_host/input/gesture_event_queue.cc index 64ab964..cca647599 100644 --- a/content/browser/renderer_host/input/gesture_event_queue.cc +++ b/content/browser/renderer_host/input/gesture_event_queue.cc
@@ -63,7 +63,7 @@ // and generates wheel events with momentum phase which are handled in the // renderer normally. if (gesture_event.event.GetType() == WebInputEvent::kGestureFlingStart && - gesture_event.event.source_device == blink::kWebGestureDeviceTouchpad) { + gesture_event.event.SourceDevice() == blink::kWebGestureDeviceTouchpad) { fling_controller_.ProcessGestureFlingStart(gesture_event); fling_in_progress_ = true; return false; @@ -176,7 +176,7 @@ "gesture-event-queue-hang-source-device", base::debug::CrashKeySize::Size32); base::debug::ScopedCrashKeyString device_key_value( - device_key, std::to_string(event.source_device)); + device_key, std::to_string(event.SourceDevice())); static auto* size_key = base::debug::AllocateCrashKeyString( "gesture-event-queue-hang-queue-size", base::debug::CrashKeySize::Size32);
diff --git a/content/browser/renderer_host/input/gesture_event_queue_unittest.cc b/content/browser/renderer_host/input/gesture_event_queue_unittest.cc index cfa74d7..f32bdcc 100644 --- a/content/browser/renderer_host/input/gesture_event_queue_unittest.cc +++ b/content/browser/renderer_host/input/gesture_event_queue_unittest.cc
@@ -260,7 +260,7 @@ WebGestureEvent merged_event = GestureEventLastQueueEvent(); EXPECT_EQ(2U, GestureEventQueueSize()); EXPECT_EQ(WebInputEvent::kGestureScrollUpdate, merged_event.GetType()); - EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device); + EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice()); // Coalesced. SimulateGestureScrollUpdateEvent(8, -6, 0); @@ -271,7 +271,7 @@ EXPECT_EQ(0, merged_event.GetModifiers()); EXPECT_EQ(16, merged_event.data.scroll_update.delta_x); EXPECT_EQ(-11, merged_event.data.scroll_update.delta_y); - EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device); + EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice()); // Enqueued. SimulateGestureScrollUpdateEvent(8, -7, 1); @@ -280,7 +280,7 @@ merged_event = GestureEventLastQueueEvent(); EXPECT_EQ(WebInputEvent::kGestureScrollUpdate, merged_event.GetType()); EXPECT_EQ(1, merged_event.GetModifiers()); - EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device); + EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice()); // Different. SimulateGestureEvent(WebInputEvent::kGestureScrollEnd, @@ -334,33 +334,33 @@ // Make sure that the queue contains what we think it should. EXPECT_EQ(2U, GestureEventQueueSize()); EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, - GestureEventLastQueueEvent().source_device); + GestureEventLastQueueEvent().SourceDevice()); // Coalesced. SimulateGestureScrollUpdateEvent(8, -6, 0); EXPECT_EQ(2U, GestureEventQueueSize()); EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, - GestureEventLastQueueEvent().source_device); + GestureEventLastQueueEvent().SourceDevice()); // Enqueued. SimulateGestureEvent(WebInputEvent::kGestureScrollUpdate, blink::kWebGestureDeviceTouchpad); EXPECT_EQ(3U, GestureEventQueueSize()); EXPECT_EQ(blink::kWebGestureDeviceTouchpad, - GestureEventLastQueueEvent().source_device); + GestureEventLastQueueEvent().SourceDevice()); // Coalesced. SimulateGestureEvent(WebInputEvent::kGestureScrollUpdate, blink::kWebGestureDeviceTouchpad); EXPECT_EQ(3U, GestureEventQueueSize()); EXPECT_EQ(blink::kWebGestureDeviceTouchpad, - GestureEventLastQueueEvent().source_device); + GestureEventLastQueueEvent().SourceDevice()); // Enqueued. SimulateGestureScrollUpdateEvent(8, -7, 0); EXPECT_EQ(4U, GestureEventQueueSize()); EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, - GestureEventLastQueueEvent().source_device); + GestureEventLastQueueEvent().SourceDevice()); } TEST_F(GestureEventQueueTest, CoalescesScrollAndPinchEvents) { @@ -391,13 +391,13 @@ EXPECT_EQ(WebInputEvent::kGesturePinchUpdate, merged_event.GetType()); EXPECT_EQ(1.5, merged_event.data.pinch_update.scale); EXPECT_EQ(1, merged_event.GetModifiers()); - EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device); + EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice()); merged_event = GestureEventSecondFromLastQueueEvent(); EXPECT_EQ(WebInputEvent::kGestureScrollUpdate, merged_event.GetType()); EXPECT_EQ(8, merged_event.data.scroll_update.delta_x); EXPECT_EQ(-4, merged_event.data.scroll_update.delta_y); EXPECT_EQ(1, merged_event.GetModifiers()); - EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device); + EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice()); // Enqueued. SimulateGestureScrollUpdateEvent(6, -3, 1); @@ -408,13 +408,13 @@ EXPECT_EQ(WebInputEvent::kGesturePinchUpdate, merged_event.GetType()); EXPECT_EQ(1.5, merged_event.data.pinch_update.scale); EXPECT_EQ(1, merged_event.GetModifiers()); - EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device); + EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice()); merged_event = GestureEventSecondFromLastQueueEvent(); EXPECT_EQ(WebInputEvent::kGestureScrollUpdate, merged_event.GetType()); EXPECT_EQ(12, merged_event.data.scroll_update.delta_x); EXPECT_EQ(-6, merged_event.data.scroll_update.delta_y); EXPECT_EQ(1, merged_event.GetModifiers()); - EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device); + EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice()); // Enqueued. SimulateGesturePinchUpdateEvent(2, 60, 60, 1); @@ -425,13 +425,13 @@ EXPECT_EQ(WebInputEvent::kGesturePinchUpdate, merged_event.GetType()); EXPECT_EQ(3, merged_event.data.pinch_update.scale); EXPECT_EQ(1, merged_event.GetModifiers()); - EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device); + EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice()); merged_event = GestureEventSecondFromLastQueueEvent(); EXPECT_EQ(WebInputEvent::kGestureScrollUpdate, merged_event.GetType()); EXPECT_EQ(12, merged_event.data.scroll_update.delta_x); EXPECT_EQ(-6, merged_event.data.scroll_update.delta_y); EXPECT_EQ(1, merged_event.GetModifiers()); - EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device); + EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice()); // Enqueued. SimulateGesturePinchUpdateEvent(2, 60, 60, 1); @@ -442,13 +442,13 @@ EXPECT_EQ(WebInputEvent::kGesturePinchUpdate, merged_event.GetType()); EXPECT_EQ(6, merged_event.data.pinch_update.scale); EXPECT_EQ(1, merged_event.GetModifiers()); - EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device); + EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice()); merged_event = GestureEventSecondFromLastQueueEvent(); EXPECT_EQ(WebInputEvent::kGestureScrollUpdate, merged_event.GetType()); EXPECT_EQ(12, merged_event.data.scroll_update.delta_x); EXPECT_EQ(-6, merged_event.data.scroll_update.delta_y); EXPECT_EQ(1, merged_event.GetModifiers()); - EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device); + EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice()); // Check that only the first event was sent. EXPECT_EQ(1U, GetAndResetSentGestureEventCount()); @@ -468,13 +468,13 @@ EXPECT_EQ(WebInputEvent::kGesturePinchUpdate, merged_event.GetType()); EXPECT_EQ(6, merged_event.data.pinch_update.scale); EXPECT_EQ(1, merged_event.GetModifiers()); - EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device); + EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice()); merged_event = GestureEventSecondFromLastQueueEvent(); EXPECT_EQ(WebInputEvent::kGestureScrollUpdate, merged_event.GetType()); EXPECT_EQ(13, merged_event.data.scroll_update.delta_x); EXPECT_EQ(-7, merged_event.data.scroll_update.delta_y); EXPECT_EQ(1, merged_event.GetModifiers()); - EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device); + EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice()); // At this point ACKs shouldn't be getting ignored. EXPECT_FALSE(WillIgnoreNextACK()); @@ -498,12 +498,12 @@ EXPECT_EQ(1, merged_event.data.scroll_update.delta_x); EXPECT_EQ(-1, merged_event.data.scroll_update.delta_y); EXPECT_EQ(1, merged_event.GetModifiers()); - EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device); + EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice()); merged_event = GestureEventSecondFromLastQueueEvent(); EXPECT_EQ(WebInputEvent::kGesturePinchUpdate, merged_event.GetType()); EXPECT_EQ(6, merged_event.data.pinch_update.scale); EXPECT_EQ(1, merged_event.GetModifiers()); - EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device); + EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice()); // Enqueued. SimulateGestureScrollUpdateEvent(2, -2, 1); @@ -515,12 +515,12 @@ EXPECT_EQ(3, merged_event.data.scroll_update.delta_x); EXPECT_EQ(-3, merged_event.data.scroll_update.delta_y); EXPECT_EQ(1, merged_event.GetModifiers()); - EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device); + EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice()); merged_event = GestureEventSecondFromLastQueueEvent(); EXPECT_EQ(WebInputEvent::kGesturePinchUpdate, merged_event.GetType()); EXPECT_EQ(6, merged_event.data.pinch_update.scale); EXPECT_EQ(1, merged_event.GetModifiers()); - EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device); + EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice()); // Enqueued. SimulateGesturePinchUpdateEvent(0.5, 60, 60, 1); @@ -531,13 +531,13 @@ EXPECT_EQ(WebInputEvent::kGesturePinchUpdate, merged_event.GetType()); EXPECT_EQ(0.5, merged_event.data.pinch_update.scale); EXPECT_EQ(1, merged_event.GetModifiers()); - EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device); + EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice()); merged_event = GestureEventSecondFromLastQueueEvent(); EXPECT_EQ(WebInputEvent::kGestureScrollUpdate, merged_event.GetType()); EXPECT_EQ(3, merged_event.data.scroll_update.delta_x); EXPECT_EQ(-3, merged_event.data.scroll_update.delta_y); EXPECT_EQ(1, merged_event.GetModifiers()); - EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device); + EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice()); // Check that the ACK gets ignored. SendInputEventACK(WebInputEvent::kGestureScrollUpdate, @@ -558,12 +558,12 @@ EXPECT_EQ(2, merged_event.data.scroll_update.delta_x); EXPECT_EQ(-2, merged_event.data.scroll_update.delta_y); EXPECT_EQ(2, merged_event.GetModifiers()); - EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device); + EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice()); merged_event = GestureEventSecondFromLastQueueEvent(); EXPECT_EQ(WebInputEvent::kGesturePinchUpdate, merged_event.GetType()); EXPECT_EQ(0.5, merged_event.data.pinch_update.scale); EXPECT_EQ(1, merged_event.GetModifiers()); - EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.source_device); + EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, merged_event.SourceDevice()); // Check that the ACK sends the next scroll pinch pair. SendInputEventACK(WebInputEvent::kGesturePinchUpdate,
diff --git a/content/browser/renderer_host/input/input_router_impl.cc b/content/browser/renderer_host/input/input_router_impl.cc index 8db3e2a..1fd1ae0c 100644 --- a/content/browser/renderer_host/input/input_router_impl.cc +++ b/content/browser/renderer_host/input/input_router_impl.cc
@@ -139,7 +139,7 @@ wheel_event_queue_.OnGestureScrollEvent(gesture_event); - if (gesture_event.event.source_device == + if (gesture_event.event.SourceDevice() == blink::kWebGestureDeviceTouchscreen) { if (gesture_event.event.GetType() == blink::WebInputEvent::kGestureScrollBegin) {
diff --git a/content/browser/renderer_host/input/input_router_impl_unittest.cc b/content/browser/renderer_host/input/input_router_impl_unittest.cc index 7a388a0..c4b2f4ca 100644 --- a/content/browser/renderer_host/input/input_router_impl_unittest.cc +++ b/content/browser/renderer_host/input/input_router_impl_unittest.cc
@@ -327,14 +327,14 @@ void SimulateGestureEvent(WebGestureEvent gesture) { if (gesture.GetType() == WebInputEvent::kGestureScrollBegin && - gesture.source_device == blink::kWebGestureDeviceTouchscreen && + gesture.SourceDevice() == blink::kWebGestureDeviceTouchscreen && !gesture.data.scroll_begin.delta_x_hint && !gesture.data.scroll_begin.delta_y_hint) { // Ensure non-zero scroll-begin offset-hint to make the event sane, // prevents unexpected filtering at TouchActionFilter. gesture.data.scroll_begin.delta_y_hint = 2.f; } else if (gesture.GetType() == WebInputEvent::kGestureFlingStart && - gesture.source_device == blink::kWebGestureDeviceTouchscreen && + gesture.SourceDevice() == blink::kWebGestureDeviceTouchscreen && !gesture.data.fling_start.velocity_x && !gesture.data.fling_start.velocity_y) { // Ensure non-zero touchscreen fling velocities, as the router will @@ -1674,10 +1674,10 @@ ASSERT_EQ(WebInputEvent::kGesturePinchUpdate, input_event->GetType()); const WebGestureEvent* gesture_event = static_cast<const WebGestureEvent*>(input_event); - EXPECT_EQ(20, gesture_event->x); - EXPECT_EQ(25, gesture_event->y); - EXPECT_EQ(20, gesture_event->global_x); - EXPECT_EQ(25, gesture_event->global_y); + EXPECT_EQ(20, gesture_event->PositionInWidget().x); + EXPECT_EQ(25, gesture_event->PositionInWidget().y); + EXPECT_EQ(20, gesture_event->PositionInScreen().x); + EXPECT_EQ(25, gesture_event->PositionInScreen().y); dispatched_messages[0]->ToEvent()->CallCallback( INPUT_EVENT_ACK_STATE_NOT_CONSUMED); @@ -2136,17 +2136,17 @@ InputRouterImplScaleGestureEventTest() {} WebGestureEvent BuildGestureEvent(WebInputEvent::Type type, - const gfx::Point& point) { + const gfx::PointF& point) { WebGestureEvent event = SyntheticWebGestureEventBuilder::Build( type, blink::kWebGestureDeviceTouchpad); - event.global_x = event.x = point.x(); - event.global_y = event.y = point.y(); + event.SetPositionInWidget(point); + event.SetPositionInScreen(point); return event; } void TestTap(const std::string& name, WebInputEvent::Type type) { SCOPED_TRACE(name); - const gfx::Point orig(10, 20), scaled(20, 40); + const gfx::PointF orig(10, 20), scaled(20, 40); WebGestureEvent event = BuildGestureEvent(type, orig); event.data.tap.width = 30; event.data.tap.height = 40; @@ -2166,7 +2166,7 @@ } void TestLongPress(const std::string& name, WebInputEvent::Type type) { - const gfx::Point orig(10, 20), scaled(20, 40); + const gfx::PointF orig(10, 20), scaled(20, 40); WebGestureEvent event = BuildGestureEvent(type, orig); event.data.long_press.width = 30; event.data.long_press.height = 40; @@ -2193,20 +2193,20 @@ } void TestLocationInSentEvent(const WebGestureEvent* sent_event, - const gfx::Point& orig, - const gfx::Point& scaled) { - EXPECT_EQ(20, sent_event->x); - EXPECT_EQ(40, sent_event->y); - EXPECT_EQ(10, sent_event->global_x); - EXPECT_EQ(20, sent_event->global_y); + const gfx::PointF& orig, + const gfx::PointF& scaled) { + EXPECT_EQ(20, sent_event->PositionInWidget().x); + EXPECT_EQ(40, sent_event->PositionInWidget().y); + EXPECT_EQ(10, sent_event->PositionInScreen().x); + EXPECT_EQ(20, sent_event->PositionInScreen().y); } void TestLocationInFilterEvent(const WebGestureEvent* filter_event, - const gfx::Point& point) { - EXPECT_EQ(10, filter_event->x); - EXPECT_EQ(20, filter_event->y); - EXPECT_EQ(10, filter_event->global_x); - EXPECT_EQ(20, filter_event->global_y); + const gfx::PointF& point) { + EXPECT_EQ(10, filter_event->PositionInWidget().x); + EXPECT_EQ(20, filter_event->PositionInWidget().y); + EXPECT_EQ(10, filter_event->PositionInScreen().x); + EXPECT_EQ(20, filter_event->PositionInScreen().y); } private: @@ -2246,7 +2246,7 @@ } TEST_F(InputRouterImplScaleGestureEventTest, GesturePinchUpdate) { - const gfx::Point orig(10, 20), scaled(20, 40); + const gfx::PointF orig(10, 20), scaled(20, 40); SimulateGesturePinchUpdateEvent(1.5f, orig.x(), orig.y(), 0, blink::kWebGestureDeviceTouchpad); FlushGestureEvent(WebInputEvent::kGesturePinchUpdate); @@ -2261,7 +2261,7 @@ } TEST_F(InputRouterImplScaleGestureEventTest, GestureTapDown) { - const gfx::Point orig(10, 20), scaled(20, 40); + const gfx::PointF orig(10, 20), scaled(20, 40); WebGestureEvent event = BuildGestureEvent(WebInputEvent::kGestureTapDown, orig); event.data.tap_down.width = 30; @@ -2287,7 +2287,7 @@ } TEST_F(InputRouterImplScaleGestureEventTest, GestureShowPress) { - const gfx::Point orig(10, 20), scaled(20, 40); + const gfx::PointF orig(10, 20), scaled(20, 40); WebGestureEvent event = BuildGestureEvent(WebInputEvent::kGestureShowPress, orig); event.data.show_press.width = 30; @@ -2314,22 +2314,22 @@ TEST_F(InputRouterImplScaleGestureEventTest, GestureTwoFingerTap) { WebGestureEvent event = BuildGestureEvent(WebInputEvent::kGestureTwoFingerTap, - gfx::Point(10, 20)); + gfx::PointF(10, 20)); event.data.two_finger_tap.first_finger_width = 30; event.data.two_finger_tap.first_finger_height = 40; SimulateGestureEvent(event); FlushGestureEvent(WebInputEvent::kGestureTwoFingerTap); const WebGestureEvent* sent_event = GetSentWebInputEvent<WebGestureEvent>(); - EXPECT_EQ(20, sent_event->x); - EXPECT_EQ(40, sent_event->y); + EXPECT_EQ(20, sent_event->PositionInWidget().x); + EXPECT_EQ(40, sent_event->PositionInWidget().y); EXPECT_EQ(60, sent_event->data.two_finger_tap.first_finger_width); EXPECT_EQ(80, sent_event->data.two_finger_tap.first_finger_height); const WebGestureEvent* filter_event = GetFilterWebInputEvent<WebGestureEvent>(); - EXPECT_EQ(10, filter_event->x); - EXPECT_EQ(20, filter_event->y); + EXPECT_EQ(10, filter_event->PositionInWidget().x); + EXPECT_EQ(20, filter_event->PositionInWidget().y); EXPECT_EQ(30, filter_event->data.two_finger_tap.first_finger_width); EXPECT_EQ(40, filter_event->data.two_finger_tap.first_finger_height); } @@ -2346,14 +2346,14 @@ 10.f, 20.f, blink::kWebGestureDeviceTouchscreen)); FlushGestureEvent(WebInputEvent::kGestureScrollBegin); - const gfx::Point orig(10, 20), scaled(20, 40); + const gfx::PointF orig(10, 20), scaled(20, 40); WebGestureEvent event = BuildGestureEvent(WebInputEvent::kGestureFlingStart, orig); // Set the source device to touchscreen to make sure that the event gets // dispatched to the renderer. When wheel scroll latching is enabled touchpad // flings are not dispatched to the renderer, instead they are handled on the // browser side. - event.source_device = blink::kWebGestureDeviceTouchscreen; + event.SetSourceDevice(blink::kWebGestureDeviceTouchscreen); event.data.fling_start.velocity_x = 30; event.data.fling_start.velocity_y = 40; SimulateGestureEvent(event);
diff --git a/content/browser/renderer_host/input/legacy_input_router_impl.cc b/content/browser/renderer_host/input/legacy_input_router_impl.cc index d0ea15b..8237c18 100644 --- a/content/browser/renderer_host/input/legacy_input_router_impl.cc +++ b/content/browser/renderer_host/input/legacy_input_router_impl.cc
@@ -138,7 +138,7 @@ wheel_event_queue_.OnGestureScrollEvent(gesture_event); - if (gesture_event.event.source_device == + if (gesture_event.event.SourceDevice() == blink::kWebGestureDeviceTouchscreen) { if (gesture_event.event.GetType() == blink::WebInputEvent::kGestureScrollBegin) {
diff --git a/content/browser/renderer_host/input/legacy_input_router_impl_perftest.cc b/content/browser/renderer_host/input/legacy_input_router_impl_perftest.cc index 0e3e7b1..c8afe30 100644 --- a/content/browser/renderer_host/input/legacy_input_router_impl_perftest.cc +++ b/content/browser/renderer_host/input/legacy_input_router_impl_perftest.cc
@@ -140,16 +140,14 @@ WebGestureEvent gesture(WebInputEvent::kGestureScrollBegin, WebInputEvent::kNoModifiers, ui::EventTimeStampToSeconds(ui::EventTimeForNow())); - gesture.x = origin.x(); - gesture.y = origin.y(); + gesture.SetPositionInWidget(gfx::PointF(origin.x(), origin.y())); gestures.push_back(gesture); gesture.SetType(WebInputEvent::kGestureScrollUpdate); gesture.data.scroll_update.delta_x = delta.x(); gesture.data.scroll_update.delta_y = delta.y(); for (size_t i = 0; i < steps; ++i) { - gesture.x += delta.x(); - gesture.y += delta.y(); + gesture.SetPositionInWidget(gesture.PositionInWidget() + delta); gestures.push_back(gesture); }
diff --git a/content/browser/renderer_host/input/legacy_input_router_impl_unittest.cc b/content/browser/renderer_host/input/legacy_input_router_impl_unittest.cc index f9d617eb..4016d94 100644 --- a/content/browser/renderer_host/input/legacy_input_router_impl_unittest.cc +++ b/content/browser/renderer_host/input/legacy_input_router_impl_unittest.cc
@@ -253,14 +253,14 @@ void SimulateGestureEvent(WebGestureEvent gesture) { if (gesture.GetType() == WebInputEvent::kGestureScrollBegin && - gesture.source_device == blink::kWebGestureDeviceTouchscreen && + gesture.SourceDevice() == blink::kWebGestureDeviceTouchscreen && !gesture.data.scroll_begin.delta_x_hint && !gesture.data.scroll_begin.delta_y_hint) { // Ensure non-zero scroll-begin offset-hint to make the event sane, // prevents unexpected filtering at TouchActionFilter. gesture.data.scroll_begin.delta_y_hint = 2.f; } else if (gesture.GetType() == WebInputEvent::kGestureFlingStart && - gesture.source_device == blink::kWebGestureDeviceTouchscreen && + gesture.SourceDevice() == blink::kWebGestureDeviceTouchscreen && !gesture.data.fling_start.velocity_x && !gesture.data.fling_start.velocity_y) { // Ensure non-zero touchscreen fling velocities, as the router will @@ -1669,10 +1669,10 @@ ASSERT_EQ(WebInputEvent::kGesturePinchUpdate, input_event->GetType()); const WebGestureEvent* gesture_event = static_cast<const WebGestureEvent*>(input_event); - EXPECT_EQ(20, gesture_event->x); - EXPECT_EQ(25, gesture_event->y); - EXPECT_EQ(20, gesture_event->global_x); - EXPECT_EQ(25, gesture_event->global_y); + EXPECT_EQ(20, gesture_event->PositionInWidget().x); + EXPECT_EQ(25, gesture_event->PositionInWidget().y); + EXPECT_EQ(20, gesture_event->PositionInScreen().x); + EXPECT_EQ(25, gesture_event->PositionInScreen().y); EXPECT_EQ(1U, GetSentMessageCountAndResetSink()); // Indicate that the wheel event was unhandled. @@ -2094,17 +2094,17 @@ LegacyInputRouterImplScaleGestureEventTest() {} WebGestureEvent BuildGestureEvent(WebInputEvent::Type type, - const gfx::Point& point) { + const gfx::PointF& point) { WebGestureEvent event = SyntheticWebGestureEventBuilder::Build( type, blink::kWebGestureDeviceTouchpad); - event.global_x = event.x = point.x(); - event.global_y = event.y = point.y(); + event.SetPositionInWidget(point); + event.SetPositionInScreen(point); return event; } void TestTap(const std::string& name, WebInputEvent::Type type) { SCOPED_TRACE(name); - const gfx::Point orig(10, 20), scaled(20, 40); + const gfx::PointF orig(10, 20), scaled(20, 40); WebGestureEvent event = BuildGestureEvent(type, orig); event.data.tap.width = 30; event.data.tap.height = 40; @@ -2125,7 +2125,7 @@ } void TestLongPress(const std::string& name, WebInputEvent::Type type) { - const gfx::Point orig(10, 20), scaled(20, 40); + const gfx::PointF orig(10, 20), scaled(20, 40); WebGestureEvent event = BuildGestureEvent(type, orig); event.data.long_press.width = 30; event.data.long_press.height = 40; @@ -2150,20 +2150,20 @@ } void TestLocationInSentEvent(const WebGestureEvent* sent_event, - const gfx::Point& orig, - const gfx::Point& scaled) { - EXPECT_EQ(20, sent_event->x); - EXPECT_EQ(40, sent_event->y); - EXPECT_EQ(10, sent_event->global_x); - EXPECT_EQ(20, sent_event->global_y); + const gfx::PointF& orig, + const gfx::PointF& scaled) { + EXPECT_EQ(20, sent_event->PositionInWidget().x); + EXPECT_EQ(40, sent_event->PositionInWidget().y); + EXPECT_EQ(10, sent_event->PositionInScreen().x); + EXPECT_EQ(20, sent_event->PositionInScreen().y); } void TestLocationInFilterEvent(const WebGestureEvent* filter_event, - const gfx::Point& point) { - EXPECT_EQ(10, filter_event->x); - EXPECT_EQ(20, filter_event->y); - EXPECT_EQ(10, filter_event->global_x); - EXPECT_EQ(20, filter_event->global_y); + const gfx::PointF& point) { + EXPECT_EQ(10, filter_event->PositionInWidget().x); + EXPECT_EQ(20, filter_event->PositionInWidget().y); + EXPECT_EQ(10, filter_event->PositionInScreen().x); + EXPECT_EQ(20, filter_event->PositionInScreen().y); } private: @@ -2201,7 +2201,7 @@ } TEST_F(LegacyInputRouterImplScaleGestureEventTest, GesturePinchUpdate) { - const gfx::Point orig(10, 20), scaled(20, 40); + const gfx::PointF orig(10, 20), scaled(20, 40); SimulateGesturePinchUpdateEvent(1.5f, orig.x(), orig.y(), 0, blink::kWebGestureDeviceTouchpad); FlushGestureEvent(WebInputEvent::kGesturePinchUpdate); @@ -2216,7 +2216,7 @@ } TEST_F(LegacyInputRouterImplScaleGestureEventTest, GestureTapDown) { - const gfx::Point orig(10, 20), scaled(20, 40); + const gfx::PointF orig(10, 20), scaled(20, 40); WebGestureEvent event = BuildGestureEvent(WebInputEvent::kGestureTapDown, orig); event.data.tap_down.width = 30; @@ -2242,7 +2242,7 @@ } TEST_F(LegacyInputRouterImplScaleGestureEventTest, GestureShowPress) { - const gfx::Point orig(10, 20), scaled(20, 40); + const gfx::PointF orig(10, 20), scaled(20, 40); WebGestureEvent event = BuildGestureEvent(WebInputEvent::kGestureShowPress, orig); event.data.show_press.width = 30; @@ -2268,21 +2268,21 @@ TEST_F(LegacyInputRouterImplScaleGestureEventTest, GestureTwoFingerTap) { WebGestureEvent event = BuildGestureEvent(WebInputEvent::kGestureTwoFingerTap, - gfx::Point(10, 20)); + gfx::PointF(10, 20)); event.data.two_finger_tap.first_finger_width = 30; event.data.two_finger_tap.first_finger_height = 40; SimulateGestureEvent(event); const WebGestureEvent* sent_event = GetSentWebInputEvent<WebGestureEvent>(); - EXPECT_EQ(20, sent_event->x); - EXPECT_EQ(40, sent_event->y); + EXPECT_EQ(20, sent_event->PositionInWidget().x); + EXPECT_EQ(40, sent_event->PositionInWidget().y); EXPECT_EQ(60, sent_event->data.two_finger_tap.first_finger_width); EXPECT_EQ(80, sent_event->data.two_finger_tap.first_finger_height); const WebGestureEvent* filter_event = GetFilterWebInputEvent<WebGestureEvent>(); - EXPECT_EQ(10, filter_event->x); - EXPECT_EQ(20, filter_event->y); + EXPECT_EQ(10, filter_event->PositionInWidget().x); + EXPECT_EQ(20, filter_event->PositionInWidget().y); EXPECT_EQ(30, filter_event->data.two_finger_tap.first_finger_width); EXPECT_EQ(40, filter_event->data.two_finger_tap.first_finger_height); } @@ -2299,14 +2299,14 @@ 10.f, 20.f, blink::kWebGestureDeviceTouchscreen)); process_->sink().ClearMessages(); - const gfx::Point orig(10, 20), scaled(20, 40); + const gfx::PointF orig(10, 20), scaled(20, 40); WebGestureEvent event = BuildGestureEvent(WebInputEvent::kGestureFlingStart, orig); // Set the source device to touchscreen to make sure that the event gets // dispatched to the renderer. When wheel scroll latching is enabled touchpad // flings are not dispatched to the renderer, instead they are handled on the // browser side. - event.source_device = blink::kWebGestureDeviceTouchscreen; + event.SetSourceDevice(blink::kWebGestureDeviceTouchscreen); event.data.fling_start.velocity_x = 30; event.data.fling_start.velocity_y = 40; SimulateGestureEvent(event);
diff --git a/content/browser/renderer_host/input/mouse_wheel_event_queue.cc b/content/browser/renderer_host/input/mouse_wheel_event_queue.cc index 5d5bead..bfb50ca 100644 --- a/content/browser/renderer_host/input/mouse_wheel_event_queue.cc +++ b/content/browser/renderer_host/input/mouse_wheel_event_queue.cc
@@ -96,15 +96,13 @@ scrolling_device_ == blink::kWebGestureDeviceTouchpad)) { WebGestureEvent scroll_update( WebInputEvent::kGestureScrollUpdate, WebInputEvent::kNoModifiers, - event_sent_for_gesture_ack_->event.TimeStampSeconds()); + event_sent_for_gesture_ack_->event.TimeStampSeconds(), + blink::kWebGestureDeviceTouchpad); - scroll_update.x = event_sent_for_gesture_ack_->event.PositionInWidget().x; - scroll_update.y = event_sent_for_gesture_ack_->event.PositionInWidget().y; - scroll_update.global_x = - event_sent_for_gesture_ack_->event.PositionInScreen().x; - scroll_update.global_y = - event_sent_for_gesture_ack_->event.PositionInScreen().y; - scroll_update.source_device = blink::kWebGestureDeviceTouchpad; + scroll_update.SetPositionInWidget( + event_sent_for_gesture_ack_->event.PositionInWidget()); + scroll_update.SetPositionInScreen( + event_sent_for_gesture_ack_->event.PositionInScreen()); scroll_update.resending_plugin_id = -1; // Swap X & Y if Shift is down and when there is no horizontal movement. @@ -267,8 +265,8 @@ const GestureEventWithLatencyInfo& gesture_event) { if (gesture_event.event.GetType() == blink::WebInputEvent::kGestureScrollBegin) { - scrolling_device_ = gesture_event.event.source_device; - } else if (scrolling_device_ == gesture_event.event.source_device && + scrolling_device_ = gesture_event.event.SourceDevice(); + } else if (scrolling_device_ == gesture_event.event.SourceDevice() && (gesture_event.event.GetType() == blink::WebInputEvent::kGestureScrollEnd || (gesture_event.event.GetType() ==
diff --git a/content/browser/renderer_host/input/mouse_wheel_event_queue_unittest.cc b/content/browser/renderer_host/input/mouse_wheel_event_queue_unittest.cc index 9db17edb..459ac23 100644 --- a/content/browser/renderer_host/input/mouse_wheel_event_queue_unittest.cc +++ b/content/browser/renderer_host/input/mouse_wheel_event_queue_unittest.cc
@@ -38,10 +38,10 @@ #define EXPECT_GESTURE_SCROLL_BEGIN_IMPL(event) \ EXPECT_EQ(WebInputEvent::kGestureScrollBegin, event->GetType()); \ - EXPECT_EQ(kWheelScrollX, event->x); \ - EXPECT_EQ(kWheelScrollY, event->y); \ - EXPECT_EQ(kWheelScrollGlobalX, event->global_x); \ - EXPECT_EQ(kWheelScrollGlobalY, event->global_y); \ + EXPECT_EQ(kWheelScrollX, event->PositionInWidget().x); \ + EXPECT_EQ(kWheelScrollY, event->PositionInWidget().y); \ + EXPECT_EQ(kWheelScrollGlobalX, event->PositionInScreen().x); \ + EXPECT_EQ(kWheelScrollGlobalY, event->PositionInScreen().y); \ EXPECT_EQ(scroll_units, event->data.scroll_begin.delta_hint_units); #define EXPECT_GESTURE_SCROLL_BEGIN(event) \ @@ -77,10 +77,10 @@ #define EXPECT_GESTURE_SCROLL_UPDATE_IMPL(event) \ EXPECT_EQ(WebInputEvent::kGestureScrollUpdate, event->GetType()); \ EXPECT_EQ(scroll_units, event->data.scroll_update.delta_units); \ - EXPECT_EQ(kWheelScrollX, event->x); \ - EXPECT_EQ(kWheelScrollY, event->y); \ - EXPECT_EQ(kWheelScrollGlobalX, event->global_x); \ - EXPECT_EQ(kWheelScrollGlobalY, event->global_y); + EXPECT_EQ(kWheelScrollX, event->PositionInWidget().x); \ + EXPECT_EQ(kWheelScrollY, event->PositionInWidget().y); \ + EXPECT_EQ(kWheelScrollGlobalX, event->PositionInScreen().x); \ + EXPECT_EQ(kWheelScrollGlobalY, event->PositionInScreen().y); #define EXPECT_GESTURE_SCROLL_UPDATE(event) \ EXPECT_GESTURE_SCROLL_UPDATE_IMPL(event); \ @@ -100,10 +100,10 @@ #define EXPECT_GESTURE_SCROLL_END_IMPL(event) \ EXPECT_EQ(WebInputEvent::kGestureScrollEnd, event->GetType()); \ EXPECT_EQ(scroll_units, event->data.scroll_end.delta_units); \ - EXPECT_EQ(kWheelScrollX, event->x); \ - EXPECT_EQ(kWheelScrollY, event->y); \ - EXPECT_EQ(kWheelScrollGlobalX, event->global_x); \ - EXPECT_EQ(kWheelScrollGlobalY, event->global_y); + EXPECT_EQ(kWheelScrollX, event->PositionInWidget().x); \ + EXPECT_EQ(kWheelScrollY, event->PositionInWidget().y); \ + EXPECT_EQ(kWheelScrollGlobalX, event->PositionInScreen().x); \ + EXPECT_EQ(kWheelScrollGlobalY, event->PositionInScreen().y); #define EXPECT_GESTURE_SCROLL_END(event) \ EXPECT_GESTURE_SCROLL_END_IMPL(event); \ @@ -344,8 +344,8 @@ void SendGestureEvent(WebInputEvent::Type type) { WebGestureEvent event(type, WebInputEvent::kNoModifiers, - ui::EventTimeStampToSeconds(ui::EventTimeForNow())); - event.source_device = blink::kWebGestureDeviceTouchscreen; + ui::EventTimeStampToSeconds(ui::EventTimeForNow()), + blink::kWebGestureDeviceTouchscreen); queue_->OnGestureScrollEvent( GestureEventWithLatencyInfo(event, ui::LatencyInfo())); }
diff --git a/content/browser/renderer_host/input/synthetic_gesture_target_mac.mm b/content/browser/renderer_host/input/synthetic_gesture_target_mac.mm index c69d14e3..71b3c59 100644 --- a/content/browser/renderer_host/input/synthetic_gesture_target_mac.mm +++ b/content/browser/renderer_host/input/synthetic_gesture_target_mac.mm
@@ -95,8 +95,9 @@ case WebInputEvent::kGesturePinchBegin: { id cocoa_event = [SyntheticPinchEvent eventWithMagnification:0.0f - locationInWindow:NSMakePoint(gesture_event->x, - gesture_event->y) + locationInWindow:NSMakePoint( + gesture_event->PositionInWidget().x, + gesture_event->PositionInWidget().y) phase:NSEventPhaseBegan]; [cocoa_view_ handleBeginGestureWithEvent:cocoa_event]; return; @@ -104,8 +105,9 @@ case WebInputEvent::kGesturePinchEnd: { id cocoa_event = [SyntheticPinchEvent eventWithMagnification:0.0f - locationInWindow:NSMakePoint(gesture_event->x, - gesture_event->y) + locationInWindow:NSMakePoint( + gesture_event->PositionInWidget().x, + gesture_event->PositionInWidget().y) phase:NSEventPhaseEnded]; [cocoa_view_ handleEndGestureWithEvent:cocoa_event]; return; @@ -113,8 +115,9 @@ case WebInputEvent::kGesturePinchUpdate: { id cocoa_event = [SyntheticPinchEvent eventWithMagnification:gesture_event->data.pinch_update.scale - 1.0f - locationInWindow:NSMakePoint(gesture_event->x, - gesture_event->y) + locationInWindow:NSMakePoint( + gesture_event->PositionInWidget().x, + gesture_event->PositionInWidget().y) phase:NSEventPhaseChanged]; [cocoa_view_ magnifyWithEvent:cocoa_event]; return;
diff --git a/content/browser/renderer_host/input/touch_action_filter.cc b/content/browser/renderer_host/input/touch_action_filter.cc index ab9e557..0c8cec82 100644 --- a/content/browser/renderer_host/input/touch_action_filter.cc +++ b/content/browser/renderer_host/input/touch_action_filter.cc
@@ -43,7 +43,7 @@ white_listed_touch_action_(cc::kTouchActionAuto) {} bool TouchActionFilter::FilterGestureEvent(WebGestureEvent* gesture_event) { - if (gesture_event->source_device != blink::kWebGestureDeviceTouchscreen) + if (gesture_event->SourceDevice() != blink::kWebGestureDeviceTouchscreen) return false; // Filter for allowable touch actions first (eg. before the TouchEventQueue
diff --git a/content/browser/renderer_host/input/touch_emulator.cc b/content/browser/renderer_host/input/touch_emulator.cc index 1fcec1be..76d97368 100644 --- a/content/browser/renderer_host/input/touch_emulator.cc +++ b/content/browser/renderer_host/input/touch_emulator.cc
@@ -459,7 +459,7 @@ DCHECK(InPinchGestureMode()); DCHECK(!pinch_gesture_active_); pinch_gesture_active_ = true; - pinch_anchor_ = gfx::Point(event.x, event.y); + pinch_anchor_ = event.PositionInWidget(); pinch_scale_ = 1.f; WebGestureEvent pinch_event = GetPinchGestureEvent(WebInputEvent::kGesturePinchBegin, event); @@ -468,7 +468,7 @@ void TouchEmulator::PinchUpdate(const WebGestureEvent& event) { DCHECK(pinch_gesture_active_); - int dy = pinch_anchor_.y() - event.y; + float dy = pinch_anchor_.y() - event.PositionInWidget().y; float scale = exp(dy * 0.002f); WebGestureEvent pinch_event = GetPinchGestureEvent(WebInputEvent::kGesturePinchUpdate, event); @@ -486,10 +486,9 @@ } void TouchEmulator::ScrollEnd(const WebGestureEvent& event) { - WebGestureEvent scroll_event(WebInputEvent::kGestureScrollEnd, - ModifiersWithoutMouseButtons(event), - event.TimeStampSeconds()); - scroll_event.source_device = blink::kWebGestureDeviceTouchscreen; + WebGestureEvent scroll_event( + WebInputEvent::kGestureScrollEnd, ModifiersWithoutMouseButtons(event), + event.TimeStampSeconds(), blink::kWebGestureDeviceTouchscreen); client_->ForwardEmulatedGestureEvent(scroll_event); } @@ -497,10 +496,9 @@ WebInputEvent::Type type, const WebInputEvent& original_event) { WebGestureEvent event(type, ModifiersWithoutMouseButtons(original_event), - original_event.TimeStampSeconds()); - event.source_device = blink::kWebGestureDeviceTouchscreen; - event.x = pinch_anchor_.x(); - event.y = pinch_anchor_.y(); + original_event.TimeStampSeconds(), + blink::kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(pinch_anchor_); return event; }
diff --git a/content/browser/renderer_host/input/touch_emulator.h b/content/browser/renderer_host/input/touch_emulator.h index f7faf48..20a3254a 100644 --- a/content/browser/renderer_host/input/touch_emulator.h +++ b/content/browser/renderer_host/input/touch_emulator.h
@@ -150,7 +150,7 @@ bool suppress_next_fling_cancel_; // Point which does not move while pinch-zooming. - gfx::Point pinch_anchor_; + gfx::PointF pinch_anchor_; // The cumulative scale change from the start of pinch gesture. float pinch_scale_; bool pinch_gesture_active_;
diff --git a/content/browser/renderer_host/input/web_input_event_builders_android.cc b/content/browser/renderer_host/input/web_input_event_builders_android.cc index a8547dbc..349b3f3 100644 --- a/content/browser/renderer_host/input/web_input_event_builders_android.cc +++ b/content/browser/renderer_host/input/web_input_event_builders_android.cc
@@ -168,14 +168,13 @@ WebGestureEvent WebGestureEventBuilder::Build(WebInputEvent::Type type, double time_sec, - int x, - int y) { + float x, + float y) { DCHECK(WebInputEvent::IsGestureEventType(type)); - WebGestureEvent result(type, WebInputEvent::kNoModifiers, time_sec); + WebGestureEvent result(type, WebInputEvent::kNoModifiers, time_sec, + blink::kWebGestureDeviceTouchscreen); - result.x = x; - result.y = y; - result.source_device = blink::kWebGestureDeviceTouchscreen; + result.SetPositionInWidget(gfx::PointF(x, y)); return result; }
diff --git a/content/browser/renderer_host/input/web_input_event_builders_android.h b/content/browser/renderer_host/input/web_input_event_builders_android.h index ce475e3..d64b2d42 100644 --- a/content/browser/renderer_host/input/web_input_event_builders_android.h +++ b/content/browser/renderer_host/input/web_input_event_builders_android.h
@@ -49,8 +49,8 @@ public: static blink::WebGestureEvent Build(blink::WebInputEvent::Type type, double time_sec, - int x, - int y); + float x, + float y); }; } // namespace content
diff --git a/content/browser/renderer_host/input/web_input_event_builders_mac.mm b/content/browser/renderer_host/input/web_input_event_builders_mac.mm index eca937f..7484a65 100644 --- a/content/browser/renderer_host/input/web_input_event_builders_mac.mm +++ b/content/browser/renderer_host/input/web_input_event_builders_mac.mm
@@ -523,15 +523,14 @@ blink::WebMouseEvent temp; SetWebEventLocationFromEventInView(&temp, event, view); - result.x = temp.PositionInWidget().x; - result.y = temp.PositionInWidget().y; - result.global_x = temp.PositionInScreen().x; - result.global_y = temp.PositionInScreen().y; + result.SetPositionInWidget(temp.PositionInWidget()); + result.SetPositionInScreen(temp.PositionInScreen()); result.SetModifiers(ModifiersFromEvent(event)); result.SetTimeStampSeconds([event timestamp]); - result.source_device = blink::kWebGestureDeviceTouchpad; + result.SetSourceDevice(blink::kWebGestureDeviceTouchpad); + switch ([event type]) { case NSEventTypeMagnify: result.SetType(blink::WebInputEvent::kGesturePinchUpdate);
diff --git a/content/browser/renderer_host/input/web_input_event_util_unittest.cc b/content/browser/renderer_host/input/web_input_event_util_unittest.cc index 3552f36..33429778 100644 --- a/content/browser/renderer_host/input/web_input_event_util_unittest.cc +++ b/content/browser/renderer_host/input/web_input_event_util_unittest.cc
@@ -109,11 +109,11 @@ EXPECT_EQ(0, web_event.GetModifiers()); EXPECT_EQ((timestamp - base::TimeTicks()).InSecondsF(), web_event.TimeStampSeconds()); - EXPECT_EQ(gfx::ToFlooredInt(pos.x()), web_event.x); - EXPECT_EQ(gfx::ToFlooredInt(pos.y()), web_event.y); - EXPECT_EQ(gfx::ToFlooredInt(raw_pos.x()), web_event.global_x); - EXPECT_EQ(gfx::ToFlooredInt(raw_pos.y()), web_event.global_y); - EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, web_event.source_device); + EXPECT_EQ(pos.x(), web_event.PositionInWidget().x); + EXPECT_EQ(pos.y(), web_event.PositionInWidget().y); + EXPECT_EQ(raw_pos.x(), web_event.PositionInScreen().x); + EXPECT_EQ(raw_pos.y(), web_event.PositionInScreen().y); + EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, web_event.SourceDevice()); EXPECT_EQ(delta.x(), web_event.data.scroll_update.delta_x); EXPECT_EQ(delta.y(), web_event.data.scroll_update.delta_y); EXPECT_TRUE(
diff --git a/content/browser/renderer_host/input/wheel_scroll_latching_browsertest.cc b/content/browser/renderer_host/input/wheel_scroll_latching_browsertest.cc index fbd77cb..97b99a3 100644 --- a/content/browser/renderer_host/input/wheel_scroll_latching_browsertest.cc +++ b/content/browser/renderer_host/input/wheel_scroll_latching_browsertest.cc
@@ -378,17 +378,15 @@ blink::WebGestureEvent gesture_scroll_begin( blink::WebGestureEvent::kGestureScrollBegin, blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::GetStaticTimeStampForTests()); - gesture_scroll_begin.source_device = blink::kWebGestureDeviceTouchpad; + blink::WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchpad); gesture_scroll_begin.data.scroll_begin.delta_hint_units = precise ? blink::WebGestureEvent::ScrollUnits::kPrecisePixels : blink::WebGestureEvent::ScrollUnits::kPixels; gesture_scroll_begin.data.scroll_begin.delta_x_hint = 0.f; gesture_scroll_begin.data.scroll_begin.delta_y_hint = -20.f; - gesture_scroll_begin.x = x; - gesture_scroll_begin.y = y; - gesture_scroll_begin.global_x = x; - gesture_scroll_begin.global_y = y; + gesture_scroll_begin.SetPositionInWidget(gfx::PointF(x, y)); + gesture_scroll_begin.SetPositionInScreen(gfx::PointF(x, y)); GetRootView()->ProcessGestureEvent(gesture_scroll_begin, ui::LatencyInfo()); // Send the first GSU event.
diff --git a/content/browser/renderer_host/overscroll_controller.cc b/content/browser/renderer_host/overscroll_controller.cc index 18c0698..3f51a8a 100644 --- a/content/browser/renderer_host/overscroll_controller.cc +++ b/content/browser/renderer_host/overscroll_controller.cc
@@ -26,7 +26,7 @@ DCHECK(blink::WebInputEvent::IsGestureEventType(event.GetType())); const blink::WebGestureEvent& gesture = static_cast<const blink::WebGestureEvent&>(event); - return gesture.source_device == blink::kWebGestureDeviceTouchpad; + return gesture.SourceDevice() == blink::kWebGestureDeviceTouchpad; } float ClampAbsoluteValue(float value, float max_abs) { @@ -335,7 +335,7 @@ event_processed = ProcessOverscroll( gesture.data.scroll_update.delta_x, gesture.data.scroll_update.delta_y, - gesture.source_device == blink::kWebGestureDeviceTouchpad); + gesture.SourceDevice() == blink::kWebGestureDeviceTouchpad); break; } case blink::WebInputEvent::kGestureFlingStart: {
diff --git a/content/browser/renderer_host/render_widget_host_impl.cc b/content/browser/renderer_host/render_widget_host_impl.cc index e5038f8..2f4acaa 100644 --- a/content/browser/renderer_host/render_widget_host_impl.cc +++ b/content/browser/renderer_host/render_widget_host_impl.cc
@@ -189,8 +189,7 @@ blink::WebGestureEvent wrap_gesture_scroll_begin( blink::WebInputEvent::kGestureScrollBegin, gesture_event.GetModifiers(), - gesture_event.TimeStampSeconds()); - wrap_gesture_scroll_begin.source_device = gesture_event.source_device; + gesture_event.TimeStampSeconds(), gesture_event.SourceDevice()); wrap_gesture_scroll_begin.data.scroll_begin.delta_x_hint = 0; wrap_gesture_scroll_begin.data.scroll_begin.delta_y_hint = 0; wrap_gesture_scroll_begin.resending_plugin_id = @@ -207,8 +206,7 @@ blink::WebGestureEvent wrap_gesture_scroll_end( blink::WebInputEvent::kGestureScrollEnd, gesture_event.GetModifiers(), - gesture_event.TimeStampSeconds()); - wrap_gesture_scroll_end.source_device = gesture_event.source_device; + gesture_event.TimeStampSeconds(), gesture_event.SourceDevice()); wrap_gesture_scroll_end.resending_plugin_id = gesture_event.resending_plugin_id; wrap_gesture_scroll_end.data.scroll_end.delta_units = @@ -1186,16 +1184,16 @@ bool scroll_update_needs_wrapping = false; if (gesture_event.GetType() == blink::WebInputEvent::kGestureScrollBegin) { - DCHECK(!is_in_gesture_scroll_[gesture_event.source_device]); - is_in_gesture_scroll_[gesture_event.source_device] = true; + DCHECK(!is_in_gesture_scroll_[gesture_event.SourceDevice()]); + is_in_gesture_scroll_[gesture_event.SourceDevice()] = true; } else if (gesture_event.GetType() == blink::WebInputEvent::kGestureScrollEnd) { - DCHECK(is_in_gesture_scroll_[gesture_event.source_device]); - is_in_gesture_scroll_[gesture_event.source_device] = false; + DCHECK(is_in_gesture_scroll_[gesture_event.SourceDevice()]); + is_in_gesture_scroll_[gesture_event.SourceDevice()] = false; is_in_touchpad_gesture_fling_ = false; } else if (gesture_event.GetType() == blink::WebInputEvent::kGestureFlingStart) { - if (gesture_event.source_device == + if (gesture_event.SourceDevice() == blink::WebGestureDevice::kWebGestureDeviceTouchpad) { // TODO(sahel): Remove the VR specific case when motion events are used // for Android VR event processing and VR touchpad scrolling is handled by @@ -1204,18 +1202,18 @@ if (GetView()->IsInVR()) { // Regardless of the state of the wheel scroll latching // WebContentsEventForwarder doesn't inject any GSE events before GFS. - DCHECK(is_in_gesture_scroll_[gesture_event.source_device]); + DCHECK(is_in_gesture_scroll_[gesture_event.SourceDevice()]); // Reset the is_in_gesture_scroll since while scrolling in Android VR // the first wheel event sent by the FlingController will cause a GSB // generation in MouseWheelEventQueue. This is because GSU events before // the GFS are directly injected to RWHI rather than being generated // from wheel events in MouseWheelEventQueue. - is_in_gesture_scroll_[gesture_event.source_device] = false; + is_in_gesture_scroll_[gesture_event.SourceDevice()] = false; } else if (GetView()->wheel_scroll_latching_enabled()) { // When wheel scroll latching is enabled, no GSE is sent before GFS, so // is_in_gesture_scroll must be true. - DCHECK(is_in_gesture_scroll_[gesture_event.source_device]); + DCHECK(is_in_gesture_scroll_[gesture_event.SourceDevice()]); // The FlingController handles GFS with touchpad source and sends wheel // events to progress the fling, the wheel events will get processed by @@ -1230,14 +1228,14 @@ // When wheel scroll latching is disabled a GSE is sent before a GFS. // The GSE has already finished the scroll sequence. - DCHECK(!is_in_gesture_scroll_[gesture_event.source_device]); + DCHECK(!is_in_gesture_scroll_[gesture_event.SourceDevice()]); } is_in_touchpad_gesture_fling_ = true; - } else { // gesture_event.source_device != + } else { // gesture_event.SourceDevice() != // blink::WebGestureDevice::kWebGestureDeviceTouchpad - DCHECK(is_in_gesture_scroll_[gesture_event.source_device]); - is_in_gesture_scroll_[gesture_event.source_device] = false; + DCHECK(is_in_gesture_scroll_[gesture_event.SourceDevice()]); + is_in_gesture_scroll_[gesture_event.SourceDevice()] = false; } } @@ -1247,7 +1245,7 @@ scroll_update_needs_wrapping = gesture_event.GetType() == blink::WebInputEvent::kGestureScrollUpdate && gesture_event.resending_plugin_id != -1 && - !is_in_gesture_scroll_[gesture_event.source_device]; + !is_in_gesture_scroll_[gesture_event.SourceDevice()]; // TODO(crbug.com/544782): Fix WebViewGuestScrollTest.TestGuestWheelScrolls- // Bubble to test the resending logic of gesture events. @@ -2125,10 +2123,7 @@ WebGestureEvent scroll_begin = SyntheticWebGestureEventBuilder::Build( WebInputEvent::kGestureScrollBegin, blink::kWebGestureDeviceSyntheticAutoscroll); - - scroll_begin.x = position.x(); - scroll_begin.y = position.y(); - scroll_begin.source_device = blink::kWebGestureDeviceSyntheticAutoscroll; + scroll_begin.SetPositionInWidget(position); input_router_->SendGestureEvent(GestureEventWithLatencyInfo(scroll_begin)); } @@ -2139,7 +2134,6 @@ blink::kWebGestureDeviceSyntheticAutoscroll); event.data.fling_start.velocity_x = velocity.x(); event.data.fling_start.velocity_y = velocity.y(); - event.source_device = blink::kWebGestureDeviceSyntheticAutoscroll; input_router_->SendGestureEvent(GestureEventWithLatencyInfo(event)); }
diff --git a/content/browser/renderer_host/render_widget_host_input_event_router.cc b/content/browser/renderer_host/render_widget_host_input_event_router.cc index f4d27d41..ae6478c 100644 --- a/content/browser/renderer_host/render_widget_host_input_event_router.cc +++ b/content/browser/renderer_host/render_widget_host_input_event_router.cc
@@ -409,7 +409,7 @@ // processed. blink::WebGestureEvent fake_scroll_update = DummyGestureScrollUpdate(mouse_wheel_event.TimeStampSeconds()); - fake_scroll_update.source_device = blink::kWebGestureDeviceTouchpad; + fake_scroll_update.SetSourceDevice(blink::kWebGestureDeviceTouchpad); SendGestureScrollEnd(bubbling_gesture_scroll_target_.target, fake_scroll_update); bubbling_gesture_scroll_target_.target = nullptr; @@ -452,7 +452,7 @@ return; } - switch (event->source_device) { + switch (event->SourceDevice()) { case blink::kWebGestureDeviceUninitialized: case blink::kWebGestureDeviceCount: NOTREACHED() << "Uninitialized device type is not allowed"; @@ -739,7 +739,7 @@ static auto* device_key = base::debug::AllocateCrashKeyString( "same-view-bubble-source-device", base::debug::CrashKeySize::Size32); base::debug::ScopedCrashKeyString device_key_value( - device_key, std::to_string(event.source_device)); + device_key, std::to_string(event.SourceDevice())); base::debug::DumpWithoutCrashing(); } @@ -1019,9 +1019,8 @@ // these we hit-test explicitly. if (gesture_event.unique_touch_event_id == 0) { gfx::PointF transformed_point; - gfx::PointF original_point(gesture_event.x, gesture_event.y); - gfx::PointF original_point_in_screen(gesture_event.global_x, - gesture_event.global_y); + gfx::PointF original_point(gesture_event.PositionInWidget()); + gfx::PointF original_point_in_screen(gesture_event.PositionInScreen()); return FindViewAtLocation(root_view, original_point, original_point_in_screen, viz::EventSource::TOUCH, &transformed_point); @@ -1097,7 +1096,7 @@ touchscreen_gesture_target_.target = target; DCHECK(target_location.has_value()); touchscreen_gesture_target_.delta = - target_location.value() - gfx::PointF(gesture_event.x, gesture_event.y); + target_location.value() - gesture_event.PositionInWidget(); } else if (no_matching_id && is_gesture_start) { // A long-standing Windows issues where occasionally a GestureStart is // encountered with no targets in the event queue. We never had a repro for @@ -1110,9 +1109,8 @@ LOG(ERROR) << "Gesture sequence start detected with no target available."; // It is still safe to continue; we will recalculate the target. gfx::PointF transformed_point; - gfx::PointF original_point(gesture_event.x, gesture_event.y); - gfx::PointF original_point_in_screen(gesture_event.global_x, - gesture_event.global_y); + gfx::PointF original_point(gesture_event.PositionInWidget()); + gfx::PointF original_point_in_screen(gesture_event.PositionInScreen()); auto result = FindViewAtLocation(root_view, original_point, original_point_in_screen, viz::EventSource::TOUCH, &transformed_point); @@ -1142,10 +1140,9 @@ return; } - // TODO(wjmaclean): Add SetPositionInWidget() to WebGestureEvent. blink::WebGestureEvent event(gesture_event); - event.x += touchscreen_gesture_target_.delta.x(); - event.y += touchscreen_gesture_target_.delta.y(); + event.SetPositionInWidget(event.PositionInWidget() + + touchscreen_gesture_target_.delta); touchscreen_gesture_target_.target->ProcessGestureEvent(event, latency); } @@ -1153,7 +1150,7 @@ RenderWidgetHostViewBase* root_view, blink::WebGestureEvent* event, const ui::LatencyInfo& latency) { - DCHECK_EQ(blink::kWebGestureDeviceTouchscreen, event->source_device); + DCHECK_EQ(blink::kWebGestureDeviceTouchscreen, event->SourceDevice()); event_targeter_->FindTargetAndDispatch(root_view, *event, latency); } @@ -1176,7 +1173,7 @@ RenderWidgetHostViewBase* root_view, blink::WebGestureEvent* event, const ui::LatencyInfo& latency) { - DCHECK_EQ(blink::kWebGestureDeviceTouchpad, event->source_device); + DCHECK_EQ(blink::kWebGestureDeviceTouchpad, event->SourceDevice()); event_targeter_->FindTargetAndDispatch(root_view, *event, latency); } @@ -1216,8 +1213,8 @@ blink::WebGestureEvent gesture_event = touchpad_gesture_event; // TODO(mohsen): Add tests to check event location. - gesture_event.x += touchpad_gesture_target_.delta.x(); - gesture_event.y += touchpad_gesture_target_.delta.y(); + gesture_event.SetPositionInWidget(gesture_event.PositionInWidget() + + touchpad_gesture_target_.delta); touchpad_gesture_target_.target->ProcessGestureEvent(gesture_event, latency); } @@ -1300,11 +1297,11 @@ } if (blink::WebInputEvent::IsGestureEventType(event.GetType())) { auto gesture_event = static_cast<const blink::WebGestureEvent&>(event); - if (gesture_event.source_device == + if (gesture_event.SourceDevice() == blink::WebGestureDevice::kWebGestureDeviceTouchscreen) { return FindTouchscreenGestureEventTarget(root_view, gesture_event); } - if (gesture_event.source_device == + if (gesture_event.SourceDevice() == blink::WebGestureDevice::kWebGestureDeviceTouchpad) { return FindTouchpadGestureEventTarget(root_view, gesture_event); } @@ -1339,13 +1336,13 @@ } if (blink::WebInputEvent::IsGestureEventType(event.GetType())) { auto gesture_event = static_cast<const blink::WebGestureEvent&>(event); - if (gesture_event.source_device == + if (gesture_event.SourceDevice() == blink::WebGestureDevice::kWebGestureDeviceTouchscreen) { DispatchTouchscreenGestureEvent(root_view, target, gesture_event, latency, target_location); return; } - if (gesture_event.source_device == + if (gesture_event.SourceDevice() == blink::WebGestureDevice::kWebGestureDeviceTouchpad) { DispatchTouchpadGestureEvent(root_view, target, gesture_event, latency, target_location);
diff --git a/content/browser/renderer_host/render_widget_host_input_event_router_unittest.cc b/content/browser/renderer_host/render_widget_host_input_event_router_unittest.cc index dae4aed1..25fc3f8b 100644 --- a/content/browser/renderer_host/render_widget_host_input_event_router_unittest.cc +++ b/content/browser/renderer_host/render_widget_host_input_event_router_unittest.cc
@@ -198,8 +198,8 @@ blink::WebGestureEvent gesture_event( blink::WebInputEvent::kGestureTapDown, blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::GetStaticTimeStampForTests()); - gesture_event.source_device = blink::kWebGestureDeviceTouchscreen; + blink::WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchscreen); gesture_event.unique_touch_event_id = touch_event.unique_touch_event_id; rwhier_.RouteGestureEvent(view_root_.get(), &gesture_event, @@ -389,8 +389,8 @@ blink::WebGestureEvent gesture_event( blink::WebInputEvent::kGestureTapDown, blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::GetStaticTimeStampForTests()); - gesture_event.source_device = blink::kWebGestureDeviceTouchscreen; + blink::WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchscreen); gesture_event.unique_touch_event_id = touch_event.unique_touch_event_id; rwhier_.RouteGestureEvent(view_root_.get(), &gesture_event, ui::LatencyInfo(ui::SourceEventType::TOUCH));
diff --git a/content/browser/renderer_host/render_widget_host_ns_view_bridge.h b/content/browser/renderer_host/render_widget_host_ns_view_bridge.h new file mode 100644 index 0000000..db28e88 --- /dev/null +++ b/content/browser/renderer_host/render_widget_host_ns_view_bridge.h
@@ -0,0 +1,40 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_NS_VIEW_BRIDGE_H_ +#define CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_NS_VIEW_BRIDGE_H_ + +@class RenderWidgetHostViewCocoa; + +#include <memory> + +#include "base/macros.h" + +namespace content { + +class RenderWidgetHostNSViewClient; + +// The interface through which RenderWidgetHostViewMac is to manipulate its +// corresponding NSView (potentially in another process). +class RenderWidgetHostNSViewBridge { + public: + RenderWidgetHostNSViewBridge() {} + virtual ~RenderWidgetHostNSViewBridge() {} + + static std::unique_ptr<RenderWidgetHostNSViewBridge> Create( + std::unique_ptr<RenderWidgetHostNSViewClient> client); + + // TODO(ccameron): RenderWidgetHostViewMac and other functions currently use + // this method to communicate directly with RenderWidgetHostViewCocoa. The + // goal of this class is to eliminate this direct communication (so this + // method is expected to go away). + virtual RenderWidgetHostViewCocoa* GetRenderWidgetHostViewCocoa() = 0; + + private: + DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostNSViewBridge); +}; + +} // namespace content + +#endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_NS_VIEW_BRIDGE_H_
diff --git a/content/browser/renderer_host/render_widget_host_ns_view_bridge.mm b/content/browser/renderer_host/render_widget_host_ns_view_bridge.mm new file mode 100644 index 0000000..3ca81c2 --- /dev/null +++ b/content/browser/renderer_host/render_widget_host_ns_view_bridge.mm
@@ -0,0 +1,51 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "content/browser/renderer_host/render_widget_host_ns_view_bridge.h" + +#import "content/browser/renderer_host/render_widget_host_view_cocoa.h" +#include "content/browser/renderer_host/render_widget_host_view_mac.h" + +namespace content { + +namespace { + +// Bridge to a locally-hosted NSView -- this is always instantiated in the same +// process as the NSView. The caller of this interface may exist in another +// process. +class RenderWidgetHostViewNSViewBridgeLocal + : public RenderWidgetHostNSViewBridge { + public: + explicit RenderWidgetHostViewNSViewBridgeLocal( + std::unique_ptr<RenderWidgetHostNSViewClient> client) { + // Since we autorelease |cocoa_view|, our caller must put |GetNativeView()| + // into the view hierarchy right after calling us. + cocoa_view_ = [[[RenderWidgetHostViewCocoa alloc] + initWithClient:std::move(client)] autorelease]; + } + ~RenderWidgetHostViewNSViewBridgeLocal() override {} + + RenderWidgetHostViewCocoa* GetRenderWidgetHostViewCocoa() override { + return cocoa_view_; + } + + private: + // Weak, this is owned by |cocoa_view_|'s |client_|, and |cocoa_view_| owns + // its |client_|. + RenderWidgetHostViewCocoa* cocoa_view_ = nil; + + DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostViewNSViewBridgeLocal); +}; + +} // namespace + +// static +std::unique_ptr<RenderWidgetHostNSViewBridge> +RenderWidgetHostNSViewBridge::Create( + std::unique_ptr<RenderWidgetHostNSViewClient> client) { + return std::make_unique<RenderWidgetHostViewNSViewBridgeLocal>( + std::move(client)); +} + +} // namespace content
diff --git a/content/browser/renderer_host/render_widget_host_ns_view_client.h b/content/browser/renderer_host/render_widget_host_ns_view_client.h new file mode 100644 index 0000000..525cf56 --- /dev/null +++ b/content/browser/renderer_host/render_widget_host_ns_view_client.h
@@ -0,0 +1,32 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_NS_VIEW_CLIENT_H_ +#define CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_NS_VIEW_CLIENT_H_ + +#include "base/macros.h" + +namespace content { + +class RenderWidgetHostViewMac; + +// The interface through which the NSView for a RenderWidgetHostViewMac is to +// communicate with the RenderWidgetHostViewMac (potentially in another +// process). +class RenderWidgetHostNSViewClient { + public: + RenderWidgetHostNSViewClient() {} + virtual ~RenderWidgetHostNSViewClient() {} + + // TODO(ccameron): As with the GetRenderWidgetHostViewCocoa method on + // RenderWidgetHostNSViewBridge, this method is to be removed. + virtual RenderWidgetHostViewMac* GetRenderWidgetHostViewMac() = 0; + + private: + DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostNSViewClient); +}; + +} // namespace content + +#endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_NS_VIEW_CLIENT_H_
diff --git a/content/browser/renderer_host/render_widget_host_view_android.cc b/content/browser/renderer_host/render_widget_host_view_android.cc index 5c53c26..b616b83 100644 --- a/content/browser/renderer_host/render_widget_host_view_android.cc +++ b/content/browser/renderer_host/render_widget_host_view_android.cc
@@ -1672,19 +1672,19 @@ // We let the touch selection controller see gesture events here, since they // may be routed and not make it to FilterInputEvent(). if (touch_selection_controller_ && - event.source_device == + event.SourceDevice() == blink::WebGestureDevice::kWebGestureDeviceTouchscreen) { switch (event.GetType()) { case blink::WebInputEvent::kGestureLongPress: touch_selection_controller_->HandleLongPressEvent( base::TimeTicks() + base::TimeDelta::FromSecondsD(event.TimeStampSeconds()), - gfx::PointF(event.x, event.y)); + event.PositionInWidget()); break; case blink::WebInputEvent::kGestureTap: - touch_selection_controller_->HandleTapEvent( - gfx::PointF(event.x, event.y), event.data.tap.tap_count); + touch_selection_controller_->HandleTapEvent(event.PositionInWidget(), + event.data.tap.tap_count); break; case blink::WebInputEvent::kGestureScrollBegin: @@ -1699,7 +1699,7 @@ ui::LatencyInfo latency_info = ui::WebInputEventTraits::CreateLatencyInfoForWebGestureEvent(event); if (wheel_scroll_latching_enabled()) { - if (event.source_device == + if (event.SourceDevice() == blink::WebGestureDevice::kWebGestureDeviceTouchscreen) { if (event.GetType() == blink::WebInputEvent::kGestureScrollBegin) { // If there is a current scroll going on and a new scroll that isn't @@ -1714,7 +1714,7 @@ } } else if (event.GetType() == blink::WebInputEvent::kGestureFlingStart && - event.source_device == + event.SourceDevice() == blink::WebGestureDevice::kWebGestureDeviceTouchpad) { // Ignore the pending wheel end event to avoid sending a wheel event with // kPhaseEnded before a GFS.
diff --git a/content/browser/renderer_host/render_widget_host_view_aura.cc b/content/browser/renderer_host/render_widget_host_view_aura.cc index b7a19301..1c7bcaef 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura.cc +++ b/content/browser/renderer_host/render_widget_host_view_aura.cc
@@ -1065,7 +1065,7 @@ static_cast<const WebGestureEvent&>(input_event); // Zero-velocity touchpad flings are an Aura-specific signal that the // touchpad scroll has ended, and should not be forwarded to the renderer. - if (gesture_event.source_device == blink::kWebGestureDeviceTouchpad && + if (gesture_event.SourceDevice() == blink::kWebGestureDeviceTouchpad && !gesture_event.data.fling_start.velocity_x && !gesture_event.data.fling_start.velocity_y) { consumed = true;
diff --git a/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc b/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc index a916856..39163b9 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc +++ b/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc
@@ -2056,12 +2056,12 @@ gesture_event = static_cast<const WebGestureEvent*>( events[1]->ToEvent()->Event()->web_event.get()); EXPECT_EQ(WebInputEvent::kGestureScrollEnd, gesture_event->GetType()); - EXPECT_EQ(blink::kWebGestureDeviceTouchpad, gesture_event->source_device); + EXPECT_EQ(blink::kWebGestureDeviceTouchpad, gesture_event->SourceDevice()); gesture_event = static_cast<const WebGestureEvent*>( events[2]->ToEvent()->Event()->web_event.get()); EXPECT_EQ(WebInputEvent::kGestureScrollBegin, gesture_event->GetType()); - EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, gesture_event->source_device); + EXPECT_EQ(blink::kWebGestureDeviceTouchscreen, gesture_event->SourceDevice()); } TEST_F(RenderWidgetHostViewAuraWheelScrollLatchingEnabledTest,
diff --git a/content/browser/renderer_host/render_widget_host_view_child_frame.cc b/content/browser/renderer_host/render_widget_host_view_child_frame.cc index 8f029c47..1ce4764 100644 --- a/content/browser/renderer_host/render_widget_host_view_child_frame.cc +++ b/content/browser/renderer_host/render_widget_host_view_child_frame.cc
@@ -921,7 +921,7 @@ static_cast<const blink::WebGestureEvent&>(input_event); // Zero-velocity touchpad flings are an Aura-specific signal that the // touchpad scroll has ended, and should not be forwarded to the renderer. - if (gesture_event.source_device == blink::kWebGestureDeviceTouchpad && + if (gesture_event.SourceDevice() == blink::kWebGestureDeviceTouchpad && !gesture_event.data.fling_start.velocity_x && !gesture_event.data.fling_start.velocity_y) { // Here we indicate that there was no consumer for this event, as
diff --git a/content/browser/renderer_host/render_widget_host_view_cocoa.h b/content/browser/renderer_host/render_widget_host_view_cocoa.h index a9197c7..84ef1dc 100644 --- a/content/browser/renderer_host/render_widget_host_view_cocoa.h +++ b/content/browser/renderer_host/render_widget_host_view_cocoa.h
@@ -23,6 +23,7 @@ } namespace content { +class RenderWidgetHostNSViewClient; class RenderWidgetHostViewMac; class RenderWidgetHostViewMacEditCommandHelper; } @@ -41,12 +42,19 @@ // RenderWidgetHostViewWin is both the view and the delegate. We split the roles // but that means that the view needs to own the delegate and will dispose of it // when it's removed from the view system. +// TODO(ccameron): Hide this interface behind RenderWidgetHostNSViewBridge. @interface RenderWidgetHostViewCocoa : ToolTipBaseView<CommandDispatcherTarget, RenderWidgetHostViewMacOwner, NSTextInputClient> { @private - std::unique_ptr<content::RenderWidgetHostViewMac> renderWidgetHostView_; + // The communications channel to the RenderWidgetHostViewMac. + std::unique_ptr<content::RenderWidgetHostNSViewClient> client_; + + // TODO(ccameron): Make all communication with the RenderWidgetHostView go + // through |client_| and delete this member variable. + content::RenderWidgetHostViewMac* renderWidgetHostView_; + // This ivar is the cocoa delegate of the NSResponder. base::scoped_nsobject<NSObject<RenderWidgetHostViewMacDelegate>> responderDelegate_; @@ -207,7 +215,8 @@ targetView:(NSView*)targetView; // Methods previously marked as private. -- (id)initWithRenderWidgetHostViewMac:(content::RenderWidgetHostViewMac*)r; +- (id)initWithClient: + (std::unique_ptr<content::RenderWidgetHostNSViewClient>)client; - (void)setResponderDelegate: (NSObject<RenderWidgetHostViewMacDelegate>*)delegate; - (void)processedGestureScrollEvent:(const blink::WebGestureEvent&)event
diff --git a/content/browser/renderer_host/render_widget_host_view_cocoa.mm b/content/browser/renderer_host/render_widget_host_view_cocoa.mm index e523c3cf..1fdb587 100644 --- a/content/browser/renderer_host/render_widget_host_view_cocoa.mm +++ b/content/browser/renderer_host/render_widget_host_view_cocoa.mm
@@ -40,6 +40,7 @@ using content::NativeWebKeyboardEvent; using content::RenderViewHost; using content::RenderWidgetHostImpl; +using content::RenderWidgetHostNSViewClient; using content::RenderWidgetHostView; using content::RenderWidgetHostViewMac; using content::RenderWidgetHostViewMacEditCommandHelper; @@ -152,14 +153,15 @@ @synthesize suppressNextEscapeKeyUp = suppressNextEscapeKeyUp_; @synthesize markedRange = markedRange_; -- (id)initWithRenderWidgetHostViewMac:(RenderWidgetHostViewMac*)r { +- (id)initWithClient:(std::unique_ptr<RenderWidgetHostNSViewClient>)client { self = [super initWithFrame:NSZeroRect]; if (self) { self.acceptsTouchEvents = YES; editCommand_helper_.reset(new RenderWidgetHostViewMacEditCommandHelper); editCommand_helper_->AddEditingSelectorsToClass([self class]); - renderWidgetHostView_.reset(r); + client_ = std::move(client); + renderWidgetHostView_ = client_->GetRenderWidgetHostViewMac(); canBeKeyView_ = YES; pinchHasReachedZoomThreshold_ = false; isStylusEnteringProximity_ = false; @@ -356,8 +358,7 @@ renderWidgetHostView_->host() ->delegate() ->GetInputEventRouter() - ->RouteMouseEvent(renderWidgetHostView_.get(), &enterEvent, - latency_info); + ->RouteMouseEvent(renderWidgetHostView_, &enterEvent, latency_info); } else { renderWidgetHostView_->ProcessMouseEvent(enterEvent, latency_info); } @@ -397,7 +398,7 @@ renderWidgetHostView_->host() ->delegate() ->GetInputEventRouter() - ->RouteMouseEvent(renderWidgetHostView_.get(), &event, latency_info); + ->RouteMouseEvent(renderWidgetHostView_, &event, latency_info); } else { renderWidgetHostView_->ProcessMouseEvent(event, latency_info); } @@ -798,8 +799,8 @@ if (gestureBeginPinchSent_) { WebGestureEvent endEvent(WebGestureEventBuilder::Build(event, self)); endEvent.SetType(WebInputEvent::kGesturePinchEnd); - endEvent.source_device = - blink::WebGestureDevice::kWebGestureDeviceTouchpad; + endEvent.SetSourceDevice( + blink::WebGestureDevice::kWebGestureDeviceTouchpad); renderWidgetHostView_->SendGesturePinchEvent(&endEvent); gestureBeginPinchSent_ = NO; } @@ -936,7 +937,7 @@ renderWidgetHostView_->host() ->delegate() ->GetInputEventRouter() - ->GetRenderWidgetHostAtPoint(renderWidgetHostView_.get(), rootPoint, + ->GetRenderWidgetHostAtPoint(renderWidgetHostView_, rootPoint, &transformedPoint); if (!widgetHost) return; @@ -1058,7 +1059,7 @@ renderWidgetHostView_->host() ->delegate() ->GetInputEventRouter() - ->RouteMouseWheelEvent(renderWidgetHostView_.get(), &webEvent, + ->RouteMouseWheelEvent(renderWidgetHostView_, &webEvent, latency_info); } else { renderWidgetHostView_->ProcessMouseWheelEvent(webEvent, latency_info); @@ -1120,8 +1121,8 @@ } WebGestureEvent beginEvent(*gestureBeginEvent_); beginEvent.SetType(WebInputEvent::kGesturePinchBegin); - beginEvent.source_device = - blink::WebGestureDevice::kWebGestureDeviceTouchpad; + beginEvent.SetSourceDevice( + blink::WebGestureDevice::kWebGestureDeviceTouchpad); renderWidgetHostView_->SendGesturePinchEvent(&beginEvent); gestureBeginPinchSent_ = YES; } @@ -1340,7 +1341,7 @@ } - (RenderWidgetHostViewMac*)renderWidgetHostViewMac { - return renderWidgetHostView_.get(); + return renderWidgetHostView_; } // Determine whether we should autohide the cursor (i.e., hide it until mouse @@ -1537,7 +1538,7 @@ renderWidgetHostView_->host() ->delegate() ->GetInputEventRouter() - ->GetRenderWidgetHostAtPoint(renderWidgetHostView_.get(), rootPoint, + ->GetRenderWidgetHostAtPoint(renderWidgetHostView_, rootPoint, &transformedPoint); if (!widgetHost) return NSNotFound; @@ -1909,7 +1910,7 @@ } - (void)startSpeaking:(id)sender { - GetRenderWidgetHostViewToUse(renderWidgetHostView_.get())->SpeakSelection(); + GetRenderWidgetHostViewToUse(renderWidgetHostView_)->SpeakSelection(); } - (void)stopSpeaking:(id)sender {
diff --git a/content/browser/renderer_host/render_widget_host_view_event_handler.cc b/content/browser/renderer_host/render_widget_host_view_event_handler.cc index ab47fc8..c2b6f75 100644 --- a/content/browser/renderer_host/render_widget_host_view_event_handler.cc +++ b/content/browser/renderer_host/render_widget_host_view_event_handler.cc
@@ -414,8 +414,7 @@ // Coordinates need to be transferred to the fling cancel gesture only // for Surface-targeting to ensure that it is targeted to the correct // RenderWidgetHost. - gesture_event.x = event->x(); - gesture_event.y = event->y(); + gesture_event.SetPositionInWidget(event->location_f()); blink::WebMouseWheelEvent mouse_wheel_event = ui::MakeWebMouseWheelEvent( *event, base::Bind(&GetScreenLocationFromEvent)); if (host_view_->wheel_scroll_latching_enabled()) @@ -449,7 +448,7 @@ mouse_wheel_phase_handler_.ResetScrollSequence(); } else if (event->type() == ui::ET_SCROLL_FLING_CANCEL) { // The user has put their fingers down. - DCHECK_EQ(blink::kWebGestureDeviceTouchpad, gesture_event.source_device); + DCHECK_EQ(blink::kWebGestureDeviceTouchpad, gesture_event.SourceDevice()); mouse_wheel_phase_handler_.ScrollingMayBegin(); } } @@ -532,7 +531,7 @@ // event to stop any in-progress flings. blink::WebGestureEvent fling_cancel = gesture; fling_cancel.SetType(blink::WebInputEvent::kGestureFlingCancel); - fling_cancel.source_device = blink::kWebGestureDeviceTouchscreen; + fling_cancel.SetSourceDevice(blink::kWebGestureDeviceTouchscreen); if (ShouldRouteEvent(event)) { host_->delegate()->GetInputEventRouter()->RouteGestureEvent( host_view_, &fling_cancel,
diff --git a/content/browser/renderer_host/render_widget_host_view_mac.h b/content/browser/renderer_host/render_widget_host_view_mac.h index 010056b..fb064ccb 100644 --- a/content/browser/renderer_host/render_widget_host_view_mac.h +++ b/content/browser/renderer_host/render_widget_host_view_mac.h
@@ -17,6 +17,7 @@ #include "components/viz/common/surfaces/surface_id.h" #include "content/browser/renderer_host/browser_compositor_view_mac.h" #include "content/browser/renderer_host/input/mouse_wheel_phase_handler.h" +#include "content/browser/renderer_host/render_widget_host_ns_view_client.h" #include "content/browser/renderer_host/render_widget_host_view_base.h" #include "content/browser/renderer_host/text_input_manager.h" #include "content/common/content_export.h" @@ -30,6 +31,8 @@ namespace content { class CursorManager; class RenderWidgetHost; +class RenderWidgetHostNSViewBridge; +class RenderWidgetHostViewMac; class WebContents; } @@ -62,6 +65,7 @@ // RenderWidgetHostView class hierarchy described in render_widget_host_view.h. class CONTENT_EXPORT RenderWidgetHostViewMac : public RenderWidgetHostViewBase, + public RenderWidgetHostNSViewClient, public BrowserCompositorMacClient, public TextInputManager::Observer, public ui::AcceleratedWidgetMacNSView, @@ -79,7 +83,7 @@ RenderWidgetHostViewMac(RenderWidgetHost* widget, bool is_guest_view_hack); ~RenderWidgetHostViewMac() override; - RenderWidgetHostViewCocoa* cocoa_view() const { return cocoa_view_; } + RenderWidgetHostViewCocoa* cocoa_view() const; // |delegate| is used to separate out the logic from the NSResponder delegate. // |delegate| is retained by this class. @@ -295,6 +299,9 @@ void PauseForPendingResizeOrRepaintsAndDraw(); + // RenderWidgetHostNSViewClient implementation. + RenderWidgetHostViewMac* GetRenderWidgetHostViewMac() override; + // BrowserCompositorMacClient implementation. SkColor BrowserCompositorMacGetGutterColor() const override; void BrowserCompositorMacOnBeginFrame() override; @@ -375,10 +382,8 @@ using SpeechCallback = base::OnceCallback<void(const base::string16&)>; void GetPageTextForSpeech(SpeechCallback callback); - // The associated view. This is weak and is inserted into the view hierarchy - // to own this RenderWidgetHostViewMac object. Set to nil at the start of the - // destructor. - RenderWidgetHostViewCocoa* cocoa_view_; + // Interface through which the NSView is to be manipulated. + std::unique_ptr<RenderWidgetHostNSViewBridge> ns_view_bridge_; // Indicates if the page is loading. bool is_loading_;
diff --git a/content/browser/renderer_host/render_widget_host_view_mac.mm b/content/browser/renderer_host/render_widget_host_view_mac.mm index 528cccc..2901db41 100644 --- a/content/browser/renderer_host/render_widget_host_view_mac.mm +++ b/content/browser/renderer_host/render_widget_host_view_mac.mm
@@ -25,6 +25,7 @@ #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/renderer_host/render_widget_helper.h" #include "content/browser/renderer_host/render_widget_host_input_event_router.h" +#import "content/browser/renderer_host/render_widget_host_ns_view_bridge.h" #import "content/browser/renderer_host/render_widget_host_view_cocoa.h" #import "content/browser/renderer_host/render_widget_host_view_mac_dictionary_helper.h" #import "content/browser/renderer_host/text_input_client_mac.h" @@ -224,7 +225,7 @@ // AcceleratedWidgetMacNSView, public: NSView* RenderWidgetHostViewMac::AcceleratedWidgetGetNSView() const { - return cocoa_view_; + return cocoa_view(); } void RenderWidgetHostViewMac::AcceleratedWidgetGetVSyncParameters( @@ -260,22 +261,24 @@ is_guest_view_hack_(is_guest_view_hack), fullscreen_parent_host_view_(nullptr), weak_factory_(this) { - // |cocoa_view_| owns us and we will be deleted when |cocoa_view_| - // goes away. Since we autorelease it, our caller must put - // |GetNativeView()| into the view hierarchy right after calling us. - cocoa_view_ = [[[RenderWidgetHostViewCocoa alloc] - initWithRenderWidgetHostViewMac:this] autorelease]; + // The NSView on the other side of |ns_view_bridge_| owns us. We will + // be destroyed when it releases the unique_ptr that we pass to it here at + // creation. + // The NSView is autoreleased, so our caller must put |GetNativeView()| into + // the view hierarchy right after calling us. + ns_view_bridge_ = RenderWidgetHostNSViewBridge::Create( + std::unique_ptr<RenderWidgetHostNSViewClient>(this)); background_layer_.reset([[CALayer alloc] init]); - [cocoa_view_ setLayer:background_layer_]; - [cocoa_view_ setWantsLayer:YES]; + [cocoa_view() setLayer:background_layer_]; + [cocoa_view() setWantsLayer:YES]; viz::FrameSinkId frame_sink_id = is_guest_view_hack_ ? AllocateFrameSinkIdForGuestViewHack() : host()->GetFrameSinkId(); browser_compositor_.reset(new BrowserCompositorMac( - this, this, host()->is_hidden(), [cocoa_view_ window], frame_sink_id)); + this, this, host()->is_hidden(), [cocoa_view() window], frame_sink_id)); display::Screen::GetScreen()->AddObserver(this); @@ -319,9 +322,10 @@ RenderWidgetHostViewMac::~RenderWidgetHostViewMac() { display::Screen::GetScreen()->RemoveObserver(this); - // This is being called from |cocoa_view_|'s destructor, so invalidate the - // pointer. - cocoa_view_ = nil; + // |this| is owned by RenderWidgetHostViewCocoa and is destroyed when the + // RenderWidgetHostViewCocoa is deallocated, so destroy the bridge to the + // RenderWidgetHostViewCocoa. + ns_view_bridge_.reset(); UnlockMouse(); @@ -344,9 +348,15 @@ text_input_manager_->RemoveObserver(this); } +RenderWidgetHostViewCocoa* RenderWidgetHostViewMac::cocoa_view() const { + if (ns_view_bridge_) + return ns_view_bridge_->GetRenderWidgetHostViewCocoa(); + return nil; +} + void RenderWidgetHostViewMac::SetDelegate( NSObject<RenderWidgetHostViewMacDelegate>* delegate) { - [cocoa_view_ setResponderDelegate:delegate]; + [cocoa_view() setResponderDelegate:delegate]; } void RenderWidgetHostViewMac::SetAllowPauseForResizeOrRepaint(bool allow) { @@ -387,8 +397,8 @@ RenderWidgetHostView* parent_host_view, const gfx::Rect& pos) { bool activatable = popup_type_ == blink::kWebPopupTypeNone; - [cocoa_view_ setCloseOnDeactivate:YES]; - [cocoa_view_ setCanBeKeyView:activatable ? YES : NO]; + [cocoa_view() setCloseOnDeactivate:YES]; + [cocoa_view() setCanBeKeyView:activatable ? YES : NO]; NSPoint origin_global = NSPointFromCGPoint(pos.origin().ToCGPoint()); origin_global.y = FlipYFromRectToScreen(origin_global.y, pos.height()); @@ -402,11 +412,11 @@ [popup_window_ setLevel:NSPopUpMenuWindowLevel]; [popup_window_ setReleasedWhenClosed:NO]; [popup_window_ makeKeyAndOrderFront:nil]; - [[popup_window_ contentView] addSubview:cocoa_view_]; - [cocoa_view_ setFrame:[[popup_window_ contentView] bounds]]; - [cocoa_view_ setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; + [[popup_window_ contentView] addSubview:cocoa_view()]; + [cocoa_view() setFrame:[[popup_window_ contentView] bounds]]; + [cocoa_view() setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [[NSNotificationCenter defaultCenter] - addObserver:cocoa_view_ + addObserver:cocoa_view() selector:@selector(popupWindowWillClose:) name:NSWindowWillCloseNotification object:popup_window_]; @@ -435,22 +445,22 @@ defer:NO]); [pepper_fullscreen_window_ setLevel:NSFloatingWindowLevel]; [pepper_fullscreen_window_ setReleasedWhenClosed:NO]; - [cocoa_view_ setCanBeKeyView:YES]; - [cocoa_view_ setFrame:[[pepper_fullscreen_window_ contentView] bounds]]; - [cocoa_view_ setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; + [cocoa_view() setCanBeKeyView:YES]; + [cocoa_view() setFrame:[[pepper_fullscreen_window_ contentView] bounds]]; + [cocoa_view() setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; // If the pepper fullscreen window isn't opaque then there are performance // issues when it's on the discrete GPU and the Chrome window is being drawn // to. http://crbug.com/171911 [pepper_fullscreen_window_ setOpaque:YES]; // Note that this forms a reference cycle between the fullscreen window and - // the rwhvmac: The PepperFlashFullscreenWindow retains cocoa_view_, - // but cocoa_view_ keeps pepper_fullscreen_window_ in an instance variable. + // the rwhvmac: The PepperFlashFullscreenWindow retains cocoa_view(), + // but cocoa_view() keeps pepper_fullscreen_window_ in an instance variable. // This cycle is normally broken when -keyEvent: receives an <esc> key, which // explicitly calls Shutdown on the host(), which calls // Destroy() on RWHVMac, which drops the reference to // pepper_fullscreen_window_. - [[pepper_fullscreen_window_ contentView] addSubview:cocoa_view_]; + [[pepper_fullscreen_window_ contentView] addSubview:cocoa_view()]; // Note that this keeps another reference to pepper_fullscreen_window_. fullscreen_window_manager_.reset([[FullscreenWindowManager alloc] @@ -472,7 +482,7 @@ } int RenderWidgetHostViewMac::window_number() const { - NSWindow* window = [cocoa_view_ window]; + NSWindow* window = [cocoa_view() window]; if (!window) return -1; return [window windowNumber]; @@ -485,7 +495,7 @@ if (is_vsync_disabled) return; - NSScreen* screen = [[cocoa_view_ window] screen]; + NSScreen* screen = [[cocoa_view() window] screen]; NSDictionary* screen_description = [screen deviceDescription]; NSNumber* screen_number = [screen_description objectForKey:@"NSScreenNumber"]; CGDirectDisplayID display_id = [screen_number unsignedIntValue]; @@ -558,7 +568,7 @@ void RenderWidgetHostViewMac::Show() { ScopedCAActionDisabler disabler; - [cocoa_view_ setHidden:NO]; + [cocoa_view() setHidden:NO]; browser_compositor_->SetRenderWidgetHostIsHidden(false); @@ -581,7 +591,7 @@ return; ScopedCAActionDisabler disabler; - [cocoa_view_ setHidden:YES]; + [cocoa_view() setHidden:YES]; host()->WasHidden(); browser_compositor_->SetRenderWidgetHostIsHidden(true); @@ -631,27 +641,27 @@ // valid for resizing to be requested (e.g., during tab capture, to size the // view to screen-capture resolution). In this case, simply treat the view as // relative to the screen. - BOOL isRelativeToScreen = IsPopup() || - ![[cocoa_view_ superview] isKindOfClass:[BaseView class]]; + BOOL isRelativeToScreen = + IsPopup() || ![[cocoa_view() superview] isKindOfClass:[BaseView class]]; if (isRelativeToScreen) { // The position of |rect| is screen coordinate system and we have to // consider Cocoa coordinate system is upside-down and also multi-screen. NSPoint origin_global = NSPointFromCGPoint(rect.origin().ToCGPoint()); NSSize size = NSMakeSize(rect.width(), rect.height()); - size = [cocoa_view_ convertSize:size toView:nil]; + size = [cocoa_view() convertSize:size toView:nil]; origin_global.y = FlipYFromRectToScreen(origin_global.y, size.height); NSRect frame = NSMakeRect(origin_global.x, origin_global.y, size.width, size.height); if (IsPopup()) [popup_window_ setFrame:frame display:YES]; else - [cocoa_view_ setFrame:frame]; + [cocoa_view() setFrame:frame]; } else { - BaseView* superview = static_cast<BaseView*>([cocoa_view_ superview]); - gfx::Rect rect2 = [superview flipNSRectToRect:[cocoa_view_ frame]]; + BaseView* superview = static_cast<BaseView*>([cocoa_view() superview]); + gfx::Rect rect2 = [superview flipNSRectToRect:[cocoa_view() frame]]; rect2.set_width(rect.width()); rect2.set_height(rect.height()); - [cocoa_view_ setFrame:[superview flipRectToNSRect:rect2]]; + [cocoa_view() setFrame:[superview flipRectToNSRect:rect2]]; } } @@ -660,19 +670,19 @@ } gfx::NativeView RenderWidgetHostViewMac::GetNativeView() const { - return cocoa_view_; + return cocoa_view(); } gfx::NativeViewAccessible RenderWidgetHostViewMac::GetNativeViewAccessible() { - return cocoa_view_; + return cocoa_view(); } void RenderWidgetHostViewMac::Focus() { - [[cocoa_view_ window] makeFirstResponder:cocoa_view_]; + [[cocoa_view() window] makeFirstResponder:cocoa_view()]; } bool RenderWidgetHostViewMac::HasFocus() const { - return [[cocoa_view_ window] firstResponder] == cocoa_view_; + return [[cocoa_view() window] firstResponder] == cocoa_view(); } bool RenderWidgetHostViewMac::IsSurfaceAvailableForCopy() const { @@ -681,19 +691,19 @@ } bool RenderWidgetHostViewMac::IsShowing() { - return ![cocoa_view_ isHidden]; + return ![cocoa_view() isHidden]; } gfx::Rect RenderWidgetHostViewMac::GetViewBounds() const { - NSRect bounds = [cocoa_view_ bounds]; + NSRect bounds = [cocoa_view() bounds]; // TODO(shess): In case of !window, the view has been removed from // the view hierarchy because the tab isn't main. Could retrieve // the information from the main tab for our window. - NSWindow* enclosing_window = ApparentWindowForView(cocoa_view_); + NSWindow* enclosing_window = ApparentWindowForView(cocoa_view()); if (!enclosing_window) return gfx::Rect(gfx::Size(NSWidth(bounds), NSHeight(bounds))); - bounds = [cocoa_view_ convertRect:bounds toView:nil]; + bounds = [cocoa_view() convertRect:bounds toView:nil]; bounds = [enclosing_window convertRectToScreen:bounds]; return FlipNSRectToRectScreen(bounds); } @@ -704,7 +714,7 @@ void RenderWidgetHostViewMac::DisplayCursor(const WebCursor& cursor) { WebCursor web_cursor = cursor; - [cocoa_view_ updateCursor:web_cursor.GetNativeCursor()]; + [cocoa_view() updateCursor:web_cursor.GetNativeCursor()]; } CursorManager* RenderWidgetHostViewMac::GetCursorManager() { @@ -765,7 +775,7 @@ void RenderWidgetHostViewMac::OnImeCancelComposition( TextInputManager* text_input_manager, RenderWidgetHostViewBase* updated_view) { - [cocoa_view_ cancelComposition]; + [cocoa_view() cancelComposition]; } void RenderWidgetHostViewMac::OnImeCompositionRangeChanged( @@ -777,7 +787,7 @@ return; // The RangeChanged message is only sent with valid values. The current // caret position (start == end) will be sent if there is no IME range. - [cocoa_view_ setMarkedRange:info->range.ToNSRange()]; + [cocoa_view() setMarkedRange:info->range.ToNSRange()]; } void RenderWidgetHostViewMac::OnSelectionBoundsChanged( @@ -799,7 +809,7 @@ if (!region) return; - NSWindow* enclosing_window = ApparentWindowForView(cocoa_view_); + NSWindow* enclosing_window = ApparentWindowForView(cocoa_view()); if (!enclosing_window) return; @@ -812,11 +822,11 @@ // Convert the caret rect to CG-style flipped widget-relative coordinates. NSRect caret_rect = NSRectFromCGRect(gfx_caret_rect.ToCGRect()); - caret_rect.origin.y = NSHeight([cocoa_view_ bounds]) - - (caret_rect.origin.y + caret_rect.size.height); + caret_rect.origin.y = NSHeight([cocoa_view() bounds]) - + (caret_rect.origin.y + caret_rect.size.height); // Now convert that to screen coordinates. - caret_rect = [cocoa_view_ convertRect:caret_rect toView:nil]; + caret_rect = [cocoa_view() convertRect:caret_rect toView:nil]; caret_rect = [enclosing_window convertRectToScreen:caret_rect]; // Finally, flip it again because UAZoomChangeFocus wants unflipped screen @@ -835,12 +845,12 @@ if (!selection) return; - [cocoa_view_ setSelectedRange:selection->range().ToNSRange()]; + [cocoa_view() setSelectedRange:selection->range().ToNSRange()]; // Updates markedRange when there is no marked text so that retrieving // markedRange immediately after calling setMarkdText: returns the current // caret position. - if (![cocoa_view_ hasMarkedText]) { - [cocoa_view_ setMarkedRange:selection->range().ToNSRange()]; + if (![cocoa_view() hasMarkedText]) { + [cocoa_view() setMarkedRange:selection->range().ToNSRange()]; } } @@ -854,14 +864,14 @@ // have already been cleared when RenderWidgetHostViewBase notified its // observers of our impending destruction. [[NSNotificationCenter defaultCenter] - removeObserver:cocoa_view_ + removeObserver:cocoa_view() name:NSWindowWillCloseNotification object:popup_window_]; // We've been told to destroy. - [cocoa_view_ retain]; - [cocoa_view_ removeFromSuperview]; - [cocoa_view_ autorelease]; + [cocoa_view() retain]; + [cocoa_view() removeFromSuperview]; + [cocoa_view() autorelease]; [popup_window_ close]; popup_window_.autorelease(); @@ -889,7 +899,7 @@ mouse_wheel_phase_handler_.IgnorePendingWheelEndEvent(); // We get this call just before host() deletes - // itself. But we are owned by |cocoa_view_|, which may be retained + // itself. But we are owned by |cocoa_view()|, which may be retained // by some other code. Examples are WebContentsViewMac's // |latent_focus_view_| and TabWindowController's // |cachedContentView_|. @@ -901,7 +911,7 @@ // of repeat work. void RenderWidgetHostViewMac::SetTooltipText( const base::string16& tooltip_text) { - if (tooltip_text != tooltip_text_ && [[cocoa_view_ window] isKeyWindow]) { + if (tooltip_text != tooltip_text_ && [[cocoa_view() window] isKeyWindow]) { tooltip_text_ = tooltip_text; // Clamp the tooltip length to kMaxTooltipLength. It's a DOS issue on @@ -913,7 +923,7 @@ display_text = tooltip_text_.substr(0, kMaxTooltipLength); NSString* tooltip_nsstring = base::SysUTF16ToNSString(display_text); - [cocoa_view_ setToolTipAtMousePoint:tooltip_nsstring]; + [cocoa_view() setToolTipAtMousePoint:tooltip_nsstring]; } } @@ -1015,7 +1025,7 @@ void RenderWidgetHostViewMac::SetShowingContextMenu(bool showing) { // Create a fake mouse event to inform the render widget that the mouse // left or entered. - NSWindow* window = [cocoa_view_ window]; + NSWindow* window = [cocoa_view() window]; // TODO(asvitkine): If the location outside of the event stream doesn't // correspond to the current event (due to delayed event processing), then // this may result in a cursor flicker if there are later mouse move events @@ -1032,7 +1042,7 @@ eventNumber:0 clickCount:0 pressure:0]; - WebMouseEvent web_event = WebMouseEventBuilder::Build(event, cocoa_view_); + WebMouseEvent web_event = WebMouseEventBuilder::Build(event, cocoa_view()); web_event.SetModifiers(web_event.GetModifiers() | WebInputEvent::kRelativeMotionEvent); ForwardMouseEvent(web_event); @@ -1055,7 +1065,7 @@ host()->ForwardMouseEvent(event); if (event.GetType() == WebInputEvent::kMouseLeave) { - [cocoa_view_ setToolTipAtMousePoint:nil]; + [cocoa_view() setToolTipAtMousePoint:nil]; tooltip_text_.clear(); } } @@ -1082,7 +1092,7 @@ void RenderWidgetHostViewMac::KillSelf() { if (!weak_factory_.HasWeakPtrs()) { - [cocoa_view_ setHidden:YES]; + [cocoa_view() setHidden:YES]; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&RenderWidgetHostViewMac::ShutdownHost, weak_factory_.GetWeakPtr())); @@ -1264,7 +1274,7 @@ void RenderWidgetHostViewMac::FocusedNodeChanged( bool is_editable_node, const gfx::Rect& node_bounds_in_screen) { - [cocoa_view_ cancelComposition]; + [cocoa_view() cancelComposition]; // If the Mac Zoom feature is enabled, update it with the bounds of the // current focused node so that it can ensure that it's scrolled into view. @@ -1317,7 +1327,7 @@ // TODO(shess): In case of !window, the view has been removed from // the view hierarchy because the tab isn't main. Could retrieve // the information from the main tab for our window. - NSWindow* enclosing_window = ApparentWindowForView(cocoa_view_); + NSWindow* enclosing_window = ApparentWindowForView(cocoa_view()); if (!enclosing_window) return gfx::Rect(); @@ -1361,7 +1371,7 @@ case WebInputEvent::kGestureScrollBegin: case WebInputEvent::kGestureScrollUpdate: case WebInputEvent::kGestureScrollEnd: - [cocoa_view_ processedGestureScrollEvent:event consumed:consumed]; + [cocoa_view() processedGestureScrollEvent:event consumed:consumed]; return; default: break; @@ -1370,7 +1380,7 @@ void RenderWidgetHostViewMac::DidOverscroll( const ui::DidOverscrollParams& params) { - [cocoa_view_ processedOverscroll:params]; + [cocoa_view() processedOverscroll:params]; } std::unique_ptr<SyntheticGestureTarget> @@ -1378,7 +1388,7 @@ RenderWidgetHostImpl* host = RenderWidgetHostImpl::From(GetRenderWidgetHost()); return std::unique_ptr<SyntheticGestureTarget>( - new SyntheticGestureTargetMac(host, cocoa_view_)); + new SyntheticGestureTargetMac(host, cocoa_view())); } viz::LocalSurfaceId RenderWidgetHostViewMac::GetLocalSurfaceId() const { @@ -1403,7 +1413,7 @@ void RenderWidgetHostViewMac::SendGesturePinchEvent(WebGestureEvent* event) { DCHECK(WebInputEvent::IsPinchGestureEventType(event->GetType())); if (ShouldRouteEvent(*event)) { - DCHECK(event->source_device == + DCHECK(event->SourceDevice() == blink::WebGestureDevice::kWebGestureDeviceTouchpad); host()->delegate()->GetInputEventRouter()->RouteGestureEvent( this, event, ui::LatencyInfo(ui::SourceEventType::WHEEL)); @@ -1418,7 +1428,7 @@ gfx::PointF* transformed_point) { // Transformations use physical pixels rather than DIP, so conversion // is necessary. - float scale_factor = ui::GetScaleFactorForNativeView(cocoa_view_); + float scale_factor = ui::GetScaleFactorForNativeView(cocoa_view()); gfx::PointF point_in_pixels = gfx::ConvertPointToPixel(scale_factor, point); if (!browser_compositor_->GetDelegatedFrameHost() ->TransformPointToLocalCoordSpace(point_in_pixels, original_surface, @@ -1534,10 +1544,10 @@ const gfx::Rect& bounds) { NSPoint origin = NSMakePoint(bounds.x(), bounds.y()); NSSize size = NSMakeSize(bounds.width(), bounds.height()); - origin.y = NSHeight([cocoa_view_ bounds]) - origin.y; - NSPoint originInWindow = [cocoa_view_ convertPoint:origin toView:nil]; + origin.y = NSHeight([cocoa_view() bounds]) - origin.y; + NSPoint originInWindow = [cocoa_view() convertPoint:origin toView:nil]; NSPoint originInScreen = - ui::ConvertPointFromWindowToScreen([cocoa_view_ window], originInWindow); + ui::ConvertPointFromWindowToScreen([cocoa_view() window], originInWindow); originInScreen.y = originInScreen.y - size.height; return gfx::Point(originInScreen.x, originInScreen.y); } @@ -1594,14 +1604,20 @@ const display::Display& display, uint32_t changed_metrics) { display::Screen* screen = display::Screen::GetScreen(); - if (display.id() != screen->GetDisplayNearestView(cocoa_view_).id()) + if (display.id() != screen->GetDisplayNearestView(cocoa_view()).id()) return; UpdateNSViewAndDisplayProperties(); } +/////////////////////////////////////////////////////////////////////////////// +// RenderWidgetHostNSViewClient implementation: + +RenderWidgetHostViewMac* RenderWidgetHostViewMac::GetRenderWidgetHostViewMac() { + return this; +} + Class GetRenderWidgetHostViewCocoaClassForTesting() { return [RenderWidgetHostViewCocoa class]; } } // namespace content -
diff --git a/content/browser/renderer_host/render_widget_targeter.cc b/content/browser/renderer_host/render_widget_targeter.cc index 59724f3c..6bb37f88 100644 --- a/content/browser/renderer_host/render_widget_targeter.cc +++ b/content/browser/renderer_host/render_widget_targeter.cc
@@ -120,9 +120,9 @@ event.GetType() == blink::WebInputEvent::kMouseWheel || blink::WebInputEvent::IsTouchEventType(event.GetType()) || (blink::WebInputEvent::IsGestureEventType(event.GetType()) && - (static_cast<const blink::WebGestureEvent&>(event).source_device == + (static_cast<const blink::WebGestureEvent&>(event).SourceDevice() == blink::WebGestureDevice::kWebGestureDeviceTouchscreen || - static_cast<const blink::WebGestureEvent&>(event).source_device == + static_cast<const blink::WebGestureEvent&>(event).SourceDevice() == blink::WebGestureDevice::kWebGestureDeviceTouchpad))); if (request_in_flight_) {
diff --git a/content/browser/site_per_process_browsertest.cc b/content/browser/site_per_process_browsertest.cc index c3b41da..e5bb06a 100644 --- a/content/browser/site_per_process_browsertest.cc +++ b/content/browser/site_per_process_browsertest.cc
@@ -1109,8 +1109,8 @@ blink::WebGestureEvent gesture_scroll_begin( blink::WebGestureEvent::kGestureScrollBegin, blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::GetStaticTimeStampForTests()); - gesture_scroll_begin.source_device = blink::kWebGestureDeviceTouchscreen; + blink::WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchscreen); gesture_scroll_begin.data.scroll_begin.delta_hint_units = blink::WebGestureEvent::ScrollUnits::kPrecisePixels; gesture_scroll_begin.data.scroll_begin.delta_x_hint = 0.f; @@ -1121,8 +1121,8 @@ blink::WebGestureEvent gesture_scroll_update( blink::WebGestureEvent::kGestureScrollUpdate, blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::GetStaticTimeStampForTests()); - gesture_scroll_update.source_device = blink::kWebGestureDeviceTouchscreen; + blink::WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchscreen); gesture_scroll_update.data.scroll_update.delta_units = blink::WebGestureEvent::ScrollUnits::kPrecisePixels; gesture_scroll_update.data.scroll_update.delta_x = 0.f; @@ -1134,8 +1134,8 @@ blink::WebGestureEvent gesture_fling_start( blink::WebGestureEvent::kGestureFlingStart, blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::GetStaticTimeStampForTests()); - gesture_fling_start.source_device = blink::kWebGestureDeviceTouchscreen; + blink::WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchscreen); gesture_fling_start.data.fling_start.velocity_x = 0.f; gesture_fling_start.data.fling_start.velocity_y = 5.f; @@ -1322,34 +1322,31 @@ blink::WebGestureEvent gesture_event( blink::WebGestureEvent::kGestureScrollBegin, blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::GetStaticTimeStampForTests()); - gesture_event.source_device = blink::kWebGestureDeviceTouchpad; - gesture_event.x = 1; - gesture_event.y = 1; + blink::WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchpad); + gesture_event.SetPositionInWidget(gfx::PointF(1, 1)); gesture_event.data.scroll_begin.delta_x_hint = 0.0f; gesture_event.data.scroll_begin.delta_y_hint = 6.0f; rwhv_nested->GetRenderWidgetHost()->ForwardGestureEvent(gesture_event); - gesture_event = blink::WebGestureEvent( - blink::WebGestureEvent::kGestureScrollUpdate, - blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::GetStaticTimeStampForTests()); - gesture_event.source_device = blink::kWebGestureDeviceTouchpad; - gesture_event.x = 1; - gesture_event.y = 1; + gesture_event = + blink::WebGestureEvent(blink::WebGestureEvent::kGestureScrollUpdate, + blink::WebInputEvent::kNoModifiers, + blink::WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchpad); + gesture_event.SetPositionInWidget(gfx::PointF(1, 1)); gesture_event.data.scroll_update.delta_x = 0.0f; gesture_event.data.scroll_update.delta_y = 6.0f; gesture_event.data.scroll_update.velocity_x = 0; gesture_event.data.scroll_update.velocity_y = 0; rwhv_nested->GetRenderWidgetHost()->ForwardGestureEvent(gesture_event); - gesture_event = blink::WebGestureEvent( - blink::WebGestureEvent::kGestureScrollEnd, - blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::GetStaticTimeStampForTests()); - gesture_event.source_device = blink::kWebGestureDeviceTouchpad; - gesture_event.x = 1; - gesture_event.y = 1; + gesture_event = + blink::WebGestureEvent(blink::WebGestureEvent::kGestureScrollEnd, + blink::WebInputEvent::kNoModifiers, + blink::WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchpad); + gesture_event.SetPositionInWidget(gfx::PointF(1, 1)); rwhv_nested->GetRenderWidgetHost()->ForwardGestureEvent(gesture_event); filter->WaitForRect();
diff --git a/content/browser/site_per_process_hit_test_browsertest.cc b/content/browser/site_per_process_hit_test_browsertest.cc index 4ad4d60..b7ae920 100644 --- a/content/browser/site_per_process_hit_test_browsertest.cc +++ b/content/browser/site_per_process_hit_test_browsertest.cc
@@ -968,8 +968,8 @@ blink::WebGestureEvent gesture_event( blink::WebInputEvent::kGestureTapDown, blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::GetStaticTimeStampForTests()); - gesture_event.source_device = blink::kWebGestureDeviceTouchscreen; + blink::WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchscreen); gesture_event.unique_touch_event_id = touch_event.unique_touch_event_id; router->RouteGestureEvent(rwhv_root, &gesture_event, ui::LatencyInfo(ui::SourceEventType::TOUCH)); @@ -1014,8 +1014,8 @@ blink::WebGestureEvent gesture_scroll_begin( blink::WebGestureEvent::kGestureScrollBegin, blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::GetStaticTimeStampForTests()); - gesture_scroll_begin.source_device = blink::kWebGestureDeviceTouchscreen; + blink::WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchscreen); gesture_scroll_begin.unique_touch_event_id = 1; gesture_scroll_begin.data.scroll_begin.delta_hint_units = blink::WebGestureEvent::ScrollUnits::kPrecisePixels; @@ -1039,8 +1039,8 @@ blink::WebGestureEvent gesture_scroll_update( blink::WebGestureEvent::kGestureScrollUpdate, blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::GetStaticTimeStampForTests()); - gesture_scroll_update.source_device = blink::kWebGestureDeviceTouchscreen; + blink::WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchscreen); gesture_scroll_update.unique_touch_event_id = 1; gesture_scroll_update.data.scroll_update.delta_units = blink::WebGestureEvent::ScrollUnits::kPrecisePixels; @@ -1080,8 +1080,8 @@ blink::WebGestureEvent gesture_scroll_end( blink::WebGestureEvent::kGestureScrollEnd, blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::GetStaticTimeStampForTests()); - gesture_scroll_end.source_device = blink::kWebGestureDeviceTouchscreen; + blink::WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchscreen); gesture_scroll_end.unique_touch_event_id = 1; gesture_scroll_end.data.scroll_end.delta_units = blink::WebGestureEvent::ScrollUnits::kPrecisePixels; @@ -2403,10 +2403,9 @@ blink::WebGestureEvent gesture_event( blink::WebGestureEvent::kGestureScrollBegin, blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::GetStaticTimeStampForTests()); - gesture_event.source_device = blink::kWebGestureDeviceTouchpad; - gesture_event.x = gesture_point.x(); - gesture_event.y = gesture_point.y(); + blink::WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchpad); + gesture_event.SetPositionInWidget(gfx::PointF(gesture_point)); gesture_event.data.scroll_begin.delta_x_hint = 0.0f; gesture_event.data.scroll_begin.delta_y_hint = 1.0f; expected_target->GetRenderWidgetHost()->ForwardGestureEvent(gesture_event); @@ -2443,10 +2442,9 @@ blink::WebGestureEvent gesture_event( blink::WebGestureEvent::kGestureScrollEnd, blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::GetStaticTimeStampForTests()); - gesture_event.source_device = blink::kWebGestureDeviceTouchpad; - gesture_event.x = gesture_point.x(); - gesture_event.y = gesture_point.y(); + blink::WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchpad); + gesture_event.SetPositionInWidget(gfx::PointF(gesture_point)); expected_target->GetRenderWidgetHost()->ForwardGestureEvent(gesture_event); } }
diff --git a/content/browser/web_contents/web_contents_view_android.cc b/content/browser/web_contents/web_contents_view_android.cc index 2efee91..4a46d79 100644 --- a/content/browser/web_contents/web_contents_view_android.cc +++ b/content/browser/web_contents/web_contents_view_android.cc
@@ -4,11 +4,13 @@ #include "content/browser/web_contents/web_contents_view_android.h" +#include "base/android/build_info.h" #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/logging.h" #include "cc/layers/layer.h" #include "content/browser/accessibility/browser_accessibility_manager_android.h" +#include "content/browser/android/content_feature_list.h" #include "content/browser/android/content_view_core.h" #include "content/browser/android/gesture_listener_manager.h" #include "content/browser/android/select_popup.h" @@ -42,6 +44,20 @@ namespace { +const int kAndroidLSDKVersion = 21; + +// True if we want to disable Android native event batching and use +// compositor event queue. +bool ShouldRequestUnbufferedDispatch() { + static bool should_request_unbuffered_dispatch = + base::FeatureList::IsEnabled( + content::android::kRequestUnbufferedDispatch) && + base::android::BuildInfo::GetInstance()->sdk_int() >= + kAndroidLSDKVersion && + !content::GetContentClient()->UsingSynchronousCompositing(); + return should_request_unbuffered_dispatch; +} + RenderWidgetHostViewAndroid* GetRenderWidgetHostViewAndroid( WebContents* web_contents) { RenderWidgetHostView* rwhv = NULL; @@ -493,8 +509,11 @@ } bool WebContentsViewAndroid::OnTouchEvent(const ui::MotionEventAndroid& event) { - if (event.GetAction() == ui::MotionEventAndroid::Action::DOWN) + if (event.GetAction() == ui::MotionEventAndroid::Action::DOWN) { + if (ShouldRequestUnbufferedDispatch()) + view_.RequestUnbufferedDispatch(event); content_view_core_->OnTouchDown(event.GetJavaObject()); + } return false; // let the children handle the actual event. }
diff --git a/content/browser/web_contents/web_contents_view_aura_browsertest.cc b/content/browser/web_contents/web_contents_view_aura_browsertest.cc index 00ce8c4a..4dc643a 100644 --- a/content/browser/web_contents/web_contents_view_aura_browsertest.cc +++ b/content/browser/web_contents/web_contents_view_aura_browsertest.cc
@@ -467,8 +467,8 @@ blink::WebGestureEvent gesture_scroll_begin( blink::WebGestureEvent::kGestureScrollBegin, blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::GetStaticTimeStampForTests()); - gesture_scroll_begin.source_device = blink::kWebGestureDeviceTouchscreen; + blink::WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchscreen); gesture_scroll_begin.data.scroll_begin.delta_hint_units = blink::WebGestureEvent::ScrollUnits::kPrecisePixels; gesture_scroll_begin.data.scroll_begin.delta_x_hint = 0.f; @@ -478,8 +478,8 @@ blink::WebGestureEvent gesture_scroll_update( blink::WebGestureEvent::kGestureScrollUpdate, blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::GetStaticTimeStampForTests()); - gesture_scroll_update.source_device = blink::kWebGestureDeviceTouchscreen; + blink::WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchscreen); gesture_scroll_update.data.scroll_update.delta_units = blink::WebGestureEvent::ScrollUnits::kPrecisePixels; gesture_scroll_update.data.scroll_update.delta_y = 0.f;
diff --git a/content/child/runtime_features.cc b/content/child/runtime_features.cc index 7e7dfdb..1dc3c151 100644 --- a/content/child/runtime_features.cc +++ b/content/child/runtime_features.cc
@@ -417,6 +417,9 @@ if (base::FeatureList::IsEnabled(features::kStopLoadingInBackground)) WebRuntimeFeatures::EnableStopLoadingInBackground(true); + if (base::FeatureList::IsEnabled(features::kStopNonTimersInBackground)) + WebRuntimeFeatures::EnableStopNonTimersInBackground(true); + WebRuntimeFeatures::EnablePWAFullCodeCache( base::FeatureList::IsEnabled(features::kPWAFullCodeCache));
diff --git a/content/common/input/event_with_latency_info_unittest.cc b/content/common/input/event_with_latency_info_unittest.cc index 0e2f6ff5a..d48f8eaf 100644 --- a/content/common/input/event_with_latency_info_unittest.cc +++ b/content/common/input/event_with_latency_info_unittest.cc
@@ -55,8 +55,7 @@ float y = 0.0f) { GestureEventWithLatencyInfo gesture(type, WebInputEvent::kNoModifiers, timestamp, ui::LatencyInfo()); - gesture.event.x = x; - gesture.event.y = y; + gesture.event.SetPositionInWidget(gfx::PointF(x, y)); return gesture; }
diff --git a/content/common/input/gesture_event_stream_validator.cc b/content/common/input/gesture_event_stream_validator.cc index 5338ce8..373b0be 100644 --- a/content/common/input/gesture_event_stream_validator.cc +++ b/content/common/input/gesture_event_stream_validator.cc
@@ -42,7 +42,7 @@ error_msg->append("Scroll update outside of scroll\n"); break; case WebInputEvent::kGestureFlingStart: - if (event.source_device == blink::kWebGestureDeviceTouchscreen && + if (event.SourceDevice() == blink::kWebGestureDeviceTouchscreen && !event.data.fling_start.velocity_x && !event.data.fling_start.velocity_y) { error_msg->append("Zero velocity touchscreen fling\n"); @@ -105,7 +105,7 @@ // 'continuity check', requiring that all events between an initial tap-down // and whatever terminates the sequence to have the same source device type, // and that touchpad gestures are only found on ScrollEvents. - if (event.source_device == blink::kWebGestureDeviceUninitialized) + if (event.SourceDevice() == blink::kWebGestureDeviceUninitialized) error_msg->append("Gesture event source is uninitialized.\n"); return error_msg->empty();
diff --git a/content/common/input/input_event_stream_validator.cc b/content/common/input/input_event_stream_validator.cc index 92067180..354ad73 100644 --- a/content/common/input/input_event_stream_validator.cc +++ b/content/common/input/input_event_stream_validator.cc
@@ -40,7 +40,7 @@ if (WebInputEvent::IsGestureEventType(event.GetType())) { const WebGestureEvent& gesture = static_cast<const WebGestureEvent&>(event); // TODO(jdduke): Validate touchpad gesture streams. - if (gesture.source_device == blink::kWebGestureDeviceTouchscreen) + if (gesture.SourceDevice() == blink::kWebGestureDeviceTouchscreen) return gesture_validator_.Validate(gesture, error_msg); } else if (WebInputEvent::IsTouchEventType(event.GetType())) { const WebTouchEvent& touch = static_cast<const WebTouchEvent&>(event);
diff --git a/content/common/input/input_event_struct_traits.cc b/content/common/input/input_event_struct_traits.cc index c6b923ed..3dfc5de 100644 --- a/content/common/input/input_event_struct_traits.cc +++ b/content/common/input/input_event_struct_traits.cc
@@ -111,18 +111,17 @@ if (!event.ReadGestureData<content::mojom::GestureDataPtr>(&gesture_data)) return false; (*out)->web_event.reset(new blink::WebGestureEvent( - type, event.modifiers(), event.timestamp_seconds())); + type, event.modifiers(), event.timestamp_seconds(), + gesture_data->source_device)); blink::WebGestureEvent* gesture_event = static_cast<blink::WebGestureEvent*>((*out)->web_event.get()); - gesture_event->x = gesture_data->widget_position.x(); - gesture_event->y = gesture_data->widget_position.y(); - gesture_event->global_x = gesture_data->screen_position.x(); - gesture_event->global_y = gesture_data->screen_position.y(); + gesture_event->SetPositionInWidget(gesture_data->widget_position); + gesture_event->SetPositionInScreen(gesture_data->screen_position); gesture_event->is_source_touch_event_set_non_blocking = gesture_data->is_source_touch_event_set_non_blocking; gesture_event->primary_pointer_type = gesture_data->primary_pointer_type; - gesture_event->source_device = gesture_data->source_device; + gesture_event->SetSourceDevice(gesture_data->source_device); gesture_event->unique_touch_event_id = gesture_data->unique_touch_event_id; gesture_event->resending_plugin_id = gesture_data->resending_plugin_id; @@ -395,7 +394,7 @@ auto gesture_data = content::mojom::GestureData::New(); gesture_data->screen_position = gesture_event->PositionInScreen(); gesture_data->widget_position = gesture_event->PositionInWidget(); - gesture_data->source_device = gesture_event->source_device; + gesture_data->source_device = gesture_event->SourceDevice(); gesture_data->is_source_touch_event_set_non_blocking = gesture_event->is_source_touch_event_set_non_blocking; gesture_data->primary_pointer_type = gesture_event->primary_pointer_type;
diff --git a/content/common/input/input_param_traits_unittest.cc b/content/common/input/input_param_traits_unittest.cc index f00519e..6b1927f 100644 --- a/content/common/input/input_param_traits_unittest.cc +++ b/content/common/input/input_param_traits_unittest.cc
@@ -105,7 +105,7 @@ blink::WebInputEvent::kGestureScrollBegin, blink::WebInputEvent::kNoModifiers, blink::WebInputEvent::GetStaticTimeStampForTests()); - gesture_event.x = -1; + gesture_event.SetPositionInWidget(gfx::PointF(-1, 0)); events.push_back(std::make_unique<InputEvent>(gesture_event, latency)); blink::WebTouchEvent touch_event(
diff --git a/content/common/input/synthetic_web_input_event_builders.cc b/content/common/input/synthetic_web_input_event_builders.cc index da8fa3d9..617d0ea 100644 --- a/content/common/input/synthetic_web_input_event_builders.cc +++ b/content/common/input/synthetic_web_input_event_builders.cc
@@ -97,8 +97,8 @@ int modifiers) { DCHECK(WebInputEvent::IsGestureEventType(type)); WebGestureEvent result(type, modifiers, - ui::EventTimeStampToSeconds(ui::EventTimeForNow())); - result.source_device = source_device; + ui::EventTimeStampToSeconds(ui::EventTimeForNow()), + source_device); if (type == WebInputEvent::kGestureTap || type == WebInputEvent::kGestureTapUnconfirmed || type == WebInputEvent::kGestureDoubleTap) { @@ -143,10 +143,8 @@ WebGestureEvent result = Build(WebInputEvent::kGesturePinchUpdate, source_device, modifiers); result.data.pinch_update.scale = scale; - result.x = anchor_x; - result.y = anchor_y; - result.global_x = anchor_x; - result.global_y = anchor_y; + result.SetPositionInWidget(blink::WebFloatPoint(anchor_x, anchor_y)); + result.SetPositionInScreen(blink::WebFloatPoint(anchor_x, anchor_y)); return result; }
diff --git a/content/common/unique_name_helper.cc b/content/common/unique_name_helper.cc index 8aed7052e..676e4412 100644 --- a/content/common/unique_name_helper.cc +++ b/content/common/unique_name_helper.cc
@@ -248,15 +248,16 @@ // tree and go down from there, it is impossible for a frame path to contain // a unique name (which needs a replacement) that has not already been seen // and inserted into |replacements|. - size_t index = 0; for (const auto& replacement : *replacements) { + // Note: this find() call should only start searching from immediately + // after the most recent replacement, to guarantee each section of the + // name is only replaced once. But it was accidentally omitted from the + // initial version of the migration code. size_t next_index = legacy_name.find(replacement.old_name); if (next_index == std::string::npos) continue; legacy_name.replace(next_index, replacement.old_name.size(), replacement.new_name); - index = next_index - - (replacement.old_name.size() - replacement.new_name.size()); } return legacy_name; }
diff --git a/content/public/android/java/src/org/chromium/content/browser/ContentFeatureList.java b/content/public/android/java/src/org/chromium/content/browser/ContentFeatureList.java index 18e75b83..e59b7cc 100644 --- a/content/public/android/java/src/org/chromium/content/browser/ContentFeatureList.java +++ b/content/public/android/java/src/org/chromium/content/browser/ContentFeatureList.java
@@ -32,7 +32,6 @@ // Alphabetical: public static final String ENHANCED_SELECTION_INSERTION_HANDLE = "EnhancedSelectionInsertionHandle"; - public static final String REQUEST_UNBUFFERED_DISPATCH = "RequestUnbufferedDispatch"; private static native boolean nativeIsEnabled(String featureName); }
diff --git a/content/public/android/java/src/org/chromium/content/browser/ContentViewCoreImpl.java b/content/public/android/java/src/org/chromium/content/browser/ContentViewCoreImpl.java index 1d90c999..9c341c25 100644 --- a/content/public/android/java/src/org/chromium/content/browser/ContentViewCoreImpl.java +++ b/content/public/android/java/src/org/chromium/content/browser/ContentViewCoreImpl.java
@@ -166,9 +166,6 @@ // if there is no render process. public static final int INVALID_RENDER_PROCESS_PID = 0; - // True if we want to disable Android native event batching and use compositor event queue. - private boolean mShouldRequestUnbufferedDispatch; - // A ViewAndroidDelegate that delegates to the current container view. private ViewAndroidDelegate mViewAndroidDelegate; @@ -287,9 +284,6 @@ SelectPopup.create(mContext, mWebContents, containerView); mWebContentsObserver = new ContentViewWebContentsObserver(this); - mShouldRequestUnbufferedDispatch = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP - && ContentFeatureList.isEnabled(ContentFeatureList.REQUEST_UNBUFFERED_DISPATCH) - && !nativeUsingSynchronousCompositing(mNativeContentViewCore); getGestureListenerManager().addListener(new ContentGestureStateListener()); mWindowEventObservers.addObserver(controller); @@ -526,7 +520,6 @@ @CalledByNative private void onTouchDown(MotionEvent event) { - if (mShouldRequestUnbufferedDispatch) requestUnbufferedDispatch(event); cancelRequestToScrollFocusedEditableNodeIntoView(); getGestureListenerManager().updateOnTouchDown(); } @@ -775,11 +768,6 @@ mSystemCaptioningBridge.syncToListener(this); } - @TargetApi(Build.VERSION_CODES.LOLLIPOP) - private void requestUnbufferedDispatch(MotionEvent touchDownEvent) { - mContainerView.requestUnbufferedDispatch(touchDownEvent); - } - @TargetApi(Build.VERSION_CODES.KITKAT) @Override public void onSystemCaptioningChanged(TextTrackSettings settings) { @@ -868,7 +856,6 @@ long nativeContentViewCore, boolean enabled); private native void nativeSetMultiTouchZoomSupportEnabled( long nativeContentViewCore, boolean enabled); - private native boolean nativeUsingSynchronousCompositing(long nativeContentViewCore); private native void nativeSetTextTrackSettings(long nativeContentViewCore, boolean textTracksEnabled, String textTrackBackgroundColor, String textTrackFontFamily, String textTrackFontStyle, String textTrackFontVariant, String textTrackTextColor,
diff --git a/content/public/android/java/src/org/chromium/content/browser/ContentViewRenderView.java b/content/public/android/java/src/org/chromium/content/browser/ContentViewRenderView.java index 70c31f6..643d2ce 100644 --- a/content/public/android/java/src/org/chromium/content/browser/ContentViewRenderView.java +++ b/content/public/android/java/src/org/chromium/content/browser/ContentViewRenderView.java
@@ -169,6 +169,7 @@ WebContents webContents = contentViewCore != null ? contentViewCore.getWebContents() : null; if (webContents != null) { + webContents.setSize(mWidth, mHeight); nativeOnPhysicalBackingSizeChanged( mNativeContentViewRenderView, webContents, mWidth, mHeight); }
diff --git a/content/public/common/content_features.cc b/content/public/common/content_features.cc index 6a6ddd8..0fb941dd 100644 --- a/content/public/common/content_features.cc +++ b/content/public/common/content_features.cc
@@ -371,6 +371,11 @@ const base::Feature kStopLoadingInBackground{"stop-loading-in-background", base::FEATURE_DISABLED_BY_DEFAULT}; +// Stop non-timer task queues in background, on Android, +// after allowed grace time. Launch bug: https://crbug.com/822954. +const base::Feature kStopNonTimersInBackground{ + "stop-non-timers-in-background", base::FEATURE_DISABLED_BY_DEFAULT}; + // Throttle Blink timers in out-of-view cross origin frames. const base::Feature kTimerThrottlingForHiddenFrames{ "TimerThrottlingForHiddenFrames", base::FEATURE_ENABLED_BY_DEFAULT};
diff --git a/content/public/common/content_features.h b/content/public/common/content_features.h index 541cad1..e203073 100644 --- a/content/public/common/content_features.h +++ b/content/public/common/content_features.h
@@ -90,6 +90,7 @@ CONTENT_EXPORT extern const base::Feature kSlimmingPaintV175; CONTENT_EXPORT extern const base::Feature kStopInBackground; CONTENT_EXPORT extern const base::Feature kStopLoadingInBackground; +CONTENT_EXPORT extern const base::Feature kStopNonTimersInBackground; CONTENT_EXPORT extern const base::Feature kTimerThrottlingForHiddenFrames; CONTENT_EXPORT extern const base::Feature kTopDocumentIsolation; CONTENT_EXPORT extern const base::Feature kTouchpadAndWheelScrollLatching;
diff --git a/content/public/test/browser_test_utils.cc b/content/public/test/browser_test_utils.cc index f1ad61b..9de46c5 100644 --- a/content/public/test/browser_test_utils.cc +++ b/content/public/test/browser_test_utils.cc
@@ -789,12 +789,9 @@ blink::WebGestureEvent pinch_begin( blink::WebInputEvent::kGesturePinchBegin, blink::WebInputEvent::kNoModifiers, - ui::EventTimeStampToSeconds(ui::EventTimeForNow())); - pinch_begin.source_device = source_device; - pinch_begin.x = point.x(); - pinch_begin.y = point.y(); - pinch_begin.global_x = point.x(); - pinch_begin.global_y = point.y(); + ui::EventTimeStampToSeconds(ui::EventTimeForNow()), source_device); + pinch_begin.SetPositionInWidget(gfx::PointF(point)); + pinch_begin.SetPositionInScreen(gfx::PointF(point)); widget_host->ForwardGestureEvent(pinch_begin); blink::WebGestureEvent pinch_update(pinch_begin); @@ -816,10 +813,9 @@ blink::WebGestureEvent scroll_begin( blink::WebGestureEvent::kGestureScrollBegin, blink::WebInputEvent::kNoModifiers, - ui::EventTimeStampToSeconds(ui::EventTimeForNow())); - scroll_begin.source_device = blink::kWebGestureDeviceTouchpad; - scroll_begin.x = point.x(); - scroll_begin.y = point.y(); + ui::EventTimeStampToSeconds(ui::EventTimeForNow()), + blink::kWebGestureDeviceTouchpad); + scroll_begin.SetPositionInWidget(gfx::PointF(point)); scroll_begin.data.scroll_begin.delta_x_hint = delta.x(); scroll_begin.data.scroll_begin.delta_y_hint = delta.y(); widget_host->ForwardGestureEvent(scroll_begin); @@ -827,10 +823,9 @@ blink::WebGestureEvent scroll_update( blink::WebGestureEvent::kGestureScrollUpdate, blink::WebInputEvent::kNoModifiers, - ui::EventTimeStampToSeconds(ui::EventTimeForNow())); - scroll_update.source_device = blink::kWebGestureDeviceTouchpad; - scroll_update.x = point.x(); - scroll_update.y = point.y(); + ui::EventTimeStampToSeconds(ui::EventTimeForNow()), + blink::kWebGestureDeviceTouchpad); + scroll_update.SetPositionInWidget(gfx::PointF(point)); scroll_update.data.scroll_update.delta_x = delta.x(); scroll_update.data.scroll_update.delta_y = delta.y(); scroll_update.data.scroll_update.velocity_x = 0; @@ -840,10 +835,9 @@ blink::WebGestureEvent scroll_end( blink::WebGestureEvent::kGestureScrollEnd, blink::WebInputEvent::kNoModifiers, - ui::EventTimeStampToSeconds(ui::EventTimeForNow())); - scroll_end.source_device = blink::kWebGestureDeviceTouchpad; - scroll_end.x = point.x() + delta.x(); - scroll_end.y = point.y() + delta.y(); + ui::EventTimeStampToSeconds(ui::EventTimeForNow()), + blink::kWebGestureDeviceTouchpad); + scroll_end.SetPositionInWidget(gfx::PointF(point)); widget_host->ForwardGestureEvent(scroll_end); } @@ -856,28 +850,25 @@ blink::WebGestureEvent scroll_begin( blink::WebGestureEvent::kGestureScrollBegin, blink::WebInputEvent::kNoModifiers, - ui::EventTimeStampToSeconds(ui::EventTimeForNow())); - scroll_begin.source_device = blink::kWebGestureDeviceTouchpad; - scroll_begin.x = point.x(); - scroll_begin.y = point.y(); + ui::EventTimeStampToSeconds(ui::EventTimeForNow()), + blink::kWebGestureDeviceTouchpad); + scroll_begin.SetPositionInWidget(gfx::PointF(point)); widget_host->ForwardGestureEvent(scroll_begin); blink::WebGestureEvent scroll_end( blink::WebGestureEvent::kGestureScrollEnd, blink::WebInputEvent::kNoModifiers, - ui::EventTimeStampToSeconds(ui::EventTimeForNow())); - scroll_end.source_device = blink::kWebGestureDeviceTouchpad; - scroll_end.x = point.x(); - scroll_end.y = point.y(); + ui::EventTimeStampToSeconds(ui::EventTimeForNow()), + blink::kWebGestureDeviceTouchpad); + scroll_end.SetPositionInWidget(gfx::PointF(point)); widget_host->ForwardGestureEvent(scroll_end); blink::WebGestureEvent fling_start( blink::WebGestureEvent::kGestureFlingStart, blink::WebInputEvent::kNoModifiers, - ui::EventTimeStampToSeconds(ui::EventTimeForNow())); - fling_start.source_device = blink::kWebGestureDeviceTouchpad; - fling_start.x = point.x(); - fling_start.y = point.y(); + ui::EventTimeStampToSeconds(ui::EventTimeForNow()), + blink::kWebGestureDeviceTouchpad); + fling_start.SetPositionInWidget(gfx::PointF(point)); fling_start.data.fling_start.target_viewport = false; fling_start.data.fling_start.velocity_x = velocity.x(); fling_start.data.fling_start.velocity_y = velocity.y(); @@ -893,12 +884,10 @@ } void SimulateTapAt(WebContents* web_contents, const gfx::Point& point) { - blink::WebGestureEvent tap( - blink::WebGestureEvent::kGestureTap, 0, - ui::EventTimeStampToSeconds(ui::EventTimeForNow())); - tap.source_device = blink::kWebGestureDeviceTouchpad; - tap.x = point.x(); - tap.y = point.y(); + blink::WebGestureEvent tap(blink::WebGestureEvent::kGestureTap, 0, + ui::EventTimeStampToSeconds(ui::EventTimeForNow()), + blink::kWebGestureDeviceTouchscreen); + tap.SetPositionInWidget(gfx::PointF(point)); RenderWidgetHostImpl* widget_host = RenderWidgetHostImpl::From( web_contents->GetRenderViewHost()->GetWidget()); widget_host->ForwardGestureEvent(tap); @@ -907,12 +896,10 @@ void SimulateTapWithModifiersAt(WebContents* web_contents, unsigned modifiers, const gfx::Point& point) { - blink::WebGestureEvent tap( - blink::WebGestureEvent::kGestureTap, modifiers, - ui::EventTimeStampToSeconds(ui::EventTimeForNow())); - tap.source_device = blink::kWebGestureDeviceTouchpad; - tap.x = point.x(); - tap.y = point.y(); + blink::WebGestureEvent tap(blink::WebGestureEvent::kGestureTap, modifiers, + ui::EventTimeStampToSeconds(ui::EventTimeForNow()), + blink::kWebGestureDeviceTouchpad); + tap.SetPositionInWidget(gfx::PointF(point)); RenderWidgetHostImpl* widget_host = RenderWidgetHostImpl::From( web_contents->GetRenderViewHost()->GetWidget()); widget_host->ForwardGestureEvent(tap);
diff --git a/content/public/test/render_view_test.cc b/content/public/test/render_view_test.cc index 178c5f1..05c36b2 100644 --- a/content/public/test/render_view_test.cc +++ b/content/public/test/render_view_test.cc
@@ -527,13 +527,12 @@ void RenderViewTest::SimulateRectTap(const gfx::Rect& rect) { WebGestureEvent gesture_event( WebInputEvent::kGestureTap, WebInputEvent::kNoModifiers, - ui::EventTimeStampToSeconds(ui::EventTimeForNow())); - gesture_event.x = rect.CenterPoint().x(); - gesture_event.y = rect.CenterPoint().y(); + ui::EventTimeStampToSeconds(ui::EventTimeForNow()), + blink::kWebGestureDeviceTouchscreen); + gesture_event.SetPositionInWidget(gfx::PointF(rect.CenterPoint())); gesture_event.data.tap.tap_count = 1; gesture_event.data.tap.width = rect.width(); gesture_event.data.tap.height = rect.height(); - gesture_event.source_device = blink::kWebGestureDeviceTouchpad; RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_); impl->OnMessageReceived(InputMsg_HandleInputEvent( 0, &gesture_event, std::vector<const WebInputEvent*>(), ui::LatencyInfo(),
diff --git a/content/renderer/input/render_widget_input_handler.cc b/content/renderer/input/render_widget_input_handler.cc index ab2968bb..16754dd 100644 --- a/content/renderer/input/render_widget_input_handler.cc +++ b/content/renderer/input/render_widget_input_handler.cc
@@ -415,7 +415,7 @@ input_event.GetType() == WebInputEvent::kGestureScrollUpdate) { const WebGestureEvent& gesture_event = static_cast<const WebGestureEvent&>(input_event); - if (gesture_event.source_device == blink::kWebGestureDeviceTouchpad) { + if (gesture_event.SourceDevice() == blink::kWebGestureDeviceTouchpad) { gfx::Vector2dF latest_overscroll_delta = event_overscroll ? event_overscroll->latest_overscroll_delta : gfx::Vector2dF();
diff --git a/content/renderer/render_view_browsertest.cc b/content/renderer/render_view_browsertest.cc index d5a2b7e..f915ac0 100644 --- a/content/renderer/render_view_browsertest.cc +++ b/content/renderer/render_view_browsertest.cc
@@ -517,10 +517,9 @@ int height) { blink::WebGestureEvent event( blink::WebInputEvent::kGestureTap, blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::GetStaticTimeStampForTests()); - event.source_device = blink::kWebGestureDeviceTouchscreen; - event.x = x; - event.y = y; + blink::WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(gfx::PointF(x, y)); event.data.tap.width = width; event.data.tap.height = height; return blink::WebCoalescedInputEvent(event); @@ -1524,8 +1523,7 @@ WebGestureEvent gesture_event( WebInputEvent::kGestureLongPress, WebInputEvent::kNoModifiers, ui::EventTimeStampToSeconds(ui::EventTimeForNow())); - gesture_event.x = 250; - gesture_event.y = 250; + gesture_event.SetPositionInWidget(gfx::PointF(250, 250)); SendWebGestureEvent(gesture_event);
diff --git a/content/renderer/render_widget.cc b/content/renderer/render_widget.cc index 4bc49d3..04ef8e7 100644 --- a/content/renderer/render_widget.cc +++ b/content/renderer/render_widget.cc
@@ -1321,7 +1321,7 @@ possible_drag_event_info_.event_source = ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH; possible_drag_event_info_.event_location = - gfx::Point(event.global_x, event.global_y); + gfx::ToFlooredPoint(event.PositionInScreen()); return false; }
diff --git a/content/renderer/render_widget_fullscreen_pepper.cc b/content/renderer/render_widget_fullscreen_pepper.cc index 3ac71cc3..36b89477 100644 --- a/content/renderer/render_widget_fullscreen_pepper.cc +++ b/content/renderer/render_widget_fullscreen_pepper.cc
@@ -13,6 +13,7 @@ #include "build/build_config.h" #include "content/common/view_messages.h" #include "content/public/common/content_switches.h" +#include "content/public/common/use_zoom_for_dsf_policy.h" #include "content/renderer/gpu/render_widget_compositor.h" #include "content/renderer/pepper/pepper_plugin_instance_impl.h" #include "content/renderer/render_thread_impl.h" @@ -25,6 +26,7 @@ #include "third_party/WebKit/public/platform/WebMouseWheelEvent.h" #include "third_party/WebKit/public/platform/WebSize.h" #include "third_party/WebKit/public/web/WebWidget.h" +#include "ui/gfx/geometry/dip_util.h" #include "ui/gfx/geometry/size_conversions.h" #include "ui/gl/gpu_preference.h" @@ -69,7 +71,7 @@ // Only convert touch screen gesture events, do not convert // touchpad/mouse wheel gesture events. (crbug.com/620974) - if (gesture.source_device != blink::kWebGestureDeviceTouchscreen) + if (gesture.SourceDevice() != blink::kWebGestureDeviceTouchscreen) return WebMouseEvent(); WebInputEvent::Type type = WebInputEvent::kUndefined; @@ -101,8 +103,10 @@ mouse.click_count = (mouse.GetType() == WebInputEvent::kMouseDown || mouse.GetType() == WebInputEvent::kMouseUp); - mouse.SetPositionInWidget(gesture.x, gesture.y); - mouse.SetPositionInScreen(gesture.global_x, gesture.global_y); + mouse.SetPositionInWidget(gesture.PositionInWidget().x, + gesture.PositionInWidget().y); + mouse.SetPositionInScreen(gesture.PositionInScreen().x, + gesture.PositionInScreen().y); return mouse; } @@ -175,9 +179,10 @@ WebMouseEvent mouse(WebInputEvent::kMouseMove, gesture_event->GetModifiers(), gesture_event->TimeStampSeconds()); - mouse.SetPositionInWidget(gesture_event->x, gesture_event->y); - mouse.SetPositionInScreen(gesture_event->global_x, - gesture_event->global_y); + mouse.SetPositionInWidget(gesture_event->PositionInWidget().x, + gesture_event->PositionInWidget().y); + mouse.SetPositionInScreen(gesture_event->PositionInScreen().x, + gesture_event->PositionInScreen().y); mouse.movement_x = 0; mouse.movement_y = 0; result |= widget_->plugin()->HandleInputEvent(mouse, &cursor); @@ -337,9 +342,7 @@ } if (!compositor()) InitializeLayerTreeView(); - // Note that root cc::Layers' bounds are specified in pixels (in contrast with - // non-root cc::Layers' bounds, which are specified in DIPs). - layer_->SetBounds(blink::WebSize(compositor_viewport_pixel_size())); + UpdateLayerBounds(); layer_->SetDrawsContent(true); compositor_->SetRootLayer(*layer_); } @@ -377,15 +380,31 @@ } void RenderWidgetFullscreenPepper::OnResize(const ResizeParams& params) { - // Note that root cc::Layers' bounds are specified in pixels (in contrast with - // non-root cc::Layers' bounds, which are specified in DIPs). - if (layer_) - layer_->SetBounds(blink::WebSize(params.compositor_viewport_pixel_size)); RenderWidget::OnResize(params); + UpdateLayerBounds(); } GURL RenderWidgetFullscreenPepper::GetURLForGraphicsContext3D() { return active_url_; } +void RenderWidgetFullscreenPepper::UpdateLayerBounds() { + if (!layer_) + return; + + if (IsUseZoomForDSFEnabled()) { + // Note that root cc::Layers' bounds are specified in pixels (in contrast + // with non-root cc::Layers' bounds, which are specified in DIPs). + layer_->SetBounds(blink::WebSize(compositor_viewport_pixel_size())); + } else { + // For reasons that are unclear, the above comment doesn't appear to apply + // when zoom for DSF is not enabled. + // https://crbug.com/822252 + gfx::Size dip_size = + gfx::ConvertSizeToDIP(GetOriginalScreenInfo().device_scale_factor, + compositor_viewport_pixel_size()); + layer_->SetBounds(blink::WebSize(dip_size)); + } +} + } // namespace content
diff --git a/content/renderer/render_widget_fullscreen_pepper.h b/content/renderer/render_widget_fullscreen_pepper.h index 9555d51..03343b65 100644 --- a/content/renderer/render_widget_fullscreen_pepper.h +++ b/content/renderer/render_widget_fullscreen_pepper.h
@@ -75,6 +75,8 @@ GURL GetURLForGraphicsContext3D() override; private: + void UpdateLayerBounds(); + // URL that is responsible for this widget, passed to ggl::CreateViewContext. GURL active_url_;
diff --git a/content/renderer/render_widget_unittest.cc b/content/renderer/render_widget_unittest.cc index 79d50a2..ec511998 100644 --- a/content/renderer/render_widget_unittest.cc +++ b/content/renderer/render_widget_unittest.cc
@@ -182,7 +182,7 @@ event.data.scroll_update.delta_y), blink::WebFloatSize(event.data.scroll_update.delta_x, event.data.scroll_update.delta_y), - blink::WebFloatPoint(event.x, event.y), + event.PositionInWidget(), blink::WebFloatSize(event.data.scroll_update.velocity_x, event.data.scroll_update.velocity_y), blink::WebOverscrollBehavior()); @@ -255,7 +255,7 @@ blink::WebInputEvent::kGestureScrollUpdate, blink::WebInputEvent::kNoModifiers, ui::EventTimeStampToSeconds(ui::EventTimeForNow())); - scroll.x = -10; + scroll.SetPositionInWidget(gfx::PointF(-10, 0)); scroll.data.scroll_update.delta_y = 10; MockHandledEventCallback handled_event;
diff --git a/content/shell/test_runner/event_sender.cc b/content/shell/test_runner/event_sender.cc index 9059b14..9d485b5 100644 --- a/content/shell/test_runner/event_sender.cc +++ b/content/shell/test_runner/event_sender.cc
@@ -266,11 +266,8 @@ void InitGestureEventFromMouseWheel(const WebMouseWheelEvent& wheel_event, WebGestureEvent* gesture_event) { - gesture_event->source_device = blink::kWebGestureDeviceTouchpad; - gesture_event->x = wheel_event.PositionInWidget().x; - gesture_event->y = wheel_event.PositionInWidget().y; - gesture_event->global_x = wheel_event.PositionInScreen().x; - gesture_event->global_y = wheel_event.PositionInScreen().y; + gesture_event->SetPositionInWidget(wheel_event.PositionInWidget()); + gesture_event->SetPositionInScreen(wheel_event.PositionInScreen()); } int GetKeyModifier(const std::string& modifier_name) { @@ -610,7 +607,7 @@ float velocity_y, gin::Arguments* args); bool IsFlinging(); - void GestureScrollFirstPoint(int x, int y); + void GestureScrollFirstPoint(float x, float y); void TouchStart(gin::Arguments* args); void TouchMove(gin::Arguments* args); void TouchCancel(gin::Arguments* args); @@ -908,7 +905,7 @@ return false; } -void EventSenderBindings::GestureScrollFirstPoint(int x, int y) { +void EventSenderBindings::GestureScrollFirstPoint(float x, float y) { if (sender_) sender_->GestureScrollFirstPoint(x, y); } @@ -1359,7 +1356,7 @@ touch_points_.clear(); last_context_menu_data_.reset(); weak_factory_.InvalidateWeakPtrs(); - current_gesture_location_ = WebPoint(0, 0); + current_gesture_location_ = WebFloatPoint(0, 0); mouse_event_queue_.clear(); time_offset_ms_ = 0; @@ -1959,11 +1956,11 @@ void EventSender::GestureFlingCancel() { WebGestureEvent event(WebInputEvent::kGestureFlingCancel, - WebInputEvent::kNoModifiers, GetCurrentEventTimeSec()); + WebInputEvent::kNoModifiers, GetCurrentEventTimeSec(), + blink::kWebGestureDeviceTouchpad); // Generally it won't matter what device we use here, and since it might // be cumbersome to expect all callers to specify a device, we'll just // choose Touchpad here. - event.source_device = blink::kWebGestureDeviceTouchpad; if (force_layout_on_events_) widget()->UpdateAllLifecyclePhases(); @@ -1984,9 +1981,9 @@ args->GetNext(&device_string); if (device_string == kSourceDeviceStringTouchpad) { - event.source_device = blink::kWebGestureDeviceTouchpad; + event.SetSourceDevice(blink::kWebGestureDeviceTouchpad); } else if (device_string == kSourceDeviceStringTouchscreen) { - event.source_device = blink::kWebGestureDeviceTouchscreen; + event.SetSourceDevice(blink::kWebGestureDeviceTouchscreen); } else { args->ThrowError(); return; @@ -2000,10 +1997,8 @@ return; } - event.x = x; - event.y = y; - event.global_x = event.x; - event.global_y = event.y; + event.SetPositionInWidget(WebFloatPoint(x, y)); + event.SetPositionInScreen(WebFloatPoint(x, y)); event.data.fling_start.velocity_x = velocity_x; event.data.fling_start.velocity_y = velocity_y; @@ -2018,8 +2013,8 @@ return mainFrameWidget()->IsFlinging(); } -void EventSender::GestureScrollFirstPoint(int x, int y) { - current_gesture_location_ = WebPoint(x, y); +void EventSender::GestureScrollFirstPoint(float x, float y) { + current_gesture_location_ = WebFloatPoint(x, y); } void EventSender::TouchStart(gin::Arguments* args) { @@ -2363,12 +2358,12 @@ void EventSender::GestureEvent(WebInputEvent::Type type, gin::Arguments* args) { WebGestureEvent event(type, WebInputEvent::kNoModifiers, - GetCurrentEventTimeSec()); + GetCurrentEventTimeSec(), + blink::kWebGestureDeviceTouchscreen); // If the first argument is a string, it is to specify the device, otherwise // the device is assumed to be a touchscreen (since most tests were written // assuming this). - event.source_device = blink::kWebGestureDeviceTouchscreen; if (!args->PeekNext().IsEmpty() && args->PeekNext()->IsString()) { std::string device_string; if (!args->GetNext(&device_string)) { @@ -2376,9 +2371,9 @@ return; } if (device_string == kSourceDeviceStringTouchpad) { - event.source_device = blink::kWebGestureDeviceTouchpad; + event.SetSourceDevice(blink::kWebGestureDeviceTouchpad); } else if (device_string == kSourceDeviceStringTouchscreen) { - event.source_device = blink::kWebGestureDeviceTouchscreen; + event.SetSourceDevice(blink::kWebGestureDeviceTouchscreen); } else { args->ThrowError(); return; @@ -2399,8 +2394,7 @@ event.data.scroll_update.delta_x = static_cast<float>(x); event.data.scroll_update.delta_y = static_cast<float>(y); - event.x = current_gesture_location_.x; - event.y = current_gesture_location_.y; + event.SetPositionInWidget(current_gesture_location_); current_gesture_location_.x = current_gesture_location_.x + event.data.scroll_update.delta_x; current_gesture_location_.y = @@ -2408,20 +2402,17 @@ break; } case WebInputEvent::kGestureScrollBegin: - current_gesture_location_ = WebPoint(x, y); - event.x = current_gesture_location_.x; - event.y = current_gesture_location_.y; + current_gesture_location_ = WebFloatPoint(x, y); + event.SetPositionInWidget(current_gesture_location_); break; case WebInputEvent::kGestureScrollEnd: case WebInputEvent::kGestureFlingStart: - event.x = current_gesture_location_.x; - event.y = current_gesture_location_.y; + event.SetPositionInWidget(current_gesture_location_); break; case WebInputEvent::kGesturePinchBegin: case WebInputEvent::kGesturePinchEnd: - current_gesture_location_ = WebPoint(x, y); - event.x = current_gesture_location_.x; - event.y = current_gesture_location_.y; + current_gesture_location_ = WebFloatPoint(x, y); + event.SetPositionInWidget(current_gesture_location_); break; case WebInputEvent::kGesturePinchUpdate: { float scale = 1; @@ -2432,9 +2423,8 @@ } } event.data.pinch_update.scale = scale; - current_gesture_location_ = WebPoint(x, y); - event.x = current_gesture_location_.x; - event.y = current_gesture_location_.y; + current_gesture_location_ = WebFloatPoint(x, y); + event.SetPositionInWidget(current_gesture_location_); break; } case WebInputEvent::kGestureTap: { @@ -2462,8 +2452,7 @@ event.data.tap.tap_count = tap_count; event.data.tap.width = width; event.data.tap.height = height; - event.x = x; - event.y = y; + event.SetPositionInWidget(WebFloatPoint(x, y)); break; } case WebInputEvent::kGestureTapUnconfirmed: @@ -2477,8 +2466,7 @@ } else { event.data.tap.tap_count = 1; } - event.x = x; - event.y = y; + event.SetPositionInWidget(WebFloatPoint(x, y)); break; case WebInputEvent::kGestureTapDown: { float width = 30; @@ -2495,8 +2483,7 @@ return; } } - event.x = x; - event.y = y; + event.SetPositionInWidget(WebFloatPoint(x, y)); event.data.tap_down.width = width; event.data.tap_down.height = height; break; @@ -2516,20 +2503,17 @@ } } } - event.x = x; - event.y = y; + event.SetPositionInWidget(WebFloatPoint(x, y)); event.data.show_press.width = width; event.data.show_press.height = height; break; } case WebInputEvent::kGestureTapCancel: - event.x = x; - event.y = y; + event.SetPositionInWidget(WebFloatPoint(x, y)); break; case WebInputEvent::kGestureLongPress: case WebInputEvent::kGestureLongTap: - event.x = x; - event.y = y; + event.SetPositionInWidget(WebFloatPoint(x, y)); if (!args->PeekNext().IsEmpty()) { float width; if (!args->GetNext(&width)) { @@ -2548,8 +2532,7 @@ } break; case WebInputEvent::kGestureTwoFingerTap: - event.x = x; - event.y = y; + event.SetPositionInWidget(WebFloatPoint(x, y)); if (!args->PeekNext().IsEmpty()) { float first_finger_width; if (!args->GetNext(&first_finger_width)) { @@ -2575,8 +2558,7 @@ if (!GetPointerType(args, false, event.primary_pointer_type)) return; - event.global_x = event.x; - event.global_y = event.y; + event.SetPositionInScreen(event.PositionInWidget()); if (force_layout_on_events_) widget()->UpdateAllLifecyclePhases(); @@ -2874,9 +2856,9 @@ void EventSender::SendGesturesForMouseWheelEvent( const WebMouseWheelEvent wheel_event) { - WebGestureEvent begin_event(WebInputEvent::kGestureScrollBegin, - wheel_event.GetModifiers(), - GetCurrentEventTimeSec()); + WebGestureEvent begin_event( + WebInputEvent::kGestureScrollBegin, wheel_event.GetModifiers(), + GetCurrentEventTimeSec(), blink::kWebGestureDeviceTouchpad); InitGestureEventFromMouseWheel(wheel_event, &begin_event); begin_event.data.scroll_begin.delta_x_hint = wheel_event.delta_x; begin_event.data.scroll_begin.delta_y_hint = wheel_event.delta_y; @@ -2903,9 +2885,9 @@ HandleInputEventOnViewOrPopup(begin_event); - WebGestureEvent update_event(WebInputEvent::kGestureScrollUpdate, - wheel_event.GetModifiers(), - GetCurrentEventTimeSec()); + WebGestureEvent update_event( + WebInputEvent::kGestureScrollUpdate, wheel_event.GetModifiers(), + GetCurrentEventTimeSec(), blink::kWebGestureDeviceTouchpad); InitGestureEventFromMouseWheel(wheel_event, &update_event); update_event.data.scroll_update.delta_x = begin_event.data.scroll_begin.delta_x_hint; @@ -2918,9 +2900,9 @@ widget()->UpdateAllLifecyclePhases(); HandleInputEventOnViewOrPopup(update_event); - WebGestureEvent end_event(WebInputEvent::kGestureScrollEnd, - wheel_event.GetModifiers(), - GetCurrentEventTimeSec()); + WebGestureEvent end_event( + WebInputEvent::kGestureScrollEnd, wheel_event.GetModifiers(), + GetCurrentEventTimeSec(), blink::kWebGestureDeviceTouchpad); InitGestureEventFromMouseWheel(wheel_event, &end_event); end_event.data.scroll_end.delta_units = begin_event.data.scroll_begin.delta_hint_units;
diff --git a/content/shell/test_runner/event_sender.h b/content/shell/test_runner/event_sender.h index 8010338..8998fde 100644 --- a/content/shell/test_runner/event_sender.h +++ b/content/shell/test_runner/event_sender.h
@@ -137,7 +137,7 @@ float velocity_y, gin::Arguments* args); bool IsFlinging(); - void GestureScrollFirstPoint(int x, int y); + void GestureScrollFirstPoint(float x, float y); void TouchStart(gin::Arguments* args); void TouchMove(gin::Arguments* args); @@ -281,7 +281,7 @@ blink::WebDragData current_drag_data_; // Location of the touch point that initiated a gesture. - blink::WebPoint current_gesture_location_; + blink::WebFloatPoint current_gesture_location_; // Mouse-like pointer properties. struct PointerState {
diff --git a/content/shell/test_runner/test_plugin.cc b/content/shell/test_runner/test_plugin.cc index e738e443..a871303 100644 --- a/content/shell/test_runner/test_plugin.cc +++ b/content/shell/test_runner/test_plugin.cc
@@ -93,8 +93,9 @@ } else if (blink::WebInputEvent::IsGestureEventType(event.GetType())) { const blink::WebGestureEvent& gesture = static_cast<const blink::WebGestureEvent&>(event); - delegate->PrintMessage( - base::StringPrintf("* %d, %d\n", gesture.x, gesture.y)); + delegate->PrintMessage(base::StringPrintf("* %.2f, %.2f\n", + gesture.PositionInWidget().x, + gesture.PositionInWidget().y)); } }
diff --git a/content/test/gpu/PRESUBMIT.py b/content/test/gpu/PRESUBMIT.py index 649911a6..522385a 100644 --- a/content/test/gpu/PRESUBMIT.py +++ b/content/test/gpu/PRESUBMIT.py
@@ -38,6 +38,6 @@ 'luci.chromium.try:linux_optional_gpu_tests_rel', 'luci.chromium.try:mac_optional_gpu_tests_rel', 'master.tryserver.chromium.win:win_optional_gpu_tests_rel', - 'master.tryserver.chromium.android:android_optional_gpu_tests_rel', + 'luci.chromium.try:android_optional_gpu_tests_rel', ], 'Automatically added optional GPU tests to run on CQ.')
diff --git a/device/bluetooth/bluetooth_adapter_mac.mm b/device/bluetooth/bluetooth_adapter_mac.mm index 09123af7..4a02598 100644 --- a/device/bluetooth/bluetooth_adapter_mac.mm +++ b/device/bluetooth/bluetooth_adapter_mac.mm
@@ -359,10 +359,13 @@ // filter has changed. if (!StartDiscovery(discovery_filter)) { // TODO: Provide a more precise error here. - error_callback.Run(UMABluetoothDiscoverySessionOutcome::UNKNOWN); + ui_task_runner_->PostTask( + FROM_HERE, + base::BindOnce(error_callback, + UMABluetoothDiscoverySessionOutcome::UNKNOWN)); return; } - callback.Run(); + ui_task_runner_->PostTask(FROM_HERE, callback); return; } @@ -370,7 +373,10 @@ if (!StartDiscovery(discovery_filter)) { // TODO: Provide a more precise error here. - error_callback.Run(UMABluetoothDiscoverySessionOutcome::UNKNOWN); + ui_task_runner_->PostTask( + FROM_HERE, + base::BindOnce(error_callback, + UMABluetoothDiscoverySessionOutcome::UNKNOWN)); return; } @@ -378,7 +384,7 @@ num_discovery_sessions_++; for (auto& observer : observers_) observer.AdapterDiscoveringChanged(this, true); - callback.Run(); + ui_task_runner_->PostTask(FROM_HERE, callback); } void BluetoothAdapterMac::RemoveDiscoverySession(
diff --git a/device/bluetooth/bluetooth_adapter_mac_unittest.mm b/device/bluetooth/bluetooth_adapter_mac_unittest.mm index 6568fc39..05d4481 100644 --- a/device/bluetooth/bluetooth_adapter_mac_unittest.mm +++ b/device/bluetooth/bluetooth_adapter_mac_unittest.mm
@@ -207,6 +207,8 @@ std::unique_ptr<BluetoothDiscoveryFilter> discovery_filter( new BluetoothDiscoveryFilter(BLUETOOTH_TRANSPORT_LE)); AddDiscoverySession(discovery_filter.get()); + EXPECT_TRUE(ui_task_runner_->HasPendingTask()); + ui_task_runner_->RunPendingTasks(); EXPECT_EQ(1, callback_count_); EXPECT_EQ(0, error_callback_count_); EXPECT_EQ(1, NumDiscoverySessions()); @@ -224,6 +226,8 @@ std::unique_ptr<BluetoothDiscoveryFilter> discovery_filter( new BluetoothDiscoveryFilter(BLUETOOTH_TRANSPORT_LE)); AddDiscoverySession(discovery_filter.get()); + EXPECT_TRUE(ui_task_runner_->HasPendingTask()); + ui_task_runner_->RunPendingTasks(); EXPECT_EQ(1, callback_count_); EXPECT_EQ(0, error_callback_count_); EXPECT_EQ(1, NumDiscoverySessions()); @@ -233,6 +237,8 @@ EXPECT_TRUE(adapter_mac_->IsDiscovering()); AddDiscoverySession(discovery_filter.get()); + EXPECT_TRUE(ui_task_runner_->HasPendingTask()); + ui_task_runner_->RunPendingTasks(); EXPECT_EQ(2, [mock_central_manager_ scanForPeripheralsCallCount]); EXPECT_EQ(2, callback_count_); EXPECT_EQ(0, error_callback_count_); @@ -247,6 +253,8 @@ std::unique_ptr<BluetoothDiscoveryFilter> discovery_filter( new BluetoothDiscoveryFilter(BLUETOOTH_TRANSPORT_LE)); AddDiscoverySession(discovery_filter.get()); + EXPECT_TRUE(ui_task_runner_->HasPendingTask()); + ui_task_runner_->RunPendingTasks(); EXPECT_EQ(1, callback_count_); EXPECT_EQ(0, error_callback_count_); EXPECT_EQ(1, NumDiscoverySessions());
diff --git a/extensions/common/manifest_handlers/csp_info.cc b/extensions/common/manifest_handlers/csp_info.cc index a5563b0..28da54f 100644 --- a/extensions/common/manifest_handlers/csp_info.cc +++ b/extensions/common/manifest_handlers/csp_info.cc
@@ -111,21 +111,19 @@ bool CSPHandler::Parse(Extension* extension, base::string16* error) { const std::string key = Keys()[0]; if (!extension->manifest()->HasPath(key)) { - if (extension->manifest_version() >= 2) { - // TODO(abarth): Should we continue to let extensions override the - // default Content-Security-Policy? - std::string content_security_policy = is_platform_app_ ? - kDefaultPlatformAppContentSecurityPolicy : - kDefaultContentSecurityPolicy; + // TODO(abarth): Should we continue to let extensions override the + // default Content-Security-Policy? + std::string content_security_policy = + is_platform_app_ ? kDefaultPlatformAppContentSecurityPolicy + : kDefaultContentSecurityPolicy; - CHECK_EQ(content_security_policy, - SanitizeContentSecurityPolicy(content_security_policy, - GetValidatorOptions(extension), - NULL)); - extension->SetManifestData( - keys::kContentSecurityPolicy, - std::make_unique<CSPInfo>(content_security_policy)); - } + CHECK_EQ( + content_security_policy, + SanitizeContentSecurityPolicy(content_security_policy, + GetValidatorOptions(extension), NULL)); + extension->SetManifestData( + keys::kContentSecurityPolicy, + std::make_unique<CSPInfo>(content_security_policy)); return true; }
diff --git a/extensions/components/native_app_window/native_app_window_views.cc b/extensions/components/native_app_window/native_app_window_views.cc index 28b0b87..bf95f76 100644 --- a/extensions/components/native_app_window/native_app_window_views.cc +++ b/extensions/components/native_app_window/native_app_window_views.cc
@@ -128,6 +128,10 @@ widget_->Hide(); } +bool NativeAppWindowViews::IsVisible() const { + return widget_->IsVisible(); +} + void NativeAppWindowViews::Close() { widget_->Close(); }
diff --git a/extensions/components/native_app_window/native_app_window_views.h b/extensions/components/native_app_window/native_app_window_views.h index a782d40..d7a8623 100644 --- a/extensions/components/native_app_window/native_app_window_views.h +++ b/extensions/components/native_app_window/native_app_window_views.h
@@ -76,6 +76,7 @@ void Show() override; void ShowInactive() override; void Hide() override; + bool IsVisible() const override; void Close() override; void Activate() override; void Deactivate() override;
diff --git a/extensions/shell/browser/shell_native_app_window_aura.cc b/extensions/shell/browser/shell_native_app_window_aura.cc index eaf92c5..b8f0092 100644 --- a/extensions/shell/browser/shell_native_app_window_aura.cc +++ b/extensions/shell/browser/shell_native_app_window_aura.cc
@@ -52,6 +52,10 @@ GetNativeWindow()->Hide(); } +bool ShellNativeAppWindowAura::IsVisible() const { + return GetNativeWindow()->IsVisible(); +} + void ShellNativeAppWindowAura::Activate() { aura::Window* window = GetNativeWindow(); if (window)
diff --git a/extensions/shell/browser/shell_native_app_window_aura.h b/extensions/shell/browser/shell_native_app_window_aura.h index c2b026b..2aec82c 100644 --- a/extensions/shell/browser/shell_native_app_window_aura.h +++ b/extensions/shell/browser/shell_native_app_window_aura.h
@@ -23,6 +23,7 @@ gfx::Rect GetBounds() const override; void Show() override; void Hide() override; + bool IsVisible() const override; void Activate() override; void Deactivate() override; void SetBounds(const gfx::Rect& bounds) override;
diff --git a/extensions/shell/browser/shell_native_app_window_mac.h b/extensions/shell/browser/shell_native_app_window_mac.h index 92c26cc7..58c5bfe 100644 --- a/extensions/shell/browser/shell_native_app_window_mac.h +++ b/extensions/shell/browser/shell_native_app_window_mac.h
@@ -45,6 +45,7 @@ gfx::Rect GetBounds() const override; void Show() override; void Hide() override; + bool IsVisible() const override; void Activate() override; void Deactivate() override; void SetBounds(const gfx::Rect& bounds) override;
diff --git a/extensions/shell/browser/shell_native_app_window_mac.mm b/extensions/shell/browser/shell_native_app_window_mac.mm index 9440d35..bc150dc 100644 --- a/extensions/shell/browser/shell_native_app_window_mac.mm +++ b/extensions/shell/browser/shell_native_app_window_mac.mm
@@ -95,6 +95,10 @@ NOTIMPLEMENTED(); } +bool ShellNativeAppWindowMac::IsVisible() const { + return [window() isVisible]; +} + void ShellNativeAppWindowMac::Activate() { // TODO(yoz): Activate in front of other applications. [[window_controller_ window] makeKeyAndOrderFront:window_controller_];
diff --git a/gpu/PRESUBMIT.py b/gpu/PRESUBMIT.py index 8e1e112b..02d4977 100644 --- a/gpu/PRESUBMIT.py +++ b/gpu/PRESUBMIT.py
@@ -26,7 +26,7 @@ 'luci.chromium.try:linux_optional_gpu_tests_rel', 'luci.chromium.try:mac_optional_gpu_tests_rel', 'master.tryserver.chromium.win:win_optional_gpu_tests_rel', - 'master.tryserver.chromium.android:android_optional_gpu_tests_rel', + 'luci.chromium.try:android_optional_gpu_tests_rel', ], 'Automatically added optional GPU tests to run on CQ.')
diff --git a/gpu/skia_bindings/gles2_implementation_with_grcontext_support.cc b/gpu/skia_bindings/gles2_implementation_with_grcontext_support.cc index 581bd1f..7eb4aad 100644 --- a/gpu/skia_bindings/gles2_implementation_with_grcontext_support.cc +++ b/gpu/skia_bindings/gles2_implementation_with_grcontext_support.cc
@@ -54,6 +54,13 @@ using_gl_from_skia_ = false; } +void GLES2ImplementationWithGrContextSupport::EndRasterCHROMIUM() { + BaseClass::EndRasterCHROMIUM(); + // Assume that invoking the GLES2-backed version of the raster interface + // invalidates everything. + ResetGrContextIfNeeded(kALL_GrGLBackendState); +} + // Calls that invalidate kRenderTarget_GrGLBackendState void GLES2ImplementationWithGrContextSupport::BindFramebuffer( GLenum target, @@ -61,6 +68,50 @@ BaseClass::BindFramebuffer(target, framebuffer); ResetGrContextIfNeeded(kRenderTarget_GrGLBackendState); } +void GLES2ImplementationWithGrContextSupport::BindRenderbuffer( + GLenum target, + GLuint renderbuffer) { + BaseClass::BindRenderbuffer(target, renderbuffer); + ResetGrContextIfNeeded(kRenderTarget_GrGLBackendState); +} +void GLES2ImplementationWithGrContextSupport::DiscardFramebufferEXT( + GLenum target, + GLsizei count, + const GLenum* attachments) { + BaseClass::DiscardFramebufferEXT(target, count, attachments); + ResetGrContextIfNeeded(kRenderTarget_GrGLBackendState); +} +void GLES2ImplementationWithGrContextSupport::DeleteFramebuffers( + GLsizei n, + const GLuint* framebuffers) { + BaseClass::DeleteFramebuffers(n, framebuffers); + ResetGrContextIfNeeded(kRenderTarget_GrGLBackendState); +} +void GLES2ImplementationWithGrContextSupport::DeleteRenderbuffers( + GLsizei n, + const GLuint* renderbuffers) { + BaseClass::DeleteRenderbuffers(n, renderbuffers); + ResetGrContextIfNeeded(kRenderTarget_GrGLBackendState); +} +void GLES2ImplementationWithGrContextSupport::FramebufferTexture2D( + GLenum target, + GLenum attachment, + GLenum textarget, + GLuint texture, + GLint level) { + BaseClass::FramebufferTexture2D(target, attachment, textarget, texture, + level); + ResetGrContextIfNeeded(kRenderTarget_GrGLBackendState); +} +void GLES2ImplementationWithGrContextSupport::FramebufferTextureLayer( + GLenum target, + GLenum attachment, + GLuint texture, + GLint level, + GLint layer) { + BaseClass::FramebufferTextureLayer(target, attachment, texture, level, layer); + ResetGrContextIfNeeded(kRenderTarget_GrGLBackendState); +} // Calls that invalidate kTextureBinding_GrGLBackendState void GLES2ImplementationWithGrContextSupport::BindTexture(GLenum target,
diff --git a/gpu/skia_bindings/gles2_implementation_with_grcontext_support.h b/gpu/skia_bindings/gles2_implementation_with_grcontext_support.h index e22b302..853457c 100644 --- a/gpu/skia_bindings/gles2_implementation_with_grcontext_support.h +++ b/gpu/skia_bindings/gles2_implementation_with_grcontext_support.h
@@ -38,8 +38,27 @@ // These must be kept in sync with the invalidation defines in // GrGLGpu::onResetContext() + // Calls that invalidate arbitrary state + void EndRasterCHROMIUM() override; + // Calls that invalidate kRenderTarget_GrGLBackendState void BindFramebuffer(GLenum target, GLuint framebuffer) override; + void BindRenderbuffer(GLenum target, GLuint renderbuffer) override; + void DiscardFramebufferEXT(GLenum target, + GLsizei count, + const GLenum* attachments) override; + void DeleteFramebuffers(GLsizei n, const GLuint* framebuffers) override; + void DeleteRenderbuffers(GLsizei n, const GLuint* renderbuffers) override; + void FramebufferTexture2D(GLenum target, + GLenum attachment, + GLenum textarget, + GLuint texture, + GLint level) override; + void FramebufferTextureLayer(GLenum target, + GLenum attachment, + GLuint texture, + GLint level, + GLint layer) override; // Calls that invalidate kTextureBinding_GrGLBackendState // Note: Deleting a texture may affect the binding if the currently bound
diff --git a/infra/config/global/cr-buildbucket-dev.cfg b/infra/config/global/cr-buildbucket-dev.cfg index 7709fb8..8a4b867 100644 --- a/infra/config/global/cr-buildbucket-dev.cfg +++ b/infra/config/global/cr-buildbucket-dev.cfg
@@ -169,7 +169,6 @@ builders { mixins: "mac" name: "LUCI ios-simulator-cronet" } builders { mixins: "mac" name: "LUCI ios-simulator-eg" } builders { mixins: "mac" name: "LUCI ios-simulator-xcode-clang" } - builders { mixins: "mac" name: "LUCI mac_chromium_10.10_macviews" } builders { mixins: "mac" name: "LUCI mac_chromium_10.10_rel_ng" } builders { mixins: "mac" name: "LUCI mac_chromium_10.12_rel_ng" } builders { mixins: "mac" name: "LUCI mac_chromium_archive_rel_ng" } @@ -194,6 +193,7 @@ builders { mixins: "mac" name: "LUCI mac_nacl_sdk_build" } builders { mixins: "mac" name: "LUCI mac_optional_gpu_tests_rel" } builders { mixins: "mac" name: "LUCI mac_upload_clang" } + builders { mixins: "mac" name: "LUCI mac-views-rel" } builders { mixins: "win" name: "LUCI win10_chromium_x64_rel_ng" } builders { mixins: "win" name: "LUCI win10_chromium_x64_rel_ng_exp" }
diff --git a/infra/config/global/cr-buildbucket.cfg b/infra/config/global/cr-buildbucket.cfg index 4159c61d..961cded 100644 --- a/infra/config/global/cr-buildbucket.cfg +++ b/infra/config/global/cr-buildbucket.cfg
@@ -478,6 +478,9 @@ builders { name: "Deterministic Linux" mixins: "linux-ci" + recipe { + name: "swarming/deterministic_build" + } } builders { @@ -690,6 +693,13 @@ dimensions: "cores:8" } builders { + name: "Win10 Tests x64 (dbg)" + mixins: "win-ci" + dimensions: "os:Windows-10" + dimensions: "cpu:x86-64" + dimensions: "cores:8" + } + builders { name: "GPU FYI Win Builder" mixins: "win-gpu-fyi-ci" dimensions: "cores:8" @@ -928,7 +938,13 @@ builders { mixins: "linux-try" name: "linux_chromium_chromeos_variable" } builders { mixins: "linux-try" name: "linux_chromium_chromeos_variable_chrome" } builders { mixins: "linux-try" name: "linux_chromium_chromeos_variable_deflake" } - builders { mixins: "linux-try" name: "linux_chromium_clobber_deterministic" } + builders { + mixins: "linux-try" + name: "linux_chromium_clobber_deterministic", + recipe { + name: "swarming/deterministic_build" + } + } builders { mixins: "linux-try" name: "linux_chromium_clobber_rel_ng" } builders { mixins: "linux-try" name: "linux_chromium_compile_dbg_32_ng" } builders { mixins: "linux-try" name: "linux_chromium_compile_dbg_ng" } @@ -984,7 +1000,6 @@ builders { mixins: "mac-angle-try" name: "mac_angle_compile_dbg_ng" } builders { mixins: "mac-angle-try" name: "mac_angle_dbg_ng" } builders { mixins: "mac-angle-try" name: "mac_angle_rel_ng" } - builders { mixins: "mac-try" name: "mac_chromium_10.10_macviews" } builders { mixins: "mac-try" name: "mac_chromium_10.10_rel_ng" } builders { mixins: "mac-try" name: "mac_chromium_10.12_rel_ng" } builders { mixins: "mac-try" name: "mac_chromium_archive_rel_ng" } @@ -1009,7 +1024,9 @@ builders { mixins: "mac-try" name: "mac_nacl_sdk_build" } builders { mixins: "mac-optional-gpu-try" name: "mac_optional_gpu_tests_rel" } builders { mixins: "mac-try" name: "mac_upload_clang" } + builders { mixins: "mac-try" name: "mac-views-rel" } + builders { mixins: "win-try" name: "win10_chromium_x64_dbg_ng" } builders { mixins: "win-try" name: "win10_chromium_x64_rel_ng" } builders { mixins: "win-try" name: "win10_chromium_x64_rel_ng_exp" } builders { mixins: "win-try" name: "win8_chromium_gn_upload" }
diff --git a/infra/config/global/luci-milo-dev.cfg b/infra/config/global/luci-milo-dev.cfg index 992acd6f..9a37a68 100644 --- a/infra/config/global/luci-milo-dev.cfg +++ b/infra/config/global/luci-milo-dev.cfg
@@ -2169,7 +2169,7 @@ category: "cronet" } builders: { - name: "buildbot/chromium.fyi/Chromium Mac 10.10 MacViews" + name: "buildbot/chromium.fyi/mac-views-rel" category: "default" } builders: {
diff --git a/infra/config/global/luci-milo.cfg b/infra/config/global/luci-milo.cfg index c528e72..b12085e 100644 --- a/infra/config/global/luci-milo.cfg +++ b/infra/config/global/luci-milo.cfg
@@ -328,6 +328,11 @@ short_name: "7" } builders: { + name: "buildbucket/luci.chromium.ci/Win10 Tests x64 (dbg)" + category: "chromium.win|debug|tester" + short_name: "10" + } + builders: { name: "buildbot/chromium.win/WinMSVC64 (dbg)" category: "chromium.win|debug|tester" short_name: "mvc" @@ -771,6 +776,11 @@ short_name: "7" } builders: { + name: "buildbucket/luci.chromium.ci/Win10 Tests x64 (dbg)" + category: "debug|tester" + short_name: "10" + } + builders: { name: "buildbot/chromium.win/WinMSVC64 (dbg)" category: "debug|tester" short_name: "mvc" @@ -2750,7 +2760,7 @@ category: "cronet" } builders: { - name: "buildbot/chromium.fyi/Chromium Mac 10.10 MacViews" + name: "buildbot/chromium.fyi/mac-views-rel" category: "default" } builders: { @@ -4681,6 +4691,9 @@ name: "buildbot/tryserver.chromium.win/win-msvc-rel" } builders: { + name: "buildbucket/luci.chromium.try/win10_chromium_x64_dbg_ng" + } + builders: { name: "buildbot/tryserver.chromium.win/win10_chromium_x64_rel_ng" } builders: { @@ -5253,6 +5266,9 @@ name: "buildbucket/luci.chromium.try/mac_upload_clang" } builders: { + name: "buildbucket/luci.chromium.try/win10_chromium_x64_dbg_ng" + } + builders: { name: "buildbucket/luci.chromium.try/win10_chromium_x64_rel_ng" } builders: {
diff --git a/infra/config/global/luci-scheduler.cfg b/infra/config/global/luci-scheduler.cfg index c765d85..a29a534 100644 --- a/infra/config/global/luci-scheduler.cfg +++ b/infra/config/global/luci-scheduler.cfg
@@ -1119,3 +1119,14 @@ builder: "Win7 Tests (dbg)(1)" } } + +job { + id: "Win10 Tests x64 (dbg)" + # Triggered by "Win Builder (dbg)" + acl_sets: "triggered-by-parent-builders" + buildbucket: { + server: "cr-buildbucket.appspot.com" + bucket: "luci.chromium.ci" + builder: "Win10 Tests x64 (dbg)" + } +}
diff --git a/ios/chrome/app/strings/ios_strings.grd b/ios/chrome/app/strings/ios_strings.grd index 8ad49495..2b4a845 100644 --- a/ios/chrome/app/strings/ios_strings.grd +++ b/ios/chrome/app/strings/ios_strings.grd
@@ -1571,6 +1571,9 @@ <message name="IDS_IOS_TOOLS_MENU_HELP_URL" translateable="false"> https://support.google.com/chrome/?p=chrome_help&hl=[GRITLANGCODE] </message> + <message name="IDS_IOS_TOOLS_MENU_HISTORY" desc="The Tools menu item for opening the navigation history menu"> + History + </message> <message name="IDS_IOS_TOOLS_MENU_NEW_INCOGNITO_TAB" desc="The iOS menu item for opening a new incognito tab [Length: 15em] [iOS only]" meaning="Tools menu entry to create a new Incognito tab."> New Incognito Tab </message> @@ -1583,6 +1586,9 @@ <message name="IDS_IOS_TOOLS_MENU_RECENT_TABS" desc="The iOS menu item for opening the panel showing the recently closed tabs and the tabs from other devices. [Length: 15em]" meaning="[In Title case] [iOS only]"> Recent Tabs </message> + <message name="IDS_IOS_TOOLS_MENU_RELOAD" desc="The title of the button in the menu allowing the user to reload the page."> + Reload This Page + </message> <message name="IDS_IOS_TOOLS_MENU_REQUEST_DESKTOP_SITE" desc="The iOS menu item for requesting the desktop site [Length: 15em] [iOS only]"> Request Desktop Site </message> @@ -1595,6 +1601,9 @@ <message name="IDS_IOS_TOOLS_MENU_SHARE" desc="The iOS menu item for sharing the current URL [Length: 15em] [iOS only]"> Share... </message> + <message name="IDS_IOS_TOOLS_MENU_SITE_INFORMATION" desc="The iOS menu item for getting the site informations."> + Site Information + </message> <message name="IDS_IOS_TRANSLATE_SETTING" desc="Title for the view and option in Settings for Translate. [Length: 25em] [iOS only]"> Google Translate </message>
diff --git a/ios/chrome/browser/reading_list/reading_list_model_factory.cc b/ios/chrome/browser/reading_list/reading_list_model_factory.cc index a7771d9c..34d8c11 100644 --- a/ios/chrome/browser/reading_list/reading_list_model_factory.cc +++ b/ios/chrome/browser/reading_list/reading_list_model_factory.cc
@@ -16,6 +16,7 @@ #include "components/reading_list/core/reading_list_pref_names.h" #include "components/reading_list/core/reading_list_store.h" #include "components/sync/base/report_unrecoverable_error.h" +#include "components/sync/model_impl/client_tag_based_model_type_processor.h" #include "ios/chrome/browser/browser_state/browser_state_otr_helper.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/experimental_flags.h" @@ -63,12 +64,13 @@ syncer::OnceModelTypeStoreFactory store_factory = browser_sync::ProfileSyncService::GetModelTypeStoreFactory( chrome_browser_state->GetStatePath()); + auto change_processor = + std::make_unique<syncer::ClientTagBasedModelTypeProcessor>( + syncer::READING_LIST, + base::BindRepeating(&syncer::ReportUnrecoverableError, + ::GetChannel())); std::unique_ptr<ReadingListStore> store = std::make_unique<ReadingListStore>( - std::move(store_factory), - base::Bind(&syncer::ModelTypeChangeProcessor::Create, - base::BindRepeating(&syncer::ReportUnrecoverableError, - GetChannel()))); - + std::move(store_factory), std::move(change_processor)); std::unique_ptr<KeyedService> reading_list_model = std::make_unique<ReadingListModelImpl>( std::move(store), chrome_browser_state->GetPrefs(),
diff --git a/ios/chrome/browser/sync/ios_user_event_service_factory.cc b/ios/chrome/browser/sync/ios_user_event_service_factory.cc index 8a7370c..85fbc90 100644 --- a/ios/chrome/browser/sync/ios_user_event_service_factory.cc +++ b/ios/chrome/browser/sync/ios_user_event_service_factory.cc
@@ -12,6 +12,7 @@ #include "components/keyed_service/ios/browser_state_dependency_manager.h" #include "components/sync/base/model_type.h" #include "components/sync/base/report_unrecoverable_error.h" +#include "components/sync/model_impl/client_tag_based_model_type_processor.h" #include "components/sync/user_events/no_op_user_event_service.h" #include "components/sync/user_events/user_event_service_impl.h" #include "components/sync/user_events/user_event_sync_bridge.h" @@ -54,12 +55,11 @@ syncer::OnceModelTypeStoreFactory store_factory = browser_sync::ProfileSyncService::GetModelTypeStoreFactory( browser_state->GetStatePath()); - syncer::ModelTypeSyncBridge::ChangeProcessorFactory processor_factory = - base::BindRepeating(&syncer::ModelTypeChangeProcessor::Create, - base::BindRepeating(&syncer::ReportUnrecoverableError, - ::GetChannel())); auto bridge = std::make_unique<syncer::UserEventSyncBridge>( - std::move(store_factory), std::move(processor_factory), + std::move(store_factory), + std::make_unique<syncer::ClientTagBasedModelTypeProcessor>( + syncer::USER_EVENTS, /*dump_stack=*/base::BindRepeating( + &syncer::ReportUnrecoverableError, ::GetChannel())), sync_service->GetGlobalIdMapper()); return std::make_unique<syncer::UserEventServiceImpl>(sync_service, std::move(bridge));
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_coordinator.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_coordinator.mm index 8e6d9bb..6f2da98 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_coordinator.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_coordinator.mm
@@ -114,8 +114,14 @@ ios::ChromeBrowserState::FromBrowserState(self.browserState)->GetPrefs(); bool contentSuggestionsEnabled = prefs->GetBoolean(prefs::kArticlesForYouEnabled); + bool contentSuggestionsVisible = + prefs->GetBoolean(ntp_snippets::prefs::kArticlesListVisible); if (contentSuggestionsEnabled) { - ntp_home::RecordNTPImpression(ntp_home::REMOTE_SUGGESTIONS); + if (contentSuggestionsVisible) { + ntp_home::RecordNTPImpression(ntp_home::REMOTE_SUGGESTIONS); + } else { + ntp_home::RecordNTPImpression(ntp_home::REMOTE_COLLAPSED); + } } else { ntp_home::RecordNTPImpression(ntp_home::LOCAL_SUGGESTIONS); }
diff --git a/ios/chrome/browser/ui/content_suggestions/ntp_home_constant.h b/ios/chrome/browser/ui/content_suggestions/ntp_home_constant.h index c7f22f2..8a9594f6 100644 --- a/ios/chrome/browser/ui/content_suggestions/ntp_home_constant.h +++ b/ios/chrome/browser/ui/content_suggestions/ntp_home_constant.h
@@ -26,6 +26,8 @@ LOCAL_SUGGESTIONS = 0, // The NTP displays local and remote suggestions. REMOTE_SUGGESTIONS = 1, + // The NTP displays local suggestions and remote suggestions are collapsed. + REMOTE_COLLAPSED = 2, // Add new enum above COUNT. COUNT };
diff --git a/ios/chrome/browser/ui/download/download_manager_coordinator.mm b/ios/chrome/browser/ui/download/download_manager_coordinator.mm index 301eade..fbb490cb 100644 --- a/ios/chrome/browser/ui/download/download_manager_coordinator.mm +++ b/ios/chrome/browser/ui/download/download_manager_coordinator.mm
@@ -93,6 +93,7 @@ - (void)downloadManagerTabHelper:(nonnull DownloadManagerTabHelper*)tabHelper didCreateDownload:(nonnull web::DownloadTask*)download webStateIsVisible:(BOOL)webStateIsVisible { + base::RecordAction(base::UserMetricsAction("MobileDownloadFileUIShown")); if (!webStateIsVisible) { // Do nothing if a background Tab requested download UI presentation. return;
diff --git a/ios/chrome/browser/ui/download/download_manager_coordinator_unittest.mm b/ios/chrome/browser/ui/download/download_manager_coordinator_unittest.mm index 3b735d0..392ff0f 100644 --- a/ios/chrome/browser/ui/download/download_manager_coordinator_unittest.mm +++ b/ios/chrome/browser/ui/download/download_manager_coordinator_unittest.mm
@@ -157,6 +157,7 @@ // animation. TEST_F(DownloadManagerCoordinatorTest, DelegateCreatedDownload) { auto task = CreateTestTask(); + ASSERT_EQ(0, user_action_tester_.GetActionCount("MobileDownloadFileUIShown")); [coordinator_ downloadManagerTabHelper:&tab_helper_ didCreateDownload:task.get() webStateIsVisible:YES]; @@ -180,6 +181,9 @@ EXPECT_FALSE(viewController.actionButton.hidden); EXPECT_NSEQ(@"Download", [viewController.actionButton titleForState:UIControlStateNormal]); + + // Verify that UMA action was logged. + EXPECT_EQ(1, user_action_tester_.GetActionCount("MobileDownloadFileUIShown")); } // Tests calling downloadManagerTabHelper:didCreateDownload:webStateIsVisible:
diff --git a/ios/chrome/browser/ui/ntp/BUILD.gn b/ios/chrome/browser/ui/ntp/BUILD.gn index dfda704..b77dac3 100644 --- a/ios/chrome/browser/ui/ntp/BUILD.gn +++ b/ios/chrome/browser/ui/ntp/BUILD.gn
@@ -265,12 +265,14 @@ "//ios/chrome/browser/ui/favicon:favicon_ui", "//ios/chrome/browser/web_state_list:test_support", "//ios/chrome/browser/web_state_list:web_state_list", + "//ios/chrome/common/app_group", "//ios/chrome/test:test_support", "//ios/public/provider/chrome/browser/images", "//ios/web/public/test", "//testing/gtest", "//third_party/ocmock", "//ui/base", + "//ui/base:test_support", "//url", ] }
diff --git a/ios/chrome/browser/ui/ntp/ntp_tile.h b/ios/chrome/browser/ui/ntp/ntp_tile.h index b65e609..ffbee121 100644 --- a/ios/chrome/browser/ui/ntp/ntp_tile.h +++ b/ios/chrome/browser/ui/ntp/ntp_tile.h
@@ -26,9 +26,6 @@ @property(assign, atomic) BOOL fallbackIsDefaultColor; // The monogram to use on the fallback icon. @property(strong, atomic) NSString* fallbackMonogram; -// Whether the favicon has been fetched for the most visited site. This can be -// YES with no fallback values or favicon path. -@property(assign, atomic) BOOL faviconFetched; // Index of the site's position in the most visited list. @property(assign, atomic) NSUInteger position; @@ -42,7 +39,6 @@ fallbackBackgroundColor:(UIColor*)fallbackTextColor fallbackIsDefaultColor:(BOOL)fallbackIsDefaultColor fallbackMonogram:(NSString*)fallbackMonogram - faviconFetched:(BOOL)faviconFetched position:(NSUInteger)position; @end
diff --git a/ios/chrome/browser/ui/ntp/ntp_tile.mm b/ios/chrome/browser/ui/ntp/ntp_tile.mm index f2dc571..0853078 100644 --- a/ios/chrome/browser/ui/ntp/ntp_tile.mm +++ b/ios/chrome/browser/ui/ntp/ntp_tile.mm
@@ -29,7 +29,6 @@ @synthesize fallbackBackgroundColor = _fallbackBackgroundColor; @synthesize fallbackIsDefaultColor = _fallbackIsDefaultColor; @synthesize fallbackMonogram = _fallbackMonogram; -@synthesize faviconFetched = _faviconFetched; @synthesize position = _position; - (instancetype)initWithTitle:(NSString*)title @@ -51,7 +50,6 @@ fallbackBackgroundColor:(UIColor*)fallbackBackgroundColor fallbackIsDefaultColor:(BOOL)fallbackIsDefaultColor fallbackMonogram:(NSString*)fallbackMonogram - faviconFetched:(BOOL)faviconFetched position:(NSUInteger)position { self = [super init]; if (self) { @@ -62,7 +60,6 @@ _fallbackBackgroundColor = fallbackBackgroundColor; _fallbackIsDefaultColor = fallbackIsDefaultColor; _fallbackMonogram = fallbackMonogram; - _faviconFetched = faviconFetched; _position = position; } return self; @@ -79,7 +76,6 @@ fallbackIsDefaultColor:[aDecoder decodeBoolForKey:kFallbackIsDefaultColorKey] fallbackMonogram:[aDecoder decodeObjectForKey:kFallbackMonogram] - faviconFetched:[aDecoder decodeBoolForKey:kFaviconFetched] position:[[aDecoder decodeObjectForKey:kPosition] unsignedIntegerValue]]; } @@ -94,7 +90,6 @@ [aCoder encodeBool:self.fallbackIsDefaultColor forKey:kFallbackIsDefaultColorKey]; [aCoder encodeObject:self.fallbackMonogram forKey:kFallbackMonogram]; - [aCoder encodeBool:self.faviconFetched forKey:kFaviconFetched]; [aCoder encodeObject:[NSNumber numberWithUnsignedInteger:self.position] forKey:kPosition]; }
diff --git a/ios/chrome/browser/ui/ntp/ntp_tile_saver.h b/ios/chrome/browser/ui/ntp/ntp_tile_saver.h index fdad542..c07d6feb 100644 --- a/ios/chrome/browser/ui/ntp/ntp_tile_saver.h +++ b/ios/chrome/browser/ui/ntp/ntp_tile_saver.h
@@ -14,25 +14,23 @@ // These functions are used to save the ntp tiles (favicon and name) offline for // the use of the content widget. The most visited info and icon fallback data -// are saved to userdefaults. The favicons are saved to a shared folder. Because -// the favicons are fetched asynchronously, they are first saved in a temporary -// folder which replaces the current favicons when all are fetched. +// are saved to userdefaults. The favicons are saved to a shared directory. namespace ntp_tile_saver { -// Saves the most visited sites to disk with icons in |favicons_folder|, using -// |favicon_fetcher| to get the favicons. +// Saves the most visited sites to disk with icons in |favicons_directory|, +// using |favicon_fetcher| to get the favicons. void SaveMostVisitedToDisk(const ntp_tiles::NTPTilesVector& most_visited_data, FaviconAttributesProvider* favicon_provider, - NSURL* favicons_folder); + NSURL* favicons_directory); // Read the current saved most visited sites from disk. NSDictionary* ReadSavedMostVisited(); // Fetches the updated favicon for a single site and saves it in -// |favicons_folder|. +// |favicons_directory|. void UpdateSingleFavicon(const GURL& site_url, FaviconAttributesProvider* favicon_provider, - NSURL* favicons_folder); + NSURL* favicons_directory); } // namespace ntp_tile_saver
diff --git a/ios/chrome/browser/ui/ntp/ntp_tile_saver.mm b/ios/chrome/browser/ui/ntp/ntp_tile_saver.mm index 986c385a..7ea7a46 100644 --- a/ios/chrome/browser/ui/ntp/ntp_tile_saver.mm +++ b/ios/chrome/browser/ui/ntp/ntp_tile_saver.mm
@@ -27,17 +27,10 @@ // Write the |most_visited_sites| to disk. void WriteSavedMostVisited(NSDictionary<NSURL*, NTPTile*>* most_visited_sites); -// Returns the path for the temporary favicon folder. -NSURL* GetTemporaryFaviconFolderPath(); - -// Replaces the current saved favicons at |favicons_folder| by the contents of -// the tmp folder. -void ReplaceSavedFavicons(NSURL* favicons_folder); - // Checks if every site in |tiles| has had its favicons fetched. If so, writes -// the info to disk, saving the favicons to |favicons_folder|. +// the info to disk, saving the favicons to |favicons_directory|. void WriteToDiskIfComplete(NSDictionary<NSURL*, NTPTile*>* tiles, - NSURL* favicons_folder); + NSURL* favicons_directory); // Gets a name for the favicon file. NSString* GetFaviconFileName(const GURL& url); @@ -46,77 +39,47 @@ // |tile|. void WriteSingleUpdatedTileToDisk(NTPTile* tile); -// Empty the temporary favicon folder. -void ClearTemporaryFaviconFolder(); - // Get the favicons using |favicon_provider| and writes them to disk. void GetFaviconsAndSave(const ntp_tiles::NTPTilesVector& most_visited_data, FaviconAttributesProvider* favicon_provider, - NSURL* favicons_folder); + NSURL* favicons_directory); + +// Updates the list of tiles that must be displayed in the content suggestion +// widget. +void UpdateTileList(const ntp_tiles::NTPTilesVector& most_visited_data); + +// Deletes icons contained in |favicons_directory| and corresponding to no URL +// in |most_visited_data|. +void ClearOutdatedIcons(const ntp_tiles::NTPTilesVector& most_visited_data, + NSURL* favicons_directory); } // namespace ntp_tile_saver namespace ntp_tile_saver { -NSURL* GetTemporaryFaviconFolderPath() { - return [[NSURL fileURLWithPath:NSTemporaryDirectory()] - URLByAppendingPathComponent:@"tmpFaviconFolder"]; -} - -void ReplaceSavedFavicons(NSURL* favicons_folder) { - base::AssertBlockingAllowed(); - if ([[NSFileManager defaultManager] - fileExistsAtPath:[favicons_folder path]]) { - [[NSFileManager defaultManager] removeItemAtURL:favicons_folder error:nil]; - } - - if ([[NSFileManager defaultManager] - fileExistsAtPath:[GetTemporaryFaviconFolderPath() path]]) { - [[NSFileManager defaultManager] - createDirectoryAtURL:favicons_folder - .URLByDeletingLastPathComponent - withIntermediateDirectories:YES - attributes:nil - error:nil]; - - [[NSFileManager defaultManager] - moveItemAtURL:GetTemporaryFaviconFolderPath() - toURL:favicons_folder - error:nil]; - } -} - -void WriteToDiskIfComplete(NSDictionary<NSURL*, NTPTile*>* tiles, - NSURL* favicons_folder) { - for (NSURL* siteURL : tiles) { - NTPTile* tile = [tiles objectForKey:siteURL]; - if (!tile.faviconFetched) { - return; +void UpdateTileList(const ntp_tiles::NTPTilesVector& most_visited_data) { + NSMutableDictionary<NSURL*, NTPTile*>* tiles = + [[NSMutableDictionary alloc] init]; + NSDictionary<NSURL*, NTPTile*>* old_tiles = ReadSavedMostVisited(); + for (size_t i = 0; i < most_visited_data.size(); i++) { + const ntp_tiles::NTPTile& ntp_tile = most_visited_data[i]; + NSURL* ns_url = net::NSURLWithGURL(ntp_tile.url); + NTPTile* tile = + [[NTPTile alloc] initWithTitle:base::SysUTF16ToNSString(ntp_tile.title) + URL:ns_url + position:i]; + tile.faviconFileName = GetFaviconFileName(ntp_tile.url); + NTPTile* old_tile = [old_tiles objectForKey:ns_url]; + if (old_tile) { + // Keep fallback data. + tile.fallbackMonogram = old_tile.fallbackMonogram; + tile.fallbackTextColor = old_tile.fallbackTextColor; + tile.fallbackIsDefaultColor = old_tile.fallbackIsDefaultColor; + tile.fallbackBackgroundColor = old_tile.fallbackBackgroundColor; } - // Any fetched tile must have a file name or a fallback monogram. - DCHECK(tile.faviconFileName || tile.fallbackMonogram); + [tiles setObject:tile forKey:tile.URL]; } - - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND}, - base::BindBlockArc(^{ - ReplaceSavedFavicons(favicons_folder); - }), - base::BindBlockArc(^{ - WriteSavedMostVisited(tiles); - })); -} - -void ClearTemporaryFaviconFolder() { - base::AssertBlockingAllowed(); - NSURL* tmpFaviconURL = GetTemporaryFaviconFolderPath(); - if ([[NSFileManager defaultManager] fileExistsAtPath:[tmpFaviconURL path]]) { - [[NSFileManager defaultManager] removeItemAtURL:tmpFaviconURL error:nil]; - } - [[NSFileManager defaultManager] createDirectoryAtPath:[tmpFaviconURL path] - withIntermediateDirectories:YES - attributes:nil - error:nil]; + WriteSavedMostVisited(tiles); } NSString* GetFaviconFileName(const GURL& url) { @@ -126,101 +89,62 @@ void GetFaviconsAndSave(const ntp_tiles::NTPTilesVector& most_visited_data, FaviconAttributesProvider* favicon_provider, - NSURL* favicons_folder) { - NSMutableDictionary<NSURL*, NTPTile*>* tiles = - [[NSMutableDictionary alloc] init]; - - // If there are 0 sites to display, the for loop below will not be entered. - // Write the updated empty list of sites to disk before returning. - if (most_visited_data.empty()) { - WriteToDiskIfComplete(tiles, favicons_folder); - return; + NSURL* favicons_directory) { + for (size_t i = 0; i < most_visited_data.size(); i++) { + const GURL& gurl = most_visited_data[i].url; + UpdateSingleFavicon(gurl, favicon_provider, favicons_directory); } +} - // For each site, get the favicon. If it is returned, write it to the - // favicon tmp folder. If a fallback value is returned, update the tile - // info. Calls WriteToDiskIfComplete after each callback execution. All the - // sites are added first to the list so that the WriteToDiskIfComplete - // command is not passed an incomplete list. +void ClearOutdatedIcons(const ntp_tiles::NTPTilesVector& most_visited_data, + NSURL* favicons_directory) { + NSMutableSet<NSString*>* allowed_files_name = [[NSMutableSet alloc] init]; for (size_t i = 0; i < most_visited_data.size(); i++) { const ntp_tiles::NTPTile& ntp_tile = most_visited_data[i]; - NTPTile* tile = - [[NTPTile alloc] initWithTitle:base::SysUTF16ToNSString(ntp_tile.title) - URL:net::NSURLWithGURL(ntp_tile.url) - position:i]; - [tiles setObject:tile forKey:tile.URL]; + NSString* favicon_file_name = GetFaviconFileName(ntp_tile.url); + [allowed_files_name addObject:favicon_file_name]; } - - NSURL* tmpFaviconURL = GetTemporaryFaviconFolderPath(); - for (NTPTile* tile : [tiles objectEnumerator]) { - const GURL& gurl = net::GURLWithNSURL(tile.URL); - NSString* faviconFileName = GetFaviconFileName(gurl); - NSURL* fileURL = - [tmpFaviconURL URLByAppendingPathComponent:faviconFileName]; - - void (^faviconAttributesBlock)(FaviconAttributes*) = - ^(FaviconAttributes* attributes) { - if (attributes.faviconImage) { - NSData* imageData = - UIImagePNGRepresentation(attributes.faviconImage); - - base::OnceCallback<BOOL()> writeImage = base::BindBlockArc(^BOOL() { - return [imageData writeToURL:fileURL atomically:YES]; - }); - - base::OnceCallback<void(BOOL)> updateTile = - base::BindBlockArc(^(BOOL imageWriteSuccess) { - if (imageWriteSuccess) { - // If saving the image is not possible, the best thing to do - // is to keep the previous tiles. - tile.faviconFetched = YES; - tile.faviconFileName = faviconFileName; - WriteToDiskIfComplete(tiles, favicons_folder); - } - }); - - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND}, - std::move(writeImage), std::move(updateTile)); - } else { - tile.faviconFetched = YES; - tile.fallbackTextColor = attributes.textColor; - tile.fallbackBackgroundColor = attributes.backgroundColor; - tile.fallbackIsDefaultColor = attributes.defaultBackgroundColor; - tile.fallbackMonogram = attributes.monogramString; - DCHECK(tile.fallbackMonogram && tile.fallbackTextColor && - tile.fallbackBackgroundColor); - WriteToDiskIfComplete(tiles, favicons_folder); - } - }; - // The cache is not used here as it is simply a way to have a synchronous - // immediate return. In this case it is unnecessary. - - [favicon_provider fetchFaviconAttributesForURL:gurl - completion:faviconAttributesBlock]; + [[NSFileManager defaultManager] createDirectoryAtURL:favicons_directory + withIntermediateDirectories:YES + attributes:nil + error:nil]; + NSArray<NSURL*>* existing_files = [[NSFileManager defaultManager] + contentsOfDirectoryAtURL:favicons_directory + includingPropertiesForKeys:nil + options:0 + error:nil]; + for (NSURL* file : existing_files) { + if (![allowed_files_name containsObject:[file lastPathComponent]]) { + [[NSFileManager defaultManager] removeItemAtURL:file error:nil]; + } } } void SaveMostVisitedToDisk(const ntp_tiles::NTPTilesVector& most_visited_data, FaviconAttributesProvider* favicon_provider, - NSURL* favicons_folder) { - if (favicons_folder == nil) { + NSURL* favicons_directory) { + if (favicons_directory == nil) { return; } + UpdateTileList(most_visited_data); base::PostTaskWithTraitsAndReply( FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND}, - base::BindOnce(&ClearTemporaryFaviconFolder), + base::BindOnce(&ClearOutdatedIcons, most_visited_data, + favicons_directory), base::Bind(base::BindBlockArc( ^(const ntp_tiles::NTPTilesVector& most_visited_data) { GetFaviconsAndSave(most_visited_data, favicon_provider, - favicons_folder); + favicons_directory); }), most_visited_data)); } void WriteSingleUpdatedTileToDisk(NTPTile* tile) { NSMutableDictionary* tiles = [ReadSavedMostVisited() mutableCopy]; + if (![tiles objectForKey:tile.URL]) { + return; + } [tiles setObject:tile forKey:tile.URL]; WriteSavedMostVisited(tiles); } @@ -244,79 +168,57 @@ void UpdateSingleFavicon(const GURL& site_url, FaviconAttributesProvider* favicon_provider, - NSURL* favicons_folder) { - NSDictionary* tiles = ReadSavedMostVisited(); - + NSURL* favicons_directory) { NSURL* siteNSURL = net::NSURLWithGURL(site_url); - NTPTile* tile = [tiles objectForKey:siteNSURL]; - if (!tile) { - return; - } - // Remove existing favicon info - tile.fallbackTextColor = nil; - tile.fallbackBackgroundColor = nil; - tile.faviconFetched = NO; - NSString* previousFaviconFileName = tile.faviconFileName; - tile.faviconFileName = nil; - - // Fetch favicon and update saved defaults. - NSString* faviconFileName = GetFaviconFileName(site_url); - NSURL* fileURL = - [favicons_folder URLByAppendingPathComponent:faviconFileName]; - NSURL* previousFileURL = - previousFaviconFileName - ? [favicons_folder - URLByAppendingPathComponent:previousFaviconFileName] - : nil; void (^faviconAttributesBlock)(FaviconAttributes*) = ^(FaviconAttributes* attributes) { if (attributes.faviconImage) { - tile.faviconFetched = YES; + // Update the available icon. + // If we have a fallback icon, do not remove it. The favicon will have + // priority, and should anything happen to the image, the fallback + // icon will be a nicer fallback. + NSString* faviconFileName = + GetFaviconFileName(net::GURLWithNSURL(siteNSURL)); + NSURL* fileURL = + [favicons_directory URLByAppendingPathComponent:faviconFileName]; NSData* imageData = UIImagePNGRepresentation(attributes.faviconImage); - base::OnceCallback<BOOL()> writeImage = base::BindBlockArc(^BOOL { + base::OnceCallback<void()> writeImage = base::BindBlockArc(^{ base::AssertBlockingAllowed(); - [[NSFileManager defaultManager] removeItemAtURL:previousFileURL - error:nil]; - return [imageData writeToURL:fileURL atomically:YES]; + [imageData writeToURL:fileURL atomically:YES]; }); - base::OnceCallback<void(BOOL)> updateTile = - base::BindBlockArc(^(BOOL imageWriteSuccess) { - if (imageWriteSuccess) { - tile.faviconFileName = faviconFileName; - } - WriteSingleUpdatedTileToDisk(tile); - - }); - - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskWithTraits( FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND}, - std::move(writeImage), std::move(updateTile)); + std::move(writeImage)); } else { - tile.faviconFetched = YES; + NSDictionary* tiles = ReadSavedMostVisited(); + NTPTile* tile = [tiles objectForKey:siteNSURL]; + if (!tile) { + return; + } tile.fallbackTextColor = attributes.textColor; tile.fallbackBackgroundColor = attributes.backgroundColor; tile.fallbackIsDefaultColor = attributes.defaultBackgroundColor; tile.fallbackMonogram = attributes.monogramString; - + WriteSingleUpdatedTileToDisk(tile); + // Favicon is outdated. Delete it. + NSString* faviconFileName = + GetFaviconFileName(net::GURLWithNSURL(siteNSURL)); + NSURL* fileURL = + [favicons_directory URLByAppendingPathComponent:faviconFileName]; base::OnceCallback<void()> removeImage = base::BindBlockArc(^{ base::AssertBlockingAllowed(); - [[NSFileManager defaultManager] removeItemAtURL:previousFileURL - error:nil]; + [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil]; }); - base::PostTaskWithTraitsAndReply( + base::PostTaskWithTraits( FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND}, - std::move(removeImage), base::BindBlockArc(^{ - WriteSingleUpdatedTileToDisk(tile); - })); + std::move(removeImage)); } }; - // The cache is not used here as it is simply a way to have a synchronous - // immediate return. In this case it is unnecessary. [favicon_provider fetchFaviconAttributesForURL:site_url completion:faviconAttributesBlock]; }
diff --git a/ios/chrome/browser/ui/ntp/ntp_tile_saver_unittest.mm b/ios/chrome/browser/ui/ntp/ntp_tile_saver_unittest.mm index de859d7..93587f3 100644 --- a/ios/chrome/browser/ui/ntp/ntp_tile_saver_unittest.mm +++ b/ios/chrome/browser/ui/ntp/ntp_tile_saver_unittest.mm
@@ -11,10 +11,12 @@ #import "ios/chrome/browser/ui/favicon/favicon_attributes.h" #import "ios/chrome/browser/ui/favicon/favicon_attributes_provider.h" #import "ios/chrome/browser/ui/ntp/ntp_tile.h" +#include "ios/chrome/common/app_group/app_group_constants.h" #import "ios/chrome/test/block_cleanup_test.h" #import "net/base/mac/url_conversions.h" #import "testing/gtest_mac.h" #import "third_party/ocmock/OCMock/OCMock.h" +#include "ui/base/test/ios/ui_image_test_utils.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." @@ -27,45 +29,54 @@ void SetUp() override { BlockCleanupTest::SetUp(); if ([[NSFileManager defaultManager] - fileExistsAtPath:[testFaviconDirectory() path]]) { - [[NSFileManager defaultManager] removeItemAtURL:testFaviconDirectory() + fileExistsAtPath:[TestFaviconDirectory() path]]) { + [[NSFileManager defaultManager] removeItemAtURL:TestFaviconDirectory() error:nil]; } + CreateMockImage([UIColor blackColor]); + NSUserDefaults* sharedDefaults = app_group::GetGroupUserDefaults(); + [sharedDefaults removeObjectForKey:app_group::kSuggestedItems]; } void TearDown() override { if ([[NSFileManager defaultManager] - fileExistsAtPath:[testFaviconDirectory() path]]) { - [[NSFileManager defaultManager] removeItemAtURL:testFaviconDirectory() + fileExistsAtPath:[TestFaviconDirectory() path]]) { + [[NSFileManager defaultManager] removeItemAtURL:TestFaviconDirectory() error:nil]; } + NSUserDefaults* sharedDefaults = app_group::GetGroupUserDefaults(); + [sharedDefaults removeObjectForKey:app_group::kSuggestedItems]; BlockCleanupTest::TearDown(); } - NSURL* testFaviconDirectory() { + UIImage* CreateMockImage(UIColor* color) { + mock_image_ = ui::test::uiimage_utils::UIImageWithSizeAndSolidColor( + CGSizeMake(10, 10), color); + return mock_image_; + } + + NSURL* TestFaviconDirectory() { return [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] - firstObject] URLByAppendingPathComponent:@"testFaviconFolder"]; + firstObject] URLByAppendingPathComponent:@"testFaviconDirectory"]; } - void setupMockCallback(id mock, - std::set<GURL> imageURLs, - std::set<GURL> fallbackURLs) { + void SetupMockCallback(id mock, + std::set<GURL> image_urls, + std::set<GURL> fallback_urls) { OCMStub([[mock ignoringNonObjectArgs] fetchFaviconAttributesForURL:GURL() completion:[OCMArg isNotNil]]) .andDo(^(NSInvocation* invocation) { GURL* urltest; [invocation getArgument:&urltest atIndex:2]; - if (imageURLs.find(GURL(*urltest)) != imageURLs.end()) { + if (image_urls.find(GURL(*urltest)) != image_urls.end()) { __unsafe_unretained void (^callback)(id); [invocation getArgument:&callback atIndex:3]; - UIGraphicsBeginImageContext(CGSizeMake(10, 10)); - UIImage* image = UIGraphicsGetImageFromCurrentImageContext(); - UIGraphicsEndImageContext(); - callback([FaviconAttributes attributesWithImage:image]); - } else if (fallbackURLs.find(GURL(*urltest)) != fallbackURLs.end()) { + callback([FaviconAttributes attributesWithImage:mock_image_]); + } else if (fallback_urls.find(GURL(*urltest)) != + fallback_urls.end()) { __unsafe_unretained void (^callback)(id); [invocation getArgument:&callback atIndex:3]; callback([FaviconAttributes @@ -77,148 +88,322 @@ }); } - void verifyWithImage(NTPTile* tile, - NSString* expectedTitle, - NSURL* expectedURL) { + // Checks that |tile| has an image and no fallback data. + // Checks that |tile| title and url match |expected_title| and + // |expected_url|. + // Checks that the file pointed by |tile| match |mock_image_|. + void VerifyWithImage(NTPTile* tile, + NSString* expected_title, + NSURL* expected_url) { EXPECT_NSNE(tile, nil); - EXPECT_NSEQ(tile.title, expectedTitle); - EXPECT_NSEQ(tile.URL, expectedURL); - EXPECT_TRUE(tile.faviconFetched); + EXPECT_NSEQ(tile.title, expected_title); + EXPECT_NSEQ(tile.URL, expected_url); EXPECT_NSNE(tile.faviconFileName, nil); EXPECT_NSEQ(tile.fallbackTextColor, nil); EXPECT_NSEQ(tile.fallbackBackgroundColor, nil); EXPECT_TRUE([[NSFileManager defaultManager] - fileExistsAtPath:[[testFaviconDirectory() + fileExistsAtPath:[[TestFaviconDirectory() + URLByAppendingPathComponent:tile.faviconFileName] + path]]); + UIImage* stored_image = [UIImage + imageWithContentsOfFile: + [[TestFaviconDirectory() + URLByAppendingPathComponent:tile.faviconFileName] path]]; + EXPECT_NSEQ(UIImagePNGRepresentation(stored_image), + UIImagePNGRepresentation(mock_image_)); + } + + // Checks that |tile| has fallback data. + // Checks that |tile| title and url match |expected_title| and + // |expected_url|. + // Checks that the file pointed by |tile| does not exist. + void VerifyWithFallback(NTPTile* tile, + NSString* expected_title, + NSURL* expected_url) { + EXPECT_NSNE(tile, nil); + EXPECT_NSEQ(tile.title, expected_title); + EXPECT_NSEQ(tile.URL, expected_url); + EXPECT_NSNE(tile.faviconFileName, nil); + EXPECT_NSEQ(tile.fallbackTextColor, UIColor.whiteColor); + EXPECT_NSEQ(tile.fallbackBackgroundColor, UIColor.blueColor); + EXPECT_EQ(tile.fallbackIsDefaultColor, NO); + EXPECT_FALSE([[NSFileManager defaultManager] + fileExistsAtPath:[[TestFaviconDirectory() URLByAppendingPathComponent:tile.faviconFileName] path]]); } - void verifyWithFallback(NTPTile* tile, - NSString* expectedTitle, - NSURL* expectedURL) { + // Checks that |tile| has an image and fallback data. + // Checks that |tile| title and url match |expected_title| and + // |expected_url|. + // Checks that the file pointed by |tile| match |mock_image_|. + void VerifyWithFallbackAndImage(NTPTile* tile, + NSString* expected_title, + NSURL* expected_url) { EXPECT_NSNE(tile, nil); - EXPECT_NSEQ(tile.title, expectedTitle); - EXPECT_NSEQ(tile.URL, expectedURL); - EXPECT_TRUE(tile.faviconFetched); - EXPECT_NSEQ(tile.faviconFileName, nil); + EXPECT_NSEQ(tile.title, expected_title); + EXPECT_NSEQ(tile.URL, expected_url); + EXPECT_NSNE(tile.faviconFileName, nil); EXPECT_NSEQ(tile.fallbackTextColor, UIColor.whiteColor); EXPECT_NSEQ(tile.fallbackBackgroundColor, UIColor.blueColor); EXPECT_EQ(tile.fallbackIsDefaultColor, NO); + EXPECT_TRUE([[NSFileManager defaultManager] + fileExistsAtPath:[[TestFaviconDirectory() + URLByAppendingPathComponent:tile.faviconFileName] + path]]); + UIImage* stored_image = [UIImage + imageWithContentsOfFile: + [[TestFaviconDirectory() + URLByAppendingPathComponent:tile.faviconFileName] path]]; + EXPECT_NSEQ(UIImagePNGRepresentation(stored_image), + UIImagePNGRepresentation(mock_image_)); } protected: base::test::ScopedTaskEnvironment scoped_task_evironment_; + UIImage* mock_image_; }; TEST_F(NTPTileSaverControllerTest, SaveMostVisitedToDisk) { - ntp_tiles::NTPTile imageTile = ntp_tiles::NTPTile(); - imageTile.title = base::ASCIIToUTF16("Title"); - imageTile.url = GURL("http://image.com"); + ntp_tiles::NTPTile image_tile = ntp_tiles::NTPTile(); + image_tile.title = base::ASCIIToUTF16("Title"); + image_tile.url = GURL("http://image.com"); - ntp_tiles::NTPTile fallbackTile = ntp_tiles::NTPTile(); - fallbackTile.title = base::ASCIIToUTF16("Title"); - fallbackTile.url = GURL("http://fallback.com"); + ntp_tiles::NTPTile fallback_tile = ntp_tiles::NTPTile(); + fallback_tile.title = base::ASCIIToUTF16("Title"); + fallback_tile.url = GURL("http://fallback.com"); - id mockFaviconFetcher = OCMClassMock([FaviconAttributesProvider class]); - setupMockCallback(mockFaviconFetcher, {imageTile.url}, {fallbackTile.url}); + id mock_favicon_fetcher = OCMClassMock([FaviconAttributesProvider class]); + SetupMockCallback(mock_favicon_fetcher, {image_tile.url}, + {fallback_tile.url}); ntp_tiles::NTPTilesVector tiles = { - fallbackTile, // NTP tile with fallback data - imageTile, // NTP tile with favicon + fallback_tile, // NTP tile with fallback data + image_tile, // NTP tile with favicon }; - ntp_tile_saver::SaveMostVisitedToDisk(tiles, mockFaviconFetcher, - testFaviconDirectory()); + ntp_tile_saver::SaveMostVisitedToDisk(tiles, mock_favicon_fetcher, + TestFaviconDirectory()); // Wait for all asynchronous tasks to complete. scoped_task_evironment_.RunUntilIdle(); // Read most visited from disk. - NSDictionary<NSURL*, NTPTile*>* savedTiles = + NSDictionary<NSURL*, NTPTile*>* saved_tiles = ntp_tile_saver::ReadSavedMostVisited(); - EXPECT_EQ(savedTiles.count, 2U); + EXPECT_EQ(saved_tiles.count, 2U); - NSString* fallbackTitle = base::SysUTF16ToNSString(fallbackTile.title); - NSURL* fallbackURL = net::NSURLWithGURL(fallbackTile.url); - NTPTile* fallbackSavedTile = [savedTiles objectForKey:fallbackURL]; - verifyWithFallback(fallbackSavedTile, fallbackTitle, fallbackURL); + NSString* fallback_title = base::SysUTF16ToNSString(fallback_tile.title); + NSURL* fallback_url = net::NSURLWithGURL(fallback_tile.url); + NTPTile* fallback_saved_tile = [saved_tiles objectForKey:fallback_url]; + VerifyWithFallback(fallback_saved_tile, fallback_title, fallback_url); - NSString* imageTitle = base::SysUTF16ToNSString(imageTile.title); - NSURL* imageURL = net::NSURLWithGURL(imageTile.url); - NTPTile* imageSavedTile = [savedTiles objectForKey:imageURL]; - verifyWithImage(imageSavedTile, imageTitle, imageURL); + NSString* image_title = base::SysUTF16ToNSString(image_tile.title); + NSURL* image_url = net::NSURLWithGURL(image_tile.url); + NTPTile* image_saved_tile = [saved_tiles objectForKey:image_url]; + VerifyWithImage(image_saved_tile, image_title, image_url); } TEST_F(NTPTileSaverControllerTest, UpdateSingleFaviconFallback) { // Set up test with 3 saved sites, 2 of which have a favicon. - ntp_tiles::NTPTile imageTile1 = ntp_tiles::NTPTile(); - imageTile1.title = base::ASCIIToUTF16("Title1"); - imageTile1.url = GURL("http://image1.com"); + ntp_tiles::NTPTile image_tile1 = ntp_tiles::NTPTile(); + image_tile1.title = base::ASCIIToUTF16("Title1"); + image_tile1.url = GURL("http://image1.com"); - ntp_tiles::NTPTile imageTile2 = ntp_tiles::NTPTile(); - imageTile2.title = base::ASCIIToUTF16("Title2"); - imageTile2.url = GURL("http://image2.com"); + ntp_tiles::NTPTile image_tile2 = ntp_tiles::NTPTile(); + image_tile2.title = base::ASCIIToUTF16("Title2"); + image_tile2.url = GURL("http://image2.com"); - ntp_tiles::NTPTile fallbackTile = ntp_tiles::NTPTile(); - fallbackTile.title = base::ASCIIToUTF16("Title"); - fallbackTile.url = GURL("http://fallback.com"); + ntp_tiles::NTPTile fallback_tile = ntp_tiles::NTPTile(); + fallback_tile.title = base::ASCIIToUTF16("Title"); + fallback_tile.url = GURL("http://fallback.com"); - id mockFaviconFetcher = OCMClassMock([FaviconAttributesProvider class]); - setupMockCallback(mockFaviconFetcher, {imageTile1.url, imageTile2.url}, - {fallbackTile.url}); + id mock_favicon_fetcher = OCMClassMock([FaviconAttributesProvider class]); + SetupMockCallback(mock_favicon_fetcher, {image_tile1.url, image_tile2.url}, + {fallback_tile.url}); - ntp_tiles::NTPTilesVector tiles = {imageTile1, fallbackTile, imageTile2}; + ntp_tiles::NTPTilesVector tiles = {image_tile1, fallback_tile, image_tile2}; - ntp_tile_saver::SaveMostVisitedToDisk(tiles, mockFaviconFetcher, - testFaviconDirectory()); + ntp_tile_saver::SaveMostVisitedToDisk(tiles, mock_favicon_fetcher, + TestFaviconDirectory()); // Wait for all asynchronous tasks to complete. scoped_task_evironment_.RunUntilIdle(); // Read most visited from disk. - NSDictionary<NSURL*, NTPTile*>* savedTiles = + NSDictionary<NSURL*, NTPTile*>* saved_tiles = ntp_tile_saver::ReadSavedMostVisited(); - EXPECT_EQ(savedTiles.count, 3U); + EXPECT_EQ(saved_tiles.count, 3U); - NSString* image1Title = base::SysUTF16ToNSString(imageTile1.title); - NSURL* image1URL = net::NSURLWithGURL(imageTile1.url); - NTPTile* image1SavedTile = [savedTiles objectForKey:image1URL]; - verifyWithImage(image1SavedTile, image1Title, image1URL); + NSString* image_title1 = base::SysUTF16ToNSString(image_tile1.title); + NSURL* image_url1 = net::NSURLWithGURL(image_tile1.url); + NTPTile* image_saved_tile1 = [saved_tiles objectForKey:image_url1]; + VerifyWithImage(image_saved_tile1, image_title1, image_url1); - NSString* image2Title = base::SysUTF16ToNSString(imageTile2.title); - NSURL* image2URL = net::NSURLWithGURL(imageTile2.url); - NTPTile* image2SavedTile = [savedTiles objectForKey:image2URL]; - verifyWithImage(image2SavedTile, image2Title, image2URL); + NSString* image_title2 = base::SysUTF16ToNSString(image_tile2.title); + NSURL* image_url2 = net::NSURLWithGURL(image_tile2.url); + NTPTile* image_saved_tile2 = [saved_tiles objectForKey:image_url2]; + VerifyWithImage(image_saved_tile2, image_title2, image_url2); - NSString* fallbackTitle = base::SysUTF16ToNSString(fallbackTile.title); - NSURL* fallbackURL = net::NSURLWithGURL(fallbackTile.url); - NTPTile* fallbackSavedTile = [savedTiles objectForKey:fallbackURL]; - verifyWithFallback(fallbackSavedTile, fallbackTitle, fallbackURL); + NSString* fallback_title = base::SysUTF16ToNSString(fallback_tile.title); + NSURL* fallback_url = net::NSURLWithGURL(fallback_tile.url); + NTPTile* fallback_saved_tile = [saved_tiles objectForKey:fallback_url]; + VerifyWithFallback(fallback_saved_tile, fallback_title, fallback_url); // Mock returning a fallback value for the first image tile. - id mockFaviconFetcher2 = OCMClassMock([FaviconAttributesProvider class]); - setupMockCallback(mockFaviconFetcher2, {imageTile2.url}, - {imageTile1.url, fallbackTile.url}); - ntp_tile_saver::UpdateSingleFavicon(imageTile1.url, mockFaviconFetcher2, - testFaviconDirectory()); + id mock_favicon_fetcher2 = OCMClassMock([FaviconAttributesProvider class]); + SetupMockCallback(mock_favicon_fetcher2, {image_tile2.url}, + {image_tile1.url, fallback_tile.url}); + ntp_tile_saver::UpdateSingleFavicon(image_tile1.url, mock_favicon_fetcher2, + TestFaviconDirectory()); // Wait for all asynchronous tasks to complete. scoped_task_evironment_.RunUntilIdle(); // Read most visited from disk. - NSDictionary<NSURL*, NTPTile*>* savedTilesAfterUpdate = + NSDictionary<NSURL*, NTPTile*>* saved_tiles_after_update = ntp_tile_saver::ReadSavedMostVisited(); - EXPECT_EQ(savedTilesAfterUpdate.count, 3U); + EXPECT_EQ(saved_tiles_after_update.count, 3U); // Verify that the first image tile now has callback data. - image1SavedTile = [savedTilesAfterUpdate objectForKey:image1URL]; - verifyWithFallback(image1SavedTile, image1Title, image1URL); + image_saved_tile1 = [saved_tiles_after_update objectForKey:image_url1]; + VerifyWithFallback(image_saved_tile1, image_title1, image_url1); // Verify that the other two tiles did not change. - image2SavedTile = [savedTiles objectForKey:image2URL]; - verifyWithImage(image2SavedTile, image2Title, image2URL); - fallbackSavedTile = [savedTilesAfterUpdate objectForKey:fallbackURL]; - verifyWithFallback(fallbackSavedTile, fallbackTitle, fallbackURL); + image_saved_tile2 = [saved_tiles objectForKey:image_url2]; + VerifyWithImage(image_saved_tile2, image_title2, image_url2); + fallback_saved_tile = [saved_tiles_after_update objectForKey:fallback_url]; + VerifyWithFallback(fallback_saved_tile, fallback_title, fallback_url); +} + +// Checks that the image saved for an item is deleted when the item is deleted. +TEST_F(NTPTileSaverControllerTest, DeleteOutdatedImage) { + ntp_tiles::NTPTile image_tile1 = ntp_tiles::NTPTile(); + image_tile1.title = base::ASCIIToUTF16("Title"); + image_tile1.url = GURL("http://image1.com"); + + ntp_tiles::NTPTile image_tile2 = ntp_tiles::NTPTile(); + image_tile2.title = base::ASCIIToUTF16("Title"); + image_tile2.url = GURL("http://image2.com"); + + id mock_favicon_fetcher = OCMClassMock([FaviconAttributesProvider class]); + SetupMockCallback(mock_favicon_fetcher, {image_tile1.url, image_tile2.url}, + {}); + + ntp_tiles::NTPTilesVector tiles = { + image_tile1, + }; + + ntp_tile_saver::SaveMostVisitedToDisk(tiles, mock_favicon_fetcher, + TestFaviconDirectory()); + // Wait for all asynchronous tasks to complete. + scoped_task_evironment_.RunUntilIdle(); + + NSDictionary<NSURL*, NTPTile*>* saved_tiles = + ntp_tile_saver::ReadSavedMostVisited(); + NSString* image_title1 = base::SysUTF16ToNSString(image_tile1.title); + NSURL* image_url1 = net::NSURLWithGURL(image_tile1.url); + NTPTile* saved_tile1 = [saved_tiles objectForKey:image_url1]; + VerifyWithImage(saved_tile1, image_title1, image_url1); + + ntp_tiles::NTPTilesVector tiles2 = { + image_tile2, + }; + + ntp_tile_saver::SaveMostVisitedToDisk(tiles2, mock_favicon_fetcher, + TestFaviconDirectory()); + // Wait for all asynchronous tasks to complete. + scoped_task_evironment_.RunUntilIdle(); + NSDictionary<NSURL*, NTPTile*>* saved_tiles2 = + ntp_tile_saver::ReadSavedMostVisited(); + NSString* image_title2 = base::SysUTF16ToNSString(image_tile2.title); + NSURL* image_url2 = net::NSURLWithGURL(image_tile2.url); + NTPTile* saved_tile2 = [saved_tiles2 objectForKey:image_url2]; + VerifyWithImage(saved_tile2, image_title2, image_url2); + + EXPECT_FALSE([[NSFileManager defaultManager] + fileExistsAtPath:[[TestFaviconDirectory() + URLByAppendingPathComponent:saved_tile1 + .faviconFileName] + path]]); +} + +// Checks the different icon transition for an item. +// Checks that when a fallback exists, it persists even if an image is set. +// Checks that if a new icon is received it replaces the old one. +TEST_F(NTPTileSaverControllerTest, UpdateEntry) { + ntp_tiles::NTPTile tile = ntp_tiles::NTPTile(); + + // Set up a red favicon. + tile.title = base::ASCIIToUTF16("Title"); + tile.url = GURL("http://url.com"); + NSString* ns_title = base::SysUTF16ToNSString(tile.title); + NSURL* ns_url = net::NSURLWithGURL(tile.url); + + UIImage* red_image = CreateMockImage([UIColor redColor]); + id mock_favicon_image_fetcher = + OCMClassMock([FaviconAttributesProvider class]); + SetupMockCallback(mock_favicon_image_fetcher, {tile.url}, {}); + id mock_favicon_fallback_fetcher = + OCMClassMock([FaviconAttributesProvider class]); + SetupMockCallback(mock_favicon_fallback_fetcher, {}, {tile.url}); + ntp_tiles::NTPTilesVector tiles = { + tile, + }; + ntp_tile_saver::SaveMostVisitedToDisk(tiles, mock_favicon_image_fetcher, + TestFaviconDirectory()); + // Wait for all asynchronous tasks to complete. + scoped_task_evironment_.RunUntilIdle(); + NSDictionary<NSURL*, NTPTile*>* saved = + ntp_tile_saver::ReadSavedMostVisited(); + NTPTile* saved_tile = [saved objectForKey:ns_url]; + VerifyWithImage(saved_tile, ns_title, ns_url); + + // Update image to blue + UIImage* blue_image = CreateMockImage([UIColor blueColor]); + EXPECT_NSNE(UIImagePNGRepresentation(red_image), + UIImagePNGRepresentation(blue_image)); + ntp_tile_saver::SaveMostVisitedToDisk(tiles, mock_favicon_image_fetcher, + TestFaviconDirectory()); + // Wait for all asynchronous tasks to complete. + scoped_task_evironment_.RunUntilIdle(); + saved = ntp_tile_saver::ReadSavedMostVisited(); + saved_tile = [saved objectForKey:ns_url]; + VerifyWithImage(saved_tile, ns_title, ns_url); + + // Update with fallback + ntp_tile_saver::SaveMostVisitedToDisk(tiles, mock_favicon_fallback_fetcher, + TestFaviconDirectory()); + // Wait for all asynchronous tasks to complete. + scoped_task_evironment_.RunUntilIdle(); + saved = ntp_tile_saver::ReadSavedMostVisited(); + saved_tile = [saved objectForKey:ns_url]; + VerifyWithFallback(saved_tile, ns_title, ns_url); + + // Update image to green + UIImage* green_image = CreateMockImage([UIColor greenColor]); + EXPECT_NSNE(UIImagePNGRepresentation(blue_image), + UIImagePNGRepresentation(green_image)); + ntp_tile_saver::SaveMostVisitedToDisk(tiles, mock_favicon_image_fetcher, + TestFaviconDirectory()); + // Wait for all asynchronous tasks to complete. + scoped_task_evironment_.RunUntilIdle(); + saved = ntp_tile_saver::ReadSavedMostVisited(); + saved_tile = [saved objectForKey:ns_url]; + // Fallback should still be present. + VerifyWithFallbackAndImage(saved_tile, ns_title, ns_url); + + // Remove tile. + ntp_tile_saver::SaveMostVisitedToDisk(ntp_tiles::NTPTilesVector(), + mock_favicon_image_fetcher, + TestFaviconDirectory()); + // Wait for all asynchronous tasks to complete. + scoped_task_evironment_.RunUntilIdle(); + EXPECT_FALSE([[NSFileManager defaultManager] + fileExistsAtPath:[[TestFaviconDirectory() + URLByAppendingPathComponent:saved_tile + .faviconFileName] + path]]); } } // anonymous namespace
diff --git a/ios/chrome/browser/ui/popup_menu/BUILD.gn b/ios/chrome/browser/ui/popup_menu/BUILD.gn index 346a4daf..6bd08f2 100644 --- a/ios/chrome/browser/ui/popup_menu/BUILD.gn +++ b/ios/chrome/browser/ui/popup_menu/BUILD.gn
@@ -13,10 +13,12 @@ deps = [ ":popup_menu_ui", "//base", + "//ios/chrome/app/strings", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/coordinators:chrome_coordinators", "//ios/chrome/browser/ui/popup_menu/cells", "//ios/chrome/browser/ui/util", + "//ui/base", ] libs = [ "UIKit.framework" ] }
diff --git a/ios/chrome/browser/ui/popup_menu/cells/BUILD.gn b/ios/chrome/browser/ui/popup_menu/cells/BUILD.gn index 3d9a4a6d..f1cf3a3 100644 --- a/ios/chrome/browser/ui/popup_menu/cells/BUILD.gn +++ b/ios/chrome/browser/ui/popup_menu/cells/BUILD.gn
@@ -5,6 +5,7 @@ source_set("cells") { configs += [ "//build/config/compiler:enable_arc" ] sources = [ + "popup_menu_item.h", "popup_menu_navigation_item.h", "popup_menu_navigation_item.mm", "popup_menu_tools_item.h",
diff --git a/ios/chrome/browser/ui/popup_menu/cells/popup_menu_item.h b/ios/chrome/browser/ui/popup_menu/cells/popup_menu_item.h new file mode 100644 index 0000000..338797f --- /dev/null +++ b/ios/chrome/browser/ui/popup_menu/cells/popup_menu_item.h
@@ -0,0 +1,37 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef IOS_CHROME_BROWSER_UI_POPUP_MENU_CELLS_POPUP_MENU_ITEM_H_ +#define IOS_CHROME_BROWSER_UI_POPUP_MENU_CELLS_POPUP_MENU_ITEM_H_ + +#import <Foundation/Foundation.h> + +// Identifier for the action associated with a popup menu item. +typedef NS_ENUM(NSInteger, PopupMenuAction) { + PopupMenuActionReload, + PopupMenuActionStop, + PopupMenuActionOpenNewTab, + PopupMenuActionOpenNewIncognitoTab, + PopupMenuActionReadLater, + PopupMenuActionRequestDesktop, + PopupMenuActionRequestMobile, + PopupMenuActionSiteInformation, + PopupMenuActionReportIssue, + PopupMenuActionHelp, + PopupMenuActionBookmarks, + PopupMenuActionReadingList, + PopupMenuActionRecentTabs, + PopupMenuActionHistory, + PopupMenuActionSettings, +}; + +// Protocol defining a popup item. +@protocol PopupMenuItem + +// Action identifier for the popup item. +@property(nonatomic, assign) PopupMenuAction actionIdentifier; + +@end + +#endif // IOS_CHROME_BROWSER_UI_POPUP_MENU_CELLS_POPUP_MENU_ITEM_H_
diff --git a/ios/chrome/browser/ui/popup_menu/cells/popup_menu_navigation_item.h b/ios/chrome/browser/ui/popup_menu/cells/popup_menu_navigation_item.h index 480eee4..29ccff5 100644 --- a/ios/chrome/browser/ui/popup_menu/cells/popup_menu_navigation_item.h +++ b/ios/chrome/browser/ui/popup_menu/cells/popup_menu_navigation_item.h
@@ -5,10 +5,11 @@ #ifndef IOS_CHROME_BROWSER_UI_POPUP_MENU_CELLS_POPUP_MENU_NAVIGATION_ITEM_H_ #define IOS_CHROME_BROWSER_UI_POPUP_MENU_CELLS_POPUP_MENU_NAVIGATION_ITEM_H_ +#import "ios/chrome/browser/ui/popup_menu/cells/popup_menu_item.h" #import "ios/chrome/browser/ui/table_view/cells/table_view_item.h" // Item used to display an item for a navigation menu. -@interface PopupMenuNavigationItem : TableViewItem +@interface PopupMenuNavigationItem : TableViewItem<PopupMenuItem> @end // Associated cell for a PopupMenuNavigationItem.
diff --git a/ios/chrome/browser/ui/popup_menu/cells/popup_menu_navigation_item.mm b/ios/chrome/browser/ui/popup_menu/cells/popup_menu_navigation_item.mm index c6b01fe..7a45720 100644 --- a/ios/chrome/browser/ui/popup_menu/cells/popup_menu_navigation_item.mm +++ b/ios/chrome/browser/ui/popup_menu/cells/popup_menu_navigation_item.mm
@@ -10,6 +10,8 @@ @implementation PopupMenuNavigationItem +@synthesize actionIdentifier = _actionIdentifier; + - (instancetype)initWithType:(NSInteger)type { self = [super initWithType:type]; if (self) {
diff --git a/ios/chrome/browser/ui/popup_menu/cells/popup_menu_tools_item.h b/ios/chrome/browser/ui/popup_menu/cells/popup_menu_tools_item.h index 3577417b..5dd2c30 100644 --- a/ios/chrome/browser/ui/popup_menu/cells/popup_menu_tools_item.h +++ b/ios/chrome/browser/ui/popup_menu/cells/popup_menu_tools_item.h
@@ -5,19 +5,25 @@ #ifndef IOS_CHROME_BROWSER_UI_POPUP_MENU_CELLS_POPUP_MENU_TOOLS_ITEM_H_ #define IOS_CHROME_BROWSER_UI_POPUP_MENU_CELLS_POPUP_MENU_TOOLS_ITEM_H_ +#import "ios/chrome/browser/ui/popup_menu/cells/popup_menu_item.h" #import "ios/chrome/browser/ui/table_view/cells/table_view_item.h" // Item for a tools menu item. -@interface PopupMenuToolsItem : TableViewItem +@interface PopupMenuToolsItem : TableViewItem<PopupMenuItem> // The title of the item. @property(nonatomic, copy) NSString* title; +// Image to be displayed on the item. +@property(nonatomic, strong) UIImage* image; @end // Associated cell for the PopupMenuToolsItem. @interface PopupMenuToolsCell : UITableViewCell +// Image view to display the image. +@property(nonatomic, strong, readonly) UIImageView* imageView; + // Sets the title of the cell. - (void)setTitleText:(NSString*)title;
diff --git a/ios/chrome/browser/ui/popup_menu/cells/popup_menu_tools_item.mm b/ios/chrome/browser/ui/popup_menu/cells/popup_menu_tools_item.mm index d6bd89c..fd0596f 100644 --- a/ios/chrome/browser/ui/popup_menu/cells/popup_menu_tools_item.mm +++ b/ios/chrome/browser/ui/popup_menu/cells/popup_menu_tools_item.mm
@@ -10,8 +10,14 @@ #error "This file requires ARC support." #endif +namespace { +const CGFloat kImageLength = 30; +} + @implementation PopupMenuToolsItem +@synthesize actionIdentifier = _actionIdentifier; +@synthesize image = _image; @synthesize title = _title; - (instancetype)initWithType:(NSInteger)type { @@ -26,6 +32,7 @@ withStyler:(ChromeTableViewStyler*)styler { [super configureCell:cell withStyler:styler]; [cell setTitleText:self.title]; + cell.imageView.image = self.image; } @end @@ -36,11 +43,14 @@ // Title label for the cell. @property(nonatomic, strong) UILabel* title; +// Image view for the cell, redefined as readwrite. +@property(nonatomic, strong, readwrite) UIImageView* imageView; @end @implementation PopupMenuToolsCell +@synthesize imageView = _imageView; @synthesize title = _title; - (instancetype)initWithStyle:(UITableViewCellStyle)style @@ -49,8 +59,26 @@ if (self) { _title = [[UILabel alloc] init]; _title.translatesAutoresizingMaskIntoConstraints = NO; + + _imageView = [[UIImageView alloc] init]; + _imageView.translatesAutoresizingMaskIntoConstraints = NO; + [NSLayoutConstraint activateConstraints:@[ + [_imageView.widthAnchor constraintEqualToConstant:kImageLength], + [_imageView.heightAnchor + constraintGreaterThanOrEqualToConstant:kImageLength], + ]]; + [self.contentView addSubview:_title]; - AddSameConstraints(self.contentView, _title); + [self.contentView addSubview:_imageView]; + + AddSameConstraintsToSides( + self.contentView, _title, + LayoutSides::kTop | LayoutSides::kBottom | LayoutSides::kTrailing); + AddSameConstraintsToSides( + self.contentView, _imageView, + LayoutSides::kTop | LayoutSides::kBottom | LayoutSides::kLeading); + [_imageView.trailingAnchor constraintEqualToAnchor:_title.leadingAnchor] + .active = YES; } return self; }
diff --git a/ios/chrome/browser/ui/popup_menu/popup_menu_coordinator.mm b/ios/chrome/browser/ui/popup_menu/popup_menu_coordinator.mm index 67b2345..fc7cd84 100644 --- a/ios/chrome/browser/ui/popup_menu/popup_menu_coordinator.mm +++ b/ios/chrome/browser/ui/popup_menu/popup_menu_coordinator.mm
@@ -63,6 +63,8 @@ - (void)showToolsMenuPopup { PopupMenuTableViewController* tableViewController = [[PopupMenuTableViewController alloc] init]; + tableViewController.dispatcher = + static_cast<id<ApplicationCommands, BrowserCommands>>(self.dispatcher); PopupMenuMediator* mediator = [[PopupMenuMediator alloc] initWithType:PopupMenuTypeToolsMenu];
diff --git a/ios/chrome/browser/ui/popup_menu/popup_menu_mediator.mm b/ios/chrome/browser/ui/popup_menu/popup_menu_mediator.mm index e2859a3b..885f123 100644 --- a/ios/chrome/browser/ui/popup_menu/popup_menu_mediator.mm +++ b/ios/chrome/browser/ui/popup_menu/popup_menu_mediator.mm
@@ -4,17 +4,32 @@ #import "ios/chrome/browser/ui/popup_menu/popup_menu_mediator.h" +#import "ios/chrome/browser/ui/popup_menu/cells/popup_menu_item.h" #import "ios/chrome/browser/ui/popup_menu/cells/popup_menu_tools_item.h" #import "ios/chrome/browser/ui/popup_menu/popup_menu_table_view_controller.h" +#include "ios/chrome/grit/ios_strings.h" +#include "ui/base/l10n/l10n_util.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif +namespace { +TableViewItem<PopupMenuItem>* CreateTableViewItem(int titleID, + PopupMenuAction action) { + PopupMenuToolsItem* item = + [[PopupMenuToolsItem alloc] initWithType:kItemTypeEnumZero]; + item.title = l10n_util::GetNSString(titleID); + item.actionIdentifier = action; + return item; +} +} + @interface PopupMenuMediator () // Items to be displayed in the popup menu. -@property(nonatomic, strong) NSArray<NSArray<TableViewItem*>*>* items; +@property(nonatomic, strong) + NSArray<NSArray<TableViewItem<PopupMenuItem>*>*>* items; // Type of this mediator. @property(nonatomic, assign) PopupMenuType type; @@ -60,23 +75,85 @@ // Creates the menu items for the tools menu. - (void)createToolsMenuItem { - NSMutableArray* section1 = [NSMutableArray array]; - for (int i = 0; i < 3; i++) { - PopupMenuToolsItem* item = - [[PopupMenuToolsItem alloc] initWithType:kItemTypeEnumZero]; - item.title = [@"Item number:" stringByAppendingFormat:@"%i", i]; - [section1 addObject:item]; - } + // Reload page action. + TableViewItem* reload = + CreateTableViewItem(IDS_IOS_TOOLS_MENU_RELOAD, PopupMenuActionReload); - NSMutableArray* section2 = [NSMutableArray array]; - for (int i = 0; i < 5; i++) { - PopupMenuToolsItem* item = - [[PopupMenuToolsItem alloc] initWithType:kItemTypeEnumZero]; - item.title = [@"Item 2 number:" stringByAppendingFormat:@"%i", i]; - [section2 addObject:item]; - } + NSArray* tabActions = + [@[ reload ] arrayByAddingObjectsFromArray:[self itemsForNewTab]]; - self.items = @[ section1, section2 ]; + NSArray* browserActions = [self actionItems]; + + NSArray* collectionActions = [self collectionItems]; + + self.items = @[ tabActions, browserActions, collectionActions ]; +} + +- (NSArray<TableViewItem*>*)itemsForNewTab { + // Open New Tab. + TableViewItem* openNewTabItem = CreateTableViewItem( + IDS_IOS_TOOLS_MENU_NEW_TAB, PopupMenuActionOpenNewTab); + + // Open New Incogntio Tab. + TableViewItem* openNewIncognitoTabItem = CreateTableViewItem( + IDS_IOS_TOOLS_MENU_NEW_INCOGNITO_TAB, PopupMenuActionOpenNewIncognitoTab); + + return @[ openNewTabItem, openNewIncognitoTabItem ]; +} + +- (NSArray<TableViewItem*>*)actionItems { + // Read Later. + TableViewItem* readLater = CreateTableViewItem( + IDS_IOS_CONTENT_CONTEXT_ADDTOREADINGLIST, PopupMenuActionReadLater); + + // Request Desktop Site. + TableViewItem* requestDesktopSite = CreateTableViewItem( + IDS_IOS_TOOLS_MENU_REQUEST_DESKTOP_SITE, PopupMenuActionRequestDesktop); + + // Request Mobile Site. + TableViewItem* requestMobileSite = CreateTableViewItem( + IDS_IOS_TOOLS_MENU_REQUEST_MOBILE_SITE, PopupMenuActionRequestMobile); + + // Site Information. + TableViewItem* siteInformation = CreateTableViewItem( + IDS_IOS_TOOLS_MENU_SITE_INFORMATION, PopupMenuActionSiteInformation); + + // Report an Issue. + TableViewItem* reportIssue = CreateTableViewItem( + IDS_IOS_OPTIONS_REPORT_AN_ISSUE, PopupMenuActionReportIssue); + + // Help. + TableViewItem* help = + CreateTableViewItem(IDS_IOS_TOOLS_MENU_HELP_MOBILE, PopupMenuActionHelp); + + return @[ + readLater, requestDesktopSite, requestMobileSite, siteInformation, + reportIssue, help + ]; +} + +- (NSArray<TableViewItem*>*)collectionItems { + // Bookmarks. + TableViewItem* bookmarks = CreateTableViewItem(IDS_IOS_TOOLS_MENU_BOOKMARKS, + PopupMenuActionBookmarks); + + // Reading List. + TableViewItem* readingList = CreateTableViewItem( + IDS_IOS_TOOLS_MENU_READING_LIST, PopupMenuActionReadingList); + + // Recent Tabs. + TableViewItem* recentTabs = CreateTableViewItem( + IDS_IOS_TOOLS_MENU_RECENT_TABS, PopupMenuActionRecentTabs); + + // History. + TableViewItem* history = + CreateTableViewItem(IDS_IOS_TOOLS_MENU_HISTORY, PopupMenuActionHistory); + + // Settings. + TableViewItem* settings = + CreateTableViewItem(IDS_IOS_TOOLS_MENU_SETTINGS, PopupMenuActionSettings); + + return @[ bookmarks, readingList, recentTabs, history, settings ]; } @end
diff --git a/ios/chrome/browser/ui/popup_menu/popup_menu_presenter.mm b/ios/chrome/browser/ui/popup_menu/popup_menu_presenter.mm index 8299b12..1d717d9 100644 --- a/ios/chrome/browser/ui/popup_menu/popup_menu_presenter.mm +++ b/ios/chrome/browser/ui/popup_menu/popup_menu_presenter.mm
@@ -7,11 +7,20 @@ #include "base/logging.h" #import "ios/chrome/browser/ui/popup_menu/popup_menu_view_controller.h" #import "ios/chrome/browser/ui/presenters/contained_presenter_delegate.h" +#import "ios/chrome/browser/ui/util/constraints_ui_util.h" +#import "ios/chrome/browser/ui/util/named_guide.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif +namespace { +const CGFloat kMinHeight = 200; +const CGFloat kMaxWidth = 250; +const CGFloat kMaxHeight = 400; +const CGFloat kMinMargin = 16; +} // namespace + @interface PopupMenuPresenter () @property(nonatomic, strong) PopupMenuViewController* popupViewController; @end @@ -34,6 +43,9 @@ self.popupViewController = [[PopupMenuViewController alloc] init]; self.popupViewController.commandHandler = self.commandHandler; + [self.presentedViewController.view + setContentCompressionResistancePriority:UILayoutPriorityDefaultHigh + 1 + forAxis:UILayoutConstraintAxisHorizontal]; [self.popupViewController addContent:self.presentedViewController]; [self.baseViewController addChildViewController:self.popupViewController]; @@ -42,6 +54,7 @@ // TODO(crbug.com/804774): Prepare for animation. self.popupViewController.contentContainer.alpha = 0; + [self positionPopupOnNamedGuide]; [self.popupViewController didMoveToParentViewController:self.baseViewController]; @@ -63,4 +76,52 @@ [self.delegate containedPresenterDidDismiss:self]; } +#pragma mark - Private + +// Positions the popup relatively to the |guideName| layout guide. The popup is +// positioned closest to the layout guide, by default it is presented below the +// layout guide, aligned on its leading edge. However, it is respecting the safe +// area bounds. +- (void)positionPopupOnNamedGuide { + UIView* parentView = self.baseViewController.view; + UIView* container = self.popupViewController.contentContainer; + + UILayoutGuide* namedGuide = + [NamedGuide guideWithName:self.guideName view:parentView]; + CGRect guideFrame = + [self.popupViewController.view convertRect:namedGuide.layoutFrame + fromView:namedGuide.owningView]; + + if (CGRectGetMaxY(guideFrame) + kMinHeight > + CGRectGetHeight(parentView.frame)) { + // Display above. + [container.bottomAnchor constraintEqualToAnchor:namedGuide.topAnchor] + .active = YES; + } else { + // Display below. + [container.topAnchor constraintEqualToAnchor:namedGuide.bottomAnchor] + .active = YES; + } + + id<LayoutGuideProvider> safeArea = SafeAreaLayoutGuideForView(parentView); + [NSLayoutConstraint activateConstraints:@[ + [container.leadingAnchor + constraintGreaterThanOrEqualToAnchor:safeArea.leadingAnchor + constant:kMinMargin], + [container.trailingAnchor + constraintLessThanOrEqualToAnchor:safeArea.trailingAnchor + constant:-kMinMargin], + [container.heightAnchor constraintLessThanOrEqualToConstant:kMaxHeight], + [container.widthAnchor constraintLessThanOrEqualToConstant:kMaxWidth], + [container.bottomAnchor + constraintLessThanOrEqualToAnchor:safeArea.bottomAnchor], + [container.topAnchor + constraintGreaterThanOrEqualToAnchor:safeArea.topAnchor], + ]]; + NSLayoutConstraint* leading = [container.leadingAnchor + constraintEqualToAnchor:namedGuide.leadingAnchor]; + leading.priority = UILayoutPriorityDefaultHigh; + leading.active = YES; +} + @end
diff --git a/ios/chrome/browser/ui/popup_menu/popup_menu_table_view_controller.h b/ios/chrome/browser/ui/popup_menu/popup_menu_table_view_controller.h index ef845db..cfd541cb 100644 --- a/ios/chrome/browser/ui/popup_menu/popup_menu_table_view_controller.h +++ b/ios/chrome/browser/ui/popup_menu/popup_menu_table_view_controller.h
@@ -7,12 +7,24 @@ #import "ios/chrome/browser/ui/table_view/chrome_table_view_controller.h" +@protocol ApplicationCommands; +@protocol BrowserCommands; +@protocol PopupMenuItem; + // TableViewController for the popup menu. @interface PopupMenuTableViewController : ChromeTableViewController +// The model of this controller. +@property(nonatomic, readonly, strong) + TableViewModel<TableViewItem<PopupMenuItem>*>* tableViewModel; + +// Dispatcher. +@property(nonatomic, weak) id<ApplicationCommands, BrowserCommands> dispatcher; + // Sets the |items| to be displayed by this Table View. Removes all the // currently presented items. -- (void)setPopupMenuItems:(NSArray<NSArray<TableViewItem*>*>*)items; +- (void)setPopupMenuItems: + (NSArray<NSArray<TableViewItem<PopupMenuItem>*>*>*)items; @end
diff --git a/ios/chrome/browser/ui/popup_menu/popup_menu_table_view_controller.mm b/ios/chrome/browser/ui/popup_menu/popup_menu_table_view_controller.mm index 5a32660b..f937851 100644 --- a/ios/chrome/browser/ui/popup_menu/popup_menu_table_view_controller.mm +++ b/ios/chrome/browser/ui/popup_menu/popup_menu_table_view_controller.mm
@@ -4,15 +4,27 @@ #import "ios/chrome/browser/ui/popup_menu/popup_menu_table_view_controller.h" +#include "base/metrics/user_metrics.h" +#include "base/metrics/user_metrics_action.h" +#import "ios/chrome/browser/ui/commands/application_commands.h" +#import "ios/chrome/browser/ui/commands/browser_commands.h" +#import "ios/chrome/browser/ui/commands/open_new_tab_command.h" +#import "ios/chrome/browser/ui/popup_menu/cells/popup_menu_item.h" + #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif +using base::UserMetricsAction; + @interface PopupMenuTableViewController () @end @implementation PopupMenuTableViewController +@dynamic tableViewModel; +@synthesize dispatcher = _dispatcher; + #pragma mark - UIViewController - (void)viewDidLoad { @@ -22,12 +34,13 @@ self.tableView.sectionFooterHeight = 0; } -- (void)setPopupMenuItems:(NSArray<NSArray<TableViewItem*>*>*)items { +- (void)setPopupMenuItems: + (NSArray<NSArray<TableViewItem<PopupMenuItem>*>*>*)items { [super loadModel]; for (NSUInteger section = 0; section < items.count; section++) { NSInteger sectionIdentifier = kSectionIdentifierEnumZero + section; [self.tableViewModel addSectionWithIdentifier:sectionIdentifier]; - for (TableViewItem* item in items[section]) { + for (TableViewItem<PopupMenuItem>* item in items[section]) { [self.tableViewModel addItem:item toSectionWithIdentifier:sectionIdentifier]; } @@ -35,4 +48,90 @@ [self.tableView reloadData]; } +#pragma mark - UITableViewDelegate + +- (void)tableView:(UITableView*)tableView + didSelectRowAtIndexPath:(NSIndexPath*)indexPath { + TableViewItem<PopupMenuItem>* item = + [self.tableViewModel itemAtIndexPath:indexPath]; + UIView* cell = [self.tableView cellForRowAtIndexPath:indexPath]; + CGPoint center = [cell convertPoint:cell.center toView:nil]; + [self executeActionForIdentifier:item.actionIdentifier origin:center]; +} + +#pragma mark - Private + +// Executes the action associated with |identifier|, using |origin| as the point +// of origin of the action if one is needed. +- (void)executeActionForIdentifier:(PopupMenuAction)identifier + origin:(CGPoint)origin { + switch (identifier) { + case PopupMenuActionReload: + base::RecordAction(UserMetricsAction("MobileMenuReload")); + [self.dispatcher reload]; + break; + case PopupMenuActionStop: + base::RecordAction(UserMetricsAction("MobileMenuStop")); + [self.dispatcher stopLoading]; + break; + case PopupMenuActionOpenNewTab: + base::RecordAction(UserMetricsAction("MobileMenuNewTab")); + [self.dispatcher + openNewTab:[[OpenNewTabCommand alloc] initWithIncognito:NO + originPoint:origin]]; + break; + case PopupMenuActionOpenNewIncognitoTab: + base::RecordAction(UserMetricsAction("MobileMenuNewIncognitoTab")); + [self.dispatcher + openNewTab:[[OpenNewTabCommand alloc] initWithIncognito:YES + originPoint:origin]]; + break; + case PopupMenuActionReadLater: + // TODO(crbug.com/822703): Add metric and action. + break; + case PopupMenuActionRequestDesktop: + base::RecordAction(UserMetricsAction("MobileMenuRequestDesktopSite")); + [self.dispatcher requestDesktopSite]; + break; + case PopupMenuActionRequestMobile: + base::RecordAction(UserMetricsAction("MobileMenuRequestMobileSite")); + [self.dispatcher requestMobileSite]; + break; + case PopupMenuActionSiteInformation: + // TODO(crbug.com/822703): Add metric and action. + break; + case PopupMenuActionReportIssue: + base::RecordAction(UserMetricsAction("MobileMenuReportAnIssue")); + // TODO(crbug.com/822703): Add action. + break; + case PopupMenuActionHelp: + base::RecordAction(UserMetricsAction("MobileMenuHelp")); + [self.dispatcher showHelpPage]; + break; + case PopupMenuActionBookmarks: + base::RecordAction(UserMetricsAction("MobileMenuAllBookmarks")); + [self.dispatcher showBookmarksManager]; + break; + case PopupMenuActionReadingList: + base::RecordAction(UserMetricsAction("MobileMenuReadingList")); + [self.dispatcher showReadingList]; + break; + case PopupMenuActionRecentTabs: + base::RecordAction(UserMetricsAction("MobileMenuRecentTabs")); + [self.dispatcher showRecentTabs]; + break; + case PopupMenuActionHistory: + base::RecordAction(UserMetricsAction("MobileMenuHistory")); + [self.dispatcher showHistory]; + break; + case PopupMenuActionSettings: + base::RecordAction(UserMetricsAction("MobileMenuSettings")); + // TODO(crbug.com/822703): Add action. + break; + } + + // Close the tools menu. + [self.dispatcher dismissPopupMenu]; +} + @end
diff --git a/ios/chrome/browser/ui/popup_menu/popup_menu_view_controller.mm b/ios/chrome/browser/ui/popup_menu/popup_menu_view_controller.mm index 5bab5e7..14331ff 100644 --- a/ios/chrome/browser/ui/popup_menu/popup_menu_view_controller.mm +++ b/ios/chrome/browser/ui/popup_menu/popup_menu_view_controller.mm
@@ -11,6 +11,13 @@ #error "This file requires ARC support." #endif +namespace { +const CGFloat kCornerRadius = 15; +const CGFloat kShadowRadius = 10; +const CGFloat kShadowOpacity = 0.3; +const CGFloat kContentMargin = 8; +} // namespace + @interface PopupMenuViewController ()<UIGestureRecognizerDelegate> // Redefined as readwrite. @property(nonatomic, strong, readwrite) UIView* contentContainer; @@ -40,7 +47,7 @@ [self addChildViewController:content]; content.view.translatesAutoresizingMaskIntoConstraints = NO; [self.contentContainer addSubview:content.view]; - AddSameConstraints(self.contentContainer, content.view); + AddSameConstraints(self.contentContainer.layoutMarginsGuide, content.view); [content didMoveToParentViewController:self]; } @@ -50,9 +57,12 @@ - (void)setUpContentContainer { _contentContainer = [[UIView alloc] init]; _contentContainer.backgroundColor = [UIColor whiteColor]; - _contentContainer.layer.cornerRadius = 15; - _contentContainer.layer.shadowRadius = 10; - _contentContainer.layer.shadowOpacity = 0.3; + _contentContainer.layer.cornerRadius = kCornerRadius; + _contentContainer.layer.shadowRadius = kShadowRadius; + _contentContainer.layer.shadowOpacity = kShadowOpacity; + _contentContainer.translatesAutoresizingMaskIntoConstraints = NO; + _contentContainer.layoutMargins = UIEdgeInsetsMake( + kContentMargin, kContentMargin, kContentMargin, kContentMargin); // TODO(crbug.com/821765): Add blur effect and update the shadow. [self.view addSubview:_contentContainer]; } @@ -68,8 +78,8 @@ - (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer shouldReceiveTouch:(UITouch*)touch { - // Do no get the touches on the container view. - return touch.view != self.contentContainer; + // Only get the touch on the scrim. + return touch.view == self.view; } @end
diff --git a/ios/chrome/browser/ui/tab_grid/tab_grid_constants.h b/ios/chrome/browser/ui/tab_grid/tab_grid_constants.h index 0acce42..c09524c 100644 --- a/ios/chrome/browser/ui/tab_grid/tab_grid_constants.h +++ b/ios/chrome/browser/ui/tab_grid/tab_grid_constants.h
@@ -7,6 +7,12 @@ #import <UIKit/UIKit.h> +// Accessibility identifiers for automated testing. +extern NSString* const kTabGridDoneButtonIdentifier; +extern NSString* const kTabGridCloseAllButtonIdentifier; +extern NSString* const kTabGridIncognitoTabsEmptyStateIdentifier; +extern NSString* const kTabGridRegularTabsEmptyStateIdentifier; + // All kxxxColor constants are RGB values stored in a Hex integer. These will be // converted into UIColors using the UIColorFromRGB() function, from // uikit_ui_util.h
diff --git a/ios/chrome/browser/ui/tab_grid/tab_grid_constants.mm b/ios/chrome/browser/ui/tab_grid/tab_grid_constants.mm index 0734b537..7feb3b2 100644 --- a/ios/chrome/browser/ui/tab_grid/tab_grid_constants.mm +++ b/ios/chrome/browser/ui/tab_grid/tab_grid_constants.mm
@@ -8,6 +8,15 @@ #error "This file requires ARC support." #endif +// Accessibility identifiers for automated testing. +NSString* const kTabGridDoneButtonIdentifier = @"TabGridDoneButtonIdentifier"; +NSString* const kTabGridCloseAllButtonIdentifier = + @"TabGridCloseAllButtonIdentifier"; +NSString* const kTabGridIncognitoTabsEmptyStateIdentifier = + @"TabGridIncognitoTabsEmptyStateIdentifier"; +NSString* const kTabGridRegularTabsEmptyStateIdentifier = + @"TabGridRegularTabsEmptyStateIdentifier"; + // The color of the text buttons in the toolbars. const int kTabGridToolbarTextButtonColor = 0xFFFFFF;
diff --git a/ios/chrome/browser/ui/tab_grid/tab_grid_egtest.mm b/ios/chrome/browser/ui/tab_grid/tab_grid_egtest.mm index f6d2fa84..78e402cd8 100644 --- a/ios/chrome/browser/ui/tab_grid/tab_grid_egtest.mm +++ b/ios/chrome/browser/ui/tab_grid/tab_grid_egtest.mm
@@ -3,7 +3,7 @@ // found in the LICENSE file. #import "ios/chrome/browser/ui/tab_grid/grid/grid_constants.h" -#import "ios/chrome/browser/ui/tab_grid/tab_grid_view_controller.h" +#import "ios/chrome/browser/ui/tab_grid/tab_grid_constants.h" #import "ios/chrome/test/app/chrome_test_util.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey_ui.h" @@ -35,12 +35,25 @@ grey_sufficientlyVisible(), nil); } -// Matcher for done button in tab grid. -id<GREYMatcher> TabGridDoneButton() { - return grey_allOf(grey_accessibilityID(kTabGridDoneButtonAccessibilityID), +// Matcher for the Done button in the tab grid. +id<GREYMatcher> DoneButton() { + return grey_allOf(grey_accessibilityID(kTabGridDoneButtonIdentifier), grey_sufficientlyVisible(), nil); } +// Matcher for the Close All button in the tab grid. +id<GREYMatcher> CloseAllButton() { + return grey_allOf(grey_accessibilityID(kTabGridCloseAllButtonIdentifier), + grey_sufficientlyVisible(), nil); +} + +// Matcher for the regular tabs empty state view. +id<GREYMatcher> RegularTabsEmptyStateView() { + return grey_allOf( + grey_accessibilityID(kTabGridRegularTabsEmptyStateIdentifier), + grey_sufficientlyVisible(), nil); +} + } // namespace @interface TabGridTestCase : ChromeTestCase @@ -52,8 +65,7 @@ - (void)testEnteringAndLeavingTabGrid { [[EarlGrey selectElementWithMatcher:chrome_test_util::ShowTabsButton()] performAction:grey_tap()]; - [[EarlGrey selectElementWithMatcher:TabGridDoneButton()] - performAction:grey_tap()]; + [[EarlGrey selectElementWithMatcher:DoneButton()] performAction:grey_tap()]; } // Tests that tapping on the first cell shows that tab. @@ -65,7 +77,7 @@ assertWithMatcher:grey_sufficientlyVisible()]; } -// Tests that closing the cell shows no tabs. +// Tests that closing the cell shows no tabs, and displays the empty state. - (void)testClosingFirstCell { [[EarlGrey selectElementWithMatcher:chrome_test_util::ShowTabsButton()] performAction:grey_tap()]; @@ -73,6 +85,20 @@ performAction:grey_tap()]; [[EarlGrey selectElementWithMatcher:CellAtIndex(0)] assertWithMatcher:grey_nil()]; + [[EarlGrey selectElementWithMatcher:RegularTabsEmptyStateView()] + assertWithMatcher:grey_sufficientlyVisible()]; +} + +// Tests that tapping Close All shows no tabs, and displays the empty state. +- (void)testShowingEmptyStateOnCloseAll { + [[EarlGrey selectElementWithMatcher:chrome_test_util::ShowTabsButton()] + performAction:grey_tap()]; + [[EarlGrey selectElementWithMatcher:CloseAllButton()] + performAction:grey_tap()]; + [[EarlGrey selectElementWithMatcher:CellAtIndex(0)] + assertWithMatcher:grey_nil()]; + [[EarlGrey selectElementWithMatcher:RegularTabsEmptyStateView()] + assertWithMatcher:grey_sufficientlyVisible()]; } @end
diff --git a/ios/chrome/browser/ui/tab_grid/tab_grid_view_controller.h b/ios/chrome/browser/ui/tab_grid/tab_grid_view_controller.h index 50d4734c..f018f58 100644 --- a/ios/chrome/browser/ui/tab_grid/tab_grid_view_controller.h +++ b/ios/chrome/browser/ui/tab_grid/tab_grid_view_controller.h
@@ -14,10 +14,6 @@ @protocol GridCommands; @protocol GridImageDataSource; -// TODO(crbug.com/818198) : Move to constants file. -// The accessibility label for the done button for use in test automation. -extern NSString* const kTabGridDoneButtonAccessibilityID; - // Delegate protocol for an object that can handle presenting ("opening") tabs // from the tab grid. @protocol TabPresentationDelegate<NSObject>
diff --git a/ios/chrome/browser/ui/tab_grid/tab_grid_view_controller.mm b/ios/chrome/browser/ui/tab_grid/tab_grid_view_controller.mm index 8ccd3bf..afbb2471c 100644 --- a/ios/chrome/browser/ui/tab_grid/tab_grid_view_controller.mm +++ b/ios/chrome/browser/ui/tab_grid/tab_grid_view_controller.mm
@@ -23,10 +23,6 @@ #error "This file requires ARC support." #endif -// The accessibility label for the done button for use in test automation. -NSString* const kTabGridDoneButtonAccessibilityID = - @"TabGridDoneButtonAccessibilityID"; - namespace { // Types of configurations of this view controller. typedef NS_ENUM(NSUInteger, TabGridConfiguration) { @@ -310,6 +306,8 @@ [viewController didMoveToParentViewController:self]; viewController.emptyStateView = [[TabGridEmptyStateView alloc] initWithPage:TabGridPageIncognitoTabs]; + viewController.emptyStateView.accessibilityIdentifier = + kTabGridIncognitoTabsEmptyStateIdentifier; viewController.theme = GridThemeDark; viewController.delegate = self; if (@available(iOS 11, *)) { @@ -342,6 +340,8 @@ [viewController didMoveToParentViewController:self]; viewController.emptyStateView = [[TabGridEmptyStateView alloc] initWithPage:TabGridPageRegularTabs]; + viewController.emptyStateView.accessibilityIdentifier = + kTabGridRegularTabsEmptyStateIdentifier; viewController.theme = GridThemeLight; viewController.delegate = self; if (@available(iOS 11, *)) { @@ -525,7 +525,9 @@ [UIFont preferredFontForTextStyle:UIFontTextStyleBody]; self.doneButton.titleLabel.adjustsFontForContentSizeCategory = YES; self.closeAllButton.titleLabel.adjustsFontForContentSizeCategory = YES; - self.doneButton.accessibilityIdentifier = kTabGridDoneButtonAccessibilityID; + self.doneButton.accessibilityIdentifier = kTabGridDoneButtonIdentifier; + self.closeAllButton.accessibilityIdentifier = + kTabGridCloseAllButtonIdentifier; [self.doneButton addTarget:self action:@selector(doneButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
diff --git a/ios/chrome/browser/ui/toolbar/adaptive/adaptive_toolbar_view_controller.mm b/ios/chrome/browser/ui/toolbar/adaptive/adaptive_toolbar_view_controller.mm index 9da4f3ed..152b089e 100644 --- a/ios/chrome/browser/ui/toolbar/adaptive/adaptive_toolbar_view_controller.mm +++ b/ios/chrome/browser/ui/toolbar/adaptive/adaptive_toolbar_view_controller.mm
@@ -67,7 +67,8 @@ [self addStandardActionsForAllButtons]; // Adds the layout guide to the buttons. - self.view.toolsMenuButton.guideName = kTabSwitcherGuide; + self.view.toolsMenuButton.guideName = kToolsMenuGuide; + self.view.tabGridButton.guideName = kTabSwitcherGuide; self.view.forwardButton.guideName = kForwardButtonGuide; self.view.backButton.guideName = kBackButtonGuide;
diff --git a/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view.mm b/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view.mm index f5df865..b42720a 100644 --- a/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view.mm +++ b/ios/chrome/browser/ui/toolbar/adaptive/primary_toolbar_view.mm
@@ -315,13 +315,7 @@ // locationBarView constraints, if present. if (self.locationBarView) { - AddSameConstraintsToSides( - self.locationBarView, self.locationBarContainer, - LayoutSides::kTop | LayoutSides::kBottom | LayoutSides::kLeading); - [self.locationBarContainer.trailingAnchor - constraintGreaterThanOrEqualToAnchor:self.locationBarView - .trailingAnchor] - .active = YES; + AddSameConstraints(self.locationBarView, self.locationBarContainer); } // Cancel button constraints. @@ -368,9 +362,7 @@ return; [self.locationBarContainer addSubview:locationBarView]; - AddSameConstraintsToSides( - self.locationBarView, self.locationBarContainer, - LayoutSides::kTop | LayoutSides::kBottom | LayoutSides::kLeading); + AddSameConstraints(self.locationBarView, self.locationBarContainer); [self.locationBarContainer.trailingAnchor constraintGreaterThanOrEqualToAnchor:self.locationBarView.trailingAnchor] .active = YES;
diff --git a/ios/web/navigation/wk_based_navigation_manager_impl.mm b/ios/web/navigation/wk_based_navigation_manager_impl.mm index 600641943..b24c730 100644 --- a/ios/web/navigation/wk_based_navigation_manager_impl.mm +++ b/ios/web/navigation/wk_based_navigation_manager_impl.mm
@@ -137,12 +137,18 @@ // in-progress navigation is a back-forward navigation. In this case, current // item has already been updated to point to the new location in back-forward // history, so pending item index should be set to the current item index. + // Similarly, current item should be reused when reloading a placeholder URL. id<CRWWebViewNavigationProxy> proxy = delegate_->GetWebViewNavigationProxy(); WKBackForwardListItem* current_wk_item = proxy.backForwardList.currentItem; GURL current_item_url = net::GURLWithNSURL(current_wk_item.URL); + bool current_item_is_pending_item = + current_item_url == pending_item_->GetURL() || + current_item_url == + placeholder_navigation_util::CreatePlaceholderUrlForUrl( + pending_item_->GetURL()); if (proxy.backForwardList.currentItem && current_item_url == net::GURLWithNSURL(proxy.URL) && - current_item_url == pending_item_->GetURL()) { + current_item_is_pending_item) { pending_item_index_ = GetWKCurrentItemIndex(); // If |currentItem| is not already associated with a NavigationItemImpl,
diff --git a/ios/web/navigation/wk_based_navigation_manager_impl_unittest.mm b/ios/web/navigation/wk_based_navigation_manager_impl_unittest.mm index 7193489..572c5a9 100644 --- a/ios/web/navigation/wk_based_navigation_manager_impl_unittest.mm +++ b/ios/web/navigation/wk_based_navigation_manager_impl_unittest.mm
@@ -292,6 +292,24 @@ EXPECT_EQ(original_item0, manager_->GetPendingItem()); } +// Tests that AddPendingItem does not create a new NavigationItem if the new +// pending item is a reload of app-specific URL. +TEST_F(WKBasedNavigationManagerTest, ReusePendingItemForReloadAppSpecificURL) { + // Simulate a previous app-specific navigation. + NSString* url = @"about:blank?for=chrome%3A%2F%2Fnewtab"; + [mock_wk_list_ setCurrentURL:url]; + NavigationItem* original_item = manager_->GetItemAtIndex(0); + + OCMExpect([mock_web_view_ URL]).andReturn([[NSURL alloc] initWithString:url]); + + manager_->AddPendingItem( + GURL("chrome://newtab"), Referrer(), ui::PAGE_TRANSITION_RELOAD, + web::NavigationInitiationType::USER_INITIATED, + web::NavigationManager::UserAgentOverrideOption::INHERIT); + + EXPECT_EQ(original_item, manager_->GetPendingItem()); +} + // Tests that transient URL rewriters are only applied to a new pending item. TEST_F(WKBasedNavigationManagerTest, TransientURLRewritersOnlyUsedForPendingItem) {
diff --git a/media/audio/PRESUBMIT.py b/media/audio/PRESUBMIT.py index 4cd32d6..a517435 100644 --- a/media/audio/PRESUBMIT.py +++ b/media/audio/PRESUBMIT.py
@@ -23,6 +23,6 @@ 'luci.chromium.try:linux_optional_gpu_tests_rel', 'luci.chromium.try:mac_optional_gpu_tests_rel', 'master.tryserver.chromium.win:win_optional_gpu_tests_rel', - 'master.tryserver.chromium.android:android_optional_gpu_tests_rel', + 'luci.chromium.try:android_optional_gpu_tests_rel', ], 'Automatically added optional GPU tests to run on CQ.')
diff --git a/media/filters/PRESUBMIT.py b/media/filters/PRESUBMIT.py index e8b1f08..3adf448 100644 --- a/media/filters/PRESUBMIT.py +++ b/media/filters/PRESUBMIT.py
@@ -23,6 +23,6 @@ 'luci.chromium.try:linux_optional_gpu_tests_rel', 'luci.chromium.try:mac_optional_gpu_tests_rel', 'master.tryserver.chromium.win:win_optional_gpu_tests_rel', - 'master.tryserver.chromium.android:android_optional_gpu_tests_rel', + 'luci.chromium.try:android_optional_gpu_tests_rel', ], 'Automatically added optional GPU tests to run on CQ.')
diff --git a/media/gpu/PRESUBMIT.py b/media/gpu/PRESUBMIT.py index 6d49ed3..5d79d65d 100644 --- a/media/gpu/PRESUBMIT.py +++ b/media/gpu/PRESUBMIT.py
@@ -23,6 +23,6 @@ 'luci.chromium.try:linux_optional_gpu_tests_rel', 'luci.chromium.try:mac_optional_gpu_tests_rel', 'master.tryserver.chromium.win:win_optional_gpu_tests_rel', - 'master.tryserver.chromium.android:android_optional_gpu_tests_rel', + 'luci.chromium.try:android_optional_gpu_tests_rel', ], 'Automatically added optional GPU tests to run on CQ.')
diff --git a/media/renderers/default_renderer_factory.cc b/media/renderers/default_renderer_factory.cc index 755881c..a740d11c 100644 --- a/media/renderers/default_renderer_factory.cc +++ b/media/renderers/default_renderer_factory.cc
@@ -48,11 +48,19 @@ namespace media { +// TODO(dalecurtis): Remove this flag once committed to using either the +// GpuMemoryBufferDecoderWrapper or VideoRendererImpl + DecoderStream prepare. +// http://crbug.com/801245 +#define USE_VIDEO_RENDERER_GMB + static std::unique_ptr<VideoDecoder> MaybeUseGpuMemoryBufferWrapper( GpuVideoAcceleratorFactories* gpu_factories, scoped_refptr<base::SingleThreadTaskRunner> media_task_runner, scoped_refptr<base::TaskRunner> worker_task_runner, std::unique_ptr<VideoDecoder> decoder) { +#if defined(USE_VIDEO_RENDERER_GMB) + return decoder; +#else if (!gpu_factories || !gpu_factories->ShouldUseGpuMemoryBuffersForVideoFrames()) { return decoder; @@ -63,6 +71,7 @@ std::move(media_task_runner), std::move(worker_task_runner), gpu_factories), std::move(decoder)); +#endif } DefaultRendererFactory::DefaultRendererFactory( @@ -187,6 +196,16 @@ if (!get_gpu_factories_cb_.is_null()) gpu_factories = get_gpu_factories_cb_.Run(); + std::unique_ptr<GpuMemoryBufferVideoFramePool> gmb_pool; +#if defined(USE_VIDEO_RENDERER_GMB) + if (gpu_factories && + gpu_factories->ShouldUseGpuMemoryBuffersForVideoFrames()) { + gmb_pool = std::make_unique<GpuMemoryBufferVideoFramePool>( + std::move(media_task_runner), std::move(worker_task_runner), + gpu_factories); + } +#endif + std::unique_ptr<VideoRenderer> video_renderer(new VideoRendererImpl( media_task_runner, video_renderer_sink, // Unretained is safe here, because the RendererFactory is guaranteed to @@ -198,7 +217,7 @@ base::Bind(&DefaultRendererFactory::CreateVideoDecoders, base::Unretained(this), media_task_runner, worker_task_runner, request_overlay_info_cb, target_color_space, gpu_factories), - true, media_log_)); + true, media_log_, std::move(gmb_pool))); return std::make_unique<RendererImpl>( media_task_runner, std::move(audio_renderer), std::move(video_renderer));
diff --git a/media/renderers/video_renderer_impl.cc b/media/renderers/video_renderer_impl.cc index b2a6e92..5403edbe 100644 --- a/media/renderers/video_renderer_impl.cc +++ b/media/renderers/video_renderer_impl.cc
@@ -109,11 +109,13 @@ VideoRendererSink* sink, const CreateVideoDecodersCB& create_video_decoders_cb, bool drop_frames, - MediaLog* media_log) + MediaLog* media_log, + std::unique_ptr<GpuMemoryBufferVideoFramePool> gmb_pool) : task_runner_(media_task_runner), sink_(sink), sink_started_(false), client_(nullptr), + gpu_memory_buffer_pool_(std::move(gmb_pool)), media_log_(media_log), low_delay_(false), received_end_of_stream_(false), @@ -177,6 +179,8 @@ // Reset |video_frame_stream_| and drop any pending read callbacks from it. pending_read_ = false; + if (gpu_memory_buffer_pool_) + gpu_memory_buffer_pool_->Abort(); frame_callback_weak_factory_.InvalidateWeakPtrs(); video_frame_stream_->Reset( base::Bind(&VideoRendererImpl::OnVideoFrameStreamResetDone, @@ -446,6 +450,22 @@ } } +void VideoRendererImpl::FrameReadyForCopyingToGpuMemoryBuffers( + base::TimeTicks read_time, + VideoFrameStream::Status status, + const scoped_refptr<VideoFrame>& frame) { + if (status != VideoFrameStream::OK || IsBeforeStartTime(frame->timestamp())) { + VideoRendererImpl::FrameReady(read_time, status, frame); + return; + } + + DCHECK(frame); + gpu_memory_buffer_pool_->MaybeCreateHardwareFrame( + frame, base::BindOnce(&VideoRendererImpl::FrameReady, + frame_callback_weak_factory_.GetWeakPtr(), + read_time, status)); +} + void VideoRendererImpl::FrameReady(base::TimeTicks read_time, VideoFrameStream::Status status, const scoped_refptr<VideoFrame>& frame) { @@ -648,9 +668,19 @@ switch (state_) { case kPlaying: pending_read_ = true; - video_frame_stream_->Read(base::BindRepeating( - &VideoRendererImpl::FrameReady, - frame_callback_weak_factory_.GetWeakPtr(), tick_clock_->NowTicks())); + if (gpu_memory_buffer_pool_) { + // TODO(dalecurtis): Move this functionality into DecoderStream via the + // concept of "prepared" buffers. + video_frame_stream_->Read(base::BindRepeating( + &VideoRendererImpl::FrameReadyForCopyingToGpuMemoryBuffers, + frame_callback_weak_factory_.GetWeakPtr(), + tick_clock_->NowTicks())); + } else { + video_frame_stream_->Read( + base::BindRepeating(&VideoRendererImpl::FrameReady, + frame_callback_weak_factory_.GetWeakPtr(), + tick_clock_->NowTicks())); + } return; case kUninitialized: case kInitializing:
diff --git a/media/renderers/video_renderer_impl.h b/media/renderers/video_renderer_impl.h index 50163612..cb11c29 100644 --- a/media/renderers/video_renderer_impl.h +++ b/media/renderers/video_renderer_impl.h
@@ -28,6 +28,7 @@ #include "media/filters/decoder_stream.h" #include "media/filters/video_renderer_algorithm.h" #include "media/renderers/default_renderer_factory.h" +#include "media/video/gpu_memory_buffer_video_frame_pool.h" namespace base { class SingleThreadTaskRunner; @@ -55,7 +56,8 @@ VideoRendererSink* sink, const CreateVideoDecodersCB& create_video_decoders_cb, bool drop_frames, - MediaLog* media_log); + MediaLog* media_log, + std::unique_ptr<GpuMemoryBufferVideoFramePool> gmb_pool); ~VideoRendererImpl() override; // VideoRenderer implementation. @@ -105,6 +107,15 @@ void OnConfigChange(const VideoDecoderConfig& config); // Callback for |video_frame_stream_| to deliver decoded video frames and + // report video decoding status. If a frame is available the planes will be + // copied asynchronously and FrameReady will be called once finished copying. + // |read_time| is the time at which this read was started. + void FrameReadyForCopyingToGpuMemoryBuffers( + base::TimeTicks read_time, + VideoFrameStream::Status status, + const scoped_refptr<VideoFrame>& frame); + + // Callback for |video_frame_stream_| to deliver decoded video frames and // report video decoding status. |read_time| is the time at which this read // was started. void FrameReady(base::TimeTicks read_time, @@ -212,6 +223,11 @@ // Provides video frames to VideoRendererImpl. std::unique_ptr<VideoFrameStream> video_frame_stream_; + // Pool of GpuMemoryBuffers and resources used to create hardware frames. + // Ensure this is destructed after |algorithm_| for optimal memory release + // when a frames are still held by the compositor. + std::unique_ptr<GpuMemoryBufferVideoFramePool> gpu_memory_buffer_pool_; + MediaLog* media_log_; // Flag indicating low-delay mode. @@ -271,8 +287,8 @@ // Algorithm for selecting which frame to render; manages frames and all // timing related information. Ensure this is destructed before - // |video_frame_stream_| for optimal memory release when a frames are still - // held by the compositor. + // |gpu_memory_buffer_pool_| for optimal memory release when a frames are + // still held by the compositor. std::unique_ptr<VideoRendererAlgorithm> algorithm_; // Indicates that Render() was called with |background_rendering| set to true,
diff --git a/media/renderers/video_renderer_impl_unittest.cc b/media/renderers/video_renderer_impl_unittest.cc index 4514003..b0ab74b 100644 --- a/media/renderers/video_renderer_impl_unittest.cc +++ b/media/renderers/video_renderer_impl_unittest.cc
@@ -36,6 +36,7 @@ #include "media/base/video_frame.h" #include "media/base/wall_clock_time_source.h" #include "media/renderers/video_renderer_impl.h" +#include "media/video/mock_gpu_memory_buffer_video_frame_pool.h" #include "testing/gmock_mutant.h" #include "testing/gtest/include/gtest/gtest.h" @@ -91,7 +92,7 @@ message_loop_.task_runner(), null_video_sink_.get(), base::Bind(&VideoRendererImplTest::CreateVideoDecodersForTest, base::Unretained(this)), - true, &media_log_)); + true, &media_log_, nullptr)); renderer_->SetTickClockForTesting(&tick_clock_); null_video_sink_->set_tick_clock_for_testing(&tick_clock_); time_source_.set_tick_clock_for_testing(&tick_clock_); @@ -1465,4 +1466,52 @@ Destroy(); } +class VideoRendererImplAsyncAddFrameReadyTest : public VideoRendererImplTest { + public: + void InitializeWithMockGpuMemoryBufferVideoFramePool() { + renderer_.reset(new VideoRendererImpl( + message_loop_.task_runner(), null_video_sink_.get(), + base::BindRepeating(&VideoRendererImplAsyncAddFrameReadyTest:: + CreateVideoDecodersForTest, + base::Unretained(this)), + true, &media_log_, + std::make_unique<MockGpuMemoryBufferVideoFramePool>( + &frame_ready_cbs_))); + VideoRendererImplTest::Initialize(); + } + + protected: + std::vector<base::OnceClosure> frame_ready_cbs_; +}; + +TEST_F(VideoRendererImplAsyncAddFrameReadyTest, InitializeAndStartPlayingFrom) { + InitializeWithMockGpuMemoryBufferVideoFramePool(); + QueueFrames("0 10 20 30"); + EXPECT_CALL(mock_cb_, FrameReceived(HasTimestampMatcher(0))); + EXPECT_CALL(mock_cb_, OnBufferingStateChange(BUFFERING_HAVE_ENOUGH)); + EXPECT_CALL(mock_cb_, OnStatisticsUpdate(_)).Times(AnyNumber()); + EXPECT_CALL(mock_cb_, OnVideoNaturalSizeChange(_)).Times(1); + EXPECT_CALL(mock_cb_, OnVideoOpacityChange(_)).Times(1); + StartPlayingFrom(0); + ASSERT_EQ(1u, frame_ready_cbs_.size()); + + uint32_t frame_ready_index = 0; + while (frame_ready_index < frame_ready_cbs_.size()) { + std::move(frame_ready_cbs_[frame_ready_index++]).Run(); + base::RunLoop().RunUntilIdle(); + } + Destroy(); +} + +TEST_F(VideoRendererImplAsyncAddFrameReadyTest, WeakFactoryDiscardsOneFrame) { + InitializeWithMockGpuMemoryBufferVideoFramePool(); + QueueFrames("0 10 20 30"); + StartPlayingFrom(0); + Flush(); + ASSERT_EQ(1u, frame_ready_cbs_.size()); + // This frame will be discarded. + std::move(frame_ready_cbs_.front()).Run(); + Destroy(); +} + } // namespace media
diff --git a/media/test/pipeline_integration_test_base.cc b/media/test/pipeline_integration_test_base.cc index 16c7b9de..f5ee7173 100644 --- a/media/test/pipeline_integration_test_base.cc +++ b/media/test/pipeline_integration_test_base.cc
@@ -462,7 +462,7 @@ scoped_task_environment_.GetMainThreadTaskRunner(), video_sink_.get(), base::Bind(&CreateVideoDecodersForTest, &media_log_, prepend_video_decoders_cb), - false, &media_log_)); + false, &media_log_, nullptr)); if (!clockless_playback_) { audio_sink_ =
diff --git a/mojo/public/cpp/base/BUILD.gn b/mojo/public/cpp/base/BUILD.gn index a266b73..081ff8f 100644 --- a/mojo/public/cpp/base/BUILD.gn +++ b/mojo/public/cpp/base/BUILD.gn
@@ -30,6 +30,8 @@ sources = [ "big_buffer_mojom_traits.cc", "big_buffer_mojom_traits.h", + "values_mojom_traits.cc", + "values_mojom_traits.h", ] defines = [ "IS_MOJO_BASE_SHARED_TRAITS_IMPL" ] @@ -51,12 +53,14 @@ "ref_counted_memory_unittest.cc", "string16_unittest.cc", "time_unittest.cc", + "values_unittest.cc", ] public_deps = [ ":base", ":shared_typemap_traits", "//base", + "//base/test:test_support", "//mojo/public/cpp/test_support:test_utils", "//mojo/public/mojom/base", "//testing/gtest",
diff --git a/mojo/public/cpp/base/typemaps.gni b/mojo/public/cpp/base/typemaps.gni index bd906f13..0837f41ba 100644 --- a/mojo/public/cpp/base/typemaps.gni +++ b/mojo/public/cpp/base/typemaps.gni
@@ -6,10 +6,11 @@ "//mojo/public/cpp/base/big_buffer.typemap", "//mojo/public/cpp/base/big_string.typemap", "//mojo/public/cpp/base/file_error.typemap", - "//mojo/public/cpp/base/ref_counted_memory.typemap", - "//mojo/public/cpp/base/string16.typemap", - "//mojo/public/cpp/base/file.typemap", "//mojo/public/cpp/base/file_info.typemap", "//mojo/public/cpp/base/file_path.typemap", + "//mojo/public/cpp/base/file.typemap", + "//mojo/public/cpp/base/ref_counted_memory.typemap", + "//mojo/public/cpp/base/string16.typemap", "//mojo/public/cpp/base/time.typemap", + "//mojo/public/cpp/base/values.typemap", ]
diff --git a/mojo/public/cpp/base/values.typemap b/mojo/public/cpp/base/values.typemap new file mode 100644 index 0000000..8dfaa675 --- /dev/null +++ b/mojo/public/cpp/base/values.typemap
@@ -0,0 +1,16 @@ +# Copyright 2018 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +mojom = "//mojo/public/mojom/base/values.mojom" +public_headers = [ "//base/values.h" ] +traits_headers = [ "//mojo/public/cpp/base/values_mojom_traits.h" ] +public_deps = [ + "//base", + "//mojo/public/cpp/base:shared_typemap_traits", +] +type_mappings = [ + "mojo_base.mojom.Value=base::Value[move_only]", + "mojo_base.mojom.DictionaryValue=base::Value[move_only]", + "mojo_base.mojom.ListValue=base::Value[move_only]", +]
diff --git a/mojo/public/cpp/base/values_mojom_traits.cc b/mojo/public/cpp/base/values_mojom_traits.cc new file mode 100644 index 0000000..2593066 --- /dev/null +++ b/mojo/public/cpp/base/values_mojom_traits.cc
@@ -0,0 +1,94 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "mojo/public/cpp/base/values_mojom_traits.h" + +#include <memory> +#include <utility> + +#include "base/strings/string_piece.h" + +namespace mojo { + +bool StructTraits<mojo_base::mojom::DictionaryValueDataView, base::Value>::Read( + mojo_base::mojom::DictionaryValueDataView data, + base::Value* value_out) { + mojo::MapDataView<mojo::StringDataView, mojo_base::mojom::ValueDataView> view; + data.GetStorageDataView(&view); + std::vector<base::Value::DictStorage::value_type> dict_storage; + dict_storage.reserve(view.size()); + for (size_t i = 0; i < view.size(); ++i) { + base::StringPiece key; + auto value = std::make_unique<base::Value>(); + if (!view.keys().Read(i, &key) || !view.values().Read(i, value.get())) + return false; + dict_storage.emplace_back(key.as_string(), std::move(value)); + } + *value_out = base::Value(base::Value::DictStorage(std::move(dict_storage), + base::KEEP_LAST_OF_DUPES)); + return true; +} + +bool StructTraits<mojo_base::mojom::ListValueDataView, base::Value>::Read( + mojo_base::mojom::ListValueDataView data, + base::Value* value_out) { + mojo::ArrayDataView<mojo_base::mojom::ValueDataView> view; + data.GetStorageDataView(&view); + base::Value::ListStorage list_storage(view.size()); + for (size_t i = 0; i < view.size(); ++i) { + if (!view.Read(i, &list_storage[i])) + return false; + } + *value_out = base::Value(std::move(list_storage)); + return true; +} + +bool UnionTraits<mojo_base::mojom::ValueDataView, base::Value>::Read( + mojo_base::mojom::ValueDataView data, + base::Value* value_out) { + switch (data.tag()) { + case mojo_base::mojom::ValueDataView::Tag::NULL_VALUE: { + *value_out = base::Value(); + return true; + } + case mojo_base::mojom::ValueDataView::Tag::BOOL_VALUE: { + *value_out = base::Value(data.bool_value()); + return true; + } + case mojo_base::mojom::ValueDataView::Tag::INT_VALUE: { + *value_out = base::Value(data.int_value()); + return true; + } + case mojo_base::mojom::ValueDataView::Tag::DOUBLE_VALUE: { + *value_out = base::Value(data.double_value()); + return true; + } + case mojo_base::mojom::ValueDataView::Tag::STRING_VALUE: { + base::StringPiece string_piece; + if (!data.ReadStringValue(&string_piece)) + return false; + *value_out = base::Value(string_piece); + return true; + } + case mojo_base::mojom::ValueDataView::Tag::BINARY_VALUE: { + mojo::ArrayDataView<uint8_t> binary_data_view; + data.GetBinaryValueDataView(&binary_data_view); + const char* data_pointer = + reinterpret_cast<const char*>(binary_data_view.data()); + base::Value::BlobStorage blob_storage( + data_pointer, data_pointer + binary_data_view.size()); + *value_out = base::Value(std::move(blob_storage)); + return true; + } + case mojo_base::mojom::ValueDataView::Tag::DICTIONARY_VALUE: { + return data.ReadDictionaryValue(value_out); + } + case mojo_base::mojom::ValueDataView::Tag::LIST_VALUE: { + return data.ReadListValue(value_out); + } + } + return false; +} + +} // namespace mojo
diff --git a/mojo/public/cpp/base/values_mojom_traits.h b/mojo/public/cpp/base/values_mojom_traits.h new file mode 100644 index 0000000..ee1dbee --- /dev/null +++ b/mojo/public/cpp/base/values_mojom_traits.h
@@ -0,0 +1,130 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef MOJO_PUBLIC_CPP_BASE_VALUES_MOJOM_TRAITS_H_ +#define MOJO_PUBLIC_CPP_BASE_VALUES_MOJOM_TRAITS_H_ + +#include <vector> + +#include "base/component_export.h" +#include "base/values.h" +#include "mojo/public/cpp/bindings/map_traits.h" +#include "mojo/public/cpp/bindings/struct_traits.h" +#include "mojo/public/cpp/bindings/union_traits.h" +#include "mojo/public/mojom/base/values.mojom-shared.h" + +namespace mojo { + +template <> +struct MapTraits<base::Value> { + using Key = std::string; + using Value = base::Value; + using Iterator = base::Value::const_dict_iterator_proxy::const_iterator; + + static size_t GetSize(const base::Value& input) { + DCHECK(input.is_dict()); + return static_cast<const base::DictionaryValue&>(input).size(); + } + + static Iterator GetBegin(const base::Value& input) { + DCHECK(input.is_dict()); + return input.DictItems().cbegin(); + } + + static void AdvanceIterator(Iterator& iterator) { ++iterator; } + + static const Key& GetKey(const Iterator& iterator) { return iterator->first; } + + static const Value& GetValue(const Iterator& iterator) { + return iterator->second; + } +}; + +template <> +struct COMPONENT_EXPORT(MOJO_BASE_SHARED_TRAITS) + StructTraits<mojo_base::mojom::DictionaryValueDataView, base::Value> { + static const base::Value& storage(const base::Value& value) { + DCHECK(value.is_dict()); + return value; + } + + static bool Read(mojo_base::mojom::DictionaryValueDataView data, + base::Value* value); +}; + +template <> +struct COMPONENT_EXPORT(MOJO_BASE_SHARED_TRAITS) + StructTraits<mojo_base::mojom::ListValueDataView, base::Value> { + static const base::Value::ListStorage& storage(const base::Value& value) { + DCHECK(value.is_list()); + return value.GetList(); + } + + static bool Read(mojo_base::mojom::ListValueDataView data, + base::Value* value); +}; + +template <> +struct COMPONENT_EXPORT(MOJO_BASE_SHARED_TRAITS) + UnionTraits<mojo_base::mojom::ValueDataView, base::Value> { + static mojo_base::mojom::ValueDataView::Tag GetTag(const base::Value& data) { + switch (data.type()) { + case base::Value::Type::NONE: + return mojo_base::mojom::ValueDataView::Tag::NULL_VALUE; + case base::Value::Type::BOOLEAN: + return mojo_base::mojom::ValueDataView::Tag::BOOL_VALUE; + case base::Value::Type::INTEGER: + return mojo_base::mojom::ValueDataView::Tag::INT_VALUE; + case base::Value::Type::DOUBLE: + return mojo_base::mojom::ValueDataView::Tag::DOUBLE_VALUE; + case base::Value::Type::STRING: + return mojo_base::mojom::ValueDataView::Tag::STRING_VALUE; + case base::Value::Type::BINARY: + return mojo_base::mojom::ValueDataView::Tag::BINARY_VALUE; + case base::Value::Type::DICTIONARY: + return mojo_base::mojom::ValueDataView::Tag::DICTIONARY_VALUE; + case base::Value::Type::LIST: + return mojo_base::mojom::ValueDataView::Tag::LIST_VALUE; + } + NOTREACHED(); + return mojo_base::mojom::ValueDataView::Tag::NULL_VALUE; + } + + static uint8_t null_value(const base::Value& value) { return 0; } + + static bool bool_value(const base::Value& value) { return value.GetBool(); } + + static int32_t int_value(const base::Value& value) { return value.GetInt(); } + + static double double_value(const base::Value& value) { + return value.GetDouble(); + } + + static base::StringPiece string_value(const base::Value& value) { + return value.GetString(); + } + + static base::span<const uint8_t> binary_value(const base::Value& value) { + // TODO(dcheng): Change base::Value::BlobStorage to uint8_t. + return base::make_span( + reinterpret_cast<const uint8_t*>(value.GetBlob().data()), + value.GetBlob().size()); + } + + static const base::Value& list_value(const base::Value& value) { + DCHECK(value.is_list()); + return value; + } + static const base::Value& dictionary_value(const base::Value& value) { + DCHECK(value.is_dict()); + return value; + } + + static bool Read(mojo_base::mojom::ValueDataView view, + base::Value* value_out); +}; + +} // namespace mojo + +#endif // MOJO_PUBLIC_CPP_BASE_VALUES_MOJOM_TRAITS_H_
diff --git a/mojo/public/cpp/base/values_unittest.cc b/mojo/public/cpp/base/values_unittest.cc new file mode 100644 index 0000000..169572bb --- /dev/null +++ b/mojo/public/cpp/base/values_unittest.cc
@@ -0,0 +1,160 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <string> +#include <utility> + +#include "base/test/gtest_util.h" +#include "base/values.h" +#include "mojo/public/cpp/base/values_mojom_traits.h" +#include "mojo/public/cpp/test_support/test_utils.h" +#include "mojo/public/mojom/base/values.mojom.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace mojo_base { + +TEST(ValuesStructTraitsTest, NullValue) { + base::Value in; + base::Value out; + ASSERT_TRUE(mojo::test::SerializeAndDeserialize<mojom::Value>(&in, &out)); + EXPECT_EQ(in, out); +} + +TEST(ValuesStructTraitsTest, BoolValue) { + static constexpr bool kTestCases[] = {true, false}; + for (auto& test_case : kTestCases) { + base::Value in(test_case); + base::Value out; + ASSERT_TRUE(mojo::test::SerializeAndDeserialize<mojom::Value>(&in, &out)); + EXPECT_EQ(in, out); + } +} + +TEST(ValuesStructTraitsTest, IntValue) { + static constexpr int kTestCases[] = {0, -1, 1, + std::numeric_limits<int>::min(), + std::numeric_limits<int>::max()}; + for (auto& test_case : kTestCases) { + base::Value in(test_case); + base::Value out; + ASSERT_TRUE(mojo::test::SerializeAndDeserialize<mojom::Value>(&in, &out)); + EXPECT_EQ(in, out); + } +} + +TEST(ValuesStructTraitsTest, DoubleValue) { + static constexpr double kTestCases[] = {-0.0, + +0.0, + -1.0, + +1.0, + std::numeric_limits<double>::min(), + std::numeric_limits<double>::max()}; + for (auto& test_case : kTestCases) { + base::Value in(test_case); + base::Value out; + ASSERT_TRUE(mojo::test::SerializeAndDeserialize<mojom::Value>(&in, &out)); + EXPECT_EQ(in, out); + } +} + +TEST(ValuesStructTraitsTest, StringValue) { + static constexpr const char* kTestCases[] = { + "", "ascii", + // 🎆: Unicode FIREWORKS + "\xf0\x9f\x8e\x86", + }; + for (auto* test_case : kTestCases) { + base::Value in(test_case); + base::Value out; + ASSERT_TRUE(mojo::test::SerializeAndDeserialize<mojom::Value>(&in, &out)); + EXPECT_EQ(in, out); + } +} + +TEST(ValuesStructTraitsTest, BinaryValue) { + std::vector<char> kBinaryData = {'\x00', '\x80', '\xff', '\x7f', '\x01'}; + base::Value in(std::move(kBinaryData)); + base::Value out; + ASSERT_TRUE(mojo::test::SerializeAndDeserialize<mojom::Value>(&in, &out)); + EXPECT_EQ(in, out); +} + +TEST(ValuesStructTraitsTest, DictionaryValue) { + // Note: here and below, it would be nice to use an initializer list, but + // move-only types and initializer lists don't mix. Initializer lists can't be + // modified: thus it's not possible to move. + std::vector<base::Value::DictStorage::value_type> storage; + storage.emplace_back("null", std::make_unique<base::Value>()); + storage.emplace_back("bool", std::make_unique<base::Value>(false)); + storage.emplace_back("int", std::make_unique<base::Value>(0)); + storage.emplace_back("double", std::make_unique<base::Value>(0.0)); + storage.emplace_back("string", std::make_unique<base::Value>("0")); + storage.emplace_back( + "binary", std::make_unique<base::Value>(base::Value::BlobStorage({0}))); + storage.emplace_back( + "dictionary", std::make_unique<base::Value>(base::Value::DictStorage())); + storage.emplace_back( + "list", std::make_unique<base::Value>(base::Value::ListStorage())); + + base::Value in( + base::Value::DictStorage(std::move(storage), base::KEEP_LAST_OF_DUPES)); + base::Value out; + ASSERT_TRUE(mojo::test::SerializeAndDeserialize<mojom::Value>(&in, &out)); + EXPECT_EQ(in, out); + + ASSERT_TRUE( + mojo::test::SerializeAndDeserialize<mojom::DictionaryValue>(&in, &out)); + EXPECT_EQ(in, out); +} + +TEST(ValuesStructTraitsTest, SerializeInvalidDictionaryValue) { + base::Value in; + ASSERT_FALSE(in.is_dict()); + + base::Value out; + EXPECT_DCHECK_DEATH( + mojo::test::SerializeAndDeserialize<mojom::DictionaryValue>(&in, &out)); +} + +TEST(ValuesStructTraitsTest, ListValue) { + base::Value::ListStorage storage; + storage.emplace_back(); + storage.emplace_back(false); + storage.emplace_back(0); + storage.emplace_back(0.0); + storage.emplace_back("0"); + storage.emplace_back(base::Value::BlobStorage({0})); + storage.emplace_back(base::Value::DictStorage()); + storage.emplace_back(base::Value::ListStorage()); + base::Value in(std::move(storage)); + base::Value out; + ASSERT_TRUE(mojo::test::SerializeAndDeserialize<mojom::Value>(&in, &out)); + EXPECT_EQ(in, out); + + ASSERT_TRUE(mojo::test::SerializeAndDeserialize<mojom::ListValue>(&in, &out)); + EXPECT_EQ(in, out); +} + +TEST(ValuesStructTraitsTest, SerializeInvalidListValue) { + base::Value in; + ASSERT_FALSE(in.is_dict()); + + base::Value out; + EXPECT_DCHECK_DEATH( + mojo::test::SerializeAndDeserialize<mojom::ListValue>(&in, &out)); +} + +// A deeply nested base::Value should trigger a deserialization error. +TEST(ValuesStructTraitsTest, DeeplyNestedValue) { + base::Value in; + for (int i = 0; i < 100; ++i) { + base::Value::ListStorage storage; + storage.emplace_back(std::move(in)); + in = base::Value(std::move(storage)); + } + base::Value out; + ASSERT_FALSE(mojo::test::SerializeAndDeserialize<mojom::Value>(&in, &out)); +} + +} // namespace mojo_base
diff --git a/mojo/public/mojom/base/BUILD.gn b/mojo/public/mojom/base/BUILD.gn index 7f6ba328..5e4ffae 100644 --- a/mojo/public/mojom/base/BUILD.gn +++ b/mojo/public/mojom/base/BUILD.gn
@@ -15,6 +15,7 @@ "ref_counted_memory.mojom", "string16.mojom", "time.mojom", + "values.mojom", ] output_prefix = "mojo_base_mojom"
diff --git a/mojo/public/mojom/base/values.mojom b/mojo/public/mojom/base/values.mojom new file mode 100644 index 0000000..ea7c1fa --- /dev/null +++ b/mojo/public/mojom/base/values.mojom
@@ -0,0 +1,38 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +module mojo_base.mojom; + +// Value represents a value that can be serialized to/from JSON. +// +// One notable caveat is that Value supports arbitrary binary data, which JSON +// does not support natively. +union Value { + // Null type placeholder. This field is never used. + uint8 null_value; + // Primitive types. + bool bool_value; + int32 int_value; + double double_value; + // Unicode string. + string string_value; + // Binary blob with arbitrary bytes. Not supported for JSON. + array<uint8> binary_value; + // Basic container support for lists and maps. + DictionaryValue dictionary_value; + ListValue list_value; +}; + +// Interfaces that only want to handle a value of dictionary or list type +// should use base.mojom.DictionaryValue or base.mojom.ListValue in the method +// declaration. Though both of these types are mapped to base::Value in C++, +// the generated deserialization will guarantee that the method is only invoked +// with a base::Value of the correct subtype. +struct DictionaryValue { + map<string, Value> storage; +}; + +struct ListValue { + array<Value> storage; +};
diff --git a/net/quic/core/quic_session.cc b/net/quic/core/quic_session.cc index e0a82cc..dd7e9fa 100644 --- a/net/quic/core/quic_session.cc +++ b/net/quic/core/quic_session.cc
@@ -929,9 +929,9 @@ } size_t QuicSession::GetNumOpenOutgoingStreams() const { - CHECK_GE(GetNumDynamicOutgoingStreams() + - GetNumLocallyClosedOutgoingStreamsHighestOffset(), - GetNumDrainingOutgoingStreams()); + DCHECK_GE(GetNumDynamicOutgoingStreams() + + GetNumLocallyClosedOutgoingStreamsHighestOffset(), + GetNumDrainingOutgoingStreams()); return GetNumDynamicOutgoingStreams() + GetNumLocallyClosedOutgoingStreamsHighestOffset() - GetNumDrainingOutgoingStreams();
diff --git a/sandbox/linux/syscall_broker/broker_file_permission.cc b/sandbox/linux/syscall_broker/broker_file_permission.cc index 05c7830..18e4c14a 100644 --- a/sandbox/linux/syscall_broker/broker_file_permission.cc +++ b/sandbox/linux/syscall_broker/broker_file_permission.cc
@@ -141,12 +141,12 @@ return false; } - // Check if read is allowed + // Check if read is allowed. if (!allow_read_ && (access_mode == O_RDONLY || access_mode == O_RDWR)) { return false; } - // Check if write is allowed + // Check if write is allowed. if (!allow_write_ && (access_mode == O_WRONLY || access_mode == O_RDWR)) { return false; } @@ -168,6 +168,12 @@ return false; } + // The effect of (O_RDONLY | O_TRUNC) is undefined, and in some cases it + // actually truncates, so deny. + if (access_mode == O_RDONLY && (flags & O_TRUNC) != 0) { + return false; + } + // Now check that all the flags are known to us. const int creation_and_status_flags = flags & ~O_ACCMODE; const int known_flags = O_APPEND | O_ASYNC | O_CLOEXEC | O_CREAT | O_DIRECT |
diff --git a/sandbox/linux/syscall_broker/broker_file_permission_unittest.cc b/sandbox/linux/syscall_broker/broker_file_permission_unittest.cc index 0071016..006cc49 100644 --- a/sandbox/linux/syscall_broker/broker_file_permission_unittest.cc +++ b/sandbox/linux/syscall_broker/broker_file_permission_unittest.cc
@@ -157,10 +157,21 @@ case O_NDELAY: #endif case kSyncFlag: - case O_TRUNC: ASSERT_TRUE( perm.CheckOpen(path, access_flags | flag, &file_to_open, NULL)); break; + case O_TRUNC: { + // The effect of (O_RDONLY | O_TRUNC) is undefined, and in some cases it + // actually truncates, so deny. + bool result = + perm.CheckOpen(path, access_flags | flag, &file_to_open, NULL); + if (access_flags == O_RDONLY) { + ASSERT_FALSE(result); + } else { + ASSERT_TRUE(result); + } + break; + } case O_CREAT: continue; // Handled below. case O_CLOEXEC: @@ -197,6 +208,14 @@ // expected. } +// Explicit test for O_RDONLY|O_TRUNC, which should be denied due to +// undefined behavior. +TEST(BrokerFilePermission, ReadOnlyTruncate) { + const char kPath[] = "/tmp/good"; + BrokerFilePermission perm = BrokerFilePermission::ReadOnly(kPath); + ASSERT_FALSE(perm.CheckOpen(kPath, O_RDONLY | O_TRUNC, nullptr, nullptr)); +} + TEST(BrokerFilePermission, WriteOnly) { const char kPath[] = "/tmp/good"; BrokerFilePermission perm = BrokerFilePermission::WriteOnly(kPath);
diff --git a/services/viz/PRESUBMIT.py b/services/viz/PRESUBMIT.py index 1682b4b4..f92af6d 100644 --- a/services/viz/PRESUBMIT.py +++ b/services/viz/PRESUBMIT.py
@@ -29,6 +29,6 @@ return output_api.EnsureCQIncludeTrybotsAreAdded( cl, [ - 'master.tryserver.chromium.android:android_optional_gpu_tests_rel', + 'luci.chromium.try:android_optional_gpu_tests_rel', ], 'Automatically added optional GPU tests to run on CQ.')
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index 23925ed..189be79 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -1092,351 +1092,6 @@ } ] }, - "Chromium Mac 10.10 MacViews": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "accessibility_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "app_shell_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "blink_heap_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "blink_platform_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "browser_tests" - }, - { - "args": [ - "--enable-surface-synchronization" - ], - "name": "surface_sync_browser_tests", - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "browser_tests" - }, - { - "args": [ - "--enable-features=VizDisplayCompositor", - "--test-launcher-filter-file=../../testing/buildbot/filters/viz.browser_tests.filter" - ], - "name": "viz_browser_tests", - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "browser_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "cast_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "cc_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "chromedriver_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "components_perftests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "components_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "content_browsertests" - }, - { - "args": [ - "--enable-surface-synchronization" - ], - "name": "surface_sync_content_browsertests", - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "content_browsertests" - }, - { - "args": [ - "--enable-features=VizDisplayCompositor", - "--test-launcher-filter-file=../../testing/buildbot/filters/viz.content_browsertests.filter" - ], - "name": "viz_content_browsertests", - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "content_unittests" - }, - { - "args": [ - "--enable-features=VizDisplayCompositor", - "--test-launcher-filter-file=../../testing/buildbot/filters/viz.content_unittests.filter" - ], - "name": "viz_content_unittests", - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "crashpad_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "gfx_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "gpu_ipc_service_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "interactive_ui_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "media_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "mojo_common_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "mojo_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "native_theme_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "net_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "sandbox_mac_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "storage_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "sync_integration_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "views_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "webkit_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": false - }, - "test": "wtf_unittests" - } - ] - }, "Chromium Mac 10.11": { "gtest_tests": [ { @@ -9426,5 +9081,356 @@ "additional_compile_targets": [ "empty_main" ] + }, + "mac-views-rel": { + "gtest_tests": [ + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "accessibility_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "app_shell_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "base_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "blink_heap_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "blink_platform_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 10 + }, + "test": "browser_tests" + }, + { + "args": [ + "--enable-surface-synchronization" + ], + "name": "surface_sync_browser_tests", + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 10 + }, + "test": "browser_tests" + }, + { + "args": [ + "--enable-features=VizDisplayCompositor", + "--test-launcher-filter-file=../../testing/buildbot/filters/viz.browser_tests.filter" + ], + "name": "viz_browser_tests", + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 10 + }, + "test": "browser_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "cacheinvalidation_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "capture_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "cast_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "cc_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "chromedriver_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "components_perftests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "components_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "content_browsertests" + }, + { + "args": [ + "--enable-surface-synchronization" + ], + "name": "surface_sync_content_browsertests", + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 2 + }, + "test": "content_browsertests" + }, + { + "args": [ + "--enable-features=VizDisplayCompositor", + "--test-launcher-filter-file=../../testing/buildbot/filters/viz.content_browsertests.filter" + ], + "name": "viz_content_browsertests", + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 2 + }, + "test": "content_browsertests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "content_unittests" + }, + { + "args": [ + "--enable-features=VizDisplayCompositor", + "--test-launcher-filter-file=../../testing/buildbot/filters/viz.content_unittests.filter" + ], + "name": "viz_content_unittests", + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "content_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "crashpad_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "crypto_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "extensions_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "gcm_unit_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "gfx_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "google_apis_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "gpu_ipc_service_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "gpu_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 2 + }, + "test": "interactive_ui_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "ipc_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "jingle_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "media_blink_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "media_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "midi_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "mojo_common_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "mojo_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "native_theme_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "net_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "pdf_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "ppapi_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "printing_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "remoting_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "sandbox_mac_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "skia_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "sql_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "storage_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "sync_integration_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "ui_base_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "unit_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "url_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "views_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "webkit_unit_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "wtf_unittests" + } + ] } }
diff --git a/testing/buildbot/chromium.win.json b/testing/buildbot/chromium.win.json index e6d140e..97cc92da 100644 --- a/testing/buildbot/chromium.win.json +++ b/testing/buildbot/chromium.win.json
@@ -1120,6 +1120,644 @@ } ] }, + "Win10 Tests x64 (dbg)": { + "gtest_tests": [ + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "accessibility_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "app_shell_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "aura_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "base_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "battor_agent_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "blink_heap_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "blink_platform_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "boringssl_crypto_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "boringssl_ssl_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 10 + }, + "test": "browser_tests" + }, + { + "args": [ + "--enable-features=VizDisplayCompositor", + "--test-launcher-filter-file=../../testing/buildbot/filters/viz.browser_tests.filter" + ], + "name": "viz_browser_tests", + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 10 + }, + "test": "browser_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "cacheinvalidation_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "capture_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "cast_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "cc_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "chrome_app_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "chrome_elf_import_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "chrome_elf_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "chromedriver_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "components_browsertests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "components_perftests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "components_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "compositor_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "content_browsertests" + }, + { + "args": [ + "--enable-features=VizDisplayCompositor", + "--test-launcher-filter-file=../../testing/buildbot/filters/viz.content_browsertests.filter" + ], + "name": "viz_content_browsertests", + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 2 + }, + "test": "content_browsertests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "content_unittests" + }, + { + "args": [ + "--enable-features=VizDisplayCompositor", + "--test-launcher-filter-file=../../testing/buildbot/filters/viz.content_unittests.filter" + ], + "name": "viz_content_unittests", + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "content_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "courgette_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "crashpad_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "crypto_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "device_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "display_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "events_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "extensions_browsertests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "extensions_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "gcm_unit_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "gfx_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "gin_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "gn_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "google_apis_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "gpu_ipc_service_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "gpu_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "headless_browsertests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "headless_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "install_static_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "integrity": "high" + } + ] + }, + "test": "installer_util_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 2 + }, + "test": "interactive_ui_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "ipc_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "jingle_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "keyboard_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "latency_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "libjingle_xmpp_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "media_blink_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "media_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "message_center_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "midi_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "mojo_common_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "mojo_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "nacl_loader_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "native_theme_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "net_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "notification_helper_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "pdf_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "ppapi_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "printing_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "remoting_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "integrity": "high" + } + ] + }, + "test": "sbox_integration_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "sbox_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "sbox_validation_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "service_manager_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "services_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "integrity": "high" + } + ] + }, + "test": "setup_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "skia_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "sql_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "storage_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "sync_integration_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "ui_base_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "ui_touch_selection_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "unit_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "url_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "views_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "viz_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "vr_common_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "vr_pixeltests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "webkit_unit_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "wm_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "wtf_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "zucchini_unittests" + } + ], + "isolated_scripts": [ + { + "isolate_name": "content_shell_crash_test", + "name": "content_shell_crash_test", + "swarming": { + "can_use_on_swarming_builders": true + } + }, + { + "isolate_name": "metrics_python_tests", + "name": "metrics_python_tests", + "swarming": { + "can_use_on_swarming_builders": true + } + }, + { + "isolate_name": "telemetry_gpu_unittests", + "name": "telemetry_gpu_unittests", + "swarming": { + "can_use_on_swarming_builders": true + } + }, + { + "isolate_name": "telemetry_perf_unittests", + "name": "telemetry_perf_unittests", + "swarming": { + "can_use_on_swarming_builders": true, + "hard_timeout": 960, + "shards": 12 + } + }, + { + "args": [ + "--jobs=1" + ], + "isolate_name": "telemetry_unittests", + "name": "telemetry_unittests", + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 4 + } + }, + { + "isolate_name": "views_perftests", + "name": "views_perftests", + "swarming": { + "can_use_on_swarming_builders": true + } + }, + { + "isolate_name": "webkit_layout_tests_exparchive", + "merge": { + "args": [ + "--verbose" + ], + "script": "//third_party/WebKit/Tools/Scripts/merge-layout-test-results" + }, + "name": "webkit_layout_tests", + "results_handler": "layout tests", + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 10 + } + }, + { + "isolate_name": "webkit_python_tests", + "name": "webkit_python_tests", + "swarming": { + "can_use_on_swarming_builders": true + } + } + ] + }, "Win7 (32) Tests": { "gtest_tests": [ {
diff --git a/testing/buildbot/test_suite_exceptions.pyl b/testing/buildbot/test_suite_exceptions.pyl index 253dd155..c032260e 100644 --- a/testing/buildbot/test_suite_exceptions.pyl +++ b/testing/buildbot/test_suite_exceptions.pyl
@@ -54,7 +54,7 @@ # chromium.clang 'ToTLinuxMSan', # chromium.fyi - 'Chromium Mac 10.10 MacViews', + 'mac-views-rel', 'Chromium Mac 10.11', 'Chromium Mac 10.11 Force Mac Toolchain', 'Chromium Mac 10.13', @@ -543,7 +543,7 @@ 'chrome_app_unittests': { 'remove_from': [ # chromium.fyi - 'Chromium Mac 10.10 MacViews', + 'mac-views-rel', 'Chromium Mac 10.11', 'Chromium Mac 10.11 Force Mac Toolchain', 'Chromium Mac 10.13', @@ -881,7 +881,7 @@ 'ToTMac', 'ToTMacASan', # chromium.fyi - 'Chromium Mac 10.10 MacViews', + 'mac-views-rel', 'Chromium Mac 10.11', 'Chromium Mac 10.11 Force Mac Toolchain', 'Chromium Mac 10.13', @@ -1469,7 +1469,7 @@ 'ToTMac', 'ToTMacASan', # chromium.fyi - 'Chromium Mac 10.10 MacViews', + 'mac-views-rel', 'Chromium Mac 10.11', 'Chromium Mac 10.11 Force Mac Toolchain', 'Chromium Mac 10.13', @@ -1535,7 +1535,7 @@ 'Unswarmed N5X Tests Dummy Builder', 'x86 Cloud Tester', # chromium.fyi - 'Chromium Mac 10.10 MacViews', + 'mac-views-rel', 'Chromium Mac 10.11 Force Mac Toolchain', # chromium.memory 'Mac ASan 64 Tests (1)', @@ -1575,7 +1575,7 @@ 'ToTMac', 'ToTMacASan', # chromium.fyi - 'Chromium Mac 10.10 MacViews', + 'mac-views-rel', 'Chromium Mac 10.11', 'Chromium Mac 10.11 Force Mac Toolchain', 'Chromium Mac 10.13', @@ -1655,7 +1655,7 @@ 'ToTLinuxASan', 'ToTLinuxMSan', # chromium.fyi - 'Chromium Mac 10.10 MacViews', + 'mac-views-rel', 'Chromium Mac 10.11', 'Chromium Mac 10.11 Force Mac Toolchain', 'Chromium Mac 10.13', @@ -1805,7 +1805,7 @@ 'ToTLinuxMSan', 'ToTLinuxUBSanVptr', # chromium.fyi - 'Chromium Mac 10.10 MacViews', + 'mac-views-rel', 'Chromium Mac 10.11', 'Chromium Mac 10.11 Force Mac Toolchain', 'Chromium Mac 10.13', @@ -2179,7 +2179,7 @@ 'ToTMac', 'ToTMacASan', # chromium.fyi - 'Chromium Mac 10.10 MacViews', + 'mac-views-rel', 'Chromium Mac 10.11', 'Chromium Mac 10.11 Force Mac Toolchain', 'Chromium Mac 10.13', @@ -2245,7 +2245,7 @@ 'Mac10.13 Tests (dbg)', # chromium.fyi - 'Chromium Mac 10.10 MacViews', + 'mac-views-rel', 'Chromium Mac 10.11', 'Chromium Mac 10.11 Force Mac Toolchain', 'Chromium Mac 10.13', @@ -2416,7 +2416,7 @@ # chromium.clang 'ToTLinuxASan', # chromium.fyi - 'Chromium Mac 10.10 MacViews', + 'mac-views-rel', 'Chromium Mac 10.11', 'Chromium Mac 10.11 Force Mac Toolchain', 'Chromium Mac 10.13', @@ -2849,7 +2849,7 @@ 'ToTLinuxMSan', 'ToTLinuxThinLTO', # chromium.fyi - 'Chromium Mac 10.10 MacViews', + 'mac-views-rel', 'Chromium Mac 10.11', 'Chromium Mac 10.11 Force Mac Toolchain', 'Chromium Mac 10.13', @@ -3055,7 +3055,7 @@ 'linux-chromeos-dbg', 'linux-chromeos-rel', # chromium.fyi - 'Chromium Mac 10.10 MacViews', + 'mac-views-rel', 'Chromium Mac 10.11', 'Chromium Mac 10.11 Force Mac Toolchain', 'Chromium Mac 10.13',
diff --git a/testing/buildbot/waterfalls.pyl b/testing/buildbot/waterfalls.pyl index 35de4aa..104f6bee 100644 --- a/testing/buildbot/waterfalls.pyl +++ b/testing/buildbot/waterfalls.pyl
@@ -943,11 +943,10 @@ 'scripts': 'check_network_annotation_auditor_script', } }, - 'Chromium Mac 10.10 MacViews': { + 'mac-views-rel': { 'test_suites': { 'gtest_tests': 'chromium_mac_fyi_gtests', }, - 'use_swarming': False, }, 'Chromium Mac 10.11': { 'test_suites': { @@ -2097,6 +2096,12 @@ 'isolated_scripts': 'chromium_dbg_isolated_scripts', }, }, + 'Win10 Tests x64 (dbg)': { + 'test_suites': { + 'gtest_tests': 'chromium_win_gtests', + 'isolated_scripts': 'chromium_dbg_isolated_scripts', + }, + }, }, }, {
diff --git a/testing/libfuzzer/fuzzers/BUILD.gn b/testing/libfuzzer/fuzzers/BUILD.gn index a3006cf..c56d538b 100644 --- a/testing/libfuzzer/fuzzers/BUILD.gn +++ b/testing/libfuzzer/fuzzers/BUILD.gn
@@ -49,24 +49,6 @@ ] } -fuzzer_test("string_tokenizer_fuzzer") { - sources = [ - "string_tokenizer_fuzzer.cc", - ] - deps = [ - "//base", - ] -} - -fuzzer_test("string_to_int_fuzzer") { - sources = [ - "string_to_int_fuzzer.cc", - ] - deps = [ - "//base", - ] -} - fuzzer_test("template_url_parser_fuzzer") { sources = [ "template_url_parser_fuzzer.cc",
diff --git a/testing/trigger_scripts/PRESUBMIT.py b/testing/trigger_scripts/PRESUBMIT.py index f4042bc..ffcd3c08 100644 --- a/testing/trigger_scripts/PRESUBMIT.py +++ b/testing/trigger_scripts/PRESUBMIT.py
@@ -42,6 +42,6 @@ 'luci.chromium.try:linux_optional_gpu_tests_rel', 'luci.chromium.try:mac_optional_gpu_tests_rel', 'master.tryserver.chromium.win:win_optional_gpu_tests_rel', - 'master.tryserver.chromium.android:android_optional_gpu_tests_rel', + 'luci.chromium.try:android_optional_gpu_tests_rel', ], 'Automatically added optional GPU tests to run on CQ.')
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 28bc3ae..158eeda 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -1757,25 +1757,6 @@ ] } ], - "LazyParseCSS": [ - { - "platforms": [ - "linux", - "mac", - "win", - "android", - "chromeos" - ], - "experiments": [ - { - "name": "Enabled", - "enable_features": [ - "LazyParseCSS" - ] - } - ] - } - ], "LocalScreenCasting": [ { "platforms": [
diff --git a/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG b/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG index 02c7246..ddba4f77b 100644 --- a/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG +++ b/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG
@@ -121,7 +121,6 @@ crbug.com/591099 compositing/overflow/get-transform-from-non-box-container.html [ Failure ] crbug.com/591099 compositing/overflow/nested-border-radius-clipping.html [ Failure ] crbug.com/591099 compositing/overflow/overflow-scroll-with-local-image-background.html [ Failure ] -crbug.com/714962 compositing/overflow/rtl-overflow.html [ Failure ] crbug.com/591099 compositing/overflow/scrolling-content-clip-to-viewport.html [ Failure ] crbug.com/591099 compositing/overflow/universal-accelerated-overflow-scroll.html [ Pass Timeout ] crbug.com/591099 compositing/overflow/update-widget-positions-on-nested-frames-and-scrollers.html [ Failure ] @@ -175,15 +174,12 @@ crbug.com/714962 css3/masking/clip-path-reference-box-inline.html [ Failure ] crbug.com/591099 css3/selectors3/html/css3-modsel-167.html [ Failure ] crbug.com/591099 css3/selectors3/html/css3-modsel-167a.html [ Failure ] -crbug.com/591099 css3/selectors3/html/css3-modsel-179a.html [ Failure ] crbug.com/591099 css3/selectors3/html/css3-modsel-38.html [ Failure ] crbug.com/591099 css3/selectors3/xhtml/css3-modsel-167.xml [ Failure ] crbug.com/591099 css3/selectors3/xhtml/css3-modsel-167a.xml [ Failure ] -crbug.com/591099 css3/selectors3/xhtml/css3-modsel-179a.xml [ Failure ] crbug.com/591099 css3/selectors3/xhtml/css3-modsel-38.xml [ Failure ] crbug.com/591099 css3/selectors3/xml/css3-modsel-167.xml [ Failure ] crbug.com/591099 css3/selectors3/xml/css3-modsel-167a.xml [ Failure ] -crbug.com/591099 css3/selectors3/xml/css3-modsel-179a.xml [ Failure ] crbug.com/591099 css3/selectors3/xml/css3-modsel-38.xml [ Failure ] crbug.com/591099 editing/assert_selection.html [ Failure ] crbug.com/591099 editing/caret/caret-color-014.html [ Failure ] @@ -999,7 +995,6 @@ crbug.com/591099 external/wpt/html/the-xhtml-syntax/parsing-xhtml-documents/xhtml-mathml-dtd-entity-4.htm [ Pass Timeout ] crbug.com/591099 external/wpt/html/the-xhtml-syntax/parsing-xhtml-documents/xhtml-mathml-dtd-entity-7.htm [ Pass Timeout ] crbug.com/591099 external/wpt/http/basic-auth-cache-test.html [ Timeout ] -crbug.com/714962 external/wpt/intersection-observer/root-margin.html [ Failure ] crbug.com/591099 external/wpt/longtask-timing/longtask-in-sibling-iframe.html [ Pass Timeout ] crbug.com/591099 external/wpt/media-source/mediasource-getvideoplaybackquality.html [ Timeout ] crbug.com/591099 external/wpt/mimesniff/mime-types/parsing.any.html [ Timeout ] @@ -1011,15 +1006,9 @@ crbug.com/591099 external/wpt/pointerevents/pointerevent_attributes_hoverable_pointers-manual.html [ Timeout ] crbug.com/591099 external/wpt/pointerevents/pointerevent_click_during_capture-manual.html [ Crash Timeout ] crbug.com/591099 external/wpt/pointerevents/pointerevent_pointerleave_pen-manual.html [ Failure ] -crbug.com/714962 external/wpt/pointerevents/pointerevent_touch-action-auto-css_touch-manual.html [ Timeout ] -crbug.com/591099 external/wpt/pointerevents/pointerevent_touch-action-button-test_touch-manual.html [ Timeout ] -crbug.com/714962 external/wpt/pointerevents/pointerevent_touch-action-keyboard-manual.html [ Timeout ] crbug.com/714962 external/wpt/pointerevents/pointerevent_touch-action-mouse-manual.html [ Pass Timeout ] crbug.com/714962 external/wpt/pointerevents/pointerevent_touch-action-pan-left-css_touch-manual.html [ Pass ] -crbug.com/714962 external/wpt/pointerevents/pointerevent_touch-action-pan-right-css_touch-manual.html [ Failure ] -crbug.com/714962 external/wpt/pointerevents/pointerevent_touch-action-pan-x-pan-y_touch-manual.html [ Timeout ] -crbug.com/591099 external/wpt/pointerevents/pointerevent_touch-action-span-test_touch-manual.html [ Timeout ] -crbug.com/591099 external/wpt/pointerevents/pointerevent_touch-action-svg-test_touch-manual.html [ Timeout ] +crbug.com/591099 external/wpt/pointerevents/pointerevent_touch-action-span-test_touch-manual.html [ Failure ] crbug.com/591099 external/wpt/quirks/line-height-calculation.html [ Failure ] crbug.com/591099 external/wpt/quirks/table-cell-width-calculation.html [ Pass ] crbug.com/591099 external/wpt/requestidlecallback/basic.html [ Pass ] @@ -1157,9 +1146,6 @@ crbug.com/591099 fast/borders/inline-mask-overlay-image-outset.html [ Failure ] crbug.com/591099 fast/borders/inline-mask-overlay-image.html [ Failure ] crbug.com/591099 fast/borders/outline-alpha-inline.html [ Failure ] -crbug.com/591099 fast/borders/rtl-border-01.html [ Failure ] -crbug.com/591099 fast/borders/rtl-border-02.html [ Failure ] -crbug.com/591099 fast/borders/rtl-border-03.html [ Failure ] crbug.com/591099 fast/borders/rtl-border-05.html [ Failure ] crbug.com/714962 fast/borders/table-borders.html [ Failure ] crbug.com/591099 fast/box-decoration-break/box-decoration-break-rendering.html [ Failure ] @@ -1267,7 +1253,6 @@ crbug.com/591099 fast/css-grid-layout/implicit-position-dynamic-change.html [ Failure ] crbug.com/591099 fast/css-grid-layout/maximize-tracks-definite-indefinite-height.html [ Failure ] crbug.com/591099 fast/css-grid-layout/maximize-tracks-definite-indefinite-width.html [ Failure ] -crbug.com/591099 fast/css-grid-layout/min-width-height-auto-overflow.html [ Failure ] crbug.com/591099 fast/css-grid-layout/minmax-fixed-logical-height-only.html [ Failure ] crbug.com/591099 fast/css-grid-layout/minmax-fixed-logical-width-only.html [ Failure ] crbug.com/591099 fast/css-grid-layout/minmax-max-content-resolution-columns.html [ Failure ] @@ -1417,7 +1402,6 @@ crbug.com/591099 fast/dom/nodesFromRect/nodesFromRect-inline-image.html [ Failure ] crbug.com/591099 fast/dom/nodesFromRect/nodesFromRect-inner-documents.html [ Failure ] crbug.com/714962 fast/dom/nodesFromRect/nodesFromRect-links-and-text.html [ Failure ] -crbug.com/591099 fast/dom/rtl-scroll-to-leftmost-and-resize.html [ Failure ] crbug.com/714962 fast/dom/shadow/scrollbar.html [ Crash ] crbug.com/591099 fast/dom/shadow/selections-in-shadow.html [ Timeout ] crbug.com/591099 fast/dom/wrapper-classes.html [ Timeout ] @@ -1453,7 +1437,6 @@ crbug.com/591099 fast/events/wheel/mainthread-touchpad-fling-latching.html [ Pass ] crbug.com/591099 fast/events/wheel/mouse-wheel-scroll-latching.html [ Pass ] crbug.com/591099 fast/events/wheel/wheel-scroll-latching-on-scrollbar.html [ Pass ] -crbug.com/714962 fast/events/wheel/wheelevent-basic.html [ Failure ] crbug.com/591099 fast/forms/calendar-picker/calendar-picker-key-operations.html [ Pass Timeout ] crbug.com/714962 fast/forms/calendar-picker/calendar-picker-mouse-operations.html [ Failure ] crbug.com/591099 fast/forms/calendar-picker/month-picker-key-operations.html [ Timeout ] @@ -1463,7 +1446,6 @@ crbug.com/591099 fast/forms/control-clip-overflow.html [ Failure ] crbug.com/591099 fast/forms/fieldset/fieldset-with-float.html [ Failure ] crbug.com/591099 fast/forms/form-hides-table.html [ Failure ] -crbug.com/591099 fast/forms/huge-mac-input-clamped-width.html [ Failure ] crbug.com/714962 fast/forms/label/continous-click-on-label.html [ Failure ] crbug.com/591099 fast/forms/label/label-selection-by-textSelection-and-click.html [ Failure Pass ] crbug.com/591099 fast/forms/long-text-in-input.html [ Crash Failure ] @@ -1889,10 +1871,7 @@ crbug.com/591099 fast/multicol/vertical-rl/unsplittable-inline-block.html [ Failure ] crbug.com/591099 fast/multicol/widows-and-orphans.html [ Failure ] crbug.com/591099 fast/multicol/widows.html [ Failure ] -crbug.com/714962 fast/overflow/005.html [ Failure ] -crbug.com/714962 fast/overflow/006.html [ Failure ] crbug.com/591099 fast/overflow/007.html [ Failure ] -crbug.com/714962 fast/overflow/childFocusRingClip.html [ Failure ] crbug.com/591099 fast/overflow/height-during-simplified-layout.html [ Failure ] crbug.com/591099 fast/overflow/image-selection-highlight.html [ Failure ] crbug.com/714962 fast/overflow/line-clamp-hides-trailing-anchor.html [ Failure ] @@ -1902,10 +1881,7 @@ crbug.com/714962 fast/overflow/overflow-text-hit-testing.html [ Failure ] crbug.com/591099 fast/overflow/overflow-update-transform.html [ Failure ] crbug.com/591099 fast/overflow/overflow-with-local-background-attachment.html [ Failure ] -crbug.com/714962 fast/overflow/overflow-x-y.html [ Failure ] crbug.com/591099 fast/overflow/recompute-overflow-of-layout-root-container.html [ Failure ] -crbug.com/591099 fast/overflow/replaced-child-100percent-height-inside-fixed-container-with-overflow-auto.html [ Failure ] -crbug.com/714962 fast/overflow/scroll-div-hide-show.html [ Failure ] crbug.com/591099 fast/pagination/auto-height-with-break.html [ Failure ] crbug.com/591099 fast/pagination/auto-height.html [ Crash ] crbug.com/591099 fast/pagination/break-in-paged-overflow.html [ Failure ] @@ -1990,10 +1966,6 @@ crbug.com/591099 fast/scrolling/fractional-scroll-offset-fixed-position-non-composited.html [ Crash ] crbug.com/591099 fast/scrolling/jquery-rtl-scroll-type.html [ Failure ] crbug.com/591099 fast/scrolling/scrollable-area-frame-overflow-hidden.html [ Failure ] -crbug.com/714962 fast/scrolling/scrollable-area-frame-overried-inherited-visibility-hidden.html [ Failure ] -crbug.com/714962 fast/scrolling/scrollable-area-frame-scrolling-yes.html [ Failure ] -crbug.com/714962 fast/scrolling/scrollable-area-frame-visibility-hidden-child.html [ Failure ] -crbug.com/714962 fast/scrolling/scrollable-area-frame.html [ Failure ] crbug.com/591099 fast/scrolling/scrollbar-tickmarks-hittest.html [ Pass ] crbug.com/714962 fast/scrolling/scrollbar-tickmarks-styled-after-onload.html [ Failure ] crbug.com/714962 fast/scrolling/scrollbar-tickmarks-styled.html [ Failure ] @@ -2065,7 +2037,6 @@ crbug.com/591099 fast/shapes/shape-outside-floats/shape-outside-rounded-boxes-001.html [ Failure ] crbug.com/591099 fast/shapes/shape-outside-floats/shape-outside-rounded-boxes-002.html [ Failure ] crbug.com/591099 fast/shapes/shape-outside-floats/shape-outside-rounded-inset.html [ Failure ] -crbug.com/591099 fast/spatial-navigation/snav-clipped-overflowed-content.html [ Failure ] crbug.com/714962 fast/spatial-navigation/snav-date.html [ Failure ] crbug.com/714962 fast/spatial-navigation/snav-fully-aligned-horizontally.html [ Failure ] crbug.com/591099 fast/spatial-navigation/snav-fully-aligned-vertically.html [ Failure ] @@ -2287,7 +2258,6 @@ crbug.com/591099 fast/text/whitespace/inline-whitespace-wrapping-4.html [ Failure ] crbug.com/591099 fast/text/whitespace/inline-whitespace-wrapping-5.html [ Failure ] crbug.com/591099 fast/text/whitespace/normal-after-nowrap-breaking.html [ Failure ] -crbug.com/714962 fast/text/whitespace/nowrap-line-break-after-white-space.html [ Failure ] crbug.com/591099 fast/text/whitespace/pre-wrap-spaces-after-newline.html [ Failure ] crbug.com/591099 fast/text/zero-width-characters-complex-script.html [ Failure ] crbug.com/591099 fast/text/zero-width-characters.html [ Failure ] @@ -2574,7 +2544,6 @@ crbug.com/714962 inspector-protocol/layout-fonts/prefix-fallback-multi-character-grapheme.js [ Failure ] crbug.com/714962 inspector-protocol/layout-fonts/tifinagh.js [ Failure ] crbug.com/591099 inspector-protocol/timeline/page-frames.js [ Pass ] -crbug.com/714962 intersection-observer/root-margin.html [ Failure ] crbug.com/714962 intersection-observer/text-target.html [ Failure ] crbug.com/591099 media/autoplay/document-user-activation.html [ Failure ] crbug.com/591099 media/video-persistence.html [ Crash ] @@ -2608,7 +2577,6 @@ crbug.com/591099 paint/invalidation/clip/replaced-clipped-positioned-not-wrong-incremental-repainting.html [ Failure ] crbug.com/714962 paint/invalidation/compositing/composited-inline-change-text-data-keep-geometry.html [ Crash ] crbug.com/591099 paint/invalidation/compositing/fixed-pos-with-abs-pos-child-scroll.html [ Failure ] -crbug.com/591099 paint/invalidation/compositing/iframe-clip-removed.html [ Failure ] crbug.com/591099 paint/invalidation/compositing/iframe-inside-squashed-layer.html [ Failure ] crbug.com/591099 paint/invalidation/compositing/remove-squashed-layer-plus-move.html [ Failure ] crbug.com/714962 paint/invalidation/compositing/repaint-via-layout-offset.html [ Failure ] @@ -2762,10 +2730,8 @@ crbug.com/591099 paint/invalidation/remove-inline-layer-after-layout.html [ Crash ] crbug.com/714962 paint/invalidation/repaint-across-writing-mode-boundary.html [ Failure ] crbug.com/591099 paint/invalidation/repaint-descandant-on-ancestor-layer-move.html [ Failure ] -crbug.com/591099 paint/invalidation/repaint-overlay/layers-overlay.html [ Failure ] crbug.com/591099 paint/invalidation/resize-iframe-text.html [ Failure ] crbug.com/591099 paint/invalidation/ruby-flipped-blocks.html [ Failure ] -crbug.com/591099 paint/invalidation/scroll/caret-with-composited-scroll.html [ Failure ] crbug.com/591099 paint/invalidation/scroll/fixed-child-of-transformed-move-after-scroll.html [ Failure ] crbug.com/591099 paint/invalidation/scroll/fixed-under-composited-absolute-scrolled.html [ Crash ] crbug.com/591099 paint/invalidation/scroll/fixed-with-border-under-composited-absolute-scrolled.html [ Crash ] @@ -2834,7 +2800,6 @@ crbug.com/591099 paint/invalidation/svg/svg-background-partial-redraw.html [ Failure ] crbug.com/591099 paint/invalidation/svg/svg-image-change-content-size.xhtml [ Failure ] crbug.com/591099 paint/invalidation/svg/text-rescale.html [ Failure ] -crbug.com/714962 paint/invalidation/svg/text-xy-updates-SVGList.xhtml [ Failure ] crbug.com/591099 paint/invalidation/svg/use-setAttribute-crash.svg [ Failure ] crbug.com/591099 paint/invalidation/table/add-table-overpaint.html [ Failure ] crbug.com/591099 paint/invalidation/table/border-collapse-change-collapse-to-separate.html [ Failure ] @@ -2941,7 +2906,7 @@ crbug.com/714962 paint/text/text-match-highlights-big-line-height.html [ Failure ] crbug.com/591099 payments/payment-request-in-iframe-nested-not-allowed.html [ Failure ] crbug.com/591099 payments/payment-request-in-iframe.html [ Failure ] -crbug.com/591099 plugins/webview-plugin-nested-iframe-scroll.html [ Failure ] +crbug.com/591099 plugins/mouse-click-plugin-clears-selection.html [ Failure ] crbug.com/591099 printing/absolute-position-headers-and-footers.html [ Failure ] crbug.com/591099 printing/absolute-positioned.html [ Failure ] crbug.com/591099 printing/allowed-page-breaks.html [ Failure ] @@ -2974,19 +2939,15 @@ crbug.com/591099 printing/page-break-orphans-and-widows.html [ Failure ] crbug.com/591099 printing/page-break-orphans.html [ Failure ] crbug.com/591099 printing/page-break-widows.html [ Failure ] -crbug.com/714962 printing/page-count-layout-overflow.html [ Failure ] crbug.com/591099 printing/page-count-relayout-shrink.html [ Failure ] crbug.com/591099 printing/respect-layout-overflow-from-pagination.html [ Failure ] -crbug.com/591099 printing/return-from-printing-mode.html [ Failure ] crbug.com/591099 printing/single-line-must-not-be-split-into-two-pages.html [ Timeout ] crbug.com/591099 printing/tfoot-repeats-at-bottom-of-each-page-multiple-tables.html [ Failure ] crbug.com/591099 printing/thead-repeats-at-top-of-each-page-multiple-tables.html [ Failure ] crbug.com/591099 printing/thead-repeats-at-top-of-each-page.html [ Failure ] crbug.com/591099 printing/thead-under-multicol.html [ Failure ] crbug.com/591099 scrollbars/auto-scrollbar-fit-content.html [ Failure ] -crbug.com/591099 scrollbars/custom-scrollbar-with-incomplete-style.html [ Failure ] crbug.com/591099 scrollbars/scrollbar-miss-mousemove-disabled.html [ Failure ] -crbug.com/714962 scrollbars/scrollbar-orientation.html [ Failure ] crbug.com/714962 scrollbars/scrollbar-position-crash.html [ Crash ] crbug.com/591099 shadow-dom/focus-navigation-with-delegatesFocus.html [ Timeout ] crbug.com/591099 shapedetection/detection-HTMLVideoElement.html [ Pass ] @@ -3010,7 +2971,6 @@ crbug.com/591099 svg/custom/getscreenctm-in-scrollable-div-area-nested.xhtml [ Failure ] crbug.com/591099 svg/custom/getscreenctm-in-scrollable-div-area.xhtml [ Failure ] crbug.com/591099 svg/custom/inline-svg-use-available-width-in-stf.html [ Failure ] -crbug.com/591099 svg/custom/invisible-text-after-scrolling.xhtml [ Failure ] crbug.com/591099 svg/custom/junk-data.svg [ Failure ] crbug.com/591099 svg/custom/load-non-wellformed.svg [ Failure ] crbug.com/591099 svg/custom/missing-xlink.svg [ Failure ] @@ -3030,7 +2990,6 @@ crbug.com/591099 svg/hixie/error/dumpAsText/004.xml [ Failure ] crbug.com/591099 svg/hixie/error/dumpAsText/005.xml [ Failure ] crbug.com/591099 svg/in-html/sizing/svg-inline.html [ Timeout ] -crbug.com/714962 svg/overflow/overflow-on-outermost-svg-element-horizontal-auto.svg [ Failure ] crbug.com/591099 svg/overflow/overflow-on-outermost-svg-element-in-xhtml-defaults.xhtml [ Failure ] crbug.com/591099 svg/parser/whitespace-length-invalid-1.html [ Pass Timeout ] crbug.com/591099 svg/parser/whitespace-length-invalid-2.html [ Pass Timeout ] @@ -3043,9 +3002,7 @@ crbug.com/591099 svg/text/text-repaint-rects.xhtml [ Failure ] crbug.com/714962 svg/text/tspan-multiple-outline.svg [ Failure ] crbug.com/591099 svg/transforms/text-with-pattern-inside-transformed-html.xhtml [ Failure ] -crbug.com/591099 svg/transforms/transformed-text-fill-pattern.html [ Failure ] crbug.com/591099 svg/wicd/test-scalable-background-image1.xhtml [ Failure ] -crbug.com/591099 svg/zoom/page/zoom-replaced-intrinsic-ratio-001.htm [ Failure ] crbug.com/591099 tables/mozilla/bugs/bug101674.html [ Failure ] crbug.com/591099 tables/mozilla/bugs/bug110566.html [ Failure ] crbug.com/714962 tables/mozilla/bugs/bug11384q.html [ Failure ]
diff --git a/third_party/WebKit/LayoutTests/FlagExpectations/enable-slimming-paint-v2 b/third_party/WebKit/LayoutTests/FlagExpectations/enable-slimming-paint-v2 index 7ce01e9..fcc8e24 100644 --- a/third_party/WebKit/LayoutTests/FlagExpectations/enable-slimming-paint-v2 +++ b/third_party/WebKit/LayoutTests/FlagExpectations/enable-slimming-paint-v2
@@ -1260,6 +1260,9 @@ Bug(none) paint/invalidation/scroll/overflow-scroll-delete.html [ Failure ] Bug(none) paint/invalidation/overflow/vertical-overflow-child.html [ Failure ] Bug(none) fast/forms/textarea/textarea-scrolled-mask.html [ Failure ] +Bug(none) fast/css/sticky/sticky-both-sides-top-left-constrained.html [ Failure ] +Bug(none) fast/css/sticky/sticky-vertically-overconstrained.html [ Failure ] +Bug(none) fast/css/sticky/sticky-overflowing.html [ Failure ] # Failures due to pixel snapping because the overflow clip rect is not snapped # in PaintPropertyTreeBuilder::UpdateOverflowClip but needs to be snapped to @@ -1367,6 +1370,9 @@ crbug.com/529963 paint/invalidation/background/background-attachment-fixed-scrolled.html [ Failure Crash ] Bug(none) fast/multicol/hit-test-translate-z.html [ Failure ] +# Invalidation is incorrect. +crbug.com/693741 paint/invalidation/reflection/scroll-absolute-layer-with-reflection.html [ Failure ] + # Failures accumulated during the bot was borrowed by spv175. Bug(none) compositing/columns/geometry-map-paginated-assert.html [ Crash ] Bug(none) compositing/geometry/fixed-position-composited-page-scale-scroll.html [ Crash ] @@ -1446,5 +1452,4 @@ Bug(none) paint/invalidation/clip/clip-path-constant-repaint.html [ Failure ] Bug(none) paint/invalidation/reflection/scroll-fixed-layer-with-reflection.html [ Failure ] Bug(none) paint/invalidation/reflection/scroll-fixed-reflected-layer.html [ Failure ] -Bug(none) paint/overflow/background-paint-into-scrolling-contents-layer-with-root-layer-scrolls-offset.html [ Failure ] Bug(none) svg/transforms/text-with-mask-with-svg-transform.svg [ Failure ]
diff --git a/third_party/WebKit/LayoutTests/TestExpectations b/third_party/WebKit/LayoutTests/TestExpectations index 7689b43..dba5fdb 100644 --- a/third_party/WebKit/LayoutTests/TestExpectations +++ b/third_party/WebKit/LayoutTests/TestExpectations
@@ -274,9 +274,6 @@ # Block: percent height in continuations. crbug.com/635619 virtual/layout_ng/external/wpt/css/CSS2/normal-flow/block-in-inline-percents-001.xht [ Failure ] -# Block: percent max-height. -crbug.com/635619 virtual/layout_ng/external/wpt/css/CSS2/normal-flow/max-height-percentage-002.xht [ Failure ] - # Inline: border in continuations. Fail in Blink. crbug.com/635619 virtual/layout_ng/external/wpt/css/CSS2/normal-flow/block-in-inline-empty-001.xht [ Failure ] crbug.com/635619 virtual/layout_ng/external/wpt/css/CSS2/normal-flow/block-in-inline-empty-004.xht [ Failure ] @@ -1677,6 +1674,8 @@ crbug.com/805463 external/wpt/acid/acid3/numbered-tests.html [ Skip ] # ====== New tests from wpt-importer added here ====== +crbug.com/626703 [ Mac10.11 ] external/wpt/payment-request/show-method-postmessage-manual.https.html [ Skip ] +crbug.com/626703 [ Linux Mac10.10 Mac10.12 Mac10.13 Retina Win ] external/wpt/payment-request/show-method-postmessage-manual.https.html [ Skip ] crbug.com/626703 virtual/incremental-shadow-dom/external/wpt/css/css-scoping/shadow-fallback-dynamic-001.html [ Failure ] crbug.com/626703 [ Android ] virtual/media-gpu-accelerated/external/wpt/media-source/mediasource-config-change-mp4-av-framesize.html [ Crash ] crbug.com/626703 external/wpt/payment-request/payment-request-show-method-manual.https.html [ Skip ]
diff --git a/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json b/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json index 4152679..fcfbbfd1 100644 --- a/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json +++ b/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json
@@ -4735,6 +4735,12 @@ {} ] ], + "payment-request/show-method-postmessage-manual.https.html": [ + [ + "/payment-request/show-method-postmessage-manual.https.html", + {} + ] + ], "payment-request/updateWith-method-pmi-handling-manual.https.html": [ [ "/payment-request/updateWith-method-pmi-handling-manual.https.html", @@ -136807,6 +136813,16 @@ {} ] ], + "generic-sensor/generic-sensor-feature-policy-test.sub.js": [ + [ + {} + ] + ], + "generic-sensor/generic-sensor-tests.js": [ + [ + {} + ] + ], "geolocation-API/OWNERS": [ [ {} @@ -144352,6 +144368,11 @@ {} ] ], + "html/infrastructure/safe-passing-of-structured-data/transfer-errors.window-expected.txt": [ + [ + {} + ] + ], "html/infrastructure/terminology/.gitkeep": [ [ {} @@ -152427,6 +152448,11 @@ {} ] ], + "payment-request/show-method-postmessage-iframe.html": [ + [ + {} + ] + ], "performance-timeline/OWNERS": [ [ {} @@ -155817,16 +155843,6 @@ {} ] ], - "sensors/generic-sensor-feature-policy-test.sub.js": [ - [ - {} - ] - ], - "sensors/generic-sensor-tests.js": [ - [ - {} - ] - ], "server-timing/OWNERS": [ [ {} @@ -192134,6 +192150,18 @@ {} ] ], + "generic-sensor/SensorErrorEvent-constructor.https.html": [ + [ + "/generic-sensor/SensorErrorEvent-constructor.https.html", + {} + ] + ], + "generic-sensor/idlharness.https.html": [ + [ + "/generic-sensor/idlharness.https.html", + {} + ] + ], "geolocation-API/PositionOptions.https.html": [ [ "/geolocation-API/PositionOptions.https.html", @@ -195650,6 +195678,12 @@ {} ] ], + "html/infrastructure/safe-passing-of-structured-data/transfer-errors.window.js": [ + [ + "/html/infrastructure/safe-passing-of-structured-data/transfer-errors.window.html", + {} + ] + ], "html/infrastructure/terminology/plugins/text-plain.html": [ [ "/html/infrastructure/terminology/plugins/text-plain.html", @@ -225506,18 +225540,6 @@ {} ] ], - "sensors/SensorErrorEvent-constructor.https.html": [ - [ - "/sensors/SensorErrorEvent-constructor.https.html", - {} - ] - ], - "sensors/idlharness.https.html": [ - [ - "/sensors/idlharness.https.html", - {} - ] - ], "server-timing/cross_origin.html": [ [ "/server-timing/cross_origin.html", @@ -249802,7 +249824,7 @@ "support" ], "accelerometer/Accelerometer-disabled-by-feature-policy.https.html": [ - "5bce003a7ab3b5016011d35c715d7968c09a89a4", + "96e5a86bf78239f3aa4a79b32bb4308de0d5f60e", "testharness" ], "accelerometer/Accelerometer-disabled-by-feature-policy.https.html.headers": [ @@ -249814,7 +249836,7 @@ "support" ], "accelerometer/Accelerometer-enabled-by-feature-policy-attribute-redirect-on-load.https.html": [ - "df5fc463567201131aeee4f8f975e39135058aab", + "f20f89a31daf399a7946b928e8deca9651d38487", "testharness" ], "accelerometer/Accelerometer-enabled-by-feature-policy-attribute.https-expected.txt": [ @@ -249822,7 +249844,7 @@ "support" ], "accelerometer/Accelerometer-enabled-by-feature-policy-attribute.https.html": [ - "fbea6404a3a380b43b2f006cb1dddadcabeb666f", + "7ce8c39f0af6c932d1e6b6f75843c090f7274b80", "testharness" ], "accelerometer/Accelerometer-enabled-by-feature-policy.https-expected.txt": [ @@ -249830,7 +249852,7 @@ "support" ], "accelerometer/Accelerometer-enabled-by-feature-policy.https.html": [ - "67193bd17d281423d7f6e84b0166b5a4c0409be3", + "dbda7cfa838c1f2d4296b545034d42f0064f331a", "testharness" ], "accelerometer/Accelerometer-enabled-by-feature-policy.https.html.headers": [ @@ -249842,7 +249864,7 @@ "support" ], "accelerometer/Accelerometer-enabled-on-self-origin-by-feature-policy.https.html": [ - "69ced186024bf92e077eccac49a66e8f86d81c96", + "b8fb07cdd23dce9690de719387b9d505382772f5", "testharness" ], "accelerometer/Accelerometer-enabled-on-self-origin-by-feature-policy.https.html.headers": [ @@ -249854,11 +249876,11 @@ "support" ], "accelerometer/Accelerometer.https.html": [ - "f70ee583dce5ed3019e900163d5d559d70d05fb2", + "3ff5f61b25c52142e9796f3903d7f2bcaa30314c", "testharness" ], "accelerometer/Accelerometer_insecure_context.html": [ - "b9837873e39416c65e8ac05f2049bfa406ba4264", + "82be1b9a5c6e75291fdc1aabe230af28e22823a8", "testharness" ], "accelerometer/Accelerometer_onerror-manual.https-expected.txt": [ @@ -249866,7 +249888,7 @@ "support" ], "accelerometer/Accelerometer_onerror-manual.https.html": [ - "c8b76601f465d0f5b26a9bc27dac503f02887448", + "c82f9595dc2582b2da40549a358da1c3fc2ff820", "manual" ], "accelerometer/LinearAccelerationSensor-shake-threshold-manual.https-expected.txt": [ @@ -326677,6 +326699,22 @@ "1cb8a0e23d31dcdeb5ba273a40e35c021c0c53f2", "support" ], + "generic-sensor/SensorErrorEvent-constructor.https.html": [ + "99bcfb42c91e084a3b847ab4bab2bad80e548540", + "testharness" + ], + "generic-sensor/generic-sensor-feature-policy-test.sub.js": [ + "c7c9c4d1c578f267cbb4241d7ea7a981be6f49ee", + "support" + ], + "generic-sensor/generic-sensor-tests.js": [ + "6364f1838215eaafd91b86690039da41d4c19cd1", + "support" + ], + "generic-sensor/idlharness.https.html": [ + "02c734b907075c8abb7504fc7e2b93730ac80a0c", + "testharness" + ], "geolocation-API/OWNERS": [ "4c338ed1db3ab41c3a0664ea20c95dc6896c377e", "support" @@ -326750,7 +326788,7 @@ "support" ], "geolocation-sensor/GeolocationSensor-disabled-by-feature-policy.https.html": [ - "b85d614841994226c2cab7fdf88e03620e453457", + "91047842ea56344c005c46de7cdd27e2373ea0a1", "testharness" ], "geolocation-sensor/GeolocationSensor-disabled-by-feature-policy.https.html.headers": [ @@ -326762,7 +326800,7 @@ "support" ], "geolocation-sensor/GeolocationSensor-enabled-by-feature-policy-attribute-redirect-on-load.https.html": [ - "2d21ee198d079dde55f02fda3eb7f8e8fb6dfac4", + "fb033fd0f0d891e9b6ed2b54b835f8f06364643e", "testharness" ], "geolocation-sensor/GeolocationSensor-enabled-by-feature-policy-attribute.https-expected.txt": [ @@ -326770,7 +326808,7 @@ "support" ], "geolocation-sensor/GeolocationSensor-enabled-by-feature-policy-attribute.https.html": [ - "2eac643f35086d5051333674f6a01a9ee524786d", + "06e4487981f8e6e062d9e9fea14d52e64b6b5035", "testharness" ], "geolocation-sensor/GeolocationSensor-enabled-by-feature-policy.https-expected.txt": [ @@ -326778,7 +326816,7 @@ "support" ], "geolocation-sensor/GeolocationSensor-enabled-by-feature-policy.https.html": [ - "49e7799a36358602efabfb219a93422078456111", + "e8287121361749246b874207dcffb92e459dfbec", "testharness" ], "geolocation-sensor/GeolocationSensor-enabled-by-feature-policy.https.html.headers": [ @@ -326790,7 +326828,7 @@ "support" ], "geolocation-sensor/GeolocationSensor-enabled-on-self-origin-by-feature-policy.https.html": [ - "4ad92dcbcc737cbc14ba3bc2c19dc8f78e75d0a1", + "4222f48c8c2a932c5b65b6426bb9a0ad476ddd0c", "testharness" ], "geolocation-sensor/GeolocationSensor-enabled-on-self-origin-by-feature-policy.https.html.headers": [ @@ -326802,11 +326840,11 @@ "support" ], "geolocation-sensor/GeolocationSensor.https.html": [ - "502b4dbd03312a2e1e0c18fb3983a077335efde6", + "c9d32faca641ec784acf9096a079d73781330216", "testharness" ], "geolocation-sensor/GeolocationSensor_insecure_context.html": [ - "f2e8f58fd7e09cfaa311c83adc4456f9463a3456", + "58fd65d3a72e6734392381fe225e3fbd7007fc06", "testharness" ], "geolocation-sensor/GeolocationSensor_onerror-manual.https-expected.txt": [ @@ -326814,7 +326852,7 @@ "support" ], "geolocation-sensor/GeolocationSensor_onerror-manual.https.html": [ - "8c5a4e48439ff0620d6267b127a5d49f85657896", + "2b7aac7d60271e12ce71f6293405ffafb471c8c8", "manual" ], "geolocation-sensor/GeolocationSensor_read.https-expected.txt": [ @@ -326882,7 +326920,7 @@ "manual" ], "gyroscope/Gyroscope-disabled-by-feature-policy.https.html": [ - "b7fb169e2a3de0df84a44b9775677d1a005e2446", + "bc6f85cb3506d3e3e062eef43dca88bf3a4ebe89", "testharness" ], "gyroscope/Gyroscope-disabled-by-feature-policy.https.html.headers": [ @@ -326890,15 +326928,15 @@ "support" ], "gyroscope/Gyroscope-enabled-by-feature-policy-attribute-redirect-on-load.https.html": [ - "0887871a9f337da76cdbf8fc0ea7a6aafa6eec37", + "cc1f4082fa420a9076f929d88268f5a1d921a44a", "testharness" ], "gyroscope/Gyroscope-enabled-by-feature-policy-attribute.https.html": [ - "b5d7fe16df3356e7e8ea202088e63734291810f0", + "75429c87bbebd19df7b4edaddc5869c6202b3fab", "testharness" ], "gyroscope/Gyroscope-enabled-by-feature-policy.https.html": [ - "92bd0aee5d2d54b50e907155fe3a6dd5b2634021", + "5129c05f9b226650a9b7fed4841871045525bf15", "testharness" ], "gyroscope/Gyroscope-enabled-by-feature-policy.https.html.headers": [ @@ -326906,7 +326944,7 @@ "support" ], "gyroscope/Gyroscope-enabled-on-self-origin-by-feature-policy.https.html": [ - "b1af2b9e1787c1ace4619509d95e4085ac0f0fc7", + "2603bd858929ae6f84ebbe0cce34c5417ccdae06", "testharness" ], "gyroscope/Gyroscope-enabled-on-self-origin-by-feature-policy.https.html.headers": [ @@ -326918,15 +326956,15 @@ "support" ], "gyroscope/Gyroscope.https.html": [ - "7d30725e44905d774a0b4554b55842cba78e1462", + "504abfa42529e08576e49c3296464bcea5fe0b8a", "testharness" ], "gyroscope/Gyroscope_insecure_context.html": [ - "79688da94e1ea93646c288bdbfdb17487e846560", + "74e51a1efc06bf8180db430b418d484fc50c07f9", "testharness" ], "gyroscope/Gyroscope_onerror-manual.https.html": [ - "c89ff6361146a5d3065c2d44088b313e5560ba8d", + "1e15b883bd317ca83783864fc563794cb0f6df8e", "manual" ], "gyroscope/OWNERS": [ @@ -335781,6 +335819,14 @@ "e0f5057cc03fe0bf0bc83587e620b623e4211da3", "testharness" ], + "html/infrastructure/safe-passing-of-structured-data/transfer-errors.window-expected.txt": [ + "45a24014e90d9a1bf673a75087ccfd202c36e692", + "support" + ], + "html/infrastructure/safe-passing-of-structured-data/transfer-errors.window.js": [ + "03fd591d7d34f35db36742111f1aa81872775a65", + "testharness" + ], "html/infrastructure/terminology/.gitkeep": [ "da39a3ee5e6b4b0d3255bfef95601890afd80709", "support" @@ -347158,7 +347204,7 @@ "support" ], "magnetometer/Magnetometer-disabled-by-feature-policy.https.html": [ - "a050a0aff6039883d521735bff4b96e0628de20d", + "9af542095f2fcd57691c0432ef3248b04a0207a0", "testharness" ], "magnetometer/Magnetometer-disabled-by-feature-policy.https.html.headers": [ @@ -347170,7 +347216,7 @@ "support" ], "magnetometer/Magnetometer-enabled-by-feature-policy-attribute-redirect-on-load.https.html": [ - "0bdab54bc63a9b28b89c7be70409a9c6c7d943c5", + "47829ff5747eed99ba22e79b12ddfff288fd031e", "testharness" ], "magnetometer/Magnetometer-enabled-by-feature-policy-attribute.https-expected.txt": [ @@ -347178,7 +347224,7 @@ "support" ], "magnetometer/Magnetometer-enabled-by-feature-policy-attribute.https.html": [ - "22a4580c08716b0395d6a0e49679b29619e2ce35", + "3b6314e9176a24976d9d882644c30f00554eed6d", "testharness" ], "magnetometer/Magnetometer-enabled-by-feature-policy.https-expected.txt": [ @@ -347186,7 +347232,7 @@ "support" ], "magnetometer/Magnetometer-enabled-by-feature-policy.https.html": [ - "8cc0dfc032b1f063e88ca43a0516b89ab05e057f", + "05128cdb7171ba230143e7b68b09968a484b602a", "testharness" ], "magnetometer/Magnetometer-enabled-by-feature-policy.https.html.headers": [ @@ -347198,7 +347244,7 @@ "support" ], "magnetometer/Magnetometer-enabled-on-self-origin-by-feature-policy.https.html": [ - "ac9154aca0c01825a78aad12b9ed242ec8780937", + "3240dafd2bc810dea0dc1ebc31728c86a29f2ec5", "testharness" ], "magnetometer/Magnetometer-enabled-on-self-origin-by-feature-policy.https.html.headers": [ @@ -347210,11 +347256,11 @@ "support" ], "magnetometer/Magnetometer.https.html": [ - "bb74316d74c488daf753ee8576761ec78db457df", + "240e7d0af55b8681f2f45ca22283634acc406325", "testharness" ], "magnetometer/Magnetometer_insecure_context.html": [ - "aef2810b55ac8672dff86b85f5d93d152b81dfe4", + "0eeb95340d7c74a0243eac8d3f004b6e06b87a92", "testharness" ], "magnetometer/Magnetometer_onerror-manual.https-expected.txt": [ @@ -347222,7 +347268,7 @@ "support" ], "magnetometer/Magnetometer_onerror-manual.https.html": [ - "f073df598684ce24f429d968da343812d68cb142", + "da4e6b8975beecdcae24da26920a56a652f781e4", "manual" ], "magnetometer/OWNERS": [ @@ -356034,7 +356080,7 @@ "manual" ], "orientation-sensor/AbsoluteOrientationSensor-disabled-by-feature-policy.https.html": [ - "9db710ef183a7bc65e6649526defe869c5fb66e9", + "0c7657e32b46c64e5f050f04e40ccfc0dce32e47", "testharness" ], "orientation-sensor/AbsoluteOrientationSensor-disabled-by-feature-policy.https.html.headers": [ @@ -356042,15 +356088,15 @@ "support" ], "orientation-sensor/AbsoluteOrientationSensor-enabled-by-feature-policy-attribute-redirect-on-load.https.html": [ - "05c28d8975c13aea8e248d2a1a5341fb146c82a5", + "71a6966fb91f8ddfe15ee690c843e4621a3b4720", "testharness" ], "orientation-sensor/AbsoluteOrientationSensor-enabled-by-feature-policy-attribute.https.html": [ - "e3679a5c3a5f1783d3311556788af9e5a18b9287", + "9bbe39e1be4a669f31f0fb3960aca22d7d159c5e", "testharness" ], "orientation-sensor/AbsoluteOrientationSensor-enabled-by-feature-policy.https.html": [ - "923b5167c76b8f8405c94043dae6d4312383d00e", + "9f110b8ceca3dd3ce3d2a9e2567d92a3fc6462bf", "testharness" ], "orientation-sensor/AbsoluteOrientationSensor-enabled-by-feature-policy.https.html.headers": [ @@ -356058,7 +356104,7 @@ "support" ], "orientation-sensor/AbsoluteOrientationSensor-enabled-on-self-origin-by-feature-policy.https.html": [ - "873f248fa5c359322f6d8b143758122450c2279c", + "c4404cf0b16c4d9ad15308392ecf52caee445b86", "testharness" ], "orientation-sensor/AbsoluteOrientationSensor-enabled-on-self-origin-by-feature-policy.https.html.headers": [ @@ -356074,19 +356120,19 @@ "support" ], "orientation-sensor/OrientationSensor.https.html": [ - "6b53127c74c55a8cf5697bc5527f36b7276e2681", + "ea9a61f9d526183071a0336e11ca844f59c284a9", "testharness" ], "orientation-sensor/OrientationSensor_insecure_context.html": [ - "4161a365bd3a72226c29049cbe46c123b8b07a04", + "eb64da888f1bedf9d5ed8b11edc1626da88b322b", "testharness" ], "orientation-sensor/OrientationSensor_onerror-manual.https.html": [ - "7d28e6caf629f82b058a33b018de34940f34916f", + "6f0eb976affc21e49f48c42c1bd9d9eb0083ee40", "manual" ], "orientation-sensor/RelativeOrientationSensor-disabled-by-feature-policy.https.html": [ - "a8178651dd87ac80268a7c9de06858a6c5ee2125", + "8c6c5f8f3bc4421f5143a3e4fab287564cf4907d", "testharness" ], "orientation-sensor/RelativeOrientationSensor-disabled-by-feature-policy.https.html.headers": [ @@ -356094,15 +356140,15 @@ "support" ], "orientation-sensor/RelativeOrientationSensor-enabled-by-feature-policy-attribute-redirect-on-load.https.html": [ - "895e2cb7837bd9cb4a8ba7b3c90f414b4d3677ea", + "34a79c9033a41c0aceab3fa6a470dd5a76f2ac81", "testharness" ], "orientation-sensor/RelativeOrientationSensor-enabled-by-feature-policy-attribute.https.html": [ - "745fc51713614d6082dec199e3491e001cf3396e", + "0e6260ccdaa8163b8db96516960be226a4d85ba7", "testharness" ], "orientation-sensor/RelativeOrientationSensor-enabled-by-feature-policy.https.html": [ - "bccd08cf93fddcf3c8e2dc18fe394454580f2c88", + "243b2d60d4c528a77e9cfb68fa256b35234e7346", "testharness" ], "orientation-sensor/RelativeOrientationSensor-enabled-by-feature-policy.https.html.headers": [ @@ -356110,7 +356156,7 @@ "support" ], "orientation-sensor/RelativeOrientationSensor-enabled-on-self-origin-by-feature-policy.https.html": [ - "3ea7f029d22c4f05f99fc0cc5c4016670265cea7", + "c9f234f6508fb778fdf91277bb8950c99479979d", "testharness" ], "orientation-sensor/RelativeOrientationSensor-enabled-on-self-origin-by-feature-policy.https.html.headers": [ @@ -356621,6 +356667,14 @@ "a07f98e117bce1f040c5e62ef3acbd2ef7475338", "manual" ], + "payment-request/show-method-postmessage-iframe.html": [ + "05167546e8763cb39873de4ca8f4e8e758ba0147", + "support" + ], + "payment-request/show-method-postmessage-manual.https.html": [ + "d2be1d2872a473a48df7139ecd3804f33187ec8f", + "manual" + ], "payment-request/updateWith-method-pmi-handling-manual.https.html": [ "b473073ad106e9e0732adb6bfbed5f54d6ec3194", "manual" @@ -365825,22 +365879,6 @@ "01ae6e757d428800555012783e290ebba575bcab", "testharness" ], - "sensors/SensorErrorEvent-constructor.https.html": [ - "99bcfb42c91e084a3b847ab4bab2bad80e548540", - "testharness" - ], - "sensors/generic-sensor-feature-policy-test.sub.js": [ - "c7c9c4d1c578f267cbb4241d7ea7a981be6f49ee", - "support" - ], - "sensors/generic-sensor-tests.js": [ - "6364f1838215eaafd91b86690039da41d4c19cd1", - "support" - ], - "sensors/idlharness.https.html": [ - "02c734b907075c8abb7504fc7e2b93730ac80a0c", - "testharness" - ], "server-timing/OWNERS": [ "2d4c432bb4394da88cb55e11d1e7a0c5dd5203d8", "support"
diff --git a/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer-disabled-by-feature-policy.https.html b/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer-disabled-by-feature-policy.https.html index 9481f30..9476efb 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer-disabled-by-feature-policy.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer-disabled-by-feature-policy.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer-enabled-by-feature-policy-attribute-redirect-on-load.https.html b/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer-enabled-by-feature-policy-attribute-redirect-on-load.https.html index 809fe0b..aa8ea10 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer-enabled-by-feature-policy-attribute-redirect-on-load.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer-enabled-by-feature-policy-attribute-redirect-on-load.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer-enabled-by-feature-policy-attribute.https.html b/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer-enabled-by-feature-policy-attribute.https.html index 3f53de0..860a027 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer-enabled-by-feature-policy-attribute.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer-enabled-by-feature-policy-attribute.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer-enabled-by-feature-policy.https.html b/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer-enabled-by-feature-policy.https.html index dca391ba..889047a0 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer-enabled-by-feature-policy.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer-enabled-by-feature-policy.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer-enabled-on-self-origin-by-feature-policy.https.html b/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer-enabled-on-self-origin-by-feature-policy.https.html index cc05a38..bf45852 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer-enabled-on-self-origin-by-feature-policy.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer-enabled-on-self-origin-by-feature-policy.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer.https.html b/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer.https.html index 73c579c..9563270 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer.https.html
@@ -5,7 +5,7 @@ <link rel="help" href="https://www.w3.org/TR/accelerometer/"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> -<script src="/sensors/generic-sensor-tests.js"></script> +<script src="/generic-sensor/generic-sensor-tests.js"></script> <div id="log"></div> <script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer_insecure_context.html b/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer_insecure_context.html index 81b33dd..ff1f083 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer_insecure_context.html +++ b/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer_insecure_context.html
@@ -5,7 +5,7 @@ <link rel="help" href="https://www.w3.org/TR/accelerometer/"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> -<script src="/sensors/generic-sensor-tests.js"></script> +<script src="/generic-sensor/generic-sensor-tests.js"></script> <div id="log"></div> <h2>Note:</h2> <ol>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer_onerror-manual.https.html b/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer_onerror-manual.https.html index ed5f190..f69b1b6 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer_onerror-manual.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/accelerometer/Accelerometer_onerror-manual.https.html
@@ -5,7 +5,7 @@ <link rel="help" href="https://www.w3.org/TR/accelerometer/"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> -<script src="/sensors/generic-sensor-tests.js"></script> +<script src="/generic-sensor/generic-sensor-tests.js"></script> <div id="log"></div> <h2>Precondition</h2> <ol>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/sensors/SensorErrorEvent-constructor.https.html b/third_party/WebKit/LayoutTests/external/wpt/generic-sensor/SensorErrorEvent-constructor.https.html similarity index 100% rename from third_party/WebKit/LayoutTests/external/wpt/sensors/SensorErrorEvent-constructor.https.html rename to third_party/WebKit/LayoutTests/external/wpt/generic-sensor/SensorErrorEvent-constructor.https.html
diff --git a/third_party/WebKit/LayoutTests/external/wpt/sensors/generic-sensor-feature-policy-test.sub.js b/third_party/WebKit/LayoutTests/external/wpt/generic-sensor/generic-sensor-feature-policy-test.sub.js similarity index 100% rename from third_party/WebKit/LayoutTests/external/wpt/sensors/generic-sensor-feature-policy-test.sub.js rename to third_party/WebKit/LayoutTests/external/wpt/generic-sensor/generic-sensor-feature-policy-test.sub.js
diff --git a/third_party/WebKit/LayoutTests/external/wpt/sensors/generic-sensor-tests.js b/third_party/WebKit/LayoutTests/external/wpt/generic-sensor/generic-sensor-tests.js similarity index 100% rename from third_party/WebKit/LayoutTests/external/wpt/sensors/generic-sensor-tests.js rename to third_party/WebKit/LayoutTests/external/wpt/generic-sensor/generic-sensor-tests.js
diff --git a/third_party/WebKit/LayoutTests/external/wpt/sensors/idlharness.https.html b/third_party/WebKit/LayoutTests/external/wpt/generic-sensor/idlharness.https.html similarity index 100% rename from third_party/WebKit/LayoutTests/external/wpt/sensors/idlharness.https.html rename to third_party/WebKit/LayoutTests/external/wpt/generic-sensor/idlharness.https.html
diff --git a/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor-disabled-by-feature-policy.https.html b/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor-disabled-by-feature-policy.https.html index 976d427..88f92c6 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor-disabled-by-feature-policy.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor-disabled-by-feature-policy.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor-enabled-by-feature-policy-attribute-redirect-on-load.https.html b/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor-enabled-by-feature-policy-attribute-redirect-on-load.https.html index 45ee97f..66b7832e 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor-enabled-by-feature-policy-attribute-redirect-on-load.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor-enabled-by-feature-policy-attribute-redirect-on-load.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor-enabled-by-feature-policy-attribute.https.html b/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor-enabled-by-feature-policy-attribute.https.html index b479057..5ea2518 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor-enabled-by-feature-policy-attribute.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor-enabled-by-feature-policy-attribute.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor-enabled-by-feature-policy.https.html b/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor-enabled-by-feature-policy.https.html index 08d45f2..46ef9b7 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor-enabled-by-feature-policy.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor-enabled-by-feature-policy.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor-enabled-on-self-origin-by-feature-policy.https.html b/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor-enabled-on-self-origin-by-feature-policy.https.html index 651d31c..1694ed00 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor-enabled-on-self-origin-by-feature-policy.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor-enabled-on-self-origin-by-feature-policy.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor.https.html b/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor.https.html index 3319c0280..6259638 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor.https.html
@@ -5,7 +5,7 @@ <link rel="help" href="https://wicg.github.io/geolocation-sensor/"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> -<script src="/sensors/generic-sensor-tests.js"></script> +<script src="/generic-sensor/generic-sensor-tests.js"></script> <script> runGenericSensorTests(GeolocationSensor);
diff --git a/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor_insecure_context.html b/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor_insecure_context.html index 6e487cb2..6a3a126 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor_insecure_context.html +++ b/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor_insecure_context.html
@@ -5,7 +5,7 @@ <link rel="help" href="https://wicg.github.io/geolocation-sensor/"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> -<script src="/sensors/generic-sensor-tests.js"></script> +<script src="/generic-sensor/generic-sensor-tests.js"></script> <script> runGenericSensorInsecureContext("GeolocationSensor");
diff --git a/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor_onerror-manual.https.html b/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor_onerror-manual.https.html index 00d1135b..b449346 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor_onerror-manual.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/geolocation-sensor/GeolocationSensor_onerror-manual.https.html
@@ -5,7 +5,7 @@ <link rel="help" href="https://wicg.github.io/geolocation-sensor/"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> -<script src="/sensors/generic-sensor-tests.js"></script> +<script src="/generic-sensor/generic-sensor-tests.js"></script> <h2>Precondition</h2> <ol> <li>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope-disabled-by-feature-policy.https.html b/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope-disabled-by-feature-policy.https.html index 5ab2fb4..de4aee2d 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope-disabled-by-feature-policy.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope-disabled-by-feature-policy.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope-enabled-by-feature-policy-attribute-redirect-on-load.https.html b/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope-enabled-by-feature-policy-attribute-redirect-on-load.https.html index 26c5edfa..3c831bb7 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope-enabled-by-feature-policy-attribute-redirect-on-load.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope-enabled-by-feature-policy-attribute-redirect-on-load.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope-enabled-by-feature-policy-attribute.https.html b/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope-enabled-by-feature-policy-attribute.https.html index e76571d60..46473c3a 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope-enabled-by-feature-policy-attribute.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope-enabled-by-feature-policy-attribute.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope-enabled-by-feature-policy.https.html b/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope-enabled-by-feature-policy.https.html index d21bd07..95eee330 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope-enabled-by-feature-policy.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope-enabled-by-feature-policy.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope-enabled-on-self-origin-by-feature-policy.https.html b/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope-enabled-on-self-origin-by-feature-policy.https.html index 9626e60..ae5a63d1 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope-enabled-on-self-origin-by-feature-policy.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope-enabled-on-self-origin-by-feature-policy.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope.https.html b/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope.https.html index 8f035222..81cdfdd 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope.https.html
@@ -5,7 +5,7 @@ <link rel="help" href="https://www.w3.org/TR/gyroscope/"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> -<script src="/sensors/generic-sensor-tests.js"></script> +<script src="/generic-sensor/generic-sensor-tests.js"></script> <div id="log"></div> <script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope_insecure_context.html b/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope_insecure_context.html index e821db00..2ae8117 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope_insecure_context.html +++ b/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope_insecure_context.html
@@ -5,7 +5,7 @@ <link rel="help" href="https://www.w3.org/TR/gyroscope/"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> -<script src="/sensors/generic-sensor-tests.js"></script> +<script src="/generic-sensor/generic-sensor-tests.js"></script> <div id="log"></div> <h2>Precondition</h2> <ol>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope_onerror-manual.https.html b/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope_onerror-manual.https.html index cf330ca..f012615 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope_onerror-manual.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/gyroscope/Gyroscope_onerror-manual.https.html
@@ -5,7 +5,7 @@ <link rel="help" href="https://www.w3.org/TR/gyroscope/"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> -<script src="/sensors/generic-sensor-tests.js"></script> +<script src="/generic-sensor/generic-sensor-tests.js"></script> <div id="log"></div> <h2>Precondition</h2> <ol>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/safe-passing-of-structured-data/transfer-errors.window-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/safe-passing-of-structured-data/transfer-errors.window-expected.txt new file mode 100644 index 0000000..305d4344 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/safe-passing-of-structured-data/transfer-errors.window-expected.txt
@@ -0,0 +1,20 @@ +This is a testharness.js-based test. +FAIL Cannot transfer all objects assert_throws: function "() => self.postMessage({ get whatever() { throw new Error("You should not have gotten to this point") } }, "*", transferList)" threw object "TypeError: Failed to execute 'postMessage' on 'Window': Value at index 0 does not have a transferable type." that is not a DOMException DataCloneError: property "code" is equal to undefined, expected 25 +PASS Cannot transfer the same ArrayBuffer twice +PASS Serialize should make the ArrayBuffer detached, so it cannot be transferred again +PASS Serialize should throw before a detached ArrayBuffer is found +PASS Cannot transfer ArrayBuffer detached while the message was serialized +PASS Cannot transfer the same MessagePort twice +PASS Serialize should make the MessagePort detached, so it cannot be transferred again +PASS Serialize should throw before a detached MessagePort is found +PASS Cannot transfer MessagePort detached while the message was serialized +PASS Cannot transfer the same ImageBitmap twice +PASS Serialize should make the ImageBitmap detached, so it cannot be transferred again +PASS Serialize should throw before a detached ImageBitmap is found +PASS Cannot transfer ImageBitmap detached while the message was serialized +PASS Cannot transfer the same OffscreenCanvas twice +PASS Serialize should make the OffscreenCanvas detached, so it cannot be transferred again +PASS Serialize should throw before a detached OffscreenCanvas is found +PASS Cannot transfer OffscreenCanvas detached while the message was serialized +Harness: the test ran to completion. +
diff --git a/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/safe-passing-of-structured-data/transfer-errors.window.js b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/safe-passing-of-structured-data/transfer-errors.window.js new file mode 100644 index 0000000..bb1c083 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/safe-passing-of-structured-data/transfer-errors.window.js
@@ -0,0 +1,47 @@ +function assert_transfer_error(transferList) { + assert_throws("DataCloneError", () => self.postMessage({ get whatever() { throw new Error("You should not have gotten to this point") } }, "*", transferList)); +} + +test(() => { + [self, self.document, new Image()].forEach(val => { + assert_transfer_error([val]); + }); +}, "Cannot transfer all objects"); + +function transfer_tests(name, create) { + promise_test(async () => { + const transferable = await create(); + assert_transfer_error([transferable, transferable]); + }, `Cannot transfer the same ${name} twice`); + + promise_test(async () => { + const transferable = await create(); + self.postMessage(null, "*", [transferable]); + assert_throws("DataCloneError", () => self.postMessage(null, "*", [transferable])); + }, `Serialize should make the ${name} detached, so it cannot be transferred again`); + + promise_test(async () => { + const transferable = await create(), + customError = new Error("hi"); + self.postMessage(null, "*", [transferable]); + assert_throws(customError, () => self.postMessage({ get whatever() { throw customError } }, "*", [transferable])); + }, `Serialize should throw before a detached ${name} is found`); + + promise_test(async () => { + const transferable = await create(); + let seen = false; + const message = { + get a() { + self.postMessage(null, '*', [transferable]); + seen = true; + } + }; + assert_throws("DataCloneError", () => self.postMessage(message, "*", [transferable])); + assert_true(seen); + }, `Cannot transfer ${name} detached while the message was serialized`); +} + +transfer_tests("ArrayBuffer", () => new ArrayBuffer(1)); +transfer_tests("MessagePort", () => new MessageChannel().port1); +transfer_tests("ImageBitmap", () => self.createImageBitmap(document.createElement("canvas"))); +transfer_tests("OffscreenCanvas", () => new OffscreenCanvas(1, 1));
diff --git a/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer-disabled-by-feature-policy.https.html b/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer-disabled-by-feature-policy.https.html index 3d861c1..56a1cc4 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer-disabled-by-feature-policy.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer-disabled-by-feature-policy.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer-enabled-by-feature-policy-attribute-redirect-on-load.https.html b/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer-enabled-by-feature-policy-attribute-redirect-on-load.https.html index f6376819..b5f6798 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer-enabled-by-feature-policy-attribute-redirect-on-load.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer-enabled-by-feature-policy-attribute-redirect-on-load.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer-enabled-by-feature-policy-attribute.https.html b/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer-enabled-by-feature-policy-attribute.https.html index 31f83f1..6cad267 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer-enabled-by-feature-policy-attribute.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer-enabled-by-feature-policy-attribute.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer-enabled-by-feature-policy.https.html b/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer-enabled-by-feature-policy.https.html index 83e08eb..24e2554b 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer-enabled-by-feature-policy.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer-enabled-by-feature-policy.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer-enabled-on-self-origin-by-feature-policy.https.html b/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer-enabled-on-self-origin-by-feature-policy.https.html index feb8fecd..59dfef5 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer-enabled-on-self-origin-by-feature-policy.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer-enabled-on-self-origin-by-feature-policy.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer.https.html b/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer.https.html index 496c5281..a3cefc2 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer.https.html
@@ -5,7 +5,7 @@ <link rel="help" href="https://www.w3.org/TR/magnetometer/"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> -<script src="/sensors/generic-sensor-tests.js"></script> +<script src="/generic-sensor/generic-sensor-tests.js"></script> <div id="log"></div> <script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer_insecure_context.html b/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer_insecure_context.html index 74521819..45ff584b 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer_insecure_context.html +++ b/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer_insecure_context.html
@@ -5,7 +5,7 @@ <link rel="help" href="https://www.w3.org/TR/magnetometer/"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> -<script src="/sensors/generic-sensor-tests.js"></script> +<script src="/generic-sensor/generic-sensor-tests.js"></script> <div id="log"></div> <h2>Precondition</h2> <ol>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer_onerror-manual.https.html b/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer_onerror-manual.https.html index 0c823d00..04b9877 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer_onerror-manual.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/magnetometer/Magnetometer_onerror-manual.https.html
@@ -5,7 +5,7 @@ <link rel="help" href="https://www.w3.org/TR/magnetometer/"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> -<script src="/sensors/generic-sensor-tests.js"></script> +<script src="/generic-sensor/generic-sensor-tests.js"></script> <div id="log"></div> <h2>Precondition</h2> <ol>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/AbsoluteOrientationSensor-disabled-by-feature-policy.https.html b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/AbsoluteOrientationSensor-disabled-by-feature-policy.https.html index b3e802ee..ccefe2e 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/AbsoluteOrientationSensor-disabled-by-feature-policy.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/AbsoluteOrientationSensor-disabled-by-feature-policy.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/AbsoluteOrientationSensor-enabled-by-feature-policy-attribute-redirect-on-load.https.html b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/AbsoluteOrientationSensor-enabled-by-feature-policy-attribute-redirect-on-load.https.html index ea416bbb..6aed47d 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/AbsoluteOrientationSensor-enabled-by-feature-policy-attribute-redirect-on-load.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/AbsoluteOrientationSensor-enabled-by-feature-policy-attribute-redirect-on-load.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/AbsoluteOrientationSensor-enabled-by-feature-policy-attribute.https.html b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/AbsoluteOrientationSensor-enabled-by-feature-policy-attribute.https.html index 2fba487..51bbba1 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/AbsoluteOrientationSensor-enabled-by-feature-policy-attribute.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/AbsoluteOrientationSensor-enabled-by-feature-policy-attribute.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/AbsoluteOrientationSensor-enabled-by-feature-policy.https.html b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/AbsoluteOrientationSensor-enabled-by-feature-policy.https.html index c61c957..c0b4cc8e 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/AbsoluteOrientationSensor-enabled-by-feature-policy.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/AbsoluteOrientationSensor-enabled-by-feature-policy.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/AbsoluteOrientationSensor-enabled-on-self-origin-by-feature-policy.https.html b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/AbsoluteOrientationSensor-enabled-on-self-origin-by-feature-policy.https.html index 412a867..9ce51ab 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/AbsoluteOrientationSensor-enabled-on-self-origin-by-feature-policy.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/AbsoluteOrientationSensor-enabled-on-self-origin-by-feature-policy.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/OrientationSensor.https.html b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/OrientationSensor.https.html index 6fca92d..5e728a6 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/OrientationSensor.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/OrientationSensor.https.html
@@ -6,7 +6,7 @@ <link rel="help" href="https://w3c.github.io/sensors/"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> -<script src="/sensors/generic-sensor-tests.js"></script> +<script src="/generic-sensor/generic-sensor-tests.js"></script> <div id="log"></div> <script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/OrientationSensor_insecure_context.html b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/OrientationSensor_insecure_context.html index 4b71e19..18d41ce 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/OrientationSensor_insecure_context.html +++ b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/OrientationSensor_insecure_context.html
@@ -5,7 +5,7 @@ <link rel="help" href="https://w3c.github.io/sensors/"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> -<script src="/sensors/generic-sensor-tests.js"></script> +<script src="/generic-sensor/generic-sensor-tests.js"></script> <div id="log"></div> <h2>Note:</h2> <ol>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/OrientationSensor_onerror-manual.https.html b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/OrientationSensor_onerror-manual.https.html index 6ea75824..d70ea304 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/OrientationSensor_onerror-manual.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/OrientationSensor_onerror-manual.https.html
@@ -6,7 +6,7 @@ <link rel="help" href="https://w3c.github.io/sensors/"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> -<script src="/sensors/generic-sensor-tests.js"></script> +<script src="/generic-sensor/generic-sensor-tests.js"></script> <div id="log"></div> <h2>Precondition</h2> <ol>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/RelativeOrientationSensor-disabled-by-feature-policy.https.html b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/RelativeOrientationSensor-disabled-by-feature-policy.https.html index e1f4401..9296af8 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/RelativeOrientationSensor-disabled-by-feature-policy.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/RelativeOrientationSensor-disabled-by-feature-policy.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/RelativeOrientationSensor-enabled-by-feature-policy-attribute-redirect-on-load.https.html b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/RelativeOrientationSensor-enabled-by-feature-policy-attribute-redirect-on-load.https.html index c1557da..01b45b0 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/RelativeOrientationSensor-enabled-by-feature-policy-attribute-redirect-on-load.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/RelativeOrientationSensor-enabled-by-feature-policy-attribute-redirect-on-load.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/RelativeOrientationSensor-enabled-by-feature-policy-attribute.https.html b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/RelativeOrientationSensor-enabled-by-feature-policy-attribute.https.html index acd9ca5..1bf4119 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/RelativeOrientationSensor-enabled-by-feature-policy-attribute.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/RelativeOrientationSensor-enabled-by-feature-policy-attribute.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/RelativeOrientationSensor-enabled-by-feature-policy.https.html b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/RelativeOrientationSensor-enabled-by-feature-policy.https.html index ca71e3d..7ea2fb5 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/RelativeOrientationSensor-enabled-by-feature-policy.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/RelativeOrientationSensor-enabled-by-feature-policy.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/RelativeOrientationSensor-enabled-on-self-origin-by-feature-policy.https.html b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/RelativeOrientationSensor-enabled-on-self-origin-by-feature-policy.https.html index 8ed6bde..6d677bf0 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/RelativeOrientationSensor-enabled-on-self-origin-by-feature-policy.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/orientation-sensor/RelativeOrientationSensor-enabled-on-self-origin-by-feature-policy.https.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/feature-policy/resources/featurepolicy.js"></script> -<script src="/sensors/generic-sensor-feature-policy-test.sub.js"></script> +<script src="/generic-sensor/generic-sensor-feature-policy-test.sub.js"></script> <script> "use strict";
diff --git a/third_party/WebKit/LayoutTests/external/wpt/payment-request/show-method-postmessage-iframe.html b/third_party/WebKit/LayoutTests/external/wpt/payment-request/show-method-postmessage-iframe.html new file mode 100644 index 0000000..fd73d6b --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/payment-request/show-method-postmessage-iframe.html
@@ -0,0 +1,40 @@ +<h1>This iframe calls shows() via postMessage()</h1> +<script> +"use strict"; +const defaultMethods = Object.freeze([ + { supportedMethods: "basic-card" }, + { supportedMethods: "https://apple.com/pay" }, +]); + +const defaultDetails = Object.freeze({ + id: "fail", + total: { + label: "Total", + amount: { + currency: "USD", + value: "1.00", + }, + }, +}); + +// We are going to use the id to prove that this works +// which we will pass back to the caller +window.onmessage = async event => { + const { source, data: { id, request } } = event; + switch (request) { + case "show-payment-request": { + const details = Object.assign({}, defaultDetails, { id }); + const request = new PaymentRequest(defaultMethods, details); + try { + const response = await request.show(); + source.postMessage(response.toJSON(), window.location.origin); + await response.complete(); + } catch (err) { + source.postMessage({ requestId: "fail" }, window.location.origin); + await request.abort(); + } + } + } +}; + +</script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/payment-request/show-method-postmessage-manual.https.html b/third_party/WebKit/LayoutTests/external/wpt/payment-request/show-method-postmessage-manual.https.html new file mode 100644 index 0000000..00ce84a --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/payment-request/show-method-postmessage-manual.https.html
@@ -0,0 +1,51 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>Test for PaymentRequest.show() method</title> +<link rel="help" href="https://w3c.github.io/browser-payment-api/#show-method"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script> +"use strict"; +setup({ + explicit_done: true, + explicit_timeout: true, +}); + +async function runUserActivation(button) { + button.disabled = true; + const { contentWindow: iframeWindow } = document.getElementById("iframe"); + const expectedId = "pass123"; + await Promise.resolve(); // next tick + const promiseForResponse = new Promise(resolve => { + window.onmessage = ({ data: { requestId } }) => resolve(requestId); + }); + const ops = { id: expectedId, request: "show-payment-request" }; + iframeWindow.postMessage(ops, window.location.origin); + promise_test(async () => { + const actualId = await promiseForResponse; + assert_equals(actualId, expectedId, "ids must match"); + }, button.textContent.trim()); + done(); +} +</script> +<h2>Test PaymentRequest.show() triggered by user activation using postMessage()</h2> +<p> + Tests that user activation works over postMessage(). +</p> +<p> + Click on bottom below. Hit "Pay". +</p> +<ol> + <li> + <button onclick="runUserActivation(this)"> + show() is triggered by user activation passed through postMessage() and a promise + </button> + </li> +</ol> +<iframe width="100%" id="iframe" src="show-method-postmessage-iframe.html" allowpaymentrequest></iframe> +<p> + <small> + If you find a buggy test, please <a href="https://github.com/w3c/web-platform-tests/issues">file a bug</a> + and tag one of the <a href="https://github.com/w3c/web-platform-tests/blob/master/payment-request/OWNERS">owners</a>. + </small> +</p>
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css1/color_and_background/background_attachment-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css1/color_and_background/background_attachment-expected.txt index d52a3a0..ca7ac321 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css1/color_and_background/background_attachment-expected.txt +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css1/color_and_background/background_attachment-expected.txt
@@ -1,4 +1,4 @@ -layer at (0,0) size 800x600 scrollHeight 1279 +layer at (0,0) size 800x600 scrollWidth 880 scrollHeight 1279 LayoutView at (0,0) size 800x600 layer at (0,0) size 800x1279 backgroundClip at (0,0) size 800x600 clip at (0,0) size 800x600 LayoutNGBlockFlow {HTML} at (0,0) size 800x1278.53
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css1/color_and_background/background_repeat-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css1/color_and_background/background_repeat-expected.txt index ac277e1..47e889a 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css1/color_and_background/background_repeat-expected.txt +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css1/color_and_background/background_repeat-expected.txt
@@ -1,4 +1,4 @@ -layer at (0,0) size 800x600 scrollHeight 1993 +layer at (0,0) size 800x600 scrollWidth 888 scrollHeight 1993 LayoutView at (0,0) size 800x600 layer at (0,0) size 800x1993 backgroundClip at (0,0) size 800x600 clip at (0,0) size 800x600 LayoutNGBlockFlow {HTML} at (0,0) size 800x1993
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css2.1/t1202-counters-08-b-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css2.1/t1202-counters-08-b-expected.txt index adae94e..aba317f 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css2.1/t1202-counters-08-b-expected.txt +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css2.1/t1202-counters-08-b-expected.txt
@@ -1,4 +1,4 @@ -layer at (0,0) size 800x600 +layer at (0,0) size 800x600 scrollWidth 954 LayoutView at (0,0) size 800x600 layer at (0,0) size 800x100 LayoutNGBlockFlow {HTML} at (0,0) size 800x100
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css3/selectors3/html/css3-modsel-179a-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css3/selectors3/html/css3-modsel-179a-expected.txt new file mode 100644 index 0000000..0618b19c --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css3/selectors3/html/css3-modsel-179a-expected.txt
@@ -0,0 +1,9 @@ +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x128 + LayoutNGBlockFlow {HTML} at (0,0) size 800x128 + LayoutNGBlockFlow {BODY} at (8,16) size 784x96 + LayoutNGBlockFlow {P} at (0,0) size 784x96 [color=#008000] + LayoutBR {BR} at (0,1) size 0x0 + LayoutText {#text} at (0,76) size 163x19 + text run at (0,76) width 163: "This line should be green."
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css3/selectors3/xhtml/css3-modsel-179a-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css3/selectors3/xhtml/css3-modsel-179a-expected.txt new file mode 100644 index 0000000..033c7468 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css3/selectors3/xhtml/css3-modsel-179a-expected.txt
@@ -0,0 +1,9 @@ +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x128 + LayoutNGBlockFlow {html} at (0,0) size 800x128 + LayoutNGBlockFlow {body} at (8,16) size 784x96 + LayoutNGBlockFlow {p} at (0,0) size 784x96 [color=#008000] + LayoutBR {br} at (0,1) size 0x0 + LayoutText {#text} at (0,76) size 163x19 + text run at (0,76) width 163: "This line should be green."
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css3/selectors3/xml/css3-modsel-179a-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css3/selectors3/xml/css3-modsel-179a-expected.txt new file mode 100644 index 0000000..04f3db8 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/css3/selectors3/xml/css3-modsel-179a-expected.txt
@@ -0,0 +1,8 @@ +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x128 + LayoutNGBlockFlow {test} at (0,0) size 800x128 + LayoutNGBlockFlow {p} at (0,16) size 800x96 [color=#008000] + LayoutBR {br} at (0,1) size 0x0 + LayoutText {#text} at (0,76) size 163x19 + text run at (0,76) width 163: "This line should be green."
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/css/line-thickness-underline-strikethrough-overline-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/css/line-thickness-underline-strikethrough-overline-expected.txt index 0a9d8c5c..c8c20e9 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/css/line-thickness-underline-strikethrough-overline-expected.txt +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-blink-features=LayoutNG/fast/css/line-thickness-underline-strikethrough-overline-expected.txt
@@ -1,4 +1,4 @@ -layer at (0,0) size 800x600 +layer at (0,0) size 800x600 scrollWidth 1031 LayoutView at (0,0) size 800x600 layer at (0,0) size 800x251 LayoutNGBlockFlow {HTML} at (0,0) size 800x251
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-slimming-paint-v2/fast/dom/scroll-reveal-left-overflow-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-slimming-paint-v2/fast/dom/scroll-reveal-left-overflow-expected.png new file mode 100644 index 0000000..c17d622 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-slimming-paint-v2/fast/dom/scroll-reveal-left-overflow-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-slimming-paint-v2/fast/dom/scroll-reveal-top-overflow-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-slimming-paint-v2/fast/dom/scroll-reveal-top-overflow-expected.png new file mode 100644 index 0000000..b1849a0c --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-slimming-paint-v2/fast/dom/scroll-reveal-top-overflow-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-slimming-paint-v2/fast/overflow/overflow_hidden-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-slimming-paint-v2/fast/overflow/overflow_hidden-expected.png new file mode 100644 index 0000000..b942d3998 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-slimming-paint-v2/fast/overflow/overflow_hidden-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-slimming-paint-v2/fast/overflow/overflow_hidden-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-slimming-paint-v2/fast/overflow/overflow_hidden-expected.txt new file mode 100644 index 0000000..02d43a36 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-slimming-paint-v2/fast/overflow/overflow_hidden-expected.txt
@@ -0,0 +1,20 @@ +layer at (0,0) size 800x600 scrollY 1555.00 scrollHeight 2155 + LayoutView at (0,0) size 800x600 +layer at (0,-1555) size 800x2155 backgroundClip at (0,0) size 800x600 clip at (0,0) size 800x600 + LayoutBlockFlow {HTML} at (0,0) size 800x2154.81 + LayoutBlockFlow {BODY} at (8,16) size 784x2122.81 + LayoutBlockFlow {P} at (0,0) size 784x20 + LayoutText {#text} at (0,0) size 612x19 + text run at (0,0) width 612: "Scrolling should occur even when the frame's overflow is hidden (i.e. it has no visible scrollbars)." + LayoutBlockFlow {DIV} at (0,36) size 784x2000 + LayoutInline {A} at (0,0) size 65x19 [color=#0000EE] + LayoutText {#text} at (0,0) size 65x19 + text run at (0,0) width 65: "Click here" + LayoutText {#text} at (0,0) size 0x0 + LayoutBlockFlow {H2} at (0,2055.91) size 784x27 + LayoutText {#text} at (0,0) size 117x26 + text run at (0,0) width 117: "Test Passed" + LayoutBlockFlow {P} at (0,2102.81) size 784x20 + LayoutText {#text} at (0,0) size 501x19 + text run at (0,0) width 501: "The test should have automatically scrolled down to show \"Test Passed\" above." +scrolled to 0,1555
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-slimming-paint-v2/fast/writing-mode/border-radius-clipping-vertical-lr-expected.png b/third_party/WebKit/LayoutTests/flag-specific/enable-slimming-paint-v2/fast/writing-mode/border-radius-clipping-vertical-lr-expected.png new file mode 100644 index 0000000..82c8338 --- /dev/null +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-slimming-paint-v2/fast/writing-mode/border-radius-clipping-vertical-lr-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-slimming-paint-v2/paint/invalidation/outline/outline-change-vertical-rl-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-slimming-paint-v2/paint/invalidation/outline/outline-change-vertical-rl-expected.txt index 8ed8d14a..3ee4320 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-slimming-paint-v2/paint/invalidation/outline/outline-change-vertical-rl-expected.txt +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-slimming-paint-v2/paint/invalidation/outline/outline-change-vertical-rl-expected.txt
@@ -8,16 +8,23 @@ }, { "name": "HorizontalScrollbar", - "bounds": [800, 600], + "position": [0, 585], + "bounds": [800, 15] + }, + { + "name": "LayoutBlockFlow HTML", + "position": [-216, 0], + "bounds": [1016, 128], + "backgroundColor": "#008000", "paintInvalidations": [ { "object": "LayoutBlockFlow DIV id='target'", - "rect": [0, 0, 800, 128], + "rect": [0, 0, 1016, 128], "reason": "style change" }, { "object": "LayoutBlockFlow DIV id='target'", - "rect": [0, 0, 800, 128], + "rect": [0, 0, 1016, 128], "reason": "style change" } ]
diff --git a/third_party/WebKit/LayoutTests/flag-specific/enable-slimming-paint-v2/paint/invalidation/scroll/outline-change-scrollable-expected.txt b/third_party/WebKit/LayoutTests/flag-specific/enable-slimming-paint-v2/paint/invalidation/scroll/outline-change-scrollable-expected.txt index 8ed8d14a..b0e646e 100644 --- a/third_party/WebKit/LayoutTests/flag-specific/enable-slimming-paint-v2/paint/invalidation/scroll/outline-change-scrollable-expected.txt +++ b/third_party/WebKit/LayoutTests/flag-specific/enable-slimming-paint-v2/paint/invalidation/scroll/outline-change-scrollable-expected.txt
@@ -8,16 +8,22 @@ }, { "name": "HorizontalScrollbar", - "bounds": [800, 600], + "position": [0, 585], + "bounds": [800, 15] + }, + { + "name": "LayoutBlockFlow HTML", + "bounds": [1008, 128], + "backgroundColor": "#008000", "paintInvalidations": [ { "object": "LayoutBlockFlow DIV id='target'", - "rect": [0, 0, 800, 128], + "rect": [0, 0, 1008, 128], "reason": "style change" }, { "object": "LayoutBlockFlow DIV id='target'", - "rect": [0, 0, 800, 128], + "rect": [0, 0, 1008, 128], "reason": "style change" } ]
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/persistence/automapping-bind-committed-network-sourcecode-expected.txt b/third_party/WebKit/LayoutTests/http/tests/devtools/persistence/automapping-bind-committed-network-sourcecode-expected.txt new file mode 100644 index 0000000..15434de --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/persistence/automapping-bind-committed-network-sourcecode-expected.txt
@@ -0,0 +1,13 @@ +Verify that committed network uiSourceCode gets bound to + fileSystem, making fileSystem dirty with its content +Binding created: { + network: http://127.0.0.1:8000/devtools/persistence/resources/foo.js + fileSystem: file:///var/www/devtools/persistence/resources/foo.js +} +FileSystem is dirty: true +FileSystem working copy: + + +window.bar = ()=>'bar'; + +
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/persistence/automapping-bind-committed-network-sourcecode.js b/third_party/WebKit/LayoutTests/http/tests/devtools/persistence/automapping-bind-committed-network-sourcecode.js new file mode 100644 index 0000000..43eb59e --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/persistence/automapping-bind-committed-network-sourcecode.js
@@ -0,0 +1,28 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +(async function() { + TestRunner.addResult(`Verify that committed network uiSourceCode gets bound to + fileSystem, making fileSystem dirty with its content`); + await TestRunner.loadModule('bindings_test_runner'); + BindingsTestRunner.overrideNetworkModificationTime( + {'http://127.0.0.1:8000/devtools/persistence/resources/foo.js': null}); + TestRunner.addScriptTag('resources/foo.js'); + var networkUISourceCode = await TestRunner.waitForUISourceCode('foo.js', Workspace.projectTypes.Network); + var content = await networkUISourceCode.requestContent(); + content = content.replace(/foo/g, 'bar'); + networkUISourceCode.addRevision(content); + + var fs = new BindingsTestRunner.TestFileSystem('file:///var/www'); + BindingsTestRunner.addFooJSFile(fs); + fs.reportCreated(function() {}); + + var binding = await BindingsTestRunner.waitForBinding('foo.js'); + TestRunner.addResult('Binding created: ' + binding); + TestRunner.addResult('FileSystem is dirty: ' + binding.fileSystem.isDirty()); + TestRunner.addResult('FileSystem working copy: '); + TestRunner.addResult(binding.fileSystem.workingCopy()); + + TestRunner.completeTest(); +})();
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/persistence/automapping-do-not-bind-dirty-sourcecode-expected.txt b/third_party/WebKit/LayoutTests/http/tests/devtools/persistence/automapping-bind-dirty-filesystem-sourcecode-expected.txt similarity index 61% rename from third_party/WebKit/LayoutTests/http/tests/devtools/persistence/automapping-do-not-bind-dirty-sourcecode-expected.txt rename to third_party/WebKit/LayoutTests/http/tests/devtools/persistence/automapping-bind-dirty-filesystem-sourcecode-expected.txt index 18172ab..915dd68 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/persistence/automapping-do-not-bind-dirty-sourcecode-expected.txt +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/persistence/automapping-bind-dirty-filesystem-sourcecode-expected.txt
@@ -1,8 +1,7 @@ -Verify that dirty uiSourceCodes are not bound. +Verify that dirty fileSystem uiSourceCodes are bound to network. -Failed to create binding: { +Binding created: { network: http://127.0.0.1:8000/devtools/persistence/resources/foo.js fileSystem: file:///var/www/devtools/persistence/resources/foo.js - exactMatch: true }
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/persistence/automapping-bind-dirty-filesystem-sourcecode.js b/third_party/WebKit/LayoutTests/http/tests/devtools/persistence/automapping-bind-dirty-filesystem-sourcecode.js new file mode 100644 index 0000000..c55386dd --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/persistence/automapping-bind-dirty-filesystem-sourcecode.js
@@ -0,0 +1,24 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +(async function() { + TestRunner.addResult(`Verify that dirty fileSystem uiSourceCodes are bound to network.\n`); + await TestRunner.loadModule('bindings_test_runner'); + BindingsTestRunner.overrideNetworkModificationTime( + {'http://127.0.0.1:8000/devtools/persistence/resources/foo.js': null}); + + var fs = new BindingsTestRunner.TestFileSystem('file:///var/www'); + BindingsTestRunner.addFooJSFile(fs); + fs.reportCreated(function() {}); + var fsUISourceCode = await TestRunner.waitForUISourceCode('foo.js', Workspace.projectTypes.FileSystem); + var content = await fsUISourceCode.requestContent(); + content = content.replace(/foo/g, 'bar'); + fsUISourceCode.setWorkingCopy(content); + + TestRunner.addScriptTag('resources/foo.js'); + var binding = await BindingsTestRunner.waitForBinding('foo.js'); + TestRunner.addResult('Binding created: ' + binding); + + TestRunner.completeTest(); +})();
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/persistence/automapping-bind-dirty-network-sourcecode-expected.txt b/third_party/WebKit/LayoutTests/http/tests/devtools/persistence/automapping-bind-dirty-network-sourcecode-expected.txt new file mode 100644 index 0000000..fb321d12 --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/persistence/automapping-bind-dirty-network-sourcecode-expected.txt
@@ -0,0 +1,13 @@ +Verify that dirty network uiSourceCodes are bound to filesystem. + +Binding created: { + network: http://127.0.0.1:8000/devtools/persistence/resources/foo.js + fileSystem: file:///var/www/devtools/persistence/resources/foo.js +} +FileSystem is dirty: true +FileSystem working copy: + + +window.bar = ()=>'bar'; + +
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/persistence/automapping-bind-dirty-network-sourcecode.js b/third_party/WebKit/LayoutTests/http/tests/devtools/persistence/automapping-bind-dirty-network-sourcecode.js new file mode 100644 index 0000000..d149a796 --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/persistence/automapping-bind-dirty-network-sourcecode.js
@@ -0,0 +1,27 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +(async function() { + TestRunner.addResult(`Verify that dirty network uiSourceCodes are bound to filesystem.\n`); + await TestRunner.loadModule('bindings_test_runner'); + BindingsTestRunner.overrideNetworkModificationTime( + {'http://127.0.0.1:8000/devtools/persistence/resources/foo.js': null}); + TestRunner.addScriptTag('resources/foo.js'); + var networkUISourceCode = await TestRunner.waitForUISourceCode('foo.js', Workspace.projectTypes.Network); + var content = await networkUISourceCode.requestContent(); + content = content.replace(/foo/g, 'bar'); + networkUISourceCode.setWorkingCopy(content); + + var fs = new BindingsTestRunner.TestFileSystem('file:///var/www'); + BindingsTestRunner.addFooJSFile(fs); + fs.reportCreated(function() {}); + + var binding = await BindingsTestRunner.waitForBinding('foo.js'); + TestRunner.addResult('Binding created: ' + binding); + TestRunner.addResult('FileSystem is dirty: ' + binding.fileSystem.isDirty()); + TestRunner.addResult('FileSystem working copy: '); + TestRunner.addResult(binding.fileSystem.workingCopy()); + + TestRunner.completeTest(); +})();
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/persistence/automapping-do-not-bind-dirty-sourcecode.js b/third_party/WebKit/LayoutTests/http/tests/devtools/persistence/automapping-do-not-bind-dirty-sourcecode.js deleted file mode 100644 index be751da..0000000 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/persistence/automapping-do-not-bind-dirty-sourcecode.js +++ /dev/null
@@ -1,25 +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. - -(async function() { - TestRunner.addResult(`Verify that dirty uiSourceCodes are not bound.\n`); - await TestRunner.loadModule('sources_test_runner'); - await TestRunner.loadModule('console_test_runner'); - await TestRunner.loadModule('bindings_test_runner'); - await TestRunner.addScriptTag('resources/foo.js'); - BindingsTestRunner.overrideNetworkModificationTime( - {'http://127.0.0.1:8000/devtools/persistence/resources/foo.js': null}); - - var networkUISourceCode = await TestRunner.waitForUISourceCode('foo.js', Workspace.projectTypes.Network); - var content = await networkUISourceCode.requestContent(); - content = content.replace(/foo/g, 'bar'); - networkUISourceCode.setWorkingCopy(content); - - var fs = new BindingsTestRunner.TestFileSystem('file:///var/www'); - BindingsTestRunner.addFooJSFile(fs); - fs.reportCreated(function() {}); - var binding = await TestRunner.addSnifferPromise(Persistence.Automapping.prototype, '_prevalidationFailedForTest'); - TestRunner.addResult('Failed to create binding: ' + binding); - TestRunner.completeTest(); -})();
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing-session-id.js b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing-session-id.js index 8ffbfa8..f6796f1 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing-session-id.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing-session-id.js
@@ -10,9 +10,14 @@ await TestRunner.loadHTML(` <p style="transform: translateZ(10px)"> <!-- Force compositing so we have SetLayerTreeHostId event as well --> </p> + <script> + function waitForRaf() { + return new Promise(f => requestAnimationFrame(f)); + } + </script> `); - await PerformanceTestRunner.evaluateWithTimeline('(function() {})'); + await PerformanceTestRunner.invokeAsyncWithTimeline('waitForRaf'); PerformanceTestRunner.tracingModel().sortedProcesses().forEach(function(process) { process.sortedThreads().forEach(function(thread) { @@ -21,15 +26,19 @@ }); TestRunner.completeTest(); - function processEvent(event) { - var metadataEvents = [ - TimelineModel.TimelineModel.RecordType.SetLayerTreeId, TimelineModel.TimelineModel.RecordType.TracingStartedInPage - ]; + var frameId = ''; - if (!event.hasCategory(SDK.TracingModel.DevToolsMetadataEventCategory) || metadataEvents.indexOf(event.name) < 0) + function processEvent(event) { + if (!event.hasCategory(SDK.TracingModel.DevToolsMetadataEventCategory)) return; - TestRunner.assertEquals(PerformanceTestRunner.timelineModel().sessionId(), event.args['data']['sessionId']); - TestRunner.addResult('Got DevTools metadata event: ' + event.name); + if (event.name === TimelineModel.TimelineModel.RecordType.TracingStartedInPage) { + TestRunner.assertEquals(PerformanceTestRunner.timelineModel()._sessionId, event.args['sessionId'] || event.args['data']['sessionId']); + TestRunner.addResult('Got DevTools metadata event: ' + event.name); + frameId = event.args['data']['frames'][0]['frame']; + } else if (event.name === TimelineModel.TimelineModel.RecordType.SetLayerTreeId) { + if (frameId === event.args['data']['frame']) + TestRunner.addResult('Got DevTools metadata event: ' + event.name); + } } })();
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/category-filter.js b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/category-filter.js index 1a11437f..804c835b 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/category-filter.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/category-filter.js
@@ -13,7 +13,9 @@ var testData = [ { - 'args': {'sessionId': sessionId}, + 'args': {'data': {'sessionId': sessionId, 'frames': [ + {'frame': 'frame1', 'url': 'frameurl', 'name': 'frame-name'} + ]}}, 'cat': 'disabled-by-default-devtools.timeline', 'name': 'TracingStartedInPage', 'ph': 'I',
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/frame-model.js b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/frame-model.js index 1cc5fa3..3bd7b55 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/frame-model.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/frame-model.js
@@ -15,7 +15,9 @@ var commonMetadata = [ { - 'args': {'sessionId': sessionId}, + 'args': {'data': {'sessionId': sessionId, 'frames': [ + {'frame': 'frame1', 'url': 'frameurl', 'name': 'frame-name'} + ]}}, 'cat': 'disabled-by-default-devtools.timeline', 'name': 'TracingStartedInPage', 'ph': 'I', @@ -24,7 +26,7 @@ 'ts': 100, }, { - 'args': {'sessionId': sessionId, 'layerTreeId': 17}, + 'args': {'data': {'frame': 'frame1', 'layerTreeId': 17}}, 'cat': 'disabled-by-default-devtools.timeline', 'name': 'SetLayerTreeId', 'ph': 'I',
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-js/timeline-js-blackboxing.js b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-js/timeline-js-blackboxing.js index 15bc81b..9d781fb 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-js/timeline-js-blackboxing.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-js/timeline-js-blackboxing.js
@@ -28,7 +28,9 @@ 'ts': 0 }, { - 'args': {'sessionId': sessionId}, + 'args': {'data': {'sessionId': sessionId, 'frames': [ + {'frame': 'frame1', 'url': 'frameurl', 'name': 'frame-name'} + ]}}, 'cat': 'disabled-by-default-devtools.timeline', 'name': 'TracingStartedInPage', 'ph': 'I',
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-js/timeline-js-callstacks.js b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-js/timeline-js-callstacks.js index 0b10c46..64c6a3e 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-js/timeline-js-callstacks.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-js/timeline-js-callstacks.js
@@ -28,7 +28,9 @@ 'ts': 0 }, { - 'args': {'sessionId': sessionId}, + 'args': {'data': {'sessionId': sessionId, 'frames': [ + {'frame': 'frame1', 'url': 'frameurl', 'name': 'frame-name'} + ]}}, 'cat': 'disabled-by-default-devtools.timeline', 'name': 'TracingStartedInPage', 'ph': 'I',
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-js/timeline-js-streamed-cpu-profile.js b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-js/timeline-js-streamed-cpu-profile.js index 602c7ab..5662a1d8 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-js/timeline-js-streamed-cpu-profile.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-js/timeline-js-streamed-cpu-profile.js
@@ -28,7 +28,9 @@ 'ts': 0 }, { - 'args': {'sessionId': sessionId}, + 'args': {'data': {'sessionId': sessionId, 'frames': [ + {'frame': 'frame1', 'url': 'frameurl', 'name': 'frame-name'} + ]}}, 'cat': 'disabled-by-default-devtools.timeline', 'name': 'TracingStartedInPage', 'ph': 'I',
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-js/timeline-open-function-call.js b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-js/timeline-open-function-call.js index 4eee36f1..beb985eb 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-js/timeline-open-function-call.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-js/timeline-open-function-call.js
@@ -28,7 +28,9 @@ 'ts': 0 }, { - 'args': {'sessionId': sessionId}, + 'args': {'data': {'sessionId': sessionId, 'frames': [ + {'frame': 'frame1', 'url': 'frameurl', 'name': 'frame-name'} + ]}}, 'cat': 'disabled-by-default-devtools.timeline', 'name': 'TracingStartedInPage', 'ph': 'I',
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-misc/timeline-auto-zoom.js b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-misc/timeline-auto-zoom.js index f69923d..dd2ee5e2 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-misc/timeline-auto-zoom.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-misc/timeline-auto-zoom.js
@@ -13,7 +13,9 @@ var traceEvents = [ { - 'args': {'sessionId': sessionId}, + 'args': {'data': {'sessionId': sessionId, 'frames': [ + {'frame': 'frame1', 'url': 'frameurl', 'name': 'frame-name'} + ]}}, 'cat': 'disabled-by-default-devtools.timeline', 'name': 'TracingStartedInPage', 'ph': 'I',
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-misc/timeline-event-details.js b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-misc/timeline-event-details.js index a259d47..517c086 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-misc/timeline-event-details.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-misc/timeline-event-details.js
@@ -34,7 +34,9 @@ 'ts': 0 }, { - 'args': {'sessionId': sessionId}, + 'args': {'data': {'sessionId': sessionId, 'frames': [ + {'frame': 'frame1', 'url': 'frameurl', 'name': 'frame-name'} + ]}}, 'cat': 'disabled-by-default-devtools.timeline', 'name': 'TracingStartedInPage', 'ph': 'I',
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-misc/timeline-filtering.js b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-misc/timeline-filtering.js index 579bf8d..9acdb7c 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-misc/timeline-filtering.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-misc/timeline-filtering.js
@@ -13,7 +13,9 @@ var testData = [ { - 'args': {'sessionId': sessionId}, + 'args': {'data': {'sessionId': sessionId, 'frames': [ + {'frame': 'frame1', 'url': 'frameurl', 'name': 'frame-name'} + ]}}, 'cat': 'disabled-by-default-devtools.timeline', 'name': 'TracingStartedInPage', 'ph': 'I',
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-misc/timeline-model.js b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-misc/timeline-model.js index 0ef6cc67..add2434 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-misc/timeline-model.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-misc/timeline-model.js
@@ -13,7 +13,9 @@ var commonMetadata = [ { - 'args': {'sessionId': sessionId}, + 'args': {'data': {'sessionId': sessionId, 'frames': [ + {'frame': 'frame1', 'url': 'frameurl', 'name': 'frame-name'} + ]}}, 'cat': 'disabled-by-default-devtools.timeline', 'name': 'TracingStartedInPage', 'ph': 'I', @@ -22,7 +24,7 @@ 'ts': 100, }, { - 'args': {'layerTreeId': 17, 'sessionId': sessionId}, + 'args': {'data': {'layerTreeId': 17, 'frame': 'frame1'}}, 'cat': 'disabled-by-default-devtools.timeline', 'name': 'SetLayerTreeId', 'ph': 'I',
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-misc/timeline-range-stats.js b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-misc/timeline-range-stats.js index 29fa007a..2ef7ac54 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-misc/timeline-range-stats.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-misc/timeline-range-stats.js
@@ -19,7 +19,9 @@ 'pid': pid, 'tid': mainThread, 'ts': 100, - 'args': {'sessionId': sessionId} + 'args': {'data': {'sessionId': sessionId, 'frames': [ + {'frame': 'frame1', 'url': 'frameurl', 'name': 'frame-name'} + ]}}, }, { 'cat': 'disabled-by-default-devtools.timeline', @@ -28,7 +30,7 @@ 'pid': pid, 'tid': mainThread, 'ts': 101, - 'args': {'sessionId': sessionId, 'layerTreeId': 17} + 'args': {'data': {'frame': 'frame1', 'layerTreeId': 17}} }, {
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-misc/timeline-search.js b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-misc/timeline-search.js index c7cada43..1552180f 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-misc/timeline-search.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/timeline-misc/timeline-search.js
@@ -14,7 +14,9 @@ var testData = [ { - 'args': {'sessionId': sessionId}, + 'args': {'data': {'sessionId': sessionId, 'frames': [ + {'frame': 'frame1', 'url': 'frameurl', 'name': 'frame-name'} + ]}}, 'cat': 'disabled-by-default-devtools.timeline', 'name': 'TracingStartedInPage', 'ph': 'I',
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/tracing-timeline-load.js b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/tracing-timeline-load.js index 36eae79b..4178990 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/tracing-timeline-load.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/tracing-timeline-load.js
@@ -286,7 +286,9 @@ 'tts': 2613843 }, { - 'args': {'sessionId': '26.5'}, + 'args': {'data': {'sessionId': '26.5', 'frames': [ + {'frame': 'frame1', 'url': 'frameurl', 'name': 'frame-name'} + ]}}, 'cat': 'disabled-by-default-devtools.timeline', 'name': 'TracingStartedInPage', 'ph': 'I', @@ -297,7 +299,7 @@ 'tts': 1432596 }, { - 'args': {'layerTreeId': 1, 'sessionId': '26.5'}, + 'args': {'data': {'layerTreeId': 1, 'frame': 'frame1'}}, 'cat': 'disabled-by-default-devtools.timeline', 'name': 'SetLayerTreeId', 'ph': 'I',
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/worker-events.js b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/worker-events.js index 15aee5ad..066f0f99 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/worker-events.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/tracing/worker-events.js
@@ -47,7 +47,7 @@ return; ++workerMetadataEventCount; - TestRunner.assertEquals(PerformanceTestRunner.timelineModel().sessionId(), event.args['data']['sessionId']); + TestRunner.assertEquals(PerformanceTestRunner.timelineModel()._sessionId, event.args['data']['sessionId']); TestRunner.addResult('Got DevTools worker metadata event(' + workerMetadataEventCount + '): ' + event.name); } })();
diff --git a/third_party/WebKit/LayoutTests/plugins/transformed-events-expected.txt b/third_party/WebKit/LayoutTests/plugins/transformed-events-expected.txt index c427a8d..2db5977c 100644 --- a/third_party/WebKit/LayoutTests/plugins/transformed-events-expected.txt +++ b/third_party/WebKit/LayoutTests/plugins/transformed-events-expected.txt
@@ -19,9 +19,9 @@ Plugin received event: MouseWheel * 10.00, 10.00 Plugin received event: GestureShowPress -* 10, 10 +* 10.00, 10.00 Plugin received event: GestureTap -* 10, 10 +* 10.00, 10.00 Plugin received event: MouseMove * 10.00, 10.00 Plugin received event: MouseDown
diff --git a/third_party/WebKit/Source/core/css/parser/CSSParserSelector.cpp b/third_party/WebKit/Source/core/css/parser/CSSParserSelector.cpp index 4abffdb4..de2e852 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSParserSelector.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSParserSelector.cpp
@@ -28,6 +28,9 @@ namespace blink { +using RelationType = CSSSelector::RelationType; +using PseudoType = CSSSelector::PseudoType; + CSSParserSelector::CSSParserSelector() : selector_(std::make_unique<CSSSelector>()) {} @@ -112,4 +115,23 @@ GetPseudoType() == CSSSelector::kPseudoHostContext; } +RelationType CSSParserSelector::GetImplicitShadowCombinatorForMatching() const { + switch (GetPseudoType()) { + case PseudoType::kPseudoSlotted: + return RelationType::kShadowSlot; + case PseudoType::kPseudoWebKitCustomElement: + case PseudoType::kPseudoBlinkInternalElement: + case PseudoType::kPseudoCue: + case PseudoType::kPseudoPlaceholder: + case PseudoType::kPseudoShadow: + return RelationType::kShadowPseudo; + default: + return RelationType::kSubSelector; + } +} + +bool CSSParserSelector::NeedsImplicitShadowCombinatorForMatching() const { + return GetImplicitShadowCombinatorForMatching() != RelationType::kSubSelector; +} + } // namespace blink
diff --git a/third_party/WebKit/Source/core/css/parser/CSSParserSelector.h b/third_party/WebKit/Source/core/css/parser/CSSParserSelector.h index 92ca5e4..b11d620 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSParserSelector.h +++ b/third_party/WebKit/Source/core/css/parser/CSSParserSelector.h
@@ -100,14 +100,12 @@ return selector_->SelectorList(); } - bool NeedsImplicitShadowCombinatorForMatching() const { - return GetPseudoType() == CSSSelector::kPseudoWebKitCustomElement || - GetPseudoType() == CSSSelector::kPseudoBlinkInternalElement || - GetPseudoType() == CSSSelector::kPseudoCue || - GetPseudoType() == CSSSelector::kPseudoPlaceholder || - GetPseudoType() == CSSSelector::kPseudoShadow || - GetPseudoType() == CSSSelector::kPseudoSlotted; - } + // Some pseudo elements behave as if they have an implicit combinator to their + // left even though they are written without one. This method returns the + // correct implicit combinator. If no new combinator should be used, it + // returns RelationType::kSubSelector. + CSSSelector::RelationType GetImplicitShadowCombinatorForMatching() const; + bool NeedsImplicitShadowCombinatorForMatching() const; bool IsSimple() const;
diff --git a/third_party/WebKit/Source/core/css/parser/CSSSelectorParser.cpp b/third_party/WebKit/Source/core/css/parser/CSSSelectorParser.cpp index 519309b3..dfb4aa1 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSSelectorParser.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSSelectorParser.cpp
@@ -919,9 +919,7 @@ std::unique_ptr<CSSParserSelector> second_compound = split_after->ReleaseTagHistory(); second_compound->AppendTagHistory( - second_compound->GetPseudoType() == CSSSelector::kPseudoSlotted - ? CSSSelector::kShadowSlot - : CSSSelector::kShadowPseudo, + second_compound->GetImplicitShadowCombinatorForMatching(), std::move(compound_selector)); return second_compound; }
diff --git a/third_party/WebKit/Source/core/events/WebInputEventConversionTest.cpp b/third_party/WebKit/Source/core/events/WebInputEventConversionTest.cpp index 93c2272c..61f92367 100644 --- a/third_party/WebKit/Source/core/events/WebInputEventConversionTest.cpp +++ b/third_party/WebKit/Source/core/events/WebInputEventConversionTest.cpp
@@ -157,12 +157,10 @@ { WebGestureEvent web_gesture_event( WebInputEvent::kGestureScrollUpdate, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - web_gesture_event.source_device = kWebGestureDeviceTouchscreen; - web_gesture_event.x = 15; - web_gesture_event.y = 18; - web_gesture_event.global_x = 20; - web_gesture_event.global_y = 22; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); + web_gesture_event.SetPositionInWidget(WebFloatPoint(15, 18)); + web_gesture_event.SetPositionInScreen(WebFloatPoint(20, 22)); web_gesture_event.data.scroll_update.delta_x = 45; web_gesture_event.data.scroll_update.delta_y = 48; web_gesture_event.data.scroll_update.velocity_x = 40; @@ -176,8 +174,8 @@ FlooredIntPoint(scaled_gesture_event.PositionInRootFrame()); EXPECT_EQ(5, position.X()); EXPECT_EQ(6, position.Y()); - EXPECT_EQ(20, scaled_gesture_event.global_x); - EXPECT_EQ(22, scaled_gesture_event.global_y); + EXPECT_EQ(20, scaled_gesture_event.PositionInScreen().x); + EXPECT_EQ(22, scaled_gesture_event.PositionInScreen().y); EXPECT_EQ(15, scaled_gesture_event.DeltaXInRootFrame()); EXPECT_EQ(16, scaled_gesture_event.DeltaYInRootFrame()); // TODO: The velocity values may need to be scaled to page scale in @@ -191,12 +189,10 @@ { WebGestureEvent web_gesture_event( WebInputEvent::kGestureScrollEnd, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - web_gesture_event.source_device = kWebGestureDeviceTouchscreen; - web_gesture_event.x = 15; - web_gesture_event.y = 18; - web_gesture_event.global_x = 20; - web_gesture_event.global_y = 22; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); + web_gesture_event.SetPositionInWidget(WebFloatPoint(15, 18)); + web_gesture_event.SetPositionInScreen(WebFloatPoint(20, 22)); WebGestureEvent scaled_gesture_event = TransformWebGestureEvent(view, web_gesture_event); @@ -204,8 +200,8 @@ FlooredIntPoint(scaled_gesture_event.PositionInRootFrame()); EXPECT_EQ(5, position.X()); EXPECT_EQ(6, position.Y()); - EXPECT_EQ(20, scaled_gesture_event.global_x); - EXPECT_EQ(22, scaled_gesture_event.global_y); + EXPECT_EQ(20, scaled_gesture_event.PositionInScreen().x); + EXPECT_EQ(22, scaled_gesture_event.PositionInScreen().y); EXPECT_EQ(WebGestureEvent::kUnknownMomentumPhase, scaled_gesture_event.InertialPhase()); } @@ -213,8 +209,8 @@ { WebGestureEvent web_gesture_event( WebInputEvent::kGestureTap, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - web_gesture_event.source_device = kWebGestureDeviceTouchscreen; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); web_gesture_event.data.tap.width = 15; web_gesture_event.data.tap.height = 15; @@ -228,8 +224,8 @@ { WebGestureEvent web_gesture_event( WebInputEvent::kGestureTapUnconfirmed, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - web_gesture_event.source_device = kWebGestureDeviceTouchscreen; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); web_gesture_event.data.tap.width = 30; web_gesture_event.data.tap.height = 30; @@ -243,8 +239,8 @@ { WebGestureEvent web_gesture_event( WebInputEvent::kGestureTapDown, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - web_gesture_event.source_device = kWebGestureDeviceTouchscreen; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); web_gesture_event.data.tap_down.width = 9; web_gesture_event.data.tap_down.height = 9; @@ -258,8 +254,8 @@ { WebGestureEvent web_gesture_event( WebInputEvent::kGestureShowPress, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - web_gesture_event.source_device = kWebGestureDeviceTouchscreen; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); web_gesture_event.data.show_press.width = 18; web_gesture_event.data.show_press.height = 18; @@ -273,8 +269,8 @@ { WebGestureEvent web_gesture_event( WebInputEvent::kGestureLongPress, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - web_gesture_event.source_device = kWebGestureDeviceTouchscreen; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); web_gesture_event.data.long_press.width = 15; web_gesture_event.data.long_press.height = 15; @@ -288,8 +284,8 @@ { WebGestureEvent web_gesture_event( WebInputEvent::kGestureTwoFingerTap, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - web_gesture_event.source_device = kWebGestureDeviceTouchscreen; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); web_gesture_event.data.two_finger_tap.first_finger_width = 15; web_gesture_event.data.two_finger_tap.first_finger_height = 15; @@ -423,12 +419,10 @@ { WebGestureEvent web_gesture_event( WebInputEvent::kGestureScrollUpdate, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - web_gesture_event.source_device = kWebGestureDeviceTouchscreen; - web_gesture_event.x = 90; - web_gesture_event.y = 90; - web_gesture_event.global_x = 90; - web_gesture_event.global_y = 90; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); + web_gesture_event.SetPositionInWidget(WebFloatPoint(90, 90)); + web_gesture_event.SetPositionInScreen(WebFloatPoint(90, 90)); web_gesture_event.data.scroll_update.delta_x = 60; web_gesture_event.data.scroll_update.delta_y = 60; @@ -438,8 +432,8 @@ EXPECT_FLOAT_EQ(30, position.X()); EXPECT_FLOAT_EQ(30, position.Y()); - EXPECT_EQ(90, scaled_gesture_event.global_x); - EXPECT_EQ(90, scaled_gesture_event.global_y); + EXPECT_EQ(90, scaled_gesture_event.PositionInScreen().x); + EXPECT_EQ(90, scaled_gesture_event.PositionInScreen().y); EXPECT_EQ(20, scaled_gesture_event.DeltaXInRootFrame()); EXPECT_EQ(20, scaled_gesture_event.DeltaYInRootFrame()); } @@ -447,8 +441,8 @@ { WebGestureEvent web_gesture_event( WebInputEvent::kGestureTap, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - web_gesture_event.source_device = kWebGestureDeviceTouchscreen; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); web_gesture_event.data.tap.width = 30; web_gesture_event.data.tap.height = 30; @@ -462,8 +456,8 @@ { WebGestureEvent web_gesture_event( WebInputEvent::kGestureTapUnconfirmed, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - web_gesture_event.source_device = kWebGestureDeviceTouchscreen; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); web_gesture_event.data.tap.width = 30; web_gesture_event.data.tap.height = 30; @@ -477,8 +471,8 @@ { WebGestureEvent web_gesture_event( WebInputEvent::kGestureTapDown, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - web_gesture_event.source_device = kWebGestureDeviceTouchscreen; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); web_gesture_event.data.tap_down.width = 30; web_gesture_event.data.tap_down.height = 30; @@ -492,8 +486,8 @@ { WebGestureEvent web_gesture_event( WebInputEvent::kGestureShowPress, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - web_gesture_event.source_device = kWebGestureDeviceTouchscreen; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); web_gesture_event.data.show_press.width = 30; web_gesture_event.data.show_press.height = 30; @@ -507,8 +501,8 @@ { WebGestureEvent web_gesture_event( WebInputEvent::kGestureLongPress, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - web_gesture_event.source_device = kWebGestureDeviceTouchscreen; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); web_gesture_event.data.long_press.width = 30; web_gesture_event.data.long_press.height = 30; @@ -522,8 +516,8 @@ { WebGestureEvent web_gesture_event( WebInputEvent::kGestureTwoFingerTap, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - web_gesture_event.source_device = kWebGestureDeviceTouchscreen; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); web_gesture_event.data.two_finger_tap.first_finger_width = 30; web_gesture_event.data.two_finger_tap.first_finger_height = 30; @@ -613,12 +607,10 @@ { WebGestureEvent web_gesture_event( WebInputEvent::kGestureTap, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - web_gesture_event.source_device = kWebGestureDeviceTouchscreen; - web_gesture_event.x = 10; - web_gesture_event.y = 10; - web_gesture_event.global_x = 10; - web_gesture_event.global_y = 10; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); + web_gesture_event.SetPositionInWidget(WebFloatPoint(10, 10)); + web_gesture_event.SetPositionInScreen(WebFloatPoint(10, 10)); web_gesture_event.data.tap.tap_count = 1; web_gesture_event.data.tap.width = 10; web_gesture_event.data.tap.height = 10; @@ -629,8 +621,8 @@ FlooredIntPoint(scaled_gesture_event.PositionInRootFrame()); EXPECT_EQ(10.f, position.X()); EXPECT_EQ(10.f, position.Y()); - EXPECT_EQ(10.f, scaled_gesture_event.global_x); - EXPECT_EQ(10.f, scaled_gesture_event.global_y); + EXPECT_EQ(10.f, scaled_gesture_event.PositionInScreen().x); + EXPECT_EQ(10.f, scaled_gesture_event.PositionInScreen().y); EXPECT_EQ(1, scaled_gesture_event.TapCount()); } } @@ -692,12 +684,10 @@ { WebGestureEvent web_gesture_event( WebInputEvent::kGestureScrollUpdate, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - web_gesture_event.source_device = kWebGestureDeviceTouchscreen; - web_gesture_event.x = 10; - web_gesture_event.y = 10; - web_gesture_event.global_x = 10; - web_gesture_event.global_y = 10; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); + web_gesture_event.SetPositionInWidget(WebFloatPoint(10, 10)); + web_gesture_event.SetPositionInScreen(WebFloatPoint(10, 10)); WebGestureEvent scaled_gesture_event = TransformWebGestureEvent(view, web_gesture_event); @@ -705,8 +695,8 @@ FlooredIntPoint(scaled_gesture_event.PositionInRootFrame()); EXPECT_EQ(5 + visual_offset.X(), position.X()); EXPECT_EQ(5 + visual_offset.Y(), position.Y()); - EXPECT_EQ(10, scaled_gesture_event.global_x); - EXPECT_EQ(10, scaled_gesture_event.global_y); + EXPECT_EQ(10, scaled_gesture_event.PositionInScreen().x); + EXPECT_EQ(10, scaled_gesture_event.PositionInScreen().y); } {
diff --git a/third_party/WebKit/Source/core/exported/WebDevToolsAgentImpl.cpp b/third_party/WebKit/Source/core/exported/WebDevToolsAgentImpl.cpp index a766407..1998bf2 100644 --- a/third_party/WebKit/Source/core/exported/WebDevToolsAgentImpl.cpp +++ b/third_party/WebKit/Source/core/exported/WebDevToolsAgentImpl.cpp
@@ -88,7 +88,6 @@ #include "platform/wtf/text/WTFString.h" #include "public/platform/Platform.h" #include "public/platform/WebFloatRect.h" -#include "public/platform/WebLayerTreeView.h" #include "public/platform/WebRect.h" #include "public/platform/WebString.h" #include "public/web/WebSettings.h" @@ -464,8 +463,6 @@ inspector_session_->Append(new InspectorAuditsAgent(network_agent_)); - tracing_agent_->SetLayerTreeId(agent_->layer_tree_id_); - if (agent_->include_view_agents_) { // TODO(dgozman): we should actually pass the view instead of frame, but // during remote->local transition we cannot access mainFrameImpl() yet, so @@ -490,29 +487,14 @@ // static WebDevToolsAgentImpl* WebDevToolsAgentImpl::CreateForFrame( WebLocalFrameImpl* frame) { - if (!IsMainFrame(frame)) { - WebDevToolsAgentImpl* agent = - new WebDevToolsAgentImpl(frame, false, nullptr); - if (frame->FrameWidgetImpl()) - agent->LayerTreeViewChanged(frame->FrameWidgetImpl()->GetLayerTreeView()); - return agent; - } - - WebViewImpl* view = frame->ViewImpl(); - WebDevToolsAgentImpl* agent = new WebDevToolsAgentImpl(frame, true, nullptr); - agent->LayerTreeViewChanged(view->LayerTreeView()); - return agent; + return new WebDevToolsAgentImpl(frame, IsMainFrame(frame), nullptr); } // static WebDevToolsAgentImpl* WebDevToolsAgentImpl::CreateForWorker( WebLocalFrameImpl* frame, WorkerClient* worker_client) { - WebViewImpl* view = frame->ViewImpl(); - WebDevToolsAgentImpl* agent = - new WebDevToolsAgentImpl(frame, true, worker_client); - agent->LayerTreeViewChanged(view->LayerTreeView()); - return agent; + return new WebDevToolsAgentImpl(frame, true, worker_client); } WebDevToolsAgentImpl::WebDevToolsAgentImpl( @@ -527,8 +509,7 @@ web_local_frame_impl_->GetFrame())), inspected_frames_(new InspectedFrames(web_local_frame_impl_->GetFrame())), resource_container_(new InspectorResourceContainer(inspected_frames_)), - include_view_agents_(include_view_agents), - layer_tree_id_(0) { + include_view_agents_(include_view_agents) { DCHECK(IsMainThread()); DCHECK(web_local_frame_impl_->GetFrame()); } @@ -655,13 +636,6 @@ session->tracing_agent()->RootLayerCleared(); } -void WebDevToolsAgentImpl::LayerTreeViewChanged( - WebLayerTreeView* layer_tree_view) { - layer_tree_id_ = layer_tree_view ? layer_tree_view->LayerTreeId() : 0; - for (auto& session : sessions_) - session->tracing_agent()->SetLayerTreeId(layer_tree_id_); -} - void WebDevToolsAgentImpl::ShowReloadingBlanket() { for (auto& session : sessions_) session->overlay_agent()->ShowReloadingBlanket();
diff --git a/third_party/WebKit/Source/core/exported/WebDevToolsAgentImpl.h b/third_party/WebKit/Source/core/exported/WebDevToolsAgentImpl.h index 98cd842..fbdffc6 100644 --- a/third_party/WebKit/Source/core/exported/WebDevToolsAgentImpl.h +++ b/third_party/WebKit/Source/core/exported/WebDevToolsAgentImpl.h
@@ -52,7 +52,6 @@ class InspectorResourceContainer; class InspectorResourceContentLoader; class LocalFrame; -class WebLayerTreeView; class WebLocalFrameImpl; class CORE_EXPORT WebDevToolsAgentImpl final @@ -87,7 +86,6 @@ void DidCommitLoadForLocalFrame(LocalFrame*); void DidStartProvisionalLoad(LocalFrame*); bool ScreencastEnabled(); - void LayerTreeViewChanged(WebLayerTreeView*); void RootLayerCleared(); String NavigationInitiatorInfo(LocalFrame*); String EvaluateInOverlayForTesting(const String& script); @@ -134,7 +132,6 @@ Member<InspectorResourceContainer> resource_container_; Member<Node> node_to_inspect_; bool include_view_agents_; - int layer_tree_id_; }; } // namespace blink
diff --git a/third_party/WebKit/Source/core/exported/WebFrameTest.cpp b/third_party/WebKit/Source/core/exported/WebFrameTest.cpp index 4b0451f..5ab5313 100644 --- a/third_party/WebKit/Source/core/exported/WebFrameTest.cpp +++ b/third_party/WebKit/Source/core/exported/WebFrameTest.cpp
@@ -2148,7 +2148,7 @@ web_view_helper.GetWebView()->GetSettings()->SetForceZeroLayoutHeight(true); web_view_helper.Resize(WebSize(viewport_width, viewport_height)); - IntPoint hit_point = IntPoint(30, 30); // button size is 100x100 + FloatPoint hit_point = FloatPoint(30, 30); // button size is 100x100 WebLocalFrameImpl* frame = web_view_helper.LocalMainFrame(); Document* document = frame->GetFrame()->GetDocument(); @@ -2159,11 +2159,11 @@ WebGestureEvent gesture_event(WebInputEvent::kGestureTap, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); gesture_event.SetFrameScale(1); - gesture_event.x = gesture_event.global_x = hit_point.X(); - gesture_event.y = gesture_event.global_y = hit_point.Y(); - gesture_event.source_device = kWebGestureDeviceTouchscreen; + gesture_event.SetPositionInWidget(hit_point); + gesture_event.SetPositionInScreen(hit_point); web_view_helper.GetWebView() ->MainFrameImpl() ->GetFrame() @@ -6282,35 +6282,35 @@ .As<v8::Int32>() ->Value(); - IntPoint hit_point; + FloatPoint hit_point; if (expected_result.Length() >= 17) { - hit_point = IntPoint(expected_result.Get(context, 15) - .ToLocalChecked() - .As<v8::Int32>() - ->Value(), - expected_result.Get(context, 16) - .ToLocalChecked() - .As<v8::Int32>() - ->Value()); + hit_point = FloatPoint(expected_result.Get(context, 15) + .ToLocalChecked() + .As<v8::Int32>() + ->Value(), + expected_result.Get(context, 16) + .ToLocalChecked() + .As<v8::Int32>() + ->Value()); } else { hit_point = - IntPoint((start_edge_top_in_layer_x + start_edge_bottom_in_layer_x + - end_edge_top_in_layer_x + end_edge_bottom_in_layer_x) / - 4, - (start_edge_top_in_layer_y + start_edge_bottom_in_layer_y + - end_edge_top_in_layer_y + end_edge_bottom_in_layer_y) / - 4 + - 3); + FloatPoint((start_edge_top_in_layer_x + start_edge_bottom_in_layer_x + + end_edge_top_in_layer_x + end_edge_bottom_in_layer_x) / + 4, + (start_edge_top_in_layer_y + start_edge_bottom_in_layer_y + + end_edge_top_in_layer_y + end_edge_bottom_in_layer_y) / + 4 + + 3); } WebGestureEvent gesture_event(WebInputEvent::kGestureTap, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); gesture_event.SetFrameScale(1); - gesture_event.x = gesture_event.global_x = hit_point.X(); - gesture_event.y = gesture_event.global_y = hit_point.Y(); - gesture_event.source_device = kWebGestureDeviceTouchscreen; + gesture_event.SetPositionInWidget(hit_point); + gesture_event.SetPositionInScreen(hit_point); web_view_helper_.GetWebView() ->MainFrameImpl() @@ -6487,10 +6487,9 @@ static WebCoalescedInputEvent FatTap(int x, int y, int diameter) { WebGestureEvent event(WebInputEvent::kGestureTap, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - event.source_device = kWebGestureDeviceTouchscreen; - event.x = x; - event.y = y; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(WebFloatPoint(x, y)); event.data.tap.width = diameter; event.data.tap.height = diameter; return WebCoalescedInputEvent(event); @@ -10075,10 +10074,9 @@ helper.GetWebView()->Resize(WebSize(1000, 1000)); WebGestureEvent event(WebInputEvent::kGestureTap, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - event.source_device = kWebGestureDeviceTouchscreen; - event.x = 20; - event.y = 20; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(WebFloatPoint(20, 20)); child_frame->FrameWidget()->HandleInputEvent(WebCoalescedInputEvent(event)); EXPECT_TRUE(child_widget_client.DidHandleGestureEvent()); @@ -10468,12 +10466,11 @@ float delta_x = 0.0, float delta_y = 0.0) { WebGestureEvent event(type, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); + WebInputEvent::GetStaticTimeStampForTests(), + GetParam().second); // TODO(wjmaclean): Make sure that touchpad device is only ever used for // gesture scrolling event types. - event.source_device = GetParam().second; - event.x = 100; - event.y = 100; + event.SetPositionInWidget(WebFloatPoint(100, 100)); if (type == WebInputEvent::kGestureScrollUpdate) { event.data.scroll_update.delta_x = delta_x; event.data.scroll_update.delta_y = delta_y; @@ -11556,18 +11553,15 @@ Document* document = web_view->MainFrameImpl()->GetFrame()->GetDocument(); document->documentElement()->SetLayoutObject(nullptr); - WebGestureEvent begin_event(WebInputEvent::kGestureScrollBegin, - WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - begin_event.source_device = kWebGestureDeviceTouchpad; - WebGestureEvent update_event(WebInputEvent::kGestureScrollUpdate, - WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - update_event.source_device = kWebGestureDeviceTouchpad; - WebGestureEvent end_event(WebInputEvent::kGestureScrollEnd, - WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - end_event.source_device = kWebGestureDeviceTouchpad; + WebGestureEvent begin_event( + WebInputEvent::kGestureScrollBegin, WebInputEvent::kNoModifiers, + WebInputEvent::GetStaticTimeStampForTests(), kWebGestureDeviceTouchpad); + WebGestureEvent update_event( + WebInputEvent::kGestureScrollUpdate, WebInputEvent::kNoModifiers, + WebInputEvent::GetStaticTimeStampForTests(), kWebGestureDeviceTouchpad); + WebGestureEvent end_event( + WebInputEvent::kGestureScrollEnd, WebInputEvent::kNoModifiers, + WebInputEvent::GetStaticTimeStampForTests(), kWebGestureDeviceTouchpad); // Try GestureScrollEnd and GestureScrollUpdate first to make sure that not // seeing a Begin first doesn't break anything. (This currently happens).
diff --git a/third_party/WebKit/Source/core/exported/WebPagePopupImpl.cpp b/third_party/WebKit/Source/core/exported/WebPagePopupImpl.cpp index e5e7964..9cbbea2 100644 --- a/third_party/WebKit/Source/core/exported/WebPagePopupImpl.cpp +++ b/third_party/WebKit/Source/core/exported/WebPagePopupImpl.cpp
@@ -473,7 +473,8 @@ return WebInputEventResult::kNotHandled; if ((event.GetType() == WebInputEvent::kGestureTap || event.GetType() == WebInputEvent::kGestureTapDown) && - !IsViewportPointInWindow(event.x, event.y)) { + !IsViewportPointInWindow(event.PositionInWidget().x, + event.PositionInWidget().y)) { Cancel(); return WebInputEventResult::kNotHandled; }
diff --git a/third_party/WebKit/Source/core/exported/WebPluginContainerImpl.cpp b/third_party/WebKit/Source/core/exported/WebPluginContainerImpl.cpp index aa9630184..9b9c5cb 100644 --- a/third_party/WebKit/Source/core/exported/WebPluginContainerImpl.cpp +++ b/third_party/WebKit/Source/core/exported/WebPluginContainerImpl.cpp
@@ -996,12 +996,10 @@ WebGestureEvent translated_event = event->NativeEvent(); WebFloatPoint absolute_root_frame_location = event->NativeEvent().PositionInRootFrame(); - IntPoint local_point = - RoundedIntPoint(element_->GetLayoutObject()->AbsoluteToLocal( - absolute_root_frame_location, kUseTransforms)); + FloatPoint local_point = element_->GetLayoutObject()->AbsoluteToLocal( + absolute_root_frame_location, kUseTransforms); translated_event.FlattenTransform(); - translated_event.x = local_point.X(); - translated_event.y = local_point.Y(); + translated_event.SetPositionInWidget(local_point); WebCursorInfo cursor_info; if (web_plugin_->HandleInputEvent(WebCoalescedInputEvent(translated_event),
diff --git a/third_party/WebKit/Source/core/exported/WebPluginContainerTest.cpp b/third_party/WebKit/Source/core/exported/WebPluginContainerTest.cpp index 52fe7440..60ee8ab 100644 --- a/third_party/WebKit/Source/core/exported/WebPluginContainerTest.cpp +++ b/third_party/WebKit/Source/core/exported/WebPluginContainerTest.cpp
@@ -769,13 +769,12 @@ WebGestureEvent event(WebInputEvent::kGestureLongPress, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - event.source_device = kWebGestureDeviceTouchscreen; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); // First, send an event that doesn't hit the plugin to verify that the // plugin doesn't receive it. - event.x = 0; - event.y = 0; + event.SetPositionInWidget(WebFloatPoint(0, 0)); web_view->HandleInputEvent(WebCoalescedInputEvent(event)); RunPendingTasks(); @@ -785,8 +784,8 @@ // Next, send an event that does hit the plugin, and verify it does receive // it. WebRect rect = plugin_container_one_element.BoundsInViewport(); - event.x = rect.x + rect.width / 2; - event.y = rect.y + rect.height / 2; + event.SetPositionInWidget( + WebFloatPoint(rect.x + rect.width / 2, rect.y + rect.height / 2)); web_view->HandleInputEvent(WebCoalescedInputEvent(event)); RunPendingTasks();
diff --git a/third_party/WebKit/Source/core/exported/WebViewImpl.cpp b/third_party/WebKit/Source/core/exported/WebViewImpl.cpp index 1255cc1..ea6bc5a 100644 --- a/third_party/WebKit/Source/core/exported/WebViewImpl.cpp +++ b/third_party/WebKit/Source/core/exported/WebViewImpl.cpp
@@ -654,9 +654,9 @@ !visual_viewport.ShouldDisableDesktopWorkarounds() && !screencast_enabled) { IntRect bounding_box(visual_viewport.ViewportToRootFrame( - IntRect(event.x - event.data.tap.width / 2, - event.y - event.data.tap.height / 2, event.data.tap.width, - event.data.tap.height))); + IntRect(event.PositionInWidget().x - event.data.tap.width / 2, + event.PositionInWidget().y - event.data.tap.height / 2, + event.data.tap.width, event.data.tap.height))); // TODO(bokan): We shouldn't pass details of the VisualViewport offset // to render_view_impl. crbug.com/459591 @@ -787,11 +787,10 @@ bool is_long_press) { WebGestureEvent event(is_long_press ? WebInputEvent::kGestureLongPress : WebInputEvent::kGestureTap, - WebInputEvent::kNoModifiers, timestamp_seconds); + WebInputEvent::kNoModifiers, timestamp_seconds, + blink::kWebGestureDeviceTouchscreen); - event.x = tap_viewport_offset.x; - event.y = tap_viewport_offset.y; - event.source_device = blink::kWebGestureDeviceTouchscreen; + event.SetPositionInWidget(FloatPoint(tap_viewport_offset)); { // Compute UMA stat about whether the node selected by disambiguation UI was @@ -827,8 +826,10 @@ WebInputEvent::kMouseWheel, pinch_event.GetModifiers() | WebInputEvent::kControlKey, pinch_event.TimeStampSeconds()); - wheel_event.SetPositionInWidget(pinch_event.x, pinch_event.y); - wheel_event.SetPositionInScreen(pinch_event.global_x, pinch_event.global_y); + wheel_event.SetPositionInWidget(pinch_event.PositionInWidget().x, + pinch_event.PositionInWidget().y); + wheel_event.SetPositionInScreen(pinch_event.PositionInScreen().x, + pinch_event.PositionInScreen().y); wheel_event.delta_x = 0; // The function to convert scales to deltaY values is designed to be @@ -2084,7 +2085,7 @@ // For touchpad gestures synthesize a Windows-like wheel event // to send to any handlers that may exist. Not necessary for touchscreen // as touch events would have already been sent for the gesture. - if (pinch_event.source_device == kWebGestureDeviceTouchpad) { + if (pinch_event.SourceDevice() == kWebGestureDeviceTouchpad) { result = HandleSyntheticWheelFromTouchpadPinchEvent(pinch_event); if (result != WebInputEventResult::kNotHandled) return result; @@ -2095,7 +2096,7 @@ if (GetPage()->GetVisualViewport().MagnifyScaleAroundAnchor( pinch_event.data.pinch_update.scale, - FloatPoint(pinch_event.x, pinch_event.y))) + pinch_event.PositionInWidget())) return WebInputEventResult::kHandledSystem; } @@ -2104,11 +2105,11 @@ const WebGestureEvent& pinch_event = static_cast<const WebGestureEvent&>(input_event); float min_scale = MinimumPageScaleFactor(); - if (pinch_event.source_device == kWebGestureDeviceTouchpad && + if (pinch_event.SourceDevice() == kWebGestureDeviceTouchpad && PageScaleFactor() <= min_scale * maximumZoomForSnapToMinimum) { IntPoint target_position = MainFrameImpl()->GetFrameView()->ViewportToContents( - IntPoint(pinch_event.x, pinch_event.y)); + FlooredIntPoint(pinch_event.PositionInWidget())); StartPageScaleAnimation(target_position, true, min_scale, snapToMiminimumZoomAnimationDurationInSeconds); } @@ -3457,13 +3458,11 @@ if (!page_->MainFrame()->IsLocalFrame()) return HitTestResult(); - WebGestureEvent tap_event(WebInputEvent::kGestureTap, - WebInputEvent::kNoModifiers, - WTF::CurrentTimeTicksInSeconds()); - tap_event.x = tap_point_window_pos.x; - tap_event.y = tap_point_window_pos.y; + WebGestureEvent tap_event( + WebInputEvent::kGestureTap, WebInputEvent::kNoModifiers, + WTF::CurrentTimeTicksInSeconds(), kWebGestureDeviceTouchscreen); // GestureTap is only ever from a touchscreen. - tap_event.source_device = kWebGestureDeviceTouchscreen; + tap_event.SetPositionInWidget(FloatPoint(tap_point_window_pos)); tap_event.data.tap.tap_count = 1; tap_event.data.tap.width = tap_area.width; tap_event.data.tap.height = tap_area.height; @@ -3648,9 +3647,6 @@ } } - if (WebDevToolsAgentImpl* dev_tools = MainFrameDevToolsAgentImpl()) - dev_tools->LayerTreeViewChanged(layer_tree_view_); - page_->GetSettings().SetAcceleratedCompositingEnabled(layer_tree_view_); if (layer_tree_view_) { page_->LayerTreeViewInitialized(*layer_tree_view_, nullptr);
diff --git a/third_party/WebKit/Source/core/exported/WebViewTest.cpp b/third_party/WebKit/Source/core/exported/WebViewTest.cpp index 2472bc1..96f6a0d 100644 --- a/third_party/WebKit/Source/core/exported/WebViewTest.cpp +++ b/third_party/WebKit/Source/core/exported/WebViewTest.cpp
@@ -196,11 +196,11 @@ void DidHandleGestureEvent(const WebGestureEvent& event, bool event_cancelled) override { if (event.GetType() == WebInputEvent::kGestureTap) { - tap_x_ = event.x; - tap_y_ = event.y; + tap_x_ = event.PositionInWidget().x; + tap_y_ = event.PositionInWidget().y; } else if (event.GetType() == WebInputEvent::kGestureLongPress) { - longpress_x_ = event.x; - longpress_y_ = event.y; + longpress_x_ = event.PositionInWidget().x; + longpress_y_ = event.PositionInWidget().y; } } @@ -2537,20 +2537,18 @@ // TODO(bokan): Technically incorrect, event positions should be in viewport // space. crbug.com/371902. - IntPoint center = + FloatPoint center( web_view_helper_.GetWebView() ->MainFrameImpl() ->GetFrameView() ->ContentsToScreen( element->GetLayoutObject()->AbsoluteBoundingBoxRect()) - .Center(); + .Center()); WebGestureEvent event(type, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - - event.source_device = kWebGestureDeviceTouchscreen; - event.x = center.X(); - event.y = center.Y(); + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(center); web_view_helper_.GetWebView()->HandleInputEvent( WebCoalescedInputEvent(event)); @@ -2582,18 +2580,16 @@ WebView* web_view = web_view_helper_.InitializeAndLoad("about:blank", nullptr, &client); WebGestureEvent event(WebInputEvent::kGestureTap, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - event.source_device = kWebGestureDeviceTouchscreen; - event.x = 3; - event.y = 8; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(WebFloatPoint(3, 8)); web_view->HandleInputEvent(WebCoalescedInputEvent(event)); RunPendingTasks(); EXPECT_EQ(3, client.TapX()); EXPECT_EQ(8, client.TapY()); client.Reset(); event.SetType(WebInputEvent::kGestureLongPress); - event.x = 25; - event.y = 7; + event.SetPositionInWidget(WebFloatPoint(25, 7)); web_view->HandleInputEvent(WebCoalescedInputEvent(event)); RunPendingTasks(); EXPECT_EQ(25, client.LongpressX()); @@ -2616,10 +2612,9 @@ blink::WebFrameWidget::Create(&web_widget_client, local_frame); WebGestureEvent event(WebInputEvent::kGestureTap, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - event.source_device = kWebGestureDeviceTouchscreen; - event.x = 3; - event.y = 8; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(WebFloatPoint(3, 8)); EXPECT_EQ(WebInputEventResult::kNotHandled, web_view->HandleInputEvent(WebCoalescedInputEvent(event))); web_view->Close(); @@ -2637,10 +2632,9 @@ WebGestureEvent event(WebInputEvent::kGestureLongPress, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - event.source_device = kWebGestureDeviceTouchscreen; - event.x = 250; - event.y = 150; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(WebFloatPoint(250, 150)); EXPECT_EQ(WebInputEventResult::kNotHandled, web_view->HandleInputEvent(WebCoalescedInputEvent(event))); @@ -2658,10 +2652,9 @@ WebGestureEvent event(WebInputEvent::kGestureLongPress, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - event.source_device = kWebGestureDeviceTouchscreen; - event.x = 250; - event.y = 150; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(WebFloatPoint(250, 150)); EXPECT_EQ(WebInputEventResult::kHandledSystem, web_view->HandleInputEvent(WebCoalescedInputEvent(event))); @@ -2679,10 +2672,9 @@ WebGestureEvent event(WebInputEvent::kGestureLongPress, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - event.source_device = kWebGestureDeviceTouchscreen; - event.x = 10; - event.y = 10; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(WebFloatPoint(10, 10)); EXPECT_NE(WebInputEventResult::kHandledSystem, web_view->HandleInputEvent(WebCoalescedInputEvent(event))); @@ -2704,10 +2696,9 @@ WebGestureEvent event(WebInputEvent::kGestureLongPress, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - event.source_device = kWebGestureDeviceTouchscreen; - event.x = 10; - event.y = 10; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(WebFloatPoint(10, 10)); EXPECT_EQ(WebInputEventResult::kHandledSystem, web_view->HandleInputEvent(WebCoalescedInputEvent(event))); @@ -2729,10 +2720,9 @@ WebGestureEvent event(WebInputEvent::kGestureLongPress, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - event.source_device = kWebGestureDeviceTouchscreen; - event.x = 10; - event.y = 10; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(WebFloatPoint(10, 10)); EXPECT_EQ(WebInputEventResult::kHandledSystem, web_view->HandleInputEvent(WebCoalescedInputEvent(event))); @@ -2750,10 +2740,9 @@ WebGestureEvent event(WebInputEvent::kGestureLongPress, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - event.source_device = kWebGestureDeviceTouchscreen; - event.x = 10; - event.y = 10; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(WebFloatPoint(10, 10)); EXPECT_EQ(WebInputEventResult::kHandledSystem, web_view->HandleInputEvent(WebCoalescedInputEvent(event))); @@ -2771,10 +2760,9 @@ WebGestureEvent event(WebInputEvent::kGestureLongPress, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - event.source_device = kWebGestureDeviceTouchscreen; - event.x = 500; - event.y = 300; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(WebFloatPoint(500, 300)); EXPECT_EQ(WebInputEventResult::kHandledSystem, web_view->HandleInputEvent(WebCoalescedInputEvent(event))); @@ -2859,10 +2847,9 @@ WebGestureEvent event(WebInputEvent::kGestureLongPress, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - event.source_device = kWebGestureDeviceTouchscreen; - event.x = 10; - event.y = 10; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(WebFloatPoint(10, 10)); EXPECT_EQ(WebInputEventResult::kHandledSystem, web_view->HandleInputEvent(WebCoalescedInputEvent(event))); @@ -2879,10 +2866,9 @@ WebGestureEvent event(WebInputEvent::kGestureLongPress, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - event.source_device = kWebGestureDeviceTouchscreen; - event.x = 300; - event.y = 300; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(WebFloatPoint(300, 300)); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); EXPECT_EQ(WebInputEventResult::kHandledSystem, @@ -2965,10 +2951,9 @@ // Double-tap on carriage returns. WebGestureEvent event(WebInputEvent::kGestureTap, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - event.source_device = kWebGestureDeviceTouchscreen; - event.x = 100; - event.y = 25; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(WebFloatPoint(100, 25)); event.data.tap.tap_count = 2; web_view->HandleInputEvent(WebCoalescedInputEvent(event)); @@ -3258,10 +3243,9 @@ WebGestureEvent event(WebInputEvent::kGestureShowPress, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - event.source_device = kWebGestureDeviceTouchscreen; - event.x = 20; - event.y = 20; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(WebFloatPoint(20, 20)); // Just make sure we don't hit any asserts. web_view_impl->HandleInputEvent(WebCoalescedInputEvent(event));
diff --git a/third_party/WebKit/Source/core/frame/BrowserControlsTest.cpp b/third_party/WebKit/Source/core/frame/BrowserControlsTest.cpp index 7c4faaf..6cd9525 100644 --- a/third_party/WebKit/Source/core/frame/BrowserControlsTest.cpp +++ b/third_party/WebKit/Source/core/frame/BrowserControlsTest.cpp
@@ -102,10 +102,8 @@ int delta_x = 0, int delta_y = 0) { WebGestureEvent event(type, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - event.source_device = kWebGestureDeviceTouchscreen; - event.x = 100; - event.y = 100; + kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(FloatPoint(100, 100)); if (type == WebInputEvent::kGestureScrollUpdate) { event.data.scroll_update.delta_x = delta_x; event.data.scroll_update.delta_y = delta_y;
diff --git a/third_party/WebKit/Source/core/frame/LocalFrameView.cpp b/third_party/WebKit/Source/core/frame/LocalFrameView.cpp index 2fe34f7..2ff905d 100644 --- a/third_party/WebKit/Source/core/frame/LocalFrameView.cpp +++ b/third_party/WebKit/Source/core/frame/LocalFrameView.cpp
@@ -3250,6 +3250,9 @@ }); { + TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), + "SetLayerTreeId", TRACE_EVENT_SCOPE_THREAD, "data", + InspectorSetLayerTreeId::Data(frame_.Get())); TRACE_EVENT1("devtools.timeline", "UpdateLayerTree", "data", InspectorUpdateLayerTreeEvent::Data(frame_.Get()));
diff --git a/third_party/WebKit/Source/core/frame/VisualViewportTest.cpp b/third_party/WebKit/Source/core/frame/VisualViewportTest.cpp index b4ab824..f4bc89d9 100644 --- a/third_party/WebKit/Source/core/frame/VisualViewportTest.cpp +++ b/third_party/WebKit/Source/core/frame/VisualViewportTest.cpp
@@ -1750,21 +1750,19 @@ EXPECT_EQ(FloatSize(300, 200), visual_viewport.GetScrollOffset()); // Send a scroll event on the main thread path. - WebGestureEvent gsb(WebInputEvent::kGestureScrollBegin, - WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); + WebGestureEvent gsb( + WebInputEvent::kGestureScrollBegin, WebInputEvent::kNoModifiers, + WebInputEvent::GetStaticTimeStampForTests(), kWebGestureDeviceTouchpad); gsb.SetFrameScale(1); - gsb.source_device = kWebGestureDeviceTouchpad; gsb.data.scroll_begin.delta_x_hint = -50; gsb.data.scroll_begin.delta_x_hint = -60; gsb.data.scroll_begin.delta_hint_units = WebGestureEvent::kPrecisePixels; GetFrame()->GetEventHandler().HandleGestureEvent(gsb); - WebGestureEvent gsu(WebInputEvent::kGestureScrollUpdate, - WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); + WebGestureEvent gsu( + WebInputEvent::kGestureScrollUpdate, WebInputEvent::kNoModifiers, + WebInputEvent::GetStaticTimeStampForTests(), kWebGestureDeviceTouchpad); gsu.SetFrameScale(1); - gsu.source_device = kWebGestureDeviceTouchpad; gsu.data.scroll_update.delta_x = -50; gsu.data.scroll_update.delta_y = -60; gsu.data.scroll_update.delta_units = WebGestureEvent::kPrecisePixels; @@ -1904,12 +1902,10 @@ RegisterMockedHttpURLLoad("200-by-800-viewport.html"); NavigateTo(base_url_ + "200-by-800-viewport.html"); - WebGestureEvent pinch_update(WebInputEvent::kGesturePinchUpdate, - WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - pinch_update.source_device = kWebGestureDeviceTouchpad; - pinch_update.x = 100; - pinch_update.y = 100; + WebGestureEvent pinch_update( + WebInputEvent::kGesturePinchUpdate, WebInputEvent::kNoModifiers, + WebInputEvent::GetStaticTimeStampForTests(), kWebGestureDeviceTouchpad); + pinch_update.SetPositionInWidget(FloatPoint(100, 100)); pinch_update.data.pinch_update.scale = 2; pinch_update.data.pinch_update.zoom_disabled = false;
diff --git a/third_party/WebKit/Source/core/frame/WebFrameWidgetBase.cpp b/third_party/WebKit/Source/core/frame/WebFrameWidgetBase.cpp index 61018dd..b1b5b75e 100644 --- a/third_party/WebKit/Source/core/frame/WebFrameWidgetBase.cpp +++ b/third_party/WebKit/Source/core/frame/WebFrameWidgetBase.cpp
@@ -462,17 +462,16 @@ WebInputEventResult event_result = WebInputEventResult::kNotHandled; switch (event.GetType()) { case WebInputEvent::kGestureFlingStart: { - if (event.source_device != kWebGestureDeviceSyntheticAutoscroll) + if (event.SourceDevice() != kWebGestureDeviceSyntheticAutoscroll) EndActiveFlingAnimation(); - position_on_fling_start_ = WebPoint(event.x, event.y); - global_position_on_fling_start_ = - WebPoint(event.global_x, event.global_y); + position_on_fling_start_ = event.PositionInWidget(); + global_position_on_fling_start_ = event.PositionInScreen(); fling_modifier_ = event.GetModifiers(); - fling_source_device_ = event.source_device; + fling_source_device_ = event.SourceDevice(); DCHECK_NE(fling_source_device_, kWebGestureDeviceUninitialized); std::unique_ptr<WebGestureCurve> fling_curve = Platform::Current()->CreateFlingAnimationCurve( - event.source_device, + event.SourceDevice(), WebFloatPoint(event.data.fling_start.velocity_x, event.data.fling_start.velocity_y), WebSize()); @@ -512,13 +511,10 @@ WebGestureEvent WebFrameWidgetBase::CreateGestureScrollEventFromFling( WebInputEvent::Type type, WebGestureDevice source_device) const { - WebGestureEvent gesture_event(type, fling_modifier_, - WTF::CurrentTimeTicksInSeconds()); - gesture_event.source_device = source_device; - gesture_event.x = position_on_fling_start_.x; - gesture_event.y = position_on_fling_start_.y; - gesture_event.global_x = global_position_on_fling_start_.x; - gesture_event.global_y = global_position_on_fling_start_.y; + WebGestureEvent gesture_event( + type, fling_modifier_, WTF::CurrentTimeTicksInSeconds(), source_device); + gesture_event.SetPositionInWidget(position_on_fling_start_); + gesture_event.SetPositionInScreen(global_position_on_fling_start_); return gesture_event; }
diff --git a/third_party/WebKit/Source/core/frame/WebFrameWidgetBase.h b/third_party/WebKit/Source/core/frame/WebFrameWidgetBase.h index 6ce7dcd..a73cb2c5 100644 --- a/third_party/WebKit/Source/core/frame/WebFrameWidgetBase.h +++ b/third_party/WebKit/Source/core/frame/WebFrameWidgetBase.h
@@ -172,8 +172,8 @@ void CancelDrag(); std::unique_ptr<WebActiveGestureAnimation> gesture_animation_; - WebPoint position_on_fling_start_; - WebPoint global_position_on_fling_start_; + WebFloatPoint position_on_fling_start_; + WebFloatPoint global_position_on_fling_start_; int fling_modifier_; WebGestureDevice fling_source_device_;
diff --git a/third_party/WebKit/Source/core/frame/WebFrameWidgetImpl.cpp b/third_party/WebKit/Source/core/frame/WebFrameWidgetImpl.cpp index 425d8c96..ccc7a812 100644 --- a/third_party/WebKit/Source/core/frame/WebFrameWidgetImpl.cpp +++ b/third_party/WebKit/Source/core/frame/WebFrameWidgetImpl.cpp
@@ -993,9 +993,6 @@ layer_tree_view_->CompositorAnimationHost()); } - if (WebDevToolsAgentImpl* dev_tools = local_root_->DevToolsAgentImpl()) - dev_tools->LayerTreeViewChanged(layer_tree_view_); - GetPage()->GetSettings().SetAcceleratedCompositingEnabled(layer_tree_view_); if (layer_tree_view_) { GetPage()->LayerTreeViewInitialized(*layer_tree_view_,
diff --git a/third_party/WebKit/Source/core/input/EventHandlerTest.cpp b/third_party/WebKit/Source/core/input/EventHandlerTest.cpp index dc00bfd..92a14e56 100644 --- a/third_party/WebKit/Source/core/input/EventHandlerTest.cpp +++ b/third_party/WebKit/Source/core/input/EventHandlerTest.cpp
@@ -41,13 +41,13 @@ class TapEventBuilder : public WebGestureEvent { public: - TapEventBuilder(IntPoint position, int tap_count) + TapEventBuilder(FloatPoint position, int tap_count) : WebGestureEvent(WebInputEvent::kGestureTap, WebInputEvent::kNoModifiers, - CurrentTimeTicksInSeconds()) { - x = global_x = position.X(); - y = global_y = position.Y(); - source_device = kWebGestureDeviceTouchscreen; + CurrentTimeTicksInSeconds(), + kWebGestureDeviceTouchscreen) { + SetPositionInWidget(position); + SetPositionInScreen(position); data.tap.tap_count = tap_count; data.tap.width = 5; data.tap.height = 5; @@ -57,11 +57,13 @@ class LongPressEventBuilder : public WebGestureEvent { public: - LongPressEventBuilder(IntPoint position) : WebGestureEvent() { - type_ = WebInputEvent::kGestureLongPress; - x = global_x = position.X(); - y = global_y = position.Y(); - source_device = kWebGestureDeviceTouchscreen; + LongPressEventBuilder(FloatPoint position) + : WebGestureEvent(WebInputEvent::kGestureLongPress, + WebInputEvent::kNoModifiers, + CurrentTimeTicksInSeconds(), + kWebGestureDeviceTouchscreen) { + SetPositionInWidget(position); + SetPositionInScreen(position); data.long_press.width = 5; data.long_press.height = 5; frame_scale_ = 1; @@ -180,7 +182,7 @@ Node* line = GetDocument().getElementById("line")->firstChild(); - TapEventBuilder single_tap_event(IntPoint(0, 0), 1); + TapEventBuilder single_tap_event(FloatPoint(0, 0), 1); GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent( single_tap_event); ASSERT_TRUE(Selection().GetSelectionInDOMTree().IsCaret()); @@ -188,7 +190,7 @@ // Multi-tap events on editable elements should trigger selection, just // like multi-click events. - TapEventBuilder double_tap_event(IntPoint(0, 0), 2); + TapEventBuilder double_tap_event(FloatPoint(0, 0), 2); GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent( double_tap_event); ASSERT_TRUE(Selection().GetSelectionInDOMTree().IsRange()); @@ -204,7 +206,7 @@ EXPECT_EQ("One", WebString(Selection().SelectedText()).Utf8()); } - TapEventBuilder triple_tap_event(IntPoint(0, 0), 3); + TapEventBuilder triple_tap_event(FloatPoint(0, 0), 3); GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent( triple_tap_event); ASSERT_TRUE(Selection().GetSelectionInDOMTree().IsRange()); @@ -221,20 +223,20 @@ Node* line = GetDocument().getElementById("line")->firstChild(); - TapEventBuilder single_tap_event(IntPoint(0, 0), 1); + TapEventBuilder single_tap_event(FloatPoint(0, 0), 1); GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent( single_tap_event); ASSERT_TRUE(Selection().GetSelectionInDOMTree().IsCaret()); EXPECT_EQ(Position(line, 0), Selection().GetSelectionInDOMTree().Base()); // As the text is readonly, multi-tap events should not trigger selection. - TapEventBuilder double_tap_event(IntPoint(0, 0), 2); + TapEventBuilder double_tap_event(FloatPoint(0, 0), 2); GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent( double_tap_event); ASSERT_TRUE(Selection().GetSelectionInDOMTree().IsCaret()); EXPECT_EQ(Position(line, 0), Selection().GetSelectionInDOMTree().Base()); - TapEventBuilder triple_tap_event(IntPoint(0, 0), 3); + TapEventBuilder triple_tap_event(FloatPoint(0, 0), 3); GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent( triple_tap_event); ASSERT_TRUE(Selection().GetSelectionInDOMTree().IsCaret()); @@ -584,7 +586,7 @@ TEST_F(EventHandlerTest, EmptyTextfieldInsertionOnTap) { SetHtmlInnerHTML("<textarea cols=50 rows=50></textarea>"); - TapEventBuilder single_tap_event(IntPoint(200, 200), 1); + TapEventBuilder single_tap_event(FloatPoint(200, 200), 1); GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent( single_tap_event); @@ -595,7 +597,7 @@ TEST_F(EventHandlerTest, NonEmptyTextfieldInsertionOnTap) { SetHtmlInnerHTML("<textarea cols=50 rows=50>Enter text</textarea>"); - TapEventBuilder single_tap_event(IntPoint(200, 200), 1); + TapEventBuilder single_tap_event(FloatPoint(200, 200), 1); GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent( single_tap_event); @@ -606,7 +608,7 @@ TEST_F(EventHandlerTest, NewlineDivInsertionOnTap) { SetHtmlInnerHTML("<div contenteditable><br/></div>"); - TapEventBuilder single_tap_event(IntPoint(10, 10), 1); + TapEventBuilder single_tap_event(FloatPoint(10, 10), 1); GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent( single_tap_event); @@ -617,7 +619,7 @@ TEST_F(EventHandlerTest, EmptyTextfieldInsertionOnLongPress) { SetHtmlInnerHTML("<textarea cols=50 rows=50></textarea>"); - LongPressEventBuilder long_press_event(IntPoint(200, 200)); + LongPressEventBuilder long_press_event(FloatPoint(200, 200)); GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent( long_press_event); @@ -625,7 +627,7 @@ ASSERT_TRUE(Selection().IsHandleVisible()); // Single Tap on an empty edit field should clear insertion handle - TapEventBuilder single_tap_event(IntPoint(200, 200), 1); + TapEventBuilder single_tap_event(FloatPoint(200, 200), 1); GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent( single_tap_event); @@ -636,7 +638,7 @@ TEST_F(EventHandlerTest, NonEmptyTextfieldInsertionOnLongPress) { SetHtmlInnerHTML("<textarea cols=50 rows=50>Enter text</textarea>"); - LongPressEventBuilder long_press_event(IntPoint(200, 200)); + LongPressEventBuilder long_press_event(FloatPoint(200, 200)); GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent( long_press_event); @@ -648,7 +650,7 @@ SetHtmlInnerHTML("<textarea cols=50 rows=10>Enter text</textarea>"); // Show handle - LongPressEventBuilder long_press_event(IntPoint(200, 10)); + LongPressEventBuilder long_press_event(FloatPoint(200, 10)); GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent( long_press_event); @@ -656,7 +658,7 @@ ASSERT_TRUE(Selection().IsHandleVisible()); // Tap away from text area should clear handle - TapEventBuilder single_tap_event(IntPoint(200, 350), 1); + TapEventBuilder single_tap_event(FloatPoint(200, 350), 1); GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent( single_tap_event); @@ -709,7 +711,7 @@ SetHtmlInnerHTML("<textarea cols=50 rows=50>Mispellinggg</textarea>"); - TapEventBuilder single_tap_event(IntPoint(10, 10), 1); + TapEventBuilder single_tap_event(FloatPoint(10, 10), 1); GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent( single_tap_event);
diff --git a/third_party/WebKit/Source/core/input/ImeOnFocusTest.cpp b/third_party/WebKit/Source/core/input/ImeOnFocusTest.cpp index f38c5ef..c6063af3 100644 --- a/third_party/WebKit/Source/core/input/ImeOnFocusTest.cpp +++ b/third_party/WebKit/Source/core/input/ImeOnFocusTest.cpp
@@ -66,15 +66,13 @@ }; void ImeOnFocusTest::SendGestureTap(WebView* web_view, IntPoint client_point) { - WebGestureEvent web_gesture_event( - WebInputEvent::kGestureTap, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); + WebGestureEvent web_gesture_event(WebInputEvent::kGestureTap, + WebInputEvent::kNoModifiers, + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); // GestureTap is only ever from touch screens. - web_gesture_event.source_device = kWebGestureDeviceTouchscreen; - web_gesture_event.x = client_point.X(); - web_gesture_event.y = client_point.Y(); - web_gesture_event.global_x = client_point.X(); - web_gesture_event.global_y = client_point.Y(); + web_gesture_event.SetPositionInWidget(FloatPoint(client_point)); + web_gesture_event.SetPositionInScreen(FloatPoint(client_point)); web_gesture_event.data.tap.tap_count = 1; web_gesture_event.data.tap.width = 10; web_gesture_event.data.tap.height = 10;
diff --git a/third_party/WebKit/Source/core/input/OverscrollBehaviorTest.cpp b/third_party/WebKit/Source/core/input/OverscrollBehaviorTest.cpp index dff6f01..5d9a32e6 100644 --- a/third_party/WebKit/Source/core/input/OverscrollBehaviorTest.cpp +++ b/third_party/WebKit/Source/core/input/OverscrollBehaviorTest.cpp
@@ -68,10 +68,10 @@ void OverscrollBehaviorTest::ScrollBegin(double hint_x, double hint_y) { WebGestureEvent event(WebInputEvent::kGestureScrollBegin, WebInputEvent::kNoModifiers, - CurrentTimeTicksInSeconds()); - event.x = event.global_x = 20; - event.y = event.global_y = 20; - event.source_device = WebGestureDevice::kWebGestureDeviceTouchscreen; + CurrentTimeTicksInSeconds(), + WebGestureDevice::kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(WebFloatPoint(20, 20)); + event.SetPositionInScreen(WebFloatPoint(20, 20)); event.data.scroll_begin.delta_x_hint = -hint_x; event.data.scroll_begin.delta_y_hint = -hint_y; event.data.scroll_begin.pointer_count = 1; @@ -82,10 +82,10 @@ void OverscrollBehaviorTest::ScrollUpdate(double delta_x, double delta_y) { WebGestureEvent event(WebInputEvent::kGestureScrollUpdate, WebInputEvent::kNoModifiers, - CurrentTimeTicksInSeconds()); - event.x = event.global_x = 20; - event.y = event.global_y = 20; - event.source_device = WebGestureDevice::kWebGestureDeviceTouchscreen; + CurrentTimeTicksInSeconds(), + WebGestureDevice::kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(WebFloatPoint(20, 20)); + event.SetPositionInScreen(WebFloatPoint(20, 20)); event.data.scroll_update.delta_x = -delta_x; event.data.scroll_update.delta_y = -delta_y; event.SetFrameScale(1); @@ -95,10 +95,10 @@ void OverscrollBehaviorTest::ScrollEnd() { WebGestureEvent event(WebInputEvent::kGestureScrollEnd, WebInputEvent::kNoModifiers, - CurrentTimeTicksInSeconds()); - event.x = event.global_x = 20; - event.y = event.global_y = 20; - event.source_device = WebGestureDevice::kWebGestureDeviceTouchscreen; + CurrentTimeTicksInSeconds(), + WebGestureDevice::kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(WebFloatPoint(20, 20)); + event.SetPositionInScreen(WebFloatPoint(20, 20)); GetDocument().GetFrame()->GetEventHandler().HandleGestureScrollEvent(event); }
diff --git a/third_party/WebKit/Source/core/input/ScrollManager.cpp b/third_party/WebKit/Source/core/input/ScrollManager.cpp index e740118..f3dbe70 100644 --- a/third_party/WebKit/Source/core/input/ScrollManager.cpp +++ b/third_party/WebKit/Source/core/input/ScrollManager.cpp
@@ -346,7 +346,7 @@ WebInputEventResult child_result = PassScrollGestureEvent( gesture_event, scroll_gesture_handling_node_->GetLayoutObject()); - RecordScrollRelatedMetrics(gesture_event.source_device); + RecordScrollRelatedMetrics(gesture_event.SourceDevice()); current_scroll_chain_.clear(); std::unique_ptr<ScrollStateData> scroll_state_data = @@ -359,7 +359,7 @@ scroll_state_data->is_beginning = true; scroll_state_data->from_user_input = true; scroll_state_data->is_direct_manipulation = - gesture_event.source_device == kWebGestureDeviceTouchscreen; + gesture_event.SourceDevice() == kWebGestureDeviceTouchscreen; scroll_state_data->delta_consumed_for_scroll_sequence = delta_consumed_for_scroll_sequence_; ScrollState* scroll_state = ScrollState::Create(std::move(scroll_state_data)); @@ -376,7 +376,7 @@ CustomizedScroll(*scroll_state); - if (gesture_event.source_device == kWebGestureDeviceTouchscreen) + if (gesture_event.SourceDevice() == kWebGestureDeviceTouchscreen) UseCounter::Count(frame_->GetDocument(), WebFeature::kScrollByTouch); else UseCounter::Count(frame_->GetDocument(), WebFeature::kScrollByWheel); @@ -446,7 +446,7 @@ scroll_state_data->is_in_inertial_phase = gesture_event.InertialPhase() == WebGestureEvent::kMomentumPhase; scroll_state_data->is_direct_manipulation = - gesture_event.source_device == kWebGestureDeviceTouchscreen; + gesture_event.SourceDevice() == kWebGestureDeviceTouchscreen; scroll_state_data->from_user_input = true; scroll_state_data->delta_consumed_for_scroll_sequence = delta_consumed_for_scroll_sequence_; @@ -520,7 +520,7 @@ gesture_event.InertialPhase() == WebGestureEvent::kMomentumPhase; scroll_state_data->from_user_input = true; scroll_state_data->is_direct_manipulation = - gesture_event.source_device == kWebGestureDeviceTouchscreen; + gesture_event.SourceDevice() == kWebGestureDeviceTouchscreen; scroll_state_data->delta_consumed_for_scroll_sequence = delta_consumed_for_scroll_sequence_; ScrollState* scroll_state = @@ -662,7 +662,7 @@ bool ScrollManager::HandleScrollGestureOnResizer( Node* event_target, const WebGestureEvent& gesture_event) { - if (gesture_event.source_device != kWebGestureDeviceTouchscreen) + if (gesture_event.SourceDevice() != kWebGestureDeviceTouchscreen) return false; if (gesture_event.GetType() == WebInputEvent::kGestureScrollBegin) {
diff --git a/third_party/WebKit/Source/core/input/ScrollSnapTest.cpp b/third_party/WebKit/Source/core/input/ScrollSnapTest.cpp index 163619a8..c3da4bf 100644 --- a/third_party/WebKit/Source/core/input/ScrollSnapTest.cpp +++ b/third_party/WebKit/Source/core/input/ScrollSnapTest.cpp
@@ -86,10 +86,10 @@ double hint_y) { WebGestureEvent event(WebInputEvent::kGestureScrollBegin, WebInputEvent::kNoModifiers, - CurrentTimeTicksInSeconds()); - event.x = event.global_x = x; - event.y = event.global_y = y; - event.source_device = WebGestureDevice::kWebGestureDeviceTouchscreen; + CurrentTimeTicksInSeconds(), + WebGestureDevice::kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(WebFloatPoint(x, y)); + event.SetPositionInScreen(WebFloatPoint(x, y)); event.data.scroll_begin.delta_x_hint = hint_x; event.data.scroll_begin.delta_y_hint = hint_y; event.data.scroll_begin.pointer_count = 1; @@ -103,10 +103,10 @@ double delta_y) { WebGestureEvent event(WebInputEvent::kGestureScrollUpdate, WebInputEvent::kNoModifiers, - CurrentTimeTicksInSeconds()); - event.x = event.global_x = x; - event.y = event.global_y = y; - event.source_device = WebGestureDevice::kWebGestureDeviceTouchscreen; + CurrentTimeTicksInSeconds(), + WebGestureDevice::kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(WebFloatPoint(x, y)); + event.SetPositionInScreen(WebFloatPoint(x, y)); event.data.scroll_update.delta_x = delta_x; event.data.scroll_update.delta_y = delta_y; event.SetFrameScale(1); @@ -116,10 +116,10 @@ void ScrollSnapTest::ScrollEnd(double x, double y) { WebGestureEvent event(WebInputEvent::kGestureScrollEnd, WebInputEvent::kNoModifiers, - CurrentTimeTicksInSeconds()); - event.x = event.global_x = x; - event.y = event.global_y = y; - event.source_device = WebGestureDevice::kWebGestureDeviceTouchscreen; + CurrentTimeTicksInSeconds(), + WebGestureDevice::kWebGestureDeviceTouchscreen); + event.SetPositionInWidget(WebFloatPoint(x, y)); + event.SetPositionInScreen(WebFloatPoint(x, y)); GetDocument().GetFrame()->GetEventHandler().HandleGestureScrollEvent(event); }
diff --git a/third_party/WebKit/Source/core/inspector/InspectorTraceEvents.cpp b/third_party/WebKit/Source/core/inspector/InspectorTraceEvents.cpp index 2e105554..51f2345 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorTraceEvents.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorTraceEvents.cpp
@@ -1285,12 +1285,13 @@ return value; } -std::unique_ptr<TracedValue> InspectorSetLayerTreeId::Data( - const String& session_id, - int layer_tree_id) { +std::unique_ptr<TracedValue> InspectorSetLayerTreeId::Data(LocalFrame* frame) { std::unique_ptr<TracedValue> value = TracedValue::Create(); - value->SetString("sessionId", session_id); - value->SetInteger("layerTreeId", layer_tree_id); + value->SetString("frame", IdentifiersFactory::FrameId(frame)); + WebLayerTreeView* layerTreeView = + frame->GetPage()->GetChromeClient().GetWebLayerTreeView(frame); + value->SetInteger("layerTreeId", + layerTreeView ? layerTreeView->LayerTreeId() : 0); return value; }
diff --git a/third_party/WebKit/Source/core/inspector/InspectorTraceEvents.h b/third_party/WebKit/Source/core/inspector/InspectorTraceEvents.h index 1a8d5a3..4108dfa 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorTraceEvents.h +++ b/third_party/WebKit/Source/core/inspector/InspectorTraceEvents.h
@@ -458,7 +458,7 @@ } namespace InspectorSetLayerTreeId { -std::unique_ptr<TracedValue> Data(const String& session_id, int layer_tree_id); +std::unique_ptr<TracedValue> Data(LocalFrame* local_root); } namespace InspectorAnimationEvent {
diff --git a/third_party/WebKit/Source/core/inspector/InspectorTracingAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorTracingAgent.cpp index 7f4e4598..dbdb82a 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorTracingAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorTracingAgent.cpp
@@ -13,6 +13,7 @@ #include "core/loader/FrameLoader.h" #include "core/workers/WorkerInspectorProxy.h" #include "platform/instrumentation/tracing/TraceEvent.h" +#include "public/platform/WebLayerTreeView.h" namespace blink { @@ -30,9 +31,7 @@ InspectorTracingAgent::InspectorTracingAgent(Client* client, InspectedFrames* inspected_frames) - : layer_tree_id_(0), - client_(client), - inspected_frames_(inspected_frames) {} + : client_(client), inspected_frames_(inspected_frames) {} InspectorTracingAgent::~InspectorTracingAgent() {} @@ -106,8 +105,6 @@ TRACE_EVENT_SCOPE_THREAD, "data", InspectorTracingStartedInFrame::Data( session_id_, inspected_frames_->Root())); - if (layer_tree_id_) - SetLayerTreeId(layer_tree_id_); for (WorkerInspectorProxy* proxy : WorkerInspectorProxy::AllProxies()) { // For now we assume this is document. TODO(kinuko): Fix this. DCHECK(proxy->GetExecutionContext()->IsDocument()); @@ -128,14 +125,6 @@ session_id_, worker_thread)); } -void InspectorTracingAgent::SetLayerTreeId(int layer_tree_id) { - layer_tree_id_ = layer_tree_id; - TRACE_EVENT_INSTANT1( - kDevtoolsMetadataEventCategory, "SetLayerTreeId", - TRACE_EVENT_SCOPE_THREAD, "data", - InspectorSetLayerTreeId::Data(session_id_, layer_tree_id_)); -} - void InspectorTracingAgent::RootLayerCleared() { if (IsStarted()) client_->HideReloadingBlanket();
diff --git a/third_party/WebKit/Source/core/inspector/InspectorTracingAgent.h b/third_party/WebKit/Source/core/inspector/InspectorTracingAgent.h index bcf51398..c01fc32d 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorTracingAgent.h +++ b/third_party/WebKit/Source/core/inspector/InspectorTracingAgent.h
@@ -56,7 +56,6 @@ void end(std::unique_ptr<EndCallback>) override; // Methods for other agents to use. - void SetLayerTreeId(int); void RootLayerCleared(); private: @@ -65,7 +64,6 @@ bool IsStarted() const; void WriteTimelineStartedEventForWorker(WorkerThread*); - int layer_tree_id_; Client* client_; String session_id_; Member<InspectedFrames> inspected_frames_;
diff --git a/third_party/WebKit/Source/core/layout/ScrollbarsTest.cpp b/third_party/WebKit/Source/core/layout/ScrollbarsTest.cpp index b7ed309..d34b364a 100644 --- a/third_party/WebKit/Source/core/layout/ScrollbarsTest.cpp +++ b/third_party/WebKit/Source/core/layout/ScrollbarsTest.cpp
@@ -440,13 +440,15 @@ ScrollableArea* scrollable_area = ToLayoutBox(scrollable->GetLayoutObject())->GetScrollableArea(); DCHECK(scrollable_area->VerticalScrollbar()); - WebGestureEvent scroll_begin(WebInputEvent::kGestureScrollBegin, - WebInputEvent::kNoModifiers, - CurrentTimeTicksInSeconds()); - scroll_begin.x = scroll_begin.global_x = - scrollable->OffsetLeft() + scrollable->OffsetWidth() - 2; - scroll_begin.y = scroll_begin.global_y = scrollable->OffsetTop(); - scroll_begin.source_device = kWebGestureDeviceTouchpad; + WebGestureEvent scroll_begin( + WebInputEvent::kGestureScrollBegin, WebInputEvent::kNoModifiers, + CurrentTimeTicksInSeconds(), kWebGestureDeviceTouchpad); + scroll_begin.SetPositionInWidget( + WebFloatPoint(scrollable->OffsetLeft() + scrollable->OffsetWidth() - 2, + scrollable->OffsetTop())); + scroll_begin.SetPositionInScreen( + WebFloatPoint(scrollable->OffsetLeft() + scrollable->OffsetWidth() - 2, + scrollable->OffsetTop())); scroll_begin.data.scroll_begin.delta_x_hint = 0; scroll_begin.data.scroll_begin.delta_y_hint = 10; scroll_begin.SetFrameScale(1);
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_break_token.cc b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_break_token.cc index f5bfb21..878835c5 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_break_token.cc +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_break_token.cc
@@ -13,13 +13,13 @@ const ComputedStyle* style, unsigned item_index, unsigned text_offset, - bool is_forced_break, + unsigned flags, // NGInlineBreakTokenFlags std::unique_ptr<const NGInlineLayoutStateStack> state_stack) : NGBreakToken(kInlineBreakToken, kUnfinished, node), style_(style), item_index_(item_index), text_offset_(text_offset), - is_forced_break_(is_forced_break), + flags_(flags), ignore_floats_(false), state_stack_(std::move(state_stack)) {} @@ -27,7 +27,7 @@ : NGBreakToken(kInlineBreakToken, kFinished, node), item_index_(0), text_offset_(0), - is_forced_break_(false), + flags_(kDefault), ignore_floats_(false), state_stack_(nullptr) {}
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_break_token.h b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_break_token.h index e513a01..56416ff 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_break_token.h +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_break_token.h
@@ -15,6 +15,13 @@ // Represents a break token for an inline node. class CORE_EXPORT NGInlineBreakToken : public NGBreakToken { public: + enum NGInlineBreakTokenFlags { + kDefault = 0, + kIsForcedBreak = 1 << 0, + kUseFirstLineStyle = 1 << 1 + // When adding values, ensure |flags_| has enough storage. + }; + // Creates a break token for a node which did fragment, and can potentially // produce more fragments. // Takes ownership of the state_stack. @@ -23,11 +30,10 @@ const ComputedStyle* style, unsigned item_index, unsigned text_offset, - bool is_forced_break, + unsigned flags, // NGInlineBreakTokenFlags std::unique_ptr<const NGInlineLayoutStateStack> state_stack) { - return base::AdoptRef(new NGInlineBreakToken(node, style, item_index, - text_offset, is_forced_break, - std::move(state_stack))); + return base::AdoptRef(new NGInlineBreakToken( + node, style, item_index, text_offset, flags, std::move(state_stack))); } // Creates a break token for a node which cannot produce any more fragments. @@ -54,9 +60,14 @@ return text_offset_; } + bool UseFirstLineStyle() const { + DCHECK(!IsFinished()); + return flags_ & kUseFirstLineStyle; + } + bool IsForcedBreak() const { DCHECK(!IsFinished()); - return is_forced_break_; + return flags_ & kIsForcedBreak; } const NGInlineLayoutStateStack& StateStack() const { @@ -82,7 +93,7 @@ const ComputedStyle*, unsigned item_index, unsigned text_offset, - bool is_forced_break, + unsigned flags, // NGInlineBreakTokenFlags std::unique_ptr<const NGInlineLayoutStateStack>); explicit NGInlineBreakToken(NGLayoutInputNode node); @@ -90,7 +101,7 @@ scoped_refptr<const ComputedStyle> style_; unsigned item_index_; unsigned text_offset_; - unsigned is_forced_break_ : 1; + unsigned flags_ : 2; // NGInlineBreakTokenFlags unsigned ignore_floats_ : 1; std::unique_ptr<const NGInlineLayoutStateStack> state_stack_;
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_items_builder.cc b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_items_builder.cc index 203143dd..596a492 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_items_builder.cc +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_items_builder.cc
@@ -156,23 +156,23 @@ last_auto_wrap_ = auto_wrap_; EWhiteSpace whitespace = style->WhiteSpace(); auto_wrap_ = ComputedStyle::AutoWrap(whitespace); + bool is_svg_text = layout_object && layout_object->IsSVGInlineText(); if (!ComputedStyle::CollapseWhiteSpace(whitespace)) - AppendWithoutWhiteSpaceCollapsing(string, style, layout_object); - else if (ComputedStyle::PreserveNewline(whitespace) && !is_svgtext_) - AppendWithPreservingNewlines(string, style, layout_object); + AppendPreserveWhitespace(string, style, layout_object); + else if (ComputedStyle::PreserveNewline(whitespace) && !is_svg_text) + AppendPreserveNewline(string, style, layout_object); else - AppendWithWhiteSpaceCollapsing(string, 0, string.length(), style, - layout_object); + AppendCollapseWhitespace(string, 0, string.length(), style, layout_object); } template <typename OffsetMappingBuilder> -void NGInlineItemsBuilderTemplate<OffsetMappingBuilder>:: - AppendWithWhiteSpaceCollapsing(const String& string, - unsigned start, - unsigned end, - const ComputedStyle* style, - LayoutText* layout_object) { +void NGInlineItemsBuilderTemplate< + OffsetMappingBuilder>::AppendCollapseWhitespace(const String& string, + unsigned start, + unsigned end, + const ComputedStyle* style, + LayoutText* layout_object) { DCHECK_GT(end, start); // Collapsed spaces are "zero advance width, invisible, but retains its soft @@ -193,7 +193,7 @@ if (c == kNewlineCharacter) { // LayoutBR does not set preserve_newline, but should be preserved. if (!i && end == 1 && layout_object && layout_object->IsBR()) { - AppendForcedBreak(style, layout_object); + AppendForcedBreakCollapseWhitespace(style, layout_object); return; } @@ -245,17 +245,17 @@ // Even when without whitespace collapsing, control characters (newlines and // tabs) are in their own control items to make the line breaker easier. template <typename OffsetMappingBuilder> -void NGInlineItemsBuilderTemplate<OffsetMappingBuilder>:: - AppendWithoutWhiteSpaceCollapsing(const String& string, - const ComputedStyle* style, - LayoutText* layout_object) { +void NGInlineItemsBuilderTemplate< + OffsetMappingBuilder>::AppendPreserveWhitespace(const String& string, + const ComputedStyle* style, + LayoutText* layout_object) { for (unsigned start = 0; start < string.length();) { UChar c = string[start]; if (IsControlItemCharacter(c)) { if (c != kNewlineCharacter) Append(NGInlineItem::kControl, c, style, layout_object); else - AppendForcedBreakWithoutWhiteSpaceCollapsing(style, layout_object); + AppendForcedBreak(style, layout_object); start++; continue; } @@ -277,13 +277,13 @@ } template <typename OffsetMappingBuilder> -void NGInlineItemsBuilderTemplate<OffsetMappingBuilder>:: - AppendWithPreservingNewlines(const String& string, - const ComputedStyle* style, - LayoutText* layout_object) { +void NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::AppendPreserveNewline( + const String& string, + const ComputedStyle* style, + LayoutText* layout_object) { for (unsigned start = 0; start < string.length();) { if (string[start] == kNewlineCharacter) { - AppendForcedBreak(style, layout_object); + AppendForcedBreakCollapseWhitespace(style, layout_object); start++; continue; } @@ -291,15 +291,15 @@ size_t end = string.find(kNewlineCharacter, start + 1); if (end == kNotFound) end = string.length(); - AppendWithWhiteSpaceCollapsing(string, start, end, style, layout_object); + AppendCollapseWhitespace(string, start, end, style, layout_object); start = end; } } template <typename OffsetMappingBuilder> -void NGInlineItemsBuilderTemplate<OffsetMappingBuilder>:: - AppendForcedBreakWithoutWhiteSpaceCollapsing(const ComputedStyle* style, - LayoutObject* layout_object) { +void NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::AppendForcedBreak( + const ComputedStyle* style, + LayoutObject* layout_object) { // At the forced break, add bidi controls to pop all contexts. // https://drafts.csswg.org/css-writing-modes-3/#bidi-embedding-breaks if (!bidi_context_.IsEmpty()) { @@ -321,13 +321,13 @@ } template <typename OffsetMappingBuilder> -void NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::AppendForcedBreak( - const ComputedStyle* style, - LayoutObject* layout_object) { +void NGInlineItemsBuilderTemplate<OffsetMappingBuilder>:: + AppendForcedBreakCollapseWhitespace(const ComputedStyle* style, + LayoutObject* layout_object) { // Remove collapsible spaces immediately before a preserved newline. RemoveTrailingCollapsibleSpaceIfExists(); - AppendForcedBreakWithoutWhiteSpaceCollapsing(style, layout_object); + AppendForcedBreak(style, layout_object); // Remove collapsible spaces immediately after a preserved newline. last_collapsible_space_ = CollapsibleSpace::kSpace; @@ -432,8 +432,9 @@ return; } - // AppendForcedBreak sets CollapsibleSpace::kSpace to ignore leading - // spaces. In this case, the trailing collapsible space does not exist. + // AppendForcedBreakCollapseWhitespace sets CollapsibleSpace::kSpace to + // ignore leading spaces. In this case, the trailing collapsible space does + // not exist. if (ch == kNewlineCharacter) return; }
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_items_builder.h b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_items_builder.h index 67e5ad0..fa00c2b5 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_items_builder.h +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_items_builder.h
@@ -47,8 +47,6 @@ String ToString(); - void SetIsSVGText(bool value) { is_svgtext_ = value; } - // Returns whether the items contain any Bidi controls. bool HasBidiControls() const { return has_bidi_controls_; } @@ -125,7 +123,6 @@ CollapsibleSpace last_collapsible_space_ = CollapsibleSpace::kSpace; bool auto_wrap_ = true; bool last_auto_wrap_ = false; - bool is_svgtext_ = false; bool has_bidi_controls_ = false; bool is_empty_inline_ = true; @@ -140,21 +137,18 @@ const ComputedStyle*, LayoutObject*); - void AppendWithWhiteSpaceCollapsing(const String&, - unsigned start, - unsigned end, - const ComputedStyle*, - LayoutText*); - void AppendWithoutWhiteSpaceCollapsing(const String&, - const ComputedStyle*, - LayoutText*); - void AppendWithPreservingNewlines(const String&, - const ComputedStyle*, - LayoutText*); + void AppendCollapseWhitespace(const String&, + unsigned start, + unsigned end, + const ComputedStyle*, + LayoutText*); + void AppendPreserveWhitespace(const String&, + const ComputedStyle*, + LayoutText*); + void AppendPreserveNewline(const String&, const ComputedStyle*, LayoutText*); + void AppendForcedBreakCollapseWhitespace(const ComputedStyle*, LayoutObject*); void AppendForcedBreak(const ComputedStyle*, LayoutObject*); - void AppendForcedBreakWithoutWhiteSpaceCollapsing(const ComputedStyle*, - LayoutObject*); void RemoveTrailingCollapsibleSpaceIfExists(); void RemoveTrailingCollapsibleSpace(unsigned);
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_layout_algorithm.cc b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_layout_algorithm.cc index dfca84b..8e4fdd52 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_layout_algorithm.cc +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_layout_algorithm.cc
@@ -88,6 +88,64 @@ baseline_type_ = FontBaseline::kIdeographicBaseline; } +NGInlineBoxState* NGInlineLayoutAlgorithm::HandleOpenTag( + const NGInlineItem& item, + const NGInlineItemResult& item_result) { + NGInlineBoxState* box = box_states_->OnOpenTag(item, item_result, line_box_); + // Compute text metrics for all inline boxes since even empty inlines + // influence the line height, except when quirks mode and the box is empty + // for the purpose of empty block calculation. + // https://drafts.csswg.org/css2/visudet.html#line-height + if (!quirks_mode_ || !item.IsEmptyItem()) + box->ComputeTextMetrics(*item.Style(), baseline_type_); + if (item.ShouldCreateBoxFragment()) + box->SetNeedsBoxFragment(); + return box; +} + +// Prepare NGInlineLayoutStateStack for a new line. +void NGInlineLayoutAlgorithm::PrepareBoxStates( + const NGLineInfo& line_info, + const NGInlineBreakToken* break_token) { + // Copy the state stack from the unfinished break token if provided. This + // enforces the layout inputs immutability constraint. + if (break_token && !break_token->UseFirstLineStyle()) { + box_states_ = + std::make_unique<NGInlineLayoutStateStack>(break_token->StateStack()); + return; + } + + // If we weren't provided with a break token we just create an empty state + // stack. + box_states_ = std::make_unique<NGInlineLayoutStateStack>(); + + // If the previous line uses first-line style, rebuild the box state stack + // because styles and metrics may be different. + if (!break_token) + return; + DCHECK(break_token->UseFirstLineStyle()); + + // Compute which tags are not closed at the beginning of this line. + const Vector<NGInlineItem>& items = Node().Items(); + Vector<const NGInlineItem*, 16> open_items; + for (unsigned i = 0; i < break_token->ItemIndex(); i++) { + const NGInlineItem& item = items[i]; + if (item.Type() == NGInlineItem::kOpenTag) + open_items.push_back(&item); + else if (item.Type() == NGInlineItem::kCloseTag) + open_items.pop_back(); + } + + // Create box states for tags that are not closed yet. + box_states_->OnBeginPlaceItems(&line_info.LineStyle(), baseline_type_, + quirks_mode_); + for (const NGInlineItem* item : open_items) { + NGInlineItemResult item_result; + NGLineBreaker::ComputeOpenTagResult(*item, ConstraintSpace(), &item_result); + HandleOpenTag(*item, item_result); + } +} + void NGInlineLayoutAlgorithm::CreateLine(NGLineInfo* line_info, NGExclusionSpace* exclusion_space) { NGInlineItemResults* line_items = &line_info->Results(); @@ -139,15 +197,7 @@ } else if (item.Type() == NGInlineItem::kControl) { PlaceControlItem(item, &item_result, box); } else if (item.Type() == NGInlineItem::kOpenTag) { - box = box_states_->OnOpenTag(item, item_result, line_box_); - // Compute text metrics for all inline boxes since even empty inlines - // influence the line height, except when quirks mode and the box is empty - // for the purpose of empty block calculation. - // https://drafts.csswg.org/css2/visudet.html#line-height - if (!(item.IsEmptyItem() && quirks_mode_)) - box->ComputeTextMetrics(*item.Style(), baseline_type_); - if (item.ShouldCreateBoxFragment()) - box->SetNeedsBoxFragment(); + box = HandleOpenTag(item, item_result); } else if (item.Type() == NGInlineItem::kCloseTag) { if (!box->needs_box_fragment && item_result.inline_size) box->SetNeedsBoxFragment(); @@ -532,13 +582,6 @@ NGInlineBreakToken* break_token = BreakToken(); for (const auto& opportunity : opportunities) { - // Copy the state stack from the unfinished break token if provided. This - // enforces the layout inputs immutability constraint. If we weren't - // provided with a break token we just create an empty state stack. - box_states_ = break_token ? std::make_unique<NGInlineLayoutStateStack>( - break_token->StateStack()) - : std::make_unique<NGInlineLayoutStateStack>(); - // Reset any state that may have been modified in a previous pass. positioned_floats.clear(); unpositioned_floats_.clear(); @@ -565,6 +608,7 @@ ConstraintSpace().AvailableSize().inline_size) continue; + PrepareBoxStates(line_info, break_token); CreateLine(&line_info, exclusion_space.get()); // We now can check the block-size of the fragment, and it fits within the @@ -582,7 +626,7 @@ // Success! positioned_floats_.AppendVector(positioned_floats); container_builder_.SetBreakToken( - line_breaker.CreateBreakToken(std::move(box_states_))); + line_breaker.CreateBreakToken(line_info, std::move(box_states_))); // Place any remaining floats which couldn't fit on the line. PositionPendingFloats(line_height, exclusion_space.get());
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_layout_algorithm.h b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_layout_algorithm.h index 903db4f..3de1428 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_layout_algorithm.h +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_layout_algorithm.h
@@ -51,6 +51,11 @@ bool IsHorizontalWritingMode() const { return is_horizontal_writing_mode_; } + void PrepareBoxStates(const NGLineInfo&, const NGInlineBreakToken*); + + NGInlineBoxState* HandleOpenTag(const NGInlineItem&, + const NGInlineItemResult&); + void BidiReorder(); void PlaceControlItem(const NGInlineItem&,
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_node.cc b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_node.cc index a8e915d..e6c990c 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_node.cc +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_node.cc
@@ -76,9 +76,7 @@ if (UNLIKELY(layout_text->IsWordBreak())) { builder->AppendBreakOpportunity(node->Style(), layout_text); } else { - builder->SetIsSVGText(node->IsSVGInlineText()); - const String& text = layout_text->GetText(); - builder->Append(text, node->Style(), layout_text); + builder->Append(layout_text->GetText(), node->Style(), layout_text); } ClearNeedsLayoutIfUpdatingLayout<OffsetMappingBuilder>(layout_text); @@ -470,7 +468,7 @@ if (!line_breaker.NextLine(opportunity, &line_info)) break; - break_token = line_breaker.CreateBreakToken(nullptr); + break_token = line_breaker.CreateBreakToken(line_info, nullptr); LayoutUnit inline_size = line_info.TextIndent(); for (const NGInlineItemResult item_result : line_info.Results()) inline_size += item_result.inline_size;
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_line_breaker.cc b/third_party/WebKit/Source/core/layout/ng/inline/ng_line_breaker.cc index 6a13aef..34f300e 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_line_breaker.cc +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_line_breaker.cc
@@ -689,39 +689,53 @@ } } -void NGLineBreaker::HandleOpenTag(const NGInlineItem& item, - NGInlineItemResult* item_result) { - DCHECK(!item_result->can_break_after); - +bool NGLineBreaker::ComputeOpenTagResult( + const NGInlineItem& item, + const NGConstraintSpace& constraint_space, + NGInlineItemResult* item_result) { + DCHECK_EQ(item.Type(), NGInlineItem::kOpenTag); DCHECK(item.Style()); const ComputedStyle& style = *item.Style(); item_result->has_edge = item.HasStartEdge(); if (item.ShouldCreateBoxFragment() && (style.HasBorder() || style.HasPadding() || (style.HasMargin() && item_result->has_edge))) { - NGBoxStrut borders = ComputeBorders(constraint_space_, style); - NGBoxStrut paddings = ComputePadding(constraint_space_, style); + NGBoxStrut borders = ComputeBorders(constraint_space, style); + NGBoxStrut paddings = ComputePadding(constraint_space, style); item_result->padding = paddings; item_result->borders_paddings_block_start = borders.block_start + paddings.block_start; item_result->borders_paddings_block_end = borders.block_end + paddings.block_end; if (item_result->has_edge) { - item_result->margins = ComputeMarginsForSelf(constraint_space_, style); + item_result->margins = ComputeMarginsForSelf(constraint_space, style); item_result->inline_size = item_result->margins.inline_start + borders.inline_start + paddings.inline_start; - line_.position += item_result->inline_size; - - // While the spec defines "non-zero margins, padding, or borders" prevents - // line boxes to be zero-height, tests indicate that only inline direction - // of them do so. See should_create_line_box_. - // Force to create a box, because such inline boxes affect line heights. - if (!line_.should_create_line_box && - (item_result->inline_size || - (item_result->margins.inline_start && !in_line_height_quirks_mode_))) - line_.should_create_line_box = true; + return true; } } + return false; +} + +void NGLineBreaker::HandleOpenTag(const NGInlineItem& item, + NGInlineItemResult* item_result) { + DCHECK(!item_result->can_break_after); + + if (ComputeOpenTagResult(item, constraint_space_, item_result)) { + line_.position += item_result->inline_size; + + // While the spec defines "non-zero margins, padding, or borders" prevents + // line boxes to be zero-height, tests indicate that only inline direction + // of them do so. See should_create_line_box_. + // Force to create a box, because such inline boxes affect line heights. + if (!line_.should_create_line_box && + (item_result->inline_size || + (item_result->margins.inline_start && !in_line_height_quirks_mode_))) + line_.should_create_line_box = true; + } + + DCHECK(item.Style()); + const ComputedStyle& style = *item.Style(); SetCurrentStyle(style); MoveToNextOf(item); } @@ -1026,13 +1040,17 @@ } scoped_refptr<NGInlineBreakToken> NGLineBreaker::CreateBreakToken( + const NGLineInfo& line_info, std::unique_ptr<const NGInlineLayoutStateStack> state_stack) const { const Vector<NGInlineItem>& items = node_.Items(); if (item_index_ >= items.size()) return NGInlineBreakToken::Create(node_); - return NGInlineBreakToken::Create(node_, current_style_.get(), item_index_, - offset_, line_.is_after_forced_break, - std::move(state_stack)); + return NGInlineBreakToken::Create( + node_, current_style_.get(), item_index_, offset_, + ((line_.is_after_forced_break ? NGInlineBreakToken::kIsForcedBreak : 0) | + (line_info.UseFirstLineStyle() ? NGInlineBreakToken::kUseFirstLineStyle + : 0)), + std::move(state_stack)); } } // namespace blink
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_line_breaker.h b/third_party/WebKit/Source/core/layout/ng/inline/ng_line_breaker.h index 29b3aaf..4ff2677 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_line_breaker.h +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_line_breaker.h
@@ -49,8 +49,15 @@ // Create an NGInlineBreakToken for the last line returned by NextLine(). scoped_refptr<NGInlineBreakToken> CreateBreakToken( + const NGLineInfo&, std::unique_ptr<const NGInlineLayoutStateStack>) const; + // Compute NGInlineItemResult for an open tag item. + // Returns true if this item has edge and may have non-zero inline size. + static bool ComputeOpenTagResult(const NGInlineItem&, + const NGConstraintSpace&, + NGInlineItemResult*); + private: // This struct holds information for the current line. struct LineData {
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_line_breaker_test.cc b/third_party/WebKit/Source/core/layout/ng/inline/ng_line_breaker_test.cc index 6f669fbb..7266e631 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_line_breaker_test.cc +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_line_breaker_test.cc
@@ -57,7 +57,7 @@ if (!line_breaker.NextLine(opportunity, &line_info)) break; - break_token = line_breaker.CreateBreakToken(nullptr); + break_token = line_breaker.CreateBreakToken(line_info, nullptr); lines.push_back(std::move(line_info.Results())); }
diff --git a/third_party/WebKit/Source/core/layout/ng/layout_ng_mixin.cc b/third_party/WebKit/Source/core/layout/ng/layout_ng_mixin.cc index bd7501e..8c34bba 100644 --- a/third_party/WebKit/Source/core/layout/ng/layout_ng_mixin.cc +++ b/third_party/WebKit/Source/core/layout/ng/layout_ng_mixin.cc
@@ -56,6 +56,21 @@ // Add overflow from the last layout cycle. if (Base::ChildrenInline()) { if (const NGPhysicalBoxFragment* physical_fragment = CurrentFragment()) { + bool has_width = + physical_fragment->Style().OverflowX() != EOverflow::kHidden; + bool has_height = + physical_fragment->Style().OverflowY() != EOverflow::kHidden; + if (has_width || has_height) { + for (const auto& child : physical_fragment->Children()) { + NGPhysicalOffsetRect child_rect(child->Offset(), child->Size()); + if (!has_width) + child_rect.size.width = LayoutUnit(); + if (!has_height) + child_rect.size.height = LayoutUnit(); + Base::AddLayoutOverflow(child_rect.ToLayoutRect()); + } + } + // TODO(kojii): If |RecalcOverflowAfterStyleChange()|, we need to // re-compute glyph bounding box. How to detect it and how to re-compute // is TBD.
diff --git a/third_party/WebKit/Source/core/layout/ng/ng_fragment_builder.cc b/third_party/WebKit/Source/core/layout/ng/ng_fragment_builder.cc index d3555ff..b9fda2ff 100644 --- a/third_party/WebKit/Source/core/layout/ng/ng_fragment_builder.cc +++ b/third_party/WebKit/Source/core/layout/ng/ng_fragment_builder.cc
@@ -118,7 +118,7 @@ // formatting context, rather than concluding that we're done with the // whole thing. inline_break_tokens_.push_back(NGInlineBreakToken::Create( - ToNGInlineNode(child), nullptr, 0, 0, false, + ToNGInlineNode(child), nullptr, 0, 0, NGInlineBreakToken::kDefault, std::make_unique<NGInlineLayoutStateStack>())); } return *this;
diff --git a/third_party/WebKit/Source/core/page/scrolling/RootScrollerTest.cpp b/third_party/WebKit/Source/core/page/scrolling/RootScrollerTest.cpp index 998fcf1..caaa732 100644 --- a/third_party/WebKit/Source/core/page/scrolling/RootScrollerTest.cpp +++ b/third_party/WebKit/Source/core/page/scrolling/RootScrollerTest.cpp
@@ -157,10 +157,8 @@ int delta_x, int delta_y) { WebGestureEvent event(type, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - event.source_device = device; - event.x = 100; - event.y = 100; + WebInputEvent::GetStaticTimeStampForTests(), device); + event.SetPositionInWidget(WebFloatPoint(100, 100)); if (type == WebInputEvent::kGestureScrollUpdate) { event.data.scroll_update.delta_x = delta_x; event.data.scroll_update.delta_y = delta_y;
diff --git a/third_party/WebKit/Source/core/page/scrolling/ScrollMetricsTest.cpp b/third_party/WebKit/Source/core/page/scrolling/ScrollMetricsTest.cpp index a70c18fe..45cb20e0 100644 --- a/third_party/WebKit/Source/core/page/scrolling/ScrollMetricsTest.cpp +++ b/third_party/WebKit/Source/core/page/scrolling/ScrollMetricsTest.cpp
@@ -51,15 +51,16 @@ class ScrollBeginEventBuilder : public WebGestureEvent { public: - ScrollBeginEventBuilder(IntPoint position, + ScrollBeginEventBuilder(FloatPoint position, FloatPoint delta, WebGestureDevice device) - : WebGestureEvent() { - type_ = WebInputEvent::kGestureScrollBegin; - x = global_x = position.X(); - y = global_y = position.Y(); + : WebGestureEvent(WebInputEvent::kGestureScrollBegin, + WebInputEvent::kNoModifiers, + CurrentTimeTicksInSeconds(), + device) { + SetPositionInWidget(position); + SetPositionInScreen(position); data.scroll_begin.delta_y_hint = delta.Y(); - source_device = device; frame_scale_ = 1; } }; @@ -101,8 +102,8 @@ DCHECK(element->getBoundingClientRect()); DOMRect* rect = element->getBoundingClientRect(); ScrollBeginEventBuilder scroll_begin( - IntPoint(rect->left() + rect->width() / 2, - rect->top() + rect->height() / 2), + FloatPoint(rect->left() + rect->width() / 2, + rect->top() + rect->height() / 2), FloatPoint(0.f, 1.f), device); ScrollUpdateEventBuilder scroll_update; ScrollEndEventBuilder scroll_end;
diff --git a/third_party/WebKit/Source/core/paint/LinkHighlightImplTest.cpp b/third_party/WebKit/Source/core/paint/LinkHighlightImplTest.cpp index 7159fc2..4c415dc 100644 --- a/third_party/WebKit/Source/core/paint/LinkHighlightImplTest.cpp +++ b/third_party/WebKit/Source/core/paint/LinkHighlightImplTest.cpp
@@ -85,22 +85,21 @@ WebGestureEvent touch_event(WebInputEvent::kGestureShowPress, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - touch_event.source_device = kWebGestureDeviceTouchscreen; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); // The coordinates below are linked to absolute positions in the referenced // .html file. - touch_event.x = 20; - touch_event.y = 20; + touch_event.SetPositionInWidget(WebFloatPoint(20, 20)); ASSERT_TRUE( web_view_impl->BestTapNode(GetTargetedEvent(web_view_impl, touch_event))); - touch_event.y = 40; + touch_event.SetPositionInWidget(WebFloatPoint(20, 40)); EXPECT_FALSE( web_view_impl->BestTapNode(GetTargetedEvent(web_view_impl, touch_event))); - touch_event.y = 20; + touch_event.SetPositionInWidget(WebFloatPoint(20, 20)); // Shouldn't crash. web_view_impl->EnableTapHighlightAtPoint( GetTargetedEvent(web_view_impl, touch_event)); @@ -110,18 +109,19 @@ EXPECT_TRUE(web_view_impl->GetLinkHighlight(0)->ClipLayer()); // Find a target inside a scrollable div - touch_event.y = 100; + touch_event.SetPositionInWidget(WebFloatPoint(20, 100)); web_view_impl->EnableTapHighlightAtPoint( GetTargetedEvent(web_view_impl, touch_event)); ASSERT_TRUE(web_view_impl->GetLinkHighlight(0)); // Don't highlight if no "hand cursor" - touch_event.y = 220; // An A-link with cross-hair cursor. + touch_event.SetPositionInWidget( + WebFloatPoint(20, 220)); // An A-link with cross-hair cursor. web_view_impl->EnableTapHighlightAtPoint( GetTargetedEvent(web_view_impl, touch_event)); ASSERT_EQ(0U, web_view_impl->NumLinkHighlights()); - touch_event.y = 260; // A text input box. + touch_event.SetPositionInWidget(WebFloatPoint(20, 260)); // A text input box. web_view_impl->EnableTapHighlightAtPoint( GetTargetedEvent(web_view_impl, touch_event)); ASSERT_EQ(0U, web_view_impl->NumLinkHighlights()); @@ -143,10 +143,9 @@ WebGestureEvent touch_event(WebInputEvent::kGestureShowPress, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - touch_event.source_device = kWebGestureDeviceTouchscreen; - touch_event.x = 20; - touch_event.y = 20; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); + touch_event.SetPositionInWidget(WebFloatPoint(20, 20)); GestureEventWithHitTestResults targeted_event = GetTargetedEvent(web_view_impl, touch_event); @@ -183,10 +182,9 @@ WebGestureEvent touch_event(WebInputEvent::kGestureShowPress, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - touch_event.source_device = kWebGestureDeviceTouchscreen; - touch_event.x = 20; - touch_event.y = 20; + WebInputEvent::GetStaticTimeStampForTests(), + kWebGestureDeviceTouchscreen); + touch_event.SetPositionInWidget(WebFloatPoint(20, 20)); GestureEventWithHitTestResults targeted_event = GetTargetedEvent(web_view_impl, touch_event); @@ -217,16 +215,16 @@ web_view_impl->UpdateAllLifecyclePhases(); WebGestureEvent touch_event; - touch_event.x = 50; - touch_event.y = 310; + touch_event.SetPositionInWidget(WebFloatPoint(50, 310)); touch_event.data.tap.width = 30; touch_event.data.tap.height = 30; Vector<IntRect> good_targets; HeapVector<Member<Node>> highlight_nodes; - IntRect bounding_box(touch_event.x - touch_event.data.tap.width / 2, - touch_event.y - touch_event.data.tap.height / 2, - touch_event.data.tap.width, touch_event.data.tap.height); + IntRect bounding_box( + touch_event.PositionInWidget().x - touch_event.data.tap.width / 2, + touch_event.PositionInWidget().y - touch_event.data.tap.height / 2, + touch_event.data.tap.width, touch_event.data.tap.height); FindGoodTouchTargets(bounding_box, web_view_impl->MainFrameImpl()->GetFrame(), good_targets, highlight_nodes);
diff --git a/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.cpp b/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.cpp index 1a5d3e00..ea75ee3 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.cpp +++ b/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.cpp
@@ -2181,12 +2181,7 @@ const PaintLayer* layer) { non_composited_main_thread_scrolling_reasons_ = 0; - // The root scroller needs composited scrolling layers even if it doesn't - // actually have scrolling since CC has these assumptions baked in for the - // viewport. If we're in non-RootLayerScrolling mode, the root layer will be - // the global root scroller (by default) but it doesn't actually handle - // scrolls itself so we don't need composited scrolling for it. - if (RootScrollerUtil::IsGlobal(*layer) && !Layer()->IsScrolledByFrameView()) + if (CompositingReasonFinder::RequiresCompositingForRootScroller(*layer)) return true; if (!layer->ScrollsOverflow())
diff --git a/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilder.cpp b/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilder.cpp index 10368cf..a1de7b0 100644 --- a/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilder.cpp +++ b/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilder.cpp
@@ -387,6 +387,19 @@ return ToLayoutBox(object).GetScrollableArea()->ScrollsOverflow(); } +static CompositingReasons CompositingReasonsForScroll(const LayoutBox& box) { + CompositingReasons compositing_reasons = CompositingReason::kNone; + if (auto* scrollable_area = box.GetScrollableArea()) { + if (auto* layer = scrollable_area->Layer()) { + if (CompositingReasonFinder::RequiresCompositingForRootScroller(*layer)) + compositing_reasons |= CompositingReason::kRootScroller; + } + } + // TODO(pdr): Set other compositing reasons for scroll here, see: + // PaintLayerScrollableArea::ComputeNeedsCompositedScrolling. + return compositing_reasons; +} + // True if a scroll translation is needed for static scroll offset (e.g., // overflow hidden with scroll), or if a scroll node is needed for composited // scrolling. @@ -1295,7 +1308,6 @@ auto element_id = scrollable_area->GetCompositorElementId(); - // TODO(pdr): Set the correct compositing reasons here. OnUpdate(properties_->UpdateScroll( context_.current.scroll, container_rect, contents_rect, user_scrollable_horizontal, user_scrollable_vertical, reasons, @@ -1312,10 +1324,11 @@ TransformationMatrix scroll_offset_matrix = TransformationMatrix().Translate(-scroll_offset.Width(), -scroll_offset.Height()); + CompositingReasons compositing_reasons = CompositingReasonsForScroll(box); OnUpdate(properties_->UpdateScrollTranslation( context_.current.transform, scroll_offset_matrix, FloatPoint3D(), context_.current.should_flatten_inherited_transform, - context_.current.rendering_context_id, CompositingReason::kNone, + context_.current.rendering_context_id, compositing_reasons, CompositorElementId(), properties_->Scroll())); } else { OnClear(properties_->ClearScrollTranslation());
diff --git a/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilderTest.cpp b/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilderTest.cpp index c17164c..c6cba59 100644 --- a/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilderTest.cpp +++ b/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilderTest.cpp
@@ -551,7 +551,6 @@ transform_properties->PaintOffsetTranslation()->Parent()); EXPECT_TRUE(transform_properties->Transform()->HasDirectCompositingReasons()); - EXPECT_FALSE(FrameScrollTranslation()->HasDirectCompositingReasons()); CHECK_EXACT_VISUAL_RECT(LayoutRect(173, 556, 400, 300), transform->GetLayoutObject(), @@ -5277,4 +5276,47 @@ } } +TEST_P(PaintPropertyTreeBuilderTest, RootHasCompositedScrolling) { + // TODO(pdr): Set compositing reasons for FrameView scrolling. + if (!RuntimeEnabledFeatures::RootLayerScrollingEnabled()) + return; + + SetBodyInnerHTML(R"HTML( + <div id='forceScroll' style='height: 2000px'></div> + )HTML"); + + // When the root scrolls, there should be direct compositing reasons. + EXPECT_TRUE(FrameScrollTranslation()->HasDirectCompositingReasons()); + + // Remove scrolling from the root. + Element* force_scroll_element = GetDocument().getElementById("forceScroll"); + force_scroll_element->setAttribute(HTMLNames::styleAttr, ""); + GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint(); + // Without scrolling, the root should not have direct compositing reasons or + // even a scroll node. + EXPECT_EQ(nullptr, FrameScrollTranslation()); +} + +TEST_P(PaintPropertyTreeBuilderTest, IframeDoesNotRequireCompositedScrolling) { + // TODO(pdr): Set compositing reasons for FrameView scrolling. + if (!RuntimeEnabledFeatures::RootLayerScrollingEnabled()) + return; + + SetBodyInnerHTML(R"HTML( + <iframe style='width: 200px; height: 200px;'></iframe> + <div id='forceScroll' style='height: 2000px'></div> + )HTML"); + SetChildFrameHTML(R"HTML( + <div id='forceInnerScroll' style='height: 2000px'></div> + )HTML"); + GetDocument().View()->UpdateAllLifecyclePhases(); + + EXPECT_TRUE(FrameScrollTranslation()->HasDirectCompositingReasons()); + + // When the child iframe scrolls, there should not be direct compositing + // reasons because only the root frame needs scrolling compositing reasons. + EXPECT_FALSE(FrameScrollTranslation(ChildDocument().View()) + ->HasDirectCompositingReasons()); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/core/paint/compositing/CompositedLayerMapping.cpp b/third_party/WebKit/Source/core/paint/compositing/CompositedLayerMapping.cpp index 03c6f1c..236768e 100644 --- a/third_party/WebKit/Source/core/paint/compositing/CompositedLayerMapping.cpp +++ b/third_party/WebKit/Source/core/paint/compositing/CompositedLayerMapping.cpp
@@ -3350,6 +3350,7 @@ FloatSize offset_from_anchor_layout_object; const LayoutBoxModelObject* anchor_layout_object; + bool should_apply_anchor_overflow_clip = false; if (graphics_layer == squashing_layer_.get()) { // All squashed layers have the same clip and transform space, so we can use // the first squashed layer's layoutObject to map the squashing layer's @@ -3371,21 +3372,31 @@ graphics_layer == scrolling_contents_layer_.get()); anchor_layout_object = &owning_layer_.GetLayoutObject(); IntSize offset = graphics_layer->OffsetFromLayoutObject(); - AdjustForCompositedScrolling(graphics_layer, offset); + should_apply_anchor_overflow_clip = + AdjustForCompositedScrolling(graphics_layer, offset) && + (RuntimeEnabledFeatures::RootLayerScrollingEnabled() || + !owning_layer_.IsRootLayer()); offset_from_anchor_layout_object = FloatSize(offset); } + + LayoutView* root_view = anchor_layout_object->View(); + while (root_view->GetFrame()->OwnerLayoutObject()) + root_view = root_view->GetFrame()->OwnerLayoutObject()->View(); + // Start with the bounds of the graphics layer in the space of the anchor // LayoutObject. FloatRect graphics_layer_bounds_in_object_space(graphics_layer_bounds); graphics_layer_bounds_in_object_space.Move(offset_from_anchor_layout_object); + if (should_apply_anchor_overflow_clip && anchor_layout_object != root_view) { + FloatRect clip_rect( + ToLayoutBox(anchor_layout_object)->OverflowClipRect(LayoutPoint())); + graphics_layer_bounds_in_object_space.Intersect(clip_rect); + } // Now map the bounds to its visible content rect in root view space, // including applying clips along the way. LayoutRect graphics_layer_bounds_in_root_view_space( graphics_layer_bounds_in_object_space); - LayoutView* root_view = anchor_layout_object->View(); - while (root_view->GetFrame()->OwnerLayoutObject()) - root_view = root_view->GetFrame()->OwnerLayoutObject()->View(); anchor_layout_object->MapToVisualRectInAncestorSpace( root_view, graphics_layer_bounds_in_root_view_space); @@ -3529,7 +3540,7 @@ : owning_layer_.NeedsRepaint(); } -void CompositedLayerMapping::AdjustForCompositedScrolling( +bool CompositedLayerMapping::AdjustForCompositedScrolling( const GraphicsLayer* graphics_layer, IntSize& offset) const { if (graphics_layer == scrolling_contents_layer_.get() || @@ -3543,9 +3554,11 @@ // beginning of flow. ScrollOffset scroll_offset = scrollable_area->GetScrollOffset(); offset.Expand(-scroll_offset.Width(), -scroll_offset.Height()); + return true; } } } + return false; } void CompositedLayerMapping::PaintContents(
diff --git a/third_party/WebKit/Source/core/paint/compositing/CompositedLayerMapping.h b/third_party/WebKit/Source/core/paint/compositing/CompositedLayerMapping.h index 9ef91c24..a0821b85 100644 --- a/third_party/WebKit/Source/core/paint/compositing/CompositedLayerMapping.h +++ b/third_party/WebKit/Source/core/paint/compositing/CompositedLayerMapping.h
@@ -305,7 +305,8 @@ void UpdateScrollingBlockSelection(); - void AdjustForCompositedScrolling(const GraphicsLayer*, + // Returns whether an adjustment happend. + bool AdjustForCompositedScrolling(const GraphicsLayer*, IntSize& offset) const; // Returns true for layers with scrollable overflow which have a background
diff --git a/third_party/WebKit/Source/core/paint/compositing/CompositedLayerMappingTest.cpp b/third_party/WebKit/Source/core/paint/compositing/CompositedLayerMappingTest.cpp index 78b8049..3065ce1 100644 --- a/third_party/WebKit/Source/core/paint/compositing/CompositedLayerMappingTest.cpp +++ b/third_party/WebKit/Source/core/paint/compositing/CompositedLayerMappingTest.cpp
@@ -430,7 +430,9 @@ TEST_P(CompositedLayerMappingTest, ScrollingLayerInterestRect) { SetBodyInnerHTML(R"HTML( - <style>div::-webkit-scrollbar{ width: 5px; }</style> + <style> + div::-webkit-scrollbar{ width: 5px; } + </style> <div id='target' style='width: 200px; height: 200px; will-change: transform; overflow: scroll'> <div style='width: 100px; height: 10000px'></div></div> @@ -442,8 +444,14 @@ ToLayoutBoxModelObject(element->GetLayoutObject())->Layer(); ASSERT_TRUE(paint_layer->GraphicsLayerBacking()); // Offscreen layers are painted as usual. - ASSERT_TRUE(paint_layer->GetCompositedLayerMapping()->ScrollingLayer()); - EXPECT_EQ(IntRect(0, 0, 195, 4592), + ASSERT_TRUE( + paint_layer->GetCompositedLayerMapping()->ScrollingContentsLayer()); + // In screen space, the scroller is (8, 8, 195, 193) (because of overflow clip + // of 'target', scrollbar and root margin). + // Applying the viewport clip of the root has no effect because + // the clip is already small. Mapping it down into the graphics layer + // space yields (0, 0, 195, 193). This is then expanded by 4000px. + EXPECT_EQ(IntRect(0, 0, 195, 4193), RecomputeInterestRect(paint_layer->GraphicsLayerBacking())); } @@ -716,26 +724,26 @@ Element* scroller = GetDocument().getElementById("scroller"); GraphicsLayer* scrolling_layer = scroller->GetLayoutBox()->Layer()->GraphicsLayerBacking(); - EXPECT_EQ(IntRect(0, 0, 400, 4600), PreviousInterestRect(scrolling_layer)); + EXPECT_EQ(IntRect(0, 0, 400, 4400), PreviousInterestRect(scrolling_layer)); scroller->setScrollTop(300); GetDocument().View()->UpdateAllLifecyclePhases(); // Still use the previous interest rect because the recomputed rect hasn't // changed enough. - EXPECT_EQ(IntRect(0, 0, 400, 4900), RecomputeInterestRect(scrolling_layer)); - EXPECT_EQ(IntRect(0, 0, 400, 4600), PreviousInterestRect(scrolling_layer)); + EXPECT_EQ(IntRect(0, 0, 400, 4700), RecomputeInterestRect(scrolling_layer)); + EXPECT_EQ(IntRect(0, 0, 400, 4400), PreviousInterestRect(scrolling_layer)); scroller->setScrollTop(600); GetDocument().View()->UpdateAllLifecyclePhases(); // Use recomputed interest rect because it changed enough. - EXPECT_EQ(IntRect(0, 0, 400, 5200), RecomputeInterestRect(scrolling_layer)); - EXPECT_EQ(IntRect(0, 0, 400, 5200), PreviousInterestRect(scrolling_layer)); + EXPECT_EQ(IntRect(0, 0, 400, 5000), RecomputeInterestRect(scrolling_layer)); + EXPECT_EQ(IntRect(0, 0, 400, 5000), PreviousInterestRect(scrolling_layer)); - scroller->setScrollTop(5400); + scroller->setScrollTop(5600); GetDocument().View()->UpdateAllLifecyclePhases(); - EXPECT_EQ(IntRect(0, 1400, 400, 8600), + EXPECT_EQ(IntRect(0, 1600, 400, 8400), RecomputeInterestRect(scrolling_layer)); - EXPECT_EQ(IntRect(0, 1400, 400, 8600), PreviousInterestRect(scrolling_layer)); + EXPECT_EQ(IntRect(0, 1600, 400, 8400), PreviousInterestRect(scrolling_layer)); scroller->setScrollTop(9000); GetDocument().View()->UpdateAllLifecyclePhases(); @@ -743,13 +751,13 @@ // interest rect. EXPECT_EQ(IntRect(0, 5000, 400, 5000), RecomputeInterestRect(scrolling_layer)); - EXPECT_EQ(IntRect(0, 1400, 400, 8600), PreviousInterestRect(scrolling_layer)); + EXPECT_EQ(IntRect(0, 1600, 400, 8400), PreviousInterestRect(scrolling_layer)); scroller->setScrollTop(2000); // Use recomputed interest rect because it changed enough. GetDocument().View()->UpdateAllLifecyclePhases(); - EXPECT_EQ(IntRect(0, 0, 400, 6600), RecomputeInterestRect(scrolling_layer)); - EXPECT_EQ(IntRect(0, 0, 400, 6600), PreviousInterestRect(scrolling_layer)); + EXPECT_EQ(IntRect(0, 0, 400, 6400), RecomputeInterestRect(scrolling_layer)); + EXPECT_EQ(IntRect(0, 0, 400, 6400), PreviousInterestRect(scrolling_layer)); } TEST_P(CompositedLayerMappingTest, @@ -776,12 +784,10 @@ scroller->setScrollTop(5400); GetDocument().View()->UpdateAllLifecyclePhases(); scroller->setScrollTop(9400); - // The above code creates an interest rect bigger than the interest rect if - // recomputed now. GetDocument().View()->UpdateAllLifecyclePhases(); EXPECT_EQ(IntRect(0, 5400, 400, 4600), RecomputeInterestRect(scrolling_layer)); - EXPECT_EQ(IntRect(0, 1400, 400, 8600), PreviousInterestRect(scrolling_layer)); + EXPECT_EQ(IntRect(0, 5400, 400, 4600), PreviousInterestRect(scrolling_layer)); // Paint invalidation and repaint should change previous paint interest rect. GetDocument().getElementById("content")->setTextContent("Change");
diff --git a/third_party/WebKit/Source/core/paint/compositing/CompositingReasonFinder.cpp b/third_party/WebKit/Source/core/paint/compositing/CompositingReasonFinder.cpp index 6162357..ceb48d3 100644 --- a/third_party/WebKit/Source/core/paint/compositing/CompositingReasonFinder.cpp +++ b/third_party/WebKit/Source/core/paint/compositing/CompositingReasonFinder.cpp
@@ -163,10 +163,7 @@ if (layer->NeedsCompositedScrolling()) direct_reasons |= CompositingReason::kOverflowScrollingTouch; - // When RLS is disabled, the root layer may be the root scroller but - // the FrameView/Compositor handles its scrolling so there's no need to - // composite it. - if (RootScrollerUtil::IsGlobal(*layer) && !layer->IsScrolledByFrameView()) + if (RequiresCompositingForRootScroller(*layer)) direct_reasons |= CompositingReason::kRootScroller; // Composite |layer| if it is inside of an ancestor scrolling layer, but that @@ -233,6 +230,16 @@ : style.HasCurrentTransformAnimation(); } +bool CompositingReasonFinder::RequiresCompositingForRootScroller( + const PaintLayer& layer) { + // The root scroller needs composited scrolling layers even if it doesn't + // actually have scrolling since CC has these assumptions baked in for the + // viewport. If we're in non-RootLayerScrolling mode, the root layer will be + // the global root scroller (by default) but it doesn't actually handle + // scrolls itself so we don't need composited scrolling for it. + return RootScrollerUtil::IsGlobal(layer) && !layer.IsScrolledByFrameView(); +} + bool CompositingReasonFinder::RequiresCompositingForScrollDependentPosition( const PaintLayer* layer, bool ignore_lcd_text) const {
diff --git a/third_party/WebKit/Source/core/paint/compositing/CompositingReasonFinder.h b/third_party/WebKit/Source/core/paint/compositing/CompositingReasonFinder.h index fbecb282..3cf977d 100644 --- a/third_party/WebKit/Source/core/paint/compositing/CompositingReasonFinder.h +++ b/third_party/WebKit/Source/core/paint/compositing/CompositingReasonFinder.h
@@ -43,6 +43,7 @@ const ComputedStyle&); static bool RequiresCompositingForTransformAnimation(const ComputedStyle&); static bool RequiresCompositingForTransform(const LayoutObject&); + static bool RequiresCompositingForRootScroller(const PaintLayer&); bool RequiresCompositingForScrollDependentPosition( const PaintLayer*,
diff --git a/third_party/WebKit/Source/devtools/BUILD.gn b/third_party/WebKit/Source/devtools/BUILD.gn index 859464a2..647cd17 100644 --- a/third_party/WebKit/Source/devtools/BUILD.gn +++ b/third_party/WebKit/Source/devtools/BUILD.gn
@@ -428,6 +428,7 @@ "front_end/network_test_runner/module.json", "front_end/network_test_runner/NetworkTestRunner.js", "front_end/network_test_runner/ProductRegistryTestRunner.js", + "front_end/node_debugger/module.json", "front_end/node_main/NodeConnectionsPanel.js", "front_end/node_main/nodeConnectionsPanel.css", "front_end/node_main/NodeMain.js", @@ -1024,6 +1025,7 @@ "$resources_out_dir/layer_viewer/layer_viewer_module.js", "$resources_out_dir/layers/layers_module.js", "$resources_out_dir/network/network_module.js", + "$resources_out_dir/node_debugger/node_debugger_module.js", "$resources_out_dir/object_ui/object_ui_module.js", "$resources_out_dir/perf_ui/perf_ui_module.js", "$resources_out_dir/profiler/profiler_module.js", @@ -1041,9 +1043,6 @@ "$resources_out_dir/workspace_diff/workspace_diff_module.js", ] -generated_resources = - generated_applications + generated_non_autostart_non_remote_modules - generated_remote_modules = [ "$resources_out_dir/accessibility/accessibility_module.js", "$resources_out_dir/audits2_worker/audits2_worker_module.js", @@ -1118,8 +1117,16 @@ ":devtools_frontend_resources", ] - grd_files = generated_resources + devtools_embedder_scripts + - [ "$resources_out_dir/devtools_extension_api.js" ] + grd_files = + generated_applications + generated_non_autostart_non_remote_modules + + devtools_embedder_scripts + + [ "$resources_out_dir/devtools_extension_api.js" ] + + # Bundle remote modules in ChromeOS. + if (is_chromeos) { + grd_files += generated_remote_modules + } + inputs = grd_files + devtools_image_files outfile = "$root_gen_dir/devtools/devtools_resources.grd" outputs = [ @@ -1202,7 +1209,9 @@ inputs = helper_scripts + all_devtools_files + generated_scripts + application_templates - outputs = generated_resources + generated_remote_modules + outputs = + generated_applications + generated_non_autostart_non_remote_modules + + generated_remote_modules args = devtools_applications + [ "--input_path",
diff --git a/third_party/WebKit/Source/devtools/front_end/animation/animationTimeline.css b/third_party/WebKit/Source/devtools/front_end/animation/animationTimeline.css index 4aedecd..0d38913c 100644 --- a/third_party/WebKit/Source/devtools/front_end/animation/animationTimeline.css +++ b/third_party/WebKit/Source/devtools/front_end/animation/animationTimeline.css
@@ -95,7 +95,8 @@ .animation-timeline-toolbar-container { display: flex; - border-bottom: 1px solid #ccc; + background-color: var(--toolbar-bg-color); + border-bottom: 1px solid #dadada; flex: 0 0; }
diff --git a/third_party/WebKit/Source/devtools/front_end/audits2/audits2Panel.css b/third_party/WebKit/Source/devtools/front_end/audits2/audits2Panel.css index d1f8dbe5..ed7643c 100644 --- a/third_party/WebKit/Source/devtools/front_end/audits2/audits2Panel.css +++ b/third_party/WebKit/Source/devtools/front_end/audits2/audits2Panel.css
@@ -5,7 +5,8 @@ */ .toolbar { - border-bottom: 1px solid #ccc; + background-color: var(--toolbar-bg-color); + border-bottom: 1px solid #dadada; } .audits2-logo {
diff --git a/third_party/WebKit/Source/devtools/front_end/browser_debugger/module.json b/third_party/WebKit/Source/devtools/front_end/browser_debugger/module.json index 2d3189cdb..10f1b3d 100644 --- a/third_party/WebKit/Source/devtools/front_end/browser_debugger/module.json +++ b/third_party/WebKit/Source/devtools/front_end/browser_debugger/module.json
@@ -74,6 +74,15 @@ "hasToolbar": true, "persistence": "permanent", "className": "BrowserDebugger.ObjectEventListenersSidebarPane" + }, + { + "type": "view", + "location": "navigator-view", + "id": "navigator-network", + "title": "Page", + "order": 2, + "persistence": "permanent", + "className": "Sources.NetworkNavigatorView" } ], "dependencies": [
diff --git a/third_party/WebKit/Source/devtools/front_end/console/consoleSidebar.css b/third_party/WebKit/Source/devtools/front_end/console/consoleSidebar.css index 13ef25d..01ad4e19 100644 --- a/third_party/WebKit/Source/devtools/front_end/console/consoleSidebar.css +++ b/third_party/WebKit/Source/devtools/front_end/console/consoleSidebar.css
@@ -6,6 +6,7 @@ :host { overflow: auto; + background-color: var(--toolbar-bg-color); } .tree-outline-disclosure {
diff --git a/third_party/WebKit/Source/devtools/front_end/console/consoleView.css b/third_party/WebKit/Source/devtools/front_end/console/consoleView.css index 98567435..1c66361 100644 --- a/third_party/WebKit/Source/devtools/front_end/console/consoleView.css +++ b/third_party/WebKit/Source/devtools/front_end/console/consoleView.css
@@ -33,6 +33,7 @@ } .console-view > .toolbar { + background-color: var(--toolbar-bg-color); border-bottom: 1px solid #dadada; }
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/stylesSidebarPane.css b/third_party/WebKit/Source/devtools/front_end/elements/stylesSidebarPane.css index 3112fc0..b914bf0 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/stylesSidebarPane.css +++ b/third_party/WebKit/Source/devtools/front_end/elements/stylesSidebarPane.css
@@ -150,7 +150,7 @@ overflow: hidden; position: sticky; top: 0; - background-color: #fff; + background-color: var(--toolbar-bg-color); z-index: 1; } @@ -168,8 +168,17 @@ outline: none !important; border: none; width: 100%; - background: transparent; - margin-left: 4px; + background: white; + padding-left: 4px; + margin: 3px; +} + +.styles-sidebar-pane-filter-box > input:hover { + box-shadow: 0 0 0 1px #e0e0e0; +} + +.styles-sidebar-pane-filter-box > input:focus { + box-shadow: 0 0 0 1px #61b8ff; } .styles-section.styles-panel-hovered:not(.read-only) span.simple-selector:hover,
diff --git a/third_party/WebKit/Source/devtools/front_end/layer_viewer/layers3DView.css b/third_party/WebKit/Source/devtools/front_end/layer_viewer/layers3DView.css index f57dd510..063e359 100644 --- a/third_party/WebKit/Source/devtools/front_end/layer_viewer/layers3DView.css +++ b/third_party/WebKit/Source/devtools/front_end/layer_viewer/layers3DView.css
@@ -9,6 +9,11 @@ -webkit-user-select: none; } +.toolbar { + background-color: var(--toolbar-bg-color); + border-bottom: 1px solid #dadada; +} + canvas { flex: 1 1; }
diff --git a/third_party/WebKit/Source/devtools/front_end/network/NetworkPanel.js b/third_party/WebKit/Source/devtools/front_end/network/NetworkPanel.js index 5c03be4b..8d0a3e4 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/NetworkPanel.js +++ b/third_party/WebKit/Source/devtools/front_end/network/NetworkPanel.js
@@ -91,6 +91,7 @@ this._closeButtonElement = createElement('div', 'dt-close-button'); this._closeButtonElement.addEventListener('click', this._showRequest.bind(this, null), false); + this._closeButtonElement.style.margin = '0 5px'; this._networkLogShowOverviewSetting.addChangeListener(this._toggleShowOverview, this); this._networkLogLargeRowsSetting.addChangeListener(this._toggleLargerRequests, this);
diff --git a/third_party/WebKit/Source/devtools/front_end/network/networkPanel.css b/third_party/WebKit/Source/devtools/front_end/network/networkPanel.css index d6732a2..e6099cd 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/networkPanel.css +++ b/third_party/WebKit/Source/devtools/front_end/network/networkPanel.css
@@ -28,7 +28,7 @@ */ .panel.network > .toolbar { - position: relative; + background-color: var(--toolbar-bg-color); border-bottom: 1px solid #dadada; }
diff --git a/third_party/WebKit/Source/devtools/front_end/network/requestHTMLView.css b/third_party/WebKit/Source/devtools/front_end/network/requestHTMLView.css index 71be4a8..a71ebee 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/requestHTMLView.css +++ b/third_party/WebKit/Source/devtools/front_end/network/requestHTMLView.css
@@ -4,7 +4,7 @@ * found in the LICENSE file. */ .html-preview-frame { - box-shadow: 0 3px 10px rgba(0, 0, 0, 0.5); + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5); flex-grow: 1; margin: 20px; }
diff --git a/third_party/WebKit/Source/devtools/front_end/node_app.json b/third_party/WebKit/Source/devtools/front_end/node_app.json index d0342ad2..35f77b3 100644 --- a/third_party/WebKit/Source/devtools/front_end/node_app.json +++ b/third_party/WebKit/Source/devtools/front_end/node_app.json
@@ -1,6 +1,7 @@ { "modules" : [ { "name": "node_main", "type": "autostart" }, + { "name": "node_debugger" }, { "name": "js_profiler" } ], "extends": "shell",
diff --git a/third_party/WebKit/Source/devtools/front_end/node_debugger/module.json b/third_party/WebKit/Source/devtools/front_end/node_debugger/module.json new file mode 100644 index 0000000..b3753682 --- /dev/null +++ b/third_party/WebKit/Source/devtools/front_end/node_debugger/module.json
@@ -0,0 +1,16 @@ +{ + "extensions": [ + { + "type": "view", + "location": "navigator-view", + "id": "navigator-network", + "title": "Node", + "order": 2, + "persistence": "permanent", + "className": "Sources.NetworkNavigatorView" + } + ], + "dependencies": [ + "sources" + ] +}
diff --git a/third_party/WebKit/Source/devtools/front_end/performance_test_runner/TimelineDataTestRunner.js b/third_party/WebKit/Source/devtools/front_end/performance_test_runner/TimelineDataTestRunner.js index 6f53685..57eb6ec 100644 --- a/third_party/WebKit/Source/devtools/front_end/performance_test_runner/TimelineDataTestRunner.js +++ b/third_party/WebKit/Source/devtools/front_end/performance_test_runner/TimelineDataTestRunner.js
@@ -50,7 +50,7 @@ 'ts': 0 }, { - 'args': {'sessionId': '9.4'}, + 'args': {'data': {'sessionId': '9.4', 'frames': [{'frame': 'frame1', 'url': 'frameurl', 'name': 'frame-name'}]}}, 'cat': 'disabled-by-default-devtools.timeline', 'name': 'TracingStartedInPage', @@ -62,7 +62,7 @@ 'tts': 170409 }, { - 'args': {'layerTreeId': 1, 'sessionId': '9.4'}, + 'args': {'data': {'layerTreeId': 17, 'frame': 'frame-unknown'}}, 'cat': 'disabled-by-default-devtools.timeline', 'name': 'SetLayerTreeId', @@ -74,6 +74,18 @@ 'tts': 170421 }, { + 'args': {'data': {'layerTreeId': 1, 'frame': 'frame1'}}, + + 'cat': 'disabled-by-default-devtools.timeline', + 'name': 'SetLayerTreeId', + 'ph': 'I', + 'pid': 3834, + 's': 'g', + 'tid': 9, + 'ts': 1122673092083, + 'tts': 170421 + }, + { 'args': {}, 'cat': 'disabled-by-default-devtools.timeline', 'name': 'Program',
diff --git a/third_party/WebKit/Source/devtools/front_end/persistence/Automapping.js b/third_party/WebKit/Source/devtools/front_end/persistence/Automapping.js index a49c9ee..08c9fd8 100644 --- a/third_party/WebKit/Source/devtools/front_end/persistence/Automapping.js +++ b/third_party/WebKit/Source/devtools/front_end/persistence/Automapping.js
@@ -182,13 +182,36 @@ if (status.network.contentType().isFromSourceMap() || !status.fileSystem.contentType().isTextType()) return status; - await Promise.all([status.network.requestContent(), status.fileSystem.requestContent()]); + // At the time binding comes, there are multiple user scenarios: + // 1. Both network and fileSystem files are **not** dirty. + // This is a typical scenario when user hasn't done any edits yet to the + // files in question. + // 2. FileSystem file has unsaved changes, network is clear. + // This typically happens with CSS files editing. Consider the following + // scenario: + // - user edits file that has been successfully mapped before + // - user doesn't save the file + // - user hits reload + // 3. Network file has either unsaved changes or commits, but fileSystem file is clear. + // This typically happens when we've been editing file and then realized we'd like to drop + // a folder and persist all the changes. + // 4. Network file has either unsaved changes or commits, and fileSystem file has unsaved changes. + // We consider this to be un-realistic scenario and in this case just fail gracefully. + // + // To support usecase (3), we need to validate against original network content. + if (status.fileSystem.isDirty() && (status.network.isDirty() || status.network.hasCommits())) + return null; + + const contents = await Promise.all([ + status.fileSystem.requestContent(), + new Promise(x => status.network.project().requestFileContent(status.network, x)) + ]); + const fileSystemContent = contents[0]; + const networkContent = contents[1]; if (networkSourceCode[Persistence.Automapping._processingPromise] !== createBindingPromise) return null; - const fileSystemContent = status.fileSystem.workingCopy(); - const networkContent = status.network.workingCopy(); const target = Bindings.NetworkProject.targetForUISourceCode(status.network); let isValid = false; if (target && target.isNodeJS()) {
diff --git a/third_party/WebKit/Source/devtools/front_end/persistence/Persistence.js b/third_party/WebKit/Source/devtools/front_end/persistence/Persistence.js index 3fa4592..a216bf4 100644 --- a/third_party/WebKit/Source/devtools/front_end/persistence/Persistence.js +++ b/third_party/WebKit/Source/devtools/front_end/persistence/Persistence.js
@@ -91,6 +91,16 @@ this._moveBreakpoints(binding.fileSystem, binding.network); + console.assert(!binding.fileSystem.isDirty() || !binding.network.isDirty()); + if (binding.fileSystem.isDirty()) { + this._syncWorkingCopy(binding.fileSystem); + } else if (binding.network.isDirty()) { + this._syncWorkingCopy(binding.network); + } else if (binding.network.hasCommits()) { + binding.network.setWorkingCopy(binding.network.content()); + this._syncWorkingCopy(binding.network); + } + this._notifyBindingEvent(binding.network); this._notifyBindingEvent(binding.fileSystem); this.dispatchEventToListeners(Persistence.Persistence.Events.BindingCreated, binding); @@ -148,6 +158,13 @@ */ _onWorkingCopyChanged(event) { const uiSourceCode = /** @type {!Workspace.UISourceCode} */ (event.data); + this._syncWorkingCopy(uiSourceCode); + } + + /** + * @param {!Workspace.UISourceCode} uiSourceCode + */ + _syncWorkingCopy(uiSourceCode) { const binding = uiSourceCode[Persistence.Persistence._binding]; if (!binding || binding[Persistence.Persistence._muteWorkingCopy]) return;
diff --git a/third_party/WebKit/Source/devtools/front_end/resources/resourcesSidebar.css b/third_party/WebKit/Source/devtools/front_end/resources/resourcesSidebar.css index ccebe240..d1d413a 100644 --- a/third_party/WebKit/Source/devtools/front_end/resources/resourcesSidebar.css +++ b/third_party/WebKit/Source/devtools/front_end/resources/resourcesSidebar.css
@@ -18,10 +18,13 @@ } li.storage-group-list-item { - border-top: 1px solid rgb(230, 230, 230); padding: 10px 8px 6px 8px; } +li.storage-group-list-item:not(:first-child) { + border-top: 1px solid rgb(230, 230, 230); +} + li.storage-group-list-item::before { display: none; }
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/SourcesPanel.js b/third_party/WebKit/Source/devtools/front_end/sources/SourcesPanel.js index f08809bc..f02e764 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/SourcesPanel.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/SourcesPanel.js
@@ -753,7 +753,7 @@ if (!uiSourceCode.project().isServiceProject() && !event.target.isSelfOrDescendant(this._navigatorTabbedLocation.widget().element)) { contextMenu.revealSection().appendItem( - Common.UIString('Reveal in navigator'), this._handleContextMenuReveal.bind(this, uiSourceCode)); + Common.UIString('Reveal in sidebar'), this._handleContextMenuReveal.bind(this, uiSourceCode)); } }
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/module.json b/third_party/WebKit/Source/devtools/front_end/sources/module.json index cae512a..3824eef 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/module.json +++ b/third_party/WebKit/Source/devtools/front_end/sources/module.json
@@ -282,15 +282,6 @@ { "type": "view", "location": "navigator-view", - "id": "navigator-network", - "title": "Network", - "order": 2, - "persistence": "permanent", - "className": "Sources.NetworkNavigatorView" - }, - { - "type": "view", - "location": "navigator-view", "id": "navigator-files", "title": "Filesystem", "order": 3, @@ -403,18 +394,18 @@ { "type": "setting", "category": "Sources", - "title": "Automatically reveal files in navigator", + "title": "Automatically reveal files in sidebar", "settingName": "autoRevealInNavigator", "settingType": "boolean", "defaultValue": false, "options": [ { "value": true, - "title": "Automatically reveal files in navigator" + "title": "Automatically reveal files in sidebar" }, { "value": false, - "title": "Do not automatically reveal files in navigator" + "title": "Do not automatically reveal files in sidebar" } ] },
diff --git a/third_party/WebKit/Source/devtools/front_end/text_editor/cmdevtools.css b/third_party/WebKit/Source/devtools/front_end/text_editor/cmdevtools.css index 44758182..35f1de3cb 100644 --- a/third_party/WebKit/Source/devtools/front_end/text_editor/cmdevtools.css +++ b/third_party/WebKit/Source/devtools/front_end/text_editor/cmdevtools.css
@@ -92,8 +92,8 @@ } .CodeMirror-gutters { - border-right: 1px solid rgb(187, 187, 187); - background-color: #eee; + border-right: 1px solid var(--split-resizer-fg-color); + background-color: var(--toolbar-bg-color); white-space: nowrap; }
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline/PerformanceModel.js b/third_party/WebKit/Source/devtools/front_end/timeline/PerformanceModel.js index e8fb15b..81a6a425 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline/PerformanceModel.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline/PerformanceModel.js
@@ -56,8 +56,7 @@ const asyncEventsByGroup = this._timelineModel.mainThreadAsyncEvents(); this._irModel.populate(asyncEventsByGroup.get(groups.input), asyncEventsByGroup.get(groups.animation)); - this._frameModel.addTraceEvents( - this._mainTarget, this._timelineModel.inspectedTargetEvents(), this._timelineModel.sessionId() || ''); + this._frameModel.addTraceEvents(this._mainTarget, this._timelineModel.inspectedTargetEvents()); for (const entry of this._extensionTracingModels) { entry.model.adjustTime(
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline/timelinePanel.css b/third_party/WebKit/Source/devtools/front_end/timeline/timelinePanel.css index 0a4e3005..4a51188 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline/timelinePanel.css +++ b/third_party/WebKit/Source/devtools/front_end/timeline/timelinePanel.css
@@ -28,6 +28,7 @@ */ .panel.timeline > .toolbar { + background-color: var(--toolbar-bg-color); border-bottom: 1px solid #dadada; } @@ -500,6 +501,7 @@ } .timeline-tree-view .toolbar { + background-color: var(--toolbar-bg-color); border-bottom: 1px solid #dadada; }
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline_model/TimelineFrameModel.js b/third_party/WebKit/Source/devtools/front_end/timeline_model/TimelineFrameModel.js index 7a0ca16..2469634 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline_model/TimelineFrameModel.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline_model/TimelineFrameModel.js
@@ -121,7 +121,7 @@ this._framePendingActivation = null; this._lastTaskBeginTime = null; this._target = null; - this._sessionId = null; + this._layerTreeId = null; this._currentTaskTimeByCategory = {}; } @@ -239,11 +239,9 @@ /** * @param {?SDK.Target} target * @param {!Array.<!SDK.TracingModel.Event>} events - * @param {string} sessionId */ - addTraceEvents(target, events, sessionId) { + addTraceEvents(target, events) { this._target = target; - this._sessionId = sessionId; for (let i = 0; i < events.length; ++i) this._addTraceEvent(events[i]); } @@ -257,11 +255,9 @@ this._minimumRecordTime = event.startTime; if (event.name === eventNames.SetLayerTreeId) { - const sessionId = event.args['sessionId'] || event.args['data']['sessionId']; - if (this._sessionId === sessionId) - this._layerTreeId = event.args['layerTreeId'] || event.args['data']['layerTreeId']; + this._layerTreeId = event.args['layerTreeId'] || event.args['data']['layerTreeId']; } else if (event.name === eventNames.TracingStartedInPage) { - this._mainThread = event.thread; + this._currentProcessMainThread = event.thread; } else if ( event.phase === SDK.TracingModel.Phase.SnapshotObject && event.name === eventNames.LayerTreeHostImplSnapshot && parseInt(event.id, 0) === this._layerTreeId) { @@ -269,7 +265,7 @@ this.handleLayerTreeSnapshot(new TimelineModel.TracingFrameLayerTree(this._target, snapshot)); } else { this._processCompositorEvents(event); - if (event.thread === this._mainThread) + if (event.thread === this._currentProcessMainThread) this._addMainThreadTraceEvent(event); else if (this._lastFrame && event.selfTime && !SDK.TracingModel.isTopLevelEvent(event)) this._lastFrame._addTimeForCategory(this._categoryMapper(event), event.selfTime);
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline_model/TimelineModel.js b/third_party/WebKit/Source/devtools/front_end/timeline_model/TimelineModel.js index 70ce69b..b6927aa 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline_model/TimelineModel.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline_model/TimelineModel.js
@@ -147,13 +147,6 @@ } /** - * @return {?string} - */ - sessionId() { - return this._sessionId; - } - - /** * @param {!SDK.TracingModel.Event} event * @return {?SDK.Target} */ @@ -699,7 +692,18 @@ break; case recordTypes.SetLayerTreeId: - this._inspectedTargetLayerTreeId = event.args['layerTreeId'] || event.args['data']['layerTreeId']; + // This is to support old traces. + if (this._sessionId && eventData['sessionId'] && this._sessionId === eventData['sessionId']) { + this._mainFrameLayerTreeId = eventData['layerTreeId']; + break; + } + + // We currently only show layer tree for the main frame. + const frameId = TimelineModel.TimelineModel.eventFrameId(event); + const pageFrame = this._pageFrames.get(frameId); + if (!pageFrame || pageFrame.parent) + return false; + this._mainFrameLayerTreeId = eventData['layerTreeId']; break; case recordTypes.Paint: { @@ -716,7 +720,7 @@ case recordTypes.DisplayItemListSnapshot: case recordTypes.PictureSnapshot: { const layerUpdateEvent = this._findAncestorEvent(recordTypes.UpdateLayer); - if (!layerUpdateEvent || layerUpdateEvent.args['layerTreeId'] !== this._inspectedTargetLayerTreeId) + if (!layerUpdateEvent || layerUpdateEvent.args['layerTreeId'] !== this._mainFrameLayerTreeId) break; const paintEvent = this._lastPaintForLayer[layerUpdateEvent.args['layerId']]; if (paintEvent) {
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/filter.css b/third_party/WebKit/Source/devtools/front_end/ui/filter.css index d0fad0c4..29e7294 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/filter.css +++ b/third_party/WebKit/Source/devtools/front_end/ui/filter.css
@@ -134,16 +134,22 @@ } .filter-input-field { - border: 1px solid rgb(163, 163, 163); - border-radius: 2px; - padding: 1px 3px 0; - margin: 0 0 0 3px; + margin: 0 3px; + padding-left: 3px; width: 163px; - height: 20px; - line-height: 17px; + height: 18px; + line-height: 20px; display: inline-block; background: #FFF; overflow: hidden; white-space: nowrap; cursor: auto; } + +.filter-input-field:hover { + box-shadow: 0 0 0 1px #e0e0e0; +} + +.filter-input-field:focus { + box-shadow: 0 0 0 1px #61b8ff; +}
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/inspectorCommon.css b/third_party/WebKit/Source/devtools/front_end/ui/inspectorCommon.css index ff5f0eb..3d4164a2 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/inspectorCommon.css +++ b/third_party/WebKit/Source/devtools/front_end/ui/inspectorCommon.css
@@ -174,16 +174,20 @@ .harmony-input[type=number], .harmony-input[type=text] { padding: 3px 6px; - border: 1px solid rgba(0, 0, 0, 0.2); - border-radius: 2px; height: 24px; + border: none; +} + +.harmony-input:not([type]):not(.error-input):not(:invalid):hover, +.harmony-input[type=number]:not(.error-input):not(:invalid):hover, +.harmony-input[type=text]:not(.error-input):not(:invalid):hover { + box-shadow: 0 0 0 1px #e0e0e0; } .harmony-input:not([type]):not(.error-input):not(:invalid):focus, .harmony-input[type=number]:not(.error-input):not(:invalid):focus, .harmony-input[type=text]:not(.error-input):not(:invalid):focus { - box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.4); - border-color: transparent; + box-shadow: 0 0 0 1px #61b8ff; } .highlighted-search-result.current-search-result {
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/inspectorStyle.css b/third_party/WebKit/Source/devtools/front_end/ui/inspectorStyle.css index 24abe8c8..3b4ea42 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/inspectorStyle.css +++ b/third_party/WebKit/Source/devtools/front_end/ui/inspectorStyle.css
@@ -42,6 +42,7 @@ --drop-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05), 0 2px 4px rgba(0, 0, 0, 0.2), 0 2px 6px rgba(0, 0, 0, 0.1); + --split-resizer-fg-color: #e0e0e0; } .-theme-with-dark-background { @@ -54,6 +55,7 @@ --drop-shadow: 0 0 0 1px rgba(255, 255, 255, 0.2), 0 2px 4px 2px rgba(0, 0, 0, 0.2), 0 2px 6px 2px rgba(0, 0, 0, 0.1); + --split-resizer-fg-color: #525252; } body {
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/splitWidget.css b/third_party/WebKit/Source/devtools/front_end/ui/splitWidget.css index 9c93d7e..78f7b7e1e 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/splitWidget.css +++ b/third_party/WebKit/Source/devtools/front_end/ui/splitWidget.css
@@ -84,20 +84,20 @@ .shadow-split-widget.vbox > .shadow-split-widget-sidebar:not(.maximized) { border: 0; - border-top: 1px solid rgb(64%, 64%, 64%); + border-top: 1px solid var(--split-resizer-fg-color); } .shadow-split-widget.vbox.shadow-split-widget-first-is-sidebar > .shadow-split-widget-sidebar:not(.maximized) { border: 0; - border-bottom: 1px solid rgb(64%, 64%, 64%); + border-bottom: 1px solid var(--split-resizer-fg-color); } .shadow-split-widget.hbox > .shadow-split-widget-sidebar:not(.maximized) { border: 0; - border-left: 1px solid rgb(64%, 64%, 64%); + border-left: 1px solid var(--split-resizer-fg-color); } .shadow-split-widget.hbox.shadow-split-widget-first-is-sidebar > .shadow-split-widget-sidebar:not(.maximized) { border: 0; - border-right: 1px solid rgb(64%, 64%, 64%); + border-right: 1px solid var(--split-resizer-fg-color); }
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/toolbar.css b/third_party/WebKit/Source/devtools/front_end/ui/toolbar.css index c8f3c7c..b360dcf5 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/toolbar.css +++ b/third_party/WebKit/Source/devtools/front_end/ui/toolbar.css
@@ -238,14 +238,16 @@ padding: 4px 3px 3px 3px; margin: 1px 3px; background-color: white; - border: solid 1px #d8d8d8; - border-radius: 2px; + border: 1px solid transparent ; min-width: 35px; } -.toolbar-input.focused, .toolbar-input:hover { - border: solid 1px rgb(202, 202, 202); + box-shadow: 0 0 0 1px #e0e0e0; +} + +.toolbar-input.focused { + box-shadow: 0 0 0 1px #61b8ff; } .toolbar-input > input {
diff --git a/third_party/WebKit/Source/modules/mediastream/InputDeviceInfo.cpp b/third_party/WebKit/Source/modules/mediastream/InputDeviceInfo.cpp index 301dd70c..a580e8c17 100644 --- a/third_party/WebKit/Source/modules/mediastream/InputDeviceInfo.cpp +++ b/third_party/WebKit/Source/modules/mediastream/InputDeviceInfo.cpp
@@ -72,6 +72,11 @@ } void InputDeviceInfo::getCapabilities(MediaTrackCapabilities& capabilities) { + // If label is null, permissions have not been given and no capabilities + // should be returned. + if (label().IsEmpty()) + return; + capabilities.setDeviceId(deviceId()); capabilities.setGroupId(groupId());
diff --git a/third_party/WebKit/Source/modules/webgl/PRESUBMIT.py b/third_party/WebKit/Source/modules/webgl/PRESUBMIT.py index 12569e2..3b79814 100644 --- a/third_party/WebKit/Source/modules/webgl/PRESUBMIT.py +++ b/third_party/WebKit/Source/modules/webgl/PRESUBMIT.py
@@ -22,5 +22,5 @@ ['luci.chromium.try:linux_optional_gpu_tests_rel', 'luci.chromium.try:mac_optional_gpu_tests_rel', 'master.tryserver.chromium.win:win_optional_gpu_tests_rel', - 'master.tryserver.chromium.android:android_optional_gpu_tests_rel'], + 'luci.chromium.try:android_optional_gpu_tests_rel'], 'Automatically added optional GPU tests to run on CQ.')
diff --git a/third_party/WebKit/Source/platform/WebGestureEvent.cpp b/third_party/WebKit/Source/platform/WebGestureEvent.cpp index eee63cc..59d05da 100644 --- a/third_party/WebKit/Source/platform/WebGestureEvent.cpp +++ b/third_party/WebKit/Source/platform/WebGestureEvent.cpp
@@ -89,8 +89,9 @@ } WebFloatPoint WebGestureEvent::PositionInRootFrame() const { - return WebFloatPoint((x / frame_scale_) + frame_translate_.x, - (y / frame_scale_) + frame_translate_.y); + return WebFloatPoint( + (position_in_widget_.x / frame_scale_) + frame_translate_.x, + (position_in_widget_.y / frame_scale_) + frame_translate_.y); } int WebGestureEvent::TapCount() const { @@ -104,8 +105,10 @@ // client co-ordinates in a 'click' event should yield the target). The // global position is intentionally left unmodified because it's intended to // reflect raw co-ordinates unrelated to any content. - frame_translate_.x = root_frame_coords.x - (x / frame_scale_); - frame_translate_.y = root_frame_coords.y - (y / frame_scale_); + frame_translate_.x = + root_frame_coords.x - (position_in_widget_.x / frame_scale_); + frame_translate_.y = + root_frame_coords.y - (position_in_widget_.y / frame_scale_); } void WebGestureEvent::FlattenTransform() { @@ -146,8 +149,7 @@ } } - x = (x / frame_scale_) + frame_translate_.x; - y = (y / frame_scale_) + frame_translate_.y; + SetPositionInWidget(PositionInRootFrame()); frame_translate_.x = 0; frame_translate_.y = 0; frame_scale_ = 1;
diff --git a/third_party/WebKit/Source/platform/WebMouseEvent.cpp b/third_party/WebKit/Source/platform/WebMouseEvent.cpp index 1ba2197..50051b8d 100644 --- a/third_party/WebKit/Source/platform/WebMouseEvent.cpp +++ b/third_party/WebKit/Source/platform/WebMouseEvent.cpp
@@ -22,8 +22,8 @@ click_count(click_count_param) { DCHECK_GE(type, kMouseTypeFirst); DCHECK_LE(type, kMouseTypeLast); - SetPositionInWidget(gesture_event.x, gesture_event.y); - SetPositionInScreen(gesture_event.global_x, gesture_event.global_y); + SetPositionInWidget(gesture_event.PositionInWidget()); + SetPositionInScreen(gesture_event.PositionInScreen()); SetFrameScale(gesture_event.FrameScale()); SetFrameTranslate(gesture_event.FrameTranslate()); SetMenuSourceType(gesture_event.GetType()); @@ -47,10 +47,7 @@ } void WebMouseEvent::FlattenTransformSelf() { - position_in_widget_.x = - floor((position_in_widget_.x / frame_scale_) + frame_translate_.x); - position_in_widget_.y = - floor((position_in_widget_.y / frame_scale_) + frame_translate_.y); + position_in_widget_ = PositionInRootFrame(); frame_translate_.x = 0; frame_translate_.y = 0; frame_scale_ = 1;
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.cc b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.cc index e335fff..dd1e665 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.cc +++ b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.cc
@@ -702,9 +702,13 @@ if (task_queue->CanBeThrottled()) AddQueueToWakeUpBudgetPool(task_queue.get()); - if (queue_class == MainThreadTaskQueue::QueueClass::kTimer) { - if (main_thread_only().virtual_time_stopped) - task_queue->InsertFence(TaskQueue::InsertFencePosition::kNow); + // If this is a timer queue, and virtual time is enabled and paused, it should + // be suspended by adding a fence to prevent immediate tasks from running when + // they're not supposed to. + if (queue_class == MainThreadTaskQueue::QueueClass::kTimer && + main_thread_only().virtual_time_stopped && + main_thread_only().use_virtual_time) { + task_queue->InsertFence(TaskQueue::InsertFencePosition::kNow); } return task_queue;
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl_unittest.cc b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl_unittest.cc index 2ae8140..58bf04b 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl_unittest.cc +++ b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl_unittest.cc
@@ -3729,6 +3729,15 @@ EXPECT_EQ(500u, unthrottled_count); } +TEST_F(RendererSchedulerImplTest, + VirtualTimePolicyDoesNotAffectNewTimerTaskQueueIfVirtualTimeNotEnabled) { + scheduler_->SetVirtualTimePolicy( + PageSchedulerImpl::VirtualTimePolicy::kPause); + scoped_refptr<MainThreadTaskQueue> timer_tq = scheduler_->NewTimerTaskQueue( + MainThreadTaskQueue::QueueType::kFrameThrottleable); + EXPECT_FALSE(timer_tq->HasActiveFence()); +} + TEST_F(RendererSchedulerImplTest, EnableVirtualTime) { EXPECT_FALSE(scheduler_->IsVirtualTimeEnabled()); scheduler_->EnableVirtualTime(
diff --git a/third_party/WebKit/Source/platform/scroll/Scrollbar.cpp b/third_party/WebKit/Source/platform/scroll/Scrollbar.cpp index 95a767b..9332b56b 100644 --- a/third_party/WebKit/Source/platform/scroll/Scrollbar.cpp +++ b/third_party/WebKit/Source/platform/scroll/Scrollbar.cpp
@@ -346,7 +346,7 @@ scroll_pos_ = pressed_pos_; return true; case WebInputEvent::kGestureScrollBegin: - switch (evt.source_device) { + switch (evt.SourceDevice()) { case kWebGestureDeviceSyntheticAutoscroll: case kWebGestureDeviceTouchpad: // Update the state on GSB for touchpad since GestureTapDown @@ -366,7 +366,7 @@ } break; case WebInputEvent::kGestureScrollUpdate: - switch (evt.source_device) { + switch (evt.SourceDevice()) { case kWebGestureDeviceSyntheticAutoscroll: case kWebGestureDeviceTouchpad: return false;
diff --git a/third_party/WebKit/public/platform/WebGestureEvent.h b/third_party/WebKit/public/platform/WebGestureEvent.h index 9abf6e51..894f8ff 100644 --- a/third_party/WebKit/public/platform/WebGestureEvent.h +++ b/third_party/WebKit/public/platform/WebGestureEvent.h
@@ -32,13 +32,6 @@ kLastPhase = kMomentumPhase, }; - // TODO(mustaq): Make these coordinates private & fractional, as in - // WebMouseEvent.h . - int x; - int y; - int global_x; - int global_y; - WebGestureDevice source_device; bool is_source_touch_event_set_non_blocking; // The pointer type for the first touch point in the gesture. @@ -163,24 +156,48 @@ } pinch_update; } data; - WebGestureEvent(Type type, int modifiers, double time_stamp_seconds) + private: + // Widget coordinate, which is relative to the bound of current RenderWidget + // (e.g. a plugin or OOPIF inside a RenderView). Similar to viewport + // coordinates but without DevTools emulation transform or overscroll applied. + WebFloatPoint position_in_widget_; + + // Screen coordinate + WebFloatPoint position_in_screen_; + + WebGestureDevice source_device_; + + public: + WebGestureEvent(Type type, + int modifiers, + double time_stamp_seconds, + WebGestureDevice device = kWebGestureDeviceUninitialized) : WebInputEvent(sizeof(WebGestureEvent), type, modifiers, time_stamp_seconds), - source_device(kWebGestureDeviceUninitialized), - resending_plugin_id(-1) {} + resending_plugin_id(-1), + source_device_(device) {} WebGestureEvent() : WebInputEvent(sizeof(WebGestureEvent)), - source_device(kWebGestureDeviceUninitialized), - resending_plugin_id(-1) {} + resending_plugin_id(-1), + source_device_(kWebGestureDeviceUninitialized) {} - WebFloatPoint PositionInWidget() const { return WebFloatPoint(x, y); } - WebFloatPoint PositionInScreen() const { - return WebFloatPoint(global_x, global_y); + const WebFloatPoint& PositionInWidget() const { return position_in_widget_; } + const WebFloatPoint& PositionInScreen() const { return position_in_screen_; } + + void SetPositionInWidget(const WebFloatPoint& point) { + position_in_widget_ = point; } + void SetPositionInScreen(const WebFloatPoint& point) { + position_in_screen_ = point; + } + + WebGestureDevice SourceDevice() const { return source_device_; } + void SetSourceDevice(WebGestureDevice device) { source_device_ = device; } + #if INSIDE_BLINK BLINK_PLATFORM_EXPORT float DeltaXInRootFrame() const; BLINK_PLATFORM_EXPORT float DeltaYInRootFrame() const;
diff --git a/third_party/WebKit/public/platform/WebPointerProperties.h b/third_party/WebKit/public/platform/WebPointerProperties.h index ce725a7..1738249 100644 --- a/third_party/WebKit/public/platform/WebPointerProperties.h +++ b/third_party/WebKit/public/platform/WebPointerProperties.h
@@ -85,6 +85,14 @@ position_in_screen_ = WebFloatPoint(x, y); } + void SetPositionInWidget(const WebFloatPoint& point) { + position_in_widget_ = point; + } + + void SetPositionInScreen(const WebFloatPoint& point) { + position_in_screen_ = point; + } + PointerId id; // The valid range is [0,1], with NaN meaning pressure is not supported by
diff --git a/third_party/WebKit/public/web/WebActiveFlingParameters.h b/third_party/WebKit/public/web/WebActiveFlingParameters.h index baed325..6214db19 100644 --- a/third_party/WebKit/public/web/WebActiveFlingParameters.h +++ b/third_party/WebKit/public/web/WebActiveFlingParameters.h
@@ -36,8 +36,8 @@ struct WebActiveFlingParameters { WebFloatPoint delta; - WebPoint point; - WebPoint global_point; + WebFloatPoint point; + WebFloatPoint global_point; int modifiers; WebGestureDevice source_device; WebSize cumulative_scroll;
diff --git a/third_party/libdrm/BUILD.gn b/third_party/libdrm/BUILD.gn index 4a199b3..188385f 100644 --- a/third_party/libdrm/BUILD.gn +++ b/third_party/libdrm/BUILD.gn
@@ -84,6 +84,7 @@ deps = [ ":libdrm", + "//build/config:exe_and_shlib_deps", ] } }
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl index 6d0243025..9b371ec 100644 --- a/tools/mb/mb_config.pyl +++ b/tools/mb/mb_config.pyl
@@ -177,7 +177,7 @@ 'Linux x64 Goma Canary LocalOutputCache': 'release_bot', 'linux-gcc-rel': 'release_bot_x86_minimal_symbols_no_clang_cxx11', - 'Chromium Mac 10.10 MacViews': 'mac_views_browser_release_bot', + 'mac-views-rel': 'mac_views_browser_release_bot', 'Chromium Mac 10.11': 'release_bot', 'Chromium Mac 10.11 Force Mac Toolchain': 'release_bot_mac_new_sdk', 'Chromium Mac 10.13': 'release_bot', @@ -664,7 +664,6 @@ 'ios-simulator-cronet': 'ios', 'ios-simulator-xcode-clang': 'ios', 'mac_chromium_10.10': 'gpu_tests_release_trybot', - 'mac_chromium_10.10_macviews': 'mac_views_browser_release_trybot', 'mac_chromium_10.12_rel_ng': 'gpu_tests_release_trybot', 'mac_chromium_10.13_rel_ng': 'release_trybot', 'mac_chromium_archive_rel_ng': 'release_bot_mac_strip', @@ -678,6 +677,7 @@ 'mac_nacl_sdk_build': 'release_bot', 'mac_optional_gpu_tests_rel': 'gpu_fyi_tests_release_trybot', 'mac_upload_clang': 'release_bot', + 'mac-views-rel': 'mac_views_browser_release_trybot', }, 'tryserver.chromium.perf': {
diff --git a/tools/metrics/actions/actions.xml b/tools/metrics/actions/actions.xml index 064a568..f9351109 100644 --- a/tools/metrics/actions/actions.xml +++ b/tools/metrics/actions/actions.xml
@@ -11620,6 +11620,11 @@ </description> </action> +<action name="MobileDownloadFileUIShown"> + <owner>eugenebut@chromium.org</owner> + <description>User was presented with the Download file UI.</description> +</action> + <action name="MobileDownloadRetryDownload"> <owner>eugenebut@chromium.org</owner> <description>
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index a1ca182b..bf5cc8cc 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -7727,6 +7727,9 @@ <int value="18" label="VeyronEmmcUpgrade.FailedWPEnable"/> <int value="19" label="VeyronEmmcUpgrade.SignatureDetected"/> <int value="20" label="Watchdog.StartupFailed"/> + <int value="21" label="Vm.VmcStart"/> + <int value="22" label="Vm.VmcStartSuccess"/> + <int value="23" label="Vm.DiskEraseFailed"/> </enum> <enum name="CrosFirstRunTutorialCompletionType"> @@ -23691,6 +23694,7 @@ <enum name="IOSNTPImpression"> <int value="0" label="Local suggestions"/> <int value="1" label="Remote suggestions"/> + <int value="2" label="Remote suggestions collapsed"/> </enum> <enum name="IOSPageLoadCountNavigationType"> @@ -26124,6 +26128,7 @@ <int value="-977476498" label="disable-eol-notification"/> <int value="-972737445" label="ArcUseAuthEndpoint:disabled"/> <int value="-972425050" label="gesture-editing"/> + <int value="-969332901" label="stop-non-timers-in-background:disabled"/> <int value="-968010468" label="SharedArrayBuffer:disabled"/> <int value="-965842218" label="MultiDeviceApi:disabled"/> <int value="-964676765" label="enable-accelerated-mjpeg-decode"/> @@ -26593,6 +26598,7 @@ label="enable-manual-fallback-for-password-saving:disabled"/> <int value="241187301" label="BrowserTouchBar:disabled"/> <int value="244697230" label="enable-theme-color-in-tabbed-mode"/> + <int value="255375615" label="stop-non-timers-in-background:enabled"/> <int value="259021228" label="OffMainThreadFetch:disabled"/> <int value="262382944" label="GuestViewCrossProcessFrames:disabled"/> <int value="266322815" label="ChromeModernDesign:disabled"/>
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 4b3ce9e..ab38b1bc 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -32454,7 +32454,7 @@ <owner>gambard@chromium.org</owner> <summary> The type of NTP impressions on iOS, split by type of suggestions shown - (local vs remote). + (local vs remote vs remote_collapsed). </summary> </histogram>
diff --git a/tools/roll_angle.py b/tools/roll_angle.py index 4edc342bf..8b0e241 100755 --- a/tools/roll_angle.py +++ b/tools/roll_angle.py
@@ -26,7 +26,7 @@ "buildernames": ["linux_optional_gpu_tests_rel"] }, { - "mastername": "master.tryserver.chromium.android", + "mastername": "luci.chromium.try", "buildernames": ["android_optional_gpu_tests_rel"] } ]
diff --git a/tools/roll_swiftshader.py b/tools/roll_swiftshader.py index 3a938a8..022a943 100755 --- a/tools/roll_swiftshader.py +++ b/tools/roll_swiftshader.py
@@ -30,7 +30,7 @@ "buildernames": ["linux_chromium_cfi_rel_ng"] }, { - "mastername": "master.tryserver.chromium.android", + "mastername": "luci.chromium.try", "buildernames": ["android_optional_gpu_tests_rel"] } ]
diff --git a/tools/roll_webgl_conformance.py b/tools/roll_webgl_conformance.py index bdc9988..df4b8255 100755 --- a/tools/roll_webgl_conformance.py +++ b/tools/roll_webgl_conformance.py
@@ -26,7 +26,7 @@ "buildernames": ["linux_optional_gpu_tests_rel"] }, { - "mastername": "master.tryserver.chromium.android", + "mastername": "luci.chromium.try", "buildernames": ["android_optional_gpu_tests_rel"] }, # Include the ANGLE tryservers which run the WebGL conformance tests
diff --git a/ui/android/java/src/org/chromium/ui/base/ViewAndroidDelegate.java b/ui/android/java/src/org/chromium/ui/base/ViewAndroidDelegate.java index a9b5fc9..18cd2be 100644 --- a/ui/android/java/src/org/chromium/ui/base/ViewAndroidDelegate.java +++ b/ui/android/java/src/org/chromium/ui/base/ViewAndroidDelegate.java
@@ -8,6 +8,7 @@ import android.content.ClipData; import android.graphics.Bitmap; import android.os.Build; +import android.view.MotionEvent; import android.view.PointerIcon; import android.view.View; import android.view.ViewGroup; @@ -340,6 +341,13 @@ } @CalledByNative + @TargetApi(Build.VERSION_CODES.LOLLIPOP) + private void requestUnbufferedDispatch(MotionEvent event) { + ViewGroup container = getContainerView(); + if (container != null) container.requestUnbufferedDispatch(event); + } + + @CalledByNative private boolean hasFocus() { ViewGroup containerView = getContainerView(); return containerView == null ? false : ViewUtils.hasFocus(containerView);
diff --git a/ui/android/view_android.cc b/ui/android/view_android.cc index 3af64e2..701200d 100644 --- a/ui/android/view_android.cc +++ b/ui/android/view_android.cc
@@ -285,6 +285,15 @@ Java_ViewAndroidDelegate_requestDisallowInterceptTouchEvent(env, delegate); } +void ViewAndroid::RequestUnbufferedDispatch(const MotionEventAndroid& event) { + ScopedJavaLocalRef<jobject> delegate(GetViewAndroidDelegate()); + if (delegate.is_null()) + return; + JNIEnv* env = base::android::AttachCurrentThread(); + Java_ViewAndroidDelegate_requestUnbufferedDispatch(env, delegate, + event.GetJavaObject()); +} + void ViewAndroid::OnAttachedToWindow() { for (auto& observer : observer_list_) observer.OnAttachedToWindow();
diff --git a/ui/android/view_android.h b/ui/android/view_android.h index c55cde24..5d32b20 100644 --- a/ui/android/view_android.h +++ b/ui/android/view_android.h
@@ -168,6 +168,7 @@ void RemoveObserver(ViewAndroidObserver* observer); void RequestDisallowInterceptTouchEvent(); + void RequestUnbufferedDispatch(const MotionEventAndroid& event); ViewAndroid* parent() const { return parent_; }
diff --git a/ui/app_list/app_list_metrics.cc b/ui/app_list/app_list_metrics.cc index 4900d25d..b30fe33c4 100644 --- a/ui/app_list/app_list_metrics.cc +++ b/ui/app_list/app_list_metrics.cc
@@ -73,7 +73,7 @@ const AppListModel* model, const SearchModel* search_model) { // Record the search metric if the SearchResult is not a suggested app. - if (result->display_type() == SearchResult::DISPLAY_RECOMMENDATION) + if (result->display_type() == ash::SearchResultDisplayType::kRecommendation) return; ApplistSearchResultOpenedSource source;
diff --git a/ui/app_list/app_list_util.cc b/ui/app_list/app_list_util.cc index 78afce6..9b77b76 100644 --- a/ui/app_list/app_list_util.cc +++ b/ui/app_list/app_list_util.cc
@@ -79,15 +79,16 @@ int GetPreferredIconDimension(SearchResult* search_result) { switch (search_result->display_type()) { - case SearchResult::DISPLAY_RECOMMENDATION: // Falls through. - case SearchResult::DISPLAY_TILE: + case ash::SearchResultDisplayType::kRecommendation: // Falls + // through. + case ash::SearchResultDisplayType::kTile: return kTileIconSize; - case SearchResult::DISPLAY_LIST: + case ash::SearchResultDisplayType::kList: return kListIconSize; - case SearchResult::DISPLAY_NONE: - case SearchResult::DISPLAY_CARD: + case ash::SearchResultDisplayType::kNone: + case ash::SearchResultDisplayType::kCard: return 0; - case SearchResult::DISPLAY_TYPE_LAST: + case ash::SearchResultDisplayType::kLast: break; } NOTREACHED();
diff --git a/ui/app_list/views/app_list_view_unittest.cc b/ui/app_list/views/app_list_view_unittest.cc index 96020b7..b45117e 100644 --- a/ui/app_list/views/app_list_view_unittest.cc +++ b/ui/app_list/views/app_list_view_unittest.cc
@@ -83,7 +83,7 @@ class TestStartPageSearchResult : public TestSearchResult { public: TestStartPageSearchResult() : menu_model_(nullptr) { - set_display_type(DISPLAY_RECOMMENDATION); + set_display_type(ash::SearchResultDisplayType::kRecommendation); } ~TestStartPageSearchResult() override {} @@ -258,11 +258,12 @@ bool card_result) { std::vector<std::pair<SearchResult::DisplayType, int>> result_types; result_types.push_back( - std::make_pair(SearchResult::DISPLAY_TILE, tile_results_num)); + std::make_pair(ash::SearchResultDisplayType::kTile, tile_results_num)); if (card_result) - result_types.push_back(std::make_pair(SearchResult::DISPLAY_CARD, 1)); + result_types.push_back( + std::make_pair(ash::SearchResultDisplayType::kCard, 1)); result_types.push_back( - std::make_pair(SearchResult::DISPLAY_LIST, list_results_num)); + std::make_pair(ash::SearchResultDisplayType::kList, list_results_num)); SearchModel::SearchResults* results = delegate_->GetSearchModel()->results();
diff --git a/ui/app_list/views/apps_grid_view_unittest.cc b/ui/app_list/views/apps_grid_view_unittest.cc index ac3625a..b640479 100644 --- a/ui/app_list/views/apps_grid_view_unittest.cc +++ b/ui/app_list/views/apps_grid_view_unittest.cc
@@ -101,7 +101,9 @@ class TestSuggestedSearchResult : public TestSearchResult { public: - TestSuggestedSearchResult() { set_display_type(DISPLAY_RECOMMENDATION); } + TestSuggestedSearchResult() { + set_display_type(ash::SearchResultDisplayType::kRecommendation); + } ~TestSuggestedSearchResult() override {} private:
diff --git a/ui/app_list/views/search_result_answer_card_view.cc b/ui/app_list/views/search_result_answer_card_view.cc index eb50732..44b4dc7 100644 --- a/ui/app_list/views/search_result_answer_card_view.cc +++ b/ui/app_list/views/search_result_answer_card_view.cc
@@ -157,7 +157,7 @@ int SearchResultAnswerCardView::DoUpdate() { std::vector<SearchResult*> display_results = SearchModel::FilterSearchResultsByDisplayType( - results(), SearchResult::DISPLAY_CARD, 1); + results(), ash::SearchResultDisplayType::kCard, 1); const bool have_result = !display_results.empty();
diff --git a/ui/app_list/views/search_result_answer_card_view_unittest.cc b/ui/app_list/views/search_result_answer_card_view_unittest.cc index 1b95114..0c70bed 100644 --- a/ui/app_list/views/search_result_answer_card_view_unittest.cc +++ b/ui/app_list/views/search_result_answer_card_view_unittest.cc
@@ -55,7 +55,7 @@ SearchModel::SearchResults* results = GetResults(); std::unique_ptr<TestSearchResult> result = std::make_unique<TestSearchResult>(); - result->set_display_type(SearchResult::DISPLAY_CARD); + result->set_display_type(ash::SearchResultDisplayType::kCard); result->set_title(base::UTF8ToUTF16(kResultTitle)); result->set_answer_card_contents_token(token_); result->set_relevance(kRelevance);
diff --git a/ui/app_list/views/search_result_list_view.cc b/ui/app_list/views/search_result_list_view.cc index 1809f27..462ea05 100644 --- a/ui/app_list/views/search_result_list_view.cc +++ b/ui/app_list/views/search_result_list_view.cc
@@ -100,7 +100,7 @@ int SearchResultListView::DoUpdate() { std::vector<SearchResult*> display_results = SearchModel::FilterSearchResultsByDisplayType( - results(), SearchResult::DISPLAY_LIST, + results(), ash::SearchResultDisplayType::kList, results_container_->child_count()); for (size_t i = 0; i < static_cast<size_t>(results_container_->child_count());
diff --git a/ui/app_list/views/search_result_list_view_unittest.cc b/ui/app_list/views/search_result_list_view_unittest.cc index ea1bd0cd..2e69a06 100644 --- a/ui/app_list/views/search_result_list_view_unittest.cc +++ b/ui/app_list/views/search_result_list_view_unittest.cc
@@ -57,7 +57,7 @@ for (int i = 0; i < kDefaultSearchItems; ++i) { std::unique_ptr<TestSearchResult> result = std::make_unique<TestSearchResult>(); - result->set_display_type(SearchResult::DISPLAY_LIST); + result->set_display_type(ash::SearchResultDisplayType::kList); result->set_title(base::UTF8ToUTF16(base::StringPrintf("Result %d", i))); if (i < 2) result->set_details(base::ASCIIToUTF16("Detail"));
diff --git a/ui/app_list/views/search_result_page_view_unittest.cc b/ui/app_list/views/search_result_page_view_unittest.cc index 33c8646..6cc10e98 100644 --- a/ui/app_list/views/search_result_page_view_unittest.cc +++ b/ui/app_list/views/search_result_page_view_unittest.cc
@@ -124,18 +124,18 @@ // Add 3 results and expect the tile list view to be the first result // container view. TestSearchResult* tile_result = new TestSearchResult(); - tile_result->set_display_type(SearchResult::DISPLAY_TILE); + tile_result->set_display_type(ash::SearchResultDisplayType::kTile); tile_result->set_relevance(1.0); results->Add(base::WrapUnique(tile_result)); { TestSearchResult* list_result = new TestSearchResult(); - list_result->set_display_type(SearchResult::DISPLAY_LIST); + list_result->set_display_type(ash::SearchResultDisplayType::kList); list_result->set_relevance(0.5); results->Add(base::WrapUnique(list_result)); } { TestSearchResult* list_result = new TestSearchResult(); - list_result->set_display_type(SearchResult::DISPLAY_LIST); + list_result->set_display_type(ash::SearchResultDisplayType::kList); list_result->set_relevance(0.3); results->Add(base::WrapUnique(list_result)); }
diff --git a/ui/app_list/views/search_result_tile_item_list_view.cc b/ui/app_list/views/search_result_tile_item_list_view.cc index 9626fb7..849744d 100644 --- a/ui/app_list/views/search_result_tile_item_list_view.cc +++ b/ui/app_list/views/search_result_tile_item_list_view.cc
@@ -6,6 +6,8 @@ #include <stddef.h> +#include <memory> + #include "ash/app_list/model/search/search_result.h" #include "base/i18n/rtl.h" #include "ui/app_list/app_list_constants.h" @@ -109,9 +111,10 @@ int SearchResultTileItemListView::DoUpdate() { std::vector<SearchResult*> display_results = SearchModel::FilterSearchResultsByDisplayType( - results(), SearchResult::DISPLAY_TILE, kMaxNumSearchResultTiles); + results(), ash::SearchResultDisplayType::kTile, + kMaxNumSearchResultTiles); - SearchResult::ResultType previous_type = SearchResult::RESULT_UNKNOWN; + SearchResult::ResultType previous_type = ash::SearchResultType::kUnknown; for (size_t i = 0; i < kMaxNumSearchResultTiles; ++i) { if (i >= display_results.size()) {
diff --git a/ui/app_list/views/search_result_tile_item_list_view_unittest.cc b/ui/app_list/views/search_result_tile_item_list_view_unittest.cc index fcf3ea6..d48afb6 100644 --- a/ui/app_list/views/search_result_tile_item_list_view_unittest.cc +++ b/ui/app_list/views/search_result_tile_item_list_view_unittest.cc
@@ -75,8 +75,8 @@ std::unique_ptr<TestSearchResult> result = std::make_unique<TestSearchResult>(); result->set_result_id(base::StringPrintf("InstalledApp %d", i)); - result->set_display_type(SearchResult::DISPLAY_TILE); - result->set_result_type(SearchResult::RESULT_INSTALLED_APP); + result->set_display_type(ash::SearchResultDisplayType::kTile); + result->set_result_type(ash::SearchResultType::kInstalledApp); result->set_title( base::UTF8ToUTF16(base::StringPrintf("InstalledApp %d", i))); results->Add(std::move(result)); @@ -88,8 +88,8 @@ std::unique_ptr<TestSearchResult> result = std::make_unique<TestSearchResult>(); result->set_result_id(base::StringPrintf("PlayStoreApp %d", i)); - result->set_display_type(SearchResult::DISPLAY_TILE); - result->set_result_type(SearchResult::RESULT_PLAYSTORE_APP); + result->set_display_type(ash::SearchResultDisplayType::kTile); + result->set_result_type(ash::SearchResultType::kPlayStoreApp); result->set_title( base::UTF8ToUTF16(base::StringPrintf("PlayStoreApp %d", i))); result->SetRating(1 + i);
diff --git a/ui/app_list/views/search_result_tile_item_view.cc b/ui/app_list/views/search_result_tile_item_view.cc index 4c3348c..5d0f270 100644 --- a/ui/app_list/views/search_result_tile_item_view.cc +++ b/ui/app_list/views/search_result_tile_item_view.cc
@@ -184,7 +184,7 @@ title_->SetLineHeight(font.GetHeight()); title_->SetEnabledColor(kGridTitleColor); } else { - DCHECK_EQ(SearchResult::DISPLAY_TILE, item_->display_type()); + DCHECK_EQ(ash::SearchResultDisplayType::kTile, item_->display_type()); // Set solid color background to avoid broken text. See crbug.com/746563. if (rating_) { rating_->SetBackground( @@ -200,9 +200,9 @@ } title_->SetMaxLines(2); - title_->SetMultiLine(item_->display_type() == SearchResult::DISPLAY_TILE && - item_->result_type() == - SearchResult::RESULT_INSTALLED_APP); + title_->SetMultiLine( + item_->display_type() == ash::SearchResultDisplayType::kTile && + item_->result_type() == ash::SearchResultType::kInstalledApp); // Only refresh the icon if it's different from the old one. This prevents // flickering. @@ -335,7 +335,7 @@ flags.setColor(kGridSelectedColor); canvas->DrawRoundRect(gfx::RectF(rect), kGridSelectedCornerRadius, flags); } else { - DCHECK(item_->display_type() == SearchResult::DISPLAY_TILE); + DCHECK(item_->display_type() == ash::SearchResultDisplayType::kTile); const int kLeftRightPadding = (rect.width() - kIconSelectedSize) / 2; rect.Inset(kLeftRightPadding, 0); rect.set_height(kIconSelectedSize); @@ -478,7 +478,8 @@ } bool SearchResultTileItemView::IsSuggestedAppTile() const { - return item_ && item_->display_type() == SearchResult::DISPLAY_RECOMMENDATION; + return item_ && + item_->display_type() == ash::SearchResultDisplayType::kRecommendation; } void SearchResultTileItemView::LogAppLaunch() const { @@ -514,7 +515,7 @@ rect.set_height(title_->GetPreferredSize().height()); title_->SetBoundsRect(rect); } else { - DCHECK(item_->display_type() == SearchResult::DISPLAY_TILE); + DCHECK(item_->display_type() == ash::SearchResultDisplayType::kTile); rect.Inset(0, kSearchTileTopPadding, 0, 0); icon_->SetBoundsRect(rect); @@ -571,7 +572,7 @@ if (IsSuggestedAppTile()) return gfx::Size(kGridTileWidth, kGridTileHeight); - DCHECK(item_->display_type() == SearchResult::DISPLAY_TILE); + DCHECK(item_->display_type() == ash::SearchResultDisplayType::kTile); return gfx::Size(kSearchTileWidth, kSearchTileHeight); }
diff --git a/ui/app_list/views/suggestions_container_view.cc b/ui/app_list/views/suggestions_container_view.cc index f41e92db..2553653 100644 --- a/ui/app_list/views/suggestions_container_view.cc +++ b/ui/app_list/views/suggestions_container_view.cc
@@ -46,7 +46,8 @@ std::vector<SearchResult*> display_results = SearchModel::FilterSearchResultsByDisplayType( - results(), SearchResult::DISPLAY_RECOMMENDATION, kNumStartPageTiles); + results(), ash::SearchResultDisplayType::kRecommendation, + kNumStartPageTiles); if (display_results.size() != search_result_tile_views_.size()) { // We should recreate the grid layout in this case. for (size_t i = 0; i < search_result_tile_views_.size(); ++i)
diff --git a/ui/base/base_window.h b/ui/base/base_window.h index f6af762c..8d4dd05 100644 --- a/ui/base/base_window.h +++ b/ui/base/base_window.h
@@ -66,6 +66,9 @@ // Hides the window. virtual void Hide() = 0; + // Returns whether the window is visible. + virtual bool IsVisible() const = 0; + // Show the window, but do not activate it. Does nothing if window // is already visible. virtual void ShowInactive() = 0;
diff --git a/ui/base/cursor/cursor_loader_ozone.cc b/ui/base/cursor/cursor_loader_ozone.cc index ef23518..b5770539 100644 --- a/ui/base/cursor/cursor_loader_ozone.cc +++ b/ui/base/cursor/cursor_loader_ozone.cc
@@ -28,7 +28,7 @@ GetImageCursorBitmap(resource_id, scale(), rotation(), &hotspot, &bitmap); - cursors_[id] = factory_->CreateImageCursor(bitmap, hotspot, scale()); + image_cursors_[id] = factory_->CreateImageCursor(bitmap, hotspot, scale()); } void CursorLoaderOzone::LoadAnimatedCursor(CursorType id, @@ -41,25 +41,23 @@ GetAnimatedCursorBitmaps( resource_id, scale(), rotation(), &hotspot, &bitmaps); - cursors_[id] = + image_cursors_[id] = factory_->CreateAnimatedCursor(bitmaps, hotspot, frame_delay_ms, scale()); } void CursorLoaderOzone::UnloadAll() { - for (ImageCursorMap::const_iterator it = cursors_.begin(); - it != cursors_.end(); ++it) { - factory_->UnrefImageCursor(it->second); - } - cursors_.clear(); + for (const auto& image_cursor : image_cursors_) + factory_->UnrefImageCursor(image_cursor.second); + image_cursors_.clear(); } void CursorLoaderOzone::SetPlatformCursor(gfx::NativeCursor* cursor) { CursorType native_type = cursor->native_type(); PlatformCursor platform; - if (cursors_.count(native_type)) { + if (image_cursors_.count(native_type)) { // An image cursor is loaded for this type. - platform = cursors_[native_type]; + platform = image_cursors_[native_type]; } else if (native_type == CursorType::kCustom) { // The platform cursor was already set via WebCursor::GetPlatformCursor. platform = cursor->platform();
diff --git a/ui/base/cursor/cursor_loader_ozone.h b/ui/base/cursor/cursor_loader_ozone.h index acb9571..ea43f0b 100644 --- a/ui/base/cursor/cursor_loader_ozone.h +++ b/ui/base/cursor/cursor_loader_ozone.h
@@ -35,8 +35,7 @@ private: // Pointers are owned by ResourceBundle and must not be freed here. - typedef std::map<CursorType, PlatformCursor> ImageCursorMap; - ImageCursorMap cursors_; + std::map<CursorType, PlatformCursor> image_cursors_; CursorFactoryOzone* factory_ = nullptr; DISALLOW_COPY_AND_ASSIGN(CursorLoaderOzone);
diff --git a/ui/base/cursor/cursor_loader_x11.h b/ui/base/cursor/cursor_loader_x11.h index e8098fb..9fa7beaa 100644 --- a/ui/base/cursor/cursor_loader_x11.h +++ b/ui/base/cursor/cursor_loader_x11.h
@@ -60,15 +60,12 @@ // A map to hold all image cursors. It maps the cursor ID to the X Cursor, the // display's scale factor, and the display's rotation. - typedef std::map<CursorType, std::unique_ptr<ImageCursor>> ImageCursorMap; - ImageCursorMap image_cursors_; + std::map<CursorType, std::unique_ptr<ImageCursor>> image_cursors_; // A map to hold all animated cursors. It maps the cursor ID to the pair of // the X Cursor and the corresponding XcursorImages. We need a pointer to the // images so that we can free them on destruction. - typedef std::map<CursorType, std::pair<::Cursor, XcursorImages*>> - AnimatedCursorMap; - AnimatedCursorMap animated_cursors_; + std::map<CursorType, std::pair<::Cursor, XcursorImages*>> animated_cursors_; const XScopedCursor invisible_cursor_;
diff --git a/ui/base/cursor/ozone/bitmap_cursor_factory_ozone.h b/ui/base/cursor/ozone/bitmap_cursor_factory_ozone.h index 7a8a2d6..28de40394 100644 --- a/ui/base/cursor/ozone/bitmap_cursor_factory_ozone.h +++ b/ui/base/cursor/ozone/bitmap_cursor_factory_ozone.h
@@ -77,9 +77,7 @@ scoped_refptr<BitmapCursorOzone> GetDefaultCursorInternal(CursorType type); // Default cursors are cached & owned by the factory. - typedef std::map<CursorType, scoped_refptr<BitmapCursorOzone>> - DefaultCursorMap; - DefaultCursorMap default_cursors_; + std::map<CursorType, scoped_refptr<BitmapCursorOzone>> default_cursors_; DISALLOW_COPY_AND_ASSIGN(BitmapCursorFactoryOzone); };
diff --git a/ui/base/cursor/ozone/cursor_data_factory_ozone.h b/ui/base/cursor/ozone/cursor_data_factory_ozone.h index c9859f2..b5cba38 100644 --- a/ui/base/cursor/ozone/cursor_data_factory_ozone.h +++ b/ui/base/cursor/ozone/cursor_data_factory_ozone.h
@@ -80,8 +80,7 @@ scoped_refptr<CursorDataOzone> GetDefaultCursorInternal(CursorType type); // Default cursors are cached & owned by the factory. - typedef std::map<CursorType, scoped_refptr<CursorDataOzone>> DefaultCursorMap; - DefaultCursorMap default_cursors_; + std::map<CursorType, scoped_refptr<CursorDataOzone>> default_cursors_; DISALLOW_COPY_AND_ASSIGN(CursorDataFactoryOzone); };
diff --git a/ui/events/blink/blink_event_util.cc b/ui/events/blink/blink_event_util.cc index f675946..593d3b9 100644 --- a/ui/events/blink/blink_event_util.cc +++ b/ui/events/blink/blink_event_util.cc
@@ -416,7 +416,7 @@ const WebGestureEvent& event) { if (event.GetType() != event_to_coalesce.GetType() || event.resending_plugin_id != event_to_coalesce.resending_plugin_id || - event.source_device != event_to_coalesce.source_device || + event.SourceDevice() != event_to_coalesce.SourceDevice() || event.GetModifiers() != event_to_coalesce.GetModifiers()) return false; @@ -426,7 +426,7 @@ // GesturePinchUpdate scales can be combined only if they share a focal point, // e.g., with double-tap drag zoom. if (event.GetType() == WebInputEvent::kGesturePinchUpdate && - event.x == event_to_coalesce.x && event.y == event_to_coalesce.y) + event.PositionInWidget() == event_to_coalesce.PositionInWidget()) return true; return false; @@ -462,9 +462,11 @@ gesture_event.data.scroll_update.delta_y); } else if (gesture_event.GetType() == WebInputEvent::kGesturePinchUpdate) { float scale = gesture_event.data.pinch_update.scale; - gesture_transform.Translate(-gesture_event.x, -gesture_event.y); + gesture_transform.Translate(-gesture_event.PositionInWidget().x, + -gesture_event.PositionInWidget().y); gesture_transform.Scale(scale, scale); - gesture_transform.Translate(gesture_event.x, gesture_event.y); + gesture_transform.Translate(gesture_event.PositionInWidget().x, + gesture_event.PositionInWidget().y); } else { NOTREACHED() << "Invalid event type for transform retrieval: " << WebInputEvent::GetName(gesture_event.GetType()); @@ -545,7 +547,7 @@ return (event_in_queue.GetType() == WebInputEvent::kGestureScrollUpdate || event_in_queue.GetType() == WebInputEvent::kGesturePinchUpdate) && event_in_queue.GetModifiers() == new_event.GetModifiers() && - event_in_queue.source_device == new_event.source_device; + event_in_queue.SourceDevice() == new_event.SourceDevice(); } std::pair<WebGestureEvent, WebGestureEvent> CoalesceScrollAndPinch( @@ -559,20 +561,17 @@ DCHECK(!second_last_event || IsCompatibleScrollorPinch(new_event, *second_last_event)); - WebGestureEvent scroll_event(WebInputEvent::kGestureScrollUpdate, - new_event.GetModifiers(), - new_event.TimeStampSeconds()); + WebGestureEvent scroll_event( + WebInputEvent::kGestureScrollUpdate, new_event.GetModifiers(), + new_event.TimeStampSeconds(), new_event.SourceDevice()); WebGestureEvent pinch_event; - scroll_event.source_device = new_event.source_device; scroll_event.primary_pointer_type = new_event.primary_pointer_type; pinch_event = scroll_event; pinch_event.SetType(WebInputEvent::kGesturePinchUpdate); - pinch_event.x = new_event.GetType() == WebInputEvent::kGesturePinchUpdate - ? new_event.x - : last_event.x; - pinch_event.y = new_event.GetType() == WebInputEvent::kGesturePinchUpdate - ? new_event.y - : last_event.y; + pinch_event.SetPositionInWidget(new_event.GetType() == + WebInputEvent::kGesturePinchUpdate + ? new_event.PositionInWidget() + : last_event.PositionInWidget()); gfx::Transform combined_scroll_pinch = GetTransformForEvent(last_event); if (second_last_event) { @@ -588,11 +587,13 @@ float combined_scroll_pinch_y = SkMScalarToFloat(combined_scroll_pinch.matrix().get(1, 3)); scroll_event.data.scroll_update.delta_x = - (combined_scroll_pinch_x + pinch_event.x) / combined_scale - - pinch_event.x; + (combined_scroll_pinch_x + pinch_event.PositionInWidget().x) / + combined_scale - + pinch_event.PositionInWidget().x; scroll_event.data.scroll_update.delta_y = - (combined_scroll_pinch_y + pinch_event.y) / combined_scale - - pinch_event.y; + (combined_scroll_pinch_y + pinch_event.PositionInWidget().y) / + combined_scale - + pinch_event.PositionInWidget().y; pinch_event.data.pinch_update.scale = combined_scale; return std::make_pair(scroll_event, pinch_event); @@ -675,26 +676,24 @@ const gfx::PointF& raw_location, int flags, uint32_t unique_touch_event_id) { - WebGestureEvent gesture(WebInputEvent::kUndefined, - EventFlagsToWebEventModifiers(flags), - ui::EventTimeStampToSeconds(timestamp)); - gesture.x = gfx::ToFlooredInt(location.x()); - gesture.y = gfx::ToFlooredInt(location.y()); - gesture.global_x = gfx::ToFlooredInt(raw_location.x()); - gesture.global_y = gfx::ToFlooredInt(raw_location.y()); - + blink::WebGestureDevice source_device = blink::kWebGestureDeviceUninitialized; switch (details.device_type()) { case GestureDeviceType::DEVICE_TOUCHSCREEN: - gesture.source_device = blink::kWebGestureDeviceTouchscreen; + source_device = blink::kWebGestureDeviceTouchscreen; break; case GestureDeviceType::DEVICE_TOUCHPAD: - gesture.source_device = blink::kWebGestureDeviceTouchpad; + source_device = blink::kWebGestureDeviceTouchpad; break; case GestureDeviceType::DEVICE_UNKNOWN: NOTREACHED() << "Unknown device type is not allowed"; - gesture.source_device = blink::kWebGestureDeviceUninitialized; break; } + WebGestureEvent gesture( + WebInputEvent::kUndefined, EventFlagsToWebEventModifiers(flags), + ui::EventTimeStampToSeconds(timestamp), source_device); + + gesture.SetPositionInWidget(location); + gesture.SetPositionInScreen(raw_location); gesture.is_source_touch_event_set_non_blocking = details.is_source_touch_event_set_non_blocking(); @@ -866,10 +865,9 @@ blink::WebGestureEvent* gesture_event = new blink::WebGestureEvent; scaled_event.reset(gesture_event); *gesture_event = static_cast<const blink::WebGestureEvent&>(event); - gesture_event->x += delta.x(); - gesture_event->y += delta.y(); - gesture_event->x *= scale; - gesture_event->y *= scale; + gesture_event->SetPositionInWidget(blink::WebFloatPoint( + (gesture_event->PositionInWidget().x + delta.x()) * scale, + (gesture_event->PositionInWidget().y + delta.y()) * scale)); switch (gesture_event->GetType()) { case blink::WebInputEvent::kGestureScrollUpdate: if (gesture_event->data.scroll_update.delta_units != @@ -1203,13 +1201,11 @@ // NOTE: Source gesture events are synthetic ones that simulate // gesture from keyboard (zoom in/out) for now. Should populate Blink // event's fields better when extended to handle more cases. - web_event->x = event.location().x(); - web_event->y = event.location().y(); - web_event->global_x = event.screen_location().x(); - web_event->global_x = event.screen_location().y(); - web_event->source_device = blink::kWebGestureDeviceTouchscreen; + web_event->SetPositionInWidget(event.location()); + web_event->SetPositionInScreen(event.screen_location()); + web_event->SetSourceDevice(blink::kWebGestureDeviceTouchscreen); if (event.synthetic_scroll()) - web_event->source_device = blink::kWebGestureDeviceSyntheticAutoscroll; + web_event->SetSourceDevice(blink::kWebGestureDeviceSyntheticAutoscroll); if (event_type == WebInputEvent::kGesturePinchUpdate) { web_event->data.pinch_update.scale = event.scale(); } else if (event_type == WebInputEvent::kGestureScrollBegin) {
diff --git a/ui/events/blink/fling_booster.cc b/ui/events/blink/fling_booster.cc index 233d720..c1f621c 100644 --- a/ui/events/blink/fling_booster.cc +++ b/ui/events/blink/fling_booster.cc
@@ -59,7 +59,7 @@ return false; // Gestures from a different source should immediately interrupt the fling. - if (gesture_event.source_device != source_device_) { + if (gesture_event.SourceDevice() != source_device_) { *out_cancel_current_fling = true; return false; } @@ -100,7 +100,7 @@ return true; case WebInputEvent::kGestureFlingStart: { - DCHECK_EQ(source_device_, gesture_event.source_device); + DCHECK_EQ(source_device_, gesture_event.SourceDevice()); gfx::Vector2dF new_fling_velocity( gesture_event.data.fling_start.velocity_x, gesture_event.data.fling_start.velocity_y);
diff --git a/ui/events/blink/fling_booster_unittest.cc b/ui/events/blink/fling_booster_unittest.cc index 07536355..9a70b41 100644 --- a/ui/events/blink/fling_booster_unittest.cc +++ b/ui/events/blink/fling_booster_unittest.cc
@@ -21,7 +21,7 @@ class FlingBoosterTest : public testing::Test { public: FlingBoosterTest() : delta_time_(base::TimeDelta::FromMilliseconds(10)) { - gesture_scroll_event_.source_device = blink::kWebGestureDeviceTouchscreen; + gesture_scroll_event_.SetSourceDevice(blink::kWebGestureDeviceTouchscreen); } WebGestureEvent CreateFlingStart(base::TimeTicks timestamp, @@ -29,8 +29,8 @@ const gfx::Vector2dF& velocity, int modifiers) { WebGestureEvent fling_start(WebInputEvent::kGestureFlingStart, modifiers, - EventTimeStampToSeconds(timestamp)); - fling_start.source_device = source_device; + EventTimeStampToSeconds(timestamp), + source_device); fling_start.data.fling_start.velocity_x = velocity.x(); fling_start.data.fling_start.velocity_y = velocity.y(); return fling_start; @@ -39,8 +39,8 @@ WebGestureEvent CreateFlingCancel(base::TimeTicks timestamp, WebGestureDevice source_device) { WebGestureEvent fling_cancel(WebInputEvent::kGestureFlingCancel, 0, - EventTimeStampToSeconds(timestamp)); - fling_cancel.source_device = source_device; + EventTimeStampToSeconds(timestamp), + source_device); return fling_cancel; }
diff --git a/ui/events/blink/input_handler_proxy.cc b/ui/events/blink/input_handler_proxy.cc index 6d779108..b5d3aaf 100644 --- a/ui/events/blink/input_handler_proxy.cc +++ b/ui/events/blink/input_handler_proxy.cc
@@ -78,8 +78,8 @@ cc::ScrollStateData scroll_state_data; switch (event.GetType()) { case WebInputEvent::kGestureScrollBegin: - scroll_state_data.position_x = event.x; - scroll_state_data.position_y = event.y; + scroll_state_data.position_x = event.PositionInWidget().x; + scroll_state_data.position_y = event.PositionInWidget().y; scroll_state_data.delta_x_hint = -event.data.scroll_begin.delta_x_hint; scroll_state_data.delta_y_hint = -event.data.scroll_begin.delta_y_hint; scroll_state_data.is_beginning = true; @@ -214,13 +214,13 @@ if (has_ongoing_compositor_scroll_fling_pinch_) { const auto& gesture_event = ToWebGestureEvent(event_with_callback->event()); bool is_from_set_non_blocking_touch = - gesture_event.source_device == blink::kWebGestureDeviceTouchscreen && + gesture_event.SourceDevice() == blink::kWebGestureDeviceTouchscreen && gesture_event.is_source_touch_event_set_non_blocking; bool is_scroll_end_from_wheel = - gesture_event.source_device == blink::kWebGestureDeviceTouchpad && + gesture_event.SourceDevice() == blink::kWebGestureDeviceTouchpad && gesture_event.GetType() == blink::WebGestureEvent::kGestureScrollEnd; bool scroll_update_has_blocking_wheel_source = - gesture_event.source_device == blink::kWebGestureDeviceTouchpad && + gesture_event.SourceDevice() == blink::kWebGestureDeviceTouchpad && gesture_event.GetType() == blink::WebGestureEvent::kGestureScrollUpdate && (!async_wheel_events_enabled_ || is_first_gesture_scroll_update_); @@ -394,7 +394,7 @@ DCHECK(!gesture_pinch_on_impl_thread_); const WebGestureEvent& gesture_event = static_cast<const WebGestureEvent&>(event); - if (gesture_event.source_device == blink::kWebGestureDeviceTouchpad && + if (gesture_event.SourceDevice() == blink::kWebGestureDeviceTouchpad && input_handler_->GetEventListenerProperties( cc::EventListenerClass::kMouseWheel) != cc::EventListenerProperties::kNone) { @@ -412,8 +412,8 @@ const WebGestureEvent& gesture_event = static_cast<const WebGestureEvent&>(event); input_handler_->PinchGestureEnd( - gfx::Point(gesture_event.x, gesture_event.y), - gesture_event.source_device == blink::kWebGestureDeviceTouchpad); + gfx::ToFlooredPoint(gesture_event.PositionInWidget()), + gesture_event.SourceDevice() == blink::kWebGestureDeviceTouchpad); return DID_HANDLE; } else { return DID_NOT_HANDLE; @@ -427,7 +427,7 @@ return DROP_EVENT; input_handler_->PinchGestureUpdate( gesture_event.data.pinch_update.scale, - gfx::Point(gesture_event.x, gesture_event.y)); + gfx::ToFlooredPoint(gesture_event.PositionInWidget())); return DID_HANDLE; } else { return DID_NOT_HANDLE; @@ -686,19 +686,19 @@ cc::MainThreadScrollingReason::kContinuingMainThreadScroll; } else if (gesture_event.data.scroll_begin.target_viewport) { scroll_status = input_handler_->RootScrollBegin( - &scroll_state, GestureScrollInputType(gesture_event.source_device)); + &scroll_state, GestureScrollInputType(gesture_event.SourceDevice())); } else if (ShouldAnimate(gesture_event.data.scroll_begin.delta_hint_units != blink::WebGestureEvent::ScrollUnits::kPixels)) { DCHECK(!scroll_state.is_in_inertial_phase()); scroll_status = input_handler_->ScrollAnimatedBegin(&scroll_state); } else { scroll_status = input_handler_->ScrollBegin( - &scroll_state, GestureScrollInputType(gesture_event.source_device)); + &scroll_state, GestureScrollInputType(gesture_event.SourceDevice())); } - RecordMainThreadScrollingReasons(gesture_event.source_device, + RecordMainThreadScrollingReasons(gesture_event.SourceDevice(), scroll_status.main_thread_scrolling_reasons); - RecordScrollingThreadStatus(gesture_event.source_device, + RecordScrollingThreadStatus(gesture_event.SourceDevice(), scroll_status.main_thread_scrolling_reasons); InputHandlerProxy::EventDisposition result = DID_NOT_HANDLE; @@ -750,7 +750,7 @@ return DID_NOT_HANDLE; cc::ScrollState scroll_state = CreateScrollStateForGesture(gesture_event); - gfx::Point scroll_point(gesture_event.x, gesture_event.y); + gfx::PointF scroll_point(gesture_event.PositionInWidget()); if (ShouldAnimate(gesture_event.data.scroll_update.delta_units != blink::WebGestureEvent::ScrollUnits::kPixels)) { @@ -759,7 +759,9 @@ base::TimeTicks() + base::TimeDelta::FromSecondsD(gesture_event.TimeStampSeconds()); base::TimeDelta delay = base::TimeTicks::Now() - event_time; - switch (input_handler_->ScrollAnimated(scroll_point, scroll_delta, delay) + switch (input_handler_ + ->ScrollAnimated(gfx::ToFlooredPoint(scroll_point), + scroll_delta, delay) .thread) { case cc::InputHandler::SCROLL_ON_IMPL_THREAD: return DID_HANDLE; @@ -779,9 +781,9 @@ if (!scroll_result.did_scroll && input_handler_->ScrollingShouldSwitchtoMainThread() && - ((gesture_event.source_device == blink::kWebGestureDeviceTouchpad && + ((gesture_event.SourceDevice() == blink::kWebGestureDeviceTouchpad && touchpad_and_wheel_scroll_latching_enabled_) || - gesture_event.source_device == blink::kWebGestureDeviceTouchscreen)) { + gesture_event.SourceDevice() == blink::kWebGestureDeviceTouchscreen)) { gesture_scroll_on_impl_thread_ = false; client_->GenerateScrollBeginAndSendToMainThread(gesture_event); @@ -829,7 +831,7 @@ InputHandlerProxy::EventDisposition InputHandlerProxy::HandleGestureFlingStart( const WebGestureEvent& gesture_event) { // Touchpad flings are handled on browser. - DCHECK(!(gesture_event.source_device == blink::kWebGestureDeviceTouchpad)); + DCHECK(!(gesture_event.SourceDevice() == blink::kWebGestureDeviceTouchpad)); #ifndef NDEBUG expect_scroll_update_end_ = false; #endif @@ -841,7 +843,7 @@ cc::InputHandler::ScrollStatus scroll_status; scroll_status.main_thread_scrolling_reasons = cc::MainThreadScrollingReason::kNotScrollingOnMain; - switch (gesture_event.source_device) { + switch (gesture_event.SourceDevice()) { case blink::kWebGestureDeviceTouchscreen: case blink::kWebGestureDeviceSyntheticAutoscroll: if (!gesture_scroll_on_impl_thread_) { @@ -1139,7 +1141,7 @@ } void InputHandlerProxy::HandleOverscroll( - const gfx::Point& causal_event_viewport_point, + const gfx::PointF& causal_event_viewport_point, const cc::InputHandlerScrollResult& scroll_result, bool bundle_overscroll_params_with_ack) { DCHECK(client_); @@ -1173,7 +1175,7 @@ current_overscroll_params_->current_fling_velocity = ToClientScrollIncrement(current_fling_velocity_); current_overscroll_params_->causal_event_viewport_point = - gfx::PointF(causal_event_viewport_point); + causal_event_viewport_point; current_overscroll_params_->overscroll_behavior = scroll_result.overscroll_behavior; return; @@ -1182,7 +1184,7 @@ client_->DidOverscroll(scroll_result.accumulated_root_overscroll, scroll_result.unused_scroll_delta, ToClientScrollIncrement(current_fling_velocity_), - gfx::PointF(causal_event_viewport_point), + causal_event_viewport_point, scroll_result.overscroll_behavior); } @@ -1345,21 +1347,20 @@ DCHECK_EQ(WebInputEvent::kGestureFlingStart, fling_start_event.GetType()); // When wheel scroll latching is enabled touchpad flings are handled on // browser. - DCHECK(fling_start_event.source_device != blink::kWebGestureDeviceTouchpad || + DCHECK(fling_start_event.SourceDevice() != blink::kWebGestureDeviceTouchpad || !touchpad_and_wheel_scroll_latching_enabled_); current_fling_velocity_ = velocity; fling_curve_ = client_->CreateFlingAnimationCurve( - fling_start_event.source_device, + fling_start_event.SourceDevice(), WebFloatPoint(velocity.x(), velocity.y()), blink::WebSize()); disallow_horizontal_fling_scroll_ = !velocity.x(); disallow_vertical_fling_scroll_ = !velocity.y(); fling_parameters_.start_time = fling_start_event.TimeStampSeconds(); fling_parameters_.delta = WebFloatPoint(velocity.x(), velocity.y()); - fling_parameters_.point = WebPoint(fling_start_event.x, fling_start_event.y); - fling_parameters_.global_point = - WebPoint(fling_start_event.global_x, fling_start_event.global_y); + fling_parameters_.point = fling_start_event.PositionInWidget(); + fling_parameters_.global_point = fling_start_event.PositionInScreen(); fling_parameters_.modifiers = fling_start_event.GetModifiers(); - fling_parameters_.source_device = fling_start_event.source_device; + fling_parameters_.source_device = fling_start_event.SourceDevice(); } } // namespace ui
diff --git a/ui/events/blink/input_handler_proxy.h b/ui/events/blink/input_handler_proxy.h index feeea9d..9c1961c 100644 --- a/ui/events/blink/input_handler_proxy.h +++ b/ui/events/blink/input_handler_proxy.h
@@ -164,7 +164,7 @@ // Used to send overscroll messages to the browser. // |bundle_overscroll_params_with_ack| means overscroll message should be // bundled with triggering event response, and won't fire |DidOverscroll|. - void HandleOverscroll(const gfx::Point& causal_event_viewport_point, + void HandleOverscroll(const gfx::PointF& causal_event_viewport_point, const cc::InputHandlerScrollResult& scroll_result, bool bundle_overscroll_params_with_ack);
diff --git a/ui/events/blink/input_handler_proxy_unittest.cc b/ui/events/blink/input_handler_proxy_unittest.cc index 2f1830b4..3e5a074f 100644 --- a/ui/events/blink/input_handler_proxy_unittest.cc +++ b/ui/events/blink/input_handler_proxy_unittest.cc
@@ -85,27 +85,25 @@ WebGestureEvent CreateFling(base::TimeTicks timestamp, WebGestureDevice source_device, WebFloatPoint velocity, - WebPoint point, - WebPoint global_point, + WebFloatPoint point, + WebFloatPoint global_point, int modifiers) { WebGestureEvent fling(WebInputEvent::kGestureFlingStart, modifiers, - (timestamp - base::TimeTicks()).InSecondsF()); + (timestamp - base::TimeTicks()).InSecondsF(), + source_device); // Touchpad fling is handled on broswer. DCHECK(source_device != blink::kWebGestureDeviceTouchpad); - fling.source_device = source_device; fling.data.fling_start.velocity_x = velocity.x; fling.data.fling_start.velocity_y = velocity.y; - fling.x = point.x; - fling.y = point.y; - fling.global_x = global_point.x; - fling.global_y = global_point.y; + fling.SetPositionInWidget(point); + fling.SetPositionInScreen(global_point); return fling; } WebGestureEvent CreateFling(WebGestureDevice source_device, WebFloatPoint velocity, - WebPoint point, - WebPoint global_point, + WebFloatPoint point, + WebFloatPoint global_point, int modifiers) { return CreateFling(base::TimeTicks(), source_device, velocity, point, global_point, modifiers); @@ -118,8 +116,8 @@ int x = 0, int y = 0) { WebGestureEvent gesture(type, WebInputEvent::kNoModifiers, - WebInputEvent::GetStaticTimeStampForTests()); - gesture.source_device = source_device; + WebInputEvent::GetStaticTimeStampForTests(), + source_device); if (type == WebInputEvent::kGestureScrollUpdate) { gesture.data.scroll_update.delta_y = delta_y_or_scale; } else if (type == WebInputEvent::kGestureFlingStart) { @@ -128,8 +126,7 @@ gesture.data.fling_start.velocity_y = delta_y_or_scale; } else if (type == WebInputEvent::kGesturePinchUpdate) { gesture.data.pinch_update.scale = delta_y_or_scale; - gesture.x = x; - gesture.y = y; + gesture.SetPositionInWidget(gfx::PointF(x, y)); } return WebInputEventTraits::Clone(gesture); } @@ -393,7 +390,7 @@ mock_input_handler_.set_is_scrolling_root(synchronous_root_scroll_); // Set a default device so tests don't always have to set this. - gesture_.source_device = blink::kWebGestureDeviceTouchpad; + gesture_.SetSourceDevice(blink::kWebGestureDeviceTouchpad); } virtual ~InputHandlerProxyTest() { input_handler_.reset(); } @@ -436,14 +433,14 @@ void StartFling(base::TimeTicks timestamp, WebGestureDevice source_device, WebFloatPoint velocity, - WebPoint position) { + WebFloatPoint position) { expected_disposition_ = InputHandlerProxy::DID_HANDLE; VERIFY_AND_RESET_MOCKS(); EXPECT_CALL(mock_input_handler_, ScrollBegin(testing::_, testing::_)) .WillOnce(testing::Return(kImplThreadScrollState)); gesture_.SetType(WebInputEvent::kGestureScrollBegin); - gesture_.source_device = source_device; + gesture_.SetSourceDevice(source_device); EXPECT_EQ(expected_disposition_, input_handler_->HandleInputEvent(gesture_)); @@ -837,8 +834,7 @@ gesture_.SetType(WebInputEvent::kGesturePinchUpdate); gesture_.data.pinch_update.scale = 1.5; - gesture_.x = 7; - gesture_.y = 13; + gesture_.SetPositionInWidget(gfx::PointF(7, 13)); EXPECT_CALL(mock_input_handler_, PinchGestureUpdate(1.5, gfx::Point(7, 13))); EXPECT_EQ(expected_disposition_, input_handler_->HandleInputEvent(gesture_)); @@ -847,8 +843,7 @@ gesture_.SetType(WebInputEvent::kGesturePinchUpdate); gesture_.data.pinch_update.scale = 0.5; gesture_.data.pinch_update.zoom_disabled = true; - gesture_.x = 9; - gesture_.y = 6; + gesture_.SetPositionInWidget(gfx::PointF(9, 6)); EXPECT_EQ(InputHandlerProxy::DROP_EVENT, input_handler_->HandleInputEvent(gesture_)); gesture_.data.pinch_update.zoom_disabled = false; @@ -857,8 +852,7 @@ gesture_.SetType(WebInputEvent::kGesturePinchUpdate); gesture_.data.pinch_update.scale = 0.5; - gesture_.x = 9; - gesture_.y = 6; + gesture_.SetPositionInWidget(gfx::PointF(9, 6)); EXPECT_CALL(mock_input_handler_, PinchGestureUpdate(.5, gfx::Point(9, 6))); EXPECT_EQ(expected_disposition_, input_handler_->HandleInputEvent(gesture_)); @@ -886,16 +880,14 @@ gesture_.SetType(WebInputEvent::kGesturePinchUpdate); gesture_.data.pinch_update.scale = 1.5; - gesture_.x = 7; - gesture_.y = 13; + gesture_.SetPositionInWidget(gfx::PointF(7, 13)); EXPECT_EQ(expected_disposition_, input_handler_->HandleInputEvent(gesture_)); VERIFY_AND_RESET_MOCKS(); gesture_.SetType(WebInputEvent::kGesturePinchUpdate); gesture_.data.pinch_update.scale = 0.5; - gesture_.x = 9; - gesture_.y = 6; + gesture_.SetPositionInWidget(gfx::PointF(9, 6)); EXPECT_EQ(expected_disposition_, input_handler_->HandleInputEvent(gesture_)); VERIFY_AND_RESET_MOCKS(); @@ -938,8 +930,7 @@ gesture_.SetType(WebInputEvent::kGesturePinchUpdate); gesture_.data.pinch_update.scale = 1.5; - gesture_.x = 7; - gesture_.y = 13; + gesture_.SetPositionInWidget(gfx::PointF(7, 13)); EXPECT_CALL(mock_input_handler_, PinchGestureUpdate(1.5, gfx::Point(7, 13))); EXPECT_EQ(expected_disposition_, input_handler_->HandleInputEvent(gesture_)); @@ -958,8 +949,7 @@ gesture_.SetType(WebInputEvent::kGesturePinchUpdate); gesture_.data.pinch_update.scale = 0.5; - gesture_.x = 9; - gesture_.y = 6; + gesture_.SetPositionInWidget(gfx::PointF(9, 6)); EXPECT_CALL(mock_input_handler_, PinchGestureUpdate(.5, gfx::Point(9, 6))); EXPECT_EQ(expected_disposition_, input_handler_->HandleInputEvent(gesture_)); @@ -1030,11 +1020,11 @@ VERIFY_AND_RESET_MOCKS(); } TEST_P(InputHandlerProxyTest, WheelScrollHandlingSwitchedToMainThread) { - gesture_.source_device = blink::kWebGestureDeviceTouchpad; + gesture_.SetSourceDevice(blink::kWebGestureDeviceTouchpad); ScrollHandlingSwitchedToMainThread(); } TEST_P(InputHandlerProxyTest, TouchScrollHandlingSwitchedToMainThread) { - gesture_.source_device = blink::kWebGestureDeviceTouchscreen; + gesture_.SetSourceDevice(blink::kWebGestureDeviceTouchscreen); ScrollHandlingSwitchedToMainThread(); } @@ -1046,7 +1036,7 @@ EXPECT_CALL(mock_input_handler_, ScrollBegin(testing::_, testing::_)) .WillOnce(testing::Return(kImplThreadScrollState)); gesture_.SetType(WebInputEvent::kGestureScrollBegin); - gesture_.source_device = blink::kWebGestureDeviceTouchscreen; + gesture_.SetSourceDevice(blink::kWebGestureDeviceTouchscreen); EXPECT_EQ(expected_disposition_, input_handler_->HandleInputEvent(gesture_)); VERIFY_AND_RESET_MOCKS(); @@ -1057,7 +1047,6 @@ gesture_.SetType(WebInputEvent::kGestureFlingStart); gesture_.data.fling_start.velocity_x = 10; - gesture_.source_device = blink::kWebGestureDeviceTouchscreen; EXPECT_EQ(expected_disposition_, input_handler_->HandleInputEvent(gesture_)); VERIFY_AND_RESET_MOCKS(); @@ -1066,7 +1055,7 @@ // Verify that a GestureFlingCancel during an animation cancels it. gesture_.SetType(WebInputEvent::kGestureFlingCancel); - gesture_.source_device = blink::kWebGestureDeviceTouchscreen; + gesture_.SetSourceDevice(blink::kWebGestureDeviceTouchscreen); EXPECT_EQ(expected_disposition_, input_handler_->HandleInputEvent(gesture_)); VERIFY_AND_RESET_MOCKS(); @@ -1088,7 +1077,7 @@ EXPECT_CALL(mock_input_handler_, FlingScrollBegin()).Times(0); gesture_.SetType(WebInputEvent::kGestureFlingStart); - gesture_.source_device = blink::kWebGestureDeviceTouchscreen; + gesture_.SetSourceDevice(blink::kWebGestureDeviceTouchscreen); EXPECT_EQ(expected_disposition_, input_handler_->HandleInputEvent(gesture_)); VERIFY_AND_RESET_MOCKS(); @@ -1096,7 +1085,7 @@ // Even if we didn't start a fling ourselves, we still need to send the cancel // event to the widget. gesture_.SetType(WebInputEvent::kGestureFlingCancel); - gesture_.source_device = blink::kWebGestureDeviceTouchscreen; + gesture_.SetSourceDevice(blink::kWebGestureDeviceTouchscreen); EXPECT_EQ(expected_disposition_, input_handler_->HandleInputEvent(gesture_)); } @@ -1108,7 +1097,7 @@ .WillOnce(testing::Return(kImplThreadScrollState)); gesture_.SetType(WebInputEvent::kGestureScrollBegin); - gesture_.source_device = blink::kWebGestureDeviceTouchscreen; + gesture_.SetSourceDevice(blink::kWebGestureDeviceTouchscreen); EXPECT_EQ(expected_disposition_, input_handler_->HandleInputEvent(gesture_)); expected_disposition_ = InputHandlerProxy::DROP_EVENT; @@ -1120,7 +1109,7 @@ .WillOnce(testing::Return(kScrollIgnoredScrollState)); gesture_.SetType(WebInputEvent::kGestureFlingStart); - gesture_.source_device = blink::kWebGestureDeviceTouchscreen; + gesture_.SetSourceDevice(blink::kWebGestureDeviceTouchscreen); EXPECT_EQ(expected_disposition_, input_handler_->HandleInputEvent(gesture_)); VERIFY_AND_RESET_MOCKS(); @@ -1131,7 +1120,7 @@ EXPECT_CALL(mock_input_handler_, ScrollBegin(testing::_, testing::_)) .WillOnce(testing::Return(kImplThreadScrollState)); gesture_.SetType(WebInputEvent::kGestureScrollBegin); - gesture_.source_device = blink::kWebGestureDeviceTouchscreen; + gesture_.SetSourceDevice(blink::kWebGestureDeviceTouchscreen); EXPECT_EQ(expected_disposition_, input_handler_->HandleInputEvent(gesture_)); VERIFY_AND_RESET_MOCKS(); @@ -1146,7 +1135,7 @@ .WillOnce(testing::Return(kImplThreadScrollState)); gesture_.SetType(WebInputEvent::kGestureScrollBegin); - gesture_.source_device = blink::kWebGestureDeviceTouchscreen; + gesture_.SetSourceDevice(blink::kWebGestureDeviceTouchscreen); EXPECT_EQ(expected_disposition_, input_handler_->HandleInputEvent(gesture_)); VERIFY_AND_RESET_MOCKS(); @@ -1154,8 +1143,8 @@ // On the fling start, we should schedule an animation but not actually start // scrolling. WebFloatPoint fling_delta = WebFloatPoint(100, 0); - WebPoint fling_point = WebPoint(7, 13); - WebPoint fling_global_point = WebPoint(17, 23); + WebFloatPoint fling_point = WebFloatPoint(7, 13); + WebFloatPoint fling_global_point = WebFloatPoint(17, 23); // Note that for touchscreen the control modifier is not special. int modifiers = WebInputEvent::kControlKey; gesture_ = CreateFling(blink::kWebGestureDeviceTouchscreen, fling_delta, @@ -1204,7 +1193,7 @@ .WillOnce(testing::Return(kImplThreadScrollState)); gesture_.SetType(WebInputEvent::kGestureScrollBegin); - gesture_.source_device = blink::kWebGestureDeviceTouchscreen; + gesture_.SetSourceDevice(blink::kWebGestureDeviceTouchscreen); EXPECT_EQ(expected_disposition_, input_handler_->HandleInputEvent(gesture_)); VERIFY_AND_RESET_MOCKS(); @@ -1214,8 +1203,8 @@ base::TimeDelta dt = base::TimeDelta::FromMilliseconds(10); base::TimeTicks time = base::TimeTicks() + dt; WebFloatPoint fling_delta = WebFloatPoint(100, 0); - WebPoint fling_point = WebPoint(7, 13); - WebPoint fling_global_point = WebPoint(17, 23); + WebFloatPoint fling_point = WebFloatPoint(7, 13); + WebFloatPoint fling_global_point = WebFloatPoint(17, 23); int modifiers = WebInputEvent::kControlKey; gesture_ = CreateFling(time, blink::kWebGestureDeviceTouchscreen, fling_delta, fling_point, fling_global_point, modifiers); @@ -1256,7 +1245,7 @@ .WillOnce(testing::Return(kImplThreadScrollState)); gesture_.SetType(WebInputEvent::kGestureScrollBegin); - gesture_.source_device = blink::kWebGestureDeviceTouchscreen; + gesture_.SetSourceDevice(blink::kWebGestureDeviceTouchscreen); EXPECT_EQ(expected_disposition_, input_handler_->HandleInputEvent(gesture_)); VERIFY_AND_RESET_MOCKS(); @@ -1264,19 +1253,18 @@ // On the fling start, we should schedule an animation but not actually start // scrolling. base::TimeDelta start_time_offset = base::TimeDelta::FromMilliseconds(10); - gesture_.SetType(WebInputEvent::kGestureFlingStart); + gesture_ = WebGestureEvent( + WebInputEvent::kGestureFlingStart, WebInputEvent::kControlKey, + start_time_offset.InSecondsF(), blink::kWebGestureDeviceTouchscreen); WebFloatPoint fling_delta = WebFloatPoint(100, 0); - WebPoint fling_point = WebPoint(7, 13); - WebPoint fling_global_point = WebPoint(17, 23); + WebFloatPoint fling_point = WebFloatPoint(7, 13); + WebFloatPoint fling_global_point = WebFloatPoint(17, 23); int modifiers = WebInputEvent::kControlKey; gesture_.SetTimeStampSeconds(start_time_offset.InSecondsF()); gesture_.data.fling_start.velocity_x = fling_delta.x; gesture_.data.fling_start.velocity_y = fling_delta.y; - gesture_.source_device = blink::kWebGestureDeviceTouchscreen; - gesture_.x = fling_point.x; - gesture_.y = fling_point.y; - gesture_.global_x = fling_global_point.x; - gesture_.global_y = fling_global_point.y; + gesture_.SetPositionInWidget(fling_point); + gesture_.SetPositionInScreen(fling_global_point); gesture_.SetModifiers(modifiers); EXPECT_SET_NEEDS_ANIMATE_INPUT(1); EXPECT_CALL(mock_input_handler_, FlingScrollBegin()) @@ -1333,8 +1321,8 @@ // On the fling start, we should schedule an animation but not actually start // scrolling. WebFloatPoint fling_delta = WebFloatPoint(100, 0); - WebPoint fling_point = WebPoint(7, 13); - WebPoint fling_global_point = WebPoint(17, 23); + WebFloatPoint fling_point = WebFloatPoint(7, 13); + WebFloatPoint fling_global_point = WebFloatPoint(17, 23); int modifiers = WebInputEvent::kControlKey | WebInputEvent::kAltKey; gesture_ = CreateFling(blink::kWebGestureDeviceTouchscreen, fling_delta, fling_point, fling_global_point, modifiers); @@ -1403,8 +1391,8 @@ // On the fling start, we should schedule an animation but not actually start // scrolling. WebFloatPoint fling_delta = WebFloatPoint(100, 0); - WebPoint fling_point = WebPoint(7, 13); - WebPoint fling_global_point = WebPoint(17, 23); + WebFloatPoint fling_point = WebFloatPoint(7, 13); + WebFloatPoint fling_global_point = WebFloatPoint(17, 23); int modifiers = WebInputEvent::kControlKey | WebInputEvent::kAltKey; gesture_ = CreateFling(blink::kWebGestureDeviceTouchscreen, fling_delta, fling_point, fling_global_point, modifiers); @@ -1435,7 +1423,7 @@ } TEST_P(InputHandlerProxyTest, GestureFlingStopsAtContentEdgeTouchscreen) { - gesture_.source_device = blink::kWebGestureDeviceTouchscreen; + gesture_.SetSourceDevice(blink::kWebGestureDeviceTouchscreen); // We shouldn't send any events to the widget for this gesture. expected_disposition_ = InputHandlerProxy::DID_HANDLE; VERIFY_AND_RESET_MOCKS(); @@ -1521,7 +1509,7 @@ .WillOnce(testing::Return(kImplThreadScrollState)); gesture_.SetType(WebInputEvent::kGestureScrollBegin); - gesture_.source_device = blink::kWebGestureDeviceTouchscreen; + gesture_.SetSourceDevice(blink::kWebGestureDeviceTouchscreen); EXPECT_EQ(expected_disposition_, input_handler_->HandleInputEvent(gesture_)); VERIFY_AND_RESET_MOCKS(); @@ -1531,8 +1519,8 @@ base::TimeDelta dt = base::TimeDelta::FromMilliseconds(10); base::TimeTicks time = base::TimeTicks() + dt; WebFloatPoint fling_delta = WebFloatPoint(100, 0); - WebPoint fling_point = WebPoint(7, 13); - WebPoint fling_global_point = WebPoint(17, 23); + WebFloatPoint fling_point = WebFloatPoint(7, 13); + WebFloatPoint fling_global_point = WebFloatPoint(17, 23); int modifiers = WebInputEvent::kControlKey; gesture_ = CreateFling(time, blink::kWebGestureDeviceTouchscreen, fling_delta, fling_point, fling_global_point, modifiers); @@ -1597,7 +1585,7 @@ EXPECT_CALL(mock_input_handler_, ScrollBegin(testing::_, testing::_)) .WillOnce(testing::Return(kImplThreadScrollState)); gesture_.SetType(WebInputEvent::kGestureScrollBegin); - gesture_.source_device = blink::kWebGestureDeviceTouchscreen; + gesture_.SetSourceDevice(blink::kWebGestureDeviceTouchscreen); EXPECT_EQ(expected_disposition_, input_handler_->HandleInputEvent(gesture_)); VERIFY_AND_RESET_MOCKS(); @@ -1997,7 +1985,7 @@ EXPECT_CALL(mock_input_handler_, ScrollBegin(testing::_, testing::_)) .WillOnce(testing::Return(kImplThreadScrollState)); gesture_.SetType(WebInputEvent::kGestureScrollBegin); - gesture_.source_device = blink::kWebGestureDeviceTouchscreen; + gesture_.SetSourceDevice(blink::kWebGestureDeviceTouchscreen); EXPECT_EQ(InputHandlerProxy::DID_HANDLE, input_handler_->HandleInputEvent(gesture_)); EXPECT_TRUE(input_handler_->gesture_scroll_on_impl_thread_for_testing()); @@ -2052,7 +2040,7 @@ .WillOnce(testing::Return(kImplThreadScrollState)); gesture_.SetType(WebInputEvent::kGestureScrollBegin); - gesture_.source_device = blink::kWebGestureDeviceTouchscreen; + gesture_.SetSourceDevice(blink::kWebGestureDeviceTouchscreen); EXPECT_EQ(expected_disposition_, input_handler_->HandleInputEvent(gesture_)); EXPECT_TRUE(input_handler_->gesture_scroll_on_impl_thread_for_testing()); VERIFY_AND_RESET_MOCKS(); @@ -2117,7 +2105,7 @@ .WillOnce(testing::Return(kImplThreadScrollState)); gesture_.SetType(WebInputEvent::kGestureScrollBegin); - gesture_.source_device = blink::kWebGestureDeviceTouchscreen; + gesture_.SetSourceDevice(blink::kWebGestureDeviceTouchscreen); EXPECT_EQ(expected_disposition_, input_handler_->HandleInputEvent(gesture_)); VERIFY_AND_RESET_MOCKS(); @@ -2127,8 +2115,8 @@ base::TimeDelta dt = base::TimeDelta::FromMilliseconds(10); base::TimeTicks time = base::TimeTicks() + dt; WebFloatPoint fling_delta = WebFloatPoint(100, 0); - WebPoint fling_point = WebPoint(7, 13); - WebPoint fling_global_point = WebPoint(17, 23); + WebFloatPoint fling_point = WebFloatPoint(7, 13); + WebFloatPoint fling_global_point = WebFloatPoint(17, 23); int modifiers = WebInputEvent::kControlKey; gesture_ = CreateFling(time, blink::kWebGestureDeviceTouchscreen, fling_delta, fling_point, fling_global_point, modifiers); @@ -2173,7 +2161,7 @@ base::TimeTicks time = base::TimeTicks() + dt; base::TimeTicks last_animate_time = time; WebFloatPoint fling_delta = WebFloatPoint(1000, 0); - WebPoint fling_point = WebPoint(7, 13); + WebFloatPoint fling_point = WebFloatPoint(7, 13); StartFling(time, blink::kWebGestureDeviceTouchscreen, fling_delta, fling_point); @@ -2291,7 +2279,7 @@ base::TimeDelta dt = base::TimeDelta::FromMilliseconds(10); base::TimeTicks time = base::TimeTicks() + dt; WebFloatPoint fling_delta = WebFloatPoint(1000, 0); - WebPoint fling_point = WebPoint(7, 13); + WebFloatPoint fling_point = WebFloatPoint(7, 13); StartFling(time, blink::kWebGestureDeviceTouchscreen, fling_delta, fling_point); @@ -2324,7 +2312,7 @@ base::TimeDelta dt = base::TimeDelta::FromMilliseconds(10); base::TimeTicks time = base::TimeTicks() + dt; WebFloatPoint fling_delta = WebFloatPoint(1000, 0); - WebPoint fling_point = WebPoint(7, 13); + WebFloatPoint fling_point = WebFloatPoint(7, 13); StartFling(time, blink::kWebGestureDeviceTouchscreen, fling_delta, fling_point); @@ -2367,7 +2355,7 @@ base::TimeDelta dt = base::TimeDelta::FromMilliseconds(10); base::TimeTicks time = base::TimeTicks() + dt; WebFloatPoint fling_delta = WebFloatPoint(1000, 0); - WebPoint fling_point = WebPoint(7, 13); + WebFloatPoint fling_point = WebFloatPoint(7, 13); StartFling(time, blink::kWebGestureDeviceTouchscreen, fling_delta, fling_point); @@ -2404,7 +2392,7 @@ base::TimeDelta dt = base::TimeDelta::FromMilliseconds(10); base::TimeTicks time = base::TimeTicks() + dt; WebFloatPoint fling_delta = WebFloatPoint(1000, 0); - WebPoint fling_point = WebPoint(7, 13); + WebFloatPoint fling_point = WebFloatPoint(7, 13); StartFling(time, blink::kWebGestureDeviceTouchscreen, fling_delta, fling_point); @@ -2444,7 +2432,7 @@ base::TimeDelta dt = base::TimeDelta::FromMilliseconds(10); base::TimeTicks time = base::TimeTicks() + dt; WebFloatPoint fling_delta = WebFloatPoint(1000, 0); - WebPoint fling_point = WebPoint(7, 13); + WebFloatPoint fling_point = WebFloatPoint(7, 13); StartFling(time, blink::kWebGestureDeviceTouchscreen, fling_delta, fling_point); @@ -2479,7 +2467,7 @@ base::TimeDelta dt = base::TimeDelta::FromMilliseconds(10); base::TimeTicks time = base::TimeTicks() + dt; WebFloatPoint fling_delta = WebFloatPoint(1000, 0); - WebPoint fling_point = WebPoint(7, 13); + WebFloatPoint fling_point = WebFloatPoint(7, 13); StartFling(time, blink::kWebGestureDeviceTouchscreen, fling_delta, fling_point); @@ -2500,7 +2488,7 @@ base::TimeTicks time = base::TimeTicks() + dt; base::TimeTicks last_animate_time = time; WebFloatPoint fling_delta = WebFloatPoint(1000, 0); - WebPoint fling_point = WebPoint(7, 13); + WebFloatPoint fling_point = WebFloatPoint(7, 13); StartFling(time, blink::kWebGestureDeviceTouchscreen, fling_delta, fling_point); @@ -2561,7 +2549,7 @@ } TEST_P(InputHandlerProxyTest, DidReceiveInputEvent_ForFlingTouchscreen) { - gesture_.source_device = blink::kWebGestureDeviceTouchscreen; + gesture_.SetSourceDevice(blink::kWebGestureDeviceTouchscreen); testing::StrictMock<MockInputHandlerProxyClientWithDidAnimateForInput> mock_client; input_handler_.reset( @@ -2580,7 +2568,7 @@ EXPECT_CALL(mock_input_handler_, ScrollBegin(testing::_, testing::_)) .WillOnce(testing::Return(kImplThreadScrollState)); gesture_.SetType(WebInputEvent::kGestureScrollBegin); - gesture_.source_device = blink::kWebGestureDeviceTouchscreen; + gesture_.SetSourceDevice(blink::kWebGestureDeviceTouchscreen); EXPECT_EQ(expected_disposition_, input_handler_->HandleInputEvent(gesture_)); VERIFY_AND_RESET_MOCKS(); @@ -2712,13 +2700,15 @@ touch_start.touches[0] = CreateWebTouchPoint(WebTouchPoint::kStatePressed, 10, 10); - WebGestureEvent gesture_scroll_begin; - gesture_scroll_begin.SetType(WebInputEvent::kGestureScrollBegin); - gesture_scroll_begin.source_device = blink::kWebGestureDeviceTouchscreen; + WebGestureEvent gesture_scroll_begin( + WebInputEvent::kGestureScrollBegin, WebInputEvent::kNoModifiers, + WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchscreen); - WebGestureEvent gesture_scroll_end; - gesture_scroll_end.SetType(WebInputEvent::kGestureScrollEnd); - gesture_scroll_end.source_device = blink::kWebGestureDeviceTouchscreen; + WebGestureEvent gesture_scroll_end( + WebInputEvent::kGestureScrollEnd, WebInputEvent::kNoModifiers, + WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchscreen); // Touch start with passive event listener. EXPECT_CALL( @@ -2816,13 +2806,15 @@ WebInputEvent::kControlKey, WebInputEvent::GetStaticTimeStampForTests()); - WebGestureEvent gesture_scroll_begin; - gesture_scroll_begin.SetType(WebInputEvent::kGestureScrollBegin); - gesture_scroll_begin.source_device = blink::kWebGestureDeviceTouchpad; + WebGestureEvent gesture_scroll_begin( + WebInputEvent::kGestureScrollBegin, WebInputEvent::kNoModifiers, + WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchpad); - WebGestureEvent gesture_scroll_end; - gesture_scroll_end.SetType(WebInputEvent::kGestureScrollEnd); - gesture_scroll_end.source_device = blink::kWebGestureDeviceTouchpad; + WebGestureEvent gesture_scroll_end( + WebInputEvent::kGestureScrollEnd, WebInputEvent::kNoModifiers, + WebInputEvent::GetStaticTimeStampForTests(), + blink::kWebGestureDeviceTouchpad); // Wheel event with passive event listener. EXPECT_CALL(mock_input_handler_,
diff --git a/ui/events/blink/input_scroll_elasticity_controller_unittest.cc b/ui/events/blink/input_scroll_elasticity_controller_unittest.cc index 777b5c93..af4f1c3 100644 --- a/ui/events/blink/input_scroll_elasticity_controller_unittest.cc +++ b/ui/events/blink/input_scroll_elasticity_controller_unittest.cc
@@ -93,8 +93,8 @@ blink::WebGestureEvent event( blink::WebInputEvent::kGestureScrollBegin, blink::WebInputEvent::kNoModifiers, - (current_time_ - base::TimeTicks()).InSecondsF()); - event.source_device = blink::kWebGestureDeviceTouchpad; + (current_time_ - base::TimeTicks()).InSecondsF(), + blink::kWebGestureDeviceTouchpad); event.data.scroll_begin.inertial_phase = static_cast<blink::WebGestureEvent::InertialPhaseState>(inertialPhase); @@ -113,8 +113,8 @@ blink::WebGestureEvent event( blink::WebInputEvent::kGestureScrollUpdate, blink::WebInputEvent::kNoModifiers, - (current_time_ - base::TimeTicks()).InSecondsF()); - event.source_device = blink::kWebGestureDeviceTouchpad; + (current_time_ - base::TimeTicks()).InSecondsF(), + blink::kWebGestureDeviceTouchpad); event.data.scroll_update.inertial_phase = static_cast<blink::WebGestureEvent::InertialPhaseState>(inertialPhase); event.data.scroll_update.delta_x = -event_delta.x(); @@ -134,8 +134,8 @@ blink::WebGestureEvent event( blink::WebInputEvent::kGestureScrollEnd, blink::WebInputEvent::kNoModifiers, - (current_time_ - base::TimeTicks()).InSecondsF()); - event.source_device = blink::kWebGestureDeviceTouchpad; + (current_time_ - base::TimeTicks()).InSecondsF(), + blink::kWebGestureDeviceTouchpad); controller_.ObserveGestureEventAndResult(event, cc::InputHandlerScrollResult());
diff --git a/ui/events/blink/web_input_event.cc b/ui/events/blink/web_input_event.cc index baaaeba..8779ba726 100644 --- a/ui/events/blink/web_input_event.cc +++ b/ui/events/blink/web_input_event.cc
@@ -171,8 +171,8 @@ blink::WebGestureEvent webkit_event( type, EventFlagsToWebEventModifiers(event.flags()), - EventTimeStampToSeconds(event.time_stamp())); - webkit_event.source_device = blink::kWebGestureDeviceTouchpad; + EventTimeStampToSeconds(event.time_stamp()), + blink::kWebGestureDeviceTouchpad); if (event.type() == ET_SCROLL_FLING_START) { webkit_event.data.fling_start.velocity_x = event.x_offset(); webkit_event.data.fling_start.velocity_y = event.y_offset(); @@ -332,13 +332,11 @@ screen_location_callback) { blink::WebGestureEvent gesture_event = MakeWebGestureEventFromUIEvent(event); - gesture_event.x = event.x(); - gesture_event.y = event.y(); + gesture_event.SetPositionInWidget(event.location_f()); const gfx::PointF screen_point = GetScreenLocationFromEvent(event, screen_location_callback); - gesture_event.global_x = screen_point.x(); - gesture_event.global_y = screen_point.y(); + gesture_event.SetPositionInScreen(screen_point); return gesture_event; } @@ -348,13 +346,11 @@ const base::Callback<gfx::PointF(const LocatedEvent& event)>& screen_location_callback) { blink::WebGestureEvent gesture_event = MakeWebGestureEventFromUiEvent(event); - gesture_event.x = event.x(); - gesture_event.y = event.y(); + gesture_event.SetPositionInWidget(event.location_f()); const gfx::PointF screen_point = GetScreenLocationFromEvent(event, screen_location_callback); - gesture_event.global_x = screen_point.x(); - gesture_event.global_y = screen_point.y(); + gesture_event.SetPositionInScreen(screen_point); return gesture_event; } @@ -363,10 +359,9 @@ blink::WebGestureEvent gesture_event( blink::WebInputEvent::kGestureFlingCancel, blink::WebInputEvent::kNoModifiers, - EventTimeStampToSeconds(EventTimeForNow())); - + EventTimeStampToSeconds(EventTimeForNow()), + blink::kWebGestureDeviceTouchpad); // All other fields are ignored on a GestureFlingCancel event. - gesture_event.source_device = blink::kWebGestureDeviceTouchpad; return gesture_event; }
diff --git a/ui/events/blink/web_input_event_traits.cc b/ui/events/blink/web_input_event_traits.cc index 6fc2c871..046361ba 100644 --- a/ui/events/blink/web_input_event_traits.cc +++ b/ui/events/blink/web_input_event_traits.cc
@@ -56,14 +56,16 @@ } void ApppendEventDetails(const WebGestureEvent& event, std::string* result) { - StringAppendF( - result, - "{\n Pos: (%d, %d)\n GlobalPos: (%d, %d)\n SourceDevice: %d\n" - " RawData: (%f, %f, %f, %f, %d)\n}", - event.x, event.y, event.global_x, event.global_y, event.source_device, - event.data.scroll_update.delta_x, event.data.scroll_update.delta_y, - event.data.scroll_update.velocity_x, event.data.scroll_update.velocity_y, - event.data.scroll_update.previous_update_in_sequence_prevented); + StringAppendF(result, + "{\n Pos: (%f, %f)\n GlobalPos: (%f, %f)\n SourceDevice: %d\n" + " RawData: (%f, %f, %f, %f, %d)\n}", + event.PositionInWidget().x, event.PositionInWidget().y, + event.PositionInScreen().x, event.PositionInScreen().y, + event.SourceDevice(), event.data.scroll_update.delta_x, + event.data.scroll_update.delta_y, + event.data.scroll_update.velocity_x, + event.data.scroll_update.velocity_y, + event.data.scroll_update.previous_update_in_sequence_prevented); } void ApppendTouchPointDetails(const WebTouchPoint& point, std::string* result) { @@ -247,10 +249,10 @@ LatencyInfo WebInputEventTraits::CreateLatencyInfoForWebGestureEvent( const WebGestureEvent& event) { SourceEventType source_event_type = SourceEventType::UNKNOWN; - if (event.source_device == + if (event.SourceDevice() == blink::WebGestureDevice::kWebGestureDeviceTouchpad) { source_event_type = SourceEventType::WHEEL; - } else if (event.source_device == + } else if (event.SourceDevice() == blink::WebGestureDevice::kWebGestureDeviceTouchscreen) { source_event_type = SourceEventType::TOUCH; }
diff --git a/ui/events/blink/web_input_event_traits_unittest.cc b/ui/events/blink/web_input_event_traits_unittest.cc index a904dc4..b59c22e 100644 --- a/ui/events/blink/web_input_event_traits_unittest.cc +++ b/ui/events/blink/web_input_event_traits_unittest.cc
@@ -41,8 +41,7 @@ WebGestureEvent gesture(WebInputEvent::kGesturePinchBegin, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests()); - gesture.x = 1; - gesture.y = 1; + gesture.SetPositionInWidget(gfx::PointF(1, 1)); EXPECT_FALSE(WebInputEventTraits::ToString(gesture).empty()); WebTouchEvent touch(WebInputEvent::kTouchStart, WebInputEvent::kNoModifiers,
diff --git a/ui/gl/PRESUBMIT.py b/ui/gl/PRESUBMIT.py index 01515c9..ede2f4e 100644 --- a/ui/gl/PRESUBMIT.py +++ b/ui/gl/PRESUBMIT.py
@@ -26,6 +26,6 @@ 'luci.chromium.try:linux_optional_gpu_tests_rel', 'luci.chromium.try:mac_optional_gpu_tests_rel', 'master.tryserver.chromium.win:win_optional_gpu_tests_rel', - 'master.tryserver.chromium.android:android_optional_gpu_tests_rel', + 'luci.chromium.try:android_optional_gpu_tests_rel', ], 'Automatically added optional GPU tests to run on CQ.')
diff --git a/ui/gl/generate_bindings.py b/ui/gl/generate_bindings.py index de032fe1..c20f860 100755 --- a/ui/gl/generate_bindings.py +++ b/ui/gl/generate_bindings.py
@@ -662,7 +662,7 @@ 'arguments': 'GLenum target, GLenum pname, GLsizei bufSize, GLsizei* length, ' 'void** params', }, -{ 'return_type': 'void', +{ 'return_type': 'GLuint', 'versions': [{ 'name': 'glGetDebugMessageLog' }, { 'name': 'glGetDebugMessageLogKHR', 'extensions': ['GL_KHR_debug'] }],
diff --git a/ui/gl/gl_bindings_api_autogen_gl.h b/ui/gl/gl_bindings_api_autogen_gl.h index 851bb00..2aeddbf6 100644 --- a/ui/gl/gl_bindings_api_autogen_gl.h +++ b/ui/gl/gl_bindings_api_autogen_gl.h
@@ -436,14 +436,14 @@ GLsizei bufSize, GLsizei* length, void** params) override; -void glGetDebugMessageLogFn(GLuint count, - GLsizei bufSize, - GLenum* sources, - GLenum* types, - GLuint* ids, - GLenum* severities, - GLsizei* lengths, - char* messageLog) override; +GLuint glGetDebugMessageLogFn(GLuint count, + GLsizei bufSize, + GLenum* sources, + GLenum* types, + GLuint* ids, + GLenum* severities, + GLsizei* lengths, + char* messageLog) override; GLenum glGetErrorFn(void) override; void glGetFenceivNVFn(GLuint fence, GLenum pname, GLint* params) override; void glGetFloatvFn(GLenum pname, GLfloat* params) override;
diff --git a/ui/gl/gl_bindings_autogen_gl.cc b/ui/gl/gl_bindings_autogen_gl.cc index 3c5bf9d..193c37c 100644 --- a/ui/gl/gl_bindings_autogen_gl.cc +++ b/ui/gl/gl_bindings_autogen_gl.cc
@@ -3146,16 +3146,16 @@ params); } -void GLApiBase::glGetDebugMessageLogFn(GLuint count, - GLsizei bufSize, - GLenum* sources, - GLenum* types, - GLuint* ids, - GLenum* severities, - GLsizei* lengths, - char* messageLog) { - driver_->fn.glGetDebugMessageLogFn(count, bufSize, sources, types, ids, - severities, lengths, messageLog); +GLuint GLApiBase::glGetDebugMessageLogFn(GLuint count, + GLsizei bufSize, + GLenum* sources, + GLenum* types, + GLuint* ids, + GLenum* severities, + GLsizei* lengths, + char* messageLog) { + return driver_->fn.glGetDebugMessageLogFn(count, bufSize, sources, types, ids, + severities, lengths, messageLog); } GLenum GLApiBase::glGetErrorFn(void) { @@ -5917,17 +5917,17 @@ params); } -void TraceGLApi::glGetDebugMessageLogFn(GLuint count, - GLsizei bufSize, - GLenum* sources, - GLenum* types, - GLuint* ids, - GLenum* severities, - GLsizei* lengths, - char* messageLog) { +GLuint TraceGLApi::glGetDebugMessageLogFn(GLuint count, + GLsizei bufSize, + GLenum* sources, + GLenum* types, + GLuint* ids, + GLenum* severities, + GLsizei* lengths, + char* messageLog) { TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glGetDebugMessageLog") - gl_api_->glGetDebugMessageLogFn(count, bufSize, sources, types, ids, - severities, lengths, messageLog); + return gl_api_->glGetDebugMessageLogFn(count, bufSize, sources, types, ids, + severities, lengths, messageLog); } GLenum TraceGLApi::glGetErrorFn(void) { @@ -9310,14 +9310,14 @@ params); } -void DebugGLApi::glGetDebugMessageLogFn(GLuint count, - GLsizei bufSize, - GLenum* sources, - GLenum* types, - GLuint* ids, - GLenum* severities, - GLsizei* lengths, - char* messageLog) { +GLuint DebugGLApi::glGetDebugMessageLogFn(GLuint count, + GLsizei bufSize, + GLenum* sources, + GLenum* types, + GLuint* ids, + GLenum* severities, + GLsizei* lengths, + char* messageLog) { GL_SERVICE_LOG("glGetDebugMessageLog" << "(" << count << ", " << bufSize << ", " << static_cast<const void*>(sources) << ", " @@ -9326,8 +9326,10 @@ << static_cast<const void*>(severities) << ", " << static_cast<const void*>(lengths) << ", " << static_cast<const void*>(messageLog) << ")"); - gl_api_->glGetDebugMessageLogFn(count, bufSize, sources, types, ids, - severities, lengths, messageLog); + GLuint result = gl_api_->glGetDebugMessageLogFn( + count, bufSize, sources, types, ids, severities, lengths, messageLog); + GL_SERVICE_LOG("GL_RESULT: " << result); + return result; } GLenum DebugGLApi::glGetErrorFn(void) { @@ -12879,15 +12881,16 @@ NoContextHelper("glGetBufferPointervRobustANGLE"); } -void NoContextGLApi::glGetDebugMessageLogFn(GLuint count, - GLsizei bufSize, - GLenum* sources, - GLenum* types, - GLuint* ids, - GLenum* severities, - GLsizei* lengths, - char* messageLog) { +GLuint NoContextGLApi::glGetDebugMessageLogFn(GLuint count, + GLsizei bufSize, + GLenum* sources, + GLenum* types, + GLuint* ids, + GLenum* severities, + GLsizei* lengths, + char* messageLog) { NoContextHelper("glGetDebugMessageLog"); + return 0U; } GLenum NoContextGLApi::glGetErrorFn(void) {
diff --git a/ui/gl/gl_bindings_autogen_gl.h b/ui/gl/gl_bindings_autogen_gl.h index 0d5fe32..353ab36 100644 --- a/ui/gl/gl_bindings_autogen_gl.h +++ b/ui/gl/gl_bindings_autogen_gl.h
@@ -506,14 +506,14 @@ GLsizei bufSize, GLsizei* length, void** params); -typedef void(GL_BINDING_CALL* glGetDebugMessageLogProc)(GLuint count, - GLsizei bufSize, - GLenum* sources, - GLenum* types, - GLuint* ids, - GLenum* severities, - GLsizei* lengths, - char* messageLog); +typedef GLuint(GL_BINDING_CALL* glGetDebugMessageLogProc)(GLuint count, + GLsizei bufSize, + GLenum* sources, + GLenum* types, + GLuint* ids, + GLenum* severities, + GLsizei* lengths, + char* messageLog); typedef GLenum(GL_BINDING_CALL* glGetErrorProc)(void); typedef void(GL_BINDING_CALL* glGetFenceivNVProc)(GLuint fence, GLenum pname, @@ -2434,14 +2434,14 @@ GLsizei bufSize, GLsizei* length, void** params) = 0; - virtual void glGetDebugMessageLogFn(GLuint count, - GLsizei bufSize, - GLenum* sources, - GLenum* types, - GLuint* ids, - GLenum* severities, - GLsizei* lengths, - char* messageLog) = 0; + virtual GLuint glGetDebugMessageLogFn(GLuint count, + GLsizei bufSize, + GLenum* sources, + GLenum* types, + GLuint* ids, + GLenum* severities, + GLsizei* lengths, + char* messageLog) = 0; virtual GLenum glGetErrorFn(void) = 0; virtual void glGetFenceivNVFn(GLuint fence, GLenum pname, GLint* params) = 0; virtual void glGetFloatvFn(GLenum pname, GLfloat* params) = 0;
diff --git a/ui/gl/gl_bindings_autogen_mock.cc b/ui/gl/gl_bindings_autogen_mock.cc index 72f639e9..cb8e0ed 100644 --- a/ui/gl/gl_bindings_autogen_mock.cc +++ b/ui/gl/gl_bindings_autogen_mock.cc
@@ -1500,7 +1500,7 @@ params); } -void GL_BINDING_CALL +GLuint GL_BINDING_CALL MockGLInterface::Mock_glGetDebugMessageLog(GLuint count, GLsizei bufSize, GLenum* sources, @@ -1510,11 +1510,11 @@ GLsizei* lengths, char* messageLog) { MakeFunctionUnique("glGetDebugMessageLog"); - interface_->GetDebugMessageLog(count, bufSize, sources, types, ids, - severities, lengths, messageLog); + return interface_->GetDebugMessageLog(count, bufSize, sources, types, ids, + severities, lengths, messageLog); } -void GL_BINDING_CALL +GLuint GL_BINDING_CALL MockGLInterface::Mock_glGetDebugMessageLogKHR(GLuint count, GLsizei bufSize, GLenum* sources, @@ -1524,8 +1524,8 @@ GLsizei* lengths, char* messageLog) { MakeFunctionUnique("glGetDebugMessageLogKHR"); - interface_->GetDebugMessageLog(count, bufSize, sources, types, ids, - severities, lengths, messageLog); + return interface_->GetDebugMessageLog(count, bufSize, sources, types, ids, + severities, lengths, messageLog); } GLenum GL_BINDING_CALL MockGLInterface::Mock_glGetError(void) {
diff --git a/ui/gl/gl_bindings_autogen_mock.h b/ui/gl/gl_bindings_autogen_mock.h index 77e4bf54..edfa300 100644 --- a/ui/gl/gl_bindings_autogen_mock.h +++ b/ui/gl/gl_bindings_autogen_mock.h
@@ -617,22 +617,22 @@ GLsizei bufSize, GLsizei* length, void** params); -static void GL_BINDING_CALL Mock_glGetDebugMessageLog(GLuint count, - GLsizei bufSize, - GLenum* sources, - GLenum* types, - GLuint* ids, - GLenum* severities, - GLsizei* lengths, - char* messageLog); -static void GL_BINDING_CALL Mock_glGetDebugMessageLogKHR(GLuint count, - GLsizei bufSize, - GLenum* sources, - GLenum* types, - GLuint* ids, - GLenum* severities, - GLsizei* lengths, - char* messageLog); +static GLuint GL_BINDING_CALL Mock_glGetDebugMessageLog(GLuint count, + GLsizei bufSize, + GLenum* sources, + GLenum* types, + GLuint* ids, + GLenum* severities, + GLsizei* lengths, + char* messageLog); +static GLuint GL_BINDING_CALL Mock_glGetDebugMessageLogKHR(GLuint count, + GLsizei bufSize, + GLenum* sources, + GLenum* types, + GLuint* ids, + GLenum* severities, + GLsizei* lengths, + char* messageLog); static GLenum GL_BINDING_CALL Mock_glGetError(void); static void GL_BINDING_CALL Mock_glGetFenceivNV(GLuint fence, GLenum pname,
diff --git a/ui/gl/gl_mock_autogen_gl.h b/ui/gl/gl_mock_autogen_gl.h index c363dd9..002a1fe 100644 --- a/ui/gl/gl_mock_autogen_gl.h +++ b/ui/gl/gl_mock_autogen_gl.h
@@ -419,14 +419,14 @@ GLsizei* length, void** params)); MOCK_METHOD8(GetDebugMessageLog, - void(GLuint count, - GLsizei bufSize, - GLenum* sources, - GLenum* types, - GLuint* ids, - GLenum* severities, - GLsizei* lengths, - char* messageLog)); + GLuint(GLuint count, + GLsizei bufSize, + GLenum* sources, + GLenum* types, + GLuint* ids, + GLenum* severities, + GLsizei* lengths, + char* messageLog)); MOCK_METHOD0(GetError, GLenum()); MOCK_METHOD3(GetFenceivNV, void(GLuint fence, GLenum pname, GLint* params)); MOCK_METHOD2(GetFloatv, void(GLenum pname, GLfloat* params));
diff --git a/ui/gl/gl_stub_autogen_gl.cc b/ui/gl/gl_stub_autogen_gl.cc index e30dbfd..80d35bd 100644 --- a/ui/gl/gl_stub_autogen_gl.cc +++ b/ui/gl/gl_stub_autogen_gl.cc
@@ -42,6 +42,17 @@ return 0; } +GLuint GLStubApiBase::glGetDebugMessageLogFn(GLuint count, + GLsizei bufSize, + GLenum* sources, + GLenum* types, + GLuint* ids, + GLenum* severities, + GLsizei* lengths, + char* messageLog) { + return 0; +} + GLenum GLStubApiBase::glGetErrorFn() { return 0; }
diff --git a/ui/gl/gl_stub_autogen_gl.h b/ui/gl/gl_stub_autogen_gl.h index 394cffd..32160fa 100644 --- a/ui/gl/gl_stub_autogen_gl.h +++ b/ui/gl/gl_stub_autogen_gl.h
@@ -438,14 +438,14 @@ GLsizei bufSize, GLsizei* length, void** params) override {} -void glGetDebugMessageLogFn(GLuint count, - GLsizei bufSize, - GLenum* sources, - GLenum* types, - GLuint* ids, - GLenum* severities, - GLsizei* lengths, - char* messageLog) override {} +GLuint glGetDebugMessageLogFn(GLuint count, + GLsizei bufSize, + GLenum* sources, + GLenum* types, + GLuint* ids, + GLenum* severities, + GLsizei* lengths, + char* messageLog) override; GLenum glGetErrorFn() override; void glGetFenceivNVFn(GLuint fence, GLenum pname, GLint* params) override {} void glGetFloatvFn(GLenum pname, GLfloat* params) override {}
diff --git a/ui/gl/init/create_gr_gl_interface.cc b/ui/gl/init/create_gr_gl_interface.cc index 283dd1f..8d6bc95 100644 --- a/ui/gl/init/create_gr_gl_interface.cc +++ b/ui/gl/init/create_gr_gl_interface.cc
@@ -465,8 +465,7 @@ functions->fDebugMessageCallback = reinterpret_cast<GrGLDebugMessageCallbackProc>( gl->glDebugMessageCallbackFn); - functions->fGetDebugMessageLog = - reinterpret_cast<GrGLGetDebugMessageLogProc>(gl->glGetDebugMessageLogFn); + functions->fGetDebugMessageLog = gl->glGetDebugMessageLogFn; functions->fPushDebugGroup = gl->glPushDebugGroupFn; functions->fPopDebugGroup = gl->glPopDebugGroupFn; functions->fObjectLabel = gl->glObjectLabelFn;
diff --git a/ui/keyboard/BUILD.gn b/ui/keyboard/BUILD.gn index a5a5119..86f6fdeb 100644 --- a/ui/keyboard/BUILD.gn +++ b/ui/keyboard/BUILD.gn
@@ -27,6 +27,8 @@ "keyboard_layout_delegate.h", "keyboard_layout_manager.cc", "keyboard_layout_manager.h", + "keyboard_resource_util.cc", + "keyboard_resource_util.h", "keyboard_switches.cc", "keyboard_switches.h", "keyboard_ui.cc", @@ -42,6 +44,7 @@ defines = [ "KEYBOARD_IMPLEMENTATION" ] deps = [ + ":resources", "//base", "//ui/aura", "//ui/base", @@ -58,27 +61,6 @@ if (use_ozone) { deps += [ "//ui/ozone" ] } -} - -jumbo_component("keyboard_with_content") { - sources = [ - "content/keyboard.cc", - "content/keyboard.h", - "content/keyboard_constants.cc", - "content/keyboard_constants.h", - "content/keyboard_content_util.cc", - "content/keyboard_content_util.h", - ] - - defines = [ "KEYBOARD_IMPLEMENTATION" ] - - deps = [ - ":keyboard", - ":resources", - "//base", - "//ui/base", - "//url", - ] data_deps = [ ":resources", @@ -165,7 +147,6 @@ deps = [ ":keyboard", - ":keyboard_with_content", ":test_support", "//base", "//base/test:test_support",
diff --git a/ui/keyboard/content/keyboard.cc b/ui/keyboard/content/keyboard.cc deleted file mode 100644 index 4f7da4d..0000000 --- a/ui/keyboard/content/keyboard.cc +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/keyboard/content/keyboard.h" - -#include "base/files/file_path.h" -#include "base/path_service.h" -#include "ui/base/resource/resource_bundle.h" - -namespace keyboard { - -void InitializeKeyboard() { - static bool initialized = false; - if (initialized) - return; - initialized = true; - - base::FilePath pak_dir; - PathService::Get(base::DIR_MODULE, &pak_dir); - base::FilePath pak_file = pak_dir.Append( - FILE_PATH_LITERAL("keyboard_resources.pak")); - ui::ResourceBundle::GetSharedInstance().AddDataPackFromPath( - pak_file, ui::SCALE_FACTOR_100P); -} - -} // namespace keyboard
diff --git a/ui/keyboard/content/keyboard.h b/ui/keyboard/content/keyboard.h deleted file mode 100644 index 0878b7b..0000000 --- a/ui/keyboard/content/keyboard.h +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_KEYBOARD_KEYBOARD_H_ -#define UI_KEYBOARD_KEYBOARD_H_ - -#include "ui/keyboard/keyboard_export.h" - -namespace keyboard { - -// Initializes the keyboard module. This includes adding the necessary pak files -// for loading resources used in for the virtual keyboard. This becomes a no-op -// after the first call. -KEYBOARD_EXPORT void InitializeKeyboard(); - -} // namespace keyboard - -#endif // UI_KEYBOARD_KEYBOARD_H_
diff --git a/ui/keyboard/content/keyboard_constants.cc b/ui/keyboard/content/keyboard_constants.cc deleted file mode 100644 index 449f96f..0000000 --- a/ui/keyboard/content/keyboard_constants.cc +++ /dev/null
@@ -1,12 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/keyboard/content/keyboard_constants.h" - -namespace keyboard { - -const char kKeyboardURL[] = "chrome://keyboard"; -const char kKeyboardHost[] = "keyboard"; - -} // namespace keyboard
diff --git a/ui/keyboard/content/keyboard_constants.h b/ui/keyboard/content/keyboard_constants.h deleted file mode 100644 index 6c4e661..0000000 --- a/ui/keyboard/content/keyboard_constants.h +++ /dev/null
@@ -1,20 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_KEYBOARD_CONTENT_KEYBOARD_CONSTANTS_H_ -#define UI_KEYBOARD_CONTENT_KEYBOARD_CONSTANTS_H_ - -#include "ui/keyboard/keyboard_export.h" - -namespace keyboard { - -// The URL of the keyboard extension. -KEYBOARD_EXPORT extern const char kKeyboardURL[]; - -// The host of the keyboard extension URL. -KEYBOARD_EXPORT extern const char kKeyboardHost[]; - -} // namespace keyboard - -#endif // UI_KEYBOARD_CONTENT_KEYBOARD_CONSTANTS_H_
diff --git a/ui/keyboard/content/keyboard_content_util.h b/ui/keyboard/content/keyboard_content_util.h deleted file mode 100644 index 179ba60..0000000 --- a/ui/keyboard/content/keyboard_content_util.h +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_KEYBOARD_CONTENT_KEYBOARD_COTNENT_UTIL_H_ -#define UI_KEYBOARD_CONTENT_KEYBOARD_COTNENT_UTIL_H_ - -#include <stddef.h> - -#include "ui/keyboard/keyboard_export.h" - -struct GritResourceMap; - -namespace keyboard { - -// Get the list of keyboard resources. |size| is populated with the number of -// resources in the returned array. -KEYBOARD_EXPORT const GritResourceMap* GetKeyboardExtensionResources( - size_t* size); - -} // namespace keyboard - -#endif // UI_KEYBOARD_CONTENT_KEYBOARD_COTNENT_UTIL_H_
diff --git a/ui/keyboard/content/keyboard_content_util.cc b/ui/keyboard/keyboard_resource_util.cc similarity index 87% rename from ui/keyboard/content/keyboard_content_util.cc rename to ui/keyboard/keyboard_resource_util.cc index e0bf3c0..70beddc 100644 --- a/ui/keyboard/content/keyboard_content_util.cc +++ b/ui/keyboard/keyboard_resource_util.cc
@@ -1,15 +1,21 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. +// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ui/keyboard/content/keyboard_content_util.h" +#include "ui/keyboard/keyboard_resource_util.h" +#include "base/files/file_path.h" #include "base/macros.h" +#include "base/path_service.h" +#include "ui/base/resource/resource_bundle.h" #include "ui/keyboard/grit/keyboard_resources.h" #include "ui/keyboard/grit/keyboard_resources_map.h" namespace keyboard { +const char kKeyboardURL[] = "chrome://keyboard"; +const char kKeyboardHost[] = "keyboard"; + const GritResourceMap* GetKeyboardExtensionResources(size_t* size) { // This looks a lot like the contents of a resource map; however it is // necessary to have a custom path for the extension path, so the resource @@ -91,4 +97,18 @@ return kKeyboardResources; } +void InitializeKeyboardResources() { + static bool initialized = false; + if (initialized) + return; + initialized = true; + + base::FilePath pak_dir; + PathService::Get(base::DIR_MODULE, &pak_dir); + base::FilePath pak_file = + pak_dir.Append(FILE_PATH_LITERAL("keyboard_resources.pak")); + ui::ResourceBundle::GetSharedInstance().AddDataPackFromPath( + pak_file, ui::SCALE_FACTOR_100P); +} + } // namespace keyboard
diff --git a/ui/keyboard/keyboard_resource_util.h b/ui/keyboard/keyboard_resource_util.h new file mode 100644 index 0000000..b10dcc5 --- /dev/null +++ b/ui/keyboard/keyboard_resource_util.h
@@ -0,0 +1,34 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef UI_KEYBOARD_KEYBOARD_RESOURCE_UTIL_H_ +#define UI_KEYBOARD_KEYBOARD_RESOURCE_UTIL_H_ + +#include <stddef.h> + +#include "ui/keyboard/keyboard_export.h" + +struct GritResourceMap; + +namespace keyboard { + +// The URL of the keyboard extension. +KEYBOARD_EXPORT extern const char kKeyboardURL[]; + +// The host of the keyboard extension URL. +KEYBOARD_EXPORT extern const char kKeyboardHost[]; + +// Get the list of keyboard resources. |size| is populated with the number of +// resources in the returned array. +KEYBOARD_EXPORT const GritResourceMap* GetKeyboardExtensionResources( + size_t* size); + +// Initializes the keyboard module. This includes adding the necessary pak files +// for loading resources used in for the virtual keyboard. This becomes a no-op +// after the first call. +KEYBOARD_EXPORT void InitializeKeyboardResources(); + +} // namespace keyboard + +#endif // UI_KEYBOARD_KEYBOARD_RESOURCE_UTIL_H_
diff --git a/ui/keyboard/keyboard_resources.grd b/ui/keyboard/keyboard_resources.grd index 60ee41e..91ca2ba2 100644 --- a/ui/keyboard/keyboard_resources.grd +++ b/ui/keyboard/keyboard_resources.grd
@@ -1,8 +1,7 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- NOTE: if you are adding resources here, you should probably also edit: - ui/keyboard/keyboard_ui_controller.cc - ui/keyboard/keyboard_util.cc + ui/keyboard/keyboard_resource_util.cc --> <grit latest_public_release="0" current_release="1" output_all_resource_defines="false"> <outputs>