diff --git a/DEPS b/DEPS index 006bd630..2908ff67d 100644 --- a/DEPS +++ b/DEPS
@@ -162,11 +162,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': '8d72456867744526108b4ab538a159459c676939', + 'skia_revision': '8ef18d359b2666828957c4c6f03f2ddfa8ce266c', # 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': '8a1c4425be25efd4f8dfb613f64cdf7067b97933', + 'v8_revision': 'a7cf9c5c1f51db3b7e9efda13edee844686dc6e2', # 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. @@ -174,11 +174,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': '56ba54cc03f37a306d156a95e1deb3493836d622', + 'angle_revision': '2c5d48a6f0e43c5a688ad85716f318ca1a9e957e', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. - 'swiftshader_revision': 'f0033328dd22db93acee5dfac2a339d7d3b27dc2', + 'swiftshader_revision': '18c9ac4971176658d2f9f13a043fe93c183556d8', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. @@ -225,7 +225,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling catapult # and whatever else without interference from each other. - 'catapult_revision': 'f5980f492582870d5e823a6a7dda2a210816df3c', + 'catapult_revision': '9e1c92c073c95229717afb53a96ef3dfbdfc2400', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -297,11 +297,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'dawn_revision': '864bae4cc6a2d2aac5ab19e6a32c089b4f1e66c5', + 'dawn_revision': 'adbecedad5e09a829fcc43fc42cc9ff457d1a1ad', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'quiche_revision': 'edeeb47d60bc7342c61c310f814f4989183dcfed', + 'quiche_revision': '28315b77c94c06e419bc8e6cddedce71884cbf4d', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ios_webkit # and whatever else without interference from each other. @@ -1027,7 +1027,7 @@ Var('chromium_git') + '/chromium/deps/hunspell_dictionaries.git' + '@' + '681ca92480ecc11d35feae8c1c00e4e035630f43', 'src/third_party/icu': - Var('chromium_git') + '/chromium/deps/icu.git' + '@' + '952ccb90fb669bb70015cabe64ce415708f125bf', + Var('chromium_git') + '/chromium/deps/icu.git' + '@' + '53f6b233a41ec982d8445996247093f7aaf41639', 'src/third_party/icu4j': { 'packages': [ @@ -1282,7 +1282,7 @@ }, 'src/third_party/quic_trace/src': - Var('chromium_git') + '/external/github.com/google/quic-trace.git' + '@' + '8415c22f0ca2485bd8a16eff64075f4361f3878e', + Var('chromium_git') + '/external/github.com/google/quic-trace.git' + '@' + '35d364f77a02b283d82dd2f874da61f765c259f4', 'src/third_party/pywebsocket/src': Var('chromium_git') + '/external/github.com/google/pywebsocket.git' + '@' + '2d7b73c3acbd0f41dcab487ae5c97c6feae06ce2', @@ -1455,7 +1455,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@d70702fad6d1949e2999d3623aac7cf8d19f8d35', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@408dc11ec29e2f55dd1d072097f07cc943684adf', 'condition': 'checkout_src_internal', },
diff --git a/PRESUBMIT.py b/PRESUBMIT.py index 2169ec3..056c061 100644 --- a/PRESUBMIT.py +++ b/PRESUBMIT.py
@@ -1023,7 +1023,7 @@ r'.*_ios\.(cc|h)$', r'^net[\\/].*\.(cc|h)$', r'.*[\\/]tools[\\/].*\.(cc|h)$', - r'^fuchsia/engine/test_devtools_list_fetcher\.cc$', + r'^fuchsia/base/test_devtools_list_fetcher\.cc$', ), ), (
diff --git a/android_webview/apk/java/proguard.flags b/android_webview/apk/java/proguard.flags index b6888be..ddc0104 100644 --- a/android_webview/apk/java/proguard.flags +++ b/android_webview/apk/java/proguard.flags
@@ -39,6 +39,10 @@ -keep class com.android.webview.chromium.DrawGLFunctor -keep class com.android.webview.chromium.GraphicsUtils +# Linker dynamically casts to $TestRunner when running tests. We don't run these +# tests in WebView. +-dontnote org.chromium.base.library_loader.Linker$TestRunner + # Don't note about the API 21 compatibility code which references various # hidden APIs via reflection. -dontnote com.android.webview.chromium.WebViewDelegateFactory$Api21CompatibilityDelegate
diff --git a/android_webview/browser/state_serializer_unittest.cc b/android_webview/browser/state_serializer_unittest.cc index f066cb4..5cdf3b6 100644 --- a/android_webview/browser/state_serializer_unittest.cc +++ b/android_webview/browser/state_serializer_unittest.cc
@@ -33,6 +33,8 @@ referrer.url = GURL("http://referrer_url"); referrer.policy = network::mojom::ReferrerPolicy::kOrigin; const base::string16 title(base::UTF8ToUTF16("title")); + const content::PageState page_state = + content::PageState::CreateFromEncodedData("completely bogus state"); const bool has_post_data = true; const GURL original_request_url("http://original_request_url"); const GURL base_url_for_data_url("http://base_url"); @@ -45,6 +47,7 @@ entry->SetVirtualURL(virtual_url); entry->SetReferrer(referrer); entry->SetTitle(title); + entry->SetPageState(page_state); entry->SetHasPostData(has_post_data); entry->SetOriginalRequestURL(original_request_url); entry->SetBaseURLForDataURL(base_url_for_data_url);
diff --git a/ash/app_list/views/app_list_view_unittest.cc b/ash/app_list/views/app_list_view_unittest.cc index 964c6fd..44ea13d1 100644 --- a/ash/app_list/views/app_list_view_unittest.cc +++ b/ash/app_list/views/app_list_view_unittest.cc
@@ -25,6 +25,7 @@ #include "ash/app_list/views/contents_view.h" #include "ash/app_list/views/expand_arrow_view.h" #include "ash/app_list/views/folder_header_view.h" +#include "ash/app_list/views/page_switcher.h" #include "ash/app_list/views/result_selection_controller.h" #include "ash/app_list/views/search_box_view.h" #include "ash/app_list/views/search_result_answer_card_view.h" @@ -70,6 +71,30 @@ constexpr int kInitialItems = 34; +// Constants used for for testing app list layout in fullscreen state: +// The expected bottom of suggestion chip view. The top is expected to be 96, +// and height 32. +constexpr int kFullscreenSuggestionChipBottom = 96 + 32; + +// The app list grid top inset - the height of the view fadeout area. +constexpr int kGridTopInset = 24; + +// The horizontal spacing between apps grid view and the page switcher. +constexpr int kPageSwitcherSpacing = 8; + +// The maximum allowed margin between items in apps item grid. +constexpr int kMaxItemMargin = 96; + +int GridItemSizeWithMargins(int grid_size, int item_size, int item_count) { + int margin = (grid_size - item_size * item_count) / (2 * (item_count - 1)); + return item_size + 2 * margin; +} + +// Calculates the apps item grid size with maximum allowed margin between items. +int GetItemGridSizeWithMaxItemMargins(int item_size, int item_count) { + return item_size * item_count + (item_count - 1) * kMaxItemMargin; +} + template <class T> size_t GetVisibleViews(const std::vector<T*>& tiles) { size_t count = 0; @@ -216,6 +241,10 @@ return contents_view()->GetAppsContainerView()->apps_grid_view(); } + PageSwitcher* page_switcher_view() { + return contents_view()->GetAppsContainerView()->page_switcher(); + } + gfx::Point GetPointBetweenTwoApps() { const views::ViewModelT<AppListItemView>* view_model = apps_grid_view()->view_model(); @@ -230,6 +259,77 @@ return delegate_->show_wallpaper_context_menu_count(); } + // Verifies fullscreen apps grid bounds and layout with + // app_list_features::kScalableAppList feature enabled. + void VerifyAppsGridLayout(const gfx::Size& container_size, + int row_count, + int column_count, + int expected_horizontal_margin, + int expected_item_size, + bool expect_max_grid_height) { + const int kShelfHeight = AppListConfig::instance().shelf_height(); + // The apps grid height including insets and margins. + const int kExpectedTotalGridHeight = container_size.height() - + kFullscreenSuggestionChipBottom - + kShelfHeight; + const int kMaxGridHeight = + GetItemGridSizeWithMaxItemMargins(expected_item_size, column_count) + + 2 * kGridTopInset; + const int kExpectedGridVerticalMargin = + expect_max_grid_height ? (kExpectedTotalGridHeight - kMaxGridHeight) / 2 + : kExpectedTotalGridHeight / 16 - kGridTopInset; + const int kExpectedGridHeight = + kExpectedTotalGridHeight - 2 * kExpectedGridVerticalMargin; + const int kExpectedGridTop = + kFullscreenSuggestionChipBottom + kExpectedGridVerticalMargin; + const int kExpectedGridWidth = + container_size.width() - 2 * expected_horizontal_margin; + + EXPECT_EQ( + gfx::Rect(expected_horizontal_margin, kExpectedGridTop, + kExpectedGridWidth, + kExpectedTotalGridHeight - 2 * kExpectedGridVerticalMargin), + apps_grid_view()->bounds()); + EXPECT_EQ(gfx::Rect(kExpectedGridWidth + expected_horizontal_margin + + kPageSwitcherSpacing, + kFullscreenSuggestionChipBottom, + PageSwitcher::kPreferredButtonStripWidth, + container_size.height() - + kFullscreenSuggestionChipBottom - kShelfHeight), + page_switcher_view()->bounds()); + + // Horizontal offset between app list item views. + const int kHorizontalOffset = GridItemSizeWithMargins( + kExpectedGridWidth, expected_item_size, row_count); + + // Verify expected bounds for the first row: + for (int i = 0; i < row_count; ++i) { + EXPECT_EQ(gfx::Rect(i * kHorizontalOffset, kGridTopInset, + expected_item_size, expected_item_size), + test_api_->GetItemTileRectAtVisualIndex(0, i)) + << "Item " << i << " bounds"; + } + + // Vertical offset between app list item views. + const int kVerticalOffset = + GridItemSizeWithMargins(kExpectedGridHeight - 2 * kGridTopInset, + expected_item_size, column_count); + + // Verify expected bounds for the first column: + for (int j = 1; j < column_count; ++j) { + EXPECT_EQ(gfx::Rect(0, kGridTopInset + j * kVerticalOffset, + expected_item_size, expected_item_size), + test_api_->GetItemTileRectAtVisualIndex(0, j * row_count)) + << "Item " << j * row_count << " bounds"; + } + + // The last item in the page (bottom right): + EXPECT_EQ(gfx::Rect((row_count - 1) * kHorizontalOffset, + kGridTopInset + (column_count - 1) * kVerticalOffset, + expected_item_size, expected_item_size), + test_api_->GetItemTileRectAtVisualIndex(0, 19)); + } + AppListView* view_ = nullptr; // Owned by native widget. std::unique_ptr<AppListTestViewDelegate> delegate_; std::unique_ptr<AppsGridViewTestApi> test_api_; @@ -2589,5 +2689,193 @@ EXPECT_TRUE(contents_view()->expand_arrow_view()->layer()->opacity() == 0.0f); } +// Tests fullscreen apps grid sizing and layout for small screens (width < 960) +// in landscape layout. +TEST_F(AppListViewTest, AppListViewLayoutForSmallLandscapeScreen) { + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitWithFeatures({app_list_features::kScalableAppList}, + {}); + + const gfx::Size window_size = gfx::Size(800, 600); + gfx::NativeView parent = GetContext(); + parent->SetBounds(gfx::Rect(window_size)); + + Initialize(false /*is_tablet_mode*/); + delegate_->GetTestModel()->PopulateApps(kInitialItems); + Show(); + view_->SetState(ash::AppListViewState::kFullscreenAllApps); + + VerifyAppsGridLayout(window_size, 5 /*row_count*/, 4 /*column_count*/, + window_size.width() / 16 /*expected_horizontal_margin*/, + 80 /*expected_item_size*/, + false /*expect_max_grid_height*/); +} + +// Tests fullscreen apps grid sizing and layout for small screens (width < 600) +// in portrait layout. +TEST_F(AppListViewTest, AppListViewLayoutForSmallPortraitScreen) { + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitWithFeatures({app_list_features::kScalableAppList}, + {}); + + const gfx::Size window_size = gfx::Size(500, 800); + gfx::NativeView parent = GetContext(); + parent->SetBounds(gfx::Rect(window_size)); + + Initialize(false /*is_tablet_mode*/); + delegate_->GetTestModel()->PopulateApps(kInitialItems); + Show(); + view_->SetState(ash::AppListViewState::kFullscreenAllApps); + + VerifyAppsGridLayout(window_size, 4 /*row_count*/, 5 /*column_count*/, + window_size.width() / 12 /*expected_horizontal_margin*/, + 80 /*expected_item_size*/, + false /*expect_max_grid_height*/); +} + +// Tests fullscreen apps grid sizing and layout for medium sized screens +// (width < 1200) in lanscape layout. +TEST_F(AppListViewTest, AppListViewLayoutForMediumLandscapeScreen) { + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitWithFeatures({app_list_features::kScalableAppList}, + {}); + + const gfx::Size window_size = gfx::Size(960, 800); + gfx::NativeView parent = GetContext(); + parent->SetBounds(gfx::Rect(window_size)); + + Initialize(false /*is_tablet_mode*/); + delegate_->GetTestModel()->PopulateApps(kInitialItems); + Show(); + view_->SetState(ash::AppListViewState::kFullscreenAllApps); + + // Horizontal margin should be set so apps grid doesn't go over the max size. + const int expected_horizontal_margin = + (window_size.width() - GetItemGridSizeWithMaxItemMargins(88, 5)) / 2; + VerifyAppsGridLayout(window_size, 5 /*row_count*/, 4 /*column_count*/, + expected_horizontal_margin, 88 /*expected_item_size*/, + false /*expect_max_grid_height*/); +} + +// Tests fullscreen apps grid sizing and layout for medium sized screens +// (width < 768) in portrait layout. +TEST_F(AppListViewTest, AppListViewLayoutForMediumPortraitScreen) { + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitWithFeatures({app_list_features::kScalableAppList}, + {}); + + const gfx::Size window_size = gfx::Size(700, 800); + gfx::NativeView parent = GetContext(); + parent->SetBounds(gfx::Rect(window_size)); + + Initialize(false /*is_tablet_mode*/); + delegate_->GetTestModel()->PopulateApps(kInitialItems); + Show(); + view_->SetState(ash::AppListViewState::kFullscreenAllApps); + + VerifyAppsGridLayout(window_size, 4 /*row_count*/, 5 /*column_count*/, + window_size.width() / 16 /*expected_horizontal_margin*/, + 88 /*expected_item_size*/, + false /*expect_max_grid_height*/); +} + +// Tests fullscreen apps grid sizing and layout for large screens +// (width >= 1200) in landscape layout. +TEST_F(AppListViewTest, AppListViewLayoutForLargeLandscapeScreen) { + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitWithFeatures({app_list_features::kScalableAppList}, + {}); + + const gfx::Size window_size = gfx::Size(1200, 960); + gfx::NativeView parent = GetContext(); + parent->SetBounds(gfx::Rect(window_size)); + + Initialize(false /*is_tablet_mode*/); + delegate_->GetTestModel()->PopulateApps(kInitialItems); + Show(); + view_->SetState(ash::AppListViewState::kFullscreenAllApps); + + // Horizontal margin should be set so apps grid doesn't go over the max size. + const int expected_horizontal_margin = + (window_size.width() - GetItemGridSizeWithMaxItemMargins(120, 5)) / 2; + + VerifyAppsGridLayout(window_size, 5 /*row_count*/, 4 /*column_count*/, + expected_horizontal_margin, 120 /*expected_item_size*/, + false /*expect_max_grid_height*/); +} + +// Tests fullscreen apps grid sizing and layout for large screens (width >= 768) +// in portrait layout. +TEST_F(AppListViewTest, AppListViewLayoutForLargePortraitScreen) { + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitWithFeatures({app_list_features::kScalableAppList}, + {}); + + const gfx::Size window_size = gfx::Size(800, 1200); + gfx::NativeView parent = GetContext(); + parent->SetBounds(gfx::Rect(window_size)); + + Initialize(false /*is_tablet_mode*/); + delegate_->GetTestModel()->PopulateApps(kInitialItems); + Show(); + view_->SetState(ash::AppListViewState::kFullscreenAllApps); + + VerifyAppsGridLayout(window_size, 4 /*row_count*/, 5 /*column_count*/, + window_size.width() / 16 /*expected_horizontal_margin*/, + 120 /*expected_item_size*/, + false /*expect_max_grid_height*/); +} + +// Tests that apps grid horizontal margin have minimum that ensures the page +// switcher view can fit next to the apps grid. +TEST_F(AppListViewTest, EnsurePageSwitcherFitsAppsGridMargin) { + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitWithFeatures({app_list_features::kScalableAppList}, + {}); + + const gfx::Size window_size = gfx::Size(600, 800); + gfx::NativeView parent = GetContext(); + parent->SetBounds(gfx::Rect(window_size)); + + Initialize(false /*is_tablet_mode*/); + delegate_->GetTestModel()->PopulateApps(kInitialItems); + Show(); + view_->SetState(ash::AppListViewState::kFullscreenAllApps); + + // The horizontal margin is selected so the page switcher fits the margin + // space (note that 600 / 16, which is how the margin is normally calculated + // is smaller than the width required by page switcher). + VerifyAppsGridLayout(window_size, 4 /*row_count*/, 5 /*column_count*/, + 40 /*expected_horizontal_margin*/, + 88 /*expected_item_size*/, + false /*expect_max_grid_height*/); +} + +// Verifies that the vertical spacing between items in apps grid has an upper +// limit, and that the apps grid is centered in the available space if item +// spacing hits that limit. +TEST_F(AppListViewTest, VerticalAppsGridItemSpacingIsBounded) { + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitWithFeatures({app_list_features::kScalableAppList}, + {}); + + const gfx::Size window_size = gfx::Size(960, 1600); + gfx::NativeView parent = GetContext(); + parent->SetBounds(gfx::Rect(window_size)); + + Initialize(false /*is_tablet_mode*/); + delegate_->GetTestModel()->PopulateApps(kInitialItems); + Show(); + view_->SetState(ash::AppListViewState::kFullscreenAllApps); + + // Horizontal margin should be set so apps grid doesn't go over the max size. + const int expected_horizontal_margin = + (window_size.width() - GetItemGridSizeWithMaxItemMargins(120, 4)) / 2; + + VerifyAppsGridLayout(window_size, 4 /*row_count*/, 5 /*column_count*/, + expected_horizontal_margin, 120 /*expected_item_size*/, + true /*expect_max_grid_height*/); +} + } // namespace test } // namespace app_list
diff --git a/ash/app_list/views/apps_container_view.cc b/ash/app_list/views/apps_container_view.cc index 0bf5065..6ff2bd1 100644 --- a/ash/app_list/views/apps_container_view.cc +++ b/ash/app_list/views/apps_container_view.cc
@@ -19,6 +19,7 @@ #include "ash/app_list/views/search_box_view.h" #include "ash/app_list/views/suggestion_chip_container_view.h" #include "ash/public/cpp/app_list/app_list_config.h" +#include "ash/public/cpp/app_list/app_list_features.h" #include "ash/public/cpp/app_list/app_list_switches.h" #include "base/command_line.h" #include "ui/base/l10n/l10n_util.h" @@ -44,6 +45,11 @@ // The ratio of allowed bounds for apps grid view to its maximum margin. constexpr int kAppsGridMarginRatio = 16; +constexpr int kAppsGridMarginRatioForSmallWidth = 12; + +// The width threshold under which kAppsGridMarginRatioForSmallWidth should be +// used to calculate apps grid horizontal margins. +constexpr int kAppsGridMarginSmallWidthThreshold = 600; // The minimum margin of apps grid view. constexpr int kAppsGridMinimumMargin = 8; @@ -62,8 +68,15 @@ gfx::Size AppsContainerView::GetNonAppsGridSize() { gfx::Size size; + // If ScalableAppList feature is enabled, there is no extra horizontal margin + // between grid view and the page switcher. + const int min_grid_horizontal_margin = + app_list_features::IsScalableAppListEnabled() + ? 0 + : kAppsGridMinimumMargin * 2; + // Enlarge with the apps grid view insets and margin. - size.Enlarge(kAppsGridMinimumMargin * 2, + size.Enlarge(min_grid_horizontal_margin, AppsGridView::kFadeoutZoneHeight * 2); // Enlarge with suggestion chips. @@ -269,9 +282,15 @@ rect.set_y(chip_container_rect.bottom()); rect.set_height(rect.height() - kSuggestionChipFullscreenY - kSuggestionChipContainerHeight); + const int page_switcher_width = page_switcher_->GetPreferredSize().width(); - rect.Inset(kAppsGridPageSwitcherSpacing + page_switcher_width, 0); + + // With scalable app list feature enabled, the margins are calculated from + // the edge of the apps container, instead of container bounds inset by + // page switcher area. + if (!app_list_features::IsScalableAppListEnabled()) + rect.Inset(kAppsGridPageSwitcherSpacing + page_switcher_width, 0); // Layout apps grid. gfx::Rect grid_rect = rect; @@ -287,8 +306,13 @@ apps_grid_view_->SetLayout(cols, rows); // Calculate the maximum margin of apps grid. + const int horizontal_margin_ratio = + (app_list_features::IsScalableAppListEnabled() && + rect.width() < kAppsGridMarginSmallWidthThreshold) + ? kAppsGridMarginRatioForSmallWidth + : kAppsGridMarginRatio; const int max_horizontal_margin = - grid_rect.width() / kAppsGridMarginRatio; + grid_rect.width() / horizontal_margin_ratio; const int max_vertical_margin = grid_rect.height() / kAppsGridMarginRatio; // Calculate the minimum size of apps grid. @@ -299,22 +323,35 @@ // keep maximum margin if apps grid can maintain at least // |min_grid_size|; Otherwise, always keep at least // |kAppsGridMinimumMargin|. - const int horizontal_margin = - max_horizontal_margin * 2 <= grid_rect.width() - min_grid_size.width() - ? max_horizontal_margin - : std::max(kAppsGridMinimumMargin, - (grid_rect.width() - min_grid_size.width()) / 2); - const int vertical_margin = - max_vertical_margin * 2 <= grid_rect.height() - min_grid_size.height() + int horizontal_margin = max_horizontal_margin; + if (app_list_features::IsScalableAppListEnabled()) { + // For scalable app list margins, ensure the max margin allow space for + // the page switcher (note that this is larger than + // |kAppsGridMinimumMargin|). + horizontal_margin = + std::max(max_horizontal_margin, + kAppsGridPageSwitcherSpacing + page_switcher_width); + } else if (max_horizontal_margin * 2 > + grid_rect.width() - min_grid_size.width()) { + horizontal_margin = + std::max(kAppsGridMinimumMargin, + (grid_rect.width() - min_grid_size.width()) / 2); + } + + int vertical_margin = + (max_vertical_margin * 2 <= + grid_rect.height() - min_grid_size.height()) ? max_vertical_margin : std::max(kAppsGridMinimumMargin, (grid_rect.height() - min_grid_size.height()) / 2); + grid_rect.Inset( horizontal_margin, std::max(apps_grid_view_->GetInsets().top(), vertical_margin)); grid_rect.ClampToCenteredSize( apps_grid_view_->GetMaximumTileGridSize(cols, rows)); grid_rect.Inset(-apps_grid_view_->GetInsets()); + apps_grid_view_->SetBoundsRect(grid_rect); // Record the distance of y position between suggestion chip container
diff --git a/ash/app_list/views/apps_container_view.h b/ash/app_list/views/apps_container_view.h index 3d115ef..46df396 100644 --- a/ash/app_list/views/apps_container_view.h +++ b/ash/app_list/views/apps_container_view.h
@@ -102,6 +102,7 @@ return folder_background_view_; } AppListFolderView* app_list_folder_view() { return app_list_folder_view_; } + PageSwitcher* page_switcher() { return page_switcher_; } // Updates suggestion chips from app list model. void UpdateSuggestionChips();
diff --git a/ash/app_list/views/search_result_page_view.cc b/ash/app_list/views/search_result_page_view.cc index 685f12e..3dbc726 100644 --- a/ash/app_list/views/search_result_page_view.cc +++ b/ash/app_list/views/search_result_page_view.cc
@@ -51,6 +51,12 @@ // The height of the search box in this page. constexpr int kSearchBoxHeight = 56; +// The spacing between search box bottom and separator line. +// Add 1 pixel spacing so that the search bbox bottom will not paint over +// the separator line drawn by SearchResultPageBackground in some scale factors +// due to the round up. +constexpr int kSearchBoxBottomSpacing = 1; + constexpr SkColor kSeparatorColor = SkColorSetA(gfx::kGoogleGrey900, 0x24); // The shadow elevation value for the shadow of the expanded search box. @@ -103,7 +109,7 @@ if (bounds.height() <= kSearchBoxHeight) return; // Draw a separator between SearchBoxView and SearchResultPageView. - bounds.set_y(kSearchBoxHeight); + bounds.set_y(kSearchBoxHeight + kSearchBoxBottomSpacing); bounds.set_height(kSeparatorThickness); canvas->FillRect(bounds, kSeparatorColor); } @@ -166,8 +172,9 @@ AppListConfig::instance().card_background_color())); views::ScrollView* const scroller = new views::ScrollView; // Leaves a placeholder area for the search box and the separator below it. - scroller->SetBorder(views::CreateEmptyBorder( - gfx::Insets(kSearchBoxHeight + kSeparatorThickness, 0, 0, 0))); + scroller->SetBorder(views::CreateEmptyBorder(gfx::Insets( + kSearchBoxHeight + kSearchBoxBottomSpacing + kSeparatorThickness, 0, 0, + 0))); scroller->SetDrawOverflowIndicator(false); scroller->SetContents(base::WrapUnique(contents_view_)); // Setting clip height is necessary to make ScrollView take into account its
diff --git a/ash/assistant/util/assistant_util.cc b/ash/assistant/util/assistant_util.cc index 4503ed5..0fd637b6 100644 --- a/ash/assistant/util/assistant_util.cc +++ b/ash/assistant/util/assistant_util.cc
@@ -5,6 +5,16 @@ #include "ash/assistant/util/assistant_util.h" #include "ash/assistant/model/assistant_ui_model.h" +#include "base/system/sys_info.h" + +namespace { + +constexpr char kEveBoardName[] = "eve"; +constexpr char kNocturneBoardName[] = "nocturne"; + +bool g_override_is_google_device = false; + +} // namespace namespace ash { namespace assistant { @@ -57,6 +67,16 @@ } } +bool IsGoogleDevice() { + const std::string board_name = base::SysInfo::GetLsbReleaseBoard(); + return g_override_is_google_device || board_name == kEveBoardName || + board_name == kNocturneBoardName; +} + +void OverrideIsGoogleDeviceForTesting() { + g_override_is_google_device = true; +} + } // namespace util } // namespace assistant } // namespace ash
diff --git a/ash/assistant/util/assistant_util.h b/ash/assistant/util/assistant_util.h index 720b20871..15b58535 100644 --- a/ash/assistant/util/assistant_util.h +++ b/ash/assistant/util/assistant_util.h
@@ -35,6 +35,12 @@ COMPONENT_EXPORT(ASSISTANT_UTIL) bool ShouldAttemptWarmerWelcome(AssistantEntryPoint entry_point); +COMPONENT_EXPORT(ASSISTANT_UTIL) +bool IsGoogleDevice(); + +COMPONENT_EXPORT(ASSISTANT_UTIL) +void OverrideIsGoogleDeviceForTesting(); + } // namespace util } // namespace assistant } // namespace ash
diff --git a/ash/login/ui/lock_screen_media_controls_view.cc b/ash/login/ui/lock_screen_media_controls_view.cc index 26ec2a7..02c25b2 100644 --- a/ash/login/ui/lock_screen_media_controls_view.cc +++ b/ash/login/ui/lock_screen_media_controls_view.cc
@@ -26,11 +26,13 @@ #include "ui/gfx/paint_vector_icon.h" #include "ui/message_center/message_center.h" #include "ui/message_center/vector_icons.h" +#include "ui/views/animation/ink_drop_mask.h" #include "ui/views/background.h" #include "ui/views/controls/button/image_button_factory.h" #include "ui/views/controls/image_view.h" #include "ui/views/controls/label.h" #include "ui/views/layout/box_layout.h" +#include "ui/views/layout/layout_provider.h" namespace ash { @@ -55,8 +57,8 @@ constexpr gfx::Size kArtworkSize = gfx::Size(80, 80); constexpr int kArtworkRowSeparator = 10; constexpr gfx::Size kArtworkRowPreferredSize = gfx::Size(300, 10); -constexpr gfx::Size kMediaButtonSize = gfx::Size(38, 38); -constexpr int kMediaButtonRowSeparator = 24; +constexpr gfx::Size kMediaButtonSize = gfx::Size(46, 46); +constexpr int kMediaButtonRowSeparator = 14; constexpr gfx::Insets kButtonRowInsets = gfx::Insets(10, 0, 0, 0); constexpr int kPlayPauseIconSize = 28; constexpr int kChangeTrackIconSize = 14; @@ -64,6 +66,7 @@ constexpr gfx::Size kMediaControlsButtonRowSize = gfx::Size(300, kMediaButtonSize.height()); constexpr int kArtworkCornerRadius = 4; +constexpr int kMediaActionButtonCornerRadius = kMediaButtonSize.width() / 2; constexpr int kDragVelocityThreshold = 6; constexpr int kDistanceDismissalThreshold = 20; @@ -123,6 +126,47 @@ return gfx::kNoneIcon; } +// MediaActionButton is an image button with a custom ink drop mask. +class MediaActionButton : public views::ImageButton { + public: + MediaActionButton(views::ButtonListener* listener, + int icon_size, + MediaSessionAction action, + const base::string16& accessible_name) + : views::ImageButton(listener), icon_size_(icon_size) { + SetInkDropMode(views::Button::InkDropMode::ON); + set_has_ink_drop_action_on_click(true); + SetImageHorizontalAlignment(views::ImageButton::ALIGN_CENTER); + SetImageVerticalAlignment(views::ImageButton::ALIGN_MIDDLE); + SetBorder( + views::CreateEmptyBorder(views::LayoutProvider::Get()->GetInsetsMetric( + views::INSETS_VECTOR_IMAGE_BUTTON))); + SetPreferredSize(kMediaButtonSize); + SetFocusBehavior(views::View::FocusBehavior::ALWAYS); + SetAction(action, accessible_name); + } + + ~MediaActionButton() override = default; + + void SetAction(MediaSessionAction action, + const base::string16& accessible_name) { + set_tag(static_cast<int>(action)); + SetTooltipText(accessible_name); + views::SetImageFromVectorIcon(this, GetVectorIconForMediaAction(action), + icon_size_, kMediaButtonColor); + } + + std::unique_ptr<views::InkDropMask> CreateInkDropMask() const override { + return std::make_unique<views::RoundRectInkDropMask>( + size(), gfx::Insets(), kMediaActionButtonCornerRadius); + } + + private: + int const icon_size_; + + DISALLOW_COPY_AND_ASSIGN(MediaActionButton); +}; + } // namespace const char LockScreenMediaControlsView::kMediaControlsHideHistogramName[] = @@ -241,47 +285,34 @@ button_row->SetPreferredSize(kMediaControlsButtonRowSize); button_row_ = contents_view_->AddChildView(std::move(button_row)); - CreateMediaButton( - kChangeTrackIconSize, MediaSessionAction::kPreviousTrack, + button_row_->AddChildView(std::make_unique<MediaActionButton>( + this, kChangeTrackIconSize, MediaSessionAction::kPreviousTrack, l10n_util::GetStringUTF16( - IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_PREVIOUS_TRACK)); + IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_PREVIOUS_TRACK))); - CreateMediaButton( - kSeekingIconsSize, MediaSessionAction::kSeekBackward, + button_row_->AddChildView(std::make_unique<MediaActionButton>( + this, kSeekingIconsSize, MediaSessionAction::kSeekBackward, l10n_util::GetStringUTF16( - IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_SEEK_BACKWARD)); + IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_SEEK_BACKWARD))); // |play_pause_button_| toggles playback. If the current media is playing, the // tag will be |MediaSessionAction::kPause|. If the current media is paused, // the tag will be |MediaSessionAction::kPlay|. - auto play_pause_button = views::CreateVectorToggleImageButton(this); - play_pause_button->set_tag(static_cast<int>(MediaSessionAction::kPause)); - play_pause_button->SetPreferredSize(kMediaButtonSize); - play_pause_button->SetFocusBehavior(views::View::FocusBehavior::ALWAYS); - play_pause_button->SetTooltipText(l10n_util::GetStringUTF16( - IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_PAUSE)); - play_pause_button->SetToggledTooltipText(l10n_util::GetStringUTF16( - IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_PLAY)); - play_pause_button_ = button_row_->AddChildView(std::move(play_pause_button)); + play_pause_button_ = + button_row_->AddChildView(std::make_unique<MediaActionButton>( + this, kPlayPauseIconSize, MediaSessionAction::kPause, + l10n_util::GetStringUTF16( + IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_PAUSE))); - // |play_pause_button_| icons. - views::SetImageFromVectorIcon( - play_pause_button_, - GetVectorIconForMediaAction(MediaSessionAction::kPause), - kPlayPauseIconSize, kMediaButtonColor); - views::SetToggledImageFromVectorIcon( - play_pause_button_, - GetVectorIconForMediaAction(MediaSessionAction::kPlay), - kPlayPauseIconSize, kMediaButtonColor); - - CreateMediaButton( - kSeekingIconsSize, MediaSessionAction::kSeekForward, + button_row_->AddChildView(std::make_unique<MediaActionButton>( + this, kSeekingIconsSize, MediaSessionAction::kSeekForward, l10n_util::GetStringUTF16( - IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_SEEK_FORWARD)); + IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_SEEK_FORWARD))); - CreateMediaButton(kChangeTrackIconSize, MediaSessionAction::kNextTrack, - l10n_util::GetStringUTF16( - IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_NEXT_TRACK)); + button_row_->AddChildView(std::make_unique<MediaActionButton>( + this, kChangeTrackIconSize, MediaSessionAction::kNextTrack, + l10n_util::GetStringUTF16( + IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_NEXT_TRACK))); // Set child view data to default values initially, until the media controller // observers are triggered by a change in media session state. @@ -583,23 +614,6 @@ media_controller_remote_.FlushForTesting(); } -void LockScreenMediaControlsView::CreateMediaButton( - int size, - MediaSessionAction action, - const base::string16& accessible_name) { - auto button = views::CreateVectorImageButton(this); - button->set_tag(static_cast<int>(action)); - button->SetPreferredSize(kMediaButtonSize); - button->SetAccessibleName(accessible_name); - button->SetFocusBehavior(views::View::FocusBehavior::ALWAYS); - - views::SetImageFromVectorIcon(button.get(), - GetVectorIconForMediaAction(action), size, - kMediaButtonColor); - - button_row_->AddChildView(std::move(button)); -} - void LockScreenMediaControlsView::UpdateActionButtonsVisibility() { std::set<MediaSessionAction> ignored_actions = { media_message_center::GetPlayPauseIgnoredAction( @@ -625,11 +639,17 @@ } void LockScreenMediaControlsView::SetIsPlaying(bool playing) { - MediaSessionAction action = - playing ? MediaSessionAction::kPause : MediaSessionAction::kPlay; - - play_pause_button_->SetToggled(!playing); - play_pause_button_->set_tag(static_cast<int>(action)); + if (playing) { + play_pause_button_->SetAction( + MediaSessionAction::kPause, + l10n_util::GetStringUTF16( + IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_PAUSE)); + } else { + play_pause_button_->SetAction( + MediaSessionAction::kPlay, + l10n_util::GetStringUTF16( + IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_PLAY)); + } UpdateActionButtonsVisibility(); }
diff --git a/ash/login/ui/lock_screen_media_controls_view.h b/ash/login/ui/lock_screen_media_controls_view.h index 839944f..ffd9b7a 100644 --- a/ash/login/ui/lock_screen_media_controls_view.h +++ b/ash/login/ui/lock_screen_media_controls_view.h
@@ -22,7 +22,6 @@ namespace views { class Label; class ImageView; -class ToggleImageButton; } // namespace views namespace media_message_center { @@ -31,6 +30,10 @@ namespace ash { +namespace { +class MediaActionButton; +} // namespace + class MediaControlsHeaderView; class NonAccessibleView; @@ -167,12 +170,6 @@ // Returns the rounded rectangle clip path for the current artwork. SkPath GetArtworkClipPath() const; - // Creates and adds a new media button to |button_row_|. This should not be - // used to create toggle buttons such as play/pause. - void CreateMediaButton(int size, - media_session::mojom::MediaSessionAction action, - const base::string16& accessible_name); - // Updates the visibility of buttons on |button_row_| depending on what is // available in the current media session. void UpdateActionButtonsVisibility(); @@ -251,7 +248,7 @@ views::Label* title_label_ = nullptr; views::Label* artist_label_ = nullptr; NonAccessibleView* button_row_ = nullptr; - views::ToggleImageButton* play_pause_button_ = nullptr; + MediaActionButton* play_pause_button_ = nullptr; media_message_center::MediaControlsProgressView* progress_ = nullptr; // Callbacks.
diff --git a/ash/login/ui/parent_access_view.cc b/ash/login/ui/parent_access_view.cc index 0a4a1c1d..4ee2111c 100644 --- a/ash/login/ui/parent_access_view.cc +++ b/ash/login/ui/parent_access_view.cc
@@ -21,6 +21,7 @@ #include "ash/wallpaper/wallpaper_controller_impl.h" #include "base/bind.h" #include "base/logging.h" +#include "base/metrics/histogram_macros.h" #include "base/optional.h" #include "base/strings/strcat.h" #include "base/strings/string16.h" @@ -28,6 +29,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" #include "base/threading/thread_task_runner_handle.h" +#include "components/session_manager/session_manager_types.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/l10n/l10n_util.h" @@ -179,6 +181,36 @@ DISALLOW_COPY_AND_ASSIGN(AccessibleInputField); }; +void RecordAction(ParentAccessView::UMAAction action) { + UMA_HISTOGRAM_ENUMERATION(ParentAccessView::kUMAParentAccessCodeAction, + action); +} + +void RecordUsage(ParentAccessRequestReason reason) { + switch (reason) { + case ParentAccessRequestReason::kUnlockTimeLimits: { + UMA_HISTOGRAM_ENUMERATION(ParentAccessView::kUMAParentAccessCodeUsage, + ParentAccessView::UMAUsage::kTimeLimits); + return; + } + case ParentAccessRequestReason::kChangeTime: { + bool is_login = Shell::Get()->session_controller()->GetSessionState() == + session_manager::SessionState::LOGIN_PRIMARY; + UMA_HISTOGRAM_ENUMERATION( + ParentAccessView::kUMAParentAccessCodeUsage, + is_login ? ParentAccessView::UMAUsage::kTimeChangeLoginScreen + : ParentAccessView::UMAUsage::kTimeChangeInSession); + return; + } + case ParentAccessRequestReason::kChangeTimezone: { + UMA_HISTOGRAM_ENUMERATION(ParentAccessView::kUMAParentAccessCodeUsage, + ParentAccessView::UMAUsage::kTimezoneChange); + return; + } + } + NOTREACHED() << "Unknown ParentAccessRequestReason"; +} + } // namespace // Digital access code input view for variable length of input codes. @@ -456,6 +488,12 @@ ParentAccessView::Callbacks::~Callbacks() = default; +// static +constexpr char ParentAccessView::kUMAParentAccessCodeAction[]; + +// static +constexpr char ParentAccessView::kUMAParentAccessCodeUsage[]; + ParentAccessView::ParentAccessView(const AccountId& account_id, const Callbacks& callbacks, ParentAccessRequestReason reason, @@ -627,6 +665,8 @@ pin_keyboard_view_->SetVisible(IsTabletMode()); tablet_mode_observer_.Add(Shell::Get()->tablet_mode_controller()); + + RecordUsage(request_reason_); } ParentAccessView::~ParentAccessView() = default; @@ -681,8 +721,10 @@ void ParentAccessView::ButtonPressed(views::Button* sender, const ui::Event& event) { if (sender == back_button_) { + RecordAction(ParentAccessView::UMAAction::kCanceledByUser); callbacks_.on_finished.Run(false); } else if (sender == help_button_) { + RecordAction(ParentAccessView::UMAAction::kGetHelp); Shell::Get()->login_screen_controller()->ShowParentAccessHelpApp(); } else if (sender == submit_button_) { SubmitCode(); @@ -721,11 +763,13 @@ if (result) { VLOG(1) << "Parent access code successfully validated"; + RecordAction(ParentAccessView::UMAAction::kValidationSuccess); callbacks_.on_finished.Run(true); return; } VLOG(1) << "Invalid parent access code entered"; + RecordAction(ParentAccessView::UMAAction::kValidationError); UpdateState(State::kError); }
diff --git a/ash/login/ui/parent_access_view.h b/ash/login/ui/parent_access_view.h index 3c7863f..1d78e86 100644 --- a/ash/login/ui/parent_access_view.h +++ b/ash/login/ui/parent_access_view.h
@@ -80,6 +80,36 @@ OnFinished on_finished; }; + // Actions that originated in parent access dialog. These values are persisted + // to metrics. Entries should not be renumbered and numeric values should + // never be reused. + enum class UMAAction { + kValidationSuccess = 0, + kValidationError = 1, + kCanceledByUser = 2, + kGetHelp = 3, + kMaxValue = kGetHelp, + }; + + // Context in which parent access code was used. These values are persisted to + // metrics. Entries should not be reordered and numeric values should never be + // reused. + enum class UMAUsage { + kTimeLimits = 0, + kTimeChangeLoginScreen = 1, + kTimeChangeInSession = 2, + kTimezoneChange = 3, + kMaxValue = kTimezoneChange, + }; + + // Histogram to log actions that originated in parent access dialog. + static constexpr char kUMAParentAccessCodeAction[] = + "Supervision.ParentAccessCode.Action"; + + // Histogram to log context in which parent access code was used. + static constexpr char kUMAParentAccessCodeUsage[] = + "Supervision.ParentAccessCode.Usage"; + // Creates parent access view that will validate the parent access code for a // specific child, when |account_id| is set, or to any child signed in the // device, when it is empty. |callbacks| will be called when user performs
diff --git a/ash/login/ui/parent_access_view_unittest.cc b/ash/login/ui/parent_access_view_unittest.cc index 44cfe6f..c2c7dcb 100644 --- a/ash/login/ui/parent_access_view_unittest.cc +++ b/ash/login/ui/parent_access_view_unittest.cc
@@ -13,6 +13,8 @@ #include "ash/login/ui/login_pin_view.h" #include "ash/login/ui/login_test_base.h" #include "ash/login/ui/login_test_utils.h" +#include "ash/login/ui/parent_access_widget.h" +#include "ash/session/test_session_controller_client.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" #include "ash/wm/tablet_mode/tablet_mode_controller.h" @@ -20,8 +22,10 @@ #include "base/macros.h" #include "base/optional.h" #include "base/test/bind_test_util.h" +#include "base/test/metrics/histogram_tester.h" #include "base/time/time.h" #include "components/account_id/account_id.h" +#include "components/session_manager/session_manager_types.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/l10n/l10n_util.h" #include "ui/events/base_event_utils.h" @@ -101,6 +105,40 @@ SetWidget(CreateWidgetWithContent(view_)); } + // Shows parent access widget with the specified |reason|. + void ShowWidget(ParentAccessRequestReason reason) { + ParentAccessWidget::Show( + account_id_, + base::BindRepeating(&ParentAccessViewTest::OnFinished, + base::Unretained(this)), + reason); + ParentAccessWidget* widget = ParentAccessWidget::Get(); + ASSERT_TRUE(widget); + } + + // Dismisses existing parent access widget with back button click. Should be + // only called when the widget is shown. + void DismissWidget() { + ParentAccessWidget* widget = ParentAccessWidget::Get(); + ASSERT_TRUE(widget); + + ParentAccessView* view = + ParentAccessWidget::TestApi(widget).parent_access_view(); + ParentAccessView::TestApi test_api(view); + ui::MouseEvent event(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), + ui::EventTimeForNow(), 0, 0); + view->ButtonPressed(test_api.back_button(), event); + } + + // Verifies expectation that UMA |action| was logged. + // Cannot be used when more than one action is reported. + void ExpectUMAActionReported(ParentAccessView::UMAAction action) { + histogram_tester_.ExpectBucketCount( + ParentAccessView::kUMAParentAccessCodeAction, action, 1); + histogram_tester_.ExpectTotalCount( + ParentAccessView::kUMAParentAccessCodeAction, 1); + } + const AccountId account_id_; std::unique_ptr<MockLoginScreenClient> login_client_; @@ -113,6 +151,8 @@ // Time that will be used on the code validation. base::Time validation_time_; + base::HistogramTester histogram_tester_; + ParentAccessView* view_ = nullptr; // Owned by test widget view hierarchy. private: @@ -151,6 +191,7 @@ EXPECT_EQ(1, back_action_); EXPECT_EQ(0, successful_validation_); + ExpectUMAActionReported(ParentAccessView::UMAAction::kCanceledByUser); } // Tests that submit button submits code from code input. @@ -176,6 +217,7 @@ SimulateButtonPress(test_api.submit_button()); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, successful_validation_); + ExpectUMAActionReported(ParentAccessView::UMAAction::kValidationSuccess); } // Tests that help button opens help app. @@ -188,6 +230,8 @@ EXPECT_CALL(*client, ShowParentAccessHelpApp()).Times(1); SimulateButtonPress(test_api.help_button()); + + ExpectUMAActionReported(ParentAccessView::UMAAction::kGetHelp); } // Tests that access code can be entered with numpad. @@ -210,6 +254,7 @@ SimulateButtonPress(test_api.submit_button()); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, successful_validation_); + ExpectUMAActionReported(ParentAccessView::UMAAction::kValidationSuccess); } // Tests that access code can be submitted with press of 'enter' key. @@ -234,6 +279,7 @@ generator->PressKey(ui::KeyboardCode::VKEY_RETURN, ui::EF_NONE); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, successful_validation_); + ExpectUMAActionReported(ParentAccessView::UMAAction::kValidationSuccess); } // Tests that 'enter' key does not submit incomplete code. @@ -273,6 +319,7 @@ generator->PressKey(ui::KeyboardCode::VKEY_RETURN, ui::EF_NONE); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, successful_validation_); + ExpectUMAActionReported(ParentAccessView::UMAAction::kValidationSuccess); } // Tests that backspace button works. @@ -322,6 +369,7 @@ SimulateButtonPress(test_api.submit_button()); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, successful_validation_); + ExpectUMAActionReported(ParentAccessView::UMAAction::kValidationSuccess); } // Tests input with virtual pin keyboard. @@ -347,6 +395,7 @@ SimulateButtonPress(test_api.submit_button()); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, successful_validation_); + ExpectUMAActionReported(ParentAccessView::UMAAction::kValidationSuccess); } // Tests that pin keyboard visibility changes upon tablet mode changes. @@ -387,6 +436,7 @@ base::RunLoop().RunUntilIdle(); EXPECT_EQ(ParentAccessView::State::kError, test_api.state()); EXPECT_EQ(0, successful_validation_); + ExpectUMAActionReported(ParentAccessView::UMAAction::kValidationError); // After access code is completed, focus moves to submit button. // Move focus back to access code input. @@ -406,6 +456,12 @@ SimulateButtonPress(test_api.submit_button()); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, successful_validation_); + + histogram_tester_.ExpectBucketCount( + ParentAccessView::kUMAParentAccessCodeAction, + ParentAccessView::UMAAction::kValidationError, 1); + histogram_tester_.ExpectTotalCount( + ParentAccessView::kUMAParentAccessCodeAction, 2); } // Tests children views traversal with tab key. @@ -477,4 +533,47 @@ EXPECT_TRUE(HasFocusInAnyChildView(test_api.access_code_view())); } +// Tests that correct usage metric is reported. +TEST_F(ParentAccessViewTest, UMAUsageMetric) { + ShowWidget(ParentAccessRequestReason::kUnlockTimeLimits); + DismissWidget(); + histogram_tester_.ExpectBucketCount( + ParentAccessView::kUMAParentAccessCodeUsage, + ParentAccessView::UMAUsage::kTimeLimits, 1); + + ShowWidget(ParentAccessRequestReason::kChangeTimezone); + DismissWidget(); + histogram_tester_.ExpectBucketCount( + ParentAccessView::kUMAParentAccessCodeUsage, + ParentAccessView::UMAUsage::kTimezoneChange, 1); + + // The below usage depends on the session state. + GetSessionControllerClient()->SetSessionState( + session_manager::SessionState::ACTIVE); + ShowWidget(ParentAccessRequestReason::kChangeTime); + DismissWidget(); + histogram_tester_.ExpectBucketCount( + ParentAccessView::kUMAParentAccessCodeUsage, + ParentAccessView::UMAUsage::kTimeChangeInSession, 1); + + GetSessionControllerClient()->SetSessionState( + session_manager::SessionState::LOGIN_PRIMARY); + ShowWidget(ParentAccessRequestReason::kChangeTime); + DismissWidget(); + histogram_tester_.ExpectBucketCount( + ParentAccessView::kUMAParentAccessCodeUsage, + ParentAccessView::UMAUsage::kTimeChangeLoginScreen, 1); + + GetSessionControllerClient()->SetSessionState( + session_manager::SessionState::ACTIVE); + ShowWidget(ParentAccessRequestReason::kChangeTime); + DismissWidget(); + histogram_tester_.ExpectBucketCount( + ParentAccessView::kUMAParentAccessCodeUsage, + ParentAccessView::UMAUsage::kTimeChangeInSession, 2); + + histogram_tester_.ExpectTotalCount( + ParentAccessView::kUMAParentAccessCodeUsage, 5); +} + } // namespace ash
diff --git a/ash/shell_test_api.cc b/ash/shell_test_api.cc index e1e7924e..1b9218b4 100644 --- a/ash/shell_test_api.cc +++ b/ash/shell_test_api.cc
@@ -12,6 +12,9 @@ #include "ash/app_list/app_list_controller_impl.h" #include "ash/app_list/presenter/app_list_presenter_impl.h" #include "ash/app_list/views/app_list_view.h" +#include "ash/home_screen/home_launcher_gesture_handler.h" +#include "ash/home_screen/home_launcher_gesture_handler_observer.h" +#include "ash/home_screen/home_screen_controller.h" #include "ash/keyboard/keyboard_controller_impl.h" #include "ash/public/cpp/app_list/app_list_types.h" #include "ash/public/cpp/tablet_mode_observer.h" @@ -104,6 +107,38 @@ DISALLOW_COPY_AND_ASSIGN(OverviewAnimationStateWaiter); }; +class HomeLauncherStateWaiter : public HomeLauncherGestureHandlerObserver { + public: + HomeLauncherStateWaiter(bool target_shown, base::OnceClosure closure) + : target_shown_(target_shown), closure_(std::move(closure)) { + Shell::Get() + ->home_screen_controller() + ->home_launcher_gesture_handler() + ->AddObserver(this); + } + ~HomeLauncherStateWaiter() override { + Shell::Get() + ->home_screen_controller() + ->home_launcher_gesture_handler() + ->RemoveObserver(this); + } + + private: + // HomeLauncherGestureHandlerObserver: + void OnHomeLauncherAnimationComplete(bool shown, + int64_t display_id) override { + if (shown == target_shown_) { + std::move(closure_).Run(); + delete this; + } + } + + bool target_shown_; + base::OnceClosure closure_; + + DISALLOW_COPY_AND_ASSIGN(HomeLauncherStateWaiter); +}; + // A waiter that waits until the animation ended with the target state, and // execute the callback. This self destruction upon completion. class LauncherStateWaiter { @@ -252,7 +287,31 @@ void ShellTestApi::WaitForLauncherAnimationState( ash::AppListViewState target_state) { base::RunLoop run_loop; - new LauncherStateWaiter(target_state, run_loop.QuitWhenIdleClosure()); + + // In the tablet mode, some of the app-list state switching is handled + // differently. For open and close, HomeLauncherGestureHandler handles the + // gestures and animation. HomeLauncherStateWaiter can wait for such + // animation. For switching between the search and apps-grid, + // LauncherStateWaiter can wait for the animation. + bool should_wait_for_home_launcher = false; + if (Shell::Get()->tablet_mode_controller()->InTabletMode() && + target_state != AppListViewState::kFullscreenSearch) { + // App-list can't enter into kPeeking or kHalf state. Thus |target_state| + // should be either kClosed or kFullscreenAllApps. + DCHECK(target_state == AppListViewState::kClosed || + target_state == AppListViewState::kFullscreenAllApps); + const AppListViewState current_state = + Shell::Get()->app_list_controller()->GetAppListViewState(); + should_wait_for_home_launcher = + (target_state == AppListViewState::kClosed) || + (current_state != AppListViewState::kFullscreenSearch); + } + if (should_wait_for_home_launcher) { + new HomeLauncherStateWaiter(target_state != ash::AppListViewState::kClosed, + run_loop.QuitWhenIdleClosure()); + } else { + new LauncherStateWaiter(target_state, run_loop.QuitWhenIdleClosure()); + } run_loop.Run(); }
diff --git a/ash/system/palette/palette_tool.cc b/ash/system/palette/palette_tool.cc index f3f5185..ff99f08 100644 --- a/ash/system/palette/palette_tool.cc +++ b/ash/system/palette/palette_tool.cc
@@ -6,6 +6,7 @@ #include <memory> +#include "ash/assistant/util/assistant_util.h" #include "ash/system/palette/palette_tool_manager.h" #include "ash/system/palette/palette_utils.h" #include "ash/system/palette/tools/capture_region_mode.h" @@ -14,7 +15,6 @@ #include "ash/system/palette/tools/laser_pointer_mode.h" #include "ash/system/palette/tools/magnifier_mode.h" #include "ash/system/palette/tools/metalayer_mode.h" -#include "chromeos/constants/chromeos_features.h" #include "ui/gfx/paint_vector_icon.h" namespace ash { @@ -24,7 +24,8 @@ tool_manager->AddTool(std::make_unique<CaptureRegionMode>(tool_manager)); tool_manager->AddTool(std::make_unique<CaptureScreenAction>(tool_manager)); tool_manager->AddTool(std::make_unique<CreateNoteAction>(tool_manager)); - tool_manager->AddTool(std::make_unique<MetalayerMode>(tool_manager)); + if (assistant::util::IsGoogleDevice()) + tool_manager->AddTool(std::make_unique<MetalayerMode>(tool_manager)); tool_manager->AddTool(std::make_unique<LaserPointerMode>(tool_manager)); tool_manager->AddTool(std::make_unique<MagnifierMode>(tool_manager)); }
diff --git a/ash/system/palette/palette_tray_unittest.cc b/ash/system/palette/palette_tray_unittest.cc index 9bd56cf5..f4ccafa7 100644 --- a/ash/system/palette/palette_tray_unittest.cc +++ b/ash/system/palette/palette_tray_unittest.cc
@@ -9,6 +9,7 @@ #include "ash/assistant/assistant_controller.h" #include "ash/assistant/test/test_assistant_service.h" +#include "ash/assistant/util/assistant_util.h" #include "ash/highlighter/highlighter_controller.h" #include "ash/highlighter/highlighter_controller_test_api.h" #include "ash/public/cpp/ash_pref_names.h" @@ -243,6 +244,8 @@ // PaletteTrayTest: void SetUp() override { + assistant::util::OverrideIsGoogleDeviceForTesting(); + PaletteTrayTest::SetUp(); // Instantiate EventGenerator now so that its constructor does not overwrite
diff --git a/ash/system/palette/palette_welcome_bubble.cc b/ash/system/palette/palette_welcome_bubble.cc index 59fd4cfb..c48cd4a 100644 --- a/ash/system/palette/palette_welcome_bubble.cc +++ b/ash/system/palette/palette_welcome_bubble.cc
@@ -6,13 +6,13 @@ #include <memory> +#include "ash/assistant/util/assistant_util.h" #include "ash/public/cpp/ash_pref_names.h" #include "ash/public/cpp/shell_window_ids.h" #include "ash/session/session_controller_impl.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" #include "ash/system/palette/palette_tray.h" -#include "chromeos/constants/chromeos_features.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "ui/aura/window.h" @@ -58,9 +58,10 @@ void Init() override { SetLayoutManager(std::make_unique<views::FillLayout>()); - // TODO(crbug.com/996312): Check if the board type is eligibile here. auto* label = new views::Label(l10n_util::GetStringUTF16( - IDS_ASH_STYLUS_WARM_WELCOME_BUBBLE_WITH_ASSISTANT_DESCRIPTION)); + assistant::util::IsGoogleDevice() + ? IDS_ASH_STYLUS_WARM_WELCOME_BUBBLE_WITH_ASSISTANT_DESCRIPTION + : IDS_ASH_STYLUS_WARM_WELCOME_BUBBLE_DESCRIPTION)); label->SetHorizontalAlignment(gfx::ALIGN_LEFT); label->SetMultiLine(true); label->SizeToFit(kBubbleContentLabelPreferredWidthDp);
diff --git a/base/BUILD.gn b/base/BUILD.gn index a0d94d1..5168c982 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -3258,7 +3258,6 @@ "android/java/src/org/chromium/base/compat/ApiHelperForP.java", "android/java/src/org/chromium/base/library_loader/LegacyLinker.java", "android/java/src/org/chromium/base/library_loader/LibraryLoader.java", - "android/java/src/org/chromium/base/library_loader/LibraryLoaderConfig.java", "android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java", "android/java/src/org/chromium/base/library_loader/Linker.java", "android/java/src/org/chromium/base/library_loader/LoaderErrors.java",
diff --git a/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java b/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java index 0f65c03..3ee374e 100644 --- a/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java +++ b/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java
@@ -191,7 +191,7 @@ */ public void preloadNowOverrideApplicationContext(Context appContext) { synchronized (mLock) { - if (LibraryLoaderConfig.useChromiumLinker()) return; + if (useChromiumLinker()) return; preloadAlreadyLocked(appContext.getApplicationInfo()); } } @@ -199,7 +199,7 @@ private void preloadAlreadyLocked(ApplicationInfo appInfo) { try (TraceEvent te = TraceEvent.scoped("LibraryLoader.preloadAlreadyLocked")) { // Preloader uses system linker, we shouldn't preload if Chromium linker is used. - assert !LibraryLoaderConfig.useChromiumLinker(); + assert !useChromiumLinker(); if (mLibraryPreloader != null && !mLibraryPreloaderCalled) { mLibraryPreloader.loadLibrary(appInfo); mLibraryPreloaderCalled = true; @@ -340,7 +340,7 @@ long startTime = SystemClock.uptimeMillis(); - if (LibraryLoaderConfig.useChromiumLinker() && !inZygote) { + if (useChromiumLinker() && !inZygote) { Linker linker = Linker.getInstance(); // See base/android/linker/config.gni, the chromium linker is only enabled when we @@ -559,7 +559,7 @@ // Called after all native initializations are complete. public void onBrowserNativeInitializationComplete() { synchronized (mLock) { - if (LibraryLoaderConfig.useChromiumLinker()) { + if (useChromiumLinker()) { RecordHistogram.recordTimesHistogram( "ChromiumAndroidLinker.BrowserLoadTime", mLibraryLoadTimeMs); } @@ -572,13 +572,22 @@ // RecordChromiumAndroidLinkerRendererHistogram() will record it correctly. public void registerRendererProcessHistogram() { synchronized (mLock) { - if (LibraryLoaderConfig.useChromiumLinker()) { + if (useChromiumLinker()) { LibraryLoaderJni.get().recordRendererLibraryLoadTime(mLibraryLoadTimeMs); } } } /** + * Call this method to determine if this chromium project must + * use this linker. If not, System.loadLibrary() should be used to load + * libraries instead. + */ + public static boolean useChromiumLinker() { + return NativeLibraries.sUseLinker; + } + + /** * Override the library loader (normally with a mock) for testing. * @param loader the mock library loader. */
diff --git a/base/android/java/src/org/chromium/base/library_loader/LibraryLoaderConfig.java b/base/android/java/src/org/chromium/base/library_loader/LibraryLoaderConfig.java deleted file mode 100644 index 48918f6..0000000 --- a/base/android/java/src/org/chromium/base/library_loader/LibraryLoaderConfig.java +++ /dev/null
@@ -1,33 +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. - -package org.chromium.base.library_loader; - -/** - * Build-time configuration of LibraryLoader. - * These are in a separate class from LibraryLoader to ensure that they are inlined. - */ -public class LibraryLoaderConfig { - private LibraryLoaderConfig() {} - - /** - * Check that native library linker tests are enabled. - * If not enabled, calls to testing functions will fail with an assertion - * error. - * - * @return true if native library linker tests are enabled. - */ - public static boolean areTestsEnabled() { - return NativeLibraries.sEnableLinkerTests; - } - - /** - * Call this method to determine if this chromium project must - * use this linker. If not, System.loadLibrary() should be used to load - * libraries instead. - */ - public static boolean useChromiumLinker() { - return NativeLibraries.sUseLinker; - } -}
diff --git a/base/android/java/src/org/chromium/base/library_loader/Linker.java b/base/android/java/src/org/chromium/base/library_loader/Linker.java index e271bd2..92570e27 100644 --- a/base/android/java/src/org/chromium/base/library_loader/Linker.java +++ b/base/android/java/src/org/chromium/base/library_loader/Linker.java
@@ -600,6 +600,16 @@ } /* ---------------------- Testing support methods. ---------------------- */ + /** + * Check that native library linker tests are enabled. + * If not enabled, calls to testing functions will fail with an assertion + * error. + * + * @return true if native library linker tests are enabled. + */ + public static boolean areTestsEnabled() { + return NativeLibraries.sEnableLinkerTests; + } /** * Get Linker implementation type.
diff --git a/base/android/proguard/chromium_code.flags b/base/android/proguard/chromium_code.flags index b06f78f..19f45e867a 100644 --- a/base/android/proguard/chromium_code.flags +++ b/base/android/proguard/chromium_code.flags
@@ -38,7 +38,7 @@ -keepclasseswithmembers class ** { @org.chromium.base.annotations.UsedByReflection <fields>; } --keepclasseswithmembers,includedescriptorclasses class !org.chromium.base.library_loader.**,** { +-keepclasseswithmembers,includedescriptorclasses class ** { native <methods>; }
diff --git a/base/android/proguard/chromium_linker.flags b/base/android/proguard/chromium_linker.flags deleted file mode 100644 index 30904bf..0000000 --- a/base/android/proguard/chromium_linker.flags +++ /dev/null
@@ -1,7 +0,0 @@ -# Copyright 2019 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - --keepclasseswithmembers,includedescriptorclasses class org.chromium.base.library_loader.** { - native <methods>; -}
diff --git a/base/android/proguard/no_chromium_linker.flags b/base/android/proguard/no_chromium_linker.flags deleted file mode 100644 index 3a7d347..0000000 --- a/base/android/proguard/no_chromium_linker.flags +++ /dev/null
@@ -1,9 +0,0 @@ -# Copyright 2019 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -# All references to Linker.getInstance() should be guarded by: -# LibraryLoaderConfig.useCrazyLinker(). --checkdiscard class org.chromium.base.library_loader.Linker { - *; -}
diff --git a/base/debug/stack_trace_unittest.cc b/base/debug/stack_trace_unittest.cc index 98acf9e4..07f51a0 100644 --- a/base/debug/stack_trace_unittest.cc +++ b/base/debug/stack_trace_unittest.cc
@@ -31,11 +31,20 @@ typedef testing::Test StackTraceTest; #endif +// TODO(https://crbug.com/999737): Rewrite this test for better clarity and +// correctness. // Note: On Linux, this test currently only fully works on Debug builds. // See comments in the #ifdef soup if you intend to change this. #if defined(OS_WIN) + // Always fails on Windows: crbug.com/32070 #define MAYBE_OutputToStream DISABLED_OutputToStream + +#elif defined(OS_FUCHSIA) && defined(OFFICIAL_BUILD) + +// Backtraces aren't supported by Fuchsia release-optimized builds. +#define MAYBE_OutputToStream DISABLED_OutputToStream + #else #define MAYBE_OutputToStream OutputToStream #endif
diff --git a/base/task/thread_pool/delayed_task_manager.cc b/base/task/thread_pool/delayed_task_manager.cc index a1ed0be..502b18e 100644 --- a/base/task/thread_pool/delayed_task_manager.cc +++ b/base/task/thread_pool/delayed_task_manager.cc
@@ -35,7 +35,10 @@ bool DelayedTaskManager::DelayedTask::operator<=( const DelayedTask& other) const { - return task.delayed_run_time <= other.task.delayed_run_time; + if (task.delayed_run_time == other.task.delayed_run_time) { + return task.sequence_num <= other.task.sequence_num; + } + return task.delayed_run_time < other.task.delayed_run_time; } bool DelayedTaskManager::DelayedTask::IsScheduled() const {
diff --git a/base/task/thread_pool/priority_queue_unittest.cc b/base/task/thread_pool/priority_queue_unittest.cc index af5cb75..454c230 100644 --- a/base/task/thread_pool/priority_queue_unittest.cc +++ b/base/task/thread_pool/priority_queue_unittest.cc
@@ -15,6 +15,7 @@ #include "base/task/thread_pool/sequence.h" #include "base/task/thread_pool/task.h" #include "base/test/gtest_util.h" +#include "base/test/task_environment.h" #include "base/time/time.h" #include "testing/gtest/include/gtest/gtest.h" @@ -45,6 +46,14 @@ num_user_blocking); } + void Push(scoped_refptr<TaskSource> task_source) { + // FastForward time to ensure that queue order between task sources is well + // defined. + task_environment.FastForwardBy(TimeDelta::FromMicroseconds(1)); + pq.Push(TransactionWithRegisteredTaskSource::FromTaskSource( + RegisteredTaskSource::CreateForTesting(std::move(task_source)))); + } + scoped_refptr<TaskSource> sequence_a = MakeSequenceWithTraitsAndTask( TaskTraits(ThreadPool(), TaskPriority::USER_VISIBLE)); SequenceSortKey sort_key_a = sequence_a->BeginTransaction().GetSortKey(); @@ -62,6 +71,8 @@ SequenceSortKey sort_key_d = sequence_d->BeginTransaction().GetSortKey(); PriorityQueue pq; + test::TaskEnvironment task_environment{ + test::ScopedTaskEnvironment::TimeSource::MOCK_TIME}; }; } // namespace @@ -72,29 +83,25 @@ // Push |sequence_a| in the PriorityQueue. It becomes the sequence with the // highest priority. - pq.Push(TransactionWithRegisteredTaskSource::FromTaskSource( - RegisteredTaskSource::CreateForTesting(sequence_a))); + Push(sequence_a); EXPECT_EQ(sort_key_a, pq.PeekSortKey()); ExpectNumSequences(0U, 1U, 0U); // Push |sequence_b| in the PriorityQueue. It becomes the sequence with the // highest priority. - pq.Push(TransactionWithRegisteredTaskSource::FromTaskSource( - RegisteredTaskSource::CreateForTesting(sequence_b))); + Push(sequence_b); EXPECT_EQ(sort_key_b, pq.PeekSortKey()); ExpectNumSequences(0U, 1U, 1U); // Push |sequence_c| in the PriorityQueue. |sequence_b| is still the sequence // with the highest priority. - pq.Push(TransactionWithRegisteredTaskSource::FromTaskSource( - RegisteredTaskSource::CreateForTesting(sequence_c))); + Push(sequence_c); EXPECT_EQ(sort_key_b, pq.PeekSortKey()); ExpectNumSequences(0U, 1U, 2U); // Push |sequence_d| in the PriorityQueue. |sequence_b| is still the sequence // with the highest priority. - pq.Push(TransactionWithRegisteredTaskSource::FromTaskSource( - RegisteredTaskSource::CreateForTesting(sequence_d))); + Push(sequence_d); EXPECT_EQ(sort_key_b, pq.PeekSortKey()); ExpectNumSequences(1U, 1U, 2U); @@ -127,14 +134,10 @@ // Push all test Sequences into the PriorityQueue. |sequence_b| // will be the sequence with the highest priority. - pq.Push(TransactionWithRegisteredTaskSource::FromTaskSource( - RegisteredTaskSource::CreateForTesting(sequence_a))); - pq.Push(TransactionWithRegisteredTaskSource::FromTaskSource( - RegisteredTaskSource::CreateForTesting(sequence_b))); - pq.Push(TransactionWithRegisteredTaskSource::FromTaskSource( - RegisteredTaskSource::CreateForTesting(sequence_c))); - pq.Push(TransactionWithRegisteredTaskSource::FromTaskSource( - RegisteredTaskSource::CreateForTesting(sequence_d))); + Push(sequence_a); + Push(sequence_b); + Push(sequence_c); + Push(sequence_d); EXPECT_EQ(sort_key_b, pq.PeekSortKey()); ExpectNumSequences(1U, 1U, 2U); @@ -176,14 +179,10 @@ // Push all test Sequences into the PriorityQueue. |sequence_b| becomes the // sequence with the highest priority. - pq.Push(TransactionWithRegisteredTaskSource::FromTaskSource( - RegisteredTaskSource::CreateForTesting(sequence_a))); - pq.Push(TransactionWithRegisteredTaskSource::FromTaskSource( - RegisteredTaskSource::CreateForTesting(sequence_b))); - pq.Push(TransactionWithRegisteredTaskSource::FromTaskSource( - RegisteredTaskSource::CreateForTesting(sequence_c))); - pq.Push(TransactionWithRegisteredTaskSource::FromTaskSource( - RegisteredTaskSource::CreateForTesting(sequence_d))); + Push(sequence_a); + Push(sequence_b); + Push(sequence_c); + Push(sequence_d); EXPECT_EQ(sort_key_b, pq.PeekSortKey()); ExpectNumSequences(1U, 1U, 2U);
diff --git a/build/android/apk_operations.py b/build/android/apk_operations.py index f9e509e..c6efb549f 100755 --- a/build/android/apk_operations.py +++ b/build/android/apk_operations.py
@@ -1525,8 +1525,7 @@ help='Build .apks archive that targets the bundle\'s minSdkVersion and ' 'contains only english splits. It still contains optional splits.') group.add_argument( - '--sdk-version', - help='Implies --minimal. The sdkVersion to build the .apks for.') + '--sdk-version', help='The sdkVersion to build the .apks for.') group.add_argument( '--build-mode', choices=app_bundle_utils.BUILD_APKS_MODES, @@ -1540,7 +1539,7 @@ _GenerateBundleApks( self.bundle_generation_info, self.args.output_apks, - minimal=self.args.sdk_version is not None or self.args.minimal, + minimal=self.args.minimal, minimal_sdk_version=self.args.sdk_version, mode=self.args.build_mode)
diff --git a/build/android/gyp/proguard.py b/build/android/gyp/proguard.py index 3ecda1b..328434110 100755 --- a/build/android/gyp/proguard.py +++ b/build/android/gyp/proguard.py
@@ -66,9 +66,6 @@ required=True, help='GN-list of configuration files.') parser.add_argument( - '--proguard-config-exclusions', - help='GN-list of paths to filter out of --proguard-configs') - parser.add_argument( '--apply-mapping', help='Path to ProGuard mapping to apply.') parser.add_argument( '--mapping-output', @@ -122,8 +119,6 @@ options.classpath = build_utils.ParseGnList(options.classpath) options.proguard_configs = build_utils.ParseGnList(options.proguard_configs) - options.proguard_config_exclusions = (build_utils.ParseGnList( - options.proguard_config_exclusions)) options.input_paths = build_utils.ParseGnList(options.input_paths) options.extra_mapping_output_paths = build_utils.ParseGnList( options.extra_mapping_output_paths) @@ -357,18 +352,12 @@ _VerifyNoEmbeddedConfigs(options.input_paths + libraries) - # Apply config exclusion filter. - config_paths = [ - p for p in options.proguard_configs - if p not in options.proguard_config_exclusions - ] - # ProGuard configs that are derived from flags. dynamic_config_data = _CreateDynamicConfig(options) # ProGuard configs that are derived from flags. merged_configs = _CombineConfigs( - config_paths, dynamic_config_data, exclude_generated=True) + options.proguard_configs, dynamic_config_data, exclude_generated=True) print_stdout = '-whyareyoukeeping' in merged_configs or options.verbose # Writing the config output before we know ProGuard is going to succeed isn't @@ -386,11 +375,11 @@ options.verify_expected_configs) if options.r8_path: - _OptimizeWithR8(options, config_paths, libraries, dynamic_config_data, - print_stdout) + _OptimizeWithR8(options, options.proguard_configs, libraries, + dynamic_config_data, print_stdout) else: - _OptimizeWithProguard(options, config_paths, libraries, dynamic_config_data, - print_stdout) + _OptimizeWithProguard(options, options.proguard_configs, libraries, + dynamic_config_data, print_stdout) # After ProGuard / R8 has run: for output in options.extra_mapping_output_paths:
diff --git a/build/android/pylib/utils/app_bundle_utils.py b/build/android/pylib/utils/app_bundle_utils.py index 2098f4f..afae645 100644 --- a/build/android/pylib/utils/app_bundle_utils.py +++ b/build/android/pylib/utils/app_bundle_utils.py
@@ -72,6 +72,10 @@ or "system_compressed". """ device_spec = None + if minimal_sdk_version: + assert minimal or system_image_locales, ( + 'minimal_sdk_version is only used when minimal or system_image_locales ' + 'is specified') if minimal: # Measure with one language split installed. Use Hindi because it is # popular. resource_size.py looks for splits/base-hi.apk.
diff --git a/build/chromeos/test_runner.py b/build/chromeos/test_runner.py index 9199c2b..9fbbf5e 100755 --- a/build/chromeos/test_runner.py +++ b/build/chromeos/test_runner.py
@@ -50,6 +50,8 @@ # depending on which lab machine you're on. LAB_DUT_HOSTNAME = 'variable_chromeos_device_hostname' +TAST_DEBUG_DOC = 'https://bit.ly/2LgvIXz' + class TestFormatError(Exception): pass @@ -349,6 +351,9 @@ # https://godoc.org/chromium.googlesource.com/chromiumos/platform/tast.git/src/chromiumos/tast/testing#Error for err in errors: error_log += str(err['stack']) + '\n' + error_log += ( + "\nIf you're unsure why this test failed, consult the steps " + 'outlined in\n%s\n' % TAST_DEBUG_DOC) base_result = base_test_result.BaseTestResult( test['name'], result, duration=duration_ms, log=error_log) suite_results.AddResult(base_result)
diff --git a/build/config/android/internal_rules.gni b/build/config/android/internal_rules.gni index 6a2611e..412864d 100644 --- a/build/config/android/internal_rules.gni +++ b/build/config/android/internal_rules.gni
@@ -1172,13 +1172,6 @@ "--proguard-configs=@FileArg($_rebased_build_config:deps_info:proguard_all_configs)", "--input-paths=@FileArg($_rebased_build_config:deps_info:java_runtime_classpath)", ] - if (defined(invoker.proguard_config_exclusions)) { - _rebased_proguard_config_exclusions = - rebase_path(invoker.proguard_config_exclusions, root_build_dir) - args += [ - "--proguard-config-exclusions=$_rebased_proguard_config_exclusions", - ] - } if (defined(invoker.proguard_args)) { args += invoker.proguard_args }
diff --git a/build/config/android/rules.gni b/build/config/android/rules.gni index c085a01..1aeb151 100644 --- a/build/config/android/rules.gni +++ b/build/config/android/rules.gni
@@ -2813,13 +2813,6 @@ if (defined(invoker.proguard_configs)) { proguard_configs += invoker.proguard_configs } - if (_use_chromium_linker) { - proguard_configs += - [ "//base/android/proguard/chromium_linker.flags" ] - } else { - proguard_configs += - [ "//base/android/proguard/no_chromium_linker.flags" ] - } if (_enable_main_dex_list) { proguard_configs += [ "//build/android/multidex.flags" ] }
diff --git a/build/config/ios/codesign.py b/build/config/ios/codesign.py index 11a021a..779e56d 100644 --- a/build/config/ios/codesign.py +++ b/build/config/ios/codesign.py
@@ -3,6 +3,7 @@ # found in the LICENSE file. import argparse +import codecs import datetime import fnmatch import glob @@ -510,6 +511,10 @@ def Main(): + # Cache this codec so that plistlib can find it. See + # https://crbug.com/999461#c12 for more details. + codecs.lookup('utf-8') + parser = argparse.ArgumentParser('codesign iOS bundles') subparsers = parser.add_subparsers()
diff --git a/build_overrides/vulkan_loader.gni b/build_overrides/vulkan_loader.gni index d0c7c523..f61d868 100644 --- a/build_overrides/vulkan_loader.gni +++ b/build_overrides/vulkan_loader.gni
@@ -4,8 +4,4 @@ import("//build_overrides/vulkan_common.gni") -vulkan_loader_extra_defines = [ - "ANGLE_VK_DATA_DIR=\"$angle_data_dir\"", - "ANGLE_VK_ICD_JSON=\"$angle_data_dir/VkICD_mock_icd.json\"", -] vulkan_loader_shared = angle_shared_libvulkan
diff --git a/cc/base/rtree.h b/cc/base/rtree.h index 83504eac6..2ee4e7cb 100644 --- a/cc/base/rtree.h +++ b/cc/base/rtree.h
@@ -63,6 +63,11 @@ const BoundsFunctor& bounds_getter, const PayloadFunctor& payload_getter); + // If false, this rtree does not have valid bounds and: + // - GetBoundsOrDie will CHECK. + // - Search* will have degraded performance. + bool has_valid_bounds() const { return has_valid_bounds_; } + // Given a query rect, returns elements that intersect the rect. Elements are // returned in the order they appeared in the initial container. void Search(const gfx::Rect& query, std::vector<T>* results) const; @@ -73,7 +78,8 @@ void SearchRefs(const gfx::Rect& query, std::vector<const T*>* results) const; // Returns the total bounds of all items in this rtree. - gfx::Rect GetBounds() const; + // if !has_valid_bounds() this function will CHECK. + gfx::Rect GetBoundsOrDie() const; // Returns respective bounds of all items in this rtree in the order of items. // Production code except tracing should not use this method. @@ -122,6 +128,15 @@ const gfx::Rect& query, std::vector<const T*>* results) const; + // The following two functions are slow fallback versions of SearchRecursive + // and SearchRefsRecursive for when !has_valid_bounds(). + void SearchRecursiveFallback(Node<T>* root, + const gfx::Rect& query, + std::vector<T>* results) const; + void SearchRefsRecursiveFallback(Node<T>* root, + const gfx::Rect& query, + std::vector<const T*>* results) const; + // Consumes the input array. Branch<T> BuildRecursive(std::vector<Branch<T>>* branches, int level); Node<T>* AllocateNodeAtLevel(int level); @@ -133,6 +148,9 @@ size_t num_data_elements_ = 0u; Branch<T> root_; std::vector<Node<T>> nodes_; + + // If false, the rtree encountered overflow does not have reliable bounds. + bool has_valid_bounds_ = true; }; template <typename T> @@ -275,6 +293,11 @@ branch.bounds.SetRect(x, y, base::ClampSub(right, x), base::ClampSub(bottom, y)); + // If we had to clamp right/bottom values, we've overflowed. + bool overflow = + branch.bounds.right() != right || branch.bounds.bottom() != bottom; + has_valid_bounds_ &= !overflow; + DCHECK_LT(new_branch_index, current_branch); (*branches)[new_branch_index] = std::move(branch); ++new_branch_index; @@ -286,16 +309,26 @@ template <typename T> void RTree<T>::Search(const gfx::Rect& query, std::vector<T>* results) const { results->clear(); - if (num_data_elements_ > 0 && query.Intersects(root_.bounds)) + if (num_data_elements_ == 0) + return; + if (!has_valid_bounds_) { + SearchRecursiveFallback(root_.subtree, query, results); + } else if (query.Intersects(root_.bounds)) { SearchRecursive(root_.subtree, query, results); + } } template <typename T> void RTree<T>::SearchRefs(const gfx::Rect& query, std::vector<const T*>* results) const { results->clear(); - if (num_data_elements_ > 0 && query.Intersects(root_.bounds)) + if (num_data_elements_ == 0) + return; + if (!has_valid_bounds_) { + SearchRefsRecursiveFallback(root_.subtree, query, results); + } else if (query.Intersects(root_.bounds)) { SearchRefsRecursive(root_.subtree, query, results); + } } template <typename T> @@ -326,8 +359,40 @@ } } +// When !has_valid_bounds(), any non-leaf bounds may have overflowed and be +// invalid. Iterate over the entire tree, checking bounds at each leaf. template <typename T> -gfx::Rect RTree<T>::GetBounds() const { +void RTree<T>::SearchRecursiveFallback(Node<T>* node, + const gfx::Rect& query, + std::vector<T>* results) const { + for (uint16_t i = 0; i < node->num_children; ++i) { + if (node->level == 0) { + if (query.Intersects(node->children[i].bounds)) + results->push_back(node->children[i].payload); + } else { + SearchRecursive(node->children[i].subtree, query, results); + } + } +} + +template <typename T> +void RTree<T>::SearchRefsRecursiveFallback( + Node<T>* node, + const gfx::Rect& query, + std::vector<const T*>* results) const { + for (uint16_t i = 0; i < node->num_children; ++i) { + if (node->level == 0) { + if (query.Intersects(node->children[i].bounds)) + results->push_back(&node->children[i].payload); + } else { + SearchRefsRecursive(node->children[i].subtree, query, results); + } + } +} + +template <typename T> +gfx::Rect RTree<T>::GetBoundsOrDie() const { + CHECK(has_valid_bounds_); return root_.bounds; } @@ -355,6 +420,7 @@ num_data_elements_ = 0; nodes_.clear(); root_.bounds = gfx::Rect(); + has_valid_bounds_ = true; } } // namespace cc
diff --git a/cc/base/rtree_unittest.cc b/cc/base/rtree_unittest.cc index 0ac0bc3a..55afad70 100644 --- a/cc/base/rtree_unittest.cc +++ b/cc/base/rtree_unittest.cc
@@ -9,6 +9,24 @@ #include "testing/gtest/include/gtest/gtest.h" namespace cc { +namespace { +// Helper function to use in place of rtree. Search that ensures that every +// call to Search / SearchRefs produces the same results. +template <typename T> +void SearchAndVerifyRefs(const RTree<T>& rtree, + const gfx::Rect& query, + std::vector<T>* results) { + rtree.Search(query, results); + + // Perform the same query with SearchRefs and make sure it matches Search. + std::vector<const T*> ref_results; + rtree.SearchRefs(query, &ref_results); + ASSERT_EQ(ref_results.size(), results->size()); + for (size_t i = 0; i < results->size(); ++i) { + EXPECT_EQ(*ref_results[i], (*results)[i]); + } +} +} // namespace TEST(RTreeTest, ReserveNodesDoesntDcheck) { // Make sure that anywhere between 0 and 1000 rects, our reserve math in rtree @@ -36,20 +54,20 @@ rtree.Build(rects); std::vector<size_t> results; - rtree.Search(gfx::Rect(0, 0, 50, 50), &results); + SearchAndVerifyRefs(rtree, gfx::Rect(0, 0, 50, 50), &results); ASSERT_EQ(2500u, results.size()); // Note that the results have to be sorted. for (size_t i = 0; i < 2500; ++i) { ASSERT_EQ(results[i], i); } - rtree.Search(gfx::Rect(0, 0, 50, 49), &results); + SearchAndVerifyRefs(rtree, gfx::Rect(0, 0, 50, 49), &results); ASSERT_EQ(2450u, results.size()); for (size_t i = 0; i < 2450; ++i) { ASSERT_EQ(results[i], i); } - rtree.Search(gfx::Rect(5, 6, 1, 1), &results); + SearchAndVerifyRefs(rtree, gfx::Rect(5, 6, 1, 1), &results); ASSERT_EQ(1u, results.size()); EXPECT_EQ(6u * 50 + 5u, results[0]); } @@ -66,14 +84,14 @@ rtree.Build(rects); std::vector<size_t> results; - rtree.Search(gfx::Rect(0, 0, 1, 1), &results); + SearchAndVerifyRefs(rtree, gfx::Rect(0, 0, 1, 1), &results); ASSERT_EQ(2500u, results.size()); // Both the checks for the elements assume elements are sorted. for (size_t i = 0; i < 2500; ++i) { ASSERT_EQ(results[i], i); } - rtree.Search(gfx::Rect(0, 49, 1, 1), &results); + SearchAndVerifyRefs(rtree, gfx::Rect(0, 49, 1, 1), &results); ASSERT_EQ(50u, results.size()); for (size_t i = 0; i < 50; ++i) { EXPECT_EQ(results[i], 2450u + i); @@ -103,11 +121,11 @@ for (int y = 0; y < 50; ++y) { for (int x = 0; x < 50; ++x) { std::vector<size_t> results; - rtree.Search(gfx::Rect(x, y, 1, 1), &results); + SearchAndVerifyRefs(rtree, gfx::Rect(x, y, 1, 1), &results); VerifySorted(results); - rtree.Search(gfx::Rect(x, y, 50, 1), &results); + SearchAndVerifyRefs(rtree, gfx::Rect(x, y, 50, 1), &results); VerifySorted(results); - rtree.Search(gfx::Rect(x, y, 1, 50), &results); + SearchAndVerifyRefs(rtree, gfx::Rect(x, y, 1, 50), &results); VerifySorted(results); } } @@ -115,7 +133,7 @@ TEST(RTreeTest, GetBoundsEmpty) { RTree<size_t> rtree; - EXPECT_EQ(gfx::Rect(), rtree.GetBounds()); + EXPECT_EQ(gfx::Rect(), rtree.GetBoundsOrDie()); EXPECT_TRUE(rtree.GetAllBoundsForTracing().empty()); } @@ -127,7 +145,7 @@ RTree<size_t> rtree; rtree.Build(rects); - EXPECT_EQ(gfx::Rect(5, 6, 19, 20), rtree.GetBounds()); + EXPECT_EQ(gfx::Rect(5, 6, 19, 20), rtree.GetBoundsOrDie()); std::map<size_t, gfx::Rect> expected_all_bounds = {{0, rects[0]}, {1, rects[1]}}; EXPECT_EQ(expected_all_bounds, rtree.GetAllBoundsForTracing()); @@ -141,7 +159,7 @@ RTree<size_t> rtree; rtree.Build(rects); - EXPECT_EQ(gfx::Rect(0, 0, 10, 10), rtree.GetBounds()); + EXPECT_EQ(gfx::Rect(0, 0, 10, 10), rtree.GetBoundsOrDie()); std::map<size_t, gfx::Rect> expected_all_bounds = {{0, rects[0]}, {1, rects[1]}}; EXPECT_EQ(expected_all_bounds, rtree.GetAllBoundsForTracing()); @@ -155,7 +173,7 @@ RTree<size_t> rtree; rtree.Build(rects); - EXPECT_EQ(gfx::Rect(5, 5, 5, 5), rtree.GetBounds()); + EXPECT_EQ(gfx::Rect(5, 5, 5, 5), rtree.GetBoundsOrDie()); std::map<size_t, gfx::Rect> expected_all_bounds = {{1, rects[1]}}; EXPECT_EQ(expected_all_bounds, rtree.GetAllBoundsForTracing()); } @@ -172,12 +190,12 @@ // Resetting should give the same as an empty rtree. rtree.Reset(); - EXPECT_EQ(gfx::Rect(), rtree.GetBounds()); + EXPECT_EQ(gfx::Rect(), rtree.GetBoundsOrDie()); EXPECT_TRUE(rtree.GetAllBoundsForTracing().empty()); // Should be able to rebuild from a reset rtree. rtree.Build(rects); - EXPECT_EQ(gfx::Rect(0, 0, 10, 10), rtree.GetBounds()); + EXPECT_EQ(gfx::Rect(0, 0, 10, 10), rtree.GetBoundsOrDie()); std::map<size_t, gfx::Rect> expected_all_bounds = { {0, rects[0]}, {1, rects[1]}, {2, rects[2]}, {3, rects[3]}}; EXPECT_EQ(expected_all_bounds, rtree.GetAllBoundsForTracing()); @@ -198,11 +216,11 @@ [](const Container& items, size_t index) { return items[index].second; }); std::vector<float> results; - rtree.Search(gfx::Rect(0, 0, 1, 1), &results); + SearchAndVerifyRefs(rtree, gfx::Rect(0, 0, 1, 1), &results); ASSERT_EQ(1u, results.size()); EXPECT_FLOAT_EQ(10.f, results[0]); - rtree.Search(gfx::Rect(5, 5, 10, 10), &results); + SearchAndVerifyRefs(rtree, gfx::Rect(5, 5, 10, 10), &results); ASSERT_EQ(4u, results.size()); // Items returned should be in the order they were inserted. EXPECT_FLOAT_EQ(40.f, results[0]); @@ -211,4 +229,78 @@ EXPECT_FLOAT_EQ(20.f, results[3]); } +TEST(RTreeTest, InvalidBounds) { + std::vector<gfx::Rect> rects; + rects.push_back(gfx::Rect(-INT_MAX, -INT_MAX, INT_MAX, INT_MAX)); + rects.push_back(gfx::Rect(100, 100, 10, 10)); + + RTree<size_t> rtree; + rtree.Build(rects); + + EXPECT_FALSE(rtree.has_valid_bounds()); +} + +TEST(RTreeTest, InvalidBoundsReset) { + std::vector<gfx::Rect> rects; + rects.push_back(gfx::Rect(-INT_MAX, -INT_MAX, INT_MAX, INT_MAX)); + rects.push_back(gfx::Rect(100, 100, 10, 10)); + + RTree<size_t> rtree; + rtree.Build(rects); + + EXPECT_FALSE(rtree.has_valid_bounds()); + + // Reset() should restore us to an empty (but valid) state. + rtree.Reset(); + ASSERT_TRUE(rtree.has_valid_bounds()); + EXPECT_EQ(rtree.GetBoundsOrDie(), gfx::Rect()); +} + +TEST(RTreeTest, InvalidBoundsSearch) { + std::vector<gfx::Rect> rects; + rects.push_back(gfx::Rect(-INT_MAX, -INT_MAX, INT_MAX, INT_MAX)); + rects.push_back(gfx::Rect(100, 100, 10, 10)); + rects.push_back(gfx::Rect(105, 105, 10, 10)); + rects.push_back(gfx::Rect(-50, -50, 10, 10)); + rects.push_back(gfx::Rect(INT_MAX - 100, INT_MAX - 100, 10, 10)); + + RTree<size_t> rtree; + rtree.Build(rects); + + EXPECT_FALSE(rtree.has_valid_bounds()); + + // Searching should still work. + std::vector<size_t> found; + SearchAndVerifyRefs(rtree, gfx::Rect(0, 0, INT_MAX, INT_MAX), &found); + EXPECT_EQ(found, std::vector<size_t>({1, 2, 4})); + SearchAndVerifyRefs(rtree, gfx::Rect(-INT_MAX, -INT_MAX, INT_MAX, INT_MAX), + &found); + EXPECT_EQ(found, std::vector<size_t>({0, 3})); + SearchAndVerifyRefs(rtree, gfx::Rect(-50, -50, INT_MAX, INT_MAX), &found); + EXPECT_EQ(found, std::vector<size_t>({0, 1, 2, 3, 4})); +} + +TEST(RTreeTest, InvalidBoundsGetAllBounds) { + std::vector<gfx::Rect> rects; + rects.push_back(gfx::Rect(-INT_MAX, -INT_MAX, INT_MAX, INT_MAX)); + rects.push_back(gfx::Rect(100, 100, 10, 10)); + rects.push_back(gfx::Rect(105, 105, 10, 10)); + rects.push_back(gfx::Rect(-50, -50, 10, 10)); + rects.push_back(gfx::Rect(INT_MAX - 100, INT_MAX - 100, 10, 10)); + + RTree<size_t> rtree; + rtree.Build(rects); + + EXPECT_FALSE(rtree.has_valid_bounds()); + + // Getting all bounds should still work. + std::map<size_t, gfx::Rect> all_bounds = rtree.GetAllBoundsForTracing(); + std::map<size_t, gfx::Rect> expected_all_bounds = {{0, rects[0]}, + {1, rects[1]}, + {2, rects[2]}, + {3, rects[3]}, + {4, rects[4]}}; + EXPECT_EQ(all_bounds, expected_all_bounds); +} + } // namespace cc
diff --git a/cc/layers/layer.cc b/cc/layers/layer.cc index d0121e5e..f622b2e 100644 --- a/cc/layers/layer.cc +++ b/cc/layers/layer.cc
@@ -564,7 +564,7 @@ return clip_rect_f; } -void Layer::SetMaskLayer(PictureLayer* mask_layer) { +void Layer::SetMaskLayer(scoped_refptr<PictureLayer> mask_layer) { DCHECK(IsPropertyChangeAllowed()); if (inputs_.mask_layer.get() == mask_layer) return;
diff --git a/cc/layers/layer.h b/cc/layers/layer.h index 688089e..d1fcf36 100644 --- a/cc/layers/layer.h +++ b/cc/layers/layer.h
@@ -217,7 +217,7 @@ // channel of the mask layer's content is used as an alpha mask of this // layer's content. IOW the mask's alpha is multiplied by this layer's alpha // for each matching pixel. - void SetMaskLayer(PictureLayer* mask_layer); + void SetMaskLayer(scoped_refptr<PictureLayer> mask_layer); PictureLayer* mask_layer() { return inputs_.mask_layer.get(); } // Marks the |dirty_rect| as being changed, which will cause a commit and
diff --git a/cc/layers/layer_unittest.cc b/cc/layers/layer_unittest.cc index 904b7f4..2c240f9 100644 --- a/cc/layers/layer_unittest.cc +++ b/cc/layers/layer_unittest.cc
@@ -288,7 +288,7 @@ EXPECT_SET_NEEDS_COMMIT(1, top->SetBounds(arbitrary_size)); EXPECT_SET_NEEDS_COMMIT(0, mask_layer1->SetBounds(arbitrary_size)); EXPECT_CALL(*layer_tree_host_, SetNeedsFullTreeSync()).Times(1); - EXECUTE_AND_VERIFY_SUBTREE_CHANGED(top->SetMaskLayer(mask_layer1.get())); + EXECUTE_AND_VERIFY_SUBTREE_CHANGED(top->SetMaskLayer(mask_layer1)); // Set up the impl layers after the full tree is constructed, including the // mask layer. @@ -948,8 +948,7 @@ EXPECT_SET_NEEDS_COMMIT(1, test_layer->SetHideLayerAndSubtree(true)); EXPECT_SET_NEEDS_COMMIT(1, test_layer->SetElementId(ElementId(2))); - EXPECT_SET_NEEDS_FULL_TREE_SYNC(1, - test_layer->SetMaskLayer(mask_layer1.get())); + EXPECT_SET_NEEDS_FULL_TREE_SYNC(1, test_layer->SetMaskLayer(mask_layer1)); // The above tests should not have caused a change to the needs_display flag. EXPECT_FALSE(LayerNeedsDisplay(test_layer.get())); @@ -1058,12 +1057,12 @@ scoped_refptr<PictureLayer> mask_replacement = PictureLayer::Create(&client); parent->AddChild(child); - child->SetMaskLayer(mask.get()); + child->SetMaskLayer(mask); EXPECT_EQ(parent.get(), child->parent()); EXPECT_EQ(child.get(), mask->parent()); - child->SetMaskLayer(mask_replacement.get()); + child->SetMaskLayer(mask_replacement); EXPECT_EQ(nullptr, mask->parent()); EXPECT_EQ(child.get(), mask_replacement->parent()); } @@ -1114,7 +1113,7 @@ // Set up a detached tree of layers. The host pointer should be nil for these // layers. parent->AddChild(child); - child->SetMaskLayer(mask.get()); + child->SetMaskLayer(mask); AssertLayerTreeHostMatchesForSubtree(parent.get(), nullptr); @@ -1157,7 +1156,7 @@ // Masks should pick up the new host too. FakeContentLayerClient client; scoped_refptr<PictureLayer> child_mask = PictureLayer::Create(&client); - child->SetMaskLayer(child_mask.get()); + child->SetMaskLayer(child_mask); parent->AddChild(child); AssertLayerTreeHostMatchesForSubtree(parent.get(), layer_tree_host.get()); @@ -1173,7 +1172,7 @@ // Same setup as the previous test. parent->AddChild(child); - child->SetMaskLayer(mask.get()); + child->SetMaskLayer(mask); LayerTreeHostFactory factory; auto animation_host1 = AnimationHost::CreateForTesting(ThreadInstance::MAIN); @@ -1245,7 +1244,7 @@ scoped_refptr<Layer> mask_child = Layer::Create(); scoped_refptr<PictureLayer> mask_replacement = PictureLayer::Create(&client); - parent->SetMaskLayer(mask.get()); + parent->SetMaskLayer(mask); mask->AddChild(mask_child); LayerTreeHostFactory factory; @@ -1257,7 +1256,7 @@ AssertLayerTreeHostMatchesForSubtree(parent.get(), layer_tree_host.get()); // Replacing the mask should clear out the old mask's subtree's host pointers. - parent->SetMaskLayer(mask_replacement.get()); + parent->SetMaskLayer(mask_replacement); EXPECT_EQ(nullptr, mask->layer_tree_host()); EXPECT_EQ(nullptr, mask_child->layer_tree_host()); @@ -1705,7 +1704,7 @@ // Setting a mask. FakeContentLayerClient client; scoped_refptr<PictureLayer> mask = PictureLayer::Create(&client); - clipped_2->SetMaskLayer(mask.get()); + clipped_2->SetMaskLayer(mask); // Setting a filter that moves pixels. FilterOperations move_pixel_filters; @@ -1818,7 +1817,7 @@ // Setting a mask. FakeContentLayerClient client; scoped_refptr<PictureLayer> mask = PictureLayer::Create(&client); - layer_2->SetMaskLayer(mask.get()); + layer_2->SetMaskLayer(mask); layer_1->SetRoundedCorner(kUpdatedRoundedCorners); layer_2->SetRoundedCorner(kUpdatedRoundedCorners);
diff --git a/cc/layers/texture_layer_unittest.cc b/cc/layers/texture_layer_unittest.cc index 23751c7..0f5a97da 100644 --- a/cc/layers/texture_layer_unittest.cc +++ b/cc/layers/texture_layer_unittest.cc
@@ -44,6 +44,7 @@ #include "components/viz/common/resources/returned_resource.h" #include "components/viz/common/resources/shared_bitmap.h" #include "components/viz/common/resources/transferable_resource.h" +#include "components/viz/common/surfaces/parent_local_surface_id_allocator.h" #include "components/viz/service/display/software_output_device.h" #include "components/viz/test/fake_output_surface.h" #include "gpu/GLES2/gl2extchromium.h" @@ -268,8 +269,10 @@ viz::SingleReleaseCallback::Create(test_data_.sw_release_callback_)); } - host->SetViewportRectAndScale(gfx::Rect(10, 10), 1.f, - viz::LocalSurfaceIdAllocation()); + viz::ParentLocalSurfaceIdAllocator allocator; + allocator.GenerateId(); + host->SetViewportRectAndScale( + gfx::Rect(10, 10), 1.f, allocator.GetCurrentLocalSurfaceIdAllocation()); host->SetVisible(true); host->SetRootLayer(layer);
diff --git a/cc/paint/display_item_list.cc b/cc/paint/display_item_list.cc index 403c58fa..fe7880d1 100644 --- a/cc/paint/display_item_list.cc +++ b/cc/paint/display_item_list.cc
@@ -144,6 +144,15 @@ auto state = std::make_unique<base::trace_event::TracedValue>(); state->BeginDictionary("params"); + gfx::Rect bounds; + if (rtree_.has_valid_bounds()) { + bounds = rtree_.GetBoundsOrDie(); + } else { + // For tracing code, just use the entire positive quadrant if the |rtree_| + // has invalid bounds. + bounds = gfx::Rect(INT_MAX, INT_MAX); + } + if (include_items) { state->BeginArray("items"); @@ -159,8 +168,7 @@ state.get()); SkPictureRecorder recorder; - SkCanvas* canvas = - recorder.beginRecording(gfx::RectToSkRect(rtree_.GetBounds())); + SkCanvas* canvas = recorder.beginRecording(gfx::RectToSkRect(bounds)); op->Raster(canvas, params); sk_sp<SkPicture> picture = recorder.finishRecordingAsPicture(); @@ -176,12 +184,11 @@ state->EndArray(); // "items". } - MathUtil::AddToTracedValue("layer_rect", rtree_.GetBounds(), state.get()); + MathUtil::AddToTracedValue("layer_rect", bounds, state.get()); state->EndDictionary(); // "params". { SkPictureRecorder recorder; - gfx::Rect bounds = rtree_.GetBounds(); SkCanvas* canvas = recorder.beginRecording(gfx::RectToSkRect(bounds)); canvas->translate(-bounds.x(), -bounds.y()); canvas->clipRect(gfx::RectToSkRect(bounds)); @@ -197,7 +204,16 @@ void DisplayItemList::GenerateDiscardableImagesMetadata() { DCHECK(usage_hint_ == kTopLevelDisplayItemList); - image_map_.Generate(&paint_op_buffer_, rtree_.GetBounds()); + + gfx::Rect bounds; + if (rtree_.has_valid_bounds()) { + bounds = rtree_.GetBoundsOrDie(); + } else { + // Bounds are only used to size an SkNoDrawCanvas, pass INT_MAX. + bounds = gfx::Rect(INT_MAX, INT_MAX); + } + + image_map_.Generate(&paint_op_buffer_, bounds); } void DisplayItemList::Reset() { @@ -231,7 +247,7 @@ DCHECK(usage_hint_ == kTopLevelDisplayItemList); std::vector<size_t>* offsets_to_use = nullptr; std::vector<size_t> offsets; - if (!rect.Contains(rtree_.GetBounds())) { + if (rtree_.has_valid_bounds() && !rect.Contains(rtree_.GetBoundsOrDie())) { rtree_.Search(rect, &offsets); offsets_to_use = &offsets; }
diff --git a/cc/test/layer_tree_test.cc b/cc/test/layer_tree_test.cc index 9d72cdc2..78ae4b69 100644 --- a/cc/test/layer_tree_test.cc +++ b/cc/test/layer_tree_test.cc
@@ -4,6 +4,9 @@ #include "cc/test/layer_tree_test.h" +#include <memory> +#include <string> + #include "base/bind.h" #include "base/cfi_buildflags.h" #include "base/command_line.h" @@ -824,7 +827,15 @@ beginning_ = true; SetupTree(); WillBeginTest(); + bool allocate_local_surface_id = !skip_allocate_initial_local_surface_id_ && + settings_.enable_surface_synchronization; + if (allocate_local_surface_id) + GenerateNewLocalSurfaceId(); BeginTest(); + if (allocate_local_surface_id) { + PostSetLocalSurfaceIdAllocationToMainThread( + GetCurrentLocalSurfaceIdAllocation()); + } beginning_ = false; if (end_when_begin_returns_) RealEndTest(); @@ -837,6 +848,19 @@ } } +void LayerTreeTest::SkipAllocateInitialLocalSurfaceId() { + skip_allocate_initial_local_surface_id_ = true; +} + +const viz::LocalSurfaceIdAllocation& +LayerTreeTest::GetCurrentLocalSurfaceIdAllocation() const { + return allocator_.GetCurrentLocalSurfaceIdAllocation(); +} + +void LayerTreeTest::GenerateNewLocalSurfaceId() { + allocator_.GenerateId(); +} + void LayerTreeTest::SetupTree() { if (!layer_tree_host()->root_layer()) { layer_tree_host()->SetRootLayer(Layer::Create());
diff --git a/cc/test/layer_tree_test.h b/cc/test/layer_tree_test.h index 522fd40..4bbc7e805 100644 --- a/cc/test/layer_tree_test.h +++ b/cc/test/layer_tree_test.h
@@ -14,6 +14,7 @@ #include "cc/trees/compositor_mode.h" #include "cc/trees/layer_tree_host.h" #include "cc/trees/layer_tree_host_impl.h" +#include "components/viz/common/surfaces/parent_local_surface_id_allocator.h" #include "components/viz/test/test_gpu_memory_buffer_manager.h" #include "testing/gtest/include/gtest/gtest.h" @@ -112,6 +113,11 @@ protected: LayerTreeTest(); + void SkipAllocateInitialLocalSurfaceId(); + const viz::LocalSurfaceIdAllocation& GetCurrentLocalSurfaceIdAllocation() + const; + void GenerateNewLocalSurfaceId(); + virtual void InitializeSettings(LayerTreeSettings* settings) {} void RealEndTest(); @@ -258,6 +264,8 @@ std::unique_ptr<TestTaskGraphRunner> task_graph_runner_; base::CancelableOnceClosure timeout_; scoped_refptr<viz::TestContextProvider> compositor_contexts_; + bool skip_allocate_initial_local_surface_id_ = false; + viz::ParentLocalSurfaceIdAllocator allocator_; base::WeakPtr<LayerTreeTest> main_thread_weak_ptr_; base::WeakPtrFactory<LayerTreeTest> weak_factory_{this}; };
diff --git a/cc/test/test_layer_tree_frame_sink.cc b/cc/test/test_layer_tree_frame_sink.cc index 540fa92..a6a3631 100644 --- a/cc/test/test_layer_tree_frame_sink.cc +++ b/cc/test/test_layer_tree_frame_sink.cc
@@ -116,8 +116,7 @@ frame_sink_manager_->RegisterBeginFrameSource(display_begin_frame_source_, frame_sink_id_); } - display_->Initialize(this, frame_sink_manager_->surface_manager(), - true /* enable_shared_images */); + display_->Initialize(this, frame_sink_manager_->surface_manager()); display_->renderer_for_testing()->SetEnlargePassTextureAmountForTesting( enlarge_pass_texture_amount_); display_->SetColorSpace(output_color_space_);
diff --git a/cc/trees/layer_tree_host_pixeltest_blending.cc b/cc/trees/layer_tree_host_pixeltest_blending.cc index 7d5ea2a..6c045aa 100644 --- a/cc/trees/layer_tree_host_pixeltest_blending.cc +++ b/cc/trees/layer_tree_host_pixeltest_blending.cc
@@ -151,7 +151,7 @@ PaintImage::GetNextContentId()) .TakePaintImage(), SkMatrix::I(), false); - layer->SetMaskLayer(mask.get()); + layer->SetMaskLayer(mask); } void SetupColorMatrix(scoped_refptr<Layer> layer) {
diff --git a/cc/trees/layer_tree_host_pixeltest_masks.cc b/cc/trees/layer_tree_host_pixeltest_masks.cc index a2c70cf..ba32c9bd 100644 --- a/cc/trees/layer_tree_host_pixeltest_masks.cc +++ b/cc/trees/layer_tree_host_pixeltest_masks.cc
@@ -112,7 +112,7 @@ mask->SetBounds(mask_bounds); mask->SetIsDrawable(true); mask->SetLayerMaskType(mask_type_); - green->SetMaskLayer(mask.get()); + green->SetMaskLayer(mask); pixel_comparator_ = std::make_unique<FuzzyPixelOffByOneComparator>(true); @@ -381,7 +381,7 @@ scoped_refptr<SolidColorLayer> green = CreateSolidColorLayerWithBorder( gfx::Rect(25, 25, 50, 50), kCSSGreen, 1, SK_ColorBLACK); - green->SetMaskLayer(mask.get()); + green->SetMaskLayer(mask); background->AddChild(green); pixel_comparator_ = @@ -412,7 +412,7 @@ mask->SetBounds(mask_bounds); mask->SetIsDrawable(true); mask->SetLayerMaskType(mask_type_); - green->SetMaskLayer(mask.get()); + green->SetMaskLayer(mask); pixel_comparator_ = std::make_unique<FuzzyPixelOffByOneComparator>(true /* discard_alpha */); @@ -437,7 +437,7 @@ mask->SetIsDrawable(true); mask->SetLayerMaskType(mask_type_); mask->set_fixed_tile_size(gfx::Size(173, 135)); - green->SetMaskLayer(mask.get()); + green->SetMaskLayer(mask); pixel_comparator_ = std::make_unique<FuzzyPixelOffByOneComparator>(true /* discard_alpha */); @@ -571,7 +571,7 @@ mask->SetBounds(mask_bounds); mask->SetIsDrawable(true); mask->SetLayerMaskType(mask_type_); - blur->SetMaskLayer(mask.get()); + blur->SetMaskLayer(mask); CHECK_EQ(Layer::LayerMaskType::SINGLE_TEXTURE_MASK, mask->mask_type()); base::FilePath image_name = @@ -626,7 +626,7 @@ mask->SetBounds(mask_bounds); mask->SetIsDrawable(true); mask->SetLayerMaskType(mask_type_); - picture_horizontal->SetMaskLayer(mask.get()); + picture_horizontal->SetMaskLayer(mask); float percentage_pixels_large_error = 0.04f; // 0.04%, ~6px / (128*128) float percentage_pixels_small_error = 0.0f; @@ -1049,7 +1049,7 @@ mask->SetBounds(mask_bounds); mask->SetIsDrawable(true); mask->SetLayerMaskType(mask_type_); - picture_horizontal->SetMaskLayer(mask.get()); + picture_horizontal->SetMaskLayer(mask); base::FilePath result_path( FILE_PATH_LITERAL("mask_of_backdrop_filter_and_blend_.png"));
diff --git a/cc/trees/layer_tree_host_unittest.cc b/cc/trees/layer_tree_host_unittest.cc index 7d93c323..eeba5d1 100644 --- a/cc/trees/layer_tree_host_unittest.cc +++ b/cc/trees/layer_tree_host_unittest.cc
@@ -615,6 +615,11 @@ class LayerTreeHostFreeContextResourcesOnDestroy : public LayerTreeHostContextCacheTest { public: + void InitializeSettings(LayerTreeSettings* settings) override { + // TODO(crbug.com/985009): Fix test with surface sync enabled. + settings->enable_surface_synchronization = false; + } + void WillBeginImplFrameOnThread(LayerTreeHostImpl* host_impl, const viz::BeginFrameArgs& args) override { // Ensure that our initialization expectations have completed. @@ -1745,6 +1750,11 @@ class LayerTreeHostTestAnimationTransformMutatedNotUsingLayerLists : public LayerTreeHostTest { protected: + void InitializeSettings(LayerTreeSettings* settings) override { + // TODO(crbug.com/985009): Fix test with surface sync enabled. + settings->enable_surface_synchronization = false; + } + void BeginTest() override { Layer* root = layer_tree_host()->root_layer(); EXPECT_EQ(gfx::Transform(), root->transform()); @@ -2145,7 +2155,7 @@ child_layer_->SetBounds(gfx::Size(10, 10)); mask_layer_ = base::MakeRefCounted<UpdateCountingLayer>(&client_); mask_layer_->SetBounds(gfx::Size(10, 10)); - child_layer_->SetMaskLayer(mask_layer_.get()); + child_layer_->SetMaskLayer(mask_layer_); root->AddChild(child_layer_); layer_tree_host()->SetRootLayer(root); LayerTreeHostTest::SetupTree(); @@ -2166,7 +2176,7 @@ EXPECT_EQ(child_layer_->update_count(), 0); layer_tree_host()->root_layer()->RemoveAllChildren(); - layer_tree_host()->root_layer()->SetMaskLayer(mask_layer_.get()); + layer_tree_host()->root_layer()->SetMaskLayer(mask_layer_); break; } } @@ -2312,8 +2322,8 @@ root->SetBounds(bounds_); layer_->SetBounds(bounds_); layer_tree_host()->SetRootLayer(root); - layer_tree_host()->SetViewportRectAndScale(gfx::Rect(bounds_), 1.f, - viz::LocalSurfaceIdAllocation()); + layer_tree_host()->SetViewportRectAndScale( + gfx::Rect(bounds_), 1.f, GetCurrentLocalSurfaceIdAllocation()); PostSetNeedsCommitToMainThread(); client_.set_bounds(layer_->bounds()); @@ -2348,8 +2358,9 @@ void DidCommitAndDrawFrame() override { // On the second commit, resize the viewport. if (num_draws_ == 1) { + GenerateNewLocalSurfaceId(); layer_tree_host()->SetViewportRectAndScale( - gfx::Rect(400, 64), 1.f, viz::LocalSurfaceIdAllocation()); + gfx::Rect(400, 64), 1.f, GetCurrentLocalSurfaceIdAllocation()); } if (num_draws_ < 2) { layer_tree_host()->SetNeedsRedrawRect(invalid_rect_); @@ -3467,30 +3478,20 @@ class LayerTreeHostInvalidLocalSurfaceIdDefersCommit : public LayerTreeHostTestDeferMainFrameUpdate { public: - LayerTreeHostInvalidLocalSurfaceIdDefersCommit() = default; - void InitializeSettings(LayerTreeSettings* settings) override { - // With surface synchronization turned on, commits are deferred until a - // LocalSurfaceId has been assigned. The set up code sets the size of the - // LayerTreeHost (using SetViewportRectAndScale()), without providing a - // LocalSurfaceId. So, commits should be deferred until we set an id later - // during the test (in AllowCommits() override below). - settings->enable_surface_synchronization = true; + LayerTreeHostInvalidLocalSurfaceIdDefersCommit() { + SkipAllocateInitialLocalSurfaceId(); } - void BeginTest() override { PostSetNeedsCommitToMainThread(); } void AllowCommits() override { - allocator_.GenerateId(); + GenerateNewLocalSurfaceId(); PostSetLocalSurfaceIdAllocationToMainThread( - allocator_.GetCurrentLocalSurfaceIdAllocation()); + GetCurrentLocalSurfaceIdAllocation()); } bool IsCommitAllowed() const override { - return allocator_.GetCurrentLocalSurfaceIdAllocation().IsValid(); + return GetCurrentLocalSurfaceIdAllocation().IsValid(); } - - private: - viz::ParentLocalSurfaceIdAllocator allocator_; }; SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostInvalidLocalSurfaceIdDefersCommit); @@ -4353,8 +4354,9 @@ ++expected_push_properties_grandchild_; break; case 10: + GenerateNewLocalSurfaceId(); layer_tree_host()->SetViewportRectAndScale( - gfx::Rect(20, 20), 1.f, viz::LocalSurfaceIdAllocation()); + gfx::Rect(20, 20), 1.f, GetCurrentLocalSurfaceIdAllocation()); // No layers need commit. break; case 11: @@ -6734,12 +6736,13 @@ // Setting an empty viewport causes draws to get skipped, so the active // tree won't update draw properties. layer_tree_host()->SetViewportRectAndScale( - gfx::Rect(), 1.f, viz::LocalSurfaceIdAllocation()); + gfx::Rect(), 1.f, GetCurrentLocalSurfaceIdAllocation()); child_->SetForceRenderSurfaceForTesting(false); break; case 3: layer_tree_host()->SetViewportRectAndScale( - gfx::Rect(root_->bounds()), 1.f, viz::LocalSurfaceIdAllocation()); + gfx::Rect(root_->bounds()), 1.f, + GetCurrentLocalSurfaceIdAllocation()); } } @@ -7710,37 +7713,24 @@ // Makes sure that viz::LocalSurfaceId is propagated to the LayerTreeFrameSink. class LayerTreeHostTestLocalSurfaceId : public LayerTreeHostTest { protected: - void InitializeSettings(LayerTreeSettings* settings) override { - settings->enable_surface_synchronization = true; - } - - void BeginTest() override { - allocator_.GenerateId(); - expected_local_surface_id_allocation_ = - allocator_.GetCurrentLocalSurfaceIdAllocation(); - PostSetLocalSurfaceIdAllocationToMainThread( - expected_local_surface_id_allocation_); - } + void BeginTest() override {} DrawResult PrepareToDrawOnThread(LayerTreeHostImpl* host_impl, LayerTreeHostImpl::FrameData* frame_data, DrawResult draw_result) override { EXPECT_EQ(DRAW_SUCCESS, draw_result); EXPECT_EQ( - expected_local_surface_id_allocation_, + GetCurrentLocalSurfaceIdAllocation(), host_impl->active_tree()->local_surface_id_allocation_from_parent()); return draw_result; } void DisplayReceivedLocalSurfaceIdOnThread( const viz::LocalSurfaceId& local_surface_id) override { - EXPECT_EQ(expected_local_surface_id_allocation_.local_surface_id(), + EXPECT_EQ(GetCurrentLocalSurfaceIdAllocation().local_surface_id(), local_surface_id); EndTest(); } - - viz::LocalSurfaceIdAllocation expected_local_surface_id_allocation_; - viz::ParentLocalSurfaceIdAllocator allocator_; }; SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostTestLocalSurfaceId); @@ -7748,18 +7738,9 @@ // viz::LocalSurfaceIds that only involve the child sequence number. class LayerTreeHostTestLocalSurfaceIdSkipChildNum : public LayerTreeHostTest { protected: - void InitializeSettings(LayerTreeSettings* settings) override { - settings->enable_surface_synchronization = true; - } - void BeginTest() override { - allocator_.GenerateId(); - expected_local_surface_id_allocation_ = - allocator_.GetCurrentLocalSurfaceIdAllocation(); EXPECT_TRUE(child_allocator_.UpdateFromParent( - allocator_.GetCurrentLocalSurfaceIdAllocation())); - PostSetLocalSurfaceIdAllocationToMainThread( - expected_local_surface_id_allocation_); + GetCurrentLocalSurfaceIdAllocation())); } DrawResult PrepareToDrawOnThread(LayerTreeHostImpl* host_impl, @@ -7768,7 +7749,7 @@ EXPECT_EQ(DRAW_SUCCESS, draw_result); // We should not be picking up the newer |child_local_surface_id_|. EXPECT_EQ( - expected_local_surface_id_allocation_, + GetCurrentLocalSurfaceIdAllocation(), host_impl->active_tree()->local_surface_id_allocation_from_parent()); // This initial test setup triggers a commit and subsequent draw. Upon the @@ -7784,7 +7765,7 @@ child_allocator_.GenerateId(); child_local_surface_id_allocation_ = child_allocator_.GetCurrentLocalSurfaceIdAllocation(); - EXPECT_NE(expected_local_surface_id_allocation_, + EXPECT_NE(GetCurrentLocalSurfaceIdAllocation(), child_local_surface_id_allocation_); PostSetLocalSurfaceIdAllocationToMainThread( child_local_surface_id_allocation_); @@ -7795,14 +7776,12 @@ void DisplayReceivedLocalSurfaceIdOnThread( const viz::LocalSurfaceId& local_surface_id) override { - EXPECT_EQ(expected_local_surface_id_allocation_.local_surface_id(), + EXPECT_EQ(GetCurrentLocalSurfaceIdAllocation().local_surface_id(), local_surface_id); EndTest(); } - viz::LocalSurfaceIdAllocation expected_local_surface_id_allocation_; viz::LocalSurfaceIdAllocation child_local_surface_id_allocation_; - viz::ParentLocalSurfaceIdAllocator allocator_; viz::ChildLocalSurfaceIdAllocator child_allocator_; }; SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostTestLocalSurfaceIdSkipChildNum); @@ -7811,16 +7790,7 @@ // to LayerTreeFrameSink. class LayerTreeHostTestRequestNewLocalSurfaceId : public LayerTreeHostTest { protected: - void InitializeSettings(LayerTreeSettings* settings) override { - settings->enable_surface_synchronization = true; - } - void BeginTest() override { - allocator_.GenerateId(); - expected_parent_local_surface_id_allocation_ = - allocator_.GetCurrentLocalSurfaceIdAllocation(); - PostSetLocalSurfaceIdAllocationToMainThread( - expected_parent_local_surface_id_allocation_); PostRequestNewLocalSurfaceIdToMainThread(); } @@ -7829,7 +7799,7 @@ DrawResult draw_result) override { EXPECT_EQ(DRAW_SUCCESS, draw_result); EXPECT_EQ( - expected_parent_local_surface_id_allocation_, + GetCurrentLocalSurfaceIdAllocation(), host_impl->active_tree()->local_surface_id_allocation_from_parent()); return draw_result; } @@ -7837,7 +7807,7 @@ void DisplayReceivedLocalSurfaceIdOnThread( const viz::LocalSurfaceId& local_surface_id) override { const viz::LocalSurfaceId& expected_parent_local_surface_id = - expected_parent_local_surface_id_allocation_.local_surface_id(); + GetCurrentLocalSurfaceIdAllocation().local_surface_id(); viz::LocalSurfaceId child_local_surface_id( expected_parent_local_surface_id.parent_sequence_number(), expected_parent_local_surface_id.child_sequence_number() + 1, @@ -7853,9 +7823,6 @@ host_impl->active_tree()->new_local_surface_id_request_for_testing()); EndTest(); } - - viz::LocalSurfaceIdAllocation expected_parent_local_surface_id_allocation_; - viz::ParentLocalSurfaceIdAllocator allocator_; }; SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostTestRequestNewLocalSurfaceId); @@ -8593,7 +8560,7 @@ mask_client_.set_bounds(gfx::Size(9, 9)); mask_->SetBounds(gfx::Size(9, 9)); - child_->SetMaskLayer(mask_.get()); + child_->SetMaskLayer(mask_); root->AddChild(child_); layer_tree_host()->SetRootLayer(std::move(root)); LayerTreeTest::SetupTree(); @@ -8648,28 +8615,18 @@ public: LayerTreeHostTestNewLocalSurfaceIdForcesDraw() {} - void InitializeSettings(LayerTreeSettings* settings) override { - settings->enable_surface_synchronization = true; - } - void BeginTest() override { layer_tree_host()->SetViewportRectAndScale(gfx::Rect(10, 10), 1.f, viz::LocalSurfaceIdAllocation()); layer_tree_host()->root_layer()->SetBounds(gfx::Size(10, 10)); - allocator_.GenerateId(); - local_surface_id_allocation_ = - allocator_.GetCurrentLocalSurfaceIdAllocation(); - PostSetLocalSurfaceIdAllocationToMainThread(local_surface_id_allocation_); } void DidReceiveCompositorFrameAck() override { switch (layer_tree_host()->SourceFrameNumber()) { case 1: - allocator_.GenerateId(); - local_surface_id_allocation_ = - allocator_.GetCurrentLocalSurfaceIdAllocation(); + GenerateNewLocalSurfaceId(); PostSetLocalSurfaceIdAllocationToMainThread( - local_surface_id_allocation_); + GetCurrentLocalSurfaceIdAllocation()); break; case 2: EndTest(); @@ -8678,9 +8635,6 @@ NOTREACHED(); } } - - viz::LocalSurfaceIdAllocation local_surface_id_allocation_; - viz::ParentLocalSurfaceIdAllocator allocator_; }; SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostTestNewLocalSurfaceIdForcesDraw);
diff --git a/cc/trees/layer_tree_host_unittest_context.cc b/cc/trees/layer_tree_host_unittest_context.cc index 74079803..55bb0a7 100644 --- a/cc/trees/layer_tree_host_unittest_context.cc +++ b/cc/trees/layer_tree_host_unittest_context.cc
@@ -936,7 +936,7 @@ PictureLayer::Create(&client_); layer_with_mask->SetBounds(gfx::Size(10, 10)); layer_with_mask->SetIsDrawable(true); - layer_with_mask->SetMaskLayer(mask.get()); + layer_with_mask->SetMaskLayer(mask); root->AddChild(layer_with_mask); scoped_refptr<VideoLayer> video_color =
diff --git a/cc/trees/layer_tree_host_unittest_copyrequest.cc b/cc/trees/layer_tree_host_unittest_copyrequest.cc index 936d2e3d..2545887 100644 --- a/cc/trees/layer_tree_host_unittest_copyrequest.cc +++ b/cc/trees/layer_tree_host_unittest_copyrequest.cc
@@ -321,7 +321,7 @@ // Prevent drawing so we can't make a copy of the impl_destroyed layer. layer_tree_host()->SetViewportRectAndScale( - gfx::Rect(), 1.f, viz::LocalSurfaceIdAllocation()); + gfx::Rect(), 1.f, GetCurrentLocalSurfaceIdAllocation()); break; case 2: // Flush the message loops and make sure the callbacks run. @@ -768,7 +768,8 @@ if (layer_tree_host()->SourceFrameNumber() == 1) { // Allow drawing. layer_tree_host()->SetViewportRectAndScale( - gfx::Rect(root_->bounds()), 1.f, viz::LocalSurfaceIdAllocation()); + gfx::Rect(root_->bounds()), 1.f, + GetCurrentLocalSurfaceIdAllocation()); AddCopyRequest(copy_layer_.get()); } @@ -1154,8 +1155,9 @@ base::Unretained(this))); copy_layer_->RequestCopyOfOutput(std::move(request)); + // Stop drawing. layer_tree_host()->SetViewportRectAndScale( - gfx::Rect(), 1.f, viz::LocalSurfaceIdAllocation()); + gfx::Rect(), 1.f, GetCurrentLocalSurfaceIdAllocation()); break; } case 2: @@ -1168,7 +1170,7 @@ // Allow us to draw now. layer_tree_host()->SetViewportRectAndScale( gfx::Rect(layer_tree_host()->root_layer()->bounds()), 1.f, - viz::LocalSurfaceIdAllocation()); + GetCurrentLocalSurfaceIdAllocation()); break; case 4: EXPECT_EQ(1, callback_count_); @@ -1243,7 +1245,7 @@ copy_layer_->RequestCopyOfOutput(std::move(request)); layer_tree_host()->SetViewportRectAndScale( - gfx::Rect(), 1.f, viz::LocalSurfaceIdAllocation()); + gfx::Rect(), 1.f, GetCurrentLocalSurfaceIdAllocation()); break; } case 2:
diff --git a/cc/trees/layer_tree_host_unittest_damage.cc b/cc/trees/layer_tree_host_unittest_damage.cc index 9169032..945d4e9 100644 --- a/cc/trees/layer_tree_host_unittest_damage.cc +++ b/cc/trees/layer_tree_host_unittest_damage.cc
@@ -107,7 +107,7 @@ switch (layer_tree_host()->SourceFrameNumber()) { case 1: layer_tree_host()->SetViewportRectAndScale( - gfx::Rect(15, 15), 1.f, viz::LocalSurfaceIdAllocation()); + gfx::Rect(15, 15), 1.f, GetCurrentLocalSurfaceIdAllocation()); break; } }
diff --git a/cc/trees/layer_tree_host_unittest_masks.cc b/cc/trees/layer_tree_host_unittest_masks.cc index 8791283..3a2edb4 100644 --- a/cc/trees/layer_tree_host_unittest_masks.cc +++ b/cc/trees/layer_tree_host_unittest_masks.cc
@@ -40,7 +40,7 @@ scoped_refptr<FakePictureLayer> mask_layer = FakePictureLayer::CreateWithRecordingSource( &client_, std::move(recording_source)); - content_layer->SetMaskLayer(mask_layer.get()); + content_layer->SetMaskLayer(mask_layer); gfx::Size root_size(100, 100); root->SetBounds(root_size); @@ -134,7 +134,7 @@ scoped_refptr<FakePictureLayer> mask_layer = FakePictureLayer::CreateWithRecordingSource( &client_, std::move(recording_source)); - content_layer->SetMaskLayer(mask_layer.get()); + content_layer->SetMaskLayer(mask_layer); gfx::Size root_size(100, 100); root->SetBounds(root_size); @@ -239,7 +239,7 @@ scoped_refptr<FakePictureLayer> mask_layer = FakePictureLayer::CreateWithRecordingSource( &client_, std::move(recording_source)); - content_layer->SetMaskLayer(mask_layer.get()); + content_layer->SetMaskLayer(mask_layer); gfx::Size root_size(100, 100); root->SetBounds(root_size); @@ -356,7 +356,7 @@ scoped_refptr<FakePictureLayer> mask_layer = FakePictureLayer::CreateWithRecordingSource( &client_, std::move(recording_source)); - content_layer->SetMaskLayer(mask_layer.get()); + content_layer->SetMaskLayer(mask_layer); gfx::Size root_size(100, 100); root->SetBounds(root_size); @@ -423,8 +423,10 @@ switch (layer_tree_host()->SourceFrameNumber()) { case 1: gfx::Size double_root_size(200, 200); + GenerateNewLocalSurfaceId(); layer_tree_host()->SetViewportRectAndScale( - gfx::Rect(double_root_size), 2.f, viz::LocalSurfaceIdAllocation()); + gfx::Rect(double_root_size), 2.f, + GetCurrentLocalSurfaceIdAllocation()); break; } } @@ -458,7 +460,7 @@ scoped_refptr<FakePictureLayer> mask_layer = FakePictureLayer::CreateWithRecordingSource( &client_, std::move(recording_source)); - content_layer->SetMaskLayer(mask_layer.get()); + content_layer->SetMaskLayer(mask_layer); gfx::Size root_size(100, 100); root->SetBounds(root_size);
diff --git a/cc/trees/layer_tree_host_unittest_occlusion.cc b/cc/trees/layer_tree_host_unittest_occlusion.cc index 052427cf..244eb6f 100644 --- a/cc/trees/layer_tree_host_unittest_occlusion.cc +++ b/cc/trees/layer_tree_host_unittest_occlusion.cc
@@ -151,7 +151,7 @@ scoped_refptr<PictureLayer> mask = PictureLayer::Create(&client_); mask->SetBounds(gfx::Size(30, 40)); mask->SetIsDrawable(true); - child_->SetMaskLayer(mask.get()); + child_->SetMaskLayer(mask); scoped_refptr<Layer> child2 = Layer::Create(); child2->SetBounds(gfx::Size(10, 12)); @@ -222,7 +222,7 @@ scoped_refptr<PictureLayer> mask = PictureLayer::Create(&client_); mask->SetBounds(gfx::Size(30, 40)); mask->SetIsDrawable(true); - child_->SetMaskLayer(mask.get()); + child_->SetMaskLayer(mask); scoped_refptr<Layer> child2 = Layer::Create(); child2->SetBounds(gfx::Size(10, 11));
diff --git a/cc/trees/layer_tree_host_unittest_picture.cc b/cc/trees/layer_tree_host_unittest_picture.cc index 532cd5a..1a10b7a 100644 --- a/cc/trees/layer_tree_host_unittest_picture.cc +++ b/cc/trees/layer_tree_host_unittest_picture.cc
@@ -192,8 +192,9 @@ // Change the picture layer's size along with the viewport, so it will // consider picking a new tile size. picture_->SetBounds(gfx::Size(768, 1056)); + GenerateNewLocalSurfaceId(); layer_tree_host()->SetViewportRectAndScale( - gfx::Rect(768, 1056), 1.f, viz::LocalSurfaceIdAllocation()); + gfx::Rect(768, 1056), 1.f, GetCurrentLocalSurfaceIdAllocation()); break; case 2: EndTest();
diff --git a/cc/trees/layer_tree_host_unittest_proxy.cc b/cc/trees/layer_tree_host_unittest_proxy.cc index 95efcf99..457b2d1 100644 --- a/cc/trees/layer_tree_host_unittest_proxy.cc +++ b/cc/trees/layer_tree_host_unittest_proxy.cc
@@ -82,6 +82,11 @@ LayerTreeHostProxyTestSetNeedsAnimate& operator=( const LayerTreeHostProxyTestSetNeedsAnimate&) = delete; + void InitializeSettings(LayerTreeSettings* settings) override { + // TODO(crbug.com/985009): Fix test with surface sync enabled. + settings->enable_surface_synchronization = false; + } + void BeginTest() override { EXPECT_EQ(ProxyMain::NO_PIPELINE_STAGE, GetProxyMain()->max_requested_pipeline_stage()); @@ -155,6 +160,11 @@ LayerTreeHostProxyTestSetNeedsUpdateLayersWhileAnimating& operator=( const LayerTreeHostProxyTestSetNeedsUpdateLayersWhileAnimating&) = delete; + void InitializeSettings(LayerTreeSettings* settings) override { + // TODO(crbug.com/985009): Fix test with surface sync enabled. + settings->enable_surface_synchronization = false; + } + void BeginTest() override { proxy()->SetNeedsAnimate(); } void WillBeginMainFrame() override { @@ -199,6 +209,11 @@ LayerTreeHostProxyTestSetNeedsCommitWhileAnimating& operator=( const LayerTreeHostProxyTestSetNeedsCommitWhileAnimating&) = delete; + void InitializeSettings(LayerTreeSettings* settings) override { + // TODO(crbug.com/985009): Fix test with surface sync enabled. + settings->enable_surface_synchronization = false; + } + void BeginTest() override { proxy()->SetNeedsAnimate(); } void WillBeginMainFrame() override {
diff --git a/cc/trees/layer_tree_settings.h b/cc/trees/layer_tree_settings.h index 8fdcc41..ea0dfd5 100644 --- a/cc/trees/layer_tree_settings.h +++ b/cc/trees/layer_tree_settings.h
@@ -111,7 +111,7 @@ // Indicates that the LayerTreeHost should defer commits unless it has a valid // viz::LocalSurfaceId set. - bool enable_surface_synchronization = false; + bool enable_surface_synchronization = true; // Indicates the case when a sub-frame gets its own LayerTree because it's // rendered in a different process from its ancestor frames.
diff --git a/cc/trees/tree_synchronizer_unittest.cc b/cc/trees/tree_synchronizer_unittest.cc index fb22e52..0869072 100644 --- a/cc/trees/tree_synchronizer_unittest.cc +++ b/cc/trees/tree_synchronizer_unittest.cc
@@ -532,7 +532,7 @@ // First child gets a mask layer. FakeContentLayerClient client; scoped_refptr<PictureLayer> mask_layer = PictureLayer::Create(&client); - layer_tree_root->children()[0]->SetMaskLayer(mask_layer.get()); + layer_tree_root->children()[0]->SetMaskLayer(mask_layer); host_->SetRootLayer(layer_tree_root); host_->BuildPropertyTreesForTesting();
diff --git a/chrome/android/BUILD.gn b/chrome/android/BUILD.gn index 6dcb3ea..61b901a 100644 --- a/chrome/android/BUILD.gn +++ b/chrome/android/BUILD.gn
@@ -738,9 +738,8 @@ "//url/mojom:url_mojom_gurl_java", ] - srcjar_deps = [ - "//components/module_installer/android:module_installer_apk_build_config", - ] + srcjar_deps = + [ "//components/module_installer/android:module_installer_build_config" ] package_name = chrome_public_manifest_package }
diff --git a/chrome/android/chrome_java_sources.gni b/chrome/android/chrome_java_sources.gni index 0f45d0a..c5139a474 100644 --- a/chrome/android/chrome_java_sources.gni +++ b/chrome/android/chrome_java_sources.gni
@@ -1431,10 +1431,12 @@ "java/src/org/chromium/chrome/browser/share/ShareHelper.java", "java/src/org/chromium/chrome/browser/share/ShareMenuActionHandler.java", "java/src/org/chromium/chrome/browser/share/ShareParams.java", + "java/src/org/chromium/chrome/browser/sharing/SharingAdapter.java", "java/src/org/chromium/chrome/browser/sharing/SharingNotificationUtil.java", "java/src/org/chromium/chrome/browser/sharing/click_to_call/ClickToCallMessageHandler.java", "java/src/org/chromium/chrome/browser/sharing/click_to_call/ClickToCallUma.java", "java/src/org/chromium/chrome/browser/sharing/shared_clipboard/SharedClipboardMessageHandler.java", + "java/src/org/chromium/chrome/browser/sharing/shared_clipboard/SharedClipboardShareActivity.java", "java/src/org/chromium/chrome/browser/sharing/SharingJNIBridge.java", "java/src/org/chromium/chrome/browser/sharing/SharingServiceProxy.java", "java/src/org/chromium/chrome/browser/signin/AccountPickerDialogFragment.java",
diff --git a/chrome/android/chrome_public_apk_tmpl.gni b/chrome/android/chrome_public_apk_tmpl.gni index 0af49f1..3659b5c 100644 --- a/chrome/android/chrome_public_apk_tmpl.gni +++ b/chrome/android/chrome_public_apk_tmpl.gni
@@ -241,20 +241,6 @@ srcjar_deps = [ "//components/module_installer/android:module_installer_apk_build_config" ] } - if (!defined(use_chromium_linker)) { - use_chromium_linker = chromium_linker_supported - } - if (use_chromium_linker) { - if (!defined(load_library_from_apk)) { - # Whether native libraries should be loaded from within the apk. - # Only attempt loading the library from the APK for 64 bit devices - # until the number of 32 bit devices which don't support this - # approach falls to a minimal level - http://crbug.com/390618. - load_library_from_apk = chromium_linker_supported && - (current_cpu == "arm64" || current_cpu == "x64") - } - } - if (!is_java_debug) { proguard_enabled = true if (!defined(proguard_configs)) { @@ -274,6 +260,20 @@ } } + if (!defined(use_chromium_linker)) { + use_chromium_linker = chromium_linker_supported + } + + if (use_chromium_linker) { + if (!defined(load_library_from_apk)) { + # Whether native libraries should be loaded from within the apk. + # Only attempt loading the library from the APK for 64 bit devices + # until the number of 32 bit devices which don't support this + # approach falls to a minimal level - http://crbug.com/390618. + load_library_from_apk = chromium_linker_supported && + (current_cpu == "arm64" || current_cpu == "x64") + } + } if (_target_type == "android_apk") { command_line_flags_file = "chrome-command-line" } else {
diff --git a/chrome/android/java/AndroidManifest.xml b/chrome/android/java/AndroidManifest.xml index 5421847..d269d07 100644 --- a/chrome/android/java/AndroidManifest.xml +++ b/chrome/android/java/AndroidManifest.xml
@@ -902,6 +902,23 @@ </intent-filter> </activity> + <activity + android:name="org.chromium.chrome.browser.sharing.shared_clipboard.SharedClipboardShareActivity" + android:icon="@drawable/ic_devices_48dp" + android:label="@string/shared_clipboard_share_activity_title" + android:enabled="false" + android:excludeFromRecents="true" + android:exported="true" + android:noHistory="true" + android:theme="@style/Theme.Chromium.Activity.Translucent" + android:configChanges="orientation|keyboardHidden|keyboard|screenSize|mcc|mnc|screenLayout|smallestScreenSize" > + <intent-filter> + <action android:name="android.intent.action.SEND" /> + <category android:name="android.intent.category.DEFAULT" /> + <data android:mimeType="text/plain" /> + </intent-filter> + </activity> + <!-- Activity for dispatching intents to Instant Apps. --> <activity android:name="org.chromium.chrome.browser.instantapps.AuthenticatedProxyActivity" @@ -1244,6 +1261,8 @@ <receiver android:name="org.chromium.chrome.browser.send_tab_to_self.NotificationManager$TimeoutReceiver" android:exported="false"/> + <receiver android:name="org.chromium.chrome.browser.sharing.SharingNotificationUtil$ActionReceiver" + android:exported="false"/> <receiver android:name="org.chromium.chrome.browser.sharing.click_to_call.ClickToCallMessageHandler$TapReceiver" android:exported="false"/> <receiver android:name="org.chromium.chrome.browser.sharing.shared_clipboard.SharedClipboardMessageHandler$TapReceiver"
diff --git a/chrome/android/java/monochrome_public_bundle.proguard_flags.expected b/chrome/android/java/monochrome_public_bundle.proguard_flags.expected index c2016b75..0eedde8 100644 --- a/chrome/android/java/monochrome_public_bundle.proguard_flags.expected +++ b/chrome/android/java/monochrome_public_bundle.proguard_flags.expected
@@ -42,6 +42,10 @@ -keep class com.android.webview.chromium.DrawGLFunctor -keep class com.android.webview.chromium.GraphicsUtils +# Linker dynamically casts to $TestRunner when running tests. We don't run these +# tests in WebView. +-dontnote org.chromium.base.library_loader.Linker$TestRunner + # Don't note about the API 21 compatibility code which references various # hidden APIs via reflection. -dontnote com.android.webview.chromium.WebViewDelegateFactory$Api21CompatibilityDelegate @@ -207,7 +211,7 @@ -keepclasseswithmembers class ** { @org.chromium.base.annotations.UsedByReflection <fields>; } --keepclasseswithmembers,includedescriptorclasses class !org.chromium.base.library_loader.**,** { +-keepclasseswithmembers,includedescriptorclasses class ** { native <methods>; } @@ -270,19 +274,6 @@ -repackageclasses '' ################################################################################ -# ../../base/android/proguard/no_chromium_linker.flags -################################################################################ -# Copyright 2019 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -# All references to Linker.getInstance() should be guarded by: -# LibraryLoaderConfig.useCrazyLinker(). --checkdiscard class org.chromium.base.library_loader.Linker { - *; -} - -################################################################################ # ../../build/android/buildhooks/proguard/build_hooks_android_impl.flags ################################################################################ # Copyright 2018 The Chromium Authors. All rights reserved.
diff --git a/chrome/android/java/monochrome_public_bundle__base_bundle_module.AndroidManifest.expected b/chrome/android/java/monochrome_public_bundle__base_bundle_module.AndroidManifest.expected index c5f5ede8..b6c3459 100644 --- a/chrome/android/java/monochrome_public_bundle__base_bundle_module.AndroidManifest.expected +++ b/chrome/android/java/monochrome_public_bundle__base_bundle_module.AndroidManifest.expected
@@ -164,6 +164,22 @@ android:enabled="false" android:excludeFromRecents="true" android:exported="true" + android:icon="@drawable/ic_devices_48dp" + android:label="@string/shared_clipboard_share_activity_title" + android:name="org.chromium.chrome.browser.sharing.shared_clipboard.SharedClipboardShareActivity" + android:noHistory="true" + android:theme="@style/Theme.Chromium.Activity.Translucent"> + <intent-filter> + <action android:name="android.intent.action.SEND"/> + <category android:name="android.intent.category.DEFAULT"/> + <data android:mimeType="text/plain"/> + </intent-filter> + </activity> + <activity + android:configChanges="orientation|keyboardHidden|keyboard|screenSize|mcc|mnc|screenLayout|smallestScreenSize" + android:enabled="false" + android:excludeFromRecents="true" + android:exported="true" android:icon="@drawable/ic_launcher" android:label="@string/send_tab_to_self_share_activity_title" android:name="org.chromium.chrome.browser.send_tab_to_self.SendTabToSelfShareActivity" @@ -1333,6 +1349,9 @@ android:name="org.chromium.chrome.browser.send_tab_to_self.NotificationManager$TimeoutReceiver"/> <receiver android:exported="false" + android:name="org.chromium.chrome.browser.sharing.SharingNotificationUtil$ActionReceiver"/> + <receiver + android:exported="false" android:name="org.chromium.chrome.browser.sharing.click_to_call.ClickToCallMessageHandler$TapReceiver"/> <receiver android:exported="false"
diff --git a/chrome/android/java/res/drawable-hdpi/ic_devices_48dp.png b/chrome/android/java/res/drawable-hdpi/ic_devices_48dp.png new file mode 100644 index 0000000..93f0b92 --- /dev/null +++ b/chrome/android/java/res/drawable-hdpi/ic_devices_48dp.png Binary files differ
diff --git a/chrome/android/java/res/drawable-hdpi/ic_error_outline_red_24dp.png b/chrome/android/java/res/drawable-hdpi/ic_error_outline_red_24dp.png new file mode 100644 index 0000000..867fdc7 --- /dev/null +++ b/chrome/android/java/res/drawable-hdpi/ic_error_outline_red_24dp.png Binary files differ
diff --git a/chrome/android/java/res/drawable-mdpi/ic_devices_48dp.png b/chrome/android/java/res/drawable-mdpi/ic_devices_48dp.png new file mode 100644 index 0000000..9104cfa --- /dev/null +++ b/chrome/android/java/res/drawable-mdpi/ic_devices_48dp.png Binary files differ
diff --git a/chrome/android/java/res/drawable-mdpi/ic_error_outline_red_24dp.png b/chrome/android/java/res/drawable-mdpi/ic_error_outline_red_24dp.png new file mode 100644 index 0000000..dc601b1 --- /dev/null +++ b/chrome/android/java/res/drawable-mdpi/ic_error_outline_red_24dp.png Binary files differ
diff --git a/chrome/android/java/res/drawable-xhdpi/ic_devices_48dp.png b/chrome/android/java/res/drawable-xhdpi/ic_devices_48dp.png new file mode 100644 index 0000000..fedbc46 --- /dev/null +++ b/chrome/android/java/res/drawable-xhdpi/ic_devices_48dp.png Binary files differ
diff --git a/chrome/android/java/res/drawable-xhdpi/ic_error_outline_red_24dp.png b/chrome/android/java/res/drawable-xhdpi/ic_error_outline_red_24dp.png new file mode 100644 index 0000000..05a012c --- /dev/null +++ b/chrome/android/java/res/drawable-xhdpi/ic_error_outline_red_24dp.png Binary files differ
diff --git a/chrome/android/java/res/drawable-xxhdpi/ic_devices_48dp.png b/chrome/android/java/res/drawable-xxhdpi/ic_devices_48dp.png new file mode 100644 index 0000000..76cc123 --- /dev/null +++ b/chrome/android/java/res/drawable-xxhdpi/ic_devices_48dp.png Binary files differ
diff --git a/chrome/android/java/res/drawable-xxhdpi/ic_error_outline_red_24dp.png b/chrome/android/java/res/drawable-xxhdpi/ic_error_outline_red_24dp.png new file mode 100644 index 0000000..aee5741 --- /dev/null +++ b/chrome/android/java/res/drawable-xxhdpi/ic_error_outline_red_24dp.png Binary files differ
diff --git a/chrome/android/java/res/drawable-xxxhdpi/ic_devices_48dp.png b/chrome/android/java/res/drawable-xxxhdpi/ic_devices_48dp.png new file mode 100644 index 0000000..60369f2 --- /dev/null +++ b/chrome/android/java/res/drawable-xxxhdpi/ic_devices_48dp.png Binary files differ
diff --git a/chrome/android/java/res/drawable-xxxhdpi/ic_error_outline_red_24dp.png b/chrome/android/java/res/drawable-xxxhdpi/ic_error_outline_red_24dp.png new file mode 100644 index 0000000..b4fd3b7 --- /dev/null +++ b/chrome/android/java/res/drawable-xxxhdpi/ic_error_outline_red_24dp.png Binary files differ
diff --git a/chrome/android/java/res/layout/sharing_device_picker.xml b/chrome/android/java/res/layout/sharing_device_picker.xml new file mode 100644 index 0000000..ca71396a --- /dev/null +++ b/chrome/android/java/res/layout/sharing_device_picker.xml
@@ -0,0 +1,53 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright 2019 The Chromium Authors. All rights reserved. + Use of this source code is governed by a BSD-style license that can be + found in the LICENSE file. --> +<LinearLayout + xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:orientation="vertical"> + + <View + android:id="@+id/mask" + android:layout_width="match_parent" + android:layout_height="0dp" + android:layout_weight="1" + android:alpha="0.5" + android:background="@android:color/black" /> + + <TextView + android:id="@+id/device_picker_toolbar" + android:layout_width="match_parent" + android:layout_height="@dimen/min_touch_target_size" + android:gravity="center_vertical" + android:paddingStart="30dp" + android:paddingEnd="30dp" + android:paddingTop="16dp" + android:paddingBottom="8dp" + android:ellipsize="end" + android:textAppearance="@style/TextAppearance.BlackHint1" + android:background="@android:color/white" /> + + <ListView + android:id="@+id/device_picker_list" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:divider="@null" + android:background="@android:color/white"/> + + <TextView + android:id="@android:id/empty" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:gravity="center_vertical" + android:paddingStart="30dp" + android:paddingEnd="30dp" + android:paddingTop="16dp" + android:paddingBottom="8dp" + android:ellipsize="end" + android:textAppearance="@style/TextAppearance.BlackHint1" + android:background="@android:color/white" + android:text="@string/sharing_device_list_empty"/> + +</LinearLayout>
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java b/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java index cdc33271..71e29045 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java
@@ -309,6 +309,7 @@ public static final String SERVICE_MANAGER_FOR_DOWNLOAD = "ServiceManagerForDownload"; public static final String SERVICE_WORKER_PAYMENT_APPS = "ServiceWorkerPaymentApps"; public static final String SETTINGS_MODERN_STATUS_BAR = "SettingsModernStatusBar"; + public static final String SHARED_CLIPBOARD_UI = "SharedClipboardUI"; public static final String SHOPPING_ASSIST = "ShoppingAssist"; public static final String SHOW_TRUSTED_PUBLISHER_URL = "ShowTrustedPublisherURL"; public static final String SPANNABLE_INLINE_AUTOCOMPLETE = "SpannableInlineAutocomplete";
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/accessibility/FontSizePrefs.java b/chrome/android/java/src/org/chromium/chrome/browser/accessibility/FontSizePrefs.java index 2366473..1398b02 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/accessibility/FontSizePrefs.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/accessibility/FontSizePrefs.java
@@ -12,6 +12,7 @@ import org.chromium.base.ThreadUtils; import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.util.MathUtils; /** @@ -56,7 +57,7 @@ } private FontSizePrefs() { - mFontSizePrefsAndroidPtr = nativeInit(); + mFontSizePrefsAndroidPtr = FontSizePrefsJni.get().init(FontSizePrefs.this); mObserverList = new ObserverList<FontSizePrefsObserver>(); } @@ -140,7 +141,8 @@ * font scale, and is the amount by which webpage text will be scaled during font boosting. */ public float getFontScaleFactor() { - return nativeGetFontScaleFactor(mFontSizePrefsAndroidPtr); + return FontSizePrefsJni.get().getFontScaleFactor( + mFontSizePrefsAndroidPtr, FontSizePrefs.this); } /** @@ -157,14 +159,16 @@ */ public void enableTouchlessMode() { mTouchlessMode = true; - nativeSetForceEnableZoom(mFontSizePrefsAndroidPtr, true); + FontSizePrefsJni.get().setForceEnableZoom( + mFontSizePrefsAndroidPtr, FontSizePrefs.this, true); } /** * Returns whether forceEnableZoom is enabled. */ public boolean getForceEnableZoom() { - return nativeGetForceEnableZoom(mFontSizePrefsAndroidPtr); + return FontSizePrefsJni.get().getForceEnableZoom( + mFontSizePrefsAndroidPtr, FontSizePrefs.this); } /** @@ -188,7 +192,8 @@ ContextUtils.getAppSharedPreferences().edit(); sharedPreferencesEditor.putBoolean(PREF_USER_SET_FORCE_ENABLE_ZOOM, fromUser); sharedPreferencesEditor.apply(); - nativeSetForceEnableZoom(mFontSizePrefsAndroidPtr, enabled); + FontSizePrefsJni.get().setForceEnableZoom( + mFontSizePrefsAndroidPtr, FontSizePrefs.this, enabled); } private boolean getUserSetForceEnableZoom() { @@ -198,7 +203,8 @@ private void setFontScaleFactor(float fontScaleFactor) { float previousFontScaleFactor = getFontScaleFactor(); - nativeSetFontScaleFactor(mFontSizePrefsAndroidPtr, fontScaleFactor); + FontSizePrefsJni.get().setFontScaleFactor( + mFontSizePrefsAndroidPtr, FontSizePrefs.this, fontScaleFactor); if (previousFontScaleFactor < FORCE_ENABLE_ZOOM_THRESHOLD_MULTIPLIER && fontScaleFactor >= FORCE_ENABLE_ZOOM_THRESHOLD_MULTIPLIER @@ -230,10 +236,14 @@ } } - private native long nativeInit(); - private native void nativeSetFontScaleFactor(long nativeFontSizePrefsAndroid, - float fontScaleFactor); - private native float nativeGetFontScaleFactor(long nativeFontSizePrefsAndroid); - private native boolean nativeGetForceEnableZoom(long nativeFontSizePrefsAndroid); - private native void nativeSetForceEnableZoom(long nativeFontSizePrefsAndroid, boolean enabled); + @NativeMethods + interface Natives { + long init(FontSizePrefs caller); + void setFontScaleFactor( + long nativeFontSizePrefsAndroid, FontSizePrefs caller, float fontScaleFactor); + float getFontScaleFactor(long nativeFontSizePrefsAndroid, FontSizePrefs caller); + boolean getForceEnableZoom(long nativeFontSizePrefsAndroid, FontSizePrefs caller); + void setForceEnableZoom( + long nativeFontSizePrefsAndroid, FontSizePrefs caller, boolean enabled); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/AutofillExpirationDateFixFlowBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/AutofillExpirationDateFixFlowBridge.java index 6479b25..e8d9783 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/AutofillExpirationDateFixFlowBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/AutofillExpirationDateFixFlowBridge.java
@@ -8,6 +8,7 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.base.task.PostTask; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.ResourceId; @@ -48,13 +49,17 @@ @Override public void onPromptDismissed() { - nativePromptDismissed(mNativeCardExpirationDateFixFlowViewAndroid); + AutofillExpirationDateFixFlowBridgeJni.get().promptDismissed( + mNativeCardExpirationDateFixFlowViewAndroid, + AutofillExpirationDateFixFlowBridge.this); mNativeCardExpirationDateFixFlowViewAndroid = 0; } @Override public void onUserAccept(String month, String year) { - nativeOnUserAccept(mNativeCardExpirationDateFixFlowViewAndroid, month, year); + AutofillExpirationDateFixFlowBridgeJni.get().onUserAccept( + mNativeCardExpirationDateFixFlowViewAndroid, + AutofillExpirationDateFixFlowBridge.this, month, year); } /** @@ -85,8 +90,11 @@ } } - private native void nativePromptDismissed(long nativeCardExpirationDateFixFlowViewAndroid); - - private native void nativeOnUserAccept( - long nativeCardExpirationDateFixFlowViewAndroid, String month, String year); + @NativeMethods + interface Natives { + void promptDismissed(long nativeCardExpirationDateFixFlowViewAndroid, + AutofillExpirationDateFixFlowBridge caller); + void onUserAccept(long nativeCardExpirationDateFixFlowViewAndroid, + AutofillExpirationDateFixFlowBridge caller, String month, String year); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/AutofillNameFixFlowBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/AutofillNameFixFlowBridge.java index e8df2f06..5f97957 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/AutofillNameFixFlowBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/AutofillNameFixFlowBridge.java
@@ -8,6 +8,7 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.base.task.PostTask; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.ResourceId; @@ -57,12 +58,14 @@ @Override public void onPromptDismissed() { - nativePromptDismissed(mNativeCardNameFixFlowViewAndroid); + AutofillNameFixFlowBridgeJni.get().promptDismissed( + mNativeCardNameFixFlowViewAndroid, AutofillNameFixFlowBridge.this); } @Override public void onUserAccept(String name) { - nativeOnUserAccept(mNativeCardNameFixFlowViewAndroid, name); + AutofillNameFixFlowBridgeJni.get().onUserAccept( + mNativeCardNameFixFlowViewAndroid, AutofillNameFixFlowBridge.this, name); } /** @@ -88,6 +91,11 @@ } } - private native void nativePromptDismissed(long nativeCardNameFixFlowViewAndroid); - private native void nativeOnUserAccept(long nativeCardNameFixFlowViewAndroid, String name); + @NativeMethods + interface Natives { + void promptDismissed( + long nativeCardNameFixFlowViewAndroid, AutofillNameFixFlowBridge caller); + void onUserAccept(long nativeCardNameFixFlowViewAndroid, AutofillNameFixFlowBridge caller, + String name); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/AutofillPopupBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/AutofillPopupBridge.java index 9c1dc5c..dce8467d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/AutofillPopupBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/AutofillPopupBridge.java
@@ -13,6 +13,7 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.ChromeFeatureList; @@ -63,17 +64,19 @@ @Override public void dismissed() { - nativePopupDismissed(mNativeAutofillPopup); + AutofillPopupBridgeJni.get().popupDismissed(mNativeAutofillPopup, AutofillPopupBridge.this); } @Override public void suggestionSelected(int listIndex) { - nativeSuggestionSelected(mNativeAutofillPopup, listIndex); + AutofillPopupBridgeJni.get().suggestionSelected( + mNativeAutofillPopup, AutofillPopupBridge.this, listIndex); } @Override public void deleteSuggestion(int listIndex) { - nativeDeletionRequested(mNativeAutofillPopup, listIndex); + AutofillPopupBridgeJni.get().deletionRequested( + mNativeAutofillPopup, AutofillPopupBridge.this, listIndex); } @Override @@ -84,7 +87,8 @@ @Override public void onClick(DialogInterface dialog, int which) { assert which == DialogInterface.BUTTON_POSITIVE; - nativeDeletionConfirmed(mNativeAutofillPopup); + AutofillPopupBridgeJni.get().deletionConfirmed( + mNativeAutofillPopup, AutofillPopupBridge.this); } /** @@ -175,10 +179,13 @@ suggestionId, isDeletable, isLabelMultiline, isLabelBold); } - private native void nativeSuggestionSelected(long nativeAutofillPopupViewAndroid, - int listIndex); - private native void nativeDeletionRequested(long nativeAutofillPopupViewAndroid, - int listIndex); - private native void nativeDeletionConfirmed(long nativeAutofillPopupViewAndroid); - private native void nativePopupDismissed(long nativeAutofillPopupViewAndroid); + @NativeMethods + interface Natives { + void suggestionSelected( + long nativeAutofillPopupViewAndroid, AutofillPopupBridge caller, int listIndex); + void deletionRequested( + long nativeAutofillPopupViewAndroid, AutofillPopupBridge caller, int listIndex); + void deletionConfirmed(long nativeAutofillPopupViewAndroid, AutofillPopupBridge caller); + void popupDismissed(long nativeAutofillPopupViewAndroid, AutofillPopupBridge caller); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/CardUnmaskBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/CardUnmaskBridge.java index a1e57951..1d498d87 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/CardUnmaskBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/CardUnmaskBridge.java
@@ -9,6 +9,7 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.ResourceId; import org.chromium.chrome.browser.autofill.CardUnmaskPrompt.CardUnmaskPromptDelegate; @@ -56,27 +57,32 @@ @Override public void dismissed() { - nativePromptDismissed(mNativeCardUnmaskPromptViewAndroid); + CardUnmaskBridgeJni.get().promptDismissed( + mNativeCardUnmaskPromptViewAndroid, CardUnmaskBridge.this); } @Override public boolean checkUserInputValidity(String userResponse) { - return nativeCheckUserInputValidity(mNativeCardUnmaskPromptViewAndroid, userResponse); + return CardUnmaskBridgeJni.get().checkUserInputValidity( + mNativeCardUnmaskPromptViewAndroid, CardUnmaskBridge.this, userResponse); } @Override public void onUserInput(String cvc, String month, String year, boolean shouldStoreLocally) { - nativeOnUserInput(mNativeCardUnmaskPromptViewAndroid, cvc, month, year, shouldStoreLocally); + CardUnmaskBridgeJni.get().onUserInput(mNativeCardUnmaskPromptViewAndroid, + CardUnmaskBridge.this, cvc, month, year, shouldStoreLocally); } @Override public void onNewCardLinkClicked() { - nativeOnNewCardLinkClicked(mNativeCardUnmaskPromptViewAndroid); + CardUnmaskBridgeJni.get().onNewCardLinkClicked( + mNativeCardUnmaskPromptViewAndroid, CardUnmaskBridge.this); } @Override public int getExpectedCvcLength() { - return nativeGetExpectedCvcLength(mNativeCardUnmaskPromptViewAndroid); + return CardUnmaskBridgeJni.get().getExpectedCvcLength( + mNativeCardUnmaskPromptViewAndroid, CardUnmaskBridge.this); } /** @@ -132,12 +138,14 @@ } } - private native void nativePromptDismissed(long nativeCardUnmaskPromptViewAndroid); - private native boolean nativeCheckUserInputValidity( - long nativeCardUnmaskPromptViewAndroid, String userResponse); - private native void nativeOnUserInput( - long nativeCardUnmaskPromptViewAndroid, String cvc, String month, String year, - boolean shouldStoreLocally); - private native void nativeOnNewCardLinkClicked(long nativeCardUnmaskPromptViewAndroid); - private native int nativeGetExpectedCvcLength(long nativeCardUnmaskPromptViewAndroid); + @NativeMethods + interface Natives { + void promptDismissed(long nativeCardUnmaskPromptViewAndroid, CardUnmaskBridge caller); + boolean checkUserInputValidity(long nativeCardUnmaskPromptViewAndroid, + CardUnmaskBridge caller, String userResponse); + void onUserInput(long nativeCardUnmaskPromptViewAndroid, CardUnmaskBridge caller, + String cvc, String month, String year, boolean shouldStoreLocally); + void onNewCardLinkClicked(long nativeCardUnmaskPromptViewAndroid, CardUnmaskBridge caller); + int getExpectedCvcLength(long nativeCardUnmaskPromptViewAndroid, CardUnmaskBridge caller); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/CreditCardScannerBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/CreditCardScannerBridge.java index 7b4429b..7d5fdefa 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/CreditCardScannerBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/CreditCardScannerBridge.java
@@ -6,6 +6,7 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.content_public.browser.WebContents; /** Native bridge for credit card scanner. */ @@ -36,17 +37,21 @@ @Override public void onScanCancelled() { - nativeScanCancelled(mNativeScanner); + CreditCardScannerBridgeJni.get().scanCancelled( + mNativeScanner, CreditCardScannerBridge.this); } @Override public void onScanCompleted( String cardHolderName, String cardNumber, int expirationMonth, int expirationYear) { - nativeScanCompleted( - mNativeScanner, cardHolderName, cardNumber, expirationMonth, expirationYear); + CreditCardScannerBridgeJni.get().scanCompleted(mNativeScanner, CreditCardScannerBridge.this, + cardHolderName, cardNumber, expirationMonth, expirationYear); } - private native void nativeScanCancelled(long nativeCreditCardScannerViewAndroid); - private native void nativeScanCompleted(long nativeCreditCardScannerViewAndroid, - String cardHolderName, String cardNumber, int expirationMonth, int expirationYear); + @NativeMethods + interface Natives { + void scanCancelled(long nativeCreditCardScannerViewAndroid, CreditCardScannerBridge caller); + void scanCompleted(long nativeCreditCardScannerViewAndroid, CreditCardScannerBridge caller, + String cardHolderName, String cardNumber, int expirationMonth, int expirationYear); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/PersonalDataManager.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/PersonalDataManager.java index b8d5469..30bcf76b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/PersonalDataManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/PersonalDataManager.java
@@ -11,6 +11,7 @@ import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.R; import org.chromium.chrome.browser.ResourceId; import org.chromium.chrome.browser.preferences.MainPreferences; @@ -572,7 +573,7 @@ private PersonalDataManager() { // Note that this technically leaks the native object, however, PersonalDataManager // is a singleton that lives forever and there's no clean shutdown of Chrome on Android - mPersonalDataManagerAndroid = nativeInit(); + mPersonalDataManagerAndroid = PersonalDataManagerJni.get().init(PersonalDataManager.this); } /** @@ -593,7 +594,8 @@ ThreadUtils.assertOnUiThread(); assert !mDataObservers.contains(observer); mDataObservers.add(observer); - return nativeIsDataLoaded(mPersonalDataManagerAndroid); + return PersonalDataManagerJni.get().isDataLoaded( + mPersonalDataManagerAndroid, PersonalDataManager.this); } /** @@ -616,8 +618,10 @@ */ public List<AutofillProfile> getProfilesForSettings() { ThreadUtils.assertOnUiThread(); - return getProfilesWithLabels(nativeGetProfileLabelsForSettings(mPersonalDataManagerAndroid), - nativeGetProfileGUIDsForSettings(mPersonalDataManagerAndroid)); + return getProfilesWithLabels(PersonalDataManagerJni.get().getProfileLabelsForSettings( + mPersonalDataManagerAndroid, PersonalDataManager.this), + PersonalDataManagerJni.get().getProfileGUIDsForSettings( + mPersonalDataManagerAndroid, PersonalDataManager.this)); } /** @@ -632,10 +636,11 @@ public ArrayList<AutofillProfile> getProfilesToSuggest(boolean includeNameInLabel) { ThreadUtils.assertOnUiThread(); return getProfilesWithLabels( - nativeGetProfileLabelsToSuggest( - mPersonalDataManagerAndroid, includeNameInLabel, + PersonalDataManagerJni.get().getProfileLabelsToSuggest(mPersonalDataManagerAndroid, + PersonalDataManager.this, includeNameInLabel, true /* includeOrganizationInLabel */, true /* includeCountryInLabel */), - nativeGetProfileGUIDsToSuggest(mPersonalDataManagerAndroid)); + PersonalDataManagerJni.get().getProfileGUIDsToSuggest( + mPersonalDataManagerAndroid, PersonalDataManager.this)); } /** @@ -653,18 +658,19 @@ boolean includeOrganizationInLabel) { ThreadUtils.assertOnUiThread(); return getProfilesWithLabels( - nativeGetProfileLabelsToSuggest(mPersonalDataManagerAndroid, - true /* includeNameInLabel */, includeOrganizationInLabel, - false /* includeCountryInLabel */), - nativeGetProfileGUIDsToSuggest(mPersonalDataManagerAndroid)); + PersonalDataManagerJni.get().getProfileLabelsToSuggest(mPersonalDataManagerAndroid, + PersonalDataManager.this, true /* includeNameInLabel */, + includeOrganizationInLabel, false /* includeCountryInLabel */), + PersonalDataManagerJni.get().getProfileGUIDsToSuggest( + mPersonalDataManagerAndroid, PersonalDataManager.this)); } private ArrayList<AutofillProfile> getProfilesWithLabels( String[] profileLabels, String[] profileGUIDs) { ArrayList<AutofillProfile> profiles = new ArrayList<AutofillProfile>(profileGUIDs.length); for (int i = 0; i < profileGUIDs.length; i++) { - AutofillProfile profile = - nativeGetProfileByGUID(mPersonalDataManagerAndroid, profileGUIDs[i]); + AutofillProfile profile = PersonalDataManagerJni.get().getProfileByGUID( + mPersonalDataManagerAndroid, PersonalDataManager.this, profileGUIDs[i]); profile.setLabel(profileLabels[i]); profiles.add(profile); } @@ -674,22 +680,26 @@ public AutofillProfile getProfile(String guid) { ThreadUtils.assertOnUiThread(); - return nativeGetProfileByGUID(mPersonalDataManagerAndroid, guid); + return PersonalDataManagerJni.get().getProfileByGUID( + mPersonalDataManagerAndroid, PersonalDataManager.this, guid); } public void deleteProfile(String guid) { ThreadUtils.assertOnUiThread(); - nativeRemoveByGUID(mPersonalDataManagerAndroid, guid); + PersonalDataManagerJni.get().removeByGUID( + mPersonalDataManagerAndroid, PersonalDataManager.this, guid); } public String setProfile(AutofillProfile profile) { ThreadUtils.assertOnUiThread(); - return nativeSetProfile(mPersonalDataManagerAndroid, profile); + return PersonalDataManagerJni.get().setProfile( + mPersonalDataManagerAndroid, PersonalDataManager.this, profile); } public String setProfileToLocal(AutofillProfile profile) { ThreadUtils.assertOnUiThread(); - return nativeSetProfileToLocal(mPersonalDataManagerAndroid, profile); + return PersonalDataManagerJni.get().setProfileToLocal( + mPersonalDataManagerAndroid, PersonalDataManager.this, profile); } /** @@ -698,7 +708,8 @@ */ public List<CreditCard> getCreditCardsForSettings() { ThreadUtils.assertOnUiThread(); - return getCreditCards(nativeGetCreditCardGUIDsForSettings(mPersonalDataManagerAndroid)); + return getCreditCards(PersonalDataManagerJni.get().getCreditCardGUIDsForSettings( + mPersonalDataManagerAndroid, PersonalDataManager.this)); } /** @@ -708,79 +719,88 @@ */ public ArrayList<CreditCard> getCreditCardsToSuggest(boolean includeServerCards) { ThreadUtils.assertOnUiThread(); - return getCreditCards( - nativeGetCreditCardGUIDsToSuggest(mPersonalDataManagerAndroid, includeServerCards)); + return getCreditCards(PersonalDataManagerJni.get().getCreditCardGUIDsToSuggest( + mPersonalDataManagerAndroid, PersonalDataManager.this, includeServerCards)); } private ArrayList<CreditCard> getCreditCards(String[] creditCardGUIDs) { ArrayList<CreditCard> cards = new ArrayList<CreditCard>(creditCardGUIDs.length); for (int i = 0; i < creditCardGUIDs.length; i++) { - cards.add(nativeGetCreditCardByGUID(mPersonalDataManagerAndroid, creditCardGUIDs[i])); + cards.add(PersonalDataManagerJni.get().getCreditCardByGUID( + mPersonalDataManagerAndroid, PersonalDataManager.this, creditCardGUIDs[i])); } return cards; } public CreditCard getCreditCard(String guid) { ThreadUtils.assertOnUiThread(); - return nativeGetCreditCardByGUID(mPersonalDataManagerAndroid, guid); + return PersonalDataManagerJni.get().getCreditCardByGUID( + mPersonalDataManagerAndroid, PersonalDataManager.this, guid); } public CreditCard getCreditCardForNumber(String cardNumber) { ThreadUtils.assertOnUiThread(); - return nativeGetCreditCardForNumber(mPersonalDataManagerAndroid, cardNumber); + return PersonalDataManagerJni.get().getCreditCardForNumber( + mPersonalDataManagerAndroid, PersonalDataManager.this, cardNumber); } public String setCreditCard(CreditCard card) { ThreadUtils.assertOnUiThread(); assert card.getIsLocal(); - return nativeSetCreditCard(mPersonalDataManagerAndroid, card); + return PersonalDataManagerJni.get().setCreditCard( + mPersonalDataManagerAndroid, PersonalDataManager.this, card); } public void updateServerCardBillingAddress(CreditCard card) { ThreadUtils.assertOnUiThread(); - nativeUpdateServerCardBillingAddress(mPersonalDataManagerAndroid, card); + PersonalDataManagerJni.get().updateServerCardBillingAddress( + mPersonalDataManagerAndroid, PersonalDataManager.this, card); } public String getBasicCardIssuerNetwork(String cardNumber, boolean emptyIfInvalid) { ThreadUtils.assertOnUiThread(); - return nativeGetBasicCardIssuerNetwork( - mPersonalDataManagerAndroid, cardNumber, emptyIfInvalid); + return PersonalDataManagerJni.get().getBasicCardIssuerNetwork( + mPersonalDataManagerAndroid, PersonalDataManager.this, cardNumber, emptyIfInvalid); } @VisibleForTesting public void addServerCreditCardForTest(CreditCard card) { ThreadUtils.assertOnUiThread(); assert !card.getIsLocal(); - nativeAddServerCreditCardForTest(mPersonalDataManagerAndroid, card); + PersonalDataManagerJni.get().addServerCreditCardForTest( + mPersonalDataManagerAndroid, PersonalDataManager.this, card); } public void deleteCreditCard(String guid) { ThreadUtils.assertOnUiThread(); - nativeRemoveByGUID(mPersonalDataManagerAndroid, guid); + PersonalDataManagerJni.get().removeByGUID( + mPersonalDataManagerAndroid, PersonalDataManager.this, guid); } public void clearUnmaskedCache(String guid) { - nativeClearUnmaskedCache(mPersonalDataManagerAndroid, guid); + PersonalDataManagerJni.get().clearUnmaskedCache( + mPersonalDataManagerAndroid, PersonalDataManager.this, guid); } public String getShippingAddressLabelWithCountryForPaymentRequest(AutofillProfile profile) { - return nativeGetShippingAddressLabelWithCountryForPaymentRequest( - mPersonalDataManagerAndroid, profile); + return PersonalDataManagerJni.get().getShippingAddressLabelWithCountryForPaymentRequest( + mPersonalDataManagerAndroid, PersonalDataManager.this, profile); } public String getShippingAddressLabelWithoutCountryForPaymentRequest(AutofillProfile profile) { - return nativeGetShippingAddressLabelWithoutCountryForPaymentRequest( - mPersonalDataManagerAndroid, profile); + return PersonalDataManagerJni.get().getShippingAddressLabelWithoutCountryForPaymentRequest( + mPersonalDataManagerAndroid, PersonalDataManager.this, profile); } public String getBillingAddressLabelForPaymentRequest(AutofillProfile profile) { - return nativeGetBillingAddressLabelForPaymentRequest(mPersonalDataManagerAndroid, profile); + return PersonalDataManagerJni.get().getBillingAddressLabelForPaymentRequest( + mPersonalDataManagerAndroid, PersonalDataManager.this, profile); } public void getFullCard(WebContents webContents, CreditCard card, FullCardRequestDelegate delegate) { - nativeGetFullCardForPaymentRequest(mPersonalDataManagerAndroid, webContents, card, - delegate); + PersonalDataManagerJni.get().getFullCardForPaymentRequest( + mPersonalDataManagerAndroid, PersonalDataManager.this, webContents, card, delegate); } /** @@ -792,25 +812,29 @@ */ public void recordAndLogProfileUse(String guid) { ThreadUtils.assertOnUiThread(); - nativeRecordAndLogProfileUse(mPersonalDataManagerAndroid, guid); + PersonalDataManagerJni.get().recordAndLogProfileUse( + mPersonalDataManagerAndroid, PersonalDataManager.this, guid); } @VisibleForTesting protected void setProfileUseStatsForTesting(String guid, int count, long date) { ThreadUtils.assertOnUiThread(); - nativeSetProfileUseStatsForTesting(mPersonalDataManagerAndroid, guid, count, date); + PersonalDataManagerJni.get().setProfileUseStatsForTesting( + mPersonalDataManagerAndroid, PersonalDataManager.this, guid, count, date); } @VisibleForTesting int getProfileUseCountForTesting(String guid) { ThreadUtils.assertOnUiThread(); - return nativeGetProfileUseCountForTesting(mPersonalDataManagerAndroid, guid); + return PersonalDataManagerJni.get().getProfileUseCountForTesting( + mPersonalDataManagerAndroid, PersonalDataManager.this, guid); } @VisibleForTesting long getProfileUseDateForTesting(String guid) { ThreadUtils.assertOnUiThread(); - return nativeGetProfileUseDateForTesting(mPersonalDataManagerAndroid, guid); + return PersonalDataManagerJni.get().getProfileUseDateForTesting( + mPersonalDataManagerAndroid, PersonalDataManager.this, guid); } /** @@ -822,31 +846,36 @@ */ public void recordAndLogCreditCardUse(String guid) { ThreadUtils.assertOnUiThread(); - nativeRecordAndLogCreditCardUse(mPersonalDataManagerAndroid, guid); + PersonalDataManagerJni.get().recordAndLogCreditCardUse( + mPersonalDataManagerAndroid, PersonalDataManager.this, guid); } @VisibleForTesting protected void setCreditCardUseStatsForTesting(String guid, int count, long date) { ThreadUtils.assertOnUiThread(); - nativeSetCreditCardUseStatsForTesting(mPersonalDataManagerAndroid, guid, count, date); + PersonalDataManagerJni.get().setCreditCardUseStatsForTesting( + mPersonalDataManagerAndroid, PersonalDataManager.this, guid, count, date); } @VisibleForTesting int getCreditCardUseCountForTesting(String guid) { ThreadUtils.assertOnUiThread(); - return nativeGetCreditCardUseCountForTesting(mPersonalDataManagerAndroid, guid); + return PersonalDataManagerJni.get().getCreditCardUseCountForTesting( + mPersonalDataManagerAndroid, PersonalDataManager.this, guid); } @VisibleForTesting long getCreditCardUseDateForTesting(String guid) { ThreadUtils.assertOnUiThread(); - return nativeGetCreditCardUseDateForTesting(mPersonalDataManagerAndroid, guid); + return PersonalDataManagerJni.get().getCreditCardUseDateForTesting( + mPersonalDataManagerAndroid, PersonalDataManager.this, guid); } @VisibleForTesting long getCurrentDateForTesting() { ThreadUtils.assertOnUiThread(); - return nativeGetCurrentDateForTesting(mPersonalDataManagerAndroid); + return PersonalDataManagerJni.get().getCurrentDateForTesting( + mPersonalDataManagerAndroid, PersonalDataManager.this); } /** @@ -856,7 +885,8 @@ */ public void loadRulesForAddressNormalization(String regionCode) { ThreadUtils.assertOnUiThread(); - nativeLoadRulesForAddressNormalization(mPersonalDataManagerAndroid, regionCode); + PersonalDataManagerJni.get().loadRulesForAddressNormalization( + mPersonalDataManagerAndroid, PersonalDataManager.this, regionCode); } /** @@ -866,7 +896,8 @@ */ public void loadRulesForSubKeys(String regionCode) { ThreadUtils.assertOnUiThread(); - nativeLoadRulesForSubKeys(mPersonalDataManagerAndroid, regionCode); + PersonalDataManagerJni.get().loadRulesForSubKeys( + mPersonalDataManagerAndroid, PersonalDataManager.this, regionCode); } /** @@ -881,14 +912,14 @@ */ public void getRegionSubKeys(String regionCode, GetSubKeysRequestDelegate delegate) { ThreadUtils.assertOnUiThread(); - nativeStartRegionSubKeysRequest( - mPersonalDataManagerAndroid, regionCode, sRequestTimeoutSeconds, delegate); + PersonalDataManagerJni.get().startRegionSubKeysRequest(mPersonalDataManagerAndroid, + PersonalDataManager.this, regionCode, sRequestTimeoutSeconds, delegate); } /** Cancels the pending subkeys request. */ public void cancelPendingGetSubKeys() { ThreadUtils.assertOnUiThread(); - nativeCancelPendingGetSubKeys(mPersonalDataManagerAndroid); + PersonalDataManagerJni.get().cancelPendingGetSubKeys(mPersonalDataManagerAndroid); } /** @@ -904,8 +935,8 @@ public void normalizeAddress( AutofillProfile profile, NormalizedAddressRequestDelegate delegate) { ThreadUtils.assertOnUiThread(); - nativeStartAddressNormalization( - mPersonalDataManagerAndroid, profile, sRequestTimeoutSeconds, delegate); + PersonalDataManagerJni.get().startAddressNormalization(mPersonalDataManagerAndroid, + PersonalDataManager.this, profile, sRequestTimeoutSeconds, delegate); } /** @@ -914,7 +945,7 @@ * @return True If there are profiles. */ public boolean hasProfiles() { - return nativeHasProfiles(mPersonalDataManagerAndroid); + return PersonalDataManagerJni.get().hasProfiles(mPersonalDataManagerAndroid); } /** @@ -923,21 +954,21 @@ * @return True If there are credit cards. */ public boolean hasCreditCards() { - return nativeHasCreditCards(mPersonalDataManagerAndroid); + return PersonalDataManagerJni.get().hasCreditCards(mPersonalDataManagerAndroid); } /** * @return Whether the Autofill feature for Profiles (addresses) is enabled. */ public static boolean isAutofillProfileEnabled() { - return nativeGetPref(Pref.AUTOFILL_PROFILE_ENABLED); + return PersonalDataManagerJni.get().getPref(Pref.AUTOFILL_PROFILE_ENABLED); } /** * @return Whether the Autofill feature for Credit Cards is enabled. */ public static boolean isAutofillCreditCardEnabled() { - return nativeGetPref(Pref.AUTOFILL_CREDIT_CARD_ENABLED); + return PersonalDataManagerJni.get().getPref(Pref.AUTOFILL_CREDIT_CARD_ENABLED); } /** @@ -945,7 +976,7 @@ * @param enable True to disable profile Autofill, false otherwise. */ public static void setAutofillProfileEnabled(boolean enable) { - nativeSetPref(Pref.AUTOFILL_PROFILE_ENABLED, enable); + PersonalDataManagerJni.get().setPref(Pref.AUTOFILL_PROFILE_ENABLED, enable); } /** @@ -953,35 +984,35 @@ * @param enable True to disable credit card Autofill, false otherwise. */ public static void setAutofillCreditCardEnabled(boolean enable) { - nativeSetPref(Pref.AUTOFILL_CREDIT_CARD_ENABLED, enable); + PersonalDataManagerJni.get().setPref(Pref.AUTOFILL_CREDIT_CARD_ENABLED, enable); } /** * @return Whether the Autofill feature is managed. */ public static boolean isAutofillManaged() { - return nativeIsAutofillManaged(); + return PersonalDataManagerJni.get().isAutofillManaged(); } /** * @return Whether the Autofill feature for Profiles (addresses) is managed. */ public static boolean isAutofillProfileManaged() { - return nativeIsAutofillProfileManaged(); + return PersonalDataManagerJni.get().isAutofillProfileManaged(); } /** * @return Whether the Autofill feature for Credit Cards is managed. */ public static boolean isAutofillCreditCardManaged() { - return nativeIsAutofillCreditCardManaged(); + return PersonalDataManagerJni.get().isAutofillCreditCardManaged(); } /** * @return Whether the Payments integration feature is enabled. */ public static boolean isPaymentsIntegrationEnabled() { - return nativeIsPaymentsIntegrationEnabled(); + return PersonalDataManagerJni.get().isPaymentsIntegrationEnabled(); } /** @@ -989,7 +1020,7 @@ * @param enable True to enable Payments data import. */ public static void setPaymentsIntegrationEnabled(boolean enable) { - nativeSetPaymentsIntegrationEnabled(enable); + PersonalDataManagerJni.get().setPaymentsIntegrationEnabled(enable); } @VisibleForTesting @@ -999,7 +1030,7 @@ @VisibleForTesting public void setSyncServiceForTesting() { - nativeSetSyncServiceForTesting(mPersonalDataManagerAndroid); + PersonalDataManagerJni.get().setSyncServiceForTesting(mPersonalDataManagerAndroid); } /** @@ -1009,84 +1040,95 @@ return DateUtils.SECOND_IN_MILLIS * sRequestTimeoutSeconds; } - private native long nativeInit(); - private native boolean nativeIsDataLoaded(long nativePersonalDataManagerAndroid); - private native String[] nativeGetProfileGUIDsForSettings(long nativePersonalDataManagerAndroid); - private native String[] nativeGetProfileGUIDsToSuggest(long nativePersonalDataManagerAndroid); - private native String[] nativeGetProfileLabelsForSettings( - long nativePersonalDataManagerAndroid); - private native String[] nativeGetProfileLabelsToSuggest(long nativePersonalDataManagerAndroid, - boolean includeNameInLabel, boolean includeOrganizationInLabel, - boolean includeCountryInLabel); - private native AutofillProfile nativeGetProfileByGUID(long nativePersonalDataManagerAndroid, - String guid); - private native String nativeSetProfile( - long nativePersonalDataManagerAndroid, AutofillProfile profile); - private native String nativeSetProfileToLocal( - long nativePersonalDataManagerAndroid, AutofillProfile profile); - private native String nativeGetShippingAddressLabelWithCountryForPaymentRequest( - long nativePersonalDataManagerAndroid, AutofillProfile profile); - private native String nativeGetShippingAddressLabelWithoutCountryForPaymentRequest( - long nativePersonalDataManagerAndroid, AutofillProfile profile); - private native String nativeGetBillingAddressLabelForPaymentRequest( - long nativePersonalDataManagerAndroid, AutofillProfile profile); - private native String[] nativeGetCreditCardGUIDsForSettings( - long nativePersonalDataManagerAndroid); - private native String[] nativeGetCreditCardGUIDsToSuggest( - long nativePersonalDataManagerAndroid, boolean includeServerCards); - private native CreditCard nativeGetCreditCardByGUID(long nativePersonalDataManagerAndroid, - String guid); - private native CreditCard nativeGetCreditCardForNumber(long nativePersonalDataManagerAndroid, - String cardNumber); - private native String nativeSetCreditCard(long nativePersonalDataManagerAndroid, - CreditCard card); - private native void nativeUpdateServerCardBillingAddress(long nativePersonalDataManagerAndroid, - CreditCard card); - private native String nativeGetBasicCardIssuerNetwork( - long nativePersonalDataManagerAndroid, String cardNumber, boolean emptyIfInvalid); - private native void nativeAddServerCreditCardForTest(long nativePersonalDataManagerAndroid, - CreditCard card); - private native void nativeRemoveByGUID(long nativePersonalDataManagerAndroid, String guid); - private native void nativeRecordAndLogProfileUse(long nativePersonalDataManagerAndroid, - String guid); - private native void nativeSetProfileUseStatsForTesting( - long nativePersonalDataManagerAndroid, String guid, int count, long date); - private native int nativeGetProfileUseCountForTesting(long nativePersonalDataManagerAndroid, - String guid); - private native long nativeGetProfileUseDateForTesting(long nativePersonalDataManagerAndroid, - String guid); - private native void nativeRecordAndLogCreditCardUse(long nativePersonalDataManagerAndroid, - String guid); - private native void nativeSetCreditCardUseStatsForTesting( - long nativePersonalDataManagerAndroid, String guid, int count, long date); - private native int nativeGetCreditCardUseCountForTesting(long nativePersonalDataManagerAndroid, - String guid); - private native long nativeGetCreditCardUseDateForTesting(long nativePersonalDataManagerAndroid, - String guid); - private native long nativeGetCurrentDateForTesting(long nativePersonalDataManagerAndroid); - private native void nativeClearUnmaskedCache( - long nativePersonalDataManagerAndroid, String guid); - private native void nativeGetFullCardForPaymentRequest(long nativePersonalDataManagerAndroid, - WebContents webContents, CreditCard card, FullCardRequestDelegate delegate); - private native void nativeLoadRulesForAddressNormalization( - long nativePersonalDataManagerAndroid, String regionCode); - private native void nativeLoadRulesForSubKeys( - long nativePersonalDataManagerAndroid, String regionCode); - private native void nativeStartAddressNormalization(long nativePersonalDataManagerAndroid, - AutofillProfile profile, int timeoutSeconds, NormalizedAddressRequestDelegate delegate); - private native void nativeStartRegionSubKeysRequest(long nativePersonalDataManagerAndroid, - String regionCode, int timeoutSeconds, GetSubKeysRequestDelegate delegate); - private static native boolean nativeHasProfiles(long nativePersonalDataManagerAndroid); - private static native boolean nativeHasCreditCards(long nativePersonalDataManagerAndroid); - private static native boolean nativeIsAutofillManaged(); - private static native boolean nativeIsAutofillProfileManaged(); - private static native boolean nativeIsAutofillCreditCardManaged(); - private static native boolean nativeIsPaymentsIntegrationEnabled(); - private static native void nativeSetPaymentsIntegrationEnabled(boolean enable); - private static native String nativeToCountryCode(String countryName); - private static native void nativeCancelPendingGetSubKeys(long nativePersonalDataManagerAndroid); - private static native void nativeSetSyncServiceForTesting( - long nativePersonalDataManagerAndroid); - private static native boolean nativeGetPref(int preference); - private static native void nativeSetPref(int preference, boolean enable); + @NativeMethods + interface Natives { + long init(PersonalDataManager caller); + boolean isDataLoaded(long nativePersonalDataManagerAndroid, PersonalDataManager caller); + String[] getProfileGUIDsForSettings( + long nativePersonalDataManagerAndroid, PersonalDataManager caller); + String[] getProfileGUIDsToSuggest( + long nativePersonalDataManagerAndroid, PersonalDataManager caller); + String[] getProfileLabelsForSettings( + long nativePersonalDataManagerAndroid, PersonalDataManager caller); + String[] getProfileLabelsToSuggest(long nativePersonalDataManagerAndroid, + PersonalDataManager caller, boolean includeNameInLabel, + boolean includeOrganizationInLabel, boolean includeCountryInLabel); + AutofillProfile getProfileByGUID( + long nativePersonalDataManagerAndroid, PersonalDataManager caller, String guid); + String setProfile(long nativePersonalDataManagerAndroid, PersonalDataManager caller, + AutofillProfile profile); + String setProfileToLocal(long nativePersonalDataManagerAndroid, PersonalDataManager caller, + AutofillProfile profile); + String getShippingAddressLabelWithCountryForPaymentRequest( + long nativePersonalDataManagerAndroid, PersonalDataManager caller, + AutofillProfile profile); + String getShippingAddressLabelWithoutCountryForPaymentRequest( + long nativePersonalDataManagerAndroid, PersonalDataManager caller, + AutofillProfile profile); + String getBillingAddressLabelForPaymentRequest(long nativePersonalDataManagerAndroid, + PersonalDataManager caller, AutofillProfile profile); + String[] getCreditCardGUIDsForSettings( + long nativePersonalDataManagerAndroid, PersonalDataManager caller); + String[] getCreditCardGUIDsToSuggest(long nativePersonalDataManagerAndroid, + PersonalDataManager caller, boolean includeServerCards); + CreditCard getCreditCardByGUID( + long nativePersonalDataManagerAndroid, PersonalDataManager caller, String guid); + CreditCard getCreditCardForNumber(long nativePersonalDataManagerAndroid, + PersonalDataManager caller, String cardNumber); + String setCreditCard( + long nativePersonalDataManagerAndroid, PersonalDataManager caller, CreditCard card); + void updateServerCardBillingAddress( + long nativePersonalDataManagerAndroid, PersonalDataManager caller, CreditCard card); + String getBasicCardIssuerNetwork(long nativePersonalDataManagerAndroid, + PersonalDataManager caller, String cardNumber, boolean emptyIfInvalid); + void addServerCreditCardForTest( + long nativePersonalDataManagerAndroid, PersonalDataManager caller, CreditCard card); + void removeByGUID( + long nativePersonalDataManagerAndroid, PersonalDataManager caller, String guid); + void recordAndLogProfileUse( + long nativePersonalDataManagerAndroid, PersonalDataManager caller, String guid); + void setProfileUseStatsForTesting(long nativePersonalDataManagerAndroid, + PersonalDataManager caller, String guid, int count, long date); + int getProfileUseCountForTesting( + long nativePersonalDataManagerAndroid, PersonalDataManager caller, String guid); + long getProfileUseDateForTesting( + long nativePersonalDataManagerAndroid, PersonalDataManager caller, String guid); + void recordAndLogCreditCardUse( + long nativePersonalDataManagerAndroid, PersonalDataManager caller, String guid); + void setCreditCardUseStatsForTesting(long nativePersonalDataManagerAndroid, + PersonalDataManager caller, String guid, int count, long date); + int getCreditCardUseCountForTesting( + long nativePersonalDataManagerAndroid, PersonalDataManager caller, String guid); + long getCreditCardUseDateForTesting( + long nativePersonalDataManagerAndroid, PersonalDataManager caller, String guid); + long getCurrentDateForTesting( + long nativePersonalDataManagerAndroid, PersonalDataManager caller); + void clearUnmaskedCache( + long nativePersonalDataManagerAndroid, PersonalDataManager caller, String guid); + void getFullCardForPaymentRequest(long nativePersonalDataManagerAndroid, + PersonalDataManager caller, WebContents webContents, CreditCard card, + FullCardRequestDelegate delegate); + void loadRulesForAddressNormalization(long nativePersonalDataManagerAndroid, + PersonalDataManager caller, String regionCode); + void loadRulesForSubKeys(long nativePersonalDataManagerAndroid, PersonalDataManager caller, + String regionCode); + void startAddressNormalization(long nativePersonalDataManagerAndroid, + PersonalDataManager caller, AutofillProfile profile, int timeoutSeconds, + NormalizedAddressRequestDelegate delegate); + void startRegionSubKeysRequest(long nativePersonalDataManagerAndroid, + PersonalDataManager caller, String regionCode, int timeoutSeconds, + GetSubKeysRequestDelegate delegate); + boolean hasProfiles(long nativePersonalDataManagerAndroid); + boolean hasCreditCards(long nativePersonalDataManagerAndroid); + boolean isAutofillManaged(); + boolean isAutofillProfileManaged(); + boolean isAutofillCreditCardManaged(); + boolean isPaymentsIntegrationEnabled(); + void setPaymentsIntegrationEnabled(boolean enable); + String toCountryCode(String countryName); + void cancelPendingGetSubKeys(long nativePersonalDataManagerAndroid); + void setSyncServiceForTesting(long nativePersonalDataManagerAndroid); + boolean getPref(int preference); + void setPref(int preference, boolean enable); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/PhoneNumberUtil.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/PhoneNumberUtil.java index f0e0bca..ea51a904 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/PhoneNumberUtil.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/PhoneNumberUtil.java
@@ -9,6 +9,7 @@ import android.text.TextWatcher; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; /** * Android wrapper of i18n::phonenumbers::PhoneNumberUtil which provides convenient methods to @@ -70,7 +71,7 @@ * @return Formatted phone number. */ public static String formatForDisplay(String phoneNumber, @Nullable String countryCode) { - return nativeFormatForDisplay(phoneNumber, countryCode); + return PhoneNumberUtilJni.get().formatForDisplay(phoneNumber, countryCode); } /** @@ -84,7 +85,7 @@ * @return Formatted phone number. */ public static String formatForResponse(String phoneNumber) { - return nativeFormatForResponse(phoneNumber); + return PhoneNumberUtilJni.get().formatForResponse(phoneNumber); } /** @@ -100,10 +101,13 @@ * @return True if the given number is a possible number, otherwise return false. */ public static boolean isPossibleNumber(String phoneNumber, @Nullable String countryCode) { - return nativeIsPossibleNumber(phoneNumber, countryCode); + return PhoneNumberUtilJni.get().isPossibleNumber(phoneNumber, countryCode); } - private static native String nativeFormatForDisplay(String phoneNumber, String countryCode); - private static native String nativeFormatForResponse(String phoneNumber); - private static native boolean nativeIsPossibleNumber(String phoneNumber, String countryCode); + @NativeMethods + interface Natives { + String formatForDisplay(String phoneNumber, String countryCode); + String formatForResponse(String phoneNumber); + boolean isPossibleNumber(String phoneNumber, String countryCode); + } } \ No newline at end of file
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/banners/AppBannerManager.java b/chrome/android/java/src/org/chromium/chrome/browser/banners/AppBannerManager.java index 5a18f90..af11c83 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/banners/AppBannerManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/banners/AppBannerManager.java
@@ -11,6 +11,7 @@ import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.R; import org.chromium.chrome.browser.ShortcutHelper; import org.chromium.chrome.browser.tab.EmptyTabObserver; @@ -140,15 +141,16 @@ String imageUrl = data.imageUrl(); if (TextUtils.isEmpty(imageUrl)) return; - nativeOnAppDetailsRetrieved( - mNativePointer, data, data.title(), data.packageName(), data.imageUrl()); + AppBannerManagerJni.get().onAppDetailsRetrieved(mNativePointer, + AppBannerManager.this, data, data.title(), data.packageName(), + data.imageUrl()); } }; } /** Returns the language option to use for the add to homescreen dialog and menu item. */ public static int getHomescreenLanguageOption() { - int languageOption = nativeGetHomescreenLanguageOption(); + int languageOption = AppBannerManagerJni.get().getHomescreenLanguageOption(); if (languageOption == LanguageOption.INSTALL) { return R.string.menu_add_to_homescreen_install; } @@ -158,7 +160,7 @@ /** Returns the language option to use for app banners. */ // TODO(https://crbug.com/959086): Remove this as it's no longer used. public static int getAppBannerLanguageOption() { - int languageOption = nativeGetHomescreenLanguageOption(); + int languageOption = AppBannerManagerJni.get().getHomescreenLanguageOption(); if (languageOption == LanguageOption.ADD) { return R.string.app_banner_add; } else if (languageOption == LanguageOption.INSTALL) { @@ -169,7 +171,8 @@ @VisibleForTesting public AddToHomescreenDialog getAddToHomescreenDialogForTesting() { - return nativeGetAddToHomescreenDialogForTesting(mNativePointer); + return AppBannerManagerJni.get().getAddToHomescreenDialogForTesting( + mNativePointer, AppBannerManager.this); } /** Overrides whether the system supports add to home screen. Used in testing. */ @@ -181,44 +184,45 @@ /** Returns whether the native AppBannerManager is working. */ @VisibleForTesting public boolean isRunningForTesting() { - return nativeIsRunningForTesting(mNativePointer); + return AppBannerManagerJni.get().isRunningForTesting(mNativePointer, AppBannerManager.this); } /** Sets constants (in days) the banner should be blocked for after dismissing and ignoring. */ @VisibleForTesting static void setDaysAfterDismissAndIgnoreForTesting(int dismissDays, int ignoreDays) { - nativeSetDaysAfterDismissAndIgnoreToTrigger(dismissDays, ignoreDays); + AppBannerManagerJni.get().setDaysAfterDismissAndIgnoreToTrigger(dismissDays, ignoreDays); } /** Sets a constant (in days) that gets added to the time when the current time is requested. */ @VisibleForTesting static void setTimeDeltaForTesting(int days) { - nativeSetTimeDeltaForTesting(days); + AppBannerManagerJni.get().setTimeDeltaForTesting(days); } /** Sets the total required engagement to trigger the banner. */ @VisibleForTesting static void setTotalEngagementForTesting(double engagement) { - nativeSetTotalEngagementToTrigger(engagement); + AppBannerManagerJni.get().setTotalEngagementToTrigger(engagement); } /** Returns the AppBannerManager object. This is owned by the C++ banner manager. */ public static AppBannerManager forTab(Tab tab) { - return nativeGetJavaBannerManagerForWebContents(tab.getWebContents()); + return AppBannerManagerJni.get().getJavaBannerManagerForWebContents(tab.getWebContents()); } - private static native int nativeGetHomescreenLanguageOption(); - private static native AppBannerManager nativeGetJavaBannerManagerForWebContents( - WebContents webContents); - private native boolean nativeOnAppDetailsRetrieved(long nativeAppBannerManagerAndroid, - AppData data, String title, String packageName, String imageUrl); + @NativeMethods + interface Natives { + int getHomescreenLanguageOption(); + AppBannerManager getJavaBannerManagerForWebContents(WebContents webContents); + boolean onAppDetailsRetrieved(long nativeAppBannerManagerAndroid, AppBannerManager caller, + AppData data, String title, String packageName, String imageUrl); + // Testing methods. + AddToHomescreenDialog getAddToHomescreenDialogForTesting( + long nativeAppBannerManagerAndroid, AppBannerManager caller); - // Testing methods. - private native AddToHomescreenDialog nativeGetAddToHomescreenDialogForTesting( - long nativeAppBannerManagerAndroid); - private native boolean nativeIsRunningForTesting(long nativeAppBannerManagerAndroid); - private static native void nativeSetDaysAfterDismissAndIgnoreToTrigger( - int dismissDays, int ignoreDays); - private static native void nativeSetTimeDeltaForTesting(int days); - private static native void nativeSetTotalEngagementToTrigger(double engagement); + boolean isRunningForTesting(long nativeAppBannerManagerAndroid, AppBannerManager caller); + void setDaysAfterDismissAndIgnoreToTrigger(int dismissDays, int ignoreDays); + void setTimeDeltaForTesting(int days); + void setTotalEngagementToTrigger(double engagement); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/banners/AppBannerUiDelegateAndroid.java b/chrome/android/java/src/org/chromium/chrome/browser/banners/AppBannerUiDelegateAndroid.java index d670de5..d2381a6 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/banners/AppBannerUiDelegateAndroid.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/banners/AppBannerUiDelegateAndroid.java
@@ -14,6 +14,7 @@ import org.chromium.base.PackageUtils; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.util.FeatureUtilities; import org.chromium.chrome.browser.webapps.AddToHomescreenDialog; @@ -46,21 +47,24 @@ mAddedToHomescreen = true; // The title is ignored for app banners as we respect the developer-provided title. if (mNativePointer != 0) { - nativeAddToHomescreen(mNativePointer); + AppBannerUiDelegateAndroidJni.get().addToHomescreen( + mNativePointer, AppBannerUiDelegateAndroid.this); } } @Override public void onNativeAppDetailsRequested() { if (mNativePointer != 0) { - nativeShowNativeAppDetails(mNativePointer); + AppBannerUiDelegateAndroidJni.get().showNativeAppDetails( + mNativePointer, AppBannerUiDelegateAndroid.this); } } @Override public void onDialogDismissed() { if (!mAddedToHomescreen && mNativePointer != 0) { - nativeOnUiCancelled(mNativePointer); + AppBannerUiDelegateAndroidJni.get().onUiCancelled( + mNativePointer, AppBannerUiDelegateAndroid.this); } mDialog = null; @@ -139,7 +143,13 @@ return new AppBannerUiDelegateAndroid(nativePtr, tab); } - private native void nativeAddToHomescreen(long nativeAppBannerUiDelegateAndroid); - private native void nativeOnUiCancelled(long nativeAppBannerUiDelegateAndroid); - private native void nativeShowNativeAppDetails(long nativeAppBannerUiDelegateAndroid); + @NativeMethods + interface Natives { + void addToHomescreen( + long nativeAppBannerUiDelegateAndroid, AppBannerUiDelegateAndroid caller); + void onUiCancelled( + long nativeAppBannerUiDelegateAndroid, AppBannerUiDelegateAndroid caller); + void showNativeAppDetails( + long nativeAppBannerUiDelegateAndroid, AppBannerUiDelegateAndroid caller); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkBridge.java index 3af8580..e37259f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkBridge.java
@@ -12,6 +12,7 @@ import org.chromium.base.ObserverList; import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.annotations.NativeMethods; import org.chromium.base.metrics.RecordHistogram; import org.chromium.chrome.browser.partnerbookmarks.PartnerBookmarksShim; import org.chromium.chrome.browser.profiles.Profile; @@ -242,8 +243,9 @@ */ public BookmarkBridge(Profile profile) { mProfile = profile; - mNativeBookmarkBridge = nativeInit(profile); - mIsDoingExtensiveChanges = nativeIsDoingExtensiveChanges(mNativeBookmarkBridge); + mNativeBookmarkBridge = BookmarkBridgeJni.get().init(BookmarkBridge.this, profile); + mIsDoingExtensiveChanges = BookmarkBridgeJni.get().isDoingExtensiveChanges( + mNativeBookmarkBridge, BookmarkBridge.this); } /** @@ -251,7 +253,7 @@ */ public void destroy() { if (mNativeBookmarkBridge != 0) { - nativeDestroy(mNativeBookmarkBridge); + BookmarkBridgeJni.get().destroy(mNativeBookmarkBridge, BookmarkBridge.this); mNativeBookmarkBridge = 0; mIsNativeBookmarkModelLoaded = false; mDelayedBookmarkCallbacks.clear(); @@ -265,7 +267,8 @@ */ @VisibleForTesting public void loadEmptyPartnerBookmarkShimForTesting() { - nativeLoadEmptyPartnerBookmarkShimForTesting(mNativeBookmarkBridge); + BookmarkBridgeJni.get().loadEmptyPartnerBookmarkShimForTesting( + mNativeBookmarkBridge, BookmarkBridge.this); } /** @@ -274,7 +277,8 @@ */ @VisibleForTesting public void loadFakePartnerBookmarkShimForTesting() { - nativeLoadFakePartnerBookmarkShimForTesting(mNativeBookmarkBridge); + BookmarkBridgeJni.get().loadFakePartnerBookmarkShimForTesting( + mNativeBookmarkBridge, BookmarkBridge.this); } /** @@ -338,7 +342,8 @@ */ public BookmarkItem getBookmarkById(BookmarkId id) { assert mIsNativeBookmarkModelLoaded; - return nativeGetBookmarkByID(mNativeBookmarkBridge, id.getId(), id.getType()); + return BookmarkBridgeJni.get().getBookmarkByID( + mNativeBookmarkBridge, BookmarkBridge.this, id.getId(), id.getType()); } /** @@ -347,7 +352,8 @@ public List<BookmarkId> getPermanentNodeIDs() { assert mIsNativeBookmarkModelLoaded; List<BookmarkId> result = new ArrayList<BookmarkId>(); - nativeGetPermanentNodeIDs(mNativeBookmarkBridge, result); + BookmarkBridgeJni.get().getPermanentNodeIDs( + mNativeBookmarkBridge, BookmarkBridge.this, result); return result; } @@ -357,7 +363,8 @@ public List<BookmarkId> getTopLevelFolderParentIDs() { assert mIsNativeBookmarkModelLoaded; List<BookmarkId> result = new ArrayList<BookmarkId>(); - nativeGetTopLevelFolderParentIDs(mNativeBookmarkBridge, result); + BookmarkBridgeJni.get().getTopLevelFolderParentIDs( + mNativeBookmarkBridge, BookmarkBridge.this, result); return result; } @@ -370,7 +377,8 @@ public List<BookmarkId> getTopLevelFolderIDs(boolean getSpecial, boolean getNormal) { assert mIsNativeBookmarkModelLoaded; List<BookmarkId> result = new ArrayList<BookmarkId>(); - nativeGetTopLevelFolderIDs(mNativeBookmarkBridge, getSpecial, getNormal, result); + BookmarkBridgeJni.get().getTopLevelFolderIDs( + mNativeBookmarkBridge, BookmarkBridge.this, getSpecial, getNormal, result); return result; } @@ -388,7 +396,8 @@ public void getAllFoldersWithDepths(List<BookmarkId> folderList, List<Integer> depthList) { assert mIsNativeBookmarkModelLoaded; - nativeGetAllFoldersWithDepths(mNativeBookmarkBridge, folderList, depthList); + BookmarkBridgeJni.get().getAllFoldersWithDepths( + mNativeBookmarkBridge, BookmarkBridge.this, folderList, depthList); } /** @@ -399,7 +408,8 @@ public void getMoveDestinations(List<BookmarkId> folderList, List<Integer> depthList, List<BookmarkId> bookmarksToMove) { assert mIsNativeBookmarkModelLoaded; - nativeGetAllFoldersWithDepths(mNativeBookmarkBridge, folderList, depthList); + BookmarkBridgeJni.get().getAllFoldersWithDepths( + mNativeBookmarkBridge, BookmarkBridge.this, folderList, depthList); if (bookmarksToMove == null || bookmarksToMove.size() == 0) return; boolean shouldTrim = false; @@ -436,7 +446,7 @@ */ public BookmarkId getRootFolderId() { assert mIsNativeBookmarkModelLoaded; - return nativeGetRootFolderId(mNativeBookmarkBridge); + return BookmarkBridgeJni.get().getRootFolderId(mNativeBookmarkBridge, BookmarkBridge.this); } /** @@ -444,7 +454,8 @@ */ public BookmarkId getMobileFolderId() { assert mIsNativeBookmarkModelLoaded; - return nativeGetMobileFolderId(mNativeBookmarkBridge); + return BookmarkBridgeJni.get().getMobileFolderId( + mNativeBookmarkBridge, BookmarkBridge.this); } /** @@ -452,7 +463,7 @@ */ public BookmarkId getOtherFolderId() { assert mIsNativeBookmarkModelLoaded; - return nativeGetOtherFolderId(mNativeBookmarkBridge); + return BookmarkBridgeJni.get().getOtherFolderId(mNativeBookmarkBridge, BookmarkBridge.this); } /** @@ -460,7 +471,8 @@ */ public BookmarkId getDesktopFolderId() { assert mIsNativeBookmarkModelLoaded; - return nativeGetDesktopFolderId(mNativeBookmarkBridge); + return BookmarkBridgeJni.get().getDesktopFolderId( + mNativeBookmarkBridge, BookmarkBridge.this); } /** @@ -468,7 +480,8 @@ */ public int getChildCount(BookmarkId id) { assert mIsNativeBookmarkModelLoaded; - return nativeGetChildCount(mNativeBookmarkBridge, id.getId(), id.getType()); + return BookmarkBridgeJni.get().getChildCount( + mNativeBookmarkBridge, BookmarkBridge.this, id.getId(), id.getType()); } /** @@ -482,12 +495,8 @@ // TODO(crbug.com/160194): Remove boolean parameters after bookmark reordering launches. assert mIsNativeBookmarkModelLoaded; List<BookmarkId> result = new ArrayList<BookmarkId>(); - nativeGetChildIDs(mNativeBookmarkBridge, - id.getId(), - id.getType(), - getFolders, - getBookmarks, - result); + BookmarkBridgeJni.get().getChildIDs(mNativeBookmarkBridge, BookmarkBridge.this, id.getId(), + id.getType(), getFolders, getBookmarks, result); return result; } @@ -500,8 +509,8 @@ */ public BookmarkId getChildAt(BookmarkId folderId, int index) { assert mIsNativeBookmarkModelLoaded; - return nativeGetChildAt(mNativeBookmarkBridge, folderId.getId(), folderId.getType(), - index); + return BookmarkBridgeJni.get().getChildAt(mNativeBookmarkBridge, BookmarkBridge.this, + folderId.getId(), folderId.getType(), index); } /** @@ -511,7 +520,8 @@ */ public int getTotalBookmarkCount(BookmarkId id) { assert mIsNativeBookmarkModelLoaded; - return nativeGetTotalBookmarkCount(mNativeBookmarkBridge, id.getId(), id.getType()); + return BookmarkBridgeJni.get().getTotalBookmarkCount( + mNativeBookmarkBridge, BookmarkBridge.this, id.getId(), id.getType()); } /** @@ -522,8 +532,8 @@ */ public List<BookmarkId> searchBookmarks(String query, int maxNumberOfResult) { List<BookmarkId> bookmarkMatches = new ArrayList<BookmarkId>(); - nativeSearchBookmarks(mNativeBookmarkBridge, bookmarkMatches, query, - maxNumberOfResult); + BookmarkBridgeJni.get().searchBookmarks(mNativeBookmarkBridge, BookmarkBridge.this, + bookmarkMatches, query, maxNumberOfResult); return bookmarkMatches; } @@ -533,7 +543,8 @@ */ public void setBookmarkTitle(BookmarkId id, String title) { assert mIsNativeBookmarkModelLoaded; - nativeSetBookmarkTitle(mNativeBookmarkBridge, id.getId(), id.getType(), title); + BookmarkBridgeJni.get().setBookmarkTitle( + mNativeBookmarkBridge, BookmarkBridge.this, id.getId(), id.getType(), title); } /** @@ -542,7 +553,8 @@ public void setBookmarkUrl(BookmarkId id, String url) { assert mIsNativeBookmarkModelLoaded; assert id.getType() == BookmarkType.NORMAL; - nativeSetBookmarkUrl(mNativeBookmarkBridge, id.getId(), id.getType(), url); + BookmarkBridgeJni.get().setBookmarkUrl( + mNativeBookmarkBridge, BookmarkBridge.this, id.getId(), id.getType(), url); } /** @@ -550,7 +562,8 @@ */ public boolean doesBookmarkExist(BookmarkId id) { assert mIsNativeBookmarkModelLoaded; - return nativeDoesBookmarkExist(mNativeBookmarkBridge, id.getId(), id.getType()); + return BookmarkBridgeJni.get().doesBookmarkExist( + mNativeBookmarkBridge, BookmarkBridge.this, id.getId(), id.getType()); } /** @@ -563,7 +576,8 @@ public List<BookmarkItem> getBookmarksForFolder(BookmarkId folderId) { assert mIsNativeBookmarkModelLoaded; List<BookmarkItem> result = new ArrayList<BookmarkItem>(); - nativeGetBookmarksForFolder(mNativeBookmarkBridge, folderId, null, result); + BookmarkBridgeJni.get().getBookmarksForFolder( + mNativeBookmarkBridge, BookmarkBridge.this, folderId, null, result); return result; } @@ -576,8 +590,8 @@ */ public void getBookmarksForFolder(BookmarkId folderId, BookmarksCallback callback) { if (mIsNativeBookmarkModelLoaded) { - nativeGetBookmarksForFolder(mNativeBookmarkBridge, folderId, callback, - new ArrayList<BookmarkItem>()); + BookmarkBridgeJni.get().getBookmarksForFolder(mNativeBookmarkBridge, + BookmarkBridge.this, folderId, callback, new ArrayList<BookmarkItem>()); } else { mDelayedBookmarkCallbacks.add(new DelayedBookmarkCallback(folderId, callback, DelayedBookmarkCallback.GET_BOOKMARKS_FOR_FOLDER, this)); @@ -591,7 +605,8 @@ */ public boolean isFolderVisible(BookmarkId id) { assert mIsNativeBookmarkModelLoaded; - return nativeIsFolderVisible(mNativeBookmarkBridge, id.getId(), id.getType()); + return BookmarkBridgeJni.get().isFolderVisible( + mNativeBookmarkBridge, BookmarkBridge.this, id.getId(), id.getType()); } /** @@ -603,8 +618,8 @@ */ public void getCurrentFolderHierarchy(BookmarkId folderId, BookmarksCallback callback) { if (mIsNativeBookmarkModelLoaded) { - nativeGetCurrentFolderHierarchy(mNativeBookmarkBridge, folderId, callback, - new ArrayList<BookmarkItem>()); + BookmarkBridgeJni.get().getCurrentFolderHierarchy(mNativeBookmarkBridge, + BookmarkBridge.this, folderId, callback, new ArrayList<BookmarkItem>()); } else { mDelayedBookmarkCallbacks.add(new DelayedBookmarkCallback(folderId, callback, DelayedBookmarkCallback.GET_CURRENT_FOLDER_HIERARCHY, this)); @@ -616,7 +631,8 @@ * @param bookmarkId The ID of the bookmark to be deleted. */ public void deleteBookmark(BookmarkId bookmarkId) { - nativeDeleteBookmark(mNativeBookmarkBridge, bookmarkId); + BookmarkBridgeJni.get().deleteBookmark( + mNativeBookmarkBridge, BookmarkBridge.this, bookmarkId); } /** @@ -625,7 +641,7 @@ * removals. */ public void removeAllUserBookmarks() { - nativeRemoveAllUserBookmarks(mNativeBookmarkBridge); + BookmarkBridgeJni.get().removeAllUserBookmarks(mNativeBookmarkBridge, BookmarkBridge.this); } /** @@ -635,7 +651,8 @@ * @param index The new index for the bookmark. */ public void moveBookmark(BookmarkId bookmarkId, BookmarkId newParentId, int index) { - nativeMoveBookmark(mNativeBookmarkBridge, bookmarkId, newParentId, index); + BookmarkBridgeJni.get().moveBookmark( + mNativeBookmarkBridge, BookmarkBridge.this, bookmarkId, newParentId, index); } /** @@ -654,7 +671,8 @@ assert index >= 0; assert title != null; - return nativeAddFolder(mNativeBookmarkBridge, parent, index, title); + return BookmarkBridgeJni.get().addFolder( + mNativeBookmarkBridge, BookmarkBridge.this, parent, index, title); } /** @@ -676,14 +694,15 @@ assert url != null; if (TextUtils.isEmpty(title)) title = url; - return nativeAddBookmark(mNativeBookmarkBridge, parent, index, title, url); + return BookmarkBridgeJni.get().addBookmark( + mNativeBookmarkBridge, BookmarkBridge.this, parent, index, title, url); } /** * Undo the last undoable action on the top of the bookmark undo stack */ public void undo() { - nativeUndo(mNativeBookmarkBridge); + BookmarkBridgeJni.get().undo(mNativeBookmarkBridge, BookmarkBridge.this); } /** @@ -691,7 +710,7 @@ * Note: This only works with BookmarkModel, not partner bookmarks. */ public void startGroupingUndos() { - nativeStartGroupingUndos(mNativeBookmarkBridge); + BookmarkBridgeJni.get().startGroupingUndos(mNativeBookmarkBridge, BookmarkBridge.this); } /** @@ -699,11 +718,11 @@ * Note: This only works with BookmarkModel, not partner bookmarks. */ public void endGroupingUndos() { - nativeEndGroupingUndos(mNativeBookmarkBridge); + BookmarkBridgeJni.get().endGroupingUndos(mNativeBookmarkBridge, BookmarkBridge.this); } public boolean isEditBookmarksEnabled() { - return nativeIsEditBookmarksEnabled(mNativeBookmarkBridge); + return BookmarkBridgeJni.get().isEditBookmarksEnabled(mNativeBookmarkBridge); } /** Gets the profile. */ @@ -731,7 +750,8 @@ * @param newOrder A list of bookmark IDs that represents the new order for these bookmarks. */ public void reorderBookmarks(BookmarkId parent, long[] newOrder) { - nativeReorderChildren(mNativeBookmarkBridge, parent, newOrder); + BookmarkBridgeJni.get().reorderChildren( + mNativeBookmarkBridge, BookmarkBridge.this, parent, newOrder); } @CalledByNative @@ -904,57 +924,64 @@ } } - private native BookmarkItem nativeGetBookmarkByID(long nativeBookmarkBridge, long id, - int type); - private native void nativeGetPermanentNodeIDs(long nativeBookmarkBridge, - List<BookmarkId> bookmarksList); - private native void nativeGetTopLevelFolderParentIDs(long nativeBookmarkBridge, - List<BookmarkId> bookmarksList); - private native void nativeGetTopLevelFolderIDs(long nativeBookmarkBridge, boolean getSpecial, - boolean getNormal, List<BookmarkId> bookmarksList); - private native void nativeGetAllFoldersWithDepths(long nativeBookmarkBridge, - List<BookmarkId> folderList, List<Integer> depthList); - private native BookmarkId nativeGetRootFolderId(long nativeBookmarkBridge); - private native BookmarkId nativeGetMobileFolderId(long nativeBookmarkBridge); - private native BookmarkId nativeGetOtherFolderId(long nativeBookmarkBridge); - private native BookmarkId nativeGetDesktopFolderId(long nativeBookmarkBridge); - private native int nativeGetChildCount(long nativeBookmarkBridge, long id, int type); - private native void nativeGetChildIDs(long nativeBookmarkBridge, long id, int type, - boolean getFolders, boolean getBookmarks, List<BookmarkId> bookmarksList); - private native BookmarkId nativeGetChildAt(long nativeBookmarkBridge, long id, int type, - int index); - private native int nativeGetTotalBookmarkCount(long nativeBookmarkBridge, long id, int type); - private native void nativeSetBookmarkTitle(long nativeBookmarkBridge, long id, int type, - String title); - private native void nativeSetBookmarkUrl(long nativeBookmarkBridge, long id, int type, - String url); - private native boolean nativeDoesBookmarkExist(long nativeBookmarkBridge, long id, int type); - private native void nativeGetBookmarksForFolder(long nativeBookmarkBridge, - BookmarkId folderId, BookmarksCallback callback, - List<BookmarkItem> bookmarksList); - private native boolean nativeIsFolderVisible(long nativeBookmarkBridge, long id, int type); - private native void nativeGetCurrentFolderHierarchy(long nativeBookmarkBridge, - BookmarkId folderId, BookmarksCallback callback, - List<BookmarkItem> bookmarksList); - private native BookmarkId nativeAddFolder(long nativeBookmarkBridge, BookmarkId parent, - int index, String title); - private native void nativeDeleteBookmark(long nativeBookmarkBridge, BookmarkId bookmarkId); - private native void nativeRemoveAllUserBookmarks(long nativeBookmarkBridge); - private native void nativeMoveBookmark(long nativeBookmarkBridge, BookmarkId bookmarkId, - BookmarkId newParentId, int index); - private native BookmarkId nativeAddBookmark(long nativeBookmarkBridge, BookmarkId parent, - int index, String title, String url); - private native void nativeUndo(long nativeBookmarkBridge); - private native void nativeStartGroupingUndos(long nativeBookmarkBridge); - private native void nativeEndGroupingUndos(long nativeBookmarkBridge); - private native void nativeLoadEmptyPartnerBookmarkShimForTesting(long nativeBookmarkBridge); - private native void nativeLoadFakePartnerBookmarkShimForTesting(long nativeBookmarkBridge); - private native void nativeSearchBookmarks(long nativeBookmarkBridge, - List<BookmarkId> bookmarkMatches, String query, int maxNumber); - private native long nativeInit(Profile profile); - private native boolean nativeIsDoingExtensiveChanges(long nativeBookmarkBridge); - private native void nativeDestroy(long nativeBookmarkBridge); - private static native boolean nativeIsEditBookmarksEnabled(long nativeBookmarkBridge); - private native void nativeReorderChildren( - long nativeBookmarkBridge, BookmarkId parent, long[] orderedNodes); + @NativeMethods + interface Natives { + BookmarkItem getBookmarkByID( + long nativeBookmarkBridge, BookmarkBridge caller, long id, int type); + void getPermanentNodeIDs( + long nativeBookmarkBridge, BookmarkBridge caller, List<BookmarkId> bookmarksList); + void getTopLevelFolderParentIDs( + long nativeBookmarkBridge, BookmarkBridge caller, List<BookmarkId> bookmarksList); + void getTopLevelFolderIDs(long nativeBookmarkBridge, BookmarkBridge caller, + boolean getSpecial, boolean getNormal, List<BookmarkId> bookmarksList); + void getAllFoldersWithDepths(long nativeBookmarkBridge, BookmarkBridge caller, + List<BookmarkId> folderList, List<Integer> depthList); + BookmarkId getRootFolderId(long nativeBookmarkBridge, BookmarkBridge caller); + BookmarkId getMobileFolderId(long nativeBookmarkBridge, BookmarkBridge caller); + BookmarkId getOtherFolderId(long nativeBookmarkBridge, BookmarkBridge caller); + BookmarkId getDesktopFolderId(long nativeBookmarkBridge, BookmarkBridge caller); + int getChildCount(long nativeBookmarkBridge, BookmarkBridge caller, long id, int type); + void getChildIDs(long nativeBookmarkBridge, BookmarkBridge caller, long id, int type, + boolean getFolders, boolean getBookmarks, List<BookmarkId> bookmarksList); + BookmarkId getChildAt( + long nativeBookmarkBridge, BookmarkBridge caller, long id, int type, int index); + int getTotalBookmarkCount( + long nativeBookmarkBridge, BookmarkBridge caller, long id, int type); + void setBookmarkTitle( + long nativeBookmarkBridge, BookmarkBridge caller, long id, int type, String title); + void setBookmarkUrl( + long nativeBookmarkBridge, BookmarkBridge caller, long id, int type, String url); + boolean doesBookmarkExist( + long nativeBookmarkBridge, BookmarkBridge caller, long id, int type); + void getBookmarksForFolder(long nativeBookmarkBridge, BookmarkBridge caller, + BookmarkId folderId, BookmarksCallback callback, List<BookmarkItem> bookmarksList); + boolean isFolderVisible( + long nativeBookmarkBridge, BookmarkBridge caller, long id, int type); + void getCurrentFolderHierarchy(long nativeBookmarkBridge, BookmarkBridge caller, + BookmarkId folderId, BookmarksCallback callback, List<BookmarkItem> bookmarksList); + BookmarkId addFolder(long nativeBookmarkBridge, BookmarkBridge caller, BookmarkId parent, + int index, String title); + void deleteBookmark( + long nativeBookmarkBridge, BookmarkBridge caller, BookmarkId bookmarkId); + void removeAllUserBookmarks(long nativeBookmarkBridge, BookmarkBridge caller); + void moveBookmark(long nativeBookmarkBridge, BookmarkBridge caller, BookmarkId bookmarkId, + BookmarkId newParentId, int index); + BookmarkId addBookmark(long nativeBookmarkBridge, BookmarkBridge caller, BookmarkId parent, + int index, String title, String url); + void undo(long nativeBookmarkBridge, BookmarkBridge caller); + void startGroupingUndos(long nativeBookmarkBridge, BookmarkBridge caller); + void endGroupingUndos(long nativeBookmarkBridge, BookmarkBridge caller); + void loadEmptyPartnerBookmarkShimForTesting( + long nativeBookmarkBridge, BookmarkBridge caller); + void loadFakePartnerBookmarkShimForTesting( + long nativeBookmarkBridge, BookmarkBridge caller); + void searchBookmarks(long nativeBookmarkBridge, BookmarkBridge caller, + List<BookmarkId> bookmarkMatches, String query, int maxNumber); + long init(BookmarkBridge caller, Profile profile); + boolean isDoingExtensiveChanges(long nativeBookmarkBridge, BookmarkBridge caller); + void destroy(long nativeBookmarkBridge, BookmarkBridge caller); + boolean isEditBookmarksEnabled(long nativeBookmarkBridge); + void reorderChildren(long nativeBookmarkBridge, BookmarkBridge caller, BookmarkId parent, + long[] orderedNodes); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/OriginVerifier.java b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/OriginVerifier.java index 460629d..08eb6c65 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/OriginVerifier.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/OriginVerifier.java
@@ -13,6 +13,9 @@ import android.support.annotation.Nullable; import android.text.TextUtils; +import androidx.browser.customtabs.CustomTabsService; +import androidx.browser.customtabs.CustomTabsService.Relation; + import org.chromium.base.CommandLine; import org.chromium.base.ContextUtils; import org.chromium.base.Log; @@ -21,6 +24,7 @@ import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.base.library_loader.LibraryProcessType; import org.chromium.base.task.PostTask; import org.chromium.chrome.browser.ChromeSwitches; @@ -46,8 +50,6 @@ import javax.inject.Inject; -import androidx.browser.customtabs.CustomTabsService; -import androidx.browser.customtabs.CustomTabsService.Relation; import dagger.Reusable; /** @@ -255,7 +257,8 @@ // Early return for testing without native. return; } - mNativeOriginVerifier = nativeInit(Profile.getLastUsedProfile().getOriginalProfile()); + mNativeOriginVerifier = OriginVerifierJni.get().init( + OriginVerifier.this, Profile.getLastUsedProfile().getOriginalProfile()); assert mNativeOriginVerifier != 0; String relationship = null; switch (mRelation) { @@ -271,8 +274,9 @@ } mVerificationStartTime = SystemClock.uptimeMillis(); - boolean requestSent = nativeVerifyOrigin(mNativeOriginVerifier, mPackageName, - mSignatureFingerprint, mOrigin.toString(), relationship); + boolean requestSent = + OriginVerifierJni.get().verifyOrigin(mNativeOriginVerifier, OriginVerifier.this, + mPackageName, mSignatureFingerprint, mOrigin.toString(), relationship); if (!requestSent) { BrowserServicesMetrics.recordVerificationResult( BrowserServicesMetrics.VerificationResult.REQUEST_FAILURE); @@ -300,7 +304,7 @@ */ public void cleanUp() { if (mNativeOriginVerifier == 0) return; - nativeDestroy(mNativeOriginVerifier); + OriginVerifierJni.get().destroy(mNativeOriginVerifier, OriginVerifier.this); mNativeOriginVerifier = 0; } @@ -359,7 +363,7 @@ return hexString.toString(); } - /** Called asynchronously by nativeVerifyOrigin. */ + /** Called asynchronously by OriginVerifierJni.get().verifyOrigin. */ @CalledByNative private void onOriginVerificationResult(int result) { switch (result) { @@ -445,8 +449,11 @@ VerificationResultStore.clearStoredRelationships(); } - private native long nativeInit(Profile profile); - private native boolean nativeVerifyOrigin(long nativeOriginVerifier, String packageName, - String signatureFingerprint, String origin, String relationship); - private native void nativeDestroy(long nativeOriginVerifier); + @NativeMethods + interface Natives { + long init(OriginVerifier caller, Profile profile); + boolean verifyOrigin(long nativeOriginVerifier, OriginVerifier caller, String packageName, + String signatureFingerprint, String origin, String relationship); + void destroy(long nativeOriginVerifier, OriginVerifier caller); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/UkmRecorder.java b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/UkmRecorder.java index 22350d1..a075ea47 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/UkmRecorder.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/UkmRecorder.java
@@ -5,6 +5,7 @@ package org.chromium.chrome.browser.browserservices; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.tab.Tab; import org.chromium.content_public.browser.WebContents; @@ -25,9 +26,12 @@ static class Bridge extends UkmRecorder { @Override public void recordTwaOpened(Tab tab) { - nativeRecordOpen(tab.getWebContents()); + UkmRecorderJni.get().recordOpen(tab.getWebContents()); } } - private static native void nativeRecordOpen(WebContents webContents); + @NativeMethods + interface Natives { + void recordOpen(WebContents webContents); + } } \ No newline at end of file
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/permissiondelegation/InstalledWebappBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/permissiondelegation/InstalledWebappBridge.java index 76aa5e57..dbe833f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/permissiondelegation/InstalledWebappBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/permissiondelegation/InstalledWebappBridge.java
@@ -5,6 +5,7 @@ package org.chromium.chrome.browser.browserservices.permissiondelegation; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.browserservices.Origin; import org.chromium.chrome.browser.preferences.website.ContentSettingValues; @@ -42,7 +43,7 @@ public static void notifyPermissionsChange() { if (sNativeInstalledWebappProvider == 0) return; - nativeNotifyPermissionsChange(sNativeInstalledWebappProvider); + InstalledWebappBridgeJni.get().notifyPermissionsChange(sNativeInstalledWebappProvider); } @CalledByNative @@ -65,5 +66,8 @@ return permission.setting; } - private static native void nativeNotifyPermissionsChange(long provider); + @NativeMethods + interface Natives { + void notifyPermissionsChange(long provider); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/browsing_data/UrlFilterBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/browsing_data/UrlFilterBridge.java index 3c6a0e1..87c30cc 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/browsing_data/UrlFilterBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/browsing_data/UrlFilterBridge.java
@@ -5,6 +5,7 @@ package org.chromium.chrome.browser.browsing_data; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.annotations.NativeMethods; /** * A {@link UrlFilter} that delegates the matching to the native side. @@ -18,13 +19,14 @@ @Override public boolean matchesUrl(String url) { assert mNativeUrlFilterBridge != 0; - return nativeMatchesUrl(mNativeUrlFilterBridge, url); + return UrlFilterBridgeJni.get().matchesUrl( + mNativeUrlFilterBridge, UrlFilterBridge.this, url); } /** Destroys the native counterpart of this object. */ public void destroy() { assert mNativeUrlFilterBridge != 0; - nativeDestroy(mNativeUrlFilterBridge); + UrlFilterBridgeJni.get().destroy(mNativeUrlFilterBridge, UrlFilterBridge.this); mNativeUrlFilterBridge = 0; } @@ -42,6 +44,9 @@ mNativeUrlFilterBridge = nativeUrlFilterBridge; } - private native boolean nativeMatchesUrl(long nativeUrlFilterBridge, String url); - private native void nativeDestroy(long nativeUrlFilterBridge); + @NativeMethods + interface Natives { + boolean matchesUrl(long nativeUrlFilterBridge, UrlFilterBridge caller, String url); + void destroy(long nativeUrlFilterBridge, UrlFilterBridge caller); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/childaccounts/ChildAccountService.java b/chrome/android/java/src/org/chromium/chrome/browser/childaccounts/ChildAccountService.java index ceefb78..c7e181ae 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/childaccounts/ChildAccountService.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/childaccounts/ChildAccountService.java
@@ -10,6 +10,7 @@ import org.chromium.base.Callback; import org.chromium.base.ThreadUtils; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.annotations.NativeMethods; import org.chromium.base.task.PostTask; import org.chromium.components.signin.AccountManagerFacade; import org.chromium.components.signin.ChildAccountStatus; @@ -57,7 +58,7 @@ * @param callback the callback to be called when the status changes. */ public static void listenForStatusChange(Callback<Boolean> callback) { - nativeListenForChildStatusReceived(callback); + ChildAccountServiceJni.get().listenForChildStatusReceived(callback); } @CalledByNative @@ -68,17 +69,21 @@ Activity activity = windowAndroid.getActivity().get(); if (activity == null) { PostTask.postTask(UiThreadTaskTraits.DEFAULT, - () -> nativeOnReauthenticationResult(nativeCallback, false)); + () + -> ChildAccountServiceJni.get().onReauthenticationResult( + nativeCallback, false)); return; } Account account = AccountManagerFacade.createAccountFromName(accountName); AccountManagerFacade.get().updateCredentials(account, activity, - result -> nativeOnReauthenticationResult(nativeCallback, result)); + result + -> ChildAccountServiceJni.get().onReauthenticationResult(nativeCallback, result)); } - private static native void nativeListenForChildStatusReceived(Callback<Boolean> callback); - - private static native void nativeOnReauthenticationResult( - long callbackPtr, boolean reauthSuccessful); + @NativeMethods + interface Natives { + void listenForChildStatusReceived(Callback<Boolean> callback); + void onReauthenticationResult(long callbackPtr, boolean reauthSuccessful); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/complex_tasks/TaskTabHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/complex_tasks/TaskTabHelper.java index 858783e3..9525323d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/complex_tasks/TaskTabHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/complex_tasks/TaskTabHelper.java
@@ -6,6 +6,7 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tab.TabAttributeKeys; import org.chromium.chrome.browser.tab.TabAttributes; @@ -27,10 +28,10 @@ */ public static void createForTab(Tab tab, Tab parentTab) { if (parentTab == null) return; - TabAttributes.from(tab).set( - TabAttributeKeys.PARENT_TAB_TASK_ID, nativeGetTaskId(parentTab.getWebContents())); + TabAttributes.from(tab).set(TabAttributeKeys.PARENT_TAB_TASK_ID, + TaskTabHelperJni.get().getTaskId(parentTab.getWebContents())); TabAttributes.from(tab).set(TabAttributeKeys.PARENT_TAB_ROOT_TASK_ID, - nativeGetRootTaskId(parentTab.getWebContents())); + TaskTabHelperJni.get().getRootTaskId(parentTab.getWebContents())); } @CalledByNative @@ -46,6 +47,9 @@ return parentRootTaskId == null ? INVALID_ID : parentRootTaskId; } - private static native long nativeGetTaskId(WebContents webContents); - private static native long nativeGetRootTaskId(WebContents webContents); + @NativeMethods + interface Natives { + long getTaskId(WebContents webContents); + long getRootTaskId(WebContents webContents); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/component_updater/UpdateScheduler.java b/chrome/android/java/src/org/chromium/chrome/browser/component_updater/UpdateScheduler.java index 444fb844..459ecdd 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/component_updater/UpdateScheduler.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/component_updater/UpdateScheduler.java
@@ -12,6 +12,7 @@ import org.chromium.base.ContextUtils; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.components.background_task_scheduler.BackgroundTask.TaskFinishedCallback; import org.chromium.components.background_task_scheduler.BackgroundTaskSchedulerFactory; import org.chromium.components.background_task_scheduler.TaskIds; @@ -47,12 +48,12 @@ /* package */ void onStartTaskWithNative() { assert mNativeScheduler != 0; - nativeOnStartTask(mNativeScheduler); + UpdateSchedulerJni.get().onStartTask(mNativeScheduler, UpdateScheduler.this); } /* package */ void onStopTask() { if (mNativeScheduler != 0) { - nativeOnStopTask(mNativeScheduler); + UpdateSchedulerJni.get().onStopTask(mNativeScheduler, UpdateScheduler.this); } mTaskFinishedCallback = null; scheduleInternal(mDelayMs); @@ -106,6 +107,9 @@ ContextUtils.getApplicationContext(), TaskIds.COMPONENT_UPDATE_JOB_ID); } - private native void nativeOnStartTask(long nativeBackgroundTaskUpdateScheduler); - private native void nativeOnStopTask(long nativeBackgroundTaskUpdateScheduler); + @NativeMethods + interface Natives { + void onStartTask(long nativeBackgroundTaskUpdateScheduler, UpdateScheduler caller); + void onStopTask(long nativeBackgroundTaskUpdateScheduler, UpdateScheduler caller); + } } \ No newline at end of file
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorView.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorView.java index 77aa6c07..02e3ccc 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorView.java
@@ -22,6 +22,7 @@ import org.chromium.base.TraceEvent; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.compositor.layouts.Layout; import org.chromium.chrome.browser.compositor.layouts.LayoutProvider; import org.chromium.chrome.browser.compositor.layouts.LayoutRenderHost; @@ -229,7 +230,9 @@ // But with SurfaceControl, switching to a new SurfaceView evicts that content when // destroying the GLSurface in the GPU process. So we need to explicitly preserve them in // the GPU process during this transition. - if (switchToSurfaceView) nativeCacheBackBufferForCurrentSurface(mNativeCompositorView); + if (switchToSurfaceView) + CompositorViewJni.get().cacheBackBufferForCurrentSurface( + mNativeCompositorView, CompositorView.this); // Trigger the creation of a new SurfaceView. CompositorSurfaceManager will handle caching // the old one during the transition. @@ -256,7 +259,8 @@ public void shutDown() { mCompositorSurfaceManager.shutDown(); if (mScreenStateReceiver != null) mScreenStateReceiver.shutDown(); - if (mNativeCompositorView != 0) nativeDestroy(mNativeCompositorView); + if (mNativeCompositorView != 0) + CompositorViewJni.get().destroy(mNativeCompositorView, CompositorView.this); mNativeCompositorView = 0; } @@ -277,8 +281,8 @@ mLayerTitleCache = layerTitleCache; mTabContentManager = tabContentManager; - mNativeCompositorView = - nativeInit(lowMemDevice, windowAndroid, layerTitleCache, tabContentManager); + mNativeCompositorView = CompositorViewJni.get().init(CompositorView.this, lowMemDevice, + windowAndroid, layerTitleCache, tabContentManager); // compositor_impl_android.cc will use 565 EGL surfaces if and only if we're using a low // memory device, and no alpha channel is desired. Otherwise, it will use 8888. Since @@ -299,10 +303,11 @@ setVisibility(View.VISIBLE); // Grab the Resource Manager - mResourceManager = nativeGetResourceManager(mNativeCompositorView); + mResourceManager = CompositorViewJni.get().getResourceManager( + mNativeCompositorView, CompositorView.this); // Redraw in case there are callbacks pending |mDrawingFinishedCallbacks|. - nativeSetNeedsComposite(mNativeCompositorView); + CompositorViewJni.get().setNeedsComposite(mNativeCompositorView, CompositorView.this); } private void setWindowAndroid(WindowAndroid windowAndroid) { @@ -324,7 +329,8 @@ * @param enabled Whether to enter or leave overlay video mode. */ public void setOverlayVideoMode(boolean enabled) { - nativeSetOverlayVideoMode(mNativeCompositorView, enabled); + CompositorViewJni.get().setOverlayVideoMode( + mNativeCompositorView, CompositorView.this, enabled); mOverlayVideoEnabled = enabled; // Request the new surface, even if it's the same as the old one. We'll get a synthetic @@ -358,15 +364,16 @@ public void surfaceRedrawNeededAsync(Runnable drawingFinished) { if (mDrawingFinishedCallbacks == null) mDrawingFinishedCallbacks = new ArrayList<>(); mDrawingFinishedCallbacks.add(drawingFinished); - if (mNativeCompositorView != 0) nativeSetNeedsComposite(mNativeCompositorView); + if (mNativeCompositorView != 0) + CompositorViewJni.get().setNeedsComposite(mNativeCompositorView, CompositorView.this); } @Override public void surfaceChanged(Surface surface, int format, int width, int height) { if (mNativeCompositorView == 0) return; - nativeSurfaceChanged( - mNativeCompositorView, format, width, height, canUseSurfaceControl(), surface); + CompositorViewJni.get().surfaceChanged(mNativeCompositorView, CompositorView.this, format, + width, height, canUseSurfaceControl(), surface); mRenderHost.onSurfaceResized(width, height); } @@ -374,7 +381,7 @@ public void surfaceCreated(Surface surface) { if (mNativeCompositorView == 0) return; - nativeSurfaceCreated(mNativeCompositorView); + CompositorViewJni.get().surfaceCreated(mNativeCompositorView, CompositorView.this); mFramesUntilHideBackground = 2; mRenderHost.onSurfaceCreated(); } @@ -383,12 +390,12 @@ public void surfaceDestroyed(Surface surface) { if (mNativeCompositorView == 0) return; - nativeSurfaceDestroyed(mNativeCompositorView); + CompositorViewJni.get().surfaceDestroyed(mNativeCompositorView, CompositorView.this); } @Override public void unownedSurfaceDestroyed() { - nativeEvictCachedBackBuffer(mNativeCompositorView); + CompositorViewJni.get().evictCachedBackBuffer(mNativeCompositorView, CompositorView.this); } @Override @@ -408,7 +415,8 @@ } void onPhysicalBackingSizeChanged(WebContents webContents, int width, int height) { - nativeOnPhysicalBackingSizeChanged(mNativeCompositorView, webContents, width, height); + CompositorViewJni.get().onPhysicalBackingSizeChanged( + mNativeCompositorView, CompositorView.this, webContents, width, height); } @CalledByNative @@ -425,7 +433,8 @@ * Request compositor view to render a frame. */ public void requestRender() { - if (mNativeCompositorView != 0) nativeSetNeedsComposite(mNativeCompositorView); + if (mNativeCompositorView != 0) + CompositorViewJni.get().setNeedsComposite(mNativeCompositorView, CompositorView.this); } @CalledByNative @@ -449,7 +458,8 @@ // Evict the SurfaceView and the associated backbuffer now that the new SurfaceView is // ready. - nativeEvictCachedBackBuffer(mNativeCompositorView); + CompositorViewJni.get().evictCachedBackBuffer( + mNativeCompositorView, CompositorView.this); mCompositorSurfaceManager.doneWithUnownedSurface(); } @@ -490,16 +500,17 @@ // If you do, you could inadvertently trigger follow up renders. For further information // see dtrainor@, tedchoc@, or klobag@. - nativeSetLayoutBounds(mNativeCompositorView); + CompositorViewJni.get().setLayoutBounds(mNativeCompositorView, CompositorView.this); SceneLayer sceneLayer = provider.getUpdatedActiveSceneLayer(mLayerTitleCache, mTabContentManager, mResourceManager, provider.getFullscreenManager()); - nativeSetSceneLayer(mNativeCompositorView, sceneLayer); + CompositorViewJni.get().setSceneLayer( + mNativeCompositorView, CompositorView.this, sceneLayer); TabModelImpl.flushActualTabSwitchLatencyMetric(); - nativeFinalizeLayers(mNativeCompositorView); + CompositorViewJni.get().finalizeLayers(mNativeCompositorView, CompositorView.this); TraceEvent.end("CompositorView:finalizeLayers"); } @@ -550,10 +561,11 @@ mIsInVr = true; mCompositorSurfaceManager.shutDown(); - nativeSetCompositorWindow(mNativeCompositorView, window); + CompositorViewJni.get().setCompositorWindow( + mNativeCompositorView, CompositorView.this, window); mCompositorSurfaceManager = vrCompositorSurfaceManager; mCompositorSurfaceManager.requestSurface(PixelFormat.OPAQUE); - nativeSetNeedsComposite(mNativeCompositorView); + CompositorViewJni.get().setNeedsComposite(mNativeCompositorView, CompositorView.this); setWindowAndroid(window); } @@ -569,33 +581,38 @@ if (mNativeCompositorView == 0) return; setWindowAndroid(windowToRestore); mCompositorSurfaceManager.shutDown(); - nativeSetCompositorWindow(mNativeCompositorView, mWindowAndroid); + CompositorViewJni.get().setCompositorWindow( + mNativeCompositorView, CompositorView.this, mWindowAndroid); createCompositorSurfaceManager(); } private void createCompositorSurfaceManager() { mCompositorSurfaceManager = new CompositorSurfaceManagerImpl(this, this); mCompositorSurfaceManager.requestSurface(getSurfacePixelFormat()); - nativeSetNeedsComposite(mNativeCompositorView); + CompositorViewJni.get().setNeedsComposite(mNativeCompositorView, CompositorView.this); mCompositorSurfaceManager.setVisibility(getVisibility()); } - private native long nativeInit(boolean lowMemDevice, WindowAndroid windowAndroid, - LayerTitleCache layerTitleCache, TabContentManager tabContentManager); - private native void nativeDestroy(long nativeCompositorView); - private native ResourceManager nativeGetResourceManager(long nativeCompositorView); - private native void nativeSurfaceCreated(long nativeCompositorView); - private native void nativeSurfaceDestroyed(long nativeCompositorView); - private native void nativeSurfaceChanged(long nativeCompositorView, int format, int width, - int height, boolean backedBySurfaceTexture, Surface surface); - private native void nativeOnPhysicalBackingSizeChanged( - long nativeCompositorView, WebContents webContents, int width, int height); - private native void nativeFinalizeLayers(long nativeCompositorView); - private native void nativeSetNeedsComposite(long nativeCompositorView); - private native void nativeSetLayoutBounds(long nativeCompositorView); - private native void nativeSetOverlayVideoMode(long nativeCompositorView, boolean enabled); - private native void nativeSetSceneLayer(long nativeCompositorView, SceneLayer sceneLayer); - private native void nativeSetCompositorWindow(long nativeCompositorView, WindowAndroid window); - private native void nativeCacheBackBufferForCurrentSurface(long nativeCompositorView); - private native void nativeEvictCachedBackBuffer(long nativeCompositorView); + @NativeMethods + interface Natives { + long init(CompositorView caller, boolean lowMemDevice, WindowAndroid windowAndroid, + LayerTitleCache layerTitleCache, TabContentManager tabContentManager); + void destroy(long nativeCompositorView, CompositorView caller); + ResourceManager getResourceManager(long nativeCompositorView, CompositorView caller); + void surfaceCreated(long nativeCompositorView, CompositorView caller); + void surfaceDestroyed(long nativeCompositorView, CompositorView caller); + void surfaceChanged(long nativeCompositorView, CompositorView caller, int format, int width, + int height, boolean backedBySurfaceTexture, Surface surface); + void onPhysicalBackingSizeChanged(long nativeCompositorView, CompositorView caller, + WebContents webContents, int width, int height); + void finalizeLayers(long nativeCompositorView, CompositorView caller); + void setNeedsComposite(long nativeCompositorView, CompositorView caller); + void setLayoutBounds(long nativeCompositorView, CompositorView caller); + void setOverlayVideoMode(long nativeCompositorView, CompositorView caller, boolean enabled); + void setSceneLayer(long nativeCompositorView, CompositorView caller, SceneLayer sceneLayer); + void setCompositorWindow( + long nativeCompositorView, CompositorView caller, WindowAndroid window); + void cacheBackBufferForCurrentSurface(long nativeCompositorView, CompositorView caller); + void evictCachedBackBuffer(long nativeCompositorView, CompositorView caller); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/LayerTitleCache.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/LayerTitleCache.java index c4ecc74c..3bb830fa 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/LayerTitleCache.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/LayerTitleCache.java
@@ -12,6 +12,7 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.compositor.layouts.content.TitleBitmapFactory; @@ -64,8 +65,9 @@ res.getDimensionPixelSize(R.dimen.tab_title_favicon_start_padding); final int faviconEndPaddingPx = res.getDimensionPixelSize(R.dimen.tab_title_favicon_end_padding); - mNativeLayerTitleCache = nativeInit(fadeWidthPx, faviconStartPaddingPx, faviconEndPaddingPx, - R.drawable.spinner, R.drawable.spinner_white); + mNativeLayerTitleCache = LayerTitleCacheJni.get().init(LayerTitleCache.this, fadeWidthPx, + faviconStartPaddingPx, faviconEndPaddingPx, R.drawable.spinner, + R.drawable.spinner_white); mFaviconSize = res.getDimensionPixelSize(R.dimen.compositor_tab_title_favicon_size); mStandardTitleBitmapFactory = new TitleBitmapFactory(context, false); mDarkTitleBitmapFactory = new TitleBitmapFactory(context, true); @@ -85,7 +87,7 @@ */ public void shutDown() { if (mNativeLayerTitleCache == 0) return; - nativeDestroy(mNativeLayerTitleCache); + LayerTitleCacheJni.get().destroy(mNativeLayerTitleCache); mNativeLayerTitleCache = 0; } @@ -151,8 +153,8 @@ boolean isRtl = tabTitle != null && LocalizationUtils.getFirstStrongCharacterDirection(tabTitle) == LocalizationUtils.RIGHT_TO_LEFT; - nativeUpdateLayer(mNativeLayerTitleCache, tabId, title.getTitleResId(), - title.getFaviconResId(), isDarkTheme, isRtl); + LayerTitleCacheJni.get().updateLayer(mNativeLayerTitleCache, LayerTitleCache.this, + tabId, title.getTitleResId(), title.getFaviconResId(), isDarkTheme, isRtl); } return titleString; } @@ -205,7 +207,8 @@ if (!title.updateFaviconFromHistory(faviconBitmap)) return; if (mNativeLayerTitleCache != 0) { - nativeUpdateFavicon(mNativeLayerTitleCache, tabId, title.getFaviconResId()); + LayerTitleCacheJni.get().updateFavicon( + mNativeLayerTitleCache, LayerTitleCache.this, tabId, title.getFaviconResId()); } } @@ -216,7 +219,8 @@ title.unregister(); mTitles.remove(tabId); if (mNativeLayerTitleCache == 0) return; - nativeUpdateLayer(mNativeLayerTitleCache, tabId, -1, -1, false, false); + LayerTitleCacheJni.get().updateLayer( + mNativeLayerTitleCache, LayerTitleCache.this, tabId, -1, -1, false, false); } @Override @@ -233,7 +237,8 @@ if (title != null) mTitles.put(exceptId, title); if (mNativeLayerTitleCache == 0) return; - nativeClearExcept(mNativeLayerTitleCache, exceptId); + LayerTitleCacheJni.get().clearExcept( + mNativeLayerTitleCache, LayerTitleCache.this, exceptId); } private class Title { @@ -282,12 +287,15 @@ } } - private native long nativeInit(int fadeWidth, int faviconStartlPadding, int faviconEndPadding, - int spinnerResId, int spinnerIncognitoResId); - private static native void nativeDestroy(long nativeLayerTitleCache); - private native void nativeClearExcept(long nativeLayerTitleCache, int exceptId); - private native void nativeUpdateLayer(long nativeLayerTitleCache, int tabId, int titleResId, - int faviconResId, boolean isIncognito, boolean isRtl); - private native void nativeUpdateFavicon(long nativeLayerTitleCache, int tabId, - int faviconResId); + @NativeMethods + interface Natives { + long init(LayerTitleCache caller, int fadeWidth, int faviconStartlPadding, + int faviconEndPadding, int spinnerResId, int spinnerIncognitoResId); + void destroy(long nativeLayerTitleCache); + void clearExcept(long nativeLayerTitleCache, LayerTitleCache caller, int exceptId); + void updateLayer(long nativeLayerTitleCache, LayerTitleCache caller, int tabId, + int titleResId, int faviconResId, boolean isIncognito, boolean isRtl); + void updateFavicon( + long nativeLayerTitleCache, LayerTitleCache caller, int tabId, int faviconResId); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanelContent.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanelContent.java index cc4f08b..758eb07 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanelContent.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanelContent.java
@@ -12,6 +12,7 @@ import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.ChromeVersionInfo; import org.chromium.chrome.browser.WebContentsFactory; @@ -170,7 +171,7 @@ public OverlayPanelContent(OverlayContentDelegate contentDelegate, OverlayContentProgressObserver progressObserver, ChromeActivity activity, boolean isIncognito, float barHeight) { - mNativeOverlayPanelContentPtr = nativeInit(); + mNativeOverlayPanelContentPtr = OverlayPanelContentJni.get().init(OverlayPanelContent.this); mContentDelegate = contentDelegate; mProgressObserver = progressObserver; mActivity = activity; @@ -319,7 +320,8 @@ ContentUtils.setUserAgentOverride(mWebContents); // Transfers the ownership of the WebContents to the native OverlayPanelContent. - nativeSetWebContents(mNativeOverlayPanelContentPtr, mWebContents, mWebContentsDelegate); + OverlayPanelContentJni.get().setWebContents(mNativeOverlayPanelContentPtr, + OverlayPanelContent.this, mWebContents, mWebContentsDelegate); mWebContentsObserver = new WebContentsObserver(mWebContents) { @@ -355,8 +357,8 @@ mContainerView = cv; mInterceptNavigationDelegate = new InterceptNavigationDelegateImpl(); - nativeSetInterceptNavigationDelegate( - mNativeOverlayPanelContentPtr, mInterceptNavigationDelegate, mWebContents); + OverlayPanelContentJni.get().setInterceptNavigationDelegate(mNativeOverlayPanelContentPtr, + OverlayPanelContent.this, mInterceptNavigationDelegate, mWebContents); mContentDelegate.onContentViewCreated(); resizePanelContentView(); @@ -369,7 +371,8 @@ private void destroyWebContents() { if (mWebContents != null) { // Native destroy will call up to destroy the Java WebContents. - nativeDestroyWebContents(mNativeOverlayPanelContentPtr); + OverlayPanelContentJni.get().destroyWebContents( + mNativeOverlayPanelContentPtr, OverlayPanelContent.this); mWebContents = null; if (mWebContentsObserver != null) { mWebContentsObserver.destroy(); @@ -398,7 +401,8 @@ * Otherwise the web contents never accounts for them. */ public void updateBrowserControlsState(boolean areControlsHidden) { - nativeUpdateBrowserControlsState(mNativeOverlayPanelContentPtr, areControlsHidden); + OverlayPanelContentJni.get().updateBrowserControlsState( + mNativeOverlayPanelContentPtr, OverlayPanelContent.this, areControlsHidden); } /** @@ -496,8 +500,8 @@ WebContents webContents = getWebContents(); if (webContents == null) return; int viewHeight = mContentViewHeight - (mSubtractBarHeight ? mBarHeightPx : 0); - nativeOnPhysicalBackingSizeChanged( - mNativeOverlayPanelContentPtr, webContents, mContentViewWidth, viewHeight); + OverlayPanelContentJni.get().onPhysicalBackingSizeChanged(mNativeOverlayPanelContentPtr, + OverlayPanelContent.this, webContents, mContentViewWidth, viewHeight); mWebContents.setSize(mContentViewWidth, viewHeight); } @@ -507,7 +511,8 @@ * @param urlTimeMs The time the URL was navigated to. */ public void removeLastHistoryEntry(String historyUrl, long urlTimeMs) { - nativeRemoveLastHistoryEntry(mNativeOverlayPanelContentPtr, historyUrl, urlTimeMs); + OverlayPanelContentJni.get().removeLastHistoryEntry( + mNativeOverlayPanelContentPtr, OverlayPanelContent.this, historyUrl, urlTimeMs); } /** @@ -518,24 +523,30 @@ if (mWebContents != null) destroyWebContents(); // Tests will not create the native pointer, so we need to check if it's not zero - // otherwise calling nativeDestroy with zero will make Chrome crash. + // otherwise calling OverlayPanelContentJni.get().destroy with zero will make Chrome crash. if (mNativeOverlayPanelContentPtr != 0L) { - nativeDestroy(mNativeOverlayPanelContentPtr); + OverlayPanelContentJni.get().destroy( + mNativeOverlayPanelContentPtr, OverlayPanelContent.this); } } - // Native calls. - private native long nativeInit(); - private native void nativeDestroy(long nativeOverlayPanelContent); - private native void nativeRemoveLastHistoryEntry( - long nativeOverlayPanelContent, String historyUrl, long urlTimeMs); - private native void nativeOnPhysicalBackingSizeChanged( - long nativeOverlayPanelContent, WebContents webContents, int width, int height); - private native void nativeSetWebContents(long nativeOverlayPanelContent, - WebContents webContents, WebContentsDelegateAndroid delegate); - private native void nativeDestroyWebContents(long nativeOverlayPanelContent); - private native void nativeSetInterceptNavigationDelegate(long nativeOverlayPanelContent, - InterceptNavigationDelegate delegate, WebContents webContents); - private native void nativeUpdateBrowserControlsState( - long nativeOverlayPanelContent, boolean areControlsHidden); + @NativeMethods + interface Natives { + // Native calls. + long init(OverlayPanelContent caller); + + void destroy(long nativeOverlayPanelContent, OverlayPanelContent caller); + void removeLastHistoryEntry(long nativeOverlayPanelContent, OverlayPanelContent caller, + String historyUrl, long urlTimeMs); + void onPhysicalBackingSizeChanged(long nativeOverlayPanelContent, + OverlayPanelContent caller, WebContents webContents, int width, int height); + void setWebContents(long nativeOverlayPanelContent, OverlayPanelContent caller, + WebContents webContents, WebContentsDelegateAndroid delegate); + void destroyWebContents(long nativeOverlayPanelContent, OverlayPanelContent caller); + void setInterceptNavigationDelegate(long nativeOverlayPanelContent, + OverlayPanelContent caller, InterceptNavigationDelegate delegate, + WebContents webContents); + void updateBrowserControlsState(long nativeOverlayPanelContent, OverlayPanelContent caller, + boolean areControlsHidden); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/content/TabContentManager.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/content/TabContentManager.java index 2727ecc..ee73add 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/content/TabContentManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/content/TabContentManager.java
@@ -23,6 +23,7 @@ import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.task.AsyncTask; import org.chromium.chrome.R; @@ -158,9 +159,9 @@ mPriorityTabIds = new int[mFullResThumbnailsMaxSize]; - mNativeTabContentManager = - nativeInit(defaultCacheSize, approximationCacheSize, compressionQueueMaxSize, - writeQueueMaxSize, useApproximationThumbnails, saveJpegThumbnails); + mNativeTabContentManager = TabContentManagerJni.get().init(TabContentManager.this, + defaultCacheSize, approximationCacheSize, compressionQueueMaxSize, + writeQueueMaxSize, useApproximationThumbnails, saveJpegThumbnails); } /** @@ -168,7 +169,7 @@ */ public void destroy() { if (mNativeTabContentManager != 0) { - nativeDestroy(mNativeTabContentManager); + TabContentManagerJni.get().destroy(mNativeTabContentManager); mNativeTabContentManager = 0; } } @@ -184,7 +185,8 @@ */ public void attachTab(Tab tab) { if (mNativeTabContentManager == 0) return; - nativeAttachTab(mNativeTabContentManager, tab, tab.getId()); + TabContentManagerJni.get().attachTab( + mNativeTabContentManager, TabContentManager.this, tab, tab.getId()); } /** @@ -193,7 +195,8 @@ */ public void detachTab(Tab tab) { if (mNativeTabContentManager == 0) return; - nativeDetachTab(mNativeTabContentManager, tab, tab.getId()); + TabContentManagerJni.get().detachTab( + mNativeTabContentManager, TabContentManager.this, tab, tab.getId()); } /** @@ -281,7 +284,8 @@ */ public boolean hasFullCachedThumbnail(int tabId) { if (mNativeTabContentManager == 0) return false; - return nativeHasFullCachedThumbnail(mNativeTabContentManager, tabId); + return TabContentManagerJni.get().hasFullCachedThumbnail( + mNativeTabContentManager, TabContentManager.this, tabId); } /** @@ -337,7 +341,8 @@ } private void getTabThumbnailFromDisk(@NonNull Tab tab, @NonNull Callback<Bitmap> callback) { - // Try JPEG thumbnail first before using the more costly nativeGetEtc1TabThumbnail. + // Try JPEG thumbnail first before using the more costly + // TabContentManagerJni.get().getEtc1TabThumbnail. new AsyncTask<Bitmap>() { @Override public Bitmap doInBackground() { @@ -355,18 +360,21 @@ return; } if (mNativeTabContentManager == 0 || !mSnapshotsEnabled) return; - nativeGetEtc1TabThumbnail(mNativeTabContentManager, tab.getId(), (etc1) -> { - if (etc1 != null) { - RecordHistogram.recordEnumeratedHistogram(UMA_THUMBNAIL_FETCHING_RESULT, - ThumbnailFetchingResult.GOT_ETC1, - ThumbnailFetchingResult.NUM_ENTRIES); - } else { - RecordHistogram.recordEnumeratedHistogram(UMA_THUMBNAIL_FETCHING_RESULT, - ThumbnailFetchingResult.GOT_NOTHING, - ThumbnailFetchingResult.NUM_ENTRIES); - } - callback.onResult(etc1); - }); + TabContentManagerJni.get().getEtc1TabThumbnail( + mNativeTabContentManager, TabContentManager.this, tab.getId(), (etc1) -> { + if (etc1 != null) { + RecordHistogram.recordEnumeratedHistogram( + UMA_THUMBNAIL_FETCHING_RESULT, + ThumbnailFetchingResult.GOT_ETC1, + ThumbnailFetchingResult.NUM_ENTRIES); + } else { + RecordHistogram.recordEnumeratedHistogram( + UMA_THUMBNAIL_FETCHING_RESULT, + ThumbnailFetchingResult.GOT_NOTHING, + ThumbnailFetchingResult.NUM_ENTRIES); + } + callback.onResult(etc1); + }); } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } @@ -386,7 +394,8 @@ Bitmap nativeBitmap = readbackNativeBitmap(tab, mThumbnailScale); if (nativeBitmap == null) return null; - nativeCacheTabWithBitmap(mNativeTabContentManager, tab, nativeBitmap, mThumbnailScale); + TabContentManagerJni.get().cacheTabWithBitmap(mNativeTabContentManager, + TabContentManager.this, tab, nativeBitmap, mThumbnailScale); return nativeBitmap; } @@ -405,11 +414,11 @@ if (tab.getNativePage() != null || isNativeViewShowing(tab)) { final float downsamplingScale = 0.5f; // If we use readbackNativeBitmap() with a downsampled scale and not saving it through - // nativeCacheTabWithBitmap(), the logic of InvalidationAwareThumbnailProvider - // might prevent captureThumbnail() from getting the latest thumbnail. - // Therefore, we have to also call cacheNativeTabThumbnail(), and do the downsampling - // here ourselves. This is less efficient than capturing a downsampled bitmap, but - // the performance here is not the bottleneck. + // TabContentManagerJni.get().cacheTabWithBitmap( TabContentManager.this, ), the logic + // of InvalidationAwareThumbnailProvider might prevent captureThumbnail() from getting + // the latest thumbnail. Therefore, we have to also call cacheNativeTabThumbnail(), and + // do the downsampling here ourselves. This is less efficient than capturing a + // downsampled bitmap, but the performance here is not the bottleneck. Bitmap bitmap = cacheNativeTabThumbnail(tab); if (callback == null) return; if (bitmap == null) { @@ -430,8 +439,9 @@ // path of capturing a downsampled copy. // This faster path is essential to Tab-to-Grid animation to be smooth. final float downsamplingScale = writeToCache ? 1 : 0.5f; - nativeCaptureThumbnail(mNativeTabContentManager, tab, - mThumbnailScale * downsamplingScale, writeToCache, callback); + TabContentManagerJni.get().captureThumbnail(mNativeTabContentManager, + TabContentManager.this, tab, mThumbnailScale * downsamplingScale, writeToCache, + callback); } } @@ -442,7 +452,8 @@ */ public void invalidateIfChanged(int tabId, String url) { if (mNativeTabContentManager != 0) { - nativeInvalidateIfChanged(mNativeTabContentManager, tabId, url); + TabContentManagerJni.get().invalidateIfChanged( + mNativeTabContentManager, TabContentManager.this, tabId, url); } } @@ -470,7 +481,8 @@ for (int i = 0; i < idsSize; i++) { mPriorityTabIds[i] = priority.get(i); } - nativeUpdateVisibleIds(mNativeTabContentManager, mPriorityTabIds, primaryTabId); + TabContentManagerJni.get().updateVisibleIds(mNativeTabContentManager, + TabContentManager.this, mPriorityTabIds, primaryTabId); } } @@ -480,18 +492,21 @@ */ public void removeTabThumbnail(int tabId) { if (mNativeTabContentManager != 0) { - nativeRemoveTabThumbnail(mNativeTabContentManager, tabId); + TabContentManagerJni.get().removeTabThumbnail( + mNativeTabContentManager, TabContentManager.this, tabId); } } @VisibleForTesting public void setCaptureMinRequestTimeForTesting(int timeMs) { - nativeSetCaptureMinRequestTimeForTesting(mNativeTabContentManager, timeMs); + TabContentManagerJni.get().setCaptureMinRequestTimeForTesting( + mNativeTabContentManager, TabContentManager.this, timeMs); } @VisibleForTesting public int getPendingReadbacksForTesting() { - return nativeGetPendingReadbacksForTesting(mNativeTabContentManager); + return TabContentManagerJni.get().getPendingReadbacksForTesting( + mNativeTabContentManager, TabContentManager.this); } @CalledByNative @@ -505,26 +520,31 @@ return tab != null && (SadTab.isShowing(tab) || SuspendedTab.isShowing(tab)); } - // Class Object Methods - private native long nativeInit(int defaultCacheSize, int approximationCacheSize, - int compressionQueueMaxSize, int writeQueueMaxSize, boolean useApproximationThumbnail, - boolean saveJpegThumbnails); - private native void nativeAttachTab(long nativeTabContentManager, Tab tab, int tabId); - private native void nativeDetachTab(long nativeTabContentManager, Tab tab, int tabId); - private native boolean nativeHasFullCachedThumbnail(long nativeTabContentManager, int tabId); - private native void nativeCaptureThumbnail(long nativeTabContentManager, Object tab, - float thumbnailScale, boolean writeToCache, Callback<Bitmap> callback); - private native void nativeCacheTabWithBitmap(long nativeTabContentManager, Object tab, - Object bitmap, float thumbnailScale); - private native void nativeInvalidateIfChanged(long nativeTabContentManager, int tabId, - String url); - private native void nativeUpdateVisibleIds( - long nativeTabContentManager, int[] priority, int primaryTabId); - private native void nativeRemoveTabThumbnail(long nativeTabContentManager, int tabId); - private native void nativeGetEtc1TabThumbnail( - long nativeTabContentManager, int tabId, Callback<Bitmap> callback); - private native void nativeSetCaptureMinRequestTimeForTesting( - long nativeTabContentManager, int timeMs); - private native int nativeGetPendingReadbacksForTesting(long nativeTabContentManager); - private static native void nativeDestroy(long nativeTabContentManager); + @NativeMethods + interface Natives { + // Class Object Methods + long init(TabContentManager caller, int defaultCacheSize, int approximationCacheSize, + int compressionQueueMaxSize, int writeQueueMaxSize, + boolean useApproximationThumbnail, boolean saveJpegThumbnails); + + void attachTab(long nativeTabContentManager, TabContentManager caller, Tab tab, int tabId); + void detachTab(long nativeTabContentManager, TabContentManager caller, Tab tab, int tabId); + boolean hasFullCachedThumbnail( + long nativeTabContentManager, TabContentManager caller, int tabId); + void captureThumbnail(long nativeTabContentManager, TabContentManager caller, Object tab, + float thumbnailScale, boolean writeToCache, Callback<Bitmap> callback); + void cacheTabWithBitmap(long nativeTabContentManager, TabContentManager caller, Object tab, + Object bitmap, float thumbnailScale); + void invalidateIfChanged( + long nativeTabContentManager, TabContentManager caller, int tabId, String url); + void updateVisibleIds(long nativeTabContentManager, TabContentManager caller, + int[] priority, int primaryTabId); + void removeTabThumbnail(long nativeTabContentManager, TabContentManager caller, int tabId); + void getEtc1TabThumbnail(long nativeTabContentManager, TabContentManager caller, int tabId, + Callback<Bitmap> callback); + void setCaptureMinRequestTimeForTesting( + long nativeTabContentManager, TabContentManager caller, int timeMs); + int getPendingReadbacksForTesting(long nativeTabContentManager, TabContentManager caller); + void destroy(long nativeTabContentManager); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/resources/ResourceFactory.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/resources/ResourceFactory.java index 06237d7..14db07bf 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/resources/ResourceFactory.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/resources/ResourceFactory.java
@@ -7,6 +7,7 @@ import android.graphics.Rect; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; /** * Utility class for creating native resources. @@ -15,13 +16,16 @@ public class ResourceFactory { public static long createToolbarContainerResource( Rect toolbarPosition, Rect locationBarPosition, int shadowHeight) { - return nativeCreateToolbarContainerResource(toolbarPosition.left, toolbarPosition.top, - toolbarPosition.right, toolbarPosition.bottom, locationBarPosition.left, - locationBarPosition.top, locationBarPosition.right, locationBarPosition.bottom, - shadowHeight); + return ResourceFactoryJni.get().createToolbarContainerResource(toolbarPosition.left, + toolbarPosition.top, toolbarPosition.right, toolbarPosition.bottom, + locationBarPosition.left, locationBarPosition.top, locationBarPosition.right, + locationBarPosition.bottom, shadowHeight); } - private static native long nativeCreateToolbarContainerResource(int toolbarLeft, int toolbarTop, - int toolbarRight, int toolbarBottom, int locationBarLeft, int locationBarTop, - int locationBarRight, int locationBarBottom, int shadowHeight); + @NativeMethods + interface Natives { + long createToolbarContainerResource(int toolbarLeft, int toolbarTop, int toolbarRight, + int toolbarBottom, int locationBarLeft, int locationBarTop, int locationBarRight, + int locationBarBottom, int shadowHeight); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/ContextualSearchSceneLayer.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/ContextualSearchSceneLayer.java index 62e0c39..6337b8c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/ContextualSearchSceneLayer.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/ContextualSearchSceneLayer.java
@@ -6,6 +6,7 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.compositor.bottombar.contextualsearch.ContextualSearchBarBannerControl; @@ -53,7 +54,8 @@ if (resourceManager == null || !panel.isShowing()) return; if (!mIsInitialized) { - nativeCreateContextualSearchLayer(mNativePtr, resourceManager); + ContextualSearchSceneLayerJni.get().createContextualSearchLayer( + mNativePtr, ContextualSearchSceneLayer.this, resourceManager); mIsInitialized = true; } mImageControl = imageControl; @@ -149,11 +151,12 @@ ? R.drawable.contextual_search_bar_background : INVALID_RESOURCE_ID; - nativeUpdateContextualSearchLayer(mNativePtr, panelShadowResourceId, - searchBarBackgroundColor, searchContextViewId, searchTermViewId, - searchCaptionViewId, R.drawable.modern_toolbar_shadow, - R.drawable.ic_logo_googleg_24dp, quickActionIconResId, R.drawable.breadcrumb_arrow, - dragHandlebarId, openNewTabIconId, ContextualSearchPanel.CLOSE_ICON_DRAWABLE_ID, + ContextualSearchSceneLayerJni.get().updateContextualSearchLayer(mNativePtr, + ContextualSearchSceneLayer.this, panelShadowResourceId, searchBarBackgroundColor, + searchContextViewId, searchTermViewId, searchCaptionViewId, + R.drawable.modern_toolbar_shadow, R.drawable.ic_logo_googleg_24dp, + quickActionIconResId, R.drawable.breadcrumb_arrow, dragHandlebarId, + openNewTabIconId, ContextualSearchPanel.CLOSE_ICON_DRAWABLE_ID, R.drawable.progress_bar_background, R.drawable.progress_bar_foreground, searchPromoViewId, R.drawable.contextual_search_promo_ripple, searchBarBannerTextViewId, mDpToPx, panel.getFullscreenWidth() * mDpToPx, @@ -186,7 +189,8 @@ @Override public void setContentTree(SceneLayer contentTree) { - nativeSetContentTree(mNativePtr, contentTree); + ContextualSearchSceneLayerJni.get().setContentTree( + mNativePtr, ContextualSearchSceneLayer.this, contentTree); } /** @@ -194,13 +198,13 @@ */ public void hideTree() { if (!mIsInitialized) return; - nativeHideTree(mNativePtr); + ContextualSearchSceneLayerJni.get().hideTree(mNativePtr, ContextualSearchSceneLayer.this); } @Override protected void initializeNative() { if (mNativePtr == 0) { - mNativePtr = nativeInit(); + mNativePtr = ContextualSearchSceneLayerJni.get().init(ContextualSearchSceneLayer.this); } assert mNativePtr != 0; } @@ -215,41 +219,44 @@ mNativePtr = 0; } - private native long nativeInit(); - private native void nativeCreateContextualSearchLayer( - long nativeContextualSearchSceneLayer, - ResourceManager resourceManager); - private native void nativeSetContentTree( - long nativeContextualSearchSceneLayer, - SceneLayer contentTree); - private native void nativeHideTree( - long nativeContextualSearchSceneLayer); - private native void nativeUpdateContextualSearchLayer(long nativeContextualSearchSceneLayer, - int searchBarBackgroundResourceId, int searchBarBackgroundColor, - int searchContextResourceId, int searchTermResourceId, int searchCaptionResourceId, - int searchBarShadowResourceId, int searchProviderIconResourceId, - int quickActionIconResourceId, int arrowUpResourceId, int dragHandlebarResourceId, - int openTabIconResourceId, int closeIconResourceId, int progressBarBackgroundResourceId, - int progressBarResourceId, int searchPromoResourceId, int barBannerRippleResourceId, - int barBannerTextResourceId, float dpToPx, float layoutWidth, float layoutHeight, - float basePageBrightness, float basePageYOffset, WebContents webContents, - boolean searchPromoVisible, float searchPromoHeight, float searchPromoOpacity, - int searchPromoBackgroundColor, boolean searchBarBannerVisible, - float searchBarBannerHeight, float searchBarBannerPaddingPx, - float searchBarBannerRippleWidth, float searchBarBannerRippleOpacity, - float searchBarBannerTextOpacity, float searchPanelX, float searchPanelY, - float searchPanelWidth, float searchPanelHeight, float searchBarMarginSide, - float searchBarMarginTop, float searchBarHeight, float searchContextOpacity, - float searchTextLayerMinHeight, float searchTermOpacity, float searchTermCaptionSpacing, - float searchCaptionAnimationPercentage, boolean searchCaptionVisible, - boolean searchBarBorderVisible, float searchBarBorderHeight, - boolean searchBarShadowVisible, boolean quickActionIconVisible, - boolean thumbnailVisible, String thumbnailUrl, float customImageVisibilityPercentage, - int barImageSize, int iconColor, int dragHandlebarColor, float arrowIconOpacity, - float arrowIconRotation, float closeIconOpacity, boolean isProgressBarVisible, - float progressBarHeight, float progressBarOpacity, int progressBarCompletion, - float dividerLineVisibilityPercentage, float dividerLineWidth, float dividerLineHeight, - int dividerLineColor, float dividerLineXOffset, boolean touchHighlightVisible, - float touchHighlightXOffset, float toucHighlightWidth, Profile profile, - int barBackgroundResourceId, int separatorLineColor); + @NativeMethods + interface Natives { + long init(ContextualSearchSceneLayer caller); + void createContextualSearchLayer(long nativeContextualSearchSceneLayer, + ContextualSearchSceneLayer caller, ResourceManager resourceManager); + void setContentTree(long nativeContextualSearchSceneLayer, + ContextualSearchSceneLayer caller, SceneLayer contentTree); + void hideTree(long nativeContextualSearchSceneLayer, ContextualSearchSceneLayer caller); + void updateContextualSearchLayer(long nativeContextualSearchSceneLayer, + ContextualSearchSceneLayer caller, int searchBarBackgroundResourceId, + int searchBarBackgroundColor, int searchContextResourceId, int searchTermResourceId, + int searchCaptionResourceId, int searchBarShadowResourceId, + int searchProviderIconResourceId, int quickActionIconResourceId, + int arrowUpResourceId, int dragHandlebarResourceId, int openTabIconResourceId, + int closeIconResourceId, int progressBarBackgroundResourceId, + int progressBarResourceId, int searchPromoResourceId, int barBannerRippleResourceId, + int barBannerTextResourceId, float dpToPx, float layoutWidth, float layoutHeight, + float basePageBrightness, float basePageYOffset, WebContents webContents, + boolean searchPromoVisible, float searchPromoHeight, float searchPromoOpacity, + int searchPromoBackgroundColor, boolean searchBarBannerVisible, + float searchBarBannerHeight, float searchBarBannerPaddingPx, + float searchBarBannerRippleWidth, float searchBarBannerRippleOpacity, + float searchBarBannerTextOpacity, float searchPanelX, float searchPanelY, + float searchPanelWidth, float searchPanelHeight, float searchBarMarginSide, + float searchBarMarginTop, float searchBarHeight, float searchContextOpacity, + float searchTextLayerMinHeight, float searchTermOpacity, + float searchTermCaptionSpacing, float searchCaptionAnimationPercentage, + boolean searchCaptionVisible, boolean searchBarBorderVisible, + float searchBarBorderHeight, boolean searchBarShadowVisible, + boolean quickActionIconVisible, boolean thumbnailVisible, String thumbnailUrl, + float customImageVisibilityPercentage, int barImageSize, int iconColor, + int dragHandlebarColor, float arrowIconOpacity, float arrowIconRotation, + float closeIconOpacity, boolean isProgressBarVisible, float progressBarHeight, + float progressBarOpacity, int progressBarCompletion, + float dividerLineVisibilityPercentage, float dividerLineWidth, + float dividerLineHeight, int dividerLineColor, float dividerLineXOffset, + boolean touchHighlightVisible, float touchHighlightXOffset, + float toucHighlightWidth, Profile profile, int barBackgroundResourceId, + int separatorLineColor); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/EphemeralTabSceneLayer.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/EphemeralTabSceneLayer.java index 5fe050aa..f3dae197 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/EphemeralTabSceneLayer.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/EphemeralTabSceneLayer.java
@@ -8,6 +8,7 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.compositor.bottombar.ephemeraltab.EphemeralTabBarControl; @@ -34,7 +35,7 @@ private final int mFaviconSizePx; /** Interface to get notified that favicon is available. */ - private interface FaviconCallback { + interface FaviconCallback { /** * Called when a favicon becomes available. Used to start the animation fading * out the default icon and fading in the favicon. @@ -66,8 +67,9 @@ // Don't try to update the layer if not initialized or showing. if (resourceManager == null || !panel.isShowing()) return; if (!mIsInitialized) { - nativeCreateEphemeralTabLayer( - mNativePtr, resourceManager, () -> panel.startFaviconAnimation(true)); + EphemeralTabSceneLayerJni.get().createEphemeralTabLayer(mNativePtr, + EphemeralTabSceneLayer.this, resourceManager, + () -> panel.startFaviconAnimation(true)); int openInTabIconId = (ChromeFeatureList.isEnabled(ChromeFeatureList.OVERLAY_NEW_LAYOUT) && panel.canPromoteToNewTab()) ? R.drawable.open_in_new_tab @@ -81,9 +83,10 @@ int panelShadowResourceId = panel.getPanelShadowVisible() ? R.drawable.contextual_search_bar_background : INVALID_RESOURCE_ID; - nativeSetResourceIds(mNativePtr, title.getViewId(), panelShadowResourceId, - roundedBarTopId, R.drawable.modern_toolbar_shadow, R.drawable.infobar_chrome, - dragHandlebarId, openInTabIconId, R.drawable.btn_close); + EphemeralTabSceneLayerJni.get().setResourceIds(mNativePtr, EphemeralTabSceneLayer.this, + title.getViewId(), panelShadowResourceId, roundedBarTopId, + R.drawable.modern_toolbar_shadow, R.drawable.infobar_chrome, dragHandlebarId, + openInTabIconId, R.drawable.btn_close); mIsInitialized = true; } @@ -103,23 +106,25 @@ int separatorLineColor = panel.getSeparatorLineColor(); WebContents panelWebContents = panel.getWebContents(); - nativeUpdate(mNativePtr, titleViewId, captionViewId, captionAnimationPercentage, - bar.getTextLayerMinHeight(), bar.getTitleCaptionSpacing(), captionVisible, - R.drawable.progress_bar_background, R.drawable.progress_bar_foreground, mDpToPx, - panel.getBasePageBrightness(), panel.getBasePageY() * mDpToPx, panelWebContents, - panel.getOffsetX() * mDpToPx, panel.getOffsetY() * mDpToPx, - panel.getWidth() * mDpToPx, panel.getHeight() * mDpToPx, - panel.getBarBackgroundColor(), panel.getBarMarginSide() * mDpToPx, - panel.getBarMarginTop() * mDpToPx, panel.getBarHeight() * mDpToPx, - panel.isBarBorderVisible(), panel.getBarBorderHeight() * mDpToPx, - panel.getBarShadowVisible(), panel.getIconColor(), panel.getDragHandlebarColor(), - panel.getFaviconOpacity(), isProgressBarVisible, progressBarHeight * mDpToPx, - progressBarOpacity, progressBarCompletion, separatorLineColor); + EphemeralTabSceneLayerJni.get().update(mNativePtr, EphemeralTabSceneLayer.this, titleViewId, + captionViewId, captionAnimationPercentage, bar.getTextLayerMinHeight(), + bar.getTitleCaptionSpacing(), captionVisible, R.drawable.progress_bar_background, + R.drawable.progress_bar_foreground, mDpToPx, panel.getBasePageBrightness(), + panel.getBasePageY() * mDpToPx, panelWebContents, panel.getOffsetX() * mDpToPx, + panel.getOffsetY() * mDpToPx, panel.getWidth() * mDpToPx, + panel.getHeight() * mDpToPx, panel.getBarBackgroundColor(), + panel.getBarMarginSide() * mDpToPx, panel.getBarMarginTop() * mDpToPx, + panel.getBarHeight() * mDpToPx, panel.isBarBorderVisible(), + panel.getBarBorderHeight() * mDpToPx, panel.getBarShadowVisible(), + panel.getIconColor(), panel.getDragHandlebarColor(), panel.getFaviconOpacity(), + isProgressBarVisible, progressBarHeight * mDpToPx, progressBarOpacity, + progressBarCompletion, separatorLineColor); } @Override public void setContentTree(SceneLayer contentTree) { - nativeSetContentTree(mNativePtr, contentTree); + EphemeralTabSceneLayerJni.get().setContentTree( + mNativePtr, EphemeralTabSceneLayer.this, contentTree); } /** @@ -127,12 +132,13 @@ */ public void hideTree() { if (!mIsInitialized) return; - nativeHideTree(mNativePtr); + EphemeralTabSceneLayerJni.get().hideTree(mNativePtr, EphemeralTabSceneLayer.this); } @Override protected void initializeNative() { - if (mNativePtr == 0) mNativePtr = nativeInit(); + if (mNativePtr == 0) + mNativePtr = EphemeralTabSceneLayerJni.get().init(EphemeralTabSceneLayer.this); assert mNativePtr != 0; } @@ -146,24 +152,29 @@ mNativePtr = 0; } - private native long nativeInit(); - private native void nativeCreateEphemeralTabLayer(long nativeEphemeralTabSceneLayer, - ResourceManager resourceManager, FaviconCallback callback); - private native void nativeSetContentTree( - long nativeEphemeralTabSceneLayer, SceneLayer contentTree); - private native void nativeHideTree(long nativeEphemeralTabSceneLayer); - private native void nativeSetResourceIds(long nativeEphemeralTabSceneLayer, - int barTextResourceId, int barBackgroundResourceId, int roundedBarTopResourceId, - int barShadowResourceId, int panelIconResourceId, int dragHandlebarResourceId, - int openTabIconResourceId, int closeIconResourceId); - private native void nativeUpdate(long nativeEphemeralTabSceneLayer, int titleViewId, - int captionViewId, float captionAnimationPercentage, float textLayerMinHeight, - float titleCaptionSpacing, boolean captionVisible, int progressBarBackgroundResourceId, - int progressBarResourceId, float dpToPx, float basePageBrightness, - float basePageYOffset, WebContents webContents, float panelX, float panelY, - float panelWidth, float panelHeight, int barBackgroundColor, float barMarginSide, - float barMarginTop, float barHeight, boolean barBorderVisible, float barBorderHeight, - boolean barShadowVisible, int iconColor, int dragHandlebarColor, float faviconOpacity, - boolean isProgressBarVisible, float progressBarHeight, float progressBarOpacity, - int progressBarCompletion, int separatorLineColor); + @NativeMethods + interface Natives { + long init(EphemeralTabSceneLayer caller); + void createEphemeralTabLayer(long nativeEphemeralTabSceneLayer, + EphemeralTabSceneLayer caller, ResourceManager resourceManager, + FaviconCallback callback); + void setContentTree(long nativeEphemeralTabSceneLayer, EphemeralTabSceneLayer caller, + SceneLayer contentTree); + void hideTree(long nativeEphemeralTabSceneLayer, EphemeralTabSceneLayer caller); + void setResourceIds(long nativeEphemeralTabSceneLayer, EphemeralTabSceneLayer caller, + int barTextResourceId, int barBackgroundResourceId, int roundedBarTopResourceId, + int barShadowResourceId, int panelIconResourceId, int dragHandlebarResourceId, + int openTabIconResourceId, int closeIconResourceId); + void update(long nativeEphemeralTabSceneLayer, EphemeralTabSceneLayer caller, + int titleViewId, int captionViewId, float captionAnimationPercentage, + float textLayerMinHeight, float titleCaptionSpacing, boolean captionVisible, + int progressBarBackgroundResourceId, int progressBarResourceId, float dpToPx, + float basePageBrightness, float basePageYOffset, WebContents webContents, + float panelX, float panelY, float panelWidth, float panelHeight, + int barBackgroundColor, float barMarginSide, float barMarginTop, float barHeight, + boolean barBorderVisible, float barBorderHeight, boolean barShadowVisible, + int iconColor, int dragHandlebarColor, float faviconOpacity, + boolean isProgressBarVisible, float progressBarHeight, float progressBarOpacity, + int progressBarCompletion, int separatorLineColor); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/SceneLayer.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/SceneLayer.java index a65cf167..c019d63fc 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/SceneLayer.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/SceneLayer.java
@@ -6,6 +6,7 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; /** * Java representation of a scene layer. @@ -28,7 +29,7 @@ */ protected void initializeNative() { if (mNativePtr == 0) { - mNativePtr = nativeInit(); + mNativePtr = SceneLayerJni.get().init(SceneLayer.this); } assert mNativePtr != 0; } @@ -38,7 +39,7 @@ */ public void destroy() { assert mNativePtr != 0; - nativeDestroy(mNativePtr); + SceneLayerJni.get().destroy(mNativePtr, SceneLayer.this); assert mNativePtr == 0; } @@ -53,6 +54,9 @@ return mNativePtr; } - private native long nativeInit(); - private native void nativeDestroy(long nativeSceneLayer); + @NativeMethods + interface Natives { + long init(SceneLayer caller); + void destroy(long nativeSceneLayer, SceneLayer caller); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/ScrollingBottomViewSceneLayer.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/ScrollingBottomViewSceneLayer.java index ec5cc4e2..fd9141e1 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/ScrollingBottomViewSceneLayer.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/ScrollingBottomViewSceneLayer.java
@@ -8,6 +8,7 @@ import android.view.View; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.compositor.LayerTitleCache; import org.chromium.chrome.browser.compositor.layouts.components.VirtualView; import org.chromium.chrome.browser.compositor.layouts.eventfilter.EventFilter; @@ -93,14 +94,16 @@ @Override protected void initializeNative() { if (mNativePtr == 0) { - mNativePtr = nativeInit(); + mNativePtr = + ScrollingBottomViewSceneLayerJni.get().init(ScrollingBottomViewSceneLayer.this); } assert mNativePtr != 0; } @Override public void setContentTree(SceneLayer contentTree) { - nativeSetContentTree(mNativePtr, contentTree); + ScrollingBottomViewSceneLayerJni.get().setContentTree( + mNativePtr, ScrollingBottomViewSceneLayer.this, contentTree); } @Override @@ -109,7 +112,8 @@ // The composited shadow should be visible if the Android toolbar's isn't. boolean isShadowVisible = mBottomView.getVisibility() != View.VISIBLE; - nativeUpdateScrollingBottomViewLayer(mNativePtr, resourceManager, mResourceId, + ScrollingBottomViewSceneLayerJni.get().updateScrollingBottomViewLayer(mNativePtr, + ScrollingBottomViewSceneLayer.this, resourceManager, mResourceId, mTopShadowHeightPx, mCurrentXOffsetPx, viewport.height() + mCurrentYOffsetPx, isShadowVisible); @@ -169,11 +173,14 @@ @Override public void tabCreated(long time, boolean incognito, int id, int prevId, boolean selected) {} - private native long nativeInit(); - private native void nativeSetContentTree( - long nativeScrollingBottomViewSceneLayer, SceneLayer contentTree); - private native void nativeUpdateScrollingBottomViewLayer( - long nativeScrollingBottomViewSceneLayer, ResourceManager resourceManager, - int viewResourceId, int shadowHeightPx, float xOffset, float yOffset, - boolean showShadow); + @NativeMethods + interface Natives { + long init(ScrollingBottomViewSceneLayer caller); + void setContentTree(long nativeScrollingBottomViewSceneLayer, + ScrollingBottomViewSceneLayer caller, SceneLayer contentTree); + void updateScrollingBottomViewLayer(long nativeScrollingBottomViewSceneLayer, + ScrollingBottomViewSceneLayer caller, ResourceManager resourceManager, + int viewResourceId, int shadowHeightPx, float xOffset, float yOffset, + boolean showShadow); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/StaticTabSceneLayer.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/StaticTabSceneLayer.java index 9f86463..1515c3a3 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/StaticTabSceneLayer.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/StaticTabSceneLayer.java
@@ -5,6 +5,7 @@ package org.chromium.chrome.browser.compositor.scene_layer; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.compositor.LayerTitleCache; import org.chromium.chrome.browser.compositor.layouts.components.LayoutTab; import org.chromium.chrome.browser.compositor.layouts.content.TabContentManager; @@ -41,16 +42,16 @@ float x = layoutTab.getRenderX() * dpToPx; float y = contentOffset + layoutTab.getRenderY() * dpToPx; - nativeUpdateTabLayer(mNativePtr, tabContentManager, layoutTab.getId(), - layoutTab.canUseLiveTexture(), layoutTab.getBackgroundColor(), x, y, - layoutTab.getStaticToViewBlend(), layoutTab.getSaturation(), - layoutTab.getBrightness()); + StaticTabSceneLayerJni.get().updateTabLayer(mNativePtr, StaticTabSceneLayer.this, + tabContentManager, layoutTab.getId(), layoutTab.canUseLiveTexture(), + layoutTab.getBackgroundColor(), x, y, layoutTab.getStaticToViewBlend(), + layoutTab.getSaturation(), layoutTab.getBrightness()); } @Override protected void initializeNative() { if (mNativePtr == 0) { - mNativePtr = nativeInit(); + mNativePtr = StaticTabSceneLayerJni.get().init(StaticTabSceneLayer.this); } assert mNativePtr != 0; } @@ -61,9 +62,12 @@ mNativePtr = 0; } - private native long nativeInit(); - private native void nativeUpdateTabLayer(long nativeStaticTabSceneLayer, - TabContentManager tabContentManager, int id, boolean canUseLiveLayer, - int backgroundColor, float x, float y, float staticToViewBlend, float saturation, - float brightness); + @NativeMethods + interface Natives { + long init(StaticTabSceneLayer caller); + void updateTabLayer(long nativeStaticTabSceneLayer, StaticTabSceneLayer caller, + TabContentManager tabContentManager, int id, boolean canUseLiveLayer, + int backgroundColor, float x, float y, float staticToViewBlend, float saturation, + float brightness); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/TabListSceneLayer.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/TabListSceneLayer.java index 9e8b2bb..62fe973 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/TabListSceneLayer.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/TabListSceneLayer.java
@@ -11,6 +11,7 @@ import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.compositor.LayerTitleCache; @@ -66,13 +67,15 @@ LayoutTab[] tabs = layout.getLayoutTabsToRender(); int tabsCount = tabs != null ? tabs.length : 0; - nativeBeginBuildingFrame(mNativePtr); + TabListSceneLayerJni.get().beginBuildingFrame(mNativePtr, TabListSceneLayer.this); - nativeUpdateLayer(mNativePtr, tabListBgColor, viewport.left, viewport.top, viewport.width(), - viewport.height(), layerTitleCache, tabContentManager, resourceManager); + TabListSceneLayerJni.get().updateLayer(mNativePtr, TabListSceneLayer.this, tabListBgColor, + viewport.left, viewport.top, viewport.width(), viewport.height(), layerTitleCache, + tabContentManager, resourceManager); if (backgroundResourceId != INVALID_RESOURCE_ID) { - nativePutBackgroundLayer(mNativePtr, backgroundResourceId, backgroundAlpha); + TabListSceneLayerJni.get().putBackgroundLayer( + mNativePtr, TabListSceneLayer.this, backgroundResourceId, backgroundAlpha); } boolean isHTSEnabled = @@ -107,9 +110,9 @@ int[] relatedTabIds = getRelatedTabIds(t.getId()); // TODO(dtrainor, clholgat): remove "* dpToPx" once the native part fully supports dp. - nativePutTabLayer(mNativePtr, t.getId(), relatedTabIds, mUseAdditionalIds, - R.id.control_container, R.drawable.btn_delete_24dp, - R.drawable.tabswitcher_border_frame_shadow, + TabListSceneLayerJni.get().putTabLayer(mNativePtr, TabListSceneLayer.this, t.getId(), + relatedTabIds, mUseAdditionalIds, R.id.control_container, + R.drawable.btn_delete_24dp, R.drawable.tabswitcher_border_frame_shadow, R.drawable.tabswitcher_border_frame_decoration, R.drawable.logo_card_back, R.drawable.tabswitcher_border_frame, R.drawable.tabswitcher_border_frame_inner_shadow, t.canUseLiveTexture(), @@ -133,7 +136,7 @@ textBoxAlpha, t.getToolbarAlpha(), t.getToolbarYOffset() * dpToPx, t.getSideBorderScale(), t.insetBorderVertical()); } - nativeFinishBuildingFrame(mNativePtr); + TabListSceneLayerJni.get().finishBuildingFrame(mNativePtr, TabListSceneLayer.this); } /** @@ -156,7 +159,7 @@ @Override protected void initializeNative() { if (mNativePtr == 0) { - mNativePtr = nativeInit(); + mNativePtr = TabListSceneLayerJni.get().init(TabListSceneLayer.this); } assert mNativePtr != 0; } @@ -178,35 +181,35 @@ return mAdditionalIds; } - private native long nativeInit(); + @NativeMethods + interface Natives { + long init(TabListSceneLayer caller); + void beginBuildingFrame(long nativeTabListSceneLayer, TabListSceneLayer caller); + void finishBuildingFrame(long nativeTabListSceneLayer, TabListSceneLayer caller); + void updateLayer(long nativeTabListSceneLayer, TabListSceneLayer caller, + int backgroundColor, float viewportX, float viewportY, float viewportWidth, + float viewportHeight, LayerTitleCache layerTitleCache, + TabContentManager tabContentManager, ResourceManager resourceManager); + // TODO(meiliang): Need to provide a resource that indicates the selected tab on the layer. + void putTabLayer(long nativeTabListSceneLayer, TabListSceneLayer caller, int selectedId, + int[] ids, boolean useAdditionalIds, int toolbarResourceId, + int closeButtonResourceId, int shadowResourceId, int contourResourceId, + int backLogoResourceId, int borderResourceId, int borderInnerShadowResourceId, + boolean canUseLiveLayer, int tabBackgroundColor, int backLogoColor, + boolean incognito, boolean isPortrait, float x, float y, float width, float height, + float contentWidth, float contentHeight, float visibleContentHeight, float shadowX, + float shadowY, float shadowWidth, float shadowHeight, float pivotX, float pivotY, + float rotationX, float rotationY, float alpha, float borderAlpha, + float borderInnerShadowAlpha, float contourAlpha, float shadowAlpha, + float closeAlpha, float closeBtnWidth, float closeBtnAssetSize, + float staticToViewBlend, float borderScale, float saturation, float brightness, + boolean showToolbar, int defaultThemeColor, int toolbarBackgroundColor, + int closeButtonColor, boolean anonymizeToolbar, boolean showTabTitle, + int toolbarTextBoxResource, int toolbarTextBoxBackgroundColor, + float toolbarTextBoxAlpha, float toolbarAlpha, float toolbarYOffset, + float sideBorderScale, boolean insetVerticalBorder); - private native void nativeBeginBuildingFrame(long nativeTabListSceneLayer); - - private native void nativeFinishBuildingFrame(long nativeTabListSceneLayer); - - private native void nativeUpdateLayer(long nativeTabListSceneLayer, int backgroundColor, - float viewportX, float viewportY, float viewportWidth, float viewportHeight, - LayerTitleCache layerTitleCache, TabContentManager tabContentManager, - ResourceManager resourceManager); - - // TODO(meiliang): Need to provide a resource that indicates the selected tab on the layer. - private native void nativePutTabLayer(long nativeTabListSceneLayer, int selectedId, int[] ids, - boolean useAdditionalIds, int toolbarResourceId, int closeButtonResourceId, - int shadowResourceId, int contourResourceId, int backLogoResourceId, - int borderResourceId, int borderInnerShadowResourceId, boolean canUseLiveLayer, - int tabBackgroundColor, int backLogoColor, boolean incognito, boolean isPortrait, - float x, float y, float width, float height, float contentWidth, float contentHeight, - float visibleContentHeight, float shadowX, float shadowY, float shadowWidth, - float shadowHeight, float pivotX, float pivotY, float rotationX, float rotationY, - float alpha, float borderAlpha, float borderInnerShadowAlpha, float contourAlpha, - float shadowAlpha, float closeAlpha, float closeBtnWidth, float closeBtnAssetSize, - float staticToViewBlend, float borderScale, float saturation, float brightness, - boolean showToolbar, int defaultThemeColor, int toolbarBackgroundColor, - int closeButtonColor, boolean anonymizeToolbar, boolean showTabTitle, - int toolbarTextBoxResource, int toolbarTextBoxBackgroundColor, - float toolbarTextBoxAlpha, float toolbarAlpha, float toolbarYOffset, - float sideBorderScale, boolean insetVerticalBorder); - - private native void nativePutBackgroundLayer( - long nativeTabListSceneLayer, int resourceId, float alpha); + void putBackgroundLayer(long nativeTabListSceneLayer, TabListSceneLayer caller, + int resourceId, float alpha); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/TabStripSceneLayer.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/TabStripSceneLayer.java index 635007c..b9b154b3 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/TabStripSceneLayer.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/TabStripSceneLayer.java
@@ -8,6 +8,7 @@ import android.os.Build; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.R; import org.chromium.chrome.browser.compositor.LayerTitleCache; import org.chromium.chrome.browser.compositor.layouts.components.CompositorButton; @@ -36,14 +37,15 @@ @Override protected void initializeNative() { if (mNativePtr == 0) { - mNativePtr = nativeInit(); + mNativePtr = TabStripSceneLayerJni.get().init(TabStripSceneLayer.this); } assert mNativePtr != 0; } @Override public void setContentTree(SceneLayer contentTree) { - nativeSetContentTree(mNativePtr, contentTree); + TabStripSceneLayerJni.get().setContentTree( + mNativePtr, TabStripSceneLayer.this, contentTree); } /** @@ -65,14 +67,15 @@ final boolean visible = yOffset > -layoutHelper.getHeight(); // This will hide the tab strips if necessary. - nativeBeginBuildingFrame(mNativePtr, visible); + TabStripSceneLayerJni.get().beginBuildingFrame( + mNativePtr, TabStripSceneLayer.this, visible); // When strip tabs are completely off screen, we don't need to update it. if (visible) { pushButtonsAndBackground(layoutHelper, resourceManager, yOffset); pushStripTabs(layoutHelper, layerTitleCache, resourceManager, stripLayoutTabsToRender, selectedTabId); } - nativeFinishBuildingFrame(mNativePtr); + TabStripSceneLayerJni.get().finishBuildingFrame(mNativePtr, TabStripSceneLayer.this); } private boolean shouldReaddBackground(int orientation) { @@ -93,35 +96,36 @@ ResourceManager resourceManager, float yOffset) { final float width = layoutHelper.getWidth() * mDpToPx; final float height = layoutHelper.getHeight() * mDpToPx; - nativeUpdateTabStripLayer(mNativePtr, width, height, yOffset * mDpToPx, - layoutHelper.getBackgroundTabBrightness(), layoutHelper.getBrightness(), - shouldReaddBackground(layoutHelper.getOrientation())); + TabStripSceneLayerJni.get().updateTabStripLayer(mNativePtr, TabStripSceneLayer.this, width, + height, yOffset * mDpToPx, layoutHelper.getBackgroundTabBrightness(), + layoutHelper.getBrightness(), shouldReaddBackground(layoutHelper.getOrientation())); CompositorButton newTabButton = layoutHelper.getNewTabButton(); CompositorButton modelSelectorButton = layoutHelper.getModelSelectorButton(); boolean newTabButtonVisible = newTabButton.isVisible(); boolean modelSelectorButtonVisible = modelSelectorButton.isVisible(); - nativeUpdateNewTabButton(mNativePtr, newTabButton.getResourceId(), - newTabButton.getX() * mDpToPx, newTabButton.getY() * mDpToPx, - newTabButton.getWidth() * mDpToPx, newTabButton.getHeight() * mDpToPx, - newTabButtonVisible, resourceManager); + TabStripSceneLayerJni.get().updateNewTabButton(mNativePtr, TabStripSceneLayer.this, + newTabButton.getResourceId(), newTabButton.getX() * mDpToPx, + newTabButton.getY() * mDpToPx, newTabButton.getWidth() * mDpToPx, + newTabButton.getHeight() * mDpToPx, newTabButtonVisible, resourceManager); - nativeUpdateModelSelectorButton(mNativePtr, modelSelectorButton.getResourceId(), - modelSelectorButton.getX() * mDpToPx, modelSelectorButton.getY() * mDpToPx, - modelSelectorButton.getWidth() * mDpToPx, modelSelectorButton.getHeight() * mDpToPx, - modelSelectorButton.isIncognito(), modelSelectorButtonVisible, resourceManager); + TabStripSceneLayerJni.get().updateModelSelectorButton(mNativePtr, TabStripSceneLayer.this, + modelSelectorButton.getResourceId(), modelSelectorButton.getX() * mDpToPx, + modelSelectorButton.getY() * mDpToPx, modelSelectorButton.getWidth() * mDpToPx, + modelSelectorButton.getHeight() * mDpToPx, modelSelectorButton.isIncognito(), + modelSelectorButtonVisible, resourceManager); int leftFadeDrawable = modelSelectorButtonVisible && LocalizationUtils.isLayoutRtl() ? R.drawable.tab_strip_fade_for_model_selector : R.drawable.tab_strip_fade; int rightFadeDrawable = modelSelectorButtonVisible && !LocalizationUtils.isLayoutRtl() ? R.drawable.tab_strip_fade_for_model_selector : R.drawable.tab_strip_fade; - nativeUpdateTabStripLeftFade(mNativePtr, leftFadeDrawable, - layoutHelper.getLeftFadeOpacity(), resourceManager); + TabStripSceneLayerJni.get().updateTabStripLeftFade(mNativePtr, TabStripSceneLayer.this, + leftFadeDrawable, layoutHelper.getLeftFadeOpacity(), resourceManager); - nativeUpdateTabStripRightFade(mNativePtr, rightFadeDrawable, - layoutHelper.getRightFadeOpacity(), resourceManager); + TabStripSceneLayerJni.get().updateTabStripRightFade(mNativePtr, TabStripSceneLayer.this, + rightFadeDrawable, layoutHelper.getRightFadeOpacity(), resourceManager); } private void pushStripTabs(StripLayoutHelperManager layoutHelper, @@ -132,8 +136,9 @@ for (int i = 0; i < tabsCount; i++) { final StripLayoutTab st = stripTabs[i]; boolean isSelected = st.getId() == selectedTabId; - nativePutStripTabLayer(mNativePtr, st.getId(), st.getCloseButton().getResourceId(), - st.getResourceId(), st.getOutlineResourceId(), st.getCloseButton().getTint(), + TabStripSceneLayerJni.get().putStripTabLayer(mNativePtr, TabStripSceneLayer.this, + st.getId(), st.getCloseButton().getResourceId(), st.getResourceId(), + st.getOutlineResourceId(), st.getCloseButton().getTint(), st.getTint(isSelected), st.getOutlineTint(isSelected), isSelected, st.getClosePressed(), layoutHelper.getWidth() * mDpToPx, st.getDrawX() * mDpToPx, st.getDrawY() * mDpToPx, st.getWidth() * mDpToPx, @@ -149,27 +154,33 @@ mNativePtr = 0; } - private native long nativeInit(); - private native void nativeBeginBuildingFrame(long nativeTabStripSceneLayer, boolean visible); - private native void nativeFinishBuildingFrame(long nativeTabStripSceneLayer); - private native void nativeUpdateTabStripLayer(long nativeTabStripSceneLayer, float width, - float height, float yOffset, float backgroundTabBrightness, float brightness, - boolean shouldReaddBackground); - private native void nativeUpdateNewTabButton(long nativeTabStripSceneLayer, int resourceId, - float x, float y, float width, float height, boolean visible, - ResourceManager resourceManager); - private native void nativeUpdateModelSelectorButton(long nativeTabStripSceneLayer, - int resourceId, float x, float y, float width, float height, boolean incognito, - boolean visible, ResourceManager resourceManager); - private native void nativeUpdateTabStripLeftFade(long nativeTabStripSceneLayer, - int resourceId, float opacity, ResourceManager resourceManager); - private native void nativeUpdateTabStripRightFade(long nativeTabStripSceneLayer, - int resourceId, float opacity, ResourceManager resourceManager); - private native void nativePutStripTabLayer(long nativeTabStripSceneLayer, int id, - int closeResourceId, int handleResourceId, int handleOutlineResourceId, int closeTint, - int handleTint, int handleOutlineTint, boolean foreground, boolean closePressed, - float toolbarWidth, float x, float y, float width, float height, float contentOffsetX, - float closeButtonAlpha, boolean isLoading, float spinnerRotation, - LayerTitleCache layerTitleCache, ResourceManager resourceManager); - private native void nativeSetContentTree(long nativeTabStripSceneLayer, SceneLayer contentTree); + @NativeMethods + interface Natives { + long init(TabStripSceneLayer caller); + void beginBuildingFrame( + long nativeTabStripSceneLayer, TabStripSceneLayer caller, boolean visible); + void finishBuildingFrame(long nativeTabStripSceneLayer, TabStripSceneLayer caller); + void updateTabStripLayer(long nativeTabStripSceneLayer, TabStripSceneLayer caller, + float width, float height, float yOffset, float backgroundTabBrightness, + float brightness, boolean shouldReaddBackground); + void updateNewTabButton(long nativeTabStripSceneLayer, TabStripSceneLayer caller, + int resourceId, float x, float y, float width, float height, boolean visible, + ResourceManager resourceManager); + void updateModelSelectorButton(long nativeTabStripSceneLayer, TabStripSceneLayer caller, + int resourceId, float x, float y, float width, float height, boolean incognito, + boolean visible, ResourceManager resourceManager); + void updateTabStripLeftFade(long nativeTabStripSceneLayer, TabStripSceneLayer caller, + int resourceId, float opacity, ResourceManager resourceManager); + void updateTabStripRightFade(long nativeTabStripSceneLayer, TabStripSceneLayer caller, + int resourceId, float opacity, ResourceManager resourceManager); + void putStripTabLayer(long nativeTabStripSceneLayer, TabStripSceneLayer caller, int id, + int closeResourceId, int handleResourceId, int handleOutlineResourceId, + int closeTint, int handleTint, int handleOutlineTint, boolean foreground, + boolean closePressed, float toolbarWidth, float x, float y, float width, + float height, float contentOffsetX, float closeButtonAlpha, boolean isLoading, + float spinnerRotation, LayerTitleCache layerTitleCache, + ResourceManager resourceManager); + void setContentTree( + long nativeTabStripSceneLayer, TabStripSceneLayer caller, SceneLayer contentTree); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/ToolbarSceneLayer.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/ToolbarSceneLayer.java index 0b4d420..f89c53d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/ToolbarSceneLayer.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/ToolbarSceneLayer.java
@@ -8,6 +8,7 @@ import android.graphics.RectF; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.R; import org.chromium.chrome.browser.compositor.LayerTitleCache; import org.chromium.chrome.browser.compositor.layouts.Layout.ViewportMode; @@ -110,13 +111,14 @@ isLocationBarShownInNtp, browserControlsBackgroundColor, isIncognito); int textBoxResourceId = R.drawable.modern_location_bar; - nativeUpdateToolbarLayer(mNativePtr, resourceManager, R.id.control_container, - browserControlsBackgroundColor, textBoxResourceId, browserControlsUrlBarAlpha, - textBoxColor, fullscreenManager.getTopControlOffset(), windowHeight, useTexture, - showShadow); + ToolbarSceneLayerJni.get().updateToolbarLayer(mNativePtr, ToolbarSceneLayer.this, + resourceManager, R.id.control_container, browserControlsBackgroundColor, + textBoxResourceId, browserControlsUrlBarAlpha, textBoxColor, + fullscreenManager.getTopControlOffset(), windowHeight, useTexture, showShadow); if (mProgressBarDrawingInfo == null) return; - nativeUpdateProgressBar(mNativePtr, mProgressBarDrawingInfo.progressBarRect.left, + ToolbarSceneLayerJni.get().updateProgressBar(mNativePtr, ToolbarSceneLayer.this, + mProgressBarDrawingInfo.progressBarRect.left, mProgressBarDrawingInfo.progressBarRect.top, mProgressBarDrawingInfo.progressBarRect.width(), mProgressBarDrawingInfo.progressBarRect.height(), @@ -130,13 +132,13 @@ @Override public void setContentTree(SceneLayer contentTree) { - nativeSetContentTree(mNativePtr, contentTree); + ToolbarSceneLayerJni.get().setContentTree(mNativePtr, ToolbarSceneLayer.this, contentTree); } @Override protected void initializeNative() { if (mNativePtr == 0) { - mNativePtr = nativeInit(); + mNativePtr = ToolbarSceneLayerJni.get().init(ToolbarSceneLayer.this); } assert mNativePtr != 0; } @@ -224,24 +226,19 @@ @Override public void tabCreated(long time, boolean incognito, int id, int prevId, boolean selected) {} - private native long nativeInit(); - private native void nativeSetContentTree( - long nativeToolbarSceneLayer, - SceneLayer contentTree); - private native void nativeUpdateToolbarLayer(long nativeToolbarSceneLayer, - ResourceManager resourceManager, int resourceId, int toolbarBackgroundColor, - int urlBarResourceId, float urlBarAlpha, int urlBarColor, float topOffset, - float viewHeight, boolean visible, boolean showShadow); - private native void nativeUpdateProgressBar( - long nativeToolbarSceneLayer, - int progressBarX, - int progressBarY, - int progressBarWidth, - int progressBarHeight, - int progressBarColor, - int progressBarBackgroundX, - int progressBarBackgroundY, - int progressBarBackgroundWidth, - int progressBarBackgroundHeight, - int progressBarBackgroundColor); + @NativeMethods + interface Natives { + long init(ToolbarSceneLayer caller); + void setContentTree( + long nativeToolbarSceneLayer, ToolbarSceneLayer caller, SceneLayer contentTree); + void updateToolbarLayer(long nativeToolbarSceneLayer, ToolbarSceneLayer caller, + ResourceManager resourceManager, int resourceId, int toolbarBackgroundColor, + int urlBarResourceId, float urlBarAlpha, int urlBarColor, float topOffset, + float viewHeight, boolean visible, boolean showShadow); + void updateProgressBar(long nativeToolbarSceneLayer, ToolbarSceneLayer caller, + int progressBarX, int progressBarY, int progressBarWidth, int progressBarHeight, + int progressBarColor, int progressBarBackgroundX, int progressBarBackgroundY, + int progressBarBackgroundWidth, int progressBarBackgroundHeight, + int progressBarBackgroundColor); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/consent_auditor/ConsentAuditorBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/consent_auditor/ConsentAuditorBridge.java index e7e23f4..13d6336 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/consent_auditor/ConsentAuditorBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/consent_auditor/ConsentAuditorBridge.java
@@ -7,6 +7,7 @@ import android.support.annotation.StringRes; import org.chromium.base.ThreadUtils; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.profiles.Profile; import java.util.List; @@ -30,8 +31,9 @@ for (int i = 0; i < consentDescription.size(); ++i) { consentDescriptionArray[i] = consentDescription.get(i); } - nativeRecordConsent(Profile.getLastUsedProfile(), accountId, feature, - consentDescriptionArray, consentConfirmation); + ConsentAuditorBridgeJni.get().recordConsent(ConsentAuditorBridge.this, + Profile.getLastUsedProfile(), accountId, feature, consentDescriptionArray, + consentConfirmation); } private ConsentAuditorBridge() {} @@ -45,6 +47,9 @@ return sInstance; } - private native void nativeRecordConsent(Profile profile, String accountId, int feature, - int[] consentDescription, int consentConfirmation); + @NativeMethods + interface Natives { + void recordConsent(ConsentAuditorBridge caller, Profile profile, String accountId, + int feature, int[] consentDescription, int consentConfirmation); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/content/ContentUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/content/ContentUtils.java index 1e9f021..07c8e4b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/content/ContentUtils.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/content/ContentUtils.java
@@ -4,6 +4,7 @@ package org.chromium.chrome.browser.content; +import org.chromium.base.annotations.NativeMethods; import org.chromium.content_public.browser.WebContents; /** @@ -14,7 +15,7 @@ * @return The user agent string of Chrome. */ public static String getBrowserUserAgent() { - return nativeGetBrowserUserAgent(); + return ContentUtilsJni.get().getBrowserUserAgent(); } /** @@ -24,9 +25,12 @@ * when a NavigationEntry requires the user agent to be overridden. */ public static void setUserAgentOverride(WebContents webContents) { - nativeSetUserAgentOverride(webContents); + ContentUtilsJni.get().setUserAgentOverride(webContents); } - private static native String nativeGetBrowserUserAgent(); - private static native void nativeSetUserAgentOverride(WebContents webContents); + @NativeMethods + interface Natives { + String getBrowserUserAgent(); + void setUserAgentOverride(WebContents webContents); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ContextMenuHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ContextMenuHelper.java index 5baeb12..d91102f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ContextMenuHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ContextMenuHelper.java
@@ -20,6 +20,7 @@ import org.chromium.base.TimeUtilsJni; import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.annotations.NativeMethods; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.task.PostTask; import org.chromium.chrome.R; @@ -120,7 +121,8 @@ mOnMenuClosed = (notAbandoned) -> { recordTimeToTakeActionHistogram(mSelectedItemBeforeDismiss || notAbandoned); if (mNativeContextMenuHelper == 0) return; - nativeOnContextMenuClosed(mNativeContextMenuHelper); + ContextMenuHelperJni.get().onContextMenuClosed( + mNativeContextMenuHelper, ContextMenuHelper.this); }; if (ChromeFeatureList.isEnabled(ChromeFeatureList.REVAMPED_CONTEXT_MENU) @@ -179,7 +181,8 @@ */ public void startContextMenuDownload(boolean isLink, boolean isDataReductionProxyEnabled) { if (mNativeContextMenuHelper != 0) { - nativeOnStartDownload(mNativeContextMenuHelper, isLink, isDataReductionProxyEnabled); + ContextMenuHelperJni.get().onStartDownload(mNativeContextMenuHelper, + ContextMenuHelper.this, isLink, isDataReductionProxyEnabled); } } @@ -195,7 +198,7 @@ */ public void searchForImage() { if (mNativeContextMenuHelper == 0) return; - nativeSearchForImage(mNativeContextMenuHelper); + ContextMenuHelperJni.get().searchForImage(mNativeContextMenuHelper, ContextMenuHelper.this); } /** @@ -232,8 +235,8 @@ ShareHelper.shareImage(mActivity, result, name, shareWithGoogleLens); } }; - nativeRetrieveImageForShare( - mNativeContextMenuHelper, callback, MAX_SHARE_DIMEN_PX, MAX_SHARE_DIMEN_PX); + ContextMenuHelperJni.get().retrieveImageForShare(mNativeContextMenuHelper, + ContextMenuHelper.this, callback, MAX_SHARE_DIMEN_PX, MAX_SHARE_DIMEN_PX); } /** @@ -249,8 +252,8 @@ final int maxWidthPx = res.getDimensionPixelSize(R.dimen.revamped_context_menu_header_image_max_size); - nativeRetrieveImageForContextMenu( - mNativeContextMenuHelper, callback, maxWidthPx, maxHeightPx); + ContextMenuHelperJni.get().retrieveImageForContextMenu(mNativeContextMenuHelper, + ContextMenuHelper.this, callback, maxWidthPx, maxHeightPx); } @Override @@ -282,12 +285,15 @@ return mPopulator; } - private native void nativeOnStartDownload( - long nativeContextMenuHelper, boolean isLink, boolean isDataReductionProxyEnabled); - private native void nativeSearchForImage(long nativeContextMenuHelper); - private native void nativeRetrieveImageForShare(long nativeContextMenuHelper, - Callback<byte[]> callback, int maxWidthPx, int maxHeightPx); - private native void nativeRetrieveImageForContextMenu(long nativeContextMenuHelper, - Callback<Bitmap> callback, int maxWidthPx, int maxHeightPx); - private native void nativeOnContextMenuClosed(long nativeContextMenuHelper); + @NativeMethods + interface Natives { + void onStartDownload(long nativeContextMenuHelper, ContextMenuHelper caller, boolean isLink, + boolean isDataReductionProxyEnabled); + void searchForImage(long nativeContextMenuHelper, ContextMenuHelper caller); + void retrieveImageForShare(long nativeContextMenuHelper, ContextMenuHelper caller, + Callback<byte[]> callback, int maxWidthPx, int maxHeightPx); + void retrieveImageForContextMenu(long nativeContextMenuHelper, ContextMenuHelper caller, + Callback<Bitmap> callback, int maxWidthPx, int maxHeightPx); + void onContextMenuClosed(long nativeContextMenuHelper, ContextMenuHelper caller); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchPolicy.java b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchPolicy.java index 25af0aaf..e33d278 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchPolicy.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchPolicy.java
@@ -116,11 +116,13 @@ * @return Whether a Tap gesture is currently supported as a trigger for the feature. */ boolean isTapSupported() { + if (isTapDisabledDueToLongpress()) return false; + return (!isUserUndecided() || ContextualSearchFieldTrial.getSwitch( ContextualSearchSwitch .IS_CONTEXTUAL_SEARCH_TAP_DISABLE_OVERRIDE_ENABLED)) - ? !isTapDisabledDueToLongpress() + ? true : (getPromoTapsRemaining() != 0); } @@ -150,7 +152,9 @@ return false; } - if (isPrivacyAggressiveResolveEnabled()) return true; + if (isPrivacyAggressiveResolveEnabled() + && mSelectionController.getSelectionType() == SelectionType.RESOLVING_LONG_PRESS) + return true; return (isPromoAvailable() || (mContextualSearchPreferenceHelper != null
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchPreferenceHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchPreferenceHelper.java index d2abb73..532dd6a8 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchPreferenceHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchPreferenceHelper.java
@@ -5,6 +5,7 @@ package org.chromium.chrome.browser.contextualsearch; import org.chromium.base.VisibleForTesting; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.preferences.ChromePreferenceManager; import org.chromium.chrome.browser.preferences.Pref; @@ -30,7 +31,8 @@ /** Constructs the singleton Unified Consent Helper instance. */ private ContextualSearchPreferenceHelper() { - mNativePointer = nativeInit(); + mNativePointer = ContextualSearchPreferenceHelperJni.get().init( + ContextualSearchPreferenceHelper.this); onPreferenceChangedInternal(); new PrefChangeRegistrar().addObserver( Pref.CONTEXTUAL_SEARCH_ENABLED, new PrefChangeRegistrar.PrefObserver() { @@ -43,11 +45,13 @@ /** * This method should be called to clean up storage when an instance of this class is - * no longer in use. The nativeDestroy will call the destructor on the native instance. + * no longer in use. The ContextualSearchPreferenceHelperJni.get().destroy will call the + * destructor on the native instance. */ void destroy() { assert mNativePointer != 0; - nativeDestroy(mNativePointer); + ContextualSearchPreferenceHelperJni.get().destroy( + mNativePointer, ContextualSearchPreferenceHelper.this); mNativePointer = 0; } @@ -70,7 +74,9 @@ /** Updates our preference metadata storage based on what our native member knows. */ void onPreferenceChangedInternal() { - updatePreviousPreferenceStorage(nativeGetPreferenceMetadata(mNativePointer)); + updatePreviousPreferenceStorage( + ContextualSearchPreferenceHelperJni.get().getPreferenceMetadata( + mNativePointer, ContextualSearchPreferenceHelper.this)); } /** @@ -126,7 +132,12 @@ ChromePreferenceManager.CONTEXTUAL_SEARCH_PRE_UNIFIED_CONSENT_PREF, metadata); } - private native long nativeInit(); - private native void nativeDestroy(long nativeContextualSearchPreferenceHelper); - private native int nativeGetPreferenceMetadata(long nativeContextualSearchPreferenceHelper); + @NativeMethods + interface Natives { + long init(ContextualSearchPreferenceHelper caller); + void destroy(long nativeContextualSearchPreferenceHelper, + ContextualSearchPreferenceHelper caller); + int getPreferenceMetadata(long nativeContextualSearchPreferenceHelper, + ContextualSearchPreferenceHelper caller); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchRankerLoggerImpl.java b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchRankerLoggerImpl.java index 1405eac..f28eb2a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchRankerLoggerImpl.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchRankerLoggerImpl.java
@@ -7,6 +7,7 @@ import android.support.annotation.Nullable; import org.chromium.base.VisibleForTesting; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.contextualsearch.ContextualSearchFieldTrial.ContextualSearchSwitch; import org.chromium.content_public.browser.WebContents; @@ -61,7 +62,9 @@ public ContextualSearchRankerLoggerImpl( ContextualSearchInteractionPersister interactionPersister) { mInteractionPersister = interactionPersister; - if (isEnabled()) mNativePointer = nativeInit(); + if (isEnabled()) + mNativePointer = ContextualSearchRankerLoggerImplJni.get().init( + ContextualSearchRankerLoggerImpl.this); } /** @@ -162,14 +165,16 @@ /** * This method should be called to clean up storage when an instance of this class is - * no longer in use. The nativeDestroy will call the destructor on the native instance. + * no longer in use. The ContextualSearchRankerLoggerImplJni.get().destroy will call the + * destructor on the native instance. */ void destroy() { // TODO(donnd): looks like this is never being called. Fix. if (isEnabled()) { assert mNativePointer != 0; writeLogAndReset(); - nativeDestroy(mNativePointer); + ContextualSearchRankerLoggerImplJni.get().destroy( + mNativePointer, ContextualSearchRankerLoggerImpl.this); mNativePointer = 0; } mIsLoggingReadyForPage = false; @@ -180,12 +185,14 @@ mIsLoggingReadyForPage = true; mBasePageWebContents = basePageWebContents; mHasInferenceOccurred = false; - nativeSetupLoggingAndRanker(mNativePointer, basePageWebContents); + ContextualSearchRankerLoggerImplJni.get().setupLoggingAndRanker( + mNativePointer, ContextualSearchRankerLoggerImpl.this, basePageWebContents); } @Override public boolean isQueryEnabled() { - return nativeIsQueryEnabled(mNativePointer); + return ContextualSearchRankerLoggerImplJni.get().isQueryEnabled( + mNativePointer, ContextualSearchRankerLoggerImpl.this); } @Override @@ -218,7 +225,8 @@ } mFeaturesLoggedForTesting = mFeaturesToLog; mFeaturesToLog = new HashMap<Integer, Object>(); - mAssistRankerPrediction = nativeRunInference(mNativePointer); + mAssistRankerPrediction = ContextualSearchRankerLoggerImplJni.get().runInference( + mNativePointer, ContextualSearchRankerLoggerImpl.this); ContextualSearchUma.logRecordedFeaturesToRanker(); } return mAssistRankerPrediction; @@ -258,7 +266,8 @@ mEventIdToPersist = 0; } } - nativeWriteLogAndReset(mNativePointer); + ContextualSearchRankerLoggerImplJni.get().writeLogAndReset( + mNativePointer, ContextualSearchRankerLoggerImpl.this); } reset(); } @@ -319,7 +328,8 @@ String featureName = outcomeName(feature) == null ? featureName(feature) : outcomeName(feature); assert featureName != null : "No Name for feature " + feature; - nativeLogInt32(mNativePointer, featureName, value); + ContextualSearchRankerLoggerImplJni.get().logInt32( + mNativePointer, ContextualSearchRankerLoggerImpl.this, featureName, value); } /** @@ -347,14 +357,24 @@ // ============================================================================================ // Native methods. // ============================================================================================ - private native long nativeInit(); - private native void nativeDestroy(long nativeContextualSearchRankerLoggerImpl); - private native void nativeLogInt32( - long nativeContextualSearchRankerLoggerImpl, String featureString, int value); - private native void nativeSetupLoggingAndRanker( - long nativeContextualSearchRankerLoggerImpl, WebContents basePageWebContents); - // Returns an AssistRankerPrediction integer value. - private native int nativeRunInference(long nativeContextualSearchRankerLoggerImpl); - private native void nativeWriteLogAndReset(long nativeContextualSearchRankerLoggerImpl); - private native boolean nativeIsQueryEnabled(long nativeContextualSearchRankerLoggerImpl); + + @NativeMethods + interface Natives { + long init(ContextualSearchRankerLoggerImpl caller); + + void destroy(long nativeContextualSearchRankerLoggerImpl, + ContextualSearchRankerLoggerImpl caller); + void logInt32(long nativeContextualSearchRankerLoggerImpl, + ContextualSearchRankerLoggerImpl caller, String featureString, int value); + void setupLoggingAndRanker(long nativeContextualSearchRankerLoggerImpl, + ContextualSearchRankerLoggerImpl caller, WebContents basePageWebContents); + // Returns an AssistRankerPrediction integer value. + int runInference(long nativeContextualSearchRankerLoggerImpl, + ContextualSearchRankerLoggerImpl caller); + + void writeLogAndReset(long nativeContextualSearchRankerLoggerImpl, + ContextualSearchRankerLoggerImpl caller); + boolean isQueryEnabled(long nativeContextualSearchRankerLoggerImpl, + ContextualSearchRankerLoggerImpl caller); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchRequest.java b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchRequest.java index 44c5b5ec..a48bb23 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchRequest.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchRequest.java
@@ -1,7 +1,6 @@ // 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. - package org.chromium.chrome.browser.contextualsearch; import android.net.Uri;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchTabHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchTabHelper.java index 4f6c1f8..f5e315a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchTabHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchTabHelper.java
@@ -8,6 +8,7 @@ import android.view.ContextMenu; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.compositor.CompositorViewHolder; import org.chromium.chrome.browser.compositor.bottombar.OverlayPanel.StateChangeReason; @@ -200,7 +201,8 @@ // Native initialization happens after a page loads or content is changed to ensure profile // is initialized. if (mNativeHelper == 0) { - mNativeHelper = nativeInit(tab.getProfile()); + mNativeHelper = ContextualSearchTabHelperJni.get().init( + ContextualSearchTabHelper.this, tab.getProfile()); } if (mTemplateUrlObserver == null) { mTemplateUrlObserver = new TemplateUrlServiceObserver() { @@ -228,7 +230,8 @@ @Override public void onDestroyed(Tab tab) { if (mNativeHelper != 0) { - nativeDestroy(mNativeHelper); + ContextualSearchTabHelperJni.get().destroy( + mNativeHelper, ContextualSearchTabHelper.this); mNativeHelper = 0; } if (mTemplateUrlObserver != null) { @@ -345,7 +348,8 @@ contextualSearchManager.getContextualSearchSelectionClient())); contextualSearchManager.setCouldSmartSelectionBeActive( mSelectionClientManager.isSmartSelectionEnabledInChrome()); - nativeInstallUnhandledTapNotifierIfNeeded(mNativeHelper, webContents, mPxToDp); + ContextualSearchTabHelperJni.get().installUnhandledTapNotifierIfNeeded( + mNativeHelper, ContextualSearchTabHelper.this, webContents, mPxToDp); } } @@ -444,8 +448,11 @@ } } - private native long nativeInit(Profile profile); - private native void nativeInstallUnhandledTapNotifierIfNeeded( - long nativeContextualSearchTabHelper, WebContents webContents, float pxToDpScaleFactor); - private native void nativeDestroy(long nativeContextualSearchTabHelper); + @NativeMethods + interface Natives { + long init(ContextualSearchTabHelper caller, Profile profile); + void installUnhandledTapNotifierIfNeeded(long nativeContextualSearchTabHelper, + ContextualSearchTabHelper caller, WebContents webContents, float pxToDpScaleFactor); + void destroy(long nativeContextualSearchTabHelper, ContextualSearchTabHelper caller); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/CtrSuppression.java b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/CtrSuppression.java index 840e2ac..4abe168 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/CtrSuppression.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/CtrSuppression.java
@@ -5,6 +5,7 @@ package org.chromium.chrome.browser.contextualsearch; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.preferences.ChromePreferenceManager; /** @@ -33,7 +34,7 @@ // This needs to be done last in this constructor because the native code may call // into this object. - mNativePointer = nativeInit(); + mNativePointer = CtrSuppressionJni.get().init(CtrSuppression.this); } /** @@ -42,7 +43,7 @@ */ public void destroy() { if (mNativePointer != 0L) { - nativeDestroy(mNativePointer); + CtrSuppressionJni.get().destroy(mNativePointer, CtrSuppression.this); } } @@ -60,17 +61,24 @@ // Since the CTR for previous time periods never changes, we only need to write to the UMA // log when we may have moved to a new week, or we have new persistent data. // We cache the current week in persistent storage so we can tell when it changes. - boolean didWeekChange = didWeekChange(nativeGetCurrentWeekNumber(mNativePointer)); + boolean didWeekChange = didWeekChange( + CtrSuppressionJni.get().getCurrentWeekNumber(mNativePointer, CtrSuppression.this)); if (didWeekChange) { - if (nativeHasPreviousWeekData(mNativePointer)) { - int previousWeekImpressions = nativeGetPreviousWeekImpressions(mNativePointer); - int previousWeekCtr = (int) (100 * nativeGetPreviousWeekCtr(mNativePointer)); + if (CtrSuppressionJni.get().hasPreviousWeekData(mNativePointer, CtrSuppression.this)) { + int previousWeekImpressions = CtrSuppressionJni.get().getPreviousWeekImpressions( + mNativePointer, CtrSuppression.this); + int previousWeekCtr = (int) (100 + * CtrSuppressionJni.get().getPreviousWeekCtr( + mNativePointer, CtrSuppression.this)); ContextualSearchUma.logPreviousWeekCtr(previousWeekImpressions, previousWeekCtr); } - if (nativeHasPrevious28DayData(mNativePointer)) { - int previous28DayImpressions = nativeGetPrevious28DayImpressions(mNativePointer); - int previous28DayCtr = (int) (100 * nativeGetPrevious28DayCtr(mNativePointer)); + if (CtrSuppressionJni.get().hasPrevious28DayData(mNativePointer, CtrSuppression.this)) { + int previous28DayImpressions = CtrSuppressionJni.get().getPrevious28DayImpressions( + mNativePointer, CtrSuppression.this); + int previous28DayCtr = (int) (100 + * CtrSuppressionJni.get().getPrevious28DayCtr( + mNativePointer, CtrSuppression.this)); ContextualSearchUma.logPrevious28DayCtr(previous28DayImpressions, previous28DayCtr); } } @@ -79,15 +87,19 @@ @Override protected void logResultsSeen(boolean wasSearchContentViewSeen, boolean wasActivatedByTap) { if (wasActivatedByTap) { - nativeRecordImpression(mNativePointer, wasSearchContentViewSeen); + CtrSuppressionJni.get().recordImpression( + mNativePointer, CtrSuppression.this, wasSearchContentViewSeen); } } @Override protected void logRankerTapSuppression(ContextualSearchInteractionRecorder recorder) { - if (nativeHasPreviousWeekData(mNativePointer)) { - int previousWeekImpressions = nativeGetPreviousWeekImpressions(mNativePointer); - int previousWeekCtr = (int) (100 * nativeGetPreviousWeekCtr(mNativePointer)); + if (CtrSuppressionJni.get().hasPreviousWeekData(mNativePointer, CtrSuppression.this)) { + int previousWeekImpressions = CtrSuppressionJni.get().getPreviousWeekImpressions( + mNativePointer, CtrSuppression.this); + int previousWeekCtr = (int) (100 + * CtrSuppressionJni.get().getPreviousWeekCtr( + mNativePointer, CtrSuppression.this)); recorder.logFeature( ContextualSearchInteractionRecorder.Feature.PREVIOUS_WEEK_IMPRESSIONS_COUNT, previousWeekImpressions); @@ -96,9 +108,12 @@ previousWeekCtr); } - if (nativeHasPrevious28DayData(mNativePointer)) { - int previous28DayImpressions = nativeGetPrevious28DayImpressions(mNativePointer); - int previous28DayCtr = (int) (100 * nativeGetPrevious28DayCtr(mNativePointer)); + if (CtrSuppressionJni.get().hasPrevious28DayData(mNativePointer, CtrSuppression.this)) { + int previous28DayImpressions = CtrSuppressionJni.get().getPrevious28DayImpressions( + mNativePointer, CtrSuppression.this); + int previous28DayCtr = (int) (100 + * CtrSuppressionJni.get().getPrevious28DayCtr( + mNativePointer, CtrSuppression.this)); recorder.logFeature( ContextualSearchInteractionRecorder.Feature.PREVIOUS_28DAY_IMPRESSIONS_COUNT, previous28DayImpressions); @@ -154,15 +169,19 @@ // ============================================================================================ // Native methods. // ============================================================================================ - private native long nativeInit(); - private native void nativeDestroy(long nativeCtrSuppression); - private native void nativeRecordImpression(long nativeCtrSuppression, boolean wasSeen); - private native int nativeGetCurrentWeekNumber(long nativeCtrSuppression); - private native boolean nativeHasPreviousWeekData(long nativeCtrSuppression); - private native int nativeGetPreviousWeekImpressions(long nativeCtrSuppression); - private native float nativeGetPreviousWeekCtr(long nativeCtrSuppression); - private native boolean nativeHasPrevious28DayData(long nativeCtrSuppression); - private native int nativeGetPrevious28DayImpressions(long nativeCtrSuppression); - private native float nativeGetPrevious28DayCtr(long nativeCtrSuppression); + @NativeMethods + interface Natives { + long init(CtrSuppression caller); + + void destroy(long nativeCtrSuppression, CtrSuppression caller); + void recordImpression(long nativeCtrSuppression, CtrSuppression caller, boolean wasSeen); + int getCurrentWeekNumber(long nativeCtrSuppression, CtrSuppression caller); + boolean hasPreviousWeekData(long nativeCtrSuppression, CtrSuppression caller); + int getPreviousWeekImpressions(long nativeCtrSuppression, CtrSuppression caller); + float getPreviousWeekCtr(long nativeCtrSuppression, CtrSuppression caller); + boolean hasPrevious28DayData(long nativeCtrSuppression, CtrSuppression caller); + int getPrevious28DayImpressions(long nativeCtrSuppression, CtrSuppression caller); + float getPrevious28DayCtr(long nativeCtrSuppression, CtrSuppression caller); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/SimpleSearchTermResolver.java b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/SimpleSearchTermResolver.java index 427eb00..61d57f76 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/SimpleSearchTermResolver.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/SimpleSearchTermResolver.java
@@ -9,6 +9,7 @@ import org.chromium.base.Log; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.contextualsearch.ResolvedSearchTerm.CardTag; import org.chromium.chrome.browser.tab.Tab; import org.chromium.content_public.browser.WebContents; @@ -57,18 +58,21 @@ mResponseCallback = responseCallback; if (baseWebContents != null && contextualSearchContext != null && contextualSearchContext.canResolve()) { - Log.i(TAG, "calling nativeStartSearchTermResolutionRequest."); - nativeStartSearchTermResolutionRequest( - mNativePointer, contextualSearchContext, baseWebContents); + Log.i(TAG, + "calling SimpleSearchTermResolverJni.get().startSearchTermResolutionRequest."); + SimpleSearchTermResolverJni.get().startSearchTermResolutionRequest(mNativePointer, + SimpleSearchTermResolver.this, contextualSearchContext, baseWebContents); } } /** * Called in response to the - * {@link ContextualSearchManager#nativeStartSearchTermResolutionRequest} method. - * If {@code nativeStartSearchTermResolutionRequest} is called with a previous request sill - * pending our native delegate is supposed to cancel all previous requests. So this code - * should only be called with data corresponding to the most recent request. + * {@link + * ContextualSearchManager#SimpleSearchTermResolverJni.get().startSearchTermResolutionRequest} + * method. If {@code SimpleSearchTermResolverJni.get().startSearchTermResolutionRequest} is + * called with a previous request sill pending our native delegate is supposed to cancel all + * previous requests. So this code should only be called with data corresponding to the most + * recent request. * @param isNetworkUnavailable Indicates if the network is unavailable, in which case all other * parameters should be ignored. * @param responseCode The HTTP response code. If the code is not OK, the query should be @@ -121,7 +125,7 @@ /** Constructs the singleton instance. */ private SimpleSearchTermResolver() { - mNativePointer = nativeInit(); + mNativePointer = SimpleSearchTermResolverJni.get().init(SimpleSearchTermResolver.this); } /** Makes a Search URL from the given {@link ResolvedSearchTerm}. */ @@ -131,16 +135,21 @@ /** * This method should be called to clean up storage when an instance of this class is - * no longer in use. The nativeDestroy will call the destructor on the native instance. + * no longer in use. The SimpleSearchTermResolverJni.get().destroy will call the destructor on + * the native instance. */ void destroy() { assert mNativePointer != 0; - nativeDestroy(mNativePointer); + SimpleSearchTermResolverJni.get().destroy(mNativePointer, SimpleSearchTermResolver.this); mNativePointer = 0; } - private native long nativeInit(); - private native void nativeDestroy(long nativeSimpleSearchTermResolver); - private native void nativeStartSearchTermResolutionRequest(long nativeSimpleSearchTermResolver, - ContextualSearchContext contextualSearchContext, WebContents baseWebContents); + @NativeMethods + interface Natives { + long init(SimpleSearchTermResolver caller); + void destroy(long nativeSimpleSearchTermResolver, SimpleSearchTermResolver caller); + void startSearchTermResolutionRequest(long nativeSimpleSearchTermResolver, + SimpleSearchTermResolver caller, ContextualSearchContext contextualSearchContext, + WebContents baseWebContents); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnection.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnection.java index ae1c4ea..cb17132 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnection.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnection.java
@@ -22,6 +22,12 @@ import android.text.TextUtils; import android.widget.RemoteViews; +import androidx.browser.customtabs.CustomTabsCallback; +import androidx.browser.customtabs.CustomTabsIntent; +import androidx.browser.customtabs.CustomTabsService; +import androidx.browser.customtabs.CustomTabsSessionToken; +import androidx.browser.customtabs.PostMessageServiceConnection; + import org.json.JSONException; import org.json.JSONObject; @@ -37,6 +43,7 @@ import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.base.library_loader.LibraryProcessType; import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.metrics.CachedMetrics.EnumeratedHistogramSample; @@ -84,12 +91,6 @@ import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; -import androidx.browser.customtabs.CustomTabsCallback; -import androidx.browser.customtabs.CustomTabsIntent; -import androidx.browser.customtabs.CustomTabsService; -import androidx.browser.customtabs.CustomTabsSessionToken; -import androidx.browser.customtabs.PostMessageServiceConnection; - /** * Implementation of the ICustomTabsService interface. * @@ -911,8 +912,8 @@ String urlString = url.toString(); String referrerString = referrer.toString(); - nativeCreateAndStartDetachedResourceRequest(Profile.getLastUsedProfile(), session, - urlString, referrerString, policy, + CustomTabsConnectionJni.get().createAndStartDetachedResourceRequest( + Profile.getLastUsedProfile(), session, urlString, referrerString, policy, DetachedResourceRequestMotivation.PARALLEL_REQUEST); if (mLogRequests) { Log.w(TAG, "startParallelRequest(%s, %s, %d)", urlString, referrerString, policy); @@ -951,8 +952,8 @@ if (urlString.isEmpty() || !isValid(url)) continue; // Session is null because we don't need completion notifications. - nativeCreateAndStartDetachedResourceRequest(Profile.getLastUsedProfile(), null, - urlString, referrerString, policy, + CustomTabsConnectionJni.get().createAndStartDetachedResourceRequest( + Profile.getLastUsedProfile(), null, urlString, referrerString, policy, DetachedResourceRequestMotivation.RESOURCE_PREFETCH); ++requestsSent; @@ -1496,10 +1497,6 @@ recordSpeculationStatusOnSwap(SPECULATION_STATUS_ON_SWAP_BACKGROUND_TAB_NOT_MATCHED); } - private static native void nativeCreateAndStartDetachedResourceRequest(Profile profile, - CustomTabsSessionToken session, String url, String origin, int referrerPolicy, - @DetachedResourceRequestMotivation int motivation); - public ModuleLoader getModuleLoader(ComponentName componentName, @Nullable String assetName) { if (!ChromeFeatureList.isEnabled(ChromeFeatureList.CCT_MODULE_DEX_LOADING)) { assetName = null; @@ -1557,4 +1554,11 @@ return ChromeApplication.getComponent().resolveCustomTabsFileProcessor() .processFile(sessionToken, uri, purpose, extras); } + + @NativeMethods + interface Natives { + void createAndStartDetachedResourceRequest(Profile profile, CustomTabsSessionToken session, + String url, String origin, int referrerPolicy, + @DetachedResourceRequestMotivation int motivation); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/dynamicmodule/ModuleMetrics.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/dynamicmodule/ModuleMetrics.java index 7c2532b..205f6a0 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/dynamicmodule/ModuleMetrics.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/dynamicmodule/ModuleMetrics.java
@@ -10,6 +10,7 @@ import org.chromium.base.Log; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.base.metrics.RecordHistogram; import org.chromium.chrome.browser.metrics.UmaSessionStats; @@ -174,8 +175,11 @@ * @param suffix Histogram suffix. */ public static void recordCodeMemoryFootprint(String packageName, String suffix) { - nativeRecordCodeMemoryFootprint(packageName, suffix); + ModuleMetricsJni.get().recordCodeMemoryFootprint(packageName, suffix); } - private static native void nativeRecordCodeMemoryFootprint(String packageName, String suffix); + @NativeMethods + interface Natives { + void recordCodeMemoryFootprint(String packageName, String suffix); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/database/SQLiteCursor.java b/chrome/android/java/src/org/chromium/chrome/browser/database/SQLiteCursor.java index 82fbfbbf..a43dc0cf 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/database/SQLiteCursor.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/database/SQLiteCursor.java
@@ -9,6 +9,7 @@ import org.chromium.base.LifetimeAssert; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.annotations.NativeMethods; import java.sql.Types; @@ -47,49 +48,51 @@ @Override public int getCount() { synchronized (mMoveLock) { - if (mCount == -1) mCount = nativeGetCount(mNativeSQLiteCursor); + if (mCount == -1) + mCount = SQLiteCursorJni.get().getCount(mNativeSQLiteCursor, SQLiteCursor.this); } return mCount; } @Override public String[] getColumnNames() { - return nativeGetColumnNames(mNativeSQLiteCursor); + return SQLiteCursorJni.get().getColumnNames(mNativeSQLiteCursor, SQLiteCursor.this); } @Override public String getString(int column) { - return nativeGetString(mNativeSQLiteCursor, column); + return SQLiteCursorJni.get().getString(mNativeSQLiteCursor, SQLiteCursor.this, column); } @Override public short getShort(int column) { - return (short) nativeGetInt(mNativeSQLiteCursor, column); + return (short) SQLiteCursorJni.get().getInt(mNativeSQLiteCursor, SQLiteCursor.this, column); } @Override public int getInt(int column) { - return nativeGetInt(mNativeSQLiteCursor, column); + return SQLiteCursorJni.get().getInt(mNativeSQLiteCursor, SQLiteCursor.this, column); } @Override public long getLong(int column) { - return nativeGetLong(mNativeSQLiteCursor, column); + return SQLiteCursorJni.get().getLong(mNativeSQLiteCursor, SQLiteCursor.this, column); } @Override public float getFloat(int column) { - return (float) nativeGetDouble(mNativeSQLiteCursor, column); + return (float) SQLiteCursorJni.get().getDouble( + mNativeSQLiteCursor, SQLiteCursor.this, column); } @Override public double getDouble(int column) { - return nativeGetDouble(mNativeSQLiteCursor, column); + return SQLiteCursorJni.get().getDouble(mNativeSQLiteCursor, SQLiteCursor.this, column); } @Override public boolean isNull(int column) { - return nativeIsNull(mNativeSQLiteCursor, column); + return SQLiteCursorJni.get().isNull(mNativeSQLiteCursor, SQLiteCursor.this, column); } @Override @@ -97,7 +100,7 @@ super.close(); synchronized (mDestoryNativeLock) { if (mNativeSQLiteCursor != 0) { - nativeDestroy(mNativeSQLiteCursor); + SQLiteCursorJni.get().destroy(mNativeSQLiteCursor, SQLiteCursor.this); mNativeSQLiteCursor = 0; LifetimeAssert.setSafeToGc(mLifetimeAssert, true); } @@ -107,7 +110,7 @@ @Override public boolean onMove(int oldPosition, int newPosition) { synchronized (mMoveLock) { - nativeMoveTo(mNativeSQLiteCursor, newPosition); + SQLiteCursorJni.get().moveTo(mNativeSQLiteCursor, SQLiteCursor.this, newPosition); } return super.onMove(oldPosition, newPosition); } @@ -115,7 +118,7 @@ @Override public byte[] getBlob(int column) { synchronized (mGetBlobLock) { - return nativeGetBlob(mNativeSQLiteCursor, column); + return SQLiteCursorJni.get().getBlob(mNativeSQLiteCursor, SQLiteCursor.this, column); } } @@ -220,22 +223,26 @@ int columnCount = getColumnCount(); mColumnTypes = new int[columnCount]; for (int i = 0; i < columnCount; i++) { - mColumnTypes[i] = nativeGetColumnType(mNativeSQLiteCursor, i); + mColumnTypes[i] = SQLiteCursorJni.get().getColumnType( + mNativeSQLiteCursor, SQLiteCursor.this, i); } } } return mColumnTypes[index]; } - private native void nativeDestroy(long nativeSQLiteCursor); - private native int nativeGetCount(long nativeSQLiteCursor); - private native String[] nativeGetColumnNames(long nativeSQLiteCursor); - private native int nativeGetColumnType(long nativeSQLiteCursor, int column); - private native String nativeGetString(long nativeSQLiteCursor, int column); - private native byte[] nativeGetBlob(long nativeSQLiteCursor, int column); - private native boolean nativeIsNull(long nativeSQLiteCursor, int column); - private native long nativeGetLong(long nativeSQLiteCursor, int column); - private native int nativeGetInt(long nativeSQLiteCursor, int column); - private native double nativeGetDouble(long nativeSQLiteCursor, int column); - private native int nativeMoveTo(long nativeSQLiteCursor, int newPosition); + @NativeMethods + interface Natives { + void destroy(long nativeSQLiteCursor, SQLiteCursor caller); + int getCount(long nativeSQLiteCursor, SQLiteCursor caller); + String[] getColumnNames(long nativeSQLiteCursor, SQLiteCursor caller); + int getColumnType(long nativeSQLiteCursor, SQLiteCursor caller, int column); + String getString(long nativeSQLiteCursor, SQLiteCursor caller, int column); + byte[] getBlob(long nativeSQLiteCursor, SQLiteCursor caller, int column); + boolean isNull(long nativeSQLiteCursor, SQLiteCursor caller, int column); + long getLong(long nativeSQLiteCursor, SQLiteCursor caller, int column); + int getInt(long nativeSQLiteCursor, SQLiteCursor caller, int column); + double getDouble(long nativeSQLiteCursor, SQLiteCursor caller, int column); + int moveTo(long nativeSQLiteCursor, SQLiteCursor caller, int newPosition); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/document/DocumentWebContentsDelegate.java b/chrome/android/java/src/org/chromium/chrome/browser/document/DocumentWebContentsDelegate.java index d9b902c0..d4d1dea 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/document/DocumentWebContentsDelegate.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/document/DocumentWebContentsDelegate.java
@@ -5,6 +5,7 @@ package org.chromium.chrome.browser.document; import org.chromium.base.BuildInfo; +import org.chromium.base.annotations.NativeMethods; import org.chromium.components.embedder_support.delegate.WebContentsDelegateAndroid; import org.chromium.content_public.browser.WebContents; @@ -39,11 +40,13 @@ * @param webContents The {@link WebContents} to attach to. */ public void attachDelegate(WebContents webContents) { - nativeAttachContents(mNativePtr, webContents); + DocumentWebContentsDelegateJni.get().attachContents( + mNativePtr, DocumentWebContentsDelegate.this, webContents); } private DocumentWebContentsDelegate() { - mNativePtr = nativeInitialize(); + mNativePtr = + DocumentWebContentsDelegateJni.get().initialize(DocumentWebContentsDelegate.this); } @Override @@ -52,7 +55,10 @@ return !BuildInfo.isDebugAndroid(); } - private native long nativeInitialize(); - private native void nativeAttachContents( - long nativeDocumentWebContentsDelegate, WebContents webContents); + @NativeMethods + interface Natives { + long initialize(DocumentWebContentsDelegate caller); + void attachContents(long nativeDocumentWebContentsDelegate, + DocumentWebContentsDelegate caller, WebContents webContents); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/dom_distiller/DomDistillerServiceFactory.java b/chrome/android/java/src/org/chromium/chrome/browser/dom_distiller/DomDistillerServiceFactory.java index 2ac26778..013b661 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/dom_distiller/DomDistillerServiceFactory.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/dom_distiller/DomDistillerServiceFactory.java
@@ -6,6 +6,7 @@ import org.chromium.base.ThreadUtils; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.components.dom_distiller.core.DomDistillerService; @@ -30,11 +31,14 @@ ThreadUtils.assertOnUiThread(); DomDistillerService service = sServiceMap.get(profile); if (service == null) { - service = nativeGetForProfile(profile); + service = DomDistillerServiceFactoryJni.get().getForProfile(profile); sServiceMap.put(profile, service); } return service; } - private static native DomDistillerService nativeGetForProfile(Profile profile); + @NativeMethods + interface Natives { + DomDistillerService getForProfile(Profile profile); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/dom_distiller/DomDistillerTabUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/dom_distiller/DomDistillerTabUtils.java index 4ebc4fb5..149d0077 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/dom_distiller/DomDistillerTabUtils.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/dom_distiller/DomDistillerTabUtils.java
@@ -5,6 +5,7 @@ package org.chromium.chrome.browser.dom_distiller; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.preferences.Pref; import org.chromium.chrome.browser.preferences.PrefServiceBridge; @@ -30,7 +31,7 @@ * @param webContents the WebContents to distill. */ public static void distillCurrentPageAndView(WebContents webContents) { - nativeDistillCurrentPageAndView(webContents); + DomDistillerTabUtilsJni.get().distillCurrentPageAndView(webContents); } /** @@ -40,7 +41,7 @@ * @param webContents the WebContents to distill. */ public static void distillCurrentPage(WebContents webContents) { - nativeDistillCurrentPage(webContents); + DomDistillerTabUtilsJni.get().distillCurrentPage(webContents); } /** @@ -53,7 +54,7 @@ */ public static void distillAndView( WebContents sourceWebContents, WebContents destinationWebContents) { - nativeDistillAndView(sourceWebContents, destinationWebContents); + DomDistillerTabUtilsJni.get().distillAndView(sourceWebContents, destinationWebContents); } /** @@ -63,7 +64,7 @@ * @return the formatted URL of the original page. */ public static String getFormattedUrlFromOriginalDistillerUrl(String url) { - return nativeGetFormattedUrlFromOriginalDistillerUrl(url); + return DomDistillerTabUtilsJni.get().getFormattedUrlFromOriginalDistillerUrl(url); } /** @@ -97,11 +98,11 @@ } /** - * Cached version of nativeGetDistillerHeuristics(). + * Cached version of DomDistillerTabUtilsJni.get().getDistillerHeuristics(). */ public static @DistillerHeuristicsType int getDistillerHeuristics() { if (sHeuristics == null) { - sHeuristics = nativeGetDistillerHeuristics(); + sHeuristics = DomDistillerTabUtilsJni.get().getDistillerHeuristics(); } return sHeuristics; } @@ -123,15 +124,17 @@ */ public static void setInterceptNavigationDelegate( InterceptNavigationDelegate delegate, WebContents webContents) { - nativeSetInterceptNavigationDelegate(delegate, webContents); + DomDistillerTabUtilsJni.get().setInterceptNavigationDelegate(delegate, webContents); } - private static native void nativeDistillCurrentPageAndView(WebContents webContents); - private static native void nativeDistillCurrentPage(WebContents webContents); - private static native void nativeDistillAndView( - WebContents sourceWebContents, WebContents destinationWebContents); - private static native String nativeGetFormattedUrlFromOriginalDistillerUrl(String url); - private static native int nativeGetDistillerHeuristics(); - private static native void nativeSetInterceptNavigationDelegate( - InterceptNavigationDelegate delegate, WebContents webContents); + @NativeMethods + interface Natives { + void distillCurrentPageAndView(WebContents webContents); + void distillCurrentPage(WebContents webContents); + void distillAndView(WebContents sourceWebContents, WebContents destinationWebContents); + String getFormattedUrlFromOriginalDistillerUrl(String url); + int getDistillerHeuristics(); + void setInterceptNavigationDelegate( + InterceptNavigationDelegate delegate, WebContents webContents); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadController.java b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadController.java index 3ed85dab..7e1cb76 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadController.java
@@ -13,6 +13,7 @@ import org.chromium.base.Callback; import org.chromium.base.ContextUtils; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.annotations.NativeMethods; import org.chromium.base.library_loader.LibraryProcessType; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; @@ -142,7 +143,8 @@ @CalledByNative private static void requestFileAccess(final long callbackId) { requestFileAccessPermissionHelper(result -> { - nativeOnAcquirePermissionResult(callbackId, result.first, result.second); + DownloadControllerJni.get().onAcquirePermissionResult( + callbackId, result.first, result.second); }); } @@ -281,7 +283,8 @@ return false; } - // native methods - private static native void nativeOnAcquirePermissionResult( - long callbackId, boolean granted, String permissionToUpdate); + @NativeMethods + interface Natives { + void onAcquirePermissionResult(long callbackId, boolean granted, String permissionToUpdate); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadLocationDialogBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadLocationDialogBridge.java index 64823b2..6c1d7834f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadLocationDialogBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadLocationDialogBridge.java
@@ -10,6 +10,7 @@ import android.view.LayoutInflater; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.annotations.NativeMethods; import org.chromium.base.metrics.RecordHistogram; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.preferences.PrefServiceBridge; @@ -118,7 +119,9 @@ assert(!TextUtils.isEmpty(dir.location)); PrefServiceBridge.getInstance().setDownloadAndSaveFileDefaultDirectory( dir.location); - nativeOnComplete(mNativeDownloadLocationDialogBridge, mSuggestedPath); + DownloadLocationDialogBridgeJni.get().onComplete( + mNativeDownloadLocationDialogBridge, DownloadLocationDialogBridge.this, + mSuggestedPath); } return; } @@ -199,7 +202,8 @@ DirectoryOption.DownloadLocationDirectoryType.NUM_ENTRIES); File file = new File(directoryOption.location, fileName); - nativeOnComplete(mNativeDownloadLocationDialogBridge, file.getAbsolutePath()); + DownloadLocationDialogBridgeJni.get().onComplete(mNativeDownloadLocationDialogBridge, + DownloadLocationDialogBridge.this, file.getAbsolutePath()); } // Update preference to show prompt based on whether checkbox is checked only when the user @@ -215,11 +219,16 @@ private void cancel() { if (mNativeDownloadLocationDialogBridge != 0) { - nativeOnCanceled(mNativeDownloadLocationDialogBridge); + DownloadLocationDialogBridgeJni.get().onCanceled( + mNativeDownloadLocationDialogBridge, DownloadLocationDialogBridge.this); } } - public native void nativeOnComplete( - long nativeDownloadLocationDialogBridge, String returnedPath); - public native void nativeOnCanceled(long nativeDownloadLocationDialogBridge); + @NativeMethods + interface Natives { + void onComplete(long nativeDownloadLocationDialogBridge, + DownloadLocationDialogBridge caller, String returnedPath); + void onCanceled( + long nativeDownloadLocationDialogBridge, DownloadLocationDialogBridge caller); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadManagerBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadManagerBridge.java index e7fdfc70..20e317b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadManagerBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadManagerBridge.java
@@ -22,6 +22,7 @@ import org.chromium.base.StrictModeContext; import org.chromium.base.ThreadUtils; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.annotations.NativeMethods; import org.chromium.base.task.AsyncTask; import org.chromium.base.task.PostTask; import org.chromium.base.task.TaskTraits; @@ -302,7 +303,8 @@ @Override protected void onPostExecute(Pair<Long, Boolean> result) { - nativeOnAddCompletedDownloadDone(callbackId, result.first, result.second); + DownloadManagerBridgeJni.get().onAddCompletedDownloadDone( + callbackId, result.first, result.second); } }; try { @@ -310,7 +312,8 @@ } catch (RejectedExecutionException e) { // Reaching thread limit, update will be reschduled for the next run. Log.e(TAG, "Thread limit reached, reschedule notification update later."); - nativeOnAddCompletedDownloadDone(callbackId, DownloadItem.INVALID_DOWNLOAD_ID, false); + DownloadManagerBridgeJni.get().onAddCompletedDownloadDone( + callbackId, DownloadItem.INVALID_DOWNLOAD_ID, false); } } @@ -454,6 +457,8 @@ } } - private static native void nativeOnAddCompletedDownloadDone( - long callbackId, long downloadId, boolean canResolve); + @NativeMethods + interface Natives { + void onAddCompletedDownloadDone(long callbackId, long downloadId, boolean canResolve); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadManagerService.java b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadManagerService.java index 0af94ee..a9fc2d50 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadManagerService.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadManagerService.java
@@ -29,6 +29,7 @@ import org.chromium.base.ThreadUtils; import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.annotations.NativeMethods; import org.chromium.base.library_loader.LibraryProcessType; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.task.AsyncTask; @@ -1096,8 +1097,9 @@ } incrementDownloadRetryCount(item.getId(), false); } - nativeResumeDownload(getNativeDownloadManagerService(), item.getId(), - item.getDownloadInfo().isOffTheRecord(), hasUserGesture); + DownloadManagerServiceJni.get().resumeDownload(getNativeDownloadManagerService(), + DownloadManagerService.this, item.getId(), item.getDownloadInfo().isOffTheRecord(), + hasUserGesture); } /** @@ -1107,8 +1109,9 @@ * @param hasUserGesture Whether the request was originated due to user gesture. */ public void retryDownload(ContentId id, DownloadItem item, boolean hasUserGesture) { - nativeRetryDownload(getNativeDownloadManagerService(), item.getId(), - item.getDownloadInfo().isOffTheRecord(), hasUserGesture); + DownloadManagerServiceJni.get().retryDownload(getNativeDownloadManagerService(), + DownloadManagerService.this, item.getId(), item.getDownloadInfo().isOffTheRecord(), + hasUserGesture); } /** @@ -1118,7 +1121,8 @@ */ @Override public void cancelDownload(ContentId id, boolean isOffTheRecord) { - nativeCancelDownload(getNativeDownloadManagerService(), id.id, isOffTheRecord); + DownloadManagerServiceJni.get().cancelDownload(getNativeDownloadManagerService(), + DownloadManagerService.this, id.id, isOffTheRecord); DownloadProgress progress = mDownloadProgressMap.get(id.id); if (progress != null) { DownloadInfo info = @@ -1140,7 +1144,8 @@ */ @Override public void pauseDownload(ContentId id, boolean isOffTheRecord) { - nativePauseDownload(getNativeDownloadManagerService(), id.id, isOffTheRecord); + DownloadManagerServiceJni.get().pauseDownload(getNativeDownloadManagerService(), + DownloadManagerService.this, id.id, isOffTheRecord); DownloadProgress progress = mDownloadProgressMap.get(id.id); // Calling pause will stop listening to the download item. Update its progress now. // If download is already completed, canceled or failed, there is no need to update the @@ -1170,7 +1175,8 @@ public void removeDownload( final String downloadGuid, boolean isOffTheRecord, boolean externallyRemoved) { mHandler.post(() -> { - nativeRemoveDownload(getNativeDownloadManagerService(), downloadGuid, isOffTheRecord); + DownloadManagerServiceJni.get().removeDownload(getNativeDownloadManagerService(), + DownloadManagerService.this, downloadGuid, isOffTheRecord); removeDownloadProgress(downloadGuid); }); @@ -1201,7 +1207,7 @@ public static boolean isSupportedMimeType(String mimeType) { // In NoTouch mode we don't support opening downloaded files in-browser. if (FeatureUtilities.isNoTouchModeEnabled()) return false; - return nativeIsSupportedMimeType(mimeType); + return DownloadManagerServiceJni.get().isSupportedMimeType(mimeType); } /** @@ -1213,7 +1219,8 @@ boolean startupCompleted = BrowserStartupController.get(LibraryProcessType.PROCESS_BROWSER) .isFullBrowserStarted(); - mNativeDownloadManagerService = nativeInit(startupCompleted); + mNativeDownloadManagerService = DownloadManagerServiceJni.get().init( + DownloadManagerService.this, startupCompleted); if (!startupCompleted) { BrowserStartupController.get(LibraryProcessType.PROCESS_BROWSER) .addStartupCompletedObserver(this); @@ -1226,7 +1233,8 @@ public void onSuccess() { if (BrowserStartupController.get(LibraryProcessType.PROCESS_BROWSER) .isFullBrowserStarted()) { - nativeOnFullBrowserStarted(mNativeDownloadManagerService); + DownloadManagerServiceJni.get().onFullBrowserStarted( + mNativeDownloadManagerService, DownloadManagerService.this); } } @@ -1623,7 +1631,8 @@ */ @Override public void getAllDownloads(boolean isOffTheRecord) { - nativeGetAllDownloads(getNativeDownloadManagerService(), isOffTheRecord); + DownloadManagerServiceJni.get().getAllDownloads( + getNativeDownloadManagerService(), DownloadManagerService.this, isOffTheRecord); } /** @@ -1643,8 +1652,8 @@ @Override public void renameDownload(ContentId id, String name, Callback<Integer /*RenameResult*/> callback, boolean isOffTheRecord) { - nativeRenameDownload( - getNativeDownloadManagerService(), id.id, name, callback, isOffTheRecord); + DownloadManagerServiceJni.get().renameDownload(getNativeDownloadManagerService(), + DownloadManagerService.this, id.id, name, callback, isOffTheRecord); } /** @@ -1678,7 +1687,8 @@ */ @Override public void checkForExternallyRemovedDownloads(boolean isOffTheRecord) { - nativeCheckForExternallyRemovedDownloads(getNativeDownloadManagerService(), isOffTheRecord); + DownloadManagerServiceJni.get().checkForExternallyRemovedDownloads( + getNativeDownloadManagerService(), DownloadManagerService.this, isOffTheRecord); } @CalledByNative @@ -1823,7 +1833,8 @@ * @param source The source where the user opened this download. */ public void openDownload(ContentId id, boolean isOffTheRecord, @DownloadOpenSource int source) { - nativeOpenDownload(getNativeDownloadManagerService(), id.id, isOffTheRecord, source); + DownloadManagerServiceJni.get().openDownload(getNativeDownloadManagerService(), + DownloadManagerService.this, id.id, isOffTheRecord, source); } /** @@ -1994,7 +2005,7 @@ int getAutoResumptionLimit() { if (mAutoResumptionLimit < 0) { - mAutoResumptionLimit = nativeGetAutoResumptionLimit(); + mAutoResumptionLimit = DownloadManagerServiceJni.get().getAutoResumptionLimit(); } return mAutoResumptionLimit; } @@ -2011,7 +2022,8 @@ mFirstBackgroundDownloadId = downloadGuid; DownloadNotificationUmaHelper.recordFirstBackgroundDownloadHistogram( UmaBackgroundDownload.STARTED, 0); - nativeRecordFirstBackgroundInterruptReason(getNativeDownloadManagerService(), + DownloadManagerServiceJni.get().recordFirstBackgroundInterruptReason( + getNativeDownloadManagerService(), DownloadManagerService.this, mFirstBackgroundDownloadId, true /* downloadStarted */); } if (ChromeFeatureList.isEnabled(ChromeFeatureList.DOWNLOAD_OFFLINE_CONTENT_PROVIDER)) { @@ -2037,7 +2049,8 @@ event, mFirstBackgroundDownloadInterruptionCount); if (event == UmaBackgroundDownload.INTERRUPTED) { mFirstBackgroundDownloadInterruptionCount++; - nativeRecordFirstBackgroundInterruptReason(getNativeDownloadManagerService(), + DownloadManagerServiceJni.get().recordFirstBackgroundInterruptReason( + getNativeDownloadManagerService(), DownloadManagerService.this, mFirstBackgroundDownloadId, false /* downloadStarted */); } } @@ -2050,8 +2063,9 @@ * @param targetPath Target file path. */ void createInterruptedDownloadForTest(String url, String guid, String targetPath) { - nativeCreateInterruptedDownloadForTest( - getNativeDownloadManagerService(), url, guid, targetPath); + DownloadManagerServiceJni.get().createInterruptedDownloadForTest( + getNativeDownloadManagerService(), DownloadManagerService.this, url, guid, + targetPath); } void disableAddCompletedDownloadToDownloadManager() { @@ -2067,7 +2081,8 @@ public void updateLastAccessTime(String downloadGuid, boolean isOffTheRecord) { if (TextUtils.isEmpty(downloadGuid)) return; - nativeUpdateLastAccessTime(getNativeDownloadManagerService(), downloadGuid, isOffTheRecord); + DownloadManagerServiceJni.get().updateLastAccessTime(getNativeDownloadManagerService(), + DownloadManagerService.this, downloadGuid, isOffTheRecord); } @Override @@ -2085,33 +2100,36 @@ @Override public void purgeActiveNetworkList(long[] activeNetIds) {} - private static native boolean nativeIsSupportedMimeType(String mimeType); - private static native int nativeGetAutoResumptionLimit(); - - private native long nativeInit(boolean isFullBrowserStarted); - private native void nativeOpenDownload(long nativeDownloadManagerService, String downloadGuid, - boolean isOffTheRecord, int source); - private native void nativeResumeDownload(long nativeDownloadManagerService, String downloadGuid, - boolean isOffTheRecord, boolean hasUserGesture); - private native void nativeRetryDownload(long nativeDownloadManagerService, String downloadGuid, - boolean isOffTheRecord, boolean hasUserGesture); - private native void nativeCancelDownload( - long nativeDownloadManagerService, String downloadGuid, boolean isOffTheRecord); - private native void nativePauseDownload(long nativeDownloadManagerService, String downloadGuid, - boolean isOffTheRecord); - private native void nativeRemoveDownload(long nativeDownloadManagerService, String downloadGuid, - boolean isOffTheRecord); - private native void nativeRenameDownload(long nativeDownloadManagerService, String downloadGuid, - String targetName, Callback</*RenameResult*/ Integer> callback, boolean isOffTheRecord); - private native void nativeGetAllDownloads( - long nativeDownloadManagerService, boolean isOffTheRecord); - private native void nativeCheckForExternallyRemovedDownloads( - long nativeDownloadManagerService, boolean isOffTheRecord); - private native void nativeUpdateLastAccessTime( - long nativeDownloadManagerService, String downloadGuid, boolean isOffTheRecord); - private native void nativeOnFullBrowserStarted(long nativeDownloadManagerService); - private native void nativeCreateInterruptedDownloadForTest( - long nativeDownloadManagerService, String url, String guid, String targetPath); - private native void nativeRecordFirstBackgroundInterruptReason( - long nativeDownloadManagerService, String guid, boolean downloadStarted); + @NativeMethods + interface Natives { + boolean isSupportedMimeType(String mimeType); + int getAutoResumptionLimit(); + long init(DownloadManagerService caller, boolean isFullBrowserStarted); + void openDownload(long nativeDownloadManagerService, DownloadManagerService caller, + String downloadGuid, boolean isOffTheRecord, int source); + void resumeDownload(long nativeDownloadManagerService, DownloadManagerService caller, + String downloadGuid, boolean isOffTheRecord, boolean hasUserGesture); + void retryDownload(long nativeDownloadManagerService, DownloadManagerService caller, + String downloadGuid, boolean isOffTheRecord, boolean hasUserGesture); + void cancelDownload(long nativeDownloadManagerService, DownloadManagerService caller, + String downloadGuid, boolean isOffTheRecord); + void pauseDownload(long nativeDownloadManagerService, DownloadManagerService caller, + String downloadGuid, boolean isOffTheRecord); + void removeDownload(long nativeDownloadManagerService, DownloadManagerService caller, + String downloadGuid, boolean isOffTheRecord); + void renameDownload(long nativeDownloadManagerService, DownloadManagerService caller, + String downloadGuid, String targetName, Callback</*RenameResult*/ Integer> callback, + boolean isOffTheRecord); + void getAllDownloads(long nativeDownloadManagerService, DownloadManagerService caller, + boolean isOffTheRecord); + void checkForExternallyRemovedDownloads(long nativeDownloadManagerService, + DownloadManagerService caller, boolean isOffTheRecord); + void updateLastAccessTime(long nativeDownloadManagerService, DownloadManagerService caller, + String downloadGuid, boolean isOffTheRecord); + void onFullBrowserStarted(long nativeDownloadManagerService, DownloadManagerService caller); + void createInterruptedDownloadForTest(long nativeDownloadManagerService, + DownloadManagerService caller, String url, String guid, String targetPath); + void recordFirstBackgroundInterruptReason(long nativeDownloadManagerService, + DownloadManagerService caller, String guid, boolean downloadStarted); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadMediaParserBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadMediaParserBridge.java index ff24469..03db9da 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadMediaParserBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadMediaParserBridge.java
@@ -5,6 +5,7 @@ package org.chromium.chrome.browser.download; import org.chromium.base.Callback; +import org.chromium.base.annotations.NativeMethods; /** * A JNI bridge that owns a native side DownloadMediaParser, which parses media file safely in an @@ -21,7 +22,8 @@ */ public DownloadMediaParserBridge( String mimeType, String filePath, Callback<DownloadMediaData> callback) { - mNativeDownloadMediaParserBridge = nativeInit(mimeType, filePath, callback); + mNativeDownloadMediaParserBridge = DownloadMediaParserBridgeJni.get().init( + DownloadMediaParserBridge.this, mimeType, filePath, callback); } /** @@ -29,7 +31,8 @@ * being destroyed. */ public void destroy() { - nativeDestroy(mNativeDownloadMediaParserBridge); + DownloadMediaParserBridgeJni.get().destroy( + mNativeDownloadMediaParserBridge, DownloadMediaParserBridge.this); mNativeDownloadMediaParserBridge = 0; } @@ -38,12 +41,16 @@ */ public void start() { if (mNativeDownloadMediaParserBridge != 0) { - nativeStart(mNativeDownloadMediaParserBridge); + DownloadMediaParserBridgeJni.get().start( + mNativeDownloadMediaParserBridge, DownloadMediaParserBridge.this); } } - private native long nativeInit( - String mimeType, String filePath, Callback<DownloadMediaData> callback); - private native void nativeDestroy(long nativeDownloadMediaParserBridge); - private native void nativeStart(long nativeDownloadMediaParserBridge); + @NativeMethods + interface Natives { + long init(DownloadMediaParserBridge caller, String mimeType, String filePath, + Callback<DownloadMediaData> callback); + void destroy(long nativeDownloadMediaParserBridge, DownloadMediaParserBridge caller); + void start(long nativeDownloadMediaParserBridge, DownloadMediaParserBridge caller); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadStartupUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadStartupUtils.java index 6de9f5e2..2ed1c3d6 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadStartupUtils.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadStartupUtils.java
@@ -3,6 +3,7 @@ // found in the LICENSE file. package org.chromium.chrome.browser.download; +import org.chromium.base.annotations.NativeMethods; /** * Handles initialization for the downloads system, i.e. creating in-progress download manager or @@ -15,8 +16,11 @@ * @param isFullBrowserStarted Whether full browser process has been started. */ public static void ensureDownloadSystemInitialized(boolean isFullBrowserStarted) { - nativeEnsureDownloadSystemInitialized(isFullBrowserStarted); + DownloadStartupUtilsJni.get().ensureDownloadSystemInitialized(isFullBrowserStarted); } - private static native void nativeEnsureDownloadSystemInitialized(boolean isFullBrowserStarted); + @NativeMethods + interface Natives { + void ensureDownloadSystemInitialized(boolean isFullBrowserStarted); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadUtils.java index dbd4e1f7..4932ed8 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadUtils.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadUtils.java
@@ -30,6 +30,7 @@ import org.chromium.base.TimeUtils; import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.annotations.NativeMethods; import org.chromium.base.library_loader.LibraryProcessType; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.RecordUserAction; @@ -1003,7 +1004,7 @@ public static String getFailStatusString(@FailState int failState) { if (BrowserStartupController.get(LibraryProcessType.PROCESS_BROWSER) .isFullBrowserStarted()) { - return nativeGetFailStateMessage(failState); + return DownloadUtilsJni.get().getFailStateMessage(failState); } Context context = ContextUtils.getApplicationContext(); return context.getString(R.string.download_notification_failed); @@ -1045,7 +1046,7 @@ * @return The resume mode for the current fail state. */ public static @ResumeMode int getResumeMode(String url, @FailState int failState) { - return nativeGetResumeMode(url, failState); + return DownloadUtilsJni.get().getResumeMode(url, failState); } /** @@ -1298,6 +1299,9 @@ return originalUri; } - private static native String nativeGetFailStateMessage(@FailState int failState); - private static native int nativeGetResumeMode(String url, @FailState int failState); + @NativeMethods + interface Natives { + String getFailStateMessage(@FailState int failState); + int getResumeMode(String url, @FailState int failState); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/home/rename/RenameUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/download/home/rename/RenameUtils.java index bd0394f..fd234d1 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/home/rename/RenameUtils.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/home/rename/RenameUtils.java
@@ -5,6 +5,7 @@ import org.chromium.base.FileUtils; import org.chromium.base.VisibleForTesting; +import org.chromium.base.annotations.NativeMethods; /** * A class containing some utility static methods for rename. @@ -23,7 +24,7 @@ */ public static String getFileExtension(String fileName) { return sIsDisabledNativeForTesting ? FileUtils.getExtension(fileName) - : nativeGetFileExtension(fileName); + : RenameUtilsJni.get().getFileExtension(fileName); } /** @@ -34,5 +35,8 @@ sIsDisabledNativeForTesting = true; } - private static native String nativeGetFileExtension(String fileName); + @NativeMethods + interface Natives { + String getFileExtension(String fileName); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/items/OfflineContentAggregatorFactory.java b/chrome/android/java/src/org/chromium/chrome/browser/download/items/OfflineContentAggregatorFactory.java index c1e5fd13..7c0565ff 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/items/OfflineContentAggregatorFactory.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/items/OfflineContentAggregatorFactory.java
@@ -7,6 +7,7 @@ import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.components.offline_items_collection.OfflineContentProvider; @@ -46,7 +47,8 @@ */ public static OfflineContentProvider get() { if (sProvider == null) { - sProvider = getProvider(nativeGetOfflineContentAggregator()); + sProvider = getProvider( + OfflineContentAggregatorFactoryJni.get().getOfflineContentAggregator()); } return sProvider; } @@ -59,5 +61,8 @@ } } - private static native OfflineContentProvider nativeGetOfflineContentAggregator(); + @NativeMethods + interface Natives { + OfflineContentProvider getOfflineContentAggregator(); + } }
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 5a3376f..759dcda3 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
@@ -8,6 +8,7 @@ import org.chromium.base.Callback; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.base.library_loader.LibraryProcessType; import org.chromium.chrome.browser.background_task_scheduler.NativeBackgroundTask; import org.chromium.chrome.browser.profiles.ProfileKey; @@ -62,8 +63,8 @@ .isFullBrowserStarted() || mStartsServiceManagerOnly; ProfileKey key = ProfileKey.getLastUsedProfileKey().getOriginalKey(); - nativeStartBackgroundTask( - key, mCurrentTaskType, needsReschedule -> callback.taskFinished(needsReschedule)); + DownloadBackgroundTaskJni.get().startBackgroundTask(DownloadBackgroundTask.this, key, + mCurrentTaskType, needsReschedule -> callback.taskFinished(needsReschedule)); } @Override @@ -81,7 +82,8 @@ @DownloadTaskType int taskType = taskParameters.getExtras().getInt(DownloadTaskScheduler.EXTRA_TASK_TYPE); ProfileKey key = ProfileKey.getLastUsedProfileKey().getOriginalKey(); - return nativeStopBackgroundTask(key, taskType); + return DownloadBackgroundTaskJni.get().stopBackgroundTask( + DownloadBackgroundTask.this, key, taskType); } @Override @@ -89,7 +91,10 @@ DownloadTaskScheduler.rescheduleAllTasks(); } - private native void nativeStartBackgroundTask( - ProfileKey key, int taskType, Callback<Boolean> callback); - private native boolean nativeStopBackgroundTask(ProfileKey key, int taskType); + @NativeMethods + interface Natives { + void startBackgroundTask(DownloadBackgroundTask caller, ProfileKey key, int taskType, + Callback<Boolean> callback); + boolean stopBackgroundTask(DownloadBackgroundTask caller, ProfileKey key, int taskType); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/engagement/SiteEngagementService.java b/chrome/android/java/src/org/chromium/chrome/browser/engagement/SiteEngagementService.java index a224d16..fe55193 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/engagement/SiteEngagementService.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/engagement/SiteEngagementService.java
@@ -6,6 +6,7 @@ import org.chromium.base.ThreadUtils; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.profiles.Profile; /** @@ -25,7 +26,7 @@ */ public static SiteEngagementService getForProfile(Profile profile) { assert ThreadUtils.runningOnUiThread(); - return nativeSiteEngagementServiceForProfile(profile); + return SiteEngagementServiceJni.get().siteEngagementServiceForProfile(profile); } /** @@ -35,7 +36,8 @@ public double getScore(String url) { assert ThreadUtils.runningOnUiThread(); if (mNativePointer == 0) return 0.0; - return nativeGetScore(mNativePointer, url); + return SiteEngagementServiceJni.get().getScore( + mNativePointer, SiteEngagementService.this, url); } /** @@ -45,14 +47,15 @@ public void resetBaseScoreForUrl(String url, double score) { assert ThreadUtils.runningOnUiThread(); if (mNativePointer == 0) return; - nativeResetBaseScoreForURL(mNativePointer, url, score); + SiteEngagementServiceJni.get().resetBaseScoreForURL( + mNativePointer, SiteEngagementService.this, url, score); } /** * Sets site engagement param values to constants for testing. */ public static void setParamValuesForTesting() { - nativeSetParamValuesForTesting(); + SiteEngagementServiceJni.get().setParamValuesForTesting(); } @CalledByNative @@ -70,10 +73,13 @@ mNativePointer = 0; } - private static native SiteEngagementService nativeSiteEngagementServiceForProfile( - Profile profile); - private static native void nativeSetParamValuesForTesting(); - private native double nativeGetScore(long nativeSiteEngagementServiceAndroid, String url); - private native void nativeResetBaseScoreForURL( - long nativeSiteEngagementServiceAndroid, String url, double score); + @NativeMethods + interface Natives { + SiteEngagementService siteEngagementServiceForProfile(Profile profile); + void setParamValuesForTesting(); + double getScore( + long nativeSiteEngagementServiceAndroid, SiteEngagementService caller, String url); + void resetBaseScoreForURL(long nativeSiteEngagementServiceAndroid, + SiteEngagementService caller, String url, double score); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExperimentalExploreSitesSection.java b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExperimentalExploreSitesSection.java index 2afa2755..51e676b1 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExperimentalExploreSitesSection.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExperimentalExploreSitesSection.java
@@ -51,7 +51,7 @@ (View v) -> mNavigationDelegate.openUrl(WindowOpenDisposition.CURRENT_TAB, new LoadUrlParams( - ExploreSitesBridgeExperimental.nativeGetCatalogUrl(), + ExploreSitesBridgeExperimentalJni.get().getCatalogUrl(), PageTransition.AUTO_BOOKMARK))); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesBridge.java index 3f92012..2d2404b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesBridge.java
@@ -13,6 +13,7 @@ import org.chromium.base.ContextUtils; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.profiles.Profile; import java.util.ArrayList; @@ -46,7 +47,7 @@ } List<ExploreSitesCategory> result = new ArrayList<>(); - nativeGetEspCatalog(profile, result, callback); + ExploreSitesBridgeJni.get().getEspCatalog(profile, result, callback); } /** @@ -72,7 +73,7 @@ } List<ExploreSitesCategory> result = new ArrayList<>(); - nativeGetCatalog(profile, source, result, callback); + ExploreSitesBridgeJni.get().getCatalog(profile, source, result, callback); } /** @@ -88,7 +89,7 @@ */ public static void initializeCatalog( Profile profile, @ExploreSitesCatalogUpdateRequestSource int source) { - nativeInitializeCatalog(profile, source); + ExploreSitesBridgeJni.get().initializeCatalog(profile, source); } public static void getSiteImage(Profile profile, int siteID, Callback<Bitmap> callback) { @@ -96,7 +97,7 @@ callback.onResult(null); return; } - nativeGetIcon(profile, siteID, callback); + ExploreSitesBridgeJni.get().getIcon(profile, siteID, callback); } /** @@ -109,7 +110,7 @@ callback.onResult(null); return; } - nativeGetCategoryImage(profile, categoryID, pixelSize, callback); + ExploreSitesBridgeJni.get().getCategoryImage(profile, categoryID, pixelSize, callback); } /** @@ -120,7 +121,7 @@ callback.onResult(null); return; } - nativeGetSummaryImage(profile, pixelSize, callback); + ExploreSitesBridgeJni.get().getSummaryImage(profile, pixelSize, callback); } /** @@ -128,14 +129,15 @@ */ public static void updateCatalogFromNetwork( Profile profile, boolean isImmediateFetch, Callback<Boolean> finishedCallback) { - nativeUpdateCatalogFromNetwork(profile, isImmediateFetch, finishedCallback); + ExploreSitesBridgeJni.get().updateCatalogFromNetwork( + profile, isImmediateFetch, finishedCallback); } /** * Adds a site to the blacklist when the user chooses "remove" from the long press menu. */ public static void blacklistSite(Profile profile, String url) { - nativeBlacklistSite(profile, url); + ExploreSitesBridgeJni.get().blacklistSite(profile, url); } /** @@ -143,7 +145,7 @@ */ public static void recordClick( Profile profile, String url, @ExploreSitesCategory.CategoryType int type) { - nativeRecordClick(profile, url, type); + ExploreSitesBridgeJni.get().recordClick(profile, url, type); } /** @@ -151,7 +153,7 @@ */ @ExploreSitesVariation public static int getVariation() { - return nativeGetVariation(); + return ExploreSitesBridgeJni.get().getVariation(); } /** @@ -160,7 +162,7 @@ */ @MostLikelyVariation public static int getIconVariation() { - return nativeGetIconVariation(); + return ExploreSitesBridgeJni.get().getIconVariation(); } /** @@ -168,7 +170,7 @@ * */ @DenseVariation public static int getDenseVariation() { - return nativeGetDenseVariation(); + return ExploreSitesBridgeJni.get().getDenseVariation(); } public static boolean isEnabled(@ExploreSitesVariation int variation) { @@ -194,7 +196,7 @@ * @param categoryId the row id of the category to increment show count for. */ public static void incrementNtpShownCount(Profile profile, int categoryId) { - nativeIncrementNtpShownCount(profile, categoryId); + ExploreSitesBridgeJni.get().incrementNtpShownCount(profile, categoryId); } @CalledByNative @@ -217,32 +219,24 @@ return metrics.density; } - static native int nativeGetVariation(); - static native int nativeGetIconVariation(); - static native int nativeGetDenseVariation(); - private static native void nativeGetEspCatalog(Profile profile, - List<ExploreSitesCategory> result, Callback<List<ExploreSitesCategory>> callback); - - private static native void nativeGetIcon( - Profile profile, int siteID, Callback<Bitmap> callback); - - private static native void nativeUpdateCatalogFromNetwork( - Profile profile, boolean isImmediateFetch, Callback<Boolean> callback); - - private static native void nativeGetCategoryImage( - Profile profile, int categoryID, int pixelSize, Callback<Bitmap> callback); - - private static native void nativeGetSummaryImage( - Profile profile, int pixelSize, Callback<Bitmap> callback); - - private static native void nativeBlacklistSite(Profile profile, String url); - - private static native void nativeRecordClick(Profile profile, String url, int type); - - private static native void nativeIncrementNtpShownCount(Profile profile, int categoryId); - - private static native void nativeGetCatalog(Profile profile, int source, - List<ExploreSitesCategory> result, Callback<List<ExploreSitesCategory>> callback); - - private static native void nativeInitializeCatalog(Profile profile, int source); + @NativeMethods + interface Natives { + int getVariation(); + int getIconVariation(); + int getDenseVariation(); + void getEspCatalog(Profile profile, List<ExploreSitesCategory> result, + Callback<List<ExploreSitesCategory>> callback); + void getIcon(Profile profile, int siteID, Callback<Bitmap> callback); + void updateCatalogFromNetwork( + Profile profile, boolean isImmediateFetch, Callback<Boolean> callback); + void getCategoryImage( + Profile profile, int categoryID, int pixelSize, Callback<Bitmap> callback); + void getSummaryImage(Profile profile, int pixelSize, Callback<Bitmap> callback); + void blacklistSite(Profile profile, String url); + void recordClick(Profile profile, String url, int type); + void incrementNtpShownCount(Profile profile, int categoryId); + void getCatalog(Profile profile, int source, List<ExploreSitesCategory> result, + Callback<List<ExploreSitesCategory>> callback); + void initializeCatalog(Profile profile, int source); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesBridgeExperimental.java b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesBridgeExperimental.java index ee41fd2..3067b6b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesBridgeExperimental.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesBridgeExperimental.java
@@ -8,6 +8,7 @@ import org.chromium.base.Callback; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.profiles.Profile; import java.util.ArrayList; @@ -25,7 +26,7 @@ public static void getNtpCategories( Profile profile, final Callback<List<ExploreSitesCategoryTile>> callback) { List<ExploreSitesCategoryTile> result = new ArrayList<>(); - nativeGetNtpCategories(profile, result, callback); + ExploreSitesBridgeExperimentalJni.get().getNtpCategories(profile, result, callback); } /** @@ -34,13 +35,16 @@ */ public static void getIcon( Profile profile, final String iconUrl, final Callback<Bitmap> callback) { - nativeGetIcon(profile, iconUrl, callback); + ExploreSitesBridgeExperimentalJni.get().getIcon(profile, iconUrl, callback); } - /* UX prototype methods. */ - private static native void nativeGetNtpCategories(Profile profile, - List<ExploreSitesCategoryTile> result, - Callback<List<ExploreSitesCategoryTile>> callback); - public static native String nativeGetCatalogUrl(); - private static native void nativeGetIcon( - Profile profile, String iconUrl, Callback<Bitmap> callback); + + @NativeMethods + interface Natives { + /* UX prototype methods. */ + void getNtpCategories(Profile profile, List<ExploreSitesCategoryTile> result, + Callback<List<ExploreSitesCategoryTile>> callback); + + String getCatalogUrl(); + void getIcon(Profile profile, String iconUrl, Callback<Bitmap> callback); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategoryTile.java b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategoryTile.java index eee1de0c..de65d6a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategoryTile.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategoryTile.java
@@ -31,7 +31,7 @@ public ExploreSitesCategoryTile(String categoryName, String iconUrl, String navigationUrl) { mCategoryName = categoryName; mIconUrl = iconUrl; - mNavigationUrl = ExploreSitesBridgeExperimental.nativeGetCatalogUrl() + navigationUrl; + mNavigationUrl = ExploreSitesBridgeExperimentalJni.get().getCatalogUrl() + navigationUrl; } public String getNavigationUrl() {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/favicon/FaviconHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/favicon/FaviconHelper.java index f8593eb..17a37873 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/favicon/FaviconHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/favicon/FaviconHelper.java
@@ -17,6 +17,7 @@ import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.R; import org.chromium.chrome.browser.ntp.NewTabPage; import org.chromium.chrome.browser.profiles.Profile; @@ -139,7 +140,7 @@ * Allocate and initialize the C++ side of this class. */ public FaviconHelper() { - mNativeFaviconHelper = nativeInit(); + mNativeFaviconHelper = FaviconHelperJni.get().init(); } /** @@ -147,7 +148,7 @@ */ public void destroy() { assert mNativeFaviconHelper != 0; - nativeDestroy(mNativeFaviconHelper); + FaviconHelperJni.get().destroy(mNativeFaviconHelper); mNativeFaviconHelper = 0; } @@ -165,8 +166,8 @@ Profile profile, String pageUrl, int desiredSizeInPixel, FaviconImageCallback faviconImageCallback) { assert mNativeFaviconHelper != 0; - return nativeGetLocalFaviconImageForURL(mNativeFaviconHelper, profile, pageUrl, - desiredSizeInPixel, faviconImageCallback); + return FaviconHelperJni.get().getLocalFaviconImageForURL( + mNativeFaviconHelper, profile, pageUrl, desiredSizeInPixel, faviconImageCallback); } /** @@ -181,7 +182,7 @@ public boolean getForeignFaviconImageForURL(Profile profile, String pageUrl, int desiredSizeInPixel, FaviconImageCallback faviconImageCallback) { assert mNativeFaviconHelper != 0; - return nativeGetForeignFaviconImageForURL( + return FaviconHelperJni.get().getForeignFaviconImageForURL( mNativeFaviconHelper, profile, pageUrl, desiredSizeInPixel, faviconImageCallback); } @@ -199,8 +200,8 @@ */ public void ensureIconIsAvailable(Profile profile, WebContents webContents, String pageUrl, String iconUrl, boolean isLargeIcon, IconAvailabilityCallback callback) { - nativeEnsureIconIsAvailable(mNativeFaviconHelper, profile, webContents, pageUrl, iconUrl, - isLargeIcon, callback); + FaviconHelperJni.get().ensureIconIsAvailable(mNativeFaviconHelper, profile, webContents, + pageUrl, iconUrl, isLargeIcon, callback); } /** @@ -210,20 +211,20 @@ * @param iconUrl The URL of the icon to touch. */ public void touchOnDemandFavicon(Profile profile, String iconUrl) { - nativeTouchOnDemandFavicon(mNativeFaviconHelper, profile, iconUrl); + FaviconHelperJni.get().touchOnDemandFavicon(mNativeFaviconHelper, profile, iconUrl); } - private static native long nativeInit(); - private static native void nativeDestroy(long nativeFaviconHelper); - private static native boolean nativeGetLocalFaviconImageForURL(long nativeFaviconHelper, - Profile profile, String pageUrl, int desiredSizeInDip, - FaviconImageCallback faviconImageCallback); - private static native boolean nativeGetForeignFaviconImageForURL(long nativeFaviconHelper, - Profile profile, String pageUrl, int desiredSizeInDip, - FaviconImageCallback faviconImageCallback); - private static native void nativeEnsureIconIsAvailable(long nativeFaviconHelper, - Profile profile, WebContents webContents, String pageUrl, String iconUrl, - boolean isLargeIcon, IconAvailabilityCallback callback); - private static native void nativeTouchOnDemandFavicon( - long nativeFaviconHelper, Profile profile, String iconUrl); + @NativeMethods + interface Natives { + long init(); + void destroy(long nativeFaviconHelper); + boolean getLocalFaviconImageForURL(long nativeFaviconHelper, Profile profile, + String pageUrl, int desiredSizeInDip, FaviconImageCallback faviconImageCallback); + boolean getForeignFaviconImageForURL(long nativeFaviconHelper, Profile profile, + String pageUrl, int desiredSizeInDip, FaviconImageCallback faviconImageCallback); + void ensureIconIsAvailable(long nativeFaviconHelper, Profile profile, + WebContents webContents, String pageUrl, String iconUrl, boolean isLargeIcon, + IconAvailabilityCallback callback); + void touchOnDemandFavicon(long nativeFaviconHelper, Profile profile, String iconUrl); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/favicon/LargeIconBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/favicon/LargeIconBridge.java index 6290af1..c04f8f2 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/favicon/LargeIconBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/favicon/LargeIconBridge.java
@@ -10,6 +10,7 @@ import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.util.ConversionUtils; @@ -62,7 +63,7 @@ * @param profile Profile to use when fetching icons. */ public LargeIconBridge(Profile profile) { - mNativeLargeIconBridge = nativeInit(); + mNativeLargeIconBridge = LargeIconBridgeJni.get().init(); mProfile = profile; } @@ -100,7 +101,7 @@ */ public void destroy() { if (mNativeLargeIconBridge != 0) { - nativeDestroy(mNativeLargeIconBridge); + LargeIconBridgeJni.get().destroy(mNativeLargeIconBridge); mNativeLargeIconBridge = 0; } } @@ -124,8 +125,8 @@ assert callback != null; if (mFaviconCache == null) { - return nativeGetLargeIconForURL(mNativeLargeIconBridge, mProfile, pageUrl, - desiredSizePx, callback); + return LargeIconBridgeJni.get().getLargeIconForURL( + mNativeLargeIconBridge, mProfile, pageUrl, desiredSizePx, callback); } else { CachedFavicon cached = mFaviconCache.get(pageUrl); if (cached != null) { @@ -145,8 +146,8 @@ icon, fallbackColor, isFallbackColorDefault, iconType); } }; - return nativeGetLargeIconForURL(mNativeLargeIconBridge, mProfile, pageUrl, - desiredSizePx, callbackWrapper); + return LargeIconBridgeJni.get().getLargeIconForURL( + mNativeLargeIconBridge, mProfile, pageUrl, desiredSizePx, callbackWrapper); } } @@ -157,8 +158,11 @@ mFaviconCache.remove(url); } - private static native long nativeInit(); - private static native void nativeDestroy(long nativeLargeIconBridge); - private static native boolean nativeGetLargeIconForURL(long nativeLargeIconBridge, - Profile profile, String pageUrl, int desiredSizePx, LargeIconCallback callback); + @NativeMethods + interface Natives { + long init(); + void destroy(long nativeLargeIconBridge); + boolean getLargeIconForURL(long nativeLargeIconBridge, Profile profile, String pageUrl, + int desiredSizePx, LargeIconCallback callback); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/feature_engagement/TrackerFactory.java b/chrome/android/java/src/org/chromium/chrome/browser/feature_engagement/TrackerFactory.java index 77ad79ec..2ed932d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/feature_engagement/TrackerFactory.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/feature_engagement/TrackerFactory.java
@@ -7,6 +7,7 @@ import android.support.annotation.Nullable; import org.chromium.base.VisibleForTesting; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.components.feature_engagement.Tracker; @@ -29,7 +30,7 @@ public static Tracker getTrackerForProfile(Profile profile) { if (sTestTracker != null) return sTestTracker; - return nativeGetTrackerForProfile(profile); + return TrackerFactoryJni.get().getTrackerForProfile(profile); } /** @@ -44,5 +45,8 @@ sTestTracker = testTracker; } - private static native Tracker nativeGetTrackerForProfile(Profile profile); + @NativeMethods + interface Natives { + Tracker getTrackerForProfile(Profile profile); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/feedback/ConnectivityChecker.java b/chrome/android/java/src/org/chromium/chrome/browser/feedback/ConnectivityChecker.java index 255957c..c48e818 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/feedback/ConnectivityChecker.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/feedback/ConnectivityChecker.java
@@ -9,6 +9,7 @@ import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.base.task.AsyncTask; import org.chromium.base.task.PostTask; import org.chromium.chrome.browser.profiles.Profile; @@ -84,7 +85,7 @@ static void checkConnectivitySystemNetworkStack( String urlStr, final int timeoutMs, final ConnectivityCheckerCallback callback) { - if (!nativeIsUrlValid(urlStr)) { + if (!ConnectivityCheckerJni.get().isUrlValid(urlStr)) { Log.w(TAG, "Predefined URL invalid."); postResult(callback, ConnectivityCheckResult.ERROR); return; @@ -159,7 +160,7 @@ static void checkConnectivityChromeNetworkStack( Profile profile, String url, long timeoutMs, ConnectivityCheckerCallback callback) { ThreadUtils.assertOnUiThread(); - nativeCheckConnectivity(profile, url, timeoutMs, callback); + ConnectivityCheckerJni.get().checkConnectivity(profile, url, timeoutMs, callback); } @CalledByNative @@ -169,8 +170,10 @@ private ConnectivityChecker() {} - private static native void nativeCheckConnectivity( - Profile profile, String url, long timeoutMs, ConnectivityCheckerCallback callback); - - private static native boolean nativeIsUrlValid(String url); + @NativeMethods + interface Natives { + void checkConnectivity( + Profile profile, String url, long timeoutMs, ConnectivityCheckerCallback callback); + boolean isUrlValid(String url); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/feedback/ProcessIdFeedbackSource.java b/chrome/android/java/src/org/chromium/chrome/browser/feedback/ProcessIdFeedbackSource.java index 3bf9598..d11e7b7 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/feedback/ProcessIdFeedbackSource.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/feedback/ProcessIdFeedbackSource.java
@@ -6,6 +6,7 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.content_public.common.ContentSwitches; import java.util.HashMap; @@ -42,14 +43,15 @@ // AsyncFeedbackSource implementation. @Override public void start(final Runnable callback) { - nativeStart(this); + ProcessIdFeedbackSourceJni.get().start(this); } @CalledByNative private void prepareCompleted(long nativeSource) { mProcessMap = new HashMap<>(); for (Map.Entry<String, Integer> entry : PROCESS_TYPES.entrySet()) { - long[] pids = nativeGetProcessIdsForType(nativeSource, entry.getValue()); + long[] pids = ProcessIdFeedbackSourceJni.get().getProcessIdsForType( + nativeSource, ProcessIdFeedbackSource.this, entry.getValue()); if (pids.length == 0) continue; StringBuilder spids = new StringBuilder(); for (long pid : pids) { @@ -58,7 +60,8 @@ } mProcessMap.put(processTypeToFeedbackKey(entry.getKey()), spids.toString()); } - mProcessMap.put(processTypeToFeedbackKey("browser"), Long.toString(nativeGetCurrentPid())); + mProcessMap.put(processTypeToFeedbackKey("browser"), + Long.toString(ProcessIdFeedbackSourceJni.get().getCurrentPid())); mIsReady = true; } @@ -72,8 +75,11 @@ return mProcessMap; } - private static native long nativeGetCurrentPid(); - private static native void nativeStart(ProcessIdFeedbackSource source); - private native long[] nativeGetProcessIdsForType( - long nativeProcessIdFeedbackSource, int processType); + @NativeMethods + interface Natives { + long getCurrentPid(); + void start(ProcessIdFeedbackSource source); + long[] getProcessIdsForType(long nativeProcessIdFeedbackSource, + ProcessIdFeedbackSource caller, int processType); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/feedback/ScreenshotTask.java b/chrome/android/java/src/org/chromium/chrome/browser/feedback/ScreenshotTask.java index a4f7aba..c7819ea3 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/feedback/ScreenshotTask.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/feedback/ScreenshotTask.java
@@ -12,6 +12,7 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.base.task.PostTask; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.tab.SadTab; @@ -73,7 +74,8 @@ return mBitmap; } - // This will be called on the UI thread in response to nativeGrabWindowSnapshotAsync. + // This will be called on the UI thread in response to + // ScreenshotTaskJni.get().grabWindowSnapshotAsync. @CalledByNative private void onBytesReceived(byte[] pngBytes) { Bitmap bitmap = null; @@ -93,7 +95,7 @@ Rect rect = new Rect(); activity.getWindow().getDecorView().getRootView().getWindowVisibleDisplayFrame(rect); - nativeGrabWindowSnapshotAsync( + ScreenshotTaskJni.get().grabWindowSnapshotAsync( this, ((ChromeActivity) activity).getWindowAndroid(), rect.width(), rect.height()); return true; @@ -144,6 +146,9 @@ return false; } - private static native void nativeGrabWindowSnapshotAsync( - ScreenshotTask callback, WindowAndroid window, int width, int height); + @NativeMethods + interface Natives { + void grabWindowSnapshotAsync( + ScreenshotTask callback, WindowAndroid window, int width, int height); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/feedback/SystemInfoFeedbackSource.java b/chrome/android/java/src/org/chromium/chrome/browser/feedback/SystemInfoFeedbackSource.java index 9245f85..4f3acc95 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/feedback/SystemInfoFeedbackSource.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/feedback/SystemInfoFeedbackSource.java
@@ -13,6 +13,7 @@ import org.chromium.base.CollectionUtil; import org.chromium.base.LocaleUtils; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.util.ConversionUtils; import java.io.File; @@ -33,12 +34,14 @@ @Override public Map<String, String> getFeedback() { Map<String, String> feedback = CollectionUtil.newHashMap( - Pair.create("CPU Architecture", nativeGetCpuArchitecture()), Pair.create( - "Available Memory (MB)", Integer.toString(nativeGetAvailableMemoryMB())), - Pair.create("Total Memory (MB)", Integer.toString(nativeGetTotalMemoryMB())), - Pair.create("GPU Vendor", nativeGetGpuVendor()), - Pair.create("GPU Model", nativeGetGpuModel()), + "CPU Architecture", SystemInfoFeedbackSourceJni.get().getCpuArchitecture()), + Pair.create("Available Memory (MB)", + Integer.toString(SystemInfoFeedbackSourceJni.get().getAvailableMemoryMB())), + Pair.create("Total Memory (MB)", + Integer.toString(SystemInfoFeedbackSourceJni.get().getTotalMemoryMB())), + Pair.create("GPU Vendor", SystemInfoFeedbackSourceJni.get().getGpuVendor()), + Pair.create("GPU Model", SystemInfoFeedbackSourceJni.get().getGpuModel()), Pair.create("UI Locale", LocaleUtils.getDefaultLocaleString())); StatFs statFs = getResult(); @@ -56,9 +59,12 @@ return feedback; } - private static native String nativeGetCpuArchitecture(); - private static native String nativeGetGpuVendor(); - private static native String nativeGetGpuModel(); - private static native int nativeGetAvailableMemoryMB(); - private static native int nativeGetTotalMemoryMB(); + @NativeMethods + interface Natives { + String getCpuArchitecture(); + String getGpuVendor(); + String getGpuModel(); + int getAvailableMemoryMB(); + int getTotalMemoryMB(); + } } \ No newline at end of file
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/findinpage/FindInPageBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/findinpage/FindInPageBridge.java index b0ddf33e..f8267b1 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/findinpage/FindInPageBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/findinpage/FindInPageBridge.java
@@ -4,6 +4,7 @@ package org.chromium.chrome.browser.findinpage; +import org.chromium.base.annotations.NativeMethods; import org.chromium.content_public.browser.WebContents; /** @@ -16,14 +17,15 @@ public FindInPageBridge(WebContents webContents) { assert webContents != null; mWebContents = webContents; - mNativeFindInPageBridge = nativeInit(webContents); + mNativeFindInPageBridge = + FindInPageBridgeJni.get().init(FindInPageBridge.this, webContents); } /** * Destroys this instance so no further calls can be executed. */ public void destroy() { - nativeDestroy(mNativeFindInPageBridge); + FindInPageBridgeJni.get().destroy(mNativeFindInPageBridge, FindInPageBridge.this); mNativeFindInPageBridge = 0; } @@ -34,7 +36,8 @@ */ public void startFinding(String searchString, boolean forwardDirection, boolean caseSensitive) { assert mNativeFindInPageBridge != 0; - nativeStartFinding(mNativeFindInPageBridge, searchString, forwardDirection, caseSensitive); + FindInPageBridgeJni.get().startFinding(mNativeFindInPageBridge, FindInPageBridge.this, + searchString, forwardDirection, caseSensitive); } /** @@ -43,7 +46,8 @@ */ public void activateFindInPageResultForAccessibility() { assert mNativeFindInPageBridge != 0; - nativeActivateFindInPageResultForAccessibility(mNativeFindInPageBridge); + FindInPageBridgeJni.get().activateFindInPageResultForAccessibility( + mNativeFindInPageBridge, FindInPageBridge.this); } /** @@ -52,19 +56,22 @@ * */ public void stopFinding(boolean clearSelection) { assert mNativeFindInPageBridge != 0; - nativeStopFinding(mNativeFindInPageBridge, clearSelection); + FindInPageBridgeJni.get().stopFinding( + mNativeFindInPageBridge, FindInPageBridge.this, clearSelection); } /** Returns the most recent find text before the current one. */ public String getPreviousFindText() { assert mNativeFindInPageBridge != 0; - return nativeGetPreviousFindText(mNativeFindInPageBridge); + return FindInPageBridgeJni.get().getPreviousFindText( + mNativeFindInPageBridge, FindInPageBridge.this); } /** Asks the renderer to send the bounding boxes of current find matches. */ public void requestFindMatchRects(int currentVersion) { assert mNativeFindInPageBridge != 0; - nativeRequestFindMatchRects(mNativeFindInPageBridge, currentVersion); + FindInPageBridgeJni.get().requestFindMatchRects( + mNativeFindInPageBridge, FindInPageBridge.this, currentVersion); } /** @@ -73,26 +80,24 @@ */ public void activateNearestFindResult(float x, float y) { assert mNativeFindInPageBridge != 0; - nativeActivateNearestFindResult(mNativeFindInPageBridge, x, y); + FindInPageBridgeJni.get().activateNearestFindResult( + mNativeFindInPageBridge, FindInPageBridge.this, x, y); } - private native long nativeInit(WebContents webContents); - - private native void nativeDestroy(long nativeFindInPageBridge); - - private native void nativeStartFinding(long nativeFindInPageBridge, String searchString, - boolean forwardDirection, boolean caseSensitive); - - private native void nativeStopFinding(long nativeFindInPageBridge, boolean clearSelection); - - private native String nativeGetPreviousFindText(long nativeFindInPageBridge); - - private native void nativeRequestFindMatchRects( - long nativeFindInPageBridge, int currentVersion); - - private native void nativeActivateNearestFindResult( - long nativeFindInPageBridge, float x, float y); - - private native void nativeActivateFindInPageResultForAccessibility( - long nativeFindInPageBridge); + @NativeMethods + interface Natives { + long init(FindInPageBridge caller, WebContents webContents); + void destroy(long nativeFindInPageBridge, FindInPageBridge caller); + void startFinding(long nativeFindInPageBridge, FindInPageBridge caller, String searchString, + boolean forwardDirection, boolean caseSensitive); + void stopFinding( + long nativeFindInPageBridge, FindInPageBridge caller, boolean clearSelection); + String getPreviousFindText(long nativeFindInPageBridge, FindInPageBridge caller); + void requestFindMatchRects( + long nativeFindInPageBridge, FindInPageBridge caller, int currentVersion); + void activateNearestFindResult( + long nativeFindInPageBridge, FindInPageBridge caller, float x, float y); + void activateFindInPageResultForAccessibility( + long nativeFindInPageBridge, FindInPageBridge caller); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/init/ProcessInitializationHandler.java b/chrome/android/java/src/org/chromium/chrome/browser/init/ProcessInitializationHandler.java index a82699d3..d3a9e6b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/init/ProcessInitializationHandler.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/init/ProcessInitializationHandler.java
@@ -73,6 +73,7 @@ import org.chromium.chrome.browser.searchwidget.SearchWidgetProvider; import org.chromium.chrome.browser.services.GoogleServicesManager; import org.chromium.chrome.browser.share.ShareHelper; +import org.chromium.chrome.browser.sharing.shared_clipboard.SharedClipboardShareActivity; import org.chromium.chrome.browser.sync.SyncController; import org.chromium.chrome.browser.util.ConversionUtils; import org.chromium.chrome.browser.util.FeatureUtilities; @@ -444,6 +445,9 @@ deferredStartupHandler.addDeferredTask( () -> IncognitoTabLauncher.updateComponentEnabledState()); + + deferredStartupHandler.addDeferredTask( + () -> SharedClipboardShareActivity.updateComponentEnabledState()); } private void initChannelsAsync() {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationConstants.java b/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationConstants.java index fe5fb6c4..f23f448 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationConstants.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationConstants.java
@@ -101,9 +101,14 @@ public static final int NOTIFICATION_ID_CLICK_TO_CALL = 9; /** - * Unique identifier for Shared Clipboard notifications. + * Unique identifier for Shared Clipboard incoming notifications. */ - public static final int NOTIFICATION_ID_SHARED_CLIPBOARD = 10; + public static final int NOTIFICATION_ID_SHARED_CLIPBOARD_INCOMING = 10; + + /** + * Unique identifier for Shared Clipboard outgoing notifications. + */ + public static final int NOTIFICATION_ID_SHARED_CLIPBOARD_OUTGOING = 11; /** * Separator used to separate the notification origin from additional data such as the
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationUmaTracker.java b/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationUmaTracker.java index 0b6a2ce6..23e6435b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationUmaTracker.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationUmaTracker.java
@@ -111,8 +111,10 @@ int WEB_APP_ACTION_OPEN_IN_CHROME = 8; // Setting button in offline content suggestion notification. int OFFLINE_CONTENT_SUGGESTION_SETTINGS = 9; + // Dismiss button on sharing notification. + int SHARING_DISMISS = 10; - int NUM_ENTRIES = 10; + int NUM_ENTRIES = 11; } private static final String LAST_SHOWN_NOTIFICATION_TYPE_KEY =
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ntp/cards/NewTabPageAdapter.java b/chrome/android/java/src/org/chromium/chrome/browser/ntp/cards/NewTabPageAdapter.java index bca423e..e786351 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ntp/cards/NewTabPageAdapter.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ntp/cards/NewTabPageAdapter.java
@@ -113,8 +113,7 @@ mFooter = new Footer(); int sectionDelay = ChromeFeatureList.getFieldTrialParamByFeatureAsInt( - ChromeFeatureList.INTEREST_FEED_CONTENT_SUGGESTIONS, - "artificial_legacy_ntp_delay_ms", 0); + ChromeFeatureList.NTP_ARTICLE_SUGGESTIONS, "artificial_legacy_ntp_delay_ms", 0); Runnable addSectionAndFooter = () -> { mRoot.addChildren(mSections); mRoot.addChildren(mFooter);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/password/SavePasswordsPreferences.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/password/SavePasswordsPreferences.java index a4cfec2..fe1243fd 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/password/SavePasswordsPreferences.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/password/SavePasswordsPreferences.java
@@ -34,6 +34,7 @@ import org.chromium.chrome.browser.preferences.PreferencesLauncher; import org.chromium.chrome.browser.preferences.SearchUtils; import org.chromium.chrome.browser.preferences.TextMessagePreference; +import org.chromium.components.signin.ChromeSigninController; import org.chromium.ui.text.SpanApplier; import java.util.Locale; @@ -72,8 +73,8 @@ private static final String PREF_KEY_SAVED_PASSWORDS_NO_TEXT = "saved_passwords_no_text"; private static final int ORDER_SWITCH = 0; - private static final int ORDER_AUTO_SIGNIN_CHECKBOX = 1; - private static final int ORDER_AUTO_LEAK_DETECTION_SWITCH = 2; + private static final int ORDER_AUTO_LEAK_DETECTION_SWITCH = 1; + private static final int ORDER_AUTO_SIGNIN_CHECKBOX = 2; private static final int ORDER_MANAGE_ACCOUNT_LINK = 3; private static final int ORDER_SAVED_PASSWORDS = 4; private static final int ORDER_EXCEPTIONS = 5; @@ -209,8 +210,13 @@ getPreferenceScreen().removeAll(); if (mSearchQuery == null) { createSavePasswordsSwitch(); + + ChromeSigninController signInController = ChromeSigninController.get(); + if (signInController != null && signInController.isSignedIn()) { + createAutoLeakDetectionSwitch(); + } + createAutoSignInCheckbox(); - createAutoLeakDetectionSwitch(); } PasswordManagerHandlerProvider.getInstance() .getPasswordManagerHandler() @@ -440,9 +446,9 @@ mAutoLeakDetectionSwitch = new ChromeSwitchPreference(getStyledContext(), null); mAutoLeakDetectionSwitch.setKey(PREF_LEAK_DETECTION_SWITCH); - // TODO(crbug.com/986317): Add description and update title. mAutoLeakDetectionSwitch.setTitle(R.string.passwords_leak_detection_switch_title); mAutoLeakDetectionSwitch.setOrder(ORDER_AUTO_LEAK_DETECTION_SWITCH); + mAutoLeakDetectionSwitch.setSummary(R.string.passwords_leak_detection_switch_description); mAutoLeakDetectionSwitch.setOnPreferenceChangeListener((preference, newValue) -> { PrefServiceBridge.getInstance().setPasswordLeakDetectionEnabled((boolean) newValue); return true;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/sharing/SharingAdapter.java b/chrome/android/java/src/org/chromium/chrome/browser/sharing/SharingAdapter.java new file mode 100644 index 0000000..bbbe188 --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/sharing/SharingAdapter.java
@@ -0,0 +1,101 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.sharing; + +import android.content.Context; +import android.content.res.Resources; +import android.graphics.drawable.Drawable; +import android.support.v7.content.res.AppCompatResources; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.BaseAdapter; +import android.widget.TextView; + +import org.chromium.chrome.R; +import org.chromium.chrome.browser.sharing.SharingServiceProxy.DeviceInfo; +import org.chromium.ui.widget.ChromeImageView; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.concurrent.TimeUnit; + +/** + * Adapter to populate the Sharing Device Picker sheet. + */ +public class SharingAdapter extends BaseAdapter { + private final ArrayList<DeviceInfo> mTargetDevices; + + public SharingAdapter(int capabilities) { + mTargetDevices = SharingServiceProxy.getInstance().getDeviceCandidates(capabilities); + } + + @Override + public int getCount() { + return mTargetDevices.size(); + } + + @Override + public DeviceInfo getItem(int position) { + return mTargetDevices.get(position); + } + + @Override + public long getItemId(int position) { + return position; + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + if (convertView == null) { + final Context context = parent.getContext(); + convertView = LayoutInflater.from(context).inflate( + R.layout.send_tab_to_self_device_picker_item, parent, false); + + DeviceInfo deviceInfo = getItem(position); + ChromeImageView deviceIcon = convertView.findViewById(R.id.device_icon); + deviceIcon.setImageDrawable(getDrawableForDeviceType(context, deviceInfo)); + deviceIcon.setVisibility(View.VISIBLE); + + TextView deviceName = convertView.findViewById(R.id.device_name); + deviceName.setText(deviceInfo.clientName); + + TextView lastActive = convertView.findViewById(R.id.last_active); + + long numDaysDeviceActive = + TimeUnit.MILLISECONDS.toDays(Calendar.getInstance().getTimeInMillis() + - deviceInfo.lastUpdatedTimestampMilliseconds); + lastActive.setText(getLastActiveMessage(context.getResources(), numDaysDeviceActive)); + } + return convertView; + } + + private static String getLastActiveMessage(Resources resources, long numDays) { + if (numDays < 1) { + return resources.getString(R.string.send_tab_to_self_device_last_active_today); + } else if (numDays == 1) { + return resources.getString(R.string.send_tab_to_self_device_last_active_one_day_ago); + } else { + return resources.getString( + R.string.send_tab_to_self_device_last_active_more_than_one_day, numDays); + } + } + + private static Drawable getDrawableForDeviceType(Context context, DeviceInfo targetDevice) { + switch (targetDevice.deviceType) { + case TYPE_CROS: + case TYPE_LINUX: + case TYPE_MAC: + case TYPE_WIN: { + return AppCompatResources.getDrawable(context, R.drawable.computer_black_24dp); + } + case TYPE_PHONE: { + return AppCompatResources.getDrawable(context, R.drawable.smartphone_black_24dp); + } + default: + return AppCompatResources.getDrawable(context, R.drawable.devices_black_24dp); + } + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/sharing/SharingNotificationUtil.java b/chrome/android/java/src/org/chromium/chrome/browser/sharing/SharingNotificationUtil.java index 1fc83c8..4e9fee7 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/sharing/SharingNotificationUtil.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/sharing/SharingNotificationUtil.java
@@ -5,7 +5,10 @@ package org.chromium.chrome.browser.sharing; import android.app.Notification; +import android.app.PendingIntent; +import android.content.BroadcastReceiver; import android.content.Context; +import android.content.Intent; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; @@ -25,21 +28,50 @@ import org.chromium.chrome.browser.notifications.PendingIntentProvider; import org.chromium.chrome.browser.notifications.channels.ChannelDefinitions; +import java.util.HashSet; + /** * Provides common functionality for handling sharing notifications. */ public final class SharingNotificationUtil { + private static final String EXTRA_NOTIFICATION_TAG = "notification_tag"; + private static final String EXTRA_NOTIFICATION_ID = "notification_id"; + private static final String EXTRA_NOTIFICATION_TOKEN = "notification_token"; + private static final int REQUEST_CODE_DISMISS = 100; + + private static HashSet<Integer> sDismissedSendingNotifications = new HashSet<>(); + private static int sSendingNotificationCount; + + /** + * Handles the action of a notification. + */ + public static final class ActionReceiver extends BroadcastReceiver { + @Override + public void onReceive(Context context, Intent intent) { + // Currently only dismiss is supported. + String tag = intent.getStringExtra(EXTRA_NOTIFICATION_TAG); + int id = intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1); + int token = intent.getIntExtra(EXTRA_NOTIFICATION_TOKEN, -1); + if (tag == null || id == -1 || token == -1) { + return; + } + + new NotificationManagerProxyImpl(context).cancel(tag, id); + sDismissedSendingNotifications.add(token); + } + } + /** * Shows a notification with a configuration common to all sharing notifications. * - * @param type The type of notification. - * @param group The notification group. - * @param id The notification id. + * @param type The type of notification. + * @param group The notification group. + * @param id The notification id. * @param contentIntent The notification content intent. - * @param contentTitle The notification title text. - * @param contentText The notification content text. - * @param smallIconId The small notification icon resource id. - * @param largeIconId The large notification icon resource id, 0 if not used. + * @param contentTitle The notification title text. + * @param contentText The notification content text. + * @param smallIconId The small notification icon resource id. + * @param largeIconId The large notification icon resource id, 0 if not used. */ public static void showNotification(@SystemNotificationType int type, String group, int id, PendingIntentProvider contentIntent, String contentTitle, String contentText, @@ -79,5 +111,103 @@ new NotificationManagerProxyImpl(context).cancel(tag, notificationId); } + /** + * Shows a notification for sending outgoing Sharing messages. + * + * @param type The type of notification. + * @param group The notification group. + * @param id The notification id. + * @param targetName The name of target device + * @return token of notification created to be used to call {@link #showSendErrorNotification} + */ + public static int showSendingNotification( + @SystemNotificationType int type, String group, int id, String targetName) { + int token = sSendingNotificationCount; + sSendingNotificationCount++; + + Context context = ContextUtils.getApplicationContext(); + Resources resources = context.getResources(); + PendingIntentProvider dismissIntent = + PendingIntentProvider.getBroadcast(context, REQUEST_CODE_DISMISS, + new Intent(context, ActionReceiver.class) + .putExtra(EXTRA_NOTIFICATION_TAG, group) + .putExtra(EXTRA_NOTIFICATION_ID, id) + .putExtra(EXTRA_NOTIFICATION_TOKEN, token), + PendingIntent.FLAG_UPDATE_CURRENT); + String contentTitle = + resources.getString(R.string.sharing_sending_notification_title, targetName); + String dismissTitle = resources.getString(R.string.sharing_dismiss_action); + ChromeNotificationBuilder builder = + NotificationBuilderFactory + .createChromeNotificationBuilder(/*preferCompat=*/true, + ChannelDefinitions.ChannelId.SHARING, + /*remoteAppPackageName=*/null, + new NotificationMetadata(type, group, id)) + .setContentTitle(contentTitle) + .setGroup(group) + .setColor(ApiCompatibilityUtils.getColor( + context.getResources(), R.color.default_icon_color_blue)) + .setPriorityBeforeO(NotificationCompat.PRIORITY_HIGH) + .setVibrate(new long[0]) + .setSmallIcon(R.drawable.ic_devices_16dp) + .setProgress(/*max=*/0, /*percentage=*/0, true) + .setOngoing(true) + .addAction(R.drawable.ic_cancel_circle, dismissTitle, dismissIntent, + NotificationUmaTracker.ActionType.SHARING_DISMISS) + .setDefaults(Notification.DEFAULT_ALL); + ChromeNotification notification = builder.buildChromeNotification(); + + new NotificationManagerProxyImpl(context).notify(notification); + NotificationUmaTracker.getInstance().onNotificationShown( + type, notification.getNotification()); + + return token; + } + + /** + * Shows a notification for displaying error after sending outgoing Sharing message. + * + * @param type The type of notification. + * @param group The notification group. + * @param id The notification id. + * @param contentNameId ResId of content name. + * @param token Token returned from {@link #showSendingNotification} + * @param result Result of sending Sharing message. + */ + public static void showSendErrorNotification(@SystemNotificationType int type, String group, + int id, int contentNameId, int token, @SharingSendMessageResult int result) { + if (sDismissedSendingNotifications.remove(token)) { + return; + } + + Context context = ContextUtils.getApplicationContext(); + Resources resources = context.getResources(); + // TODO(crbug/996322): Show error message base on |result|. + String contentName = resources.getString(contentNameId); + String contentTitle = resources.getString( + R.string.sharing_internal_error_notification_title, contentName); + String contentText = resources.getString(R.string.sharing_internal_error_notification_text); + ChromeNotificationBuilder builder = + NotificationBuilderFactory + .createChromeNotificationBuilder(/*preferCompat=*/true, + ChannelDefinitions.ChannelId.SHARING, + /*remoteAppPackageName=*/null, + new NotificationMetadata(type, group, id)) + .setContentTitle(contentTitle) + .setGroup(group) + .setColor(ApiCompatibilityUtils.getColor( + context.getResources(), R.color.google_red_600)) + .setPriorityBeforeO(NotificationCompat.PRIORITY_HIGH) + .setVibrate(new long[0]) + .setSmallIcon(R.drawable.ic_error_outline_red_24dp) + .setContentText(contentText) + .setDefaults(Notification.DEFAULT_ALL); + ChromeNotification notification = builder.buildChromeNotification(); + + new NotificationManagerProxyImpl(context).notify(notification); + NotificationUmaTracker.getInstance().onNotificationShown( + type, notification.getNotification()); + } + private SharingNotificationUtil() {} }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/sharing/shared_clipboard/SharedClipboardMessageHandler.java b/chrome/android/java/src/org/chromium/chrome/browser/sharing/shared_clipboard/SharedClipboardMessageHandler.java index 7202eec..3f23942 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/sharing/shared_clipboard/SharedClipboardMessageHandler.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/sharing/shared_clipboard/SharedClipboardMessageHandler.java
@@ -50,7 +50,7 @@ SharingNotificationUtil.showNotification( NotificationUmaTracker.SystemNotificationType.SHARED_CLIPBOARD, NotificationConstants.GROUP_SHARED_CLIPBOARD, - NotificationConstants.NOTIFICATION_ID_SHARED_CLIPBOARD, contentIntent, + NotificationConstants.NOTIFICATION_ID_SHARED_CLIPBOARD_INCOMING, contentIntent, notificationTitle, resources.getString(R.string.shared_clipboard_notification_text), R.drawable.ic_devices_16dp, R.drawable.shared_clipboard_40dp); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/sharing/shared_clipboard/SharedClipboardShareActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/sharing/shared_clipboard/SharedClipboardShareActivity.java new file mode 100644 index 0000000..ced49fc --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/sharing/shared_clipboard/SharedClipboardShareActivity.java
@@ -0,0 +1,136 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.sharing.shared_clipboard; + +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.view.View; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemClickListener; +import android.widget.ListView; +import android.widget.TextView; + +import org.chromium.base.ContextUtils; +import org.chromium.base.ThreadUtils; +import org.chromium.base.task.PostTask; +import org.chromium.base.task.TaskTraits; +import org.chromium.chrome.R; +import org.chromium.chrome.browser.ChromeFeatureList; +import org.chromium.chrome.browser.init.AsyncInitializationActivity; +import org.chromium.chrome.browser.notifications.NotificationConstants; +import org.chromium.chrome.browser.notifications.NotificationUmaTracker; +import org.chromium.chrome.browser.sharing.SharingAdapter; +import org.chromium.chrome.browser.sharing.SharingDeviceCapability; +import org.chromium.chrome.browser.sharing.SharingNotificationUtil; +import org.chromium.chrome.browser.sharing.SharingSendMessageResult; +import org.chromium.chrome.browser.sharing.SharingServiceProxy; +import org.chromium.chrome.browser.sharing.SharingServiceProxy.DeviceInfo; + +/** + * Activity to display device targets to share text. + */ +public class SharedClipboardShareActivity + extends AsyncInitializationActivity implements OnItemClickListener { + private SharingAdapter mAdapter; + private ListView mListView; + + /** + * Checks whether sending shared clipboard message is enabled for the user and enables/disables + * the SharedClipboardShareActivity appropriately. This call requires native to be loaded. + */ + public static void updateComponentEnabledState() { + boolean enabled = ChromeFeatureList.isEnabled(ChromeFeatureList.SHARED_CLIPBOARD_UI); + PostTask.postTask(TaskTraits.USER_VISIBLE, () -> setComponentEnabled(enabled)); + } + + /** + * Sets whether or not the SharedClipboardShareActivity should be enabled. This may trigger a + * StrictMode violation so shouldn't be called on the UI thread. + */ + private static void setComponentEnabled(boolean enabled) { + ThreadUtils.assertOnBackgroundThread(); + Context context = ContextUtils.getApplicationContext(); + PackageManager packageManager = context.getPackageManager(); + ComponentName componentName = + new ComponentName(context, SharedClipboardShareActivity.class); + + int newState = enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED + : PackageManager.COMPONENT_ENABLED_STATE_DISABLED; + + // This indicates that we don't want to kill Chrome when changing component enabled state. + int flags = PackageManager.DONT_KILL_APP; + + if (packageManager.getComponentEnabledSetting(componentName) != newState) { + packageManager.setComponentEnabledSetting(componentName, newState, flags); + } + } + + @Override + protected void triggerLayoutInflation() { + setContentView(R.layout.sharing_device_picker); + + View mask = findViewById(R.id.mask); + mask.setOnClickListener(v -> finish()); + + TextView toolbarText = findViewById(R.id.device_picker_toolbar); + toolbarText.setText(R.string.send_tab_to_self_sheet_toolbar); + + mListView = findViewById(R.id.device_picker_list); + mListView.setAdapter(mAdapter); + mListView.setOnItemClickListener(this); + mListView.setEmptyView(findViewById(android.R.id.empty)); + + onInitialLayoutInflationComplete(); + } + + @Override + public void finishNativeInitialization() { + super.finishNativeInitialization(); + + mAdapter = new SharingAdapter(SharingDeviceCapability.SHARED_CLIPBOARD); + mListView.setAdapter(mAdapter); + } + + @Override + public boolean shouldStartGpuProcess() { + return false; + } + + @Override + public void onItemClick(AdapterView<?> parent, View view, int position, long id) { + DeviceInfo device = mAdapter.getItem(position); + + String text = getIntent().getStringExtra(Intent.EXTRA_TEXT); + + int token = SharingNotificationUtil.showSendingNotification( + NotificationUmaTracker.SystemNotificationType.SHARED_CLIPBOARD, + NotificationConstants.GROUP_SHARED_CLIPBOARD, + NotificationConstants.NOTIFICATION_ID_SHARED_CLIPBOARD_OUTGOING, device.clientName); + + SharingServiceProxy.getInstance().sendSharedClipboardMessage(device.guid, text, result -> { + if (result == SharingSendMessageResult.SUCCESSFUL) { + SharingNotificationUtil.dismissNotification( + NotificationConstants.GROUP_SHARED_CLIPBOARD, + NotificationConstants.NOTIFICATION_ID_SHARED_CLIPBOARD_OUTGOING); + } else { + SharingNotificationUtil.showSendErrorNotification( + NotificationUmaTracker.SystemNotificationType.SHARED_CLIPBOARD, + NotificationConstants.GROUP_SHARED_CLIPBOARD, + NotificationConstants.NOTIFICATION_ID_SHARED_CLIPBOARD_OUTGOING, + R.string.shared_clipboard_content_name, token, result); + } + }); + finish(); + } + + @Override + public void finish() { + super.finish(); + // TODO(alexchau): Handle animations. + overridePendingTransition(R.anim.no_anim, R.anim.no_anim); + } +}
diff --git a/chrome/android/java/strings/android_chrome_strings.grd b/chrome/android/java/strings/android_chrome_strings.grd index dfcca4d6..92d8ea9 100644 --- a/chrome/android/java/strings/android_chrome_strings.grd +++ b/chrome/android/java/strings/android_chrome_strings.grd
@@ -556,9 +556,12 @@ <message name="IDS_PASSWORDS_AUTO_SIGNIN_DESCRIPTION" desc="Text under 'Auto sign-in' checkbox"> Automatically sign in to websites using stored credentials. When the feature is off, you’ll be asked for verification every time before signing in to a website. </message> - <message name="IDS_PASSWORDS_LEAK_DETECTION_SWITCH_TITLE" desc="Title for the switch togglingwhether Chrome should check that entered credentials have been part of a leak."> + <message name="IDS_PASSWORDS_LEAK_DETECTION_SWITCH_TITLE" desc="Title for the switch toggling whether Chrome should check that entered credentials have been part of a leak."> Check password safety </message> + <message name="IDS_PASSWORDS_LEAK_DETECTION_SWITCH_DESCRIPTION" desc="Description for the switch toggling whether Chrome should check that entered credentials have been part of a leak."> + Warns you if a password you use was part of a data breach + </message> <message name="IDS_SECTION_SAVED_PASSWORDS_EXCEPTIONS" desc="Header for the list of websites for which user selected to never save passwords. [CHAR-LIMIT=32]"> Never saved </message> @@ -3870,6 +3873,23 @@ Active today </message> + <!-- Sharing --> + <message name="IDS_SHARING_SENDING_NOTIFICATION_TITLE" desc="Title text displayed in a sharing sending notification."> + Sharing to <ph name="DEVICE_NAME">%1$s<ex>Pixel 3</ex></ph> + </message> + <message name="IDS_SHARING_INTERNAL_ERROR_NOTIFICATION_TITLE" desc="Title text displayed in a sharing sending error notification for internal error."> + Can't share <ph name="CONTENT_NAME">%1$s<ex>text</ex></ph> + </message> + <message name="IDS_SHARING_INTERNAL_ERROR_NOTIFICATION_TEXT" desc="Content text displayed in a sharing sending error notification for internal error."> + Something went wrong. Try again later + </message> + <message name="IDS_SHARING_DISMISS_ACTION" desc="Text for action that dismiss a sharing sending notification."> + Dismiss + </message> + <message name="IDS_SHARING_DEVICE_LIST_EMPTY" desc="Text to shown when no device targets are available for sharing."> + No devices available. + </message> + <!-- ClickToCall --> <message name="IDS_CLICK_TO_CALL_NOTIFICATION_TEXT" desc="Text displayed in a click to call notification."> Tap to make call @@ -3885,6 +3905,12 @@ <message name="IDS_SHARED_CLIPBOARD_NOTIFICATION_TEXT" desc="Content text displayed in a shared clipboard notification."> Copied to your clipboard </message> + <message name="IDS_SHARED_CLIPBOARD_SHARE_ACTIVITY_TITLE" desc="Title of the Shared Clipboard Share activity that will appear in the Android share dialog."> + Send text to Your Devices + </message> + <message name="IDS_SHARED_CLIPBOARD_CONTENT_NAME" desc="Name of shared clipboard content in a shared clipboard notification."> + text + </message> <!-- Chrome Duet --> <message name="IDS_IPH_DUET_TITLE" desc="This string appears in an overlay that explains a new UI to users. 'Search' refers to searching the web, and 'explore' refers to Chrome's suggested content.">
diff --git a/chrome/android/java/strings/android_chrome_strings_grd/IDS_PASSWORDS_LEAK_DETECTION_SWITCH_DESCRIPTION.png.sha1 b/chrome/android/java/strings/android_chrome_strings_grd/IDS_PASSWORDS_LEAK_DETECTION_SWITCH_DESCRIPTION.png.sha1 new file mode 100644 index 0000000..773117e5 --- /dev/null +++ b/chrome/android/java/strings/android_chrome_strings_grd/IDS_PASSWORDS_LEAK_DETECTION_SWITCH_DESCRIPTION.png.sha1
@@ -0,0 +1 @@ +4ce3fc0c7ec4f132ea462f09e7f2986266c05000 \ No newline at end of file
diff --git a/chrome/android/java/strings/android_chrome_strings_grd/IDS_PASSWORDS_LEAK_DETECTION_SWITCH_TITLE.png.sha1 b/chrome/android/java/strings/android_chrome_strings_grd/IDS_PASSWORDS_LEAK_DETECTION_SWITCH_TITLE.png.sha1 index 642279b..773117e5 100644 --- a/chrome/android/java/strings/android_chrome_strings_grd/IDS_PASSWORDS_LEAK_DETECTION_SWITCH_TITLE.png.sha1 +++ b/chrome/android/java/strings/android_chrome_strings_grd/IDS_PASSWORDS_LEAK_DETECTION_SWITCH_TITLE.png.sha1
@@ -1 +1 @@ -feb1d516f50af8ba55ff6753762220dca3ab18ab \ No newline at end of file +4ce3fc0c7ec4f132ea462f09e7f2986266c05000 \ No newline at end of file
diff --git a/chrome/android/java/strings/android_chrome_strings_grd/IDS_SHARED_CLIPBOARD_CONTENT_NAME.png.sha1 b/chrome/android/java/strings/android_chrome_strings_grd/IDS_SHARED_CLIPBOARD_CONTENT_NAME.png.sha1 new file mode 100644 index 0000000..92103c3 --- /dev/null +++ b/chrome/android/java/strings/android_chrome_strings_grd/IDS_SHARED_CLIPBOARD_CONTENT_NAME.png.sha1
@@ -0,0 +1 @@ +1bfc321b7c10a264017654332d7e344b6aec8342 \ No newline at end of file
diff --git a/chrome/android/java/strings/android_chrome_strings_grd/IDS_SHARED_CLIPBOARD_SHARE_ACTIVITY_TITLE.png.sha1 b/chrome/android/java/strings/android_chrome_strings_grd/IDS_SHARED_CLIPBOARD_SHARE_ACTIVITY_TITLE.png.sha1 new file mode 100644 index 0000000..e2d7b47a --- /dev/null +++ b/chrome/android/java/strings/android_chrome_strings_grd/IDS_SHARED_CLIPBOARD_SHARE_ACTIVITY_TITLE.png.sha1
@@ -0,0 +1 @@ +9d42550f98b9c77cc3fc9e56a49e7b63eb7a13e7 \ No newline at end of file
diff --git a/chrome/android/java/strings/android_chrome_strings_grd/IDS_SHARING_DEVICE_LIST_EMPTY.png.sha1 b/chrome/android/java/strings/android_chrome_strings_grd/IDS_SHARING_DEVICE_LIST_EMPTY.png.sha1 new file mode 100644 index 0000000..a6b3a78 --- /dev/null +++ b/chrome/android/java/strings/android_chrome_strings_grd/IDS_SHARING_DEVICE_LIST_EMPTY.png.sha1
@@ -0,0 +1 @@ +cce81a441bd0548b3eb6e1a775e6325987350935 \ No newline at end of file
diff --git a/chrome/android/java/strings/android_chrome_strings_grd/IDS_SHARING_DISMISS_ACTION.png.sha1 b/chrome/android/java/strings/android_chrome_strings_grd/IDS_SHARING_DISMISS_ACTION.png.sha1 new file mode 100644 index 0000000..a79552b --- /dev/null +++ b/chrome/android/java/strings/android_chrome_strings_grd/IDS_SHARING_DISMISS_ACTION.png.sha1
@@ -0,0 +1 @@ +da0b6aa681f1f02735f8b1f355c734a8c2e8f58e \ No newline at end of file
diff --git a/chrome/android/java/strings/android_chrome_strings_grd/IDS_SHARING_INTERNAL_ERROR_NOTIFICATION_TEXT.png.sha1 b/chrome/android/java/strings/android_chrome_strings_grd/IDS_SHARING_INTERNAL_ERROR_NOTIFICATION_TEXT.png.sha1 new file mode 100644 index 0000000..92103c3 --- /dev/null +++ b/chrome/android/java/strings/android_chrome_strings_grd/IDS_SHARING_INTERNAL_ERROR_NOTIFICATION_TEXT.png.sha1
@@ -0,0 +1 @@ +1bfc321b7c10a264017654332d7e344b6aec8342 \ No newline at end of file
diff --git a/chrome/android/java/strings/android_chrome_strings_grd/IDS_SHARING_INTERNAL_ERROR_NOTIFICATION_TITLE.png.sha1 b/chrome/android/java/strings/android_chrome_strings_grd/IDS_SHARING_INTERNAL_ERROR_NOTIFICATION_TITLE.png.sha1 new file mode 100644 index 0000000..92103c3 --- /dev/null +++ b/chrome/android/java/strings/android_chrome_strings_grd/IDS_SHARING_INTERNAL_ERROR_NOTIFICATION_TITLE.png.sha1
@@ -0,0 +1 @@ +1bfc321b7c10a264017654332d7e344b6aec8342 \ No newline at end of file
diff --git a/chrome/android/java/strings/android_chrome_strings_grd/IDS_SHARING_SENDING_NOTIFICATION_TITLE.png.sha1 b/chrome/android/java/strings/android_chrome_strings_grd/IDS_SHARING_SENDING_NOTIFICATION_TITLE.png.sha1 new file mode 100644 index 0000000..4bb6e731 --- /dev/null +++ b/chrome/android/java/strings/android_chrome_strings_grd/IDS_SHARING_SENDING_NOTIFICATION_TITLE.png.sha1
@@ -0,0 +1 @@ +bdf2eee6629e5bc1210df06d2fbd2a44ef7e6cad \ No newline at end of file
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java index 6a073613..cb32db9 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java
@@ -720,22 +720,6 @@ } /** - * Asserts that the tap triggered promo counter is enabled and at the specified count. - */ - private void assertTapPromoCounterEnabledAt(int expectedCount) { - Assert.assertTrue(mPolicy.getPromoTapCounter().isEnabled()); - Assert.assertEquals(expectedCount, mPolicy.getPromoTapCounter().getCount()); - } - - /** - * Asserts that the tap triggered promo counter is disabled and at the specified count. - */ - private void assertTapPromoCounterDisabledAt(int expectedCount) { - Assert.assertFalse(mPolicy.getPromoTapCounter().isEnabled()); - Assert.assertEquals(expectedCount, mPolicy.getPromoTapCounter().getCount()); - } - - /** * Waits for the Search Panel (the Search Bar) to peek up from the bottom, and asserts that it * did peek. * @throws InterruptedException @@ -3268,4 +3252,56 @@ RecordHistogram.getHistogramValueCountForTesting( "Search.ContextualSearch.OutcomesDuration", 0)); } + + // -------------------------------------------------------------------------------------------- + // Longpress-resolve Feature tests. + // -------------------------------------------------------------------------------------------- + @Test + @SmallTest + @Feature({"ContextualSearch"}) + @Features.EnableFeatures("ContextualSearchLongpressResolve") + public void testTapIsIgnoredWithLongpressResolveEnabled() + throws InterruptedException, TimeoutException { + clickNode("states"); + Assert.assertNull(getSelectedText()); + assertPanelClosedOrUndefined(); + assertLoadedNoUrl(); + } + + @Test + @SmallTest + @Feature({"ContextualSearch"}) + @CommandLineFlags.Add({"enable-features=ContextualSearchLongpressResolve<FakeStudyName", + "force-fieldtrials=FakeStudyName/FakeGroup", + "force-fieldtrial-params=FakeStudyName.FakeGroup:longpress_resolve_variation/" + + ContextualSearchFieldTrial.LONGPRESS_RESOLVE_PRESERVE_TAP}) + public void + testTapNotIgnoredWithLongpressResolveEnabledAndVariationPreserveTap() + throws InterruptedException, TimeoutException { + clickWordNode("states"); + Assert.assertEquals("States", getSelectedText()); + waitForPanelToPeek(); + } + + @Test + @SmallTest + @Feature({"ContextualSearch"}) + @CommandLineFlags.Add({"enable-features=ContextualSearchLongpressResolve<FakeStudyName", + "force-fieldtrials=FakeStudyName/FakeGroup", + "force-fieldtrial-params=FakeStudyName.FakeGroup:longpress_resolve_variation/" + + ContextualSearchFieldTrial.LONGPRESS_RESOLVE_PRIVACY_AGGRESSIVE}) + public void + testLongpressResolvesWithLongpressResolveEnabledAndVariationPrivacyAggressive() + throws InterruptedException, TimeoutException { + mPolicy.overrideDecidedStateForTesting(false); + mFakeServer.setShouldUseHttps(true); + longPressNode("states"); + assertLoadedNoUrl(); + assertSearchTermRequested(); + + fakeResponse(false, 200, "states", "United States Intelligence", "alternate-term", false); + waitForPanelToPeek(); + assertLoadedLowPriorityUrl(); + assertContainsParameters("states", "alternate-term"); + } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/metrics/StartupLoadingMetricsTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/metrics/StartupLoadingMetricsTest.java index 12cd335..9a780b92 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/metrics/StartupLoadingMetricsTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/metrics/StartupLoadingMetricsTest.java
@@ -19,7 +19,7 @@ import org.chromium.base.Log; import org.chromium.base.compat.ApiHelperForM; -import org.chromium.base.library_loader.LibraryLoaderConfig; +import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.library_loader.LoadStatusRecorder.LoadLibraryStatus; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.test.util.CommandLineFlags; @@ -159,7 +159,7 @@ assertHistogramsRecorded(1, TABBED_SUFFIX); // LibraryLoader checks. - if (!LibraryLoaderConfig.useChromiumLinker()) { + if (!LibraryLoader.useChromiumLinker()) { Log.w(TAG, "Skipping test because not using ChromiumLinker."); return; }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/offlinepages/OfflinePageUtilsTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/offlinepages/OfflinePageUtilsTest.java index 9fc1d59..9356b35 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/offlinepages/OfflinePageUtilsTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/offlinepages/OfflinePageUtilsTest.java
@@ -482,6 +482,24 @@ savePage(SavePageResult.SUCCESS, mTestPage, clientId); } + /** + * This test checks that an offline page saved with on-the-fly hash computation enabled will + * be trusted when loaded. + */ + @Test + @MediumTest + @CommandLineFlags.Add({"enable-features=OnTheFlyMhtmlHashComputation"}) + public void testOnTheFlyProducesTrustedPage() throws Exception { + // Load the test offline page. + loadOfflinePage(SUGGESTED_ARTICLES_ID); + + // Verify that we are currently showing a trusted page. + TestThreadUtils.runOnUiThreadBlocking(() -> { + Assert.assertTrue(OfflinePageUtils.isShowingTrustedOfflinePage( + mActivityTestRule.getActivity().getActivityTab())); + }); + } + // Utility to load an offline page into the current tab. private void loadOfflinePage(ClientId clientId) throws Exception { // Start by loading a normal page, and saving an offline copy.
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/preferences/password/SavePasswordsPreferencesTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/preferences/password/SavePasswordsPreferencesTest.java index f0322f6f..eb3d6cb4 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/preferences/password/SavePasswordsPreferencesTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/preferences/password/SavePasswordsPreferencesTest.java
@@ -540,6 +540,9 @@ @Feature({"Preferences"}) @Features.EnableFeatures({SavePasswordsPreferences.PASSWORD_LEAK_DETECTION_FEATURE}) public void testLeakDetectionSwitchEnabled() throws Exception { + // The switch is only displayed for signed in users. + ChromeSigninController.get().setSignedInAccountName("Test Account"); + TestThreadUtils.runOnUiThreadBlocking( () -> { PrefServiceBridge.getInstance().setPasswordLeakDetectionEnabled(true); }); @@ -566,6 +569,9 @@ @Feature({"Preferences"}) @Features.EnableFeatures({SavePasswordsPreferences.PASSWORD_LEAK_DETECTION_FEATURE}) public void testLeakDetectionSwitchDisabled() throws Exception { + // The switch is only displayed for signed in users. + ChromeSigninController.get().setSignedInAccountName("Test Account"); + TestThreadUtils.runOnUiThreadBlocking( () -> { PrefServiceBridge.getInstance().setPasswordLeakDetectionEnabled(false); }); final Preferences preferences = @@ -579,6 +585,21 @@ Assert.assertFalse(onOffSwitch.isChecked()); } + @Test + @SmallTest + @Feature({"Preferences"}) + @Features.EnableFeatures({SavePasswordsPreferences.PASSWORD_LEAK_DETECTION_FEATURE}) + public void testLeakDetectionNonSignedIn() throws Exception { + final Preferences preferences = + PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(), + SavePasswordsPreferences.class.getName()); + SavePasswordsPreferences savedPasswordPrefs = + (SavePasswordsPreferences) preferences.getMainFragment(); + // The switch shouldn't be displayed for non signed-in users. + Assert.assertNull(savedPasswordPrefs.findPreference( + SavePasswordsPreferences.PREF_LEAK_DETECTION_SWITCH)); + } + /** * Tests that the link pointing to managing passwords in the user's account is not displayed * for non signed in users.
diff --git a/chrome/android/webapk/shell_apk/javatests/src/org/chromium/webapk/shell_apk/DexLoaderTest.java b/chrome/android/webapk/shell_apk/javatests/src/org/chromium/webapk/shell_apk/DexLoaderTest.java index 131fbc98..d5be7caf 100644 --- a/chrome/android/webapk/shell_apk/javatests/src/org/chromium/webapk/shell_apk/DexLoaderTest.java +++ b/chrome/android/webapk/shell_apk/javatests/src/org/chromium/webapk/shell_apk/DexLoaderTest.java
@@ -27,6 +27,7 @@ import org.chromium.base.FileUtils; import org.chromium.base.test.BaseJUnit4ClassRunner; import org.chromium.base.test.util.CallbackHelper; +import org.chromium.base.test.util.DisableIf; import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.MinAndroidSdkLevel; import org.chromium.webapk.shell_apk.test.dex_optimizer.IDexOptimizerService; @@ -176,6 +177,7 @@ */ @Test @MediumTest + @DisableIf.Build(sdk_is_greater_than = 25, message = "crbug.com/999363") public void testLoadFromLocalDataDir() { ClassLoader loader = mDexLoader.load( mRemoteContext, DEX_ASSET_NAME, CANARY_CLASS_NAME, null, mLocalDexDir);
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index bb1cf197..4f1d73f 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -1987,6 +1987,9 @@ <message name="IDS_ABANDON_DOWNLOAD_DIALOG_INCOGNITO_MESSAGE" desc="Message on a dialog shown when the user closes the last incognito window while one or more downloads are in progress. This string is shown on Windows, Chrome OS, and Linux, which all use 'Exit' to refer to closing a browser."> Exit incognito mode anyway? </message> + <message name="IDS_ABANDON_DOWNLOAD_DIALOG_GUEST_MESSAGE" desc="Message on a dialog shown when the user closes the last guest window while one or more downloads are in progress. This string is shown on Windows, Chrome OS, and Linux, which all use 'Exit' to refer to closing a browser."> + Exit guest mode anyway? + </message> <message name="IDS_ABANDON_DOWNLOAD_DIALOG_EXIT_BUTTON" desc="Button text on a dialog shown when the user closes the browser or the last incognito window while one or more downloads are in progress. When clicked, the button will abandon the download and exit. This string is shown on Windows, Chrome OS, and Linux, which all use 'Exit' to refer to closing a browser."> Exit </message> @@ -1995,6 +1998,9 @@ <message name="IDS_ABANDON_DOWNLOAD_DIALOG_INCOGNITO_MESSAGE" desc="Message on a dialog shown when the user closes the last incognito window while one or more downloads are in progress. This string is shown on Mac OSX only, which uses 'Quit' to refer to closing a browser."> Quit incognito mode anyway? </message> + <message name="IDS_ABANDON_DOWNLOAD_DIALOG_GUEST_MESSAGE" desc="Message on a dialog shown when the user closes the last guest window while one or more downloads are in progress. This string is shown on Mac OSX only, which uses 'Exit' to refer to closing a browser."> + Exit guest mode anyway? + </message> <message name="IDS_ABANDON_DOWNLOAD_DIALOG_EXIT_BUTTON" desc="Button text on a dialog shown when the user closes the browser or the last incognito window while one or more downloads are in progress. When clicked, the button will abandon the download and quit. This string is shown on Mac OSX only, which uses 'Quit' to refer to closing a browser."> Quit </message> @@ -6112,6 +6118,9 @@ <message name="IDS_TAB_CXMENU_REMOVE_TAB_FROM_GROUP" desc="The label of the tab context menu item for removing one or more tabs from the groups that contain them."> Remove from group </message> + <message name="IDS_TAB_CXMENU_PLACEHOLDER_GROUP_TITLE" desc="The descriptive placeholder title of a group used when the user has not explicitly named a group. The plural value refers to the number of tabs in the group other than the one explicitly named. [ICU Syntax]"> + {NUM_OTHER_TABS, plural, =0 {"<ph name="TAB_TITLE">$1<ex>Google News</ex></ph>"} =1 {"<ph name="TAB_TITLE">$1<ex>Google News</ex></ph>" and 1 other tab} other {"<ph name="TAB_TITLE">$1<ex>Google News</ex></ph>" and # other tabs}} + </message> </if> <if expr="use_titlecase"> <message name="IDS_TAB_CXMENU_RELOAD" desc="In Title Case: The label of the 'Reload' Tab context menu item."> @@ -6150,6 +6159,9 @@ <message name="IDS_TAB_CXMENU_REMOVE_TAB_FROM_GROUP" desc="In Title Case: The label of the tab context menu item for removing one or more tabs from the groups that contain them."> Remove From Group </message> + <message name="IDS_TAB_CXMENU_PLACEHOLDER_GROUP_TITLE" desc="The descriptive placeholder title of a group used when the user has not explicitly named a group. The plural value refers to the number of tabs in the group other than the one explicitly named. [ICU Syntax]"> + {NUM_OTHER_TABS, plural, =0 {"<ph name="TAB_TITLE">$1<ex>Google News</ex></ph>"} =1 {"<ph name="TAB_TITLE">$1<ex>Google News</ex></ph>" and 1 Other Tab} other {"<ph name="TAB_TITLE">$1<ex>Google News</ex></ph>" and # Other Tabs}} + </message> </if> <!-- Application window menu -->
diff --git a/chrome/app/generated_resources_grd/IDS_ABANDON_DOWNLOAD_DIALOG_GUEST_MESSAGE.png.sha1 b/chrome/app/generated_resources_grd/IDS_ABANDON_DOWNLOAD_DIALOG_GUEST_MESSAGE.png.sha1 new file mode 100644 index 0000000..eb81814 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_ABANDON_DOWNLOAD_DIALOG_GUEST_MESSAGE.png.sha1
@@ -0,0 +1 @@ +af99345df89626973e0d81dbf704dad7ed6451a9 \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_TAB_CXMENU_PLACEHOLDER_GROUP_TITLE.png.sha1 b/chrome/app/generated_resources_grd/IDS_TAB_CXMENU_PLACEHOLDER_GROUP_TITLE.png.sha1 new file mode 100644 index 0000000..aada6ae --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_TAB_CXMENU_PLACEHOLDER_GROUP_TITLE.png.sha1
@@ -0,0 +1 @@ +6e373264a3e21f79321206775dcca0899370197d \ No newline at end of file
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index e1a2071..ce15485 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -87,6 +87,7 @@ #include "components/ntp_tiles/features.h" #include "components/offline_pages/core/offline_page_feature.h" #include "components/omnibox/browser/omnibox_field_trial.h" +#include "components/omnibox/browser/zero_suggest_provider.h" #include "components/omnibox/common/omnibox_features.h" #include "components/password_manager/core/common/password_manager_features.h" #include "components/payments/core/features.h" @@ -855,6 +856,13 @@ base::size(kOmniboxDocumentProviderServerAndClientScoring), nullptr}}; #endif // defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_WIN) +const FeatureEntry::FeatureParam kOmniboxOnFocusSuggestionsParamNTPRealbox[] = { + {"ZeroSuggestVariant:15:*", ZeroSuggestProvider::kRemoteNoUrlVariant}}; +const FeatureEntry::FeatureVariation kOmniboxOnFocusSuggestionsVariations[] = { + {"NTP Realbox - Remote", kOmniboxOnFocusSuggestionsParamNTPRealbox, + base::size(kOmniboxOnFocusSuggestionsParamNTPRealbox), + "t3316133" /* variation_id */}}; + const FeatureEntry::FeatureParam kOmniboxUIMaxAutocompleteMatches3[] = { {OmniboxFieldTrial::kUIMaxAutocompleteMatchesParam, "3"}}; const FeatureEntry::FeatureParam kOmniboxUIMaxAutocompleteMatches4[] = { @@ -2682,11 +2690,6 @@ #endif // defined(OS_WIN) #if defined(OS_ANDROID) - {"omnibox-on-device-head-suggestions", - flag_descriptions::kOmniboxOnDeviceHeadSuggestionsName, - flag_descriptions::kOmniboxOnDeviceHeadSuggestionsDescription, kOsAndroid, - FEATURE_VALUE_TYPE(omnibox::kOnDeviceHeadProvider)}, - {"omnibox-search-engine-logo", flag_descriptions::kOmniboxSearchEngineLogoName, flag_descriptions::kOmniboxSearchEngineLogoDescription, kOsAndroid, @@ -2695,6 +2698,18 @@ "OmniboxSearchEngineLogo")}, #endif // defined(OS_ANDROID) + {"omnibox-on-device-head-suggestions", + flag_descriptions::kOmniboxOnDeviceHeadSuggestionsName, + flag_descriptions::kOmniboxOnDeviceHeadSuggestionsDescription, kOsAll, + FEATURE_VALUE_TYPE(omnibox::kOnDeviceHeadProvider)}, + + {"omnibox-on-focus-suggestions", + flag_descriptions::kOmniboxOnFocusSuggestionsName, + flag_descriptions::kOmniboxOnFocusSuggestionsDescription, kOsAll, + FEATURE_WITH_PARAMS_VALUE_TYPE(omnibox::kOnFocusSuggestions, + kOmniboxOnFocusSuggestionsVariations, + "OmniboxBundledExperimentV1")}, + {"omnibox-rich-entity-suggestions", flag_descriptions::kOmniboxRichEntitySuggestionsName, flag_descriptions::kOmniboxRichEntitySuggestionsDescription, kOsAll,
diff --git a/chrome/browser/android/chrome_feature_list.cc b/chrome/browser/android/chrome_feature_list.cc index 9a57a6d5f..44539bea 100644 --- a/chrome/browser/android/chrome_feature_list.cc +++ b/chrome/browser/android/chrome_feature_list.cc
@@ -13,6 +13,7 @@ #include "base/metrics/field_trial_params.h" #include "base/stl_util.h" #include "chrome/android/chrome_jni_headers/ChromeFeatureList_jni.h" +#include "chrome/browser/sharing/shared_clipboard/feature_flags.h" #include "chrome/common/chrome_features.h" #include "components/autofill/core/common/autofill_features.h" #include "components/autofill_assistant/browser/features.h" @@ -167,6 +168,7 @@ &kServiceManagerForBackgroundPrefetch, &kServiceManagerForDownload, &kSettingsModernStatusBar, + &kSharedClipboardUI, &kShoppingAssist, &kSpannableInlineAutocomplete, &kSpecialLocaleWrapper,
diff --git a/chrome/browser/chromeos/accessibility/accessibility_manager.cc b/chrome/browser/chromeos/accessibility/accessibility_manager.cc index 4ce0def..19fc56c6 100644 --- a/chrome/browser/chromeos/accessibility/accessibility_manager.cc +++ b/chrome/browser/chromeos/accessibility/accessibility_manager.cc
@@ -77,7 +77,6 @@ #include "content/public/browser/tts_controller.h" #include "content/public/browser/web_ui.h" #include "content/public/common/content_switches.h" -#include "extensions/browser/extension_registry.h" #include "extensions/common/constants.h" #include "extensions/common/extension.h" #include "extensions/common/extension_messages.h" @@ -238,26 +237,10 @@ ShowSingletonTab(browser, GURL(chrome::kChromeAccessibilityHelpURL)); } -AccessibilityManager::AccessibilityManager() - : profile_(NULL), - spoken_feedback_enabled_(false), - select_to_speak_enabled_(false), - switch_access_enabled_(false), - autoclick_enabled_(false), - braille_display_connected_(false), - scoped_braille_observer_(this), - braille_ime_current_(false), - chromevox_panel_(nullptr), - switch_access_panel_(nullptr), - extension_registry_observer_(this) { +AccessibilityManager::AccessibilityManager() { notification_registrar_.Add(this, chrome::NOTIFICATION_LOGIN_OR_LOCK_WEBUI_VISIBLE, content::NotificationService::AllSources()); - notification_registrar_.Add(this, - chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED, - content::NotificationService::AllSources()); - notification_registrar_.Add(this, chrome::NOTIFICATION_SESSION_STARTED, - content::NotificationService::AllSources()); notification_registrar_.Add(this, chrome::NOTIFICATION_PROFILE_DESTROYED, content::NotificationService::AllSources()); notification_registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING, @@ -265,6 +248,7 @@ notification_registrar_.Add(this, content::NOTIFICATION_FOCUS_CHANGED_IN_PAGE, content::NotificationService::AllSources()); input_method::InputMethodManager::Get()->AddObserver(this); + user_manager::UserManager::Get()->AddSessionStateObserver(this); ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance(); audio::SoundsManager* manager = audio::SoundsManager::Get(); @@ -347,6 +331,7 @@ false); NotifyAccessibilityStatusChanged(details); CrasAudioHandler::Get()->RemoveAudioObserver(this); + user_manager::UserManager::Get()->RemoveSessionStateObserver(this); input_method::InputMethodManager::Get()->RemoveObserver(this); if (chromevox_panel_) { @@ -1067,10 +1052,6 @@ } void AccessibilityManager::SetProfile(Profile* profile) { - // Do nothing if this is called for the current profile. This can happen. For - // example, ChromeSessionManager fires both - // NOTIFICATION_LOGIN_USER_PROFILE_PREPARED and NOTIFICATION_SESSION_STARTED, - // and we are observing both events. if (profile_ == profile) return; @@ -1178,10 +1159,28 @@ OnAutoclickChanged(); } +void AccessibilityManager::SetProfileByUser(const user_manager::User* user) { + Profile* profile = ProfileHelper::Get()->GetProfileByUser(user); + DCHECK(profile); + SetProfile(profile); +} + void AccessibilityManager::ActiveUserChanged( const user_manager::User* active_user) { - if (active_user && active_user->is_profile_created()) - SetProfile(ProfileManager::GetActiveUserProfile()); + if (!active_user) + return; + + if (active_user->is_profile_created()) { + SetProfileByUser(active_user); + } else { + // |active_user| is unfortunately const. + user_manager::User* user = + user_manager::UserManager::Get()->GetActiveUser(); + DCHECK_EQ(user, active_user); + user->AddProfileCreatedObserver( + base::BindOnce(&AccessibilityManager::SetProfileByUser, + weak_ptr_factory_.GetWeakPtr(), user)); + } } base::TimeDelta AccessibilityManager::PlayShutdownSound() { @@ -1287,26 +1286,11 @@ SetProfile(profile); break; } - case chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED: - // Update |profile_| when login user profile is prepared. - // NOTIFICATION_SESSION_STARTED is not fired from UserSessionManager, but - // profile may be changed by UserSessionManager in OOBE flow. - SetProfile(ProfileManager::GetActiveUserProfile()); - break; - case chrome::NOTIFICATION_SESSION_STARTED: - // Update |profile_| when entering a session. - SetProfile(ProfileManager::GetActiveUserProfile()); - - // Add a session state observer to be able to monitor session changes. - if (!session_state_observer_.get()) - session_state_observer_.reset( - new user_manager::ScopedUserSessionStateObserver(this)); - break; case chrome::NOTIFICATION_PROFILE_DESTROYED: { // Update |profile_| when exiting a session or shutting down. Profile* profile = content::Source<Profile>(source).ptr(); if (profile_ == profile) - SetProfile(NULL); + SetProfile(nullptr); break; } case chrome::NOTIFICATION_APP_TERMINATING: {
diff --git a/chrome/browser/chromeos/accessibility/accessibility_manager.h b/chrome/browser/chromeos/accessibility/accessibility_manager.h index b3a98f73..0917fdb 100644 --- a/chrome/browser/chromeos/accessibility/accessibility_manager.h +++ b/chrome/browser/chromeos/accessibility/accessibility_manager.h
@@ -26,6 +26,8 @@ #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "extensions/browser/event_router.h" +#include "extensions/browser/extension_registry.h" +#include "extensions/browser/extension_registry_observer.h" #include "extensions/browser/extension_system.h" #include "services/media_session/public/mojom/audio_focus.mojom.h" #include "ui/accessibility/ax_enums.mojom-forward.h" @@ -393,6 +395,8 @@ void SetProfile(Profile* profile); + void SetProfileByUser(const user_manager::User* user); + void UpdateChromeOSAccessibilityHistograms(); void PlayVolumeAdjustSound(); @@ -425,43 +429,41 @@ void OnActiveOutputNodeChanged() override; // Profile which has the current a11y context. - Profile* profile_; + Profile* profile_ = nullptr; content::NotificationRegistrar notification_registrar_; std::unique_ptr<PrefChangeRegistrar> pref_change_registrar_; std::unique_ptr<PrefChangeRegistrar> local_state_pref_change_registrar_; - std::unique_ptr<user_manager::ScopedUserSessionStateObserver> - session_state_observer_; - bool spoken_feedback_enabled_; - bool select_to_speak_enabled_; - bool switch_access_enabled_; - bool autoclick_enabled_; + bool spoken_feedback_enabled_ = false; + bool select_to_speak_enabled_ = false; + bool switch_access_enabled_ = false; + bool autoclick_enabled_ = false; AccessibilityStatusCallbackList callback_list_; - bool braille_display_connected_; + bool braille_display_connected_ = false; ScopedObserver<extensions::api::braille_display_private::BrailleController, - AccessibilityManager> - scoped_braille_observer_; + extensions::api::braille_display_private::BrailleObserver> + scoped_braille_observer_{this}; - bool braille_ime_current_; + bool braille_ime_current_ = false; - ChromeVoxPanel* chromevox_panel_; + ChromeVoxPanel* chromevox_panel_ = nullptr; std::unique_ptr<AccessibilityPanelWidgetObserver> chromevox_panel_widget_observer_; - SwitchAccessPanel* switch_access_panel_; + SwitchAccessPanel* switch_access_panel_ = nullptr; std::unique_ptr<AccessibilityPanelWidgetObserver> switch_access_panel_widget_observer_; std::string keyboard_listener_extension_id_; - bool keyboard_listener_capture_; + bool keyboard_listener_capture_ = false; // Listen to extension unloaded notifications. ScopedObserver<extensions::ExtensionRegistry, extensions::ExtensionRegistryObserver> - extension_registry_observer_; + extension_registry_observer_{this}; std::unique_ptr<AccessibilityExtensionLoader> autoclick_extension_loader_;
diff --git a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc index a9ea66d..3903e86 100644 --- a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc +++ b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc
@@ -2280,6 +2280,40 @@ } /////////////////////////////////////////////////////////////////////////////// +// AutotestPrivateSetArcAppWindowFocusFunction +/////////////////////////////////////////////////////////////////////////////// + +AutotestPrivateSetArcAppWindowFocusFunction:: + AutotestPrivateSetArcAppWindowFocusFunction() = default; +AutotestPrivateSetArcAppWindowFocusFunction:: + ~AutotestPrivateSetArcAppWindowFocusFunction() = default; + +ExtensionFunction::ResponseAction +AutotestPrivateSetArcAppWindowFocusFunction::Run() { + std::unique_ptr<api::autotest_private::SetArcAppWindowFocus::Params> params( + api::autotest_private::SetArcAppWindowFocus::Params::Create(*args_)); + EXTENSION_FUNCTION_VALIDATE(params); + DVLOG(1) << "AutotestPrivateSetArcAppWindowFocusFunction " + << params->package_name; + aura::Window* arc_window = GetArcAppWindow(params->package_name); + if (!arc_window) { + return RespondNow(Error(base::StrCat( + {"No ARC app window is found for ", params->package_name}))); + } + if (!arc_window->CanFocus()) { + return RespondNow(Error(base::StrCat( + {"ARC app window can't focus for ", params->package_name}))); + } + // No matter whether it is focused already, set it focused. + arc_window->Focus(); + if (!arc_window->HasFocus()) { + return RespondNow(Error(base::StrCat( + {"Failed to set focus for ARC App window ", params->package_name}))); + } + return RespondNow(NoArguments()); +} + +/////////////////////////////////////////////////////////////////////////////// // AutotestPrivateSwapWindowsInSplitViewFunction ///////////////////////////////////////////////////////////////////////////////
diff --git a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.h b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.h index bd8af6bc..4e9bae9 100644 --- a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.h +++ b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.h
@@ -719,6 +719,17 @@ std::unique_ptr<WindowStateChangeObserver> window_state_observer_; }; +class AutotestPrivateSetArcAppWindowFocusFunction : public ExtensionFunction { + public: + AutotestPrivateSetArcAppWindowFocusFunction(); + DECLARE_EXTENSION_FUNCTION("autotestPrivate.setArcAppWindowFocus", + AUTOTESTPRIVATE_SETARCAPPWINDOWFOCUS) + + private: + ~AutotestPrivateSetArcAppWindowFocusFunction() override; + ResponseAction Run() override; +}; + class AutotestPrivateGetArcAppWindowStateFunction : public ExtensionFunction { public: AutotestPrivateGetArcAppWindowStateFunction();
diff --git a/chrome/browser/chromeos/login/users/chrome_user_manager_impl.cc b/chrome/browser/chromeos/login/users/chrome_user_manager_impl.cc index 7b6499d..1d31ce4 100644 --- a/chrome/browser/chromeos/login/users/chrome_user_manager_impl.cc +++ b/chrome/browser/chromeos/login/users/chrome_user_manager_impl.cc
@@ -371,7 +371,7 @@ registrar_.Add(this, chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED, content::NotificationService::AllSources()); - registrar_.Add(this, chrome::NOTIFICATION_PROFILE_CREATED, + registrar_.Add(this, chrome::NOTIFICATION_PROFILE_ADDED, content::NotificationService::AllSources()); // Since we're in ctor postpone any actions till this is fully created. @@ -650,7 +650,7 @@ UpdateUserTimeZoneRefresher(profile); break; } - case chrome::NOTIFICATION_PROFILE_CREATED: { + case chrome::NOTIFICATION_PROFILE_ADDED: { Profile* profile = content::Source<Profile>(source).ptr(); user_manager::User* user = ProfileHelper::Get()->GetUserByProfile(profile); @@ -663,14 +663,7 @@ // If there is pending user switch, do it now. if (GetPendingUserSwitchID().is_valid()) { - // Call SwitchActiveUser async because otherwise it may cause - // ProfileManager::GetProfile before the profile gets registered - // in ProfileManager. It happens in case of sync profile load when - // NOTIFICATION_PROFILE_CREATED is called synchronously. - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(&ChromeUserManagerImpl::SwitchActiveUser, - weak_factory_.GetWeakPtr(), - GetPendingUserSwitchID())); + SwitchActiveUser(GetPendingUserSwitchID()); SetPendingUserSwitchId(EmptyAccountId()); } break;
diff --git a/chrome/browser/chromeos/policy/status_collector/device_status_collector.cc b/chrome/browser/chromeos/policy/status_collector/device_status_collector.cc index 29a3be3..6300d2d3 100644 --- a/chrome/browser/chromeos/policy/status_collector/device_status_collector.cc +++ b/chrome/browser/chromeos/policy/status_collector/device_status_collector.cc
@@ -228,7 +228,7 @@ int32_t temperature = 0; if (base::ReadFileToString(temperature_path, &temperature_string) && sscanf(temperature_string.c_str(), "%d", &temperature) == 1) { - has_data = false; + has_data = true; // CPU temp in millidegree Celsius to Celsius temperature /= 1000;
diff --git a/chrome/browser/extensions/cross_origin_read_blocking_browsertest.cc b/chrome/browser/extensions/cross_origin_read_blocking_browsertest.cc index 35da70b..fd3e6a85 100644 --- a/chrome/browser/extensions/cross_origin_read_blocking_browsertest.cc +++ b/chrome/browser/extensions/cross_origin_read_blocking_browsertest.cc
@@ -5,14 +5,12 @@ #include "chrome/browser/extensions/extension_action_runner.h" #include "base/bind.h" -#include "base/feature_list.h" #include "base/files/file_path.h" #include "base/json/json_reader.h" #include "base/strings/string16.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/test/metrics/histogram_tester.h" -#include "base/test/scoped_feature_list.h" #include "base/values.h" #include "chrome/browser/apps/app_service/app_launch_params.h" #include "chrome/browser/apps/launch_service/launch_service.h" @@ -33,12 +31,13 @@ #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_navigation_observer.h" #include "extensions/browser/browsertest_util.h" -#include "extensions/common/extension_features.h" +#include "extensions/browser/url_loader_factory_manager.h" #include "extensions/test/test_extension_dir.h" #include "net/dns/mock_host_resolver.h" +#include "net/test/embedded_test_server/controllable_http_response.h" #include "net/test/embedded_test_server/embedded_test_server.h" +#include "net/test/embedded_test_server/http_request.h" #include "services/network/cross_origin_read_blocking.h" -#include "services/network/public/cpp/features.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" @@ -344,13 +343,9 @@ DISALLOW_COPY_AND_ASSIGN(CrossOriginReadBlockingExtensionTest); }; -struct AllowlistingParam { - AllowlistingParam(bool feature_enabled, bool test_extension_allowlisted) - : feature_enabled(feature_enabled), - test_extension_allowlisted(test_extension_allowlisted) {} - - bool feature_enabled; - bool test_extension_allowlisted; +enum class AllowlistingParam { + kAllowlisted, + kNotAllowlisted, }; class CrossOriginReadBlockingExtensionAllowlistingTest @@ -361,9 +356,8 @@ CrossOriginReadBlockingExtensionAllowlistingTest() {} - bool IsAllowlistFeatureEnabled() { return GetParam().feature_enabled; } bool IsExtensionAllowlisted() { - return GetParam().test_extension_allowlisted; + return GetParam() == AllowlistingParam::kAllowlisted; } const Extension* InstallExtension( @@ -371,30 +365,22 @@ const Extension* extension = Base::InstallExtension( resource_to_fetch_from_declarative_content_script); - if (IsAllowlistFeatureEnabled()) { - if (IsExtensionAllowlisted()) { - scoped_feature_list_.InitAndEnableFeatureWithParameters( - extensions_features::kBypassCorbOnlyForExtensionsAllowlist, - {{extensions_features::kBypassCorbAllowlistParamName, - extension->hashed_id().value()}}); - } else { - scoped_feature_list_.InitAndEnableFeature( - extensions_features::kBypassCorbOnlyForExtensionsAllowlist); - } + if (IsExtensionAllowlisted()) { + URLLoaderFactoryManager::AddExtensionToAllowlistForTesting(*extension); } else { - scoped_feature_list_.InitAndDisableFeature( - extensions_features::kBypassCorbOnlyForExtensionsAllowlist); + URLLoaderFactoryManager::RemoveExtensionFromAllowlistForTesting( + *extension); } return extension; } bool AreContentScriptFetchesExpectedToBeBlocked() { - return IsAllowlistFeatureEnabled() && !IsExtensionAllowlisted(); + return !IsExtensionAllowlisted(); } bool IsCorbExpectedToBeTurnedOffAltogether() { - return (IsExtensionAllowlisted() || !IsAllowlistFeatureEnabled()); + return IsExtensionAllowlisted(); } void VerifyFetchFromContentScriptWasBlocked( @@ -454,8 +440,6 @@ } private: - base::test::ScopedFeatureList scoped_feature_list_; - DISALLOW_COPY_AND_ASSIGN(CrossOriginReadBlockingExtensionAllowlistingTest); }; @@ -1225,14 +1209,61 @@ ::testing::Not(::testing::HasSubstr("Origin: chrome-extension"))); } -INSTANTIATE_TEST_SUITE_P(AllowlistingDisabled, - CrossOriginReadBlockingExtensionAllowlistingTest, - ::testing::Values(AllowlistingParam(false, false))); +IN_PROC_BROWSER_TEST_P(CrossOriginReadBlockingExtensionAllowlistingTest, + RequestHeaders_InSameOriginXhr_FromContentScript) { + // Sec-Fetch-Site only works on secure origins - setting up a https test + // server to help with this. + net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS); + https_server.AddDefaultHandlers(GetChromeTestDataDir()); + https_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK); + net::test_server::ControllableHttpResponse subresource_request( + &https_server, "/subresource"); + ASSERT_TRUE(https_server.Start()); + + // Load the test extension. + ASSERT_TRUE(InstallExtension()); + + // Navigate to https test page. + GURL page_url = https_server.GetURL("/title1.html"); + ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_EQ(page_url, + active_web_contents()->GetMainFrame()->GetLastCommittedURL()); + ASSERT_EQ(url::Origin::Create(page_url), + active_web_contents()->GetMainFrame()->GetLastCommittedOrigin()); + + // Inject a content script that performs a same-origin GET XHR. + GURL same_origin_resource(https_server.GetURL("/subresource")); + EXPECT_EQ(url::Origin::Create(page_url), + url::Origin::Create(same_origin_resource)); + const char* kScriptTemplate = R"( + fetch($1, {method: 'GET', mode: 'no-cors'}) )"; + ExecuteContentScript( + active_web_contents(), + content::JsReplace(kScriptTemplate, same_origin_resource)); + + // Verify the Referrer and Sec-Fetch-* header values. + subresource_request.WaitForRequest(); + const char* expected_sec_fetch_site = "same-origin"; + if (IsExtensionAllowlisted()) { + expected_sec_fetch_site = "cross-site"; + } else { + // TODO(lukasza): https://crbug.com/998247: Once the default factory uses + // request_initiator=website, we should get the desired behavior below - + // 'same-origin'. + expected_sec_fetch_site = "cross-site"; + } + EXPECT_THAT(subresource_request.http_request()->headers, + testing::IsSupersetOf( + {testing::Pair("Referer", page_url.spec().c_str()), + testing::Pair("Sec-Fetch-Mode", "no-cors"), + testing::Pair("Sec-Fetch-Site", expected_sec_fetch_site)})); +} + INSTANTIATE_TEST_SUITE_P(Allowlisted, CrossOriginReadBlockingExtensionAllowlistingTest, - ::testing::Values(AllowlistingParam(true, true))); + ::testing::Values(AllowlistingParam::kAllowlisted)); INSTANTIATE_TEST_SUITE_P(NotAllowlisted, CrossOriginReadBlockingExtensionAllowlistingTest, - ::testing::Values(AllowlistingParam(true, false))); + ::testing::Values(AllowlistingParam::kNotAllowlisted)); } // namespace extensions
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index 3a9738e..a0281498 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -2417,7 +2417,7 @@ "name": "new-overview-tablet-layout", "owners": [ "sammiequon" ], "expiry_milestone": 85 - }, + }, { "name": "new-tabstrip-animation", "owners": [ "tbergquist" ], @@ -2589,6 +2589,11 @@ "expiry_milestone": 80 }, { + "name": "omnibox-on-focus-suggestions", + "owners": [ "chrome-omnibox-team@google.com" ], + "expiry_milestone": 85 + }, + { "name": "omnibox-pedal-suggestions", "owners": [ "orinj", "chrome-omnibox-team@google.com" ], "expiry_milestone": 80
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index bd1039756..87d4934 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -1350,6 +1350,11 @@ "Use material design weather icons in the omnibox when displaying weather " "answers."; +const char kOmniboxOnFocusSuggestionsName[] = "Omnibox on-focus suggestions"; +const char kOmniboxOnFocusSuggestionsDescription[] = + "Configures Omnibox on-focus suggestions - suggestions displayed on-focus " + "before the user has typed any input"; + const char kOmniboxRichEntitySuggestionsName[] = "Omnibox rich entity suggestions"; const char kOmniboxRichEntitySuggestionsDescription[] =
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 966dc060..1b73f59 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -822,6 +822,9 @@ extern const char kOmniboxMaterialDesignWeatherIconsName[]; extern const char kOmniboxMaterialDesignWeatherIconsDescription[]; +extern const char kOmniboxOnFocusSuggestionsName[]; +extern const char kOmniboxOnFocusSuggestionsDescription[]; + extern const char kOmniboxRichEntitySuggestionsName[]; extern const char kOmniboxRichEntitySuggestionsDescription[];
diff --git a/chrome/browser/lifetime/browser_close_manager.cc b/chrome/browser/lifetime/browser_close_manager.cc index 1c63306..5e8964f5 100644 --- a/chrome/browser/lifetime/browser_close_manager.cc +++ b/chrome/browser/lifetime/browser_close_manager.cc
@@ -120,9 +120,7 @@ Browser* browser = BrowserList::GetInstance()->GetLastActive(); DCHECK(browser); browser->window()->ConfirmBrowserCloseWithPendingDownloads( - download_count, - Browser::DOWNLOAD_CLOSE_BROWSER_SHUTDOWN, - true, + download_count, Browser::DownloadCloseType::kBrowserShutdown, true, callback); }
diff --git a/chrome/browser/lifetime/browser_close_manager_browsertest.cc b/chrome/browser/lifetime/browser_close_manager_browsertest.cc index 6461dd87..7d4fc7b6 100644 --- a/chrome/browser/lifetime/browser_close_manager_browsertest.cc +++ b/chrome/browser/lifetime/browser_close_manager_browsertest.cc
@@ -1042,7 +1042,7 @@ int num_downloads_blocking = 0; ASSERT_EQ( - Browser::DOWNLOAD_CLOSE_OK, + Browser::DownloadCloseType::kOk, otr_browser->OkToCloseWithInProgressDownloads(&num_downloads_blocking)); ASSERT_EQ(0, num_downloads_blocking); @@ -1052,7 +1052,7 @@ } ASSERT_EQ( - Browser::DOWNLOAD_CLOSE_BROWSER_SHUTDOWN, + Browser::DownloadCloseType::kBrowserShutdown, browser()->OkToCloseWithInProgressDownloads(&num_downloads_blocking)); ASSERT_EQ(1, num_downloads_blocking);
diff --git a/chrome/browser/native_file_system/chrome_native_file_system_permission_context.cc b/chrome/browser/native_file_system/chrome_native_file_system_permission_context.cc index 758a9c5..5b3bbad 100644 --- a/chrome/browser/native_file_system/chrome_native_file_system_permission_context.cc +++ b/chrome/browser/native_file_system/chrome_native_file_system_permission_context.cc
@@ -9,6 +9,7 @@ #include "base/base_paths.h" #include "base/bind.h" +#include "base/metrics/histogram_functions.h" #include "base/path_service.h" #include "base/task/post_task.h" #include "build/build_config.h" @@ -26,6 +27,32 @@ namespace { +// These values are persisted to logs. Entries should not be renumbered and +// numeric values should never be reused. +enum class PermissionRequestOutcome { + kBlockedByContentSetting = 0, + kInvalidFrame = 1, + kNoUserActivation = 2, + kThirdPartyContext = 3, + kUserGranted = 4, + kUserDenied = 5, + kUserDismissed = 6, + kMaxValue = kUserDismissed +}; + +void RecordPermissionRequestOutcome(bool is_directory, + PermissionRequestOutcome outcome) { + base::UmaHistogramEnumeration( + "NativeFileSystemAPI.WritePermissionRequestOutcome", outcome); + if (is_directory) { + base::UmaHistogramEnumeration( + "NativeFileSystemAPI.WritePermissionRequestOutcome.Directory", outcome); + } else { + base::UmaHistogramEnumeration( + "NativeFileSystemAPI.WritePermissionRequestOutcome.File", outcome); + } +} + void ShowWritePermissionPromptOnUIThread( int process_id, int frame_id, @@ -38,12 +65,16 @@ content::RenderFrameHost::FromID(process_id, frame_id); if (!rfh || !rfh->IsCurrent()) { // Requested from a no longer valid render frame host. + RecordPermissionRequestOutcome(is_directory, + PermissionRequestOutcome::kInvalidFrame); std::move(callback).Run(PermissionAction::DISMISSED); return; } if (!rfh->HasTransientUserActivation()) { // No permission prompts without user activation. + RecordPermissionRequestOutcome(is_directory, + PermissionRequestOutcome::kNoUserActivation); std::move(callback).Run(PermissionAction::DISMISSED); return; } @@ -52,6 +83,8 @@ content::WebContents::FromRenderFrameHost(rfh); if (!web_contents) { // Requested from a worker, or a no longer existing tab. + RecordPermissionRequestOutcome(is_directory, + PermissionRequestOutcome::kInvalidFrame); std::move(callback).Run(PermissionAction::DISMISSED); return; } @@ -60,6 +93,8 @@ url::Origin::Create(web_contents->GetLastCommittedURL()); if (embedding_origin != origin) { // Third party iframes are not allowed to request more permissions. + RecordPermissionRequestOutcome( + is_directory, PermissionRequestOutcome::kThirdPartyContext); std::move(callback).Run(PermissionAction::DISMISSED); return; } @@ -71,8 +106,18 @@ return; } - request_manager->AddRequest({origin, path, is_directory}, - std::move(callback)); + request_manager->AddRequest( + {origin, path, is_directory}, + base::BindOnce( + [](bool is_directory, + base::OnceCallback<void(PermissionAction result)> callback, + PermissionAction result) { + if (result == PermissionAction::DISMISSED) + RecordPermissionRequestOutcome( + is_directory, PermissionRequestOutcome::kUserDismissed); + std::move(callback).Run(result); + }, + is_directory, std::move(callback))); } void ShowDirectoryAccessConfirmationPromptOnUIThread( @@ -335,6 +380,8 @@ // Check if |write_guard_content_setting_type_| is blocked by the user and // update the status if it is. if (!CanRequestPermission()) { + RecordPermissionRequestOutcome( + is_directory_, PermissionRequestOutcome::kBlockedByContentSetting); SetStatus(PermissionStatus::DENIED); std::move(callback).Run(); return; @@ -381,13 +428,19 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); switch (result) { case PermissionAction::GRANTED: + RecordPermissionRequestOutcome(is_directory_, + PermissionRequestOutcome::kUserGranted); SetStatus(PermissionStatus::GRANTED); break; case PermissionAction::DENIED: + RecordPermissionRequestOutcome(is_directory_, + PermissionRequestOutcome::kUserDenied); SetStatus(PermissionStatus::DENIED); break; case PermissionAction::DISMISSED: case PermissionAction::IGNORED: + // No histogram recorded here, the caller would have already recorded this + // outcome. break; case PermissionAction::REVOKED: case PermissionAction::NUM:
diff --git a/chrome/browser/net/system_network_context_manager.cc b/chrome/browser/net/system_network_context_manager.cc index a5a68e65..1668725 100644 --- a/chrome/browser/net/system_network_context_manager.cc +++ b/chrome/browser/net/system_network_context_manager.cc
@@ -48,6 +48,7 @@ #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/cors_exempt_headers.h" +#include "content/public/browser/network_context_client_base.h" #include "content/public/browser/network_service_instance.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" @@ -56,6 +57,7 @@ #include "content/public/common/user_agent.h" #include "crypto/sha2.h" #include "mojo/public/cpp/bindings/associated_interface_ptr.h" +#include "mojo/public/cpp/bindings/strong_binding.h" #include "net/net_buildflags.h" #include "net/third_party/uri_template/uri_template.h" #include "services/network/network_service.h" @@ -599,6 +601,12 @@ MakeRequest(&network_service_network_context_), CreateNetworkContextParams()); + network::mojom::NetworkContextClientPtr client_ptr; + auto client_request = mojo::MakeRequest(&client_ptr); + mojo::MakeStrongBinding(std::make_unique<content::NetworkContextClientBase>(), + std::move(client_request)); + network_service_network_context_->SetClient(std::move(client_ptr)); + // Configure the stub resolver. This must be done after the system // NetworkContext is created, but before anything has the chance to use it. bool insecure_stub_resolver_enabled;
diff --git a/chrome/browser/offline_pages/offline_page_mhtml_archiver.cc b/chrome/browser/offline_pages/offline_page_mhtml_archiver.cc index d69112f7..0d61085 100644 --- a/chrome/browser/offline_pages/offline_page_mhtml_archiver.cc +++ b/chrome/browser/offline_pages/offline_page_mhtml_archiver.cc
@@ -21,7 +21,6 @@ #include "components/offline_pages/core/archive_validator.h" #include "components/offline_pages/core/model/offline_page_model_utils.h" #include "components/offline_pages/core/offline_clock.h" -#include "components/offline_pages/core/offline_page_feature.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/web_contents.h" #include "content/public/common/mhtml_generation_params.h" @@ -103,9 +102,10 @@ params.remove_popup_overlay = create_archive_params.remove_popup_overlay; params.use_page_problem_detectors = create_archive_params.use_page_problem_detectors; - params.compute_contents_hash = IsOnTheFlyMhtmlHashComputationEnabled(); + params.compute_contents_hash = + create_archive_params.use_on_the_fly_hash_computation; - web_contents->GenerateMHTML( + web_contents->GenerateMHTMLWithResult( params, base::BindOnce(&OfflinePageMHTMLArchiver::OnGenerateMHTMLDone, weak_ptr_factory_.GetWeakPtr(), url, file_path, title, @@ -118,8 +118,8 @@ const base::string16& title, const std::string& name_space, base::Time mhtml_start_time, - int64_t file_size) { - if (file_size < 0) { + const content::MHTMLGenerationResult& result) { + if (result.file_size < 0) { DeleteFileAndReportFailure(file_path, ArchiverResult::ERROR_ARCHIVE_CREATION_FAILED); return; @@ -130,11 +130,17 @@ model_utils::AddHistogramSuffix( name_space, "OfflinePages.SavePage.CreateArchiveTime"), digest_start_time - mhtml_start_time); - ComputeDigestOnFileThread( - file_path, - base::BindOnce(&OfflinePageMHTMLArchiver::OnComputeDigestDone, - weak_ptr_factory_.GetWeakPtr(), url, file_path, title, - name_space, digest_start_time, file_size)); + + if (result.file_digest) { + OnComputeDigestDone(url, file_path, title, name_space, base::Time(), + result.file_size, result.file_digest.value()); + } else { + ComputeDigestOnFileThread( + file_path, + base::BindOnce(&OfflinePageMHTMLArchiver::OnComputeDigestDone, + weak_ptr_factory_.GetWeakPtr(), url, file_path, title, + name_space, digest_start_time, result.file_size)); + } } void OfflinePageMHTMLArchiver::OnComputeDigestDone( @@ -151,10 +157,12 @@ return; } - base::UmaHistogramTimes( - model_utils::AddHistogramSuffix( - name_space, "OfflinePages.SavePage.ComputeDigestTime"), - OfflineTimeNow() - digest_start_time); + if (!digest_start_time.is_null()) { + base::UmaHistogramTimes( + model_utils::AddHistogramSuffix( + name_space, "OfflinePages.SavePage.ComputeDigestTime"), + OfflineTimeNow() - digest_start_time); + } base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE,
diff --git a/chrome/browser/offline_pages/offline_page_mhtml_archiver.h b/chrome/browser/offline_pages/offline_page_mhtml_archiver.h index eb019fa..d92ea2d 100644 --- a/chrome/browser/offline_pages/offline_page_mhtml_archiver.h +++ b/chrome/browser/offline_pages/offline_page_mhtml_archiver.h
@@ -16,6 +16,7 @@ #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "components/offline_pages/core/offline_page_archiver.h" +#include "content/public/browser/mhtml_generation_result.h" namespace base { class FilePath; @@ -67,7 +68,7 @@ const base::string16& title, const std::string& name_space, base::Time mhtml_start_time, - int64_t file_size); + const content::MHTMLGenerationResult& result); void OnComputeDigestDone(const GURL& url, const base::FilePath& file_path, const base::string16& title,
diff --git a/chrome/browser/offline_pages/offline_page_mhtml_archiver_unittest.cc b/chrome/browser/offline_pages/offline_page_mhtml_archiver_unittest.cc index f6d5e90b..7cd45315 100644 --- a/chrome/browser/offline_pages/offline_page_mhtml_archiver_unittest.cc +++ b/chrome/browser/offline_pages/offline_page_mhtml_archiver_unittest.cc
@@ -99,10 +99,12 @@ base::FilePath archive_file_path = archives_dir.AppendASCII(url_.ExtractFileName()); base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(&TestMHTMLArchiver::OnGenerateMHTMLDone, - base::Unretained(this), url_, archive_file_path, - kTestTitle, create_archive_params.name_space, - OfflineTimeNow(), kTestFileSize)); + FROM_HERE, + base::BindOnce(&TestMHTMLArchiver::OnGenerateMHTMLDone, + base::Unretained(this), url_, archive_file_path, + kTestTitle, create_archive_params.name_space, + OfflineTimeNow(), + content::MHTMLGenerationResult(kTestFileSize, nullptr))); clock_->Advance(kTimeToSaveMhtml); }
diff --git a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer.cc b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer.cc index b89d3ec..71aa4eb5 100644 --- a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer.cc +++ b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer.cc
@@ -186,10 +186,10 @@ render_frame_host, render_frame_host->GetLastCommittedURL(), heavy_ads::PrepareHeavyAdPage(), net::ERR_BLOCKED_BY_CLIENT); - ADS_HISTOGRAM("HeavyAds.InterventionType", UMA_HISTOGRAM_ENUMERATION, + ADS_HISTOGRAM("HeavyAds.InterventionType2", UMA_HISTOGRAM_ENUMERATION, FrameData::FrameVisibility::kAnyVisibility, frame_data->heavy_ad_status()); - ADS_HISTOGRAM("HeavyAds.InterventionType", UMA_HISTOGRAM_ENUMERATION, + ADS_HISTOGRAM("HeavyAds.InterventionType2", UMA_HISTOGRAM_ENUMERATION, frame_data->visibility(), frame_data->heavy_ad_status()); // Report intervention to the blocklist. @@ -820,7 +820,7 @@ ADS_HISTOGRAM("FrameCounts.AdFrames.PerFrame.UserActivation", UMA_HISTOGRAM_ENUMERATION, visibility, ad_frame_data.user_activation_status()); - ADS_HISTOGRAM("HeavyAds.ComputedType", UMA_HISTOGRAM_ENUMERATION, + ADS_HISTOGRAM("HeavyAds.ComputedType2", UMA_HISTOGRAM_ENUMERATION, visibility, ad_frame_data.heavy_ad_status()); } }
diff --git a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc index 0abf74c..7ae8b61 100644 --- a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc +++ b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc
@@ -69,6 +69,9 @@ const char kPeakWindowdPercentHistogramId[] = "PageLoad.Clients.Ads.Cpu.FullPage.PeakWindowedPercent"; +const char kHeavyAdInterventionTypeHistogramId[] = + "PageLoad.Clients.Ads.HeavyAds.InterventionType2"; + const char kHttpOkResponseHeader[] = "HTTP/1.1 200 OK\r\n" "Content-Type: text/html; charset=utf-8\r\n" @@ -899,9 +902,8 @@ heavy_ad_thresholds::kMaxNetworkBytes); waiter->Wait(); - histogram_tester.ExpectUniqueSample( - "PageLoad.Clients.Ads.HeavyAds.InterventionType", - FrameData::HeavyAdStatus::kNetwork, 1); + histogram_tester.ExpectUniqueSample(kHeavyAdInterventionTypeHistogramId, + FrameData::HeavyAdStatus::kNetwork, 1); // Wait for the intervention page navigation to finish on the frame. same_tab_observer.Wait(); @@ -942,8 +944,7 @@ // We can't check whether the navigation didn't occur because the error page // load is not synchronous. Instead check that we didn't log intervention UMA // that is always recorded when the intervention occurs. - histogram_tester.ExpectTotalCount( - "PageLoad.Clients.Ads.HeavyAds.InterventionType", 0); + histogram_tester.ExpectTotalCount(kHeavyAdInterventionTypeHistogramId, 0); } // Check that we don't activate a HeavyAdIntervention field trial if we don't @@ -972,8 +973,7 @@ heavy_ad_thresholds::kMaxNetworkBytes / 2); waiter->Wait(); - histogram_tester.ExpectTotalCount( - "PageLoad.Clients.Ads.HeavyAds.InterventionType", 0); + histogram_tester.ExpectTotalCount(kHeavyAdInterventionTypeHistogramId, 0); // Verify that the trial is not activated if no heavy ads are seen. EXPECT_FALSE(base::FieldTrialList::IsTrialActive( @@ -1019,9 +1019,8 @@ heavy_ad_thresholds::kMaxNetworkBytes); waiter->Wait(); - histogram_tester.ExpectUniqueSample( - "PageLoad.Clients.Ads.HeavyAds.InterventionType", - FrameData::HeavyAdStatus::kNetwork, 1); + histogram_tester.ExpectUniqueSample(kHeavyAdInterventionTypeHistogramId, + FrameData::HeavyAdStatus::kNetwork, 1); // Wait for the intervention page navigation to finish on the frame. first_frame_observer.Wait(); @@ -1043,9 +1042,8 @@ waiter->Wait(); // Check that the intervention did not trigger on this frame. - histogram_tester.ExpectUniqueSample( - "PageLoad.Clients.Ads.HeavyAds.InterventionType", - FrameData::HeavyAdStatus::kNetwork, 1); + histogram_tester.ExpectUniqueSample(kHeavyAdInterventionTypeHistogramId, + FrameData::HeavyAdStatus::kNetwork, 1); } // Verify that UKM metrics are recorded correctly.
diff --git a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_unittest.cc b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_unittest.cc index 2da6aba..bae6138 100644 --- a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_unittest.cc +++ b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_unittest.cc
@@ -315,6 +315,20 @@ tester_->SimulateCpuTimingUpdate(cpu_timing, render_frame_host); } + // Sends |total_time| in CPU timing updates spread across a variable amount of + // 30 second windows to not hit the peak window usage cap for the heavy ad + // intervention. + void UseCpuTimeUnderThreshold(RenderFrameHost* render_frame_host, + base::TimeDelta total_time) { + const base::TimeDelta peak_threshold = base::TimeDelta::FromMilliseconds( + heavy_ad_thresholds::kMaxPeakWindowedPercent * 30000 / 100 - 1); + for (; total_time > peak_threshold; total_time -= peak_threshold) { + OnCpuTimingUpdate(render_frame_host, peak_threshold); + AdvancePageDuration(base::TimeDelta::FromSeconds(31)); + } + OnCpuTimingUpdate(render_frame_host, total_time); + } + void OnHidden() { web_contents()->WasHidden(); } void OnShown() { web_contents()->WasShown(); } @@ -1471,40 +1485,52 @@ TEST_F(AdsPageLoadMetricsObserverTest, HeavyAdFeatureOff_UMARecorded) { base::test::ScopedFeatureList feature_list; feature_list.InitAndDisableFeature(features::kHeavyAdIntervention); + OverrideVisibilityTrackerWithMockClock(); RenderFrameHost* main_frame = NavigateMainFrame(kNonAdUrl); RenderFrameHost* ad_frame_none = CreateAndNavigateSubFrame(kAdUrl, main_frame); RenderFrameHost* ad_frame_net = CreateAndNavigateSubFrame(kAdUrl, main_frame); RenderFrameHost* ad_frame_cpu = CreateAndNavigateSubFrame(kAdUrl, main_frame); + RenderFrameHost* ad_frame_total_cpu = + CreateAndNavigateSubFrame(kAdUrl, main_frame); // Load some bytes in each frame so they are considered ad iframes. ResourceDataUpdate(ad_frame_none, ResourceCached::NOT_CACHED, 1); ResourceDataUpdate(ad_frame_net, ResourceCached::NOT_CACHED, 1); ResourceDataUpdate(ad_frame_cpu, ResourceCached::NOT_CACHED, 1); + ResourceDataUpdate(ad_frame_total_cpu, ResourceCached::NOT_CACHED, 1); - // Make two of the ad frames hit thresholds for heavy ads. + // Make three of the ad frames hit thresholds for heavy ads. ResourceDataUpdate(ad_frame_net, ResourceCached::NOT_CACHED, (heavy_ad_thresholds::kMaxNetworkBytes / 1024)); - OnCpuTimingUpdate(ad_frame_cpu, base::TimeDelta::FromMilliseconds( - heavy_ad_thresholds::kMaxCpuTime)); + OnCpuTimingUpdate( + ad_frame_cpu, + base::TimeDelta::FromMilliseconds( + heavy_ad_thresholds::kMaxPeakWindowedPercent * 30000 / 100)); + UseCpuTimeUnderThreshold( + ad_frame_total_cpu, + base::TimeDelta::FromMilliseconds(heavy_ad_thresholds::kMaxCpuTime)); // Navigate again to trigger histograms. NavigateFrame(kNonAdUrl, main_frame); histogram_tester().ExpectTotalCount( - SuffixedHistogram("HeavyAds.ComputedType"), 3); + SuffixedHistogram("HeavyAds.ComputedType2"), 4); histogram_tester().ExpectBucketCount( - SuffixedHistogram("HeavyAds.ComputedType"), + SuffixedHistogram("HeavyAds.ComputedType2"), FrameData::HeavyAdStatus::kNone, 1); histogram_tester().ExpectBucketCount( - SuffixedHistogram("HeavyAds.ComputedType"), + SuffixedHistogram("HeavyAds.ComputedType2"), FrameData::HeavyAdStatus::kNetwork, 1); histogram_tester().ExpectBucketCount( - SuffixedHistogram("HeavyAds.ComputedType"), - FrameData::HeavyAdStatus::kCpu, 1); + SuffixedHistogram("HeavyAds.ComputedType2"), + FrameData::HeavyAdStatus::kPeakCpu, 1); + histogram_tester().ExpectBucketCount( + SuffixedHistogram("HeavyAds.ComputedType2"), + FrameData::HeavyAdStatus::kTotalCpu, 1); histogram_tester().ExpectTotalCount( - SuffixedHistogram("HeavyAds.InterventionType"), 0); + SuffixedHistogram("HeavyAds.InterventionType2"), 0); } TEST_F(AdsPageLoadMetricsObserverTest, HeavyAdNetworkUsage_InterventionFired) { @@ -1519,17 +1545,17 @@ ResourceDataUpdate(ad_frame, ResourceCached::NOT_CACHED, (heavy_ad_thresholds::kMaxNetworkBytes / 1024) - 1); histogram_tester().ExpectTotalCount( - SuffixedHistogram("HeavyAds.InterventionType"), 0); + SuffixedHistogram("HeavyAds.InterventionType2"), 0); // Load enough bytes to trigger the intervention. ResourceDataUpdate(ad_frame, ResourceCached::NOT_CACHED, 2); histogram_tester().ExpectUniqueSample( - SuffixedHistogram("HeavyAds.InterventionType"), + SuffixedHistogram("HeavyAds.InterventionType2"), FrameData::HeavyAdStatus::kNetwork, 1); } -TEST_F(AdsPageLoadMetricsObserverTest, HeavyAdCpuUsage_InterventionFired) { +TEST_F(AdsPageLoadMetricsObserverTest, HeavyAdTotalCpuUsage_InterventionFired) { base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(features::kHeavyAdIntervention); OverrideVisibilityTrackerWithMockClock(); @@ -1540,18 +1566,48 @@ // Add some data to the ad frame so it get reported. ResourceDataUpdate(ad_frame, ResourceCached::NOT_CACHED, 1); - // Use just under the threshold amount of CPU. - OnCpuTimingUpdate(ad_frame, base::TimeDelta::FromMilliseconds( - heavy_ad_thresholds::kMaxCpuTime - 1)); + // Use just under the threshold amount of CPU.Needs to spread across enough + // windows to not trigger peak threshold. + AdvancePageDuration(base::TimeDelta::FromSeconds(30)); + UseCpuTimeUnderThreshold(ad_frame, base::TimeDelta::FromMilliseconds( + heavy_ad_thresholds::kMaxCpuTime - 1)); histogram_tester().ExpectTotalCount( - SuffixedHistogram("HeavyAds.InterventionType"), 0); - + SuffixedHistogram("HeavyAds.InterventionType2"), 0); + AdvancePageDuration(base::TimeDelta::FromSeconds(30)); // Use enough CPU to trigger the intervention. OnCpuTimingUpdate(ad_frame, base::TimeDelta::FromMilliseconds(1)); histogram_tester().ExpectUniqueSample( - SuffixedHistogram("HeavyAds.InterventionType"), - FrameData::HeavyAdStatus::kCpu, 1); + SuffixedHistogram("HeavyAds.InterventionType2"), + FrameData::HeavyAdStatus::kTotalCpu, 1); +} + +TEST_F(AdsPageLoadMetricsObserverTest, HeavyAdPeakCpuUsage_InterventionFired) { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature(features::kHeavyAdIntervention); + OverrideVisibilityTrackerWithMockClock(); + + RenderFrameHost* main_frame = NavigateMainFrame(kNonAdUrl); + RenderFrameHost* ad_frame = CreateAndNavigateSubFrame(kAdUrl, main_frame); + + // Add some data to the ad frame so it get reported. + ResourceDataUpdate(ad_frame, ResourceCached::NOT_CACHED, 1); + + // Use just under the peak threshold amount of CPU. + OnCpuTimingUpdate( + ad_frame, + base::TimeDelta::FromMilliseconds( + heavy_ad_thresholds::kMaxPeakWindowedPercent * 30000 / 100 - 1)); + histogram_tester().ExpectTotalCount( + SuffixedHistogram("HeavyAds.InterventionType2"), 0); + + // Use enough CPU to trigger the intervention. + AdvancePageDuration(base::TimeDelta::FromSeconds(10)); + OnCpuTimingUpdate(ad_frame, base::TimeDelta::FromMilliseconds(1)); + + histogram_tester().ExpectUniqueSample( + SuffixedHistogram("HeavyAds.InterventionType2"), + FrameData::HeavyAdStatus::kPeakCpu, 1); } TEST_F(AdsPageLoadMetricsObserverTest, HeavyAdFeatureDisabled_NotFired) { @@ -1566,7 +1622,7 @@ (heavy_ad_thresholds::kMaxNetworkBytes / 1024) + 1); histogram_tester().ExpectTotalCount( - SuffixedHistogram("HeavyAds.InterventionType"), 0); + SuffixedHistogram("HeavyAds.InterventionType2"), 0); } TEST_F(AdsPageLoadMetricsObserverTest, @@ -1585,13 +1641,13 @@ (heavy_ad_thresholds::kMaxNetworkBytes / 1024) + 1); histogram_tester().ExpectTotalCount( - SuffixedHistogram("HeavyAds.InterventionType"), 0); + SuffixedHistogram("HeavyAds.InterventionType2"), 0); // Navigate again to trigger histograms. NavigateFrame(kNonAdUrl, main_frame); histogram_tester().ExpectUniqueSample( - SuffixedHistogram("HeavyAds.ComputedType"), + SuffixedHistogram("HeavyAds.ComputedType2"), FrameData::HeavyAdStatus::kNone, 1); } @@ -1612,7 +1668,7 @@ (heavy_ad_thresholds::kMaxNetworkBytes / 1024) + 1); histogram_tester().ExpectTotalCount( - SuffixedHistogram("HeavyAds.InterventionType"), 0); + SuffixedHistogram("HeavyAds.InterventionType2"), 0); } TEST_F(AdsPageLoadMetricsObserverTest, @@ -1634,7 +1690,7 @@ (heavy_ad_thresholds::kMaxNetworkBytes / 1024) + 1); histogram_tester().ExpectTotalCount( - SuffixedHistogram("HeavyAds.InterventionType"), 1); + SuffixedHistogram("HeavyAds.InterventionType2"), 1); } TEST_F(AdsPageLoadMetricsObserverTest, HeavyAdBlocklist_InterventionReported) { @@ -1655,7 +1711,7 @@ // Verify the intervention triggered. histogram_tester().ExpectUniqueSample( - SuffixedHistogram("HeavyAds.InterventionType"), + SuffixedHistogram("HeavyAds.InterventionType2"), FrameData::HeavyAdStatus::kNetwork, 1); // Verify the blocklist blocks the next intervention. @@ -1667,6 +1723,6 @@ // Verify the intervention did not occur again. histogram_tester().ExpectUniqueSample( - SuffixedHistogram("HeavyAds.InterventionType"), + SuffixedHistogram("HeavyAds.InterventionType2"), FrameData::HeavyAdStatus::kNetwork, 1); }
diff --git a/chrome/browser/page_load_metrics/observers/ad_metrics/frame_data.cc b/chrome/browser/page_load_metrics/observers/ad_metrics/frame_data.cc index c4e007f7..10f7763 100644 --- a/chrome/browser/page_load_metrics/observers/ad_metrics/frame_data.cc +++ b/chrome/browser/page_load_metrics/observers/ad_metrics/frame_data.cc
@@ -302,9 +302,15 @@ } FrameData::HeavyAdStatus FrameData::ComputeHeavyAdStatus() const { + // Check if the frame meets the peak CPU usage threshold. + if (peak_windowed_cpu_percent_ >= + heavy_ad_thresholds::kMaxPeakWindowedPercent) { + return HeavyAdStatus::kPeakCpu; + } + // Check if the frame meets the absolute CPU time threshold. if (GetTotalCpuUsage().InMilliseconds() >= heavy_ad_thresholds::kMaxCpuTime) - return HeavyAdStatus::kCpu; + return HeavyAdStatus::kTotalCpu; // Check if the frame meets the network threshold. if (network_bytes_ >= heavy_ad_thresholds::kMaxNetworkBytes)
diff --git a/chrome/browser/page_load_metrics/observers/ad_metrics/frame_data.h b/chrome/browser/page_load_metrics/observers/ad_metrics/frame_data.h index 98bc3d9..cd6fef4 100644 --- a/chrome/browser/page_load_metrics/observers/ad_metrics/frame_data.h +++ b/chrome/browser/page_load_metrics/observers/ad_metrics/frame_data.h
@@ -15,7 +15,7 @@ // Resource usage thresholds for the Heavy Ad Intervention feature. These // numbers are platform specific and are intended to target 1 in 1000 ad iframes -// on each platform. +// on each platform, for network and CPU use respectively. namespace heavy_ad_thresholds { // Maximum number of network bytes allowed to be loaded by a frame. These @@ -24,12 +24,15 @@ // desktop. const int kMaxNetworkBytes = 4.0 * 1024 * 1024; -// Maximum number of milliseconds of CPU use allowed to be used by a frame. -// These numbers reflect the 99.9th percentile of the -// PageLoad.Clients.Ads.Cpu.AdFrames.PerFrame.TotalUsage.Unactivated histogram -// on mobile and desktop. +// CPU thresholds are selected from AdFrameLoad UKM, and are intended to target +// 1 in 1000 ad iframes combined, with each threshold responsible for roughly +// half of those intervention. Maximum number of milliseconds of CPU use allowed +// to be used by a frame. const int kMaxCpuTime = 60 * 1000; +// Maximum percentage of CPU utilization over a 30 second window allowed. +const int kMaxPeakWindowedPercent = 50; + } // namespace heavy_ad_thresholds // Store information received for a frame on the page. FrameData is meant @@ -59,8 +62,9 @@ enum class HeavyAdStatus { kNone = 0, kNetwork = 1, - kCpu = 2, - kMaxValue = kCpu, + kTotalCpu = 2, + kPeakCpu = 3, + kMaxValue = kPeakCpu, }; // These values are persisted to logs. Entries should not be renumbered and
diff --git a/chrome/browser/performance_manager/graph/page_node_impl_browsertest.cc b/chrome/browser/performance_manager/graph/page_node_impl_browsertest.cc index 748c00b..60c0df3 100644 --- a/chrome/browser/performance_manager/graph/page_node_impl_browsertest.cc +++ b/chrome/browser/performance_manager/graph/page_node_impl_browsertest.cc
@@ -14,47 +14,45 @@ #include "chrome/common/chrome_switches.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" -#include "net/http/http_status_code.h" -#include "net/test/embedded_test_server/embedded_test_server.h" -#include "net/test/embedded_test_server/http_request.h" -#include "net/test/embedded_test_server/http_response.h" +#include "content/public/test/url_loader_interceptor.h" #include "testing/gtest/include/gtest/gtest.h" namespace performance_manager { namespace { -// Origin Trial tokens are bound to a specific origin (incl. port), so we need -// to force our test server to run on the same port that the test token has -// been generated for. -const int kServerPort = 54321; - constexpr char kOriginTrialTestPublicKey[] = "dRCs+TocuKkocNKa0AtZ4awrt9XKH2SQCI6o4FY6BNA="; +const char kTestHeaders[] = "HTTP/1.1 200 OK\nContent-type: text/html\n\n"; + +constexpr char kOriginTrialTestHostname[] = "https://lifecycle_ot_test.com"; + // Origin Trial Token for PageLifecycleTransitionsOptOut generated with: // $ tools/origin_trials/generate_token.py \ -// https://127.0.0.1:54321/ \ +// https://lifecycle_ot_test.com/ \ // "PageLifecycleTransitionsOptOut" \ // --expire-timestamp=2000000000 // (Token will expire ca. ~2033. See content/test/data/origin_trials/basic.html) constexpr char kOriginTrialPageLifecycleOptOutToken[] = - "Ah4aYo237SBR30bpy6p2AtxDi//nEjBJMvdRVK5XywJHT3h6AZEdfvIejN9BBTn+" - "JXWpxCBU6PcSPQct5BSZAAEAAABoeyJvcmlnaW4iOiAiaHR0cHM6Ly8xMjcuMC4wLjE6NTQzMj" - "EiLCAiZmVhdHVyZSI6ICJQYWdlTGlmZWN5Y2xlVHJhbnNpdGlvbnNPcHRPdXQiLCAiZXhwaXJ5" - "IjogMjAwMDAwMDAwMH0="; + "ArFuhJf1Qa7r7LIOWprpcssb/Vz76rIe0QyGJw2NP+S/Zy7Q7AVg2UfUqgARHPNk6KQ60/" + "ii4ef4ZwJmNi+" + "VbwoAAAByeyJvcmlnaW4iOiAiaHR0cHM6Ly9saWZlY3ljbGVfb3RfdGVzdC5jb206NDQzIiwgI" + "mZlYXR1cmUiOiAiUGFnZUxpZmVjeWNsZVRyYW5zaXRpb25zT3B0T3V0IiwgImV4cGlyeSI6IDI" + "wMDAwMDAwMDB9"; // Origin Trial Token for PageLifecycleTransitionsOptIn generated with: // $ tools/origin_trials/generate_token.py \ -// https://127.0.0.1:54321/ \ +// https://lifecycle_ot_test.com/ \ // "PageLifecycleTransitionsOptIn" \ // --expire-timestamp=2000000000 // (Token will expire ca. ~2033. See content/test/data/origin_trials/basic.html) constexpr char kOriginTrialPageLifecycleOptInToken[] = - "AhTNLPzOPkxjkQoNWrLvdOBbET3ZX+OCe7k4SnkYHikPsq2aFTTKF2xVwwTZnepfn1heEK7q" - "bJu6yokw9zFjwwAAAABneyJvcmlnaW4iOiAiaHR0cHM6Ly8xMjcuMC4wLjE6NTQzMjEiLCAiZm" - "VhdHVyZSI6ICJQYWdlTGlmZWN5Y2xlVHJhbnNpdGlvbnNPcHRJbiIsICJleHBpcnkiOiAyMDAw" - "MDAwMDAwfQ=="; + "AgI1yybGRSVe5oDQ1EAK9/" + "bp3vmEbysprYviipejGsRR5aqAj37I6SHEnZGvmg4iEzxDRWfwvctZH+" + "rSdZ58kA0AAABxeyJvcmlnaW4iOiAiaHR0cHM6Ly9saWZlY3ljbGVfb3RfdGVzdC5jb206NDQz" + "IiwgImZlYXR1cmUiOiAiUGFnZUxpZmVjeWNsZVRyYW5zaXRpb25zT3B0SW4iLCAiZXhwaXJ5Ij" + "ogMjAwMDAwMDAwMH0="; // The path used in the URL of the Page Lifecycle Origin Trial tests. constexpr char kOriginTrialTestLifecyclePath[] = "lifecycle_origin_trial"; @@ -87,7 +85,7 @@ constexpr char kTwoiFrameTestBody[] = R"( <html> -<base href="https://127.0.0.1:54321/"> +<base href="https://lifecycle_ot_test.com/"> <head> <title>iFrame Test</title> </head> @@ -137,17 +135,10 @@ return contents; } -// Request handler for these tests, redirect the query to the appropriate -// handler. Return 404 for all paths not ending in ".html". -std::unique_ptr<net::test_server::HttpResponse> RequestHandler( - const net::test_server::HttpRequest& request) { - std::unique_ptr<net::test_server::BasicHttpResponse> response = - std::make_unique<net::test_server::BasicHttpResponse>(); - std::string url = request.GetURL().path(); - if (!base::EndsWith(url, ".html", base::CompareCase::SENSITIVE)) { - response->set_code(net::HTTP_NOT_FOUND); - return response; - } +// Generate the HTML content that should be served for |url|. +std::string GetContentForURL(const std::string& url) { + if (!base::EndsWith(url, ".html", base::CompareCase::SENSITIVE)) + return std::string(); auto url_parts = base::SplitString(url, "/", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY); @@ -156,15 +147,12 @@ // generates the response to serve the appropriate content. EXPECT_EQ(2U, url_parts.size()); + std::string response; if (url_parts[0].compare(kOriginTrialTestLifecyclePath) == 0) { - response->set_content(GetPageLifecycleOriginTrialPageContent(url_parts[1])); + response = GetPageLifecycleOriginTrialPageContent(url_parts[1]); } else if (url_parts[0].compare(k2iFramesPath) == 0) { - response->set_content( - GetPageLifecycleOriginTrialiFramePageContent(url_parts[1])); + response = GetPageLifecycleOriginTrialiFramePageContent(url_parts[1]); } - - response->set_content_type("text/html"); - response->set_code(net::HTTP_OK); return response; } @@ -192,6 +180,15 @@ run_loop.Run(); } +bool URLLoaderInterceptorCallback( + content::URLLoaderInterceptor::RequestParams* params) { + content::URLLoaderInterceptor::WriteResponse( + kTestHeaders, GetContentForURL(params->url_request.url.path()), + params->client.get()); + + return true; +} + } // namespace class PageNodeImplBrowserTest : public InProcessBrowserTest { @@ -205,27 +202,33 @@ kOriginTrialTestPublicKey); } - void SetUpInProcessBrowserTestFixture() override { - server_ = std::make_unique<net::test_server::EmbeddedTestServer>( - net::test_server::EmbeddedTestServer::TYPE_HTTPS); - server_->RegisterRequestHandler(base::Bind(&RequestHandler)); - EXPECT_TRUE(server_->Start(kServerPort)); + void SetUpOnMainThread() override { + InProcessBrowserTest::SetUpOnMainThread(); + + // We use a URLLoaderInterceptor, rather than the EmbeddedTestServer, since + // the origin trial token in the response is associated with a fixed + // origin, whereas EmbeddedTestServer serves content on a random port. + url_loader_interceptor_ = std::make_unique<content::URLLoaderInterceptor>( + base::BindRepeating(&URLLoaderInterceptorCallback)); } - net::test_server::EmbeddedTestServer* server() { return server_.get(); } + void TearDownOnMainThread() override { + url_loader_interceptor_.reset(); + InProcessBrowserTest::TearDownOnMainThread(); + } private: - std::unique_ptr<net::test_server::EmbeddedTestServer> server_; + std::unique_ptr<content::URLLoaderInterceptor> url_loader_interceptor_; DISALLOW_COPY_AND_ASSIGN(PageNodeImplBrowserTest); }; IN_PROC_BROWSER_TEST_F(PageNodeImplBrowserTest, PageLifecycleOriginTrialOptIn) { ui_test_utils::NavigateToURL( - browser(), - server()->GetURL("/" + base::JoinString({kOriginTrialTestLifecyclePath, - kOriginTrialOptInPage}, - "/"))); + browser(), GURL(base::JoinString( + {kOriginTrialTestHostname, kOriginTrialTestLifecyclePath, + kOriginTrialOptInPage}, + "/"))); RunOriginTrialTestOnPMSequence( resource_coordinator::mojom::InterventionPolicy::kOptIn); } @@ -233,10 +236,10 @@ IN_PROC_BROWSER_TEST_F(PageNodeImplBrowserTest, PageLifecycleOriginTrialOptOut) { ui_test_utils::NavigateToURL( - browser(), - server()->GetURL("/" + base::JoinString({kOriginTrialTestLifecyclePath, - kOriginTrialOptOutPage}, - "/"))); + browser(), GURL(base::JoinString( + {kOriginTrialTestHostname, kOriginTrialTestLifecyclePath, + kOriginTrialOptOutPage}, + "/"))); RunOriginTrialTestOnPMSequence( resource_coordinator::mojom::InterventionPolicy::kOptOut); } @@ -244,10 +247,10 @@ IN_PROC_BROWSER_TEST_F(PageNodeImplBrowserTest, PageLifecycleOriginTrialDefault) { ui_test_utils::NavigateToURL( - browser(), - server()->GetURL("/" + base::JoinString({kOriginTrialTestLifecyclePath, - kOriginTrialDefaultPage}, - "/"))); + browser(), GURL(base::JoinString( + {kOriginTrialTestHostname, kOriginTrialTestLifecyclePath, + kOriginTrialDefaultPage}, + "/"))); RunOriginTrialTestOnPMSequence( resource_coordinator::mojom::InterventionPolicy::kDefault); } @@ -255,9 +258,9 @@ IN_PROC_BROWSER_TEST_F(PageNodeImplBrowserTest, PageLifecycleOriginTrialOptInOptOut) { ui_test_utils::NavigateToURL( - browser(), server()->GetURL( - "/" + base::JoinString( - {k2iFramesPath, kOriginTrialOptInOptOut}, "/"))); + browser(), GURL(base::JoinString({kOriginTrialTestHostname, k2iFramesPath, + kOriginTrialOptInOptOut}, + "/"))); RunOriginTrialTestOnPMSequence( resource_coordinator::mojom::InterventionPolicy::kOptOut); } @@ -265,9 +268,9 @@ IN_PROC_BROWSER_TEST_F(PageNodeImplBrowserTest, PageLifecycleOriginTrialOptOutOptIn) { ui_test_utils::NavigateToURL( - browser(), server()->GetURL( - "/" + base::JoinString( - {k2iFramesPath, kOriginTrialOptOutOptIn}, "/"))); + browser(), GURL(base::JoinString({kOriginTrialTestHostname, k2iFramesPath, + kOriginTrialOptOutOptIn}, + "/"))); RunOriginTrialTestOnPMSequence( resource_coordinator::mojom::InterventionPolicy::kOptOut); } @@ -275,10 +278,9 @@ IN_PROC_BROWSER_TEST_F(PageNodeImplBrowserTest, PageLifecycleOriginTrialDefaultOptIn) { ui_test_utils::NavigateToURL( - browser(), - server()->GetURL( - "/" + - base::JoinString({k2iFramesPath, kOriginTrialDefaultOptIn}, "/"))); + browser(), GURL(base::JoinString({kOriginTrialTestHostname, k2iFramesPath, + kOriginTrialDefaultOptIn}, + "/"))); RunOriginTrialTestOnPMSequence( resource_coordinator::mojom::InterventionPolicy::kOptIn); } @@ -286,10 +288,9 @@ IN_PROC_BROWSER_TEST_F(PageNodeImplBrowserTest, PageLifecycleOriginTrialDefaultOptOut) { ui_test_utils::NavigateToURL( - browser(), - server()->GetURL( - "/" + - base::JoinString({k2iFramesPath, kOriginTrialDefaultOptOut}, "/"))); + browser(), GURL(base::JoinString({kOriginTrialTestHostname, k2iFramesPath, + kOriginTrialDefaultOptOut}, + "/"))); RunOriginTrialTestOnPMSequence( resource_coordinator::mojom::InterventionPolicy::kOptOut); } @@ -297,9 +298,9 @@ IN_PROC_BROWSER_TEST_F(PageNodeImplBrowserTest, PageLifecycleOriginTrialOptInOptIn) { ui_test_utils::NavigateToURL( - browser(), server()->GetURL( - "/" + base::JoinString( - {k2iFramesPath, kOriginTrialOptInOptIn}, "/"))); + browser(), GURL(base::JoinString({kOriginTrialTestHostname, k2iFramesPath, + kOriginTrialOptInOptIn}, + "/"))); RunOriginTrialTestOnPMSequence( resource_coordinator::mojom::InterventionPolicy::kOptIn); } @@ -307,10 +308,9 @@ IN_PROC_BROWSER_TEST_F(PageNodeImplBrowserTest, PageLifecycleOriginTrialOptOutOptOut) { ui_test_utils::NavigateToURL( - browser(), - server()->GetURL( - "/" + - base::JoinString({k2iFramesPath, kOriginTrialOptOutOptOut}, "/"))); + browser(), GURL(base::JoinString({kOriginTrialTestHostname, k2iFramesPath, + kOriginTrialOptOutOptOut}, + "/"))); RunOriginTrialTestOnPMSequence( resource_coordinator::mojom::InterventionPolicy::kOptOut); } @@ -318,10 +318,9 @@ IN_PROC_BROWSER_TEST_F(PageNodeImplBrowserTest, PageLifecycleOriginTrialDefaultDefault) { ui_test_utils::NavigateToURL( - browser(), - server()->GetURL( - "/" + - base::JoinString({k2iFramesPath, kOriginTrialDefaultDefault}, "/"))); + browser(), GURL(base::JoinString({kOriginTrialTestHostname, k2iFramesPath, + kOriginTrialDefaultDefault}, + "/"))); RunOriginTrialTestOnPMSequence( resource_coordinator::mojom::InterventionPolicy::kDefault); }
diff --git a/chrome/browser/previews/previews_lite_page_serving_url_loader.cc b/chrome/browser/previews/previews_lite_page_serving_url_loader.cc index 3b47ce4..ac4eb27e 100644 --- a/chrome/browser/previews/previews_lite_page_serving_url_loader.cc +++ b/chrome/browser/previews/previews_lite_page_serving_url_loader.cc
@@ -392,14 +392,19 @@ void PreviewsLitePageServingURLLoader::OnComplete( const network::URLLoaderCompletionStatus& status) { - base::UmaHistogramSparse("Previews.ServerLitePage.ServerNetError", - -status.error_code); - if (forwarding_client_) { + base::UmaHistogramSparse( + "Previews.ServerLitePage.ServerNetError.AfterCommit", + -status.error_code); + forwarding_client_->OnComplete(status); return; } + base::UmaHistogramSparse( + "Previews.ServerLitePage.ServerNetError.BeforeCommit", + -status.error_code); + UMA_HISTOGRAM_ENUMERATION("Previews.ServerLitePage.ServerResponse", PreviewsLitePageNavigationThrottle::ServerResponse:: kOnCompleteBeforeOnResponse);
diff --git a/chrome/browser/previews/resource_loading_hints/resource_loading_hints_browsertest.cc b/chrome/browser/previews/resource_loading_hints/resource_loading_hints_browsertest.cc index ab25e80f..3dca722 100644 --- a/chrome/browser/previews/resource_loading_hints/resource_loading_hints_browsertest.cc +++ b/chrome/browser/previews/resource_loading_hints/resource_loading_hints_browsertest.cc
@@ -297,6 +297,24 @@ ->GetID(); } + void RetryUntilAllExpectedSubresourcesSeen() { + while (true) { + base::ThreadPoolInstance::Get()->FlushForTesting(); + base::RunLoop().RunUntilIdle(); + + bool have_seen_all_expected_subresources = true; + for (const auto& expect : subresource_expected_) { + if (expect.second) { + have_seen_all_expected_subresources = false; + break; + } + } + + if (have_seen_all_expected_subresources) + break; + } + } + protected: std::unique_ptr<net::EmbeddedTestServer> https_server_; @@ -339,6 +357,7 @@ EXPECT_TRUE(expect.second) << " GURL " << gurl << " was expected to be blocked, but was actually fetched"; + // Subresource should not be fetched again. subresource_expected_[gurl.path()] = false; return; @@ -493,6 +512,7 @@ base::HistogramTester histogram_tester; ui_test_utils::NavigateToURL(browser(), url); + RetryUntilAllExpectedSubresourcesSeen(); RetryForHistogramUntilCountReached( &histogram_tester, "ResourceLoadingHints.CountBlockedSubresourcePatterns", @@ -516,6 +536,7 @@ SetExpectedBarJpgRequest(true); ui_test_utils::NavigateToURL(browser(), url); + RetryUntilAllExpectedSubresourcesSeen(); RetryForHistogramUntilCountReached( &histogram_tester, "ResourceLoadingHints.CountBlockedSubresourcePatterns", @@ -546,6 +567,7 @@ ui_test_utils::NavigateToURL( browser(), GetURLWithMockHost(*https_server_, "/resource_loading_hints.html")); + RetryUntilAllExpectedSubresourcesSeen(); int current_process_id = GetProcessID(); EXPECT_NE(previous_process_id, current_process_id); @@ -582,6 +604,7 @@ base::HistogramTester histogram_tester; ui_test_utils::NavigateToURL(browser(), url); + RetryUntilAllExpectedSubresourcesSeen(); histogram_tester.ExpectBucketCount( "Previews.EligibilityReason.ResourceLoadingHints", @@ -643,6 +666,7 @@ base::HistogramTester histogram_tester; ui_test_utils::NavigateToURL(browser(), url); + RetryUntilAllExpectedSubresourcesSeen(); histogram_tester.ExpectBucketCount( "Previews.EligibilityReason.ResourceLoadingHints", @@ -678,6 +702,7 @@ base::HistogramTester histogram_tester; ui_test_utils::NavigateToURL(browser(), url); + RetryUntilAllExpectedSubresourcesSeen(); RetryForHistogramUntilCountReached( &histogram_tester, "ResourceLoadingHints.CountBlockedSubresourcePatterns", @@ -723,6 +748,7 @@ base::HistogramTester histogram_tester; ui_test_utils::NavigateToURL(browser(), url); + RetryUntilAllExpectedSubresourcesSeen(); RetryForHistogramUntilCountReached( &histogram_tester, "ResourceLoadingHints.CountBlockedSubresourcePatterns", @@ -762,7 +788,7 @@ // The URL is not whitelisted. Verify that the hints are not used. ui_test_utils::NavigateToURL(browser(), url); - base::RunLoop().RunUntilIdle(); + RetryUntilAllExpectedSubresourcesSeen(); histogram_tester.ExpectBucketCount( "Previews.EligibilityReason.ResourceLoadingHints", @@ -795,6 +821,7 @@ base::HistogramTester histogram_tester_1; ui_test_utils::NavigateToURL(browser(), https_url()); + RetryUntilAllExpectedSubresourcesSeen(); RetryForHistogramUntilCountReached( &histogram_tester_1, @@ -862,6 +889,7 @@ base::HistogramTester histogram_tester; ui_test_utils::NavigateToURL(browser(), url); + RetryUntilAllExpectedSubresourcesSeen(); RetryForHistogramUntilCountReached( &histogram_tester, "ResourceLoadingHints.CountBlockedSubresourcePatterns", @@ -892,6 +920,7 @@ base::HistogramTester histogram_tester; ui_test_utils::NavigateToURL(browser(), url); + RetryUntilAllExpectedSubresourcesSeen(); RetryForHistogramUntilCountReached( &histogram_tester, "ResourceLoadingHints.CountBlockedSubresourcePatterns", @@ -924,7 +953,7 @@ // The URL is not whitelisted. ui_test_utils::NavigateToURL(browser(), url); - base::RunLoop().RunUntilIdle(); + RetryUntilAllExpectedSubresourcesSeen(); histogram_tester.ExpectBucketCount( "Previews.EligibilityReason.ResourceLoadingHints", @@ -950,7 +979,7 @@ base::HistogramTester histogram_tester; ui_test_utils::NavigateToURL(browser(), url); - base::RunLoop().RunUntilIdle(); + RetryUntilAllExpectedSubresourcesSeen(); histogram_tester.ExpectBucketCount( "Previews.EligibilityReason.ResourceLoadingHints", @@ -975,7 +1004,7 @@ base::HistogramTester histogram_tester; ui_test_utils::NavigateToURL(browser(), url); - base::RunLoop().RunUntilIdle(); + RetryUntilAllExpectedSubresourcesSeen(); histogram_tester.ExpectBucketCount( "Previews.EligibilityReason.ResourceLoadingHints", @@ -1011,6 +1040,7 @@ base::HistogramTester histogram_tester; ui_test_utils::NavigateToURL(browser(), url); + RetryUntilAllExpectedSubresourcesSeen(); histogram_tester.ExpectBucketCount( "Previews.EligibilityReason.ResourceLoadingHints",
diff --git a/chrome/browser/profiles/profile_manager.cc b/chrome/browser/profiles/profile_manager.cc index 7f924f9..8b9e5e2 100644 --- a/chrome/browser/profiles/profile_manager.cc +++ b/chrome/browser/profiles/profile_manager.cc
@@ -1119,10 +1119,9 @@ // Perform initialization. if (success) { - DoFinalInit(profile, go_off_the_record); + DoFinalInit(info, go_off_the_record); if (go_off_the_record) profile = profile->GetOffTheRecordProfile(); - info->created = true; } else { profile = NULL; profiles_info_.erase(iter); @@ -1145,13 +1144,33 @@ Profile::CREATE_STATUS_LOCAL_FAIL); } -void ProfileManager::DoFinalInit(Profile* profile, bool go_off_the_record) { +Profile* ProfileManager::CreateProfileHelper(const base::FilePath& path) { + TRACE_EVENT0("browser", "ProfileManager::CreateProfileHelper"); + + return Profile::CreateProfile(path, nullptr, Profile::CREATE_MODE_SYNCHRONOUS) + .release(); +} + +std::unique_ptr<Profile> ProfileManager::CreateProfileAsyncHelper( + const base::FilePath& path, + Delegate* delegate) { + return Profile::CreateProfile(path, delegate, + Profile::CREATE_MODE_ASYNCHRONOUS); +} + +void ProfileManager::DoFinalInit(ProfileInfo* profile_info, + bool go_off_the_record) { TRACE_EVENT0("browser", "ProfileManager::DoFinalInit"); + Profile* profile = profile_info->profile.get(); DoFinalInitForServices(profile, go_off_the_record); AddProfileToStorage(profile); DoFinalInitLogging(profile); + // Set the |created| flag now so that PROFILE_ADDED handlers can use + // GetProfileByPath(). + profile_info->created = true; + content::NotificationService::current()->Notify( chrome::NOTIFICATION_PROFILE_ADDED, content::Source<Profile>(profile), @@ -1166,6 +1185,9 @@ void ProfileManager::DoFinalInitForServices(Profile* profile, bool go_off_the_record) { + if (!do_final_services_init_) + return; + TRACE_EVENT0("browser", "ProfileManager::DoFinalInitForServices"); #if BUILDFLAG(ENABLE_EXTENSIONS) @@ -1264,6 +1286,9 @@ } void ProfileManager::DoFinalInitLogging(Profile* profile) { + if (!do_final_services_init_) + return; + TRACE_EVENT0("browser", "ProfileManager::DoFinalInitLogging"); // Count number of extensions in this profile. int enabled_app_count = -1; @@ -1280,20 +1305,6 @@ base::TimeDelta::FromSeconds(112)); } -Profile* ProfileManager::CreateProfileHelper(const base::FilePath& path) { - TRACE_EVENT0("browser", "ProfileManager::CreateProfileHelper"); - - return Profile::CreateProfile(path, NULL, Profile::CREATE_MODE_SYNCHRONOUS) - .release(); -} - -std::unique_ptr<Profile> ProfileManager::CreateProfileAsyncHelper( - const base::FilePath& path, - Delegate* delegate) { - return Profile::CreateProfile(path, delegate, - Profile::CREATE_MODE_ASYNCHRONOUS); -} - ProfileManager::ProfileInfo::ProfileInfo(std::unique_ptr<Profile> profile, bool created) : profile(std::move(profile)), created(created) {} @@ -1343,20 +1354,19 @@ TRACE_EVENT0("browser", "ProfileManager::AddProfile"); DCHECK(profile); - Profile* profile_ptr = profile.get(); // Make sure that we're not loading a profile with the same ID as a profile // that's already loaded. - if (GetProfileByPathInternal(profile_ptr->GetPath())) { + if (GetProfileByPathInternal(profile->GetPath())) { NOTREACHED() << "Attempted to add profile with the same path (" - << profile_ptr->GetPath().value() + << profile->GetPath().value() << ") as an already-loaded profile."; return false; } - RegisterProfile(std::move(profile), true); - InitProfileUserPrefs(profile_ptr); - DoFinalInit(profile_ptr, ShouldGoOffTheRecord(profile_ptr)); + ProfileInfo* profile_info = RegisterProfile(std::move(profile), true); + InitProfileUserPrefs(profile_info->profile.get()); + DoFinalInit(profile_info, ShouldGoOffTheRecord(profile_info->profile.get())); return true; } @@ -1854,4 +1864,5 @@ ProfileManagerWithoutInit::ProfileManagerWithoutInit( const base::FilePath& user_data_dir) : ProfileManager(user_data_dir) { + set_do_final_services_init(false); }
diff --git a/chrome/browser/profiles/profile_manager.h b/chrome/browser/profiles/profile_manager.h index 3b5da1d..bcfb7d7 100644 --- a/chrome/browser/profiles/profile_manager.h +++ b/chrome/browser/profiles/profile_manager.h
@@ -246,11 +246,6 @@ bool is_new_profile) override; protected: - // Does final initial actions. - virtual void DoFinalInit(Profile* profile, bool go_off_the_record); - virtual void DoFinalInitForServices(Profile* profile, bool go_off_the_record); - virtual void DoFinalInitLogging(Profile* profile); - // Creates a new profile by calling into the profile's profile creation // method. Virtual so that unittests can return a TestingProfile instead // of the Profile's result. Returns null if creation fails. @@ -263,6 +258,10 @@ const base::FilePath& path, Delegate* delegate); + void set_do_final_services_init(bool do_final_services_init) { + do_final_services_init_ = do_final_services_init; + } + private: friend class TestingProfileManager; FRIEND_TEST_ALL_PREFIXES(ProfileManagerBrowserTest, DeleteAllProfiles); @@ -286,6 +285,11 @@ DISALLOW_COPY_AND_ASSIGN(ProfileInfo); }; + // Does final initial actions. + void DoFinalInit(ProfileInfo* profile_info, bool go_off_the_record); + void DoFinalInitForServices(Profile* profile, bool go_off_the_record); + void DoFinalInitLogging(Profile* profile); + // Returns the profile of the active user and / or the off the record profile // if needed. This adds the profile to the ProfileManager if it doesn't // already exist. The method will return NULL if the profile doesn't exist @@ -438,6 +442,9 @@ std::vector<Profile*> active_profiles_; bool closing_all_browsers_ = false; + // Controls whether to initialize some services. Only disabled for testing. + bool do_final_services_init_ = true; + // TODO(chrome/browser/profiles/OWNERS): Usage of this in profile_manager.cc // should likely be turned into DCHECK_CURRENTLY_ON(BrowserThread::UI) for // consistency with surrounding code in the same file but that wasn't trivial @@ -454,9 +461,8 @@ public: explicit ProfileManagerWithoutInit(const base::FilePath& user_data_dir); - protected: - void DoFinalInitForServices(Profile*, bool) override {} - void DoFinalInitLogging(Profile*) override {} + private: + DISALLOW_COPY_AND_ASSIGN(ProfileManagerWithoutInit); }; #endif // CHROME_BROWSER_PROFILES_PROFILE_MANAGER_H_
diff --git a/chrome/browser/resources/chromeos/login/security_token_pin.html b/chrome/browser/resources/chromeos/login/security_token_pin.html index b9797c2a..9ff5c11 100644 --- a/chrome/browser/resources/chromeos/login/security_token_pin.html +++ b/chrome/browser/resources/chromeos/login/security_token_pin.html
@@ -4,6 +4,39 @@ <link rel="import" href="chrome://resources/cr_elements/icons.html"> +<iron-iconset-svg name="security-token-pin-dialog-32" size="32"> + <svg> + <defs> + <g id="lock"> + <defs> + <path id="a" d="M24 12h-1.333V9.333A6.67 6.67 0 0 0 16 2.667a6.67 6.67 0 0 0-6.667 6.666V12H8a2.675 2.675 0 0 0-2.667 2.667V28c0 1.467 1.2 2.667 2.667 2.667h16c1.467 0 2.667-1.2 2.667-2.667V14.667C26.667 13.2 25.467 12 24 12zM12 9.333c0-2.213 1.787-4 4-4s4 1.787 4 4V12h-8V9.333zM24 28H8V14.667h16V28zm-8-4c1.467 0 2.667-1.2 2.667-2.667 0-1.466-1.2-2.666-2.667-2.666a2.675 2.675 0 0 0-2.667 2.666C13.333 22.8 14.533 24 16 24z"> + </path> + </defs> + <g fill="none" fill-rule="evenodd"> + <use fill="#1A73E8" fill-rule="nonzero" xlink:href="#a"></use> + <path d="M0 0h32v32H0z"></path> + </g> + </g> + </defs> + </svg> +</iron-iconset-svg> + +<iron-iconset-svg name="security-token-pin-dialog-64" size="64"> + <svg> + <defs> + <g id="lock"> + <defs> + <path id="a" d="M48 24h-2.667v-5.333c0-7.36-5.973-13.334-13.333-13.334s-13.333 5.974-13.333 13.334V24H16c-2.933 0-5.333 2.4-5.333 5.333V56c0 2.933 2.4 5.333 5.333 5.333h32c2.933 0 5.333-2.4 5.333-5.333V29.333C53.333 26.4 50.933 24 48 24zm-24-5.333c0-4.427 3.573-8 8-8s8 3.573 8 8V24H24v-5.333zM48 56H16V29.333h32V56zm-16-8c2.933 0 5.333-2.4 5.333-5.333 0-2.934-2.4-5.334-5.333-5.334-2.933 0-5.333 2.4-5.333 5.334C26.667 45.6 29.067 48 32 48z"></path> + </defs> + <g fill="none" fill-rule="evenodd"> + <use fill="#1A73E8" fill-rule="nonzero" xlink:href="#a"></use> + <path d="M0 0h64v64H0z"></path> + </g> + </g> + </defs> + </svg> +</iron-iconset-svg> + <dom-module id="security-token-pin"> <link rel="stylesheet" href="oobe_dialog_host.css"> <link rel="stylesheet" href="oobe_flex_layout.css"> @@ -12,6 +45,9 @@ <template> <oobe-dialog class="gaia-dialog" has-buttons> + <hd-iron-icon slot="oobe-icon" icon1x="security-token-pin-dialog-32:lock" + icon2x="security-token-pin-dialog-64:lock"> + </hd-iron-icon> <h1 slot="title"> [[i18nDynamic(locale, 'securityTokenPinDialogTitle')]] </h1>
diff --git a/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/BUILD.gn b/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/BUILD.gn index 2ccb355..afe509d3 100644 --- a/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/BUILD.gn +++ b/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/BUILD.gn
@@ -20,7 +20,6 @@ ":main_view", ":permission_item", ":permission_toggle", - ":permission_view_header", ":pin_to_shelf_item", ":pwa_permission_view", ":reducers", @@ -29,6 +28,7 @@ ":store_client", ":toggle_row", ":types", + ":uninstall_button", ":util", ] } @@ -83,7 +83,6 @@ ":constants", ":fake_page_handler", ":permission_item", - ":permission_view_header", ":pin_to_shelf_item", ":store_client", ] @@ -146,13 +145,6 @@ ] } -js_library("permission_view_header") { - deps = [ - ":browser_proxy", - ":store_client", - ] -} - js_library("pin_to_shelf_item") { deps = [ ":browser_proxy", @@ -219,6 +211,14 @@ ] } +js_library("uninstall_button") { + deps = [ + ":store_client", + ":util", + "//ui/webui/resources/js:cr", + ] +} + js_library("util") { deps = [ ":constants",
diff --git a/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/arc_permission_view.html b/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/arc_permission_view.html index 78168e0..969d123b 100644 --- a/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/arc_permission_view.html +++ b/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/arc_permission_view.html
@@ -3,7 +3,6 @@ <link rel="import" href="browser_proxy.html"> <link rel="import" href="icons.html"> <link rel="import" href="permission_item.html"> -<link rel="import" href="permission_view_header.html"> <link rel="import" href="shared_style.html"> <link rel="import" href="store_client.html"> <link rel="import" href="pin_to_shelf_item.html">
diff --git a/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/permission_view_header.html b/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/permission_view_header.html deleted file mode 100644 index d0c6f0c..0000000 --- a/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/permission_view_header.html +++ /dev/null
@@ -1,62 +0,0 @@ -<link rel="import" href="chrome://resources/html/polymer.html"> - -<link rel="import" href="shared_style.html"> -<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html"> -<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html"> -<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html"> - -<dom-module id="app-management-permission-view-header"> - <template> - <style include="app-management-shared-css"> - :host { - align-items: center; - display: flex; - margin: 24px auto; - max-width: var(--card-max-width); - min-width: var(--card-min-width); - } - - #permission-view-header-icon { - height: 26px; - margin-inline-end: 8px; - margin-inline-start: 24px; - width: 26px; - } - - #app-title { - flex: 1; - font-size: 16px; - overflow: hidden; - text-overflow: ellipsis; - } - - cr-icon-button { - margin: 0; - } - - #uninstall-button { - background: white; - } - - #policy-indicator { - fill: var(--google-grey-refresh-700); - margin-inline-end: 12px; - } - </style> - <cr-icon-button class="icon-arrow-back" id="backButton" - on-click="onClickBackButton_" aria-label="$i18n{back}"></cr-icon-button> - <img id="permission-view-header-icon" src="[[iconUrlFromId_(app_)]]"> - <div class="page-title">[[app_.title]]</div> - - <div id="uninstall-wrapper" title$="[[getUninstallButtonHoverText_(app_)]]"> - <template is="dom-if" if="[[isPolicyApp_(app_)]]"> - <iron-icon id="policy-indicator" icon="cr:domain"></iron-icon> - </template> - <cr-button id="uninstall-button" on-click="onClickUninstallButton_" - disabled$="[[getUninstallButtonDisableState_(app_)]]"> - $i18n{uninstall} - </cr-button> - </div> - </template> - <script src="permission_view_header.js"></script> -</dom-module>
diff --git a/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/uninstall_button.html b/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/uninstall_button.html new file mode 100644 index 0000000..04357b7 --- /dev/null +++ b/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/uninstall_button.html
@@ -0,0 +1,32 @@ +<link rel="import" href="chrome://resources/html/polymer.html"> + +<link rel="import" href="shared_style.html"> +<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html"> + +<dom-module id="app-management-uninstall-button"> + <template> + <style include="app-management-shared-css"> + #uninstall-button { + background: white; + } + + #policy-indicator { + fill: var(--google-grey-refresh-700); + margin-inline-end: 12px; + } + </style> + <!-- TODO(crbug.com/999632): rename polymer element IDs to camel case. --> + <div id="uninstall-wrapper" title$="[[getUninstallButtonHoverText_(app_)]]"> + <template is="dom-if" if="[[isPolicyApp_(app_)]]"> + <iron-icon id="policy-indicator" icon="cr:domain"></iron-icon> + </template> + <cr-button id="uninstall-button" on-click="onClickUninstallButton_" + disabled$="[[getUninstallButtonDisableState_(app_)]]"> + <!-- TODO(crbug.com/999636) rename uninstall to uninstallApp.--> + $i18n{uninstall} + </cr-button> + </div> + </template> + <script src="uninstall_button.js"></script> +</dom-module>
diff --git a/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/permission_view_header.js b/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/uninstall_button.js similarity index 74% rename from chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/permission_view_header.js rename to chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/uninstall_button.js index a6caf89..83c954e 100644 --- a/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/permission_view_header.js +++ b/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/uninstall_button.js
@@ -1,18 +1,19 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. +// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. + Polymer({ - is: 'app-management-permission-view-header', + is: 'app-management-uninstall-button', behaviors: [ app_management.StoreClient, ], properties: { - /** @type {App} */ - app_: { - type: Object, - }, + /** + * @private {App} + */ + app_: Object, }, attached: function() { @@ -21,12 +22,11 @@ }, /** - * * Returns True if the uninstall button should be disabled due to app install * type. * * @param {App} app - * @return {boolean} + * @return {?boolean} * @private */ getUninstallButtonDisableState_: function(app) { @@ -49,11 +49,11 @@ * Returns string to be shown as a tool tip over the uninstall button. * * @param {App} app - * @return {string} + * @return {?string} * @private */ getUninstallButtonHoverText_: function(app) { - // TODO(crbug.com/957795) Replace strings and add them into i18n. + // TODO(crbug.com/957795): Replace strings and add them into i18n. switch (app.installSource) { case InstallSource.kSystem: return app.title + ' cannot be uninstalled as it is part of Chrome OS.'; @@ -75,7 +75,7 @@ * Returns true if the app was installed by a policy * * @param {App} app - * @returns {boolean} + * @returns {?boolean} * @private */ isPolicyApp_: function(app) { @@ -83,26 +83,6 @@ }, /** - * @param {App} app - * @return {string} - * @private - */ - iconUrlFromId_: function(app) { - return app_management.util.getAppIcon(app); - }, - - /** - * @private - */ - onClickBackButton_: function() { - if (!window.history.state) { - this.dispatch(app_management.actions.changePage(PageType.MAIN)); - } else { - window.history.back(); - } - }, - - /** * @private */ onClickUninstallButton_: function() {
diff --git a/chrome/browser/resources/settings/chromeos/os_apps_page/os_apps_page.html b/chrome/browser/resources/settings/chromeos/os_apps_page/os_apps_page.html index 117804f..32ecca3 100644 --- a/chrome/browser/resources/settings/chromeos/os_apps_page/os_apps_page.html +++ b/chrome/browser/resources/settings/chromeos/os_apps_page/os_apps_page.html
@@ -3,6 +3,7 @@ <link rel="import" href="chrome://resources/cr_elements/cr_link_row/cr_link_row.html"> <link rel="import" href="app_management_page/app_management_page.html"> <link rel="import" href="app_management_page/app_permission_view.html"> +<link rel="import" href="app_management_page/uninstall_button.html"> <link rel="import" href="../../route.html"> <link rel="import" href="../../settings_shared_css.html"> @@ -29,6 +30,8 @@ <settings-subpage page-title="[[app_.title]]" title-icon="[[iconUrlFromId_(app_)]]"> + <app-management-uninstall-button slot="subpage-title-extra"> + </app-management-uninstall-button> <app-management-app-permission-view> </app-management-app-permission-view> </settings-subpage>
diff --git a/chrome/browser/resources/settings/controls/password_prompt_dialog.html b/chrome/browser/resources/settings/controls/password_prompt_dialog.html index d58fddd..4a0026e 100644 --- a/chrome/browser/resources/settings/controls/password_prompt_dialog.html +++ b/chrome/browser/resources/settings/controls/password_prompt_dialog.html
@@ -8,19 +8,18 @@ <dom-module id="settings-password-prompt-dialog"> <template> <style include="settings-shared"> - #passwordInput { - display: inline-block; + cr-dialog::part(dialog) { + width: 320px; } - .settings-box { + #passwordPrompt { padding: 0; } </style> - <cr-dialog id="dialog" close-text="$i18n{close}"> <div slot="title">$i18n{passwordPromptTitle}</div> <div slot="body"> - <div class="settings-box first"> + <div id="passwordPrompt" class="settings-box first line-only"> [[passwordPromptText]] </div> <cr-input id="passwordInput" type="password"
diff --git a/chrome/browser/resources/settings/internet_page/internet_subpage.js b/chrome/browser/resources/settings/internet_page/internet_subpage.js index ae0f91a..a6d80af9 100644 --- a/chrome/browser/resources/settings/internet_page/internet_subpage.js +++ b/chrome/browser/resources/settings/internet_page/internet_subpage.js
@@ -576,7 +576,7 @@ assert(this.defaultNetwork !== undefined); const networkState = e.detail; e.target.blur(); - if (this.canConnect_(networkState)) { + if (this.canAttemptConnection_(networkState)) { this.fire('network-connect', {networkState: networkState}); return; } @@ -601,11 +601,13 @@ }, /** - * Determines whether or not a network state can be connected to. + * Determines whether or not it is possible to attempt a connection to the + * provided network (e.g., whether it's possible to connect or configure the + * network for connection). * @param {!OncMojo.NetworkStateProperties} state The network state. * @private */ - canConnect_: function(state) { + canAttemptConnection_: function(state) { if (state.connectionState != mojom.ConnectionStateType.kNotConnected) { return false; } @@ -618,6 +620,11 @@ this.defaultNetwork.connectionState))) { return false; } + // Cellular networks do not have a configuration flow, so it's not possible + // to attempt a connection if the network is not conncetable. + if (state.type == mojom.NetworkType.kCellular && !state.connectable) { + return false; + } return true; },
diff --git a/chrome/browser/resources/settings/os_settings_resources.grd b/chrome/browser/resources/settings/os_settings_resources.grd index b2df032..8338d49 100644 --- a/chrome/browser/resources/settings/os_settings_resources.grd +++ b/chrome/browser/resources/settings/os_settings_resources.grd
@@ -127,12 +127,6 @@ <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_PERMISSION_TOGGLE_HTML" file="chromeos/os_apps_page/app_management_page/permission_toggle.html" type="chrome_html" /> - <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_PERMISSION_VIEW_HEADER_JS" - file="chromeos/os_apps_page/app_management_page/permission_view_header.js" - type="chrome_html" /> - <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_PERMISSION_VIEW_HEADER_HTML" - file="chromeos/os_apps_page/app_management_page/permission_view_header.html" - type="chrome_html" /> <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_PIN_TO_SHELF_ITEM_JS" file="chromeos/os_apps_page/app_management_page/pin_to_shelf_item.js" type="chrome_html" /> @@ -172,6 +166,12 @@ <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_ICONS_HTML" file="chromeos/os_apps_page/app_management_page/icons.html" type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_UNINSTALL_BUTTON_JS" + file="chromeos/os_apps_page/app_management_page/uninstall_button.js" + type="chrome_html" /> + <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PAGE_APP_UNINSTALL_BUTTON_HTML" + file="chromeos/os_apps_page/app_management_page/uninstall_button.html" + type="chrome_html" /> <structure name="IDR_OS_SETTINGS_MANAGE_A11Y_PAGE_JS" file="a11y_page/manage_a11y_page.js" type="chrome_html" />
diff --git a/chrome/browser/safe_browsing/download_protection/two_phase_uploader_unittest.cc b/chrome/browser/safe_browsing/download_protection/two_phase_uploader_unittest.cc index 4b62633..b060db9 100644 --- a/chrome/browser/safe_browsing/download_protection/two_phase_uploader_unittest.cc +++ b/chrome/browser/safe_browsing/download_protection/two_phase_uploader_unittest.cc
@@ -21,8 +21,9 @@ #include "content/public/test/test_utils.h" #include "net/base/net_errors.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" +#include "services/network/network_context.h" #include "services/network/network_service.h" -#include "services/network/test/test_network_service_client.h" +#include "services/network/test/test_network_context_client.h" #include "services/network/test/test_shared_url_loader_factory.h" #include "testing/gtest/include/gtest/gtest.h" @@ -75,17 +76,17 @@ content::GetNetworkService(); content::RunAllPendingInMessageLoop(content::BrowserThread::IO); - // A NetworkServiceClient is needed for uploads to work. - network::mojom::NetworkServiceClientPtr network_service_client_ptr; - network_service_client_ = - std::make_unique<network::TestNetworkServiceClient>( - mojo::MakeRequest(&network_service_client_ptr)); - network::NetworkService::GetNetworkServiceForTesting()->SetClient( - std::move(network_service_client_ptr), - network::mojom::NetworkServiceParams::New()); shared_url_loader_factory_ = base::MakeRefCounted<network::TestSharedURLLoaderFactory>( network::NetworkService::GetNetworkServiceForTesting()); + + // A NetworkContextClient is needed for uploads to work. + network::mojom::NetworkContextClientPtr network_context_client_ptr; + network_context_client_ = + std::make_unique<network::TestNetworkContextClient>( + mojo::MakeRequest(&network_context_client_ptr)); + shared_url_loader_factory_->network_context()->SetClient( + std::move(network_context_client_ptr)); } protected: @@ -93,7 +94,7 @@ const scoped_refptr<base::SequencedTaskRunner> task_runner_ = base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}); - std::unique_ptr<network::TestNetworkServiceClient> network_service_client_; + std::unique_ptr<network::mojom::NetworkContextClient> network_context_client_; scoped_refptr<network::TestSharedURLLoaderFactory> shared_url_loader_factory_; };
diff --git a/chrome/browser/sessions/session_service_unittest.cc b/chrome/browser/sessions/session_service_unittest.cc index ea3fd13e..855909b9 100644 --- a/chrome/browser/sessions/session_service_unittest.cc +++ b/chrome/browser/sessions/session_service_unittest.cc
@@ -35,7 +35,6 @@ #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/testing_profile_manager.h" -#include "components/sessions/content/content_serialized_navigation_builder.h" #include "components/sessions/content/content_test_helper.h" #include "components/sessions/core/serialized_navigation_entry_test_helper.h" #include "components/sessions/core/session_command.h" @@ -911,30 +910,26 @@ SessionID tab_id = SessionID::NewUnique(); ASSERT_NE(window_id, tab_id); + // Create a page state representing a HTTP body without posted passwords. + content::PageState page_state = + content::PageState::CreateForTesting(GURL(), false, "data", NULL); + // Create a TabNavigation containing page_state and representing a POST // request. - std::string post_data = "data"; - std::unique_ptr<content::NavigationEntry> entry1 = - content::NavigationEntry::Create(); - entry1->SetURL(GURL("http://google.com")); - entry1->SetTitle(base::UTF8ToUTF16("title1")); - entry1->SetHasPostData(true); - entry1->SetPostData(network::ResourceRequestBody::CreateFromBytes( - post_data.data(), post_data.size())); SerializedNavigationEntry nav1 = - sessions::ContentSerializedNavigationBuilder::FromNavigationEntry( - 0 /* == index*/, entry1.get()); + ContentTestHelper::CreateNavigation("http://google.com", "title"); + SerializedNavigationEntryTestHelper::SetEncodedPageState( + page_state.ToEncodedData(), &nav1); + SerializedNavigationEntryTestHelper::SetHasPostData(true, &nav1); + nav1.set_index(0); // Create a TabNavigation containing page_state and representing a normal // request. - std::unique_ptr<content::NavigationEntry> entry2 = - content::NavigationEntry::Create(); - entry2->SetURL(GURL("http://google.com/nopost")); - entry2->SetTitle(base::UTF8ToUTF16("title2")); - entry2->SetHasPostData(false); SerializedNavigationEntry nav2 = - sessions::ContentSerializedNavigationBuilder::FromNavigationEntry( - 1 /* == index*/, entry2.get()); + ContentTestHelper::CreateNavigation("http://google.com/nopost", "title"); + SerializedNavigationEntryTestHelper::SetEncodedPageState( + page_state.ToEncodedData(), &nav2); + nav2.set_index(1); helper_.PrepareTabInWindow(window_id, tab_id, 0, true); UpdateNavigation(window_id, tab_id, nav1, true);
diff --git a/chrome/browser/sharing/sharing_service.cc b/chrome/browser/sharing/sharing_service.cc index 0beffce1..93a5b42 100644 --- a/chrome/browser/sharing/sharing_service.cc +++ b/chrome/browser/sharing/sharing_service.cc
@@ -123,7 +123,7 @@ std::vector<std::unique_ptr<syncer::DeviceInfo>> SharingService::GetDeviceCandidates(int required_capabilities) const { std::vector<std::unique_ptr<syncer::DeviceInfo>> device_candidates; - if (!IsSyncEnabled()) + if (IsSyncDisabled()) return device_candidates; std::vector<std::unique_ptr<syncer::DeviceInfo>> all_devices = @@ -396,10 +396,14 @@ } bool SharingService::IsSyncDisabled() const { + // TODO(alexchau): Better way to make + // ClickToCallBrowserTest.ContextMenu_DevicesAvailable_SyncTurnedOff pass + // without unnecessarily checking SyncService::GetDisableReasons. return sync_service_ && (sync_service_->GetTransportState() == syncer::SyncService::TransportState::DISABLED || (sync_service_->GetTransportState() == syncer::SyncService::TransportState::ACTIVE && - !sync_service_->GetActiveDataTypes().Has(syncer::PREFERENCES))); + !sync_service_->GetActiveDataTypes().Has(syncer::PREFERENCES)) || + sync_service_->GetDisableReasons()); }
diff --git a/chrome/browser/ui/app_list/app_list_client_impl.cc b/chrome/browser/ui/app_list/app_list_client_impl.cc index a6a7b86..43f71a6 100644 --- a/chrome/browser/ui/app_list/app_list_client_impl.cc +++ b/chrome/browser/ui/app_list/app_list_client_impl.cc
@@ -297,6 +297,7 @@ const user_manager::User* active_user) { if (!active_user->is_profile_created()) return; + UpdateProfile(); } @@ -304,8 +305,9 @@ Profile* profile = ProfileManager::GetActiveUserProfile(); app_list::AppListSyncableService* syncable_service = app_list::AppListSyncableServiceFactory::GetForProfile(profile); - DCHECK(syncable_service); - SetProfile(profile); + // AppListSyncableService is null in tests. + if (syncable_service) + SetProfile(profile); } void AppListClientImpl::SetProfile(Profile* new_profile) {
diff --git a/chrome/browser/ui/app_list/app_list_client_impl_browsertest.cc b/chrome/browser/ui/app_list/app_list_client_impl_browsertest.cc index cdab02b..80d0e398 100644 --- a/chrome/browser/ui/app_list/app_list_client_impl_browsertest.cc +++ b/chrome/browser/ui/app_list/app_list_client_impl_browsertest.cc
@@ -24,7 +24,6 @@ #include "chrome/browser/apps/platform_apps/app_browsertest_util.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/login/demo_mode/demo_session.h" -#include "chrome/browser/chromeos/login/users/fake_chrome_user_manager.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" @@ -33,7 +32,6 @@ #include "chrome/browser/ui/app_list/app_list_client_impl.h" #include "chrome/browser/ui/app_list/app_list_controller_delegate.h" #include "chrome/browser/ui/app_list/app_list_model_updater.h" -#include "chrome/browser/ui/app_list/app_list_syncable_service_factory.h" #include "chrome/browser/ui/app_list/chrome_app_list_item.h" #include "chrome/browser/ui/app_list/search/search_controller.h" #include "chrome/browser/ui/app_list/test/chrome_app_list_test_support.h" @@ -48,7 +46,6 @@ #include "chromeos/constants/chromeos_switches.h" #include "components/browser_sync/browser_sync_switches.h" #include "components/prefs/pref_service.h" -#include "components/user_manager/scoped_user_manager.h" #include "components/user_manager/user_names.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_types.h"
diff --git a/chrome/browser/ui/ash/launcher_drag_interactive_uitest.cc b/chrome/browser/ui/ash/launcher_drag_interactive_uitest.cc index d01ff88..08128e5 100644 --- a/chrome/browser/ui/ash/launcher_drag_interactive_uitest.cc +++ b/chrome/browser/ui/ash/launcher_drag_interactive_uitest.cc
@@ -21,16 +21,20 @@ // Test launcher drag performance in clamshell mode. // TODO(oshima): Add test for tablet mode. -class LauncherDragTest : public UIPerformanceTest { +class LauncherDragTest : public UIPerformanceTest, + public ::testing::WithParamInterface<bool> { public: LauncherDragTest() = default; ~LauncherDragTest() override = default; // UIPerformanceTest: void SetUpOnMainThread() override { + tablet_mode_ = GetParam(); UIPerformanceTest::SetUpOnMainThread(); test::PopulateDummyAppListItems(100); + if (tablet_mode_) + ash::ShellTestApi().SetTabletModeEnabledForTest(true); // Ash may not be ready to receive events right away. int warmup_seconds = base::SysInfo::IsRunningOnChromeOS() ? 5 : 1; base::RunLoop run_loop; @@ -42,7 +46,8 @@ // UIPerformanceTest: std::vector<std::string> GetUMAHistogramNames() const override { return { - "Apps.StateTransition.Drag.PresentationTime.ClamshellMode", + base::StringPrintf("Apps.StateTransition.Drag.PresentationTime.%s", + tablet_mode_ ? "TabletMode" : "ClamshellMode"), }; } @@ -53,11 +58,13 @@ } private: + bool tablet_mode_ = false; + DISALLOW_COPY_AND_ASSIGN(LauncherDragTest); }; // Drag to open the launcher from shelf. -IN_PROC_BROWSER_TEST_F(LauncherDragTest, Open) { +IN_PROC_BROWSER_TEST_P(LauncherDragTest, Open) { BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser()); aura::Window* browser_window = browser_view->GetWidget()->GetNativeWindow(); ash::ShellTestApi shell_test_api; @@ -79,7 +86,7 @@ } // Drag to close the launcher. -IN_PROC_BROWSER_TEST_F(LauncherDragTest, Close) { +IN_PROC_BROWSER_TEST_P(LauncherDragTest, Close) { BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser()); aura::Window* browser_window = browser_view->GetWidget()->GetNativeWindow(); ash::ShellTestApi shell_test_api; @@ -104,3 +111,7 @@ shell_test_api.WaitForLauncherAnimationState(ash::AppListViewState::kClosed); } + +INSTANTIATE_TEST_SUITE_P(, + LauncherDragTest, + /*tablet_mode=*/::testing::Bool());
diff --git a/chrome/browser/ui/browser.cc b/chrome/browser/ui/browser.cc index 846dade1..17f2591a 100644 --- a/chrome/browser/ui/browser.cc +++ b/chrome/browser/ui/browser.cc
@@ -543,7 +543,7 @@ int num_downloads; if (!browser_defaults::kBrowserAliveWithNoWindows && OkToCloseWithInProgressDownloads(&num_downloads) == - DOWNLOAD_CLOSE_BROWSER_SHUTDOWN) { + DownloadCloseType::kBrowserShutdown) { DownloadCoreService::CancelAllDownloads(); } @@ -830,7 +830,7 @@ //////////////////////////////////////////////////////////////////////////////// // In-progress download termination handling: -Browser::DownloadClosePreventionType Browser::OkToCloseWithInProgressDownloads( +Browser::DownloadCloseType Browser::OkToCloseWithInProgressDownloads( int* num_downloads_blocking) const { DCHECK(num_downloads_blocking); *num_downloads_blocking = 0; @@ -838,12 +838,12 @@ // If we're not running a full browser process with a profile manager // (testing), it's ok to close the browser. if (!g_browser_process->profile_manager()) - return DOWNLOAD_CLOSE_OK; + return DownloadCloseType::kOk; int total_download_count = DownloadCoreService::NonMaliciousDownloadCountAllProfiles(); if (total_download_count == 0) - return DOWNLOAD_CLOSE_OK; // No downloads; can definitely close. + return DownloadCloseType::kOk; // No downloads; can definitely close. // Figure out how many windows are open total, and associated with this // profile, that are relevant for the ok-to-close decision. @@ -865,7 +865,7 @@ // which would cancel all current downloads. if (total_window_count == 0) { *num_downloads_blocking = total_download_count; - return DOWNLOAD_CLOSE_BROWSER_SHUTDOWN; + return DownloadCloseType::kBrowserShutdown; } // If there aren't any other windows on our profile, and we're an incognito @@ -878,11 +878,13 @@ profile()->IsOffTheRecord()) { *num_downloads_blocking = download_core_service->NonMaliciousDownloadCount(); - return DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE; + return profile()->IsGuestSession() + ? DownloadCloseType::kLastWindowInGuestSession + : DownloadCloseType::kLastWindowInIncognitoProfile; } // Those are the only conditions under which we will block shutdown. - return DOWNLOAD_CLOSE_OK; + return DownloadCloseType::kOk; } //////////////////////////////////////////////////////////////////////////////// @@ -2472,9 +2474,9 @@ return cancel_download_confirmation_state_ != WAITING_FOR_RESPONSE; int num_downloads_blocking; - Browser::DownloadClosePreventionType dialog_type = + DownloadCloseType dialog_type = OkToCloseWithInProgressDownloads(&num_downloads_blocking); - if (dialog_type == DOWNLOAD_CLOSE_OK) + if (dialog_type == DownloadCloseType::kOk) return true; // Closing this window will kill some downloads; prompt to make sure
diff --git a/chrome/browser/ui/browser.h b/chrome/browser/ui/browser.h index 253a8e19..6cf62a9a 100644 --- a/chrome/browser/ui/browser.h +++ b/chrome/browser/ui/browser.h
@@ -151,17 +151,21 @@ // The context for a download blocked notification from // OkToCloseWithInProgressDownloads. - enum DownloadClosePreventionType { + enum class DownloadCloseType { // Browser close is not blocked by download state. - DOWNLOAD_CLOSE_OK, + kOk, // The browser is shutting down and there are active downloads // that would be cancelled. - DOWNLOAD_CLOSE_BROWSER_SHUTDOWN, + kBrowserShutdown, // There are active downloads associated with this incognito profile // that would be canceled. - DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE, + kLastWindowInIncognitoProfile, + + // There are active downloads associated with this guest session + // that would be canceled. + kLastWindowInGuestSession, }; // Represents the result of the user being warned before closing the browser. @@ -443,7 +447,7 @@ // If executing downloads would be cancelled by this window close, // then |*num_downloads_blocking| is updated with how many downloads // would be canceled if the close continued. - DownloadClosePreventionType OkToCloseWithInProgressDownloads( + DownloadCloseType OkToCloseWithInProgressDownloads( int* num_downloads_blocking) const; // External state change handling //////////////////////////////////////////// @@ -620,6 +624,7 @@ FRIEND_TEST_ALL_PREFIXES(AppModeTest, EnableAppModeTest); FRIEND_TEST_ALL_PREFIXES(BrowserCommandControllerTest, IsReservedCommandOrKeyIsApp); + FRIEND_TEST_ALL_PREFIXES(BrowserCloseTest, LastGuest); FRIEND_TEST_ALL_PREFIXES(BrowserCloseTest, LastIncognito); FRIEND_TEST_ALL_PREFIXES(BrowserCloseTest, LastRegular); FRIEND_TEST_ALL_PREFIXES(BrowserCommandControllerTest, AppFullScreen);
diff --git a/chrome/browser/ui/browser_close_unittest.cc b/chrome/browser/ui/browser_close_unittest.cc index 6fdbc57..b06a9bb 100644 --- a/chrome/browser/ui/browser_close_unittest.cc +++ b/chrome/browser/ui/browser_close_unittest.cc
@@ -130,6 +130,14 @@ return otr_profile; } + Profile* CreateGuestProfile(int windows, int downloads) { + TestingProfile* profile = profile_manager_.CreateGuestProfile(); + Profile* incognito_profile = profile->GetOffTheRecordProfile(); + ConfigureCreatedProfile(incognito_profile, windows, downloads); + + return incognito_profile; + } + Browser* GetProfileBrowser(Profile* profile, int index) { CHECK(browsers_.end() != browsers_.find(profile)); CHECK_GT(browsers_[profile].size(), static_cast<size_t>(index)); @@ -186,7 +194,7 @@ Browser* browser = GetProfileBrowser(incognito_profile, 0); int num_downloads_blocking = 0; - EXPECT_EQ(Browser::DOWNLOAD_CLOSE_BROWSER_SHUTDOWN, + EXPECT_EQ(Browser::DownloadCloseType::kBrowserShutdown, browser->OkToCloseWithInProgressDownloads(&num_downloads_blocking)); EXPECT_EQ(num_downloads_blocking, 1); } @@ -198,7 +206,7 @@ Browser* browser(GetProfileBrowser(incognito_profile, 0)); int num_downloads_blocking = 0; - EXPECT_EQ(Browser::DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE, + EXPECT_EQ(Browser::DownloadCloseType::kLastWindowInIncognitoProfile, browser->OkToCloseWithInProgressDownloads(&num_downloads_blocking)); EXPECT_EQ(num_downloads_blocking, 1); @@ -212,7 +220,7 @@ Browser* browser = GetProfileBrowser(incognito_profile, 0); int num_downloads_blocking = 0; - EXPECT_EQ(Browser::DOWNLOAD_CLOSE_OK, + EXPECT_EQ(Browser::DownloadCloseType::kOk, browser->OkToCloseWithInProgressDownloads(&num_downloads_blocking)); } @@ -227,7 +235,7 @@ Browser* browser = GetProfileBrowser(incognito_profile1, 0); int num_downloads_blocking = 0; - EXPECT_EQ(Browser::DOWNLOAD_CLOSE_OK, + EXPECT_EQ(Browser::DownloadCloseType::kOk, browser->OkToCloseWithInProgressDownloads(&num_downloads_blocking)); } @@ -238,7 +246,7 @@ Browser* browser = GetProfileBrowser(incognito_profile, 0); int num_downloads_blocking = 0; - EXPECT_EQ(Browser::DOWNLOAD_CLOSE_OK, + EXPECT_EQ(Browser::DownloadCloseType::kOk, browser->OkToCloseWithInProgressDownloads(&num_downloads_blocking)); } @@ -248,7 +256,7 @@ Browser* browser = GetProfileBrowser(profile, 0); int num_downloads_blocking = 0; - EXPECT_EQ(Browser::DOWNLOAD_CLOSE_OK, + EXPECT_EQ(Browser::DownloadCloseType::kOk, browser->OkToCloseWithInProgressDownloads(&num_downloads_blocking)); } @@ -258,7 +266,7 @@ Browser* browser = GetProfileBrowser(profile, 0); int num_downloads_blocking = 0; - EXPECT_EQ(Browser::DOWNLOAD_CLOSE_BROWSER_SHUTDOWN, + EXPECT_EQ(Browser::DownloadCloseType::kBrowserShutdown, browser->OkToCloseWithInProgressDownloads(&num_downloads_blocking)); EXPECT_EQ(num_downloads_blocking, 1); #if defined(OS_MACOSX) @@ -277,7 +285,7 @@ Browser* browser = GetProfileBrowser(profile1, 0); int num_downloads_blocking = 0; - EXPECT_EQ(Browser::DOWNLOAD_CLOSE_BROWSER_SHUTDOWN, + EXPECT_EQ(Browser::DownloadCloseType::kBrowserShutdown, browser->OkToCloseWithInProgressDownloads(&num_downloads_blocking)); EXPECT_EQ(num_downloads_blocking, 1); } @@ -290,7 +298,7 @@ Browser* browser = GetProfileBrowser(profile, 0); int num_downloads_blocking = 0; - EXPECT_EQ(Browser::DOWNLOAD_CLOSE_OK, + EXPECT_EQ(Browser::DownloadCloseType::kOk, browser->OkToCloseWithInProgressDownloads(&num_downloads_blocking)); } @@ -302,7 +310,7 @@ Browser* browser = GetProfileBrowser(profile, 0); int num_downloads_blocking = 0; - EXPECT_EQ(Browser::DOWNLOAD_CLOSE_OK, + EXPECT_EQ(Browser::DownloadCloseType::kOk, browser->OkToCloseWithInProgressDownloads(&num_downloads_blocking)); } @@ -315,7 +323,7 @@ Browser* browser = GetProfileBrowser(profile1, 0); int num_downloads_blocking = 0; - EXPECT_EQ(Browser::DOWNLOAD_CLOSE_OK, + EXPECT_EQ(Browser::DownloadCloseType::kOk, browser->OkToCloseWithInProgressDownloads(&num_downloads_blocking)); } @@ -327,7 +335,7 @@ Browser* browser = GetProfileBrowser(profile, 0); int num_downloads_blocking = 0; - EXPECT_EQ(Browser::DOWNLOAD_CLOSE_OK, + EXPECT_EQ(Browser::DownloadCloseType::kOk, browser->OkToCloseWithInProgressDownloads(&num_downloads_blocking)); } @@ -338,7 +346,7 @@ Browser* browser = GetProfileBrowser(profile, 0); int num_downloads_blocking = 0; - EXPECT_EQ(Browser::DOWNLOAD_CLOSE_BROWSER_SHUTDOWN, + EXPECT_EQ(Browser::DownloadCloseType::kBrowserShutdown, browser->OkToCloseWithInProgressDownloads(&num_downloads_blocking)); EXPECT_EQ(2, num_downloads_blocking); } @@ -351,7 +359,52 @@ Browser* browser = GetProfileBrowser(incognito_profile, 0); int num_downloads_blocking = 0; - EXPECT_EQ(Browser::DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE, + EXPECT_EQ(Browser::DownloadCloseType::kLastWindowInIncognitoProfile, browser->OkToCloseWithInProgressDownloads(&num_downloads_blocking)); EXPECT_EQ(2, num_downloads_blocking); } + +// Last window close (guest window) will trigger warning. +TEST_F(BrowserCloseTest, LastWindowGuest) { + Profile* guest_profile = CreateGuestProfile(1, 1); + Browser* browser = GetProfileBrowser(guest_profile, 0); + + int num_downloads_blocking = 0; + EXPECT_EQ(Browser::DownloadCloseType::kBrowserShutdown, + browser->OkToCloseWithInProgressDownloads(&num_downloads_blocking)); + EXPECT_EQ(num_downloads_blocking, 1); +} + +// Last guest window close triggers download warning. +TEST_F(BrowserCloseTest, LastGuest) { + CreateProfile(1, 0); + Profile* profile = CreateGuestProfile(1, 1); + Browser* browser(GetProfileBrowser(profile, 0)); + + int num_downloads_blocking = 0; + EXPECT_EQ(Browser::DownloadCloseType::kLastWindowInGuestSession, + browser->OkToCloseWithInProgressDownloads(&num_downloads_blocking)); + EXPECT_EQ(num_downloads_blocking, 1); + + EXPECT_EQ(false, browser->CanCloseWithInProgressDownloads()); +} + +// Last guest window close with no downloads => no warning. +TEST_F(BrowserCloseTest, LastGuestNoDownloads) { + Profile* profile = CreateGuestProfile(1, 0); + Browser* browser = GetProfileBrowser(profile, 0); + + int num_downloads_blocking = 0; + EXPECT_EQ(Browser::DownloadCloseType::kOk, + browser->OkToCloseWithInProgressDownloads(&num_downloads_blocking)); +} + +// Non-last guest window => no warning. +TEST_F(BrowserCloseTest, NonLastGuest) { + Profile* profile = CreateGuestProfile(2, 1); + Browser* browser = GetProfileBrowser(profile, 0); + + int num_downloads_blocking = 0; + EXPECT_EQ(Browser::DownloadCloseType::kOk, + browser->OkToCloseWithInProgressDownloads(&num_downloads_blocking)); +}
diff --git a/chrome/browser/ui/browser_navigator.cc b/chrome/browser/ui/browser_navigator.cc index d115e0b..f7e171b 100644 --- a/chrome/browser/ui/browser_navigator.cc +++ b/chrome/browser/ui/browser_navigator.cc
@@ -768,6 +768,9 @@ return host != chrome::kChromeUIAppLauncherPageHost && host != chrome::kChromeUIAppManagementHost && host != chrome::kChromeUISettingsHost && +#if defined(OS_CHROMEOS) + host != chrome::kChromeUIOSSettingsHost && +#endif host != chrome::kChromeUIHelpHost && host != chrome::kChromeUIHistoryHost && host != chrome::kChromeUIExtensionsHost &&
diff --git a/chrome/browser/ui/browser_navigator_browsertest.cc b/chrome/browser/ui/browser_navigator_browsertest.cc index cf3266c..92572514 100644 --- a/chrome/browser/ui/browser_navigator_browsertest.cc +++ b/chrome/browser/ui/browser_navigator_browsertest.cc
@@ -169,7 +169,9 @@ browser()->tab_strip_model()->GetActiveWebContents()->GetURL()); } -void BrowserNavigatorTest::RunUseNonIncognitoWindowTest(const GURL& url) { +void BrowserNavigatorTest::RunUseNonIncognitoWindowTest( + const GURL& url, + const ui::PageTransition& page_transition) { Browser* incognito_browser = CreateIncognitoBrowser(); EXPECT_EQ(2u, chrome::GetTotalBrowserCount()); @@ -181,6 +183,7 @@ params.disposition = WindowOpenDisposition::SINGLETON_TAB; params.url = url; params.window_action = NavigateParams::SHOW_WINDOW; + params.transition = page_transition; Navigate(¶ms); // This page should be opened in browser() window. @@ -1315,7 +1318,8 @@ // window. IN_PROC_BROWSER_TEST_F(BrowserNavigatorTest, Disposition_Settings_UseNonIncognitoWindow) { - RunUseNonIncognitoWindowTest(GetSettingsURL()); + RunUseNonIncognitoWindowTest( + GetSettingsURL(), ui::PageTransition::PAGE_TRANSITION_AUTO_BOOKMARK); } // This test verifies that the view-source settings page isn't opened in the @@ -1337,7 +1341,8 @@ std::string view_source(content::kViewSourceScheme); view_source.append(":"); view_source.append(chrome::kChromeUISettingsURL); - RunUseNonIncognitoWindowTest(GURL(view_source)); + RunUseNonIncognitoWindowTest( + GURL(view_source), ui::PageTransition::PAGE_TRANSITION_AUTO_BOOKMARK); } // This test verifies that the settings page isn't opened in the incognito @@ -1373,7 +1378,9 @@ // window. IN_PROC_BROWSER_TEST_F(BrowserNavigatorTest, Disposition_Bookmarks_UseNonIncognitoWindow) { - RunUseNonIncognitoWindowTest(GURL(chrome::kChromeUIBookmarksURL)); + RunUseNonIncognitoWindowTest( + GURL(chrome::kChromeUIBookmarksURL), + ui::PageTransition::PAGE_TRANSITION_AUTO_BOOKMARK); } // Bookmark manager is expected to always open in normal mode regardless
diff --git a/chrome/browser/ui/browser_navigator_browsertest.h b/chrome/browser/ui/browser_navigator_browsertest.h index 79af5d6..c6379bb 100644 --- a/chrome/browser/ui/browser_navigator_browsertest.h +++ b/chrome/browser/ui/browser_navigator_browsertest.h
@@ -36,7 +36,8 @@ bool initialize_renderer); void RunSuppressTest(WindowOpenDisposition disposition); - void RunUseNonIncognitoWindowTest(const GURL& url); + void RunUseNonIncognitoWindowTest(const GURL& url, + const ui::PageTransition& page_transition); void RunDoNothingIfIncognitoIsForcedTest(const GURL& url); // content::NotificationObserver:
diff --git a/chrome/browser/ui/browser_navigator_browsertest_chromeos.cc b/chrome/browser/ui/browser_navigator_browsertest_chromeos.cc index 4bc4569..1d8d041 100644 --- a/chrome/browser/ui/browser_navigator_browsertest_chromeos.cc +++ b/chrome/browser/ui/browser_navigator_browsertest_chromeos.cc
@@ -39,6 +39,14 @@ using BrowserNavigatorTestChromeOS = BrowserNavigatorTest; +// This test verifies that the OS Settings page isn't opened in the incognito +// window. +IN_PROC_BROWSER_TEST_F(BrowserNavigatorTestChromeOS, + Disposition_OSSettings_UseNonIncognitoWindow) { + RunUseNonIncognitoWindowTest(GURL(chrome::kChromeUIOSSettingsURL), + ui::PageTransition::PAGE_TRANSITION_TYPED); +} + // Verifies that the OS settings page opens in a standalone surface when // accessed via link or url. IN_PROC_BROWSER_TEST_F(BrowserNavigatorTestChromeOS, NavigateToOSSettings) {
diff --git a/chrome/browser/ui/browser_window.h b/chrome/browser/ui/browser_window.h index 9622e01..728fa18a 100644 --- a/chrome/browser/ui/browser_window.h +++ b/chrome/browser/ui/browser_window.h
@@ -401,7 +401,7 @@ // This method should call |callback| with the user's response. virtual void ConfirmBrowserCloseWithPendingDownloads( int download_count, - Browser::DownloadClosePreventionType dialog_type, + Browser::DownloadCloseType dialog_type, bool app_modal, const base::Callback<void(bool)>& callback) = 0;
diff --git a/chrome/browser/ui/global_media_controls/media_toolbar_button_controller.cc b/chrome/browser/ui/global_media_controls/media_toolbar_button_controller.cc index 69e1242f..61278bb 100644 --- a/chrome/browser/ui/global_media_controls/media_toolbar_button_controller.cc +++ b/chrome/browser/ui/global_media_controls/media_toolbar_button_controller.cc
@@ -13,6 +13,7 @@ #include "services/service_manager/public/cpp/connector.h" MediaToolbarButtonController::MediaToolbarButtonController( + const base::UnguessableToken& source_id, service_manager::Connector* connector, MediaToolbarButtonControllerDelegate* delegate) : connector_(connector), delegate_(delegate) { @@ -30,12 +31,14 @@ // Connect to receive audio focus events. connector_->Connect(media_session::mojom::kServiceName, audio_focus_remote_.BindNewPipeAndPassReceiver()); - audio_focus_remote_->AddObserver( - audio_focus_observer_receiver_.BindNewPipeAndPassRemote()); + audio_focus_remote_->AddSourceObserver( + source_id, audio_focus_observer_receiver_.BindNewPipeAndPassRemote()); - audio_focus_remote_->GetFocusRequests(base::BindOnce( - &MediaToolbarButtonController::OnReceivedAudioFocusRequests, - weak_ptr_factory_.GetWeakPtr())); + audio_focus_remote_->GetSourceFocusRequests( + source_id, + base::BindOnce( + &MediaToolbarButtonController::OnReceivedAudioFocusRequests, + weak_ptr_factory_.GetWeakPtr())); } MediaToolbarButtonController::~MediaToolbarButtonController() = default;
diff --git a/chrome/browser/ui/global_media_controls/media_toolbar_button_controller.h b/chrome/browser/ui/global_media_controls/media_toolbar_button_controller.h index f639d98..1c52184 100644 --- a/chrome/browser/ui/global_media_controls/media_toolbar_button_controller.h +++ b/chrome/browser/ui/global_media_controls/media_toolbar_button_controller.h
@@ -35,7 +35,8 @@ : public media_session::mojom::AudioFocusObserver, public media_message_center::MediaNotificationController { public: - MediaToolbarButtonController(service_manager::Connector* connector, + MediaToolbarButtonController(const base::UnguessableToken& source_id, + service_manager::Connector* connector, MediaToolbarButtonControllerDelegate* delegate); ~MediaToolbarButtonController() override;
diff --git a/chrome/browser/ui/global_media_controls/media_toolbar_button_controller_unittest.cc b/chrome/browser/ui/global_media_controls/media_toolbar_button_controller_unittest.cc index 5d0a766..ff2c39c 100644 --- a/chrome/browser/ui/global_media_controls/media_toolbar_button_controller_unittest.cc +++ b/chrome/browser/ui/global_media_controls/media_toolbar_button_controller_unittest.cc
@@ -82,8 +82,8 @@ ~MediaToolbarButtonControllerTest() override = default; void SetUp() override { - controller_ = - std::make_unique<MediaToolbarButtonController>(nullptr, &delegate_); + controller_ = std::make_unique<MediaToolbarButtonController>( + base::UnguessableToken::Create(), nullptr, &delegate_); } protected:
diff --git a/chrome/browser/ui/tabs/existing_tab_group_sub_menu_model.cc b/chrome/browser/ui/tabs/existing_tab_group_sub_menu_model.cc index e6727c21..2ff68ba3 100644 --- a/chrome/browser/ui/tabs/existing_tab_group_sub_menu_model.cc +++ b/chrome/browser/ui/tabs/existing_tab_group_sub_menu_model.cc
@@ -23,9 +23,8 @@ // Start command ids after the parent menu's ids to avoid collisions. int group_index = kFirstCommandIndex; for (TabGroupId group : model_->ListTabGroups()) { - if (ShouldShowGroup(model_, context_index_, group)) { - AddItem(group_index, model_->GetVisualDataForGroup(group)->title()); - } + if (ShouldShowGroup(model_, context_index_, group)) + AddItem(group_index, model_->GetUserVisibleGroupTitle(group)); group_index++; } }
diff --git a/chrome/browser/ui/tabs/tab_group_visual_data.cc b/chrome/browser/ui/tabs/tab_group_visual_data.cc index 572c2bd..ba9d322 100644 --- a/chrome/browser/ui/tabs/tab_group_visual_data.cc +++ b/chrome/browser/ui/tabs/tab_group_visual_data.cc
@@ -9,10 +9,7 @@ #include "third_party/skia/include/utils/SkRandom.h" TabGroupVisualData::TabGroupVisualData() { - static int next_placeholder_title_number = 1; - title_ = base::ASCIIToUTF16( - "Group " + base::NumberToString(next_placeholder_title_number)); - ++next_placeholder_title_number; + title_ = base::ASCIIToUTF16(""); static SkRandom rand; color_ = rand.nextU() | 0xff000000;
diff --git a/chrome/browser/ui/tabs/tab_strip_model.cc b/chrome/browser/ui/tabs/tab_strip_model.cc index 4142c02f..cfb3019 100644 --- a/chrome/browser/ui/tabs/tab_strip_model.cc +++ b/chrome/browser/ui/tabs/tab_strip_model.cc
@@ -16,6 +16,7 @@ #include "base/metrics/user_metrics.h" #include "base/numerics/ranges.h" #include "base/stl_util.h" +#include "base/strings/string_util.h" #include "build/build_config.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" @@ -28,6 +29,7 @@ #include "chrome/browser/send_tab_to_self/send_tab_to_self_util.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" +#include "chrome/browser/ui/tab_ui_helper.h" #include "chrome/browser/ui/tabs/tab_group_id.h" #include "chrome/browser/ui/tabs/tab_group_visual_data.h" #include "chrome/browser/ui/tabs/tab_strip_model_delegate.h" @@ -37,6 +39,7 @@ #include "chrome/browser/ui/web_applications/web_app_launch_utils.h" #include "chrome/browser/ui/web_contents_sizer.h" #include "chrome/common/url_constants.h" +#include "chrome/grit/generated_resources.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/feature_engagement/buildflags.h" #include "components/web_modal/web_contents_modal_dialog_manager.h" @@ -46,6 +49,8 @@ #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_observer.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/gfx/text_elider.h" using base::UserMetricsAction; using content::WebContents; @@ -809,6 +814,25 @@ return &group_data_.at(group).visual_data(); } +base::string16 TabStripModel::GetUserVisibleGroupTitle(TabGroupId group) const { + base::string16 title = GetVisualDataForGroup(group)->title(); + if (title.empty()) { + // Generate a descriptive placeholder title for the group. + std::vector<int> tabs_in_group = ListTabsInGroup(group); + TabUIHelper* const tab_ui_helper = + TabUIHelper::FromWebContents(GetWebContentsAt(tabs_in_group.front())); + constexpr size_t kContextMenuTabTitleMaxLength = 30; + base::string16 format_string = l10n_util::GetPluralStringFUTF16( + IDS_TAB_CXMENU_PLACEHOLDER_GROUP_TITLE, tabs_in_group.size() - 1); + base::string16 short_title; + gfx::ElideString(tab_ui_helper->GetTitle(), kContextMenuTabTitleMaxLength, + &short_title); + title = + base::ReplaceStringPlaceholders(format_string, {short_title}, nullptr); + } + return title; +} + void TabStripModel::SetVisualDataForGroup(TabGroupId group, TabGroupVisualData data) { DCHECK(!reentrancy_guard_);
diff --git a/chrome/browser/ui/tabs/tab_strip_model.h b/chrome/browser/ui/tabs/tab_strip_model.h index 0f92f861..66b9d22 100644 --- a/chrome/browser/ui/tabs/tab_strip_model.h +++ b/chrome/browser/ui/tabs/tab_strip_model.h
@@ -18,6 +18,7 @@ #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/optional.h" +#include "base/strings/string16.h" #include "base/time/time.h" #include "base/timer/timer.h" #include "build/build_config.h" @@ -339,6 +340,10 @@ // SetVisualDataForGroup is called for |group|. const TabGroupVisualData* GetVisualDataForGroup(TabGroupId group) const; + // Returns a title for |group| that can be shown in the UI, generating a + // descriptive placeholder if the user has not named the group. + base::string16 GetUserVisibleGroupTitle(TabGroupId group) const; + // Sets the visual data for |group|. Notifies observers of the change. void SetVisualDataForGroup(TabGroupId group, TabGroupVisualData data);
diff --git a/chrome/browser/ui/views/chrome_layout_provider.cc b/chrome/browser/ui/views/chrome_layout_provider.cc index 59d065a..3ee2466 100644 --- a/chrome/browser/ui/views/chrome_layout_provider.cc +++ b/chrome/browser/ui/views/chrome_layout_provider.cc
@@ -72,11 +72,12 @@ case INSETS_TOAST: return gfx::Insets(0, kHarmonyLayoutUnit); case INSETS_TAB_GROUP_TITLE_CHIP: - return gfx::Insets(2, 4); + return gfx::Insets(0, 12); default: return LayoutProvider::GetInsetsMetric(metric); } } + int ChromeLayoutProvider::GetDistanceMetric(int metric) const { DCHECK_GE(metric, views::VIEWS_INSETS_MAX); switch (metric) { @@ -144,7 +145,7 @@ case DISTANCE_SUBSECTION_HORIZONTAL_INDENT: return 0; case DISTANCE_TAB_GROUP_TITLE_CHIP_MARGIN: - return 8; + return 4; case DISTANCE_TOAST_CONTROL_VERTICAL: return 8; case DISTANCE_TOAST_LABEL_VERTICAL:
diff --git a/chrome/browser/ui/views/download/download_in_progress_dialog_view.cc b/chrome/browser/ui/views/download/download_in_progress_dialog_view.cc index a5d77d74..312a71f 100644 --- a/chrome/browser/ui/views/download/download_in_progress_dialog_view.cc +++ b/chrome/browser/ui/views/download/download_in_progress_dialog_view.cc
@@ -19,7 +19,7 @@ void DownloadInProgressDialogView::Show( gfx::NativeWindow parent, int download_count, - Browser::DownloadClosePreventionType dialog_type, + Browser::DownloadCloseType dialog_type, bool app_modal, const base::Callback<void(bool)>& callback) { DownloadInProgressDialogView* window = new DownloadInProgressDialogView( @@ -29,7 +29,7 @@ DownloadInProgressDialogView::DownloadInProgressDialogView( int download_count, - Browser::DownloadClosePreventionType dialog_type, + Browser::DownloadCloseType dialog_type, bool app_modal, const base::Callback<void(bool)>& callback) : download_count_(download_count), @@ -39,15 +39,26 @@ set_margins(ChromeLayoutProvider::Get()->GetDialogInsetsForContentType( views::TEXT, views::TEXT)); - // This dialog should have been created within the same thread invocation - // as the original test, so it's never ok to close. - DCHECK_NE(Browser::DOWNLOAD_CLOSE_OK, dialog_type); - base::string16 message_text = l10n_util::GetStringUTF16( - dialog_type == Browser::DOWNLOAD_CLOSE_BROWSER_SHUTDOWN - ? IDS_ABANDON_DOWNLOAD_DIALOG_BROWSER_MESSAGE - : IDS_ABANDON_DOWNLOAD_DIALOG_INCOGNITO_MESSAGE); + int message_id = 0; + switch (dialog_type) { + case Browser::DownloadCloseType::kLastWindowInIncognitoProfile: + message_id = IDS_ABANDON_DOWNLOAD_DIALOG_INCOGNITO_MESSAGE; + break; + case Browser::DownloadCloseType::kLastWindowInGuestSession: + message_id = IDS_ABANDON_DOWNLOAD_DIALOG_GUEST_MESSAGE; + break; + case Browser::DownloadCloseType::kBrowserShutdown: + message_id = IDS_ABANDON_DOWNLOAD_DIALOG_BROWSER_MESSAGE; + break; + case Browser::DownloadCloseType::kOk: + // This dialog should have been created within the same thread invocation + // as the original test, so it's never ok to close. + NOTREACHED(); + break; + } auto message_label = std::make_unique<views::Label>( - message_text, CONTEXT_BODY_TEXT_LARGE, views::style::STYLE_SECONDARY); + l10n_util::GetStringUTF16(message_id), CONTEXT_BODY_TEXT_LARGE, + views::style::STYLE_SECONDARY); message_label->SetMultiLine(true); message_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); AddChildView(message_label.release());
diff --git a/chrome/browser/ui/views/download/download_in_progress_dialog_view.h b/chrome/browser/ui/views/download/download_in_progress_dialog_view.h index fe6cea46..8c7c54e 100644 --- a/chrome/browser/ui/views/download/download_in_progress_dialog_view.h +++ b/chrome/browser/ui/views/download/download_in_progress_dialog_view.h
@@ -21,13 +21,13 @@ // the download should be canceled, or false if the download should proceed. static void Show(gfx::NativeWindow parent_window, int download_count, - Browser::DownloadClosePreventionType dialog_type, + Browser::DownloadCloseType dialog_type, bool app_modal, const base::Callback<void(bool)>& callback); private: DownloadInProgressDialogView(int download_count, - Browser::DownloadClosePreventionType dialog_type, + Browser::DownloadCloseType dialog_type, bool app_modal, const base::Callback<void(bool)>& callback); ~DownloadInProgressDialogView() override;
diff --git a/chrome/browser/ui/views/frame/browser_view.cc b/chrome/browser/ui/views/frame/browser_view.cc index ec9cb45..1bfac551 100644 --- a/chrome/browser/ui/views/frame/browser_view.cc +++ b/chrome/browser/ui/views/frame/browser_view.cc
@@ -1544,7 +1544,7 @@ void BrowserView::ConfirmBrowserCloseWithPendingDownloads( int download_count, - Browser::DownloadClosePreventionType dialog_type, + Browser::DownloadCloseType dialog_type, bool app_modal, const base::Callback<void(bool)>& callback) { // The dialog eats mouse events which results in the close button
diff --git a/chrome/browser/ui/views/frame/browser_view.h b/chrome/browser/ui/views/frame/browser_view.h index 1b6ac7c..8de26bf 100644 --- a/chrome/browser/ui/views/frame/browser_view.h +++ b/chrome/browser/ui/views/frame/browser_view.h
@@ -405,7 +405,7 @@ DownloadShelf* GetDownloadShelf() override; void ConfirmBrowserCloseWithPendingDownloads( int download_count, - Browser::DownloadClosePreventionType dialog_type, + Browser::DownloadCloseType dialog_type, bool app_modal, const base::Callback<void(bool)>& callback) override; void UserChangedTheme(BrowserThemeChangeType theme_change_type) override;
diff --git a/chrome/browser/ui/views/global_media_controls/media_toolbar_button_view.cc b/chrome/browser/ui/views/global_media_controls/media_toolbar_button_view.cc index e1b09cf..d11d43ed 100644 --- a/chrome/browser/ui/views/global_media_controls/media_toolbar_button_view.cc +++ b/chrome/browser/ui/views/global_media_controls/media_toolbar_button_view.cc
@@ -15,10 +15,11 @@ #include "ui/views/controls/button/button_controller.h" MediaToolbarButtonView::MediaToolbarButtonView( + const base::UnguessableToken& source_id, service_manager::Connector* connector) : ToolbarButton(this), connector_(connector), - controller_(connector_, this) { + controller_(source_id, connector_, this) { button_controller()->set_notify_action( views::ButtonController::NotifyAction::NOTIFY_ON_PRESS); SetTooltipText(
diff --git a/chrome/browser/ui/views/global_media_controls/media_toolbar_button_view.h b/chrome/browser/ui/views/global_media_controls/media_toolbar_button_view.h index 4b002e3..19790b5 100644 --- a/chrome/browser/ui/views/global_media_controls/media_toolbar_button_view.h +++ b/chrome/browser/ui/views/global_media_controls/media_toolbar_button_view.h
@@ -11,6 +11,10 @@ #include "chrome/browser/ui/global_media_controls/media_toolbar_button_controller_delegate.h" #include "chrome/browser/ui/views/toolbar/toolbar_button.h" +namespace base { +class UnguessableToken; +} // namespace base + namespace service_manager { class Connector; } // namespace service_manager @@ -22,7 +26,8 @@ public MediaToolbarButtonControllerDelegate, public views::ButtonListener { public: - explicit MediaToolbarButtonView(service_manager::Connector* connector); + explicit MediaToolbarButtonView(const base::UnguessableToken& source_id, + service_manager::Connector* connector); ~MediaToolbarButtonView() override; // MediaToolbarButtonControllerDelegate implementation.
diff --git a/chrome/browser/ui/views/native_file_system/native_file_system_usage_bubble_view.cc b/chrome/browser/ui/views/native_file_system/native_file_system_usage_bubble_view.cc index 2a5f726..3b09e31 100644 --- a/chrome/browser/ui/views/native_file_system/native_file_system_usage_bubble_view.cc +++ b/chrome/browser/ui/views/native_file_system/native_file_system_usage_bubble_view.cc
@@ -6,6 +6,7 @@ #include "base/i18n/message_formatter.h" #include "base/i18n/unicodestring.h" +#include "base/metrics/user_metrics.h" #include "base/stl_util.h" #include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/native_file_system/chrome_native_file_system_permission_context.h" @@ -240,6 +241,9 @@ content::WebContents* web_contents, const url::Origin& origin, Usage usage) { + base::RecordAction( + base::UserMetricsAction("NativeFileSystemAPI.OpenedBubble")); + Browser* browser = chrome::FindBrowserWithWebContents(web_contents); if (!browser) return; @@ -423,6 +427,9 @@ void NativeFileSystemUsageBubbleView::ButtonPressed(views::Button* sender, const ui::Event& event) { + base::RecordAction( + base::UserMetricsAction("NativeFileSystemAPI.RevokePermissions")); + if (!web_contents()) return;
diff --git a/chrome/browser/ui/views/tabs/tab_group_editor_bubble_view.cc b/chrome/browser/ui/views/tabs/tab_group_editor_bubble_view.cc index e6873b7..7c47cab 100644 --- a/chrome/browser/ui/views/tabs/tab_group_editor_bubble_view.cc +++ b/chrome/browser/ui/views/tabs/tab_group_editor_bubble_view.cc
@@ -73,14 +73,10 @@ bool TabGroupEditorBubbleView::Accept() { TabGroupVisualData old_data = *tab_controller_->GetVisualDataForGroup(group_); - base::string16 title = title_field_->GetText(); - if (title.empty()) - title = old_data.title(); - base::Optional<SkColor> selected_color = color_selector_->GetSelectedColor(); const SkColor color = selected_color.has_value() ? selected_color.value() : old_data.color(); - TabGroupVisualData new_data(std::move(title), color); + TabGroupVisualData new_data(title_field_->GetText(), color); tab_controller_->SetVisualDataForGroup(group_, new_data); @@ -95,6 +91,8 @@ SetAnchorView(anchor_view); const auto* layout_provider = ChromeLayoutProvider::Get(); + const TabGroupVisualData* current_data = + tab_controller_->GetVisualDataForGroup(group_); // Add the text field for editing the title along with a label above it. View* title_label = AddChildView(std::make_unique<views::Label>( @@ -103,6 +101,7 @@ title_field_ = AddChildView(std::make_unique<views::Textfield>()); title_field_->SetAssociatedLabel(title_label); title_field_->SetDefaultWidthInChars(15); + title_field_->SetText(current_data->title()); title_field_->SetProperty( views::kMarginsKey,
diff --git a/chrome/browser/ui/views/tabs/tab_group_header.cc b/chrome/browser/ui/views/tabs/tab_group_header.cc index 0252fc0..2305df62 100644 --- a/chrome/browser/ui/views/tabs/tab_group_header.cc +++ b/chrome/browser/ui/views/tabs/tab_group_header.cc
@@ -27,6 +27,7 @@ #include "ui/views/layout/flex_layout.h" #include "ui/views/layout/flex_layout_types.h" #include "ui/views/layout/layout_provider.h" +#include "ui/views/view.h" #include "ui/views/view_class_properties.h" TabGroupHeader::TabGroupHeader(TabController* controller, TabGroupId group) @@ -39,12 +40,12 @@ .SetMainAxisAlignment(views::LayoutAlignment::kCenter) .SetCrossAxisAlignment(views::LayoutAlignment::kCenter); - const ChromeLayoutProvider* provider = ChromeLayoutProvider::Get(); + title_chip_ = AddChildView(std::make_unique<views::View>()); + title_chip_->SetLayoutManager(std::make_unique<views::FillLayout>()); + // Color and border are set in VisualsChanged(). - title_ = AddChildView(std::make_unique<views::Label>()); - title_->SetBorder(views::CreateEmptyBorder( - provider->GetInsetsMetric(INSETS_TAB_GROUP_TITLE_CHIP))); - // Color is set in VisualsChanged(). + title_ = title_chip_->AddChildView(std::make_unique<views::Label>()); + title_->SetCollapseWhenHidden(true); title_->SetAutoColorReadabilityEnabled(false); title_->SetHorizontalAlignment(gfx::ALIGN_CENTER); title_->SetElideBehavior(gfx::FADE_TAIL); @@ -78,15 +79,28 @@ // when the header is in the first slot and thus wouldn't overlap anything to // the left. const int overlap_margin = TabStyle::GetTabOverlap() * 2; - return title_->GetPreferredSize().width() + title_chip_outside_margin + + return title_chip_->GetPreferredSize().width() + title_chip_outside_margin + overlap_margin; } void TabGroupHeader::VisualsChanged() { const ChromeLayoutProvider* provider = ChromeLayoutProvider::Get(); const TabGroupVisualData* data = controller_->GetVisualDataForGroup(group_); - title_->SetBackground(views::CreateRoundedRectBackground( - data->color(), provider->GetCornerRadiusMetric(views::EMPHASIS_LOW))); - title_->SetEnabledColor(color_utils::GetColorWithMaxContrast(data->color())); - title_->SetText(data->title()); + if (data->title().empty()) { + title_->SetVisible(false); + constexpr gfx::Rect kEmptyTitleChipSize(12, 12); + title_chip_->SetBorder( + views::CreateEmptyBorder(kEmptyTitleChipSize.InsetsFrom(gfx::Rect()))); + } else { + title_->SetVisible(true); + title_->SetEnabledColor( + color_utils::GetColorWithMaxContrast(data->color())); + title_->SetText(data->title()); + title_chip_->SetBorder(views::CreateEmptyBorder( + provider->GetInsetsMetric(INSETS_TAB_GROUP_TITLE_CHIP))); + } + title_chip_->SetBackground(views::CreateRoundedRectBackground( + data->color(), + provider->GetCornerRadiusMetric(views::EMPHASIS_MAXIMUM, + title_chip_->GetPreferredSize()))); }
diff --git a/chrome/browser/ui/views/tabs/tab_group_header.h b/chrome/browser/ui/views/tabs/tab_group_header.h index 2ca4137..c50fa8d 100644 --- a/chrome/browser/ui/views/tabs/tab_group_header.h +++ b/chrome/browser/ui/views/tabs/tab_group_header.h
@@ -14,6 +14,7 @@ namespace views { class Label; +class View; } // View for tab group headers in the tab strip, which are markers of group @@ -39,6 +40,7 @@ TabController* const controller_; const TabGroupId group_; + views::View* title_chip_; views::Label* title_; DISALLOW_COPY_AND_ASSIGN(TabGroupHeader);
diff --git a/chrome/browser/ui/views/toolbar/toolbar_view.cc b/chrome/browser/ui/views/toolbar/toolbar_view.cc index 37aca84a..005cfb2 100644 --- a/chrome/browser/ui/views/toolbar/toolbar_view.cc +++ b/chrome/browser/ui/views/toolbar/toolbar_view.cc
@@ -63,6 +63,7 @@ #include "components/prefs/pref_service.h" #include "components/strings/grit/components_strings.h" #include "components/vector_icons/vector_icons.h" +#include "content/public/browser/media_session.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/system_connector.h" #include "content/public/browser/web_contents.h" @@ -247,8 +248,10 @@ std::unique_ptr<MediaToolbarButtonView> media_button; if (base::FeatureList::IsEnabled(media::kGlobalMediaControls)) { - media_button = - std::make_unique<MediaToolbarButtonView>(content::GetSystemConnector()); + const base::UnguessableToken& source_id = + content::MediaSession::GetSourceId(browser_->profile()); + media_button = std::make_unique<MediaToolbarButtonView>( + source_id, content::GetSystemConnector()); } std::unique_ptr<ToolbarPageActionIconContainerView>
diff --git a/chrome/common/extensions/api/autotest_private.idl b/chrome/common/extensions/api/autotest_private.idl index f0b9806a..29fb2a7 100644 --- a/chrome/common/extensions/api/autotest_private.idl +++ b/chrome/common/extensions/api/autotest_private.idl
@@ -535,5 +535,11 @@ // Swap the windows in the split view. // |callback|: Called when the operation has completed. static void swapWindowsInSplitView(VoidCallback callback); + + // Set ARC app window focused. + // |packageName|: the package name of the ARC app window. + // |callback|: called when the operation has completed. + static void setArcAppWindowFocus(DOMString packageName, + VoidCallback callback); }; };
diff --git a/chrome/common/webui_url_constants.cc b/chrome/common/webui_url_constants.cc index 300cba6..71adf51 100644 --- a/chrome/common/webui_url_constants.cc +++ b/chrome/common/webui_url_constants.cc
@@ -569,6 +569,7 @@ kChromeUINetworkHost, kChromeUIOobeHost, kChromeUIOSCreditsHost, + kChromeUIOSSettingsHost, kChromeUIPowerHost, kChromeUIInternetConfigDialogHost, kChromeUIInternetDetailDialogHost,
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 51fdbe3..86bcda0 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -589,7 +589,7 @@ "android/browsertests_apk/src/org/chromium/android_browsertests_apk/ChromeBrowserTestsApplication.java", ] srcjar_deps = [ - "//components/module_installer/android:module_installer_apk_build_config", + "//components/module_installer/android:module_installer_build_config", ] } @@ -3588,7 +3588,7 @@ } srcjar_deps = [ - "//components/module_installer/android:module_installer_apk_build_config", + "//components/module_installer/android:module_installer_build_config", ] } else { # !is_android
diff --git a/chrome/test/android/browsertests_apk/AndroidManifest.xml.jinja2 b/chrome/test/android/browsertests_apk/AndroidManifest.xml.jinja2 index 2c15484..561835b8 100644 --- a/chrome/test/android/browsertests_apk/AndroidManifest.xml.jinja2 +++ b/chrome/test/android/browsertests_apk/AndroidManifest.xml.jinja2
@@ -83,6 +83,23 @@ </intent-filter> </activity> + <activity + android:name="org.chromium.chrome.browser.sharing.shared_clipboard.SharedClipboardShareActivity" + android:icon="@drawable/ic_devices_48dp" + android:label="@string/shared_clipboard_share_activity_title" + android:enabled="false" + android:excludeFromRecents="true" + android:exported="true" + android:noHistory="true" + android:theme="@style/Theme.Chromium.Activity.Translucent" + android:configChanges="orientation|keyboardHidden|keyboard|screenSize|mcc|mnc|screenLayout|smallestScreenSize" > + <intent-filter> + <action android:name="android.intent.action.SEND" /> + <category android:name="android.intent.category.DEFAULT" /> + <data android:mimeType="text/plain" /> + </intent-filter> + </activity> + <service android:name="org.chromium.components.background_task_scheduler.BackgroundTaskJobService" android:exported="false" android:permission="android.permission.BIND_JOB_SERVICE"/>
diff --git a/chrome/test/base/test_browser_window.h b/chrome/test/base/test_browser_window.h index 3af49a1b..d03a611 100644 --- a/chrome/test/base/test_browser_window.h +++ b/chrome/test/base/test_browser_window.h
@@ -159,7 +159,7 @@ DownloadShelf* GetDownloadShelf() override; void ConfirmBrowserCloseWithPendingDownloads( int download_count, - Browser::DownloadClosePreventionType dialog_type, + Browser::DownloadCloseType dialog_type, bool app_modal, const base::Callback<void(bool)>& callback) override {} void UserChangedTheme(BrowserThemeChangeType theme_change_type) override {}
diff --git a/chrome/test/chromedriver/chrome/web_view_impl.cc b/chrome/test/chromedriver/chrome/web_view_impl.cc index 8552d20..857e266 100644 --- a/chrome/test/chromedriver/chrome/web_view_impl.cc +++ b/chrome/test/chromedriver/chrome/web_view_impl.cc
@@ -532,7 +532,8 @@ params.SetInteger("buttons", it->buttons); params.SetInteger("clickCount", it->click_count); params.SetString("pointerType", GetAsString(it->pointer_type)); - Status status = client_->SendCommand("Input.dispatchMouseEvent", params); + Status status = client_->SendCommandAndIgnoreResponse( + "Input.dispatchMouseEvent", params); if (status.IsError()) return status; } @@ -556,7 +557,8 @@ point_list->Append(std::move(point)); } params.Set("touchPoints", std::move(point_list)); - return client_->SendCommand("Input.dispatchTouchEvent", params); + return client_->SendCommandAndIgnoreResponse("Input.dispatchTouchEvent", + params); } Status WebViewImpl::DispatchTouchEvents(const std::list<TouchEvent>& events) { @@ -604,7 +606,8 @@ else params.SetInteger("location", it->location); } - Status status = client_->SendCommand("Input.dispatchKeyEvent", params); + Status status = + client_->SendCommandAndIgnoreResponse("Input.dispatchKeyEvent", params); if (status.IsError()) return status; }
diff --git a/chrome/test/chromedriver/session_commands.cc b/chrome/test/chromedriver/session_commands.cc index 9b32776c..ef32ec0 100644 --- a/chrome/test/chromedriver/session_commands.cc +++ b/chrome/test/chromedriver/session_commands.cc
@@ -317,8 +317,10 @@ if (session->chrome->GetBrowserInfo()->is_headless) { std::string download_directory; if (capabilities.prefs && - capabilities.prefs->GetString("download.default_directory", - &download_directory)) + (capabilities.prefs->GetString("download.default_directory", + &download_directory) || + capabilities.prefs->GetStringWithoutPathExpansion( + "download.default_directory", &download_directory))) session->headless_download_directory = std::make_unique<std::string>(download_directory); else
diff --git a/chrome/test/chromedriver/test/run_py_tests.py b/chrome/test/chromedriver/test/run_py_tests.py index 33be2ad..4f3f474 100755 --- a/chrome/test/chromedriver/test/run_py_tests.py +++ b/chrome/test/chromedriver/test/run_py_tests.py
@@ -780,6 +780,10 @@ '});' 'return div;') actions = ({"actions": [{ + "actions": [{"duration": 32, "type": "pause"}], + "id": "0", + "type": "none" + }, { "type":"pointer", "actions":[{"type": "pointerMove", "x": 10, "y": 10}], "parameters": {"pointerType": "mouse"}, @@ -839,6 +843,12 @@ # Move to center of target element and drag it to a new location. actions = ({'actions': [{ + "actions": [{"duration": 32, "type": "pause"}, + {"duration": 32, "type": "pause"}, + {"duration": 32, "type": "pause"}], + "id": "0", + "type": "none" + }, { 'type': 'pointer', 'actions': [ {'type': 'pointerMove', 'x': 100, 'y': 100}, @@ -854,6 +864,10 @@ # Without releasing mouse button, should continue the drag. actions = ({'actions': [{ + "actions": [{"duration": 32, "type": "pause"}], + "id": "0", + "type": "none" + }, { 'type': 'pointer', 'actions': [ {'type': 'pointerMove', 'x': 30, 'y': 40, 'origin': 'pointer'} @@ -867,6 +881,11 @@ # Releasing mouse button stops the drag. actions = ({'actions': [{ + "actions": [{"duration": 32, "type": "pause"}, + {"duration": 32, "type": "pause"}], + "id": "0", + "type": "none" + }, { 'type': 'pointer', 'actions': [ {'type': 'pointerUp', 'button': 0},
diff --git a/chrome/test/chromedriver/window_commands.cc b/chrome/test/chromedriver/window_commands.cc index 6830a2f..a981efc3 100644 --- a/chrome/test/chromedriver/window_commands.cc +++ b/chrome/test/chromedriver/window_commands.cc
@@ -1719,12 +1719,33 @@ Status status = session->chrome->ActivateWebView(web_view->GetId()); if (status.IsError()) return status; + std::unique_ptr<base::Value> browser_info; + status = web_view->EvaluateScript( + std::string(), + "({x: document.documentElement.scrollLeft || document.body.scrollLeft," + " y: document.documentElement.scrollTop || document.body.scrollTop," + " height: window.innerHeight," + " width: window.innerWidth," + " device_pixel_ratio: window.devicePixelRatio})", + &browser_info); + + std::unique_ptr<base::DictionaryValue> clip_dict = + std::make_unique<base::DictionaryValue>(); + clip_dict->SetDouble("x", browser_info->FindKey("x")->GetDouble()); + clip_dict->SetDouble("y", browser_info->FindKey("y")->GetDouble()); + clip_dict->SetDouble("height", browser_info->FindKey("height")->GetDouble()); + clip_dict->SetDouble("width", browser_info->FindKey("width")->GetDouble()); + clip_dict->SetDouble( + "scale", + 1 / browser_info->FindKey("device_pixel_ratio")->GetDouble()); + base::DictionaryValue screenshot_params; + screenshot_params.SetDictionary("clip", std::move(clip_dict)); std::string screenshot; - status = web_view->CaptureScreenshot(&screenshot, base::DictionaryValue()); + status = web_view->CaptureScreenshot(&screenshot, screenshot_params); if (status.IsError()) { LOG(WARNING) << "screenshot failed, retrying"; - status = web_view->CaptureScreenshot(&screenshot, base::DictionaryValue()); + status = web_view->CaptureScreenshot(&screenshot, screenshot_params); } if (status.IsError()) return status;
diff --git a/chromecast/media/audio/BUILD.gn b/chromecast/media/audio/BUILD.gn index d1002c7..1f853230 100644 --- a/chromecast/media/audio/BUILD.gn +++ b/chromecast/media/audio/BUILD.gn
@@ -34,6 +34,7 @@ "//chromecast/media/audio/mixer_service:connection", "//chromecast/media/audio/mixer_service:proto", "//chromecast/media/base", + "//chromecast/media/base:monotonic_clock", "//chromecast/media/cma/backend", "//chromecast/media/cma/base", "//chromecast/public/media", @@ -98,7 +99,6 @@ header = "audio_buildflags.h" flags = [ - "MEDIA_CLOCK_MONOTONIC_RAW=$media_clock_monotonic_raw", "MINIMUM_OUTPUT_BUFFER_SIZE_IN_FRAMES=$minimum_output_buffer_size_in_frames", "MAXIMUM_OUTPUT_BUFFER_SIZE_IN_FRAMES=$maximum_output_buffer_size_in_frames", "DEFAULT_OUTPUT_BUFFER_SIZE_IN_FRAMES=$default_output_buffer_size_in_frames",
diff --git a/chromecast/media/audio/cast_audio_output_stream.cc b/chromecast/media/audio/cast_audio_output_stream.cc index cd17327e..97ad131 100644 --- a/chromecast/media/audio/cast_audio_output_stream.cc +++ b/chromecast/media/audio/cast_audio_output_stream.cc
@@ -14,17 +14,17 @@ #include "base/callback_helpers.h" #include "base/location.h" #include "base/logging.h" -#include "base/synchronization/lock.h" #include "base/message_loop/message_pump_type.h" +#include "base/synchronization/lock.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread_task_runner_handle.h" #include "chromecast/base/bind_to_task_runner.h" #include "chromecast/base/metrics/cast_metrics_helper.h" #include "chromecast/common/mojom/constants.mojom.h" -#include "chromecast/media/audio/audio_buildflags.h" #include "chromecast/media/audio/cast_audio_manager.h" #include "chromecast/media/audio/mixer_service/mixer_service.pb.h" #include "chromecast/media/audio/mixer_service/mixer_service_connection.h" +#include "chromecast/media/base/monotonic_clock.h" #include "chromecast/media/cma/backend/cma_backend_factory.h" #include "chromecast/public/cast_media_shlib.h" #include "chromecast/public/media/decoder_config.h" @@ -64,16 +64,6 @@ namespace media { namespace { -int64_t MonotonicClockNow() { - timespec now = {0, 0}; -#if BUILDFLAG(MEDIA_CLOCK_MONOTONIC_RAW) - clock_gettime(CLOCK_MONOTONIC_RAW, &now); -#else - clock_gettime(CLOCK_MONOTONIC, &now); -#endif // BUILDFLAG(MEDIA_CLOCK_MONOTONIC_RAW) - return static_cast<int64_t>(now.tv_sec) * 1000000 + now.tv_nsec / 1000; -} - AudioContentType GetContentType(const std::string& device_id) { if (::media::AudioDeviceDescription::IsCommunicationsDevice(device_id)) { return AudioContentType::kCommunication;
diff --git a/chromeos/constants/chromeos_features.cc b/chromeos/constants/chromeos_features.cc index 92916bb..d6dda742 100644 --- a/chromeos/constants/chromeos_features.cc +++ b/chromeos/constants/chromeos_features.cc
@@ -159,7 +159,7 @@ // Enables or disables showing the battery level in the System Tray and Settings // UI for supported Bluetooth Devices. const base::Feature kShowBluetoothDeviceBattery{ - "ShowBluetoothDeviceBattery", base::FEATURE_ENABLED_BY_DEFAULT}; + "ShowBluetoothDeviceBattery", base::FEATURE_DISABLED_BY_DEFAULT}; // Shows the Play Store icon in Demo Mode. const base::Feature kShowPlayInDemoMode{"ShowPlayInDemoMode",
diff --git a/chromeos/services/device_sync/cryptauth_device_sync_result.cc b/chromeos/services/device_sync/cryptauth_device_sync_result.cc index 85d046f..931ea924 100644 --- a/chromeos/services/device_sync/cryptauth_device_sync_result.cc +++ b/chromeos/services/device_sync/cryptauth_device_sync_result.cc
@@ -10,7 +10,7 @@ // static CryptAuthDeviceSyncResult::ResultType CryptAuthDeviceSyncResult::GetResultType( - const ResultCode& result_code) { + ResultCode result_code) { switch (result_code) { case CryptAuthDeviceSyncResult::ResultCode::kSuccess: return CryptAuthDeviceSyncResult::ResultType::kSuccess;
diff --git a/chromeos/services/device_sync/cryptauth_device_sync_result.h b/chromeos/services/device_sync/cryptauth_device_sync_result.h index 980edbf..a2c48fd 100644 --- a/chromeos/services/device_sync/cryptauth_device_sync_result.h +++ b/chromeos/services/device_sync/cryptauth_device_sync_result.h
@@ -71,7 +71,7 @@ enum class ResultType { kSuccess, kNonFatalError, kFatalError }; - static ResultType GetResultType(const ResultCode& result_code); + static ResultType GetResultType(ResultCode result_code); CryptAuthDeviceSyncResult( ResultCode result_code,
diff --git a/chromeos/services/device_sync/cryptauth_device_syncer_impl.cc b/chromeos/services/device_sync/cryptauth_device_syncer_impl.cc index d10698a..dd24c86 100644 --- a/chromeos/services/device_sync/cryptauth_device_syncer_impl.cc +++ b/chromeos/services/device_sync/cryptauth_device_syncer_impl.cc
@@ -259,12 +259,13 @@ std::unique_ptr<CryptAuthKey> new_group_key, const base::Optional<cryptauthv2::EncryptedGroupPrivateKey>& encrypted_group_private_key, - const CryptAuthDeviceSyncResult& device_sync_result) { + const base::Optional<cryptauthv2::ClientDirective>& new_client_directive, + CryptAuthDeviceSyncResult::ResultCode device_sync_result_code) { DCHECK_EQ(State::kWaitingForMetadataSync, state_); id_to_device_metadata_packet_map_ = id_to_device_metadata_packet_map; encrypted_group_private_key_ = encrypted_group_private_key; - new_client_directive_ = device_sync_result.client_directive(); + new_client_directive_ = new_client_directive; // If a new group key pair was created or if CryptAuth returned a new group // public key during the metadata sync, add the new group key to the key @@ -272,7 +273,7 @@ if (new_group_key) SetGroupKey(*new_group_key); - switch (device_sync_result.GetResultType()) { + switch (CryptAuthDeviceSyncResult::GetResultType(device_sync_result_code)) { case CryptAuthDeviceSyncResult::ResultType::kNonFatalError: did_non_fatal_error_occur_ = true; FALLTHROUGH; @@ -289,7 +290,7 @@ AttemptNextStep(); return; case CryptAuthDeviceSyncResult::ResultType::kFatalError: - FinishAttempt(device_sync_result.result_code()); + FinishAttempt(device_sync_result_code); return; } } @@ -346,7 +347,7 @@ void CryptAuthDeviceSyncerImpl::OnGetFeatureStatusesFinished( const CryptAuthFeatureStatusGetter::IdToFeatureStatusMap& id_to_feature_status_map, - const CryptAuthDeviceSyncResult::ResultCode& device_sync_result_code) { + CryptAuthDeviceSyncResult::ResultCode device_sync_result_code) { DCHECK_EQ(State::kWaitingForFeatureStatuses, state_); // We require that the local device feature statuses are returned; the local @@ -597,7 +598,7 @@ } void CryptAuthDeviceSyncerImpl::OnShareGroupPrivateKeyFinished( - const CryptAuthDeviceSyncResult::ResultCode& device_sync_result_code) { + CryptAuthDeviceSyncResult::ResultCode device_sync_result_code) { DCHECK_EQ(State::kWaitingForGroupPrivateKeySharing, state_); switch (CryptAuthDeviceSyncResult::GetResultType(device_sync_result_code)) { @@ -614,7 +615,7 @@ } void CryptAuthDeviceSyncerImpl::FinishAttempt( - const CryptAuthDeviceSyncResult::ResultCode& result_code) { + CryptAuthDeviceSyncResult::ResultCode result_code) { SetState(State::kFinished); metadata_syncer_.reset();
diff --git a/chromeos/services/device_sync/cryptauth_device_syncer_impl.h b/chromeos/services/device_sync/cryptauth_device_syncer_impl.h index ba690c17..cb99b47 100644 --- a/chromeos/services/device_sync/cryptauth_device_syncer_impl.h +++ b/chromeos/services/device_sync/cryptauth_device_syncer_impl.h
@@ -119,7 +119,8 @@ std::unique_ptr<CryptAuthKey> new_group_key, const base::Optional<cryptauthv2::EncryptedGroupPrivateKey>& encrypted_group_private_key, - const CryptAuthDeviceSyncResult& device_sync_result); + const base::Optional<cryptauthv2::ClientDirective>& new_client_directive, + CryptAuthDeviceSyncResult::ResultCode device_sync_result_code); void SetGroupKey(const CryptAuthKey& new_group_key); @@ -127,7 +128,7 @@ void OnGetFeatureStatusesFinished( const CryptAuthFeatureStatusGetter::IdToFeatureStatusMap& id_to_feature_status_map, - const CryptAuthDeviceSyncResult::ResultCode& device_sync_result_code); + CryptAuthDeviceSyncResult::ResultCode device_sync_result_code); // Builds a new device registry map with all device information except // decrypted BetterTogetherDeviceMetadata for remote devices. @@ -154,12 +155,12 @@ void ShareGroupPrivateKey(); void OnShareGroupPrivateKeyFinished( - const CryptAuthDeviceSyncResult::ResultCode& device_sync_result_code); + CryptAuthDeviceSyncResult::ResultCode device_sync_result_code); // Replaces the current device registry if devices were able to be extracted // from the DeviceSync attempt. Finishes the DeviceSync attempt, sending back // the relevant CryptAuthDeviceSyncResult. - void FinishAttempt(const CryptAuthDeviceSyncResult::ResultCode& result_code); + void FinishAttempt(CryptAuthDeviceSyncResult::ResultCode result_code); bool did_non_fatal_error_occur_ = false;
diff --git a/chromeos/services/device_sync/cryptauth_device_syncer_impl_unittest.cc b/chromeos/services/device_sync/cryptauth_device_syncer_impl_unittest.cc index a03b82d..59811d9 100644 --- a/chromeos/services/device_sync/cryptauth_device_syncer_impl_unittest.cc +++ b/chromeos/services/device_sync/cryptauth_device_syncer_impl_unittest.cc
@@ -221,7 +221,7 @@ const base::Optional<CryptAuthKey>& new_group_key, const base::Optional<std::string>& encrypted_group_private_key, const base::Optional<cryptauthv2::ClientDirective> new_client_directive, - const CryptAuthDeviceSyncResult::ResultCode& device_sync_result_code) { + CryptAuthDeviceSyncResult::ResultCode device_sync_result_code) { CryptAuthMetadataSyncer::IdToDeviceMetadataPacketMap id_to_device_metadata_packet_map; for (const cryptauthv2::DeviceMetadataPacket& packet : metadata_packets) { @@ -239,10 +239,7 @@ : nullptr; metadata_syncer()->FinishAttempt( id_to_device_metadata_packet_map, std::move(new_group_key_ptr), - private_key, - CryptAuthDeviceSyncResult(device_sync_result_code, - false /* did_device_registry_change */, - new_client_directive)); + private_key, new_client_directive, device_sync_result_code); } void VerifyFeatureStatusGetterInput( @@ -262,7 +259,7 @@ void FinishFeatureStatusGetterAttempt( const base::flat_set<std::string>& device_ids, - const CryptAuthDeviceSyncResult::ResultCode& device_sync_result_code) { + CryptAuthDeviceSyncResult::ResultCode device_sync_result_code) { CryptAuthFeatureStatusGetter::IdToFeatureStatusMap id_to_feature_status_map; for (const std::string& id : device_ids) { id_to_feature_status_map.insert_or_assign( @@ -355,7 +352,7 @@ } void FinishShareGroupPrivateKeyAttempt( - const CryptAuthDeviceSyncResult::ResultCode& device_sync_result_code) { + CryptAuthDeviceSyncResult::ResultCode device_sync_result_code) { group_private_key_sharer()->FinishAttempt(device_sync_result_code); }
diff --git a/chromeos/services/device_sync/cryptauth_feature_status_getter.cc b/chromeos/services/device_sync/cryptauth_feature_status_getter.cc index 93b8c53..04ed2d00 100644 --- a/chromeos/services/device_sync/cryptauth_feature_status_getter.cc +++ b/chromeos/services/device_sync/cryptauth_feature_status_getter.cc
@@ -29,7 +29,7 @@ void CryptAuthFeatureStatusGetter::OnAttemptFinished( const IdToFeatureStatusMap& id_to_feature_status_map, - const CryptAuthDeviceSyncResult::ResultCode& device_sync_result_code) { + CryptAuthDeviceSyncResult::ResultCode device_sync_result_code) { DCHECK(callback_); std::move(callback_).Run(id_to_feature_status_map, device_sync_result_code); }
diff --git a/chromeos/services/device_sync/cryptauth_feature_status_getter.h b/chromeos/services/device_sync/cryptauth_feature_status_getter.h index 8644a0a3..2941a27 100644 --- a/chromeos/services/device_sync/cryptauth_feature_status_getter.h +++ b/chromeos/services/device_sync/cryptauth_feature_status_getter.h
@@ -37,7 +37,7 @@ using IdToFeatureStatusMap = base::flat_map<std::string, FeatureStatusMap>; using GetFeatureStatusesAttemptFinishedCallback = base::OnceCallback<void(const IdToFeatureStatusMap&, - const CryptAuthDeviceSyncResult::ResultCode&)>; + CryptAuthDeviceSyncResult::ResultCode)>; virtual ~CryptAuthFeatureStatusGetter(); @@ -59,7 +59,7 @@ void OnAttemptFinished( const IdToFeatureStatusMap& id_to_feature_status_map, - const CryptAuthDeviceSyncResult::ResultCode& device_sync_result_code); + CryptAuthDeviceSyncResult::ResultCode device_sync_result_code); private: GetFeatureStatusesAttemptFinishedCallback callback_;
diff --git a/chromeos/services/device_sync/cryptauth_feature_status_getter_impl.cc b/chromeos/services/device_sync/cryptauth_feature_status_getter_impl.cc index a0d1efc4..3c42700 100644 --- a/chromeos/services/device_sync/cryptauth_feature_status_getter_impl.cc +++ b/chromeos/services/device_sync/cryptauth_feature_status_getter_impl.cc
@@ -276,7 +276,7 @@ } void CryptAuthFeatureStatusGetterImpl::FinishAttempt( - const CryptAuthDeviceSyncResult::ResultCode& result_code) { + CryptAuthDeviceSyncResult::ResultCode result_code) { cryptauth_client_.reset(); timer_->Stop();
diff --git a/chromeos/services/device_sync/cryptauth_feature_status_getter_impl.h b/chromeos/services/device_sync/cryptauth_feature_status_getter_impl.h index 1662acc..19f2bd9c 100644 --- a/chromeos/services/device_sync/cryptauth_feature_status_getter_impl.h +++ b/chromeos/services/device_sync/cryptauth_feature_status_getter_impl.h
@@ -60,7 +60,7 @@ void OnBatchGetFeatureStatusesFailure(NetworkRequestError error); void OnBatchGetFeatureStatusesTimeout(); - void FinishAttempt(const CryptAuthDeviceSyncResult::ResultCode& result_code); + void FinishAttempt(CryptAuthDeviceSyncResult::ResultCode result_code); IdToFeatureStatusMap id_to_feature_status_map_;
diff --git a/chromeos/services/device_sync/cryptauth_feature_status_getter_impl_unittest.cc b/chromeos/services/device_sync/cryptauth_feature_status_getter_impl_unittest.cc index e1062f9..d036b75c 100644 --- a/chromeos/services/device_sync/cryptauth_feature_status_getter_impl_unittest.cc +++ b/chromeos/services/device_sync/cryptauth_feature_status_getter_impl_unittest.cc
@@ -185,7 +185,7 @@ void VerifyGetFeatureStatuesResult( const base::flat_set<std::string>& expected_device_ids, - const CryptAuthDeviceSyncResult::ResultCode& expected_result_code) { + CryptAuthDeviceSyncResult::ResultCode expected_result_code) { ASSERT_TRUE(device_sync_result_code_); EXPECT_EQ(expected_device_ids.size(), id_to_feature_status_map_.size()); EXPECT_EQ(expected_result_code, device_sync_result_code_); @@ -216,7 +216,7 @@ void OnGetFeatureStatusesComplete( const CryptAuthFeatureStatusGetter::IdToFeatureStatusMap& id_to_feature_status_map, - const CryptAuthDeviceSyncResult::ResultCode& device_sync_result_code) { + CryptAuthDeviceSyncResult::ResultCode device_sync_result_code) { id_to_feature_status_map_ = id_to_feature_status_map; device_sync_result_code_ = device_sync_result_code; }
diff --git a/chromeos/services/device_sync/cryptauth_group_private_key_sharer.cc b/chromeos/services/device_sync/cryptauth_group_private_key_sharer.cc index 5d3391f0..9b43c9f 100644 --- a/chromeos/services/device_sync/cryptauth_group_private_key_sharer.cc +++ b/chromeos/services/device_sync/cryptauth_group_private_key_sharer.cc
@@ -34,7 +34,7 @@ } void CryptAuthGroupPrivateKeySharer::OnAttemptFinished( - const CryptAuthDeviceSyncResult::ResultCode& device_sync_result_code) { + CryptAuthDeviceSyncResult::ResultCode device_sync_result_code) { DCHECK(callback_); std::move(callback_).Run(device_sync_result_code); }
diff --git a/chromeos/services/device_sync/cryptauth_group_private_key_sharer.h b/chromeos/services/device_sync/cryptauth_group_private_key_sharer.h index ae43044..41d86d7 100644 --- a/chromeos/services/device_sync/cryptauth_group_private_key_sharer.h +++ b/chromeos/services/device_sync/cryptauth_group_private_key_sharer.h
@@ -34,7 +34,7 @@ public: using IdToEncryptingKeyMap = base::flat_map<std::string, std::string>; using ShareGroupPrivateKeyAttemptFinishedCallback = - base::OnceCallback<void(const CryptAuthDeviceSyncResult::ResultCode&)>; + base::OnceCallback<void(CryptAuthDeviceSyncResult::ResultCode)>; virtual ~CryptAuthGroupPrivateKeySharer(); @@ -58,7 +58,7 @@ const IdToEncryptingKeyMap& id_to_encrypting_key_map) = 0; void OnAttemptFinished( - const CryptAuthDeviceSyncResult::ResultCode& device_sync_result_code); + CryptAuthDeviceSyncResult::ResultCode device_sync_result_code); private: ShareGroupPrivateKeyAttemptFinishedCallback callback_;
diff --git a/chromeos/services/device_sync/cryptauth_group_private_key_sharer_impl.cc b/chromeos/services/device_sync/cryptauth_group_private_key_sharer_impl.cc index 950580f..8432b22 100644 --- a/chromeos/services/device_sync/cryptauth_group_private_key_sharer_impl.cc +++ b/chromeos/services/device_sync/cryptauth_group_private_key_sharer_impl.cc
@@ -320,7 +320,7 @@ } void CryptAuthGroupPrivateKeySharerImpl::FinishAttempt( - const CryptAuthDeviceSyncResult::ResultCode& result_code) { + CryptAuthDeviceSyncResult::ResultCode result_code) { encryptor_.reset(); cryptauth_client_.reset();
diff --git a/chromeos/services/device_sync/cryptauth_group_private_key_sharer_impl.h b/chromeos/services/device_sync/cryptauth_group_private_key_sharer_impl.h index c94f158..2af3d9b1 100644 --- a/chromeos/services/device_sync/cryptauth_group_private_key_sharer_impl.h +++ b/chromeos/services/device_sync/cryptauth_group_private_key_sharer_impl.h
@@ -84,7 +84,7 @@ const cryptauthv2::ShareGroupPrivateKeyResponse& response); void OnShareGroupPrivateKeyFailure(NetworkRequestError error); - void FinishAttempt(const CryptAuthDeviceSyncResult::ResultCode& result_code); + void FinishAttempt(CryptAuthDeviceSyncResult::ResultCode result_code); // Used for batch encrypting the group private key with each encrypting key. std::unique_ptr<CryptAuthEciesEncryptor> encryptor_;
diff --git a/chromeos/services/device_sync/cryptauth_group_private_key_sharer_impl_unittest.cc b/chromeos/services/device_sync/cryptauth_group_private_key_sharer_impl_unittest.cc index 474f22e..b6aada2 100644 --- a/chromeos/services/device_sync/cryptauth_group_private_key_sharer_impl_unittest.cc +++ b/chromeos/services/device_sync/cryptauth_group_private_key_sharer_impl_unittest.cc
@@ -236,7 +236,7 @@ } void VerifyShareGroupPrivateKeyResult( - const CryptAuthDeviceSyncResult::ResultCode& expected_result_code) { + CryptAuthDeviceSyncResult::ResultCode expected_result_code) { ASSERT_TRUE(device_sync_result_code_); EXPECT_EQ(expected_result_code, device_sync_result_code_); } @@ -262,7 +262,7 @@ } void OnShareGroupPrivateKeyComplete( - const CryptAuthDeviceSyncResult::ResultCode& device_sync_result_code) { + CryptAuthDeviceSyncResult::ResultCode device_sync_result_code) { device_sync_result_code_ = device_sync_result_code; }
diff --git a/chromeos/services/device_sync/cryptauth_metadata_syncer.cc b/chromeos/services/device_sync/cryptauth_metadata_syncer.cc index cfe44da..237b846 100644 --- a/chromeos/services/device_sync/cryptauth_metadata_syncer.cc +++ b/chromeos/services/device_sync/cryptauth_metadata_syncer.cc
@@ -6,8 +6,6 @@ #include <utility> -#include "chromeos/services/device_sync/cryptauth_device_sync_result.h" - namespace chromeos { namespace device_sync { @@ -35,11 +33,13 @@ std::unique_ptr<CryptAuthKey> new_group_key, const base::Optional<cryptauthv2::EncryptedGroupPrivateKey>& encrypted_group_private_key, - const CryptAuthDeviceSyncResult& device_sync_result) { + const base::Optional<cryptauthv2::ClientDirective>& new_client_directive, + CryptAuthDeviceSyncResult::ResultCode device_sync_result_code) { DCHECK(callback_); std::move(callback_).Run(id_to_device_metadata_packet_map, std::move(new_group_key), - encrypted_group_private_key, device_sync_result); + encrypted_group_private_key, new_client_directive, + device_sync_result_code); } } // namespace device_sync
diff --git a/chromeos/services/device_sync/cryptauth_metadata_syncer.h b/chromeos/services/device_sync/cryptauth_metadata_syncer.h index 00c658c4..c90bb71 100644 --- a/chromeos/services/device_sync/cryptauth_metadata_syncer.h +++ b/chromeos/services/device_sync/cryptauth_metadata_syncer.h
@@ -11,8 +11,10 @@ #include "base/containers/flat_map.h" #include "base/macros.h" #include "base/optional.h" +#include "chromeos/services/device_sync/cryptauth_device_sync_result.h" #include "chromeos/services/device_sync/cryptauth_key.h" #include "chromeos/services/device_sync/proto/cryptauth_devicesync.pb.h" +#include "chromeos/services/device_sync/proto/cryptauth_directive.pb.h" namespace cryptauthv2 { class BetterTogetherDeviceMetadata; @@ -22,8 +24,6 @@ namespace device_sync { -class CryptAuthDeviceSyncResult; - // Handles the SyncMetadata portion of the CryptAuth v2 DeviceSync protocol, // which consists of one or two SyncMetadata request/response interactions with // the CryptAuth servers: @@ -63,6 +63,7 @@ // created. // - (Optional) A group private key, encrypted with this device's // CryptAuthKeyBunde::kDeviceSyncBetterTogether public key. +// - (Optional) A new ClientDirective sent from the CryptAuth server. // // A CryptAuthMetadataSyncer object is designed to be used for only one // SyncMetadata() call. For a new DeviceSync attempt, a new object should be @@ -75,7 +76,8 @@ const IdToDeviceMetadataPacketMap&, std::unique_ptr<CryptAuthKey>, const base::Optional<cryptauthv2::EncryptedGroupPrivateKey>&, - const CryptAuthDeviceSyncResult&)>; + const base::Optional<cryptauthv2::ClientDirective>&, + CryptAuthDeviceSyncResult::ResultCode)>; virtual ~CryptAuthMetadataSyncer(); @@ -99,7 +101,8 @@ std::unique_ptr<CryptAuthKey> new_group_key, const base::Optional<cryptauthv2::EncryptedGroupPrivateKey>& encrypted_group_private_key, - const CryptAuthDeviceSyncResult& device_sync_result); + const base::Optional<cryptauthv2::ClientDirective>& new_client_directive, + CryptAuthDeviceSyncResult::ResultCode device_sync_result_code); private: SyncMetadataAttemptFinishedCallback callback_;
diff --git a/chromeos/services/device_sync/cryptauth_metadata_syncer_impl.cc b/chromeos/services/device_sync/cryptauth_metadata_syncer_impl.cc index f26f2629..a6a6c25 100644 --- a/chromeos/services/device_sync/cryptauth_metadata_syncer_impl.cc +++ b/chromeos/services/device_sync/cryptauth_metadata_syncer_impl.cc
@@ -511,7 +511,7 @@ } void CryptAuthMetadataSyncerImpl::FinishAttempt( - const CryptAuthDeviceSyncResult::ResultCode& result_code) { + CryptAuthDeviceSyncResult::ResultCode result_code) { cryptauth_client_.reset(); key_creator_.reset(); encryptor_.reset(); @@ -533,9 +533,7 @@ OnAttemptFinished(id_to_device_metadata_packet_map_, std::move(new_group_key_), encrypted_group_private_key, - CryptAuthDeviceSyncResult( - result_code, false /* did_device_registry_change */, - new_client_directive)); + new_client_directive, result_code); } std::ostream& operator<<(std::ostream& stream,
diff --git a/chromeos/services/device_sync/cryptauth_metadata_syncer_impl.h b/chromeos/services/device_sync/cryptauth_metadata_syncer_impl.h index 10ca8621..1af751d5 100644 --- a/chromeos/services/device_sync/cryptauth_metadata_syncer_impl.h +++ b/chromeos/services/device_sync/cryptauth_metadata_syncer_impl.h
@@ -121,7 +121,7 @@ void OnSyncMetadataFailure(NetworkRequestError error); void FilterMetadataAndFinishAttempt(); - void FinishAttempt(const CryptAuthDeviceSyncResult::ResultCode& result_code); + void FinishAttempt(CryptAuthDeviceSyncResult::ResultCode result_code); size_t num_sync_metadata_calls_ = 0; cryptauthv2::RequestContext request_context_;
diff --git a/chromeos/services/device_sync/cryptauth_metadata_syncer_impl_unittest.cc b/chromeos/services/device_sync/cryptauth_metadata_syncer_impl_unittest.cc index 7312e284..41f56d3d 100644 --- a/chromeos/services/device_sync/cryptauth_metadata_syncer_impl_unittest.cc +++ b/chromeos/services/device_sync/cryptauth_metadata_syncer_impl_unittest.cc
@@ -229,14 +229,19 @@ expected_device_metadata_packets, const base::Optional<CryptAuthKey>& expected_new_group_key, const base::Optional<std::string>& expected_group_private_key, - const CryptAuthDeviceSyncResult& expected_result) { - ASSERT_TRUE(device_sync_result_); + const base::Optional<cryptauthv2::ClientDirective>& + expected_new_client_directive, + CryptAuthDeviceSyncResult::ResultCode expected_result_code) { + ASSERT_TRUE(device_sync_result_code_); EXPECT_EQ(expected_device_metadata_packets.size(), id_to_device_metadata_packet_map_.size()); EXPECT_EQ(expected_new_group_key.has_value(), new_group_key_ != nullptr); EXPECT_EQ(expected_group_private_key.has_value(), encrypted_group_private_key_.has_value()); - EXPECT_EQ(expected_result, device_sync_result_); + EXPECT_EQ(expected_new_client_directive.has_value(), + new_client_directive_.has_value()); + + EXPECT_EQ(expected_result_code, *device_sync_result_code_); for (const cryptauthv2::DeviceMetadataPacket& expected_packet : expected_device_metadata_packets) { @@ -257,6 +262,11 @@ GetLocalDeviceForTest().device_better_together_public_key)); EXPECT_EQ(expected_group_private_key, decrypted_group_private_key); } + + if (expected_new_client_directive && new_client_directive_) { + EXPECT_EQ(expected_new_client_directive->SerializeAsString(), + new_client_directive_->SerializeAsString()); + } } base::MockOneShotTimer* timer() { return timer_; } @@ -361,11 +371,13 @@ std::unique_ptr<CryptAuthKey> new_group_key, const base::Optional<cryptauthv2::EncryptedGroupPrivateKey>& encrypted_group_private_key, - const CryptAuthDeviceSyncResult& device_sync_result) { + const base::Optional<cryptauthv2::ClientDirective>& new_client_directive, + CryptAuthDeviceSyncResult::ResultCode device_sync_result_code) { id_to_device_metadata_packet_map_ = id_to_device_metadata_packet_map; new_group_key_ = std::move(new_group_key); encrypted_group_private_key_ = encrypted_group_private_key; - device_sync_result_ = device_sync_result; + new_client_directive_ = new_client_directive; + device_sync_result_code_ = device_sync_result_code; } FakeCryptAuthKeyCreator* key_creator() { @@ -399,7 +411,9 @@ std::unique_ptr<CryptAuthKey> new_group_key_; base::Optional<cryptauthv2::EncryptedGroupPrivateKey> encrypted_group_private_key_; - base::Optional<CryptAuthDeviceSyncResult> device_sync_result_; + base::Optional<cryptauthv2::ClientDirective> new_client_directive_; + base::Optional<CryptAuthDeviceSyncResult::ResultCode> + device_sync_result_code_; base::Optional<CryptAuthKey> initial_group_key_; std::unique_ptr<CryptAuthMetadataSyncer> metadata_syncer_; @@ -434,9 +448,8 @@ CryptAuthKey(group_public_key, group_private_key, CryptAuthKey::Status::kActive, cryptauthv2::KeyType::P256), base::nullopt /* expected_group_private_key */, - CryptAuthDeviceSyncResult(CryptAuthDeviceSyncResult::ResultCode::kSuccess, - false /* device_registry_changed */, - cryptauthv2::GetClientDirectiveForTest())); + cryptauthv2::GetClientDirectiveForTest(), + CryptAuthDeviceSyncResult::ResultCode::kSuccess); } TEST_F(DeviceSyncCryptAuthMetadataSyncerImplTest, @@ -458,13 +471,11 @@ base::nullopt /* group_private_key */, cryptauthv2::GetClientDirectiveForTest()); - VerifyMetadataSyncResult( - GetAllTestDeviceMetadataPackets(), - base::nullopt /* expected_new_group_key */, - base::nullopt /* expected_group_private_key */, - CryptAuthDeviceSyncResult(CryptAuthDeviceSyncResult::ResultCode::kSuccess, - false /* device_registry_changed */, - cryptauthv2::GetClientDirectiveForTest())); + VerifyMetadataSyncResult(GetAllTestDeviceMetadataPackets(), + base::nullopt /* expected_new_group_key */, + base::nullopt /* expected_group_private_key */, + cryptauthv2::GetClientDirectiveForTest(), + CryptAuthDeviceSyncResult::ResultCode::kSuccess); } TEST_F(DeviceSyncCryptAuthMetadataSyncerImplTest, @@ -490,12 +501,11 @@ group_public_key, group_private_key, cryptauthv2::GetClientDirectiveForTest()); - VerifyMetadataSyncResult( - GetAllTestDeviceMetadataPackets(), - base::nullopt /* expected_new_group_key */, group_private_key, - CryptAuthDeviceSyncResult(CryptAuthDeviceSyncResult::ResultCode::kSuccess, - false /* device_registry_changed */, - cryptauthv2::GetClientDirectiveForTest())); + VerifyMetadataSyncResult(GetAllTestDeviceMetadataPackets(), + base::nullopt /* expected_new_group_key */, + group_private_key, + cryptauthv2::GetClientDirectiveForTest(), + CryptAuthDeviceSyncResult::ResultCode::kSuccess); } TEST_F(DeviceSyncCryptAuthMetadataSyncerImplTest, @@ -538,9 +548,8 @@ CryptAuthKey(group_public_key, group_private_key, CryptAuthKey::Status::kActive, cryptauthv2::KeyType::P256), base::nullopt /* expected_group_private_key */, - CryptAuthDeviceSyncResult(CryptAuthDeviceSyncResult::ResultCode::kSuccess, - false /* device_registry_changed */, - cryptauthv2::GetClientDirectiveForTest())); + cryptauthv2::GetClientDirectiveForTest(), + CryptAuthDeviceSyncResult::ResultCode::kSuccess); } TEST_F(DeviceSyncCryptAuthMetadataSyncerImplTest, @@ -584,10 +593,8 @@ GetAllTestDeviceMetadataPackets(), CryptAuthKey(group_public_key, std::string() /* group_private_key */, CryptAuthKey::Status::kActive, cryptauthv2::KeyType::P256), - group_private_key, - CryptAuthDeviceSyncResult(CryptAuthDeviceSyncResult::ResultCode::kSuccess, - false /* device_registry_changed */, - cryptauthv2::GetClientDirectiveForTest())); + group_private_key, cryptauthv2::GetClientDirectiveForTest(), + CryptAuthDeviceSyncResult::ResultCode::kSuccess); } TEST_F(DeviceSyncCryptAuthMetadataSyncerImplTest, @@ -630,9 +637,8 @@ CryptAuthKey(group_public_key, std::string() /* group_private_key */, CryptAuthKey::Status::kActive, cryptauthv2::KeyType::P256), base::nullopt /* expected_group_private_key */, - CryptAuthDeviceSyncResult(CryptAuthDeviceSyncResult::ResultCode::kSuccess, - false /* device_registry_changed */, - cryptauthv2::GetClientDirectiveForTest())); + cryptauthv2::GetClientDirectiveForTest(), + CryptAuthDeviceSyncResult::ResultCode::kSuccess); } TEST_F(DeviceSyncCryptAuthMetadataSyncerImplTest, Failure_MetadataEncryption) { @@ -650,10 +656,8 @@ {} /* expected_device_metadata_packets */, base::nullopt /* expected_new_group_key */, base::nullopt /* expected_group_private_key */, - CryptAuthDeviceSyncResult( - CryptAuthDeviceSyncResult::ResultCode::kErrorEncryptingDeviceMetadata, - false /* device_registry_changed */, - base::nullopt /* client_directive */)); + base::nullopt /* expected_new_client_directive */, + CryptAuthDeviceSyncResult::ResultCode::kErrorEncryptingDeviceMetadata); } TEST_F( @@ -702,10 +706,8 @@ CryptAuthKey(group_public_key, group_private_key, CryptAuthKey::Status::kActive, cryptauthv2::KeyType::P256), base::nullopt /* expected_group_private_key */, - CryptAuthDeviceSyncResult(CryptAuthDeviceSyncResult::ResultCode:: - kErrorEstablishingGroupPublicKey, - false /* device_registry_changed */, - cryptauthv2::GetClientDirectiveForTest())); + cryptauthv2::GetClientDirectiveForTest(), + CryptAuthDeviceSyncResult::ResultCode::kErrorEstablishingGroupPublicKey); } TEST_F( @@ -754,11 +756,8 @@ {} /* expected_device_metadata_packets */, CryptAuthKey(group_public_key, group_private_key, CryptAuthKey::Status::kActive, cryptauthv2::KeyType::P256), - stale_group_private_key, - CryptAuthDeviceSyncResult(CryptAuthDeviceSyncResult::ResultCode:: - kErrorEstablishingGroupPublicKey, - false /* device_registry_changed */, - cryptauthv2::GetClientDirectiveForTest())); + stale_group_private_key, cryptauthv2::GetClientDirectiveForTest(), + CryptAuthDeviceSyncResult::ResultCode::kErrorEstablishingGroupPublicKey); } TEST_F(DeviceSyncCryptAuthMetadataSyncerImplTest, @@ -784,10 +783,8 @@ {} /* expected_device_metadata_packets */, base::nullopt /* expected_new_group_key */, base::nullopt /* expected_group_private_key */, - CryptAuthDeviceSyncResult( - CryptAuthDeviceSyncResult::ResultCode::kErrorNoMetadataInResponse, - false /* device_registry_changed */, - cryptauthv2::GetClientDirectiveForTest())); + cryptauthv2::GetClientDirectiveForTest(), + CryptAuthDeviceSyncResult::ResultCode::kErrorNoMetadataInResponse); } TEST_F(DeviceSyncCryptAuthMetadataSyncerImplTest, @@ -821,10 +818,8 @@ GetRemoteDeviceMetadataPacketNeedsGroupPrivateKeyForTest()}, base::nullopt /* expected_new_group_key */, base::nullopt /* expected_group_private_key */, - CryptAuthDeviceSyncResult( - CryptAuthDeviceSyncResult::ResultCode::kFinishedWithNonFatalErrors, - false /* device_registry_changed */, - cryptauthv2::GetClientDirectiveForTest())); + cryptauthv2::GetClientDirectiveForTest(), + CryptAuthDeviceSyncResult::ResultCode::kFinishedWithNonFatalErrors); } TEST_F(DeviceSyncCryptAuthMetadataSyncerImplTest, @@ -852,10 +847,8 @@ {} /* expected_device_metadata_packets */, base::nullopt /* expected_new_group_key */, base::nullopt /* expected_group_private_key */, - CryptAuthDeviceSyncResult(CryptAuthDeviceSyncResult::ResultCode:: - kErrorAllResponseMetadataInvalid, - false /* device_registry_changed */, - cryptauthv2::GetClientDirectiveForTest())); + cryptauthv2::GetClientDirectiveForTest(), + CryptAuthDeviceSyncResult::ResultCode::kErrorAllResponseMetadataInvalid); } TEST_F(DeviceSyncCryptAuthMetadataSyncerImplTest, @@ -888,10 +881,8 @@ GetAllTestDeviceMetadataPackets(), base::nullopt /* expected_new_group_key */, base::nullopt /* expected_group_private_key */, - CryptAuthDeviceSyncResult( - CryptAuthDeviceSyncResult::ResultCode::kFinishedWithNonFatalErrors, - false /* device_registry_changed */, - cryptauthv2::GetClientDirectiveForTest())); + cryptauthv2::GetClientDirectiveForTest(), + CryptAuthDeviceSyncResult::ResultCode::kFinishedWithNonFatalErrors); } TEST_F(DeviceSyncCryptAuthMetadataSyncerImplTest, @@ -919,10 +910,9 @@ GetRemoteDeviceMetadataPacketHasGroupPrivateKeyForTest()}, base::nullopt /* expected_new_group_key */, base::nullopt /* expected_group_private_key */, - CryptAuthDeviceSyncResult(CryptAuthDeviceSyncResult::ResultCode:: - kErrorNoLocalDeviceMetadataInResponse, - false /* device_registry_changed */, - cryptauthv2::GetClientDirectiveForTest())); + cryptauthv2::GetClientDirectiveForTest(), + CryptAuthDeviceSyncResult::ResultCode:: + kErrorNoLocalDeviceMetadataInResponse); } TEST_F(DeviceSyncCryptAuthMetadataSyncerImplTest, @@ -933,14 +923,12 @@ // Timeout before group key creation completes. timer()->Fire(); - VerifyMetadataSyncResult( - {} /* expected_device_metadata_packets */, - base::nullopt /* expected_new_group_key */, - base::nullopt /* expected_group_private_key */, - CryptAuthDeviceSyncResult(CryptAuthDeviceSyncResult::ResultCode:: - kErrorTimeoutWaitingForGroupKeyCreation, - false /* device_registry_changed */, - base::nullopt /* client_directive */)); + VerifyMetadataSyncResult({} /* expected_device_metadata_packets */, + base::nullopt /* expected_new_group_key */, + base::nullopt /* expected_group_private_key */, + base::nullopt /* expected_new_client_directive */, + CryptAuthDeviceSyncResult::ResultCode:: + kErrorTimeoutWaitingForGroupKeyCreation); } TEST_F(DeviceSyncCryptAuthMetadataSyncerImplTest, @@ -957,11 +945,9 @@ {} /* expected_device_metadata_packets */, base::nullopt /* expected_new_group_key */, base::nullopt /* expected_group_private_key */, - CryptAuthDeviceSyncResult( - CryptAuthDeviceSyncResult::ResultCode:: - kErrorTimeoutWaitingForLocalDeviceMetadataEncryption, - false /* device_registry_changed */, - base::nullopt /* client_directive */)); + base::nullopt /* expected_new_client_directive */, + CryptAuthDeviceSyncResult::ResultCode:: + kErrorTimeoutWaitingForLocalDeviceMetadataEncryption); } TEST_F(DeviceSyncCryptAuthMetadataSyncerImplTest, @@ -983,11 +969,9 @@ {} /* expected_device_metadata_packets */, base::nullopt /* expected_new_group_key */, base::nullopt /* expected_group_private_key */, - CryptAuthDeviceSyncResult( - CryptAuthDeviceSyncResult::ResultCode:: - kErrorTimeoutWaitingForFirstSyncMetadataResponse, - false /* device_registry_changed */, - base::nullopt /* client_directive */)); + base::nullopt /* expected_new_client_directive */, + CryptAuthDeviceSyncResult::ResultCode:: + kErrorTimeoutWaitingForFirstSyncMetadataResponse); } TEST_F(DeviceSyncCryptAuthMetadataSyncerImplTest, @@ -1027,11 +1011,9 @@ CryptAuthKey(group_public_key, group_private_key, CryptAuthKey::Status::kActive, cryptauthv2::KeyType::P256), base::nullopt /* expected_group_private_key */, - CryptAuthDeviceSyncResult( - CryptAuthDeviceSyncResult::ResultCode:: - kErrorTimeoutWaitingForSecondSyncMetadataResponse, - false /* device_registry_changed */, - cryptauthv2::GetClientDirectiveForTest())); + cryptauthv2::GetClientDirectiveForTest(), + CryptAuthDeviceSyncResult::ResultCode:: + kErrorTimeoutWaitingForSecondSyncMetadataResponse); } TEST_F(DeviceSyncCryptAuthMetadataSyncerImplTest, @@ -1049,14 +1031,12 @@ // The first SyncMetadata API call fails with a HTTP 400 Bad Request error. FailFirstSyncMetadataRequest(NetworkRequestError::kBadRequest); - VerifyMetadataSyncResult( - {} /* expected_device_metadata_packets */, - base::nullopt /* expected_new_group_key */, - base::nullopt /* expected_group_private_key */, - CryptAuthDeviceSyncResult(CryptAuthDeviceSyncResult::ResultCode:: - kErrorSyncMetadataApiCallBadRequest, - false /* device_registry_changed */, - base::nullopt /* client_directive */)); + VerifyMetadataSyncResult({} /* expected_device_metadata_packets */, + base::nullopt /* expected_new_group_key */, + base::nullopt /* expected_group_private_key */, + base::nullopt /* expected_new_client_directive */, + CryptAuthDeviceSyncResult::ResultCode:: + kErrorSyncMetadataApiCallBadRequest); } TEST_F(DeviceSyncCryptAuthMetadataSyncerImplTest, @@ -1096,10 +1076,9 @@ CryptAuthKey(group_public_key, group_private_key, CryptAuthKey::Status::kActive, cryptauthv2::KeyType::P256), base::nullopt /* expected_group_private_key */, - CryptAuthDeviceSyncResult(CryptAuthDeviceSyncResult::ResultCode:: - kErrorSyncMetadataApiCallBadRequest, - false /* device_registry_changed */, - cryptauthv2::GetClientDirectiveForTest())); + cryptauthv2::GetClientDirectiveForTest(), + CryptAuthDeviceSyncResult::ResultCode:: + kErrorSyncMetadataApiCallBadRequest); } } // namespace device_sync
diff --git a/chromeos/services/device_sync/fake_cryptauth_feature_status_getter.cc b/chromeos/services/device_sync/fake_cryptauth_feature_status_getter.cc index bca3d6949..d07ace3 100644 --- a/chromeos/services/device_sync/fake_cryptauth_feature_status_getter.cc +++ b/chromeos/services/device_sync/fake_cryptauth_feature_status_getter.cc
@@ -14,7 +14,7 @@ void FakeCryptAuthFeatureStatusGetter::FinishAttempt( const IdToFeatureStatusMap& id_to_feature_status_map, - const CryptAuthDeviceSyncResult::ResultCode& device_sync_result_code) { + CryptAuthDeviceSyncResult::ResultCode device_sync_result_code) { DCHECK(request_context_); DCHECK(device_ids_);
diff --git a/chromeos/services/device_sync/fake_cryptauth_feature_status_getter.h b/chromeos/services/device_sync/fake_cryptauth_feature_status_getter.h index 34f94ae..99967e5 100644 --- a/chromeos/services/device_sync/fake_cryptauth_feature_status_getter.h +++ b/chromeos/services/device_sync/fake_cryptauth_feature_status_getter.h
@@ -44,7 +44,7 @@ // Calls OnAttemptFinished() with the same input parameters. void FinishAttempt( const IdToFeatureStatusMap& id_to_feature_status_map, - const CryptAuthDeviceSyncResult::ResultCode& device_sync_result_code); + CryptAuthDeviceSyncResult::ResultCode device_sync_result_code); private: // CryptAuthFeatureStatusGetter:
diff --git a/chromeos/services/device_sync/fake_cryptauth_group_private_key_sharer.cc b/chromeos/services/device_sync/fake_cryptauth_group_private_key_sharer.cc index c62a86d0..de378246 100644 --- a/chromeos/services/device_sync/fake_cryptauth_group_private_key_sharer.cc +++ b/chromeos/services/device_sync/fake_cryptauth_group_private_key_sharer.cc
@@ -17,7 +17,7 @@ default; void FakeCryptAuthGroupPrivateKeySharer::FinishAttempt( - const CryptAuthDeviceSyncResult::ResultCode& device_sync_result_code) { + CryptAuthDeviceSyncResult::ResultCode device_sync_result_code) { DCHECK(request_context_); DCHECK(group_key_); DCHECK(id_to_encrypting_key_map_);
diff --git a/chromeos/services/device_sync/fake_cryptauth_group_private_key_sharer.h b/chromeos/services/device_sync/fake_cryptauth_group_private_key_sharer.h index e5ddd8c..77dd41e 100644 --- a/chromeos/services/device_sync/fake_cryptauth_group_private_key_sharer.h +++ b/chromeos/services/device_sync/fake_cryptauth_group_private_key_sharer.h
@@ -45,7 +45,7 @@ } void FinishAttempt( - const CryptAuthDeviceSyncResult::ResultCode& device_sync_result_code); + CryptAuthDeviceSyncResult::ResultCode device_sync_result_code); private: // CryptAuthGroupPrivateKeySharer:
diff --git a/chromeos/services/device_sync/fake_cryptauth_metadata_syncer.cc b/chromeos/services/device_sync/fake_cryptauth_metadata_syncer.cc index 9d38f99..ab24581b 100644 --- a/chromeos/services/device_sync/fake_cryptauth_metadata_syncer.cc +++ b/chromeos/services/device_sync/fake_cryptauth_metadata_syncer.cc
@@ -17,13 +17,15 @@ std::unique_ptr<CryptAuthKey> new_group_key, const base::Optional<cryptauthv2::EncryptedGroupPrivateKey>& encrypted_group_private_key, - const CryptAuthDeviceSyncResult& device_sync_result) { + const base::Optional<cryptauthv2::ClientDirective>& new_client_directive, + CryptAuthDeviceSyncResult::ResultCode device_sync_result_code) { DCHECK(request_context_); DCHECK(local_device_metadata_); DCHECK(initial_group_key_); OnAttemptFinished(id_to_device_metadata_packet_map, std::move(new_group_key), - encrypted_group_private_key, device_sync_result); + encrypted_group_private_key, new_client_directive, + device_sync_result_code); } void FakeCryptAuthMetadataSyncer::OnAttemptStarted(
diff --git a/chromeos/services/device_sync/fake_cryptauth_metadata_syncer.h b/chromeos/services/device_sync/fake_cryptauth_metadata_syncer.h index af9f471d..2bdff59 100644 --- a/chromeos/services/device_sync/fake_cryptauth_metadata_syncer.h +++ b/chromeos/services/device_sync/fake_cryptauth_metadata_syncer.h
@@ -11,17 +11,18 @@ #include "base/macros.h" #include "base/optional.h" #include "base/timer/timer.h" +#include "chromeos/services/device_sync/cryptauth_device_sync_result.h" #include "chromeos/services/device_sync/cryptauth_metadata_syncer.h" #include "chromeos/services/device_sync/cryptauth_metadata_syncer_impl.h" #include "chromeos/services/device_sync/proto/cryptauth_better_together_device_metadata.pb.h" #include "chromeos/services/device_sync/proto/cryptauth_devicesync.pb.h" +#include "chromeos/services/device_sync/proto/cryptauth_directive.pb.h" namespace chromeos { namespace device_sync { class CryptAuthClientFactory; -class CryptAuthDeviceSyncResult; class CryptAuthKey; class FakeCryptAuthMetadataSyncer : public CryptAuthMetadataSyncer { @@ -53,7 +54,8 @@ std::unique_ptr<CryptAuthKey> new_group_key, const base::Optional<cryptauthv2::EncryptedGroupPrivateKey>& encrypted_group_private_key, - const CryptAuthDeviceSyncResult& device_sync_result); + const base::Optional<cryptauthv2::ClientDirective>& new_client_directive, + CryptAuthDeviceSyncResult::ResultCode device_sync_result_code); private: // CryptAuthMetadataSyncer:
diff --git a/components/feature_engagement/README.md b/components/feature_engagement/README.md index ea4a5711..e9909078 100644 --- a/components/feature_engagement/README.md +++ b/components/feature_engagement/README.md
@@ -589,13 +589,14 @@ python ./tools/variations/fieldtrial_util.py DownloadStudy.json android shell_cmd ``` -1. Pass the command line along to the binary you are planning on running or the - command line utility for the Android platform. +1. Pass the command line along to the binary you are planning on running. - For the target `chrome_public_apk` it would be: + Note: For Android you need to ensure that all arguments are are within one + set of double quotes. In particular, for the Android target + `chrome_public_apk` it would be: ```bash - ./build/android/adb_chrome_public_command_line "--force-fieldtrials=DownloadStudy/DownloadExperiment" "--force-fieldtrial-params=DownloadStudy.DownloadExperiment:availability/>=30/event_1/name%3Adownload_completed;comparator%3A>=1;window%3A120;storage%3A180/event_trigger/name%3Adownload_home_iph_trigger;comparator%3Aany;window%3A90;storage%3A360/event_used/name%3Adownload_home_opened;comparator%3Aany;window%3A90;storage%3A360/session_rate/<1" "--enable-features=IPH_DownloadHome<DownloadStudy" + ./out/Debug/bin/chrome_public_apk run --args "--force-fieldtrials=DownloadStudy/DownloadExperiment --force-fieldtrial-params=DownloadStudy.DownloadExperiment:availability/>=30/event_1/name%3Adownload_completed;comparator%3A>=1;window%3A120;storage%3A180/event_trigger/name%3Adownload_home_iph_trigger;comparator%3Aany;window%3A90;storage%3A360/event_used/name%3Adownload_home_opened;comparator%3Aany;window%3A90;storage%3A360/session_rate/<1 --enable-features=IPH_DownloadHome<DownloadStudy" ``` ### Printf debugging
diff --git a/components/network_session_configurator/browser/network_session_configurator.cc b/components/network_session_configurator/browser/network_session_configurator.cc index b7e28cce..af811ae 100644 --- a/components/network_session_configurator/browser/network_session_configurator.cc +++ b/components/network_session_configurator/browser/network_session_configurator.cc
@@ -25,6 +25,7 @@ #include "components/variations/variations_associated_data.h" #include "net/base/host_mapping_rules.h" #include "net/http/http_stream_factory.h" +#include "net/quic/platform/impl/quic_flags_impl.h" #include "net/quic/quic_utils_chromium.h" #include "net/spdy/spdy_session.h" #include "net/spdy/spdy_session_pool.h" @@ -438,6 +439,19 @@ return base::flat_set<std::string>(std::move(host_vector)); } +void SetQuicFlags(const VariationParameters& quic_trial_params) { + std::string flags_list = + GetVariationParam(quic_trial_params, "set_quic_flags"); + for (const auto& flag : base::SplitString( + flags_list, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) { + std::vector<std::string> tokens = base::SplitString( + flag, "=", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); + if (tokens.size() != 2) + continue; + SetQuicFlagByName(tokens[0], tokens[1]); + } +} + size_t GetQuicMaxPacketLength(const VariationParameters& quic_trial_params) { unsigned value; if (base::StringToUint( @@ -579,6 +593,8 @@ params->quic_params.allow_server_migration = ShouldQuicAllowServerMigration(quic_trial_params); params->quic_host_allowlist = GetQuicHostAllowlist(quic_trial_params); + + SetQuicFlags(quic_trial_params); } size_t max_packet_length = GetQuicMaxPacketLength(quic_trial_params);
diff --git a/components/network_session_configurator/browser/network_session_configurator_unittest.cc b/components/network_session_configurator/browser/network_session_configurator_unittest.cc index a4ded6a..45e18a4 100644 --- a/components/network_session_configurator/browser/network_session_configurator_unittest.cc +++ b/components/network_session_configurator/browser/network_session_configurator_unittest.cc
@@ -604,6 +604,22 @@ EXPECT_TRUE(params_.quic_host_allowlist.empty()); } +TEST_F(NetworkSessionConfiguratorTest, QuicFlags) { + FLAGS_quic_supports_tls_handshake = false; + FLAGS_quic_reloadable_flag_quic_enable_version_99 = false; + std::map<std::string, std::string> field_trial_params; + field_trial_params["set_quic_flags"] = + "FLAGS_quic_supports_tls_handshake=true," + "FLAGS_quic_reloadable_flag_quic_enable_version_99=true"; + variations::AssociateVariationParams("QUIC", "Enabled", field_trial_params); + base::FieldTrialList::CreateFieldTrial("QUIC", "Enabled"); + + ParseFieldTrials(); + + EXPECT_TRUE(FLAGS_quic_supports_tls_handshake); + EXPECT_TRUE(FLAGS_quic_reloadable_flag_quic_enable_version_99); +} + TEST_F(NetworkSessionConfiguratorTest, Http2SettingsFromFieldTrialParams) { std::map<std::string, std::string> field_trial_params; field_trial_params["http2_settings"] = "7:1234,25:5678";
diff --git a/components/offline_pages/core/model/offline_page_model_taskified.cc b/components/offline_pages/core/model/offline_page_model_taskified.cc index e1ecaf0..bef904d0 100644 --- a/components/offline_pages/core/model/offline_page_model_taskified.cc +++ b/components/offline_pages/core/model/offline_page_model_taskified.cc
@@ -230,12 +230,23 @@ create_archive_params.use_page_problem_detectors = save_page_params.use_page_problem_detectors; + // Set on-the-fly hashing if enabled. + create_archive_params.use_on_the_fly_hash_computation = + IsOnTheFlyMhtmlHashComputationEnabled(); + + // Save directly to public location if on-the-fly enabled. + // + // TODO(crbug.com/999247): We would like to skip renaming the file if + // streaming the file directly to it's end location. Knowing the file path or + // name before calling the archiver would make this possible. + base::FilePath save_file_dir = + GetArchiveDirectory(save_page_params.client_id.name_space); + // Note: the archiver instance must be kept alive until the final callback // coming from it takes place. OfflinePageArchiver* raw_archiver = archiver.get(); raw_archiver->CreateArchive( - GetInternalArchiveDirectory(save_page_params.client_id.name_space), - create_archive_params, web_contents, + save_file_dir, create_archive_params, web_contents, base::BindOnce(&OfflinePageModelTaskified::OnCreateArchiveDone, weak_ptr_factory_.GetWeakPtr(), save_page_params, offline_id, OfflineTimeNow(), std::move(archiver), @@ -349,10 +360,12 @@ store_.get(), offline_id, std::move(callback))); } -const base::FilePath& OfflinePageModelTaskified::GetInternalArchiveDirectory( +const base::FilePath& OfflinePageModelTaskified::GetArchiveDirectory( const std::string& name_space) const { if (GetPolicy(name_space).lifetime_type == LifetimeType::TEMPORARY) return archive_manager_->GetTemporaryArchivesDir(); + if (IsOnTheFlyMhtmlHashComputationEnabled()) + return archive_manager_->GetPublicArchivesDir(); return archive_manager_->GetPrivateArchivesDir(); }
diff --git a/components/offline_pages/core/model/offline_page_model_taskified.h b/components/offline_pages/core/model/offline_page_model_taskified.h index ba8b37561..dbca3ef3 100644 --- a/components/offline_pages/core/model/offline_page_model_taskified.h +++ b/components/offline_pages/core/model/offline_page_model_taskified.h
@@ -102,7 +102,7 @@ void GetVisualsAvailability( int64_t offline_id, base::OnceCallback<void(VisualsAvailability)> callback) override; - const base::FilePath& GetInternalArchiveDirectory( + const base::FilePath& GetArchiveDirectory( const std::string& name_space) const override; bool IsArchiveInInternalDir(const base::FilePath& file_path) const override; OfflineEventLogger* GetLogger() override;
diff --git a/components/offline_pages/core/model/offline_page_model_taskified_unittest.cc b/components/offline_pages/core/model/offline_page_model_taskified_unittest.cc index e0b5dc8..79892109 100644 --- a/components/offline_pages/core/model/offline_page_model_taskified_unittest.cc +++ b/components/offline_pages/core/model/offline_page_model_taskified_unittest.cc
@@ -1240,10 +1240,10 @@ TEST_F(OfflinePageModelTaskifiedTest, GetArchiveDirectory) { base::FilePath temporary_dir = - model()->GetInternalArchiveDirectory(kDefaultNamespace); + model()->GetArchiveDirectory(kDefaultNamespace); EXPECT_EQ(temporary_dir_path(), temporary_dir); base::FilePath persistent_dir = - model()->GetInternalArchiveDirectory(kDownloadNamespace); + model()->GetArchiveDirectory(kDownloadNamespace); EXPECT_EQ(private_archive_dir_path(), persistent_dir); }
diff --git a/components/offline_pages/core/offline_page_archiver.h b/components/offline_pages/core/offline_page_archiver.h index 4f5e7b2..9efe6540 100644 --- a/components/offline_pages/core/offline_page_archiver.h +++ b/components/offline_pages/core/offline_page_archiver.h
@@ -72,6 +72,9 @@ // Run page problem detectors while generating MTHML if true. bool use_page_problem_detectors = false; + + // Whether to enable on-the-fly hash computation. + bool use_on_the_fly_hash_computation = false; }; // Callback for the final result of an attempt to generate of offline page
diff --git a/components/offline_pages/core/offline_page_model.h b/components/offline_pages/core/offline_page_model.h index 86c8e5a..b5ab571 100644 --- a/components/offline_pages/core/offline_page_model.h +++ b/components/offline_pages/core/offline_page_model.h
@@ -191,7 +191,7 @@ PublishPageCallback publish_done_callback) = 0; // Get the archive directory based on client policy of the namespace. - virtual const base::FilePath& GetInternalArchiveDirectory( + virtual const base::FilePath& GetArchiveDirectory( const std::string& name_space) const = 0; // Returns whether given archive file is in the internal directory.
diff --git a/components/offline_pages/core/prefetch/prefetch_importer_impl.cc b/components/offline_pages/core/prefetch/prefetch_importer_impl.cc index 99b6d57..3e5d886 100644 --- a/components/offline_pages/core/prefetch/prefetch_importer_impl.cc +++ b/components/offline_pages/core/prefetch/prefetch_importer_impl.cc
@@ -76,8 +76,7 @@ // The target file name will be auto generated based on GUID to prevent any // name collision. base::FilePath archives_dir = - offline_page_model_->GetInternalArchiveDirectory( - archive.client_id.name_space); + offline_page_model_->GetArchiveDirectory(archive.client_id.name_space); base::FilePath dest_path = archives_dir.AppendASCII(base::GenerateGUID()) .AddExtension(FILE_PATH_LITERAL("mhtml"));
diff --git a/components/offline_pages/core/prefetch/prefetch_importer_impl_unittest.cc b/components/offline_pages/core/prefetch/prefetch_importer_impl_unittest.cc index d683cbe..b0ea704 100644 --- a/components/offline_pages/core/prefetch/prefetch_importer_impl_unittest.cc +++ b/components/offline_pages/core/prefetch/prefetch_importer_impl_unittest.cc
@@ -50,7 +50,7 @@ page.offline_id); } - const base::FilePath& GetInternalArchiveDirectory( + const base::FilePath& GetArchiveDirectory( const std::string& name_space) const override { return archive_dir_.GetPath(); }
diff --git a/components/offline_pages/core/stub_offline_page_model.cc b/components/offline_pages/core/stub_offline_page_model.cc index 7163dc2..7474de87 100644 --- a/components/offline_pages/core/stub_offline_page_model.cc +++ b/components/offline_pages/core/stub_offline_page_model.cc
@@ -55,7 +55,7 @@ void StubOfflinePageModel::PublishInternalArchive( const OfflinePageItem& offline_page, PublishPageCallback publish_done_callback) {} -const base::FilePath& StubOfflinePageModel::GetInternalArchiveDirectory( +const base::FilePath& StubOfflinePageModel::GetArchiveDirectory( const std::string& name_space) const { return archive_directory_; }
diff --git a/components/offline_pages/core/stub_offline_page_model.h b/components/offline_pages/core/stub_offline_page_model.h index 05e207e8..91d7caa90 100644 --- a/components/offline_pages/core/stub_offline_page_model.h +++ b/components/offline_pages/core/stub_offline_page_model.h
@@ -53,7 +53,7 @@ void PublishInternalArchive( const OfflinePageItem& offline_page, PublishPageCallback publish_done_callback) override; - const base::FilePath& GetInternalArchiveDirectory( + const base::FilePath& GetArchiveDirectory( const std::string& name_space) const override; bool IsArchiveInInternalDir(const base::FilePath& file_path) const override; OfflineEventLogger* GetLogger() override;
diff --git a/components/omnibox/browser/autocomplete_controller.cc b/components/omnibox/browser/autocomplete_controller.cc index 0945087..fe3fd8c8 100644 --- a/components/omnibox/browser/autocomplete_controller.cc +++ b/components/omnibox/browser/autocomplete_controller.cc
@@ -441,6 +441,9 @@ } if (match.deletable) { + // This histogram is defined in the internal histograms.xml. This is because + // the vast majority of OmniboxProviderAndResultType histograms are + // generated by internal tools, and we wish to keep them together. base::UmaHistogramSparse("Omnibox.SuggestionDeleted.ProviderAndResultType", combined_type); match.provider->DeleteMatch(match);
diff --git a/components/omnibox/bug-triage.md b/components/omnibox/bug-triage.md index 243a97af..760a1fb 100644 --- a/components/omnibox/bug-triage.md +++ b/components/omnibox/bug-triage.md
@@ -33,9 +33,9 @@ * Every week on Tuesday, the triage engineer looks over [all *Unconfirmed* and *Untriaged* bugs filed that aren’t categorized as omnibox yet have relevant terms](https://bugs.chromium.org/p/chromium/issues/list?can=2&q=omnibox+-component%3AUI%3EBrowser%3EOmnibox+status%3AUnconfirmed%2CUntriaged+-has%3Aowner+OR+%E2%80%9Comni+box%E2%80%9D+-component%3AUI%3EBrowser%3EOmnibox+status%3AUnconfirmed%2CUntriaged+-has%3Aowner+OR+omnibar+-component%3AUI%3EBrowser%3EOmnibox+status%3AUnconfirmed%2CUntriaged+-has%3Aowner+OR+%E2%80%9Comni+bar%E2%80%9D+-component%3AUI%3EBrowser%3EOmnibox+status%3AUnconfirmed%2CUntriaged+-has%3Aowner+OR+locationbar+-component%3AUI%3EBrowser%3EOmnibox+status%3AUnconfirmed%2CUntriaged+-has%3Aowner+OR+%E2%80%9Clocation+bar%E2%80%9D+-component%3AUI%3EBrowser%3EOmnibox+status%3AUnconfirmed%2CUntriaged+-has%3Aowner+OR+addressbar+-component%3AUI%3EBrowser%3EOmnibox+status%3AUnconfirmed%2CUntriaged+-has%3Aowner+OR+%E2%80%9Caddress+bar%E2%80%9D+-component%3AUI%3EBrowser%3EOmnibox+status%3AUnconfirmed%2CUntriaged+-has%3Aowner&colspec=ID+Pri+M+Stars+ReleaseBlock+Component+Status+Owner+Summary+OS+Modified&x=m&y=releaseblock&cells=ids) - to see if any should be moved to the omnibox component and triaged. (This + to see if any should be moved to the omnibox component and triaged. ([This scan can be limited to those filed in the last week, i.e., since the last - check.) + check.](https://bugs.chromium.org/p/chromium/issues/list?colspec=ID%20Pri%20M%20Stars%20ReleaseBlock%20Component%20Status%20Owner%20Summary%20OS%20Modified&x=m&y=releaseblock&cells=ids&q=omnibox%20-component%3AUI>Browser>Omnibox%20status%3AUnconfirmed%2CUntriaged%20-has%3Aowner%20modified>today-14%20OR%20“omni%20box”%20-component%3AUI>Browser>Omnibox%20status%3AUnconfirmed%2CUntriaged%20-has%3Aowner%20modified>today-14%20OR%20omnibar%20-component%3AUI>Browser>Omnibox%20status%3AUnconfirmed%2CUntriaged%20-has%3Aowner%20modified>today-14%20OR%20“omni%20bar”%20-component%3AUI>Browser>Omnibox%20status%3AUnconfirmed%2CUntriaged%20-has%3Aowner%20modified>today-14%20OR%20locationbar%20-component%3AUI>Browser>Omnibox%20status%3AUnconfirmed%2CUntriaged%20-has%3Aowner%20modified>today-14%20OR%20“location%20bar”%20-component%3AUI>Browser>Omnibox%20status%3AUnconfirmed%2CUntriaged%20-has%3Aowner%20modified>today-14%20OR%20addressbar%20-component%3AUI>Browser>Omnibox%20status%3AUnconfirmed%2CUntriaged%20-has%3Aowner%20modified>today-14%20OR%20“address%20bar”%20-component%3AUI>Browser>Omnibox%20status%3AUnconfirmed%2CUntriaged%20-has%3Aowner%20modified>today-14&can=2)) * Every week on Thursday, the triage engineer looks over all alerts sent to [chrome-omnibox-team-alerts@](https://groups.google.com/a/google.com/forum/#!forum/chrome-omnibox-team-alerts) and, for each, either files a bug or replies to the message indicating why
diff --git a/components/omnibox/common/omnibox_features.cc b/components/omnibox/common/omnibox_features.cc index b24f0b2..7b624d3 100644 --- a/components/omnibox/common/omnibox_features.cc +++ b/components/omnibox/common/omnibox_features.cc
@@ -291,8 +291,6 @@ // This feature's main job is to contain some field trial parameters such as: // - "ZeroSuggestVariant" configures the per-page-classification mode of // ZeroSuggestProvider. -// - "CustomEndpointURL" configures a custom endpoint for remote suggestions. -// - "CustomEndpointExperimentID" sends an id number to the custom endpoint. const base::Feature kOnFocusSuggestions{"OmniboxOnFocusSuggestions", base::FEATURE_ENABLED_BY_DEFAULT};
diff --git a/components/previews/content/previews_optimization_guide_decider.cc b/components/previews/content/previews_optimization_guide_decider.cc index 08b9ac4..fc446b83 100644 --- a/components/previews/content/previews_optimization_guide_decider.cc +++ b/components/previews/content/previews_optimization_guide_decider.cc
@@ -109,8 +109,7 @@ PreviewsType type) { // See if we need to bypass the lite page redirect blacklist. if (type == PreviewsType::LITE_PAGE_REDIRECT && - base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kIgnoreLitePageRedirectOptimizationBlacklist)) { + params::LitePageRedirectPreviewIgnoresOptimizationGuideFilter()) { return true; }
diff --git a/components/previews/content/previews_optimization_guide_impl.cc b/components/previews/content/previews_optimization_guide_impl.cc index adea6b9..49e7cd1 100644 --- a/components/previews/content/previews_optimization_guide_impl.cc +++ b/components/previews/content/previews_optimization_guide_impl.cc
@@ -117,11 +117,11 @@ // Check if LITE_PAGE_REDIRECT is blacklisted or not. if (type == PreviewsType::LITE_PAGE_REDIRECT) { if (current_effective_connection_type_ > - params::GetECTThresholdForPreview(type)) + params::GetECTThresholdForPreview(type)) { return false; + } - if (base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kIgnoreLitePageRedirectOptimizationBlacklist)) { + if (params::LitePageRedirectPreviewIgnoresOptimizationGuideFilter()) { return true; }
diff --git a/components/previews/core/previews_experiments.cc b/components/previews/core/previews_experiments.cc index 9835ccb8..6958134 100644 --- a/components/previews/core/previews_experiments.cc +++ b/components/previews/core/previews_experiments.cc
@@ -226,6 +226,14 @@ true); } +bool LitePageRedirectPreviewIgnoresOptimizationGuideFilter() { + return base::GetFieldTrialParamByFeatureAsBool( + features::kLitePageServerPreviews, + "ignore_optimization_guide_filtering", false) || + base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kIgnoreLitePageRedirectOptimizationBlacklist); +} + bool LitePageRedirectOnlyTriggerOnSuccessfulProbe() { return base::GetFieldTrialParamByFeatureAsBool( features::kLitePageServerPreviews, "only_trigger_after_probe_success",
diff --git a/components/previews/core/previews_experiments.h b/components/previews/core/previews_experiments.h index 44d1c09..992f25d5 100644 --- a/components/previews/core/previews_experiments.h +++ b/components/previews/core/previews_experiments.h
@@ -136,6 +136,10 @@ // Whether we should preresolve the lite page redirect server or the origin. bool LitePageRedirectPreviewShouldPresolve(); +// Whether the Optimization Guide logic should be ignored for lite page redirect +// previews. +bool LitePageRedirectPreviewIgnoresOptimizationGuideFilter(); + // Whether to only trigger a lite page preview if there has been a successful // probe to the server. This is returns true, lite page redirect previews should // only been attempted when a probe to the previews server has completed
diff --git a/components/safe_browsing/browser/safe_browsing_network_context.cc b/components/safe_browsing/browser/safe_browsing_network_context.cc index 8d3caad..0b2ac17 100644 --- a/components/safe_browsing/browser/safe_browsing_network_context.cc +++ b/components/safe_browsing/browser/safe_browsing_network_context.cc
@@ -13,7 +13,9 @@ #include "components/safe_browsing/common/safebrowsing_constants.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" +#include "content/public/browser/network_context_client_base.h" #include "content/public/browser/network_service_instance.h" +#include "mojo/public/cpp/bindings/strong_binding.h" #include "net/net_buildflags.h" #include "services/network/network_context.h" #include "services/network/public/mojom/url_loader_factory.mojom.h" @@ -41,6 +43,13 @@ if (!network_context_ || network_context_.encountered_error()) { content::GetNetworkService()->CreateNetworkContext( MakeRequest(&network_context_), CreateNetworkContextParams()); + + network::mojom::NetworkContextClientPtr client_ptr; + auto client_request = mojo::MakeRequest(&client_ptr); + mojo::MakeStrongBinding( + std::make_unique<content::NetworkContextClientBase>(), + std::move(client_request)); + network_context_->SetClient(std::move(client_ptr)); } return network_context_.get(); }
diff --git a/components/sessions/content/content_serialized_navigation_builder.cc b/components/sessions/content/content_serialized_navigation_builder.cc index 54e9345..4bd035d 100644 --- a/components/sessions/content/content_serialized_navigation_builder.cc +++ b/components/sessions/content/content_serialized_navigation_builder.cc
@@ -4,8 +4,6 @@ #include "components/sessions/content/content_serialized_navigation_builder.h" -#include <string> - #include "base/logging.h" #include "components/sessions/content/content_record_password_state.h" #include "components/sessions/content/content_serialized_navigation_driver.h" @@ -90,15 +88,19 @@ ContentSerializedNavigationBuilder::ToNavigationEntry( const SerializedNavigationEntry* navigation, content::BrowserContext* browser_context) { - // The initial values of the NavigationEntry are only temporary - they - // will get cloberred by one of the SetPageState calls below. - GURL temporary_url; - content::Referrer temporary_referrer; - base::Optional<url::Origin> temporary_initiator_origin = base::nullopt; + // TODO(lukasza): https://crbug.com/976055: |initiator_origin| should be + // persisted across session restore. + base::Optional<url::Origin> initiator_origin = base::nullopt; + network::mojom::ReferrerPolicy policy = + static_cast<network::mojom::ReferrerPolicy>(navigation->referrer_policy_); std::unique_ptr<content::NavigationEntry> entry( content::NavigationController::CreateNavigationEntry( - temporary_url, temporary_referrer, temporary_initiator_origin, + navigation->virtual_url_, + content::Referrer::SanitizeForRequest( + navigation->virtual_url_, + content::Referrer(navigation->referrer_url_, policy)), + initiator_origin, // Use a transition type of reload so that we don't incorrectly // increase the typed count. ui::PAGE_TRANSITION_RELOAD, false, @@ -107,20 +109,8 @@ nullptr /* blob_url_loader_factory */)); entry->SetTitle(navigation->title_); - if (navigation->encoded_page_state_.empty()) { - // Conjure a new PageState, based on the URL. - // - // One case where the PageState may be empty is WebUI pages - see - // ChromeSerializedNavigationDriver::Sanitize. Another case is tests for - // "foreign" session restore entries, such as - // SessionRestoreTest.RestoreForeignTab. - entry->SetPageState( - content::PageState::CreateFromURL(navigation->virtual_url_)); - } else { - // Restore PageState. - entry->SetPageState(content::PageState::CreateFromEncodedData( - navigation->encoded_page_state_)); - } + entry->SetPageState(content::PageState::CreateFromEncodedData( + navigation->encoded_page_state_)); entry->SetHasPostData(navigation->has_post_data_); entry->SetPostID(navigation->post_id_); entry->SetOriginalRequestURL(navigation->original_request_url_); @@ -128,7 +118,6 @@ entry->SetTimestamp(navigation->timestamp_); entry->SetHttpStatusCode(navigation->http_status_code_); entry->SetRedirectChain(navigation->redirect_chain_); - entry->SetVirtualURL(navigation->virtual_url_); sessions::NavigationTaskId* navigation_task_id = sessions::NavigationTaskId::Get(entry.get()); navigation_task_id->set_id(navigation->task_id());
diff --git a/components/sessions/content/content_serialized_navigation_builder_unittest.cc b/components/sessions/content/content_serialized_navigation_builder_unittest.cc index d293f061..d7832d1 100644 --- a/components/sessions/content/content_serialized_navigation_builder_unittest.cc +++ b/components/sessions/content/content_serialized_navigation_builder_unittest.cc
@@ -4,10 +4,6 @@ #include "components/sessions/content/content_serialized_navigation_builder.h" -#include <memory> -#include <string> -#include <vector> - #include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "components/sessions/content/content_record_password_state.h" @@ -68,9 +64,10 @@ navigation_entry->SetReferrer(content::Referrer( test_data::kReferrerURL, static_cast<network::mojom::ReferrerPolicy>(test_data::kReferrerPolicy))); - navigation_entry->SetURL(test_data::kURL); navigation_entry->SetVirtualURL(test_data::kVirtualURL); navigation_entry->SetTitle(test_data::kTitle); + navigation_entry->SetPageState( + content::PageState::CreateFromEncodedData(test_data::kEncodedPageState)); navigation_entry->SetTransitionType(test_data::kTransitionType); navigation_entry->SetHasPostData(test_data::kHasPostData); navigation_entry->SetPostID(test_data::kPostID); @@ -150,8 +147,7 @@ EXPECT_EQ(test_data::kReferrerPolicy, navigation.referrer_policy()); EXPECT_EQ(test_data::kVirtualURL, navigation.virtual_url()); EXPECT_EQ(test_data::kTitle, navigation.title()); - EXPECT_EQ(navigation_entry->GetPageState().ToEncodedData(), - navigation.encoded_page_state()); + EXPECT_EQ(test_data::kEncodedPageState, navigation.encoded_page_state()); EXPECT_TRUE(ui::PageTransitionTypeIncludingQualifiersIs( navigation.transition_type(), test_data::kTransitionType)); EXPECT_EQ(test_data::kHasPostData, navigation.has_post_data()); @@ -192,7 +188,7 @@ ContentSerializedNavigationBuilder::FromNavigationEntry( test_data::kIndex, navigation_entry.get(), ContentSerializedNavigationBuilder::DEFAULT); - EXPECT_EQ(navigation_entry->GetPageState().ToEncodedData(), + EXPECT_EQ(test_data::kEncodedPageState, default_navigation.encoded_page_state()); const SerializedNavigationEntry& excluded_page_state_navigation = @@ -222,10 +218,9 @@ EXPECT_EQ(test_data::kReferrerURL, new_navigation_entry->GetReferrer().url); EXPECT_EQ(test_data::kReferrerPolicy, static_cast<int>(new_navigation_entry->GetReferrer().policy)); - EXPECT_EQ(test_data::kURL, new_navigation_entry->GetURL()); EXPECT_EQ(test_data::kVirtualURL, new_navigation_entry->GetVirtualURL()); EXPECT_EQ(test_data::kTitle, new_navigation_entry->GetTitle()); - EXPECT_EQ(old_navigation_entry->GetPageState().ToEncodedData(), + EXPECT_EQ(test_data::kEncodedPageState, new_navigation_entry->GetPageState().ToEncodedData()); EXPECT_TRUE(ui::PageTransitionTypeIncludingQualifiersIs( new_navigation_entry->GetTransitionType(), ui::PAGE_TRANSITION_RELOAD));
diff --git a/components/sessions/core/serialized_navigation_entry_test_helper.cc b/components/sessions/core/serialized_navigation_entry_test_helper.cc index 8bb74fde..f5f08bc 100644 --- a/components/sessions/core/serialized_navigation_entry_test_helper.cc +++ b/components/sessions/core/serialized_navigation_entry_test_helper.cc
@@ -18,8 +18,7 @@ const int kUniqueID = 50; const GURL kReferrerURL = GURL("http://www.referrer.com"); const int kReferrerPolicy = 0; -const GURL kURL = GURL("http://www.url.com"); -const GURL kVirtualURL = GURL("http://www.virtual-url.com"); +const GURL kVirtualURL= GURL("http://www.virtual-url.com"); const base::string16 kTitle = base::ASCIIToUTF16("title"); const std::string kEncodedPageState = "page state"; const ui::PageTransition kTransitionType =
diff --git a/components/sessions/core/serialized_navigation_entry_test_helper.h b/components/sessions/core/serialized_navigation_entry_test_helper.h index 9e8af07..606b235 100644 --- a/components/sessions/core/serialized_navigation_entry_test_helper.h +++ b/components/sessions/core/serialized_navigation_entry_test_helper.h
@@ -2,13 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef COMPONENTS_SESSIONS_CORE_SERIALIZED_NAVIGATION_ENTRY_TEST_HELPER_H_ -#define COMPONENTS_SESSIONS_CORE_SERIALIZED_NAVIGATION_ENTRY_TEST_HELPER_H_ +#ifndef COMPONENTS_SESSIONS_SESSION_TYPES_TEST_HELPER_H_ +#define COMPONENTS_SESSIONS_SESSION_TYPES_TEST_HELPER_H_ #include <stdint.h> #include <string> -#include <vector> #include "base/macros.h" #include "base/strings/string16.h" @@ -29,7 +28,6 @@ extern const int kUniqueID; extern const GURL kReferrerURL; extern const int kReferrerPolicy; -extern const GURL kURL; extern const GURL kVirtualURL; extern const base::string16 kTitle; extern const std::string kEncodedPageState; @@ -65,11 +63,6 @@ const SerializedNavigationEntry& actual); // Creates a SerializedNavigationEntry using the |test_data| constants above. - // - // Note that the returned SerializedNavigationEntry will have a bogus - // PageState and therefore can only be used in limited unit tests (e.g. it - // will most likely hit DCHECKs/NOTREACHEDs when passed to the //content - // layer). static SerializedNavigationEntry CreateNavigationForTest(); static void SetReferrerPolicy(int policy, @@ -104,6 +97,6 @@ DISALLOW_IMPLICIT_CONSTRUCTORS(SerializedNavigationEntryTestHelper); }; -} // namespace sessions +} // sessions -#endif // COMPONENTS_SESSIONS_CORE_SERIALIZED_NAVIGATION_ENTRY_TEST_HELPER_H_ +#endif // COMPONENTS_SESSIONS_SESSION_TYPES_TEST_HELPER_H_
diff --git a/components/variations/service/variations_field_trial_creator.cc b/components/variations/service/variations_field_trial_creator.cc index 3ce23fd..d3e7a42 100644 --- a/components/variations/service/variations_field_trial_creator.cc +++ b/components/variations/service/variations_field_trial_creator.cc
@@ -388,9 +388,11 @@ board.resize(index); return base::ToUpperASCII(board); +#elif defined(OS_ANDROID) + return base::SysInfo::HardwareModelName(); #else return std::string(); -#endif // OS_CHROMEOS +#endif } bool VariationsFieldTrialCreator::LoadSeed(VariationsSeed* seed,
diff --git a/components/variations/service/variations_field_trial_creator.h b/components/variations/service/variations_field_trial_creator.h index 8b99b3a..f2ea136 100644 --- a/components/variations/service/variations_field_trial_creator.h +++ b/components/variations/service/variations_field_trial_creator.h
@@ -133,8 +133,8 @@ const std::string& application_locale() const { return application_locale_; } // Returns the short hardware class value used to evaluate variations hardware - // class filters. Only implemented on CrOS - returns empty string on other - // platforms. + // class filters. Only implemented on CrOS and Android - returns empty string + // on other platforms. static std::string GetShortHardwareClass(); private:
diff --git a/components/variations/service/variations_field_trial_creator_unittest.cc b/components/variations/service/variations_field_trial_creator_unittest.cc index 590c7680..db8e2baa 100644 --- a/components/variations/service/variations_field_trial_creator_unittest.cc +++ b/components/variations/service/variations_field_trial_creator_unittest.cc
@@ -521,6 +521,24 @@ EXPECT_EQ(kTestSeedExperimentName, base::FieldTrialList::FindFullName(kTestSeedStudyName)); } + +// Tests that the hardware class is set on Android. +TEST_F(FieldTrialCreatorTest, ClientFilterableState_HardwareClass) { + testing::NiceMock<MockSafeSeedManager> safe_seed_manager(&prefs_); + ON_CALL(safe_seed_manager, ShouldRunInSafeMode()) + .WillByDefault(Return(false)); + + TestVariationsServiceClient variations_service_client; + TestVariationsFieldTrialCreator field_trial_creator( + &prefs_, &variations_service_client, &safe_seed_manager); + + const base::Version& current_version = version_info::GetVersion(); + EXPECT_TRUE(current_version.IsValid()); + + std::unique_ptr<ClientFilterableState> client_filterable_state = + field_trial_creator.GetClientFilterableStateForVersion(current_version); + EXPECT_NE(client_filterable_state->hardware_class, std::string()); +} #endif // OS_ANDROID } // namespace variations
diff --git a/components/viz/service/display/display.h b/components/viz/service/display/display.h index 72e2e1b..1e01b18 100644 --- a/components/viz/service/display/display.h +++ b/components/viz/service/display/display.h
@@ -90,9 +90,16 @@ base::TimeDelta::FromMilliseconds(50); static constexpr uint32_t kDrawToSwapUsBuckets = 50; + // TODO(cblume, crbug.com/900973): |enable_shared_images| is a temporary + // solution that unblocks us until SharedImages are threadsafe in WebView. +#if defined(ANDROID) + static constexpr bool kEnableSharedImages = false; +#else + static constexpr bool kEnableSharedImages = true; +#endif void Initialize(DisplayClient* client, SurfaceManager* surface_manager, - bool enable_shared_images); + bool enable_shared_images = kEnableSharedImages); void AddObserver(DisplayObserver* observer); void RemoveObserver(DisplayObserver* observer);
diff --git a/components/viz/service/display/display_unittest.cc b/components/viz/service/display/display_unittest.cc index 3d3f0a5..e2f3b6f 100644 --- a/components/viz/service/display/display_unittest.cc +++ b/components/viz/service/display/display_unittest.cc
@@ -236,7 +236,7 @@ gfx::ColorSpace color_space_2 = gfx::ColorSpace::CreateSCRGBLinear(); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); display_->SetColorSpace(color_space_1); EXPECT_FALSE(scheduler_->damaged); @@ -528,7 +528,7 @@ SetUpSoftwareDisplay(RendererSettings()); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); id_allocator_.GenerateId(); LocalSurfaceId local_surface_id( @@ -610,7 +610,7 @@ SetUpGpuDisplay(settings); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); display_->SetLocalSurfaceId(local_surface_id1, 1.f); @@ -687,7 +687,7 @@ SetUpGpuDisplay(RendererSettings()); CountLossDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); // Verify DidLoseOutputSurface callback is hooked up correctly. EXPECT_EQ(0, client.loss_count()); @@ -710,7 +710,7 @@ // Set up first display. SetUpSoftwareDisplay(settings); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); display_->SetLocalSurfaceId(local_surface_id, 1.f); // Set up second frame sink + display. @@ -728,7 +728,7 @@ manager_.RegisterBeginFrameSource(begin_frame_source2.get(), kAnotherFrameSinkId); StubDisplayClient client2; - display2->Initialize(&client2, manager_.surface_manager(), true); + display2->Initialize(&client2, manager_.surface_manager()); display2->SetLocalSurfaceId(local_surface_id, 1.f); display_->Resize(gfx::Size(100, 100)); @@ -762,7 +762,7 @@ SetUpGpuDisplay(RendererSettings()); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); CompositorFrame frame = MakeDefaultCompositorFrame(); gfx::Rect rect1(0, 0, 100, 100); @@ -983,7 +983,7 @@ SetUpGpuDisplay(settings); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); CompositorFrame frame = MakeDefaultCompositorFrame(); gfx::Rect rect1(0, 0, 100, 100); @@ -1114,7 +1114,7 @@ SetUpGpuDisplay(RendererSettings()); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); CompositorFrame frame = MakeDefaultCompositorFrame(); gfx::Rect more_then_minimum_size( @@ -1239,7 +1239,7 @@ SetUpGpuDisplay(RendererSettings()); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); CompositorFrame frame = MakeDefaultCompositorFrame(); gfx::Rect rect1(0, 0, 50, 50); @@ -1301,7 +1301,7 @@ SetUpGpuDisplay(settings); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); // Rect 2, 3, 4 are contained in rect 1 only after applying the half scale // matrix. They are repetition of CompositorFrameWithOverlapDrawQuad. @@ -1572,7 +1572,7 @@ SetUpGpuDisplay(RendererSettings()); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); CompositorFrame frame = MakeDefaultCompositorFrame(); gfx::Rect rect(0, 0, 100, 100); @@ -1684,7 +1684,7 @@ SetUpGpuDisplay(RendererSettings()); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); CompositorFrame frame = MakeDefaultCompositorFrame(); gfx::Rect rect(0, 0, 100, 100); @@ -1808,7 +1808,7 @@ SetUpGpuDisplay(settings); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); // rect 2 is inside rect 1 initially. CompositorFrame frame = MakeDefaultCompositorFrame(); @@ -1937,7 +1937,7 @@ SetUpGpuDisplay(settings); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); // rect 2 is inside rect 1 initially. CompositorFrame frame = MakeDefaultCompositorFrame(); @@ -2013,7 +2013,7 @@ SetUpGpuDisplay(settings); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); CompositorFrame frame = MakeDefaultCompositorFrame(); gfx::Rect rect1(0, 0, 100, 100); @@ -2080,7 +2080,7 @@ SetUpGpuDisplay(settings); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); CompositorFrame frame = MakeDefaultCompositorFrame(); gfx::Rect rect1(0, 0, 100, 100); @@ -2148,7 +2148,7 @@ SetUpGpuDisplay(settings); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); CompositorFrame frame = MakeDefaultCompositorFrame(); gfx::Rect rect1(0, 0, 100, 100); @@ -2203,7 +2203,7 @@ SetUpGpuDisplay(settings); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); // rect 2 and 3 are outside rect 1 initially. CompositorFrame frame = MakeDefaultCompositorFrame(); @@ -2324,7 +2324,7 @@ SetUpGpuDisplay(settings); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); // rect 3 is inside of combined rect of rect 1 and rect 2. CompositorFrame frame = MakeDefaultCompositorFrame(); @@ -2452,7 +2452,7 @@ SetUpGpuDisplay(settings); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); // rect 3 is inside of combined rect of rect 1 and rect 2. CompositorFrame frame = MakeDefaultCompositorFrame(); @@ -2526,7 +2526,7 @@ SetUpGpuDisplay(RendererSettings()); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); // rect 3 is inside of combined rect of rect 1 and rect 2. CompositorFrame frame = MakeDefaultCompositorFrame(); @@ -2597,7 +2597,7 @@ SetUpGpuDisplay(settings); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); CompositorFrame frame = MakeDefaultCompositorFrame(); gfx::Rect rect1(0, 0, 100, 100); @@ -2714,7 +2714,7 @@ SetUpGpuDisplay(settings); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); CompositorFrame frame = MakeDefaultCompositorFrame(); gfx::Rect rect1(0, 0, 100, 100); @@ -2762,7 +2762,7 @@ SetUpGpuDisplay(settings); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); CompositorFrame frame = MakeDefaultCompositorFrame(); gfx::Rect rect1(0, 0, 100, 100); @@ -2942,7 +2942,7 @@ SetUpGpuDisplay(settings); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); CompositorFrame frame = MakeDefaultCompositorFrame(); gfx::Rect rect1(0, 0, 100, 100); @@ -3120,7 +3120,7 @@ SetUpGpuDisplay(settings); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); CompositorFrame frame = MakeDefaultCompositorFrame(); gfx::Rect rect1(0, 0, 100, 100); gfx::Rect rect2(10, 10, 50, 50); @@ -3223,7 +3223,7 @@ SetUpGpuDisplay(RendererSettings()); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); CompositorFrame frame = MakeDefaultCompositorFrame(); // The size of this DrawQuad will be 237790x237790 > 2^32 (uint32_t.max()) @@ -3269,7 +3269,7 @@ // Set up first display. SetUpSoftwareDisplay(settings); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); display_->SetLocalSurfaceId(local_surface_id, 1.f); // Create frame sink for a sub surface. @@ -3380,7 +3380,7 @@ SetUpGpuDisplay(RendererSettings()); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); display_->SetLocalSurfaceId( id_allocator_.GetCurrentLocalSurfaceIdAllocation().local_surface_id(), 1.f); @@ -3457,7 +3457,7 @@ SetUpGpuDisplay(RendererSettings()); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); display_->SetLocalSurfaceId( id_allocator_.GetCurrentLocalSurfaceIdAllocation().local_surface_id(), 1.f); @@ -3534,7 +3534,7 @@ SetUpGpuDisplay(RendererSettings()); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); display_->SetLocalSurfaceId( id_allocator_.GetCurrentLocalSurfaceIdAllocation().local_surface_id(), 1.f); @@ -3624,7 +3624,7 @@ // Set up first display. SetUpSoftwareDisplay(settings); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); display_->SetLocalSurfaceId(local_surface_id, 1.f); display_->Resize(gfx::Size(25, 25)); @@ -3698,7 +3698,7 @@ SetUpGpuDisplay(RendererSettings()); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); CompositorFrame frame = MakeDefaultCompositorFrame(); @@ -3755,7 +3755,7 @@ SetUpGpuDisplay(RendererSettings()); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); // The quad with rounded corner completely covers the quad below it. CompositorFrame frame = MakeDefaultCompositorFrame(); @@ -3810,7 +3810,7 @@ SetUpGpuDisplay(RendererSettings()); StubDisplayClient client; - display_->Initialize(&client, manager_.surface_manager(), true); + display_->Initialize(&client, manager_.surface_manager()); // The quad with rounded corner completely covers the quad below it. CompositorFrame frame = MakeDefaultCompositorFrame();
diff --git a/components/viz/service/display/renderer_perftest.cc b/components/viz/service/display/renderer_perftest.cc index 8757b72..f6ad154d 100644 --- a/components/viz/service/display/renderer_perftest.cc +++ b/components/viz/service/display/renderer_perftest.cc
@@ -266,8 +266,7 @@ std::move(output_surface), /*display_scheduler=*/nullptr, base::ThreadTaskRunnerHandle::Get()); display_->SetVisible(true); - display_->Initialize(&client_, manager_.surface_manager(), - true /* enable_shared_images */); + display_->Initialize(&client_, manager_.surface_manager()); display_->Resize(kSurfaceSize); id_allocator_.GenerateId();
diff --git a/components/viz/service/frame_sinks/direct_layer_tree_frame_sink.cc b/components/viz/service/frame_sinks/direct_layer_tree_frame_sink.cc index df3798f..6a1979c 100644 --- a/components/viz/service/frame_sinks/direct_layer_tree_frame_sink.cc +++ b/components/viz/service/frame_sinks/direct_layer_tree_frame_sink.cc
@@ -112,8 +112,7 @@ // Avoid initializing GL context here, as this should be sharing the // Display's context. - display_->Initialize(this, frame_sink_manager_->surface_manager(), - true /* enable_shared_images */); + display_->Initialize(this, frame_sink_manager_->surface_manager()); support_->SetUpHitTest(display_);
diff --git a/components/viz/service/frame_sinks/root_compositor_frame_sink_impl.cc b/components/viz/service/frame_sinks/root_compositor_frame_sink_impl.cc index aef0e72..7af0101 100644 --- a/components/viz/service/frame_sinks/root_compositor_frame_sink_impl.cc +++ b/components/viz/service/frame_sinks/root_compositor_frame_sink_impl.cc
@@ -318,8 +318,7 @@ DCHECK(begin_frame_source()); frame_sink_manager->RegisterBeginFrameSource(begin_frame_source(), support_->frame_sink_id()); - display_->Initialize(this, support_->frame_sink_manager()->surface_manager(), - true /* enable_shared_images */); + display_->Initialize(this, support_->frame_sink_manager()->surface_manager()); support_->SetUpHitTest(display_.get()); }
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index 5adeccac..7c8a677 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -1265,6 +1265,8 @@ "net/network_quality_observer_impl.h", "net/quota_policy_cookie_store.cc", "net/quota_policy_cookie_store.h", + "network_context_client_base_impl.cc", + "network_context_client_base_impl.h", "network_service_client.cc", "network_service_client.h", "network_service_instance_impl.cc",
diff --git a/content/browser/frame_host/navigation_controller_impl_unittest.cc b/content/browser/frame_host/navigation_controller_impl_unittest.cc index 19b3c788..648b1cda 100644 --- a/content/browser/frame_host/navigation_controller_impl_unittest.cc +++ b/content/browser/frame_host/navigation_controller_impl_unittest.cc
@@ -2450,6 +2450,7 @@ std::string(), browser_context(), nullptr /* blob_url_loader_factory */); entry->SetTitle(base::ASCIIToUTF16("Title")); + entry->SetPageState(PageState::CreateFromEncodedData("state")); const base::Time timestamp = base::Time::Now(); entry->SetTimestamp(timestamp); entries.push_back(std::move(entry)); @@ -2518,6 +2519,7 @@ std::string(), browser_context(), nullptr /* blob_url_loader_factory */); new_entry->SetTitle(base::ASCIIToUTF16("Title")); + new_entry->SetPageState(PageState::CreateFromEncodedData("state")); entries.push_back(std::move(new_entry)); std::unique_ptr<WebContents> our_contents = WebContents::Create(WebContents::CreateParams(browser_context()));
diff --git a/content/browser/frame_host/navigation_entry_impl.cc b/content/browser/frame_host/navigation_entry_impl.cc index b4ade6c94..7575f08 100644 --- a/content/browser/frame_host/navigation_entry_impl.cc +++ b/content/browser/frame_host/navigation_entry_impl.cc
@@ -95,12 +95,6 @@ } } -base::Optional<base::string16> UrlToOptionalString16(const GURL& url) { - if (!url.is_valid()) - return base::nullopt; - return base::UTF8ToUTF16(url.spec()); -} - void RecursivelyGenerateFrameState( NavigationEntryImpl::TreeNode* node, ExplodedFrameState* state, @@ -118,35 +112,6 @@ // Copy the FrameNavigationEntry's frame state into the destination state. *state = frame_state; - // Some data is stored *both* in 1) PageState/ExplodedFrameState and 2) - // FrameNavigationEntry. We want to treat FrameNavigationEntry as the - // authoritative source of the data, so we clobber the ExplodedFrameState with - // the data taken from FrameNavigationEntry. - // - // The following ExplodedFrameState fields do not have an equivalent - // FrameNavigationEntry field: - // - target - // - state_object - // - document_state - // - scroll_restoration_type - // - did_save_scroll_or_scale_state - // - visual_viewport_scroll_offset - // - scroll_offset - // - page_scale_factor - // - http_body (FrameNavigationEntry::GetPostData extracts the body from - // the ExplodedFrameState) - // - scroll_anchor_selector - // - scroll_anchor_offset - // - scroll_anchor_simhash - state->url_string = UrlToOptionalString16(node->frame_entry->url()); - state->referrer = UrlToOptionalString16(node->frame_entry->referrer().url); - state->referrer_policy = node->frame_entry->referrer().policy; - state->item_sequence_number = node->frame_entry->item_sequence_number(); - state->document_sequence_number = - node->frame_entry->document_sequence_number(); - // TODO(lukasza): https://crbug.com/976055: Persist |initiator_origin| in - // the ExplodedFrameState. - // Copy the frame's files into the PageState's |referenced_files|. referenced_files->reserve(referenced_files->size() + exploded_page_state.referenced_files.size()); @@ -421,10 +386,12 @@ if (!frame_tree_->children.empty()) frame_tree_->children.clear(); - // If the PageState can't be parsed, just store it on the main frame's - // FrameNavigationEntry without recursively creating subframe entries. + // If the PageState can't be parsed or has no children, just store it on the + // main frame's FrameNavigationEntry without recursively creating subframe + // entries. ExplodedPageState exploded_state; - if (!DecodePageState(state.ToEncodedData(), &exploded_state)) { + if (!DecodePageState(state.ToEncodedData(), &exploded_state) || + exploded_state.top.children.size() == 0U) { frame_tree_->frame_entry->SetPageState(state); return; } @@ -434,8 +401,14 @@ } PageState NavigationEntryImpl::GetPageState() { - // Each FrameNavigationEntry has a frame-specific PageState. We combine these - // into an ExplodedPageState tree and generate a full PageState from it. + // Just return the main frame's state if there are no subframe + // FrameNavigationEntries. + if (frame_tree_->children.size() == 0U) + return frame_tree_->frame_entry->page_state(); + + // When we're using subframe entries, each FrameNavigationEntry has a + // frame-specific PageState. We combine these into an ExplodedPageState tree + // and generate a full PageState from it. ExplodedPageState exploded_state; RecursivelyGenerateFrameState(frame_tree_.get(), &exploded_state.top, &exploded_state.referenced_files);
diff --git a/content/browser/frame_host/navigation_entry_impl_unittest.cc b/content/browser/frame_host/navigation_entry_impl_unittest.cc index 45cb8cd6..9bbcf168 100644 --- a/content/browser/frame_host/navigation_entry_impl_unittest.cc +++ b/content/browser/frame_host/navigation_entry_impl_unittest.cc
@@ -14,7 +14,6 @@ #include "base/time/time.h" #include "build/build_config.h" #include "content/browser/site_instance_impl.h" -#include "content/common/page_state_serialization.h" #include "content/public/browser/ssl_status.h" #include "content/public/test/browser_task_environment.h" #include "content/public/test/test_browser_context.h" @@ -50,13 +49,6 @@ DISALLOW_COPY_AND_ASSIGN(TestSSLStatusData); }; -PageState CreateTestPageState() { - ExplodedPageState exploded_state; - std::string encoded_data; - EncodePageState(exploded_state, &encoded_data); - return PageState::CreateFromEncodedData(encoded_data); -} - } // namespace class NavigationEntryTest : public testing::Test { @@ -239,6 +231,12 @@ entry2_->SetTitle(ASCIIToUTF16("title2")); EXPECT_EQ(ASCIIToUTF16("title2"), entry2_->GetTitle()); + // State + EXPECT_FALSE(entry1_->GetPageState().IsValid()); + EXPECT_FALSE(entry2_->GetPageState().IsValid()); + entry2_->SetPageState(PageState::CreateFromEncodedData("state")); + EXPECT_EQ("state", entry2_->GetPageState().ToEncodedData()); + // Transition type EXPECT_TRUE(ui::PageTransitionTypeIncludingQualifiersIs( entry1_->GetTransitionType(), ui::PAGE_TRANSITION_LINK)); @@ -294,21 +292,10 @@ // Initiator origin. EXPECT_FALSE( entry1_->root_node()->frame_entry->initiator_origin().has_value()); - ASSERT_TRUE( + EXPECT_TRUE( entry2_->root_node()->frame_entry->initiator_origin().has_value()); EXPECT_EQ(url::Origin::Create(GURL("https://initiator.example.com")), entry2_->root_node()->frame_entry->initiator_origin().value()); - - // State. - // - // Note that calling SetPageState may also set some other FNE members - // (referrer, initiator, etc.). This is why it is important to test - // SetPageState/GetPageState last. - PageState test_page_state = CreateTestPageState(); - entry2_->SetPageState(test_page_state); - // TODO(lukasza): https://crbug.com/976055: Once |initiator_origin| is - // persisted across session restore, the test here should verify that - // SetPageState round-trips via GetPageState. } // Test basic Clone behavior.
diff --git a/content/browser/media/session/media_session_impl.cc b/content/browser/media/session/media_session_impl.cc index b336a85..db2159b 100644 --- a/content/browser/media/session/media_session_impl.cc +++ b/content/browser/media/session/media_session_impl.cc
@@ -180,6 +180,12 @@ } // static +const base::UnguessableToken& MediaSession::GetSourceId( + BrowserContext* browser_context) { + return MediaSessionData::GetOrCreate(browser_context)->source_id(); +} + +// static MediaSessionImpl* MediaSessionImpl::Get(WebContents* web_contents) { MediaSessionImpl* session = FromWebContents(web_contents); if (!session) {
diff --git a/content/browser/native_file_system/file_system_chooser.cc b/content/browser/native_file_system/file_system_chooser.cc index 98687a1..bee4810 100644 --- a/content/browser/native_file_system/file_system_chooser.cc +++ b/content/browser/native_file_system/file_system_chooser.cc
@@ -7,6 +7,7 @@ #include "base/bind.h" #include "base/files/file_path.h" #include "base/files/file_util.h" +#include "base/metrics/histogram_functions.h" #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" #include "build/build_config.h" @@ -23,6 +24,28 @@ namespace { +std::string TypeToString(blink::mojom::ChooseFileSystemEntryType type) { + switch (type) { + case blink::mojom::ChooseFileSystemEntryType::kOpenFile: + return "OpenFile"; + case blink::mojom::ChooseFileSystemEntryType::kOpenMultipleFiles: + return "OpenMultipleFiles"; + case blink::mojom::ChooseFileSystemEntryType::kSaveFile: + return "SaveFile"; + case blink::mojom::ChooseFileSystemEntryType::kOpenDirectory: + return "OpenDirectory"; + } + NOTREACHED(); + return nullptr; +} + +void RecordFileSelectionResult(blink::mojom::ChooseFileSystemEntryType type, + int count) { + base::UmaHistogramCounts1000("NativeFileSystemAPI.FileChooserResult", count); + base::UmaHistogramCounts1000( + "NativeFileSystemAPI.FileChooserResult." + TypeToString(type), count); +} + bool GetFileTypesFromAcceptsOption( const blink::mojom::ChooseFileSystemEntryAcceptsOption& option, std::vector<base::FilePath::StringType>* extensions, @@ -156,6 +179,8 @@ auto* isolated_context = storage::IsolatedContext::GetInstance(); DCHECK(isolated_context); + RecordFileSelectionResult(type_, files.size()); + if (type_ == blink::mojom::ChooseFileSystemEntryType::kSaveFile) { // Create files if they don't yet exist, and truncate files if they do // exist. @@ -201,6 +226,7 @@ } void FileSystemChooser::FileSelectionCanceled(void* params) { + RecordFileSelectionResult(type_, 0); callback_runner_->PostTask( FROM_HERE, base::BindOnce(
diff --git a/content/browser/native_file_system/native_file_system_manager_impl.cc b/content/browser/native_file_system/native_file_system_manager_impl.cc index 22d66e7..8aa23c1 100644 --- a/content/browser/native_file_system/native_file_system_manager_impl.cc +++ b/content/browser/native_file_system/native_file_system_manager_impl.cc
@@ -6,6 +6,7 @@ #include "base/files/file_path.h" #include "base/logging.h" +#include "base/metrics/histogram_functions.h" #include "base/task/post_task.h" #include "content/browser/native_file_system/file_system_chooser.h" #include "content/browser/native_file_system/fixed_native_file_system_permission_grant.h" @@ -438,6 +439,9 @@ ChooseEntriesCallback callback, std::vector<base::FilePath> entries, SensitiveDirectoryResult result) { + base::UmaHistogramEnumeration( + "NativeFileSystemAPI.SensitiveDirectoryAccessResult", result); + if (result == SensitiveDirectoryResult::kAbort) { std::move(callback).Run( native_file_system_error::FromStatus( @@ -496,6 +500,9 @@ const base::FilePath& path, ChooseEntriesCallback callback, NativeFileSystemPermissionContext::PermissionStatus permission) { + base::UmaHistogramEnumeration( + "NativeFileSystemAPI.ConfirmReadDirectoryResult", permission); + std::vector<blink::mojom::NativeFileSystemEntryPtr> result_entries; if (permission != PermissionStatus::GRANTED) { std::move(callback).Run(native_file_system_error::FromStatus(
diff --git a/content/browser/network_context_client_base_impl.cc b/content/browser/network_context_client_base_impl.cc new file mode 100644 index 0000000..8d4c408c --- /dev/null +++ b/content/browser/network_context_client_base_impl.cc
@@ -0,0 +1,179 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/browser/network_context_client_base_impl.h" + +#include "base/bind.h" +#include "base/task/post_task.h" +#include "base/task/task_traits.h" +#include "base/task_runner.h" +#include "build/build_config.h" +#include "content/browser/child_process_security_policy_impl.h" +#include "content/public/browser/network_context_client_base.h" + +#if defined(OS_ANDROID) +#include "base/android/content_uri_utils.h" +#endif + +namespace content { + +namespace { + +void HandleFileUploadRequest( + uint32_t process_id, + bool async, + const std::vector<base::FilePath>& file_paths, + network::mojom::NetworkContextClient::OnFileUploadRequestedCallback + callback, + scoped_refptr<base::TaskRunner> task_runner) { + std::vector<base::File> files; + uint32_t file_flags = base::File::FLAG_OPEN | base::File::FLAG_READ | + (async ? base::File::FLAG_ASYNC : 0); + ChildProcessSecurityPolicy* cpsp = ChildProcessSecurityPolicy::GetInstance(); + for (const auto& file_path : file_paths) { + if (process_id != network::mojom::kBrowserProcessId && + !cpsp->CanReadFile(process_id, file_path)) { + task_runner->PostTask( + FROM_HERE, base::BindOnce(std::move(callback), net::ERR_ACCESS_DENIED, + std::vector<base::File>())); + return; + } +#if defined(OS_ANDROID) + if (file_path.IsContentUri()) { + files.push_back(base::OpenContentUriForRead(file_path)); + } else { + files.emplace_back(file_path, file_flags); + } +#else + files.emplace_back(file_path, file_flags); +#endif + if (!files.back().IsValid()) { + task_runner->PostTask( + FROM_HERE, + base::BindOnce(std::move(callback), + net::FileErrorToNetError(files.back().error_details()), + std::vector<base::File>())); + return; + } + } + task_runner->PostTask(FROM_HERE, base::BindOnce(std::move(callback), net::OK, + std::move(files))); +} + +} // namespace + +void NetworkContextOnFileUploadRequested( + uint32_t process_id, + bool async, + const std::vector<base::FilePath>& file_paths, + network::mojom::NetworkContextClient::OnFileUploadRequestedCallback + callback) { + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + base::BindOnce(&HandleFileUploadRequest, process_id, async, file_paths, + std::move(callback), + base::SequencedTaskRunnerHandle::Get())); +} + +NetworkContextClientBase::NetworkContextClientBase() = default; +NetworkContextClientBase::~NetworkContextClientBase() = default; + +void NetworkContextClientBase::OnAuthRequired( + const base::Optional<base::UnguessableToken>& window_id, + uint32_t process_id, + uint32_t routing_id, + uint32_t request_id, + const GURL& url, + bool first_auth_attempt, + const net::AuthChallengeInfo& auth_info, + network::mojom::URLResponseHeadPtr head, + network::mojom::AuthChallengeResponderPtr auth_challenge_responder) { + std::move(auth_challenge_responder)->OnAuthCredentials(base::nullopt); +} + +void NetworkContextClientBase::OnCertificateRequested( + const base::Optional<base::UnguessableToken>& window_id, + uint32_t process_id, + uint32_t routing_id, + uint32_t request_id, + const scoped_refptr<net::SSLCertRequestInfo>& cert_info, + network::mojom::ClientCertificateResponderPtr cert_responder) { + cert_responder->CancelRequest(); +} + +void NetworkContextClientBase::OnSSLCertificateError( + uint32_t process_id, + uint32_t routing_id, + const GURL& url, + int net_error, + const net::SSLInfo& ssl_info, + bool fatal, + OnSSLCertificateErrorCallback response) { + std::move(response).Run(net::ERR_ABORTED); +} + +void NetworkContextClientBase::OnFileUploadRequested( + uint32_t process_id, + bool async, + const std::vector<base::FilePath>& file_paths, + OnFileUploadRequestedCallback callback) { + NetworkContextOnFileUploadRequested(process_id, async, file_paths, + std::move(callback)); +} + +void NetworkContextClientBase::OnCanSendReportingReports( + const std::vector<url::Origin>& origins, + OnCanSendReportingReportsCallback callback) { + std::move(callback).Run(std::vector<url::Origin>()); +} + +void NetworkContextClientBase::OnCanSendDomainReliabilityUpload( + const GURL& origin, + OnCanSendDomainReliabilityUploadCallback callback) { + std::move(callback).Run(false); +} + +void NetworkContextClientBase::OnClearSiteData( + uint32_t process_id, + int32_t routing_id, + const GURL& url, + const std::string& header_value, + int load_flags, + OnClearSiteDataCallback callback) { + std::move(callback).Run(); +} + +void NetworkContextClientBase::OnCookiesChanged( + bool is_service_worker, + int32_t process_id, + int32_t routing_id, + const GURL& url, + const GURL& site_for_cookies, + const std::vector<net::CookieWithStatus>& cookie_list) {} + +void NetworkContextClientBase::OnCookiesRead( + bool is_service_worker, + int32_t process_id, + int32_t routing_id, + const GURL& url, + const GURL& site_for_cookies, + const std::vector<net::CookieWithStatus>& cookie_list) {} + +#if defined(OS_ANDROID) +void NetworkContextClientBase::OnGenerateHttpNegotiateAuthToken( + const std::string& server_auth_token, + bool can_delegate, + const std::string& auth_negotiate_android_account_type, + const std::string& spn, + OnGenerateHttpNegotiateAuthTokenCallback callback) { + std::move(callback).Run(net::ERR_FAILED, server_auth_token); +} +#endif + +#if defined(OS_CHROMEOS) +void NetworkContextClientBase::OnTrustAnchorUsed() {} +#endif + +} // namespace content
diff --git a/content/browser/network_context_client_base_impl.h b/content/browser/network_context_client_base_impl.h new file mode 100644 index 0000000..bbdde0af --- /dev/null +++ b/content/browser/network_context_client_base_impl.h
@@ -0,0 +1,23 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_NETWORK_CONTEXT_CLIENT_BASE_IMPL_H_ +#define CONTENT_BROWSER_NETWORK_CONTEXT_CLIENT_BASE_IMPL_H_ + +#include "services/network/public/mojom/network_context.mojom.h" + +namespace content { + +// Helper method that NetworkContext::OnFileUploadRequested need to use for +// their implementation. +void NetworkContextOnFileUploadRequested( + uint32_t process_id, + bool async, + const std::vector<base::FilePath>& file_paths, + network::mojom::NetworkContextClient::OnFileUploadRequestedCallback + callback); + +} // namespace content + +#endif // CONTENT_BROWSER_NETWORK_CONTEXT_CLIENT_BASE_IMPL_H_
diff --git a/content/browser/network_service_client_unittest.cc b/content/browser/network_context_client_base_impl_unittest.cc similarity index 88% rename from content/browser/network_service_client_unittest.cc rename to content/browser/network_context_client_base_impl_unittest.cc index 23091f9..6f18a31 100644 --- a/content/browser/network_service_client_unittest.cc +++ b/content/browser/network_context_client_base_impl_unittest.cc
@@ -1,8 +1,8 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. +// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "content/browser/network_service_client.h" +#include "content/public/browser/network_context_client_base.h" #include "base/bind.h" #include "base/files/file.h" @@ -32,7 +32,7 @@ this->opened_files = std::move(opened_files); } - network::mojom::NetworkServiceClient::OnFileUploadRequestedCallback callback; + network::mojom::NetworkContextClient::OnFileUploadRequestedCallback callback; int error_code; std::vector<base::File> opened_files; }; @@ -65,9 +65,9 @@ } // namespace -class NetworkServiceClientTest : public testing::Test { +class NetworkContextClientBaseTest : public testing::Test { public: - NetworkServiceClientTest() : client_(mojo::MakeRequest(&client_ptr_)) {} + NetworkContextClientBaseTest() {} void SetUp() override { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); @@ -82,12 +82,11 @@ protected: BrowserTaskEnvironment task_environment_; TestBrowserContext browser_context_; - network::mojom::NetworkServiceClientPtr client_ptr_; - NetworkServiceClient client_; + NetworkContextClientBase client_; base::ScopedTempDir temp_dir_; }; -TEST_F(NetworkServiceClientTest, UploadNoFiles) { +TEST_F(NetworkContextClientBaseTest, UploadNoFiles) { UploadResponse response; client_.OnFileUploadRequested(kRendererProcessId, true, {}, std::move(response.callback)); @@ -96,7 +95,7 @@ EXPECT_EQ(0U, response.opened_files.size()); } -TEST_F(NetworkServiceClientTest, UploadOneValidAsyncFile) { +TEST_F(NetworkContextClientBaseTest, UploadOneValidAsyncFile) { base::FilePath path = temp_dir_.GetPath().AppendASCII("filename"); CreateFile(path, kFileContent1); GrantAccess(path, kRendererProcessId); @@ -110,7 +109,7 @@ EXPECT_TRUE(response.opened_files[0].async()); } -TEST_F(NetworkServiceClientTest, UploadOneValidFile) { +TEST_F(NetworkContextClientBaseTest, UploadOneValidFile) { base::FilePath path = temp_dir_.GetPath().AppendASCII("filename"); CreateFile(path, kFileContent1); GrantAccess(path, kRendererProcessId); @@ -126,7 +125,7 @@ } #if defined(OS_ANDROID) -TEST_F(NetworkServiceClientTest, UploadOneValidFileWithContentUri) { +TEST_F(NetworkContextClientBaseTest, UploadOneValidFileWithContentUri) { base::FilePath image_path; EXPECT_TRUE(base::PathService::Get(base::DIR_SOURCE_ROOT, &image_path)); image_path = image_path.AppendASCII("content") @@ -152,7 +151,7 @@ } #endif -TEST_F(NetworkServiceClientTest, UploadTwoValidFiles) { +TEST_F(NetworkContextClientBaseTest, UploadTwoValidFiles) { base::FilePath path1 = temp_dir_.GetPath().AppendASCII("filename1"); base::FilePath path2 = temp_dir_.GetPath().AppendASCII("filename2"); CreateFile(path1, kFileContent1); @@ -170,7 +169,7 @@ ValidateFileContents(response.opened_files[1], kFileContent2); } -TEST_F(NetworkServiceClientTest, UploadOneUnauthorizedFile) { +TEST_F(NetworkContextClientBaseTest, UploadOneUnauthorizedFile) { base::FilePath path = temp_dir_.GetPath().AppendASCII("filename"); CreateFile(path, kFileContent1); @@ -182,7 +181,7 @@ EXPECT_EQ(0U, response.opened_files.size()); } -TEST_F(NetworkServiceClientTest, UploadOneValidFileAndOneUnauthorized) { +TEST_F(NetworkContextClientBaseTest, UploadOneValidFileAndOneUnauthorized) { base::FilePath path1 = temp_dir_.GetPath().AppendASCII("filename1"); base::FilePath path2 = temp_dir_.GetPath().AppendASCII("filename2"); CreateFile(path1, kFileContent1); @@ -197,7 +196,7 @@ EXPECT_EQ(0U, response.opened_files.size()); } -TEST_F(NetworkServiceClientTest, UploadOneValidFileAndOneNotFound) { +TEST_F(NetworkContextClientBaseTest, UploadOneValidFileAndOneNotFound) { base::FilePath path1 = temp_dir_.GetPath().AppendASCII("filename1"); base::FilePath path2 = temp_dir_.GetPath().AppendASCII("filename2"); CreateFile(path1, kFileContent1); @@ -212,7 +211,7 @@ EXPECT_EQ(0U, response.opened_files.size()); } -TEST_F(NetworkServiceClientTest, UploadFromBrowserProcess) { +TEST_F(NetworkContextClientBaseTest, UploadFromBrowserProcess) { base::FilePath path = temp_dir_.GetPath().AppendASCII("filename"); CreateFile(path, kFileContent1); // No grant necessary for browser process. @@ -226,4 +225,4 @@ ValidateFileContents(response.opened_files[0], kFileContent1); } -} // namespace content +} // namespace content \ No newline at end of file
diff --git a/content/browser/network_service_client.cc b/content/browser/network_service_client.cc index fc61785c..7b0b560 100644 --- a/content/browser/network_service_client.cc +++ b/content/browser/network_service_client.cc
@@ -39,46 +39,6 @@ namespace content { namespace { -void HandleFileUploadRequest( - uint32_t process_id, - bool async, - const std::vector<base::FilePath>& file_paths, - NetworkServiceClient::OnFileUploadRequestedCallback callback, - scoped_refptr<base::TaskRunner> task_runner) { - std::vector<base::File> files; - uint32_t file_flags = base::File::FLAG_OPEN | base::File::FLAG_READ | - (async ? base::File::FLAG_ASYNC : 0); - ChildProcessSecurityPolicy* cpsp = ChildProcessSecurityPolicy::GetInstance(); - for (const auto& file_path : file_paths) { - if (process_id != network::mojom::kBrowserProcessId && - !cpsp->CanReadFile(process_id, file_path)) { - task_runner->PostTask( - FROM_HERE, base::BindOnce(std::move(callback), net::ERR_ACCESS_DENIED, - std::vector<base::File>())); - return; - } -#if defined(OS_ANDROID) - if (file_path.IsContentUri()) { - files.push_back(base::OpenContentUriForRead(file_path)); - } else { - files.emplace_back(file_path, file_flags); - } -#else - files.emplace_back(file_path, file_flags); -#endif - if (!files.back().IsValid()) { - task_runner->PostTask( - FROM_HERE, - base::BindOnce(std::move(callback), - net::FileErrorToNetError(files.back().error_details()), - std::vector<base::File>())); - return; - } - } - task_runner->PostTask(FROM_HERE, base::BindOnce(std::move(callback), net::OK, - std::move(files))); -} - WebContents* GetWebContents(int process_id, int routing_id) { if (process_id != network::mojom::kBrowserProcessId) { return WebContentsImpl::FromRenderFrameHostID(process_id, routing_id); @@ -139,19 +99,6 @@ } } -void NetworkServiceClient::OnFileUploadRequested( - uint32_t process_id, - bool async, - const std::vector<base::FilePath>& file_paths, - OnFileUploadRequestedCallback callback) { - base::PostTask( - FROM_HERE, - {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, - base::BindOnce(&HandleFileUploadRequest, process_id, async, file_paths, - std::move(callback), - base::SequencedTaskRunnerHandle::Get())); -} - void NetworkServiceClient::OnLoadingStateUpdate( std::vector<network::mojom::LoadInfoPtr> infos, OnLoadingStateUpdateCallback callback) {
diff --git a/content/browser/network_service_client.h b/content/browser/network_service_client.h index 8f875f1..1df7126 100644 --- a/content/browser/network_service_client.h +++ b/content/browser/network_service_client.h
@@ -42,10 +42,6 @@ ~NetworkServiceClient() override; // network::mojom::NetworkServiceClient implementation: - void OnFileUploadRequested(uint32_t process_id, - bool async, - const std::vector<base::FilePath>& file_paths, - OnFileUploadRequestedCallback callback) override; void OnLoadingStateUpdate(std::vector<network::mojom::LoadInfoPtr> infos, OnLoadingStateUpdateCallback callback) override; void OnDataUseUpdate(int32_t network_traffic_annotation_id_hash,
diff --git a/content/browser/renderer_host/dwrite_font_lookup_table_builder_win_unittest.cc b/content/browser/renderer_host/dwrite_font_lookup_table_builder_win_unittest.cc index b02ef48..23b573f 100644 --- a/content/browser/renderer_host/dwrite_font_lookup_table_builder_win_unittest.cc +++ b/content/browser/renderer_host/dwrite_font_lookup_table_builder_win_unittest.cc
@@ -87,7 +87,9 @@ // Run a test similar to DWriteFontProxyImplUnitTest, TestFindUniqueFont but // without going through Mojo and running it on the DWRiteFontLookupTableBuilder // class directly. -TEST_F(DWriteFontLookupTableBuilderTest, TestFindUniqueFontDirect) { +// TODO(https://crbug.com/996167): Re-enable the DWriteFontLookupTableBuilder +// tests once the root cause for flakiness is addressed. +TEST_F(DWriteFontLookupTableBuilderTest, DISABLED_TestFindUniqueFontDirect) { font_lookup_table_builder_->SchedulePrepareFontUniqueNameTableIfNeeded(); bool test_callback_executed = false; font_lookup_table_builder_->QueueShareMemoryRegionWhenReady( @@ -101,7 +103,9 @@ ASSERT_TRUE(test_callback_executed); } -TEST_P(DWriteFontLookupTableBuilderTimeoutTest, TestTimeout) { +// TODO(https://crbug.com/996167): Re-enable the DWriteFontLookupTableBuilder +// tests once the root cause for flakiness is addressed. +TEST_P(DWriteFontLookupTableBuilderTimeoutTest, DISABLED_TestTimeout) { font_lookup_table_builder_->SetSlowDownIndexingForTestingWithTimeout( GetParam(), kTestingTimeout); font_lookup_table_builder_->SchedulePrepareFontUniqueNameTableIfNeeded(); @@ -127,14 +131,18 @@ ASSERT_TRUE(test_callback_executed); } -INSTANTIATE_TEST_SUITE_P( - , - DWriteFontLookupTableBuilderTimeoutTest, - ::testing::Values( - DWriteFontLookupTableBuilder::SlowDownMode::kDelayEachTask, - DWriteFontLookupTableBuilder::SlowDownMode::kHangOneTask)); +// TODO(https://crbug.com/996167): Re-enable the DWriteFontLookupTableBuilder +// tests once the root cause for flakiness is addressed. +// INSTANTIATE_TEST_SUITE_P( +// , +// DWriteFontLookupTableBuilderTimeoutTest, +// ::testing::Values( +// DWriteFontLookupTableBuilder::SlowDownMode::kDelayEachTask, +// DWriteFontLookupTableBuilder::SlowDownMode::kHangOneTask)); -TEST_F(DWriteFontLookupTableBuilderTest, TestReadyEarly) { +// TODO(https://crbug.com/996167): Re-enable the DWriteFontLookupTableBuilder +// tests once the root cause for flakiness is addressed. +TEST_F(DWriteFontLookupTableBuilderTest, DISABLED_TestReadyEarly) { font_lookup_table_builder_->SetSlowDownIndexingForTestingWithTimeout( DWriteFontLookupTableBuilder::SlowDownMode::kHangOneTask, kTestingTimeout); @@ -154,7 +162,9 @@ ASSERT_TRUE(test_callback_executed); } -TEST_F(DWriteFontLookupTableBuilderTest, RepeatedScheduling) { +// TODO(https://crbug.com/996167): Re-enable the DWriteFontLookupTableBuilder +// tests once the root cause for flakiness is addressed. +TEST_F(DWriteFontLookupTableBuilderTest, DISABLED_RepeatedScheduling) { for (unsigned i = 0; i < 3; ++i) { font_lookup_table_builder_->ResetLookupTableForTesting(); font_lookup_table_builder_->SetCachingEnabledForTesting(false); @@ -171,11 +181,15 @@ } } -TEST_F(DWriteFontLookupTableBuilderTest, FontsHash) { +// TODO(https://crbug.com/996167): Re-enable the DWriteFontLookupTableBuilder +// tests once the root cause for flakiness is addressed. +TEST_F(DWriteFontLookupTableBuilderTest, DISABLED_FontsHash) { ASSERT_GT(font_lookup_table_builder_->ComputePersistenceHash().size(), 0u); } -TEST_F(DWriteFontLookupTableBuilderTest, HandleCorruptCacheFile) { +// TODO(https://crbug.com/996167): Re-enable the DWriteFontLookupTableBuilder +// tests once the root cause for flakiness is addressed. +TEST_F(DWriteFontLookupTableBuilderTest, DISABLED_HandleCorruptCacheFile) { // Cycle once to build cache file. font_lookup_table_builder_->ResetLookupTableForTesting(); font_lookup_table_builder_->SchedulePrepareFontUniqueNameTableIfNeeded();
diff --git a/content/browser/renderer_host/dwrite_font_proxy_impl_win_unittest.cc b/content/browser/renderer_host/dwrite_font_proxy_impl_win_unittest.cc index 50186030..6ee3650 100644 --- a/content/browser/renderer_host/dwrite_font_proxy_impl_win_unittest.cc +++ b/content/browser/renderer_host/dwrite_font_proxy_impl_win_unittest.cc
@@ -303,7 +303,9 @@ } } // namespace -TEST_F(DWriteFontProxyTableMatchingTest, TestFindUniqueFont) { +// TODO(https://crbug.com/996167): Re-enable the DWriteFontLookupTableBuilder +// tests once the root cause for flakiness is addressed. +TEST_F(DWriteFontProxyTableMatchingTest, DISABLED_TestFindUniqueFont) { bool lookup_table_results_were_tested = false; dwrite_font_proxy().GetUniqueNameLookupTable(base::BindOnce( &TestWhenLookupTableReady, &lookup_table_results_were_tested));
diff --git a/content/browser/storage_partition_impl.cc b/content/browser/storage_partition_impl.cc index b41efa3..a4e31cf 100644 --- a/content/browser/storage_partition_impl.cc +++ b/content/browser/storage_partition_impl.cc
@@ -42,6 +42,7 @@ #include "content/browser/gpu/shader_cache_factory.h" #include "content/browser/loader/prefetch_url_loader_service.h" #include "content/browser/native_file_system/native_file_system_manager_impl.h" +#include "content/browser/network_context_client_base_impl.h" #include "content/browser/notifications/platform_notification_context_impl.h" #include "content/browser/service_worker/service_worker_context_wrapper.h" #include "content/browser/ssl/ssl_client_auth_handler.h" @@ -1665,6 +1666,15 @@ std::move(web_contents_getter), net_error, ssl_info, fatal); } +void StoragePartitionImpl::OnFileUploadRequested( + uint32_t process_id, + bool async, + const std::vector<base::FilePath>& file_paths, + OnFileUploadRequestedCallback callback) { + NetworkContextOnFileUploadRequested(process_id, async, file_paths, + std::move(callback)); +} + void StoragePartitionImpl::OnCanSendReportingReports( const std::vector<url::Origin>& origins, OnCanSendReportingReportsCallback callback) {
diff --git a/content/browser/storage_partition_impl.h b/content/browser/storage_partition_impl.h index ff68cbd..7898ce2e 100644 --- a/content/browser/storage_partition_impl.h +++ b/content/browser/storage_partition_impl.h
@@ -213,6 +213,10 @@ const net::SSLInfo& ssl_info, bool fatal, OnSSLCertificateErrorCallback response) override; + void OnFileUploadRequested(uint32_t process_id, + bool async, + const std::vector<base::FilePath>& file_paths, + OnFileUploadRequestedCallback callback) override; void OnCanSendReportingReports( const std::vector<url::Origin>& origins, OnCanSendReportingReportsCallback callback) override;
diff --git a/content/public/android/java/src/org/chromium/content/app/ContentChildProcessServiceDelegate.java b/content/public/android/java/src/org/chromium/content/app/ContentChildProcessServiceDelegate.java index 0b82a217..c941bb9 100644 --- a/content/public/android/java/src/org/chromium/content/app/ContentChildProcessServiceDelegate.java +++ b/content/public/android/java/src/org/chromium/content/app/ContentChildProcessServiceDelegate.java
@@ -20,7 +20,6 @@ import org.chromium.base.annotations.MainDex; import org.chromium.base.annotations.NativeMethods; import org.chromium.base.library_loader.LibraryLoader; -import org.chromium.base.library_loader.LibraryLoaderConfig; import org.chromium.base.library_loader.Linker; import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.memory.MemoryPressureUma; @@ -83,8 +82,7 @@ mCpuFeatures = connectionBundle.getLong(ContentChildProcessConstants.EXTRA_CPU_FEATURES); assert mCpuCount > 0; - if (LibraryLoaderConfig.useChromiumLinker() - && !LibraryLoader.getInstance().isLoadedByZygote()) { + if (LibraryLoader.useChromiumLinker() && !LibraryLoader.getInstance().isLoadedByZygote()) { Bundle sharedRelros = connectionBundle.getBundle(Linker.EXTRA_LINKER_SHARED_RELROS); if (sharedRelros != null) getLinker().provideSharedRelros(sharedRelros); } @@ -108,7 +106,7 @@ Linker linker = null; boolean requestedSharedRelro = false; - if (LibraryLoaderConfig.useChromiumLinker()) { + if (LibraryLoader.useChromiumLinker()) { assert mLinkerParams != null; linker = getLinker(); if (mLinkerParams.mWaitForSharedRelro) { @@ -186,7 +184,7 @@ // Return a Linker instance. If testing, the Linker needs special setup. private Linker getLinker() { - if (LibraryLoaderConfig.areTestsEnabled()) { + if (Linker.areTestsEnabled()) { // For testing, set the Linker implementation and the test runner // class name to match those used by the parent. assert mLinkerParams != null;
diff --git a/content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncherHelperImpl.java b/content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncherHelperImpl.java index 615bd78f4..0762587 100644 --- a/content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncherHelperImpl.java +++ b/content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncherHelperImpl.java
@@ -24,7 +24,7 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.NativeMethods; -import org.chromium.base.library_loader.LibraryLoaderConfig; +import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.library_loader.Linker; import org.chromium.base.process_launcher.ChildConnectionAllocator; import org.chromium.base.process_launcher.ChildProcessConnection; @@ -133,7 +133,7 @@ ContentChildProcessConstants.EXTRA_CPU_COUNT, CpuFeatures.getCount()); connectionBundle.putLong( ContentChildProcessConstants.EXTRA_CPU_FEATURES, CpuFeatures.getMask()); - if (LibraryLoaderConfig.useChromiumLinker()) { + if (LibraryLoader.useChromiumLinker()) { connectionBundle.putBundle(Linker.EXTRA_LINKER_SHARED_RELROS, Linker.getInstance().getSharedRelros()); } @@ -594,7 +594,7 @@ private static void initLinker() { assert LauncherThread.runningOnLauncherThread(); if (sLinkerInitialized) return; - if (LibraryLoaderConfig.useChromiumLinker()) { + if (LibraryLoader.useChromiumLinker()) { sLinkerLoadAddress = Linker.getInstance().getBaseLoadAddress(); if (sLinkerLoadAddress == 0) { Log.i(TAG, "Shared RELRO support disabled!"); @@ -612,7 +612,7 @@ // Always wait for the shared RELROs in service processes. final boolean waitForSharedRelros = true; - if (LibraryLoaderConfig.areTestsEnabled()) { + if (Linker.areTestsEnabled()) { Linker linker = Linker.getInstance(); return new ChromiumLinkerParams(sLinkerLoadAddress, waitForSharedRelros, linker.getTestRunnerClassNameForTesting(),
diff --git a/content/public/browser/BUILD.gn b/content/public/browser/BUILD.gn index a801763..c3fdbfd 100644 --- a/content/public/browser/BUILD.gn +++ b/content/public/browser/BUILD.gn
@@ -226,6 +226,7 @@ "navigation_throttle.h", "navigation_type.h", "navigation_ui_data.h", + "network_context_client_base.h", "network_quality_observer_factory.h", "network_service_instance.h", "notification_database_data.cc",
diff --git a/content/public/browser/media_session.h b/content/public/browser/media_session.h index 628793e5..39aa9d06 100644 --- a/content/public/browser/media_session.h +++ b/content/public/browser/media_session.h
@@ -13,6 +13,7 @@ namespace content { +class BrowserContext; class WebContents; // MediaSession manages the media session and audio focus for a given @@ -22,11 +23,15 @@ // and allows clients to resume/suspend/stop the managed players. class MediaSession : public media_session::mojom::MediaSession { public: + ~MediaSession() override = default; + // Returns the MediaSession associated to this WebContents. Creates one if // none is currently available. CONTENT_EXPORT static MediaSession* Get(WebContents* contents); - ~MediaSession() override = default; + // Returns the source identity for the given BrowserContext. + CONTENT_EXPORT static const base::UnguessableToken& GetSourceId( + BrowserContext* browser_context); // Tell the media session a user action has performed. virtual void DidReceiveAction(
diff --git a/content/public/browser/native_file_system_permission_context.h b/content/public/browser/native_file_system_permission_context.h index cf08b64..1a924a3 100644 --- a/content/public/browser/native_file_system_permission_context.h +++ b/content/public/browser/native_file_system_permission_context.h
@@ -72,10 +72,13 @@ int frame_id, base::OnceCallback<void(PermissionStatus)> callback) = 0; + // These values are persisted to logs. Entries should not be renumbered and + // numeric values should never be reused. enum class SensitiveDirectoryResult { - kAllowed, // Access to directory is okay. - kTryAgain, // User should pick a different directory. - kAbort, // Abandon entirely, as if picking was cancelled. + kAllowed = 0, // Access to directory is okay. + kTryAgain = 1, // User should pick a different directory. + kAbort = 2, // Abandon entirely, as if picking was cancelled. + kMaxValue = kAbort }; // Checks if access to the given |paths| should be allowed or blocked. This is // used to implement blocks for certain sensitive directories such as the
diff --git a/content/public/browser/network_context_client_base.h b/content/public/browser/network_context_client_base.h new file mode 100644 index 0000000..47bd3a7 --- /dev/null +++ b/content/public/browser/network_context_client_base.h
@@ -0,0 +1,93 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_PUBLIC_BROWSER_NETWORK_CONTEXT_CLIENT_BASE_H_ +#define CONTENT_PUBLIC_BROWSER_NETWORK_CONTEXT_CLIENT_BASE_H_ + +#include "build/build_config.h" +#include "content/common/content_export.h" +#include "services/network/public/mojom/network_context.mojom.h" + +namespace content { + +// This is a mostly empty NetworkContextClient implementation that code can use +// as a default client. The only method it implements is OnFileUploadRequested +// so that POSTs in a given NetworkContext work. +class CONTENT_EXPORT NetworkContextClientBase + : public network::mojom::NetworkContextClient { + public: + NetworkContextClientBase(); + ~NetworkContextClientBase() override; + + // network::mojom::NetworkContextClient implementation: + void OnAuthRequired(const base::Optional<base::UnguessableToken>& window_id, + uint32_t process_id, + uint32_t routing_id, + uint32_t request_id, + const GURL& url, + bool first_auth_attempt, + const net::AuthChallengeInfo& auth_info, + network::mojom::URLResponseHeadPtr head, + network::mojom::AuthChallengeResponderPtr + auth_challenge_responder) override; + void OnCertificateRequested( + const base::Optional<base::UnguessableToken>& window_id, + uint32_t process_id, + uint32_t routing_id, + uint32_t request_id, + const scoped_refptr<net::SSLCertRequestInfo>& cert_info, + network::mojom::ClientCertificateResponderPtr cert_responder) override; + void OnSSLCertificateError(uint32_t process_id, + uint32_t routing_id, + const GURL& url, + int net_error, + const net::SSLInfo& ssl_info, + bool fatal, + OnSSLCertificateErrorCallback response) override; + void OnFileUploadRequested(uint32_t process_id, + bool async, + const std::vector<base::FilePath>& file_paths, + OnFileUploadRequestedCallback callback) override; + void OnCanSendReportingReports( + const std::vector<url::Origin>& origins, + OnCanSendReportingReportsCallback callback) override; + void OnCanSendDomainReliabilityUpload( + const GURL& origin, + OnCanSendDomainReliabilityUploadCallback callback) override; + void OnClearSiteData(uint32_t process_id, + int32_t routing_id, + const GURL& url, + const std::string& header_value, + int load_flags, + OnClearSiteDataCallback callback) override; + void OnCookiesChanged( + bool is_service_worker, + int32_t process_id, + int32_t routing_id, + const GURL& url, + const GURL& site_for_cookies, + const std::vector<net::CookieWithStatus>& cookie_list) override; + void OnCookiesRead( + bool is_service_worker, + int32_t process_id, + int32_t routing_id, + const GURL& url, + const GURL& site_for_cookies, + const std::vector<net::CookieWithStatus>& cookie_list) override; +#if defined(OS_ANDROID) + void OnGenerateHttpNegotiateAuthToken( + const std::string& server_auth_token, + bool can_delegate, + const std::string& auth_negotiate_android_account_type, + const std::string& spn, + OnGenerateHttpNegotiateAuthTokenCallback callback) override; +#endif +#if defined(OS_CHROMEOS) + void OnTrustAnchorUsed() override; +#endif +}; + +} // namespace content + +#endif // CONTENT_PUBLIC_BROWSER_NETWORK_CONTEXT_CLIENT_BASE_H_
diff --git a/content/public/common/content_features.cc b/content/public/common/content_features.cc index 1dda5be..2b09e01 100644 --- a/content/public/common/content_features.cc +++ b/content/public/common/content_features.cc
@@ -148,8 +148,15 @@ // Enables fixes for matching src: local() for web fonts correctly against full // font name or postscript name. Rolling out behind a flag, as enabling this // enables a font indexer on Android which we need to test in the field first. +// TODO(https://crbug.com/996027): Re-enable this on Windows once Windows 7 +// DWRiteFontLookupTableBuilder stability is fixed. +#if !defined(OS_WIN) const base::Feature kFontSrcLocalMatching{"FontSrcLocalMatching", base::FEATURE_ENABLED_BY_DEFAULT}; +#else +const base::Feature kFontSrcLocalMatching{"FontSrcLocalMatching", + base::FEATURE_DISABLED_BY_DEFAULT}; +#endif // Enables scrollers inside Blink to store scroll offsets in fractional // floating-point numbers rather than truncating to integers.
diff --git a/content/renderer/android/synchronous_layer_tree_frame_sink.cc b/content/renderer/android/synchronous_layer_tree_frame_sink.cc index fa353746..ce56f14 100644 --- a/content/renderer/android/synchronous_layer_tree_frame_sink.cc +++ b/content/renderer/android/synchronous_layer_tree_frame_sink.cc
@@ -227,8 +227,8 @@ &shared_bitmap_manager_, software_renderer_settings, kRootFrameSinkId, std::move(output_surface), nullptr /* scheduler */, nullptr /* current_task_runner */); - display_->Initialize(&display_client_, frame_sink_manager_->surface_manager(), - true /* enable_shared_images */); + display_->Initialize(&display_client_, + frame_sink_manager_->surface_manager()); display_->SetVisible(true); return true; }
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index f1e661e..fb449d8 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -1701,7 +1701,7 @@ "../browser/native_file_system/native_file_system_manager_impl_unittest.cc", "../browser/net/network_quality_observer_impl_unittest.cc", "../browser/net/quota_policy_cookie_store_unittest.cc", - "../browser/network_service_client_unittest.cc", + "../browser/network_context_client_base_impl_unittest.cc", "../browser/notification_service_impl_unittest.cc", "../browser/notifications/blink_notification_service_impl_unittest.cc", "../browser/notifications/notification_database_conversions_unittest.cc",
diff --git a/device/fido/cable/fido_cable_device.cc b/device/fido/cable/fido_cable_device.cc index ad91ad5..f41deea 100644 --- a/device/fido/cable/fido_cable_device.cc +++ b/device/fido/cable/fido_cable_device.cc
@@ -52,7 +52,7 @@ return false; crypto::Aead aes_key(crypto::Aead::AES_256_GCM); - aes_key.Init(&encryption_data->session_key); + aes_key.Init(encryption_data->session_key); DCHECK_EQ(nonce->size(), aes_key.NonceLength()); const uint8_t additional_data[1] = { @@ -76,7 +76,7 @@ return false; crypto::Aead aes_key(crypto::Aead::AES_256_GCM); - aes_key.Init(&encryption_data->session_key); + aes_key.Init(encryption_data->session_key); DCHECK_EQ(nonce->size(), aes_key.NonceLength()); const uint8_t additional_data[1] = { @@ -97,9 +97,9 @@ // FidoCableDevice::EncryptionData ---------------------------------------- FidoCableDevice::EncryptionData::EncryptionData( - std::string encryption_key, + base::span<const uint8_t, 32> encryption_key, base::span<const uint8_t, 8> nonce) - : session_key(std::move(encryption_key)), + : session_key(fido_parsing_utils::Materialize(encryption_key)), nonce(fido_parsing_utils::Materialize(nonce)) {} FidoCableDevice::EncryptionData::EncryptionData(EncryptionData&& data) = @@ -172,11 +172,12 @@ std::move(handshake_message), std::move(callback)); } -void FidoCableDevice::SetEncryptionData(std::string session_key, - base::span<const uint8_t, 8> nonce) { +void FidoCableDevice::SetEncryptionData( + base::span<const uint8_t, 32> session_key, + base::span<const uint8_t, 8> nonce) { // Encryption data must be set at most once during Cable handshake protocol. DCHECK(!encryption_data_); - encryption_data_.emplace(std::move(session_key), nonce); + encryption_data_.emplace(session_key, nonce); } FidoTransportProtocol FidoCableDevice::DeviceTransport() const {
diff --git a/device/fido/cable/fido_cable_device.h b/device/fido/cable/fido_cable_device.h index 7902b8d..0d498af 100644 --- a/device/fido/cable/fido_cable_device.h +++ b/device/fido/cable/fido_cable_device.h
@@ -29,12 +29,13 @@ // Encapsulates state FidoCableDevice maintains to encrypt and decrypt // data within FidoBleFrame. struct COMPONENT_EXPORT(DEVICE_FIDO) EncryptionData { - EncryptionData(std::string session_key, base::span<const uint8_t, 8> nonce); + EncryptionData(base::span<const uint8_t, 32> session_key, + base::span<const uint8_t, 8> nonce); EncryptionData(EncryptionData&& data); EncryptionData& operator=(EncryptionData&& other); ~EncryptionData(); - std::string session_key; + std::array<uint8_t, 32> session_key; std::array<uint8_t, 8> nonce; uint32_t write_sequence_num = 0; uint32_t read_sequence_num = 0; @@ -59,7 +60,7 @@ void SendHandshakeMessage(std::vector<uint8_t> handshake_message, DeviceCallback callback); - void SetEncryptionData(std::string session_key, + void SetEncryptionData(base::span<const uint8_t, 32> session_key, base::span<const uint8_t, 8> nonce); FidoTransportProtocol DeviceTransport() const override;
diff --git a/device/fido/cable/fido_cable_device_unittest.cc b/device/fido/cable/fido_cable_device_unittest.cc index e9e791d..1979d32 100644 --- a/device/fido/cable/fido_cable_device_unittest.cc +++ b/device/fido/cable/fido_cable_device_unittest.cc
@@ -41,10 +41,14 @@ constexpr auto kControlPointLength = std::numeric_limits<uint16_t>::max(); // Counter value that is larger than FidoCableDevice::kMaxCounter. constexpr uint32_t kInvalidCounter = 1 << 24; -constexpr char kTestSessionKey[] = "00000000000000000000000000000000"; +constexpr std::array<uint8_t, 32> kTestSessionKey = {0}; constexpr std::array<uint8_t, 8> kTestEncryptionNonce = { {1, 1, 1, 1, 1, 1, 1, 1}}; constexpr uint8_t kTestData[] = {'T', 'E', 'S', 'T'}; +// kCTAPFramingLength is the number of bytes of framing data at the beginning +// of transmitted BLE messages. See +// https://fidoalliance.org/specs/fido-v2.0-ps-20190130/fido-client-to-authenticator-protocol-v2.0-ps-20190130.html#ble-client-to-authenticator +constexpr size_t kCTAPFramingLength = 3; std::vector<uint8_t> ConstructSerializedOutgoingFragment( base::span<const uint8_t> data) { @@ -120,7 +124,9 @@ } std::array<uint8_t, 8> nonce_ = kTestEncryptionNonce; - std::string session_key_ = kTestSessionKey; + std::string session_key_{ + reinterpret_cast<const char*>(kTestSessionKey.data()), + kTestSessionKey.size()}; uint32_t expected_client_counter_ = 0; uint32_t authenticator_counter_ = 0; }; @@ -173,7 +179,7 @@ FROM_HERE, base::BindOnce(std::move(*cb), true)); const auto authenticator_reply = authenticator()->ReplyWithSameMessage( - base::make_span(data).subspan(3)); + base::make_span(data).subspan(kCTAPFramingLength)); base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(connection()->read_callback(), ConstructSerializedOutgoingFragment( @@ -201,7 +207,7 @@ FROM_HERE, base::BindOnce(std::move(*cb), true)); const auto authenticator_reply = authenticator()->ReplyWithSameMessage( - base::make_span(data).subspan(3)); + base::make_span(data).subspan(kCTAPFramingLength)); base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(connection()->read_callback(), ConstructSerializedOutgoingFragment( @@ -246,7 +252,7 @@ authenticator()->SetSessionKey(kIncorrectSessionKey); const auto authenticator_reply = authenticator()->ReplyWithSameMessage( - base::make_span(data).subspan(3)); + base::make_span(data).subspan(kCTAPFramingLength)); base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(connection()->read_callback(), @@ -275,7 +281,7 @@ authenticator()->SetAuthenticatorCounter( kIncorrectAuthenticatorCounter); const auto authenticator_reply = authenticator()->ReplyWithSameMessage( - base::make_span(data).subspan(3)); + base::make_span(data).subspan(kCTAPFramingLength)); base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(connection()->read_callback(), @@ -307,7 +313,7 @@ authenticator()->SetAuthenticatorCounter(kInvalidCounter); const auto authenticator_reply = authenticator()->ReplyWithSameMessage( - base::make_span(data).subspan(3)); + base::make_span(data).subspan(kCTAPFramingLength)); base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(connection()->read_callback(),
diff --git a/device/fido/cable/fido_cable_handshake_handler.cc b/device/fido/cable/fido_cable_handshake_handler.cc index c3e8fa3..76d7f5b 100644 --- a/device/fido/cable/fido_cable_handshake_handler.cc +++ b/device/fido/cable/fido_cable_handshake_handler.cc
@@ -20,6 +20,7 @@ #include "crypto/hkdf.h" #include "crypto/hmac.h" #include "crypto/random.h" +#include "crypto/sha2.h" #include "device/fido/cable/fido_cable_device.h" #include "device/fido/fido_constants.h" #include "device/fido/fido_parsing_utils.h" @@ -44,14 +45,6 @@ constexpr size_t kCableHandshakeMacMessageSize = 16; -// Derives key of size 32 bytes using HDKF algorithm. -// See https://tools.ietf.org/html/rfc5869 for details. -std::string GenerateKey(base::StringPiece secret, - base::StringPiece salt, - base::StringPiece info) { - return crypto::HkdfSha256(secret, salt, info, 32); -} - base::Optional<std::array<uint8_t, kClientHelloMessageSize>> ConstructHandshakeMessage(base::StringPiece handshake_key, base::span<const uint8_t, 16> client_random_nonce) { @@ -94,10 +87,11 @@ : cable_device_(cable_device), nonce_(fido_parsing_utils::Materialize(nonce)), session_pre_key_(fido_parsing_utils::Materialize(session_pre_key)), - handshake_key_(GenerateKey( + handshake_key_(crypto::HkdfSha256( fido_parsing_utils::ConvertToStringPiece(session_pre_key_), fido_parsing_utils::ConvertToStringPiece(nonce_), - kCableHandshakeKeyInfo)) { + kCableHandshakeKeyInfo, + /*derived_key_size=*/32)) { crypto::RandBytes(client_session_random_.data(), client_session_random_.size()); } @@ -162,26 +156,24 @@ } cable_device_->SetEncryptionData( - GetEncryptionKeyAfterSuccessfulHandshake(base::make_span<16>( - authenticator_random_nonce->second.GetBytestring())), + base::make_span<32>( + GetEncryptionKeyAfterSuccessfulHandshake(base::make_span<16>( + authenticator_random_nonce->second.GetBytestring()))), nonce_); return true; } -std::string +std::vector<uint8_t> FidoCableV1HandshakeHandler::GetEncryptionKeyAfterSuccessfulHandshake( base::span<const uint8_t, 16> authenticator_random_nonce) const { std::vector<uint8_t> nonce_message; fido_parsing_utils::Append(&nonce_message, nonce_); fido_parsing_utils::Append(&nonce_message, client_session_random_); fido_parsing_utils::Append(&nonce_message, authenticator_random_nonce); - return GenerateKey( - fido_parsing_utils::ConvertToStringPiece(session_pre_key_), - fido_parsing_utils::ConvertToStringPiece( - fido_parsing_utils::CreateSHA256Hash( - fido_parsing_utils::ConvertToStringPiece(nonce_message))), - kCableDeviceEncryptionKeyInfo); + return crypto::HkdfSha256(session_pre_key_, crypto::SHA256Hash(nonce_message), + kCableDeviceEncryptionKeyInfo, + /*derived_key_length=*/32); } FidoCableV2HandshakeHandler::FidoCableV2HandshakeHandler( @@ -319,9 +311,7 @@ HKDF2(chaining_key_, base::span<const uint8_t>()); uint8_t zero_nonce[8] = {0}; - cable_device_->SetEncryptionData( - std::string(reinterpret_cast<const char*>(key1.data()), key1.size()), - zero_nonce); + cable_device_->SetEncryptionData(key1, zero_nonce); return true; }
diff --git a/device/fido/cable/fido_cable_handshake_handler.h b/device/fido/cable/fido_cable_handshake_handler.h index bd137a7..06c4bef 100644 --- a/device/fido/cable/fido_cable_handshake_handler.h +++ b/device/fido/cable/fido_cable_handshake_handler.h
@@ -57,7 +57,7 @@ FRIEND_TEST_ALL_PREFIXES(FidoCableHandshakeHandlerTest, HandshakeFailWithIncorrectAuthenticatorResponse); - std::string GetEncryptionKeyAfterSuccessfulHandshake( + std::vector<uint8_t> GetEncryptionKeyAfterSuccessfulHandshake( base::span<const uint8_t, 16> authenticator_random_nonce) const; FidoCableDevice* const cable_device_;
diff --git a/device/fido/cable/fido_cable_handshake_handler_unittest.cc b/device/fido/cable/fido_cable_handshake_handler_unittest.cc index 06aba84..828602e 100644 --- a/device/fido/cable/fido_cable_handshake_handler_unittest.cc +++ b/device/fido/cable/fido_cable_handshake_handler_unittest.cc
@@ -117,18 +117,15 @@ // factors (i.e. authenticator session random, session pre key, and nonce) are // |kAuthenticatorSessionRandom|, |kTestSessionPreKey|, and |kTestNonce|, // respectively. -std::string GetExpectedEncryptionKey( +std::vector<uint8_t> GetExpectedEncryptionKey( base::span<const uint8_t> client_random_nonce) { std::vector<uint8_t> nonce_message = fido_parsing_utils::Materialize(kTestNonce); fido_parsing_utils::Append(&nonce_message, client_random_nonce); fido_parsing_utils::Append(&nonce_message, kAuthenticatorSessionRandom); - return crypto::HkdfSha256( - fido_parsing_utils::ConvertToStringPiece(kTestSessionPreKey), - fido_parsing_utils::ConvertToStringPiece( - fido_parsing_utils::CreateSHA256Hash( - fido_parsing_utils::ConvertToStringPiece(nonce_message))), - kCableDeviceEncryptionKeyInfo, 32); + return crypto::HkdfSha256(kTestSessionPreKey, + crypto::SHA256Hash(nonce_message), + kCableDeviceEncryptionKeyInfo, 32); } // Given a hello message and handshake key from the authenticator, construct
diff --git a/device/fido/fido_constants.cc b/device/fido/fido_constants.cc index a2151d2..c07c373 100644 --- a/device/fido/fido_constants.cc +++ b/device/fido/fido_constants.cc
@@ -52,7 +52,10 @@ } const char kCableHandshakeKeyInfo[] = "FIDO caBLE v1 handshakeKey"; -const char kCableDeviceEncryptionKeyInfo[] = "FIDO caBLE v1 sessionKey"; +const std::array<uint8_t, 24> kCableDeviceEncryptionKeyInfo = { + 'F', 'I', 'D', 'O', ' ', 'c', 'a', 'B', 'L', 'E', ' ', 'v', + '1', ' ', 's', 'e', 's', 's', 'i', 'o', 'n', 'K', 'e', 'y', +}; const char kCableAuthenticatorHelloMessage[] = "caBLE v1 authenticator hello"; const char kCableClientHelloMessage[] = "caBLE v1 client hello";
diff --git a/device/fido/fido_constants.h b/device/fido/fido_constants.h index f996e00..128ad7e8 100644 --- a/device/fido/fido_constants.h +++ b/device/fido/fido_constants.h
@@ -332,7 +332,8 @@ // Values used to construct/validate handshake messages for Cable handshake // protocol. COMPONENT_EXPORT(DEVICE_FIDO) extern const char kCableHandshakeKeyInfo[]; -COMPONENT_EXPORT(DEVICE_FIDO) extern const char kCableDeviceEncryptionKeyInfo[]; +COMPONENT_EXPORT(DEVICE_FIDO) +extern const std::array<uint8_t, 24> kCableDeviceEncryptionKeyInfo; COMPONENT_EXPORT(DEVICE_FIDO) extern const char kCableAuthenticatorHelloMessage[]; COMPONENT_EXPORT(DEVICE_FIDO) extern const char kCableClientHelloMessage[];
diff --git a/docs/testing/chromeos_debugging_tips.md b/docs/testing/chromeos_debugging_tips.md new file mode 100644 index 0000000..c69f0895 --- /dev/null +++ b/docs/testing/chromeos_debugging_tips.md
@@ -0,0 +1,61 @@ +# Chrome OS Debugging Instructions +Chrome on Chrome OS is tested using a handful of frameworks, each of which +you'll find running on Chrome's CQ and waterfalls. If you're investigating +failures in these tests, below are some tips for debugging and identifying the +cause. + +*** note + +This doc outlines tests running in true Chrome OS environments (ie: on virtual +machines or real devices). [linux-chromeos] tests, on the other hand, can be +debugged like any other linux test. +*** + +## Tast + +[Tast] is Chrome OS's integration testing framework. Since Chrome itself is +instrumental to the Chrome OS system, it's equally important that we run some +of these integration tests on Chrome's waterfalls. If you find one of these +tests failing (likely in the `chrome_all_tast_tests` step), you can: + +- **Inspect the failed test's log snippet**: There should be a log link for +each failed test with failure information. eg: For this [failed build], opening +the [platform.Histograms] log link contains stack traces and error messages. + +- **View browser & system logs**: A common cause of failure on Chrome's builders +are browser crashes. When this happens, each test's log snippets will simply +contain warnings like "[Chrome probably crashed]". To debug these crashes, +navigate to the test's Isolated output, most likely listed in the build under +the test step's [shard #0 isolated out] link. From there, view the various +`log/chrome/...` or `log/ui/...` text files and you should find some with +browser [crashes and stack traces]. + +To disable a test on Chrome's builders, the preferred method is to add the +`informational` attribute to the test's definition (see [Tast attributes] for +more info). Note that this requires a full Chrome OS checkout. If that's not an +option, or if it needs to be disabled ASAP, you can add it to the list of +disabled tests for the step's GN target. For example, to disable a test in the +`chrome_all_tast_tests` step, add it to [this list]. + +## Telemetry + +>TODO: Add instructions for debugging telemetry failures. + +## GTest + +>TODO: Add instructions for debugging GTest failures. + +## Rerunning these tests locally + +>TODO: Add instructions for rerunning these tests locally. + + +[linux-chromeos]: https://chromium.googlesource.com/chromium/src/+/master/docs/chromeos_build_instructions.md +[Tast]: https://chromium.googlesource.com/chromiumos/platform/tast/+/HEAD/README.md +[failed build]: https://ci.chromium.org/p/chromium/builders/ci/chromeos-kevin-rel/14102 +[platform.Histograms]: https://logs.chromium.org/logs/chromium/buildbucket/cr-buildbucket.appspot.com/8904949911599004400/+/steps/chrome_all_tast_tests_on_ChromeOS/0/logs/Deterministic_failure:_platform.Histograms__status_FAILURE_/0 +[Chrome probably crashed]: https://logs.chromium.org/logs/chromium/buildbucket/cr-buildbucket.appspot.com/8905974915785988832/+/steps/chrome_all_tast_tests__retry_shards_with_patch__on_ChromeOS/0/logs/Deterministic_failure:_ui.ChromeLogin__status_FAILURE_/0 +[shard #0 isolated out]: https://isolateserver.appspot.com/browse?namespace=default-gzip&hash=fd1f6d76b076f07cc98fa7b2e0c0097f35c51cd0 +[crashes and stack traces]: https://isolateserver.appspot.com/browse?namespace=default-gzip&digest=993d58ff48bb08071d951bd8e103fa5a3c03efb1&as=chrome_20190805-044653 +[Tast attributes]: https://chromium.googlesource.com/chromiumos/platform/tast/+/HEAD/docs/test_attributes.md +[this list]: https://codesearch.chromium.org/chromium/src/chromeos/BUILD.gn?rcl=7b0393a9091fd02edc9ae773739124f7be5a0782&l=242
diff --git a/docs/testing/testing_in_chromium.md b/docs/testing/testing_in_chromium.md index 706e3bc..eda1efc8 100644 --- a/docs/testing/testing_in_chromium.md +++ b/docs/testing/testing_in_chromium.md
@@ -34,6 +34,7 @@ It allows you to perform arbitrary actions on a set of web pages and report metrics about it. * **[Fuzzer Tests]** is used to uncover potential security & stability problems in Chromium. +* **[Tast]** is a test framework for system integration tests on Chrome OS. The following table shows which types of test works on which platforms. @@ -44,10 +45,11 @@ | Junit(Java) | | | | √ | | | | Browser Tests(C++) | √ | √ | √ | √ | | | | Web Tests(HTML, JS) | √ | √ | √ | | | | -| Telemetry(Python) | √ | √ | √ | √ | | ? | +| Telemetry(Python) | √ | √ | √ | √ | | √ | | Instrumentation Tests(Java) | | | | √ | | | | EarlGrey | | | | | √ | | | Fuzzer Tests(C++) | √ | √ | √ | √ | | √ | +| Tast(Golang) | | | | | | √ | *** note **Browser Tests Note** @@ -68,19 +70,6 @@ see [this thread](https://groups.google.com/a/chromium.org/forum/#!topic/blink-dev/338WKwWPbPI/discussion) for more context. *** -*** note -**Telemetry** - -Telemetry works on CrOS, but it is not officially supported yet. -*** - -*** note -**CrOS Note** - -There is an on going effort to enable existing Chromium tests on CrOS VM hosted on Linux, -right now only unit tests are enabled on CrOS VM. -*** - ## General Principles * All the tests in Chromium running on CQ and main waterfall should be hermetic and stable. @@ -154,6 +143,7 @@ ## How to debug tests * [Android Debugging Instructions] +* [Chrome OS Debugging Tips] * [Debugging Web Tests] ## How to deal with flaky tests @@ -173,6 +163,7 @@ [EarlGrey]: https://github.com/google/EarlGrey [Telemetry]: https://chromium.googlesource.com/catapult/+/HEAD/telemetry/README.md [Fuzzer Tests]: https://chromium.googlesource.com/chromium/src/+/master/testing/libfuzzer/README.md +[Tast]: https://chromium.googlesource.com/chromiumos/platform/tast/+/HEAD/README.md [Web Tests]: ./web_tests.md [crbug/611756]: https://bugs.chromium.org/p/chromium/issues/detail?id=611756 [Flaky portal]: https://analysis.chromium.org/p/chromium/flake-portal @@ -180,6 +171,7 @@ [Telemetry: Run benchmarks locally]: https://chromium.googlesource.com/catapult/+/HEAD/telemetry/docs/run_benchmarks_locally.md [Run fuzz target locally]: https://chromium.googlesource.com/chromium/src/+/master/testing/libfuzzer/getting_started.md#build-and-run-fuzz-target-locally [Android Debugging Instructions]: https://chromium.googlesource.com/chromium/src/+/HEAD/docs/android_debugging_instructions.md +[Chrome OS Debugging Tips]: ./chromeos_debugging_tips.md [Debugging Web Tests]: https://chromium.googlesource.com/chromium/src/+/HEAD/docs/testing/web_tests.md#Debugging-Web-Tests [code coverage dashboard]: https://analysis.chromium.org/p/chromium/coverage [How do I disable a flaky test]: https://www.chromium.org/developers/tree-sheriffs/sheriff-details-chromium#TOC-How-do-I-disable-a-flaky-test-
diff --git a/extensions/browser/extension_function_histogram_value.h b/extensions/browser/extension_function_histogram_value.h index 251dec9..411decaf6 100644 --- a/extensions/browser/extension_function_histogram_value.h +++ b/extensions/browser/extension_function_histogram_value.h
@@ -1438,6 +1438,7 @@ AUTOTESTPRIVATE_GETARCAPPWINDOWINFO = 1375, AUTOTESTPRIVATE_GETALLINSTALLEDAPPS = 1376, AUTOTESTPRIVATE_SWAPWINDOWSINSPLITVIEW = 1377, + AUTOTESTPRIVATE_SETARCAPPWINDOWFOCUS = 1378, // Last entry: Add new entries above, then run: // python tools/metrics/histograms/update_extension_histograms.py ENUM_BOUNDARY
diff --git a/extensions/browser/url_loader_factory_manager.cc b/extensions/browser/url_loader_factory_manager.cc index 807e49d..5b000fd 100644 --- a/extensions/browser/url_loader_factory_manager.cc +++ b/extensions/browser/url_loader_factory_manager.cc
@@ -252,43 +252,20 @@ return allowlist; } - // Make sure kHardcodedPartOfAllowlist will fit, but also leave some room - // for field trial params. - allowlist.reserve(base::size(kHardcodedPartOfCorbAllowlist) + 10); - // Append extensions from the hardcoded allowlist. + allowlist.reserve(base::size(kHardcodedPartOfCorbAllowlist)); for (const char* hash : kHardcodedPartOfCorbAllowlist) { DCHECK(IsValidHashedExtensionId(hash)); // It also validates the length. allowlist.push_back(std::string(hash, kHashedExtensionIdLength)); } - // Append extensions from the field trial param. - std::string field_trial_arg = base::GetFieldTrialParamValueByFeature( - extensions_features::kBypassCorbOnlyForExtensionsAllowlist, - extensions_features::kBypassCorbAllowlistParamName); - field_trial_arg = base::ToUpperASCII(field_trial_arg); - std::vector<std::string> field_trial_allowlist = base::SplitString( - field_trial_arg, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); - base::EraseIf(field_trial_allowlist, [](const std::string& hash) { - // Filter out invalid data from |field_trial_allowlist|. - if (IsValidHashedExtensionId(hash)) - return false; // Don't remove. - - LOG(ERROR) << "Invalid extension hash: " << hash; - return true; // Remove. - }); - std::move(field_trial_allowlist.begin(), field_trial_allowlist.end(), - std::back_inserter(allowlist)); - return allowlist; } // Returns a set of HashedExtensionId of extensions that depend on relaxed CORB // behavior in their content scripts. -const base::flat_set<std::string>& GetExtensionsAllowlist() { - DCHECK(base::FeatureList::IsEnabled( - extensions_features::kBypassCorbOnlyForExtensionsAllowlist)); - static const base::NoDestructor<base::flat_set<std::string>> s_allowlist([] { +base::flat_set<std::string>& GetExtensionsAllowlist() { + static base::NoDestructor<base::flat_set<std::string>> s_allowlist([] { base::flat_set<std::string> result(CreateExtensionAllowlist()); result.shrink_to_fit(); return result; @@ -305,10 +282,6 @@ // Content scripts in the current version of extensions might depend on // relaxed CORB. if (extension.manifest_version() <= 2) { - if (!base::FeatureList::IsEnabled( - extensions_features::kBypassCorbOnlyForExtensionsAllowlist)) - return true; - const std::string& hash = extension.hashed_id().value(); DCHECK(IsValidHashedExtensionId(hash)); return base::Contains(GetExtensionsAllowlist(), hash); @@ -589,4 +562,16 @@ *extension); } +// static +void URLLoaderFactoryManager::AddExtensionToAllowlistForTesting( + const Extension& extension) { + GetExtensionsAllowlist().insert(extension.hashed_id().value()); +} + +// static +void URLLoaderFactoryManager::RemoveExtensionFromAllowlistForTesting( + const Extension& extension) { + GetExtensionsAllowlist().erase(extension.hashed_id().value()); +} + } // namespace extensions
diff --git a/extensions/browser/url_loader_factory_manager.h b/extensions/browser/url_loader_factory_manager.h index cd4e995..3810ff7 100644 --- a/extensions/browser/url_loader_factory_manager.h +++ b/extensions/browser/url_loader_factory_manager.h
@@ -69,6 +69,10 @@ header_client, const url::Origin& initiator_origin); + static void AddExtensionToAllowlistForTesting(const Extension& extension); + static void RemoveExtensionFromAllowlistForTesting( + const Extension& extension); + private: // If |extension|'s manifest declares that it may inject JavaScript content // script into the |navigating_frame| / |navigation_target|, then
diff --git a/extensions/common/extension_features.cc b/extensions/common/extension_features.cc index 0da1b3c29..6027451 100644 --- a/extensions/common/extension_features.cc +++ b/extensions/common/extension_features.cc
@@ -6,14 +6,6 @@ namespace extensions_features { -// Enables enforcement of Cross-Origin Read Blocking (CORB) for most extension -// content scripts, except ones that are on an allowlist. See also -// https://crbug.com/846346 and DoContentScriptsDependOnRelaxedCorb function in -// extensions/browser/url_loader_factory_manager.cc. -const base::Feature kBypassCorbOnlyForExtensionsAllowlist{ - "BypassCorbOnlyForExtensionsAllowlist", base::FEATURE_ENABLED_BY_DEFAULT}; -const char kBypassCorbAllowlistParamName[] = "BypassCorbExtensionsAllowlist"; - // Enables new extension updater service. const base::Feature kNewExtensionUpdaterService{ "NewExtensionUpdaterService", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/extensions/common/extension_features.h b/extensions/common/extension_features.h index 0eb0bd61..dfa5383 100644 --- a/extensions/common/extension_features.h +++ b/extensions/common/extension_features.h
@@ -9,8 +9,6 @@ namespace extensions_features { -extern const base::Feature kBypassCorbOnlyForExtensionsAllowlist; -extern const char kBypassCorbAllowlistParamName[]; extern const base::Feature kNewExtensionUpdaterService; extern const base::Feature kForceWebRequestProxyForTest;
diff --git a/fuchsia/base/BUILD.gn b/fuchsia/base/BUILD.gn index 556b683f..e8ba2b60 100644 --- a/fuchsia/base/BUILD.gn +++ b/fuchsia/base/BUILD.gn
@@ -69,6 +69,8 @@ "frame_test_util.cc", "frame_test_util.h", "result_receiver.h", + "test_devtools_list_fetcher.cc", + "test_devtools_list_fetcher.h", "test_navigation_listener.cc", "test_navigation_listener.h", ] @@ -76,6 +78,8 @@ ":base", ":modular", "//base", + "//net", + "//net:test_support", "//third_party/fuchsia-sdk/sdk:modular", "//third_party/fuchsia-sdk/sdk:web", "//url",
diff --git a/fuchsia/engine/test_devtools_list_fetcher.cc b/fuchsia/base/test_devtools_list_fetcher.cc similarity index 95% rename from fuchsia/engine/test_devtools_list_fetcher.cc rename to fuchsia/base/test_devtools_list_fetcher.cc index 0cca898..e8b0335 100644 --- a/fuchsia/engine/test_devtools_list_fetcher.cc +++ b/fuchsia/base/test_devtools_list_fetcher.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 "fuchsia/engine/test_devtools_list_fetcher.h" +#include "fuchsia/base/test_devtools_list_fetcher.h" #include "base/callback.h" #include "base/json/json_reader.h" @@ -68,7 +68,11 @@ } // namespace +namespace cr_fuchsia { + base::Value GetDevToolsListFromPort(uint16_t port) { DevToolsListFetcher devtools_fetcher; return devtools_fetcher.GetDevToolsListFromPort(port); } + +} // namespace cr_fuchsia
diff --git a/fuchsia/engine/test_devtools_list_fetcher.h b/fuchsia/base/test_devtools_list_fetcher.h similarity index 65% rename from fuchsia/engine/test_devtools_list_fetcher.h rename to fuchsia/base/test_devtools_list_fetcher.h index b133cbf4..6971e49 100644 --- a/fuchsia/engine/test_devtools_list_fetcher.h +++ b/fuchsia/base/test_devtools_list_fetcher.h
@@ -2,13 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FUCHSIA_ENGINE_TEST_DEVTOOLS_LIST_FETCHER_H_ -#define FUCHSIA_ENGINE_TEST_DEVTOOLS_LIST_FETCHER_H_ +#ifndef FUCHSIA_BASE_TEST_DEVTOOLS_LIST_FETCHER_H_ +#define FUCHSIA_BASE_TEST_DEVTOOLS_LIST_FETCHER_H_ #include "base/values.h" +namespace cr_fuchsia { + // Returns the JSON value of the list URL for the DevTools service listening // on port |port| on localhost. Returns an empty value on error. base::Value GetDevToolsListFromPort(uint16_t port); -#endif // FUCHSIA_ENGINE_TEST_DEVTOOLS_LIST_FETCHER_H_ +} // namespace cr_fuchsia + +#endif // FUCHSIA_BASE_TEST_DEVTOOLS_LIST_FETCHER_H_
diff --git a/fuchsia/engine/BUILD.gn b/fuchsia/engine/BUILD.gn index e41d7b7..90f36eb 100644 --- a/fuchsia/engine/BUILD.gn +++ b/fuchsia/engine/BUILD.gn
@@ -270,8 +270,6 @@ sources = [ "test_debug_listener.cc", "test_debug_listener.h", - "test_devtools_list_fetcher.cc", - "test_devtools_list_fetcher.h", "web_engine_debug_integration_test.cc", "web_engine_integration_test.cc", ] @@ -283,8 +281,6 @@ "//base/test:run_all_unittests", "//fuchsia/base", "//fuchsia/base:test_support", - "//net", - "//net:test_support", "//third_party/fuchsia-sdk/sdk:web", ] package_deps = [ [
diff --git a/fuchsia/engine/web_engine_debug_integration_test.cc b/fuchsia/engine/web_engine_debug_integration_test.cc index baf89c0..2168aebe 100644 --- a/fuchsia/engine/web_engine_debug_integration_test.cc +++ b/fuchsia/engine/web_engine_debug_integration_test.cc
@@ -16,9 +16,9 @@ #include "fuchsia/base/fit_adapter.h" #include "fuchsia/base/frame_test_util.h" #include "fuchsia/base/result_receiver.h" +#include "fuchsia/base/test_devtools_list_fetcher.h" #include "fuchsia/base/test_navigation_listener.h" #include "fuchsia/engine/test_debug_listener.h" -#include "fuchsia/engine/test_devtools_list_fetcher.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "testing/gtest/include/gtest/gtest.h" @@ -156,8 +156,8 @@ // Test the debug information is correct. dev_tools_listener_.RunUntilNumberOfPortsIs(1u); - base::Value devtools_list = - GetDevToolsListFromPort(*dev_tools_listener_.debug_ports().begin()); + base::Value devtools_list = cr_fuchsia::GetDevToolsListFromPort( + *dev_tools_listener_.debug_ports().begin()); ASSERT_TRUE(devtools_list.is_list()); EXPECT_EQ(devtools_list.GetList().size(), 1u); @@ -184,7 +184,7 @@ dev_tools_listener_.RunUntilNumberOfPortsIs(1u); uint16_t port1 = *dev_tools_listener_.debug_ports().begin(); - base::Value devtools_list1 = GetDevToolsListFromPort(port1); + base::Value devtools_list1 = cr_fuchsia::GetDevToolsListFromPort(port1); ASSERT_TRUE(devtools_list1.is_list()); EXPECT_EQ(devtools_list1.GetList().size(), 1u); @@ -218,7 +218,7 @@ ASSERT_NE(dev_tools_listener_.debug_ports().find(port2), dev_tools_listener_.debug_ports().end()); - base::Value devtools_list2 = GetDevToolsListFromPort(port2); + base::Value devtools_list2 = cr_fuchsia::GetDevToolsListFromPort(port2); ASSERT_TRUE(devtools_list2.is_list()); EXPECT_EQ(devtools_list2.GetList().size(), 1u);
diff --git a/fuchsia/engine/web_engine_integration_test.cc b/fuchsia/engine/web_engine_integration_test.cc index a6bf2ff..a1ad9b4 100644 --- a/fuchsia/engine/web_engine_integration_test.cc +++ b/fuchsia/engine/web_engine_integration_test.cc
@@ -17,8 +17,8 @@ #include "fuchsia/base/fit_adapter.h" #include "fuchsia/base/frame_test_util.h" #include "fuchsia/base/result_receiver.h" +#include "fuchsia/base/test_devtools_list_fetcher.h" #include "fuchsia/base/test_navigation_listener.h" -#include "fuchsia/engine/test_devtools_list_fetcher.h" #include "net/http/http_request_headers.h" #include "net/test/embedded_test_server/default_handlers.h" #include "net/test/embedded_test_server/embedded_test_server.h" @@ -254,7 +254,8 @@ nav_controller.get(), fuchsia::web::LoadUrlParams(), url.spec())); navigation_listener.RunUntilUrlEquals(url); - base::Value devtools_list = GetDevToolsListFromPort(remote_debugging_port); + base::Value devtools_list = + cr_fuchsia::GetDevToolsListFromPort(remote_debugging_port); ASSERT_TRUE(devtools_list.is_list()); EXPECT_EQ(devtools_list.GetList().size(), 1u);
diff --git a/fuchsia/runners/cast/cast_component.cc b/fuchsia/runners/cast/cast_component.cc index ced96cce..9aed46f 100644 --- a/fuchsia/runners/cast/cast_component.cc +++ b/fuchsia/runners/cast/cast_component.cc
@@ -38,21 +38,22 @@ } // namespace -CastComponent::CastComponent( - CastRunner* runner, - chromium::cast::ApplicationConfig application_config, - std::unique_ptr<ApiBindingsClient> api_bindings_client, - std::unique_ptr<base::fuchsia::StartupContext> context, - fidl::InterfaceRequest<fuchsia::sys::ComponentController> - controller_request, - std::unique_ptr<cr_fuchsia::AgentManager> agent_manager) - : WebComponent(runner, std::move(context), std::move(controller_request)), - agent_manager_(std::move(agent_manager)), - application_config_(std::move(application_config)), +CastComponent::CastComponentParams::CastComponentParams() = default; +CastComponent::CastComponentParams::CastComponentParams(CastComponentParams&&) = + default; +CastComponent::CastComponentParams::~CastComponentParams() = default; + +CastComponent::CastComponent(CastRunner* runner, + CastComponent::CastComponentParams params) + : WebComponent(runner, + std::move(params.startup_context), + std::move(params.controller_request)), + agent_manager_(std::move(params.agent_manager)), + application_config_(std::move(params.app_config)), touch_input_policy_( TouchInputPolicyFromApplicationConfig(application_config_)), connector_(frame()), - api_bindings_client_(std::move(api_bindings_client)), + api_bindings_client_(std::move(params.api_bindings_client)), navigation_listener_binding_(this) { base::AutoReset<bool> constructor_active_reset(&constructor_active_, true);
diff --git a/fuchsia/runners/cast/cast_component.h b/fuchsia/runners/cast/cast_component.h index 5e35124..9b1fe7d 100644 --- a/fuchsia/runners/cast/cast_component.h +++ b/fuchsia/runners/cast/cast_component.h
@@ -9,6 +9,8 @@ #include <memory> #include "base/fuchsia/service_directory.h" +#include "base/fuchsia/startup_context.h" +#include "base/optional.h" #include "fuchsia/base/agent_manager.h" #include "fuchsia/runners/cast/api_bindings_client.h" #include "fuchsia/runners/cast/application_controller_impl.h" @@ -22,13 +24,23 @@ class CastComponent : public WebComponent, public fuchsia::web::NavigationEventListener { public: - CastComponent(CastRunner* runner, - chromium::cast::ApplicationConfig application_config, - std::unique_ptr<ApiBindingsClient> bindings_manager, - std::unique_ptr<base::fuchsia::StartupContext> startup_context, - fidl::InterfaceRequest<fuchsia::sys::ComponentController> - controller_request, - std::unique_ptr<cr_fuchsia::AgentManager> agent_manager); + struct CastComponentParams { + CastComponentParams(); + CastComponentParams(CastComponentParams&&); + ~CastComponentParams(); + + chromium::cast::ApplicationConfigManagerPtr app_config_manager; + std::unique_ptr<base::fuchsia::StartupContext> startup_context; + std::unique_ptr<cr_fuchsia::AgentManager> agent_manager; + std::unique_ptr<ApiBindingsClient> api_bindings_client; + fidl::InterfaceRequest<fuchsia::sys::ComponentController> + controller_request; + chromium::cast::ApplicationConfig app_config; + fuchsia::web::AdditionalHeadersProviderPtr headers_provider; + base::Optional<std::vector<fuchsia::net::http::Header>> headers; + }; + + CastComponent(CastRunner* runner, CastComponentParams params); ~CastComponent() override; private:
diff --git a/fuchsia/runners/cast/cast_runner.cc b/fuchsia/runners/cast/cast_runner.cc index 0e51983..a6d9368 100644 --- a/fuchsia/runners/cast/cast_runner.cc +++ b/fuchsia/runners/cast/cast_runner.cc
@@ -10,10 +10,7 @@ #include <utility> #include "base/fuchsia/fuchsia_logging.h" -#include "base/fuchsia/startup_context.h" #include "base/logging.h" -#include "fuchsia/base/agent_manager.h" -#include "fuchsia/runners/cast/cast_component.h" #include "url/gurl.h" CastRunner::CastRunner(sys::OutgoingDirectory* outgoing_directory, @@ -22,17 +19,6 @@ CastRunner::~CastRunner() = default; -struct CastRunner::PendingComponent { - chromium::cast::ApplicationConfigManagerPtr app_config_manager; - std::unique_ptr<base::fuchsia::StartupContext> startup_context; - std::unique_ptr<cr_fuchsia::AgentManager> agent_manager; - std::unique_ptr<ApiBindingsClient> bindings_manager; - fidl::InterfaceRequest<fuchsia::sys::ComponentController> controller_request; - chromium::cast::ApplicationConfig app_config; - fuchsia::web::AdditionalHeadersProviderPtr headers_provider; - base::Optional<std::vector<fuchsia::net::http::Header>> headers; -}; - void CastRunner::StartComponent( fuchsia::sys::Package package, fuchsia::sys::StartupInfo startup_info, @@ -54,7 +40,8 @@ // The application configuration asynchronously via the per-component // ApplicationConfigManager, the pointer to that service must be kept live // until the request completes, or CastRunner is deleted. - auto pending_component = std::make_unique<PendingComponent>(); + auto pending_component = + std::make_unique<CastComponent::CastComponentParams>(); pending_component->startup_context = std::make_unique<base::fuchsia::StartupContext>(std::move(startup_info)); pending_component->agent_manager = std::make_unique<cr_fuchsia::AgentManager>( @@ -75,7 +62,7 @@ fidl::InterfaceHandle<chromium::cast::ApiBindings> api_bindings_client; pending_component->agent_manager->ConnectToAgentService( kAgentComponentUrl, api_bindings_client.NewRequest()); - pending_component->bindings_manager = std::make_unique<ApiBindingsClient>( + pending_component->api_bindings_client = std::make_unique<ApiBindingsClient>( std::move(api_bindings_client), base::BindOnce(&CastRunner::MaybeStartComponent, base::Unretained(this), base::Unretained(pending_component.get()))); @@ -116,12 +103,8 @@ "fuchsia-pkg://fuchsia.com/cast_agent#meta/cast_agent.cmx"; void CastRunner::GetConfigCallback( - PendingComponent* pending_component, + CastComponent::CastComponentParams* pending_component, chromium::cast::ApplicationConfig app_config) { - // Ideally the PendingComponent would be move()d out of |pending_components_| - // here, but that requires extract(), which isn't available until C++17. - // Instead find |pending_component| and move() the individual fields out - // before erase()ing it. auto it = pending_components_.find(pending_component); DCHECK(it != pending_components_.end()); @@ -137,25 +120,23 @@ MaybeStartComponent(pending_component); } -void CastRunner::MaybeStartComponent(PendingComponent* pending_component) { +void CastRunner::MaybeStartComponent( + CastComponent::CastComponentParams* pending_component) { if (pending_component->app_config.IsEmpty()) return; - if (!pending_component->bindings_manager->HasBindings()) + if (!pending_component->api_bindings_client->HasBindings()) return; if (!pending_component->headers.has_value()) return; // Create a component based on the returned configuration, and pass it the - // fields stashed in PendingComponent. - GURL cast_app_url(pending_component->app_config.web_url()); - auto component = std::make_unique<CastComponent>( - this, std::move(pending_component->app_config), - std::move(pending_component->bindings_manager), - std::move(pending_component->startup_context), - std::move(pending_component->controller_request), - std::move(pending_component->agent_manager)); + // |pending_component|. std::vector<fuchsia::net::http::Header> additional_headers = pending_component->headers.value(); + + GURL cast_app_url(pending_component->app_config.web_url()); + auto component = + std::make_unique<CastComponent>(this, std::move(*pending_component)); pending_components_.erase(pending_component); component->LoadUrl(std::move(cast_app_url), std::move(additional_headers));
diff --git a/fuchsia/runners/cast/cast_runner.h b/fuchsia/runners/cast/cast_runner.h index bc3cbdc..afbcaae6 100644 --- a/fuchsia/runners/cast/cast_runner.h +++ b/fuchsia/runners/cast/cast_runner.h
@@ -14,6 +14,7 @@ #include "base/containers/unique_ptr_adapters.h" #include "base/macros.h" #include "fuchsia/fidl/chromium/cast/cpp/fidl.h" +#include "fuchsia/runners/cast/cast_component.h" #include "fuchsia/runners/common/web_content_runner.h" // sys::Runner which instantiates Cast activities specified via cast/casts URIs. @@ -34,19 +35,20 @@ static const char kAgentComponentUrl[]; private: - struct PendingComponent; - - void GetConfigCallback(PendingComponent* pending_component, + void GetConfigCallback(CastComponent::CastComponentParams* pending_component, chromium::cast::ApplicationConfig app_config); - void GetBindingsCallback(PendingComponent* pending_component, - std::vector<chromium::cast::ApiBinding> bindings); + void GetBindingsCallback( + CastComponent::CastComponentParams* pending_component, + std::vector<chromium::cast::ApiBinding> bindings); // Starts a component once all configuration data is available. - void MaybeStartComponent(PendingComponent* pending_component); + void MaybeStartComponent( + CastComponent::CastComponentParams* pending_component); // Holds StartComponent() requests while the ApplicationConfig is being // fetched from the ApplicationConfigManager. - base::flat_set<std::unique_ptr<PendingComponent>, base::UniquePtrComparator> + base::flat_set<std::unique_ptr<CastComponent::CastComponentParams>, + base::UniquePtrComparator> pending_components_; DISALLOW_COPY_AND_ASSIGN(CastRunner);
diff --git a/google_apis/drive/drive_api_requests_unittest.cc b/google_apis/drive/drive_api_requests_unittest.cc index 0c25281..06f54a9 100644 --- a/google_apis/drive/drive_api_requests_unittest.cc +++ b/google_apis/drive/drive_api_requests_unittest.cc
@@ -33,6 +33,7 @@ #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "services/network/network_service.h" #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" +#include "services/network/test/test_network_context_client.h" #include "services/network/test/test_network_service_client.h" #include "testing/gtest/include/gtest/gtest.h" @@ -140,6 +141,12 @@ network_service_ptr->SetClient(std::move(network_service_client_ptr), network::mojom::NetworkServiceParams::New()); + network::mojom::NetworkContextClientPtr network_context_client_ptr; + network_context_client_ = + std::make_unique<network::TestNetworkContextClient>( + mojo::MakeRequest(&network_context_client_ptr)); + network_context_->SetClient(std::move(network_context_client_ptr)); + network::mojom::URLLoaderFactoryParamsPtr params = network::mojom::URLLoaderFactoryParams::New(); params->process_id = network::mojom::kBrowserProcessId; @@ -219,6 +226,7 @@ std::unique_ptr<DriveApiUrlGenerator> url_generator_; std::unique_ptr<network::mojom::NetworkService> network_service_; std::unique_ptr<network::mojom::NetworkServiceClient> network_service_client_; + std::unique_ptr<network::mojom::NetworkContextClient> network_context_client_; network::mojom::NetworkContextPtr network_context_; network::mojom::URLLoaderFactoryPtr url_loader_factory_; scoped_refptr<network::WeakWrapperSharedURLLoaderFactory>
diff --git a/ios/chrome/browser/ui/webui/web_ui_egtest.mm b/ios/chrome/browser/ui/webui/web_ui_egtest.mm index e71c378..3baab248 100644 --- a/ios/chrome/browser/ui/webui/web_ui_egtest.mm +++ b/ios/chrome/browser/ui/webui/web_ui_egtest.mm
@@ -236,4 +236,26 @@ [ChromeEarlGrey waitForWebStateContainingText:kChromeVersionWebText]; } +- (void)testChromeFlags { + LoadWebUIUrl(kChromeUIFlagsHost); + + // Not using kChromeUIFlagsHost because it has a final "/" that is not + // displayed in Omnibox. + [[EarlGrey selectElementWithMatcher:WaitForOmniboxText("chrome://flags")] + assertWithMatcher:grey_notNil()]; + + // Validates that some of the expected text on the page exists. + [ChromeEarlGrey waitForWebStateContainingText:"Experiments"]; + [ChromeEarlGrey waitForWebStateContainingText:"Available"]; + + // Validates that the experimental flags container is visible. + NSError* error = nil; + id result = chrome_test_util::ExecuteJavaScript( + @"document.getElementById('body-container').style.visibility", &error); + GREYAssert(!error, @"JavaScript execution error"); + NSString* resultString = base::mac::ObjCCastStrict<NSString>(result); + GREYAssertEqualObjects(@"visible", resultString, + @"body-container is not visible"); +} + @end
diff --git a/mojo/core/ports/node.cc b/mojo/core/ports/node.cc index c895dee8..ec1e05c 100644 --- a/mojo/core/ports/node.cc +++ b/mojo/core/ports/node.cc
@@ -962,7 +962,8 @@ if (ack_request_event) delegate_->ForwardEvent(peer_node_name, std::move(ack_request_event)); - delegate_->PortStatusChanged(port_ref); + if (port_ref.is_valid()) + delegate_->PortStatusChanged(port_ref); return OK; }
diff --git a/net/quic/quic_flags_list.h b/net/quic/quic_flags_list.h index b181db9..8792f53 100644 --- a/net/quic/quic_flags_list.h +++ b/net/quic/quic_flags_list.h
@@ -406,3 +406,6 @@ // If true, no SPDY SETTINGS will be sent after handshake is confirmed. QUIC_FLAG(bool, FLAGS_quic_reloadable_flag_quic_do_not_send_settings, false) + +// The maximum amount of CRYPTO frame data that can be buffered. +QUIC_FLAG(int32_t, FLAGS_quic_max_buffered_crypto_bytes, 16 * 1024)
diff --git a/net/quic/quic_network_transaction_unittest.cc b/net/quic/quic_network_transaction_unittest.cc index e7c4ebf..da85df7 100644 --- a/net/quic/quic_network_transaction_unittest.cc +++ b/net/quic/quic_network_transaction_unittest.cc
@@ -398,10 +398,12 @@ uint64_t smallest_received, uint64_t least_unacked, quic::QuicErrorCode quic_error, - const std::string& quic_error_details) { + const std::string& quic_error_details, + uint64_t frame_type) { return client_maker_.MakeAckAndConnectionClosePacket( num, false, delta_time_largest_observed, largest_received, - smallest_received, least_unacked, quic_error, quic_error_details); + smallest_received, least_unacked, quic_error, quic_error_details, + frame_type); } std::unique_ptr<quic::QuicEncryptedPacket> ConstructServerRstPacket( @@ -3051,7 +3053,8 @@ quic_data.AddWrite( SYNCHRONOUS, ConstructClientAckAndConnectionClosePacket( packet_number++, quic::QuicTime::Delta::Zero(), 1, 1, 1, - quic::QUIC_INVALID_STREAM_ID, quic_error_details)); + quic::QUIC_INVALID_STREAM_ID, quic_error_details, + quic::IETF_RST_STREAM)); quic_data.AddSocketDataToFactory(&socket_factory_); // In order for a new QUIC session to be established via alternate-protocol @@ -3434,7 +3437,7 @@ SYNCHRONOUS, client_maker_.MakeAckAndConnectionClosePacket( 12, false, quic::QuicTime::Delta::FromMilliseconds(4000), 1, 1, 1, - quic::QUIC_NETWORK_IDLE_TIMEOUT, "No recent network activity.")); + quic::QUIC_NETWORK_IDLE_TIMEOUT, "No recent network activity.", 0)); } else { // Settings were sent in the request packet so there is only 1 packet to // retransmit. @@ -3468,7 +3471,7 @@ SYNCHRONOUS, client_maker_.MakeAckAndConnectionClosePacket( 8, false, quic::QuicTime::Delta::FromMilliseconds(4000), 1, 1, 1, - quic::QUIC_NETWORK_IDLE_TIMEOUT, "No recent network activity.")); + quic::QUIC_NETWORK_IDLE_TIMEOUT, "No recent network activity.", 0)); } quic_data.AddRead(ASYNC, ERR_IO_PENDING); @@ -3847,7 +3850,8 @@ quic_data.AddWrite( SYNCHRONOUS, ConstructClientAckAndConnectionClosePacket( packet_number++, quic::QuicTime::Delta::Zero(), 1, 1, 1, - quic::QUIC_INVALID_STREAM_ID, quic_error_details)); + quic::QUIC_INVALID_STREAM_ID, quic_error_details, + quic::IETF_RST_STREAM)); quic_data.AddSocketDataToFactory(&socket_factory_); // After that fails, it will be resent via TCP. @@ -5271,10 +5275,11 @@ 1, false, GetNthClientInitiatedBidirectionalStreamId(47), quic::QUIC_STREAM_LAST_ERROR)); std::string quic_error_details = "Data for nonexistent stream"; - mock_quic_data.AddWrite( - SYNCHRONOUS, ConstructClientAckAndConnectionClosePacket( - 3, quic::QuicTime::Delta::Zero(), 1, 1, 1, - quic::QUIC_INVALID_STREAM_ID, quic_error_details)); + mock_quic_data.AddWrite(SYNCHRONOUS, + ConstructClientAckAndConnectionClosePacket( + 3, quic::QuicTime::Delta::Zero(), 1, 1, 1, + quic::QUIC_INVALID_STREAM_ID, quic_error_details, + quic::IETF_RST_STREAM)); mock_quic_data.AddSocketDataToFactory(&socket_factory_); // The non-alternate protocol job needs to hang in order to guarantee that @@ -6027,7 +6032,7 @@ socket_data.AddWrite( SYNCHRONOUS, client_maker_.MakeAckAndConnectionClosePacket( 4, false, quic::QuicTime::Delta::FromMilliseconds(0), 2, - 1, 1, quic::QUIC_CONNECTION_CANCELLED, "net error")); + 1, 1, quic::QUIC_CONNECTION_CANCELLED, "net error", 0)); socket_data.AddSocketDataToFactory(&socket_factory_); @@ -6062,7 +6067,7 @@ socket_data.AddWrite( SYNCHRONOUS, client_maker_.MakeAckAndConnectionClosePacket( 4, false, quic::QuicTime::Delta::FromMilliseconds(0), 2, - 1, 1, quic::QUIC_CONNECTION_CANCELLED, "net error")); + 1, 1, quic::QUIC_CONNECTION_CANCELLED, "net error", 0)); socket_data.AddSocketDataToFactory(&socket_factory_);
diff --git a/net/quic/quic_test_packet_maker.cc b/net/quic/quic_test_packet_maker.cc index ac77c23e..9008a009 100644 --- a/net/quic/quic_test_packet_maker.cc +++ b/net/quic/quic_test_packet_maker.cc
@@ -506,7 +506,8 @@ uint64_t smallest_received, uint64_t least_unacked, quic::QuicErrorCode quic_error, - const std::string& quic_error_details) { + const std::string& quic_error_details, + uint64_t frame_type) { InitializeHeader(num, include_version); quic::QuicAckFrame ack(MakeAckFrame(largest_received)); @@ -528,6 +529,7 @@ close.error_details = MaybePrependErrorCode(quic_error_details, quic_error); if (version_.transport_version == quic::QUIC_VERSION_99) { close.close_type = quic::IETF_QUIC_TRANSPORT_CONNECTION_CLOSE; + close.transport_close_frame_type = frame_type; } frames.push_back(quic::QuicFrame(&close));
diff --git a/net/quic/quic_test_packet_maker.h b/net/quic/quic_test_packet_maker.h index 62c408e..13e48563 100644 --- a/net/quic/quic_test_packet_maker.h +++ b/net/quic/quic_test_packet_maker.h
@@ -142,7 +142,8 @@ uint64_t smallest_received, uint64_t least_unacked, quic::QuicErrorCode quic_error, - const std::string& quic_error_details); + const std::string& quic_error_details, + uint64_t frame_type); std::unique_ptr<quic::QuicReceivedPacket> MakeConnectionClosePacket( uint64_t num, bool include_version,
diff --git a/net/socket/ssl_client_socket_unittest.cc b/net/socket/ssl_client_socket_unittest.cc index 6c6452c..95421dc 100644 --- a/net/socket/ssl_client_socket_unittest.cc +++ b/net/socket/ssl_client_socket_unittest.cc
@@ -5440,8 +5440,15 @@ SSLConnectionStatusToVersion(info.connection_status)); } +// Failed on Android builder. See https://crbug.com/999647 +#if defined(OS_ANDROID) +#define MAYBE_TLS13DowngradeEnforcedKnownKnown \ + DISABLED_TLS13DowngradeEnforcedKnownKnown +#else +#define MAYBE_TLS13DowngradeEnforcedKnownKnown TLS13DowngradeEnforcedKnownKnown +#endif // Test downgrade enforcement enforces known roots when configured to. -TEST_F(SSLClientSocketTest, TLS13DowngradeEnforcedKnownKnown) { +TEST_F(SSLClientSocketTest, MAYBE_TLS13DowngradeEnforcedKnownKnown) { base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeatureWithParameters( features::kEnforceTLS13Downgrade, {{"known_roots_only", "true"}});
diff --git a/services/media_session/audio_focus_manager.cc b/services/media_session/audio_focus_manager.cc index 654a3c3..b5abcdf 100644 --- a/services/media_session/audio_focus_manager.cc +++ b/services/media_session/audio_focus_manager.cc
@@ -56,6 +56,39 @@ DISALLOW_COPY_AND_ASSIGN(MediaPowerDelegate); }; +class AudioFocusManager::SourceObserverHolder { + public: + SourceObserverHolder(AudioFocusManager* owner, + const base::UnguessableToken& source_id, + mojo::PendingRemote<mojom::AudioFocusObserver> observer) + : identity_(source_id), observer_(std::move(observer)) { + // Set a connection error handler so that we will remove observers that have + // had an error / been closed. + observer_.set_connection_error_handler(base::BindOnce( + &AudioFocusManager::CleanupSourceObservers, base::Unretained(owner))); + } + + ~SourceObserverHolder() = default; + + bool is_valid() const { return !observer_.encountered_error(); } + + const base::UnguessableToken& identity() const { return identity_; } + + void OnFocusGained(mojom::AudioFocusRequestStatePtr session) { + observer_->OnFocusGained(std::move(session)); + } + + void OnFocusLost(mojom::AudioFocusRequestStatePtr session) { + observer_->OnFocusLost(std::move(session)); + } + + private: + const base::UnguessableToken identity_; + mojom::AudioFocusObserverPtr observer_; + + DISALLOW_COPY_AND_ASSIGN(SourceObserverHolder); +}; + void AudioFocusManager::RequestAudioFocus( mojo::PendingReceiver<mojom::AudioFocusRequestClient> receiver, mojo::PendingRemote<mojom::MediaSession> media_session, @@ -158,6 +191,11 @@ for (const auto& observer : observers_) observer->OnFocusLost(session_state.Clone()); + for (auto& holder : source_observers_) { + if (holder->identity() == row->identity()) + holder->OnFocusLost(session_state.Clone()); + } + if (!was_top_most_session || audio_focus_stack_.empty()) return; @@ -166,6 +204,11 @@ for (const auto& observer : observers_) observer->OnFocusGained(new_session->ToAudioFocusRequestState()); + + for (auto& holder : source_observers_) { + if (holder->identity() == new_session->identity()) + holder->OnFocusGained(new_session->ToAudioFocusRequestState()); + } } void AudioFocusManager::AddObserver( @@ -198,6 +241,27 @@ EnforceAudioFocus(); } +void AudioFocusManager::AddSourceObserver( + const base::UnguessableToken& source_id, + mojo::PendingRemote<mojom::AudioFocusObserver> observer) { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + source_observers_.push_back(std::make_unique<SourceObserverHolder>( + this, source_id, std::move(observer))); +} + +void AudioFocusManager::GetSourceFocusRequests( + const base::UnguessableToken& source_id, + GetFocusRequestsCallback callback) { + std::vector<mojom::AudioFocusRequestStatePtr> requests; + + for (const auto& row : audio_focus_stack_) { + if (row->identity() == source_id) + requests.push_back(row->ToAudioFocusRequestState()); + } + + std::move(callback).Run(std::move(requests)); +} + void AudioFocusManager::CreateActiveMediaController( mojo::PendingReceiver<mojom::MediaController> receiver) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); @@ -245,6 +309,7 @@ void AudioFocusManager::RequestAudioFocusInternal( std::unique_ptr<AudioFocusRequest> row, mojom::AudioFocusType type) { + const auto& identity = row->identity(); row->set_audio_focus_type(type); audio_focus_stack_.push_back(std::move(row)); @@ -256,6 +321,11 @@ audio_focus_stack_.back()->ToAudioFocusRequestState(); for (const auto& observer : observers_) observer->OnFocusGained(session_state.Clone()); + + for (auto& holder : source_observers_) { + if (holder->identity() == identity) + holder->OnFocusGained(session_state.Clone()); + } } void AudioFocusManager::EnforceAudioFocus() { @@ -415,4 +485,9 @@ } } +void AudioFocusManager::CleanupSourceObservers() { + base::EraseIf(source_observers_, + [](const auto& holder) { return !holder->is_valid(); }); +} + } // namespace media_session
diff --git a/services/media_session/audio_focus_manager.h b/services/media_session/audio_focus_manager.h index 8252577..2e26176 100644 --- a/services/media_session/audio_focus_manager.h +++ b/services/media_session/audio_focus_manager.h
@@ -8,6 +8,7 @@ #include <list> #include <string> #include <unordered_map> +#include <vector> #include "base/memory/weak_ptr.h" #include "base/threading/thread_checker.h" @@ -69,6 +70,11 @@ void SetSource(const base::UnguessableToken& identity, const std::string& name) override; void SetEnforcementMode(mojom::EnforcementMode mode) override; + void AddSourceObserver( + const base::UnguessableToken& source_id, + mojo::PendingRemote<mojom::AudioFocusObserver> observer) override; + void GetSourceFocusRequests(const base::UnguessableToken& source_id, + GetFocusRequestsCallback callback) override; // mojom::AudioFocusManagerDebug. void GetDebugInfoForRequest(const RequestId& request_id, @@ -98,6 +104,8 @@ friend class MediaControllerTest; friend class test::MockMediaSession; + class SourceObserverHolder; + // BindingContext stores associated metadata for mojo binding. struct BindingContext { // The source name is associated with a binding when a client calls @@ -141,6 +149,9 @@ void EnforceSingleSession(AudioFocusRequest* session, const EnforcementState& state); + // Removes unbound or faulty source observers. + void CleanupSourceObservers(); + // This |MediaController| acts as a proxy for controlling the active // |MediaSession| over mojo. MediaController active_media_controller_; @@ -159,6 +170,9 @@ // themselves before being destroyed. mojo::RemoteSet<mojom::AudioFocusObserver> observers_; + // Manages individual source observers. + std::vector<std::unique_ptr<SourceObserverHolder>> source_observers_; + // A stack of Mojo interface pointers and their requested audio focus type. // A MediaSession must abandon audio focus before its destruction. std::list<std::unique_ptr<AudioFocusRequest>> audio_focus_stack_;
diff --git a/services/media_session/audio_focus_manager_unittest.cc b/services/media_session/audio_focus_manager_unittest.cc index 49695c47..b532745 100644 --- a/services/media_session/audio_focus_manager_unittest.cc +++ b/services/media_session/audio_focus_manager_unittest.cc
@@ -156,6 +156,18 @@ return observer; } + std::unique_ptr<test::TestAudioFocusObserver> CreateSourceObserver( + const base::UnguessableToken& source_id) { + std::unique_ptr<test::TestAudioFocusObserver> observer = + std::make_unique<test::TestAudioFocusObserver>(); + + GetService()->AddSourceObserver(source_id, + observer->BindNewPipeAndPassRemote()); + + audio_focus_remote_.FlushForTesting(); + return observer; + } + mojom::MediaSessionInfo::SessionState GetStateFromParam( mojom::MediaSessionInfo::SessionState state) { // If enforcement is enabled then returns the provided state, otherwise @@ -205,12 +217,31 @@ return controller_manager_remote_; } + std::vector<mojom::AudioFocusRequestStatePtr> GetSourceFocusRequests( + const base::UnguessableToken& source_id) { + std::vector<mojom::AudioFocusRequestStatePtr> result; + + GetService()->GetSourceFocusRequests( + source_id, + base::BindOnce( + [](std::vector<mojom::AudioFocusRequestStatePtr>* out, + std::vector<mojom::AudioFocusRequestStatePtr> requests) { + *out = std::move(requests); + }, + &result)); + + audio_focus_remote_.FlushForTesting(); + return result; + } + const base::UnguessableToken& GetIdentityForLastRequest() const { return service_->audio_focus_manager_for_testing() .audio_focus_stack_.back() ->identity(); } + void FlushForTesting() { audio_focus_remote_.FlushForTesting(); } + private: int GetCountForType(mojom::AudioFocusType type) { const auto audio_focus_requests = GetRequests(); @@ -1624,4 +1655,102 @@ EXPECT_EQ(request_id, GetAudioFocusedSession()); } +TEST_P(AudioFocusManagerTest, SourceObservers) { + // Create two identity observers for two different identities. + base::UnguessableToken identity_1 = base::UnguessableToken::Create(); + base::UnguessableToken identity_2 = base::UnguessableToken::Create(); + std::unique_ptr<test::TestAudioFocusObserver> observer_1 = + CreateSourceObserver(identity_1); + std::unique_ptr<test::TestAudioFocusObserver> observer_2 = + CreateSourceObserver(identity_2); + + // Request audio focus for the first identity. + SetSource(identity_1, kExampleSourceName); + test::MockMediaSession media_session_1; + base::UnguessableToken request_id_1 = + RequestAudioFocus(&media_session_1, mojom::AudioFocusType::kGain); + + // The observer for the first identity should see the gained focus, while the + // observer for the second identity should see nothing. + EXPECT_EQ(request_id_1, observer_1->focus_gained_session()->request_id); + EXPECT_TRUE(observer_2->focus_gained_session().is_null()); + + // Request audio focus for the second identity. + SetSource(identity_2, kExampleSourceName); + test::MockMediaSession media_session_2; + base::UnguessableToken request_id_2 = + RequestAudioFocus(&media_session_2, mojom::AudioFocusType::kGain); + + // The observer for the first identity should still show the first request, + // while the observer for the second identity should see the new session. + EXPECT_EQ(request_id_1, observer_1->focus_gained_session()->request_id); + EXPECT_EQ(request_id_2, observer_2->focus_gained_session()->request_id); + + // Make another request in the second identity. + test::MockMediaSession media_session_3; + base::UnguessableToken request_id_3 = + RequestAudioFocus(&media_session_3, mojom::AudioFocusType::kGain); + + // The observer for the first identity should still show the first request, + // while the observer for the second identity should see the new session. + EXPECT_EQ(request_id_1, observer_1->focus_gained_session()->request_id); + EXPECT_EQ(request_id_3, observer_2->focus_gained_session()->request_id); + + // Abandon the topmost session. + media_session_3.AbandonAudioFocusFromClient(); + FlushForTesting(); + + // The observer for the second identity should get the new lost and gained + // sessions, with no updates to the first observer. + EXPECT_EQ(request_id_3, observer_2->focus_lost_session()->request_id); + EXPECT_EQ(request_id_2, observer_2->focus_gained_session()->request_id); + EXPECT_EQ(request_id_1, observer_1->focus_gained_session()->request_id); + EXPECT_TRUE(observer_1->focus_lost_session().is_null()); +} + +TEST_P(AudioFocusManagerTest, GetSourceFocusRequests) { + // Establish identities. + base::UnguessableToken identity_1 = base::UnguessableToken::Create(); + base::UnguessableToken identity_2 = base::UnguessableToken::Create(); + base::UnguessableToken identity_3 = base::UnguessableToken::Create(); + + // Create a focus request for the first identity. + SetSource(identity_1, kExampleSourceName); + test::MockMediaSession media_session_1; + base::UnguessableToken request_id_1 = + RequestAudioFocus(&media_session_1, mojom::AudioFocusType::kGain); + + // Create a focus request for the second identity. + SetSource(identity_2, kExampleSourceName); + test::MockMediaSession media_session_2; + base::UnguessableToken request_id_2 = + RequestAudioFocus(&media_session_2, mojom::AudioFocusType::kGain); + + // Create another focus request for the first identity. + SetSource(identity_1, kExampleSourceName); + test::MockMediaSession media_session_3; + base::UnguessableToken request_id_3 = + RequestAudioFocus(&media_session_3, mojom::AudioFocusType::kGain); + + // Use the GetSourceFocusRequests API to get requests for each identity. + std::vector<mojom::AudioFocusRequestStatePtr> identity_1_requests = + GetSourceFocusRequests(identity_1); + std::vector<mojom::AudioFocusRequestStatePtr> identity_2_requests = + GetSourceFocusRequests(identity_2); + std::vector<mojom::AudioFocusRequestStatePtr> identity_3_requests = + GetSourceFocusRequests(identity_3); + + // Ensure that the API returned the right requests for the first identity. + EXPECT_EQ(2u, identity_1_requests.size()); + EXPECT_EQ(request_id_1, identity_1_requests[0]->request_id); + EXPECT_EQ(request_id_3, identity_1_requests[1]->request_id); + + // Ensure that the API returned the right requests for the second identity. + EXPECT_EQ(1u, identity_2_requests.size()); + EXPECT_EQ(request_id_2, identity_2_requests[0]->request_id); + + // Ensure that the API returned nothing for the unused identity. + EXPECT_TRUE(identity_3_requests.empty()); +} + } // namespace media_session
diff --git a/services/media_session/public/mojom/audio_focus.mojom b/services/media_session/public/mojom/audio_focus.mojom index 7086a8ad..45e04a4 100644 --- a/services/media_session/public/mojom/audio_focus.mojom +++ b/services/media_session/public/mojom/audio_focus.mojom
@@ -7,7 +7,7 @@ import "mojo/public/mojom/base/unguessable_token.mojom"; import "services/media_session/public/mojom/media_session.mojom"; -// Next MinVersion: 7 +// Next MinVersion: 8 // These are the different modes the AudioFocusManager can enforce audio focus. [Extensible] @@ -90,7 +90,7 @@ // Controls audio focus across the entire system. After binding // AudioFocusManager clients should call SetSource to identify themselves to // the media session service. -// Next Method ID: 7 +// Next Method ID: 9 // Deprecated method IDs: 3 interface AudioFocusManager { // Requests audio focus with |type| for the |media_session| with @@ -137,6 +137,18 @@ // Sets the enforcement mode for the Audio Focus Manager. [MinVersion=5] SetEnforcementMode@5(EnforcementMode mode); + + // Adds observers that receive audio focus events only for their associated + // source. + [MinVersion=7] AddSourceObserver@7( + mojo_base.mojom.UnguessableToken source_id, + pending_remote<AudioFocusObserver> observer); + + // Gets all the information about all |MediaSessions| that have requested + // audio focus and their current requested type for the given source. + [MinVersion=7] GetSourceFocusRequests@8( + mojo_base.mojom.UnguessableToken source_id) + => (array<AudioFocusRequestState> requests); }; // Provides debug information about audio focus requests.
diff --git a/services/network/BUILD.gn b/services/network/BUILD.gn index e0a1d73..b000b4e 100644 --- a/services/network/BUILD.gn +++ b/services/network/BUILD.gn
@@ -423,6 +423,7 @@ "test/test_network_connection_tracker.cc", "test/test_network_connection_tracker.h", "test/test_network_context.h", + "test/test_network_context_client.cc", "test/test_network_context_client.h", "test/test_network_quality_tracker.cc", "test/test_network_quality_tracker.h",
diff --git a/services/network/public/cpp/simple_url_loader_unittest.cc b/services/network/public/cpp/simple_url_loader_unittest.cc index cb943f0..80f1f1a5 100644 --- a/services/network/public/cpp/simple_url_loader_unittest.cc +++ b/services/network/public/cpp/simple_url_loader_unittest.cc
@@ -50,6 +50,7 @@ #include "services/network/public/cpp/url_loader_completion_status.h" #include "services/network/public/mojom/network_service.mojom.h" #include "services/network/public/mojom/url_loader_factory.mojom.h" +#include "services/network/test/test_network_context_client.h" #include "services/network/test/test_network_service_client.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" @@ -586,6 +587,11 @@ network_service_ptr->SetClient(std::move(network_service_client_ptr), network::mojom::NetworkServiceParams::New()); + network::mojom::NetworkContextClientPtr network_context_client_ptr; + network_context_client_ = std::make_unique<TestNetworkContextClient>( + mojo::MakeRequest(&network_context_client_ptr)); + network_context_->SetClient(std::move(network_context_client_ptr)); + mojom::URLLoaderFactoryParamsPtr params = mojom::URLLoaderFactoryParams::New(); params->process_id = mojom::kBrowserProcessId; @@ -631,6 +637,7 @@ std::unique_ptr<network::mojom::NetworkService> network_service_; std::unique_ptr<network::mojom::NetworkServiceClient> network_service_client_; + std::unique_ptr<network::mojom::NetworkContextClient> network_context_client_; network::mojom::NetworkContextPtr network_context_; network::mojom::URLLoaderFactoryPtr url_loader_factory_;
diff --git a/services/network/public/mojom/network_context.mojom b/services/network/public/mojom/network_context.mojom index 0edfa89..d5a30e8 100644 --- a/services/network/public/mojom/network_context.mojom +++ b/services/network/public/mojom/network_context.mojom
@@ -5,6 +5,7 @@ module network.mojom; import "mojo/public/mojom/base/big_buffer.mojom"; +import "mojo/public/mojom/base/file.mojom"; import "mojo/public/mojom/base/file_path.mojom"; import "mojo/public/mojom/base/time.mojom"; import "mojo/public/mojom/base/unguessable_token.mojom"; @@ -624,6 +625,19 @@ SSLInfo ssl_info, bool fatal) => (int32 net_error); + // Called when file uploading was requested. + // If the process that requested the uploads has permission to read all of + // the files referenced by |file_paths|, the callback arguments will be + // net::OK, along with an array of open file handles. The array will contain + // exactly one handle for each path in |file_paths|, in the same order. + // If any files referenced by |file_paths| cannot be read, a net::ERROR will + // be returned, and |files| will be an empty list. If the |async| parameter + // is true, the files will be opened with FLAG_ASYNC. + OnFileUploadRequested(uint32 process_id, + bool async, + array<mojo_base.mojom.FilePath> file_paths) => + (int32 net_error, array<mojo_base.mojom.File> files); + // Checks if network error reports could be sent for the given origins. // Replies with the origins that are allowed. OnCanSendReportingReports(array<url.mojom.Origin> origins) =>
diff --git a/services/network/public/mojom/network_service.mojom b/services/network/public/mojom/network_service.mojom index 1295248..1661bea7 100644 --- a/services/network/public/mojom/network_service.mojom +++ b/services/network/public/mojom/network_service.mojom
@@ -41,19 +41,6 @@ // Network service interface to the browser. interface NetworkServiceClient { - // Called when file uploading was requested. - // If the process that requested the uploads has permission to read all of - // the files referenced by |file_paths|, the callback arguments will be - // net::OK, along with an array of open file handles. The array will contain - // exactly one handle for each path in |file_paths|, in the same order. - // If any files referenced by |file_paths| cannot be read, a net::ERROR will - // be returned, and |files| will be an empty list. If the |async| parameter - // is true, the files will be opened with FLAG_ASYNC. - OnFileUploadRequested(uint32 process_id, - bool async, - array<mojo_base.mojom.FilePath> file_paths) => - (int32 net_error, array<mojo_base.mojom.File> files); - // Called periodically to update the client about progress of the current // loads. To avoid flooding the client, it has to ack the update before it can // receive the next update.
diff --git a/services/network/test/test_network_context_client.cc b/services/network/test/test_network_context_client.cc new file mode 100644 index 0000000..fffe1dc --- /dev/null +++ b/services/network/test/test_network_context_client.cc
@@ -0,0 +1,55 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "services/network/test/test_network_context_client.h" + +#include <utility> + +#include "base/optional.h" +#include "base/task/post_task.h" +#include "base/threading/thread_restrictions.h" +#include "net/base/net_errors.h" + +namespace network { + +TestNetworkContextClient::TestNetworkContextClient() : binding_(nullptr) {} + +TestNetworkContextClient::TestNetworkContextClient( + mojom::NetworkContextClientRequest request) + : binding_(this, std::move(request)) {} + +TestNetworkContextClient::~TestNetworkContextClient() {} + +void TestNetworkContextClient::OnFileUploadRequested( + uint32_t process_id, + bool async, + const std::vector<base::FilePath>& file_paths, + OnFileUploadRequestedCallback callback) { + if (upload_files_invalid_) { + std::move(callback).Run(net::ERR_ACCESS_DENIED, std::vector<base::File>()); + return; + } + base::ScopedAllowBlockingForTesting allow_blocking; + uint32_t file_flags = base::File::FLAG_OPEN | base::File::FLAG_READ | + (async ? base::File::FLAG_ASYNC : 0); + std::vector<base::File> files; + for (base::FilePath path : file_paths) { + files.emplace_back(path, file_flags); + if (!files.back().IsValid()) { + std::move(callback).Run( + net::FileErrorToNetError(files.back().error_details()), + std::vector<base::File>()); + return; + } + } + + if (ignore_last_upload_file_) { + // Make the TestNetworkServiceClient respond one less file as requested. + files.pop_back(); + } + + std::move(callback).Run(net::OK, std::move(files)); +} + +} // namespace network
diff --git a/services/network/test/test_network_context_client.h b/services/network/test/test_network_context_client.h index 49f6f3f3..1c22c745 100644 --- a/services/network/test/test_network_context_client.h +++ b/services/network/test/test_network_context_client.h
@@ -7,7 +7,7 @@ #include "build/build_config.h" #include "mojo/public/cpp/bindings/binding.h" -#include "services/network/public/mojom/network_service.mojom.h" +#include "services/network/public/mojom/network_context.mojom.h" namespace network { @@ -15,8 +15,16 @@ // unittests, so they can just override the parts they need. class TestNetworkContextClient : public network::mojom::NetworkContextClient { public: - TestNetworkContextClient() = default; - ~TestNetworkContextClient() override = default; + TestNetworkContextClient(); + explicit TestNetworkContextClient(mojom::NetworkContextClientRequest request); + ~TestNetworkContextClient() override; + + void set_upload_files_invalid(bool upload_files_invalid) { + upload_files_invalid_ = upload_files_invalid; + } + void set_ignore_last_upload_file(bool ignore_last_upload_file) { + ignore_last_upload_file_ = ignore_last_upload_file; + } void OnAuthRequired( const base::Optional<base::UnguessableToken>& window_id, @@ -26,7 +34,7 @@ const GURL& url, bool first_auth_attempt, const net::AuthChallengeInfo& auth_info, - mojom::URLResponseHeadPtr head, + network::mojom::URLResponseHeadPtr head, mojom::AuthChallengeResponderPtr auth_challenge_responder) override {} void OnCertificateRequested( const base::Optional<base::UnguessableToken>& window_id, @@ -42,6 +50,10 @@ const net::SSLInfo& ssl_info, bool fatal, OnSSLCertificateErrorCallback response) override {} + void OnFileUploadRequested(uint32_t process_id, + bool async, + const std::vector<base::FilePath>& file_paths, + OnFileUploadRequestedCallback callback) override; void OnCanSendReportingReports( const std::vector<url::Origin>& origins, OnCanSendReportingReportsCallback callback) override {} @@ -79,6 +91,11 @@ #if defined(OS_CHROMEOS) void OnTrustAnchorUsed() override {} #endif + + private: + mojo::Binding<mojom::NetworkContextClient> binding_; + bool upload_files_invalid_ = false; + bool ignore_last_upload_file_ = false; }; } // namespace network
diff --git a/services/network/test/test_network_service_client.cc b/services/network/test/test_network_service_client.cc index 664f7dbf..44f5f84f 100644 --- a/services/network/test/test_network_service_client.cc +++ b/services/network/test/test_network_service_client.cc
@@ -20,37 +20,6 @@ TestNetworkServiceClient::~TestNetworkServiceClient() {} -void TestNetworkServiceClient::OnFileUploadRequested( - uint32_t process_id, - bool async, - const std::vector<base::FilePath>& file_paths, - OnFileUploadRequestedCallback callback) { - if (upload_files_invalid_) { - std::move(callback).Run(net::ERR_ACCESS_DENIED, std::vector<base::File>()); - return; - } - base::ScopedAllowBlockingForTesting allow_blocking; - uint32_t file_flags = base::File::FLAG_OPEN | base::File::FLAG_READ | - (async ? base::File::FLAG_ASYNC : 0); - std::vector<base::File> files; - for (base::FilePath path : file_paths) { - files.emplace_back(path, file_flags); - if (!files.back().IsValid()) { - std::move(callback).Run( - net::FileErrorToNetError(files.back().error_details()), - std::vector<base::File>()); - return; - } - } - - if (ignore_last_upload_file_) { - // Make the TestNetworkServiceClient respond one less file as requested. - files.pop_back(); - } - - std::move(callback).Run(net::OK, std::move(files)); -} - void TestNetworkServiceClient::OnLoadingStateUpdate( std::vector<mojom::LoadInfoPtr> infos, OnLoadingStateUpdateCallback callback) {}
diff --git a/services/network/test/test_network_service_client.h b/services/network/test/test_network_service_client.h index e4f642a..9bda9be 100644 --- a/services/network/test/test_network_service_client.h +++ b/services/network/test/test_network_service_client.h
@@ -24,18 +24,7 @@ explicit TestNetworkServiceClient(mojom::NetworkServiceClientRequest request); ~TestNetworkServiceClient() override; - void set_upload_files_invalid(bool upload_files_invalid) { - upload_files_invalid_ = upload_files_invalid; - } - void set_ignore_last_upload_file(bool ignore_last_upload_file) { - ignore_last_upload_file_ = ignore_last_upload_file; - } - // network::mojom::NetworkServiceClient implementation: - void OnFileUploadRequested(uint32_t process_id, - bool async, - const std::vector<base::FilePath>& file_paths, - OnFileUploadRequestedCallback callback) override; void OnLoadingStateUpdate(std::vector<mojom::LoadInfoPtr> infos, OnLoadingStateUpdateCallback callback) override; void OnDataUseUpdate(int32_t network_traffic_annotation_id_hash, @@ -56,8 +45,6 @@ const base::Optional<std::string>& raw_response_headers) override; private: - bool upload_files_invalid_ = false; - bool ignore_last_upload_file_ = false; mojo::Binding<mojom::NetworkServiceClient> binding_; DISALLOW_COPY_AND_ASSIGN(TestNetworkServiceClient);
diff --git a/services/network/test/test_shared_url_loader_factory.h b/services/network/test/test_shared_url_loader_factory.h index 2e2d46b..8750e83 100644 --- a/services/network/test/test_shared_url_loader_factory.h +++ b/services/network/test/test_shared_url_loader_factory.h
@@ -41,6 +41,8 @@ // SharedURLLoaderFactoryInfo implementation std::unique_ptr<SharedURLLoaderFactoryInfo> Clone() override; + NetworkContext* network_context() { return network_context_.get(); } + private: friend class base::RefCounted<TestSharedURLLoaderFactory>; ~TestSharedURLLoaderFactory() override;
diff --git a/services/network/url_loader.cc b/services/network/url_loader.cc index c1ea0bc02..5f3aef1 100644 --- a/services/network/url_loader.cc +++ b/services/network/url_loader.cc
@@ -493,12 +493,12 @@ FileOpenerForUpload(std::vector<base::FilePath> paths, URLLoader* url_loader, uint32_t process_id, - mojom::NetworkServiceClient* network_service_client, + mojom::NetworkContextClient* const network_context_client, SetUpUploadCallback set_up_upload_callback) : paths_(std::move(paths)), url_loader_(url_loader), process_id_(process_id), - network_service_client_(network_service_client), + network_context_client_(network_context_client), set_up_upload_callback_(std::move(set_up_upload_callback)) { StartOpeningNextBatch(); } @@ -558,7 +558,7 @@ paths_.begin() + opened_files_.size(), paths_.begin() + opened_files_.size() + num_files_to_request); - network_service_client_->OnFileUploadRequested( + network_context_client_->OnFileUploadRequested( process_id_, /*async=*/true, batch_paths, base::BindOnce(&FileOpenerForUpload::OnFilesForUploadOpened, weak_ptr_factory_.GetWeakPtr(), num_files_to_request)); @@ -577,7 +577,7 @@ const std::vector<base::FilePath> paths_; URLLoader* const url_loader_; const uint32_t process_id_; - mojom::NetworkServiceClient* const network_service_client_; + mojom::NetworkContextClient* const network_context_client_; SetUpUploadCallback set_up_upload_callback_; // The files opened so far. std::vector<base::File> opened_files_; @@ -597,7 +597,9 @@ SetUpUpload(request, net::OK, std::vector<base::File>()); return; } - if (!network_service_client_) { + if (!network_context_client_) { + DLOG(ERROR) << "URLLoader couldn't upload a file because no " + "NetworkContextClient is set."; // Defer calling NotifyCompleted to make sure the URLLoader finishes // initializing before getting deleted. base::SequencedTaskRunnerHandle::Get()->PostTask( @@ -609,7 +611,7 @@ url_request_->LogBlockedBy("Opening Files"); file_opener_for_upload_ = std::make_unique<FileOpenerForUpload>( std::move(paths), this, factory_params_->process_id, - network_service_client_, + network_context_client_, base::BindOnce(&URLLoader::SetUpUpload, base::Unretained(this), request)); }
diff --git a/services/network/url_loader_unittest.cc b/services/network/url_loader_unittest.cc index 9f8f162..02008ff 100644 --- a/services/network/url_loader_unittest.cc +++ b/services/network/url_loader_unittest.cc
@@ -451,11 +451,11 @@ if (send_ssl_for_cert_error_) options |= mojom::kURLLoadOptionSendSSLInfoForCertificateError; - std::unique_ptr<TestNetworkServiceClient> network_service_client; + std::unique_ptr<TestNetworkContextClient> network_context_client; if (allow_file_uploads_) { - network_service_client = std::make_unique<TestNetworkServiceClient>(); - network_service_client->set_upload_files_invalid(upload_files_invalid_); - network_service_client->set_ignore_last_upload_file( + network_context_client = std::make_unique<TestNetworkContextClient>(); + network_context_client->set_upload_files_invalid(upload_files_invalid_); + network_context_client->set_ignore_last_upload_file( ignore_last_upload_file_); } @@ -469,8 +469,8 @@ params.process_id = mojom::kBrowserProcessId; params.is_corb_enabled = false; url_loader = std::make_unique<URLLoader>( - context(), network_service_client.get(), - nullptr /* network_context_client */, + context(), nullptr /* network_service_client */, + network_context_client.get(), DeleteLoaderCallback(&delete_run_loop, &url_loader), mojo::MakeRequest(&loader), options, request, client_.CreateInterfacePtr(), TRAFFIC_ANNOTATION_FOR_TESTS, ¶ms, @@ -1563,7 +1563,7 @@ EXPECT_EQ(net::ERR_ACCESS_DENIED, Load(test_server()->GetURL("/echo"))); } -class CallbackSavingNetworkServiceClient : public TestNetworkServiceClient { +class CallbackSavingNetworkContextClient : public TestNetworkContextClient { public: void OnFileUploadRequested(uint32_t process_id, bool async, @@ -1608,11 +1608,11 @@ static mojom::URLLoaderFactoryParams params; params.process_id = mojom::kBrowserProcessId; params.is_corb_enabled = false; - auto network_service_client = - std::make_unique<CallbackSavingNetworkServiceClient>(); + auto network_context_client = + std::make_unique<CallbackSavingNetworkContextClient>(); std::unique_ptr<URLLoader> url_loader = std::make_unique<URLLoader>( - context(), network_service_client.get(), - nullptr /* network_context_client */, + context(), nullptr /* network_service_client */, + network_context_client.get(), DeleteLoaderCallback(&delete_run_loop, &url_loader), mojo::MakeRequest(&loader), 0, request, client()->CreateInterfacePtr(), TRAFFIC_ANNOTATION_FOR_TESTS, ¶ms, 0 /* request_id */, @@ -1620,8 +1620,8 @@ nullptr /* network_usage_accumulator */, nullptr /* header_client */, nullptr /* origin_policy_manager */); - mojom::NetworkServiceClient::OnFileUploadRequestedCallback callback; - network_service_client->RunUntilUploadRequested(&callback); + mojom::NetworkContextClient::OnFileUploadRequestedCallback callback; + network_context_client->RunUntilUploadRequested(&callback); // Check we can call the callback from a deleted URLLoader without crashing. url_loader.reset();
diff --git a/testing/buildbot/chromium.android.json b/testing/buildbot/chromium.android.json index e1460ea..1cd2e7c 100644 --- a/testing/buildbot/chromium.android.json +++ b/testing/buildbot/chromium.android.json
@@ -843,8 +843,7 @@ "args": [ "--disable-field-trials", "--gs-results-bucket=chromium-result-details", - "--recover-devices", - "--test-launcher-filter-file=../../testing/buildbot/filters/android.webview_instrumentation_tests_nougat.filter" + "--recover-devices" ], "merge": { "args": [ @@ -24322,7 +24321,8 @@ }, "android-marshmallow-arm64-rel": { "additional_compile_targets": [ - "monochrome_static_initializers" + "monochrome_static_initializers", + "weblayer_shell" ], "gtest_tests": [ {
diff --git a/testing/buildbot/chromium.clang.json b/testing/buildbot/chromium.clang.json index 8608630..9329e87 100644 --- a/testing/buildbot/chromium.clang.json +++ b/testing/buildbot/chromium.clang.json
@@ -38230,7 +38230,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38245,7 +38245,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38260,7 +38260,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38275,7 +38275,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38290,7 +38290,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38305,7 +38305,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38320,7 +38320,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38335,7 +38335,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38350,7 +38350,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38365,7 +38365,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38381,7 +38381,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38396,7 +38396,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38411,7 +38411,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38431,7 +38431,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38446,7 +38446,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38464,7 +38464,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38479,7 +38479,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38494,7 +38494,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38509,7 +38509,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38524,7 +38524,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38539,7 +38539,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38554,7 +38554,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38569,7 +38569,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38584,7 +38584,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38599,7 +38599,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38614,7 +38614,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ], "shards": 6 @@ -38635,7 +38635,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38650,7 +38650,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38665,7 +38665,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38680,7 +38680,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38695,7 +38695,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38710,7 +38710,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38725,7 +38725,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38740,7 +38740,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38755,7 +38755,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38770,7 +38770,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38785,7 +38785,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38800,7 +38800,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38815,7 +38815,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38830,7 +38830,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38845,7 +38845,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38860,7 +38860,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38875,7 +38875,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38890,7 +38890,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38905,7 +38905,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38920,7 +38920,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38935,7 +38935,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38950,7 +38950,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38965,7 +38965,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38980,7 +38980,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -38996,7 +38996,7 @@ "dimension_sets": [ { "integrity": "high", - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39011,7 +39011,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ], "shards": 3 @@ -39032,7 +39032,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39047,7 +39047,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39062,7 +39062,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39077,7 +39077,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39092,7 +39092,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39107,7 +39107,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39122,7 +39122,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39137,7 +39137,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39152,7 +39152,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39167,7 +39167,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39182,7 +39182,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39197,7 +39197,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39212,7 +39212,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39227,7 +39227,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39242,7 +39242,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39257,7 +39257,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39272,7 +39272,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39287,7 +39287,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39302,7 +39302,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39317,7 +39317,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39332,7 +39332,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39348,7 +39348,7 @@ "dimension_sets": [ { "integrity": "high", - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39363,7 +39363,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39378,7 +39378,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39393,7 +39393,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39408,7 +39408,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39424,7 +39424,7 @@ "dimension_sets": [ { "integrity": "high", - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39439,7 +39439,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39454,7 +39454,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39469,7 +39469,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39484,7 +39484,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39499,7 +39499,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39514,7 +39514,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39529,7 +39529,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39544,7 +39544,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39559,7 +39559,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39574,7 +39574,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39589,7 +39589,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39604,7 +39604,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39619,7 +39619,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39634,7 +39634,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39649,7 +39649,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39664,7 +39664,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39679,7 +39679,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] }, @@ -39694,7 +39694,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Windows-10" + "os": "Windows-10-15063" } ] },
diff --git a/testing/buildbot/filters/BUILD.gn b/testing/buildbot/filters/BUILD.gn index 0ec8e30..9dc9165 100644 --- a/testing/buildbot/filters/BUILD.gn +++ b/testing/buildbot/filters/BUILD.gn
@@ -133,7 +133,6 @@ testonly = true data = [ - "//testing/buildbot/filters/android.webview_instrumentation_tests_nougat.filter", "//testing/buildbot/filters/android.webview_instrumentation_tests_oreo.filter", "//testing/buildbot/filters/mojo.fyi.network_webview_instrumentation_test_apk.filter", ]
diff --git a/testing/buildbot/filters/PRESUBMIT.py b/testing/buildbot/filters/PRESUBMIT.py index 18ece598ac..dae77206 100644 --- a/testing/buildbot/filters/PRESUBMIT.py +++ b/testing/buildbot/filters/PRESUBMIT.py
@@ -38,6 +38,11 @@ if line.startswith('#'): # A comment. Ignore these. continue + if line.find('#') >= 0: + errors.append( + '%s:%d "#" is not a valid method separator. Use ".": "%s"' % ( + filename, line_num, line)) + continue if line.startswith('//') or line.startswith('/*'): errors.append( '%s:%d Not a valid comment syntax. Use "#" instead: "%s"' % (
diff --git a/testing/buildbot/filters/android.webview_instrumentation_tests_nougat.filter b/testing/buildbot/filters/android.webview_instrumentation_tests_nougat.filter deleted file mode 100644 index 1fd2e54..0000000 --- a/testing/buildbot/filters/android.webview_instrumentation_tests_nougat.filter +++ /dev/null
@@ -1,2 +0,0 @@ --org.chromium.android_webview.test.AwNetworkConfigurationTest#testSHA1LocalAnchorsAllowed --org.chromium.android_webview.test.SslPreferencesTest#testSslErrorNotCalledForOkCert
diff --git a/testing/buildbot/filters/android.webview_instrumentation_tests_oreo.filter b/testing/buildbot/filters/android.webview_instrumentation_tests_oreo.filter index 7c07b13..f97cf295 100644 --- a/testing/buildbot/filters/android.webview_instrumentation_tests_oreo.filter +++ b/testing/buildbot/filters/android.webview_instrumentation_tests_oreo.filter
@@ -1,3 +1,3 @@ --org.chromium.android_webview.test.AwAutofillTest#testJavascriptNotTriggerSelectControlChangeNotification --org.chromium.android_webview.test.AwAutofillTest#testSelectControlChangeStartAutofillSession --org.chromium.android_webview.test.AwAutofillTest#testSelectControlChangeNotification +-org.chromium.android_webview.test.AwAutofillTest.testJavascriptNotTriggerSelectControlChangeNotification +-org.chromium.android_webview.test.AwAutofillTest.testSelectControlChangeStartAutofillSession +-org.chromium.android_webview.test.AwAutofillTest.testSelectControlChangeNotification
diff --git a/testing/buildbot/gn_isolate_map.pyl b/testing/buildbot/gn_isolate_map.pyl index f3f3454..9a49684 100644 --- a/testing/buildbot/gn_isolate_map.pyl +++ b/testing/buildbot/gn_isolate_map.pyl
@@ -2976,6 +2976,10 @@ "label": "//android_webview/tools/automated_ui_tests:webview_ui_test_app_test_apk", "type": "console_test_launcher", }, + "weblayer_shell": { + "label": "//weblayer/shell:weblayer_shell", + "type": "additional_compile_target", + }, "wm_unittests": { "label": "//ui/wm:wm_unittests", "type": "windowed_test_launcher",
diff --git a/testing/buildbot/test_suite_exceptions.pyl b/testing/buildbot/test_suite_exceptions.pyl index 19bee9c..5041a8c 100644 --- a/testing/buildbot/test_suite_exceptions.pyl +++ b/testing/buildbot/test_suite_exceptions.pyl
@@ -2060,12 +2060,6 @@ # either passing or there is more capacity. 'experiment_percentage': 0, }, - 'Android WebView N (dbg)': { - #TODO(crbug.com/998926): Remove test filters once bug is resolved. - 'args': [ - '--test-launcher-filter-file=../../testing/buildbot/filters/android.webview_instrumentation_tests_nougat.filter', - ], - }, 'Android WebView O (dbg)': { #TODO(crbug.com/997362): Remove test filters once bug is resolved. 'args': [
diff --git a/testing/buildbot/waterfalls.pyl b/testing/buildbot/waterfalls.pyl index 6a1b998e..965e54c 100644 --- a/testing/buildbot/waterfalls.pyl +++ b/testing/buildbot/waterfalls.pyl
@@ -573,6 +573,7 @@ ], 'additional_compile_targets': [ 'monochrome_static_initializers', + 'weblayer_shell', ], 'test_suites': { 'gtest_tests': 'chromium_android_gtests', @@ -1019,13 +1020,9 @@ }, }, 'linux-win_cross-rel': { - 'swarming': { - 'dimension_sets': [ - { - 'os': 'Windows-10', - }, - ], - }, + 'mixins': [ + 'win10', + ], 'test_suites': { 'gtest_tests': 'chromium_win_gtests', },
diff --git a/testing/libfuzzer/README.md b/testing/libfuzzer/README.md index 86be8786..5301c31 100644 --- a/testing/libfuzzer/README.md +++ b/testing/libfuzzer/README.md
@@ -1,6 +1,6 @@ # Fuzzing in Chromium -[go/chrome-fuzzing](https://goto.google.com/chrome-fuzzing) (Googler only) +[go/chrome-fuzzing](https://goto.google.com/chrome-fuzzing) [Fuzzing] is a testing technique that feeds randomized inputs to a target code in an attempt to crash it. It's one of the most effective methods we have for @@ -24,33 +24,29 @@ ## Advanced Topics -* Improving fuzz target effectiveness: [Efficient Fuzzing Guide]. -* Creating a fuzz target that expects a protobuf (instead of a byte steam) as - input: [Guide to libprotobuf-mutator (LPM)]. +* [Improving fuzz target efficiency]. +* [Creating a fuzz target that expects a protobuf] instead of a byte stream as + input. *** note - **Note:** you can also use LPM to fuzz code that needs multiple mutated + **Note:** You can also fuzz code that needs multiple mutated inputs, or to generate inputs defined by a grammar. *** -* Reproducing bugs found by libFuzzer/AFL and reported by ClusterFuzz: - [Reproducing Bugs]. +* [Reproducing bugs] found by libFuzzer/AFL and reported by ClusterFuzz. ## Further Reading -* LibFuzzer's integration with Chromium and ClusterFuzz: [LibFuzzer - Integration]. -* AFL's integration with Chromium and ClusterFuzz: [AFL Integration]. -* Detailed references for other integration parts: [Reference]. -* Writing fuzzers for the non-browser parts of Chrome OS: [Fuzzing on Chrome - OS]. +* [LibFuzzer integration] with Chromium and ClusterFuzz. +* [AFL integration] with Chromium and ClusterFuzz. +* [Detailed references] for other integration parts. +* Writing fuzzers for the [non-browser parts of Chrome OS]. ## Trophies -* Issues found with in-process fuzzing and automatically filed by ClusterFuzz: - [ClusterFuzz Bugs]. -* Issues filed manually after running fuzz targets: [Manual Bugs]. -* Bugs found in PDFium by manual fuzzing: [PDFium Bugs]. -* Bugs found with libFuzzer in open-source projects: [OSS Trophies]. +* [Issues automatically filed] by ClusterFuzz. +* [Issues filed manually] after running fuzz targets. +* [Bugs found in PDFium] by manual fuzzing. +* [Bugs found in open-source projects] with libFuzzer. ## Other Links * [Guided in-process fuzzing of Chrome components] blog post. @@ -58,23 +54,23 @@ libFuzzer. [AFL]: http://lcamtuf.coredump.cx/afl/ -[AFL Integration]: AFL_integration.md +[AFL integration]: AFL_integration.md [Blackbox fuzzing]: https://google.github.io/clusterfuzz/setting-up-fuzzing/blackbox-fuzzing/ +[Bugs found in open-source projects]: http://llvm.org/docs/LibFuzzer.html#trophies +[Bugs found in PDFium]: https://bugs.chromium.org/p/pdfium/issues/list?can=1&q=libfuzzer&colspec=ID+Type+Status+Priority+Milestone+Owner+Summary&cells=tiles [ClusterFuzz]: https://clusterfuzz.com/ -[ClusterFuzz Bugs]: https://bugs.chromium.org/p/chromium/issues/list?sort=-modified&colspec=ID%20Pri%20M%20Stars%20ReleaseBlock%20Component%20Status%20Owner%20Summary%20OS%20Modified&q=label%3AStability-LibFuzzer%2CStability-AFL%20label%3AClusterFuzz%20-status%3AWontFix%2CDuplicate&can=1 [ClusterFuzz Stats]: https://clusterfuzz.com/fuzzer-stats/by-fuzzer/fuzzer/libFuzzer/job/libfuzzer_chrome_asan -[Efficient Fuzzing Guide]: efficient_fuzzing.md +[Creating a fuzz target that expects a protobuf]: libprotobuf-mutator.md +[Detailed references]: reference.md [Fuzzing]: https://en.wikipedia.org/wiki/Fuzzing -[Fuzzing on Chrome OS]: https://chromium.googlesource.com/chromiumos/docs/+/master/fuzzing.md [Getting Started Guide]: getting_started.md -[Guide to libprotobuf-mutator (LPM)]: libprotobuf-mutator.md [Guided in-process fuzzing of Chrome components]: https://security.googleblog.com/2016/08/guided-in-process-fuzzing-of-chrome.html -[Manual Bugs]: https://bugs.chromium.org/p/chromium/issues/list?can=1&q=label%3AStability-LibFuzzer+-label%3AClusterFuzz&sort=-modified&colspec=ID+Pri+M+Stars+ReleaseBlock+Component+Status+Owner+Summary+OS+Modified&x=m&y=releaseblock&cells=ids -[OSS Trophies]: http://llvm.org/docs/LibFuzzer.html#trophies -[PDFium Bugs]: https://bugs.chromium.org/p/pdfium/issues/list?can=1&q=libfuzzer&colspec=ID+Type+Status+Priority+Milestone+Owner+Summary&cells=tiles -[Reference]: reference.md -[Reproducing Bugs]: reproducing.md +[Improving fuzz target efficiency]: efficient_fuzzing.md +[Issues automatically filed]: https://bugs.chromium.org/p/chromium/issues/list?sort=-modified&colspec=ID%20Pri%20M%20Stars%20ReleaseBlock%20Component%20Status%20Owner%20Summary%20OS%20Modified&q=label%3AStability-LibFuzzer%2CStability-AFL%20label%3AClusterFuzz%20-status%3AWontFix%2CDuplicate&can=1 +[Issues filed manually]: https://bugs.chromium.org/p/chromium/issues/list?can=1&q=label%3AStability-LibFuzzer+-label%3AClusterFuzz&sort=-modified&colspec=ID+Pri+M+Stars+ReleaseBlock+Component+Status+Owner+Summary+OS+Modified&x=m&y=releaseblock&cells=ids +[non-browser parts of Chrome OS]: https://chromium.googlesource.com/chromiumos/docs/+/master/fuzzing.md +[Reproducing bugs]: reproducing.md [crbug.com/539572]: https://bugs.chromium.org/p/chromium/issues/detail?id=539572 [go/fuzzing-success]: https://goto.google.com/fuzzing-success [libFuzzer]: http://llvm.org/docs/LibFuzzer.html -[libFuzzer Integration]: libFuzzer_integration.md +[libFuzzer integration]: libFuzzer_integration.md
diff --git a/third_party/blink/public/BUILD.gn b/third_party/blink/public/BUILD.gn index ccbfa55..94e8fe87 100644 --- a/third_party/blink/public/BUILD.gn +++ b/third_party/blink/public/BUILD.gn
@@ -175,7 +175,6 @@ "platform/modules/webrtc/track_observer.h", "platform/modules/webrtc/webrtc_logging.h", "platform/modules/webrtc/webrtc_source.h", - "platform/modules/webrtc/webrtc_video_frame_adapter.h", "platform/platform.h", "platform/pointer_id.h", "platform/pointer_properties.h",
diff --git a/third_party/blink/public/mojom/web_feature/web_feature.mojom b/third_party/blink/public/mojom/web_feature/web_feature.mojom index ce249cc..e5c54ed 100644 --- a/third_party/blink/public/mojom/web_feature/web_feature.mojom +++ b/third_party/blink/public/mojom/web_feature/web_feature.mojom
@@ -2395,6 +2395,8 @@ kFetchRedirectError = 3012, kFetchRedirectManual = 3013, kFetchCacheReload = 3014, + kV8Window_ChooseFileSystemEntries_Method = 3015, + kV8FileSystemDirectoryHandle_GetSystemDirectory_Method = 3016, // Add new features immediately above this line. Don't change assigned // numbers of any item, and don't reuse removed slots.
diff --git a/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.cc b/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.cc index f0d7b4f5..2ab26cc 100644 --- a/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.cc +++ b/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.cc
@@ -182,6 +182,8 @@ // returned but with an 'Invalid' entry; this is used for "multi-entry" // indexes where an array with invalid members is permitted will later be // sanitized. +// A V8 exception may be thrown on bad data or by script's getters; if so, +// callers should not make further V8 calls. static std::unique_ptr<IDBKey> CreateIDBKeyFromValue( v8::Isolate* isolate, v8::Local<v8::Value> value, @@ -245,6 +247,10 @@ } std::unique_ptr<IDBKey> subkey = CreateIDBKeyFromValue(isolate, item, stack, exception_state); + if (exception_state.HadException()) { + exception_state.RethrowV8Exception(block.Exception()); + return nullptr; + } if (!subkey) subkeys.emplace_back(IDBKey::CreateInvalid()); else @@ -265,6 +271,8 @@ // sanitized. This is used to implement both of the following spec algorithms: // https://w3c.github.io/IndexedDB/#convert-value-to-key // https://w3c.github.io/IndexedDB/#convert-a-value-to-a-multientry-key +// A V8 exception may be thrown on bad data or by script's getters; if so, +// callers should not make further V8 calls. static std::unique_ptr<IDBKey> CreateIDBKeyFromValue( v8::Isolate* isolate, v8::Local<v8::Value> value, @@ -310,6 +318,8 @@ // to a key is representing by returning an 'Invalid' key. (An array with // invalid members will be returned if needed.) // https://w3c.github.io/IndexedDB/#evaluate-a-key-path-on-a-value +// A V8 exception may be thrown on bad data or by script's getters; if so, +// callers should not make further V8 calls. static std::unique_ptr<IDBKey> CreateIDBKeyFromValueAndKeyPath( v8::Isolate* isolate, v8::Local<v8::Value> v8_value, @@ -397,6 +407,8 @@ // paths, nullptr is returned if evaluation of any sub-path fails, otherwise // an array key is returned (with potentially 'Invalid' members). // https://w3c.github.io/IndexedDB/#evaluate-a-key-path-on-a-value +// A V8 exception may be thrown on bad data or by script's getters; if so, +// callers should not make further V8 calls. static std::unique_ptr<IDBKey> CreateIDBKeyFromValueAndKeyPath( v8::Isolate* isolate, v8::Local<v8::Value> value, @@ -411,6 +423,8 @@ for (const String& path : array) { auto key = CreateIDBKeyFromValueAndKeyPath(isolate, value, path, exception_state); + if (exception_state.HadException()) + return nullptr; // Evaluation of path failed - overall failure. if (!key) return nullptr;
diff --git a/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.h b/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.h index 904c526..82b5d7b 100644 --- a/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.h +++ b/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.h
@@ -60,9 +60,8 @@ // Note that an Array key may contain Invalid members, as the "multi-entry" // index case allows these, and will filter them out later. Use IsValid() to // recursively check. - static std::unique_ptr<IDBKey> NativeValue(v8::Isolate*, - v8::Local<v8::Value>, - ExceptionState&); + MODULES_EXPORT static std::unique_ptr<IDBKey> + NativeValue(v8::Isolate*, v8::Local<v8::Value>, ExceptionState&); // Implementation for ScriptValue::To<std::unique_ptr<IDBKey>>(). //
diff --git a/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules_test.cc b/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules_test.cc index 76eae52..9745ddce 100644 --- a/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules_test.cc +++ b/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules_test.cc
@@ -48,6 +48,15 @@ namespace { +v8::Local<v8::Object> EvaluateScriptAsObject(V8TestingScope& scope, + const char* source) { + v8::Local<v8::Script> script = + v8::Script::Compile(scope.GetContext(), + V8String(scope.GetIsolate(), source)) + .ToLocalChecked(); + return script->Run(scope.GetContext()).ToLocalChecked().As<v8::Object>(); +} + std::unique_ptr<IDBKey> CheckKeyFromValueAndKeyPathInternal( v8::Isolate* isolate, const ScriptValue& value, @@ -227,6 +236,71 @@ CheckKeyPathNullValue(isolate, script_value, "bar"); } +TEST(IDBKeyFromValue, Exceptions) { + V8TestingScope scope; + { + // Value is an array with a getter that throws. + ScriptValue script_value( + scope.GetScriptState(), + EvaluateScriptAsObject( + scope, + "(()=>{" + " const a = [0, 1, 2];" + " Object.defineProperty(a, 1, {get: () => { throw Error(); }});" + " return a;" + "})()")); + + DummyExceptionStateForTesting exception_state; + auto key = ScriptValue::To<std::unique_ptr<IDBKey>>( + scope.GetIsolate(), script_value, exception_state); + EXPECT_FALSE(key->IsValid()); + EXPECT_TRUE(exception_state.HadException()); + } + { + // Value is an array containing an array with a getter that throws. + ScriptValue script_value( + scope.GetScriptState(), + EvaluateScriptAsObject( + scope, + "(()=>{" + " const a = [0, 1, 2];" + " Object.defineProperty(a, 1, {get: () => { throw Error(); }});" + " return ['x', a, 'z'];" + "})()")); + + DummyExceptionStateForTesting exception_state; + auto key = ScriptValue::To<std::unique_ptr<IDBKey>>( + scope.GetIsolate(), script_value, exception_state); + EXPECT_FALSE(key->IsValid()); + EXPECT_TRUE(exception_state.HadException()); + } +} + +TEST(IDBKeyFromValueAndKeyPathTest, Exceptions) { + V8TestingScope scope; + ScriptValue script_value( + scope.GetScriptState(), + EvaluateScriptAsObject(scope, + "({id:1, get throws() { throw Error(); }})")); + { + // Key path references a property that throws. + DummyExceptionStateForTesting exception_state; + EXPECT_FALSE(ScriptValue::To<std::unique_ptr<IDBKey>>( + scope.GetIsolate(), script_value, exception_state, + IDBKeyPath("throws"))); + EXPECT_TRUE(exception_state.HadException()); + } + + { + // Compound key path references a property that throws. + DummyExceptionStateForTesting exception_state; + EXPECT_FALSE(ScriptValue::To<std::unique_ptr<IDBKey>>( + scope.GetIsolate(), script_value, exception_state, + IDBKeyPath(Vector<String>{"id", "throws"}))); + EXPECT_TRUE(exception_state.HadException()); + } +} + TEST(InjectIDBKeyTest, ImplicitValues) { V8TestingScope scope; v8::Isolate* isolate = scope.GetIsolate();
diff --git a/third_party/blink/renderer/core/css/css_math_expression_node.cc b/third_party/blink/renderer/core/css/css_math_expression_node.cc index 2077fe5..3a325ef 100644 --- a/third_party/blink/renderer/core/css/css_math_expression_node.cc +++ b/third_party/blink/renderer/core/css/css_math_expression_node.cc
@@ -1103,8 +1103,13 @@ // static CSSMathExpressionNode* CSSMathExpressionNode::Create(PixelsAndPercent value) { - double pixels = value.pixels; double percent = value.percent; + double pixels = value.pixels; + CSSMathOperator op = CSSMathOperator::kAdd; + if (pixels < 0) { + pixels = -pixels; + op = CSSMathOperator::kSubtract; + } return CSSMathExpressionBinaryOperation::Create( CSSMathExpressionNumericLiteral::Create( CSSNumericLiteralValue::Create( @@ -1114,7 +1119,7 @@ CSSNumericLiteralValue::Create(pixels, CSSPrimitiveValue::UnitType::kPixels), pixels == trunc(pixels)), - CSSMathOperator::kAdd); + op); } // static
diff --git a/third_party/blink/renderer/core/dom/element.cc b/third_party/blink/renderer/core/dom/element.cc index 23bf3e9..519bc96 100644 --- a/third_party/blink/renderer/core/dom/element.cc +++ b/third_party/blink/renderer/core/dom/element.cc
@@ -2400,13 +2400,19 @@ if (HasRareData()) { ElementRareData* rare_data = GetElementRareData(); - if (rare_data->IntersectionObserverData() && - rare_data->IntersectionObserverData()->HasObservations()) { - GetDocument().EnsureIntersectionObserverController().AddTrackedTarget( - *this, - rare_data->IntersectionObserverData()->NeedsOcclusionTracking()); - if (LocalFrameView* frame_view = GetDocument().View()) - frame_view->SetIntersectionObservationState(LocalFrameView::kRequired); + if (ElementIntersectionObserverData* observer_data = + rare_data->IntersectionObserverData()) { + if (observer_data->IsTargetOfImplicitRootObserver() || + observer_data->IsRoot()) { + GetDocument().EnsureIntersectionObserverController().AddTrackedElement( + *this, observer_data->NeedsOcclusionTracking()); + } + if (observer_data->IsTarget() || observer_data->IsRoot()) { + if (LocalFrameView* frame_view = GetDocument().View()) { + frame_view->SetIntersectionObservationState( + LocalFrameView::kRequired); + } + } } } @@ -2496,10 +2502,10 @@ element_animations->CssAnimations().Cancel(); if (data->IntersectionObserverData()) { - data->IntersectionObserverData()->ComputeObservations( + data->IntersectionObserverData()->ComputeIntersectionsForTarget( IntersectionObservation::kExplicitRootObserversNeedUpdate | IntersectionObservation::kImplicitRootObserversNeedUpdate); - GetDocument().EnsureIntersectionObserverController().RemoveTrackedTarget( + GetDocument().EnsureIntersectionObserverController().RemoveTrackedElement( *this); } DCHECK(!data->HasPseudoElements()); @@ -4309,9 +4315,9 @@ return EnsureElementRareData().EnsureIntersectionObserverData(); } -bool Element::ComputeIntersectionObservations(unsigned flags) { +bool Element::ComputeIntersectionsForLifecycleUpdate(unsigned flags) { if (ElementIntersectionObserverData* data = IntersectionObserverData()) - return data->ComputeObservations(flags); + return data->ComputeIntersectionsForLifecycleUpdate(flags); return false; }
diff --git a/third_party/blink/renderer/core/dom/element.h b/third_party/blink/renderer/core/dom/element.h index 813931c..45816bec 100644 --- a/third_party/blink/renderer/core/dom/element.h +++ b/third_party/blink/renderer/core/dom/element.h
@@ -910,7 +910,7 @@ ElementIntersectionObserverData* IntersectionObserverData() const; ElementIntersectionObserverData& EnsureIntersectionObserverData(); - bool ComputeIntersectionObservations(unsigned flags); + bool ComputeIntersectionsForLifecycleUpdate(unsigned flags); // Returns true if the Element is being observed by an IntersectionObserver // for which trackVisibility() is true. bool NeedsOcclusionTracking() const;
diff --git a/third_party/blink/renderer/core/exported/web_frame_test.cc b/third_party/blink/renderer/core/exported/web_frame_test.cc index 5a3a95c2..65e92a1 100644 --- a/third_party/blink/renderer/core/exported/web_frame_test.cc +++ b/third_party/blink/renderer/core/exported/web_frame_test.cc
@@ -8710,7 +8710,7 @@ WebRemoteFrame* remote_frame = frame_test_helpers::CreateRemote(); MainFrame()->Swap(remote_frame); - remote_frame->View()->MainFrameWidget()->Resize(size); + remote_frame->View()->Resize(size); WebLocalFrame* local_frame = frame_test_helpers::CreateProvisional(*remote_frame); @@ -9507,7 +9507,7 @@ *helper.RemoteMainFrame(), WebString(), WebFrameOwnerProperties(), nullptr, nullptr, &child_widget_client); - helper.GetWebView()->MainFrameWidget()->Resize(WebSize(1000, 1000)); + helper.GetWebView()->Resize(WebSize(1000, 1000)); WebGestureEvent event(WebInputEvent::kGestureTap, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests(),
diff --git a/third_party/blink/renderer/core/exported/web_view_impl.cc b/third_party/blink/renderer/core/exported/web_view_impl.cc index 33445355..b286951e 100644 --- a/third_party/blink/renderer/core/exported/web_view_impl.cc +++ b/third_party/blink/renderer/core/exported/web_view_impl.cc
@@ -1014,7 +1014,8 @@ void WebViewImpl::EnableTapHighlights( HeapVector<Member<Node>>& highlight_nodes) { GetPage()->GetLinkHighlights().SetTapHighlights(highlight_nodes); - UpdateAllLifecyclePhases(LifecycleUpdateReason::kOther); + UpdateLifecycle(WebWidget::LifecycleUpdate::kAll, + WebWidget::LifecycleUpdateReason::kOther); } void WebViewImpl::AnimateDoubleTapZoom(const gfx::Point& point_in_root_frame, @@ -1378,7 +1379,8 @@ // Update lifecyle phases immediately to recalculate the minimum scale limit // for rotation anchoring, and to make sure that no lifecycle states are // stale if this WebView is embedded in another one. - UpdateAllLifecyclePhases(LifecycleUpdateReason::kOther); + UpdateLifecycle(WebWidget::LifecycleUpdate::kAll, + WebWidget::LifecycleUpdateReason::kOther); } void WebViewImpl::ResizeWithBrowserControls( @@ -1457,6 +1459,10 @@ fullscreen_controller_->DidExitFullscreen(); } +void WebViewImpl::SetWebWidget(WebWidget* widget) { + web_widget_ = widget; +} + void WebViewImpl::SetSuppressFrameRequestsWorkaroundFor704763Only( bool suppress_frame_requests) { AsView().page->Animator().SetSuppressFrameRequestsWorkaroundFor704763Only( @@ -1573,8 +1579,8 @@ .RecordEndOfFrameMetrics(frame_begin_time, base::TimeTicks::Now()); } -void WebViewImpl::UpdateLifecycle(LifecycleUpdate requested_update, - LifecycleUpdateReason reason) { +void WebViewImpl::UpdateLifecycle(WebWidget::LifecycleUpdate requested_update, + WebWidget::LifecycleUpdateReason reason) { TRACE_EVENT0("blink", "WebViewImpl::updateAllLifecyclePhases"); if (!MainFrameImpl()) return; @@ -1584,7 +1590,7 @@ PageWidgetDelegate::UpdateLifecycle( *AsView().page, *MainFrameImpl()->GetFrame(), requested_update, reason); - if (requested_update != LifecycleUpdate::kAll) + if (requested_update != WebWidget::LifecycleUpdate::kAll) return; // There is no background color for non-composited WebViews (eg printing). @@ -3585,7 +3591,7 @@ } WebWidget* WebViewImpl::MainFrameWidget() { - return this; + return web_widget_; } void WebViewImpl::AddAutoplayFlags(int32_t value) {
diff --git a/third_party/blink/renderer/core/exported/web_view_impl.h b/third_party/blink/renderer/core/exported/web_view_impl.h index 7d4052ea..61d54c30 100644 --- a/third_party/blink/renderer/core/exported/web_view_impl.h +++ b/third_party/blink/renderer/core/exported/web_view_impl.h
@@ -73,6 +73,11 @@ } namespace blink { + +namespace frame_test_helpers { +class WebViewHelper; +} + class BrowserControls; class DevToolsEmulator; class Frame; @@ -95,7 +100,6 @@ using PaintHoldingCommitTrigger = cc::PaintHoldingCommitTrigger; class CORE_EXPORT WebViewImpl final : public WebView, - private WebWidget, public RefCounted<WebViewImpl>, public PageWidgetEventHandler { public: @@ -104,8 +108,8 @@ bool compositing_enabled, WebViewImpl* opener); - // This method is overridden from both WebWidget and WebView. The former is - // meaningless, and this is only used to Close the WebView. + // All calls to Create() should be balanced with a call to Close(). This + // synchronously destroys the WebViewImpl. void Close() override; static HashSet<WebViewImpl*>& AllInstances(); @@ -164,6 +168,7 @@ WebFloatPoint VisualViewportOffset() const override; WebFloatSize VisualViewportSize() const override; void ResizeVisualViewport(const WebSize&) override; + void Resize(const WebSize&) override; void ResetScrollAndScaleState() override; void SetIgnoreViewportTagScaleLimits(bool) override; WebSize ContentsPreferredMinimumSize() override; @@ -181,7 +186,7 @@ void DisableAutoResizeMode() override; void PerformPluginAction(const WebPluginAction&, const gfx::Point&) override; void AudioStateChanged(bool is_audio_playing) override; - WebHitTestResult HitTestResultAt(const gfx::Point&) override; + WebHitTestResult HitTestResultAt(const gfx::Point&); WebHitTestResult HitTestResultForTap(const gfx::Point&, const WebSize&) override; uint64_t CreateUniqueIdentifierForRequest() override; @@ -372,6 +377,7 @@ void ClearAutoplayFlags() override; int32_t AutoplayFlagsForTest() override; + WebSize Size(); IntSize MainFrameSize(); WebDisplayMode DisplayMode() const { return display_mode_; } @@ -406,10 +412,10 @@ Node* FindNodeFromScrollableCompositorElementId( cc::ElementId element_id) const; - // WebWidget overrides - void DidEnterFullscreen() override; - void DidExitFullscreen() override; - void Resize(const WebSize&) override; + void DidEnterFullscreen(); + void DidExitFullscreen(); + + void SetWebWidget(WebWidget* widget); private: FRIEND_TEST_ALL_PREFIXES(WebFrameTest, DivScrollIntoEditableTest); @@ -419,6 +425,12 @@ DivScrollIntoEditableTestZoomToLegibleScaleDisabled); FRIEND_TEST_ALL_PREFIXES(WebFrameTest, DivScrollIntoEditableTestWithDeviceScaleFactor); + FRIEND_TEST_ALL_PREFIXES(WebViewTest, SetBaseBackgroundColorBeforeMainFrame); + friend class frame_test_helpers::WebViewHelper; + friend class SimCompositor; + friend class WebView; // So WebView::Create can call our constructor + friend class WebViewFrameWidget; + friend class WTF::RefCounted<WebViewImpl>; // TODO(danakj): DCHECK in these that we're not inside a wrong API stackframe. struct ViewData; @@ -429,44 +441,42 @@ // still valid until after this method is called. void DidDetachLocalMainFrame(); - // WebWidget methods: - void SetAnimationHost(cc::AnimationHost*) override; - WebSize Size() override; - void SetSuppressFrameRequestsWorkaroundFor704763Only(bool) override; + // These are temporary methods to allow WebViewFrameWidget to delegate to + // WebViewImpl. We expect to eventually move these out. + void SetAnimationHost(cc::AnimationHost*); + void SetSuppressFrameRequestsWorkaroundFor704763Only(bool); void BeginFrame(base::TimeTicks last_frame_time, - bool record_main_frame_metrics) override; - void DidBeginFrame() override; - void BeginRafAlignedInput() override; - void EndRafAlignedInput() override; - void BeginUpdateLayers() override; - void EndUpdateLayers() override; - void BeginCommitCompositorFrame() override; - void EndCommitCompositorFrame() override; - void RecordStartOfFrameMetrics() override; - void RecordEndOfFrameMetrics(base::TimeTicks frame_begin_time) override; - void UpdateLifecycle(LifecycleUpdate requested_update, - LifecycleUpdateReason reason) override; - void ThemeChanged() override; - WebInputEventResult HandleInputEvent(const WebCoalescedInputEvent&) override; - WebInputEventResult DispatchBufferedTouchEvents() override; - void SetCursorVisibilityState(bool is_visible) override; - void OnFallbackCursorModeToggled(bool is_on) override; - void ApplyViewportChanges(const ApplyViewportChangesArgs& args) override; - void RecordManipulationTypeCounts(cc::ManipulationInfo info) override; - void SendOverscrollEventFromImplSide( - const gfx::Vector2dF& overscroll_delta, - cc::ElementId scroll_latched_element_id) override; - void SendScrollEndEventFromImplSide( - cc::ElementId scroll_latched_element_id) override; - void MouseCaptureLost() override; + bool record_main_frame_metrics); + void DidBeginFrame(); + void BeginRafAlignedInput(); + void EndRafAlignedInput(); + void BeginUpdateLayers(); + void EndUpdateLayers(); + void BeginCommitCompositorFrame(); + void EndCommitCompositorFrame(); + void RecordStartOfFrameMetrics(); + void RecordEndOfFrameMetrics(base::TimeTicks frame_begin_time); + void UpdateLifecycle(WebWidget::LifecycleUpdate requested_update, + WebWidget::LifecycleUpdateReason reason); + void ThemeChanged(); + WebInputEventResult HandleInputEvent(const WebCoalescedInputEvent&); + WebInputEventResult DispatchBufferedTouchEvents(); + void SetCursorVisibilityState(bool is_visible); + void OnFallbackCursorModeToggled(bool is_on); + void ApplyViewportChanges(const ApplyViewportChangesArgs& args); + void RecordManipulationTypeCounts(cc::ManipulationInfo info); + void SendOverscrollEventFromImplSide(const gfx::Vector2dF& overscroll_delta, + cc::ElementId scroll_latched_element_id); + void SendScrollEndEventFromImplSide(cc::ElementId scroll_latched_element_id); + void MouseCaptureLost(); void SetFocus(bool enable) override; - bool SelectionBounds(WebRect& anchor, WebRect& focus) const override; - bool IsAcceleratedCompositingActive() const override; - void DidAcquirePointerLock() override; - void DidNotAcquirePointerLock() override; - void DidLosePointerLock() override; - void ShowContextMenu(WebMenuSourceType) override; - WebURL GetURLForDebugTrace() override; + bool SelectionBounds(WebRect& anchor, WebRect& focus) const; + bool IsAcceleratedCompositingActive() const; + void DidAcquirePointerLock(); + void DidNotAcquirePointerLock(); + void DidLosePointerLock(); + void ShowContextMenu(WebMenuSourceType); + WebURL GetURLForDebugTrace(); void SetPageScaleFactorAndLocation(float scale, bool is_pinch_gesture_active, @@ -485,11 +495,6 @@ void UpdateBaseBackgroundColor(); - friend class WebView; // So WebView::Create can call our constructor - friend class WebViewFrameWidget; - friend class WTF::RefCounted<WebViewImpl>; - friend class SimCompositor; - WebViewImpl(WebViewClient*, bool is_hidden, bool does_composite, @@ -693,6 +698,10 @@ // registered. WeakPersistent<WebLocalFrameImpl> local_root_with_empty_mouse_wheel_listener_; + // The WebWidget for the main frame. This is expected to be unset when the + // WebWidget destroys itself. + WebWidget* web_widget_ = nullptr; + WebPageImportanceSignals page_importance_signals_; // We defer commits when transitioning to a new page. ChromeClientImpl calls
diff --git a/third_party/blink/renderer/core/exported/web_view_test.cc b/third_party/blink/renderer/core/exported/web_view_test.cc index 3679ed503..77a68d57 100644 --- a/third_party/blink/renderer/core/exported/web_view_test.cc +++ b/third_party/blink/renderer/core/exported/web_view_test.cc
@@ -514,8 +514,7 @@ { // Copy the steps done from WebViewHelper::InitializeWithOpener() to set up // the appropriate pointers! - web_view->MainFrameWidget()->SetAnimationHost( - web_widget_client.animation_host()); + web_view->SetAnimationHost(web_widget_client.animation_host()); blink::WebFrameWidget::CreateForMainFrame(&web_widget_client, frame); web_view->DidAttachLocalMainFrame(); }
diff --git a/third_party/blink/renderer/core/frame/frame_test_helpers.cc b/third_party/blink/renderer/core/frame/frame_test_helpers.cc index dd554f4..c9aedfb1 100644 --- a/third_party/blink/renderer/core/frame/frame_test_helpers.cc +++ b/third_party/blink/renderer/core/frame/frame_test_helpers.cc
@@ -354,8 +354,7 @@ // TODO(danakj): Make this part of attaching the main frame's WebFrameWidget. // This happens before CreateForMainFrame as the WebFrameWidget binding to the // WebLocalFrameImpl sets up animations. - web_view_->MainFrameWidget()->SetAnimationHost( - test_web_widget_client_->animation_host()); + web_view_->SetAnimationHost(test_web_widget_client_->animation_host()); // TODO(dcheng): The main frame widget currently has a special case. // Eliminate this once WebView is no longer a WebWidget. blink::WebFrameWidget::CreateForMainFrame(test_web_widget_client_, frame); @@ -423,8 +422,7 @@ test_web_widget_client_ = CreateDefaultClientIfNeeded( web_widget_client, owned_test_web_widget_client_); - web_view_->MainFrameWidget()->SetAnimationHost( - test_web_widget_client_->animation_host()); + web_view_->SetAnimationHost(test_web_widget_client_->animation_host()); return web_view_; } @@ -460,7 +458,7 @@ } void WebViewHelper::Resize(WebSize size) { - GetWebView()->MainFrameWidget()->Resize(size); + GetWebView()->Resize(size); } void WebViewHelper::InitializeWebView(TestWebViewClient* web_view_client,
diff --git a/third_party/blink/renderer/core/frame/fullscreen_controller.cc b/third_party/blink/renderer/core/frame/fullscreen_controller.cc index 291b342..13d190ce 100644 --- a/third_party/blink/renderer/core/frame/fullscreen_controller.cc +++ b/third_party/blink/renderer/core/frame/fullscreen_controller.cc
@@ -260,9 +260,7 @@ web_view_base_->GetPageScaleConstraintsSet().SetNeedsReset(true); } else { fullscreen_constraints = PageScaleConstraints(1.0, 1.0, 1.0); - DCHECK(web_view_base_->MainFrameWidget()); - fullscreen_constraints.layout_size = - FloatSize(web_view_base_->MainFrameWidget()->Size()); + fullscreen_constraints.layout_size = FloatSize(web_view_base_->Size()); } web_view_base_->GetPageScaleConstraintsSet().SetFullscreenConstraints( fullscreen_constraints);
diff --git a/third_party/blink/renderer/core/frame/local_frame_view.cc b/third_party/blink/renderer/core/frame/local_frame_view.cc index 08dfb2ee..66911ff 100644 --- a/third_party/blink/renderer/core/frame/local_frame_view.cc +++ b/third_party/blink/renderer/core/frame/local_frame_view.cc
@@ -3925,8 +3925,7 @@ // Notify javascript IntersectionObservers if (IntersectionObserverController* controller = GetFrame().GetDocument()->GetIntersectionObserverController()) { - needs_occlusion_tracking |= - controller->ComputeTrackedIntersectionObservations(flags); + needs_occlusion_tracking |= controller->ComputeIntersections(flags); } intersection_observation_state_ = kNotNeeded; } @@ -3954,7 +3953,7 @@ void LocalFrameView::DeliverSynchronousIntersectionObservations() { if (IntersectionObserverController* controller = GetFrame().GetDocument()->GetIntersectionObserverController()) { - controller->DeliverIntersectionObservations( + controller->DeliverNotifications( IntersectionObserver::kDeliverDuringPostLifecycleSteps); } ForAllChildLocalFrameViews([](LocalFrameView& frame_view) {
diff --git a/third_party/blink/renderer/core/frame/web_view_frame_widget.cc b/third_party/blink/renderer/core/frame/web_view_frame_widget.cc index 8f7e233..950529614 100644 --- a/third_party/blink/renderer/core/frame/web_view_frame_widget.cc +++ b/third_party/blink/renderer/core/frame/web_view_frame_widget.cc
@@ -13,16 +13,16 @@ WebViewImpl& web_view) : WebFrameWidgetBase(client), web_view_(&web_view), - self_keep_alive_(PERSISTENT_FROM_HERE, this) {} + self_keep_alive_(PERSISTENT_FROM_HERE, this) { + web_view_->SetWebWidget(this); +} WebViewFrameWidget::~WebViewFrameWidget() = default; void WebViewFrameWidget::Close() { // Closing the WebViewFrameWidget happens in response to the local main frame // being detached from the Page/WebViewImpl. - // TODO(danakj): Close the WebWidget parts of WebViewImpl here. This should - // drop the WebWidgetClient from it as well. For now, WebViewImpl requires a - // WebWidgetClient to always be present so this does nothing. + web_view_->SetWebWidget(nullptr); web_view_ = nullptr; WebFrameWidgetBase::Close(); self_keep_alive_.Clear();
diff --git a/third_party/blink/renderer/core/html/forms/external_popup_menu.cc b/third_party/blink/renderer/core/html/forms/external_popup_menu.cc index 144dced..b787036 100644 --- a/third_party/blink/renderer/core/html/forms/external_popup_menu.cc +++ b/third_party/blink/renderer/core/html/forms/external_popup_menu.cc
@@ -39,12 +39,12 @@ #include "third_party/blink/public/web/web_local_frame_client.h" #include "third_party/blink/public/web/web_menu_item_info.h" #include "third_party/blink/public/web/web_popup_menu_info.h" -#include "third_party/blink/public/web/web_view.h" #include "third_party/blink/renderer/core/dom/node_computed_style.h" #include "third_party/blink/renderer/core/events/current_input_event.h" #include "third_party/blink/renderer/core/exported/web_view_impl.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/frame/local_frame_view.h" +#include "third_party/blink/renderer/core/frame/web_frame_widget_base.h" #include "third_party/blink/renderer/core/frame/web_local_frame_impl.h" #include "third_party/blink/renderer/core/html/forms/html_option_element.h" #include "third_party/blink/renderer/core/html/forms/html_select_element.h" @@ -61,11 +61,9 @@ namespace blink { ExternalPopupMenu::ExternalPopupMenu(LocalFrame& frame, - HTMLSelectElement& owner_element, - WebView& web_view) + HTMLSelectElement& owner_element) : owner_element_(owner_element), local_frame_(frame), - web_view_(web_view), dispatch_event_timer_(frame.GetTaskRunner(TaskType::kInternalDefault), this, &ExternalPopupMenu::DispatchEvent), @@ -133,9 +131,9 @@ } void ExternalPopupMenu::DispatchEvent(TimerBase*) { - DCHECK(web_view_.MainFrameWidget()); - web_view_.MainFrameWidget()->HandleInputEvent( - blink::WebCoalescedInputEvent(*synthetic_event_)); + WebLocalFrameImpl::FromFrame(local_frame_) + ->FrameWidgetImpl() + ->HandleInputEvent(blink::WebCoalescedInputEvent(*synthetic_event_)); synthetic_event_.reset(); } @@ -187,6 +185,7 @@ void ExternalPopupMenu::DisconnectClient() { Hide(); owner_element_ = nullptr; + dispatch_event_timer_.Stop(); } void ExternalPopupMenu::DidChangeSelection(int index) {}
diff --git a/third_party/blink/renderer/core/html/forms/external_popup_menu.h b/third_party/blink/renderer/core/html/forms/external_popup_menu.h index 9048585..2c572003 100644 --- a/third_party/blink/renderer/core/html/forms/external_popup_menu.h +++ b/third_party/blink/renderer/core/html/forms/external_popup_menu.h
@@ -44,7 +44,6 @@ class LocalFrame; class WebExternalPopupMenu; class WebMouseEvent; -class WebView; struct WebPopupMenuInfo; // The ExternalPopupMenu is a PopupMenu implementation for macOS and Android. @@ -52,7 +51,7 @@ class CORE_EXPORT ExternalPopupMenu final : public PopupMenu, public WebExternalPopupMenuClient { public: - ExternalPopupMenu(LocalFrame&, HTMLSelectElement&, WebView&); + ExternalPopupMenu(LocalFrame&, HTMLSelectElement&); ~ExternalPopupMenu() override; // Fills |info| with the popup menu information contained in the @@ -84,7 +83,6 @@ Member<HTMLSelectElement> owner_element_; Member<LocalFrame> local_frame_; - WebView& web_view_; std::unique_ptr<WebMouseEvent> synthetic_event_; TaskRunnerTimer<ExternalPopupMenu> dispatch_event_timer_; // The actual implementor of the show menu.
diff --git a/third_party/blink/renderer/core/html/media/video_wake_lock.cc b/third_party/blink/renderer/core/html/media/video_wake_lock.cc index ebf154c..9caa86f7 100644 --- a/third_party/blink/renderer/core/html/media/video_wake_lock.cc +++ b/third_party/blink/renderer/core/html/media/video_wake_lock.cc
@@ -22,6 +22,7 @@ video_element_(video) { VideoElement().addEventListener(event_type_names::kPlaying, this, true); VideoElement().addEventListener(event_type_names::kPause, this, true); + VideoElement().addEventListener(event_type_names::kEmptied, this, true); VideoElement().addEventListener(event_type_names::kEnterpictureinpicture, this, true); VideoElement().addEventListener(event_type_names::kLeavepictureinpicture, @@ -54,7 +55,11 @@ void VideoWakeLock::Invoke(ExecutionContext*, Event* event) { if (event->type() == event_type_names::kPlaying) { playing_ = true; - } else if (event->type() == event_type_names::kPause) { + } else if (event->type() == event_type_names::kPause || + event->type() == event_type_names::kEmptied) { + // In 4.8.12.5 steps 6.6.1, the media element is paused when a new load + // happens without actually firing a pause event. Because of this, we need + // to listen to the emptied event. playing_ = false; } else { DCHECK(event->type() == event_type_names::kEnterpictureinpicture ||
diff --git a/third_party/blink/renderer/core/html/media/video_wake_lock_test.cc b/third_party/blink/renderer/core/html/media/video_wake_lock_test.cc index 6a2d579..148cbc4 100644 --- a/third_party/blink/renderer/core/html/media/video_wake_lock_test.cc +++ b/third_party/blink/renderer/core/html/media/video_wake_lock_test.cc
@@ -162,6 +162,10 @@ void SimulateContextDestroyed() { GetDocument().NotifyContextDestroyed(); } + void SimulateNetworkState(HTMLMediaElement::NetworkState network_state) { + video_->SetNetworkState(network_state); + } + private: Persistent<HTMLVideoElement> video_; Persistent<VideoWakeLock> video_wake_lock_; @@ -347,4 +351,16 @@ EXPECT_FALSE(GetVideoWakeLock()->active_for_tests()); } +TEST_F(VideoWakeLockTest, LoadingCancelsLock) { + SimulatePlaying(); + EXPECT_TRUE(GetVideoWakeLock()->active_for_tests()); + + // The network state has to be non-empty for the resetting to actually kick. + SimulateNetworkState(HTMLMediaElement::kNetworkIdle); + + Video()->SetSrc(""); + test::RunPendingTasks(); + EXPECT_FALSE(GetVideoWakeLock()->active_for_tests()); +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/intersection_observer/element_intersection_observer_data.cc b/third_party/blink/renderer/core/intersection_observer/element_intersection_observer_data.cc index 94586c75..4c7edb7 100644 --- a/third_party/blink/renderer/core/intersection_observer/element_intersection_observer_data.cc +++ b/third_party/blink/renderer/core/intersection_observer/element_intersection_observer_data.cc
@@ -27,22 +27,60 @@ intersection_observations_.insert(observation.Observer(), &observation); } +void ElementIntersectionObserverData::AddObserver( + IntersectionObserver& observer) { + intersection_observers_.insert(&observer); +} + +bool ElementIntersectionObserverData::IsTargetOfImplicitRootObserver() const { + for (auto& entry : intersection_observations_) { + if (entry.key->RootIsImplicit()) + return true; + } + return false; +} + void ElementIntersectionObserverData::RemoveObservation( IntersectionObserver& observer) { intersection_observations_.erase(&observer); } -bool ElementIntersectionObserverData::ComputeObservations(unsigned flags) { +bool ElementIntersectionObserverData::ComputeIntersectionsForTarget( + unsigned flags) { bool needs_occlusion_tracking = false; HeapVector<Member<IntersectionObservation>> observations_to_process; CopyValuesToVector(intersection_observations_, observations_to_process); for (auto& observation : observations_to_process) { - needs_occlusion_tracking |= observation->Observer()->trackVisibility(); - observation->Compute(flags); + needs_occlusion_tracking |= + observation->Observer()->NeedsOcclusionTracking(); + observation->ComputeIntersection(flags); } return needs_occlusion_tracking; } +bool ElementIntersectionObserverData::ComputeIntersectionsForLifecycleUpdate( + unsigned flags) { + bool needs_occlusion_tracking = false; + + // Process explicit-root observers for which this element is root. + HeapVector<Member<IntersectionObserver>> observers_to_process; + // TODO(szager): Do we still need this copy? + CopyToVector(intersection_observers_, observers_to_process); + for (auto& observer : observers_to_process) { + needs_occlusion_tracking |= observer->NeedsOcclusionTracking(); + if (flags & IntersectionObservation::kExplicitRootObserversNeedUpdate) { + observer->ComputeIntersections(flags); + } + } + + // Process implicit-root observations for which this element is target. + unsigned implicit_root_flags = + flags & ~IntersectionObservation::kExplicitRootObserversNeedUpdate; + needs_occlusion_tracking |= + ComputeIntersectionsForTarget(implicit_root_flags); + return needs_occlusion_tracking; +} + bool ElementIntersectionObserverData::NeedsOcclusionTracking() const { for (auto& entry : intersection_observations_) { if (entry.key->trackVisibility()) @@ -53,6 +91,7 @@ void ElementIntersectionObserverData::Trace(blink::Visitor* visitor) { visitor->Trace(intersection_observations_); + visitor->Trace(intersection_observers_); } } // namespace blink
diff --git a/third_party/blink/renderer/core/intersection_observer/element_intersection_observer_data.h b/third_party/blink/renderer/core/intersection_observer/element_intersection_observer_data.h index 1507408..488a438 100644 --- a/third_party/blink/renderer/core/intersection_observer/element_intersection_observer_data.h +++ b/third_party/blink/renderer/core/intersection_observer/element_intersection_observer_data.h
@@ -22,9 +22,19 @@ IntersectionObservation* GetObservationFor(IntersectionObserver&); void AddObservation(IntersectionObservation&); + void AddObserver(IntersectionObserver&); void RemoveObservation(IntersectionObserver&); - bool HasObservations() const { return !intersection_observations_.IsEmpty(); } - bool ComputeObservations(unsigned flags); + bool IsTarget() const { return !intersection_observations_.IsEmpty(); } + bool IsTargetOfImplicitRootObserver() const; + bool IsRoot() const { return !intersection_observers_.IsEmpty(); } + // Run the IntersectionObserver algorithm for all observations for which this + // element is target. + bool ComputeIntersectionsForTarget(unsigned flags); + // Run the IntersectionObserver algorithm for all implicit-root observations + // for which this element is target; and all explicit-root observers for which + // this element is root. Returns true if any observer needs occlusion + // tracking. + bool ComputeIntersectionsForLifecycleUpdate(unsigned flags); bool NeedsOcclusionTracking() const; void Trace(blink::Visitor*); @@ -36,6 +46,10 @@ // IntersectionObservations for which the Node owning this data is target. HeapHashMap<Member<IntersectionObserver>, Member<IntersectionObservation>> intersection_observations_; + // IntersectionObservers for which the Node owning this data is root. + // Weak because once an observer is unreachable from javascript and has no + // active observations, it should be allowed to die. + HeapHashSet<WeakMember<IntersectionObserver>> intersection_observers_; }; } // namespace blink
diff --git a/third_party/blink/renderer/core/intersection_observer/intersection_geometry.cc b/third_party/blink/renderer/core/intersection_observer/intersection_geometry.cc index 9a73f50..7628b902a 100644 --- a/third_party/blink/renderer/core/intersection_observer/intersection_geometry.cc +++ b/third_party/blink/renderer/core/intersection_observer/intersection_geometry.cc
@@ -217,6 +217,21 @@ ComputeGeometry(root_geometry, root, target, thresholds); } +IntersectionGeometry::IntersectionGeometry(const RootGeometry& root_geometry, + const Element& explicit_root, + const Element& target_element, + const Vector<float>& thresholds, + unsigned flags) + : flags_(flags & kConstructorFlagsMask), + intersection_ratio_(0), + threshold_index_(0) { + LayoutObject* target = GetTargetLayoutObject(target_element); + LayoutObject* root = explicit_root.GetLayoutObject(); + if (!IsContainingBlockChainDescendant(target, root)) + return; + ComputeGeometry(root_geometry, root, target, thresholds); +} + IntersectionGeometry::~IntersectionGeometry() = default; void IntersectionGeometry::ComputeGeometry(const RootGeometry& root_geometry,
diff --git a/third_party/blink/renderer/core/intersection_observer/intersection_geometry.h b/third_party/blink/renderer/core/intersection_observer/intersection_geometry.h index 3c8080f6..f05ad2b 100644 --- a/third_party/blink/renderer/core/intersection_observer/intersection_geometry.h +++ b/third_party/blink/renderer/core/intersection_observer/intersection_geometry.h
@@ -58,6 +58,12 @@ const Vector<float>& thresholds, unsigned flags); + IntersectionGeometry(const RootGeometry& root_geometry, + const Element& explicit_root, + const Element& target, + const Vector<float>& thresholds, + unsigned flags); + IntersectionGeometry(const IntersectionGeometry&) = default; ~IntersectionGeometry();
diff --git a/third_party/blink/renderer/core/intersection_observer/intersection_observation.cc b/third_party/blink/renderer/core/intersection_observer/intersection_observation.cc index 01a69b5af..c07392fc 100644 --- a/third_party/blink/renderer/core/intersection_observer/intersection_observation.cc +++ b/third_party/blink/renderer/core/intersection_observer/intersection_observation.cc
@@ -30,65 +30,26 @@ // different sentinel value. last_threshold_index_(kMaxThresholdIndex - 1) {} -void IntersectionObservation::Compute(unsigned flags) { - DCHECK(Observer()); - if (!target_ || !observer_->RootIsValid() | !observer_->GetExecutionContext()) +void IntersectionObservation::ComputeIntersection( + const IntersectionGeometry::RootGeometry& root_geometry, + unsigned compute_flags) { + if (!ShouldCompute(compute_flags)) return; - if (flags & - (observer_->RootIsImplicit() ? kImplicitRootObserversNeedUpdate - : kExplicitRootObserversNeedUpdate)) { - needs_update_ = true; - } - if (!needs_update_) - return; - DOMHighResTimeStamp timestamp = observer_->GetTimeStamp(); - if (timestamp == -1) - return; - if (!(flags & kIgnoreDelay) && - timestamp - last_run_time_ < observer_->GetEffectiveDelay()) { - return; - } - if (target_->isConnected() && Observer()->trackVisibility()) { - FrameOcclusionState occlusion_state = - target_->GetDocument().GetFrame()->GetOcclusionState(); - // If we're tracking visibility, and we don't have occlusion information - // from our parent frame, then postpone computing intersections until a - // later lifecycle when the occlusion information is known. - if (occlusion_state == FrameOcclusionState::kUnknown) - return; - } - last_run_time_ = timestamp; - needs_update_ = 0; - Vector<Length> root_margin(4); - root_margin[0] = observer_->TopMargin(); - root_margin[1] = observer_->RightMargin(); - root_margin[2] = observer_->BottomMargin(); - root_margin[3] = observer_->LeftMargin(); - bool report_root_bounds = observer_->AlwaysReportRootBounds() || - (flags & kReportImplicitRootBounds) || - !observer_->RootIsImplicit(); - unsigned geometry_flags = IntersectionGeometry::kShouldConvertToCSSPixels; - if (report_root_bounds) - geometry_flags |= IntersectionGeometry::kShouldReportRootBounds; - if (Observer()->trackVisibility()) - geometry_flags |= IntersectionGeometry::kShouldComputeVisibility; - if (Observer()->trackFractionOfRoot()) - geometry_flags |= IntersectionGeometry::kShouldTrackFractionOfRoot; - - IntersectionGeometry geometry(observer_->root(), *Target(), root_margin, + DCHECK(observer_->root()); + unsigned geometry_flags = GetIntersectionGeometryFlags(compute_flags); + IntersectionGeometry geometry(root_geometry, *observer_->root(), *Target(), observer_->thresholds(), geometry_flags); + ProcessIntersectionGeometry(geometry); +} - // TODO(tkent): We can't use CHECK_LT due to a compile error. - CHECK(geometry.ThresholdIndex() < kMaxThresholdIndex - 1); - - if (last_threshold_index_ != geometry.ThresholdIndex() || - last_is_visible_ != geometry.IsVisible()) { - entries_.push_back(MakeGarbageCollected<IntersectionObserverEntry>( - geometry, timestamp, Target())); - Observer()->SetNeedsDelivery(); - SetLastThresholdIndex(geometry.ThresholdIndex()); - SetWasVisible(geometry.IsVisible()); - } +void IntersectionObservation::ComputeIntersection(unsigned compute_flags) { + if (!ShouldCompute(compute_flags)) + return; + unsigned geometry_flags = GetIntersectionGeometryFlags(compute_flags); + IntersectionGeometry geometry(observer_->root(), *Target(), + observer_->RootMargin(), + observer_->thresholds(), geometry_flags); + ProcessIntersectionGeometry(geometry); } void IntersectionObservation::TakeRecords( @@ -100,12 +61,16 @@ void IntersectionObservation::Disconnect() { DCHECK(Observer()); if (target_) { - Target()->EnsureIntersectionObserverData().RemoveObservation(*Observer()); + DCHECK(target_->IntersectionObserverData()); + ElementIntersectionObserverData* observer_data = + target_->IntersectionObserverData(); + observer_data->RemoveObservation(*Observer()); if (target_->isConnected() && - !Target()->EnsureIntersectionObserverData().HasObservations()) { + !observer_data->IsTargetOfImplicitRootObserver() && + !observer_data->IsRoot()) { target_->GetDocument() .EnsureIntersectionObserverController() - .RemoveTrackedTarget(*target_); + .RemoveTrackedElement(*target_); } } entries_.clear(); @@ -118,4 +83,66 @@ visitor->Trace(target_); } +bool IntersectionObservation::ShouldCompute(unsigned flags) { + DCHECK(Observer()); + if (!target_ || !observer_->RootIsValid() | !observer_->GetExecutionContext()) + return false; + if (flags & + (observer_->RootIsImplicit() ? kImplicitRootObserversNeedUpdate + : kExplicitRootObserversNeedUpdate)) { + needs_update_ = true; + } + if (!needs_update_) + return false; + DOMHighResTimeStamp timestamp = observer_->GetTimeStamp(); + if (timestamp == -1) + return false; + if (!(flags & kIgnoreDelay) && + timestamp - last_run_time_ < observer_->GetEffectiveDelay()) { + return false; + } + if (target_->isConnected() && Observer()->trackVisibility()) { + FrameOcclusionState occlusion_state = + target_->GetDocument().GetFrame()->GetOcclusionState(); + // If we're tracking visibility, and we don't have occlusion information + // from our parent frame, then postpone computing intersections until a + // later lifecycle when the occlusion information is known. + if (occlusion_state == FrameOcclusionState::kUnknown) + return false; + } + last_run_time_ = timestamp; + needs_update_ = false; + return true; +} + +unsigned IntersectionObservation::GetIntersectionGeometryFlags( + unsigned compute_flags) const { + bool report_root_bounds = observer_->AlwaysReportRootBounds() || + (compute_flags & kReportImplicitRootBounds) || + !observer_->RootIsImplicit(); + unsigned geometry_flags = IntersectionGeometry::kShouldConvertToCSSPixels; + if (report_root_bounds) + geometry_flags |= IntersectionGeometry::kShouldReportRootBounds; + if (Observer()->trackVisibility()) + geometry_flags |= IntersectionGeometry::kShouldComputeVisibility; + if (Observer()->trackFractionOfRoot()) + geometry_flags |= IntersectionGeometry::kShouldTrackFractionOfRoot; + return geometry_flags; +} + +void IntersectionObservation::ProcessIntersectionGeometry( + const IntersectionGeometry& geometry) { + // TODO(tkent): We can't use CHECK_LT due to a compile error. + CHECK(geometry.ThresholdIndex() < kMaxThresholdIndex - 1); + + if (last_threshold_index_ != geometry.ThresholdIndex() || + last_is_visible_ != geometry.IsVisible()) { + entries_.push_back(MakeGarbageCollected<IntersectionObserverEntry>( + geometry, last_run_time_, Target())); + Observer()->SetNeedsDelivery(); + SetLastThresholdIndex(geometry.ThresholdIndex()); + SetWasVisible(geometry.IsVisible()); + } +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/intersection_observer/intersection_observation.h b/third_party/blink/renderer/core/intersection_observer/intersection_observation.h index 7d31224..8b4a8ebd 100644 --- a/third_party/blink/renderer/core/intersection_observer/intersection_observation.h +++ b/third_party/blink/renderer/core/intersection_observer/intersection_observation.h
@@ -21,8 +21,8 @@ class IntersectionObservation final : public GarbageCollected<IntersectionObservation> { public: - // Flags that drive the behavior of the Compute() methods. For an explanation - // of implicit vs. explicit root, see intersection_observer.h. + // Flags that drive the behavior of the ComputeIntersections() method. For an + // explanation of implicit vs. explicit root, see intersection_observer.h. enum ComputeFlags { // If this bit is set, and observer_->RootIsImplicit() is true, then the // root bounds (i.e., size of the top document's viewport) should be @@ -45,15 +45,21 @@ IntersectionObserver* Observer() const { return observer_.Get(); } Element* Target() const { return target_; } unsigned LastThresholdIndex() const { return last_threshold_index_; } - // If the parameter is true and the observer doesn't have an explicit root, - // then any notifications generated will contain root bounds geometry. - void Compute(unsigned flags); + void ComputeIntersection(unsigned flags); + void ComputeIntersection( + const IntersectionGeometry::RootGeometry& root_geometry, + unsigned flags); void TakeRecords(HeapVector<Member<IntersectionObserverEntry>>&); void Disconnect(); void Trace(blink::Visitor*); private: + bool ShouldCompute(unsigned flags); + unsigned GetIntersectionGeometryFlags(unsigned compute_flags) const; + // Inspect the geometry to see if there has been a transition event; if so, + // generate a notification and schedule it for delivery. + void ProcessIntersectionGeometry(const IntersectionGeometry& geometry); void SetLastThresholdIndex(unsigned index) { last_threshold_index_ = index; } void SetWasVisible(bool last_is_visible) { last_is_visible_ = last_is_visible ? 1 : 0;
diff --git a/third_party/blink/renderer/core/intersection_observer/intersection_observer.cc b/third_party/blink/renderer/core/intersection_observer/intersection_observer.cc index 6d5effa..c8b56a7 100644 --- a/third_party/blink/renderer/core/intersection_observer/intersection_observer.cc +++ b/third_party/blink/renderer/core/intersection_observer/intersection_observer.cc
@@ -230,10 +230,7 @@ root_(root), thresholds_(thresholds), delay_(delay), - top_margin_(Length::Fixed(0)), - right_margin_(Length::Fixed(0)), - bottom_margin_(Length::Fixed(0)), - left_margin_(Length::Fixed(0)), + root_margin_(4, Length::Fixed(0)), root_is_implicit_(root ? 0 : 1), track_visibility_(track_visibility ? 1 : 0), track_fraction_of_root_(semantics == kFractionOfRoot), @@ -243,28 +240,34 @@ case 0: break; case 1: - top_margin_ = right_margin_ = bottom_margin_ = left_margin_ = + root_margin_[0] = root_margin_[1] = root_margin_[2] = root_margin_[3] = root_margin[0]; break; case 2: - top_margin_ = bottom_margin_ = root_margin[0]; - right_margin_ = left_margin_ = root_margin[1]; + root_margin_[0] = root_margin_[2] = root_margin[0]; + root_margin_[1] = root_margin_[3] = root_margin[1]; break; case 3: - top_margin_ = root_margin[0]; - right_margin_ = left_margin_ = root_margin[1]; - bottom_margin_ = root_margin[2]; + root_margin_[0] = root_margin[0]; + root_margin_[1] = root_margin_[3] = root_margin[1]; + root_margin_[2] = root_margin[2]; break; case 4: - top_margin_ = root_margin[0]; - right_margin_ = root_margin[1]; - bottom_margin_ = root_margin[2]; - left_margin_ = root_margin[3]; + root_margin_[0] = root_margin[0]; + root_margin_[1] = root_margin[1]; + root_margin_[2] = root_margin[2]; + root_margin_[3] = root_margin[3]; break; default: NOTREACHED(); break; } + if (root) { + root->EnsureIntersectionObserverData().AddObserver(*this); + root->GetDocument() + .EnsureIntersectionObserverController() + .AddTrackedElement(*root, track_visibility); + } } void IntersectionObserver::ClearWeakMembers(Visitor* visitor) { @@ -299,9 +302,11 @@ target->EnsureIntersectionObserverData().AddObservation(*observation); observations_.insert(observation); if (target->isConnected()) { - target->GetDocument() - .EnsureIntersectionObserverController() - .AddTrackedTarget(*target, track_visibility_); + if (RootIsImplicit()) { + target->GetDocument() + .EnsureIntersectionObserverController() + .AddTrackedElement(*target, track_visibility_); + } if (LocalFrameView* frame_view = target_frame->View()) { // The IntersectionObsever spec requires that at least one observation // be recorded after observe() is called, even if the frame is throttled. @@ -311,7 +316,7 @@ } else { // The IntersectionObsever spec requires that at least one observation // be recorded after observe() is called, even if the target is detached. - observation->Compute( + observation->ComputeIntersection( IntersectionObservation::kImplicitRootObserversNeedUpdate | IntersectionObservation::kExplicitRootObserversNeedUpdate); } @@ -356,13 +361,13 @@ String IntersectionObserver::rootMargin() const { StringBuilder string_builder; - AppendLength(string_builder, top_margin_); + AppendLength(string_builder, root_margin_[0]); string_builder.Append(' '); - AppendLength(string_builder, right_margin_); + AppendLength(string_builder, root_margin_[1]); string_builder.Append(' '); - AppendLength(string_builder, bottom_margin_); + AppendLength(string_builder, root_margin_[2]); string_builder.Append(' '); - AppendLength(string_builder, left_margin_); + AppendLength(string_builder, root_margin_[3]); return string_builder.ToString(); } @@ -378,6 +383,21 @@ return -1; } +bool IntersectionObserver::ComputeIntersections(unsigned flags) { + DCHECK(!RootIsImplicit()); + if (!RootIsValid() || !GetExecutionContext() || observations_.IsEmpty()) + return false; + IntersectionGeometry::RootGeometry root_geometry(root()->GetLayoutObject(), + root_margin_); + HeapVector<Member<IntersectionObservation>> observations_to_process; + // TODO(szager): Is this copy necessary? + CopyToVector(observations_, observations_to_process); + for (auto& observation : observations_to_process) { + observation->ComputeIntersection(root_geometry, flags); + } + return trackVisibility(); +} + void IntersectionObserver::SetNeedsDelivery() { if (needs_delivery_) return;
diff --git a/third_party/blink/renderer/core/intersection_observer/intersection_observer.h b/third_party/blink/renderer/core/intersection_observer/intersection_observer.h index 876c584..2cbd6de 100644 --- a/third_party/blink/renderer/core/intersection_observer/intersection_observer.h +++ b/third_party/blink/renderer/core/intersection_observer/intersection_observer.h
@@ -130,13 +130,20 @@ bool RootIsImplicit() const { return root_is_implicit_; } bool AlwaysReportRootBounds() const { return always_report_root_bounds_; } + bool NeedsOcclusionTracking() const { + return trackVisibility() && !observations_.IsEmpty(); + } DOMHighResTimeStamp GetTimeStamp() const; DOMHighResTimeStamp GetEffectiveDelay() const; - const Length& TopMargin() const { return top_margin_; } - const Length& RightMargin() const { return right_margin_; } - const Length& BottomMargin() const { return bottom_margin_; } - const Length& LeftMargin() const { return left_margin_; } + const Vector<Length>& RootMargin() const { return root_margin_; } + const Length& TopMargin() const { return root_margin_[0]; } + const Length& RightMargin() const { return root_margin_[1]; } + const Length& BottomMargin() const { return root_margin_[2]; } + const Length& LeftMargin() const { return root_margin_[3]; } + + bool ComputeIntersections(unsigned flags); + void SetNeedsDelivery(); DeliveryBehavior GetDeliveryBehavior() const; void Deliver(); @@ -162,10 +169,7 @@ HeapLinkedHashSet<WeakMember<IntersectionObservation>> observations_; Vector<float> thresholds_; DOMHighResTimeStamp delay_; - Length top_margin_; - Length right_margin_; - Length bottom_margin_; - Length left_margin_; + Vector<Length> root_margin_; unsigned root_is_implicit_ : 1; unsigned track_visibility_ : 1; unsigned track_fraction_of_root_ : 1;
diff --git a/third_party/blink/renderer/core/intersection_observer/intersection_observer_controller.cc b/third_party/blink/renderer/core/intersection_observer/intersection_observer_controller.cc index 1299a1a..8dd294b 100644 --- a/third_party/blink/renderer/core/intersection_observer/intersection_observer_controller.cc +++ b/third_party/blink/renderer/core/intersection_observer/intersection_observer_controller.cc
@@ -23,16 +23,15 @@ IntersectionObserverController::~IntersectionObserverController() = default; -void IntersectionObserverController::PostTaskToDeliverObservations() { +void IntersectionObserverController::PostTaskToDeliverNotifications() { DCHECK(GetExecutionContext()); GetExecutionContext() ->GetTaskRunner(TaskType::kInternalIntersectionObserver) ->PostTask( FROM_HERE, - WTF::Bind( - &IntersectionObserverController::DeliverIntersectionObservations, - WrapWeakPersistent(this), - IntersectionObserver::kPostTaskToDeliver)); + WTF::Bind(&IntersectionObserverController::DeliverNotifications, + WrapWeakPersistent(this), + IntersectionObserver::kPostTaskToDeliver)); } void IntersectionObserverController::ScheduleIntersectionObserverForDelivery( @@ -40,10 +39,10 @@ pending_intersection_observers_.insert(&observer); if (observer.GetDeliveryBehavior() == IntersectionObserver::kPostTaskToDeliver) - PostTaskToDeliverObservations(); + PostTaskToDeliverNotifications(); } -void IntersectionObserverController::DeliverIntersectionObservations( +void IntersectionObserverController::DeliverNotifications( IntersectionObserver::DeliveryBehavior behavior) { ExecutionContext* context = GetExecutionContext(); if (!context) { @@ -61,30 +60,29 @@ } } -bool IntersectionObserverController::ComputeTrackedIntersectionObservations( - unsigned flags) { +bool IntersectionObserverController::ComputeIntersections(unsigned flags) { needs_occlusion_tracking_ = false; if (Document* document = To<Document>(GetExecutionContext())) { TRACE_EVENT0("blink", "IntersectionObserverController::" - "computeTrackedIntersectionObservations"); + "computeIntersections"); HeapVector<Member<Element>> elements_to_process; - CopyToVector(tracked_observation_targets_, elements_to_process); + CopyToVector(tracked_elements_, elements_to_process); for (auto& element : elements_to_process) { needs_occlusion_tracking_ |= - element->ComputeIntersectionObservations(flags); + element->ComputeIntersectionsForLifecycleUpdate(flags); } } return needs_occlusion_tracking_; } -void IntersectionObserverController::AddTrackedTarget(Element& target, - bool track_occlusion) { - tracked_observation_targets_.insert(&target); +void IntersectionObserverController::AddTrackedElement(Element& element, + bool track_occlusion) { + tracked_elements_.insert(&element); if (!track_occlusion) return; needs_occlusion_tracking_ = true; - if (LocalFrameView* frame_view = target.GetDocument().View()) { + if (LocalFrameView* frame_view = element.GetDocument().View()) { if (FrameOwner* frame_owner = frame_view->GetFrame().Owner()) { // Set this bit as early as possible, rather than waiting for a lifecycle // update to recompute it. @@ -93,17 +91,17 @@ } } -void IntersectionObserverController::RemoveTrackedTarget(Element& target) { +void IntersectionObserverController::RemoveTrackedElement(Element& target) { // Note that we don't try to opportunistically turn off the 'needs occlusion // tracking' bit here, like the way we turn it on in AddTrackedTarget. The // bit will get recomputed on the next lifecycle update; there's no // compelling reason to do it here, so we avoid the iteration through targets // and observations here. - tracked_observation_targets_.erase(&target); + tracked_elements_.erase(&target); } void IntersectionObserverController::Trace(blink::Visitor* visitor) { - visitor->Trace(tracked_observation_targets_); + visitor->Trace(tracked_elements_); visitor->Trace(pending_intersection_observers_); ContextClient::Trace(visitor); }
diff --git a/third_party/blink/renderer/core/intersection_observer/intersection_observer_controller.h b/third_party/blink/renderer/core/intersection_observer/intersection_observer_controller.h index 937a480..c67d7347 100644 --- a/third_party/blink/renderer/core/intersection_observer/intersection_observer_controller.h +++ b/third_party/blink/renderer/core/intersection_observer/intersection_observer_controller.h
@@ -32,19 +32,18 @@ // Immediately deliver all notifications for all observers for which // (observer->GetDeliveryBehavior() == behavior). - void DeliverIntersectionObservations( - IntersectionObserver::DeliveryBehavior behavior); + void DeliverNotifications(IntersectionObserver::DeliveryBehavior behavior); // The flags argument is composed of values from // IntersectionObservation::ComputeFlags. They are dirty bits that control // whether an IntersectionObserver needs to do any work. The return value // communicates whether observer->trackVisibility() is true for any tracked // observer. - bool ComputeTrackedIntersectionObservations(unsigned flags); - // The second argument indicates whether the Element is being tracked by any + bool ComputeIntersections(unsigned flags); + // The second argument indicates whether the Element is a target of any // observers for which observer->trackVisibility() is true. - void AddTrackedTarget(Element&, bool); - void RemoveTrackedTarget(Element&); + void AddTrackedElement(Element&, bool); + void RemoveTrackedElement(Element&); bool NeedsOcclusionTracking() const { return needs_occlusion_tracking_; } void Trace(blink::Visitor*) override; @@ -52,21 +51,21 @@ return "IntersectionObserverController"; } unsigned GetTrackedTargetCountForTesting() const { - return tracked_observation_targets_.size(); + return tracked_elements_.size(); } private: - void PostTaskToDeliverObservations(); + void PostTaskToDeliverNotifications(); private: - // Elements in this document which are the target of an - // IntersectionObservation. - HeapHashSet<WeakMember<Element>> tracked_observation_targets_; + // Elements in this document which are the target of an IntersectionObserver + // with implicit root; or the explicit root of an IntersectionObserver. + HeapHashSet<WeakMember<Element>> tracked_elements_; // IntersectionObservers for which this is the execution context of the // callback. HeapHashSet<Member<IntersectionObserver>> pending_intersection_observers_; - // This is 'true' if any tracked observation target is being tracked by an - // observer for which observer->trackVisibility() is true. + // This is 'true' if any tracked element is the target of an observer for + // which observer->trackVisibility() is true. bool needs_occlusion_tracking_; };
diff --git a/third_party/blink/renderer/core/page/chrome_client_impl.cc b/third_party/blink/renderer/core/page/chrome_client_impl.cc index 53ebd843..39bd751 100644 --- a/third_party/blink/renderer/core/page/chrome_client_impl.cc +++ b/third_party/blink/renderer/core/page/chrome_client_impl.cc
@@ -857,7 +857,7 @@ HTMLSelectElement& select) { NotifyPopupOpeningObservers(); if (WebViewImpl::UseExternalPopupMenus()) - return MakeGarbageCollected<ExternalPopupMenu>(frame, select, *web_view_); + return MakeGarbageCollected<ExternalPopupMenu>(frame, select); DCHECK(RuntimeEnabledFeatures::PagePopupEnabled()); return MakeGarbageCollected<InternalPopupMenu>(this, select);
diff --git a/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/sets.mjs b/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/sets.mjs index 9df6062..cd89ffe 100644 --- a/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/sets.mjs +++ b/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/sets.mjs
@@ -22,3 +22,29 @@ } return result; } + +/** + * Callback applying to an item in a set. + * + * @callback applyToDiff + * @param {any} item + */ + +/** + * Calculates the difference between |oldSet| and |newSet| and applies + * |deletedFunc| or |addedFunc| to the elements that were deleted or added. + * + * Returns the number of elements operated on. + * + * @param {!Set} oldSet A set of elements. + * @param {!Set} newSet A set of elements. + * @param {applyToDiff} deletedFun A function to be applied to deleted elements. + * @param {applyToDiff} addedFun A function to be applied to added elements. + */ +export function applyToDiffs(oldSet, newSet, deletedFunc, addedFunc) { + const deleted = difference(oldSet, newSet); + const added = difference(newSet, oldSet); + deleted.forEach(deletedFunc); + added.forEach(addedFunc); + return deleted.size + added.size; +}
diff --git a/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/visibility-manager.mjs b/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/visibility-manager.mjs index f5994b1a5..14362f0b 100644 --- a/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/visibility-manager.mjs +++ b/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/visibility-manager.mjs
@@ -137,6 +137,7 @@ #intersectionObserver; #revealed = new Set(); + #observed = new Set(); constructor(container) { this.#elements = container.children; @@ -185,27 +186,58 @@ const newBounds = this.#findElementBounds(desiredLow, desiredHigh); const newRevealed = newBounds.elementSet(); - // TODO(fergal): We need to observe 1 element off the end of the - // list, to cope with e.g. the scrolling region suddenly growing. + // This should include all of the elements to be revealed and + // also 1 element above and below those (if such elements + // exist). + const newObserved = new Set(); + if (newRevealed.size !== 0) { + newObserved.add(...newRevealed); + const p = newBounds.low.previousElementSibling; + if (p) { + newObserved.add(p); + } + const n = newBounds.high.nextElementSibling; + if (n) { + newObserved.add(n); + } + } - // Lock and unlock the minimal set of elements to get us to the - // new state. - const toHide = sets.difference(this.#revealed, newRevealed); - toHide.forEach(e => this.#hide(e)); - const toReveal = sets.difference(newRevealed, this.#revealed); - toReveal.forEach(e => this.#reveal(e)); - - // Now we have revealed what we hope will fill the screen. It + // Having revealed what we hope will fill the screen. It // could be incorrect. Rather than measuring now and correcting it // which would involve an unknown number of forced layouts, we // come back next frame and try to make it better. We know we can // stop when we didn't hide or reveal any elements. - if (toHide.size > 0 || toReveal.size > 0) { + if (this.#syncRevealed(newRevealed) + + this.#syncObserved(newObserved) > 0) { this.scheduleSync(); } } /** + * Calls hide and reveal on child elements to take us to the new state. + * + * Returns the number of elements impacted. + */ + #syncRevealed = + newRevealed => { + return sets.applyToDiffs( + this.#revealed, newRevealed, e => this.#hide(e), + e => this.#reveal(e)); + } + + /** + * Calls observe and unobserve on child elements to take us to the new state. + * + * Returns the number of elements impacted. + */ + #syncObserved = + newObserved => { + return sets.applyToDiffs( + this.#observed, newObserved, e => this.#unobserve(e), + e => this.#observe(e)); + } + + /** * Searches within the managed elements and returns an ElementBounds * object. This object may represent an empty range or a range whose low * element contains or is lower than |low| (or the lowest element @@ -254,24 +286,32 @@ } /** - * Reveals |element| so that it can be rendered. This includes - * unlocking and adding to various observers. + * Unlocks |element| so that it can be rendered. * * @param {!Element} element The element to reveal. */ #reveal = element => { this.#revealed.add(element); - this.#intersectionObserver.observe(element); this.#unlock(element); } + /** + * Observes |element| so that it coming on-/off-screen causes a sync. + * + * @param {!Element} element The element to observe. + */ + #observe = + element => { + this.#intersectionObserver.observe(element); + this.#observed.add(element); + } + #logLockingError = (operation, reason, element) => { // TODO: Figure out the LAPIs error/warning logging story. console.error( // eslint-disable-line no-console - 'Rejected: ', operation, element, - reason); + 'Rejected: ', operation, element, reason); } /** @@ -290,15 +330,13 @@ } /** - * Hides |element| so that it cannot be rendered. This includes - * locking and removing from various observers. + * Locks |element| so that it cannot be rendered. * - * @param {!Element} element The element to hide. + * @param {!Element} element The element to lock. */ #hide = element => { this.#revealed.delete(element); - this.#intersectionObserver.unobserve(element); element.displayLock .acquire({ timeout: Infinity, @@ -315,6 +353,18 @@ } /** + * Unobserves |element| so that it coming on-/off-screen does not + * cause a sync. + * + * @param {!Element} element The element to unobserve. + */ + #unobserve = + element => { + this.#intersectionObserver.unobserve(element); + this.#observed.delete(element); + } + + /** * Notify the manager that |element| has been added to the list of * managed elements. * @@ -349,7 +399,7 @@ this.#unlock(element); } this.#revealed.delete(element); - this.#intersectionObserver.unobserve(element); + this.#unobserve(element); this.#sizeManager.remove(element); }
diff --git a/third_party/blink/renderer/devtools/front_end/common/Settings.js b/third_party/blink/renderer/devtools/front_end/common/Settings.js index 551fc34..2c1e9844 100644 --- a/third_party/blink/renderer/devtools/front_end/common/Settings.js +++ b/third_party/blink/renderer/devtools/front_end/common/Settings.js
@@ -73,8 +73,8 @@ } const setting = isRegex ? this.createRegExpSetting(settingName, defaultValue, undefined, storageType) : this.createSetting(settingName, defaultValue, storageType); - if (descriptor['title']) - setting.setTitle(descriptor['title']); + if (extension.title()) + setting.setTitle(extension.title()); if (descriptor['userActionCondition']) setting.setRequiresUserAction(!!Runtime.queryParam(descriptor['userActionCondition'])); setting._extension = extension;
diff --git a/third_party/blink/renderer/modules/native_file_system/file_system_directory_handle.idl b/third_party/blink/renderer/modules/native_file_system/file_system_directory_handle.idl index 5cb829a..5bbe384a 100644 --- a/third_party/blink/renderer/modules/native_file_system/file_system_directory_handle.idl +++ b/third_party/blink/renderer/modules/native_file_system/file_system_directory_handle.idl
@@ -15,6 +15,6 @@ [CallWith=ScriptState] Promise<void> removeEntry(USVString name, optional FileSystemRemoveOptions options); - [CallWith=ScriptState] + [CallWith=ScriptState, Measure] static Promise<FileSystemDirectoryHandle> getSystemDirectory(GetSystemDirectoryOptions options); };
diff --git a/third_party/blink/renderer/modules/native_file_system/file_system_handle.idl b/third_party/blink/renderer/modules/native_file_system/file_system_handle.idl index 39c7edc..05af4219 100644 --- a/third_party/blink/renderer/modules/native_file_system/file_system_handle.idl +++ b/third_party/blink/renderer/modules/native_file_system/file_system_handle.idl
@@ -17,8 +17,8 @@ readonly attribute USVString name; - [CallWith = ScriptState] Promise<PermissionState> queryPermission( + [CallWith=ScriptState] Promise<PermissionState> queryPermission( optional FileSystemHandlePermissionDescriptor descriptor); - [CallWith = ScriptState] Promise<PermissionState> requestPermission( + [CallWith=ScriptState] Promise<PermissionState> requestPermission( optional FileSystemHandlePermissionDescriptor descriptor); };
diff --git a/third_party/blink/renderer/modules/native_file_system/window_native_file_system.idl b/third_party/blink/renderer/modules/native_file_system/window_native_file_system.idl index f17cd62..e2b338d 100644 --- a/third_party/blink/renderer/modules/native_file_system/window_native_file_system.idl +++ b/third_party/blink/renderer/modules/native_file_system/window_native_file_system.idl
@@ -8,7 +8,7 @@ RuntimeEnabled=NativeFileSystem, ImplementedAs=WindowNativeFileSystem ] partial interface Window { - [CallWith=ScriptState] + [CallWith=ScriptState, Measure] Promise<(FileSystemHandle or sequence<FileSystemHandle>)> chooseFileSystemEntries(optional ChooseFileSystemEntriesOptions options); };
diff --git a/third_party/blink/renderer/modules/peerconnection/media_stream_remote_video_source.cc b/third_party/blink/renderer/modules/peerconnection/media_stream_remote_video_source.cc index ea9d9c8a..77da47c9 100644 --- a/third_party/blink/renderer/modules/peerconnection/media_stream_remote_video_source.cc +++ b/third_party/blink/renderer/modules/peerconnection/media_stream_remote_video_source.cc
@@ -16,8 +16,8 @@ #include "media/base/video_util.h" #include "third_party/blink/public/mojom/mediastream/media_stream.mojom-blink.h" #include "third_party/blink/public/platform/modules/webrtc/track_observer.h" -#include "third_party/blink/public/platform/modules/webrtc/webrtc_video_frame_adapter.h" #include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h" +#include "third_party/blink/renderer/platform/webrtc/webrtc_video_frame_adapter.h" #include "third_party/blink/renderer/platform/webrtc/webrtc_video_utils.h" #include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h" #include "third_party/blink/renderer/platform/wtf/functional.h"
diff --git a/third_party/blink/renderer/platform/BUILD.gn b/third_party/blink/renderer/platform/BUILD.gn index e24340b6..354e6c7 100644 --- a/third_party/blink/renderer/platform/BUILD.gn +++ b/third_party/blink/renderer/platform/BUILD.gn
@@ -1378,6 +1378,7 @@ "webrtc/track_observer.cc", "webrtc/webrtc_logging.cc", "webrtc/webrtc_video_frame_adapter.cc", + "webrtc/webrtc_video_frame_adapter.h", "webrtc/webrtc_video_utils.cc", "webrtc/webrtc_video_utils.h", "windows_keyboard_codes.h",
diff --git a/third_party/blink/renderer/platform/peerconnection/rtc_video_decoder_adapter.cc b/third_party/blink/renderer/platform/peerconnection/rtc_video_decoder_adapter.cc index 056c14f..007fae4 100644 --- a/third_party/blink/renderer/platform/peerconnection/rtc_video_decoder_adapter.cc +++ b/third_party/blink/renderer/platform/peerconnection/rtc_video_decoder_adapter.cc
@@ -29,8 +29,8 @@ #include "media/video/gpu_video_accelerator_factories.h" #include "media/video/video_decode_accelerator.h" #include "third_party/blink/public/platform/modules/peerconnection/web_rtc_video_frame_adapter_factory.h" -#include "third_party/blink/public/platform/modules/webrtc/webrtc_video_frame_adapter.h" #include "third_party/blink/public/platform/platform.h" +#include "third_party/blink/renderer/platform/webrtc/webrtc_video_frame_adapter.h" #include "third_party/blink/renderer/platform/webrtc/webrtc_video_utils.h" #include "third_party/webrtc/api/video/video_frame.h" #include "third_party/webrtc/media/base/vp9_profile.h"
diff --git a/third_party/blink/renderer/platform/peerconnection/rtc_video_encoder.cc b/third_party/blink/renderer/platform/peerconnection/rtc_video_encoder.cc index e6fd3978..30f76ab 100644 --- a/third_party/blink/renderer/platform/peerconnection/rtc_video_encoder.cc +++ b/third_party/blink/renderer/platform/peerconnection/rtc_video_encoder.cc
@@ -30,8 +30,8 @@ #include "media/video/video_encode_accelerator.h" #include "mojo/public/cpp/base/shared_memory_utils.h" #include "third_party/blink/public/platform/modules/peerconnection/web_rtc_video_encoder_factory.h" -#include "third_party/blink/public/platform/modules/webrtc/webrtc_video_frame_adapter.h" #include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h" +#include "third_party/blink/renderer/platform/webrtc/webrtc_video_frame_adapter.h" #include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h" #include "third_party/blink/renderer/platform/wtf/deque.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
diff --git a/third_party/blink/renderer/platform/peerconnection/webrtc_video_track_source.cc b/third_party/blink/renderer/platform/peerconnection/webrtc_video_track_source.cc index 171d58e..95788af 100644 --- a/third_party/blink/renderer/platform/peerconnection/webrtc_video_track_source.cc +++ b/third_party/blink/renderer/platform/peerconnection/webrtc_video_track_source.cc
@@ -7,7 +7,7 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/trace_event/trace_event.h" -#include "third_party/blink/public/platform/modules/webrtc/webrtc_video_frame_adapter.h" +#include "third_party/blink/renderer/platform/webrtc/webrtc_video_frame_adapter.h" #include "third_party/libyuv/include/libyuv/scale.h" #include "third_party/webrtc/rtc_base/ref_counted_object.h"
diff --git a/third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h b/third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h index ad6a9ee..cfbe0ea5 100644 --- a/third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h +++ b/third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h
@@ -14,18 +14,18 @@ namespace blink { // For cross-thread posting. Can be called from any thread. -inline void PostCrossThreadTask(base::SequencedTaskRunner& task_runner, +inline bool PostCrossThreadTask(base::SequencedTaskRunner& task_runner, const base::Location& location, WTF::CrossThreadOnceClosure task) { - task_runner.PostDelayedTask( + return task_runner.PostDelayedTask( location, ConvertToBaseOnceCallback(std::move(task)), base::TimeDelta()); } -inline void PostDelayedCrossThreadTask(base::SequencedTaskRunner& task_runner, +inline bool PostDelayedCrossThreadTask(base::SequencedTaskRunner& task_runner, const base::Location& location, WTF::CrossThreadOnceClosure task, base::TimeDelta delay) { - task_runner.PostDelayedTask( + return task_runner.PostDelayedTask( location, ConvertToBaseOnceCallback(std::move(task)), delay); }
diff --git a/third_party/blink/renderer/platform/webrtc/webrtc_video_frame_adapter.cc b/third_party/blink/renderer/platform/webrtc/webrtc_video_frame_adapter.cc index 13f8fdb..f7708a9 100644 --- a/third_party/blink/renderer/platform/webrtc/webrtc_video_frame_adapter.cc +++ b/third_party/blink/renderer/platform/webrtc/webrtc_video_frame_adapter.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 "third_party/blink/public/platform/modules/webrtc/webrtc_video_frame_adapter.h" +#include "third_party/blink/renderer/platform/webrtc/webrtc_video_frame_adapter.h" #include "base/logging.h" #include "third_party/webrtc/common_video/include/video_frame_buffer.h"
diff --git a/third_party/blink/public/platform/modules/webrtc/webrtc_video_frame_adapter.h b/third_party/blink/renderer/platform/webrtc/webrtc_video_frame_adapter.h similarity index 73% rename from third_party/blink/public/platform/modules/webrtc/webrtc_video_frame_adapter.h rename to third_party/blink/renderer/platform/webrtc/webrtc_video_frame_adapter.h index 670339f..3b674a2 100644 --- a/third_party/blink/public/platform/modules/webrtc/webrtc_video_frame_adapter.h +++ b/third_party/blink/renderer/platform/webrtc/webrtc_video_frame_adapter.h
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_WEBRTC_WEBRTC_VIDEO_FRAME_ADAPTER_H_ -#define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_WEBRTC_WEBRTC_VIDEO_FRAME_ADAPTER_H_ +#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_WEBRTC_WEBRTC_VIDEO_FRAME_ADAPTER_H_ +#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_WEBRTC_WEBRTC_VIDEO_FRAME_ADAPTER_H_ #include <stdint.h> #include "media/base/video_frame.h" -#include "third_party/blink/public/platform/web_common.h" +#include "third_party/blink/renderer/platform/platform_export.h" #include "third_party/webrtc/api/video/video_frame_buffer.h" namespace blink { @@ -16,10 +16,7 @@ // implementation is read-only and will return null if trying to get a // non-const pointer to the pixel data. This object will be accessed from // different threads, but that's safe since it's read-only. -// -// TODO(crbug.com/704136): Move the class below out of the Blink exposed -// API when all users of it have been Onion souped. -class BLINK_PLATFORM_EXPORT WebRtcVideoFrameAdapter +class PLATFORM_EXPORT WebRtcVideoFrameAdapter : public webrtc::VideoFrameBuffer { public: explicit WebRtcVideoFrameAdapter(scoped_refptr<media::VideoFrame> frame); @@ -48,4 +45,4 @@ } // namespace blink -#endif // THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_WEBRTC_WEBRTC_VIDEO_FRAME_ADAPTER_H_ +#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_WEBRTC_WEBRTC_VIDEO_FRAME_ADAPTER_H_
diff --git a/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py b/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py index 9a3e6bc..86bf13b9 100755 --- a/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py +++ b/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py
@@ -372,6 +372,10 @@ # Some test helpers live in the blink::test namespace. 'test::.+', + # Some test helpers that live in the blink::frame_test_helpers + # namespace. + 'frame_test_helpers::.+', + # Blink uses Mojo, so it needs mojo::Binding, mojo::InterfacePtr, et # cetera, as well as generated Mojo bindings. # Note that the Mojo callback helpers are explicitly forbidden:
diff --git a/third_party/blink/web_tests/external/wpt/css/css-grid/animation/grid-template-columns-interpolation-expected.txt b/third_party/blink/web_tests/external/wpt/css/css-grid/animation/grid-template-columns-interpolation-expected.txt index dad4474d..15f1181 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-grid/animation/grid-template-columns-interpolation-expected.txt +++ b/third_party/blink/web_tests/external/wpt/css/css-grid/animation/grid-template-columns-interpolation-expected.txt
@@ -141,25 +141,25 @@ FAIL CSS Transitions: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (0.4) should be [calc(8% + 6px) calc(12% + 12px) 34px] assert_equals: expected "calc ( 8 % + 6px ) calc ( 12 % + 12px ) 34px " but got "20 % 30 % 40px " FAIL CSS Transitions: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (0.6) should be [calc(12% + 4px) calc(18% + 8px) 36px] assert_equals: expected "calc ( 12 % + 4px ) calc ( 18 % + 8px ) 36px " but got "20 % 30 % 40px " PASS CSS Transitions: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (1) should be [20% 30% 40px] -FAIL CSS Transitions: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (2) should be [calc(40% + -10px) calc(60% + -20px) 50px] assert_equals: expected "calc ( 40 % + - 10px ) calc ( 60 % + - 20px ) 50px " but got "20 % 30 % 40px " +FAIL CSS Transitions: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (2) should be [calc(40% - 10px) calc(60% - 20px) 50px] assert_equals: expected "calc ( 40 % - 10px ) calc ( 60 % - 20px ) 50px " but got "20 % 30 % 40px " FAIL CSS Transitions with transition: all: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (-1) should be [calc(-20% + 20px) calc(-30% + 40px) 20px] assert_equals: expected "calc ( - 20 % + 20px ) calc ( - 30 % + 40px ) 20px " but got "20 % 30 % 40px " FAIL CSS Transitions with transition: all: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (0) should be [10px 20px 30px] assert_equals: expected "10px 20px 30px " but got "20 % 30 % 40px " FAIL CSS Transitions with transition: all: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (0.4) should be [calc(8% + 6px) calc(12% + 12px) 34px] assert_equals: expected "calc ( 8 % + 6px ) calc ( 12 % + 12px ) 34px " but got "20 % 30 % 40px " FAIL CSS Transitions with transition: all: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (0.6) should be [calc(12% + 4px) calc(18% + 8px) 36px] assert_equals: expected "calc ( 12 % + 4px ) calc ( 18 % + 8px ) 36px " but got "20 % 30 % 40px " PASS CSS Transitions with transition: all: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (1) should be [20% 30% 40px] -FAIL CSS Transitions with transition: all: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (2) should be [calc(40% + -10px) calc(60% + -20px) 50px] assert_equals: expected "calc ( 40 % + - 10px ) calc ( 60 % + - 20px ) 50px " but got "20 % 30 % 40px " +FAIL CSS Transitions with transition: all: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (2) should be [calc(40% - 10px) calc(60% - 20px) 50px] assert_equals: expected "calc ( 40 % - 10px ) calc ( 60 % - 20px ) 50px " but got "20 % 30 % 40px " FAIL CSS Animations: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (-1) should be [calc(-20% + 20px) calc(-30% + 40px) 20px] assert_equals: expected "calc ( - 20 % + 20px ) calc ( - 30 % + 40px ) 20px " but got "10px 20px 30px " PASS CSS Animations: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (0) should be [10px 20px 30px] FAIL CSS Animations: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (0.4) should be [calc(8% + 6px) calc(12% + 12px) 34px] assert_equals: expected "calc ( 8 % + 6px ) calc ( 12 % + 12px ) 34px " but got "10px 20px 30px " FAIL CSS Animations: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (0.6) should be [calc(12% + 4px) calc(18% + 8px) 36px] assert_equals: expected "calc ( 12 % + 4px ) calc ( 18 % + 8px ) 36px " but got "20 % 30 % 40px " PASS CSS Animations: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (1) should be [20% 30% 40px] -FAIL CSS Animations: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (2) should be [calc(40% + -10px) calc(60% + -20px) 50px] assert_equals: expected "calc ( 40 % + - 10px ) calc ( 60 % + - 20px ) 50px " but got "20 % 30 % 40px " +FAIL CSS Animations: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (2) should be [calc(40% - 10px) calc(60% - 20px) 50px] assert_equals: expected "calc ( 40 % - 10px ) calc ( 60 % - 20px ) 50px " but got "20 % 30 % 40px " FAIL Web Animations: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (-1) should be [calc(-20% + 20px) calc(-30% + 40px) 20px] assert_equals: expected "calc ( - 20 % + 20px ) calc ( - 30 % + 40px ) 20px " but got "10px 20px 30px " PASS Web Animations: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (0) should be [10px 20px 30px] FAIL Web Animations: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (0.4) should be [calc(8% + 6px) calc(12% + 12px) 34px] assert_equals: expected "calc ( 8 % + 6px ) calc ( 12 % + 12px ) 34px " but got "10px 20px 30px " FAIL Web Animations: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (0.6) should be [calc(12% + 4px) calc(18% + 8px) 36px] assert_equals: expected "calc ( 12 % + 4px ) calc ( 18 % + 8px ) 36px " but got "20 % 30 % 40px " PASS Web Animations: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (1) should be [20% 30% 40px] -FAIL Web Animations: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (2) should be [calc(40% + -10px) calc(60% + -20px) 50px] assert_equals: expected "calc ( 40 % + - 10px ) calc ( 60 % + - 20px ) 50px " but got "20 % 30 % 40px " +FAIL Web Animations: property <grid-template-columns> from [10px 20px 30px] to [20% 30% 40px] at (2) should be [calc(40% - 10px) calc(60% - 20px) 50px] assert_equals: expected "calc ( 40 % - 10px ) calc ( 60 % - 20px ) 50px " but got "20 % 30 % 40px " FAIL CSS Transitions: property <grid-template-columns> from [1fr 1fr 1fr] to [2fr auto 2fr] at (-1) should be [0fr 1fr 0fr] assert_equals: expected "0fr 1fr 0fr " but got "2fr auto 2fr " FAIL CSS Transitions: property <grid-template-columns> from [1fr 1fr 1fr] to [2fr auto 2fr] at (0) should be [1fr 1fr 1fr] assert_equals: expected "1fr 1fr 1fr " but got "2fr auto 2fr " FAIL CSS Transitions: property <grid-template-columns> from [1fr 1fr 1fr] to [2fr auto 2fr] at (0.4) should be [1.4fr 1fr 1.4fr] assert_equals: expected "1.4fr 1fr 1.4fr " but got "2fr auto 2fr "
diff --git a/third_party/blink/web_tests/external/wpt/css/css-grid/animation/grid-template-rows-interpolation-expected.txt b/third_party/blink/web_tests/external/wpt/css/css-grid/animation/grid-template-rows-interpolation-expected.txt index 2a2a6d8..497a536 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-grid/animation/grid-template-rows-interpolation-expected.txt +++ b/third_party/blink/web_tests/external/wpt/css/css-grid/animation/grid-template-rows-interpolation-expected.txt
@@ -141,25 +141,25 @@ FAIL CSS Transitions: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (0.4) should be [calc(8% + 6px) calc(12% + 12px) 34px] assert_equals: expected "calc ( 8 % + 6px ) calc ( 12 % + 12px ) 34px " but got "20 % 30 % 40px " FAIL CSS Transitions: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (0.6) should be [calc(12% + 4px) calc(18% + 8px) 36px] assert_equals: expected "calc ( 12 % + 4px ) calc ( 18 % + 8px ) 36px " but got "20 % 30 % 40px " PASS CSS Transitions: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (1) should be [20% 30% 40px] -FAIL CSS Transitions: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (2) should be [calc(40% + -10px) calc(60% + -20px) 50px] assert_equals: expected "calc ( 40 % + - 10px ) calc ( 60 % + - 20px ) 50px " but got "20 % 30 % 40px " +FAIL CSS Transitions: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (2) should be [calc(40% - 10px) calc(60% - 20px) 50px] assert_equals: expected "calc ( 40 % - 10px ) calc ( 60 % - 20px ) 50px " but got "20 % 30 % 40px " FAIL CSS Transitions with transition: all: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (-1) should be [calc(-20% + 20px) calc(-30% + 40px) 20px] assert_equals: expected "calc ( - 20 % + 20px ) calc ( - 30 % + 40px ) 20px " but got "20 % 30 % 40px " FAIL CSS Transitions with transition: all: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (0) should be [10px 20px 30px] assert_equals: expected "10px 20px 30px " but got "20 % 30 % 40px " FAIL CSS Transitions with transition: all: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (0.4) should be [calc(8% + 6px) calc(12% + 12px) 34px] assert_equals: expected "calc ( 8 % + 6px ) calc ( 12 % + 12px ) 34px " but got "20 % 30 % 40px " FAIL CSS Transitions with transition: all: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (0.6) should be [calc(12% + 4px) calc(18% + 8px) 36px] assert_equals: expected "calc ( 12 % + 4px ) calc ( 18 % + 8px ) 36px " but got "20 % 30 % 40px " PASS CSS Transitions with transition: all: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (1) should be [20% 30% 40px] -FAIL CSS Transitions with transition: all: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (2) should be [calc(40% + -10px) calc(60% + -20px) 50px] assert_equals: expected "calc ( 40 % + - 10px ) calc ( 60 % + - 20px ) 50px " but got "20 % 30 % 40px " +FAIL CSS Transitions with transition: all: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (2) should be [calc(40% - 10px) calc(60% - 20px) 50px] assert_equals: expected "calc ( 40 % - 10px ) calc ( 60 % - 20px ) 50px " but got "20 % 30 % 40px " FAIL CSS Animations: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (-1) should be [calc(-20% + 20px) calc(-30% + 40px) 20px] assert_equals: expected "calc ( - 20 % + 20px ) calc ( - 30 % + 40px ) 20px " but got "10px 20px 30px " PASS CSS Animations: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (0) should be [10px 20px 30px] FAIL CSS Animations: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (0.4) should be [calc(8% + 6px) calc(12% + 12px) 34px] assert_equals: expected "calc ( 8 % + 6px ) calc ( 12 % + 12px ) 34px " but got "10px 20px 30px " FAIL CSS Animations: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (0.6) should be [calc(12% + 4px) calc(18% + 8px) 36px] assert_equals: expected "calc ( 12 % + 4px ) calc ( 18 % + 8px ) 36px " but got "20 % 30 % 40px " PASS CSS Animations: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (1) should be [20% 30% 40px] -FAIL CSS Animations: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (2) should be [calc(40% + -10px) calc(60% + -20px) 50px] assert_equals: expected "calc ( 40 % + - 10px ) calc ( 60 % + - 20px ) 50px " but got "20 % 30 % 40px " +FAIL CSS Animations: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (2) should be [calc(40% - 10px) calc(60% - 20px) 50px] assert_equals: expected "calc ( 40 % - 10px ) calc ( 60 % - 20px ) 50px " but got "20 % 30 % 40px " FAIL Web Animations: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (-1) should be [calc(-20% + 20px) calc(-30% + 40px) 20px] assert_equals: expected "calc ( - 20 % + 20px ) calc ( - 30 % + 40px ) 20px " but got "10px 20px 30px " PASS Web Animations: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (0) should be [10px 20px 30px] FAIL Web Animations: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (0.4) should be [calc(8% + 6px) calc(12% + 12px) 34px] assert_equals: expected "calc ( 8 % + 6px ) calc ( 12 % + 12px ) 34px " but got "10px 20px 30px " FAIL Web Animations: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (0.6) should be [calc(12% + 4px) calc(18% + 8px) 36px] assert_equals: expected "calc ( 12 % + 4px ) calc ( 18 % + 8px ) 36px " but got "20 % 30 % 40px " PASS Web Animations: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (1) should be [20% 30% 40px] -FAIL Web Animations: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (2) should be [calc(40% + -10px) calc(60% + -20px) 50px] assert_equals: expected "calc ( 40 % + - 10px ) calc ( 60 % + - 20px ) 50px " but got "20 % 30 % 40px " +FAIL Web Animations: property <grid-template-rows> from [10px 20px 30px] to [20% 30% 40px] at (2) should be [calc(40% - 10px) calc(60% - 20px) 50px] assert_equals: expected "calc ( 40 % - 10px ) calc ( 60 % - 20px ) 50px " but got "20 % 30 % 40px " FAIL CSS Transitions: property <grid-template-rows> from [1fr 1fr 1fr] to [2fr auto 2fr] at (-1) should be [0fr 1fr 0fr] assert_equals: expected "0fr 1fr 0fr " but got "2fr auto 2fr " FAIL CSS Transitions: property <grid-template-rows> from [1fr 1fr 1fr] to [2fr auto 2fr] at (0) should be [1fr 1fr 1fr] assert_equals: expected "1fr 1fr 1fr " but got "2fr auto 2fr " FAIL CSS Transitions: property <grid-template-rows> from [1fr 1fr 1fr] to [2fr auto 2fr] at (0.4) should be [1.4fr 1fr 1.4fr] assert_equals: expected "1.4fr 1fr 1.4fr " but got "2fr auto 2fr "
diff --git a/third_party/blink/web_tests/external/wpt/css/css-images/parsing/object-position-computed.html b/third_party/blink/web_tests/external/wpt/css/css-images/parsing/object-position-computed.html index 37b198c5..9748914 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-images/parsing/object-position-computed.html +++ b/third_party/blink/web_tests/external/wpt/css/css-images/parsing/object-position-computed.html
@@ -26,6 +26,7 @@ test_computed_value("object-position", "center top", "50% 0%"); test_computed_value("object-position", "center", "50% 50%"); test_computed_value("object-position", "center center", "50% 50%"); +test_computed_value("object-position", "right 20px bottom 10px", "calc(100% - 20px) calc(100% - 10px)"); </script> </body> </html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/values/shape-margin-003-expected.txt b/third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/values/shape-margin-003-expected.txt deleted file mode 100644 index 104e0bb..0000000 --- a/third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/values/shape-margin-003-expected.txt +++ /dev/null
@@ -1,17 +0,0 @@ -This is a testharness.js-based test. -PASS calc(10in) - inline style -PASS calc(10in + 20px) - inline style -PASS calc(30%) - inline style -PASS calc(100%/4) - inline style -PASS calc(25%*3) - inline style -PASS calc(25%*3 - 10in) - inline style -PASS calc((12.5%*6 + 10in) / 4) - inline style -PASS calc(10in) - computed style -PASS calc(10in + 20px) - computed style -PASS calc(30%) - computed style -PASS calc(100%/4) - computed style -PASS calc(25%*3) - computed style -FAIL calc(25%*3 - 10in) - computed style assert_in_array: value "calc(75% + -960px)" not in array ["calc(75% - 960px)", "calc(-960px + 75%)"] -PASS calc((12.5%*6 + 10in) / 4) - computed style -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/values/shape-outside-circle-010-expected.txt b/third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/values/shape-outside-circle-010-expected.txt deleted file mode 100644 index f6d4093..0000000 --- a/third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/values/shape-outside-circle-010-expected.txt +++ /dev/null
@@ -1,17 +0,0 @@ -This is a testharness.js-based test. -PASS circle(calc(10in)) - inline style -PASS circle(calc(10in + 20px)) - inline style -PASS circle(calc(30%)) - inline style -PASS circle(calc(100%/4)) - inline style -PASS circle(calc(25%*3)) - inline style -PASS circle(calc(25%*3 - 10in)) - inline style -PASS circle(calc((12.5%*6 + 10in) / 4)) - inline style -PASS circle(calc(10in)) - computed style -PASS circle(calc(10in + 20px)) - computed style -PASS circle(calc(30%)) - computed style -PASS circle(calc(100%/4)) - computed style -PASS circle(calc(25%*3)) - computed style -FAIL circle(calc(25%*3 - 10in)) - computed style assert_in_array: value "circle(calc(75% + -960px) at 50% 50%)" not in array ["circle(calc(75% - 960px) at 50% 50%)", "circle(calc(-960px + 75%) at 50% 50%)"] -PASS circle(calc((12.5%*6 + 10in) / 4)) - computed style -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/values/shape-outside-circle-011-expected.txt b/third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/values/shape-outside-circle-011-expected.txt deleted file mode 100644 index 823faea1..0000000 --- a/third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/values/shape-outside-circle-011-expected.txt +++ /dev/null
@@ -1,17 +0,0 @@ -This is a testharness.js-based test. -PASS circle(at calc(10in)) - inline style -PASS circle(at calc(10in + 20px)) - inline style -PASS circle(at calc(30%)) - inline style -PASS circle(at calc(100%/4)) - inline style -PASS circle(at calc(25%*3)) - inline style -PASS circle(at calc(25%*3 - 10in)) - inline style -PASS circle(at calc((12.5%*6 + 10in) / 4)) - inline style -PASS circle(at calc(10in)) - computed style -PASS circle(at calc(10in + 20px)) - computed style -PASS circle(at calc(30%)) - computed style -PASS circle(at calc(100%/4)) - computed style -PASS circle(at calc(25%*3)) - computed style -FAIL circle(at calc(25%*3 - 10in)) - computed style assert_in_array: value "circle(at calc(75% + -960px) 50%)" not in array ["circle(at calc(75% - 960px) 50%)", "circle(at calc(-960px + 75%) 50%)"] -PASS circle(at calc((12.5%*6 + 10in) / 4)) - computed style -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/values/shape-outside-ellipse-010-expected.txt b/third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/values/shape-outside-ellipse-010-expected.txt deleted file mode 100644 index b7f5a6c7..0000000 --- a/third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/values/shape-outside-ellipse-010-expected.txt +++ /dev/null
@@ -1,31 +0,0 @@ -This is a testharness.js-based test. -PASS ellipse(farthest-side calc(10in)) - inline style -PASS ellipse(farthest-side calc(10in + 20px)) - inline style -PASS ellipse(farthest-side calc(30%)) - inline style -PASS ellipse(farthest-side calc(100%/4)) - inline style -PASS ellipse(farthest-side calc(25%*3)) - inline style -PASS ellipse(farthest-side calc(25%*3 - 10in)) - inline style -PASS ellipse(farthest-side calc((12.5%*6 + 10in) / 4)) - inline style -PASS ellipse(calc(10in) calc(10in)) - inline style -PASS ellipse(calc(10in + 20px) calc(10in + 20px)) - inline style -PASS ellipse(calc(30%) calc(30%)) - inline style -PASS ellipse(calc(100%/4) calc(100%/4)) - inline style -PASS ellipse(calc(25%*3) calc(25%*3)) - inline style -PASS ellipse(calc(25%*3 - 10in) calc(25%*3 - 10in)) - inline style -PASS ellipse(calc((12.5%*6 + 10in) / 4) calc((12.5%*6 + 10in) / 4)) - inline style -PASS ellipse(farthest-side calc(10in)) - computed style -PASS ellipse(farthest-side calc(10in + 20px)) - computed style -PASS ellipse(farthest-side calc(30%)) - computed style -PASS ellipse(farthest-side calc(100%/4)) - computed style -PASS ellipse(farthest-side calc(25%*3)) - computed style -FAIL ellipse(farthest-side calc(25%*3 - 10in)) - computed style assert_in_array: value "ellipse(farthest-side calc(75% + -960px) at 50% 50%)" not in array ["ellipse(farthest-side calc(75% - 960px) at 50% 50%)", "ellipse(farthest-side calc(-960px + 75%) at 50% 50%)"] -PASS ellipse(farthest-side calc((12.5%*6 + 10in) / 4)) - computed style -PASS ellipse(calc(10in) calc(10in)) - computed style -PASS ellipse(calc(10in + 20px) calc(10in + 20px)) - computed style -PASS ellipse(calc(30%) calc(30%)) - computed style -PASS ellipse(calc(100%/4) calc(100%/4)) - computed style -PASS ellipse(calc(25%*3) calc(25%*3)) - computed style -FAIL ellipse(calc(25%*3 - 10in) calc(25%*3 - 10in)) - computed style assert_in_array: value "ellipse(calc(75% + -960px) calc(75% + -960px) at 50% 50%)" not in array ["ellipse(calc(75% - 960px) calc(75% - 960px) at 50% 50%)", "ellipse(calc(-960px + 75%) calc(-960px + 75%) at 50% 50%)"] -PASS ellipse(calc((12.5%*6 + 10in) / 4) calc((12.5%*6 + 10in) / 4)) - computed style -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/values/shape-outside-ellipse-011-expected.txt b/third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/values/shape-outside-ellipse-011-expected.txt deleted file mode 100644 index 9bb0068..0000000 --- a/third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/values/shape-outside-ellipse-011-expected.txt +++ /dev/null
@@ -1,31 +0,0 @@ -This is a testharness.js-based test. -PASS ellipse(at calc(10in) 50%) - inline style -PASS ellipse(at calc(10in + 20px) 50%) - inline style -PASS ellipse(at calc(30%) 50%) - inline style -PASS ellipse(at calc(100%/4) 50%) - inline style -PASS ellipse(at calc(25%*3) 50%) - inline style -PASS ellipse(at calc(25%*3 - 10in) 50%) - inline style -PASS ellipse(at calc((12.5%*6 + 10in) / 4) 50%) - inline style -PASS ellipse(closest-side farthest-side at calc(10in) calc(10in)) - inline style -PASS ellipse(closest-side farthest-side at calc(10in + 20px) calc(10in + 20px)) - inline style -PASS ellipse(closest-side farthest-side at calc(30%) calc(30%)) - inline style -PASS ellipse(closest-side farthest-side at calc(100%/4) calc(100%/4)) - inline style -PASS ellipse(closest-side farthest-side at calc(25%*3) calc(25%*3)) - inline style -PASS ellipse(closest-side farthest-side at calc(25%*3 - 10in) calc(25%*3 - 10in)) - inline style -PASS ellipse(closest-side farthest-side at calc((12.5%*6 + 10in) / 4) calc((12.5%*6 + 10in) / 4)) - inline style -PASS ellipse(at calc(10in) 50%) - computed style -PASS ellipse(at calc(10in + 20px) 50%) - computed style -PASS ellipse(at calc(30%) 50%) - computed style -PASS ellipse(at calc(100%/4) 50%) - computed style -PASS ellipse(at calc(25%*3) 50%) - computed style -FAIL ellipse(at calc(25%*3 - 10in) 50%) - computed style assert_in_array: value "ellipse(at calc(75% + -960px) 50%)" not in array ["ellipse(at calc(75% - 960px) 50%)", "ellipse(at calc(-960px + 75%) 50%)"] -PASS ellipse(at calc((12.5%*6 + 10in) / 4) 50%) - computed style -PASS ellipse(closest-side farthest-side at calc(10in) calc(10in)) - computed style -PASS ellipse(closest-side farthest-side at calc(10in + 20px) calc(10in + 20px)) - computed style -PASS ellipse(closest-side farthest-side at calc(30%) calc(30%)) - computed style -PASS ellipse(closest-side farthest-side at calc(100%/4) calc(100%/4)) - computed style -PASS ellipse(closest-side farthest-side at calc(25%*3) calc(25%*3)) - computed style -FAIL ellipse(closest-side farthest-side at calc(25%*3 - 10in) calc(25%*3 - 10in)) - computed style assert_in_array: value "ellipse(closest-side farthest-side at calc(75% + -960px) calc(75% + -960px))" not in array ["ellipse(closest-side farthest-side at calc(75% - 960px) calc(75% - 960px))", "ellipse(closest-side farthest-side at calc(-960px + 75%) calc(-960px + 75%))"] -PASS ellipse(closest-side farthest-side at calc((12.5%*6 + 10in) / 4) calc((12.5%*6 + 10in) / 4)) - computed style -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/values/shape-outside-inset-008-expected.txt b/third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/values/shape-outside-inset-008-expected.txt deleted file mode 100644 index b969e06..0000000 --- a/third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/values/shape-outside-inset-008-expected.txt +++ /dev/null
@@ -1,31 +0,0 @@ -This is a testharness.js-based test. -PASS inset(calc(10in)) - inline style -PASS inset(calc(10in + 20px)) - inline style -PASS inset(calc(30%)) - inline style -PASS inset(calc(100%/4)) - inline style -PASS inset(calc(25%*3)) - inline style -PASS inset(calc(25%*3 - 10in)) - inline style -PASS inset(calc((12.5%*6 + 10in) / 4)) - inline style -PASS inset(calc(10in) calc(10in)) - inline style -PASS inset(calc(10in + 20px) calc(10in + 20px)) - inline style -PASS inset(calc(30%) calc(30%)) - inline style -PASS inset(calc(100%/4) calc(100%/4)) - inline style -PASS inset(calc(25%*3) calc(25%*3)) - inline style -PASS inset(calc(25%*3 - 10in) calc(25%*3 - 10in)) - inline style -PASS inset(calc((12.5%*6 + 10in) / 4) calc((12.5%*6 + 10in) / 4)) - inline style -PASS inset(calc(10in)) - computed style -PASS inset(calc(10in + 20px)) - computed style -PASS inset(calc(30%)) - computed style -PASS inset(calc(100%/4)) - computed style -PASS inset(calc(25%*3)) - computed style -FAIL inset(calc(25%*3 - 10in)) - computed style assert_in_array: value "inset(calc(75% + -960px))" not in array ["inset(calc(75% - 960px))", "inset(calc(-960px + 75%))"] -PASS inset(calc((12.5%*6 + 10in) / 4)) - computed style -PASS inset(calc(10in) calc(10in)) - computed style -PASS inset(calc(10in + 20px) calc(10in + 20px)) - computed style -PASS inset(calc(30%) calc(30%)) - computed style -PASS inset(calc(100%/4) calc(100%/4)) - computed style -PASS inset(calc(25%*3) calc(25%*3)) - computed style -FAIL inset(calc(25%*3 - 10in) calc(25%*3 - 10in)) - computed style assert_in_array: value "inset(calc(75% + -960px))" not in array ["inset(calc(75% - 960px))", "inset(calc(-960px + 75%))"] -PASS inset(calc((12.5%*6 + 10in) / 4) calc((12.5%*6 + 10in) / 4)) - computed style -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/values/shape-outside-inset-009-expected.txt b/third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/values/shape-outside-inset-009-expected.txt deleted file mode 100644 index 4a387910..0000000 --- a/third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/values/shape-outside-inset-009-expected.txt +++ /dev/null
@@ -1,31 +0,0 @@ -This is a testharness.js-based test. -PASS inset(10px 10px 10px 10px round calc(10in)) - inline style -PASS inset(10px 10px 10px 10px round calc(10in + 20px)) - inline style -PASS inset(10px 10px 10px 10px round calc(30%)) - inline style -PASS inset(10px 10px 10px 10px round calc(100%/4)) - inline style -PASS inset(10px 10px 10px 10px round calc(25%*3)) - inline style -PASS inset(10px 10px 10px 10px round calc(25%*3 - 10in)) - inline style -PASS inset(10px 10px 10px 10px round calc((12.5%*6 + 10in) / 4)) - inline style -PASS inset(10px 10px 10px 10px round calc(10in) calc(10in)) - inline style -PASS inset(10px 10px 10px 10px round calc(10in + 20px) calc(10in + 20px)) - inline style -PASS inset(10px 10px 10px 10px round calc(30%) calc(30%)) - inline style -PASS inset(10px 10px 10px 10px round calc(100%/4) calc(100%/4)) - inline style -PASS inset(10px 10px 10px 10px round calc(25%*3) calc(25%*3)) - inline style -PASS inset(10px 10px 10px 10px round calc(25%*3 - 10in) calc(25%*3 - 10in)) - inline style -PASS inset(10px 10px 10px 10px round calc((12.5%*6 + 10in) / 4) calc((12.5%*6 + 10in) / 4)) - inline style -PASS inset(10px 10px 10px 10px round calc(10in)) - computed style -PASS inset(10px 10px 10px 10px round calc(10in + 20px)) - computed style -PASS inset(10px 10px 10px 10px round calc(30%)) - computed style -PASS inset(10px 10px 10px 10px round calc(100%/4)) - computed style -PASS inset(10px 10px 10px 10px round calc(25%*3)) - computed style -FAIL inset(10px 10px 10px 10px round calc(25%*3 - 10in)) - computed style assert_in_array: value "inset(10px round calc(75% + -960px))" not in array ["inset(10px round calc(75% - 960px))", "inset(10px round calc(-960px + 75%))"] -PASS inset(10px 10px 10px 10px round calc((12.5%*6 + 10in) / 4)) - computed style -PASS inset(10px 10px 10px 10px round calc(10in) calc(10in)) - computed style -PASS inset(10px 10px 10px 10px round calc(10in + 20px) calc(10in + 20px)) - computed style -PASS inset(10px 10px 10px 10px round calc(30%) calc(30%)) - computed style -PASS inset(10px 10px 10px 10px round calc(100%/4) calc(100%/4)) - computed style -PASS inset(10px 10px 10px 10px round calc(25%*3) calc(25%*3)) - computed style -FAIL inset(10px 10px 10px 10px round calc(25%*3 - 10in) calc(25%*3 - 10in)) - computed style assert_in_array: value "inset(10px round calc(75% + -960px))" not in array ["inset(10px round calc(75% - 960px))", "inset(10px round calc(-960px + 75%))"] -PASS inset(10px 10px 10px 10px round calc((12.5%*6 + 10in) / 4) calc((12.5%*6 + 10in) / 4)) - computed style -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/values/shape-outside-polygon-006-expected.txt b/third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/values/shape-outside-polygon-006-expected.txt deleted file mode 100644 index f6747fa..0000000 --- a/third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/values/shape-outside-polygon-006-expected.txt +++ /dev/null
@@ -1,31 +0,0 @@ -This is a testharness.js-based test. -PASS polygon(calc(10in) calc(10in)) - inline style -PASS polygon(calc(10in + 20px) calc(10in + 20px)) - inline style -PASS polygon(calc(30%) calc(30%)) - inline style -PASS polygon(calc(100%/4) calc(100%/4)) - inline style -PASS polygon(calc(25%*3) calc(25%*3)) - inline style -PASS polygon(calc(25%*3 - 10in) calc(25%*3 - 10in)) - inline style -PASS polygon(calc((12.5%*6 + 10in) / 4) calc((12.5%*6 + 10in) / 4)) - inline style -PASS polygon(evenodd, calc(10in) calc(10in), calc(10in) calc(10in)) - inline style -PASS polygon(evenodd, calc(10in + 20px) calc(10in + 20px), calc(10in + 20px) calc(10in + 20px)) - inline style -PASS polygon(evenodd, calc(30%) calc(30%), calc(30%) calc(30%)) - inline style -PASS polygon(evenodd, calc(100%/4) calc(100%/4), calc(100%/4) calc(100%/4)) - inline style -PASS polygon(evenodd, calc(25%*3) calc(25%*3), calc(25%*3) calc(25%*3)) - inline style -PASS polygon(evenodd, calc(25%*3 - 10in) calc(25%*3 - 10in), calc(25%*3 - 10in) calc(25%*3 - 10in)) - inline style -PASS polygon(evenodd, calc((12.5%*6 + 10in) / 4) calc((12.5%*6 + 10in) / 4), calc((12.5%*6 + 10in) / 4) calc((12.5%*6 + 10in) / 4)) - inline style -PASS polygon(calc(10in) calc(10in)) - computed style -PASS polygon(calc(10in + 20px) calc(10in + 20px)) - computed style -PASS polygon(calc(30%) calc(30%)) - computed style -PASS polygon(calc(100%/4) calc(100%/4)) - computed style -PASS polygon(calc(25%*3) calc(25%*3)) - computed style -FAIL polygon(calc(25%*3 - 10in) calc(25%*3 - 10in)) - computed style assert_in_array: value "polygon(calc(75% + -960px) calc(75% + -960px))" not in array ["polygon(calc(75% - 960px) calc(75% - 960px))", "polygon(calc(-960px + 75%) calc(-960px + 75%))"] -PASS polygon(calc((12.5%*6 + 10in) / 4) calc((12.5%*6 + 10in) / 4)) - computed style -PASS polygon(evenodd, calc(10in) calc(10in), calc(10in) calc(10in)) - computed style -PASS polygon(evenodd, calc(10in + 20px) calc(10in + 20px), calc(10in + 20px) calc(10in + 20px)) - computed style -PASS polygon(evenodd, calc(30%) calc(30%), calc(30%) calc(30%)) - computed style -PASS polygon(evenodd, calc(100%/4) calc(100%/4), calc(100%/4) calc(100%/4)) - computed style -PASS polygon(evenodd, calc(25%*3) calc(25%*3), calc(25%*3) calc(25%*3)) - computed style -FAIL polygon(evenodd, calc(25%*3 - 10in) calc(25%*3 - 10in), calc(25%*3 - 10in) calc(25%*3 - 10in)) - computed style assert_in_array: value "polygon(evenodd, calc(75% + -960px) calc(75% + -960px), calc(75% + -960px) calc(75% + -960px))" not in array ["polygon(evenodd, calc(75% - 960px) calc(75% - 960px), calc(75% - 960px) calc(75% - 960px))", "polygon(evenodd, calc(-960px + 75%) calc(-960px + 75%), calc(-960px + 75%) calc(-960px + 75%))"] -PASS polygon(evenodd, calc((12.5%*6 + 10in) / 4) calc((12.5%*6 + 10in) / 4), calc((12.5%*6 + 10in) / 4) calc((12.5%*6 + 10in) / 4)) - computed style -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transforms/transforms-support-calc-expected.txt b/third_party/blink/web_tests/external/wpt/css/css-transforms/transforms-support-calc-expected.txt deleted file mode 100644 index 3e16e0c..0000000 --- a/third_party/blink/web_tests/external/wpt/css/css-transforms/transforms-support-calc-expected.txt +++ /dev/null
@@ -1,10 +0,0 @@ -This is a testharness.js-based test. -FAIL translate supports calc assert_equals: expected "calc(20% + 30px) calc(100% - 200px)" but got "calc(20% + 30px) calc(100% + -200px)" -PASS rotate supports calc -PASS scale supports calc -PASS perspective supports calc -PASS perspective-origin supports calc -PASS transform supports calc -PASS transform-origin supports calc -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/css/css-values/calc-background-position-002-expected.txt b/third_party/blink/web_tests/external/wpt/css/css-values/calc-background-position-002-expected.txt deleted file mode 100644 index d2d0ec0..0000000 --- a/third_party/blink/web_tests/external/wpt/css/css-values/calc-background-position-002-expected.txt +++ /dev/null
@@ -1,9 +0,0 @@ -This is a testharness.js-based test. -PASS testing background-position: calc(2px + 3px) calc(4px + 5px) -PASS testing background-position: calc(18px - 7px) calc(19px - 7px) -PASS testing background-position: calc(4 * 5px) calc(6px * 4) -PASS testing background-position: calc(100px / 4) calc(119px / 7) -PASS testing background-position: calc(6px + 21%) calc(7em + 22%) -FAIL testing background-position: calc(-8px + 23%) calc(-9em + 24%) assert_equals: expected "calc(23% - 8px) calc(24% - 144px)" but got "calc(23% + -8px) calc(24% + -144px)" -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/css/motion/offset-supports-calc-expected.txt b/third_party/blink/web_tests/external/wpt/css/motion/offset-supports-calc-expected.txt deleted file mode 100644 index c777241..0000000 --- a/third_party/blink/web_tests/external/wpt/css/motion/offset-supports-calc-expected.txt +++ /dev/null
@@ -1,8 +0,0 @@ -This is a testharness.js-based test. -FAIL offset-position supports calc assert_equals: expected "calc(20% + 30px) calc(100% - 40px)" but got "calc(20% + 30px) calc(100% + -40px)" -PASS offset-path supports calc -FAIL offset-distance supports calc assert_equals: expected "calc(50% - 100px)" but got "calc(50% + -100px)" -PASS offset-rotate supports calc -FAIL offset-anchor supports calc assert_equals: expected "calc(20% + 30px) calc(100% - 40px)" but got "calc(20% + 30px) calc(100% + -40px)" -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/addition-per-property-expected.txt b/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/addition-per-property-expected.txt index 260c457..bc5e8c8 100644 --- a/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/addition-per-property-expected.txt +++ b/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/addition-per-property-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 568 tests; 539 PASS, 29 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 568 tests; 540 PASS, 28 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS Setup PASS align-content (type: discrete) has testAddition function PASS align-content: "flex-end" onto "flex-start" @@ -539,7 +539,7 @@ PASS translate (type: translateList) has testAddition function PASS translate PASS translate with underlying transform -FAIL translate with underlying percentage value assert_equals: The value should be calc(50% - 200px) at 0ms expected "calc(50% - 200px)" but got "calc(50% + -200px)" +PASS translate with underlying percentage value PASS scale (type: scaleList) has testAddition function PASS scale with two unspecified values PASS scale with one unspecified value
diff --git a/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/interpolation-per-property-expected.txt b/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/interpolation-per-property-expected.txt index c611fb4..c62109d 100644 --- a/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/interpolation-per-property-expected.txt +++ b/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/interpolation-per-property-expected.txt
@@ -671,7 +671,7 @@ PASS translate with two unspecified values PASS translate with one unspecified value PASS translate with all three values specified -FAIL translate with combination of percentages and lengths assert_equals: The value should be calc(0% + 200px) calc(25% - 50.5px) 200px at 500ms expected "calc(0% + 200px) calc(25% - 50.5px) 200px" but got "200px calc(25% + -50.5px) 200px" +FAIL translate with combination of percentages and lengths assert_equals: The value should be calc(0% + 200px) calc(25% - 50.5px) 200px at 500ms expected "calc(0% + 200px) calc(25% - 50.5px) 200px" but got "200px calc(25% - 50.5px) 200px" PASS scale (type: scaleList) has testInterpolation function PASS scale with two unspecified values PASS scale with one unspecified value
diff --git a/third_party/blink/web_tests/fast/css-grid-layout/non-grid-columns-rows-get-set-multiple-expected.txt b/third_party/blink/web_tests/fast/css-grid-layout/non-grid-columns-rows-get-set-multiple-expected.txt index 04f9f3b..8101af7 100644 --- a/third_party/blink/web_tests/fast/css-grid-layout/non-grid-columns-rows-get-set-multiple-expected.txt +++ b/third_party/blink/web_tests/fast/css-grid-layout/non-grid-columns-rows-get-set-multiple-expected.txt
@@ -32,9 +32,9 @@ PASS window.getComputedStyle(gridWithCalcAndFixed, '').getPropertyValue('grid-template-columns') is "50% 80px" PASS window.getComputedStyle(gridWithCalcAndFixed, '').getPropertyValue('grid-template-rows') is "88px 25%" PASS window.getComputedStyle(gridWithCalcAndMinMax, '').getPropertyValue('grid-template-columns') is "calc(20% + 30px) minmax(min-content, 80px)" -PASS window.getComputedStyle(gridWithCalcAndMinMax, '').getPropertyValue('grid-template-rows') is "minmax(25%, max-content) calc(10% + -7px)" +PASS window.getComputedStyle(gridWithCalcAndMinMax, '').getPropertyValue('grid-template-rows') is "minmax(25%, max-content) calc(10% - 7px)" PASS window.getComputedStyle(gridWithCalcInsideMinMax, '').getPropertyValue('grid-template-columns') is "minmax(calc(10% + 23px), 400px) 120px" -PASS window.getComputedStyle(gridWithCalcInsideMinMax, '').getPropertyValue('grid-template-rows') is "150px minmax(5%, calc(50% + -125px))" +PASS window.getComputedStyle(gridWithCalcInsideMinMax, '').getPropertyValue('grid-template-rows') is "150px minmax(5%, calc(50% - 125px))" PASS window.getComputedStyle(gridWithAutoInsideMinMax, '').getPropertyValue('grid-template-columns') is "minmax(auto, 20px) 10%" PASS window.getComputedStyle(gridWithAutoInsideMinMax, '').getPropertyValue('grid-template-rows') is "max-content minmax(min-content, auto)"
diff --git a/third_party/blink/web_tests/fast/css-grid-layout/resources/non-grid-columns-rows-get-set-multiple.js b/third_party/blink/web_tests/fast/css-grid-layout/resources/non-grid-columns-rows-get-set-multiple.js index f17f76f5..672ca04 100644 --- a/third_party/blink/web_tests/fast/css-grid-layout/resources/non-grid-columns-rows-get-set-multiple.js +++ b/third_party/blink/web_tests/fast/css-grid-layout/resources/non-grid-columns-rows-get-set-multiple.js
@@ -15,8 +15,8 @@ testGridDefinitionsValues(document.getElementById("gridWithFractionMinMax"), "minmax(min-content, 45px) 2fr", "3fr minmax(14px, max-content)"); testGridDefinitionsValues(document.getElementById("gridWithCalcCalc"), "200px 100px", "150px 75px"); testGridDefinitionsValues(document.getElementById("gridWithCalcAndFixed"), "50% 80px", "88px 25%"); -testGridDefinitionsValues(document.getElementById("gridWithCalcAndMinMax"), "calc(20% + 30px) minmax(min-content, 80px)", "minmax(25%, max-content) calc(10% + -7px)"); -testGridDefinitionsValues(document.getElementById("gridWithCalcInsideMinMax"), "minmax(calc(10% + 23px), 400px) 120px", "150px minmax(5%, calc(50% + -125px))"); +testGridDefinitionsValues(document.getElementById("gridWithCalcAndMinMax"), "calc(20% + 30px) minmax(min-content, 80px)", "minmax(25%, max-content) calc(10% - 7px)"); +testGridDefinitionsValues(document.getElementById("gridWithCalcInsideMinMax"), "minmax(calc(10% + 23px), 400px) 120px", "150px minmax(5%, calc(50% - 125px))"); testGridDefinitionsValues(document.getElementById("gridWithAutoInsideMinMax"), "minmax(auto, 20px) 10%", "max-content minmax(min-content, auto)"); debug("");
diff --git a/third_party/blink/web_tests/fast/css/parsing-object-position-expected.txt b/third_party/blink/web_tests/fast/css/parsing-object-position-expected.txt index ca387d6a..9fd9344 100644 --- a/third_party/blink/web_tests/fast/css/parsing-object-position-expected.txt +++ b/third_party/blink/web_tests/fast/css/parsing-object-position-expected.txt
@@ -9,7 +9,7 @@ PASS testComputedStyle("object-position: top right;") is "100% 0%" PASS testComputedStyle("object-position: left 20px bottom 50%;") is "20px 50%" PASS testComputedStyle("object-position: right 50% bottom 25%;") is "50% 75%" -PASS testComputedStyle("object-position: bottom 20px right 12px;") is "calc(100% + -12px) calc(100% + -20px)" +PASS testComputedStyle("object-position: bottom 20px right 12px;") is "calc(100% - 12px) calc(100% - 20px)" PASS test("object-position: inherit;") is "inherit" PASS test("object-position: initial;") is "initial" PASS test("object-position: left;") is "left center"
diff --git a/third_party/blink/web_tests/fast/css/parsing-object-position.html b/third_party/blink/web_tests/fast/css/parsing-object-position.html index 78c257b..1e222d8 100644 --- a/third_party/blink/web_tests/fast/css/parsing-object-position.html +++ b/third_party/blink/web_tests/fast/css/parsing-object-position.html
@@ -36,7 +36,7 @@ shouldBeEqualToString('testComputedStyle("object-position: top right;")', '100% 0%'); shouldBeEqualToString('testComputedStyle("object-position: left 20px bottom 50%;")', '20px 50%'); shouldBeEqualToString('testComputedStyle("object-position: right 50% bottom 25%;")', '50% 75%'); - shouldBeEqualToString('testComputedStyle("object-position: bottom 20px right 12px;")', 'calc(100% + -12px) calc(100% + -20px)'); + shouldBeEqualToString('testComputedStyle("object-position: bottom 20px right 12px;")', 'calc(100% - 12px) calc(100% - 20px)'); shouldBeEqualToString('test("object-position: inherit;")', 'inherit'); shouldBeEqualToString('test("object-position: initial;")', 'initial');
diff --git a/third_party/blink/web_tests/fast/shapes/parsing/parsing-shape-margin-expected.txt b/third_party/blink/web_tests/fast/shapes/parsing/parsing-shape-margin-expected.txt index 664aac3..5380144 100644 --- a/third_party/blink/web_tests/fast/shapes/parsing/parsing-shape-margin-expected.txt +++ b/third_party/blink/web_tests/fast/shapes/parsing/parsing-shape-margin-expected.txt
@@ -20,7 +20,7 @@ PASS getComputedStyleValue("shape-margin", "-5em") is "0px" PASS getComputedStyleValue("shape-margin", "identifier") is "0px" PASS getComputedStyleValue("shape-margin", "'string'") is "0px" -PASS getComputedStyleValue("shape-margin", "calc(25%*3 - 10in)") is "calc(75% + -960px)" +PASS getComputedStyleValue("shape-margin", "calc(25%*3 - 10in)") is "calc(75% - 960px)" PASS getChildComputedStyle("shape-margin", "0", "0") is "0px" PASS getChildComputedStyle("shape-margin", "0", "1px") is "1px" PASS getChildComputedStyle("shape-margin", "1px", "-1em") is "0px"
diff --git a/third_party/blink/web_tests/fast/shapes/parsing/parsing-shape-margin.html b/third_party/blink/web_tests/fast/shapes/parsing/parsing-shape-margin.html index 659eda3..41f0c7d 100644 --- a/third_party/blink/web_tests/fast/shapes/parsing/parsing-shape-margin.html +++ b/third_party/blink/web_tests/fast/shapes/parsing/parsing-shape-margin.html
@@ -28,7 +28,7 @@ ["shape-margin", "-5em", "0px"], ["shape-margin", "identifier", "0px"], ["shape-margin", "\'string\'", "0px"], - ["shape-margin", "calc(25%*3 - 10in)", "calc(75% + -960px)"]] + ["shape-margin", "calc(25%*3 - 10in)", "calc(75% - 960px)"]] ); applyToEachArglist(
diff --git a/third_party/blink/web_tests/fast/shapes/parsing/parsing-shape-outside-expected.txt b/third_party/blink/web_tests/fast/shapes/parsing/parsing-shape-outside-expected.txt index b749dfdf..0d7e2f0 100644 --- a/third_party/blink/web_tests/fast/shapes/parsing/parsing-shape-outside-expected.txt +++ b/third_party/blink/web_tests/fast/shapes/parsing/parsing-shape-outside-expected.txt
@@ -67,9 +67,9 @@ PASS getCSSText("shape-outside", "inset(10px round 0px / 10px)") is "inset(10px round 0px / 10px)" PASS getComputedStyleValue("shape-outside", "inset(10px round 0px / 10px)") is "inset(10px round 0px / 10px)" PASS getCSSText("shape-outside", "inset(calc(25%*3 - 10in) 0 0 0)") is "inset(calc(75% - 10in) 0px 0px)" -FAIL getComputedStyleValue("shape-outside", "inset(calc(25%*3 - 10in) 0 0 0)") should be inset(calc(-960px + 75%) 0px 0px). Was inset(calc(75% + -960px) 0px 0px). +FAIL getComputedStyleValue("shape-outside", "inset(calc(25%*3 - 10in) 0 0 0)") should be inset(calc(-960px + 75%) 0px 0px). Was inset(calc(75% - 960px) 0px 0px). PASS getCSSText("shape-outside", "inset(10px 10px 10px 10px round calc(25%*3 - 10in))") is "inset(10px round calc(75% - 10in))" -FAIL getComputedStyleValue("shape-outside", "inset(10px 10px 10px 10px round calc(25%*3 - 10in))") should be inset(10px round calc(-960px + 75%)). Was inset(10px round calc(75% + -960px)). +FAIL getComputedStyleValue("shape-outside", "inset(10px 10px 10px 10px round calc(25%*3 - 10in))") should be inset(10px round calc(-960px + 75%)). Was inset(10px round calc(75% - 960px)). PASS getCSSText("shape-outside", "circle()") is "circle(at 50% 50%)" PASS getComputedStyleValue("shape-outside", "circle()") is "circle(at 50% 50%)" PASS getCSSText("shape-outside", "circle(farthest-side)") is "circle(farthest-side at 50% 50%)"
diff --git a/third_party/blink/web_tests/transforms/translate-parsing.html b/third_party/blink/web_tests/transforms/translate-parsing.html index fdd82133..8e66608 100644 --- a/third_party/blink/web_tests/transforms/translate-parsing.html +++ b/third_party/blink/web_tests/transforms/translate-parsing.html
@@ -19,8 +19,8 @@ expect('42.5% -20.5% 5px').parsesAs('42.5% -20.5% 5px').isComputedTo('42.5% -20.5% 5px'); expect('calc(100%) calc(20px) calc(-1px)').isComputedTo('100% 20px -1px'); -expect('calc(100% + 10px) calc(100% - 10px) calc(100px + 200px)').parsesAs('calc(100% + 10px) calc(100% - 10px) calc(300px)').isComputedTo('calc(100% + 10px) calc(100% + -10px) 300px'); -expect('calc(100% * 0.5 + 2px) calc(100% - 10px / 2) calc(100px - 200px)').parsesAs('calc(50% + 2px) calc(100% - 5px) calc(-100px)').isComputedTo('calc(50% + 2px) calc(100% + -5px) -100px'); +expect('calc(100% + 10px) calc(100% - 10px) calc(100px + 200px)').parsesAs('calc(100% + 10px) calc(100% - 10px) calc(300px)').isComputedTo('calc(100% + 10px) calc(100% - 10px) 300px'); +expect('calc(100% * 0.5 + 2px) calc(100% - 10px / 2) calc(100px - 200px)').parsesAs('calc(50% + 2px) calc(100% - 5px) calc(-100px)').isComputedTo('calc(50% + 2px) calc(100% - 5px) -100px'); expect('2').isInvalid(); expect('10deg 10px').isInvalid();
diff --git a/third_party/blink/web_tests/wpt_internal/virtual-scroller/large-child-comment-ref.html b/third_party/blink/web_tests/wpt_internal/virtual-scroller/large-child-comment-ref.html new file mode 100644 index 0000000..b41cecd --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/virtual-scroller/large-child-comment-ref.html
@@ -0,0 +1,8 @@ +<!DOCTYPE html> +<html class="reftest-wait"> + <style>body { overflow:hidden; }</style> + <script type="module"> + import * as refTests from './resources/ref-tests.mjs'; + refTests.withDiv(refTests.testLargeChildComment); + </script> +</html>
diff --git a/third_party/blink/web_tests/wpt_internal/virtual-scroller/large-child-comment.html b/third_party/blink/web_tests/wpt_internal/virtual-scroller/large-child-comment.html new file mode 100644 index 0000000..6cb8542 --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/virtual-scroller/large-child-comment.html
@@ -0,0 +1,13 @@ +<!DOCTYPE html> +<html class="reftest-wait"> + <meta charset="utf8"> + <title>Scrolling a very large element should reveal the next element.</title> + <style>body { overflow:hidden; }</style> + <link rel="author" title="Fergal Daly" href="mailto:fergal@chromium.org"> + <link rel="match" href="large-child-comment-ref.html"> + <script type="module"> + import 'std:elements/virtual-scroller'; + import * as refTests from './resources/ref-tests.mjs'; + refTests.withVirtualScroller(refTests.testLargeChildComment); + </script> +</html>
diff --git a/third_party/blink/web_tests/wpt_internal/virtual-scroller/large-child-ref.html b/third_party/blink/web_tests/wpt_internal/virtual-scroller/large-child-ref.html new file mode 100644 index 0000000..87841a3e --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/virtual-scroller/large-child-ref.html
@@ -0,0 +1,8 @@ +<!DOCTYPE html> +<html class="reftest-wait"> + <style>body { overflow:hidden; }</style> + <script type="module"> + import * as refTests from './resources/ref-tests.mjs'; + refTests.withDiv(refTests.testLargeChild); + </script> +</html>
diff --git a/third_party/blink/web_tests/wpt_internal/virtual-scroller/large-child.html b/third_party/blink/web_tests/wpt_internal/virtual-scroller/large-child.html new file mode 100644 index 0000000..0e8a147 --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/virtual-scroller/large-child.html
@@ -0,0 +1,13 @@ +<!DOCTYPE html> +<html class="reftest-wait"> + <meta charset="utf8"> + <title>Scrolling a very large element should reveal the next element.</title> + <style>body { overflow:hidden; }</style> + <link rel="author" title="Fergal Daly" href="mailto:fergal@chromium.org"> + <link rel="match" href="large-child-ref.html"> + <script type="module"> + import 'std:elements/virtual-scroller'; + import * as refTests from './resources/ref-tests.mjs'; + refTests.withVirtualScroller(refTests.testLargeChild); + </script> +</html>
diff --git a/third_party/blink/web_tests/wpt_internal/virtual-scroller/resources/ref-tests.mjs b/third_party/blink/web_tests/wpt_internal/virtual-scroller/resources/ref-tests.mjs index 1823699..602a84ec 100644 --- a/third_party/blink/web_tests/wpt_internal/virtual-scroller/resources/ref-tests.mjs +++ b/third_party/blink/web_tests/wpt_internal/virtual-scroller/resources/ref-tests.mjs
@@ -26,6 +26,47 @@ }); }; +export function testLargeChild(target) { + // This scrollTo and nextFrame are not necessary for the ref-test + // however it helps when trying to debug this test in a + // browser. Without it, the scroll offset may be preserved across + // page reloads. + document.body.scrollTo(0, 0); + helpers.nextFrame(() => { + const largeChild = helpers.largeDiv("largeChild"); + target.appendChild(largeChild); + const child = helpers.div("child"); + target.appendChild(child); + + // Give the scroller time to settle. + helpers.inNFrames(10, () => { + window.scrollBy(0, largeChild.getBoundingClientRect().height); + helpers.stopWaiting(); + }); + }); +} + +export function testLargeChildComment(target) { + // This scrollTo and nextFrame are not necessary for the ref-test + // however it helps when trying to debug this test in a + // browser. Without it, the scroll offset may be preserved across + // page reloads. + document.body.scrollTo(0, 0); + helpers.nextFrame(() => { + const largeChild = helpers.largeDiv("largeChild"); + target.appendChild(largeChild); + // Ensure that non-element nodes don't cause problems. + target.appendChild(document.createComment("comment")); + target.appendChild(helpers.div("child")); + + // Give the scroller time to settle. + helpers.inNFrames(10, () => { + window.scrollBy(0, largeChild.getBoundingClientRect().height); + helpers.stopWaiting(); + }); + }); +} + export function testMoveElement(target) { helpers.appendDivs(target, MORE_THAN_SCREENFUL, '10px'); helpers.nextFrame(() => {
diff --git a/third_party/crashpad/README.chromium b/third_party/crashpad/README.chromium index cf423d6..70f0caa 100644 --- a/third_party/crashpad/README.chromium +++ b/third_party/crashpad/README.chromium
@@ -2,7 +2,7 @@ Short Name: crashpad URL: https://crashpad.chromium.org/ Version: unknown -Revision: 3a6c6012ba2b9ed662872ccaf7d276d56240943b +Revision: cd92fba233d3cc28909c3791710a747c818de244 License: Apache 2.0 License File: crashpad/LICENSE Security Critical: yes
diff --git a/third_party/crashpad/crashpad/DEPS b/third_party/crashpad/crashpad/DEPS index acb4a39..46c3424 100644 --- a/third_party/crashpad/crashpad/DEPS +++ b/third_party/crashpad/crashpad/DEPS
@@ -33,7 +33,7 @@ '8048ece6c16c91acfe0d36d1d3cc0890ab6e945c', 'crashpad/third_party/mini_chromium/mini_chromium': Var('chromium_git') + '/chromium/mini_chromium@' + - '6ad086b2b6ed3b3169226ee9f311eb2332f332c2', + '5889767521eed1483b5858b12c54893f21d72fd0', 'crashpad/third_party/libfuzzer/src': Var('chromium_git') + '/chromium/llvm-project/compiler-rt/lib/fuzzer.git@' + 'fda403cf93ecb8792cb1d061564d89a6553ca020',
diff --git a/third_party/crashpad/crashpad/build/BUILDCONFIG.gn b/third_party/crashpad/crashpad/build/BUILDCONFIG.gn index 95dc277..bc53108 100644 --- a/third_party/crashpad/crashpad/build/BUILDCONFIG.gn +++ b/third_party/crashpad/crashpad/build/BUILDCONFIG.gn
@@ -55,6 +55,7 @@ _default_configs = [ "//third_party/mini_chromium/mini_chromium/build:default", "//third_party/mini_chromium/mini_chromium/build:Wexit_time_destructors", + "//third_party/mini_chromium/mini_chromium/build:Wimplicit_fallthrough", ] if (crashpad_use_libfuzzer) {
diff --git a/third_party/crashpad/crashpad/client/crashpad_client.h b/third_party/crashpad/crashpad/client/crashpad_client.h index 56d738b..36c9d1f8 100644 --- a/third_party/crashpad/crashpad/client/crashpad_client.h +++ b/third_party/crashpad/crashpad/client/crashpad_client.h
@@ -588,6 +588,16 @@ static void UseSystemDefaultHandler(); #endif +#if defined(OS_CHROMEOS) + //! \brief Sets a timestamp on the signal handler to be passed on to + //! crashpad_handler and then eventually Chrome OS's crash_reporter. + //! + //! \note This method is used by clients that use `StartHandler()` to start + //! a handler and not by clients that use any other handler starting + //! methods. + static void SetCrashLoopBefore(uint64_t crash_loop_before_time); +#endif + private: #if defined(OS_MACOSX) base::mac::ScopedMachSendRight exception_port_;
diff --git a/third_party/crashpad/crashpad/client/crashpad_client_linux.cc b/third_party/crashpad/crashpad/client/crashpad_client_linux.cc index 2e2ec30..eb210a2 100644 --- a/third_party/crashpad/crashpad/client/crashpad_client_linux.cc +++ b/third_party/crashpad/crashpad/client/crashpad_client_linux.cc
@@ -301,11 +301,20 @@ ExceptionHandlerProtocol::ClientInformation info = {}; info.exception_information_address = FromPointerCast<VMAddress>(&GetExceptionInfo()); +#if defined(OS_CHROMEOS) + info.crash_loop_before_time = crash_loop_before_time_; +#endif ExceptionHandlerClient client(sock_to_handler_.get(), true); client.RequestCrashDump(info); } +#if defined(OS_CHROMEOS) + void SetCrashLoopBefore(uint64_t crash_loop_before_time) { + crash_loop_before_time_ = crash_loop_before_time; + } +#endif + private: RequestCrashDumpHandler() = default; @@ -314,6 +323,14 @@ ScopedFileHandle sock_to_handler_; pid_t handler_pid_ = -1; +#if defined(OS_CHROMEOS) + // An optional UNIX timestamp passed to us from Chrome. + // This will pass to crashpad_handler and then to Chrome OS crash_reporter. + // This should really be a time_t, but it's basically an opaque value (we + // don't anything with it except pass it along). + uint64_t crash_loop_before_time_ = 0; +#endif + DISALLOW_COPY_AND_ASSIGN(RequestCrashDumpHandler); }; @@ -526,4 +543,12 @@ SignalHandler::Get()->SetFirstChanceHandler(handler); } +#if defined(OS_CHROMEOS) +// static +void CrashpadClient::SetCrashLoopBefore(uint64_t crash_loop_before_time) { + auto request_crash_dump_handler = RequestCrashDumpHandler::Get(); + request_crash_dump_handler->SetCrashLoopBefore(crash_loop_before_time); +} +#endif + } // namespace crashpad
diff --git a/third_party/crashpad/crashpad/compat/BUILD.gn b/third_party/crashpad/crashpad/compat/BUILD.gn index 7a33d7ca..62ee528 100644 --- a/third_party/crashpad/crashpad/compat/BUILD.gn +++ b/third_party/crashpad/crashpad/compat/BUILD.gn
@@ -79,6 +79,8 @@ if (crashpad_is_linux || crashpad_is_android) { sources += [ "linux/signal.h", + "linux/sys/mman.cc", + "linux/sys/mman.h", "linux/sys/ptrace.h", "linux/sys/user.h", ]
diff --git a/third_party/crashpad/crashpad/compat/linux/sys/mman.cc b/third_party/crashpad/crashpad/compat/linux/sys/mman.cc new file mode 100644 index 0000000..12aaa2c7 --- /dev/null +++ b/third_party/crashpad/crashpad/compat/linux/sys/mman.cc
@@ -0,0 +1,35 @@ +// Copyright 2019 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include <sys/mman.h> + +#include <dlfcn.h> +#include <sys/syscall.h> +#include <unistd.h> + +#if defined(__GLIBC__) + +extern "C" { + +int memfd_create(const char* name, unsigned int flags) { + using MemfdCreateType = int (*)(const char*, int); + static const MemfdCreateType next_memfd_create = + reinterpret_cast<MemfdCreateType>(dlsym(RTLD_NEXT, "memfd_create")); + return next_memfd_create ? next_memfd_create(name, flags) + : syscall(SYS_memfd_create, name, flags); +} + +} // extern "C" + +#endif // __GLIBC__
diff --git a/third_party/crashpad/crashpad/compat/linux/sys/mman.h b/third_party/crashpad/crashpad/compat/linux/sys/mman.h new file mode 100644 index 0000000..61c55d7 --- /dev/null +++ b/third_party/crashpad/crashpad/compat/linux/sys/mman.h
@@ -0,0 +1,40 @@ +// Copyright 2019 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef CRASHPAD_COMPAT_LINUX_SYS_MMAN_H_ +#define CRASHPAD_COMPAT_LINUX_SYS_MMAN_H_ + +#include_next <sys/mman.h> + +#include <features.h> + +// There's no memfd_create() wrapper before glibc 2.27. +// This can't select for glibc < 2.27 because linux-chromeos-rel bots build this +// code using a sysroot which has glibc 2.27, but then run it on Ubuntu 16.04, +// which doesn't. +#if defined(__GLIBC__) + +#ifdef __cplusplus +extern "C" { +#endif + +int memfd_create(const char* name, unsigned int flags); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // __GLIBC__ + +#endif // CRASHPAD_COMPAT_LINUX_SYS_MMAN_H_
diff --git a/third_party/crashpad/crashpad/handler/BUILD.gn b/third_party/crashpad/crashpad/handler/BUILD.gn index b841b0c..550f686a 100644 --- a/third_party/crashpad/crashpad/handler/BUILD.gn +++ b/third_party/crashpad/crashpad/handler/BUILD.gn
@@ -42,6 +42,8 @@ if (crashpad_is_linux || crashpad_is_android) { set_sources_assignment_filter([]) sources += [ + "linux/capture_snapshot.cc", + "linux/capture_snapshot.h", "linux/crash_report_exception_handler.cc", "linux/crash_report_exception_handler.h", "linux/exception_handler_server.cc", @@ -49,6 +51,13 @@ ] } + if (crashpad_is_linux) { + sources += [ + "linux/cros_crash_report_exception_handler.cc", + "linux/cros_crash_report_exception_handler.h", + ] + } + if (crashpad_is_win) { sources += [ "win/crash_report_exception_handler.cc",
diff --git a/third_party/crashpad/crashpad/handler/handler_main.cc b/third_party/crashpad/crashpad/handler/handler_main.cc index 05a2e7b..7b69e84 100644 --- a/third_party/crashpad/crashpad/handler/handler_main.cc +++ b/third_party/crashpad/crashpad/handler/handler_main.cc
@@ -56,6 +56,10 @@ #include "util/string/split_string.h" #include "util/synchronization/semaphore.h" +#if defined(OS_CHROMEOS) +#include "handler/linux/cros_crash_report_exception_handler.h" +#endif + #if defined(OS_LINUX) || defined(OS_ANDROID) #include <unistd.h> @@ -157,6 +161,9 @@ #endif // OS_LINUX || OS_ANDROID " --url=URL send crash reports to this Breakpad server URL,\n" " only if uploads are enabled for the database\n" +#if defined(OS_CHROMEOS) +" --use-cros-crash-reporter\n" +#endif // OS_CHROMEOS " --help display this help and exit\n" " --version output version information and exit\n", me.value().c_str()); @@ -188,6 +195,9 @@ bool periodic_tasks; bool rate_limit; bool upload_gzip; +#if defined(OS_CHROMEOS) + bool use_cros_crash_reporter; +#endif // OS_CHROMEOS }; // Splits |key_value| on '=' and inserts the resulting key and value into |map|. @@ -509,6 +519,12 @@ int HandlerMain(int argc, char* argv[], const UserStreamDataSources* user_stream_sources) { +#if defined(OS_CHROMEOS) + if (freopen("/var/log/chrome/chrome", "a", stderr) == nullptr) { + PLOG(ERROR) << "Failed to redirect stderr to /var/log/chrome/chrome"; + } +#endif + InstallCrashHandler(); CallMetricsRecordNormalExit metrics_record_normal_exit; @@ -553,6 +569,9 @@ kOptionTraceParentWithException, #endif kOptionURL, +#if defined(OS_CHROMEOS) + kOptionUseCrosCrashReporter, +#endif // OS_CHROMEOS // Standard options. kOptionHelp = -2, @@ -618,6 +637,12 @@ kOptionTraceParentWithException}, #endif // OS_LINUX || OS_ANDROID {"url", required_argument, nullptr, kOptionURL}, +#if defined(OS_CHROEMOS) + {"use-cros-crash-reporter", + no_argument, + nullptr, + kOptionUseCrosCrashReporter}, +#endif // OS_CHROMEOS {"help", no_argument, nullptr, kOptionHelp}, {"version", no_argument, nullptr, kOptionVersion}, {nullptr, 0, nullptr, 0}, @@ -759,6 +784,12 @@ options.url = optarg; break; } +#if defined(OS_CHROMEOS) + case kOptionUseCrosCrashReporter: { + options.use_cros_crash_reporter = true; + break; + } +#endif // OS_CHROMEOS case kOptionHelp: { Usage(me); MetricsRecordExit(Metrics::LifetimeMilestone::kExitedEarly); @@ -884,7 +915,27 @@ upload_thread.Get()->Start(); } - CrashReportExceptionHandler exception_handler( +#if defined(OS_LINUX) || defined(OS_ANDROID) + std::unique_ptr<ExceptionHandlerServer::Delegate> exception_handler; +#else + std::unique_ptr<CrashReportExceptionHandler> exception_handler; +#endif + +#if defined(OS_CHROMEOS) + if (options.use_cros_crash_reporter) { + exception_handler = std::make_unique<CrosCrashReportExceptionHandler>( + database.get(), + &options.annotations, + user_stream_sources); + } else { + exception_handler = std::make_unique<CrashReportExceptionHandler>( + database.get(), + static_cast<CrashReportUploadThread*>(upload_thread.Get()), + &options.annotations, + user_stream_sources); + } +#else + exception_handler = std::make_unique<CrashReportExceptionHandler>( database.get(), static_cast<CrashReportUploadThread*>(upload_thread.Get()), &options.annotations, @@ -893,15 +944,17 @@ nullptr, #endif user_stream_sources); +#endif // OS_CHROMEOS - #if defined(OS_LINUX) || defined(OS_ANDROID) +#if defined(OS_LINUX) || defined(OS_ANDROID) if (options.exception_information_address) { ExceptionHandlerProtocol::ClientInformation info; info.exception_information_address = options.exception_information_address; info.sanitization_information_address = options.sanitization_information_address; - return exception_handler.HandleException(getppid(), info) ? EXIT_SUCCESS - : ExitFailure(); + return exception_handler->HandleException(getppid(), geteuid(), info) + ? EXIT_SUCCESS + : ExitFailure(); } #endif // OS_LINUX || OS_ANDROID @@ -1005,7 +1058,7 @@ #if defined(OS_WIN) if (options.initial_client_data.IsValid()) { exception_handler_server.InitializeWithInheritedDataForInitialClient( - options.initial_client_data, &exception_handler); + options.initial_client_data, exception_handler.get()); } #elif defined(OS_LINUX) || defined(OS_ANDROID) if (options.initial_client_fd == kInvalidFileHandle || @@ -1016,7 +1069,7 @@ } #endif // OS_WIN - exception_handler_server.Run(&exception_handler); + exception_handler_server.Run(exception_handler.get()); return EXIT_SUCCESS; }
diff --git a/third_party/crashpad/crashpad/handler/linux/capture_snapshot.cc b/third_party/crashpad/crashpad/handler/linux/capture_snapshot.cc new file mode 100644 index 0000000..005402956 --- /dev/null +++ b/third_party/crashpad/crashpad/handler/linux/capture_snapshot.cc
@@ -0,0 +1,119 @@ +// Copyright 2019 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "handler/linux/capture_snapshot.h" + +#include <utility> + +#include "snapshot/crashpad_info_client_options.h" +#include "snapshot/sanitized/sanitization_information.h" +#include "util/misc/metrics.h" +#include "util/misc/tri_state.h" + +namespace crashpad { + +bool CaptureSnapshot( + PtraceConnection* connection, + const ExceptionHandlerProtocol::ClientInformation& info, + const std::map<std::string, std::string>& process_annotations, + uid_t client_uid, + VMAddress requesting_thread_stack_address, + pid_t* requesting_thread_id, + std::unique_ptr<ProcessSnapshotLinux>* snapshot, + std::unique_ptr<ProcessSnapshotSanitized>* sanitized_snapshot) { + std::unique_ptr<ProcessSnapshotLinux> process_snapshot( + new ProcessSnapshotLinux()); + if (!process_snapshot->Initialize(connection)) { + Metrics::ExceptionCaptureResult(Metrics::CaptureResult::kSnapshotFailed); + return false; + } + + pid_t local_requesting_thread_id = -1; + if (requesting_thread_stack_address) { + local_requesting_thread_id = process_snapshot->FindThreadWithStackAddress( + requesting_thread_stack_address); + } + + if (requesting_thread_id) { + *requesting_thread_id = local_requesting_thread_id; + } + + if (!process_snapshot->InitializeException(info.exception_information_address, + local_requesting_thread_id)) { + Metrics::ExceptionCaptureResult( + Metrics::CaptureResult::kExceptionInitializationFailed); + return false; + } + + Metrics::ExceptionCode(process_snapshot->Exception()->Exception()); + + CrashpadInfoClientOptions client_options; + process_snapshot->GetCrashpadOptions(&client_options); + if (client_options.crashpad_handler_behavior == TriState::kDisabled) { + return false; + } + + for (auto& p : process_annotations) { + process_snapshot->AddAnnotation(p.first, p.second); + } + + if (info.sanitization_information_address) { + SanitizationInformation sanitization_info; + ProcessMemoryRange range; + if (!range.Initialize(connection->Memory(), connection->Is64Bit()) || + !range.Read(info.sanitization_information_address, + sizeof(sanitization_info), + &sanitization_info)) { + Metrics::ExceptionCaptureResult( + Metrics::CaptureResult::kSanitizationInitializationFailed); + return false; + } + + auto annotations_whitelist = std::make_unique<std::vector<std::string>>(); + auto memory_range_whitelist = + std::make_unique<std::vector<std::pair<VMAddress, VMAddress>>>(); + if (!ReadAnnotationsWhitelist( + range, + sanitization_info.annotations_whitelist_address, + annotations_whitelist.get()) || + !ReadMemoryRangeWhitelist( + range, + sanitization_info.memory_range_whitelist_address, + memory_range_whitelist.get())) { + Metrics::ExceptionCaptureResult( + Metrics::CaptureResult::kSanitizationInitializationFailed); + return false; + } + + std::unique_ptr<ProcessSnapshotSanitized> sanitized( + new ProcessSnapshotSanitized()); + if (!sanitized->Initialize(process_snapshot.get(), + sanitization_info.annotations_whitelist_address + ? std::move(annotations_whitelist) + : nullptr, + std::move(memory_range_whitelist), + sanitization_info.target_module_address, + sanitization_info.sanitize_stacks)) { + Metrics::ExceptionCaptureResult( + Metrics::CaptureResult::kSkippedDueToSanitization); + return false; + } + *sanitized_snapshot = std::move(sanitized); + } + + *snapshot = std::move(process_snapshot); + return true; +} + +} // namespace crashpad
diff --git a/third_party/crashpad/crashpad/handler/linux/capture_snapshot.h b/third_party/crashpad/crashpad/handler/linux/capture_snapshot.h new file mode 100644 index 0000000..78886dc5 --- /dev/null +++ b/third_party/crashpad/crashpad/handler/linux/capture_snapshot.h
@@ -0,0 +1,67 @@ +// Copyright 2019 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef CRASHPAD_HANDLER_LINUX_CAPTURE_SNAPSHOT_H_ +#define CRASHPAD_HANDLER_LINUX_CAPTURE_SNAPSHOT_H_ + +#include <sys/types.h> + +#include <map> +#include <memory> +#include <string> + +#include "snapshot/linux/process_snapshot_linux.h" +#include "snapshot/sanitized/process_snapshot_sanitized.h" +#include "util/linux/exception_handler_protocol.h" +#include "util/linux/ptrace_connection.h" +#include "util/misc/address_types.h" + +namespace crashpad { + +//! \brief Captures a snapshot of a client over \a connection. +//! +//! \param[in] connection A PtraceConnection to the client to snapshot. +//! \param[in] info Information about the client configuring the snapshot. +//! \param[in] process_annotations A map of annotations to insert as +//! process-level annotations into the snapshot. +//! \param[in] client_uid The client's user ID. +//! \param[in] requesting_thread_stack_address An address on the stack of the +//! thread requesting the snapshot. If \a info includes an exception +//! address, the exception will be assigned to the thread whose stack +//! address range contains this address. If 0, \a requesting_thread_id will +//! be -1. +//! \param[out] requesting_thread_id The thread ID of the thread corresponding +//! to \a requesting_thread_stack_address. Set to -1 if the thread ID could +//! not be determined. Optional. +//! \param[out] process_snapshot A snapshot of the client process, valid if this +//! function returns `true`. +//! \param[out] sanitized_snapshot A sanitized snapshot of the client process, +//! valid if this function returns `true` and sanitization was requested in +//! \a info. +//! \return `true` if \a process_snapshot was successfully created. A message +//! will be logged on failure, but not if the snapshot was skipped because +//! handling was disabled by CrashpadInfoClientOptions. +bool CaptureSnapshot( + PtraceConnection* connection, + const ExceptionHandlerProtocol::ClientInformation& info, + const std::map<std::string, std::string>& process_annotations, + uid_t client_uid, + VMAddress requesting_thread_stack_address, + pid_t* requesting_thread_id, + std::unique_ptr<ProcessSnapshotLinux>* process_snapshot, + std::unique_ptr<ProcessSnapshotSanitized>* sanitized_snapshot); + +} // namespace crashpad + +#endif // CRASHPAD_HANDLER_LINUX_CAPTURE_SNAPSHOT_H_
diff --git a/third_party/crashpad/crashpad/handler/linux/crash_report_exception_handler.cc b/third_party/crashpad/crashpad/handler/linux/crash_report_exception_handler.cc index 875afec..9b4f201 100644 --- a/third_party/crashpad/crashpad/handler/linux/crash_report_exception_handler.cc +++ b/third_party/crashpad/crashpad/handler/linux/crash_report_exception_handler.cc
@@ -14,19 +14,19 @@ #include "handler/linux/crash_report_exception_handler.h" -#include <vector> +#include <memory> +#include <utility> #include "base/logging.h" #include "client/settings.h" +#include "handler/linux/capture_snapshot.h" #include "minidump/minidump_file_writer.h" -#include "snapshot/crashpad_info_client_options.h" #include "snapshot/linux/process_snapshot_linux.h" #include "snapshot/sanitized/process_snapshot_sanitized.h" -#include "snapshot/sanitized/sanitization_information.h" #include "util/linux/direct_ptrace_connection.h" #include "util/linux/ptrace_client.h" +#include "util/misc/implicit_cast.h" #include "util/misc/metrics.h" -#include "util/misc/tri_state.h" #include "util/misc/uuid.h" namespace crashpad { @@ -45,6 +45,7 @@ bool CrashReportExceptionHandler::HandleException( pid_t client_process_id, + uid_t client_uid, const ExceptionHandlerProtocol::ClientInformation& info, VMAddress requesting_thread_stack_address, pid_t* requesting_thread_id, @@ -60,6 +61,7 @@ return HandleExceptionWithConnection(&connection, info, + client_uid, requesting_thread_stack_address, requesting_thread_id, local_report_id); @@ -67,6 +69,7 @@ bool CrashReportExceptionHandler::HandleExceptionWithBroker( pid_t client_process_id, + uid_t client_uid, const ExceptionHandlerProtocol::ClientInformation& info, int broker_sock, UUID* local_report_id) { @@ -80,142 +83,83 @@ } return HandleExceptionWithConnection( - &client, info, 0, nullptr, local_report_id); + &client, info, client_uid, 0, nullptr, local_report_id); } bool CrashReportExceptionHandler::HandleExceptionWithConnection( PtraceConnection* connection, const ExceptionHandlerProtocol::ClientInformation& info, + uid_t client_uid, VMAddress requesting_thread_stack_address, pid_t* requesting_thread_id, UUID* local_report_id) { - ProcessSnapshotLinux process_snapshot; - if (!process_snapshot.Initialize(connection)) { - Metrics::ExceptionCaptureResult(Metrics::CaptureResult::kSnapshotFailed); + std::unique_ptr<ProcessSnapshotLinux> process_snapshot; + std::unique_ptr<ProcessSnapshotSanitized> sanitized_snapshot; + if (!CaptureSnapshot(connection, + info, + *process_annotations_, + client_uid, + requesting_thread_stack_address, + requesting_thread_id, + &process_snapshot, + &sanitized_snapshot)) { return false; } - pid_t local_requesting_thread_id = -1; - if (requesting_thread_stack_address) { - local_requesting_thread_id = process_snapshot.FindThreadWithStackAddress( - requesting_thread_stack_address); + UUID client_id; + Settings* const settings = database_->GetSettings(); + if (settings) { + // If GetSettings() or GetClientID() fails, something else will log a + // message and client_id will be left at its default value, all zeroes, + // which is appropriate. + settings->GetClientID(&client_id); } + process_snapshot->SetClientID(client_id); - if (requesting_thread_id) { - *requesting_thread_id = local_requesting_thread_id; - } - - if (!process_snapshot.InitializeException(info.exception_information_address, - local_requesting_thread_id)) { + std::unique_ptr<CrashReportDatabase::NewReport> new_report; + CrashReportDatabase::OperationStatus database_status = + database_->PrepareNewCrashReport(&new_report); + if (database_status != CrashReportDatabase::kNoError) { + LOG(ERROR) << "PrepareNewCrashReport failed"; Metrics::ExceptionCaptureResult( - Metrics::CaptureResult::kExceptionInitializationFailed); + Metrics::CaptureResult::kPrepareNewCrashReportFailed); return false; } - Metrics::ExceptionCode(process_snapshot.Exception()->Exception()); + process_snapshot->SetReportID(new_report->ReportID()); - CrashpadInfoClientOptions client_options; - process_snapshot.GetCrashpadOptions(&client_options); - if (client_options.crashpad_handler_behavior != TriState::kDisabled) { - UUID client_id; - Settings* const settings = database_->GetSettings(); - if (settings) { - // If GetSettings() or GetClientID() fails, something else will log a - // message and client_id will be left at its default value, all zeroes, - // which is appropriate. - settings->GetClientID(&client_id); - } + ProcessSnapshot* snapshot = + sanitized_snapshot + ? implicit_cast<ProcessSnapshot*>(sanitized_snapshot.get()) + : implicit_cast<ProcessSnapshot*>(process_snapshot.get()); - process_snapshot.SetClientID(client_id); - for (auto& p : *process_annotations_) { - process_snapshot.AddAnnotation(p.first, p.second); - } + MinidumpFileWriter minidump; + minidump.InitializeFromSnapshot(snapshot); + AddUserExtensionStreams(user_stream_data_sources_, snapshot, &minidump); - std::unique_ptr<CrashReportDatabase::NewReport> new_report; - CrashReportDatabase::OperationStatus database_status = - database_->PrepareNewCrashReport(&new_report); - if (database_status != CrashReportDatabase::kNoError) { - LOG(ERROR) << "PrepareNewCrashReport failed"; - Metrics::ExceptionCaptureResult( - Metrics::CaptureResult::kPrepareNewCrashReportFailed); - return false; - } + if (!minidump.WriteEverything(new_report->Writer())) { + LOG(ERROR) << "WriteEverything failed"; + Metrics::ExceptionCaptureResult( + Metrics::CaptureResult::kMinidumpWriteFailed); + return false; + } - process_snapshot.SetReportID(new_report->ReportID()); + UUID uuid; + database_status = + database_->FinishedWritingCrashReport(std::move(new_report), &uuid); + if (database_status != CrashReportDatabase::kNoError) { + LOG(ERROR) << "FinishedWritingCrashReport failed"; + Metrics::ExceptionCaptureResult( + Metrics::CaptureResult::kFinishedWritingCrashReportFailed); + return false; + } - ProcessSnapshot* snapshot = nullptr; - ProcessSnapshotSanitized sanitized; - std::vector<std::string> annotations_whitelist; - std::vector<std::pair<VMAddress, VMAddress>> memory_range_whitelist; - if (info.sanitization_information_address) { - SanitizationInformation sanitization_info; - ProcessMemoryRange range; - if (!range.Initialize(connection->Memory(), connection->Is64Bit()) || - !range.Read(info.sanitization_information_address, - sizeof(sanitization_info), - &sanitization_info)) { - Metrics::ExceptionCaptureResult( - Metrics::CaptureResult::kSanitizationInitializationFailed); - return false; - } + if (upload_thread_) { + upload_thread_->ReportPending(uuid); + } - if (!ReadAnnotationsWhitelist( - range, - sanitization_info.annotations_whitelist_address, - &annotations_whitelist) || - !ReadMemoryRangeWhitelist( - range, - sanitization_info.memory_range_whitelist_address, - &memory_range_whitelist)) { - Metrics::ExceptionCaptureResult( - Metrics::CaptureResult::kSanitizationInitializationFailed); - return false; - } - - if (!sanitized.Initialize(&process_snapshot, - sanitization_info.annotations_whitelist_address - ? &annotations_whitelist - : nullptr, - &memory_range_whitelist, - sanitization_info.target_module_address, - sanitization_info.sanitize_stacks)) { - Metrics::ExceptionCaptureResult( - Metrics::CaptureResult::kSkippedDueToSanitization); - return true; - } - - snapshot = &sanitized; - } else { - snapshot = &process_snapshot; - } - - MinidumpFileWriter minidump; - minidump.InitializeFromSnapshot(snapshot); - AddUserExtensionStreams(user_stream_data_sources_, snapshot, &minidump); - - if (!minidump.WriteEverything(new_report->Writer())) { - LOG(ERROR) << "WriteEverything failed"; - Metrics::ExceptionCaptureResult( - Metrics::CaptureResult::kMinidumpWriteFailed); - return false; - } - - UUID uuid; - database_status = - database_->FinishedWritingCrashReport(std::move(new_report), &uuid); - if (database_status != CrashReportDatabase::kNoError) { - LOG(ERROR) << "FinishedWritingCrashReport failed"; - Metrics::ExceptionCaptureResult( - Metrics::CaptureResult::kFinishedWritingCrashReportFailed); - return false; - } - if (local_report_id != nullptr) { - *local_report_id = uuid; - } - - if (upload_thread_) { - upload_thread_->ReportPending(uuid); - } + if (local_report_id != nullptr) { + *local_report_id = uuid; } Metrics::ExceptionCaptureResult(Metrics::CaptureResult::kSuccess);
diff --git a/third_party/crashpad/crashpad/handler/linux/crash_report_exception_handler.h b/third_party/crashpad/crashpad/handler/linux/crash_report_exception_handler.h index dba8b63..522a77d 100644 --- a/third_party/crashpad/crashpad/handler/linux/crash_report_exception_handler.h +++ b/third_party/crashpad/crashpad/handler/linux/crash_report_exception_handler.h
@@ -60,11 +60,12 @@ const std::map<std::string, std::string>* process_annotations, const UserStreamDataSources* user_stream_data_sources); - ~CrashReportExceptionHandler(); + ~CrashReportExceptionHandler() override; // ExceptionHandlerServer::Delegate: bool HandleException(pid_t client_process_id, + uid_t client_uid, const ExceptionHandlerProtocol::ClientInformation& info, VMAddress requesting_thread_stack_address = 0, pid_t* requesting_thread_id = nullptr, @@ -72,6 +73,7 @@ bool HandleExceptionWithBroker( pid_t client_process_id, + uid_t client_uid, const ExceptionHandlerProtocol::ClientInformation& info, int broker_sock, UUID* local_report_id = nullptr) override; @@ -80,6 +82,7 @@ bool HandleExceptionWithConnection( PtraceConnection* connection, const ExceptionHandlerProtocol::ClientInformation& info, + uid_t client_uid, VMAddress requesting_thread_stack_address, pid_t* requesting_thread_id, UUID* local_report_id = nullptr);
diff --git a/third_party/crashpad/crashpad/handler/linux/cros_crash_report_exception_handler.cc b/third_party/crashpad/crashpad/handler/linux/cros_crash_report_exception_handler.cc new file mode 100644 index 0000000..a24b17f6 --- /dev/null +++ b/third_party/crashpad/crashpad/handler/linux/cros_crash_report_exception_handler.cc
@@ -0,0 +1,278 @@ +// Copyright 2019 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "handler/linux/cros_crash_report_exception_handler.h" + +#include <vector> + +#include "base/logging.h" +#include "client/settings.h" +#include "handler/linux/capture_snapshot.h" +#include "handler/minidump_to_upload_parameters.h" +#include "minidump/minidump_file_writer.h" +#include "snapshot/linux/process_snapshot_linux.h" +#include "snapshot/minidump/process_snapshot_minidump.h" +#include "snapshot/sanitized/process_snapshot_sanitized.h" +#include "util/file/file_writer.h" +#include "util/linux/direct_ptrace_connection.h" +#include "util/linux/ptrace_client.h" +#include "util/misc/metrics.h" +#include "util/misc/uuid.h" +#include "util/posix/double_fork_and_exec.h" + +namespace crashpad { + +namespace { + +// Returns the process name for a pid. +const std::string GetProcessNameFromPid(pid_t pid) { + // Symlink to process binary is at /proc/###/exe. + std::string link_path = "/proc/" + std::to_string(pid) + "/exe"; + + constexpr int kMaxSize = 4096; + std::unique_ptr<char[]> buf(new char[kMaxSize]); + ssize_t size = readlink(link_path.c_str(), buf.get(), kMaxSize); + std::string result; + if (size < 0) { + PLOG(ERROR) << "Failed to readlink " << link_path; + } else { + result.assign(buf.get(), size); + size_t last_slash_pos = result.rfind('/'); + if (last_slash_pos != std::string::npos) { + result = result.substr(last_slash_pos + 1); + } + } + return result; +} + +bool WriteAnnotationsAndMinidump( + const std::map<std::string, std::string>& parameters, + MinidumpFileWriter& minidump, + FileWriter& file_writer) { + for (const auto& kv : parameters) { + if (kv.first.find(':') != std::string::npos) { + LOG(ERROR) << "Annotation key cannot have ':' in it " << kv.first; + return false; + } + if (!file_writer.Write(kv.first.c_str(), strlen(kv.first.c_str()))) { + return false; + } + if (!file_writer.Write(":", 1)) { + return false; + } + size_t value_size = strlen(kv.second.c_str()); + std::string value_size_str = std::to_string(value_size); + if (!file_writer.Write(value_size_str.c_str(), value_size_str.size())) { + return false; + } + if (!file_writer.Write(":", 1)) { + return false; + } + if (!file_writer.Write(kv.second.c_str(), strlen(kv.second.c_str()))) { + return false; + } + } + + static constexpr char kMinidumpName[] = + "upload_file_minidump\"; filename=\"dump\":"; + if (!file_writer.Write(kMinidumpName, sizeof(kMinidumpName) - 1)) { + return false; + } + crashpad::FileOffset dump_size_start_offset = file_writer.Seek(0, SEEK_CUR); + if (dump_size_start_offset < 0) { + LOG(ERROR) << "Failed to get minidump size start offset"; + return false; + } + static constexpr char kMinidumpLengthFilling[] = "00000000000000000000:"; + if (!file_writer.Write(kMinidumpLengthFilling, + sizeof(kMinidumpLengthFilling) - 1)) { + return false; + } + crashpad::FileOffset dump_start_offset = file_writer.Seek(0, SEEK_CUR); + if (dump_start_offset < 0) { + LOG(ERROR) << "Failed to get minidump start offset"; + return false; + } + if (!minidump.WriteEverything(&file_writer)) { + return false; + } + crashpad::FileOffset dump_end_offset = file_writer.Seek(0, SEEK_CUR); + if (dump_end_offset < 0) { + LOG(ERROR) << "Failed to get minidump end offset"; + return false; + } + + size_t dump_data_size = dump_end_offset - dump_start_offset; + std::string dump_data_size_str = std::to_string(dump_data_size); + file_writer.Seek(dump_size_start_offset + strlen(kMinidumpLengthFilling) - 1 - + dump_data_size_str.size(), + SEEK_SET); + if (!file_writer.Write(dump_data_size_str.c_str(), + dump_data_size_str.size())) { + return false; + } + return true; +} + +} // namespace + +CrosCrashReportExceptionHandler::CrosCrashReportExceptionHandler( + CrashReportDatabase* database, + const std::map<std::string, std::string>* process_annotations, + const UserStreamDataSources* user_stream_data_sources) + : database_(database), + process_annotations_(process_annotations), + user_stream_data_sources_(user_stream_data_sources) {} + +CrosCrashReportExceptionHandler::~CrosCrashReportExceptionHandler() = default; + +bool CrosCrashReportExceptionHandler::HandleException( + pid_t client_process_id, + uid_t client_uid, + const ExceptionHandlerProtocol::ClientInformation& info, + VMAddress requesting_thread_stack_address, + pid_t* requesting_thread_id, + UUID* local_report_id) { + Metrics::ExceptionEncountered(); + + DirectPtraceConnection connection; + if (!connection.Initialize(client_process_id)) { + Metrics::ExceptionCaptureResult( + Metrics::CaptureResult::kDirectPtraceFailed); + return false; + } + + return HandleExceptionWithConnection(&connection, + info, + client_uid, + requesting_thread_stack_address, + requesting_thread_id, + local_report_id); +} + +bool CrosCrashReportExceptionHandler::HandleExceptionWithBroker( + pid_t client_process_id, + uid_t client_uid, + const ExceptionHandlerProtocol::ClientInformation& info, + int broker_sock, + UUID* local_report_id) { + Metrics::ExceptionEncountered(); + + PtraceClient client; + if (!client.Initialize(broker_sock, client_process_id)) { + Metrics::ExceptionCaptureResult( + Metrics::CaptureResult::kBrokeredPtraceFailed); + return false; + } + + return HandleExceptionWithConnection( + &client, info, client_uid, 0, nullptr, local_report_id); +} + +bool CrosCrashReportExceptionHandler::HandleExceptionWithConnection( + PtraceConnection* connection, + const ExceptionHandlerProtocol::ClientInformation& info, + uid_t client_uid, + VMAddress requesting_thread_stack_address, + pid_t* requesting_thread_id, + UUID* local_report_id) { + std::unique_ptr<ProcessSnapshotLinux> process_snapshot; + std::unique_ptr<ProcessSnapshotSanitized> sanitized_snapshot; + if (!CaptureSnapshot(connection, + info, + *process_annotations_, + client_uid, + requesting_thread_stack_address, + requesting_thread_id, + &process_snapshot, + &sanitized_snapshot)) { + return false; + } + + UUID client_id; + Settings* const settings = database_->GetSettings(); + if (settings) { + // If GetSettings() or GetClientID() fails, something else will log a + // message and client_id will be left at its default value, all zeroes, + // which is appropriate. + settings->GetClientID(&client_id); + } + process_snapshot->SetClientID(client_id); + + UUID uuid; + uuid.InitializeWithNew(); + process_snapshot->SetReportID(uuid); + + ProcessSnapshot* snapshot = + sanitized_snapshot + ? implicit_cast<ProcessSnapshot*>(sanitized_snapshot.get()) + : implicit_cast<ProcessSnapshot*>(process_snapshot.get()); + + MinidumpFileWriter minidump; + minidump.InitializeFromSnapshot(snapshot); + AddUserExtensionStreams(user_stream_data_sources_, snapshot, &minidump); + + FileWriter file_writer; + if (!file_writer.OpenMemfd(base::FilePath("/tmp/minidump"))) { + Metrics::ExceptionCaptureResult(Metrics::CaptureResult::kOpenMemfdFailed); + return false; + } + + std::map<std::string, std::string> parameters = + BreakpadHTTPFormParametersFromMinidump(snapshot); + // Used to differentiate between breakpad and crashpad while the switch is + // ramping up. + parameters.emplace("crash_library", "crashpad"); + + if (!WriteAnnotationsAndMinidump(parameters, minidump, file_writer)) { + Metrics::ExceptionCaptureResult( + Metrics::CaptureResult::kMinidumpWriteFailed); + return false; + } + + // CrOS uses crash_reporter instead of Crashpad to report crashes. + // crash_reporter needs to know the pid and uid of the crashing process. + std::vector<std::string> argv({"/sbin/crash_reporter"}); + + argv.push_back("--chrome_memfd=" + std::to_string(file_writer.fd())); + argv.push_back("--pid=" + std::to_string(*requesting_thread_id)); + argv.push_back("--uid=" + std::to_string(client_uid)); + std::string process_name = GetProcessNameFromPid(*requesting_thread_id); + argv.push_back("--exe=" + (process_name.empty() ? "chrome" : process_name)); + + if (info.crash_loop_before_time != 0) { + argv.push_back("--crash_loop_before=" + + std::to_string(info.crash_loop_before_time)); + } + + if (!DoubleForkAndExec(argv, + nullptr /* envp */, + file_writer.fd() /* preserve_fd */, + false /* use_path */, + nullptr /* child_function */)) { + LOG(ERROR) << "DoubleForkAndExec failed"; + Metrics::ExceptionCaptureResult( + Metrics::CaptureResult::kFinishedWritingCrashReportFailed); + return false; + } + + if (local_report_id != nullptr) { + *local_report_id = uuid; + } + + Metrics::ExceptionCaptureResult(Metrics::CaptureResult::kSuccess); + return true; +} + +} // namespace crashpad
diff --git a/third_party/crashpad/crashpad/handler/linux/cros_crash_report_exception_handler.h b/third_party/crashpad/crashpad/handler/linux/cros_crash_report_exception_handler.h new file mode 100644 index 0000000..f6ca445b --- /dev/null +++ b/third_party/crashpad/crashpad/handler/linux/cros_crash_report_exception_handler.h
@@ -0,0 +1,97 @@ +// Copyright 2019 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef CRASHPAD_HANDLER_LINUX_CROS_CRASH_REPORT_EXCEPTION_HANDLER_H_ +#define CRASHPAD_HANDLER_LINUX_CROS_CRASH_REPORT_EXCEPTION_HANDLER_H_ + +#include <map> +#include <string> + +#include "base/macros.h" +#include "client/crash_report_database.h" +#include "handler/linux/exception_handler_server.h" +#include "handler/user_stream_data_source.h" +#include "util/linux/exception_handler_protocol.h" +#include "util/linux/ptrace_connection.h" +#include "util/misc/address_types.h" +#include "util/misc/uuid.h" + +namespace crashpad { + +//! \brief An exception handler that writes crash reports to the ChromeOS +//! crash_reporter. +class CrosCrashReportExceptionHandler + : public ExceptionHandlerServer::Delegate { + public: + //! \brief Creates a new object that will pass reports to + //! `/sbin/crash_reporter`. + //! + //! \param[in] database The database that supplies settings for this client. + //! This object does not write its reports to this database. + //! \param[in] process_annotations A map of annotations to insert as + //! process-level annotations into each crash report that is written. Do + //! not confuse this with module-level annotations, which are under the + //! control of the crashing process, and are used to implement Chrome’s + //! “crash keys.” Process-level annotations are those that are beyond the + //! control of the crashing process, which must reliably be set even if + //! the process crashes before it’s able to establish its own annotations. + //! To interoperate with Breakpad servers, the recommended practice is to + //! specify values for the `"prod"` and `"ver"` keys as process + //! annotations. + //! \param[in] user_stream_data_sources Data sources to be used to extend + //! crash reports. For each crash report that is written, the data sources + //! are called in turn. These data sources may contribute additional + //! minidump streams. `nullptr` if not required. + CrosCrashReportExceptionHandler( + CrashReportDatabase* database, + const std::map<std::string, std::string>* process_annotations, + const UserStreamDataSources* user_stream_data_sources); + + ~CrosCrashReportExceptionHandler() override; + + // ExceptionHandlerServer::Delegate: + + bool HandleException(pid_t client_process_id, + uid_t client_uid, + const ExceptionHandlerProtocol::ClientInformation& info, + VMAddress requesting_thread_stack_address = 0, + pid_t* requesting_thread_id = nullptr, + UUID* local_report_id = nullptr) override; + + bool HandleExceptionWithBroker( + pid_t client_process_id, + uid_t client_uid, + const ExceptionHandlerProtocol::ClientInformation& info, + int broker_sock, + UUID* local_report_id = nullptr) override; + + private: + bool HandleExceptionWithConnection( + PtraceConnection* connection, + const ExceptionHandlerProtocol::ClientInformation& info, + uid_t client_uid, + VMAddress requesting_thread_stack_address, + pid_t* requesting_thread_id, + UUID* local_report_id = nullptr); + + CrashReportDatabase* database_; // weak + const std::map<std::string, std::string>* process_annotations_; // weak + const UserStreamDataSources* user_stream_data_sources_; // weak + + DISALLOW_COPY_AND_ASSIGN(CrosCrashReportExceptionHandler); +}; + +} // namespace crashpad + +#endif // CRASHPAD_HANDLER_LINUX_CROS_CRASH_REPORT_EXCEPTION_HANDLER_H_
diff --git a/third_party/crashpad/crashpad/handler/linux/exception_handler_server.cc b/third_party/crashpad/crashpad/handler/linux/exception_handler_server.cc index ef03696a..7bb14f92 100644 --- a/third_party/crashpad/crashpad/handler/linux/exception_handler_server.cc +++ b/third_party/crashpad/crashpad/handler/linux/exception_handler_server.cc
@@ -448,6 +448,7 @@ bool multiple_clients) { pid_t client_process_id = creds.pid; pid_t requesting_thread_id = -1; + uid_t client_uid = creds.uid; switch ( strategy_decider_->ChooseStrategy(client_sock, multiple_clients, creds)) { @@ -469,6 +470,7 @@ case PtraceStrategyDecider::Strategy::kDirectPtrace: { delegate_->HandleException(client_process_id, + client_uid, client_info, requesting_thread_stack_address, &requesting_thread_id); @@ -482,7 +484,7 @@ case PtraceStrategyDecider::Strategy::kUseBroker: DCHECK(!multiple_clients); delegate_->HandleExceptionWithBroker( - client_process_id, client_info, client_sock); + client_process_id, client_uid, client_info, client_sock); break; }
diff --git a/third_party/crashpad/crashpad/handler/linux/exception_handler_server.h b/third_party/crashpad/crashpad/handler/linux/exception_handler_server.h index b6251e1..ac430a4c 100644 --- a/third_party/crashpad/crashpad/handler/linux/exception_handler_server.h +++ b/third_party/crashpad/crashpad/handler/linux/exception_handler_server.h
@@ -76,6 +76,7 @@ //! \brief Called on receipt of a crash dump request from a client. //! //! \param[in] client_process_id The process ID of the crashing client. + //! \param[in] client_uid The user ID of the crashing client. //! \param[in] info Information on the client. //! \param[in] requesting_thread_stack_address Any address within the stack //! range for the the thread that sent the crash dump request. Optional. @@ -88,6 +89,7 @@ //! \return `true` on success. `false` on failure with a message logged. virtual bool HandleException( pid_t client_process_id, + uid_t client_uid, const ExceptionHandlerProtocol::ClientInformation& info, VMAddress requesting_thread_stack_address = 0, pid_t* requesting_thread_id = nullptr, @@ -97,6 +99,7 @@ //! crash that should be mediated by a PtraceBroker. //! //! \param[in] client_process_id The process ID of the crashing client. + //! \param[in] client_uid The uid of the crashing client. //! \param[in] info Information on the client. //! \param[in] broker_sock A socket connected to the PtraceBroker. //! \param[out] local_report_id The unique identifier for the report created @@ -104,12 +107,12 @@ //! \return `true` on success. `false` on failure with a message logged. virtual bool HandleExceptionWithBroker( pid_t client_process_id, + uid_t client_uid, const ExceptionHandlerProtocol::ClientInformation& info, int broker_sock, UUID* local_report_id = nullptr) = 0; - protected: - ~Delegate() {} + virtual ~Delegate() {} }; ExceptionHandlerServer();
diff --git a/third_party/crashpad/crashpad/handler/linux/exception_handler_server_test.cc b/third_party/crashpad/crashpad/handler/linux/exception_handler_server_test.cc index ea10db35..45f19965 100644 --- a/third_party/crashpad/crashpad/handler/linux/exception_handler_server_test.cc +++ b/third_party/crashpad/crashpad/handler/linux/exception_handler_server_test.cc
@@ -108,6 +108,7 @@ } bool HandleException(pid_t client_process_id, + uid_t client_uid, const ExceptionHandlerProtocol::ClientInformation& info, VMAddress requesting_thread_stack_address, pid_t* requesting_thread_id = nullptr, @@ -141,6 +142,7 @@ bool HandleExceptionWithBroker( pid_t client_process_id, + uid_t client_uid, const ExceptionHandlerProtocol::ClientInformation& info, int broker_sock, UUID* local_report_id = nullptr) override {
diff --git a/third_party/crashpad/crashpad/handler/mac/crash_report_exception_handler.h b/third_party/crashpad/crashpad/handler/mac/crash_report_exception_handler.h index 0b44de6..b5a59e4 100644 --- a/third_party/crashpad/crashpad/handler/mac/crash_report_exception_handler.h +++ b/third_party/crashpad/crashpad/handler/mac/crash_report_exception_handler.h
@@ -30,7 +30,8 @@ //! \brief An exception handler that writes crash reports for exception messages //! to a CrashReportDatabase. -class CrashReportExceptionHandler : public UniversalMachExcServer::Interface { +class CrashReportExceptionHandler final + : public UniversalMachExcServer::Interface { public: //! \brief Creates a new object that will store crash reports in \a database. //!
diff --git a/third_party/crashpad/crashpad/handler/win/crash_report_exception_handler.h b/third_party/crashpad/crashpad/handler/win/crash_report_exception_handler.h index c2781de3..566f0472d 100644 --- a/third_party/crashpad/crashpad/handler/win/crash_report_exception_handler.h +++ b/third_party/crashpad/crashpad/handler/win/crash_report_exception_handler.h
@@ -31,7 +31,8 @@ //! \brief An exception handler that writes crash reports for exception messages //! to a CrashReportDatabase. -class CrashReportExceptionHandler : public ExceptionHandlerServer::Delegate { +class CrashReportExceptionHandler final + : public ExceptionHandlerServer::Delegate { public: //! \brief Creates a new object that will store crash reports in \a database. //!
diff --git a/third_party/crashpad/crashpad/minidump/minidump_file_writer.cc b/third_party/crashpad/crashpad/minidump/minidump_file_writer.cc index 7226545..f29a6fa 100644 --- a/third_party/crashpad/crashpad/minidump/minidump_file_writer.cc +++ b/third_party/crashpad/crashpad/minidump/minidump_file_writer.cc
@@ -232,7 +232,7 @@ // it as a valid minidump file. header_.Signature = MINIDUMP_SIGNATURE; - if (file_writer->Seek(start_offset, SEEK_SET) != 0) { + if (file_writer->Seek(start_offset, SEEK_SET) < 0) { return false; }
diff --git a/third_party/crashpad/crashpad/snapshot/fuchsia/process_reader_fuchsia.cc b/third_party/crashpad/crashpad/snapshot/fuchsia/process_reader_fuchsia.cc index ecad29a..c76a1f57 100644 --- a/third_party/crashpad/crashpad/snapshot/fuchsia/process_reader_fuchsia.cc +++ b/third_party/crashpad/crashpad/snapshot/fuchsia/process_reader_fuchsia.cc
@@ -105,8 +105,6 @@ process_memory_.reset(new ProcessMemoryFuchsia()); process_memory_->Initialize(*process_); - memory_map_.Initialize(*process_); - INITIALIZATION_STATE_SET_VALID(initialized_); return true; } @@ -133,6 +131,16 @@ return threads_; } +const MemoryMapFuchsia* ProcessReaderFuchsia::MemoryMap() { + INITIALIZATION_STATE_DCHECK_VALID(initialized_); + + if (!initialized_memory_map_) { + InitializeMemoryMap(); + } + + return memory_map_.get(); +} + void ProcessReaderFuchsia::InitializeModules() { DCHECK(!initialized_modules_); DCHECK(modules_.empty()); @@ -255,13 +263,15 @@ std::unique_ptr<ProcessMemoryRange> process_memory_range( new ProcessMemoryRange()); // TODO(scottmg): Could this be limited range? - process_memory_range->Initialize(process_memory_.get(), true); - process_memory_ranges_.push_back(std::move(process_memory_range)); + if (process_memory_range->Initialize(process_memory_.get(), true)) { + process_memory_ranges_.push_back(std::move(process_memory_range)); - reader->Initialize(*process_memory_ranges_.back(), base); - module.reader = reader.get(); - module_readers_.push_back(std::move(reader)); - modules_.push_back(module); + if (reader->Initialize(*process_memory_ranges_.back(), base)) { + module.reader = reader.get(); + module_readers_.push_back(std::move(reader)); + modules_.push_back(module); + } + } map = next; } @@ -311,7 +321,13 @@ } else { thread.general_registers = general_regs; - GetStackRegions(general_regs, memory_map_, &thread.stack_regions); + const MemoryMapFuchsia* memory_map = MemoryMap(); + if (memory_map) { + // Attempt to retrive stack regions if a memory map was retrieved. In + // particular, this may be null when operating on the current process + // where the memory map will not be able to be retrieved. + GetStackRegions(general_regs, *memory_map, &thread.stack_regions); + } } zx_thread_state_vector_regs_t vector_regs; @@ -329,4 +345,15 @@ } } +void ProcessReaderFuchsia::InitializeMemoryMap() { + DCHECK(!initialized_memory_map_); + + initialized_memory_map_ = true; + + memory_map_.reset(new MemoryMapFuchsia); + if (!memory_map_->Initialize(*process_)) { + memory_map_.reset(); + } +} + } // namespace crashpad
diff --git a/third_party/crashpad/crashpad/snapshot/fuchsia/process_reader_fuchsia.h b/third_party/crashpad/crashpad/snapshot/fuchsia/process_reader_fuchsia.h index 1392004e..91c6331c7 100644 --- a/third_party/crashpad/crashpad/snapshot/fuchsia/process_reader_fuchsia.h +++ b/third_party/crashpad/crashpad/snapshot/fuchsia/process_reader_fuchsia.h
@@ -112,7 +112,7 @@ const ProcessMemory* Memory() const { return process_memory_.get(); } //! \brief Return a memory map for the target process. - const MemoryMapFuchsia* MemoryMap() const { return &memory_map_; } + const MemoryMapFuchsia* MemoryMap(); private: //! Performs lazy initialization of the \a modules_ vector on behalf of @@ -123,15 +123,20 @@ //! Threads(). void InitializeThreads(); + //! Performs lazy initialization of the \a memory_map_ on behalf of + //! MemoryMap(). + void InitializeMemoryMap(); + std::vector<Module> modules_; std::vector<Thread> threads_; std::vector<std::unique_ptr<ElfImageReader>> module_readers_; std::vector<std::unique_ptr<ProcessMemoryRange>> process_memory_ranges_; std::unique_ptr<ProcessMemoryFuchsia> process_memory_; - MemoryMapFuchsia memory_map_; + std::unique_ptr<MemoryMapFuchsia> memory_map_; zx::unowned_process process_; bool initialized_modules_ = false; bool initialized_threads_ = false; + bool initialized_memory_map_ = false; InitializationStateDcheck initialized_; DISALLOW_COPY_AND_ASSIGN(ProcessReaderFuchsia);
diff --git a/third_party/crashpad/crashpad/snapshot/fuchsia/process_snapshot_fuchsia.cc b/third_party/crashpad/crashpad/snapshot/fuchsia/process_snapshot_fuchsia.cc index 1ff758d1..294c9f9 100644 --- a/third_party/crashpad/crashpad/snapshot/fuchsia/process_snapshot_fuchsia.cc +++ b/third_party/crashpad/crashpad/snapshot/fuchsia/process_snapshot_fuchsia.cc
@@ -41,10 +41,13 @@ InitializeThreads(); InitializeModules(); - for (const auto& entry : process_reader_.MemoryMap()->Entries()) { - if (entry.type == ZX_INFO_MAPS_TYPE_MAPPING) { - memory_map_.push_back( - std::make_unique<internal::MemoryMapRegionSnapshotFuchsia>(entry)); + const MemoryMapFuchsia* memory_map = process_reader_.MemoryMap(); + if (memory_map) { + for (const auto& entry : memory_map->Entries()) { + if (entry.type == ZX_INFO_MAPS_TYPE_MAPPING) { + memory_map_.push_back( + std::make_unique<internal::MemoryMapRegionSnapshotFuchsia>(entry)); + } } }
diff --git a/third_party/crashpad/crashpad/snapshot/sanitized/process_snapshot_sanitized.cc b/third_party/crashpad/crashpad/snapshot/sanitized/process_snapshot_sanitized.cc index ae689e5..722abac 100644 --- a/third_party/crashpad/crashpad/snapshot/sanitized/process_snapshot_sanitized.cc +++ b/third_party/crashpad/crashpad/snapshot/sanitized/process_snapshot_sanitized.cc
@@ -84,13 +84,14 @@ bool ProcessSnapshotSanitized::Initialize( const ProcessSnapshot* snapshot, - const std::vector<std::string>* annotations_whitelist, - const std::vector<std::pair<VMAddress, VMAddress>>* memory_range_whitelist, + std::unique_ptr<const std::vector<std::string>> annotations_whitelist, + std::unique_ptr<const std::vector<std::pair<VMAddress, VMAddress>>> + memory_range_whitelist, VMAddress target_module_address, bool sanitize_stacks) { INITIALIZATION_STATE_SET_INITIALIZING(initialized_); snapshot_ = snapshot; - annotations_whitelist_ = annotations_whitelist; + annotations_whitelist_ = std::move(annotations_whitelist); sanitize_stacks_ = sanitize_stacks; if (target_module_address) { @@ -141,7 +142,7 @@ if (annotations_whitelist_) { for (const auto module : snapshot_->Modules()) { modules_.emplace_back(std::make_unique<internal::ModuleSnapshotSanitized>( - module, annotations_whitelist_)); + module, annotations_whitelist_.get())); } } @@ -158,7 +159,7 @@ } } - process_memory_.Initialize(snapshot_->Memory(), memory_range_whitelist); + process_memory_.Initialize(snapshot_->Memory(), memory_range_whitelist.get()); INITIALIZATION_STATE_SET_VALID(initialized_); return true;
diff --git a/third_party/crashpad/crashpad/snapshot/sanitized/process_snapshot_sanitized.h b/third_party/crashpad/crashpad/snapshot/sanitized/process_snapshot_sanitized.h index 9ed2350..4e7e6d6 100644 --- a/third_party/crashpad/crashpad/snapshot/sanitized/process_snapshot_sanitized.h +++ b/third_party/crashpad/crashpad/snapshot/sanitized/process_snapshot_sanitized.h
@@ -61,12 +61,13 @@ //! internal::StackSnapshotSanitized. //! \return `false` if \a snapshot does not meet sanitization requirements and //! should be filtered entirely. Otherwise `true`. - bool Initialize(const ProcessSnapshot* snapshot, - const std::vector<std::string>* annotations_whitelist, - const std::vector<std::pair<VMAddress, VMAddress>>* - memory_range_whitelist, - VMAddress target_module_address, - bool sanitize_stacks); + bool Initialize( + const ProcessSnapshot* snapshot, + std::unique_ptr<const std::vector<std::string>> annotations_whitelist, + std::unique_ptr<const std::vector<std::pair<VMAddress, VMAddress>>> + memory_range_whitelist, + VMAddress target_module_address, + bool sanitize_stacks); // ProcessSnapshot: @@ -99,7 +100,7 @@ RangeSet address_ranges_; const ProcessSnapshot* snapshot_; ProcessMemorySanitized process_memory_; - const std::vector<std::string>* annotations_whitelist_; + std::unique_ptr<const std::vector<std::string>> annotations_whitelist_; bool sanitize_stacks_; InitializationStateDcheck initialized_;
diff --git a/third_party/crashpad/crashpad/snapshot/sanitized/process_snapshot_sanitized_test.cc b/third_party/crashpad/crashpad/snapshot/sanitized/process_snapshot_sanitized_test.cc index 9bad86c..5c5ff1a 100644 --- a/third_party/crashpad/crashpad/snapshot/sanitized/process_snapshot_sanitized_test.cc +++ b/third_party/crashpad/crashpad/snapshot/sanitized/process_snapshot_sanitized_test.cc
@@ -271,17 +271,18 @@ addrs.string_address, /* sanitized= */ false); - std::vector<std::string> annotations_whitelist; - annotations_whitelist.push_back(kWhitelistedAnnotationName); + auto annotations_whitelist = std::make_unique<std::vector<std::string>>(); + annotations_whitelist->push_back(kWhitelistedAnnotationName); - std::vector<std::pair<VMAddress, VMAddress>> memory_ranges_whitelist; - memory_ranges_whitelist.push_back( + auto memory_ranges_whitelist = + std::make_unique<std::vector<std::pair<VMAddress, VMAddress>>>(); + memory_ranges_whitelist->push_back( std::make_pair(addrs.string_address, addrs.string_address + 1)); ProcessSnapshotSanitized sanitized; ASSERT_TRUE(sanitized.Initialize(&snapshot, - &annotations_whitelist, - &memory_ranges_whitelist, + std::move(annotations_whitelist), + std::move(memory_ranges_whitelist), addrs.module_address, true));
diff --git a/third_party/crashpad/crashpad/third_party/fuchsia/BUILD.gn b/third_party/crashpad/crashpad/third_party/fuchsia/BUILD.gn index b7f69e6..9c25b58 100644 --- a/third_party/crashpad/crashpad/third_party/fuchsia/BUILD.gn +++ b/third_party/crashpad/crashpad/third_party/fuchsia/BUILD.gn
@@ -17,8 +17,8 @@ if (crashpad_is_in_fuchsia) { group("fuchsia") { public_deps = [ - "//zircon/public/fidl/fuchsia.mem", - "//zircon/public/fidl/fuchsia.sysinfo:fuchsia.sysinfo_c", + "//zircon/system/fidl/fuchsia-mem", + "//zircon/system/fidl/fuchsia-sysinfo:fuchsia-sysinfo_c", "//zircon/public/lib/fdio", "//zircon/public/lib/zx", ]
diff --git a/third_party/crashpad/crashpad/third_party/zlib/BUILD.gn b/third_party/crashpad/crashpad/third_party/zlib/BUILD.gn index f84b8baf..3267b981 100644 --- a/third_party/crashpad/crashpad/third_party/zlib/BUILD.gn +++ b/third_party/crashpad/crashpad/third_party/zlib/BUILD.gn
@@ -104,6 +104,10 @@ ] } + configs -= [ + "//third_party/mini_chromium/mini_chromium/build:Wimplicit_fallthrough", + ] + if (current_cpu == "x86" || current_cpu == "x64") { sources += [ "zlib/crc_folding.c",
diff --git a/third_party/crashpad/crashpad/util/file/file_io.h b/third_party/crashpad/crashpad/util/file/file_io.h index 797db682..3c956cc 100644 --- a/third_party/crashpad/crashpad/util/file/file_io.h +++ b/third_party/crashpad/crashpad/util/file/file_io.h
@@ -398,6 +398,19 @@ FileWriteMode mode, FilePermissions permissions); +#if defined(OS_LINUX) +//! \brief Wraps memfd_create(), logging an error if the operation fails. +//! Unlike other file open operations, this doesn't set `O_CLOEXEC`. +//! +//! \return The newly opened FileHandle, or an invalid FileHandle on failure. +//! +//! \sa ScopedFileHandle +//! \sa LoggingOpenFileForRead +//! \sa LoggingOpenFileForWrite +//! \sa LoggingOpenFileForReadAndWrite +FileHandle LoggingOpenMemFileForWrite(const base::FilePath& path); +#endif // OS_LINUX + //! \brief Wraps OpenFileForReadAndWrite(), logging an error if the operation //! fails. //!
diff --git a/third_party/crashpad/crashpad/util/file/file_io_posix.cc b/third_party/crashpad/crashpad/util/file/file_io_posix.cc index f311616..b72a48eb 100644 --- a/third_party/crashpad/crashpad/util/file/file_io_posix.cc +++ b/third_party/crashpad/crashpad/util/file/file_io_posix.cc
@@ -16,6 +16,7 @@ #include <fcntl.h> #include <sys/file.h> +#include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> @@ -98,6 +99,12 @@ permissions == FilePermissions::kWorldReadable ? 0644 : 0600)); } +#if defined(OS_LINUX) +FileHandle OpenMemFileForOutput(const base::FilePath& path) { + return HANDLE_EINTR(memfd_create(path.value().c_str(), 0)); +} +#endif + } // namespace namespace internal { @@ -149,6 +156,14 @@ return fd; } +#if defined(OS_LINUX) +FileHandle LoggingOpenMemFileForWrite(const base::FilePath& path) { + FileHandle fd = OpenMemFileForOutput(path); + PLOG_IF(ERROR, fd < 0) << "memfd_create " << path.value(); + return fd; +} +#endif + FileHandle LoggingOpenFileForReadAndWrite(const base::FilePath& path, FileWriteMode mode, FilePermissions permissions) {
diff --git a/third_party/crashpad/crashpad/util/file/file_writer.cc b/third_party/crashpad/crashpad/util/file/file_writer.cc index 13ac6cf..de28575d 100644 --- a/third_party/crashpad/crashpad/util/file/file_writer.cc +++ b/third_party/crashpad/crashpad/util/file/file_writer.cc
@@ -171,6 +171,23 @@ return true; } +#if defined(OS_LINUX) +bool FileWriter::OpenMemfd(const base::FilePath& path) { + CHECK(!file_.is_valid()); + file_.reset(LoggingOpenMemFileForWrite(path)); + if (!file_.is_valid()) { + return false; + } + + weak_file_handle_file_writer_.set_file_handle(file_.get()); + return true; +} + +int FileWriter::fd() { + return file_.get(); +} +#endif + void FileWriter::Close() { CHECK(file_.is_valid());
diff --git a/third_party/crashpad/crashpad/util/file/file_writer.h b/third_party/crashpad/crashpad/util/file/file_writer.h index ed261ec..663adff 100644 --- a/third_party/crashpad/crashpad/util/file/file_writer.h +++ b/third_party/crashpad/crashpad/util/file/file_writer.h
@@ -131,6 +131,22 @@ FileWriteMode write_mode, FilePermissions permissions); +#if defined(OS_LINUX) + //! \brief Wraps LoggingOpenMemFileForWrite(). + //! + //! \return `true` if the operation succeeded, `false` if it failed, with an + //! error message logged. + //! + //! \note After a successful call, this method or Open() cannot be called + // again until after Close(). + bool OpenMemfd(const base::FilePath& path); + + //! \brief Returns the underlying file descriptor. + //! + //! \note This is used when this writes to a Memfd. + int fd(); +#endif + //! \brief Wraps CheckedCloseHandle(). //! //! \note It is only valid to call this method on an object that has had a
diff --git a/third_party/crashpad/crashpad/util/linux/exception_handler_protocol.h b/third_party/crashpad/crashpad/util/linux/exception_handler_protocol.h index 7f4da26..90688c7 100644 --- a/third_party/crashpad/crashpad/util/linux/exception_handler_protocol.h +++ b/third_party/crashpad/crashpad/util/linux/exception_handler_protocol.h
@@ -50,6 +50,13 @@ //! \brief The address in the client's address space of a //! SanitizationInformation struct, or 0 if there is no such struct. VMAddress sanitization_information_address; + +#if defined(OS_LINUX) + //! \brief Indicates that the client is likely in a crash loop if a crash + //! occurs before this timestamp. This value is only used by ChromeOS's + //! `/sbin/crash_reporter`. + uint64_t crash_loop_before_time; +#endif }; //! \brief The signal used to indicate a crash dump is complete.
diff --git a/third_party/crashpad/crashpad/util/misc/metrics.h b/third_party/crashpad/crashpad/util/misc/metrics.h index 8046497..d976381 100644 --- a/third_party/crashpad/crashpad/util/misc/metrics.h +++ b/third_party/crashpad/crashpad/util/misc/metrics.h
@@ -139,6 +139,9 @@ //! \brief Sanitization caused this crash dump to be skipped. kSkippedDueToSanitization = 11, + //! \brief Failure to open a memfd caused this crash dump to be skipped. + kOpenMemfdFailed = 12, + //! \brief The number of values in this enumeration; not a valid value. kMaxValue };
diff --git a/tools/metrics/actions/actions.xml b/tools/metrics/actions/actions.xml index c8f9858..ef7d652c 100644 --- a/tools/metrics/actions/actions.xml +++ b/tools/metrics/actions/actions.xml
@@ -13938,6 +13938,24 @@ <description>Please enter the description of this user action.</description> </action> +<action name="NativeFileSystemAPI.OpenedBubble"> + <owner>mek@chromium.org</owner> + <owner>src/content/browser/native_file_system/OWNERS</owner> + <description> + Recorded any time the user opens the usage indicator bubble for the Native + File System API. + </description> +</action> + +<action name="NativeFileSystemAPI.RevokePermissions"> + <owner>mek@chromium.org</owner> + <owner>src/content/browser/native_file_system/OWNERS</owner> + <description> + Recorded any time the user revokes all Native File System API permissions + from the usage indicator bubble. + </description> +</action> + <action name="NativeUI_Applications"> <owner>Please list the metric's owners. Add more owner tags as needed.</owner> <description>Please enter the description of this user action.</description>
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 0fc43f76..75daa7c 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -20452,6 +20452,7 @@ <int value="1375" label="AUTOTESTPRIVATE_GETARCAPPWINDOWINFO"/> <int value="1376" label="AUTOTESTPRIVATE_GETALLINSTALLEDAPPS"/> <int value="1377" label="AUTOTESTPRIVATE_SWAPWINDOWSINSPLITVIEW"/> + <int value="1378" label="AUTOTESTPRIVATE_SETARCAPPWINDOWFOCUS"/> </enum> <enum name="ExtensionIconState"> @@ -24489,6 +24490,9 @@ <int value="3012" label="FetchRedirectError"/> <int value="3013" label="FetchRedirectManual"/> <int value="3014" label="FetchCacheReload"/> + <int value="3015" label="V8Window_ChooseFileSystemEntries_Method"/> + <int value="3016" + label="V8FileSystemDirectoryHandle_GetSystemDirectory_Method"/> </enum> <enum name="FeaturePolicyAllowlistType"> @@ -29575,6 +29579,9 @@ </enum> <enum name="HeavyAdStatus"> + <obsolete> + Deprected 09/2019 in favor of HeavyAdStatus2. + </obsolete> <int value="0" label="Not heavy"/> <int value="1" label="Network"> The ad exceeded the network threshold for the Heavy Ad Intervention. @@ -29584,6 +29591,19 @@ </int> </enum> +<enum name="HeavyAdStatus2"> + <int value="0" label="Not heavy"/> + <int value="1" label="Network"> + The ad exceeded the network threshold for the Heavy Ad Intervention. + </int> + <int value="2" label="Total CPU"> + The ad exceeded the total CPU usage threshold for the Heavy Ad Intervention. + </int> + <int value="3" label="Peak CPU"> + The ad exceeded the peak CPU usage threshold for the Heavy Ad Intervention. + </int> +</enum> + <enum name="HeavyPageCappingInfoBarInteraction"> <int value="0" label="InfoBar shown"> The user was shown the capping heavy pages InfoBar. @@ -34899,6 +34919,7 @@ <int value="-1444051091" label="ash-disable-night-light"/> <int value="-1443796945" label="OfflinePagesSharing:disabled"/> <int value="-1442753429" label="SystemTrayFeaturePodsPagination:disabled"/> + <int value="-1441695001" label="OmniboxOnFocusSuggestions:enabled"/> <int value="-1441340278" label="NewTabPageIcons:enabled"/> <int value="-1440440375" label="WebVrAutopresent:enabled"/> <int value="-1440152291" label="disable-gesture-typing"/> @@ -35320,6 +35341,7 @@ <int value="-913294939" label="DriveFS:enabled"/> <int value="-912456561" label="MidiManagerWinrt:enabled"/> <int value="-910452816" label="ChromeOSParentalControlsSettings:disabled"/> + <int value="-909351661" label="OmniboxOnFocusSuggestions:disabled"/> <int value="-908421850" label="PointerEvent:enabled"/> <int value="-907234795" label="NewAudioRenderingMixingStrategy:disabled"/> <int value="-905538983" label="SimplifyHttpsIndicator:disabled"/> @@ -40940,6 +40962,16 @@ <int value="1" label="Hit"/> </enum> +<enum name="NativeFileSystemPermissionRequestOutcome"> + <int value="0" label="Blocked by Content Setting"/> + <int value="1" label="Blocked from invalid frame"/> + <int value="2" label="Blocked for lack of user activation"/> + <int value="3" label="Blocked from third-party context"/> + <int value="4" label="Granted"/> + <int value="5" label="Denied by user"/> + <int value="6" label="Dismissed by user"/> +</enum> + <enum name="NativeLibraryPreloaderResult"> <obsolete> Removed in July 2019. See https://crbug.com/975556. @@ -44824,86 +44856,6 @@ <int value="5" label="forced query"/> </enum> -<enum name="OmniboxPageContext"> - <int value="0" label="invalid spec; shouldn't happen"/> - <int value="1" - label="extension-replaced new tab page OR obsolete new tab page"/> - <int value="2" label="about:blank"/> - <int value="3" label="the user's home page"/> - <int value="4" label="other (typically an arbitrary URL)"/> - <int value="5" label="obsolete: instant new tab page"/> - <int value="6" label="search results page with search term replacement"/> - <int value="7" label="new tab page with omnibox as starting focus"/> - <int value="8" label="new tab page with fakebox as starting focus"/> - <int value="9" label="search results page without search term replacement"/> - <int value="10" label="home screen"/> - <int value="11" label="search app"/> - <int value="12" label="maps app"/> - <int value="13" label="interaction starting with the search button"/> -</enum> - -<enum name="OmniboxProviderAndResultType"> - <int value="101" label="URL_WHAT_YOU_TYPED via HistoryURL provider"/> - <int value="102" label="HISTORY_URL via HistoryURL provider"/> - <int value="302" label="HISTORY_URL via HistoryQuick provider"/> - <int value="303" label="HISTORY_TITLE via HistoryQuick provider"/> - <int value="406" label="NAVSUGGEST via SearchProvider"/> - <int value="407" label="SEARCH_WHAT_YOU_TYPED via SearchProvider"/> - <int value="408" label="SEARCH_HISTORY via SearchProvider"/> - <int value="409" label="SEARCH_SUGGEST via SearchProvider"/> - <int value="410" label="SEARCH_OTHER_ENGINE via SearchProvider"/> - <int value="414" label="SEARCH_SUGGEST_ENTITY via SearchProvider"/> - <int value="415" label="SEARCH_SUGGEST_TAIL via SearchProvider"/> - <int value="416" label="SEARCH_SUGGEST_PERSONALIZED via SearchProvider"/> - <int value="422" label="SEARCH_SUGGEST_ANSWER via SearchProvider"/> - <int value="423" label="CALCULATOR via SearchProvider"/> - <int value="505" label="HISTORY_KEYWORD via KeywordProvider"/> - <int value="510" label="SEARCH_OTHER_ENGINE via KeywordProvider"/> - <int value="606" label="NAVSUGGEST via BuiltinProvider"/> - <int value="700" label="UNKNOWN_RESULT_TYPE via Shortcuts provider"/> - <int value="701" label="URL_WHAT_YOU_TYPED via Shortcuts provider"/> - <int value="702" label="HISTORY_URL via Shortcuts provider"/> - <int value="703" label="HISTORY_TITLE via Shortcuts provider"/> - <int value="705" label="HISTORY_KEYWORD via Shortcuts provider"/> - <int value="708" label="SEARCH_HISTORY via Shortcuts provider"/> - <int value="710" label="SEARCH_OTHER_ENGINE via Shortcuts provider"/> - <int value="713" label="BOOKMARK_TITLE via Shortcuts provider"/> - <int value="716" label="SEARCH_SUGGEST_PERSONALIZED via Shortcuts provider"/> - <int value="717" label="SEARCH_SUGGEST_PROFILE via Shortcuts provider"/> - <int value="1013" label="BOOKMARK_TITLE via BookmarkProvider"/> - <int value="1106" label="NAVSUGGEST via ZeroSuggest"/> - <int value="1109" label="SEARCH_SUGGEST via ZeroSuggest"/> - <int value="1116" label="SEARCH_SUGGEST_PERSONALIZED via ZeroSuggest"/> - <int value="1202" label="HISTORY_URL from on-device service"/> - <int value="1212" label="CONTACT from on-device service"/> - <int value="1218" label="APP_RESULT from on-device service"/> - <int value="1219" label="APP from on-device service"/> - <int value="1220" label="LEGACY_ON_DEVICE from on-device service"/> - <int value="1424" label="CLIPBOARD_URL from Clipboard provider"/> - <int value="1428" label="CLIPBOARD_TEXT from Clipboard provider"/> - <int value="1429" label="CLIPBOARD_IMAGE from Clipboard provider"/> - <int value="1627" label="DOCUMENT via DocumentProvider"/> -</enum> - -<enum name="OmniboxProviderType"> - <int value="1" label="HistoryURL"/> - <int value="2" label="deprecated: HistoryContents"/> - <int value="3" label="HistoryQuick"/> - <int value="4" label="SearchProvider"/> - <int value="5" label="KeywordProvider"/> - <int value="6" label="BuiltinProvider"/> - <int value="7" label="ShortcutsProvider"/> - <int value="8" label="deprecated: ExtensionAppProvider"/> - <int value="9" label="deprecated: ContactsProvider"/> - <int value="10" label="BookmarkProvider"/> - <int value="11" label="ZeroSuggest"/> - <int value="12" label="on device (only used by Android GSA)"/> - <int value="13" label="on device chrome (chrome content provider)"/> - <int value="14" label="clipboard provider"/> - <int value="15" label="deprecated: Physical Web"/> - <int value="16" label="DocumentProvider"/> -</enum> - <enum name="OmniboxSearchEngine"> <int value="0" label="Unknown"/> <int value="1" label="Google"/> @@ -45047,15 +44999,6 @@ <int value="3" label="(non-invalidated) replies received"/> </enum> -<enum name="OmniboxSummarizedResultType"> - <int value="0" label="URL"/> - <int value="1" label="search"/> - <int value="2" label="app/extension"/> - <int value="3" label="contact"/> - <int value="4" label="on-device"/> - <int value="5" label="unknown"/> -</enum> - <enum name="OmniboxUserTextCleared"> <int value="0" label="cleared by editing"/> <int value="1" label="cleared with escape"/> @@ -46026,6 +45969,22 @@ <int value="9" label="Unknown range support from the response header."/> </enum> +<enum name="ParentAccessCodeAction"> + <summary>Action resulting from parent access code dialog</summary> + <int value="0" label="Validation success"/> + <int value="1" label="Validation error"/> + <int value="2" label="Validation canceled by user"/> + <int value="3" label="Get help user action"/> +</enum> + +<enum name="ParentAccessCodeUsage"> + <summary>Context in which parent access code was used</summary> + <int value="0" label="Time limits"/> + <int value="1" label="Time change on login screen"/> + <int value="2" label="Time change user session"/> + <int value="3" label="Timezone change"/> +</enum> + <enum name="ParentFrameKnown"> <int value="0" label="Parent Frame Not Known"/> <int value="1" label="Parent Frame Known"/> @@ -53719,6 +53678,12 @@ <int value="8" label="Payload is too large"/> </enum> +<enum name="SensitiveDirectoryAccessResult"> + <int value="0" label="Allowed"/> + <int value="1" label="Blocked, try again"/> + <int value="2" label="Blocked"/> +</enum> + <enum name="ServiceProcessEventType"> <int value="0" label="SERVICE_EVENT_INITIALIZE"/> <int value="1" label="SERVICE_EVENT_ENABLED_ON_LAUNCH"/> @@ -60142,9 +60107,9 @@ <enum name="UpdateEngineDownloadErrorCode"> <int value="0" label="Download Error"/> - <int value="97" label="libcurl recovered from unresolved host error"/> - <int value="98" label="libcurl unresolved host error"/> - <int value="99" label="libcurl HTTP request internal error"/> + <int value="97" label="libcurl Recovered From Unresolved Host Error"/> + <int value="98" label="libcurl Unresolved Host Error"/> + <int value="99" label="libcurl HTTP Request Internal Error"/> <int value="100" label="Input Malformed (Internal Error)"/> <int value="101" label="Unknown HTTP Status (not 200-599)"/> <int value="400" label="Bad Request (HTTP Status 400)"/> @@ -60239,6 +60204,10 @@ <int value="53" label="kErrorCodeNoUpdate"/> <int value="54" label="kErrorCodeRollbackNotPossible"/> <int value="55" label="kErrorCodeFirstActiveOmahaPingSentPersistenceError"/> + <int value="56" label="kErrorCodeVerityCalculationError"/> + <int value="57" label="kErrorCodeInternalLibCurlError"/> + <int value="58" label="kErrorCodeUnresolvedHostError"/> + <int value="59" label="kErrorCodeUnresolvedHostRecovered"/> </enum> <enum name="UpdateEngineInstallDateProvisioningSource">
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 6187af0..cded103f 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -26333,7 +26333,10 @@ </histogram> <histogram name="CustomTabs.SpareWebContents.Status" - enum="SpareWebContentsStatus"> + enum="SpareWebContentsStatus" expires_after="2019-03-28"> + <obsolete> + Replaced by CustomTabs.SpareWebContents.Status2 as of 03/2019. + </obsolete> <owner>lizeb@chromium.org</owner> <summary> Android: When a spare WebContents is created from Custom Tabs, record @@ -26343,6 +26346,18 @@ </summary> </histogram> +<histogram name="CustomTabs.SpareWebContents.Status2" + enum="SpareWebContentsStatus2"> + <owner>lizeb@chromium.org</owner> + <owner>mthiesse@chromium.org</owner> + <summary> + Android: When a spare WebContents is created from Custom Tabs, record + creation, and whether it was used by CCT, stolen by another Chrome Activity, + killed or destroyed. Creation is recorded to get the "abandoned" + case, that is when Chrome is killed before the renderer. + </summary> +</histogram> + <histogram name="CustomTabs.SpareWebContents.TimeBeforeDeath" units="ms"> <owner>lizeb@chromium.org</owner> <summary> @@ -69193,6 +69208,45 @@ </summary> </histogram> +<histogram name="NativeFileSystemAPI.ConfirmReadDirectoryResult" + enum="PermissionAction" expires_after="M82"> + <owner>mek@chromium.org</owner> + <owner>src/content/browser/native_file_system/OWNERS</owner> + <summary> + Did the user confirm read access to a directory via the Native File System + API. + </summary> +</histogram> + +<histogram name="NativeFileSystemAPI.FileChooserResult" expires_after="M82"> + <owner>mek@chromium.org</owner> + <owner>src/content/browser/native_file_system/OWNERS</owner> + <summary> + The number of files a user picked using the file picker in the Native File + System API. Recorded as 0 if the user cancelled the picker. + </summary> +</histogram> + +<histogram name="NativeFileSystemAPI.SensitiveDirectoryAccessResult" + enum="SensitiveDirectoryAccessResult" expires_after="M82"> + <owner>mek@chromium.org</owner> + <owner>src/content/browser/native_file_system/OWNERS</owner> + <summary> + Records if the file or directory selected by the user through the Native + File System API is considered a sensitive directory, and thus was blocked. + </summary> +</histogram> + +<histogram name="NativeFileSystemAPI.WritePermissionRequestOutcome" + enum="NativeFileSystemPermissionRequestOutcome" expires_after="M82"> + <owner>mek@chromium.org</owner> + <owner>src/content/browser/native_file_system/OWNERS</owner> + <summary> + The result of an attempt to request write permission to a file or directory + via the Native File System API. + </summary> +</histogram> + <histogram name="NativeSmbFileShare.AuthenticationMethod" enum="NativeSmbFileShare_AuthMethod"> <owner>zentaro@chromium.org</owner> @@ -91116,20 +91170,6 @@ </summary> </histogram> -<histogram name="Omnibox.PageContext" enum="OmniboxPageContext"> - <owner>mpearson@chromium.org</owner> - <owner>jdonnelly@chromium.org</owner> - <summary> - The type of page the user was viewing when the user used the omnibox to go - somewhere. - - In M-74 and earlier, this was only recorded if the user had no incognito - windows open. In M-75 and later, it records all omnibox interactions - regardless, in order to be consistent with how user actions and histograms - are handled. - </summary> -</histogram> - <histogram name="Omnibox.PaintTime" units="ms"> <owner>asvitkine@chromium.org</owner> <owner>mpearson@chromium.org</owner> @@ -91452,25 +91492,6 @@ </summary> </histogram> -<histogram name="Omnibox.SuggestionDeleted.ProviderAndResultType" - enum="OmniboxProviderAndResultType" expires_after="2020-09-01"> - <owner>mpearson@chromium.org</owner> - <owner>jdonnelly@chromium.org</owner> - <owner>ender@chromium.org</owner> - <summary> - The provider and result type of the suggestion the user deleted. In case of - duplicate suggestions, only the displayed one (the one chosen as canonical - representative) is considered. As such, some deletion requests will not be - recorded here. This is because if something in the set of duplicates was - deletable then Chrome was willing to allow a delete action to happen on the - set. However, if the canonical item is not deletable, the histogram will not - be emitted. - - This histogram records all user suggestion delete interactions, both local - and remote. - </summary> -</histogram> - <histogram name="Omnibox.SuggestionUsed.AnswerInSuggest" enum="SuggestionAnswerOptionalType" expires_after="M83"> <owner>chrome-android-omnibox-team@google.com</owner> @@ -91578,68 +91599,6 @@ </summary> </histogram> -<histogram name="Omnibox.SuggestionUsed.Provider" enum="OmniboxProviderType"> - <owner>mpearson@chromium.org</owner> - <owner>jdonnelly@chromium.org</owner> - <summary> - The provider of the suggestion the user selected when the user used the - omnibox to go somewhere. - - In M-74 and earlier, this was only recorded if the user had no incognito - windows open. In M-75 and later, it records all omnibox interactions - regardless, in order to be consistent with how user actions and histograms - are handled. - </summary> -</histogram> - -<histogram base="true" name="Omnibox.SuggestionUsed.Provider.ByPageContext" - enum="OmniboxProviderType"> - <owner>mpearson@chromium.org</owner> - <owner>jdonnelly@chromium.org</owner> - <summary> - The provider of the suggestion the user selected when the user used the - omnibox to go somewhere, only for omnibox interactions that start in the - specified page context: - - In M-74 and earlier, this was only recorded if the user had no incognito - windows open. In M-75 and later, it records all omnibox interactions - regardless, in order to be consistent with how user actions and histograms - are handled. - </summary> -</histogram> - -<histogram name="Omnibox.SuggestionUsed.ProviderAndResultType" - enum="OmniboxProviderAndResultType"> - <owner>mpearson@chromium.org</owner> - <owner>jdonnelly@chromium.org</owner> - <summary> - The provider and result type of the suggestion the user selected when the - user used the omnibox to go somewhere. - - In M-74 and earlier, this was only recorded if the user had no incognito - windows open. In M-75 and later, it records all omnibox interactions - regardless, in order to be consistent with how user actions and histograms - are handled. - </summary> -</histogram> - -<histogram base="true" - name="Omnibox.SuggestionUsed.ProviderAndResultType.ByPageContext" - enum="OmniboxProviderAndResultType"> - <owner>mpearson@chromium.org</owner> - <owner>jdonnelly@chromium.org</owner> - <summary> - The provider and result type of the suggestion the user selected when the - user used the omnibox to go somewhere, only for omnibox interactions that - start in the specified page context: - - In M-74 and earlier, this was only recorded if the user had no incognito - windows open. In M-75 and later, it records all omnibox interactions - regardless, in order to be consistent with how user actions and histograms - are handled. - </summary> -</histogram> - <histogram name="Omnibox.SuggestionUsed.RichEntity" enum="BooleanUsage" expires_after="M84"> <owner>chrome-android-omnibox-team@google.com</owner> @@ -91712,43 +91671,6 @@ </summary> </histogram> -<histogram name="Omnibox.SuggestionUsed.SearchVsUrl" - enum="OmniboxSummarizedResultType" expires_after="never"> -<!-- expires-never: guiding metric (internal: go/chrome-browser-guiding-metrics) --> - - <owner>mpearson@chromium.org</owner> - <owner>jdonnelly@chromium.org</owner> - <owner>chrome-analysis-team@google.com</owner> - <summary> - The rough type of the suggestion the user selected when the user used the - omnibox to go somewhere. - - In M-74 and earlier, this was only recorded if the user had no incognito - windows open. In M-75 and later, it records all omnibox interactions - regardless, in order to be consistent with how user actions and histograms - are handled. - - This histogram is of special interest to the chrome-analysis-team@. Do not - change its semantics or retire it without talking to them first. - </summary> -</histogram> - -<histogram base="true" name="Omnibox.SuggestionUsed.SearchVsUrl.ByPageContext" - enum="OmniboxSummarizedResultType"> - <owner>mpearson@chromium.org</owner> - <owner>jdonnelly@chromium.org</owner> - <summary> - The rough type of the suggestion the user selected when the user used the - omnibox to go somewhere, only for omnibox interactions that start in the - specified page context: - - In M-74 and earlier, this was only recorded if the user had no incognito - windows open. In M-75 and later, it records all omnibox interactions - regardless, in order to be consistent with how user actions and histograms - are handled. - </summary> -</histogram> - <histogram name="Omnibox.SuggestionUsed.SelectedTabMatch" enum="BooleanSelected"> <owner>krb@chromium.org</owner> @@ -91877,40 +91799,6 @@ </summary> </histogram> -<histogram name="Omnibox.TypedLength" units="characters"> - <owner>mpearson@chromium.org</owner> - <owner>jdonnelly@chromium.org</owner> - <summary> - The length of the text the user entered in the omnibox when they used the - omnibox to go somewhere. Switched on March 27 2018 from an bucketing where - every typed length is emitted exactly (up to 500) to ordinary exponential - bucketing. - - In M-74 and earlier, this was only recorded if the user had no incognito - windows open. In M-75 and later, it records all omnibox interactions - regardless, in order to be consistent with how user actions and histograms - are handled. - </summary> -</histogram> - -<histogram name="Omnibox.TypingDuration" units="ms"> - <owner>mpearson@chromium.org</owner> - <owner>jdonnelly@chromium.org</owner> - <summary> - The amount of time, in milliseconds, since the user first began modifying - the text in the omnibox until the user used the omnibox to go somewhere. If - at some point after modifying the text, the user reverted the modifications - (thus seeing the current web page's URL again), then wrote in the omnibox - again, this duration starts from the time of the second series of - modification. - - In M-74 and earlier, this was only recorded if the user had no incognito - windows open. In M-75 and later, it records all omnibox interactions - regardless, in order to be consistent with how user actions and histograms - are handled. - </summary> -</histogram> - <histogram name="Omnibox.URLNavigationScheme" enum="NavigationScheme"> <owner>mpearson@chromium.org</owner> <owner>jdonnelly@chromium.org</owner> @@ -95646,19 +95534,41 @@ <histogram base="true" name="PageLoad.HeavyAds.ComputedType" enum="HeavyAdStatus" expires_after="2020-08-05"> + <obsolete> + Deprecated 09/2018 in favor of PageLoad.HeavyAds.ComputedType2. + </obsolete> <owner>johnidel@chromium.org</owner> <owner>jkarlin@chromium.org</owner> <summary> - Records heavy ad type for each ad frame, as determine by the ifrst threshold - hit (see FrameData::HeavyadStatus). This is recorded regardless of feature - flag or other conditions that prevent the heavy ad intervention from + Records heavy ad type for each ad frame, as determined by the first + threshold hit (see FrameData::HeavyadStatus). This is recorded regardless of + feature flag or other conditions that prevent the heavy ad intervention from occuring. Recored for all ad frames with non-zero bytes. Recorded when the ad frame destroyed or when the page is destroyed. </summary> </histogram> +<histogram base="true" name="PageLoad.HeavyAds.ComputedType2" + enum="HeavyAdStatus2" expires_after="2020-08-05"> + <owner>johnidel@chromium.org</owner> + <owner>jkarlin@chromium.org</owner> + <summary> + Records heavy ad type for each ad frame, as determined by the first + threshold hit (see FrameData::HeavyadStatus). This is recorded regardless of + feature flag or other conditions that prevent the heavy ad intervention from + occuring. Recored for all ad frames with non-zero bytes. Recorded when the + ad frame destroyed or when the page is destroyed. + + It is possible for multiple thresholds to be hit at the same time, with the + higher valued enums winning those race conditions. + </summary> +</histogram> + <histogram base="true" name="PageLoad.HeavyAds.InterventionType" enum="HeavyAdStatus" expires_after="2020-08-05"> + <obsolete> + Deprecated 09/2018 in favor of PageLoad.HeavyAds.InterventionType2. + </obsolete> <owner>johnidel@chromium.org</owner> <owner>jkarlin@chromium.org</owner> <summary> @@ -95670,6 +95580,22 @@ </summary> </histogram> +<histogram base="true" name="PageLoad.HeavyAds.InterventionType2" + enum="HeavyAdStatus2" expires_after="2020-08-05"> + <owner>johnidel@chromium.org</owner> + <owner>jkarlin@chromium.org</owner> + <summary> + Records the type of heavy ad unloaded by the heavy ad intervention. Heavy ad + type is determined by the first threshold hit. This is not recorded for ad + frames that are considered heavy but did not fufill other criteria for the + intervention. This includes the feature being enabled and being below the + per-origin intervention cap. + + It is possible for multiple thresholds to be hit at the same time, with the + higher valued enums winning those race conditions. + </summary> +</histogram> + <histogram name="PageLoad.InputTiming.NavigationToFirstNonScroll.AfterPaint" units="ms" expires_after="M77"> <owner>tdresser@chromium.org</owner> @@ -108792,6 +108718,10 @@ <histogram name="Previews.ServerLitePage.ServerNetError" enum="NetErrorCodes" expires_after="M85"> + <obsolete> + Deprecated in favor of + Previews.ServerLitePage.ServerNetError.(After|Before)Commit + </obsolete> <owner>robertogden@chromium.org</owner> <owner>ryansturm@chromium.org</owner> <summary> @@ -108800,6 +108730,26 @@ </summary> </histogram> +<histogram name="Previews.ServerLitePage.ServerNetError.AfterCommit" + enum="NetErrorCodes" expires_after="M85"> + <owner>robertogden@chromium.org</owner> + <owner>ryansturm@chromium.org</owner> + <summary> + The net error from connecting to the previews server after commit. Recorded + every time a connection to the server is finished after commit. + </summary> +</histogram> + +<histogram name="Previews.ServerLitePage.ServerNetError.BeforeCommit" + enum="NetErrorCodes" expires_after="M85"> + <owner>robertogden@chromium.org</owner> + <owner>ryansturm@chromium.org</owner> + <summary> + The net error from connecting to the previews server before commit. Recorded + every time a connection to the server is finished before commit. + </summary> +</histogram> + <histogram name="Previews.ServerLitePage.ServerResponse" enum="PreviewsServerLitePageServerResponse" expires_after="2020-01-20"> <owner>robertogden@chromium.org</owner> @@ -137375,6 +137325,26 @@ </summary> </histogram> +<histogram name="Supervision.ParentAccessCode.Action" + enum="ParentAccessCodeAction" expires_after="M88"> + <owner>agawronska@chromium.org</owner> + <owner>cros-families@google.com</owner> + <summary> + Action originated in parent access code dialog. Logged every time the action + happens. + </summary> +</histogram> + +<histogram name="Supervision.ParentAccessCode.Usage" + enum="ParentAccessCodeUsage" expires_after="M88"> + <owner>agawronska@chromium.org</owner> + <owner>cros-families@google.com</owner> + <summary> + The context in which parent access code was used. Logged every time the new + parent access dialog is shown. + </summary> +</histogram> + <histogram name="Supervision.StatusReport.Event" enum="SupervisionStatusReportEvent" expires_after="M85"> <owner>escordeiro@google.com</owner> @@ -159124,7 +159094,9 @@ name="PageLoad.FrameCounts.AdFrames.PerFrame.UserActivation"/> <affected-histogram name="PageLoad.FrameCounts.AnyParentFrame.AdFrames"/> <affected-histogram name="PageLoad.HeavyAds.ComputedType"/> + <affected-histogram name="PageLoad.HeavyAds.ComputedType2"/> <affected-histogram name="PageLoad.HeavyAds.InterventionType"/> + <affected-histogram name="PageLoad.HeavyAds.InterventionType2"/> </histogram_suffixes> <histogram_suffixes name="AffiliationDummyData" separator="."> @@ -165628,6 +165600,20 @@ name="Net.ResourceDispatcherHost.PeakOutstandingRequests"/> </histogram_suffixes> +<histogram_suffixes name="NativeFileSystemAPIChooserType" separator="."> + <suffix name="OpenDirectory"/> + <suffix name="OpenFile"/> + <suffix name="OpenMultipleFiles"/> + <suffix name="SaveFile"/> + <affected-histogram name="NativeFileSystemAPI.FileChooserResult"/> +</histogram_suffixes> + +<histogram_suffixes name="NativeFileSystemAPIHandleType" separator="."> + <suffix name="Directory"/> + <suffix name="File"/> + <affected-histogram name="NativeFileSystemAPI.WritePermissionRequestOutcome"/> +</histogram_suffixes> + <histogram_suffixes name="NativeWindowVisibility" separator="."> <suffix name="Hidden" label="The native window is not visible because it is in a minimized @@ -168001,35 +167987,6 @@ <affected-histogram name="Omnibox.TimeUntilFirst"/> </histogram_suffixes> -<histogram_suffixes name="OmniboxPageContext" separator="."> - <suffix name="APP_HOME" label="home screen"/> - <suffix name="APP_MAPS" label="maps app"/> - <suffix name="APP_SEARCH" label="search app"/> - <suffix name="BLANK" label="about:blank"/> - <suffix name="HOME_PAGE" label="the user's home page"/> - <suffix name="INSTANT_NTP_WITH_FAKEBOX_AS_STARTING_FOCUS" - label="new tab page with fakebox as starting focus"/> - <suffix name="INSTANT_NTP_WITH_OMNIBOX_AS_STARTING_FOCUS" - label="new tab page with omnibox as starting focus"/> - <suffix name="INVALID_SPEC" label="invalid spec; shouldn't happen"/> - <suffix name="NTP" - label="extension-replaced new tab page OR obsolete new tab page"/> - <suffix name="OBSOLETE_INSTANT_NTP" label="obsolete: instant new tab page"/> - <suffix name="OBSOLETE_SEARCH_RESULT_PAGE_DOING_SEARCH_TERM_REPLACEMENT" - label="obsolete: search results page with search term replacement"/> - <suffix name="OTHER" - label="other (typically an arbitrary URL, not a search results page, - new tab page, etc.)"/> - <suffix name="SEARCH_BUTTON_AS_STARTING_FOCUS" - label="interaction starting with the search button"/> - <suffix name="SEARCH_RESULT_PAGE_NO_SEARCH_TERM_REPLACEMENT" - label="search results page without search term replacement"/> - <affected-histogram name="Omnibox.SuggestionUsed.Provider.ByPageContext"/> - <affected-histogram - name="Omnibox.SuggestionUsed.ProviderAndResultType.ByPageContext"/> - <affected-histogram name="Omnibox.SuggestionUsed.SearchVsUrl.ByPageContext"/> -</histogram_suffixes> - <histogram_suffixes name="OmniboxProviderTime" separator="."> <suffix name="Bookmark"/> <suffix name="Builtin"/>
diff --git a/ui/views/controls/tree/tree_view.cc b/ui/views/controls/tree/tree_view.cc index 3e6841c0..b15886ae 100644 --- a/ui/views/controls/tree/tree_view.cc +++ b/ui/views/controls/tree/tree_view.cc
@@ -482,9 +482,12 @@ // deleted value. selected_node_ = nullptr; const auto& children = model_->GetChildren(parent); - TreeModelNode* to_select = - children.empty() ? parent - : children[std::min(start, children.size() - 1)]; + TreeModelNode* to_select = nullptr; + if (!children.empty()) { + to_select = children[std::min(start, children.size() - 1)]; + } else if (parent != root_.model_node() || root_shown_) { + to_select = parent; + } SetSelectedNode(to_select); } if (IsExpanded(parent))
diff --git a/ui/views/controls/tree/tree_view_unittest.cc b/ui/views/controls/tree/tree_view_unittest.cc index ceb1e16d..68fe06220 100644 --- a/ui/views/controls/tree/tree_view_unittest.cc +++ b/ui/views/controls/tree/tree_view_unittest.cc
@@ -13,6 +13,7 @@ #include "ui/base/models/tree_node_model.h" #include "ui/views/controls/prefix_selector.h" #include "ui/views/controls/textfield/textfield.h" +#include "ui/views/controls/tree/tree_view_controller.h" #include "ui/views/test/views_test_base.h" using ui::TreeModel; @@ -310,6 +311,41 @@ EXPECT_EQ(2, GetRowCount()); } +class TestController : public TreeViewController { + public: + void OnTreeViewSelectionChanged(TreeView* tree_view) override { + call_count_++; + } + + bool CanEdit(TreeView* tree_view, ui::TreeModelNode* node) override { + return true; + } + + int selection_change_count() const { return call_count_; } + + private: + int call_count_ = 0; +}; + +TEST_F(TreeViewTest, RemovingLastNodeNotifiesSelectionChanged) { + TestController controller; + tree_.SetController(&controller); + tree_.SetRootShown(false); + tree_.SetModel(&model_); + + // Remove all but one node. + model_.Remove(GetNodeByTitle("b")->parent(), GetNodeByTitle("b")); + model_.Remove(GetNodeByTitle("c")->parent(), GetNodeByTitle("c")); + tree_.SetSelectedNode(GetNodeByTitle("a")); + EXPECT_EQ("root [a]", TreeViewContentsAsString()); + + const int prior_call_count = controller.selection_change_count(); + // Remove the final node and expect + // |TestController::OnTreeViewSelectionChanged| to be called. + model_.Remove(GetNodeByTitle("a")->parent(), GetNodeByTitle("a")); + EXPECT_EQ(prior_call_count + 1, controller.selection_change_count()); +} + // Verifies changing a node title works. TEST_F(TreeViewTest, TreeNodeChanged) { // Add c1 as a child of c and c11 as a child of c1.
diff --git a/ui/webui/resources/js/cr.js b/ui/webui/resources/js/cr.js index 101e3c8..9696ef8 100644 --- a/ui/webui/resources/js/cr.js +++ b/ui/webui/resources/js/cr.js
@@ -464,7 +464,13 @@ /** Whether this is on iOS. */ get isIOS() { - return /iPad|iPhone|iPod/.test(navigator.platform); + // iPads are returning "MacIntel" for iOS 13 (devices & simulators). + // Chrome on macOS also returns "MacIntel" for navigator.platform, + // but navigator.userAgent includes /Safari/. + // TODO(crbug.com/998999): Fix navigator.userAgent such that it reliably + // returns an agent string containing "CriOS". + return /iPad|iPhone|iPod|MacIntel/.test(navigator.platform) && + !(/Safari/.test(navigator.userAgent)); } }; }(this);
diff --git a/ui/webui/resources/js/cr.m.js b/ui/webui/resources/js/cr.m.js index f24f239a..172604dd 100644 --- a/ui/webui/resources/js/cr.m.js +++ b/ui/webui/resources/js/cr.m.js
@@ -190,4 +190,10 @@ export const isAndroid = /Android/.test(navigator.userAgent); /** Whether this is on iOS. */ -export const isIOS = /iPad|iPhone|iPod/.test(navigator.platform); +// iPads are returning "MacIntel" for iOS 13 (devices & simulators). +// Chrome on macOS also returns "MacIntel" for navigator.platform, +// but navigator.userAgent includes /Safari/. +// TODO(crbug.com/998999): Fix navigator.userAgent such that it reliably +// returns an agent string containing "CriOS". +export const isIOS = /iPad|iPhone|iPod|MacIntel/.test(navigator.platform) && + !(/Safari/.test(navigator.userAgent));