diff --git a/BUILD.gn b/BUILD.gn index 95f4b6514..b1f4f32 100644 --- a/BUILD.gn +++ b/BUILD.gn
@@ -10,6 +10,7 @@ import("//build/config/chromeos/ui_mode.gni") import("//build/config/compiler/compiler.gni") +import("//build/config/dcheck_always_on.gni") import("//build/config/features.gni") import("//build/config/sanitizers/sanitizers.gni") import("//build/config/ui.gni") @@ -1113,9 +1114,6 @@ "//third_party/blink/web_tests/wpt_internal/", "//third_party/pywebsocket3/src/mod_pywebsocket/", "//third_party/test_fonts/test_fonts/", - - # Needed by run_web_tests.py to detect DCHECK build. - "$root_out_dir/args.gn", ] if (is_win) { @@ -1147,6 +1145,9 @@ _common_web_test_args += [ "--debug" ] } else { _common_web_test_args += [ "--release" ] + if (dcheck_always_on) { + _common_web_test_args += [ "--time-out-ms=12000" ] + } } if (is_android) {
diff --git a/DEPS b/DEPS index becc2c44..c310e5c 100644 --- a/DEPS +++ b/DEPS
@@ -195,11 +195,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': '658ae8fc6aba3e987cf3b4cf711ba308435a3f64', + 'skia_revision': '61003cde76882c43ab593a5fd889fc90b7d10abf', # 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': 'e4ed803f4c09ff72bb1eaadf59ec31facf507368', + 'v8_revision': '07b0b1dcde4a99294b8028d83f4ea244885cc091', # 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. @@ -211,7 +211,7 @@ # 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': '51b03d58fb17b09120c886d5df36fb191d12fa8e', + 'swiftshader_revision': '0aca3ca9427d1d2aa8d8e706de62360c61af3598', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. @@ -896,7 +896,7 @@ # For Linux and Chromium OS. 'src/third_party/cros_system_api': { - 'url': Var('chromium_git') + '/chromiumos/platform2/system_api.git' + '@' + 'fe6fea125882232dd19446232a53c9bd3fa1f4f0', + 'url': Var('chromium_git') + '/chromiumos/platform2/system_api.git' + '@' + '16aafbd27d09c779e67f11291d8cb34b7bc7abb4', 'condition': 'checkout_linux', }, @@ -1237,7 +1237,7 @@ Var('chromium_git') + '/external/github.com/cisco/openh264' + '@' + '3dd5b80bc4f172dd82925bb259cb7c82348409c5', 'src/third_party/openscreen/src': - Var('chromium_git') + '/openscreen' + '@' + '71f3a45238af2576f4872396ce5f0de9cb5bf6ed', + Var('chromium_git') + '/openscreen' + '@' + 'a3f46f23c52688cc3c0de927b7fb8a86ff9e8dff', 'src/third_party/openxr/src': { 'url': Var('chromium_git') + '/external/github.com/KhronosGroup/OpenXR-SDK' + '@' + '9e97b73e7dd2bfc07745489d728f6a36665c648f', @@ -1254,7 +1254,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + '815983783a765fa04e31bb514020fd1c55291a71', + Var('android_git') + '/platform/external/perfetto.git' + '@' + '109c355900d140e616c7ddc66c57e626678133ca', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1332,7 +1332,7 @@ 'packages': [ { 'package': 'fuchsia/third_party/aemu/linux-amd64', - 'version': 'sc_IY63udetl6YG0-ExCPBOGDcD1JagmZiWBkq2mBl0C' + 'version': '1wcgrsmCBOkqmqgVO1zI-z2_mk9oLiVRGlx-INget24C' }, ], 'condition': 'host_os == "linux" and checkout_fuchsia', @@ -1486,7 +1486,7 @@ }, 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + 'eacbd972ab7e85e9d61851ced57aba1eb194de3d', + Var('webrtc_git') + '/src.git' + '@' + '294729f33cbfac484a4b77c29dd42f03ffe65fa2', 'src/third_party/libgifcodec': Var('skia_git') + '/libgifcodec' + '@'+ Var('libgifcodec_revision'), @@ -1524,7 +1524,7 @@ 'packages': [ { 'package': 'skia/tools/goldctl/linux-amd64', - 'version': 'ehm_yIO4CdwsvaJZJPQ2xBXAFv3KXEgrDpTY3AaK7EYC', + 'version': 'sEWxSos77EKQLWziVoCV6Sa52qijVB0fz9uN1EGoUd0C', }, ], 'dep_type': 'cipd', @@ -1534,7 +1534,7 @@ 'packages': [ { 'package': 'skia/tools/goldctl/windows-amd64', - 'version': 'ixP2POw1dVLvzG-YPiGAJdFrTLwpr--nwyQr_S5FoRkC', + 'version': '6eX8c167sU_avc61blSZpNkSEa5HwWNYfWCk-88QTNsC', }, ], 'dep_type': 'cipd', @@ -1544,7 +1544,7 @@ 'packages': [ { 'package': 'skia/tools/goldctl/mac-amd64', - 'version': 'wIHfWG-DQOw0ISbpkWZrm2f2GoKa3H1Z4I2w8MxhlVIC', + 'version': 'rp50J-ChpY5Dyvjwl71mK28FOzgevSspS8YE1qxgkrAC', }, ], 'dep_type': 'cipd', @@ -1558,7 +1558,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@99db0de96759bae0298c1f5e81498e48b7f219f5', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@6dc612511e7b53778e59f30b96f71f1af0ab7ca4', 'condition': 'checkout_src_internal', },
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index 971e0260..9e0586b3 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -298,6 +298,8 @@ "clipboard/clipboard_history_resource_manager.h", "clipboard/clipboard_history_util.cc", "clipboard/clipboard_history_util.h", + "clipboard/clipboard_nudge.cc", + "clipboard/clipboard_nudge.h", "clipboard/clipboard_nudge_constants.h", "clipboard/clipboard_nudge_controller.cc", "clipboard/clipboard_nudge_controller.h",
diff --git a/ash/accelerators/accelerator_commands.cc b/ash/accelerators/accelerator_commands.cc index 01c305e..12c3e9e2 100644 --- a/ash/accelerators/accelerator_commands.cc +++ b/ash/accelerators/accelerator_commands.cc
@@ -23,6 +23,8 @@ namespace ash { namespace accelerators { +using ::chromeos::WindowStateType; + bool ZoomDisplay(bool up) { if (up) base::RecordAction(base::UserMetricsAction("Accel_Scale_Ui_Up"));
diff --git a/ash/accelerators/accelerator_controller_unittest.cc b/ash/accelerators/accelerator_controller_unittest.cc index 618d4b2..a8bda3a 100644 --- a/ash/accelerators/accelerator_controller_unittest.cc +++ b/ash/accelerators/accelerator_controller_unittest.cc
@@ -85,6 +85,7 @@ namespace ash { +using ::chromeos::WindowStateType; using media_session::mojom::MediaSessionAction; namespace {
diff --git a/ash/ambient/ambient_controller.cc b/ash/ambient/ambient_controller.cc index 5263dc8..7e95dfa 100644 --- a/ash/ambient/ambient_controller.cc +++ b/ash/ambient/ambient_controller.cc
@@ -429,6 +429,11 @@ void AmbientController::ShowHiddenUi() { DVLOG(1) << __func__; + if (!IsAmbientModeEnabled()) { + LOG(WARNING) << "Ambient mode is not allowed."; + return; + } + ambient_ui_model_.SetUiVisibility(AmbientUiVisibility::kHidden); } @@ -510,10 +515,17 @@ } void AmbientController::DismissUI() { - if (LockScreen::HasInstance()) - ShowHiddenUi(); - else + if (!IsAmbientModeEnabled()) { CloseUi(); + return; + } + + if (LockScreen::HasInstance()) { + ShowHiddenUi(); + return; + } + + CloseUi(); } AmbientBackendModel* AmbientController::GetAmbientBackendModel() {
diff --git a/ash/app_list/app_list_color_provider_impl.cc b/ash/app_list/app_list_color_provider_impl.cc index 7969e6b..0e6df00 100644 --- a/ash/app_list/app_list_color_provider_impl.cc +++ b/ash/app_list/app_list_color_provider_impl.cc
@@ -15,8 +15,7 @@ AppListColorProviderImpl::~AppListColorProviderImpl() = default; SkColor AppListColorProviderImpl::GetExpandArrowInkDropBaseColor() const { - return DeprecatedGetShelfInkDropBaseColor( - SkColorSetARGB(0x14, 0xFF, 0xFF, 0xFF)); + return DeprecatedGetInkDropBaseColor(SkColorSetARGB(0x14, 0xFF, 0xFF, 0xFF)); } SkColor AppListColorProviderImpl::GetExpandArrowIconBaseColor() const { @@ -81,23 +80,28 @@ AshColorProvider::ContentLayerType::kTextColorPrimary, SK_ColorBLACK); } -SkColor AppListColorProviderImpl::GetPageSwitcherButtonColor() const { - return ash_color_provider_->GetContentLayerColor( - AshColorProvider::ContentLayerType::kButtonIconColor); +SkColor AppListColorProviderImpl::GetPageSwitcherButtonColor( + bool is_root_app_grid_page_switcher) const { + return DeprecatedGetContentLayerColor( + AshColorProvider::ContentLayerType::kButtonIconColor, + is_root_app_grid_page_switcher ? SkColorSetARGB(255, 232, 234, 237) + : SkColorSetARGB(255, 232, 234, 237)); } -SkColor AppListColorProviderImpl::GetPageSwitcherInkDropBaseColor() const { - AshColorProvider::RippleAttributes ripple_attributes = - ash_color_provider_->GetRippleAttributes(GetAppListBackgroundColor()); - return SkColorSetA(ripple_attributes.base_color, - ripple_attributes.inkdrop_opacity * 255); +SkColor AppListColorProviderImpl::GetPageSwitcherInkDropBaseColor( + bool is_root_app_grid_page_switcher) const { + return DeprecatedGetInkDropRippleColor( + is_root_app_grid_page_switcher + ? SkColorSetA(SkColorSetRGB(241, 243, 244), 15) + : SkColorSetA(SkColorSetRGB(241, 243, 244), 8)); } -SkColor AppListColorProviderImpl::GetPageSwitcherInkDropHighlightColor() const { - AshColorProvider::RippleAttributes ripple_attributes = - ash_color_provider_->GetRippleAttributes(GetAppListBackgroundColor()); - return SkColorSetA(ripple_attributes.base_color, - ripple_attributes.highlight_opacity * 255); +SkColor AppListColorProviderImpl::GetPageSwitcherInkDropHighlightColor( + bool is_root_app_grid_page_switcher) const { + return DeprecatedGetInkDropHighlightColor( + is_root_app_grid_page_switcher + ? SkColorSetA(SkColorSetARGB(255, 95, 99, 104), 20) + : SkColorSetA(SkColorSetARGB(255, 95, 99, 104), 24)); } SkColor AppListColorProviderImpl::GetSearchBoxIconColor(
diff --git a/ash/app_list/app_list_color_provider_impl.h b/ash/app_list/app_list_color_provider_impl.h index e2d779e4f..c6f31a3 100644 --- a/ash/app_list/app_list_color_provider_impl.h +++ b/ash/app_list/app_list_color_provider_impl.h
@@ -27,9 +27,12 @@ SkColor GetSuggestionChipBackgroundColor() const override; SkColor GetSuggestionChipTextColor() const override; SkColor GetAppListItemTextColor() const override; - SkColor GetPageSwitcherButtonColor() const override; - SkColor GetPageSwitcherInkDropBaseColor() const override; - SkColor GetPageSwitcherInkDropHighlightColor() const override; + SkColor GetPageSwitcherButtonColor( + bool is_root_app_grid_page_switcher) const override; + SkColor GetPageSwitcherInkDropBaseColor( + bool is_root_app_grid_page_switcher) const override; + SkColor GetPageSwitcherInkDropHighlightColor( + bool is_root_app_grid_page_switcher) const override; SkColor GetSearchBoxIconColor(SkColor default_color) const override; SkColor GetSearchBoxCardBackgroundColor() const override; SkColor GetFolderBackgroundColor(SkColor default_color) const override;
diff --git a/ash/app_list/app_list_controller_impl_unittest.cc b/ash/app_list/app_list_controller_impl_unittest.cc index 65c5c7d..c01c7e8 100644 --- a/ash/app_list/app_list_controller_impl_unittest.cc +++ b/ash/app_list/app_list_controller_impl_unittest.cc
@@ -743,7 +743,7 @@ wm::ActivateWindow(w1.get()); Shell::Get()->home_screen_controller()->GoHome( display::Screen::GetScreen()->GetPrimaryDisplay().id()); - EXPECT_EQ(WindowStateType::kMinimized, + EXPECT_EQ(chromeos::WindowStateType::kMinimized, WindowState::Get(w1.get())->GetStateType()); EXPECT_TRUE(GetExpandArrowViewVisibility());
diff --git a/ash/app_list/test/test_app_list_color_provider.cc b/ash/app_list/test/test_app_list_color_provider.cc index 4551a27..cb2e9e0c 100644 --- a/ash/app_list/test/test_app_list_color_provider.cc +++ b/ash/app_list/test/test_app_list_color_provider.cc
@@ -61,15 +61,18 @@ return gfx::kGoogleGrey900; } -SkColor TestAppListColorProvider::GetPageSwitcherButtonColor() const { +SkColor TestAppListColorProvider::GetPageSwitcherButtonColor( + bool is_root_app_grid_page_switcher) const { return gfx::kGoogleGrey700; } -SkColor TestAppListColorProvider::GetPageSwitcherInkDropBaseColor() const { +SkColor TestAppListColorProvider::GetPageSwitcherInkDropBaseColor( + bool is_root_app_grid_page_switcher) const { return SkColorSetA(SK_ColorBLACK, 0x0F); } -SkColor TestAppListColorProvider::GetPageSwitcherInkDropHighlightColor() const { +SkColor TestAppListColorProvider::GetPageSwitcherInkDropHighlightColor( + bool is_root_app_grid_page_switcher) const { return SkColorSetA(SK_ColorBLACK, 0x0F); }
diff --git a/ash/app_list/test/test_app_list_color_provider.h b/ash/app_list/test/test_app_list_color_provider.h index 0345d81..19ffa76 100644 --- a/ash/app_list/test/test_app_list_color_provider.h +++ b/ash/app_list/test/test_app_list_color_provider.h
@@ -27,9 +27,12 @@ SkColor GetSuggestionChipBackgroundColor() const override; SkColor GetSuggestionChipTextColor() const override; SkColor GetAppListItemTextColor() const override; - SkColor GetPageSwitcherButtonColor() const override; - SkColor GetPageSwitcherInkDropBaseColor() const override; - SkColor GetPageSwitcherInkDropHighlightColor() const override; + SkColor GetPageSwitcherButtonColor( + bool is_root_app_grid_page_switcher) const override; + SkColor GetPageSwitcherInkDropBaseColor( + bool is_root_app_grid_page_switcher) const override; + SkColor GetPageSwitcherInkDropHighlightColor( + bool is_root_app_grid_page_switcher) const override; SkColor GetSearchBoxIconColor(SkColor default_color) const override; SkColor GetSearchBoxCardBackgroundColor() const override; SkColor GetFolderBackgroundColor(SkColor default_color) const override;
diff --git a/ash/app_list/views/page_switcher.cc b/ash/app_list/views/page_switcher.cc index f7a1423..0c60f3f 100644 --- a/ash/app_list/views/page_switcher.cc +++ b/ash/app_list/views/page_switcher.cc
@@ -102,14 +102,17 @@ return std::make_unique<views::FloodFillInkDropRipple>( size(), GetLocalBounds().InsetsFrom(bounds), GetInkDropCenterBasedOnLastEvent(), - AppListColorProvider::Get()->GetPageSwitcherInkDropBaseColor(), 1.0f); + AppListColorProvider::Get()->GetPageSwitcherInkDropBaseColor( + is_root_app_grid_page_switcher_), + 1.0f); } std::unique_ptr<views::InkDropHighlight> CreateInkDropHighlight() const override { auto highlight = std::make_unique<views::InkDropHighlight>( gfx::SizeF(size()), - AppListColorProvider::Get()->GetPageSwitcherInkDropHighlightColor()); + AppListColorProvider::Get()->GetPageSwitcherInkDropHighlightColor( + is_root_app_grid_page_switcher_)); highlight->set_visible_opacity(1.f); return highlight; } @@ -131,7 +134,8 @@ // Returns the information of how to paint selected/normal button. PaintButtonInfo BuildPaintButtonInfo() { PaintButtonInfo info; - info.color = AppListColorProvider::Get()->GetPageSwitcherButtonColor(); + info.color = AppListColorProvider::Get()->GetPageSwitcherButtonColor( + is_root_app_grid_page_switcher_); if (selected_) { info.style = cc::PaintFlags::kFill_Style; info.radius = SkIntToScalar(kSelectedButtonRadius);
diff --git a/ash/capture_mode/capture_mode_controller.cc b/ash/capture_mode/capture_mode_controller.cc index 055f724..24c525dd 100644 --- a/ash/capture_mode/capture_mode_controller.cc +++ b/ash/capture_mode/capture_mode_controller.cc
@@ -455,9 +455,10 @@ // Show the item in the folder. delegate_->ShowScreenCaptureItemInFolder(screen_capture_path); } else { - // TODO: fill in here. + // TODO(crbug.com/1136666): Remove edit button for video recording. switch (button_index.value()) { case NotificationButtonIndex::BUTTON_EDIT: + delegate_->OpenScreenshotInImageEditor(screen_capture_path); break; case NotificationButtonIndex::BUTTON_DELETE: DeleteFileAsync(screen_capture_path);
diff --git a/ash/capture_mode/capture_mode_session.cc b/ash/capture_mode/capture_mode_session.cc index 0123abe..d7bfedf 100644 --- a/ash/capture_mode/capture_mode_session.cc +++ b/ash/capture_mode/capture_mode_session.cc
@@ -202,7 +202,7 @@ capture_mode_bar_view_->OnCaptureSourceChanged(new_source); SetMouseWarpEnabled(new_source != CaptureModeSource::kRegion); - UpdateCaptureRegionWidgets(); + UpdateDimensionsLabelWidget(/*is_resizing=*/false); layer()->SchedulePaint(layer()->bounds()); UpdateCaptureLabelWidget(); } @@ -468,7 +468,7 @@ } else if (!CaptureModeBarView::GetBounds(current_root_) .Contains(location_in_root)) { is_selecting_region_ = true; - UpdateCaptureRegion(gfx::Rect()); + UpdateCaptureRegion(gfx::Rect(), /*is_resizing=*/true); } return; } @@ -485,7 +485,8 @@ // press location and the current location. if (is_selecting_region_) { UpdateCaptureRegion( - GetRectEnclosingPoints({initial_location_in_root_, location_in_root})); + GetRectEnclosingPoints({initial_location_in_root_, location_in_root}), + /*is_resizing=*/true); return; } @@ -499,7 +500,7 @@ gfx::Rect new_capture_region = controller_->user_capture_region(); new_capture_region.Offset(location_in_root - previous_location_in_root); new_capture_region.AdjustToFit(current_root_->bounds()); - UpdateCaptureRegion(new_capture_region); + UpdateCaptureRegion(new_capture_region, /*is_resizing=*/false); return; } @@ -508,7 +509,7 @@ std::vector<gfx::Point> points = anchor_points_; DCHECK(!points.empty()); points.push_back(location_in_root); - UpdateCaptureRegion(GetRectEnclosingPoints(points)); + UpdateCaptureRegion(GetRectEnclosingPoints(points), /*is_resizing=*/true); } void CaptureModeSession::OnLocatedEventReleased( @@ -523,17 +524,19 @@ gfx::Insets(-kAffordanceCircleRadiusDp - kCaptureRegionBorderStrokePx)); layer()->SchedulePaint(damage_region); + UpdateDimensionsLabelWidget(/*is_resizing=*/false); + if (!is_selecting_region_) return; // After first release event, we advance to the next phase. is_selecting_region_ = false; - UpdateCaptureRegionWidgets(); UpdateCaptureLabelWidget(); } void CaptureModeSession::UpdateCaptureRegion( - const gfx::Rect& new_capture_region) { + const gfx::Rect& new_capture_region, + bool is_resizing) { const gfx::Rect old_capture_region = controller_->user_capture_region(); if (old_capture_region == new_capture_region) return; @@ -548,25 +551,19 @@ layer()->SchedulePaint(damage_region); controller_->set_user_capture_region(new_capture_region); - UpdateCaptureRegionWidgets(); + UpdateDimensionsLabelWidget(is_resizing); UpdateCaptureLabelWidget(); } -void CaptureModeSession::UpdateCaptureRegionWidgets() { - // TODO(chinsenj): The dimensons label is always shown and the capture - // button label is always shown in the fine tune stage. Update this to match - // the specs. - const bool show = controller_->source() == CaptureModeSource::kRegion; - if (!show) { +void CaptureModeSession::UpdateDimensionsLabelWidget(bool is_resizing) { + const bool should_not_show = + !is_resizing || controller_->source() != CaptureModeSource::kRegion || + controller_->user_capture_region().IsEmpty(); + if (should_not_show) { dimensions_label_widget_.reset(); return; } - MaybeCreateAndUpdateDimensionsLabelWidget(); - UpdateDimensionsLabelBounds(); -} - -void CaptureModeSession::MaybeCreateAndUpdateDimensionsLabelWidget() { if (!dimensions_label_widget_) { auto* parent = GetParentContainer(current_root_); dimensions_label_widget_ = std::make_unique<views::Widget>(); @@ -595,6 +592,8 @@ const gfx::Rect capture_region = controller_->user_capture_region(); size_label->SetText(base::UTF8ToUTF16(base::StringPrintf( "%d x %d", capture_region.width(), capture_region.height()))); + + UpdateDimensionsLabelBounds(); } void CaptureModeSession::UpdateDimensionsLabelBounds() {
diff --git a/ash/capture_mode/capture_mode_session.h b/ash/capture_mode/capture_mode_session.h index 0828895..ca47e45 100644 --- a/ash/capture_mode/capture_mode_session.h +++ b/ash/capture_mode/capture_mode_session.h
@@ -106,18 +106,16 @@ void OnLocatedEventDragged(const gfx::Point& location_in_root); void OnLocatedEventReleased(const gfx::Point& location_in_root); - // Updates the capture region and the capture region widgets. - void UpdateCaptureRegion(const gfx::Rect& new_capture_region); + // Updates the capture region and the capture region widgets depending on the + // value of |is_resizing|. + void UpdateCaptureRegion(const gfx::Rect& new_capture_region, + bool is_resizing); - // Updates the widgets that are used to display text/icons while selecting a - // capture region. They are not visible during fullscreen or window capture, - // and some are only visible during certain phases of region capture. This - // will create or destroy the widgets as needed. - void UpdateCaptureRegionWidgets(); - - // Creates |dimensions_label_widget_| if it does not exist and then set its - // content view to the size label view. - void MaybeCreateAndUpdateDimensionsLabelWidget(); + // Updates the dimensions label widget shown during a region capture session. + // If not |is_resizing|, not a region capture session or the capture region is + // empty, clear existing |dimensions_label_widget_|. Otherwise, create and + // update the dimensions label. + void UpdateDimensionsLabelWidget(bool is_resizing); // Updates the bounds of |dimensions_label_widget_| relative to the current // capture region. Both |dimensions_label_widget_| and its content view must
diff --git a/ash/capture_mode/capture_mode_unittests.cc b/ash/capture_mode/capture_mode_unittests.cc index 8bfbd6eb..5f11ce50 100644 --- a/ash/capture_mode/capture_mode_unittests.cc +++ b/ash/capture_mode/capture_mode_unittests.cc
@@ -136,22 +136,25 @@ } // Select a region by pressing and dragging the mouse. - void SelectRegion(const gfx::Rect& region) { + void SelectRegion(const gfx::Rect& region, bool release_mouse = true) { auto* controller = CaptureModeController::Get(); ASSERT_TRUE(controller->IsActive()); ASSERT_EQ(CaptureModeSource::kRegion, controller->source()); auto* event_generator = GetEventGenerator(); event_generator->set_current_screen_location(region.origin()); - event_generator->DragMouseTo(region.bottom_right()); + event_generator->PressLeftButton(); + event_generator->MoveMouseTo(region.bottom_right()); + if (release_mouse) + event_generator->ReleaseLeftButton(); EXPECT_EQ(region, controller->user_capture_region()); } aura::Window* GetDimensionsLabelWindow() const { auto* controller = CaptureModeController::Get(); DCHECK(controller->IsActive()); - return controller->capture_mode_session() - ->dimensions_label_widget() - ->GetNativeWindow(); + auto* widget = + controller->capture_mode_session()->dimensions_label_widget(); + return widget ? widget->GetNativeWindow() : nullptr; } void WaitForCountDownToFinish() { @@ -480,40 +483,57 @@ // Start Capture Mode in a region in image mode. StartImageRegionCapture(); + // Press down and don't move the mouse. Label shouldn't display for empty + // capture regions. + auto* generator = GetEventGenerator(); + generator->set_current_screen_location(gfx::Point(0, 0)); + generator->PressLeftButton(); + auto* controller = CaptureModeController::Get(); + EXPECT_TRUE(controller->IsActive()); + EXPECT_TRUE(controller->user_capture_region().IsEmpty()); + EXPECT_EQ(nullptr, GetDimensionsLabelWindow()); + generator->ReleaseLeftButton(); + // Press down and drag to select a large region. Verify that the dimensions // label is centered and that the label is below the capture region. gfx::Rect capture_region{100, 100, 600, 200}; - SelectRegion(capture_region); - - aura::Window* dimensions_label_window = GetDimensionsLabelWindow(); + SelectRegion(capture_region, /*release_mouse=*/false); EXPECT_EQ(capture_region.CenterPoint().x(), - dimensions_label_window->bounds().CenterPoint().x()); + GetDimensionsLabelWindow()->bounds().CenterPoint().x()); EXPECT_EQ(capture_region.bottom() + CaptureModeSession::kSizeLabelYDistanceFromRegionDp, - dimensions_label_window->bounds().y()); + GetDimensionsLabelWindow()->bounds().y()); + generator->ReleaseLeftButton(); + EXPECT_EQ(nullptr, GetDimensionsLabelWindow()); // Create a new capture region close to the left side of the screen such that // if the label was centered it would extend out of the screen. // The x value of the label should be the left edge of the screen (0). capture_region.SetRect(2, 100, 2, 100); - SelectRegion(capture_region); - EXPECT_EQ(0, dimensions_label_window->bounds().x()); + SelectRegion(capture_region, /*release_mouse=*/false); + EXPECT_EQ(0, GetDimensionsLabelWindow()->bounds().x()); + generator->ReleaseLeftButton(); + EXPECT_EQ(nullptr, GetDimensionsLabelWindow()); // Create a new capture region close to the right side of the screen such that // if the label was centered it would extend out of the screen. // The right (x + width) of the label should be the right edge of the screen // (800). capture_region.SetRect(796, 100, 2, 100); - SelectRegion(capture_region); - EXPECT_EQ(800, dimensions_label_window->bounds().right()); + SelectRegion(capture_region, /*release_mouse=*/false); + EXPECT_EQ(800, GetDimensionsLabelWindow()->bounds().right()); + generator->ReleaseLeftButton(); + EXPECT_EQ(nullptr, GetDimensionsLabelWindow()); // Create a new capture region close to the bottom side of the screen. // The label should now appear inside the capture region, just above the // bottom edge. It should be above the bottom of the screen as well. capture_region.SetRect(100, 700, 600, 790); - SelectRegion(capture_region); + SelectRegion(capture_region, /*release_mouse=*/false); EXPECT_EQ(800 - CaptureModeSession::kSizeLabelYDistanceFromRegionDp, - dimensions_label_window->bounds().bottom()); + GetDimensionsLabelWindow()->bounds().bottom()); + generator->ReleaseLeftButton(); + EXPECT_EQ(nullptr, GetDimensionsLabelWindow()); } TEST_F(CaptureModeTest, WindowCapture) {
diff --git a/ash/capture_mode/test_capture_mode_delegate.cc b/ash/capture_mode/test_capture_mode_delegate.cc index 67729c0..2325551 100644 --- a/ash/capture_mode/test_capture_mode_delegate.cc +++ b/ash/capture_mode/test_capture_mode_delegate.cc
@@ -16,6 +16,9 @@ void TestCaptureModeDelegate::ShowScreenCaptureItemInFolder( const base::FilePath& file_path) {} +void TestCaptureModeDelegate::OpenScreenshotInImageEditor( + const base::FilePath& file_path) {} + bool TestCaptureModeDelegate::Uses24HourFormat() const { return false; }
diff --git a/ash/capture_mode/test_capture_mode_delegate.h b/ash/capture_mode/test_capture_mode_delegate.h index 5acfbd3b..e3c6e6d 100644 --- a/ash/capture_mode/test_capture_mode_delegate.h +++ b/ash/capture_mode/test_capture_mode_delegate.h
@@ -19,6 +19,7 @@ // CaptureModeDelegate: base::FilePath GetActiveUserDownloadsDir() const override; void ShowScreenCaptureItemInFolder(const base::FilePath& file_path) override; + void OpenScreenshotInImageEditor(const base::FilePath& file_path) override; bool Uses24HourFormat() const override; bool IsCaptureAllowed(const aura::Window* window, const gfx::Rect& bounds,
diff --git a/ash/clipboard/clipboard_nudge.cc b/ash/clipboard/clipboard_nudge.cc new file mode 100644 index 0000000..dbd5ffb --- /dev/null +++ b/ash/clipboard/clipboard_nudge.cc
@@ -0,0 +1,142 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ash/clipboard/clipboard_nudge.h" +#include "ash/public/cpp/ash_features.h" +#include "ash/public/cpp/assistant/assistant_state.h" +#include "ash/public/cpp/shelf_config.h" +#include "ash/public/cpp/shell_window_ids.h" +#include "ash/resources/vector_icons/vector_icons.h" +#include "ash/shell.h" +#include "ash/style/ash_color_provider.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/chromeos/events/keyboard_layout_util.h" +#include "ui/gfx/color_palette.h" +#include "ui/gfx/paint_vector_icon.h" +#include "ui/views/controls/image_view.h" +#include "ui/views/controls/label.h" +#include "ui/wm/core/coordinate_conversion.h" + +namespace ash { + +namespace { + +// The corner radius of the nudge view. +constexpr int kNudgeCornerRadius = 8; + +// The blur radius for the nudge view's background. +constexpr int kNudgeBlurRadius = 30; + +// The size of the clipboard icon. +constexpr int kClipboardIconSize = 20; + +// The size of the keyboard shortcut icon. +constexpr int kKeyboardShortcutIconSize = 16; + +// The minimum width of the label. +constexpr int kMinLabelWidth = 200; + +// The margin between the edge of the screen/shelf and the nudge widget bounds. +constexpr int kNudgeMargin = 8; + +// The spacing between the icon and label in the nudge view. +constexpr int kIconLabelSpacing = 16; + +// The padding which separates the nudge's border with its inner contents. +constexpr int kNudgePadding = 16; + +} // namespace + +class ClipboardNudge::ClipboardNudgeView : public views::View { + public: + ClipboardNudgeView() { + SetPaintToLayer(ui::LAYER_SOLID_COLOR); + layer()->SetColor(ShelfConfig::Get()->GetDefaultShelfColor()); + if (features::IsBackgroundBlurEnabled()) + layer()->SetBackgroundBlur(kNudgeBlurRadius); + layer()->SetRoundedCornerRadius({kNudgeCornerRadius, kNudgeCornerRadius, + kNudgeCornerRadius, kNudgeCornerRadius}); + + SkColor icon_color = AshColorProvider::Get()->GetContentLayerColor( + AshColorProvider::ContentLayerType::kIconColorPrimary); + + clipboard_icon_ = AddChildView(std::make_unique<views::ImageView>()); + clipboard_icon_->SetPaintToLayer(); + clipboard_icon_->layer()->SetFillsBoundsOpaquely(false); + clipboard_icon_->SetBounds(kNudgePadding, kNudgePadding, kClipboardIconSize, + kClipboardIconSize); + clipboard_icon_->SetImage( + gfx::CreateVectorIcon(kClipboardIcon, icon_color)); + + label_ = AddChildView(std::make_unique<views::Label>()); + label_->SetPaintToLayer(); + label_->layer()->SetFillsBoundsOpaquely(false); + label_->SetMultiLine(true); + label_->SetPosition(gfx::Point( + kNudgePadding + kClipboardIconSize + kIconLabelSpacing, kNudgePadding)); + label_->SetHorizontalAlignment(gfx::ALIGN_LEFT); + label_->SetVerticalAlignment(gfx::ALIGN_TOP); + label_->SetEnabledColor(AshColorProvider::Get()->GetContentLayerColor( + AshColorProvider::ContentLayerType::kTextColorPrimary)); + label_->SetBackgroundColor(SK_ColorTRANSPARENT); + + // TODO(mmourgos): Create and set text for |label_|. + label_->SetSize(gfx::Size(kMinLabelWidth, kKeyboardShortcutIconSize)); + } + + ~ClipboardNudgeView() override = default; + + views::Label* label_ = nullptr; + views::ImageView* clipboard_icon_ = nullptr; +}; + +ClipboardNudge::ClipboardNudge() : widget_(std::make_unique<views::Widget>()) { + views::Widget::InitParams params( + views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); + params.z_order = ui::ZOrderLevel::kFloatingWindow; + params.activatable = views::Widget::InitParams::ACTIVATABLE_NO; + params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; + params.name = "ClipboardContextualNudge"; + params.layer_type = ui::LAYER_NOT_DRAWN; + params.parent = Shell::GetPrimaryRootWindow()->GetChildById( + kShellWindowId_OverlayContainer); + widget_->Init(std::move(params)); + + nudge_view_ = + widget_->SetContentsView(std::make_unique<ClipboardNudgeView>()); + CalculateAndSetWidgetBounds(); + widget_->Show(); +} + +ClipboardNudge::~ClipboardNudge() = default; + +void ClipboardNudge::Close() { + widget_->CloseWithReason(views::Widget::ClosedReason::kUnspecified); +} + +void ClipboardNudge::CalculateAndSetWidgetBounds() { + aura::Window* root_window = Shell::GetRootWindowForNewWindows(); + gfx::Rect display_bounds = root_window->bounds(); + ::wm::ConvertRectToScreen(root_window, &display_bounds); + gfx::Rect widget_bounds; + + // Calculate the nudge's size to ensure the label text accurately fits. + const int nudge_height = + 2 * kNudgePadding + nudge_view_->label_->bounds().height(); + const int nudge_width = 2 * kNudgePadding + kClipboardIconSize + + kIconLabelSpacing + + nudge_view_->label_->bounds().width(); + + widget_bounds = + gfx::Rect(display_bounds.x() + kNudgeMargin, + display_bounds.height() - ShelfConfig::Get()->shelf_size() - + nudge_height - kNudgeMargin, + nudge_width, nudge_height); + if (base::i18n::IsRTL()) + widget_bounds.set_x(display_bounds.right() - nudge_width - kNudgeMargin); + + widget_->SetBounds(widget_bounds); +} + +} // namespace ash \ No newline at end of file
diff --git a/ash/clipboard/clipboard_nudge.h b/ash/clipboard/clipboard_nudge.h new file mode 100644 index 0000000..2724461 --- /dev/null +++ b/ash/clipboard/clipboard_nudge.h
@@ -0,0 +1,37 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef ASH_CLIPBOARD_CLIPBOARD_NUDGE_H_ +#define ASH_CLIPBOARD_CLIPBOARD_NUDGE_H_ + +#include "ash/ash_export.h" +#include "ui/views/widget/widget.h" + +namespace ash { + +// Implements a contextual nudge for multipaste. +class ASH_EXPORT ClipboardNudge { + public: + ClipboardNudge(); + ClipboardNudge(const ClipboardNudge&) = delete; + ClipboardNudge& operator=(const ClipboardNudge&) = delete; + ~ClipboardNudge(); + + void Close(); + + private: + class ClipboardNudgeView; + + // Calculate and set widget bounds based ona fixed width and a variable + // height to correctly fit the text. + void CalculateAndSetWidgetBounds(); + + std::unique_ptr<views::Widget> widget_; + + ClipboardNudgeView* nudge_view_ = nullptr; // not_owned +}; + +} // namespace ash + +#endif // ASH_CLIPBOARD_CLIPBOARD_NUDGE_H_
diff --git a/ash/clipboard/clipboard_nudge_constants.h b/ash/clipboard/clipboard_nudge_constants.h index 90e80ea..c7983f6 100644 --- a/ash/clipboard/clipboard_nudge_constants.h +++ b/ash/clipboard/clipboard_nudge_constants.h
@@ -13,6 +13,8 @@ constexpr static base::TimeDelta kMinInterval = base::TimeDelta::FromDays(1); constexpr static base::TimeDelta kMaxTimeBetweenPaste = base::TimeDelta::FromMinutes(10); +constexpr static base::TimeDelta kNudgeShowTime = + base::TimeDelta::FromSeconds(6); } // namespace ash
diff --git a/ash/clipboard/clipboard_nudge_controller.cc b/ash/clipboard/clipboard_nudge_controller.cc index afc8f1d..dd9eb33 100644 --- a/ash/clipboard/clipboard_nudge_controller.cc +++ b/ash/clipboard/clipboard_nudge_controller.cc
@@ -5,6 +5,7 @@ #include "ash/clipboard/clipboard_nudge_controller.h" #include "ash/clipboard/clipboard_history_item.h" +#include "ash/clipboard/clipboard_nudge.h" #include "ash/clipboard/clipboard_nudge_constants.h" #include "ash/public/cpp/ash_pref_names.h" #include "ash/session/session_controller_impl.h" @@ -15,6 +16,7 @@ #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" +#include "ui/base/clipboard/clipboard_monitor.h" namespace { @@ -30,10 +32,12 @@ ClipboardHistory* clipboard_history) : clipboard_history_(clipboard_history) { clipboard_history_->AddObserver(this); + ui::ClipboardMonitor::GetInstance()->AddObserver(this); } ClipboardNudgeController::~ClipboardNudgeController() { clipboard_history_->RemoveObserver(this); + ui::ClipboardMonitor::GetInstance()->RemoveObserver(this); } // static @@ -80,8 +84,8 @@ return; case ClipboardState::kSecondCopy: if (GetTime() - last_paste_timestamp_ < kMaxTimeBetweenPaste) { - clipboard_state_ = ClipboardState::kShouldShowNudge; - // TODO(crbug/1105541): Show clipboard nudge. + ShowNudge(); + HandleNudgeShown(); } else { // ClipboardState should be reset to kFirstPaste when timed out. clipboard_state_ = ClipboardState::kFirstPaste; @@ -94,6 +98,21 @@ } } +void ClipboardNudgeController::ShowNudge() { + // Create and show the nudge. + nudge_ = std::make_unique<ClipboardNudge>(); + + // Start a timer to close the nudge after a set amount of time. + hide_nudge_timer_.Start(FROM_HERE, kNudgeShowTime, + base::BindOnce(&ClipboardNudgeController::HideNudge, + weak_ptr_factory_.GetWeakPtr())); +} + +void ClipboardNudgeController::HideNudge() { + nudge_->Close(); + nudge_.reset(); +} + void ClipboardNudgeController::HandleNudgeShown() { clipboard_state_ = ClipboardState::kInit; PrefService* prefs =
diff --git a/ash/clipboard/clipboard_nudge_controller.h b/ash/clipboard/clipboard_nudge_controller.h index 8d3b361..a7c12ba 100644 --- a/ash/clipboard/clipboard_nudge_controller.h +++ b/ash/clipboard/clipboard_nudge_controller.h
@@ -7,7 +7,9 @@ #include "ash/ash_export.h" #include "ash/clipboard/clipboard_history.h" +#include "base/memory/weak_ptr.h" #include "base/time/clock.h" +#include "base/timer/timer.h" #include "ui/base/clipboard/clipboard_observer.h" class PrefService; @@ -15,6 +17,7 @@ class ClipboardHistoryItem; namespace ash { +class ClipboardNudge; // The clipboard contextual nudge will be shown after 4 user actions that must // happen in sequence. The user must perform copy, paste, copy and paste in @@ -38,7 +41,7 @@ // Registers profile prefs. static void RegisterProfilePrefs(PrefRegistrySimple* registry); - // ui::ClipboardHistoryObserver: + // ui::ClipboardHistory::Observer: void OnClipboardHistoryItemAdded(const ClipboardHistoryItem& item) override; // ui::ClipboardObserver: @@ -52,6 +55,7 @@ void ClearClockOverrideForTesting(); const ClipboardState& GetClipboardStateForTesting(); + ClipboardNudge* GetClipboardNudgeForTesting() { return nudge_.get(); } private: // Gets the number of times the nudge has been shown. @@ -63,6 +67,12 @@ // Gets the current time. Can be overridden for testing. base::Time GetTime(); + // Shows the nudge widget. + void ShowNudge(); + + // Hides the nudge widget. + void HideNudge(); + // Owned by ClipboardHistoryController. const ClipboardHistory* clipboard_history_; @@ -72,6 +82,14 @@ base::Time last_paste_timestamp_; // Clock that can be overridden for testing. base::Clock* g_clock_override = nullptr; + + // Contextual nudge which shows a view to inform the user on multipaste usage. + std::unique_ptr<ClipboardNudge> nudge_; + + // Timer to hide the clipboard nudge. + base::OneShotTimer hide_nudge_timer_; + + base::WeakPtrFactory<ClipboardNudgeController> weak_ptr_factory_{this}; }; } // namespace ash
diff --git a/ash/clipboard/clipboard_nudge_controller_unittest.cc b/ash/clipboard/clipboard_nudge_controller_unittest.cc index b3aea50a..c89dd42 100644 --- a/ash/clipboard/clipboard_nudge_controller_unittest.cc +++ b/ash/clipboard/clipboard_nudge_controller_unittest.cc
@@ -75,10 +75,16 @@ EXPECT_EQ(ClipboardState::kSecondCopy, nudge_controller_->GetClipboardStateForTesting()); - // Checks that the second paste advances state as expected. + // Check that clipbaord nudge has not yet been created. + EXPECT_FALSE(nudge_controller_->GetClipboardNudgeForTesting()); + + // Checks that the second paste resets state as expected. nudge_controller_->OnClipboardDataRead(); - EXPECT_EQ(ClipboardState::kShouldShowNudge, + EXPECT_EQ(ClipboardState::kInit, nudge_controller_->GetClipboardStateForTesting()); + + // Check that clipbaord nudge has been created. + EXPECT_TRUE(nudge_controller_->GetClipboardNudgeForTesting()); } // Checks that the clipboard state does not advace if too much time passes @@ -121,6 +127,9 @@ nudge_controller_->GetClipboardStateForTesting()); } + // Check that clipbaord nudge has not yet been created. + EXPECT_FALSE(nudge_controller_->GetClipboardNudgeForTesting()); + // Check that HandleClipboardChanged() will advance nudge_controller's // ClipboardState. nudge_controller_->OnClipboardHistoryItemAdded( @@ -128,8 +137,11 @@ EXPECT_EQ(ClipboardState::kSecondCopy, nudge_controller_->GetClipboardStateForTesting()); nudge_controller_->OnClipboardDataRead(); - EXPECT_EQ(ClipboardState::kShouldShowNudge, + EXPECT_EQ(ClipboardState::kInit, nudge_controller_->GetClipboardStateForTesting()); + + // Check that clipbaord nudge has been created. + EXPECT_TRUE(nudge_controller_->GetClipboardNudgeForTesting()); } // Checks that consecutive copy events does not advance the clipboard state.
diff --git a/ash/frame/caption_buttons/frame_size_button_unittest.cc b/ash/frame/caption_buttons/frame_size_button_unittest.cc index 81b1d1e..6f943f4a 100644 --- a/ash/frame/caption_buttons/frame_size_button_unittest.cc +++ b/ash/frame/caption_buttons/frame_size_button_unittest.cc
@@ -27,6 +27,8 @@ namespace { +using ::chromeos::WindowStateType; + class TestWidgetDelegate : public views::WidgetDelegateView { public: explicit TestWidgetDelegate(bool resizable) {
diff --git a/ash/frame/non_client_frame_view_ash.cc b/ash/frame/non_client_frame_view_ash.cc index 71d57868..3485a40 100644 --- a/ash/frame/non_client_frame_view_ash.cc +++ b/ash/frame/non_client_frame_view_ash.cc
@@ -39,6 +39,8 @@ namespace ash { +using ::chromeos::WindowStateType; + DEFINE_UI_CLASS_PROPERTY_KEY(NonClientFrameViewAsh*, kNonClientFrameViewAshKey, nullptr)
diff --git a/ash/metrics/user_metrics_recorder.cc b/ash/metrics/user_metrics_recorder.cc index 12701581..2fa09b5 100644 --- a/ash/metrics/user_metrics_recorder.cc +++ b/ash/metrics/user_metrics_recorder.cc
@@ -29,6 +29,8 @@ namespace { +using ::chromeos::WindowStateType; + // Time in seconds between calls to "RecordPeriodicMetrics". const int kAshPeriodicMetricsTimeInSeconds = 30 * 60;
diff --git a/ash/public/cpp/BUILD.gn b/ash/public/cpp/BUILD.gn index bcf647e..8f82490 100644 --- a/ash/public/cpp/BUILD.gn +++ b/ash/public/cpp/BUILD.gn
@@ -323,8 +323,6 @@ "window_pin_type.h", "window_properties.cc", "window_properties.h", - "window_state_type.cc", - "window_state_type.h", ] defines = [ "ASH_PUBLIC_IMPLEMENTATION" ]
diff --git a/ash/public/cpp/app_list/app_list_color_provider.h b/ash/public/cpp/app_list/app_list_color_provider.h index 18c7a09..c4687c0d 100644 --- a/ash/public/cpp/app_list/app_list_color_provider.h +++ b/ash/public/cpp/app_list/app_list_color_provider.h
@@ -26,9 +26,12 @@ virtual SkColor GetSuggestionChipBackgroundColor() const = 0; virtual SkColor GetSuggestionChipTextColor() const = 0; virtual SkColor GetAppListItemTextColor() const = 0; - virtual SkColor GetPageSwitcherButtonColor() const = 0; - virtual SkColor GetPageSwitcherInkDropBaseColor() const = 0; - virtual SkColor GetPageSwitcherInkDropHighlightColor() const = 0; + virtual SkColor GetPageSwitcherButtonColor( + bool is_root_app_grid_page_switcher) const = 0; + virtual SkColor GetPageSwitcherInkDropBaseColor( + bool is_root_app_grid_page_switcher) const = 0; + virtual SkColor GetPageSwitcherInkDropHighlightColor( + bool is_root_app_grid_page_switcher) const = 0; virtual SkColor GetSearchBoxIconColor(SkColor default_color) const = 0; virtual SkColor GetSearchBoxCardBackgroundColor() const = 0; virtual SkColor GetFolderBackgroundColor(SkColor default_color) const = 0;
diff --git a/ash/public/cpp/capture_mode_delegate.h b/ash/public/cpp/capture_mode_delegate.h index b2faa97..08d4f0f10 100644 --- a/ash/public/cpp/capture_mode_delegate.h +++ b/ash/public/cpp/capture_mode_delegate.h
@@ -36,6 +36,9 @@ virtual void ShowScreenCaptureItemInFolder( const base::FilePath& file_path) = 0; + // Opens the screenshot item in an image editor. + virtual void OpenScreenshotInImageEditor(const base::FilePath& file_path) = 0; + // Returns true if the current user is using the 24-hour format (i.e. 14:00 // vs. 2:00 PM). This is used to build the file name of the captured image or // video.
diff --git a/ash/public/cpp/default_frame_header.cc b/ash/public/cpp/default_frame_header.cc index 181707df..440cce0 100644 --- a/ash/public/cpp/default_frame_header.cc +++ b/ash/public/cpp/default_frame_header.cc
@@ -8,8 +8,8 @@ #include "ash/public/cpp/caption_buttons/caption_button_model.h" #include "ash/public/cpp/caption_buttons/frame_caption_button_container_view.h" #include "ash/public/cpp/window_properties.h" -#include "ash/public/cpp/window_state_type.h" #include "base/logging.h" // DCHECK +#include "chromeos/ui/base/window_state_type.h" #include "third_party/skia/include/core/SkPath.h" #include "ui/gfx/canvas.h" #include "ui/gfx/color_utils.h"
diff --git a/ash/public/cpp/window_properties.cc b/ash/public/cpp/window_properties.cc index 383c0a23..84fd5fca 100644 --- a/ash/public/cpp/window_properties.cc +++ b/ash/public/cpp/window_properties.cc
@@ -8,14 +8,15 @@ #include "ash/public/cpp/shelf_types.h" #include "ash/public/cpp/window_backdrop.h" #include "ash/public/cpp/window_pin_type.h" -#include "ash/public/cpp/window_state_type.h" #include "chromeos/ui/base/chromeos_ui_constants.h" +#include "chromeos/ui/base/window_state_type.h" #include "third_party/skia/include/core/SkRegion.h" #include "ui/aura/window.h" #include "ui/wm/core/window_properties.h" DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(ASH_PUBLIC_EXPORT, ash::WindowPinType) -DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(ASH_PUBLIC_EXPORT, ash::WindowStateType) +DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(ASH_PUBLIC_EXPORT, + chromeos::WindowStateType) DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(ASH_PUBLIC_EXPORT, ash::WindowBackdrop*) DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(ASH_PUBLIC_EXPORT, bool*) DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(ASH_PUBLIC_EXPORT, float*) @@ -46,9 +47,9 @@ DEFINE_UI_CLASS_PROPERTY_KEY(bool, kIsDraggingTabsKey, false) DEFINE_UI_CLASS_PROPERTY_KEY(bool, kHideInDeskMiniViewKey, false) DEFINE_UI_CLASS_PROPERTY_KEY(bool, kForceVisibleInMiniViewKey, false) -DEFINE_UI_CLASS_PROPERTY_KEY(WindowStateType, +DEFINE_UI_CLASS_PROPERTY_KEY(chromeos::WindowStateType, kPrePipWindowStateTypeKey, - WindowStateType::kDefault) + chromeos::WindowStateType::kDefault) DEFINE_UI_CLASS_PROPERTY_KEY(bool, kWindowManagerManagesOpacityKey, false) DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(bool, kMinimizeOnBackKey, nullptr) DEFINE_UI_CLASS_PROPERTY_KEY(bool, kPipOriginalWindowKey, false) @@ -57,9 +58,9 @@ DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(gfx::Rect, kRestoreBoundsOverrideKey, nullptr) -DEFINE_UI_CLASS_PROPERTY_KEY(WindowStateType, +DEFINE_UI_CLASS_PROPERTY_KEY(chromeos::WindowStateType, kRestoreWindowStateTypeOverrideKey, - WindowStateType::kDefault) + chromeos::WindowStateType::kDefault) DEFINE_UI_CLASS_PROPERTY_KEY(bool, kSearchKeyAcceleratorReservedKey, false) DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(std::string, kShelfIDKey, nullptr) DEFINE_UI_CLASS_PROPERTY_KEY(int32_t, kShelfItemTypeKey, TYPE_UNDEFINED) @@ -83,9 +84,9 @@ kWindowPinTypeKey, WindowPinType::kNone) DEFINE_UI_CLASS_PROPERTY_KEY(bool, kWindowPositionManagedTypeKey, false) -DEFINE_UI_CLASS_PROPERTY_KEY(WindowStateType, +DEFINE_UI_CLASS_PROPERTY_KEY(chromeos::WindowStateType, kWindowStateTypeKey, - WindowStateType::kDefault) + chromeos::WindowStateType::kDefault) DEFINE_UI_CLASS_PROPERTY_KEY(bool, kWindowPipTypeKey, false)
diff --git a/ash/public/cpp/window_properties.h b/ash/public/cpp/window_properties.h index ec3c5b7d..2d92595 100644 --- a/ash/public/cpp/window_properties.h +++ b/ash/public/cpp/window_properties.h
@@ -21,6 +21,10 @@ using WindowProperty = ui::ClassProperty<T>; } // namespace aura +namespace chromeos { +enum class WindowStateType; +} + namespace gfx { class Rect; } @@ -28,7 +32,6 @@ namespace ash { enum class WindowPinType; -enum class WindowStateType; class WindowBackdrop; @@ -134,8 +137,8 @@ kMinimizeOnBackKey; // A property key to store the window state the window had before entering PIP. -ASH_PUBLIC_EXPORT extern const aura::WindowProperty<WindowStateType>* const - kPrePipWindowStateTypeKey; +ASH_PUBLIC_EXPORT extern const aura::WindowProperty< + chromeos::WindowStateType>* const kPrePipWindowStateTypeKey; // If true, the current PIP window is spawned from this window. // Android PIP has two types of behavior depending on how many activities the @@ -177,8 +180,8 @@ // take preference over the current state if // |kRestoreWindowStateTypeOverrideKey| is set. This is used by e.g. the tablet // mode window manager. -ASH_PUBLIC_EXPORT extern const aura::WindowProperty<WindowStateType>* const - kRestoreWindowStateTypeOverrideKey; +ASH_PUBLIC_EXPORT extern const aura::WindowProperty< + chromeos::WindowStateType>* const kRestoreWindowStateTypeOverrideKey; // A property key to store whether search key accelerator is reserved for a // window. This is used to pass through search key accelerators to Android @@ -237,8 +240,8 @@ kWindowPositionManagedTypeKey; // A property key to indicate ash's extended window state. -ASH_PUBLIC_EXPORT extern const aura::WindowProperty<WindowStateType>* const - kWindowStateTypeKey; +ASH_PUBLIC_EXPORT extern const aura::WindowProperty< + chromeos::WindowStateType>* const kWindowStateTypeKey; // A property key to indicate pip window state. ASH_PUBLIC_EXPORT extern const aura::WindowProperty<bool>* const
diff --git a/ash/resources/vector_icons/BUILD.gn b/ash/resources/vector_icons/BUILD.gn index 4cddaa4..1bd3ffd 100644 --- a/ash/resources/vector_icons/BUILD.gn +++ b/ash/resources/vector_icons/BUILD.gn
@@ -37,6 +37,7 @@ "capture_mode_window.icon", "check_circle.icon", "chevron_right.icon", + "clipboard.icon", "close_button.icon", "copy.icon", "dark_theme_color_mode.icon",
diff --git a/ash/resources/vector_icons/clipboard.icon b/ash/resources/vector_icons/clipboard.icon new file mode 100644 index 0000000..17af8e6 --- /dev/null +++ b/ash/resources/vector_icons/clipboard.icon
@@ -0,0 +1,34 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +CANVAS_DIMENSIONS, 20, +MOVE_TO, 16, 3, +R_H_LINE_TO, -3.2f, +ARC_TO, 3, 3, 0, 0, 0, 10, 1, +R_ARC_TO, 3, 3, 0, 0, 0, -2.8f, 2, +H_LINE_TO, 4, +R_ARC_TO, 2, 2, 0, 0, 0, -2, 2, +R_V_LINE_TO, 11, +R_CUBIC_TO, 0, 1.1f, 0.9f, 2, 2, 2, +R_H_LINE_TO, 12, +R_ARC_TO, 2, 2, 0, 0, 0, 2, -2, +V_LINE_TO, 5, +R_ARC_TO, 2, 2, 0, 0, 0, -2, -2, +CLOSE, +R_MOVE_TO, -6, 0, +R_ARC_TO, 1, 1, 0, 0, 1, 1, 1, +R_ARC_TO, 1, 1, 0, 0, 1, -1, 1, +R_ARC_TO, 1, 1, 0, 0, 1, -1, -1, +R_ARC_TO, 1, 1, 0, 0, 1, 1, -1, +CLOSE, +R_MOVE_TO, 6, 13, +H_LINE_TO, 4, +V_LINE_TO, 5, +R_H_LINE_TO, 3, +R_V_LINE_TO, 2, +R_H_LINE_TO, 6, +V_LINE_TO, 5, +R_H_LINE_TO, 3, +R_V_LINE_TO, 11, +CLOSE \ No newline at end of file
diff --git a/ash/shelf/login_shelf_view.cc b/ash/shelf/login_shelf_view.cc index 614ed16..949058a 100644 --- a/ash/shelf/login_shelf_view.cc +++ b/ash/shelf/login_shelf_view.cc
@@ -189,9 +189,9 @@ SetInkDropMode(InkDropMode::ON); SetHasInkDropActionOnClick(true); SetInkDropBaseColor( - DeprecatedGetShelfInkDropBaseColor(kDefaultShelfInkDropColor)); + DeprecatedGetInkDropBaseColor(kDefaultShelfInkDropColor)); SetInkDropVisibleOpacity( - DeprecatedGetShelfInkDropOpacity(kDefaultShelfInkDropOpacity)); + DeprecatedGetInkDropOpacity(kDefaultShelfInkDropOpacity)); // Layer rendering is required when the shelf background is visible, which // happens when the wallpaper is not blurred. @@ -305,9 +305,9 @@ SetInkDropMode(InkDropMode::ON); SetHasInkDropActionOnClick(true); SetInkDropBaseColor( - DeprecatedGetShelfInkDropBaseColor(kDefaultShelfInkDropColor)); + DeprecatedGetInkDropBaseColor(kDefaultShelfInkDropColor)); SetInkDropVisibleOpacity( - DeprecatedGetShelfInkDropOpacity(kDefaultShelfInkDropOpacity)); + DeprecatedGetInkDropOpacity(kDefaultShelfInkDropOpacity)); // Layer rendering is required when the shelf background is visible, which // happens when the wallpaper is not blurred.
diff --git a/ash/shelf/shelf_button.cc b/ash/shelf/shelf_button.cc index fa2ca8a8..9976dba 100644 --- a/ash/shelf/shelf_button.cc +++ b/ash/shelf/shelf_button.cc
@@ -23,10 +23,9 @@ shelf_button_delegate_(shelf_button_delegate) { DCHECK(shelf_button_delegate_); SetHideInkDropWhenShowingContextMenu(false); - SetInkDropBaseColor( - DeprecatedGetShelfInkDropBaseColor(kDefaultShelfInkDropColor)); + SetInkDropBaseColor(DeprecatedGetInkDropBaseColor(kDefaultShelfInkDropColor)); SetInkDropVisibleOpacity( - DeprecatedGetShelfInkDropOpacity(kDefaultShelfInkDropOpacity)); + DeprecatedGetInkDropOpacity(kDefaultShelfInkDropOpacity)); SetFocusBehavior(FocusBehavior::ALWAYS); SetInkDropMode(InkDropMode::ON_NO_GESTURE_HANDLER); SetFocusPainter(views::Painter::CreateSolidFocusPainter(
diff --git a/ash/strings/ash_strings_fa.xtb b/ash/strings/ash_strings_fa.xtb index 04fe535..15155c2 100644 --- a/ash/strings/ash_strings_fa.xtb +++ b/ash/strings/ash_strings_fa.xtb
@@ -156,7 +156,7 @@ <translation id="2435457462613246316">نمایش گذرواژه</translation> <translation id="2473177541599297363">تأیید وضوح</translation> <translation id="2475982808118771221">یک خطا روی داد</translation> -<translation id="2479579251444854687">برای باز کردن «مرور کلی»، با سه انگشت تند به بالا بکشید و برای بستن به پایین بکشید.</translation> +<translation id="2479579251444854687">برای باز کردن «مرور کلی»، با سه انگشت تند بهبالا بکشید و برای بستن به پایین بکشید.</translation> <translation id="2482878487686419369">اعلانها</translation> <translation id="2484513351006226581">برای تغییر جانمایی صفحهکلید، <ph name="KEYBOARD_SHORTCUT" /> را فشار دهید.</translation> <translation id="2501920221385095727">کلیدهای چسبان</translation> @@ -169,7 +169,7 @@ <translation id="2595239820337756193">5K in miles (۵ کیلومتر به مایل)</translation> <translation id="2617342710774726426">سیمکارت قفل است</translation> <translation id="2621713457727696555">ایمن شد</translation> -<translation id="2640255526076764619">اشاره صفحه لمسی برای جابهجایی به میزکار قبلی تغییر کرده است. برای جابهجایی به میزکار قبلی، با چهار انگشت تند به چپ بکشید.</translation> +<translation id="2640255526076764619">اشاره صفحه لمسی برای جابهجایی به میزکار قبلی تغییر کرده است. برای جابهجایی به میزکار قبلی، با چهار انگشت تند بهچپ بکشید.</translation> <translation id="2653659639078652383">ارسال</translation> <translation id="2658778018866295321">کلیک کنید و بکشید</translation> <translation id="2700493154570097719">تنظیم صفحهکلید</translation> @@ -262,7 +262,7 @@ <translation id="3571734092741541777">تنظیم</translation> <translation id="3573179567135747900">به "<ph name="FROM_LOCALE" />" تغییر دهید (به راهاندازی دوباره نیاز دارد)</translation> <translation id="3576141592585647168">تغییر منطقه زمانی</translation> -<translation id="3593646411856133110">برای دیدن برنامههای باز، تند به بالا بکشید و نگه دارید</translation> +<translation id="3593646411856133110">برای دیدن برنامههای باز، تند بهبالا بکشید و نگه دارید</translation> <translation id="3595596368722241419">باتری پر است</translation> <translation id="3604801046548457007">میز <ph name="DESK_TITILE" /> ایجاد شد</translation> <translation id="3606978283550408104">نمایشگر بریل متصل شد.</translation> @@ -493,7 +493,7 @@ <translation id="6018164090099858612">خروج از حالت آینه</translation> <translation id="602001110135236999">پیمایش به چپ</translation> <translation id="6025324406281560198"><ph name="SECURITY_STATUS" />، <ph name="CONNECTION_STATUS" />، قدرت سیگنال <ph name="SIGNAL_STRENGTH" />، تحتمدیریت سرپرست</translation> -<translation id="6029337736376922061">اشاره صفحه لمسی برای جابهجایی به میزکار بعدی تغییر کرده است. برای جابهجایی به میزکار بعدی، با ۴ انگشت تند به راست بکشید.</translation> +<translation id="6029337736376922061">اشاره صفحه لمسی برای جابهجایی به میزکار بعدی تغییر کرده است. برای جابهجایی به میزکار بعدی، با ۴ انگشت تند بهراست بکشید.</translation> <translation id="6030495522958826102">منو به گوشه راست پایین صفحه منتقل شد.</translation> <translation id="6040143037577758943">بستن</translation> <translation id="6043212731627905357">این نمایشگر با <ph name="DEVICE_TYPE" /> سازگار نیست (نمایشگر پشتیبانی نمیشود).</translation> @@ -791,7 +791,7 @@ <translation id="9072519059834302790"><ph name="TIME_LEFT" /> زمان تا تخلیه باتری باقیمانده است.</translation> <translation id="9074739597929991885">بلوتوث</translation> <translation id="9079731690316798640">Wi-Fi: <ph name="ADDRESS" /></translation> -<translation id="9080132581049224423">برای رفتن به صفحه اصلی تند به بالا بکشید</translation> +<translation id="9080132581049224423">برای رفتن به صفحه اصلی تند بهبالا بکشید</translation> <translation id="9080206825613744995">میکروفون در حال استفاده است.</translation> <translation id="9084606467167974638">جابهجایی موقعیت منو</translation> <translation id="9089416786594320554">روشهای ورودی</translation>
diff --git a/ash/strings/ash_strings_ja.xtb b/ash/strings/ash_strings_ja.xtb index 97ad7d4..3955f3f 100644 --- a/ash/strings/ash_strings_ja.xtb +++ b/ash/strings/ash_strings_ja.xtb
@@ -798,7 +798,7 @@ <translation id="9089416786594320554">入力方法</translation> <translation id="9091626656156419976">ディスプレイ「<ph name="DISPLAY_NAME" />」が取り外されました</translation> <translation id="9151726767154816831">更新するには、再起動して Powerwash を実行してください</translation> -<translation id="9166331175924255663">ニアバイシェアの広範囲の共有設定を切り替えます。</translation> +<translation id="9166331175924255663">ニアバイシェアで付近のデバイスに表示されるモードのオン/オフを切り替えます。</translation> <translation id="9168436347345867845">後で行う</translation> <translation id="9179259655489829027">この機能を使用すると、パスワードを入力せずにログイン ユーザーにすばやくアクセスできます。この機能は信頼できるアカウントにのみ使用してください。</translation> <translation id="9183456764293710005">全画面拡大鏡</translation>
diff --git a/ash/strings/ash_strings_nl.xtb b/ash/strings/ash_strings_nl.xtb index ff58ad4..073d124 100644 --- a/ash/strings/ash_strings_nl.xtb +++ b/ash/strings/ash_strings_nl.xtb
@@ -25,7 +25,7 @@ <translation id="119944043368869598">Alles wissen</translation> <translation id="1199716647557067911">Weet je zeker dat je 'Toegang via schakelaar' wilt uitschakelen?</translation> <translation id="121097972571826261">Vooruit per woord</translation> -<translation id="1225748608451425081">Je Chromebook is vergrendeld door een bekend probleem. Je kunt inloggen over: <ph name="TIME_LEFT" />.</translation> +<translation id="1225748608451425081">Je Chromebook is vergrendeld vanwege een bekend probleem. Je kunt inloggen over: <ph name="TIME_LEFT" />.</translation> <translation id="1229194443904279055">Selecteren stoppen</translation> <translation id="1239161794459865856"><ph name="FEATURE_NAME" /> is verbonden.</translation> <translation id="1247372569136754018">Microfoon (intern)</translation>
diff --git a/ash/style/default_color_constants.h b/ash/style/default_color_constants.h index c637e30..6ff2b49d 100644 --- a/ash/style/default_color_constants.h +++ b/ash/style/default_color_constants.h
@@ -33,4 +33,8 @@ const SkColor kBackgroundColorBeforeActivated = SK_ColorWHITE; const SkColor kBackgroundColorAfterActivated = gfx::kGoogleBlue600; +// Colors for back gesture nudge. +constexpr SkColor kCircleColor = SK_ColorWHITE; +constexpr SkColor kLabelBackgroundColor = SkColorSetA(SK_ColorBLACK, 0xDE); + #endif // ASH_STYLE_DEFAULT_COLOR_CONSTANTS_H_
diff --git a/ash/style/default_colors.cc b/ash/style/default_colors.cc index 4745dc7d..13a0e93 100644 --- a/ash/style/default_colors.cc +++ b/ash/style/default_colors.cc
@@ -47,14 +47,38 @@ return AshColorProvider::Get()->GetLoginBackgroundBaseColor(); } -SkColor DeprecatedGetShelfInkDropBaseColor(SkColor default_color) { +SkColor DeprecatedGetInkDropBaseColor(SkColor default_color) { if (!features::IsDarkLightModeEnabled()) return default_color; return AshColorProvider::Get()->GetRippleAttributes().base_color; } -float DeprecatedGetShelfInkDropOpacity(float default_opacity) { +SkColor DeprecatedGetInkDropRippleColor(SkColor default_color) { + if (!features::IsDarkLightModeEnabled()) + return default_color; + + AshColorProvider::RippleAttributes ripple_attributes = + AshColorProvider::Get()->GetRippleAttributes( + AshColorProvider::Get()->GetShieldLayerColor( + AshColorProvider::ShieldLayerType::kShield80)); + return SkColorSetA(ripple_attributes.base_color, + ripple_attributes.inkdrop_opacity * 255); +} + +SkColor DeprecatedGetInkDropHighlightColor(SkColor default_color) { + if (!features::IsDarkLightModeEnabled()) + return default_color; + + AshColorProvider::RippleAttributes ripple_attributes = + AshColorProvider::Get()->GetRippleAttributes( + AshColorProvider::Get()->GetShieldLayerColor( + AshColorProvider::ShieldLayerType::kShield80)); + return SkColorSetA(ripple_attributes.base_color, + ripple_attributes.inkdrop_opacity * 255); +} + +float DeprecatedGetInkDropOpacity(float default_opacity) { if (!features::IsDarkLightModeEnabled()) return default_opacity;
diff --git a/ash/style/default_colors.h b/ash/style/default_colors.h index 71a17efd..caa1226a 100644 --- a/ash/style/default_colors.h +++ b/ash/style/default_colors.h
@@ -25,8 +25,10 @@ SkColor DeprecatedGetContentLayerColor(AshColorProvider::ContentLayerType type, SkColor default_color); SkColor DeprecatedGetLoginBackgroundBaseColor(SkColor default_color); -SkColor DeprecatedGetShelfInkDropBaseColor(SkColor default_color); -float DeprecatedGetShelfInkDropOpacity(float default_opacity); +SkColor DeprecatedGetInkDropBaseColor(SkColor default_color); +SkColor DeprecatedGetInkDropRippleColor(SkColor default_color); +SkColor DeprecatedGetInkDropHighlightColor(SkColor default_color); +float DeprecatedGetInkDropOpacity(float default_opacity); SkColor DeprecatedGetAppStateIndicatorColor(bool active, SkColor active_color, SkColor default_color);
diff --git a/ash/system/holding_space/holding_space_tray.cc b/ash/system/holding_space/holding_space_tray.cc index f9d375f..ced25cf 100644 --- a/ash/system/holding_space/holding_space_tray.cc +++ b/ash/system/holding_space/holding_space_tray.cc
@@ -52,38 +52,16 @@ void HoldingSpaceTray::HideBubbleWithView(const TrayBubbleView* bubble_view) {} -base::string16 HoldingSpaceTray::GetAccessibleNameForBubble() { - return GetAccessibleNameForTray(); -} - -bool HoldingSpaceTray::ShouldEnableExtraKeyboardAccessibility() { - return Shell::Get()->accessibility_controller()->spoken_feedback().enabled(); -} - -void HoldingSpaceTray::HideBubble(const TrayBubbleView* bubble_view) { - CloseBubble(); -} - -void HoldingSpaceTray::OnWidgetDragWillStart(views::Widget* widget) { - // The holding space bubble should be closed while dragging holding space - // items so as not to obstruct drop targets. Post the task to close the bubble - // so that we don't attempt to destroy the bubble widget before the associated - // drag event has been fully initialized. - base::SequencedTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(&HoldingSpaceTray::CloseBubble, - weak_factory_.GetWeakPtr())); -} - -void HoldingSpaceTray::OnWidgetDestroying(views::Widget* widget) { - widget->RemoveObserver(this); - CloseBubble(); -} - void HoldingSpaceTray::AnchorUpdated() { if (bubble_) bubble_->AnchorUpdated(); } +void HoldingSpaceTray::UpdateAfterLoginStatusChange() { + SetVisiblePreferred(shelf()->GetStatusAreaWidget()->login_status() == + LoginStatus::USER); +} + bool HoldingSpaceTray::PerformAction(const ui::Event& event) { holding_space_metrics::RecordPodAction( holding_space_metrics::PodAction::kClick); @@ -106,11 +84,6 @@ return true; } -void HoldingSpaceTray::UpdateAfterLoginStatusChange() { - SetVisiblePreferred(shelf()->GetStatusAreaWidget()->login_status() == - LoginStatus::USER); -} - void HoldingSpaceTray::CloseBubble() { if (!bubble_) return; @@ -150,4 +123,31 @@ return "HoldingSpaceTray"; } +base::string16 HoldingSpaceTray::GetAccessibleNameForBubble() { + return GetAccessibleNameForTray(); +} + +bool HoldingSpaceTray::ShouldEnableExtraKeyboardAccessibility() { + return Shell::Get()->accessibility_controller()->spoken_feedback().enabled(); +} + +void HoldingSpaceTray::HideBubble(const TrayBubbleView* bubble_view) { + CloseBubble(); +} + +void HoldingSpaceTray::OnWidgetDragWillStart(views::Widget* widget) { + // The holding space bubble should be closed while dragging holding space + // items so as not to obstruct drop targets. Post the task to close the bubble + // so that we don't attempt to destroy the bubble widget before the associated + // drag event has been fully initialized. + base::SequencedTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(&HoldingSpaceTray::CloseBubble, + weak_factory_.GetWeakPtr())); +} + +void HoldingSpaceTray::OnWidgetDestroying(views::Widget* widget) { + widget->RemoveObserver(this); + CloseBubble(); +} + } // namespace ash
diff --git a/ash/system/holding_space/holding_space_tray_bubble.cc b/ash/system/holding_space/holding_space_tray_bubble.cc index 3d5bd5a..a95f02a 100644 --- a/ash/system/holding_space/holding_space_tray_bubble.cc +++ b/ash/system/holding_space/holding_space_tray_bubble.cc
@@ -83,11 +83,13 @@ private: // views::View: void ChildPreferredSizeChanged(views::View* child) override { - PreferredSizeChanged(); + if (GetWidget()) + PreferredSizeChanged(); } void ChildVisibilityChanged(views::View* child) override { - PreferredSizeChanged(); + if (GetWidget()) + PreferredSizeChanged(); } views::BoxLayout* layout_ = nullptr; @@ -133,6 +135,13 @@ std::make_unique<RecentFilesContainer>(&delegate_)); SetupViewLayer(recent_files_container_); + // Populate both containers if holding space model has already been attached. + HoldingSpaceModel* model = HoldingSpaceController::Get()->model(); + if (model) { + pinned_files_container_->OnHoldingSpaceModelAttached(model); + recent_files_container_->OnHoldingSpaceModelAttached(model); + } + // Show the bubble. bubble_wrapper_ = std::make_unique<TrayBubbleWrapper>( holding_space_tray, bubble_view, false /* is_persistent */);
diff --git a/ash/system/holding_space/pinned_files_container.cc b/ash/system/holding_space/pinned_files_container.cc index 0b6d061f..edaf505 100644 --- a/ash/system/holding_space/pinned_files_container.cc +++ b/ash/system/holding_space/pinned_files_container.cc
@@ -10,6 +10,8 @@ #include "ash/public/cpp/holding_space/holding_space_controller.h" #include "ash/public/cpp/holding_space/holding_space_item.h" #include "ash/public/cpp/holding_space/holding_space_model.h" +#include "ash/public/cpp/holding_space/holding_space_prefs.h" +#include "ash/session/session_controller_impl.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" #include "ash/system/holding_space/holding_space_item_chip_view.h" @@ -17,6 +19,7 @@ #include "ash/system/tray/tray_constants.h" #include "ash/system/tray/tray_popup_item_style.h" #include "base/optional.h" +#include "components/prefs/pref_service.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/border.h" #include "ui/views/controls/label.h" @@ -29,6 +32,15 @@ namespace { +bool HasEverPinnedHoldingSpaceItem() { + PrefService* active_pref_service = + Shell::Get()->session_controller()->GetActivePrefService(); + return active_pref_service + ? holding_space_prefs::GetTimeOfFirstPin(active_pref_service) + .has_value() + : false; +} + // HoldingSpaceScrollView ------------------------------------------------------ class HoldingSpaceScrollView : public views::ScrollView, @@ -84,16 +96,18 @@ TrayPopupItemStyle(TrayPopupItemStyle::FontStyle::SUB_HEADER) .SetupLabel(title_label); - empty_prompt_label_ = AddChildView(std::make_unique<views::Label>( - l10n_util::GetStringUTF16(IDS_ASH_HOLDING_SPACE_PINNED_EMPTY_PROMPT))); - empty_prompt_label_->SetHorizontalAlignment( - gfx::HorizontalAlignment::ALIGN_LEFT); - empty_prompt_label_->SetMultiLine(true); - empty_prompt_label_->SetPaintToLayer(); - empty_prompt_label_->layer()->SetFillsBoundsOpaquely(false); + if (!HasEverPinnedHoldingSpaceItem()) { + empty_prompt_label_ = AddChildView(std::make_unique<views::Label>( + l10n_util::GetStringUTF16(IDS_ASH_HOLDING_SPACE_PINNED_EMPTY_PROMPT))); + empty_prompt_label_->SetHorizontalAlignment( + gfx::HorizontalAlignment::ALIGN_LEFT); + empty_prompt_label_->SetMultiLine(true); + empty_prompt_label_->SetPaintToLayer(); + empty_prompt_label_->layer()->SetFillsBoundsOpaquely(false); - TrayPopupItemStyle(TrayPopupItemStyle::FontStyle::DETAILED_VIEW_LABEL) - .SetupLabel(empty_prompt_label_); + TrayPopupItemStyle(TrayPopupItemStyle::FontStyle::DETAILED_VIEW_LABEL) + .SetupLabel(empty_prompt_label_); + } auto* scroll_view = AddChildView(std::make_unique<HoldingSpaceScrollView>()); scroll_view->SetBackgroundColor(base::nullopt); @@ -105,10 +119,11 @@ item_chips_container_ = scroll_view->SetContents( std::make_unique<HoldingSpaceItemChipsContainer>()); - item_chips_container_->SetVisible(false); - if (HoldingSpaceController::Get()->model()) - OnHoldingSpaceModelAttached(HoldingSpaceController::Get()->model()); + if (HasEverPinnedHoldingSpaceItem()) + SetVisible(false); + else + item_chips_container_->SetVisible(false); } PinnedFilesContainer::~PinnedFilesContainer() = default; @@ -120,15 +135,15 @@ item_chips_container_->children().size() != 1u) { return; } - if (details.is_add) { - // `item_chips_container_` is becoming non-empty. + + if (details.is_add && empty_prompt_label_ && + empty_prompt_label_->GetVisible()) { + // An item has been added to `item_chips_container_` for the first time. empty_prompt_label_->SetVisible(false); item_chips_container_->SetVisible(true); - } else { - // `item_chips_container_` is becoming empty. - item_chips_container_->SetVisible(false); - empty_prompt_label_->SetVisible(true); } + + SetVisible(details.is_add); } void PinnedFilesContainer::AddHoldingSpaceItemView(
diff --git a/ash/system/holding_space/recent_files_container.cc b/ash/system/holding_space/recent_files_container.cc index 79568fed..708165e0 100644 --- a/ash/system/holding_space/recent_files_container.cc +++ b/ash/system/holding_space/recent_files_container.cc
@@ -122,9 +122,6 @@ downloads_container_ = AddChildView(std::make_unique<HoldingSpaceItemChipsContainer>()); downloads_container_->SetVisible(false); - - if (HoldingSpaceController::Get()->model()) - OnHoldingSpaceModelAttached(HoldingSpaceController::Get()->model()); } RecentFilesContainer::~RecentFilesContainer() = default;
diff --git a/ash/system/phonehub/phone_hub_notification_controller_unittest.cc b/ash/system/phonehub/phone_hub_notification_controller_unittest.cc index 85e01eae..b9506f58 100644 --- a/ash/system/phonehub/phone_hub_notification_controller_unittest.cc +++ b/ash/system/phonehub/phone_hub_notification_controller_unittest.cc
@@ -4,6 +4,7 @@ #include "ash/system/phonehub/phone_hub_notification_controller.h" +#include "ash/public/cpp/test/test_system_tray_client.h" #include "ash/shell.h" #include "ash/system/message_center/message_center_controller.h" #include "ash/test/ash_test_base.h" @@ -169,7 +170,13 @@ } TEST_F(PhoneHubNotificationControllerTest, ClickSettings) { - // TODO(tengs): Test this case once it is implemented. + notification_manager_.SetNotificationsInternal(fake_notifications_); + EXPECT_TRUE( + message_center_->FindVisibleNotificationById(kCrOSNotificationId0)); + EXPECT_EQ(0, GetSystemTrayClient()->show_connected_devices_settings_count()); + + message_center_->ClickOnSettingsButton(kCrOSNotificationId0); + EXPECT_EQ(1, GetSystemTrayClient()->show_connected_devices_settings_count()); } TEST_F(PhoneHubNotificationControllerTest, CancelReply) {
diff --git a/ash/system/tray/tray_background_view.cc b/ash/system/tray/tray_background_view.cc index 4a64f5b..d866871 100644 --- a/ash/system/tray/tray_background_view.cc +++ b/ash/system/tray/tray_background_view.cc
@@ -162,10 +162,9 @@ DCHECK(shelf_); SetNotifyEnterExitOnChild(true); - SetInkDropBaseColor( - DeprecatedGetShelfInkDropBaseColor(kDefaultShelfInkDropColor)); + SetInkDropBaseColor(DeprecatedGetInkDropBaseColor(kDefaultShelfInkDropColor)); SetInkDropVisibleOpacity( - DeprecatedGetShelfInkDropOpacity(kDefaultShelfInkDropOpacity)); + DeprecatedGetInkDropOpacity(kDefaultShelfInkDropOpacity)); SetInkDropMode(InkDropMode::ON_NO_GESTURE_HANDLER); SetLayoutManager(std::make_unique<views::FillLayout>());
diff --git a/ash/wallpaper/wallpaper_window_state_manager.cc b/ash/wallpaper/wallpaper_window_state_manager.cc index e85b298..db29ae8 100644 --- a/ash/wallpaper/wallpaper_window_state_manager.cc +++ b/ash/wallpaper/wallpaper_window_state_manager.cc
@@ -24,7 +24,7 @@ DesksMruType::kActiveDesk)); for (auto* window : mru_windows) { if (WindowState::Get(window)->GetStateType() != - WindowStateType::kMinimized) { + chromeos::WindowStateType::kMinimized) { WindowState::Get(window)->Activate(); return; }
diff --git a/ash/wm/always_on_top_controller.cc b/ash/wm/always_on_top_controller.cc index 37cb4eb..ae420df0 100644 --- a/ash/wm/always_on_top_controller.cc +++ b/ash/wm/always_on_top_controller.cc
@@ -126,7 +126,7 @@ void AlwaysOnTopController::OnPreWindowStateTypeChange( WindowState* window_state, - WindowStateType old_type) { + chromeos::WindowStateType old_type) { ReparentWindow(window_state->window()); }
diff --git a/ash/wm/always_on_top_controller.h b/ash/wm/always_on_top_controller.h index 0dd0f36..d7dc848 100644 --- a/ash/wm/always_on_top_controller.h +++ b/ash/wm/always_on_top_controller.h
@@ -49,7 +49,7 @@ // Overridden from WindowStateObserver: void OnPreWindowStateTypeChange(WindowState* window_state, - WindowStateType old_type) override; + chromeos::WindowStateType old_type) override; aura::Window* always_on_top_container_; aura::Window* pip_container_;
diff --git a/ash/wm/base_state.cc b/ash/wm/base_state.cc index 3db10e6..d8c094e 100644 --- a/ash/wm/base_state.cc +++ b/ash/wm/base_state.cc
@@ -6,7 +6,6 @@ #include "ash/public/cpp/window_animation_types.h" #include "ash/public/cpp/window_properties.h" -#include "ash/public/cpp/window_state_type.h" #include "ash/screen_util.h" #include "ash/shell.h" #include "ash/wm/overview/overview_controller.h" @@ -15,11 +14,14 @@ #include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "ash/wm/window_positioning_utils.h" #include "ash/wm/wm_event.h" +#include "chromeos/ui/base/window_state_type.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/window.h" namespace ash { +using ::chromeos::WindowStateType; + BaseState::BaseState(WindowStateType initial_state_type) : state_type_(initial_state_type) {} BaseState::~BaseState() = default;
diff --git a/ash/wm/base_state.h b/ash/wm/base_state.h index 92b259f..ed374193 100644 --- a/ash/wm/base_state.h +++ b/ash/wm/base_state.h
@@ -18,16 +18,17 @@ // BaseState implements the common framework for WindowState::State. class BaseState : public WindowState::State { public: - explicit BaseState(WindowStateType initial_state_type); + explicit BaseState(chromeos::WindowStateType initial_state_type); ~BaseState() override; // WindowState::State: void OnWMEvent(WindowState* window_state, const WMEvent* event) override; - WindowStateType GetType() const override; + chromeos::WindowStateType GetType() const override; protected: - // Returns the WindowStateType corresponds to the WMEvent type. - static WindowStateType GetStateForTransitionEvent(const WMEvent* event); + // Returns the chromeos::WindowStateType corresponds to the WMEvent type. + static chromeos::WindowStateType GetStateForTransitionEvent( + const WMEvent* event); static void CenterWindow(WindowState* window_state); static void CycleSnap(WindowState* window_state, WMEventType event); @@ -51,14 +52,15 @@ // Shows/Hides window when minimized state changes. void UpdateMinimizedState(WindowState* window_state, - WindowStateType previous_state_type); + chromeos::WindowStateType previous_state_type); // Returns the window bounds for snapped window state. - gfx::Rect GetSnappedWindowBoundsInParent(aura::Window* window, - const WindowStateType state_type); + gfx::Rect GetSnappedWindowBoundsInParent( + aura::Window* window, + const chromeos::WindowStateType state_type); // The current type of the window. - WindowStateType state_type_; + chromeos::WindowStateType state_type_; private: DISALLOW_COPY_AND_ASSIGN(BaseState);
diff --git a/ash/wm/client_controlled_state.cc b/ash/wm/client_controlled_state.cc index 1d410ea..0dc4484e 100644 --- a/ash/wm/client_controlled_state.cc +++ b/ash/wm/client_controlled_state.cc
@@ -6,7 +6,6 @@ #include "ash/public/cpp/shell_window_ids.h" #include "ash/public/cpp/window_animation_types.h" -#include "ash/public/cpp/window_state_type.h" #include "ash/root_window_controller.h" #include "ash/screen_util.h" #include "ash/shell.h" @@ -19,6 +18,7 @@ #include "ash/wm/window_state_delegate.h" #include "ash/wm/window_state_util.h" #include "ash/wm/wm_event.h" +#include "chromeos/ui/base/window_state_type.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/window.h" #include "ui/aura/window_delegate.h" @@ -29,6 +29,9 @@ namespace ash { namespace { + +using ::chromeos::WindowStateType; + // |kMinimumOnScreenArea + 1| is used to avoid adjusting loop. constexpr int kClientControlledWindowMinimumOnScreenArea = kMinimumOnScreenArea + 1;
diff --git a/ash/wm/client_controlled_state.h b/ash/wm/client_controlled_state.h index a3da5f8a..2e7b8949 100644 --- a/ash/wm/client_controlled_state.h +++ b/ash/wm/client_controlled_state.h
@@ -15,9 +15,6 @@ #include "ui/gfx/geometry/rect.h" namespace ash { -namespace mojom { -enum class WindowStateType; -} // ClientControlledState delegates the window state transition and // bounds control to the client. Its window state and bounds are @@ -31,15 +28,16 @@ // Handles the state change of |window_state| to |requested_state|. // Delegate may decide to ignore the state change, proceed with the state // change, or can move to a different state. - virtual void HandleWindowStateRequest(WindowState* window_state, - WindowStateType requested_state) = 0; + virtual void HandleWindowStateRequest( + WindowState* window_state, + chromeos::WindowStateType requested_state) = 0; // Handles the bounds change request for |window_state|. The bounds change // might come from a state change request |requested_state| (currently it // should only be a snapped window state). Delegate may choose to ignore the // request, set the given bounds, or set the different bounds. virtual void HandleBoundsRequest( WindowState* window_state, - WindowStateType requested_state, + chromeos::WindowStateType requested_state, const gfx::Rect& requested_bounds_in_display, int64_t display_id) = 0; }; @@ -97,11 +95,12 @@ // within the same desktop mode. Returns true if the state has changed, or // false otherwise. bool EnterNextState(WindowState* window_state, - WindowStateType next_state_type); + chromeos::WindowStateType next_state_type); private: - WindowStateType GetResolvedNextWindowStateType(WindowState* window_state, - const WMEvent* event); + chromeos::WindowStateType GetResolvedNextWindowStateType( + WindowState* window_state, + const WMEvent* event); std::unique_ptr<Delegate> delegate_;
diff --git a/ash/wm/client_controlled_state_unittest.cc b/ash/wm/client_controlled_state_unittest.cc index 6724557..bd0cb44 100644 --- a/ash/wm/client_controlled_state_unittest.cc +++ b/ash/wm/client_controlled_state_unittest.cc
@@ -25,6 +25,8 @@ namespace ash { namespace { +using ::chromeos::WindowStateType; + constexpr gfx::Rect kInitialBounds(0, 0, 100, 100); class TestClientControlledStateDelegate @@ -41,13 +43,13 @@ } void HandleBoundsRequest(WindowState* window_state, - ash::WindowStateType requested_state, + WindowStateType requested_state, const gfx::Rect& bounds, int64_t display_id) override { requested_bounds_ = bounds; if (requested_state != window_state->GetStateType()) { - DCHECK(requested_state == ash::WindowStateType::kLeftSnapped || - requested_state == ash::WindowStateType::kRightSnapped); + DCHECK(requested_state == WindowStateType::kLeftSnapped || + requested_state == WindowStateType::kRightSnapped); old_state_ = window_state->GetStateType(); new_state_ = requested_state; }
diff --git a/ash/wm/default_state.cc b/ash/wm/default_state.cc index ab67b0e..15bb88f 100644 --- a/ash/wm/default_state.cc +++ b/ash/wm/default_state.cc
@@ -7,7 +7,6 @@ #include "ash/public/cpp/metrics_util.h" #include "ash/public/cpp/shell_window_ids.h" #include "ash/public/cpp/window_animation_types.h" -#include "ash/public/cpp/window_state_type.h" #include "ash/root_window_controller.h" #include "ash/screen_util.h" #include "ash/shell.h" @@ -20,6 +19,7 @@ #include "ash/wm/workspace_controller.h" #include "base/bind.h" #include "base/metrics/histogram_macros.h" +#include "chromeos/ui/base/window_state_type.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/window.h" #include "ui/aura/window_delegate.h" @@ -32,6 +32,8 @@ namespace ash { namespace { +using ::chromeos::WindowStateType; + // This specifies how much percent (30%) of a window rect // must be visible when the window is added to the workspace. const float kMinimumPercentOnScreenArea = 0.3f; @@ -92,8 +94,8 @@ // If previous state is unminimized but window state is minimized, sync window // state to unminimized. - if (window_state->IsMinimized() && - !IsMinimizedWindowStateType(state_in_previous_mode->GetType())) { + if (window_state->IsMinimized() && !chromeos::IsMinimizedWindowStateType( + state_in_previous_mode->GetType())) { aura::Window* window = window_state->window(); window->SetProperty( aura::client::kShowStateKey,
diff --git a/ash/wm/default_state.h b/ash/wm/default_state.h index 31b9937..c6f1321 100644 --- a/ash/wm/default_state.h +++ b/ash/wm/default_state.h
@@ -21,7 +21,7 @@ // DefaultState implements Ash behavior without state machine. class DefaultState : public BaseState { public: - explicit DefaultState(WindowStateType initial_state_type); + explicit DefaultState(chromeos::WindowStateType initial_state_type); ~DefaultState() override; // WindowState::State overrides: @@ -49,7 +49,7 @@ // Enters next state. This is used when the state moves from one to another // within the same desktop mode. void EnterToNextState(WindowState* window_state, - WindowStateType next_state_type); + chromeos::WindowStateType next_state_type); // Reenters the current state. This is called when migrating from // previous desktop mode, and the window's state needs to re-construct the @@ -59,7 +59,7 @@ // Animates to new window bounds based on the current and previous state type. void UpdateBoundsFromState(WindowState* window_state, - WindowStateType old_state_type); + chromeos::WindowStateType old_state_type); // Updates the window bounds for display bounds, or display work area bounds // changes.
diff --git a/ash/wm/desks/desks_unittests.cc b/ash/wm/desks/desks_unittests.cc index e5c972b..04635aa 100644 --- a/ash/wm/desks/desks_unittests.cc +++ b/ash/wm/desks/desks_unittests.cc
@@ -2748,7 +2748,8 @@ WindowState* win0_state = WindowState::Get(win0.get()); WMEvent snap_to_left(WM_EVENT_CYCLE_SNAP_LEFT); win0_state->OnWMEvent(&snap_to_left); - EXPECT_EQ(WindowStateType::kLeftSnapped, win0_state->GetStateType()); + EXPECT_EQ(chromeos::WindowStateType::kLeftSnapped, + win0_state->GetStateType()); // Switch to |desk_2| and then back to |desk_1|. Verify that neither split // view nor overview arises.
diff --git a/ash/wm/drag_details.h b/ash/wm/drag_details.h index 5a8bd99c..5952d1c 100644 --- a/ash/wm/drag_details.h +++ b/ash/wm/drag_details.h
@@ -5,7 +5,7 @@ #ifndef ASH_WM_DRAG_DETAILS_H_ #define ASH_WM_DRAG_DETAILS_H_ -#include "ash/public/cpp/window_state_type.h" +#include "chromeos/ui/base/window_state_type.h" #include "ui/gfx/geometry/point_f.h" #include "ui/gfx/geometry/rect.h" #include "ui/wm/public/window_move_client.h" @@ -24,7 +24,7 @@ ::wm::WindowMoveSource source); ~DragDetails(); - const WindowStateType initial_state_type; + const chromeos::WindowStateType initial_state_type; // Initial bounds of the window in parent coordinates. const gfx::Rect initial_bounds_in_parent;
diff --git a/ash/wm/gestures/back_gesture/back_gesture_affordance.cc b/ash/wm/gestures/back_gesture/back_gesture_affordance.cc index 626854a..c66cbb2 100644 --- a/ash/wm/gestures/back_gesture/back_gesture_affordance.cc +++ b/ash/wm/gestures/back_gesture/back_gesture_affordance.cc
@@ -167,7 +167,7 @@ kControlBackgroundColorActive, kBackgroundColorAfterActivated) : DeprecatedGetBaseLayerColor( - AshColorProvider::BaseLayerType::kTransparent80, + AshColorProvider::BaseLayerType::kOpaque, kBackgroundColorBeforeActivated)); canvas->DrawCircle(center_point, kBackgroundRadius, bg_flags);
diff --git a/ash/wm/gestures/back_gesture/back_gesture_contextual_nudge.cc b/ash/wm/gestures/back_gesture/back_gesture_contextual_nudge.cc index 91cdaa13b..4d28d0d 100644 --- a/ash/wm/gestures/back_gesture/back_gesture_contextual_nudge.cc +++ b/ash/wm/gestures/back_gesture/back_gesture_contextual_nudge.cc
@@ -9,6 +9,9 @@ #include "ash/shelf/contextual_tooltip.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" +#include "ash/style/ash_color_provider.h" +#include "ash/style/default_color_constants.h" +#include "ash/style/default_colors.h" #include "base/callback.h" #include "base/i18n/rtl.h" #include "base/timer/timer.h" @@ -32,21 +35,12 @@ // Radius of the circle in the middle of the contextual nudge. constexpr int kCircleRadius = 20; -// Color of the circle in the middle of the contextual nudge. -constexpr SkColor kCircleColor = SK_ColorWHITE; - // Width of the circle that inside the screen at the beginning. constexpr int kCircleInsideScreenWidth = 12; // Padding between the circle and the label. constexpr int kPaddingBetweenCircleAndLabel = 8; -// Color of the label. -constexpr SkColor kLabelColor = gfx::kGoogleGrey200; - -// Color of the label background. -constexpr SkColor kLabelBackgroundColor = SkColorSetA(SK_ColorBLACK, 0xDE); - // Line height of the label. constexpr int kLabelLineHeight = 18; @@ -193,7 +187,8 @@ label_ = AddChildView(std::make_unique<views::Label>()); label_->SetBackgroundColor(SK_ColorTRANSPARENT); - label_->SetEnabledColor(kLabelColor); + label_->SetEnabledColor(AshColorProvider::Get()->GetContentLayerColor( + AshColorProvider::ContentLayerType::kTextColorPrimary)); label_->SetText(l10n_util::GetStringUTF16( base::i18n::IsRTL() ? IDS_ASH_BACK_GESTURE_CONTEXTUAL_NUDGE_RTL : IDS_ASH_BACK_GESTURE_CONTEXTUAL_NUDGE)); @@ -255,7 +250,8 @@ cc::PaintFlags circle_flags; circle_flags.setAntiAlias(true); circle_flags.setStyle(cc::PaintFlags::kFill_Style); - circle_flags.setColor(kCircleColor); + circle_flags.setColor(DeprecatedGetBaseLayerColor( + AshColorProvider::BaseLayerType::kOpaque, kCircleColor)); gfx::ShadowValues shadows; shadows.push_back(gfx::ShadowValue( gfx::Vector2d(0, kBackNudgeShadowOffsetY1), @@ -280,7 +276,8 @@ cc::PaintFlags round_rect_flags; round_rect_flags.setStyle(cc::PaintFlags::kFill_Style); round_rect_flags.setAntiAlias(true); - round_rect_flags.setColor(kLabelBackgroundColor); + round_rect_flags.setColor(DeprecatedGetBaseLayerColor( + AshColorProvider::BaseLayerType::kOpaque, kLabelBackgroundColor)); gfx::Rect label_bounds(label_->GetMirroredBounds()); label_bounds.Inset(/*horizontal=*/-kLabelCornerRadius, /*vertical=*/-kLabelTopBottomInset);
diff --git a/ash/wm/lock_window_state.cc b/ash/wm/lock_window_state.cc index d28a23a..bfd169a4 100644 --- a/ash/wm/lock_window_state.cc +++ b/ash/wm/lock_window_state.cc
@@ -24,6 +24,8 @@ namespace ash { +using ::chromeos::WindowStateType; + LockWindowState::LockWindowState(aura::Window* window, bool exclude_shelf) : current_state_type_(WindowState::Get(window)->GetStateType()), exclude_shelf_(exclude_shelf) {}
diff --git a/ash/wm/lock_window_state.h b/ash/wm/lock_window_state.h index 4ac6f7b..b31dfe9 100644 --- a/ash/wm/lock_window_state.h +++ b/ash/wm/lock_window_state.h
@@ -29,7 +29,7 @@ // WindowState::State overrides: void OnWMEvent(WindowState* window_state, const WMEvent* event) override; - WindowStateType GetType() const override; + chromeos::WindowStateType GetType() const override; void AttachState(WindowState* window_state, WindowState::State* previous_state) override; void DetachState(WindowState* window_state) override; @@ -42,11 +42,13 @@ // Updates the window to |new_state_type| and resulting bounds: // Either full screen, maximized centered or minimized. If the state does not // change, only the bounds will be changed. - void UpdateWindow(WindowState* window_state, WindowStateType new_state_type); + void UpdateWindow(WindowState* window_state, + chromeos::WindowStateType new_state_type); // Depending on the capabilities of the window we either return // |WindowStateType::kMaximized| or |WindowStateType::kNormal|. - WindowStateType GetMaximizedOrCenteredWindowType(WindowState* window_state); + chromeos::WindowStateType GetMaximizedOrCenteredWindowType( + WindowState* window_state); // Returns boudns to be used for the provided window. gfx::Rect GetWindowBounds(aura::Window* window); @@ -56,7 +58,7 @@ // The current state type. Due to the nature of this state, this can only be // WM_STATE_TYPE{NORMAL, MINIMIZED, MAXIMIZED}. - WindowStateType current_state_type_; + chromeos::WindowStateType current_state_type_; // Restrict window size to the work area defined by the shelf - i.e. window // bounds exclude system shelf bounds.
diff --git a/ash/wm/overview/overview_item.cc b/ash/wm/overview/overview_item.cc index f509e0b..a90fd6a 100644 --- a/ash/wm/overview/overview_item.cc +++ b/ash/wm/overview/overview_item.cc
@@ -11,7 +11,6 @@ #include "ash/accessibility/accessibility_controller_impl.h" #include "ash/public/cpp/shell_window_ids.h" #include "ash/public/cpp/window_properties.h" -#include "ash/public/cpp/window_state_type.h" #include "ash/scoped_animation_disabler.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" @@ -42,6 +41,7 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/metrics/user_metrics.h" +#include "chromeos/ui/base/window_state_type.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/aura/client/aura_constants.h" #include "ui/base/l10n/l10n_util.h" @@ -62,6 +62,8 @@ namespace { +using ::chromeos::WindowStateType; + // Opacity for fading out during closing a window. constexpr float kClosingItemOpacity = 0.8f; @@ -1091,8 +1093,8 @@ } WindowStateType new_type = window_state->GetStateType(); - if (IsMinimizedWindowStateType(old_type) == - IsMinimizedWindowStateType(new_type)) { + if (chromeos::IsMinimizedWindowStateType(old_type) == + chromeos::IsMinimizedWindowStateType(new_type)) { return; }
diff --git a/ash/wm/overview/overview_item.h b/ash/wm/overview/overview_item.h index c472d4c8..2a50d99 100644 --- a/ash/wm/overview/overview_item.h +++ b/ash/wm/overview/overview_item.h
@@ -215,9 +215,9 @@ // WindowStateObserver: void OnPreWindowStateTypeChange(WindowState* window_state, - WindowStateType old_type) override; + chromeos::WindowStateType old_type) override; void OnPostWindowStateTypeChange(WindowState* window_state, - WindowStateType old_type) override; + chromeos::WindowStateType old_type) override; // Returns the root window on which this item is shown. aura::Window* root_window() { return root_window_; }
diff --git a/ash/wm/overview/overview_session.cc b/ash/wm/overview/overview_session.cc index 612a61e..6679569 100644 --- a/ash/wm/overview/overview_session.cc +++ b/ash/wm/overview/overview_session.cc
@@ -105,7 +105,7 @@ // WindowStateObserver: void OnPostWindowStateTypeChange(WindowState* window_state, - WindowStateType) override { + chromeos::WindowStateType) override { RemoveAllObservers(); std::move(on_post_window_state_changed_).Run(window_state); delete this;
diff --git a/ash/wm/overview/overview_session_unittest.cc b/ash/wm/overview/overview_session_unittest.cc index 86e0c2d..2eae3f2 100644 --- a/ash/wm/overview/overview_session_unittest.cc +++ b/ash/wm/overview/overview_session_unittest.cc
@@ -106,6 +106,8 @@ namespace ash { namespace { +using ::chromeos::WindowStateType; + constexpr const char kActiveWindowChangedFromOverview[] = "WindowSelector_ActiveWindowChanged";
diff --git a/ash/wm/pip/pip_window_resizer_unittest.cc b/ash/wm/pip/pip_window_resizer_unittest.cc index 12c4d2d..1c03415 100644 --- a/ash/wm/pip/pip_window_resizer_unittest.cc +++ b/ash/wm/pip/pip_window_resizer_unittest.cc
@@ -35,6 +35,8 @@ namespace { +using ::chromeos::WindowStateType; + // WindowState based on a given initial state. Records the last resize bounds. class FakeWindowState : public WindowState::State { public:
diff --git a/ash/wm/splitview/split_view_controller.cc b/ash/wm/splitview/split_view_controller.cc index cfa16d6..398bba7 100644 --- a/ash/wm/splitview/split_view_controller.cc +++ b/ash/wm/splitview/split_view_controller.cc
@@ -66,6 +66,8 @@ namespace { +using ::chromeos::WindowStateType; + // Three fixed position ratios of the divider, which means the divider can // always be moved to these three positions. constexpr float kFixedPositionRatios[] = {0.f, 0.5f, 1.0f};
diff --git a/ash/wm/splitview/split_view_controller.h b/ash/wm/splitview/split_view_controller.h index ea11bbe..b1721b58 100644 --- a/ash/wm/splitview/split_view_controller.h +++ b/ash/wm/splitview/split_view_controller.h
@@ -239,7 +239,7 @@ // WindowStateObserver: void OnPostWindowStateTypeChange(WindowState* window_state, - WindowStateType old_type) override; + chromeos::WindowStateType old_type) override; // ShellObserver: void OnPinnedStateChanged(aura::Window* pinned_window) override;
diff --git a/ash/wm/splitview/split_view_controller_unittest.cc b/ash/wm/splitview/split_view_controller_unittest.cc index 03672f4..5ddea92 100644 --- a/ash/wm/splitview/split_view_controller_unittest.cc +++ b/ash/wm/splitview/split_view_controller_unittest.cc
@@ -4619,7 +4619,7 @@ // Switch to clamshell mode and check that |snapped_window| keeps its snapped // window state. Shell::Get()->tablet_mode_controller()->SetEnabledForTest(false); - EXPECT_EQ(WindowStateType::kLeftSnapped, + EXPECT_EQ(chromeos::WindowStateType::kLeftSnapped, WindowState::Get(snapped_window.get())->GetStateType()); }
diff --git a/ash/wm/splitview/split_view_utils.cc b/ash/wm/splitview/split_view_utils.cc index 90aad1f..8c2f337 100644 --- a/ash/wm/splitview/split_view_utils.cc +++ b/ash/wm/splitview/split_view_utils.cc
@@ -33,6 +33,8 @@ namespace { +using ::chromeos::WindowStateType; + // The animation speed at which the highlights fade in or out. constexpr base::TimeDelta kHighlightsFadeInOut = base::TimeDelta::FromMilliseconds(250);
diff --git a/ash/wm/tablet_mode/tablet_mode_window_manager.cc b/ash/wm/tablet_mode/tablet_mode_window_manager.cc index 9a83cc8..b0ccb205 100644 --- a/ash/wm/tablet_mode/tablet_mode_window_manager.cc +++ b/ash/wm/tablet_mode/tablet_mode_window_manager.cc
@@ -43,6 +43,8 @@ namespace { +using ::chromeos::WindowStateType; + // This function is called to check if window[i] is eligible to be carried over // to split view mode during clamshell <-> tablet mode transition or multi-user // switch transition. Returns true if windows[i] exists, is on |root_window|,
diff --git a/ash/wm/tablet_mode/tablet_mode_window_manager.h b/ash/wm/tablet_mode/tablet_mode_window_manager.h index b34cd06..bda7adc5 100644 --- a/ash/wm/tablet_mode/tablet_mode_window_manager.h +++ b/ash/wm/tablet_mode/tablet_mode_window_manager.h
@@ -111,18 +111,18 @@ // current bounds or state type of |window|. gfx::Rect GetWindowBoundsInScreen(aura::Window* window, bool from_clamshell) const; - WindowStateType GetWindowStateType(aura::Window* window, - bool from_clamshell) const; + chromeos::WindowStateType GetWindowStateType(aura::Window* window, + bool from_clamshell) const; // Returns the windows that are going to be carried over to split view during // clamshell <-> tablet transition or multi-user switch transition. - base::flat_map<aura::Window*, WindowStateType> GetCarryOverWindowsInSplitView( - bool clamshell_to_tablet) const; + base::flat_map<aura::Window*, chromeos::WindowStateType> + GetCarryOverWindowsInSplitView(bool clamshell_to_tablet) const; // Calculates the split view divider position that will best preserve the // bounds of the windows. int CalculateCarryOverDividerPosition( - const base::flat_map<aura::Window*, WindowStateType>& + const base::flat_map<aura::Window*, chromeos::WindowStateType>& windows_in_splitview, bool clamshell_to_tablet) const; @@ -136,7 +136,8 @@ // windows will be carried over to clamshell split view. |was_in_overview| // indicates whether overview is active before entering clamshell mode. void ArrangeWindowsForClamshellMode( - base::flat_map<aura::Window*, WindowStateType> windows_in_splitview, + base::flat_map<aura::Window*, chromeos::WindowStateType> + windows_in_splitview, bool was_in_overview); // If the given window should be handled by us, this function will add it to
diff --git a/ash/wm/tablet_mode/tablet_mode_window_manager_unittest.cc b/ash/wm/tablet_mode/tablet_mode_window_manager_unittest.cc index 064cc18..ec7e5089 100644 --- a/ash/wm/tablet_mode/tablet_mode_window_manager_unittest.cc +++ b/ash/wm/tablet_mode/tablet_mode_window_manager_unittest.cc
@@ -14,7 +14,6 @@ #include "ash/public/cpp/shelf_prefs.h" #include "ash/public/cpp/test/shell_test_api.h" #include "ash/public/cpp/window_properties.h" -#include "ash/public/cpp/window_state_type.h" #include "ash/root_window_controller.h" #include "ash/screen_util.h" #include "ash/session/session_controller_impl.h" @@ -48,6 +47,7 @@ #include "base/test/scoped_feature_list.h" #include "base/values.h" #include "chromeos/constants/chromeos_switches.h" +#include "chromeos/ui/base/window_state_type.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/test/test_window_delegate.h" #include "ui/aura/test/test_windows.h" @@ -61,6 +61,8 @@ namespace ash { +using ::chromeos::WindowStateType; + // A helper function to set the shelf auto-hide preference. This has the same // effect as the user toggling the shelf context menu option. void SetShelfAutoHideBehaviorPref(int64_t display_id,
diff --git a/ash/wm/tablet_mode/tablet_mode_window_state.cc b/ash/wm/tablet_mode/tablet_mode_window_state.cc index 52e1997c..8a3b066 100644 --- a/ash/wm/tablet_mode/tablet_mode_window_state.cc +++ b/ash/wm/tablet_mode/tablet_mode_window_state.cc
@@ -11,7 +11,6 @@ #include "ash/public/cpp/shell_window_ids.h" #include "ash/public/cpp/window_animation_types.h" #include "ash/public/cpp/window_properties.h" -#include "ash/public/cpp/window_state_type.h" #include "ash/screen_util.h" #include "ash/shell.h" #include "ash/wm/desks/desks_controller.h" @@ -24,6 +23,7 @@ #include "ash/wm/window_state_util.h" #include "ash/wm/window_util.h" #include "ash/wm/wm_event.h" +#include "chromeos/ui/base/window_state_type.h" #include "ui/aura/window.h" #include "ui/aura/window_delegate.h" #include "ui/compositor/layer.h" @@ -34,6 +34,8 @@ namespace ash { namespace { +using ::chromeos::WindowStateType; + // Sets the restore bounds and show state overrides. These values take // precedence over the restore bounds and restore show state (if set). // If |bounds_override| is empty the values are cleared. @@ -46,7 +48,7 @@ return; } window->SetProperty(kRestoreWindowStateTypeOverrideKey, - ToWindowStateType(window_state_override)); + chromeos::ToWindowStateType(window_state_override)); window->SetProperty(kRestoreBoundsOverrideKey, new gfx::Rect(bounds_override)); }
diff --git a/ash/wm/tablet_mode/tablet_mode_window_state.h b/ash/wm/tablet_mode/tablet_mode_window_state.h index cf808e9..3d7c2e8 100644 --- a/ash/wm/tablet_mode/tablet_mode_window_state.h +++ b/ash/wm/tablet_mode/tablet_mode_window_state.h
@@ -53,7 +53,7 @@ // WindowState::State overrides: void OnWMEvent(WindowState* window_state, const WMEvent* event) override; - WindowStateType GetType() const override; + chromeos::WindowStateType GetType() const override; void AttachState(WindowState* window_state, WindowState::State* previous_state) override; void DetachState(WindowState* window_state) override; @@ -69,19 +69,21 @@ // change, only the bounds will be changed. If |animate| is set, the bound // change get animated. void UpdateWindow(WindowState* window_state, - WindowStateType new_state_type, + chromeos::WindowStateType new_state_type, bool animate); // Depending on the capabilities of the window we either return // |WindowStateType::kMaximized| or |WindowStateType::kNormal|. - WindowStateType GetMaximizedOrCenteredWindowType(WindowState* window_state); + chromeos::WindowStateType GetMaximizedOrCenteredWindowType( + WindowState* window_state); // If |target_state| is LEFT/RIGHT_SNAPPED and the window can be snapped, // returns |target_state|. Otherwise depending on the capabilities of the // window either returns |WindowStateType::kMaximized| or // |WindowStateType::kNormal|. - WindowStateType GetSnappedWindowStateType(WindowState* window_state, - WindowStateType target_state); + chromeos::WindowStateType GetSnappedWindowStateType( + WindowState* window_state, + chromeos::WindowStateType target_state); // Updates the bounds to the maximum possible bounds according to the current // window state. If |animated| is set we animate the change. @@ -100,7 +102,7 @@ // The state type to be established in AttachState(), unless // previous_state->GetType() is MAXIMIZED, MINIMIZED, FULLSCREEN, PINNED, or // TRUSTED_PINNED. - WindowStateType state_type_on_attach_; + chromeos::WindowStateType state_type_on_attach_; // Whether to animate in case of a bounds update when switching to // |state_type_on_attach_|. @@ -108,7 +110,7 @@ // The current state type. Due to the nature of this state, this can only be // WM_STATE_TYPE{NORMAL, MINIMIZED, MAXIMIZED}. - WindowStateType current_state_type_; + chromeos::WindowStateType current_state_type_; // If true, the state will not process events. bool ignore_wm_events_ = false;
diff --git a/ash/wm/toplevel_window_event_handler.cc b/ash/wm/toplevel_window_event_handler.cc index 1ca134c..badcbfe 100644 --- a/ash/wm/toplevel_window_event_handler.cc +++ b/ash/wm/toplevel_window_event_handler.cc
@@ -120,7 +120,7 @@ // WindowStateObserver overrides: void OnPreWindowStateTypeChange(WindowState* window_state, - WindowStateType type) override; + chromeos::WindowStateType type) override; private: ToplevelWindowEventHandler* handler_; @@ -173,7 +173,8 @@ } void ToplevelWindowEventHandler::ScopedWindowResizer:: - OnPreWindowStateTypeChange(WindowState* window_state, WindowStateType old) { + OnPreWindowStateTypeChange(WindowState* window_state, + chromeos::WindowStateType old) { handler_->CompleteDrag(DragResult::SUCCESS); }
diff --git a/ash/wm/toplevel_window_event_handler_unittest.cc b/ash/wm/toplevel_window_event_handler_unittest.cc index c4a9fba7..286797b 100644 --- a/ash/wm/toplevel_window_event_handler_unittest.cc +++ b/ash/wm/toplevel_window_event_handler_unittest.cc
@@ -53,6 +53,8 @@ namespace { +using ::chromeos::WindowStateType; + // A simple window delegate that returns the specified hit-test code when // requested and applies a minimum size constraint if there is one. class TestWindowDelegate : public aura::test::TestWindowDelegate {
diff --git a/ash/wm/window_state.cc b/ash/wm/window_state.cc index 8e1c02e8..31ed30d 100644 --- a/ash/wm/window_state.cc +++ b/ash/wm/window_state.cc
@@ -14,7 +14,6 @@ #include "ash/public/cpp/window_animation_types.h" #include "ash/public/cpp/window_pin_type.h" #include "ash/public/cpp/window_properties.h" -#include "ash/public/cpp/window_state_type.h" #include "ash/screen_util.h" #include "ash/shell.h" #include "ash/wm/collision_detection/collision_detection_utils.h" @@ -31,6 +30,7 @@ #include "base/auto_reset.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" +#include "chromeos/ui/base/window_state_type.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/layout_manager.h" #include "ui/aura/window.h" @@ -51,6 +51,8 @@ namespace ash { namespace { +using ::chromeos::WindowStateType; + bool IsTabletModeEnabled() { return Shell::Get()->tablet_mode_controller()->InTabletMode(); } @@ -563,7 +565,8 @@ autohide_shelf_when_maximized_or_fullscreen_(false), cached_z_order_(ui::ZOrderLevel::kNormal), ignore_property_change_(false), - current_state_(new DefaultState(ToWindowStateType(GetShowState()))) { + current_state_( + new DefaultState(chromeos::ToWindowStateType(GetShowState()))) { window_->AddObserver(this); UpdateWindowPropertiesFromStateType(); OnPrePipStateChange(WindowStateType::kDefault);
diff --git a/ash/wm/window_state.h b/ash/wm/window_state.h index d6504758..8e8075bc 100644 --- a/ash/wm/window_state.h +++ b/ash/wm/window_state.h
@@ -20,6 +20,10 @@ #include "ui/display/display.h" #include "ui/gfx/animation/tween.h" +namespace chromeos { +enum class WindowStateType; +} + namespace gfx { class Rect; } @@ -32,7 +36,6 @@ class WindowState; class WindowStateDelegate; class WindowStateObserver; -enum class WindowStateType; class WMEvent; // WindowState manages and defines ash specific window state and @@ -53,7 +56,7 @@ base::TimeDelta::FromMilliseconds(120); // A subclass of State class represents one of the window's states - // that corresponds to WindowStateType in Ash environment, e.g. + // that corresponds to chromeos::WindowStateType in Ash environment, e.g. // maximized, minimized or side snapped, as subclass. // Each subclass defines its own behavior and transition for each WMEvent. class State { @@ -64,7 +67,7 @@ // Update WindowState based on |event|. virtual void OnWMEvent(WindowState* window_state, const WMEvent* event) = 0; - virtual WindowStateType GetType() const = 0; + virtual chromeos::WindowStateType GetType() const = 0; // Gets called when the state object became active and the managed window // needs to be adjusted to the State's requirement. @@ -105,9 +108,9 @@ void SetDelegate(std::unique_ptr<WindowStateDelegate> delegate); // Returns the window's current ash state type. - // Refer to WindowStateType definition in wm_types.h as for why Ash + // Refer to chromeos::WindowStateType definition in wm_types.h as for why Ash // has its own state type. - WindowStateType GetStateType() const; + chromeos::WindowStateType GetStateType() const; // Predicates to check window state. bool IsMinimized() const; @@ -118,12 +121,13 @@ bool IsTrustedPinned() const; bool IsPip() const; - // True if the window's state type is WindowStateType::kMaximized, - // WindowStateType::kFullscreen or WindowStateType::kPinned. + // True if the window's state type is chromeos::WindowStateType::kMaximized, + // chromeos::WindowStateType::kFullscreen or + // chromeos::WindowStateType::kPinned. bool IsMaximizedOrFullscreenOrPinned() const; - // True if the window's state type is WindowStateType::kNormal or - // WindowStateType::kDefault. + // True if the window's state type is chromeos::WindowStateType::kNormal or + // chromeos::WindowStateType::kDefault. bool IsNormalStateType() const; bool IsNormalOrSnapped() const; @@ -406,8 +410,10 @@ // Note that this does not update the window bounds. void UpdateWindowPropertiesFromStateType(); - void NotifyPreStateTypeChange(WindowStateType old_window_state_type); - void NotifyPostStateTypeChange(WindowStateType old_window_state_type); + void NotifyPreStateTypeChange( + chromeos::WindowStateType old_window_state_type); + void NotifyPostStateTypeChange( + chromeos::WindowStateType old_window_state_type); // Sets |bounds| as is and ensure the layer is aligned with pixel boundary. void SetBoundsDirect(const gfx::Rect& bounds); @@ -429,11 +435,11 @@ // Called before the state change and update PIP related state, such as next // window animation type, upon state change. - void OnPrePipStateChange(WindowStateType old_window_state_type); + void OnPrePipStateChange(chromeos::WindowStateType old_window_state_type); // Called after the state change and update PIP related state, such as next // window animation type, upon state change. - void OnPostPipStateChange(WindowStateType old_window_state_type); + void OnPostPipStateChange(chromeos::WindowStateType old_window_state_type); // Update the PIP bounds if necessary. This may need to happen when the // display work area changes, or if system ui regions like the virtual
diff --git a/ash/wm/window_state_observer.h b/ash/wm/window_state_observer.h index 80ff2ec..6a01625 100644 --- a/ash/wm/window_state_observer.h +++ b/ash/wm/window_state_observer.h
@@ -7,10 +7,13 @@ #include "ash/ash_export.h" +namespace chromeos { +enum class WindowStateType; +} + namespace ash { class WindowState; -enum class WindowStateType; class ASH_EXPORT WindowStateObserver { public: @@ -26,13 +29,14 @@ // This is used to update the shell state such as work area so // that the window can use the correct environment to update its bounds. virtual void OnPreWindowStateTypeChange(WindowState* window_state, - WindowStateType old_type) {} + chromeos::WindowStateType old_type) {} // Called after the window's state has been updated. // This is used to update the shell state that depends on the updated // window bounds, such as shelf visibility. virtual void OnPostWindowStateTypeChange(WindowState* window_state, - WindowStateType old_type) {} + chromeos::WindowStateType old_type) { + } }; } // namespace ash
diff --git a/ash/wm/window_state_unittest.cc b/ash/wm/window_state_unittest.cc index 77d6f9d..83a3dd2 100644 --- a/ash/wm/window_state_unittest.cc +++ b/ash/wm/window_state_unittest.cc
@@ -25,7 +25,7 @@ #include "ui/views/widget/widget.h" #include "ui/wm/core/window_util.h" -using ash::WindowStateType; +using chromeos::WindowStateType; namespace ash { namespace {
diff --git a/ash/wm/window_util_unittest.cc b/ash/wm/window_util_unittest.cc index 6297d17..329a55e 100644 --- a/ash/wm/window_util_unittest.cc +++ b/ash/wm/window_util_unittest.cc
@@ -36,7 +36,9 @@ if (event->type() == WM_EVENT_MINIMIZE) was_visible_on_minimize_ = window_state->window()->IsVisible(); } - WindowStateType GetType() const override { return WindowStateType::kNormal; } + chromeos::WindowStateType GetType() const override { + return chromeos::WindowStateType::kNormal; + } void AttachState(WindowState* window_state, WindowState::State* previous_state) override {} void DetachState(WindowState* window_state) override {}
diff --git a/ash/wm/workspace/multi_window_resize_controller.cc b/ash/wm/workspace/multi_window_resize_controller.cc index eb2f985..67676e9 100644 --- a/ash/wm/workspace/multi_window_resize_controller.cc +++ b/ash/wm/workspace/multi_window_resize_controller.cc
@@ -287,7 +287,7 @@ void MultiWindowResizeController::OnPostWindowStateTypeChange( WindowState* window_state, - WindowStateType old_type) { + chromeos::WindowStateType old_type) { if (window_state->IsMaximized() || window_state->IsFullscreen() || window_state->IsMinimized()) { ResetResizer();
diff --git a/ash/wm/workspace/multi_window_resize_controller.h b/ash/wm/workspace/multi_window_resize_controller.h index a6adfd4..1854f99 100644 --- a/ash/wm/workspace/multi_window_resize_controller.h +++ b/ash/wm/workspace/multi_window_resize_controller.h
@@ -57,7 +57,7 @@ // WindowStateObserver: void OnPostWindowStateTypeChange(WindowState* window_state, - WindowStateType old_type) override; + chromeos::WindowStateType old_type) override; // OverviewObserver: void OnOverviewModeStarting() override;
diff --git a/ash/wm/workspace/multi_window_resize_controller_unittest.cc b/ash/wm/workspace/multi_window_resize_controller_unittest.cc index 6086bb1c..bdc266db 100644 --- a/ash/wm/workspace/multi_window_resize_controller_unittest.cc +++ b/ash/wm/workspace/multi_window_resize_controller_unittest.cc
@@ -32,6 +32,7 @@ using chromeos::kResizeInsideBoundsSize; using chromeos::kResizeOutsideBoundsSize; +using chromeos::WindowStateType; namespace ash {
diff --git a/ash/wm/workspace/workspace_event_handler_unittest.cc b/ash/wm/workspace/workspace_event_handler_unittest.cc index 52c8031a..964441d 100644 --- a/ash/wm/workspace/workspace_event_handler_unittest.cc +++ b/ash/wm/workspace/workspace_event_handler_unittest.cc
@@ -32,6 +32,8 @@ namespace { +using ::chromeos::WindowStateType; + // Clicks |button| with |flags|. void ClickButtonWithFlags(ui::test::EventGenerator* generator, int button,
diff --git a/ash/wm/workspace/workspace_layout_manager.cc b/ash/wm/workspace/workspace_layout_manager.cc index f7463de..483572b4 100644 --- a/ash/wm/workspace/workspace_layout_manager.cc +++ b/ash/wm/workspace/workspace_layout_manager.cc
@@ -40,6 +40,8 @@ namespace ash { +using ::chromeos::WindowStateType; + WorkspaceLayoutManager::BubbleWindowObserver::BubbleWindowObserver( WorkspaceLayoutManager* workspace_layout_manager) : workspace_layout_manager_(workspace_layout_manager) {}
diff --git a/ash/wm/workspace/workspace_layout_manager.h b/ash/wm/workspace/workspace_layout_manager.h index 30e9f63..a7f44d2d 100644 --- a/ash/wm/workspace/workspace_layout_manager.h +++ b/ash/wm/workspace/workspace_layout_manager.h
@@ -83,7 +83,7 @@ // WindowStateObserver: void OnPostWindowStateTypeChange(WindowState* window_state, - WindowStateType old_type) override; + chromeos::WindowStateType old_type) override; // display::DisplayObserver: void OnDisplayMetricsChanged(const display::Display& display,
diff --git a/ash/wm/workspace/workspace_layout_manager_unittest.cc b/ash/wm/workspace/workspace_layout_manager_unittest.cc index e850bc8..9e717cf 100644 --- a/ash/wm/workspace/workspace_layout_manager_unittest.cc +++ b/ash/wm/workspace/workspace_layout_manager_unittest.cc
@@ -75,6 +75,8 @@ namespace ash { namespace { +using ::chromeos::WindowStateType; + class MaximizeDelegateView : public views::WidgetDelegateView { public: explicit MaximizeDelegateView(const gfx::Rect& initial_bounds)
diff --git a/ash/wm/workspace/workspace_window_resizer.cc b/ash/wm/workspace/workspace_window_resizer.cc index 5390064..0328548 100644 --- a/ash/wm/workspace/workspace_window_resizer.cc +++ b/ash/wm/workspace/workspace_window_resizer.cc
@@ -48,6 +48,8 @@ namespace { +using ::chromeos::WindowStateType; + constexpr double kMinHorizVelocityForWindowSwipe = 1100; constexpr double kMinVertVelocityForWindowMinimize = 1000; @@ -326,7 +328,9 @@ // Snapped and maximized windows need to be dragged a certain amount before // bounds start changing. - return IsNormalWindowStateType(state) ? 0 : kResizeRestoreDragThresholdDp; + return chromeos::IsNormalWindowStateType(state) + ? 0 + : kResizeRestoreDragThresholdDp; } void ResetFrameRestoreLookKey(WindowState* window_state) {
diff --git a/ash/wm/workspace/workspace_window_resizer.h b/ash/wm/workspace/workspace_window_resizer.h index adf6f6a5..69b6ed47 100644 --- a/ash/wm/workspace/workspace_window_resizer.h +++ b/ash/wm/workspace/workspace_window_resizer.h
@@ -145,13 +145,13 @@ // Returns true if |bounds_in_parent| are valid bounds for snapped state type // |snapped_type|. - bool AreBoundsValidSnappedBounds(WindowStateType snapped_type, + bool AreBoundsValidSnappedBounds(chromeos::WindowStateType snapped_type, const gfx::Rect& bounds_in_parent) const; // Sets |window|'s state type to |new_state_type|. Called after the drag has // been completed for fling/swipe gestures. void SetWindowStateTypeFromGesture(aura::Window* window, - WindowStateType new_state_type); + chromeos::WindowStateType new_state_type); // Start/End drag for attached windows if there is any. void StartDragForAttachedWindows();
diff --git a/ash/wm/workspace/workspace_window_resizer_unittest.cc b/ash/wm/workspace/workspace_window_resizer_unittest.cc index 828128c..075be8b 100644 --- a/ash/wm/workspace/workspace_window_resizer_unittest.cc +++ b/ash/wm/workspace/workspace_window_resizer_unittest.cc
@@ -38,6 +38,8 @@ namespace ash { namespace { +using chromeos::WindowStateType; + constexpr int kRootHeight = 600; gfx::PointF CalculateDragPoint(const WindowResizer& resizer,
diff --git a/base/fuchsia/intl_profile_watcher.cc b/base/fuchsia/intl_profile_watcher.cc index 27247f8..0c4e992 100644 --- a/base/fuchsia/intl_profile_watcher.cc +++ b/base/fuchsia/intl_profile_watcher.cc
@@ -16,15 +16,16 @@ using ::fuchsia::intl::Profile; namespace base { -namespace fuchsia { -IntlProfileWatcher::IntlProfileWatcher(ProfileChangeCallback on_profile_changed) - : IntlProfileWatcher(ComponentContextForProcess() - ->svc() - ->Connect<::fuchsia::intl::PropertyProvider>(), - on_profile_changed) {} +FuchsiaIntlProfileWatcher::FuchsiaIntlProfileWatcher( + ProfileChangeCallback on_profile_changed) + : FuchsiaIntlProfileWatcher( + ComponentContextForProcess() + ->svc() + ->Connect<::fuchsia::intl::PropertyProvider>(), + on_profile_changed) {} -IntlProfileWatcher::IntlProfileWatcher( +FuchsiaIntlProfileWatcher::FuchsiaIntlProfileWatcher( ::fuchsia::intl::PropertyProviderPtr property_provider, ProfileChangeCallback on_profile_changed) : property_provider_(std::move(property_provider)), @@ -43,10 +44,10 @@ }; } -IntlProfileWatcher::~IntlProfileWatcher() = default; +FuchsiaIntlProfileWatcher::~FuchsiaIntlProfileWatcher() = default; // static -std::string IntlProfileWatcher::GetPrimaryTimeZoneIdFromProfile( +std::string FuchsiaIntlProfileWatcher::GetPrimaryTimeZoneIdFromProfile( const Profile& profile) { if (!profile.has_time_zones()) { DLOG(WARNING) << "Profile does not contain time zones."; @@ -64,14 +65,15 @@ } // static -std::string IntlProfileWatcher::GetPrimaryTimeZoneIdForIcuInitialization() { +std::string +FuchsiaIntlProfileWatcher::GetPrimaryTimeZoneIdForIcuInitialization() { ::fuchsia::intl::PropertyProviderSyncPtr provider; ComponentContextForProcess()->svc()->Connect(provider.NewRequest()); return GetPrimaryTimeZoneIdFromPropertyProvider(std::move(provider)); } // static -std::string IntlProfileWatcher::GetPrimaryTimeZoneIdFromPropertyProvider( +std::string FuchsiaIntlProfileWatcher::GetPrimaryTimeZoneIdFromPropertyProvider( ::fuchsia::intl::PropertyProviderSyncPtr property_provider) { DCHECK(property_provider.is_bound()); Profile profile; @@ -84,5 +86,4 @@ return GetPrimaryTimeZoneIdFromProfile(profile); } -} // namespace fuchsia } // namespace base
diff --git a/base/fuchsia/intl_profile_watcher.h b/base/fuchsia/intl_profile_watcher.h index 47ed419..7222b70e 100644 --- a/base/fuchsia/intl_profile_watcher.h +++ b/base/fuchsia/intl_profile_watcher.h
@@ -13,22 +13,22 @@ #include "base/strings/string_piece_forward.h" namespace base { -namespace fuchsia { // Watches fuchsia.intl.PropertyProvider for change notifications and notifies // the provided callback. If necessary, the caller is responsible for // determining whether an actual change of interest has occurred. -class BASE_EXPORT IntlProfileWatcher { +class BASE_EXPORT FuchsiaIntlProfileWatcher { public: using ProfileChangeCallback = base::RepeatingCallback<void(const ::fuchsia::intl::Profile&)>; // |on_profile_changed| will be called each time the profile may have changed. - explicit IntlProfileWatcher(ProfileChangeCallback on_profile_changed); + explicit FuchsiaIntlProfileWatcher(ProfileChangeCallback on_profile_changed); - IntlProfileWatcher(const IntlProfileWatcher&) = delete; - IntlProfileWatcher& operator=(const IntlProfileWatcher&) = delete; - ~IntlProfileWatcher(); + FuchsiaIntlProfileWatcher(const FuchsiaIntlProfileWatcher&) = delete; + FuchsiaIntlProfileWatcher& operator=(const FuchsiaIntlProfileWatcher&) = + delete; + ~FuchsiaIntlProfileWatcher(); // Returns the ID of the primary time zone in |profile|. // Returns the empty string if the ID cannot be obtained. @@ -45,8 +45,9 @@ friend class GetPrimaryTimeZoneIdFromPropertyProviderTest; friend class IntlProfileWatcherTest; - IntlProfileWatcher(::fuchsia::intl::PropertyProviderPtr property_provider, - ProfileChangeCallback on_profile_changed); + FuchsiaIntlProfileWatcher( + ::fuchsia::intl::PropertyProviderPtr property_provider, + ProfileChangeCallback on_profile_changed); // Returns the ID of the primary time zone from the profile obtained from // |property_provider|. Returns the empty string if the ID cannot be obtained. @@ -57,7 +58,14 @@ const ProfileChangeCallback on_profile_changed_; }; +// TODO(crbug.com/1073821): Remove this block when out-of-tree callers have been +// changed to use the non-fuchsia-sub-namespace version. +namespace fuchsia { + +using IntlProfileWatcher = ::base::FuchsiaIntlProfileWatcher; + } // namespace fuchsia + } // namespace base #endif // BASE_FUCHSIA_INTL_PROFILE_WATCHER_H_
diff --git a/base/fuchsia/intl_profile_watcher_unittest.cc b/base/fuchsia/intl_profile_watcher_unittest.cc index 110e5bf..6368000 100644 --- a/base/fuchsia/intl_profile_watcher_unittest.cc +++ b/base/fuchsia/intl_profile_watcher_unittest.cc
@@ -24,7 +24,6 @@ using ::fuchsia::intl::Profile; namespace base { -namespace fuchsia { namespace { @@ -135,7 +134,7 @@ protected: static std::string GetPrimaryTimeZoneIdFromPropertyProvider( ::fuchsia::intl::PropertyProviderSyncPtr property_provider) { - return IntlProfileWatcher::GetPrimaryTimeZoneIdFromPropertyProvider( + return FuchsiaIntlProfileWatcher::GetPrimaryTimeZoneIdFromPropertyProvider( std::move(property_provider)); } @@ -155,9 +154,9 @@ base::test::SingleThreadTaskEnvironment task_environment_{ base::test::SingleThreadTaskEnvironment::MainThreadType::IO}; - std::unique_ptr<IntlProfileWatcher> CreateIntlProfileWatcher( - IntlProfileWatcher::ProfileChangeCallback on_profile_changed) { - return base::WrapUnique(new IntlProfileWatcher( + std::unique_ptr<FuchsiaIntlProfileWatcher> CreateIntlProfileWatcher( + FuchsiaIntlProfileWatcher::ProfileChangeCallback on_profile_changed) { + return base::WrapUnique(new FuchsiaIntlProfileWatcher( std::move(property_provider_ptr_), std::move(on_profile_changed))); } @@ -169,15 +168,16 @@ // Unit tests are run in an environment where intl is not provided. // However, this is not exposed by the API. -TEST(IntlServiceNotAvailableTest, IntlProfileWatcher) { +TEST(IntlServiceNotAvailableTest, FuchsiaIntlProfileWatcher) { base::test::SingleThreadTaskEnvironment task_environment_{ base::test::SingleThreadTaskEnvironment::MainThreadType::IO}; base::RunLoop run_loop; - base::MockCallback<IntlProfileWatcher::ProfileChangeCallback> + base::MockCallback<FuchsiaIntlProfileWatcher::ProfileChangeCallback> on_profile_changed; EXPECT_CALL(on_profile_changed, Run(testing::_)).Times(0); - auto watcher = std::make_unique<IntlProfileWatcher>(on_profile_changed.Get()); + auto watcher = + std::make_unique<FuchsiaIntlProfileWatcher>(on_profile_changed.Get()); EXPECT_TRUE(watcher); run_loop.RunUntilIdle(); @@ -220,7 +220,7 @@ } TEST_F(IntlProfileWatcherTest, NoZones_NoNotification) { - base::MockCallback<IntlProfileWatcher::ProfileChangeCallback> callback; + base::MockCallback<FuchsiaIntlProfileWatcher::ProfileChangeCallback> callback; EXPECT_CALL(callback, Run(testing::_)).Times(0); auto watcher = CreateIntlProfileWatcher(callback.Get()); run_loop_.RunUntilIdle(); @@ -230,7 +230,8 @@ auto watcher = CreateIntlProfileWatcher(base::BindLambdaForTesting( [quit_loop = run_loop_.QuitClosure()](const Profile& profile) { EXPECT_EQ(kPrimaryTimeZoneName, - IntlProfileWatcher::GetPrimaryTimeZoneIdFromProfile(profile)); + FuchsiaIntlProfileWatcher::GetPrimaryTimeZoneIdFromProfile( + profile)); quit_loop.Run(); })); @@ -247,7 +248,8 @@ auto watcher = CreateIntlProfileWatcher(base::BindLambdaForTesting( [quit_loop = run_loop_.QuitClosure()](const Profile& profile) { EXPECT_EQ(kPrimaryTimeZoneName, - IntlProfileWatcher::GetPrimaryTimeZoneIdFromProfile(profile)); + FuchsiaIntlProfileWatcher::GetPrimaryTimeZoneIdFromProfile( + profile)); quit_loop.Run(); })); @@ -256,7 +258,7 @@ // Ensure no crash when the peer service cannot be reached during creation. TEST_F(IntlProfileWatcherTest, ChannelClosedBeforeCreation) { - base::MockCallback<IntlProfileWatcher::ProfileChangeCallback> callback; + base::MockCallback<FuchsiaIntlProfileWatcher::ProfileChangeCallback> callback; EXPECT_CALL(callback, Run(testing::_)).Times(0); property_provider_.Close(); @@ -269,7 +271,7 @@ // Ensure no crash when the channel is closed after creation. TEST_F(IntlProfileWatcherTest, ChannelClosedAfterCreation) { - base::MockCallback<IntlProfileWatcher::ProfileChangeCallback> callback; + base::MockCallback<FuchsiaIntlProfileWatcher::ProfileChangeCallback> callback; EXPECT_CALL(callback, Run(testing::_)).Times(0); auto watcher = CreateIntlProfileWatcher(callback.Get()); @@ -281,26 +283,26 @@ } TEST(IntlProfileWatcherGetPrimaryTimeZoneIdFromProfileTest, NoZones) { - EXPECT_EQ("", IntlProfileWatcher::GetPrimaryTimeZoneIdFromProfile(Profile())); + EXPECT_EQ("", FuchsiaIntlProfileWatcher::GetPrimaryTimeZoneIdFromProfile( + Profile())); } TEST(IntlProfileWatcherGetPrimaryTimeZoneIdFromProfileTest, EmptyZonesList) { - EXPECT_EQ("", IntlProfileWatcher::GetPrimaryTimeZoneIdFromProfile( + EXPECT_EQ("", FuchsiaIntlProfileWatcher::GetPrimaryTimeZoneIdFromProfile( CreateProfileWithTimeZones({}))); } TEST(IntlProfileWatcherGetPrimaryTimeZoneIdFromProfileTest, OneZone) { EXPECT_EQ(kPrimaryTimeZoneName, - IntlProfileWatcher::GetPrimaryTimeZoneIdFromProfile( + FuchsiaIntlProfileWatcher::GetPrimaryTimeZoneIdFromProfile( CreateProfileWithTimeZones({kPrimaryTimeZoneName}))); } TEST(IntlProfileWatcherGetPrimaryTimeZoneIdFromProfileTest, TwoZones) { EXPECT_EQ(kPrimaryTimeZoneName, - IntlProfileWatcher::GetPrimaryTimeZoneIdFromProfile( + FuchsiaIntlProfileWatcher::GetPrimaryTimeZoneIdFromProfile( CreateProfileWithTimeZones( {kPrimaryTimeZoneName, kSecondaryTimeZoneName}))); } -} // namespace fuchsia } // namespace base
diff --git a/base/i18n/icu_util.cc b/base/i18n/icu_util.cc index 36f8e18..b225f1d 100644 --- a/base/i18n/icu_util.cc +++ b/base/i18n/icu_util.cc
@@ -338,7 +338,7 @@ // If the system time zone cannot be obtained or is not understood by ICU, // the "unknown" time zone will be returned by createTimeZone() and used. std::string zone_id = - fuchsia::IntlProfileWatcher::GetPrimaryTimeZoneIdForIcuInitialization(); + FuchsiaIntlProfileWatcher::GetPrimaryTimeZoneIdForIcuInitialization(); icu::TimeZone::adoptDefault( icu::TimeZone::createTimeZone(icu::UnicodeString::fromUTF8(zone_id))); #elif (defined(OS_LINUX) || defined(OS_CHROMEOS)) && !BUILDFLAG(IS_CHROMECAST)
diff --git a/base/trace_event/auto_open_close_event.h b/base/trace_event/auto_open_close_event.h index fb88db8..8a89663 100644 --- a/base/trace_event/auto_open_close_event.h +++ b/base/trace_event/auto_open_close_event.h
@@ -5,7 +5,6 @@ #ifndef BASE_TRACE_EVENT_AUTO_OPEN_CLOSE_EVENT_H_ #define BASE_TRACE_EVENT_AUTO_OPEN_CLOSE_EVENT_H_ -#include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/threading/thread_checker.h" #include "base/time/time.h" @@ -38,6 +37,8 @@ base::trace_event::TraceLog::GetInstance()->AddAsyncEnabledStateObserver( weak_factory_.GetWeakPtr()); } + AutoOpenCloseEvent(const AutoOpenCloseEvent&) = delete; + AutoOpenCloseEvent& operator=(const AutoOpenCloseEvent&) = delete; ~AutoOpenCloseEvent() override { DCHECK(thread_checker_.CalledOnValidThread()); base::trace_event::TraceLog::GetInstance()->RemoveAsyncEnabledStateObserver( @@ -71,8 +72,6 @@ base::TimeTicks start_time_; base::ThreadChecker thread_checker_; WeakPtrFactory<AutoOpenCloseEvent> weak_factory_{this}; - - DISALLOW_COPY_AND_ASSIGN(AutoOpenCloseEvent); }; } // namespace trace_event
diff --git a/base/trace_event/heap_profiler_allocation_context_tracker.cc b/base/trace_event/heap_profiler_allocation_context_tracker.cc index 28fd0646..6aa3125 100644 --- a/base/trace_event/heap_profiler_allocation_context_tracker.cc +++ b/base/trace_event/heap_profiler_allocation_context_tracker.cc
@@ -97,8 +97,7 @@ return tracker; } -AllocationContextTracker::AllocationContextTracker() - : thread_name_(nullptr), ignore_scope_depth_(0) { +AllocationContextTracker::AllocationContextTracker() { tracked_stack_.reserve(kMaxStackDepth); task_contexts_.reserve(kMaxTaskDepth); task_contexts_.push_back("UntrackedTask");
diff --git a/base/trace_event/heap_profiler_allocation_context_tracker.h b/base/trace_event/heap_profiler_allocation_context_tracker.h index a117ea0..1ae1bd14 100644 --- a/base/trace_event/heap_profiler_allocation_context_tracker.h +++ b/base/trace_event/heap_profiler_allocation_context_tracker.h
@@ -9,7 +9,6 @@ #include "base/atomicops.h" #include "base/base_export.h" -#include "base/macros.h" #include "base/trace_event/heap_profiler_allocation_context.h" namespace base { @@ -84,6 +83,9 @@ // if capture is enabled. static void SetCurrentThreadName(const char* name); + AllocationContextTracker(const AllocationContextTracker&) = delete; + AllocationContextTracker& operator=(const AllocationContextTracker&) = delete; + // Starts and ends a new ignore scope between which the allocations are // ignored by the heap profiler. GetContextSnapshot() returns false when // allocations are ignored. @@ -128,15 +130,13 @@ std::vector<StackFrame> tracked_stack_; // The thread name is used as the first entry in the pseudo stack. - const char* thread_name_; + const char* thread_name_ = nullptr; // Stack of tasks' contexts. Context serves as a different dimension than // pseudo stack to cluster allocations. std::vector<const char*> task_contexts_; - uint32_t ignore_scope_depth_; - - DISALLOW_COPY_AND_ASSIGN(AllocationContextTracker); + uint32_t ignore_scope_depth_ = 0; }; } // namespace trace_event
diff --git a/base/trace_event/heap_profiler_event_filter.cc b/base/trace_event/heap_profiler_event_filter.cc index 937072ca..bb16d9c 100644 --- a/base/trace_event/heap_profiler_event_filter.cc +++ b/base/trace_event/heap_profiler_event_filter.cc
@@ -32,9 +32,6 @@ // static const char HeapProfilerEventFilter::kName[] = "heap_profiler_predicate"; -HeapProfilerEventFilter::HeapProfilerEventFilter() = default; -HeapProfilerEventFilter::~HeapProfilerEventFilter() = default; - bool HeapProfilerEventFilter::FilterTraceEvent( const TraceEvent& trace_event) const { if (!IsPseudoStackEnabled())
diff --git a/base/trace_event/heap_profiler_event_filter.h b/base/trace_event/heap_profiler_event_filter.h index 47368a1..9150875 100644 --- a/base/trace_event/heap_profiler_event_filter.h +++ b/base/trace_event/heap_profiler_event_filter.h
@@ -6,7 +6,6 @@ #define BASE_TRACE_EVENT_HEAP_PROFILER_EVENT_FILTER_H_ #include "base/base_export.h" -#include "base/macros.h" #include "base/trace_event/trace_event_filter.h" namespace base { @@ -22,16 +21,15 @@ public: static const char kName[]; - HeapProfilerEventFilter(); - ~HeapProfilerEventFilter() override; + HeapProfilerEventFilter() = default; + HeapProfilerEventFilter(const HeapProfilerEventFilter&) = delete; + HeapProfilerEventFilter& operator=(const HeapProfilerEventFilter&) = delete; + ~HeapProfilerEventFilter() override = default; // TraceEventFilter implementation. bool FilterTraceEvent(const TraceEvent& trace_event) const override; void EndEvent(const char* category_name, const char* event_name) const override; - - private: - DISALLOW_COPY_AND_ASSIGN(HeapProfilerEventFilter); }; } // namespace trace_event
diff --git a/base/trace_event/java_heap_dump_provider_android.cc b/base/trace_event/java_heap_dump_provider_android.cc index 684f7301c..624f743 100644 --- a/base/trace_event/java_heap_dump_provider_android.cc +++ b/base/trace_event/java_heap_dump_provider_android.cc
@@ -16,12 +16,6 @@ LeakySingletonTraits<JavaHeapDumpProvider>>::get(); } -JavaHeapDumpProvider::JavaHeapDumpProvider() { -} - -JavaHeapDumpProvider::~JavaHeapDumpProvider() { -} - // Called at trace dump point time. Creates a snapshot with the memory counters // for the current process. bool JavaHeapDumpProvider::OnMemoryDump(const MemoryDumpArgs& args,
diff --git a/base/trace_event/java_heap_dump_provider_android.h b/base/trace_event/java_heap_dump_provider_android.h index b9f2333..37edab0 100644 --- a/base/trace_event/java_heap_dump_provider_android.h +++ b/base/trace_event/java_heap_dump_provider_android.h
@@ -5,7 +5,6 @@ #ifndef BASE_TRACE_EVENT_JAVA_HEAP_DUMP_PROVIDER_ANDROID_H_ #define BASE_TRACE_EVENT_JAVA_HEAP_DUMP_PROVIDER_ANDROID_H_ -#include "base/macros.h" #include "base/memory/singleton.h" #include "base/trace_event/memory_dump_provider.h" @@ -17,6 +16,9 @@ public: static JavaHeapDumpProvider* GetInstance(); + JavaHeapDumpProvider(const JavaHeapDumpProvider&) = delete; + JavaHeapDumpProvider& operator=(const JavaHeapDumpProvider&) = delete; + // MemoryDumpProvider implementation. bool OnMemoryDump(const MemoryDumpArgs& args, ProcessMemoryDump* pmd) override; @@ -24,10 +26,8 @@ private: friend struct DefaultSingletonTraits<JavaHeapDumpProvider>; - JavaHeapDumpProvider(); - ~JavaHeapDumpProvider() override; - - DISALLOW_COPY_AND_ASSIGN(JavaHeapDumpProvider); + JavaHeapDumpProvider() = default; + ~JavaHeapDumpProvider() override = default; }; } // namespace trace_event
diff --git a/base/trace_event/log_message.h b/base/trace_event/log_message.h index 4c8cbcc..30da1e1 100644 --- a/base/trace_event/log_message.h +++ b/base/trace_event/log_message.h
@@ -11,7 +11,6 @@ #include <string> #include <vector> -#include "base/macros.h" #include "base/strings/string_piece.h" #include "base/trace_event/trace_event_impl.h" @@ -24,6 +23,8 @@ class BASE_EXPORT LogMessage : public ConvertableToTraceFormat { public: LogMessage(const char* file, base::StringPiece message, int line); + LogMessage(const LogMessage&) = delete; + LogMessage& operator=(const LogMessage&) = delete; ~LogMessage() override; // ConvertableToTraceFormat class implementation. @@ -40,10 +41,9 @@ const char* file_; std::string message_; int line_number_; - DISALLOW_COPY_AND_ASSIGN(LogMessage); }; } // namespace trace_event } // namespace base -#endif // BASE_TRACE_EVENT_LOG_MESSAGE_H_ \ No newline at end of file +#endif // BASE_TRACE_EVENT_LOG_MESSAGE_H_
diff --git a/base/trace_event/malloc_dump_provider.h b/base/trace_event/malloc_dump_provider.h index 39f85832..f6c83b4 100644 --- a/base/trace_event/malloc_dump_provider.h +++ b/base/trace_event/malloc_dump_provider.h
@@ -5,7 +5,6 @@ #ifndef BASE_TRACE_EVENT_MALLOC_DUMP_PROVIDER_H_ #define BASE_TRACE_EVENT_MALLOC_DUMP_PROVIDER_H_ -#include "base/macros.h" #include "base/memory/singleton.h" #include "base/synchronization/lock.h" #include "base/trace_event/memory_dump_provider.h" @@ -28,6 +27,9 @@ static MallocDumpProvider* GetInstance(); + MallocDumpProvider(const MallocDumpProvider&) = delete; + MallocDumpProvider& operator=(const MallocDumpProvider&) = delete; + // MemoryDumpProvider implementation. bool OnMemoryDump(const MemoryDumpArgs& args, ProcessMemoryDump* pmd) override; @@ -46,8 +48,6 @@ bool emit_metrics_on_memory_dump_ = true; base::Lock emit_metrics_on_memory_dump_lock_; - - DISALLOW_COPY_AND_ASSIGN(MallocDumpProvider); }; } // namespace trace_event
diff --git a/base/trace_event/memory_allocator_dump.h b/base/trace_event/memory_allocator_dump.h index fe0837d..d0fbb8a 100644 --- a/base/trace_event/memory_allocator_dump.h +++ b/base/trace_event/memory_allocator_dump.h
@@ -10,10 +10,10 @@ #include <memory> #include <ostream> #include <string> +#include <vector> #include "base/base_export.h" #include "base/gtest_prod_util.h" -#include "base/macros.h" #include "base/optional.h" #include "base/trace_event/memory_allocator_dump_guid.h" #include "base/trace_event/memory_dump_request_args.h" @@ -62,6 +62,8 @@ Entry(std::string name, std::string units, uint64_t value); Entry(std::string name, std::string units, std::string value); Entry(Entry&& other) noexcept; + Entry(const Entry&) = delete; + Entry& operator=(const Entry&) = delete; Entry& operator=(Entry&& other); bool operator==(const Entry& rhs) const; @@ -72,13 +74,13 @@ uint64_t value_uint64; std::string value_string; - - DISALLOW_COPY_AND_ASSIGN(Entry); }; MemoryAllocatorDump(const std::string& absolute_name, MemoryDumpLevelOfDetail, const MemoryAllocatorDumpGuid&); + MemoryAllocatorDump(const MemoryAllocatorDump&) = delete; + MemoryAllocatorDump& operator=(const MemoryAllocatorDump&) = delete; ~MemoryAllocatorDump(); // Standard attribute |name|s for the AddScalar and AddString() methods. @@ -151,8 +153,6 @@ int flags_; // See enum Flags. mutable Optional<uint64_t> cached_size_; // Lazy, for GetSizeInternal(). std::vector<Entry> entries_; - - DISALLOW_COPY_AND_ASSIGN(MemoryAllocatorDump); }; // This is required by gtest to print a readable output on test failures.
diff --git a/base/trace_event/memory_dump_manager.cc b/base/trace_event/memory_dump_manager.cc index 8a168e29..c582d104 100644 --- a/base/trace_event/memory_dump_manager.cc +++ b/base/trace_event/memory_dump_manager.cc
@@ -99,10 +99,7 @@ return instance; } -MemoryDumpManager::MemoryDumpManager() - : is_coordinator_(false), - tracing_process_id_(kInvalidTracingProcessId), - dumper_registrations_ignored_for_testing_(false) {} +MemoryDumpManager::MemoryDumpManager() = default; MemoryDumpManager::~MemoryDumpManager() { Thread* dump_thread = nullptr; @@ -290,7 +287,7 @@ void MemoryDumpManager::CreateProcessDump(const MemoryDumpRequestArgs& args, ProcessMemoryDumpCallback callback) { char guid_str[20]; - sprintf(guid_str, "0x%" PRIx64, args.dump_guid); + snprintf(guid_str, base::size(guid_str), "0x%" PRIx64, args.dump_guid); TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(kTraceCategory, "ProcessMemoryDump", TRACE_ID_LOCAL(args.dump_guid), "dump_guid", TRACE_STR_COPY(guid_str));
diff --git a/base/trace_event/memory_dump_manager.h b/base/trace_event/memory_dump_manager.h index 7d4fb112..f83b491 100644 --- a/base/trace_event/memory_dump_manager.h +++ b/base/trace_event/memory_dump_manager.h
@@ -13,7 +13,6 @@ #include <vector> #include "base/atomicops.h" -#include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/singleton.h" #include "base/synchronization/lock.h" @@ -51,6 +50,9 @@ static MemoryDumpManager* GetInstance(); static std::unique_ptr<MemoryDumpManager> CreateInstanceForTesting(); + MemoryDumpManager(const MemoryDumpManager&) = delete; + MemoryDumpManager& operator=(const MemoryDumpManager&) = delete; + // Invoked once per process to listen to trace begin / end events. // Initialization can happen after (Un)RegisterMemoryDumpProvider() calls // and the MemoryDumpManager guarantees to support this. @@ -162,6 +164,9 @@ const MemoryDumpProviderInfo::OrderedSet& dump_providers, ProcessMemoryDumpCallback callback, scoped_refptr<SequencedTaskRunner> dump_thread_task_runner); + ProcessMemoryDumpAsyncState(const ProcessMemoryDumpAsyncState&) = delete; + ProcessMemoryDumpAsyncState& operator=(const ProcessMemoryDumpAsyncState&) = + delete; ~ProcessMemoryDumpAsyncState(); // A ProcessMemoryDump to collect data from MemoryDumpProviders. @@ -189,9 +194,6 @@ // threads outside of the lock_ to avoid races when disabling tracing. // It is immutable for all the duration of a tracing session. const scoped_refptr<SequencedTaskRunner> dump_thread_task_runner; - - private: - DISALLOW_COPY_AND_ASSIGN(ProcessMemoryDumpAsyncState); }; static const int kMaxConsecutiveFailuresCount; @@ -244,7 +246,7 @@ RequestGlobalDumpFunction request_dump_function_; // True when current process coordinates the periodic dump triggering. - bool is_coordinator_ GUARDED_BY(lock_); + bool is_coordinator_ GUARDED_BY(lock_) = false; // Protects from concurrent accesses to the local state, eg: to guard against // disabling logging while dumping on another thread. @@ -256,12 +258,10 @@ // The unique id of the child process. This is created only for tracing and is // expected to be valid only when tracing is enabled. - uint64_t tracing_process_id_; + uint64_t tracing_process_id_ = kInvalidTracingProcessId; // When true, calling |RegisterMemoryDumpProvider| is a no-op. - bool dumper_registrations_ignored_for_testing_; - - DISALLOW_COPY_AND_ASSIGN(MemoryDumpManager); + bool dumper_registrations_ignored_for_testing_ = false; }; } // namespace trace_event
diff --git a/base/trace_event/memory_dump_provider.h b/base/trace_event/memory_dump_provider.h index f55e2cf..9839407 100644 --- a/base/trace_event/memory_dump_provider.h +++ b/base/trace_event/memory_dump_provider.h
@@ -6,7 +6,6 @@ #define BASE_TRACE_EVENT_MEMORY_DUMP_PROVIDER_H_ #include "base/base_export.h" -#include "base/macros.h" #include "base/process/process_handle.h" #include "base/trace_event/memory_dump_request_args.h" @@ -28,6 +27,8 @@ bool dumps_on_single_thread_task_runner; }; + MemoryDumpProvider(const MemoryDumpProvider&) = delete; + MemoryDumpProvider& operator=(const MemoryDumpProvider&) = delete; virtual ~MemoryDumpProvider() = default; // Called by the MemoryDumpManager when generating memory dumps. @@ -42,8 +43,6 @@ protected: MemoryDumpProvider() = default; - - DISALLOW_COPY_AND_ASSIGN(MemoryDumpProvider); }; } // namespace trace_event
diff --git a/base/trace_event/memory_dump_scheduler.cc b/base/trace_event/memory_dump_scheduler.cc index ac9b12ba..a9ad574 100644 --- a/base/trace_event/memory_dump_scheduler.cc +++ b/base/trace_event/memory_dump_scheduler.cc
@@ -20,7 +20,7 @@ return instance; } -MemoryDumpScheduler::MemoryDumpScheduler() : period_ms_(0), generation_(0) {} +MemoryDumpScheduler::MemoryDumpScheduler() = default; MemoryDumpScheduler::~MemoryDumpScheduler() { // Hit only in tests. Check that tests don't leave without stopping. DCHECK(!is_enabled_for_testing());
diff --git a/base/trace_event/memory_dump_scheduler.h b/base/trace_event/memory_dump_scheduler.h index 21334f0..bfccd6a 100644 --- a/base/trace_event/memory_dump_scheduler.h +++ b/base/trace_event/memory_dump_scheduler.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_TRACE_EVENT_MEMORY_DUMP_SCHEDULER_H -#define BASE_TRACE_EVENT_MEMORY_DUMP_SCHEDULER_H +#ifndef BASE_TRACE_EVENT_MEMORY_DUMP_SCHEDULER_H_ +#define BASE_TRACE_EVENT_MEMORY_DUMP_SCHEDULER_H_ #include <stdint.h> @@ -43,6 +43,9 @@ static MemoryDumpScheduler* GetInstance(); + MemoryDumpScheduler(const MemoryDumpScheduler&) = delete; + MemoryDumpScheduler& operator=(const MemoryDumpScheduler&) = delete; + void Start(Config, scoped_refptr<SequencedTaskRunner> task_runner); void Stop(); bool is_enabled_for_testing() const { return bool(task_runner_); } @@ -60,17 +63,16 @@ scoped_refptr<SequencedTaskRunner> task_runner_; // These fields instead are only accessed from within the task runner. - uint32_t period_ms_; // 0 == disabled. - uint32_t generation_; // Used to invalidate outstanding tasks after Stop(). + uint32_t period_ms_ = 0; // 0 == disabled. + // Used to invalidate outstanding tasks after Stop(). + uint32_t generation_ = 0; uint32_t tick_count_; uint32_t light_dump_rate_; uint32_t heavy_dump_rate_; PeriodicCallback callback_; - - DISALLOW_COPY_AND_ASSIGN(MemoryDumpScheduler); }; } // namespace trace_event } // namespace base -#endif // BASE_TRACE_EVENT_MEMORY_DUMP_SCHEDULER_H +#endif // BASE_TRACE_EVENT_MEMORY_DUMP_SCHEDULER_H_
diff --git a/base/trace_event/trace_arguments.h b/base/trace_event/trace_arguments.h index cf2f297..b658e8dd 100644 --- a/base/trace_event/trace_arguments.h +++ b/base/trace_event/trace_arguments.h
@@ -11,9 +11,9 @@ #include <algorithm> #include <memory> #include <string> +#include <utility> #include "base/base_export.h" -#include "base/macros.h" #include "base/trace_event/common/trace_event_common.h" // Trace macro can have one or two optional arguments, each one of them @@ -139,6 +139,8 @@ class BASE_EXPORT ConvertableToTraceFormat { public: ConvertableToTraceFormat() = default; + ConvertableToTraceFormat(const ConvertableToTraceFormat&) = delete; + ConvertableToTraceFormat& operator=(const ConvertableToTraceFormat&) = delete; virtual ~ConvertableToTraceFormat() = default; // Append the class info to the provided |out| string. The appended @@ -163,9 +165,6 @@ virtual bool AppendToProto(ProtoAppender* appender); virtual void EstimateTraceMemoryOverhead(TraceEventMemoryOverhead* overhead); - - private: - DISALLOW_COPY_AND_ASSIGN(ConvertableToTraceFormat); }; const int kTraceMaxNumArgs = 2;
diff --git a/base/trace_event/trace_event.h b/base/trace_event/trace_event.h index a0baf22..6c6a6c0 100644 --- a/base/trace_event/trace_event.h +++ b/base/trace_event/trace_event.h
@@ -12,11 +12,12 @@ #include <stddef.h> #include <stdint.h> +#include <memory> #include <string> +#include <utility> #include "base/atomicops.h" #include "base/debug/debugging_buildflags.h" -#include "base/macros.h" #include "base/time/time.h" #include "base/time/time_override.h" #include "base/trace_event/builtin_categories.h" @@ -181,10 +182,8 @@ // Implementation detail: trace event macros create temporary variables // to keep instrumentation overhead low. These macros give each temporary // variable a unique name based on the line number to prevent name collisions. -#define INTERNAL_TRACE_EVENT_UID3(a,b) \ - trace_event_unique_##a##b -#define INTERNAL_TRACE_EVENT_UID2(a,b) \ - INTERNAL_TRACE_EVENT_UID3(a,b) +#define INTERNAL_TRACE_EVENT_UID3(a, b) trace_event_unique_##a##b +#define INTERNAL_TRACE_EVENT_UID2(a, b) INTERNAL_TRACE_EVENT_UID3(a, b) #define INTERNAL_TRACE_EVENT_UID(name_prefix) \ INTERNAL_TRACE_EVENT_UID2(name_prefix, __LINE__) @@ -811,6 +810,9 @@ : name_(name), id_(id) { TRACE_EVENT_OBJECT_CREATED_WITH_ID(category, name_, id_); } + TraceScopedTrackableObject(const TraceScopedTrackableObject&) = delete; + TraceScopedTrackableObject& operator=(const TraceScopedTrackableObject&) = + delete; template <typename ArgType> void snapshot(ArgType snapshot) { TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(category, name_, id_, snapshot); @@ -823,8 +825,6 @@ private: const char* name_; IDType id_; - - DISALLOW_COPY_AND_ASSIGN(TraceScopedTrackableObject); }; } // namespace trace_event
diff --git a/base/trace_event/trace_event_etw_export_win.h b/base/trace_event/trace_event_etw_export_win.h index 8f5c884..b8d122c 100644 --- a/base/trace_event/trace_event_etw_export_win.h +++ b/base/trace_event/trace_event_etw_export_win.h
@@ -13,7 +13,6 @@ #include <memory> #include "base/base_export.h" -#include "base/macros.h" #include "base/strings/string_piece.h" #include "base/trace_event/trace_event_impl.h" #include "base/trace_event/trace_logging_minimal_win.h" @@ -27,6 +26,8 @@ class BASE_EXPORT TraceEventETWExport { public: + TraceEventETWExport(const TraceEventETWExport&) = delete; + TraceEventETWExport& operator=(const TraceEventETWExport&) = delete; ~TraceEventETWExport(); // Retrieves the singleton. @@ -90,8 +91,6 @@ // Maps category names to their keyword. std::map<StringPiece, uint64_t> categories_keyword_; - - DISALLOW_COPY_AND_ASSIGN(TraceEventETWExport); }; } // namespace trace_event
diff --git a/base/trace_event/trace_event_filter_test_utils.h b/base/trace_event/trace_event_filter_test_utils.h index 419068b22..d3f0102 100644 --- a/base/trace_event/trace_event_filter_test_utils.h +++ b/base/trace_event/trace_event_filter_test_utils.h
@@ -8,7 +8,6 @@ #include <memory> #include <string> -#include "base/macros.h" #include "base/trace_event/trace_event_filter.h" namespace base { @@ -31,6 +30,8 @@ const std::string& predicate_name); TestEventFilter(); + TestEventFilter(const TestEventFilter&) = delete; + TestEventFilter& operator=(const TestEventFilter&) = delete; ~TestEventFilter() override; // TraceEventFilter implementation. @@ -43,8 +44,6 @@ private: static bool filter_return_value_; - - DISALLOW_COPY_AND_ASSIGN(TestEventFilter); }; } // namespace trace_event
diff --git a/base/trace_event/trace_event_impl.h b/base/trace_event/trace_event_impl.h index eb41386..04216fd2 100644 --- a/base/trace_event/trace_event_impl.h +++ b/base/trace_event/trace_event_impl.h
@@ -15,7 +15,6 @@ #include "base/atomicops.h" #include "base/base_export.h" #include "base/callback.h" -#include "base/macros.h" #include "base/observer_list.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_util.h" @@ -71,6 +70,8 @@ TraceArguments* args, unsigned int flags); + TraceEvent(const TraceEvent&) = delete; + TraceEvent& operator=(const TraceEvent&) = delete; ~TraceEvent(); // Allow move operations. @@ -189,8 +190,6 @@ unsigned int flags_ = 0; unsigned long long bind_id_ = 0; char phase_ = TRACE_EVENT_PHASE_BEGIN; - - DISALLOW_COPY_AND_ASSIGN(TraceEvent); }; } // namespace trace_event
diff --git a/base/trace_event/trace_event_memory_overhead.h b/base/trace_event/trace_event_memory_overhead.h index e10a3ec..e7902c82 100644 --- a/base/trace_event/trace_event_memory_overhead.h +++ b/base/trace_event/trace_event_memory_overhead.h
@@ -12,7 +12,6 @@ #include <unordered_map> #include "base/base_export.h" -#include "base/macros.h" namespace base { @@ -45,6 +44,8 @@ }; TraceEventMemoryOverhead(); + TraceEventMemoryOverhead(const TraceEventMemoryOverhead&) = delete; + TraceEventMemoryOverhead& operator=(const TraceEventMemoryOverhead&) = delete; ~TraceEventMemoryOverhead(); // Use this method to account the overhead of an object for which an estimate @@ -86,8 +87,6 @@ size_t count, size_t allocated_size_in_bytes, size_t resident_size_in_bytes); - - DISALLOW_COPY_AND_ASSIGN(TraceEventMemoryOverhead); }; } // namespace trace_event
diff --git a/base/trace_event/trace_event_stub.h b/base/trace_event/trace_event_stub.h index b10e949..e11fcdd 100644 --- a/base/trace_event/trace_event_stub.h +++ b/base/trace_event/trace_event_stub.h
@@ -7,10 +7,10 @@ #include <stddef.h> +#include <memory> #include <string> #include "base/base_export.h" -#include "base/macros.h" #include "base/strings/string_piece.h" #include "base/trace_event/common/trace_event_common.h" #include "base/trace_event/memory_allocator_dump_guid.h" @@ -78,6 +78,8 @@ class BASE_EXPORT ConvertableToTraceFormat { public: ConvertableToTraceFormat() = default; + ConvertableToTraceFormat(const ConvertableToTraceFormat&) = delete; + ConvertableToTraceFormat& operator=(const ConvertableToTraceFormat&) = delete; virtual ~ConvertableToTraceFormat(); // Append the class info to the provided |out| string. The appended @@ -85,9 +87,6 @@ // escaped. There is no processing applied to the content after it is // appended. virtual void AppendAsTraceFormat(std::string* out) const = 0; - - private: - DISALLOW_COPY_AND_ASSIGN(ConvertableToTraceFormat); }; class BASE_EXPORT TracedValue : public ConvertableToTraceFormat { @@ -159,6 +158,8 @@ class BASE_EXPORT MemoryDumpProvider { public: + MemoryDumpProvider(const MemoryDumpProvider&) = delete; + MemoryDumpProvider& operator=(const MemoryDumpProvider&) = delete; virtual ~MemoryDumpProvider(); virtual bool OnMemoryDump(const MemoryDumpArgs& args, @@ -166,8 +167,6 @@ protected: MemoryDumpProvider() = default; - - DISALLOW_COPY_AND_ASSIGN(MemoryDumpProvider); }; } // namespace trace_event
diff --git a/base/trace_event/trace_log.cc b/base/trace_event/trace_log.cc index 27d132b..b7728b9 100644 --- a/base/trace_event/trace_log.cc +++ b/base/trace_event/trace_log.cc
@@ -17,7 +17,6 @@ #include "base/debug/leak_annotations.h" #include "base/location.h" #include "base/logging.h" -#include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/memory/ref_counted_memory.h" #include "base/no_destructor.h" @@ -138,11 +137,12 @@ DCHECK(!thread_local_boolean_->Get()); thread_local_boolean_->Set(true); } + AutoThreadLocalBoolean(const AutoThreadLocalBoolean&) = delete; + AutoThreadLocalBoolean& operator=(const AutoThreadLocalBoolean&) = delete; ~AutoThreadLocalBoolean() { thread_local_boolean_->Set(false); } private: ThreadLocalBoolean* thread_local_boolean_; - DISALLOW_COPY_AND_ASSIGN(AutoThreadLocalBoolean); }; // Use this function instead of TraceEventHandle constructor to keep the @@ -186,7 +186,10 @@ // and unlocks at the end of scope if locked. class TraceLog::OptionalAutoLock { public: - explicit OptionalAutoLock(Lock* lock) : lock_(lock), locked_(false) {} + explicit OptionalAutoLock(Lock* lock) : lock_(lock) {} + + OptionalAutoLock(const OptionalAutoLock&) = delete; + OptionalAutoLock& operator=(const OptionalAutoLock&) = delete; ~OptionalAutoLock() { if (locked_) @@ -204,8 +207,7 @@ private: Lock* lock_; - bool locked_; - DISALLOW_COPY_AND_ASSIGN(OptionalAutoLock); + bool locked_ = false; }; class TraceLog::ThreadLocalEventBuffer @@ -213,6 +215,8 @@ public MemoryDumpProvider { public: explicit ThreadLocalEventBuffer(TraceLog* trace_log); + ThreadLocalEventBuffer(const ThreadLocalEventBuffer&) = delete; + ThreadLocalEventBuffer& operator=(const ThreadLocalEventBuffer&) = delete; ~ThreadLocalEventBuffer() override; TraceEvent* AddTraceEvent(TraceEventHandle* handle); @@ -246,15 +250,12 @@ // as long as the thread exists. TraceLog* trace_log_; std::unique_ptr<TraceBufferChunk> chunk_; - size_t chunk_index_; + size_t chunk_index_ = 0; int generation_; - - DISALLOW_COPY_AND_ASSIGN(ThreadLocalEventBuffer); }; TraceLog::ThreadLocalEventBuffer::ThreadLocalEventBuffer(TraceLog* trace_log) : trace_log_(trace_log), - chunk_index_(0), generation_(trace_log->generation()) { // ThreadLocalEventBuffer is created only if the thread has a message loop, so // the following message_loop won't be NULL.
diff --git a/base/trace_event/traced_value.h b/base/trace_event/traced_value.h index ee00440..5c251e2 100644 --- a/base/trace_event/traced_value.h +++ b/base/trace_event/traced_value.h
@@ -12,7 +12,6 @@ #include <string> #include <vector> -#include "base/macros.h" #include "base/pickle.h" #include "base/strings/string_piece.h" #include "base/trace_event/trace_event_impl.h" @@ -28,6 +27,8 @@ // TODO(oysteine): |capacity| is not used in any production code. Consider // removing it. explicit TracedValue(size_t capacity = 0); + TracedValue(const TracedValue&) = delete; + TracedValue& operator=(const TracedValue&) = delete; ~TracedValue() override; void EndDictionary(); @@ -393,8 +394,6 @@ // In debug builds checks the pairings of {Start,End}{Dictionary,Array} std::vector<bool> nesting_stack_; #endif - - DISALLOW_COPY_AND_ASSIGN(TracedValue); }; // TracedValue that is convertable to JSON format. This has lower performance
diff --git a/build/android/gyp/gcc_preprocess.py b/build/android/gyp/gcc_preprocess.py index 8c5c404..8f6ec8d 100755 --- a/build/android/gyp/gcc_preprocess.py +++ b/build/android/gyp/gcc_preprocess.py
@@ -4,51 +4,60 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -import optparse +import argparse import os +import posixpath +import re import sys +import zipfile from util import build_utils -def DoGcc(options): - build_utils.MakeDirectory(os.path.dirname(options.output)) - gcc_cmd = [ 'gcc' ] # invoke host gcc. - if options.defines: - gcc_cmd.extend(sum(map(lambda w: ['-D', w], options.defines), [])) - - with build_utils.AtomicOutput(options.output) as f: - gcc_cmd.extend([ - '-E', # stop after preprocessing. - '-D', 'ANDROID', # Specify ANDROID define for pre-processor. - '-x', 'c-header', # treat sources as C header files - '-P', # disable line markers, i.e. '#line 309' - '-I', options.include_path, - '-o', f.name, - options.template - ]) - - build_utils.CheckOutput(gcc_cmd) +def _ParsePackageName(data): + m = re.match(r'^\s*package\s+(.*?)\s*;', data, re.MULTILINE) + return m.group(1) if m else '' def main(args): args = build_utils.ExpandFileArgs(args) - parser = optparse.OptionParser() - build_utils.AddDepfileOption(parser) + parser = argparse.ArgumentParser() + parser.add_argument('--include-dirs', help='GN list of include directories.') + parser.add_argument('--output', help='Path for .srcjar.') + parser.add_argument('--define', + action='append', + dest='defines', + help='List of -D args') + parser.add_argument('templates', nargs='+', help='Template files.') + options = parser.parse_args(args) - parser.add_option('--include-path', help='Include path for gcc.') - parser.add_option('--template', help='Path to template.') - parser.add_option('--output', help='Path for generated file.') - parser.add_option('--defines', help='Pre-defines macros', action='append') + options.defines = build_utils.ParseGnList(options.defines) + options.include_dirs = build_utils.ParseGnList(options.include_dirs) - options, _ = parser.parse_args(args) + gcc_cmd = [ + 'gcc', + '-E', # stop after preprocessing. + '-DANDROID', # Specify ANDROID define for pre-processor. + '-x', + 'c-header', # treat sources as C header files + '-P', # disable line markers, i.e. '#line 309' + ] + gcc_cmd.extend('-D' + x for x in options.defines) + gcc_cmd.extend('-I' + x for x in options.include_dirs) - DoGcc(options) - - if options.depfile: - build_utils.WriteDepfile(options.depfile, options.output) + with build_utils.AtomicOutput(options.output) as f: + with zipfile.ZipFile(f, 'w') as z: + for template in options.templates: + data = build_utils.CheckOutput(gcc_cmd + [template]) + package_name = _ParsePackageName(data) + if not package_name: + raise Exception('Could not find java package of ' + template) + zip_path = posixpath.join( + package_name.replace('.', '/'), + os.path.splitext(os.path.basename(template))[0]) + '.java' + build_utils.AddToZipHermetic(z, zip_path, data=data) if __name__ == '__main__': - sys.exit(main(sys.argv[1:])) + main(sys.argv[1:])
diff --git a/build/config/android/rules.gni b/build/config/android/rules.gni index 7fd7bf1..4832714 100644 --- a/build/config/android/rules.gni +++ b/build/config/android/rules.gni
@@ -405,8 +405,7 @@ # FooBar.java. # inputs: additional compile-time dependencies. Any files # `#include`-ed in the templates should be listed here. - # package_path: this will be the subdirectory for each .java file in the - # .srcjar. + # defines: List of -D arguments for the preprocessor. # # Example # java_cpp_template("foo_generated_enum") { @@ -416,72 +415,41 @@ # inputs = [ # "android/java/templates/native_foo_header.h", # ] - # - # package_path = "org/chromium/base/library_loader" - # include_path = "android/java/templates" # } template("java_cpp_template") { - forward_variables_from(invoker, [ "testonly" ]) - - _include_path = "//" - if (defined(invoker.include_path)) { - _include_path = invoker.include_path - } - - _apply_gcc_target_name = "${target_name}__apply_gcc" - _base_gen_dir = "${target_gen_dir}/${target_name}/java_cpp_template" - _package_path = invoker.package_path - - action_foreach_with_pydeps(_apply_gcc_target_name) { + action_with_pydeps(target_name) { forward_variables_from(invoker, [ + "data_deps", "deps", "inputs", "public_deps", - "data_deps", + "sources", + "testonly", + "visibility", ]) script = "//build/android/gyp/gcc_preprocess.py" - depfile = - "${target_gen_dir}/${invoker.target_name}_{{source_name_part}}.d" + outputs = [ "$target_gen_dir/$target_name.srcjar" ] - sources = invoker.sources - - outputs = [ "$_base_gen_dir/${_package_path}/{{source_name_part}}.java" ] - + _include_dirs = [ + "//", + root_gen_dir, + ] + _rebased_include_dirs = rebase_path(_include_dirs, root_build_dir) args = [ - "--depfile", - rebase_path(depfile, root_build_dir), - "--include-path", - rebase_path(_include_path, root_build_dir), + "--include-dirs=$_rebased_include_dirs", "--output", rebase_path(outputs[0], root_build_dir), - "--template={{source}}", ] - if (defined(invoker.defines)) { - foreach(_def, invoker.defines) { + foreach(_define, invoker.defines) { args += [ - "--defines", - _def, + "--define", + _define, ] } } - } - - # Filter out .d files. - sources = [] - foreach(_output, get_target_outputs(":$_apply_gcc_target_name")) { - if (get_path_info(_output, "extension") != "d") { - sources += [ _output ] - } - } - - zip(target_name) { - forward_variables_from(invoker, [ "visibility" ]) - inputs = sources - output = "${target_gen_dir}/${target_name}.srcjar" - base_dir = _base_gen_dir - deps = [ ":$_apply_gcc_target_name" ] + args += rebase_path(sources, root_build_dir) } } @@ -2058,7 +2026,6 @@ # is_incremental_install: template("generate_build_config_srcjar") { java_cpp_template(target_name) { - package_path = "org/chromium/base" sources = [ "//base/android/java/templates/BuildConfig.template" ] defines = [] @@ -2132,7 +2099,6 @@ defines += [ "USE_FINAL" ] } - package_path = string_replace(invoker.java_package, ".", "/") sources = [ "//build/android/java/templates/ProductConfig.template" ] defines += [ "PACKAGE=${invoker.java_package}" ]
diff --git a/build/config/fuchsia/generate_runner_scripts.gni b/build/config/fuchsia/generate_runner_scripts.gni index 2a50b0f..05d4752c 100644 --- a/build/config/fuchsia/generate_runner_scripts.gni +++ b/build/config/fuchsia/generate_runner_scripts.gni
@@ -129,7 +129,7 @@ } foreach(fuchsia_additional_boot_image, fuchsia_additional_boot_images) { - data += [ "${fuchsia_additional_boot_images}/" ] + data += [ "${fuchsia_additional_boot_image}/" ] } executable_args = []
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1 index 7831db06..a3a002f8 100644 --- a/build/fuchsia/linux.sdk.sha1 +++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@ -0.20201009.1.1 +0.20201009.3.1
diff --git a/build/fuchsia/mac.sdk.sha1 b/build/fuchsia/mac.sdk.sha1 index 7831db06..a3a002f8 100644 --- a/build/fuchsia/mac.sdk.sha1 +++ b/build/fuchsia/mac.sdk.sha1
@@ -1 +1 @@ -0.20201009.1.1 +0.20201009.3.1
diff --git a/build/lacros/BUILD.gn b/build/lacros/BUILD.gn index 683ae18..82bca9a 100644 --- a/build/lacros/BUILD.gn +++ b/build/lacros/BUILD.gn
@@ -6,5 +6,6 @@ python_library("lacros_resource_sizes_py") { pydeps_file = "lacros_resource_sizes.pydeps" + data = [ "//buildtools/third_party/eu-strip/bin/eu-strip" ] data_deps = [ "//third_party/catapult/tracing:convert_chart_json" ] }
diff --git a/build/lacros/lacros_resource_sizes.py b/build/lacros/lacros_resource_sizes.py index 1244364..0d6fb7d 100755 --- a/build/lacros/lacros_resource_sizes.py +++ b/build/lacros/lacros_resource_sizes.py
@@ -8,12 +8,14 @@ """ import argparse +import collections import contextlib import json import logging import os import subprocess import sys +import tempfile @contextlib.contextmanager @@ -41,6 +43,9 @@ TRACING_PATH = os.path.join(DIR_SOURCE_ROOT, 'third_party', 'catapult', 'tracing') +EU_STRIP_PATH = os.path.join(DIR_SOURCE_ROOT, 'buildtools', 'third_party', + 'eu-strip', 'bin', 'eu-strip') + with _SysPath(BUILD_COMMON_PATH): import perf_tests_results_helper # pylint: disable=import-error @@ -55,6 +60,11 @@ 'charts': {} } +_KEY_RAW = 'raw' +_KEY_GZIPPED = 'gzipped' +_KEY_STRIPPED = 'stripped' +_KEY_STRIPPED_GZIPPED = 'stripped_then_gzipped' + class _Group: """A group of build artifacts whose file sizes are summed and tracked. @@ -67,12 +77,15 @@ Attributes: paths: A list of files or directories to be tracked together. title: The display name of the group. + track_stripped: Whether to also track summed stripped ELF sizes. track_compressed: Whether to also track summed compressed sizes. """ - def __init__(self, paths, title, track_compressed=False): + def __init__(self, paths, title, track_stripped=False, + track_compressed=False): self.paths = paths self.title = title + self.track_stripped = track_stripped self.track_compressed = track_compressed @@ -81,7 +94,10 @@ # //infra/config/subprojects/chromium/ci.star) and # chromeos-amd64-generic-lacros-internal builder (specified in src-internal). _TRACKED_GROUPS = [ - _Group(paths=['chrome'], title='File: chrome', track_compressed=True), + _Group(paths=['chrome'], + title='File: chrome', + track_stripped=True, + track_compressed=True), _Group(paths=['crashpad_handler'], title='File: crashpad_handler'), _Group(paths=['icudtl.dat'], title='File: icudtl.dat'), _Group(paths=['nacl_helper'], title='File: nacl_helper'), @@ -120,6 +136,17 @@ logging.critical('Not found: %s', path) +def _is_probably_elf(filename): + """Heuristically decides whether |filename| is ELF via magic signature.""" + with open(filename, 'rb') as fh: + return fh.read(4) == '\x7FELF' + + +def _is_unstrippable_elf(filename): + """Identifies known-unstrippable ELF files to denoise the system.""" + return filename.endswith('.nexe') or filename.endswith('libwidevinecdm.so') + + def _get_filesize(filename): """Returns the size of a file, or 0 if file is not found.""" try: @@ -152,6 +179,37 @@ return 0 +def _get_catagorized_filesizes(filename): + """Measures |filename| sizes under various transforms. + + Returns: A Counter (keyed by _Key_* constants) that stores measured sizes. + """ + sizes = collections.Counter() + sizes[_KEY_RAW] = _get_filesize(filename) + sizes[_KEY_GZIPPED] = _get_gzipped_filesize(filename) + + # Pre-assign values for non-ELF, or in case of failure for ELF. + sizes[_KEY_STRIPPED] = sizes[_KEY_RAW] + sizes[_KEY_STRIPPED_GZIPPED] = sizes[_KEY_GZIPPED] + + if _is_probably_elf(filename) and not _is_unstrippable_elf(filename): + try: + fd, temp_file = tempfile.mkstemp() + os.close(fd) + cmd = [EU_STRIP_PATH, filename, '-o', temp_file] + subprocess.check_output(cmd) + sizes[_KEY_STRIPPED] = _get_filesize(temp_file) + sizes[_KEY_STRIPPED_GZIPPED] = _get_gzipped_filesize(temp_file) + if sizes[_KEY_STRIPPED] > sizes[_KEY_RAW]: + # This weird case has been observed for libwidevinecdm.so. + logging.critical('Stripping made things worse for %s' % filename) + except subprocess.CalledProcessError: + logging.critical('Failed to strip file: %s' % filename) + finally: + os.unlink(temp_file) + return sizes + + def _dump_chart_json(output_dir, chartjson): """Writes chart histogram to JSON files. @@ -189,41 +247,49 @@ """Main flow to extract and output size data.""" chartjson = _BASE_CHART.copy() report_func = perf_tests_results_helper.ReportPerfResult - total_size = 0 - total_gzipped = 0 - for group in _TRACKED_GROUPS: - group_size = sum(map(_get_filesize, _visit_paths(args.out_dir, - group.paths))) - group_gzipped = sum( - map(_get_gzipped_filesize, _visit_paths(args.out_dir, group.paths))) + total_sizes = collections.Counter() + + def report_sizes(sizes, title, track_stripped, track_compressed): report_func(chart_data=chartjson, - graph_title=group.title, + graph_title=title, trace_title='size', - value=group_size, + value=sizes[_KEY_RAW], units='bytes') - if group.track_compressed: + + if track_stripped: report_func(chart_data=chartjson, - graph_title=group.title + ' (Gzipped)', + graph_title=title + ' (Stripped)', trace_title='size', - value=group_gzipped, + value=sizes[_KEY_STRIPPED], units='bytes') - total_size += group_size - # Summing compressed size of separate groups (instead of concatanating - # first) to get a conservative estimate. File metadata and overheads are - # assumed to be negligible. - total_gzipped += group_gzipped - report_func(chart_data=chartjson, - graph_title='Total', - trace_title='size', - value=total_size, - units='bytes') + if track_compressed: + report_func(chart_data=chartjson, + graph_title=title + ' (Gzipped)', + trace_title='size', + value=sizes[_KEY_GZIPPED], + units='bytes') - report_func(chart_data=chartjson, - graph_title='Total (Gzipped)', - trace_title='size', - value=total_gzipped, - units='bytes') + if track_stripped and track_compressed: + report_func(chart_data=chartjson, + graph_title=title + ' (Stripped, Gzipped)', + trace_title='size', + value=sizes[_KEY_STRIPPED_GZIPPED], + units='bytes') + + for g in _TRACKED_GROUPS: + sizes = sum( + map(_get_catagorized_filesizes, _visit_paths(args.out_dir, g.paths)), + collections.Counter()) + report_sizes(sizes, g.title, g.track_stripped, g.track_compressed) + + # Total compressed size is summed over individual compressed sizes, instead + # of concatanating first, then compress everything. This is done for + # simplicity. It also gives a conservative size estimate (assuming file + # metadata and overheads are negligible). + total_sizes += sizes + + report_sizes(total_sizes, 'Total', True, True) _dump_chart_json(args.output_dir, chartjson)
diff --git a/cc/benchmarks/rasterize_and_record_benchmark.cc b/cc/benchmarks/rasterize_and_record_benchmark.cc index 5c23cd8..44928c4 100644 --- a/cc/benchmarks/rasterize_and_record_benchmark.cc +++ b/cc/benchmarks/rasterize_and_record_benchmark.cc
@@ -125,14 +125,8 @@ return; ContentLayerClient* painter = layer->client(); - RecordingSource recording_source; - - scoped_refptr<DisplayItemList> display_list; - display_list = painter->PaintContentsToDisplayList(); - recording_source.UpdateDisplayItemList( - display_list, painter->GetApproximateUnsharedMemoryUsage(), - layer_tree_host_->recording_scale_factor()); - + scoped_refptr<DisplayItemList> display_list = + painter->PaintContentsToDisplayList(); record_results_.painter_memory_usage += painter->GetApproximateUnsharedMemoryUsage(); record_results_.paint_op_memory_usage += display_list->BytesUsed();
diff --git a/chrome/android/BUILD.gn b/chrome/android/BUILD.gn index 461a445e..8f36311 100644 --- a/chrome/android/BUILD.gn +++ b/chrome/android/BUILD.gn
@@ -266,7 +266,6 @@ } java_cpp_template("vr_build_config") { - package_path = "org/chromium/chrome/browser/vr" sources = [ "//chrome/android/java/src/org/chromium/chrome/browser/vr/VrBuildConfig.template" ] if (enable_vr) { defines = [ "ENABLE_VR" ] @@ -600,7 +599,6 @@ java_cpp_template("chrome_strict_mode_switch") { sources = [ "java/src/org/chromium/chrome/browser/ChromeStrictModeSwitch.template" ] - package_path = "org/chromium/chrome/browser" # Strict mode detection is disabled for canary channel in order to catch bugs # related to strict mode detection being turned off early (before beta @@ -745,7 +743,6 @@ java_cpp_template("resource_id_javagen") { sources = [ "java/ResourceId.template" ] - package_path = "org/chromium/chrome/browser/resources" inputs = [ "../browser/android/resource_id.h", "//components/resources/android/blocked_content_resource_id.h",
diff --git a/chrome/android/features/tab_ui/java/strings/translations/android_chrome_tab_ui_strings_ne.xtb b/chrome/android/features/tab_ui/java/strings/translations/android_chrome_tab_ui_strings_ne.xtb index 956fb34..f5133aa8 100644 --- a/chrome/android/features/tab_ui/java/strings/translations/android_chrome_tab_ui_strings_ne.xtb +++ b/chrome/android/features/tab_ui/java/strings/translations/android_chrome_tab_ui_strings_ne.xtb
@@ -23,7 +23,7 @@ <translation id="4648718555153979859">तपाईंका ट्याबहरू यहाँ एकै ठाउँमा समूहबद्ध गरिएको छन्</translation> <translation id="5007392906805964215">समीक्षा गर्नुहोस्</translation> <translation id="5073204694187207510">फुल स्क्रिन ग्रिड लुकाउनुहोस्</translation> -<translation id="5082793167783849073">कुनै समूह बनाएर द्रुत रूपमा पृष्ठहरूको तुलना गर्नुहोस्। सुरु गर्न कुनै लिंकमा छोइराख्नुहोस्।</translation> +<translation id="5082793167783849073">कुनै समूह बनाएर द्रुत रूपमा पृष्ठहरूको तुलना गर्नुहोस्। सुरु गर्न कुनै लिंकमा टच एण्ड होल्ड गर्नुहोस्।</translation> <translation id="5490235265819901748">ट्याब समूह विस्तृत गरियो</translation> <translation id="5533021382642990449">पछि देखाइयोस्</translation> <translation id="5558362125926932819"><ph name="NUMBER_OF_TABS" /> वटा ट्याब भएको ट्याब समूह बन्द गर्नुहोस्</translation> @@ -35,7 +35,7 @@ <translation id="6510648526783655549">ट्याब स्ट्रिप बन्द गर्नुहोस्</translation> <translation id="6562820390860419811">ट्याब सारेर बायाँतिर लैजानुहोस्</translation> <translation id="6615455863669487791">मलाई देखाउनुहोस्</translation> -<translation id="6840760312327750441">ट्याबहरू समूहबद्ध गर्न कुनै ट्याबमा छोइराख्नुहोस्। त्यसपछि, त्यसलाई ड्र्याग गरी अर्को ट्याबमा लैजानुहोस्।</translation> +<translation id="6840760312327750441">ट्याबहरू समूहबद्ध गर्न कुनै ट्याबमा टच एण्ड होल्ड गर्नुहोस्। त्यसपछि, त्यसलाई ड्र्याग गरी अर्को ट्याबमा लैजानुहोस्।</translation> <translation id="6856809498882026482">एकभन्दा बढी ट्याब चयन गर्ने मोड लुकाउनुहोस्</translation> <translation id="7151209024774799310">समूहबाट ट्याबहरू हटाउनुहोस्</translation> <translation id="7204204600596740190">एकभन्दा बढी ट्याब चयन गर्ने मोड</translation>
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ChromeStrictMode.java b/chrome/android/java/src/org/chromium/chrome/browser/ChromeStrictMode.java index dc9bedb..3af8707 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeStrictMode.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeStrictMode.java
@@ -211,6 +211,12 @@ threadInterceptor.ignoreExternalMethod(Violation.DETECT_DISK_READ, "android.net.ConnectivityManager#registerDefaultNetworkCallback"); } + + // crbug.com/1133401 + threadInterceptor.ignoreExternalMethod( + Violation.DETECT_DISK_IO, "android.content.ContentResolver#setIsSyncable"); + threadInterceptor.ignoreExternalMethod( + Violation.DETECT_DISK_IO, "android.content.ContentResolver#setSyncAutomatically"); } public static void addExemptions(ThreadStrictModeInterceptor.Builder threadInterceptor) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/accessibility_tab_switcher/AccessibilityTabModelAdapter.java b/chrome/android/java/src/org/chromium/chrome/browser/accessibility_tab_switcher/AccessibilityTabModelAdapter.java index 826fd3c2..0b3b17d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/accessibility_tab_switcher/AccessibilityTabModelAdapter.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/accessibility_tab_switcher/AccessibilityTabModelAdapter.java
@@ -139,7 +139,8 @@ } listItem.setTab(TabModelUtils.getTabById(mUndoneTabModel, tabId), - mActualTabModel.supportsPendingClosures()); + mActualTabModel.supportsPendingClosures(), + TabModelUtils.getCurrentTab(mUndoneTabModel).getId() == tabId); listItem.setListeners(mInternalListener, mCanScrollListener); listItem.resetState();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/accessibility_tab_switcher/AccessibilityTabModelListItem.java b/chrome/android/java/src/org/chromium/chrome/browser/accessibility_tab_switcher/AccessibilityTabModelListItem.java index abc29f7..b8d24d0 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/accessibility_tab_switcher/AccessibilityTabModelListItem.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/accessibility_tab_switcher/AccessibilityTabModelListItem.java
@@ -86,6 +86,7 @@ private Tab mTab; private boolean mCanUndo; + private boolean mIsSelected; private AccessibilityTabModelListItemListener mListener; private final GestureDetector mSwipeGestureDetector; private final int mDefaultHeight; @@ -269,12 +270,14 @@ * Sets the {@link Tab} this {@link View} will represent in the list. * @param tab The {@link Tab} to represent. * @param canUndo Whether or not closing this {@link Tab} can be undone. + * @param isSelected Whether or not the {@link Tab} is the currently selected one. */ - public void setTab(Tab tab, boolean canUndo) { + public void setTab(Tab tab, boolean canUndo, boolean isSelected) { if (mTab != null) mTab.removeObserver(mTabObserver); mTab = tab; tab.addObserver(mTabObserver); mCanUndo = canUndo; + mIsSelected = isSelected; updateTabText(); updateFavicon(); } @@ -315,11 +318,11 @@ if (!title.equals(mTitleView.getText())) mTitleView.setText(title); - String accessibilityString = - getContext().getString(R.string.accessibility_tabstrip_tab, title); + String accessibilityString = mIsSelected + ? getContext().getString(R.string.accessibility_tabstrip_tab_selected, title) + : getContext().getString(R.string.accessibility_tabstrip_tab, title); if (!accessibilityString.equals(getContentDescription())) { - setContentDescription( - getContext().getString(R.string.accessibility_tabstrip_tab, title)); + setContentDescription(accessibilityString); mCloseButton.setContentDescription( getContext().getString(R.string.accessibility_tabstrip_btn_close_tab, title)); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/sync/AndroidSyncSettings.java b/chrome/android/java/src/org/chromium/chrome/browser/sync/AndroidSyncSettings.java index ff9f5cc..21aef454 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/sync/AndroidSyncSettings.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/sync/AndroidSyncSettings.java
@@ -16,7 +16,6 @@ import org.chromium.base.ContextUtils; import org.chromium.base.ObserverList; -import org.chromium.base.StrictModeContext; import org.chromium.base.ThreadUtils; import org.chromium.base.task.PostTask; import org.chromium.chrome.browser.flags.ChromeFeatureList; @@ -227,9 +226,7 @@ if (value == mChromeSyncEnabled || mAccount == null) return; mChromeSyncEnabled = value; - try (StrictModeContext ignored = StrictModeContext.allowDiskWrites()) { - mSyncContentResolverDelegate.setSyncAutomatically(mAccount, mContractAuthority, value); - } + mSyncContentResolverDelegate.setSyncAutomatically(mAccount, mContractAuthority, value); notifyObservers(); } @@ -246,29 +243,24 @@ mIsSyncable = shouldBeSyncable; - try (StrictModeContext ignored = StrictModeContext.allowDiskWrites()) { - // Make account syncable if there is one. - if (shouldBeSyncable) { - mSyncContentResolverDelegate.setIsSyncable(mAccount, mContractAuthority, 1); - // This reduces unnecessary resource usage. See http://crbug.com/480688 for details. - mSyncContentResolverDelegate.removePeriodicSync( - mAccount, mContractAuthority, Bundle.EMPTY); - } else if (mAccount != null) { - mSyncContentResolverDelegate.setIsSyncable(mAccount, mContractAuthority, 0); - } + // Make account syncable if there is one. + if (shouldBeSyncable) { + mSyncContentResolverDelegate.setIsSyncable(mAccount, mContractAuthority, 1); + // This reduces unnecessary resource usage. See http://crbug.com/480688 for details. + mSyncContentResolverDelegate.removePeriodicSync( + mAccount, mContractAuthority, Bundle.EMPTY); + } else if (mAccount != null) { + mSyncContentResolverDelegate.setIsSyncable(mAccount, mContractAuthority, 0); } // Disable the syncability of Chrome for all other accounts. AccountManagerFacadeProvider.getInstance().tryGetGoogleAccounts(accounts -> { - try (StrictModeContext ignored = StrictModeContext.allowDiskWrites()) { - for (Account account : accounts) { - if (account.equals(mAccount)) continue; - if (mSyncContentResolverDelegate.getIsSyncable(account, mContractAuthority) - <= 0) { - continue; - } - mSyncContentResolverDelegate.setIsSyncable(account, mContractAuthority, 0); + for (Account account : accounts) { + if (account.equals(mAccount)) continue; + if (mSyncContentResolverDelegate.getIsSyncable(account, mContractAuthority) <= 0) { + continue; } + mSyncContentResolverDelegate.setIsSyncable(account, mContractAuthority, 0); } }); } @@ -283,19 +275,16 @@ boolean oldChromeSyncEnabled = mChromeSyncEnabled; boolean oldMasterSyncEnabled = mMasterSyncEnabled; - try (StrictModeContext ignored = StrictModeContext.allowDiskWrites()) { - if (mAccount != null) { - mIsSyncable = - mSyncContentResolverDelegate.getIsSyncable(mAccount, mContractAuthority) - > 0; - mChromeSyncEnabled = mSyncContentResolverDelegate.getSyncAutomatically( - mAccount, mContractAuthority); - } else { - mIsSyncable = false; - mChromeSyncEnabled = false; - } - mMasterSyncEnabled = mSyncContentResolverDelegate.getMasterSyncAutomatically(); + if (mAccount != null) { + mIsSyncable = + mSyncContentResolverDelegate.getIsSyncable(mAccount, mContractAuthority) > 0; + mChromeSyncEnabled = + mSyncContentResolverDelegate.getSyncAutomatically(mAccount, mContractAuthority); + } else { + mIsSyncable = false; + mChromeSyncEnabled = false; } + mMasterSyncEnabled = mSyncContentResolverDelegate.getMasterSyncAutomatically(); if (mAccount != null && ProfileSyncService.get() != null && ChromeFeatureList.isEnabled(
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestTestRule.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestTestRule.java index 6dabb663..fb941f6c 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestTestRule.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestTestRule.java
@@ -158,12 +158,59 @@ private final MainActivityStartCallback mCallback; + /** + * Creates an instance of PaymentRequestTestRule. + * @param testFileName The file name of an test page in //components/test/data/payments, + * 'about:blank', or a data url which starts with 'data:'. + */ + public PaymentRequestTestRule(String testFileName) { + this(testFileName, null); + } + + /** + * Creates an instance of PaymentRequestTestRule. + * @param testFileName The file name of an test page in //components/test/data/payments, + * 'about:blank', or a data url which starts with 'data:'. + * @param callback A callback that is invoked on the start of the main activity. + */ public PaymentRequestTestRule(String testFileName, MainActivityStartCallback callback) { this(testFileName, callback, false); } + /** + * Creates an instance of PaymentRequestTestRule. + * @param testFileName The file name of an test page in //components/test/data/payments, + * 'about:blank', or a data url which starts with 'data:'. + * @param callback A callback that is invoked on the start of the main activity. + * @param delayStartActivity Whether to delay the start of the main activity. When true, {@link + * #startMainActivity()} needs to be called to start the main activity; otherwise, the + * main activity would start automatically. + */ public PaymentRequestTestRule( String testFileName, MainActivityStartCallback callback, boolean delayStartActivity) { + this(testFileName, /*pathPrefix=*/"components/test/data/payments/", callback, + delayStartActivity); + } + + /** + * Creates an instance of PaymentRequestTestRule with a test page, which is specified by + * pathPrefix and testFileName combined into a path relative to the repository root. For + * example, if testFileName is "merchant.html", pathPrefix is "components/test/data/payments/", + * the method would look for a test page at "components/test/data/payments/merchant.html". + * This method is used by the //clank tests. + * @param testFileName The file name of the test page. + * @param pathPrefix The prefix path to testFileName. + * @param delayStartActivity Whether to delay the start of the main activity. + * @return The created instance. + */ + public static PaymentRequestTestRule createWithPathPrefix( + String testFileName, String pathPrefix, boolean delayStartActivity) { + assert pathPrefix.endsWith("/"); + return new PaymentRequestTestRule(testFileName, pathPrefix, null, delayStartActivity); + } + + private PaymentRequestTestRule(String testFilePath, String pathPrefix, + MainActivityStartCallback callback, boolean delayStartActivity) { super(); mReadyForInput = new PaymentsCallbackHelper<>(); mReadyToPay = new PaymentsCallbackHelper<>(); @@ -187,23 +234,21 @@ mCompleteReplied = new CallbackHelper(); mRendererClosedMojoConnection = new CallbackHelper(); mWebContentsRef = new AtomicReference<>(); - mTestFilePath = testFileName.equals("about:blank") || testFileName.startsWith("data:") - ? testFileName - : UrlUtils.getIsolatedTestFilePath( - String.format("components/test/data/payments/%s", testFileName)); + if (testFilePath.equals("about:blank") || testFilePath.startsWith("data:")) { + mTestFilePath = testFilePath; + } else { + mTestFilePath = UrlUtils.getIsolatedTestFilePath(pathPrefix + testFilePath); + } mCallback = callback; mDelayStartActivity = delayStartActivity; } - public PaymentRequestTestRule(String testFileName) { - this(testFileName, null); - } - public void startMainActivity() { startMainActivityWithURL(mTestFilePath); } - protected void openPage() throws TimeoutException { + // public is used so as to be visible to the payment tests in //clank. + public void openPage() throws TimeoutException { onMainActivityStarted(); ThreadUtils.runOnUiThreadBlocking(() -> { mWebContentsRef.set(getActivity().getCurrentWebContents()); @@ -327,7 +372,8 @@ return JavaScriptUtils.executeJavaScriptAndWaitForResult(mWebContentsRef.get(), script); } - protected String runJavascriptWithAsyncResult(String script) throws TimeoutException { + // public is used so as to be visible to the payment tests in //clank. + public String runJavascriptWithAsyncResult(String script) throws TimeoutException { return JavaScriptUtils.runJavascriptWithAsyncResult(mWebContentsRef.get(), script); }
diff --git a/chrome/android/webapk/libs/client/BUILD.gn b/chrome/android/webapk/libs/client/BUILD.gn index 32b6f20..1184019 100644 --- a/chrome/android/webapk/libs/client/BUILD.gn +++ b/chrome/android/webapk/libs/client/BUILD.gn
@@ -24,7 +24,6 @@ } java_cpp_template("runtime_library_version_java") { - package_path = "org/chromium/webapk/lib/client" sources = [ "src/org/chromium/webapk/lib/client/WebApkVersion.template" ] defines = [ "CURRENT_RUNTIME_DEX_VERSION_VALUE=$runtime_library_version",
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index 4415140..5bb50d0 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -6305,6 +6305,9 @@ <message name="IDS_FEEDBACK_CLOSE_BUTTON_LABEL" desc="Label of the app close button."> Close </message> + <message name="IDS_FEEDBACK_FREE_TEXT_LABEL" desc="Label of the text box where users can describe a problem they are having"> + Describe the issue in detail + </message> <message name="IDS_FEEDBACK_REPORT_URL_LABEL" desc="Label showing the URL that will be reported"> URL </message>
diff --git a/chrome/app/generated_resources_grd/IDS_FEEDBACK_FREE_TEXT_LABEL.png.sha1 b/chrome/app/generated_resources_grd/IDS_FEEDBACK_FREE_TEXT_LABEL.png.sha1 new file mode 100644 index 0000000..9a02781 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_FEEDBACK_FREE_TEXT_LABEL.png.sha1
@@ -0,0 +1 @@ +62ab3da137c6ef42076a8f50ebb70c8e6060ab61 \ No newline at end of file
diff --git a/chrome/app/resources/generated_resources_af.xtb b/chrome/app/resources/generated_resources_af.xtb index f23ac2c8..f57872b 100644 --- a/chrome/app/resources/generated_resources_af.xtb +++ b/chrome/app/resources/generated_resources_af.xtb
@@ -112,7 +112,7 @@ <translation id="1123753900084781868">Intydse Onderskrifte is nie nou onmiddellik beskikbaar nie</translation> <translation id="1124772482545689468">Gebruiker</translation> <translation id="1125550662859510761">Lyk soos <ph name="WIDTH" /> x <ph name="HEIGHT" /> (oorspronlik)</translation> -<translation id="1126809382673880764">Beskerm jou nie teen gevaarlike webwerwe, aflaaie en uitbreidings nie. Jy sal steeds Veiligblaai-beskerming in ander Google-dienste, soos Gmail en Search, kry waar dit beskikbaar is.</translation> +<translation id="1126809382673880764">Beskerm jou nie teen gevaarlike webwerwe, aflaaie en uitbreidings nie. Jy sal steeds Veiligblaai-beskerming kry, indien beskikbaar, in ander Google-dienste, soos Gmail en Search.</translation> <translation id="112752777279960360">Om 'n Android-foon vir die eerste keer op te stel om as 'n sekuriteitsleutel saam met hierdie rekenaar gebruik te word, moet jy Chrome op jou foon oopmaak en gaan na "Instellings > Wagwoorde > Gebruik foon as 'n sekuriteitsleutel". Tik dan op "Koppel nuwe toestel" en skandeer hierdie QR-kode.</translation> <translation id="1128109161498068552">Moenie enige werwe toelaat om boodskappe wat eksklusief tot die stelsel is, te gebruik om by MIDI-toestelle in te gaan nie.</translation> <translation id="1128128132059598906">EAP-TTLS</translation> @@ -4937,7 +4937,7 @@ <translation id="6876469544038980967">Nie nuttig nie</translation> <translation id="6878422606530379992">Sensors toegelaat</translation> <translation id="6880587130513028875">Prente is op hierdie bladsy geblokkeer.</translation> -<translation id="6882836635272038266">Standaardbeskerming teen webwerwe, aflaaie en uitbreidings wat bekend is dat hulle gevaarlik is.</translation> +<translation id="6882836635272038266">Standaardbeskerming teen webwerwe, aflaaie en uitbreidings wat bekend is daarvoor dat hulle gevaarlik is.</translation> <translation id="6883319974225028188">Oeps! Die stelsel het nie toestelopstelling gestoor nie.</translation> <translation id="6885771755599377173">Voorskou van stelselinligting</translation> <translation id="6886476658664859389">NFC-sekuriteitsleutel</translation>
diff --git a/chrome/app/resources/generated_resources_ar.xtb b/chrome/app/resources/generated_resources_ar.xtb index 3930d20..5827f81 100644 --- a/chrome/app/resources/generated_resources_ar.xtb +++ b/chrome/app/resources/generated_resources_ar.xtb
@@ -3358,7 +3358,7 @@ <translation id="4965808351167763748">هل تريد فعلاً إعداد هذا الجهاز لتشغيل Hangouts Meet؟</translation> <translation id="496888482094675990">يوفر تطبيق الملفات وصولاً سريعًا إلى الملفات التي حفظتها على Google Drive، أو مساحة التخزين الخارجي، أو جهاز نظام التشغيل Chrome.</translation> <translation id="4971412780836297815">فتح عند اكتمال التنزيل</translation> -<translation id="4971735654804503942">يوفّر حماية استباقية سريعة من الإضافات وعمليات التنزيل والمواقع الإلكترونية الضارة. ويُحذّرك من اختراقات كلمة المرور. يتطلّب إرسال بيانات التصفّح إلى Google.</translation> +<translation id="4971735654804503942">يوفّر حماية استباقية وسريعة من الإضافات وعمليات التنزيل والمواقع الإلكترونية الضارة، ويُحذّرك من عمليات اختراق كلمة المرور. يتطلّب إرسال بيانات التصفّح إلى Google.</translation> <translation id="4972129977812092092">تعديل الطابعة</translation> <translation id="4972164225939028131">كلمة مرور غير صحيحة</translation> <translation id="4972737347717125191">السماح للمواقع الإلكترونية بطلب استخدام أجهزة الواقع الافتراضي وبياناتها</translation>
diff --git a/chrome/app/resources/generated_resources_fa.xtb b/chrome/app/resources/generated_resources_fa.xtb index 700a510c..5340812 100644 --- a/chrome/app/resources/generated_resources_fa.xtb +++ b/chrome/app/resources/generated_resources_fa.xtb
@@ -641,7 +641,7 @@ <translation id="1726100011689679555">سرورهای نام</translation> <translation id="1727662110063605623">برای اتصال <ph name="USB_DEVICE_NAME" /> به Parallels Desktop یا Linux، «تنظیمات» را باز کنید</translation> <translation id="1729533290416704613">این برنامه صفحهای را که هنگام جستجو از Omnibox نشان داده میشود، کنترل میکند.</translation> -<translation id="1730917990259790240"><ph name="BEGIN_PARAGRAPH1" />برای حذف برنامهها به «تنظیمات > فروشگاه Google Play > مدیریت اولویتهای Android > برنامهها یا مدیر برنامه» بروید. سپس روی برنامهای که میخواهید حذف نصب شود ضربه بزنید (ممکن است برای پیدا کردن برنامه نیاز باشد صفحه را تند به راست یا چپ بکشید). سپس روی «حذف نصب» یا «غیرفعال کردن» ضربه بزنید.<ph name="END_PARAGRAPH1" /></translation> +<translation id="1730917990259790240"><ph name="BEGIN_PARAGRAPH1" />برای حذف برنامهها به «تنظیمات > فروشگاه Google Play > مدیریت اولویتهای Android > برنامهها یا مدیر برنامه» بروید. سپس روی برنامهای که میخواهید حذف نصب شود ضربه بزنید (ممکن است برای پیدا کردن برنامه نیاز باشد صفحه را تند بهراست یا چپ بکشید). سپس روی «حذف نصب» یا «غیرفعال کردن» ضربه بزنید.<ph name="END_PARAGRAPH1" /></translation> <translation id="1731911755844941020">در حال ارسال درخواست...</translation> <translation id="1733383495376208985">رمزگذاری دادههای همگامسازیشده با <ph name="BEGIN_LINK" />عبارت عبور همگامسازی<ph name="END_LINK" /> خودتان. این کار شامل روشهای پرداخت و نشانیهای موجود در Google Pay نمیشود.</translation> <translation id="1734212868489994726">آبی روشن</translation> @@ -2349,7 +2349,7 @@ <translation id="3742666961763734085">واحد سازمانی با این نام پیدا نشد. لطفاً دوباره امتحان کنید.</translation> <translation id="3744111561329211289">همگامسازی پسزمینه</translation> <translation id="3746127522257263495">امکان افزودن حساب G Suite for Education در برنامههای Android وجود ندارد.</translation> -<translation id="3747077776423672805">برای حذف برنامهها به «تنظیمات > فروشگاه Google Play > مدیریت اولویتهای Android > برنامهها یا مدیر برنامه» بروید. سپس روی برنامهای که میخواهید حذف نصب شود ضربه بزنید (ممکن است برای پیدا کردن برنامه نیاز باشد صفحه را تند به راست یا چپ بکشید). سپس روی «حذف نصب» یا «غیرفعال کردن» ضربه بزنید.</translation> +<translation id="3747077776423672805">برای حذف برنامهها به «تنظیمات > فروشگاه Google Play > مدیریت اولویتهای Android > برنامهها یا مدیر برنامه» بروید. سپس روی برنامهای که میخواهید حذف نصب شود ضربه بزنید (ممکن است برای پیدا کردن برنامه نیاز باشد صفحه را تند بهراست یا چپ بکشید). سپس روی «حذف نصب» یا «غیرفعال کردن» ضربه بزنید.</translation> <translation id="3748026146096797577">متصل نیست</translation> <translation id="3748706263662799310">گزارش یک اشکال</translation> <translation id="3752582316358263300">تأیید...</translation>
diff --git a/chrome/app/resources/generated_resources_hy.xtb b/chrome/app/resources/generated_resources_hy.xtb index 6dfca86c2..b2ff52d 100644 --- a/chrome/app/resources/generated_resources_hy.xtb +++ b/chrome/app/resources/generated_resources_hy.xtb
@@ -204,7 +204,8 @@ <translation id="1223853788495130632">Ադմինիստրատորը խորհուրդ է տալիս այս կարգավորման համար որոշակի արժեք ընտրել:</translation> <translation id="1225177025209879837">Հարցումը մշակվում է…</translation> <translation id="1227507814927581609">«<ph name="DEVICE_NAME" />»-ին կապակցվելիս իսկորոշումը ձախողվեց:</translation> -<translation id="1230417814058465809">Սովորական պաշտպանությունը միացված է։ Ավելի շատ ապահովության համար օգտագործեք լրացուցիչ պաշտպանությունը։</translation> +<translation id="1230417814058465809">Սովորական պաշտպանությունը միացված է։ Հավելյալ ապահովության համար օգտագործեք բարելավված + պաշտպանությունը։</translation> <translation id="1231733316453485619">Միացնե՞լ համաժամացումը</translation> <translation id="1232569758102978740">Անանուն</translation> <translation id="1233497634904001272">Հարցումն ավարտելու համար նորից հպեք անվտանգության բանալուն:</translation> @@ -437,7 +438,7 @@ <translation id="150411034776756821">Հեռացնել <ph name="SITE" /> կայքը</translation> <translation id="1504311855864906891">Ավելացրեք ենթագրեր մեդիա բովանդակությանը</translation> <translation id="1504551620756424144">Ընդհանուր պանակները Windows-ում հասանելի են այստեղ՝ <ph name="BASE_DIR" />։</translation> -<translation id="1506061864768559482">Որոնիչ</translation> +<translation id="1506061864768559482">Որոնողական համակարգ</translation> <translation id="1507170440449692343">Այս էջին արգելված է օգտագործել ձեր տեսախցիկը:</translation> <translation id="1507246803636407672">&Հրաժարվել</translation> <translation id="1508491105858779599">Սարքն ապակողպելու համար մատը դրեք մատնահետքի սենսորի վրա։</translation> @@ -3670,7 +3671,7 @@ <translation id="5352033265844765294">Ժամադրոշմ</translation> <translation id="5353252989841766347">Գաղտնաբառերի արտահանում Chrome-ից</translation> <translation id="5355099869024327351">Թույլ տվեք Օգնականին ցուցադրել ծանուցումներ</translation> -<translation id="5355191726083956201">Լրացուցիչ պաշտպանությունը միացված է</translation> +<translation id="5355191726083956201">Բարելավված պաշտպանությունը միացված է</translation> <translation id="5355926466126177564">«<ph name="EXTENSION_NAME" />» ընդլայնումը փոխել է Omnibox-ում որոնման ժամանակ ցուցադրվող էջը:</translation> <translation id="5359910752122114278">1 արդյունք</translation> <translation id="5360150013186312835">Ցույց տալ գործիքագոտիում</translation> @@ -4950,7 +4951,7 @@ <translation id="6897363604023044284">Ընտրել կայքեր՝ մաքրելու համար</translation> <translation id="6898440773573063262">Այժմ այս սարքի վրա Kiosk ծրագրերը կարելի է կազմաձևել այնպես, որ դրանք ավտոմատ գործարկվեն:</translation> <translation id="6900284862687837908">Ետին պլանի հավելված՝ <ph name="BACKGROUND_APP_URL" /></translation> -<translation id="6900532703269623216">Լրացուցիչ պաշտպանություն</translation> +<translation id="6900532703269623216">Բարելավված պաշտպանություն</translation> <translation id="6900651018461749106">Նորից մուտք գործեք՝ <ph name="USER_EMAIL" /> հաշիվը թարմացնելու համար</translation> <translation id="6902066522699286937">Ձայնի նախնական հնչեցում</translation> <translation id="6902336033320348843">Բաժինը չի աջակցվում՝ <ph name="ERROR_LINE" /></translation>
diff --git a/chrome/app/resources/generated_resources_kk.xtb b/chrome/app/resources/generated_resources_kk.xtb index 61e5501..adfaf405 100644 --- a/chrome/app/resources/generated_resources_kk.xtb +++ b/chrome/app/resources/generated_resources_kk.xtb
@@ -112,7 +112,7 @@ <translation id="1123753900084781868">Live Caption қазір қолжетімді емес.</translation> <translation id="1124772482545689468">Пайдаланушы</translation> <translation id="1125550662859510761"><ph name="WIDTH" /> x <ph name="HEIGHT" /> (жергілікті) болып көрінеді</translation> -<translation id="1126809382673880764">Қауіпті веб-сайттардан, жүктеп алынатын файлдардан және кеңейтімдерден қорғамайды. Gmail және Search сияқты басқа Google қызметтерінде "Қауіпсіз шолу" функциясы қорғайтын болады.</translation> +<translation id="1126809382673880764">Қауіпті веб-сайттардан, жүктеп алынған файлдардан және кеңейтімдерден қорғамайды. Gmail және Search сияқты басқа Google қызметтерінде "Қауіпсіз шолу" функциясы қорғайтын болады.</translation> <translation id="112752777279960360">Осы компьютермен алғаш рет қолданылған Android телефонын қауіпсіздік кілті ретінде орнату үшін телефоныңыздан Chrome браузерін ашыңыз да, "Параметрлер > Құпия сөздер > Телефонды қауіпсіздік кілті ретінде пайдалану" тармағына өтіңіз. Содан кейін "Жаңа құрылғы қосу" функциясын түртіп, осы QR кодын сканерлеңіз.</translation> <translation id="1128109161498068552">Кез келген сайттардың MIDI құрылғыларына қатынасу үшін жүйенің эксклюзивті хабарларын пайдалануына рұқсат етпеу</translation> <translation id="1128128132059598906">EAP-TTLS</translation> @@ -960,7 +960,7 @@ <translation id="2114326799768592691">&Кадрды қайта жүктеу</translation> <translation id="2114896190328250491"><ph name="NAME" /> суреті</translation> <translation id="2119349053129246860"><ph name="APP" /> қолданбасынан ашу</translation> -<translation id="2119461801241504254">"Қауіпсіз шолу" функциясы қосулы және ол зиянды сайттар мен жүктеп алынатын файлдардан қорғайды.</translation> +<translation id="2119461801241504254">"Қауіпсіз шолу" функциясы қосулы және ол зиянды сайттар мен жүктеп алынған файлдардан қорғайды.</translation> <translation id="2120297377148151361">Белсенділік және өзара әрекеттер</translation> <translation id="2120639962942052471"><ph name="PERMISSION" /> бөгелді.</translation> <translation id="2121055421682309734">{COUNT,plural, =0{Cookie файлдары бөгелді}=1{Cookie файлдары бөгелді (1 ерекше жағдай)}other{Cookie файлдары бөгелді ({COUNT} ерекше жағдай)}}</translation> @@ -2817,7 +2817,7 @@ <translation id="4303079906735388947">Қауіпсіздік кілтіңіз үшін жаңа PIN кодын орнатыңыз.</translation> <translation id="4305402730127028764"><ph name="DEVICE_NAME" /> құрылғысына көшіру</translation> <translation id="4306119971288449206">Қолданбаларға "<ph name="CONTENT_TYPE" />" мазмұнымен қызмет көрсетілуі керек</translation> -<translation id="4307992518367153382">Негіздер</translation> +<translation id="4307992518367153382">Негізгілер</translation> <translation id="4309420042698375243"><ph name="NUM_KILOBYTES" /> KБ (<ph name="NUM_KILOBYTES_LIVE" /> KБ белсенді)</translation> <translation id="4310139701823742692">Файлдың форматы дұрыс емес. PPD файлын тексеріп, әрекетті қайталап көріңіз.</translation> <translation id="431076611119798497">&Мәліметтер</translation>
diff --git a/chrome/app/resources/generated_resources_mk.xtb b/chrome/app/resources/generated_resources_mk.xtb index b533dee..7082919 100644 --- a/chrome/app/resources/generated_resources_mk.xtb +++ b/chrome/app/resources/generated_resources_mk.xtb
@@ -866,7 +866,7 @@ <translation id="1979095679518582070">Исклучувањето на функцијава нема да влијае врз способноста на уредов да ги испраќа информациите што се потребни за основните услуги, како што се ажурирањата на системот и безбедноста.</translation> <translation id="1979280758666859181">Се префрлате на канал со постара верзија на <ph name="PRODUCT_NAME" />. Промената на каналот ќе се примени кога неговата верзија ќе се совпадне со верзијата што тековно е инсталирана на уредот.</translation> <translation id="197989455406964291">KDC не го поддржува типот шифрирање</translation> -<translation id="1984417487208496350">Нема заштита (не се препорачува)</translation> +<translation id="1984417487208496350">Без заштита (не се препорачува)</translation> <translation id="1987317783729300807">Сметки</translation> <translation id="1988494864246143197">Сајтовите обично користат Flash за да пуштат аудио, видео или видеоигри. Flash Player веќе нема да се поддржува по истекот на декември 2020 г.</translation> <translation id="1989112275319619282">Прелистувај</translation>
diff --git a/chrome/app/resources/generated_resources_pt-BR.xtb b/chrome/app/resources/generated_resources_pt-BR.xtb index e76a8cb8..6ce5525 100644 --- a/chrome/app/resources/generated_resources_pt-BR.xtb +++ b/chrome/app/resources/generated_resources_pt-BR.xtb
@@ -142,7 +142,7 @@ <translation id="1153636665119721804">Programa Proteção Avançada do Google</translation> <translation id="1161575384898972166">Faça login no <ph name="TOKEN_NAME" /> para exportar o certificado do cliente.</translation> <translation id="1163931534039071049">&Exibir código fonte do frame</translation> -<translation id="1164891049599601209">Inserida em site enganoso</translation> +<translation id="1164891049599601209">Inserida em fraudulento</translation> <translation id="1164899421101904659">Informar chave para desbloqueio de PIN</translation> <translation id="1165039591588034296">Erro</translation> <translation id="1166212789817575481">Fechar guias à direita</translation> @@ -204,7 +204,7 @@ <translation id="1223853788495130632">Seu administrador recomenda um valor específico para esta configuração.</translation> <translation id="1225177025209879837">Processando solicitação...</translation> <translation id="1227507814927581609">Falha na autenticação ao conectar-se com "<ph name="DEVICE_NAME" />".</translation> -<translation id="1230417814058465809">A proteção padrão está ativada. Para ter ainda mais segurança, use a proteção aprimorada.</translation> +<translation id="1230417814058465809">A Proteção padrão está ativa. Para ter ainda mais segurança, selecione a Proteção reforçada.</translation> <translation id="1231733316453485619">Ativar sincronização?</translation> <translation id="1232569758102978740">Sem título</translation> <translation id="1233497634904001272">Toque na chave de segurança novamente para concluir a solicitação.</translation> @@ -2137,7 +2137,7 @@ <translation id="3498215018399854026">Não foi possível contatar seu pai/mãe no momento. Tente novamente.</translation> <translation id="3500417806337761827">Erro ao ativar o compartilhamento. Muitos compartilhamentos SMB já estão ativos.</translation> <translation id="3505030558724226696">Revogar acesso ao dispositivo</translation> -<translation id="3507132249039706973">A "Proteção padrão" está ativada</translation> +<translation id="3507132249039706973">A Proteção padrão está ativa</translation> <translation id="3507421388498836150">Permissões atuais para "<ph name="EXTENSION_NAME" />"</translation> <translation id="3507888235492474624">Procurar dispositivos Bluetooth novamente</translation> <translation id="3508492320654304609">Não foi possível excluir os dados de login</translation> @@ -2198,7 +2198,7 @@ <translation id="357886715122934472"><strong><ph name="SENDER" /></strong> deseja compartilhar uma impressora <strong><ph name="PRINTER_NAME" /></strong> com um grupo de sua propriedade: <strong><ph name="GROUP_NAME" /></strong>. Se você aceitar, todos os membros do grupo poderão imprimir pela impressora.</translation> <translation id="357889014807611375">Wi-Fi limitado</translation> <translation id="3581605050355435601">Configurar endereço IP automaticamente</translation> -<translation id="3582057310199111521">Inserida em um site enganoso e encontrada em uma violação de dados</translation> +<translation id="3582057310199111521">Inserida em um fraudulento e encontrada em uma violação de dados</translation> <translation id="3584169441612580296">Ler e alterar fotos, músicas e outras mídias do seu computador</translation> <translation id="3586806079541226322">Não é possível abrir o arquivo</translation> <translation id="3586931643579894722">Ocultar detalhes</translation> @@ -3668,7 +3668,7 @@ <translation id="5352033265844765294">Carimbo de data/hora</translation> <translation id="5353252989841766347">Exportar senhas do Chrome</translation> <translation id="5355099869024327351">Permitir que o Assistente mostre notificações</translation> -<translation id="5355191726083956201">A "Proteção reforçada" está ativa</translation> +<translation id="5355191726083956201">A Proteção reforçada está ativa</translation> <translation id="5355926466126177564">A extensão "<ph name="EXTENSION_NAME" />" alterou a página que é exibida quando você pesquisa na Omnibox.</translation> <translation id="5359910752122114278">1 resultado</translation> <translation id="5360150013186312835">Mostrar na barra de ferramentas</translation>
diff --git a/chrome/app/resources/generated_resources_te.xtb b/chrome/app/resources/generated_resources_te.xtb index 118c67d4..5937b069 100644 --- a/chrome/app/resources/generated_resources_te.xtb +++ b/chrome/app/resources/generated_resources_te.xtb
@@ -824,7 +824,7 @@ <translation id="1927632033341042996">వేలు <ph name="NEW_FINGER_NUMBER" /></translation> <translation id="192817607445937251">స్క్రీన్ లాక్ పిన్</translation> <translation id="1928202201223835302">పాత PINని నమోదు చేయండి</translation> -<translation id="1928696683969751773">నవీకరిస్తుంది</translation> +<translation id="1928696683969751773">అప్డేట్లు</translation> <translation id="1929186283613845153">ఈ ఫైల్ స్కాన్ అవుతోంది.</translation> <translation id="1929546189971853037">మీరు సైన్-ఇన్ చేసిన అన్ని పరికరాల్లో మీ బ్రౌజింగ్ చరిత్రను చదవడానికి అనుమతి</translation> <translation id="1930879306590754738">ఈ పరికరం నుండి అలాగే మీ Google ఖాతా నుండి పాస్వర్డ్ తొలగించబడింది</translation>
diff --git a/chrome/app/resources/generated_resources_uk.xtb b/chrome/app/resources/generated_resources_uk.xtb index 22035f7..efbe8aa 100644 --- a/chrome/app/resources/generated_resources_uk.xtb +++ b/chrome/app/resources/generated_resources_uk.xtb
@@ -3361,7 +3361,7 @@ <translation id="4965808351167763748">Налаштувати пристрій для роботи Hangouts Meet?</translation> <translation id="496888482094675990">Додаток Файли надає швидкий доступ до файлів, збережених на Google Диску, у зовнішній пам’яті або на пристрої з ОС Chrome.</translation> <translation id="4971412780836297815">Відкрити після завантаження</translation> -<translation id="4971735654804503942">Швидший активний захист від небезпечних веб-сайтів, завантажень і розширень. Попереджає про розкриття паролів через порушення безпеки даних. Вимагає надсилати в Google дані веб-перегляду.</translation> +<translation id="4971735654804503942">Швидший активний захист від небезпечних веб-сайтів, завантажень і розширень. Попереджає про розкриття паролів через порушення безпеки даних. Дані веб-перегляду потрібно надсилати в Google.</translation> <translation id="4972129977812092092">Змінити принтер</translation> <translation id="4972164225939028131">Неправильний пароль</translation> <translation id="4972737347717125191">Сайти можуть запитувати дозвіл на використання пристроїв і даних віртуальної реальності</translation> @@ -4513,7 +4513,7 @@ <translation id="6340071272923955280">Протокол друку через Інтернет (IPPS)</translation> <translation id="6340526405444716530">Персоналізація</translation> <translation id="6341850831632289108">Визначати ваше фізичне місцезнаходження</translation> -<translation id="6342069812937806050">Лише зараз</translation> +<translation id="6342069812937806050">Щойно</translation> <translation id="6344170822609224263">Отримувати доступ до списку мережевих з’єднань</translation> <translation id="6344576354370880196">Збережені принтери</translation> <translation id="6345418402353744910">Укажіть своє ім'я користувача та пароль для проксі <ph name="PROXY" />, щоб адміністратор міг налаштувати вашу мережу</translation>
diff --git a/chrome/app/resources/generated_resources_ur.xtb b/chrome/app/resources/generated_resources_ur.xtb index f6ea255..5ebe019e 100644 --- a/chrome/app/resources/generated_resources_ur.xtb +++ b/chrome/app/resources/generated_resources_ur.xtb
@@ -6508,7 +6508,7 @@ <translation id="8730621377337864115">ہوگیا</translation> <translation id="8731629443331803108"><ph name="SITE_NAME" /> کو درکار ہے: <ph name="PERMISSION" /></translation> <translation id="8731787661154643562">پورٹ نمبر</translation> -<translation id="8731851055419582926">چیک کردہ پاس ورڈز</translation> +<translation id="8731851055419582926">پاس ورڈز چیک کیے گئے</translation> <translation id="8732030010853991079">اس آئیکن پر کلک کر کے یہ ایکسٹینشن استعمال کریں۔</translation> <translation id="8732212173949624846">اپنے سبھی سائن ان کردہ آلات پر اپنی براؤزنگ سرگزشت پڑھیں اور تبدیل کریں</translation> <translation id="8732844209475700754">راز داری، سیکیورٹی اور ڈیٹا کے مجموعے سے متعلق مزید ترتیبات</translation>
diff --git a/chrome/app/resources/generated_resources_vi.xtb b/chrome/app/resources/generated_resources_vi.xtb index 4cd2a1c..1fc15003 100644 --- a/chrome/app/resources/generated_resources_vi.xtb +++ b/chrome/app/resources/generated_resources_vi.xtb
@@ -824,7 +824,7 @@ <translation id="1927632033341042996">Ngón tay <ph name="NEW_FINGER_NUMBER" /></translation> <translation id="192817607445937251">Phương thức khóa màn hình: mã PIN</translation> <translation id="1928202201223835302">Nhập mã PIN cũ</translation> -<translation id="1928696683969751773">Số lần cập nhật</translation> +<translation id="1928696683969751773">Bản cập nhật</translation> <translation id="1929186283613845153">Tệp này đang được quét.</translation> <translation id="1929546189971853037">Đọc lịch sử duyệt web của bạn trên tất cả các thiết bị đã đăng nhập</translation> <translation id="1930879306590754738">Đã xóa mật khẩu khỏi thiết bị này và Tài khoản Google của bạn</translation> @@ -2197,7 +2197,7 @@ <translation id="357886715122934472"><strong><ph name="SENDER" /></strong> muốn chia sẻ máy in <strong><ph name="PRINTER_NAME" /></strong> với một nhóm bạn sở hữu: <strong><ph name="GROUP_NAME" /></strong>. Nếu bạn chấp nhận, tất cả thành viên của nhóm sẽ có thể in tới máy in.</translation> <translation id="357889014807611375">mạng Wi‑Fi có giới hạn dữ liệu</translation> <translation id="3581605050355435601">Tự động định cấu hình địa chỉ IP</translation> -<translation id="3582057310199111521">Bạn đã nhập mật khẩu vào trang web lừa đảo và mật khẩu này bị lộ trong một sự cố rò rỉ dữ liệu</translation> +<translation id="3582057310199111521">Bạn đã nhập mật khẩu vào trang web lừa đảo và mật khẩu này được phát hiện thấy trong một sự cố rò rỉ dữ liệu</translation> <translation id="3584169441612580296">Đọc và thay đổi ảnh, nhạc và phương tiện khác từ máy tính của bạn</translation> <translation id="3586806079541226322">Không thể mở tệp này</translation> <translation id="3586931643579894722">Ẩn chi tiết</translation> @@ -5653,7 +5653,7 @@ <translation id="7742706086992565332">Bạn có thể đặt mức phóng to hoặc thu nhỏ trên một số trang web</translation> <translation id="774377079771918250">Chọn vị trí lưu</translation> <translation id="7744047395460924128">Xem lịch sử in của bạn</translation> -<translation id="7744192722284567281">Phát hiện mật khẩu bị rò rỉ</translation> +<translation id="7744192722284567281">Phát hiện thấy trong một sự cố rò rỉ dữ liệu</translation> <translation id="7750228210027921155">Hình trong hình</translation> <translation id="7751260505918304024">Hiển thị tất cả</translation> <translation id="7753735457098489144">Cài đặt không thành công do thiếu dung lượng bộ nhớ. Để giải phóng dung lượng, hãy xóa bớt tệp khỏi bộ nhớ của thiết bị.</translation>
diff --git a/chrome/app/resources/google_chrome_strings_pt-BR.xtb b/chrome/app/resources/google_chrome_strings_pt-BR.xtb index 8252772c..7e06bc43 100644 --- a/chrome/app/resources/google_chrome_strings_pt-BR.xtb +++ b/chrome/app/resources/google_chrome_strings_pt-BR.xtb
@@ -121,7 +121,7 @@ <translation id="4325083532956419387">Versão do Chrome OS</translation> <translation id="4328355335528187361">Google Chrome Dev (mDNS-In)</translation> <translation id="4331809312908958774">Sistema operacional Chrome</translation> -<translation id="4335235004908507846">O Chrome pode ajudar a proteger você de violações de dados, extensões maliciosas e muito mais</translation> +<translation id="4335235004908507846">O Chrome pode ajudar na proteção contra violações de dados, extensões maliciosas e muito mais</translation> <translation id="4343195214584226067">A extensão <ph name="EXTENSION_NAME" /> foi adicionada ao Chrome</translation> <translation id="4384570495110188418">O Chrome não pode verificar suas senhas porque sua conta não está conectada</translation> <translation id="4407807842708586359">Sistema operacional (OS) do Google Chrome</translation>
diff --git a/chrome/app/resources/google_chrome_strings_ru.xtb b/chrome/app/resources/google_chrome_strings_ru.xtb index 67e4a790..102ea7e 100644 --- a/chrome/app/resources/google_chrome_strings_ru.xtb +++ b/chrome/app/resources/google_chrome_strings_ru.xtb
@@ -121,7 +121,7 @@ <translation id="4325083532956419387">Версия Chrome OS</translation> <translation id="4328355335528187361">Google Chrome для разработчиков (mDNS-In)</translation> <translation id="4331809312908958774">Chrome OS</translation> -<translation id="4335235004908507846">Chrome поможет обеспечить защиту от утечки данных, ненадежных расширений и других проблем с безопасностью.</translation> +<translation id="4335235004908507846">Chrome поможет защитить вас от утечки данных, ненадежных расширений и других проблем с безопасностью.</translation> <translation id="4343195214584226067">Расширение "<ph name="EXTENSION_NAME" />" установлено</translation> <translation id="4384570495110188418">Не удается запустить проверку паролей в Chrome, поскольку вы не вошли в аккаунт.</translation> <translation id="4407807842708586359">Google Chrome OS</translation>
diff --git a/chrome/app/resources/google_chrome_strings_ur.xtb b/chrome/app/resources/google_chrome_strings_ur.xtb index 92f8a9bb7..ac73587 100644 --- a/chrome/app/resources/google_chrome_strings_ur.xtb +++ b/chrome/app/resources/google_chrome_strings_ur.xtb
@@ -125,7 +125,7 @@ <translation id="4325083532956419387">Chrome OS ورژن</translation> <translation id="4328355335528187361">Google Chrome Dev (mDNS-In)</translation> <translation id="4331809312908958774">Chrome OS</translation> -<translation id="4335235004908507846">Chrome آپ کو ڈیٹا کی خلاف ورزیوں، غلط ایکسٹینشنز اور بہت کچھ سے محفوظ رکھنے میں مدد کر سکتا ہے</translation> +<translation id="4335235004908507846">Chrome آپ کو ڈیٹا کی خلاف ورزیوں، غلط ایکسٹینشنز اور مزید بہت کچھ سے محفوظ رکھنے میں مدد کر سکتا ہے</translation> <translation id="4343195214584226067"><ph name="EXTENSION_NAME" /> کو Chrome میں شامل کر دیا گیا ہے</translation> <translation id="4384570495110188418">Chrome آپ کے پاس ورڈز چیک نہیں کر سکتا کیونکہ آپ سائن ان نہیں ہیں</translation> <translation id="4407807842708586359">Google Chrome OS</translation>
diff --git a/chrome/app/resources/google_chrome_strings_vi.xtb b/chrome/app/resources/google_chrome_strings_vi.xtb index 868f3f5..57e6181 100644 --- a/chrome/app/resources/google_chrome_strings_vi.xtb +++ b/chrome/app/resources/google_chrome_strings_vi.xtb
@@ -60,7 +60,7 @@ <translation id="2534507159460261402">Google Pay (đã sao chép vào Chrome)</translation> <translation id="2580411288591421699">Không thể cài đặt phiên bản Google Chrome giống với phiên bản hiện đang chạy. Vui lòng đóng Google Chrome và thử lại.</translation> <translation id="2586406160782125153">Thao tác này sẽ xóa dữ liệu duyệt web của bạn khỏi thiết bị này. Để truy xuất dữ liệu của bạn sau, hãy đăng nhập vào Chrome dưới dạng <ph name="USER_EMAIL" />.</translation> -<translation id="2622559029861875898">Chrome không thể kiểm tra các bản cập nhật. Hãy thử kiểm tra kết nối Internet.</translation> +<translation id="2622559029861875898">Chrome không thể kiểm tra để tìm các bản cập nhật. Hãy thử kiểm tra kết nối Internet.</translation> <translation id="2644798301485385923">Hệ thống Chrome OS</translation> <translation id="2652691236519827073">Mở liên kết trong &tab mới của Chrome</translation> <translation id="2665296953892887393">Giúp cải thiện Google Chrome bằng cách gửi báo cáo sự cố và <ph name="UMA_LINK" /> tới Google</translation>
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index eab74c78..2c6e030 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -3793,10 +3793,6 @@ "sharing/sharing_notification_handler.h", "sharing/sharing_ui_controller.cc", "sharing/sharing_ui_controller.h", - "sharing/webrtc/ice_config_fetcher.cc", - "sharing/webrtc/ice_config_fetcher.h", - "sharing/webrtc/sharing_mojo_service.cc", - "sharing/webrtc/sharing_mojo_service.h", "signin/signin_promo.cc", "signin/signin_promo.h", "signin/signin_ui_util.cc", @@ -3972,9 +3968,6 @@ "//chrome/common/search:generate_colors_info", "//chrome/common/themes:autogenerated_theme_util", "//chrome/services/media_gallery_util/public/cpp", - "//chrome/services/sharing/public/cpp", - "//chrome/services/sharing/public/mojom", - "//chrome/services/sharing/public/proto", "//components/download/quarantine", "//components/feedback", "//components/image_fetcher/core", @@ -4000,10 +3993,19 @@ "//third_party/sqlite", ] if (is_chromeos) { + sources += [ + "sharing/webrtc/ice_config_fetcher.cc", + "sharing/webrtc/ice_config_fetcher.h", + "sharing/webrtc/sharing_mojo_service.cc", + "sharing/webrtc/sharing_mojo_service.h", + ] deps += [ "//chrome/browser/supervised_user:supervised_user_unscaled_resources", + "//chrome/services/sharing/public/cpp", + "//chrome/services/sharing/public/proto", "//chromeos/dbus/session_manager", "//chromeos/login/session", + "//chromeos/services/nearby/public/mojom", "//components/arc:arc_base_utils", ] } @@ -4496,8 +4498,6 @@ "themes/theme_helper_win.cc", "themes/theme_helper_win.h", "upgrade_detector/get_installed_version_win.cc", - "webshare/win/share_operation.cc", - "webshare/win/share_operation.h", "webshare/win/show_share_ui_for_window_operation.cc", "webshare/win/show_share_ui_for_window_operation.h", "win/app_icon.cc",
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 88fd57ee..d7758580 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -4147,10 +4147,10 @@ flag_descriptions::kOmniboxUISwapTitleAndUrlDescription, kOsDesktop, FEATURE_VALUE_TYPE(omnibox::kUIExperimentSwapTitleAndUrl)}, - {"omnibox-disable-instant-extended-limit", - flag_descriptions::kOmniboxDisableInstantExtendedLimitName, - flag_descriptions::kOmniboxDisableInstantExtendedLimitDescription, kOsAll, - FEATURE_VALUE_TYPE(omnibox::kOmniboxDisableInstantExtendedLimit)}, + {"omnibox-webui-omnibox-popup", + flag_descriptions::kOmniboxWebUIOmniboxPopupName, + flag_descriptions::kOmniboxWebUIOmniboxPopupDescription, kOsDesktop, + FEATURE_VALUE_TYPE(omnibox::kWebUIOmniboxPopup)}, #if defined(OS_CHROMEOS) {"handwriting-gesture", flag_descriptions::kHandwritingGestureName,
diff --git a/chrome/browser/chromeos/BUILD.gn b/chrome/browser/chromeos/BUILD.gn index 40cbd1e..1416f14 100644 --- a/chrome/browser/chromeos/BUILD.gn +++ b/chrome/browser/chromeos/BUILD.gn
@@ -218,6 +218,7 @@ "//chromeos/system", "//chromeos/timezone", "//chromeos/tpm", + "//chromeos/ui/base", "//components/arc", "//components/arc/media_session", "//components/arc/mojom:mojom_traits", @@ -3749,6 +3750,7 @@ "../ui/webui/settings/chromeos/search/per_session_settings_user_action_tracker_unittest.cc", "../ui/webui/settings/chromeos/search/search_handler_unittest.cc", "../ui/webui/settings/chromeos/search/search_tag_registry_unittest.cc", + "../ui/webui/settings/chromeos/settings_user_action_tracker_unittest.cc", ] if (use_cups) { sources += [
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 6c665910..a5c7f16 100644 --- a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc +++ b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc
@@ -499,24 +499,24 @@ } // Gets expected window state type according to |event_type|. -ash::WindowStateType GetExpectedWindowState( +chromeos::WindowStateType GetExpectedWindowState( api::autotest_private::WMEventType event_type) { switch (event_type) { case api::autotest_private::WMEventType::WM_EVENT_TYPE_WMEVENTNORMAL: - return ash::WindowStateType::kNormal; + return chromeos::WindowStateType::kNormal; case api::autotest_private::WMEventType::WM_EVENT_TYPE_WMEVENTMAXIMIZE: - return ash::WindowStateType::kMaximized; + return chromeos::WindowStateType::kMaximized; case api::autotest_private::WMEventType::WM_EVENT_TYPE_WMEVENTMINIMIZE: - return ash::WindowStateType::kMinimized; + return chromeos::WindowStateType::kMinimized; case api::autotest_private::WMEventType::WM_EVENT_TYPE_WMEVENTFULLSCREEN: - return ash::WindowStateType::kFullscreen; + return chromeos::WindowStateType::kFullscreen; case api::autotest_private::WMEventType::WM_EVENT_TYPE_WMEVENTSNAPLEFT: - return ash::WindowStateType::kLeftSnapped; + return chromeos::WindowStateType::kLeftSnapped; case api::autotest_private::WMEventType::WM_EVENT_TYPE_WMEVENTSNAPRIGHT: - return ash::WindowStateType::kRightSnapped; + return chromeos::WindowStateType::kRightSnapped; default: NOTREACHED(); - return ash::WindowStateType::kNormal; + return chromeos::WindowStateType::kNormal; } } @@ -541,28 +541,28 @@ } api::autotest_private::WindowStateType ToWindowStateType( - ash::WindowStateType state_type) { + chromeos::WindowStateType state_type) { switch (state_type) { // Consider adding DEFAULT type to idl. - case ash::WindowStateType::kDefault: - case ash::WindowStateType::kNormal: + case chromeos::WindowStateType::kDefault: + case chromeos::WindowStateType::kNormal: return api::autotest_private::WindowStateType::WINDOW_STATE_TYPE_NORMAL; - case ash::WindowStateType::kMinimized: + case chromeos::WindowStateType::kMinimized: return api::autotest_private::WindowStateType:: WINDOW_STATE_TYPE_MINIMIZED; - case ash::WindowStateType::kMaximized: + case chromeos::WindowStateType::kMaximized: return api::autotest_private::WindowStateType:: WINDOW_STATE_TYPE_MAXIMIZED; - case ash::WindowStateType::kFullscreen: + case chromeos::WindowStateType::kFullscreen: return api::autotest_private::WindowStateType:: WINDOW_STATE_TYPE_FULLSCREEN; - case ash::WindowStateType::kLeftSnapped: + case chromeos::WindowStateType::kLeftSnapped: return api::autotest_private::WindowStateType:: WINDOW_STATE_TYPE_LEFTSNAPPED; - case ash::WindowStateType::kRightSnapped: + case chromeos::WindowStateType::kRightSnapped: return api::autotest_private::WindowStateType:: WINDOW_STATE_TYPE_RIGHTSNAPPED; - case ash::WindowStateType::kPip: + case chromeos::WindowStateType::kPip: return api::autotest_private::WindowStateType::WINDOW_STATE_TYPE_PIP; default: NOTREACHED(); @@ -809,7 +809,7 @@ class WindowStateChangeObserver : public aura::WindowObserver { public: WindowStateChangeObserver(aura::Window* window, - ash::WindowStateType expected_type, + chromeos::WindowStateType expected_type, base::OnceCallback<void(bool)> callback) : expected_type_(expected_type), callback_(std::move(callback)) { DCHECK_NE(window->GetProperty(ash::kWindowStateTypeKey), expected_type_); @@ -836,7 +836,7 @@ } private: - ash::WindowStateType expected_type_; + chromeos::WindowStateType expected_type_; ScopedObserver<aura::Window, aura::WindowObserver> scoped_observer_{this}; base::OnceCallback<void(bool)> callback_; @@ -3713,7 +3713,7 @@ base::StringPrintf("No app window was found : id=%d", params->id))); } - ash::WindowStateType expected_state = + chromeos::WindowStateType expected_state = GetExpectedWindowState(params->change.event_type); if (window->GetProperty(ash::kWindowStateTypeKey) == expected_state) { if (params->change.fail_if_no_change && @@ -3734,11 +3734,11 @@ // TODO(crbug.com/990713): Make WMEvent trigger split view in tablet mode. if (ash::TabletMode::Get()->InTabletMode()) { - if (expected_state == ash::WindowStateType::kLeftSnapped) { + if (expected_state == chromeos::WindowStateType::kLeftSnapped) { ash::SplitViewTestApi().SnapWindow( window, ash::SplitViewTestApi::SnapPosition::LEFT); return RespondLater(); - } else if (expected_state == ash::WindowStateType::kRightSnapped) { + } else if (expected_state == chromeos::WindowStateType::kRightSnapped) { ash::SplitViewTestApi().SnapWindow( window, ash::SplitViewTestApi::SnapPosition::RIGHT); return RespondLater(); @@ -3752,7 +3752,7 @@ } void AutotestPrivateSetAppWindowStateFunction::WindowStateChanged( - ash::WindowStateType expected_type, + chromeos::WindowStateType expected_type, bool success) { if (!success) { Respond(Error( @@ -4552,8 +4552,8 @@ } auto* state = ash::WindowState::Get(window); - if (!state || - ash::ToWindowShowState(state->GetStateType()) != ui::SHOW_STATE_NORMAL) { + if (!state || chromeos::ToWindowShowState(state->GetStateType()) != + ui::SHOW_STATE_NORMAL) { return RespondNow( Error("Cannot set bounds of window not in normal show state.")); }
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 ef1ef65..5d96a90 100644 --- a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.h +++ b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.h
@@ -11,7 +11,6 @@ #include "ash/display/screen_orientation_controller.h" #include "ash/public/cpp/assistant/assistant_state.h" -#include "ash/public/cpp/window_state_type.h" #include "ash/rotator/screen_rotation_animator_observer.h" #include "base/compiler_specific.h" #include "base/optional.h" @@ -22,6 +21,7 @@ #include "chrome/browser/web_applications/components/web_app_id.h" #include "chromeos/services/machine_learning/public/mojom/machine_learning_service.mojom-forward.h" #include "chromeos/services/machine_learning/public/mojom/model.mojom.h" +#include "chromeos/ui/base/window_state_type.h" #include "extensions/browser/browser_context_keyed_api_factory.h" #include "extensions/browser/extension_function.h" #include "mojo/public/cpp/bindings/remote.h" @@ -1007,7 +1007,8 @@ ~AutotestPrivateSetAppWindowStateFunction() override; ResponseAction Run() override; - void WindowStateChanged(ash::WindowStateType expected_type, bool success); + void WindowStateChanged(chromeos::WindowStateType expected_type, + bool success); std::unique_ptr<WindowStateChangeObserver> window_state_observer_; };
diff --git a/chrome/browser/chromeos/policy/extension_install_event_log_collector.cc b/chrome/browser/chromeos/policy/extension_install_event_log_collector.cc index 518bccc..91014ce 100644 --- a/chrome/browser/chromeos/policy/extension_install_event_log_collector.cc +++ b/chrome/browser/chromeos/policy/extension_install_event_log_collector.cc
@@ -242,6 +242,30 @@ } } +em::ExtensionInstallReportLogEvent_DownloadCacheStatus +ConvertDownloadCacheStatusToProto( + extensions::ExtensionDownloaderDelegate::CacheStatus status) { + using Status = extensions::ExtensionDownloaderDelegate::CacheStatus; + switch (status) { + case Status::CACHE_UNKNOWN: + return em::ExtensionInstallReportLogEvent::CACHE_UNKNOWN; + case Status::CACHE_DISABLED: + return em::ExtensionInstallReportLogEvent::CACHE_DISABLED; + case Status::CACHE_MISS: + return em::ExtensionInstallReportLogEvent::CACHE_MISS; + case Status::CACHE_OUTDATED: + return em::ExtensionInstallReportLogEvent::CACHE_OUTDATED; + case Status::CACHE_HIT: + return em::ExtensionInstallReportLogEvent::CACHE_HIT; + case Status::CACHE_HIT_ON_MANIFEST_FETCH_FAILURE: + return em::ExtensionInstallReportLogEvent:: + CACHE_HIT_ON_MANIFEST_FETCH_FAILURE; + default: + NOTREACHED(); + return em::ExtensionInstallReportLogEvent::CACHE_UNKNOWN; + } +} + } // namespace ExtensionInstallEventLogCollector::ExtensionInstallEventLogCollector( @@ -377,6 +401,17 @@ delegate_->Add(id, false /* gather_disk_space_info */, std::move(event)); } +void ExtensionInstallEventLogCollector::OnExtensionDownloadCacheStatusRetrieved( + const extensions::ExtensionId& id, + extensions::ExtensionDownloaderDelegate::CacheStatus cache_status) { + if (!delegate_->IsExtensionPending(id)) + return; + auto event = std::make_unique<em::ExtensionInstallReportLogEvent>(); + event->set_download_cache_status( + ConvertDownloadCacheStatusToProto(cache_status)); + delegate_->Add(id, false /* gather_disk_space_info */, std::move(event)); +} + void ExtensionInstallEventLogCollector::OnExtensionLoaded( content::BrowserContext* browser_context, const extensions::Extension* extension) {
diff --git a/chrome/browser/chromeos/policy/extension_install_event_log_collector.h b/chrome/browser/chromeos/policy/extension_install_event_log_collector.h index 49899d9..923747e7 100644 --- a/chrome/browser/chromeos/policy/extension_install_event_log_collector.h +++ b/chrome/browser/chromeos/policy/extension_install_event_log_collector.h
@@ -106,6 +106,10 @@ void OnExtensionInstallCreationStageChanged( const extensions::ExtensionId& id, extensions::InstallStageTracker::InstallCreationStage stage) override; + void OnExtensionDownloadCacheStatusRetrieved( + const extensions::ExtensionId& id, + extensions::ExtensionDownloaderDelegate::CacheStatus cache_status) + override; // Reports success events for the extensions which are requested from policy // and are already loaded.
diff --git a/chrome/browser/chromeos/policy/extension_install_event_log_collector_unittest.cc b/chrome/browser/chromeos/policy/extension_install_event_log_collector_unittest.cc index 9b235580..a6fccaf 100644 --- a/chrome/browser/chromeos/policy/extension_install_event_log_collector_unittest.cc +++ b/chrome/browser/chromeos/policy/extension_install_event_log_collector_unittest.cc
@@ -605,4 +605,21 @@ delegate()->last_request().event.install_creation_stage()); } +// Verifies that a new event is created when the cache status is retrieved +// during the extension downloading process. +TEST_F(ExtensionInstallEventLogCollectorTest, DownloadCacheStatusRetrieved) { + std::unique_ptr<ExtensionInstallEventLogCollector> collector = + std::make_unique<ExtensionInstallEventLogCollector>( + registry(), delegate(), profile()); + + auto ext = extensions::ExtensionBuilder(kExtensionName1) + .SetID(kExtensionId1) + .Build(); + collector->OnExtensionDownloadCacheStatusRetrieved( + kExtensionId1, + extensions::ExtensionDownloaderDelegate::CacheStatus::CACHE_MISS); + ASSERT_TRUE(VerifyEventAddedSuccessfully(1 /*expected_add_count*/, + 0 /*expected_add_all_count*/)); +} + } // namespace policy
diff --git a/chrome/browser/chromeos/policy/install_event_log_util.cc b/chrome/browser/chromeos/policy/install_event_log_util.cc index 98342e3..0f71f063 100644 --- a/chrome/browser/chromeos/policy/install_event_log_util.cc +++ b/chrome/browser/chromeos/policy/install_event_log_util.cc
@@ -49,6 +49,7 @@ constexpr char kIsNewUser[] = "isNewUser"; constexpr char kIsMisconfigurationFailure[] = "isMisconfigurationFailure"; constexpr char kInstallCreationStage[] = "installCreationStage"; +constexpr char kDownloadCacheStatus[] = "downloadCacheStatus"; // Calculates hash for the given |event| and |context|, and stores the hash in // |hash|. Returns true if |event| and |context| are json serializable and @@ -208,6 +209,11 @@ extension_install_report_log_event.install_creation_stage()); } + if (extension_install_report_log_event.has_download_cache_status()) { + event.SetIntKey(kDownloadCacheStatus, + extension_install_report_log_event.download_cache_status()); + } + base::Value wrapper(base::Value::Type::DICTIONARY); wrapper.SetKey(kExtensionInstallEvent, std::move(event));
diff --git a/chrome/browser/chromeos/policy/install_event_log_util_unittest.cc b/chrome/browser/chromeos/policy/install_event_log_util_unittest.cc index c468e536..a930a94 100644 --- a/chrome/browser/chromeos/policy/install_event_log_util_unittest.cc +++ b/chrome/browser/chromeos/policy/install_event_log_util_unittest.cc
@@ -48,6 +48,7 @@ constexpr char kIsNewUser[] = "isNewUser"; constexpr char kIsMisconfigurationFailure[] = "isMisconfigurationFailure"; constexpr char kInstallCreationStage[] = "installCreationStage"; +constexpr char kDownloadCacheStatus[] = "downloadCacheStatus"; void ConvertToValueAndVerify(const em::ExtensionInstallReportLogEvent& event, const std::vector<std::string>& keys) { @@ -139,4 +140,12 @@ ConvertToValueAndVerify(event_, {kInstallCreationStage}); } +// Verifies that an event reporting cache status during downloading process is +// successfully parsed. +TEST_F(ExtensionInstallEventLogUtilTest, DownloadCacheStatusEvent) { + event_.set_download_cache_status( + em::ExtensionInstallReportLogEvent::CACHE_OUTDATED); + ConvertToValueAndVerify(event_, {kDownloadCacheStatus}); +} + } // namespace policy
diff --git a/chrome/browser/data_saver/lite_video_browsertest.cc b/chrome/browser/data_saver/lite_video_browsertest.cc index dc37317..a409f1e 100644 --- a/chrome/browser/data_saver/lite_video_browsertest.cc +++ b/chrome/browser/data_saver/lite_video_browsertest.cc
@@ -307,6 +307,55 @@ lite_video::LiteVideoThrottleResult::kThrottleStoppedOnRebuffer)); } +// When video is seeked throttling is stopped. +IN_PROC_BROWSER_TEST_F(LiteVideoBrowserTest, StopsThrottlingOnPlaybackSeek) { + ukm::TestAutoSetUkmRecorder ukm_recorder; + TestMSEPlayback("bear-vp9.webm", "2000", "2000", false); + + RetryForHistogramUntilCountReached(histogram_tester(), + "Media.VideoHeight.Initial.MSE", 1); + + histogram_tester().ExpectUniqueSample("LiteVideo.HintAgent.HasHint", true, 1); + + // Trigger a media playback seek. + ASSERT_TRUE(content::ExecuteScript( + browser()->tab_strip_model()->GetActiveWebContents(), + "document.querySelector('video').currentTime = 1")); + + // Verify some responses were throttled and then throttling is stopped. + RetryForHistogramUntilCountReached(histogram_tester(), + "LiteVideo.HintsAgent.StopThrottling", 1); + EXPECT_GE(1U, histogram_tester() + .GetAllSamples("LiteVideo.URLLoader.ThrottleLatency") + .size()); + EXPECT_EQ(1U, histogram_tester() + .GetAllSamples("LiteVideo.HintsAgent.StopThrottling") + .size()); + EXPECT_GE( + 1U, histogram_tester() + .GetAllSamples("LiteVideo.NavigationMetrics.FrameRebufferMapSize") + .size()); + + // Close the tab to flush the UKM metrics. + browser()->tab_strip_model()->GetActiveWebContents()->Close(); + + auto entries = + ukm_recorder.GetEntriesByName(ukm::builders::LiteVideo::kEntryName); + ASSERT_EQ(1u, entries.size()); + auto* entry = entries[0]; + ukm_recorder.ExpectEntrySourceHasUrl(entry, media_url()); + ukm_recorder.ExpectEntryMetric( + entry, ukm::builders::LiteVideo::kThrottlingStartDecisionName, + static_cast<int>(lite_video::LiteVideoDecision::kAllowed)); + ukm_recorder.ExpectEntryMetric( + entry, ukm::builders::LiteVideo::kBlocklistReasonName, + static_cast<int>(lite_video::LiteVideoBlocklistReason::kUnknown)); + ukm_recorder.ExpectEntryMetric( + entry, ukm::builders::LiteVideo::kThrottlingResultName, + static_cast<int>( + lite_video::LiteVideoThrottleResult::kThrottledWithoutStop)); +} + class LiteVideoAndLiteModeDisabledBrowserTest : public LiteVideoBrowserTest { public: LiteVideoAndLiteModeDisabledBrowserTest()
diff --git a/chrome/browser/extensions/api/extension_action/extension_action_apitest.cc b/chrome/browser/extensions/api/extension_action/extension_action_apitest.cc index 065f2ae..0ef6a3b0 100644 --- a/chrome/browser/extensions/api/extension_action/extension_action_apitest.cc +++ b/chrome/browser/extensions/api/extension_action/extension_action_apitest.cc
@@ -184,6 +184,14 @@ DISALLOW_COPY_AND_ASSIGN(ActionTestHelper); }; +// Forces a flush of the StateStore, where action state is persisted. +void FlushStateStore(Profile* profile) { + base::RunLoop run_loop; + ExtensionSystem::Get(profile)->state_store()->FlushForTesting( + run_loop.QuitWhenIdleClosure()); + run_loop.Run(); +} + } // namespace using ExtensionActionAPITest = ExtensionApiTest; @@ -638,6 +646,78 @@ EXPECT_EQ("1", foo); } +using ActionAndBrowserActionAPITest = MultiActionAPITest; + +// Tests whether action values persist across sessions. +// Note: Since pageActions are only applicable on a specific tab, this test +// doesn't apply to them. +IN_PROC_BROWSER_TEST_P(ActionAndBrowserActionAPITest, PRE_ValuesArePersisted) { + const char* dir_name = nullptr; + switch (GetParam()) { + case ActionInfo::TYPE_ACTION: + dir_name = "extension_action/action_persistence"; + break; + case ActionInfo::TYPE_BROWSER: + dir_name = "extension_action/browser_action_persistence"; + break; + case ActionInfo::TYPE_PAGE: + NOTREACHED(); + break; + } + // Load up an extension, which then modifies the popup, title, and badge text + // of the action. We need to use a "real" extension on disk here (rather than + // a TestExtensionDir owned by the test fixture), because it needs to persist + // to the next test. + ResultCatcher catcher; + const Extension* extension = + LoadExtension(test_data_dir_.AppendASCII(dir_name)); + ASSERT_TRUE(extension); + ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); + + // Verify the values were modified. + auto* action_manager = ExtensionActionManager::Get(profile()); + ExtensionAction* action = action_manager->GetExtensionAction(*extension); + EXPECT_EQ(extension->GetResourceURL("modified_popup.html"), + action->GetPopupUrl(ExtensionAction::kDefaultTabId)); + EXPECT_EQ("modified title", action->GetTitle(ExtensionAction::kDefaultTabId)); + EXPECT_EQ("custom badge text", + action->GetExplicitlySetBadgeText(ExtensionAction::kDefaultTabId)); + + // We flush the state store to ensure the modified state is correctly stored + // on-disk (which could otherwise be potentially racy). + FlushStateStore(profile()); +} + +IN_PROC_BROWSER_TEST_P(ActionAndBrowserActionAPITest, ValuesArePersisted) { + const Extension* extension = GetSingleLoadedExtension(); + ASSERT_TRUE(extension); + EXPECT_EQ("Action persistence check", extension->name()); + + // The previous action states are read from the state store on start-up. + // Flushing it ensures that any pending tasks have run, and the action + // should be up-to-date. + FlushStateStore(profile()); + + auto* action_manager = ExtensionActionManager::Get(profile()); + ExtensionAction* action = action_manager->GetExtensionAction(*extension); + + // Only browser actions - not generic actions - persist values. + bool expect_persisted_values = GetParam() == ActionInfo::TYPE_BROWSER; + + std::string expected_badge_text = + expect_persisted_values ? "custom badge text" : ""; + + EXPECT_EQ(expected_badge_text, + action->GetExplicitlySetBadgeText(ExtensionAction::kDefaultTabId)); + + // Due to https://crbug.com/1110156, action values with defaults specified in + // the manifest - like popup and title - aren't persisted, even for browser + // actions. + EXPECT_EQ(extension->GetResourceURL("default_popup.html"), + action->GetPopupUrl(ExtensionAction::kDefaultTabId)); + EXPECT_EQ("default title", action->GetTitle(ExtensionAction::kDefaultTabId)); +} + // Tests setting the icon dynamically from the background page. IN_PROC_BROWSER_TEST_P(MultiActionAPICanvasTest, DynamicSetIcon) { constexpr char kManifestTemplate[] = @@ -1178,6 +1258,11 @@ ActionInfo::TYPE_BROWSER)); INSTANTIATE_TEST_SUITE_P(All, + ActionAndBrowserActionAPITest, + testing::Values(ActionInfo::TYPE_ACTION, + ActionInfo::TYPE_BROWSER)); + +INSTANTIATE_TEST_SUITE_P(All, MultiActionAPICanvasTest, testing::Values(ActionInfo::TYPE_ACTION, ActionInfo::TYPE_PAGE,
diff --git a/chrome/browser/extensions/api/feedback_private/chrome_feedback_private_delegate.cc b/chrome/browser/extensions/api/feedback_private/chrome_feedback_private_delegate.cc index 312a3838..ba41298 100644 --- a/chrome/browser/extensions/api/feedback_private/chrome_feedback_private_delegate.cc +++ b/chrome/browser/extensions/api/feedback_private/chrome_feedback_private_delegate.cc
@@ -77,6 +77,7 @@ SET_STRING("additionalInfo", IDS_FEEDBACK_ADDITIONAL_INFO_LABEL); SET_STRING("minimizeBtnLabel", IDS_FEEDBACK_MINIMIZE_BUTTON_LABEL); SET_STRING("closeBtnLabel", IDS_FEEDBACK_CLOSE_BUTTON_LABEL); + SET_STRING("freeFormText", IDS_FEEDBACK_FREE_TEXT_LABEL); SET_STRING("pageUrl", IDS_FEEDBACK_REPORT_URL_LABEL); SET_STRING("screenshot", IDS_FEEDBACK_SCREENSHOT_LABEL); SET_STRING("screenshotA11y", IDS_FEEDBACK_SCREENSHOT_A11Y_TEXT);
diff --git a/chrome/browser/extensions/extension_action_storage_manager.cc b/chrome/browser/extensions/extension_action_storage_manager.cc index c92fe7e..6160c89 100644 --- a/chrome/browser/extensions/extension_action_storage_manager.cc +++ b/chrome/browser/extensions/extension_action_storage_manager.cc
@@ -233,7 +233,6 @@ // is null. We only persist the default settings to disk, since per-tab // settings can't be persisted across browser sessions. bool for_default_tab = !web_contents; - // TODO(devlin): We should probably persist for TYPE_ACTION as well. if (browser_context_ == browser_context && extension_action->action_type() == ActionInfo::TYPE_BROWSER && for_default_tab) {
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index 3785512..41a09a6 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -3372,11 +3372,6 @@ "expiry_milestone": 87 }, { - "name": "omnibox-disable-instant-extended-limit", - "owners": [ "pnoland", "chrome-omnibox-team@google.com" ], - "expiry_milestone": 85 - }, - { "name": "omnibox-display-title-for-current-url", "owners": [ "chrome-omnibox-team@google.com" ], "expiry_milestone": 76 @@ -3567,6 +3562,11 @@ "expiry_milestone": 76 }, { + "name": "omnibox-webui-omnibox-popup", + "owners": [ "tommycli", "chrome-omnibox-team@google.com" ], + "expiry_milestone": 99 + }, + { "name": "on-the-fly-mhtml-hash-computation", "owners": [ "sclittle", "srsudar", "offline-dev" ], "expiry_milestone": 76
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index 9c11055..122df7a 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -1496,12 +1496,6 @@ "the current page is provided as the first suggestion without a title. " "Enabling this flag causes the title to be displayed."; -const char kOmniboxDisableInstantExtendedLimitName[] = - "Disable the 'instant extended' limit on search suggestions"; -const char kOmniboxDisableInstantExtendedLimitDescription[] = - "Effectively doubles the max number of Google-provided search suggestions " - "on Android by disabling the 'Instant Extended' check."; - const char kOmniboxExperimentalSuggestScoringName[] = "Omnibox Experimental Suggest Scoring"; const char kOmniboxExperimentalSuggestScoringDescription[] = @@ -1690,6 +1684,11 @@ "In the omnibox dropdown, shows titles before URLs when both are " "available."; +const char kOmniboxWebUIOmniboxPopupName[] = "WebUI Omnibox Popup"; +const char kOmniboxWebUIOmniboxPopupDescription[] = + "If enabled, uses WebUI to render the omnibox suggestions popup, similar " + "to how the NTP \"realbox\" is implemented."; + const char kOnTheFlyMhtmlHashComputationName[] = "On-The-Fly MHTML Hash Computation"; const char kOnTheFlyMhtmlHashComputationDescription[] =
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 8235995..db42c69 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -870,9 +870,6 @@ extern const char kOmniboxDeferredKeyboardPopupName[]; extern const char kOmniboxDeferredKeyboardPopupDescription[]; -extern const char kOmniboxDisableInstantExtendedLimitName[]; -extern const char kOmniboxDisableInstantExtendedLimitDescription[]; - extern const char kOmniboxDisplayTitleForCurrentUrlName[]; extern const char kOmniboxDisplayTitleForCurrentUrlDescription[]; @@ -976,6 +973,9 @@ extern const char kOmniboxUISwapTitleAndUrlName[]; extern const char kOmniboxUISwapTitleAndUrlDescription[]; +extern const char kOmniboxWebUIOmniboxPopupName[]; +extern const char kOmniboxWebUIOmniboxPopupDescription[]; + extern const char kOnTheFlyMhtmlHashComputationName[]; extern const char kOnTheFlyMhtmlHashComputationDescription[];
diff --git a/chrome/browser/intranet_redirect_detector.cc b/chrome/browser/intranet_redirect_detector.cc index c21bfecf..56eb9cf 100644 --- a/chrome/browser/intranet_redirect_detector.cc +++ b/chrome/browser/intranet_redirect_detector.cc
@@ -73,6 +73,7 @@ registry->RegisterStringPref(prefs::kLastKnownIntranetRedirectOrigin, std::string()); registry->RegisterBooleanPref(prefs::kDNSInterceptionChecksEnabled, true); + registry->RegisterIntegerPref(prefs::kIntranetRedirectBehavior, 0); } void IntranetRedirectDetector::Restart() {
diff --git a/chrome/browser/lite_video/lite_video_observer.cc b/chrome/browser/lite_video/lite_video_observer.cc index 55173b3..d2e9cae 100644 --- a/chrome/browser/lite_video/lite_video_observer.cc +++ b/chrome/browser/lite_video/lite_video_observer.cc
@@ -275,4 +275,29 @@ render_frame_host->GetLastCommittedURL(), true); } +void LiteVideoObserver::MediaPlayerSeek(const content::MediaPlayerId& id) { + content::RenderFrameHost* render_frame_host = id.render_frame_host; + + if (!render_frame_host || !render_frame_host->GetProcess()) + return; + + // Only consider a seek event related to LiteVideos if they were allowed on + // current navigation. + if (!nav_metrics_ || + nav_metrics_->decision() != lite_video::LiteVideoDecision::kAllowed) { + return; + } + + mojo::AssociatedRemote<blink::mojom::PreviewsResourceLoadingHintsReceiver> + loading_hints_agent; + + if (!render_frame_host->GetRemoteAssociatedInterfaces()) + return; + + render_frame_host->GetRemoteAssociatedInterfaces()->GetInterface( + &loading_hints_agent); + + loading_hints_agent->StopThrottlingMediaRequests(); +} + WEB_CONTENTS_USER_DATA_KEY_IMPL(LiteVideoObserver)
diff --git a/chrome/browser/lite_video/lite_video_observer.h b/chrome/browser/lite_video/lite_video_observer.h index 283f3e3..2c85eeb0 100644 --- a/chrome/browser/lite_video/lite_video_observer.h +++ b/chrome/browser/lite_video/lite_video_observer.h
@@ -44,6 +44,7 @@ void DidFinishNavigation( content::NavigationHandle* navigation_handle) override; void MediaBufferUnderflow(const content::MediaPlayerId& id) override; + void MediaPlayerSeek(const content::MediaPlayerId& id) override; // Determines the LiteVideoDecision based on |hint| and the coinflip // holdback state.
diff --git a/chrome/browser/media/router/discovery/dial/dial_url_fetcher.cc b/chrome/browser/media/router/discovery/dial/dial_url_fetcher.cc index f86e0c1..c7390f4 100644 --- a/chrome/browser/media/router/discovery/dial/dial_url_fetcher.cc +++ b/chrome/browser/media/router/discovery/dial/dial_url_fetcher.cc
@@ -125,9 +125,15 @@ auto request = std::make_unique<network::ResourceRequest>(); request->url = url; request->method = method; - // As a security mitigation, DIAL launch requests now require a fake origin - // which cannot be spoofed by the drive-by Web. Rather than attempt to - // coerce this fake origin into a url::Origin, set the header directly. + // DIAL requests are made by the browser to a fixed set of URLs in response to + // user actions, not by Web frames. They require an Origin header, to prevent + // arbitrary Web frames from issuing site-controlled DIAL requests via Fetch + // or XHR. We set a fake Origin that is only used by the browser to satisfy + // this requirement. Rather than attempt to coerce this fake origin into a + // url::Origin, set the header directly. + // + // TODO(crbug.com/1136284): Pass through an actual Origin, which improves + // compatibility with certain DIAL applications (e.g., Netflix). request->headers.SetHeader("Origin", GetFakeOriginForDialLaunch()); method_ = method;
diff --git a/chrome/browser/nearby_sharing/BUILD.gn b/chrome/browser/nearby_sharing/BUILD.gn index 3ef8bd8..d19e7fe98 100644 --- a/chrome/browser/nearby_sharing/BUILD.gn +++ b/chrome/browser/nearby_sharing/BUILD.gn
@@ -18,8 +18,8 @@ deps = [ "//base", - "//chrome/services/sharing/public/mojom", - "//chrome/services/sharing/public/mojom:nearby_share_target_types", + "//chromeos/services/nearby/public/mojom", + "//chromeos/services/nearby/public/mojom:nearby_share_target_types", "//net", "//url", ]
diff --git a/chrome/browser/nearby_sharing/fake_nearby_connections_manager.h b/chrome/browser/nearby_sharing/fake_nearby_connections_manager.h index 757e722..a54e937 100644 --- a/chrome/browser/nearby_sharing/fake_nearby_connections_manager.h +++ b/chrome/browser/nearby_sharing/fake_nearby_connections_manager.h
@@ -14,7 +14,7 @@ #include "base/callback.h" #include "base/optional.h" #include "chrome/browser/nearby_sharing/nearby_connections_manager.h" -#include "chrome/services/sharing/public/mojom/nearby_connections.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_connections.mojom.h" class NearbyConnection;
diff --git a/chrome/browser/nearby_sharing/file_attachment.h b/chrome/browser/nearby_sharing/file_attachment.h index a8b7ccc6..917bbab 100644 --- a/chrome/browser/nearby_sharing/file_attachment.h +++ b/chrome/browser/nearby_sharing/file_attachment.h
@@ -10,7 +10,7 @@ #include "base/files/file_path.h" #include "base/optional.h" #include "chrome/browser/nearby_sharing/attachment.h" -#include "chrome/services/sharing/public/mojom/nearby_decoder_types.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_decoder_types.mojom.h" // A single attachment to be sent by / received from a |ShareTarget|, can be // either a file or text.
diff --git a/chrome/browser/nearby_sharing/incoming_frames_reader.cc b/chrome/browser/nearby_sharing/incoming_frames_reader.cc index b3a2d525..285a8dd3 100644 --- a/chrome/browser/nearby_sharing/incoming_frames_reader.cc +++ b/chrome/browser/nearby_sharing/incoming_frames_reader.cc
@@ -11,7 +11,7 @@ #include "chrome/browser/nearby_sharing/nearby_connection.h" #include "chrome/browser/nearby_sharing/nearby_process_manager.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/services/sharing/public/mojom/nearby_decoder.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_decoder.mojom.h" namespace {
diff --git a/chrome/browser/nearby_sharing/incoming_frames_reader.h b/chrome/browser/nearby_sharing/incoming_frames_reader.h index 8de1b85..d072dc7 100644 --- a/chrome/browser/nearby_sharing/incoming_frames_reader.h +++ b/chrome/browser/nearby_sharing/incoming_frames_reader.h
@@ -15,7 +15,7 @@ #include "base/sequence_checker.h" #include "base/time/time.h" #include "chrome/browser/nearby_sharing/nearby_process_manager.h" -#include "chrome/services/sharing/public/mojom/nearby_decoder_types.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_decoder_types.mojom.h" class NearbyConnection; class Profile;
diff --git a/chrome/browser/nearby_sharing/mock_nearby_connections.h b/chrome/browser/nearby_sharing/mock_nearby_connections.h index e5dc630c..067e907 100644 --- a/chrome/browser/nearby_sharing/mock_nearby_connections.h +++ b/chrome/browser/nearby_sharing/mock_nearby_connections.h
@@ -5,7 +5,7 @@ #ifndef CHROME_BROWSER_NEARBY_SHARING_MOCK_NEARBY_CONNECTIONS_H_ #define CHROME_BROWSER_NEARBY_SHARING_MOCK_NEARBY_CONNECTIONS_H_ -#include "chrome/services/sharing/public/mojom/nearby_connections.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_connections.mojom.h" #include "testing/gmock/include/gmock/gmock.h"
diff --git a/chrome/browser/nearby_sharing/mock_nearby_sharing_decoder.h b/chrome/browser/nearby_sharing/mock_nearby_sharing_decoder.h index b5ac24ac..4e4794b6 100644 --- a/chrome/browser/nearby_sharing/mock_nearby_sharing_decoder.h +++ b/chrome/browser/nearby_sharing/mock_nearby_sharing_decoder.h
@@ -5,7 +5,7 @@ #ifndef CHROME_BROWSER_NEARBY_SHARING_MOCK_NEARBY_SHARING_DECODER_H_ #define CHROME_BROWSER_NEARBY_SHARING_MOCK_NEARBY_SHARING_DECODER_H_ -#include "chrome/services/sharing/public/mojom/nearby_decoder.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_decoder.mojom.h" #include "testing/gmock/include/gmock/gmock.h" class MockNearbySharingDecoder : public sharing::mojom::NearbySharingDecoder {
diff --git a/chrome/browser/nearby_sharing/nearby_connection_impl.h b/chrome/browser/nearby_sharing/nearby_connection_impl.h index 58368c16..ebb0f199 100644 --- a/chrome/browser/nearby_sharing/nearby_connection_impl.h +++ b/chrome/browser/nearby_sharing/nearby_connection_impl.h
@@ -10,7 +10,7 @@ #include <queue> #include <vector> #include "base/sequence_checker.h" -#include "chrome/services/sharing/public/mojom/nearby_connections_types.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_connections_types.mojom.h" class NearbyConnectionsManager;
diff --git a/chrome/browser/nearby_sharing/nearby_connections_manager.h b/chrome/browser/nearby_sharing/nearby_connections_manager.h index e2de9f55..7a6c71c 100644 --- a/chrome/browser/nearby_sharing/nearby_connections_manager.h +++ b/chrome/browser/nearby_sharing/nearby_connections_manager.h
@@ -14,7 +14,7 @@ #include "base/optional.h" #include "chrome/browser/nearby_sharing/common/nearby_share_enums.h" #include "chrome/browser/nearby_sharing/nearby_connection.h" -#include "chrome/services/sharing/public/mojom/nearby_connections_types.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_connections_types.mojom.h" // A wrapper around the Nearby Connections mojo API. class NearbyConnectionsManager {
diff --git a/chrome/browser/nearby_sharing/nearby_connections_manager_impl.cc b/chrome/browser/nearby_sharing/nearby_connections_manager_impl.cc index 6d3a301..5647093 100644 --- a/chrome/browser/nearby_sharing/nearby_connections_manager_impl.cc +++ b/chrome/browser/nearby_sharing/nearby_connections_manager_impl.cc
@@ -10,7 +10,7 @@ #include "base/unguessable_token.h" #include "chrome/browser/nearby_sharing/constants.h" #include "chrome/browser/nearby_sharing/logging/logging.h" -#include "chrome/services/sharing/public/mojom/nearby_connections_types.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_connections_types.mojom.h" #include "crypto/random.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "net/base/network_change_notifier.h"
diff --git a/chrome/browser/nearby_sharing/nearby_connections_manager_impl.h b/chrome/browser/nearby_sharing/nearby_connections_manager_impl.h index fa38c65..6e2fbcd 100644 --- a/chrome/browser/nearby_sharing/nearby_connections_manager_impl.h +++ b/chrome/browser/nearby_sharing/nearby_connections_manager_impl.h
@@ -16,7 +16,7 @@ #include "chrome/browser/nearby_sharing/nearby_connection_impl.h" #include "chrome/browser/nearby_sharing/nearby_file_handler.h" #include "chrome/browser/nearby_sharing/nearby_process_manager.h" -#include "chrome/services/sharing/public/mojom/nearby_connections.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_connections.mojom.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/receiver_set.h"
diff --git a/chrome/browser/nearby_sharing/nearby_connections_manager_impl_unittest.cc b/chrome/browser/nearby_sharing/nearby_connections_manager_impl_unittest.cc index 1e1be284..f4ed152d 100644 --- a/chrome/browser/nearby_sharing/nearby_connections_manager_impl_unittest.cc +++ b/chrome/browser/nearby_sharing/nearby_connections_manager_impl_unittest.cc
@@ -15,9 +15,9 @@ #include "chrome/browser/nearby_sharing/mock_nearby_connections.h" #include "chrome/browser/nearby_sharing/mock_nearby_process_manager.h" #include "chrome/browser/nearby_sharing/nearby_connection_impl.h" -#include "chrome/services/sharing/public/mojom/nearby_connections_types.mojom.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" +#include "chromeos/services/nearby/public/mojom/nearby_connections_types.mojom.h" #include "content/public/test/browser_task_environment.h" #include "mojo/public/cpp/bindings/remote.h" #include "net/base/mock_network_change_notifier.h"
diff --git a/chrome/browser/nearby_sharing/nearby_file_handler.cc b/chrome/browser/nearby_sharing/nearby_file_handler.cc index 1d7ed085..37776ec 100644 --- a/chrome/browser/nearby_sharing/nearby_file_handler.cc +++ b/chrome/browser/nearby_sharing/nearby_file_handler.cc
@@ -7,7 +7,7 @@ #include "base/files/file_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" -#include "chrome/services/sharing/public/mojom/nearby_connections_types.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_connections_types.mojom.h" namespace {
diff --git a/chrome/browser/nearby_sharing/nearby_file_handler.h b/chrome/browser/nearby_sharing/nearby_file_handler.h index d766260..f5711be 100644 --- a/chrome/browser/nearby_sharing/nearby_file_handler.h +++ b/chrome/browser/nearby_sharing/nearby_file_handler.h
@@ -13,7 +13,7 @@ #include "base/files/file_path.h" #include "base/memory/scoped_refptr.h" #include "base/sequenced_task_runner.h" -#include "chrome/services/sharing/public/mojom/nearby_connections_types.mojom-forward.h" +#include "chromeos/services/nearby/public/mojom/nearby_connections_types.mojom-forward.h" // This class manages async File IO for Nearby Share file payloads. Opening and // releasing files need to run on a MayBlock task runner.
diff --git a/chrome/browser/nearby_sharing/nearby_process_manager.cc b/chrome/browser/nearby_sharing/nearby_process_manager.cc index 2e851b1c..fb3d7b5e 100644 --- a/chrome/browser/nearby_sharing/nearby_process_manager.cc +++ b/chrome/browser/nearby_sharing/nearby_process_manager.cc
@@ -24,7 +24,7 @@ #include "chrome/browser/sharing/webrtc/ice_config_fetcher.h" #include "chrome/browser/sharing/webrtc/sharing_mojo_service.h" #include "chrome/browser/signin/identity_manager_factory.h" -#include "chrome/services/sharing/public/mojom/nearby_connections.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_connections.mojom.h" #include "components/prefs/pref_service.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "content/public/browser/network_context_client_base.h"
diff --git a/chrome/browser/nearby_sharing/nearby_process_manager.h b/chrome/browser/nearby_sharing/nearby_process_manager.h index a20afda5..9e04802 100644 --- a/chrome/browser/nearby_sharing/nearby_process_manager.h +++ b/chrome/browser/nearby_sharing/nearby_process_manager.h
@@ -12,9 +12,9 @@ #include "base/observer_list_types.h" #include "base/scoped_observer.h" #include "chrome/browser/profiles/profile_manager_observer.h" -#include "chrome/services/sharing/public/mojom/nearby_connections.mojom.h" -#include "chrome/services/sharing/public/mojom/nearby_decoder.mojom.h" -#include "chrome/services/sharing/public/mojom/sharing.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_connections.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_decoder.mojom.h" +#include "chromeos/services/nearby/public/mojom/sharing.mojom.h" #include "device/bluetooth/bluetooth_adapter.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h"
diff --git a/chrome/browser/nearby_sharing/nearby_process_manager_unittest.cc b/chrome/browser/nearby_sharing/nearby_process_manager_unittest.cc index 3ff3e48..2f80bcd 100644 --- a/chrome/browser/nearby_sharing/nearby_process_manager_unittest.cc +++ b/chrome/browser/nearby_sharing/nearby_process_manager_unittest.cc
@@ -20,14 +20,14 @@ #include "chrome/browser/nearby_sharing/mock_nearby_sharing_decoder.h" #include "chrome/browser/profiles/profile_attributes_entry.h" #include "chrome/browser/profiles/profile_attributes_storage.h" -#include "chrome/services/sharing/public/mojom/nearby_connections.mojom.h" -#include "chrome/services/sharing/public/mojom/nearby_connections_types.mojom.h" -#include "chrome/services/sharing/public/mojom/nearby_decoder.mojom.h" -#include "chrome/services/sharing/public/mojom/sharing.mojom.h" -#include "chrome/services/sharing/public/mojom/webrtc.mojom.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/testing_profile_manager.h" +#include "chromeos/services/nearby/public/mojom/nearby_connections.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_connections_types.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_decoder.mojom.h" +#include "chromeos/services/nearby/public/mojom/sharing.mojom.h" +#include "chromeos/services/nearby/public/mojom/webrtc.mojom.h" #include "components/account_id/account_id.h" #include "components/prefs/pref_service.h" #include "content/public/test/browser_task_environment.h"
diff --git a/chrome/browser/nearby_sharing/nearby_sharing_service_impl.cc b/chrome/browser/nearby_sharing/nearby_sharing_service_impl.cc index 7ccf80f..487fb418 100644 --- a/chrome/browser/nearby_sharing/nearby_sharing_service_impl.cc +++ b/chrome/browser/nearby_sharing/nearby_sharing_service_impl.cc
@@ -38,7 +38,7 @@ #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/services/sharing/public/cpp/advertisement.h" #include "chrome/services/sharing/public/cpp/conversions.h" -#include "chrome/services/sharing/public/mojom/nearby_connections_types.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_connections_types.mojom.h" #include "components/prefs/pref_service.h" #include "content/public/browser/download_manager.h" #include "content/public/browser/storage_partition.h"
diff --git a/chrome/browser/nearby_sharing/nearby_sharing_service_impl.h b/chrome/browser/nearby_sharing/nearby_sharing_service_impl.h index 467763b..281da60 100644 --- a/chrome/browser/nearby_sharing/nearby_sharing_service_impl.h +++ b/chrome/browser/nearby_sharing/nearby_sharing_service_impl.h
@@ -39,8 +39,8 @@ #include "chrome/browser/nearby_sharing/share_target.h" #include "chrome/browser/nearby_sharing/transfer_metadata.h" #include "chrome/browser/ui/webui/nearby_share/public/mojom/nearby_share_settings.mojom.h" -#include "chrome/services/sharing/public/mojom/nearby_decoder_types.mojom.h" #include "chrome/services/sharing/public/proto/wire_format.pb.h" +#include "chromeos/services/nearby/public/mojom/nearby_decoder_types.mojom.h" #include "components/prefs/pref_change_registrar.h" class FastInitiationManager;
diff --git a/chrome/browser/nearby_sharing/nearby_sharing_service_impl_unittest.cc b/chrome/browser/nearby_sharing/nearby_sharing_service_impl_unittest.cc index 04cdd52..5e0dfd1 100644 --- a/chrome/browser/nearby_sharing/nearby_sharing_service_impl_unittest.cc +++ b/chrome/browser/nearby_sharing/nearby_sharing_service_impl_unittest.cc
@@ -47,11 +47,11 @@ #include "chrome/browser/ui/webui/nearby_share/public/mojom/nearby_share_settings.mojom.h" #include "chrome/services/sharing/nearby/decoder/advertisement_decoder.h" #include "chrome/services/sharing/public/cpp/advertisement.h" -#include "chrome/services/sharing/public/mojom/nearby_connections_types.mojom.h" #include "chrome/services/sharing/public/proto/wire_format.pb.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/testing_profile_manager.h" +#include "chromeos/services/nearby/public/mojom/nearby_connections_types.mojom.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "content/public/test/browser_task_environment.h" #include "device/bluetooth/bluetooth_adapter.h"
diff --git a/chrome/browser/nearby_sharing/outgoing_share_target_info.h b/chrome/browser/nearby_sharing/outgoing_share_target_info.h index 18b5b73..4aff6a7 100644 --- a/chrome/browser/nearby_sharing/outgoing_share_target_info.h +++ b/chrome/browser/nearby_sharing/outgoing_share_target_info.h
@@ -10,7 +10,7 @@ #include "base/optional.h" #include "chrome/browser/nearby_sharing/share_target_info.h" -#include "chrome/services/sharing/public/mojom/nearby_connections_types.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_connections_types.mojom.h" // A description of the outgoing connection to a remote device. class OutgoingShareTargetInfo : public ShareTargetInfo {
diff --git a/chrome/browser/nearby_sharing/paired_key_verification_runner.h b/chrome/browser/nearby_sharing/paired_key_verification_runner.h index 73e3d6e..c62ced7 100644 --- a/chrome/browser/nearby_sharing/paired_key_verification_runner.h +++ b/chrome/browser/nearby_sharing/paired_key_verification_runner.h
@@ -18,7 +18,7 @@ #include "chrome/browser/nearby_sharing/nearby_connection.h" #include "chrome/browser/nearby_sharing/share_target.h" #include "chrome/browser/ui/webui/nearby_share/public/mojom/nearby_share_settings.mojom.h" -#include "chrome/services/sharing/public/mojom/nearby_decoder_types.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_decoder_types.mojom.h" class PairedKeyVerificationRunner { public:
diff --git a/chrome/browser/nearby_sharing/payload_tracker.h b/chrome/browser/nearby_sharing/payload_tracker.h index d47f79e..b9da936c 100644 --- a/chrome/browser/nearby_sharing/payload_tracker.h +++ b/chrome/browser/nearby_sharing/payload_tracker.h
@@ -12,7 +12,7 @@ #include "chrome/browser/nearby_sharing/nearby_connections_manager.h" #include "chrome/browser/nearby_sharing/share_target.h" #include "chrome/browser/nearby_sharing/transfer_metadata.h" -#include "chrome/services/sharing/public/mojom/nearby_connections_types.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_connections_types.mojom.h" class PayloadTracker : public NearbyConnectionsManager::PayloadStatusListener { public:
diff --git a/chrome/browser/nearby_sharing/share_target.h b/chrome/browser/nearby_sharing/share_target.h index 5708453..de0d2886 100644 --- a/chrome/browser/nearby_sharing/share_target.h +++ b/chrome/browser/nearby_sharing/share_target.h
@@ -13,7 +13,7 @@ #include "base/unguessable_token.h" #include "chrome/browser/nearby_sharing/file_attachment.h" #include "chrome/browser/nearby_sharing/text_attachment.h" -#include "chrome/services/sharing/public/mojom/nearby_share_target_types.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_share_target_types.mojom.h" #include "url/gurl.h" // A remote device.
diff --git a/chrome/browser/nearby_sharing/text_attachment.h b/chrome/browser/nearby_sharing/text_attachment.h index 6397a58..71f4c7ae 100644 --- a/chrome/browser/nearby_sharing/text_attachment.h +++ b/chrome/browser/nearby_sharing/text_attachment.h
@@ -9,7 +9,7 @@ #include "base/optional.h" #include "chrome/browser/nearby_sharing/attachment.h" -#include "chrome/services/sharing/public/mojom/nearby_decoder_types.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_decoder_types.mojom.h" // Represents a text attachment. class TextAttachment : public Attachment {
diff --git a/chrome/browser/nearby_sharing/webrtc_signaling_messenger.h b/chrome/browser/nearby_sharing/webrtc_signaling_messenger.h index 74fe4dc..f6f935e 100644 --- a/chrome/browser/nearby_sharing/webrtc_signaling_messenger.h +++ b/chrome/browser/nearby_sharing/webrtc_signaling_messenger.h
@@ -11,7 +11,7 @@ #include "chrome/browser/nearby_sharing/instantmessaging/receive_messages_express.h" #include "chrome/browser/nearby_sharing/instantmessaging/send_message_express.h" #include "chrome/browser/nearby_sharing/instantmessaging/token_fetcher.h" -#include "chrome/services/sharing/public/mojom/webrtc_signaling_messenger.mojom.h" +#include "chromeos/services/nearby/public/mojom/webrtc_signaling_messenger.mojom.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "services/network/public/cpp/shared_url_loader_factory.h"
diff --git a/chrome/browser/page_load_metrics/observers/translate_page_load_metrics_observer.cc b/chrome/browser/page_load_metrics/observers/translate_page_load_metrics_observer.cc index fdfb2502..481bb7a6 100644 --- a/chrome/browser/page_load_metrics/observers/translate_page_load_metrics_observer.cc +++ b/chrome/browser/page_load_metrics/observers/translate_page_load_metrics_observer.cc
@@ -4,15 +4,25 @@ #include "chrome/browser/page_load_metrics/observers/translate_page_load_metrics_observer.h" +#include "chrome/browser/translate/chrome_translate_client.h" +#include "components/translate/core/browser/translate_manager.h" #include "components/translate/core/browser/translate_metrics_logger_impl.h" std::unique_ptr<TranslatePageLoadMetricsObserver> -TranslatePageLoadMetricsObserver::CreateIfNeeded() { - // TODO(curranamx): Connect the new TranslateMetricsLogger to a - // TranslateManager. https://crbug.com/1114868. - std::unique_ptr<translate::TranslateMetricsLogger> translate_metrics_logger = - std::make_unique<translate::TranslateMetricsLoggerImpl>(); +TranslatePageLoadMetricsObserver::CreateIfNeeded( + content::WebContents* web_contents) { + // Gets the |TranslateManager| associated with the same |WebContents| as this + // |TranslatePageLoadMetricsObserver|. + translate::TranslateManager* translate_manager = + ChromeTranslateClient::GetManagerFromWebContents(web_contents); + if (translate_manager == nullptr) + return nullptr; + // Creates a new |TranslateMetricsLoggerImpl| and associates with the above + // |TranslateManager|. + std::unique_ptr<translate::TranslateMetricsLogger> translate_metrics_logger = + std::make_unique<translate::TranslateMetricsLoggerImpl>( + translate_manager->GetWeakPtr()); return std::make_unique<TranslatePageLoadMetricsObserver>( std::move(translate_metrics_logger)); } @@ -28,8 +38,6 @@ content::NavigationHandle* navigation_handle, const GURL& currently_committed_url, bool started_in_foreground) { - DCHECK(translate_metrics_logger_ != nullptr); - translate_metrics_logger_->OnPageLoadStart(started_in_foreground); return CONTINUE_OBSERVING; } @@ -37,16 +45,12 @@ page_load_metrics::PageLoadMetricsObserver::ObservePolicy TranslatePageLoadMetricsObserver::OnHidden( const page_load_metrics::mojom::PageLoadTiming& timing) { - DCHECK(translate_metrics_logger_ != nullptr); - translate_metrics_logger_->OnForegroundChange(false); return CONTINUE_OBSERVING; } page_load_metrics::PageLoadMetricsObserver::ObservePolicy TranslatePageLoadMetricsObserver::OnShown() { - DCHECK(translate_metrics_logger_ != nullptr); - translate_metrics_logger_->OnForegroundChange(true); return CONTINUE_OBSERVING; } @@ -54,15 +58,11 @@ page_load_metrics::PageLoadMetricsObserver::ObservePolicy TranslatePageLoadMetricsObserver::FlushMetricsOnAppEnterBackground( const page_load_metrics::mojom::PageLoadTiming& timing) { - DCHECK(translate_metrics_logger_ != nullptr); - translate_metrics_logger_->RecordMetrics(false); return CONTINUE_OBSERVING; } void TranslatePageLoadMetricsObserver::OnComplete( const page_load_metrics::mojom::PageLoadTiming& timing) { - DCHECK(translate_metrics_logger_ != nullptr); - translate_metrics_logger_->RecordMetrics(true); }
diff --git a/chrome/browser/page_load_metrics/observers/translate_page_load_metrics_observer.h b/chrome/browser/page_load_metrics/observers/translate_page_load_metrics_observer.h index 8ef882e..c4902b6 100644 --- a/chrome/browser/page_load_metrics/observers/translate_page_load_metrics_observer.h +++ b/chrome/browser/page_load_metrics/observers/translate_page_load_metrics_observer.h
@@ -24,7 +24,8 @@ class TranslatePageLoadMetricsObserver : public page_load_metrics::PageLoadMetricsObserver { public: - static std::unique_ptr<TranslatePageLoadMetricsObserver> CreateIfNeeded(); + static std::unique_ptr<TranslatePageLoadMetricsObserver> CreateIfNeeded( + content::WebContents* web_contents); explicit TranslatePageLoadMetricsObserver( std::unique_ptr<translate::TranslateMetricsLogger>
diff --git a/chrome/browser/page_load_metrics/page_load_metrics_initialize.cc b/chrome/browser/page_load_metrics/page_load_metrics_initialize.cc index 904e197..ba7e8c363 100644 --- a/chrome/browser/page_load_metrics/page_load_metrics_initialize.cc +++ b/chrome/browser/page_load_metrics/page_load_metrics_initialize.cc
@@ -167,8 +167,9 @@ web_contents()->GetBrowserContext())); tracker->AddObserver(std::make_unique<DataUseMetricsObserver>()); std::unique_ptr<TranslatePageLoadMetricsObserver> translate_observer = - TranslatePageLoadMetricsObserver::CreateIfNeeded(); - if (translate_observer != nullptr) + TranslatePageLoadMetricsObserver::CreateIfNeeded( + tracker->GetWebContents()); + if (translate_observer) tracker->AddObserver(std::move(translate_observer)); }
diff --git a/chrome/browser/password_check/android/internal/java/strings/translations/android_password_check_strings_pa.xtb b/chrome/browser/password_check/android/internal/java/strings/translations/android_password_check_strings_pa.xtb index 909c825..d6db0709 100644 --- a/chrome/browser/password_check/android/internal/java/strings/translations/android_password_check_strings_pa.xtb +++ b/chrome/browser/password_check/android/internal/java/strings/translations/android_password_check_strings_pa.xtb
@@ -14,7 +14,7 @@ <translation id="3235063766008841141">ਕਿਸੇ ਧੋਖੇਬਾਜ਼ ਸਾਈਟ 'ਤੇ ਦਾਖਲ ਕੀਤਾ ਗਿਆ ਅਤੇ ਡਾਟਾ ਉਲੰਘਣਾ ਵਿੱਚ ਲੱਭਿਆ</translation> <translation id="3533694711092285624">ਕੋਈ ਰੱਖਿਅਤ ਕੀਤੇ ਪਾਸਵਰਡ ਨਹੀਂ। ਤੁਹਾਡੇ ਵੱਲੋਂ ਆਪਣੇ ਪਾਸਵਰਡ ਰੱਖਿਅਤ ਕਰਨ 'ਤੇ Chrome ਉਹਨਾਂ ਦੀ ਜਾਂਚ ਕਰ ਸਕਦਾ ਹੈ।</translation> <translation id="3568945271227339929">ਕਿਸੇ ਪਾਸਵਰਡ ਨਾਲ ਛੇੜਛਾੜ ਨਹੀਂ ਹੋਈ</translation> -<translation id="3918034518766455210">ਜਾਂਚੇ ਗਏ ਪਾਸਵਰਡ · <ph name="TIME_SINCE_LAST_CHECK" /></translation> +<translation id="3918034518766455210">ਪਾਸਵਰਡ ਜਾਂਚੇ ਗਏ · <ph name="TIME_SINCE_LAST_CHECK" /></translation> <translation id="5254370105662291020">ਪਾਸਵਰਡ ਦੇਖਣ ਲਈ ਅਣਲਾਕ ਕਰੋ</translation> <translation id="543338862236136125">ਪਾਸਵਰਡ ਦਾ ਸੰਪਾਦਨ ਕਰੋ</translation> <translation id="5539342724706569402">ਧੋਖੇਬਾਜ਼ ਸਾਈਟ 'ਤੇ ਦਾਖਲ ਕੀਤਾ</translation>
diff --git a/chrome/browser/password_check/android/internal/java/strings/translations/android_password_check_strings_pt-BR.xtb b/chrome/browser/password_check/android/internal/java/strings/translations/android_password_check_strings_pt-BR.xtb index 2eac2d2..d16dd12c 100644 --- a/chrome/browser/password_check/android/internal/java/strings/translations/android_password_check_strings_pt-BR.xtb +++ b/chrome/browser/password_check/android/internal/java/strings/translations/android_password_check_strings_pt-BR.xtb
@@ -5,19 +5,19 @@ <translation id="1513858653616922153">Excluir senha</translation> <translation id="1547725796794473036">{COMPROMISED_PASSWORDS,plural, =1{# senha comprometida}one{# senha comprometida}other{# senhas comprometidas}}</translation> <translation id="1599766761352751884">Verificando senhas (<ph name="ANALYSED_PASSWORDS" /> de <ph name="TOTAL_PASSWORDS" />)…</translation> -<translation id="1713125606790339209">As contas a seguir usam senhas que foram expostas em uma violação de dados de terceiros ou foram inseridas em um site enganoso. Mude essas senhas imediatamente para manter suas contas seguras.</translation> +<translation id="1713125606790339209">As contas a seguir usam senhas que foram expostas em uma violação de dados de terceiros ou foram inseridas em um fraudulento. Mude essas senhas imediatamente para manter suas contas seguras.</translation> <translation id="2224120951664717045">O Chrome avisará quando você fizer login com uma senha comprometida.</translation> <translation id="2369870139632127592">Desbloqueie para editar a senha</translation> <translation id="2388655922303272221">Mudar manualmente</translation> <translation id="2670599755795384625">Reiniciar a verificação de senhas</translation> <translation id="2775140325783767197">O Chrome não pode verificar suas senhas. Verifique sua conexão com a Internet.</translation> -<translation id="3235063766008841141">Utilizada em um site enganoso e encontrada em uma violação de dados</translation> +<translation id="3235063766008841141">Utilizada em um fraudulento e encontrada em uma violação de dados</translation> <translation id="3533694711092285624">Nenhuma senha salva. O Chrome poderá verificar suas senhas quando elas forem salvas.</translation> <translation id="3568945271227339929">Nenhuma senha comprometida</translation> <translation id="3918034518766455210">Senhas verificadas · <ph name="TIME_SINCE_LAST_CHECK" /></translation> <translation id="5254370105662291020">Desbloqueie para ver a senha</translation> <translation id="543338862236136125">Editar senha</translation> -<translation id="5539342724706569402">Inserida em um site enganoso</translation> +<translation id="5539342724706569402">Inserida em um fraudulento</translation> <translation id="5840081916976222104">Mude a senha no app</translation> <translation id="6342069812937806050">Neste instante</translation> <translation id="6407955178761087876">Permita que o Google Assistente ajude você a mudar sua senha</translation>
diff --git a/chrome/browser/password_check/android/internal/java/strings/translations/android_password_check_strings_uk.xtb b/chrome/browser/password_check/android/internal/java/strings/translations/android_password_check_strings_uk.xtb index e4d0771e..7de2d1f4 100644 --- a/chrome/browser/password_check/android/internal/java/strings/translations/android_password_check_strings_uk.xtb +++ b/chrome/browser/password_check/android/internal/java/strings/translations/android_password_check_strings_uk.xtb
@@ -19,7 +19,7 @@ <translation id="543338862236136125">Змінити пароль</translation> <translation id="5539342724706569402">Введено на оманливому сайті</translation> <translation id="5840081916976222104">Змініть пароль у додатку</translation> -<translation id="6342069812937806050">Лише зараз</translation> +<translation id="6342069812937806050">Щойно</translation> <translation id="6407955178761087876">Google Асистент може допомогти вам змінити пароль</translation> <translation id="686366188661646310">Видалити пароль?</translation> <translation id="7253951228444156601">Перевірка паролів…</translation>
diff --git a/chrome/browser/password_check/android/internal/java/strings/translations/android_password_check_strings_ur.xtb b/chrome/browser/password_check/android/internal/java/strings/translations/android_password_check_strings_ur.xtb index 69bf0c1..7e78dc1 100644 --- a/chrome/browser/password_check/android/internal/java/strings/translations/android_password_check_strings_ur.xtb +++ b/chrome/browser/password_check/android/internal/java/strings/translations/android_password_check_strings_ur.xtb
@@ -14,7 +14,7 @@ <translation id="3235063766008841141">ایک فریب کار سائٹ میں داخل ہو گیا اور ڈیٹا کی خلاف ورزی میں پایا گیا</translation> <translation id="3533694711092285624">کوئی محفوظ کردہ پاس ورڈز نہیں۔ جب آپ پاس ورڈز کو محفوظ کرتے ہیں تو Chrome انہیں چیک کر سکتا ہے۔</translation> <translation id="3568945271227339929">کوئی متاثرہ پاس ورڈ نہیں</translation> -<translation id="3918034518766455210">چیک کردہ پاس ورڈز · <ph name="TIME_SINCE_LAST_CHECK" /></translation> +<translation id="3918034518766455210">پاس ورڈز چیک کیے گئے ۔ <ph name="TIME_SINCE_LAST_CHECK" /></translation> <translation id="5254370105662291020">پاس ورڈ دیکھنے کے لیے غیر مقفل کریں</translation> <translation id="543338862236136125">پاس ورڈ میں ترمیم کریں</translation> <translation id="5539342724706569402">ایک فریب کار سائٹ میں داخل ہو گئے</translation>
diff --git a/chrome/browser/password_check/android/internal/java/strings/translations/android_password_check_strings_vi.xtb b/chrome/browser/password_check/android/internal/java/strings/translations/android_password_check_strings_vi.xtb index 67d8ede..b7a5be58 100644 --- a/chrome/browser/password_check/android/internal/java/strings/translations/android_password_check_strings_vi.xtb +++ b/chrome/browser/password_check/android/internal/java/strings/translations/android_password_check_strings_vi.xtb
@@ -25,7 +25,7 @@ <translation id="7253951228444156601">Đang kiểm tra mật khẩu…</translation> <translation id="7658239707568436148">Hủy</translation> <translation id="7693089333295158718">Chrome không thể kiểm tra mật khẩu của bạn. Hãy thử lại.</translation> -<translation id="7744192722284567281">Phát hiện mật khẩu bị rò rỉ</translation> +<translation id="7744192722284567281">Phát hiện thấy trong một sự cố rò rỉ dữ liệu</translation> <translation id="7808889146555843082">Thao tác xóa mật khẩu này sẽ không xóa tài khoản của bạn trên <ph name="SITE" />. Hãy đổi mật khẩu hoặc xóa tài khoản của bạn trên <ph name="SITE" /> để giữ an toàn cho tài khoản của bạn.</translation> <translation id="7986497153528221272">Để xem mật khẩu, trước tiên, hãy đặt phương thức khóa màn hình trên thiết bị của bạn</translation> <translation id="808894953321890993">Đổi mật khẩu</translation>
diff --git a/chrome/browser/performance_manager/mechanisms/userspace_swap_chromeos.cc b/chrome/browser/performance_manager/mechanisms/userspace_swap_chromeos.cc index bf861b23..39073052 100644 --- a/chrome/browser/performance_manager/mechanisms/userspace_swap_chromeos.cc +++ b/chrome/browser/performance_manager/mechanisms/userspace_swap_chromeos.cc
@@ -4,12 +4,17 @@ #include "chrome/browser/performance_manager/mechanisms/userspace_swap_chromeos.h" +#include <memory> + #include "base/bind.h" +#include "base/bits.h" #include "base/callback_helpers.h" #include "base/files/scoped_file.h" #include "base/posix/safe_strerror.h" +#include "base/process/process_metrics.h" #include "base/task/post_task.h" #include "base/threading/scoped_blocking_call.h" +#include "chromeos/memory/userspace_swap/region.h" #include "chromeos/memory/userspace_swap/swap_storage.h" #include "chromeos/memory/userspace_swap/userfaultfd.h" #include "chromeos/memory/userspace_swap/userspace_swap.h" @@ -32,34 +37,30 @@ namespace userspace_swap { namespace { + +using chromeos::memory::userspace_swap::RendererSwapData; using chromeos::memory::userspace_swap::SwapFile; using chromeos::memory::userspace_swap::UserfaultFD; using chromeos::memory::userspace_swap::UserspaceSwapConfig; -// The RendererSwapData structure contains all the state related to userspace -// swap for an individual renderer. -// -// TODO(bgeffon): This moves to a shared file later when the remainder of the -// code lands. -struct RendererSwapData { - int render_process_host_id; - bool setup_complete = false; - - std::unique_ptr<UserfaultFD> uffd; - std::unique_ptr<SwapFile> swap_file; -}; +// We cache the swap device free space so we don't hammer the FS layer with +// unnecessary syscalls. The initial value of 30s was chosen because it seemed +// like a safe value that would prevent hitting the disk too frequently while +// preventing space from getting too low in times of heavy swap. Feel free to +// change it if you find a better value. +constexpr base::TimeDelta kSwapDeviceAvailableSpaceCheckInterval = + base::TimeDelta::FromSeconds(30); +base::TimeTicks g_last_swap_device_free_space_check; +uint64_t g_swap_device_free_swap_bytes; // UserspaceSwapMechanismData contains process node specific details and // handles. class UserspaceSwapMechanismData : public ExternalNodeAttachedDataImpl<UserspaceSwapMechanismData> { public: - explicit UserspaceSwapMechanismData(const ProcessNode* node) - : swap_data(new RendererSwapData) {} + explicit UserspaceSwapMechanismData(const ProcessNode* node) {} ~UserspaceSwapMechanismData() override = default; - // Note: This is a unique_ptr because it will be used with code that is added - // in a follow up CL. std::unique_ptr<RendererSwapData> swap_data; }; @@ -79,7 +80,7 @@ } if (!process_node) { - LOG(ERROR) << "Couldn't find process node for RPH: " + LOG(ERROR) << "Couldn't find process node for rphid: " << render_process_host_id; return; } @@ -90,12 +91,10 @@ } auto* data = UserspaceSwapMechanismData::GetOrCreate(process_node); - auto& swap_data = data->swap_data; - swap_data->render_process_host_id = render_process_host_id; - - // Finally wrap up the received userfaultfd into a UserfaultFD instance. - swap_data->uffd = UserfaultFD::WrapFD(std::move(uffd)); + // Wrap up the received userfaultfd into a UserfaultFD instance. + std::unique_ptr<UserfaultFD> userfaultfd = + UserfaultFD::WrapFD(std::move(uffd)); // The SwapFile is always encrypted but the compression layer is optional. SwapFile::Type swap_type = SwapFile::Type::kEncrypted; @@ -104,9 +103,9 @@ static_cast<SwapFile::Type>(swap_type | SwapFile::Type::kCompressed); } - swap_data->swap_file = SwapFile::Create(swap_type); + std::unique_ptr<SwapFile> swap_file = SwapFile::Create(swap_type); - if (!swap_data->swap_file) { + if (!swap_file) { PLOG(ERROR) << "Unable to complete userspace swap initialization failure " "creating swap file"; @@ -116,7 +115,8 @@ return; } - swap_data->setup_complete = true; + data->swap_data = RendererSwapData::Create( + render_process_host_id, std::move(userfaultfd), std::move(swap_file)); } } // namespace @@ -127,16 +127,101 @@ } auto* data = UserspaceSwapMechanismData::Get(process_node); - if (!data) { + if (!data || !data->swap_data) { return false; } + // Now let the implementation decide if swap should actually be allowed. + return data->swap_data->SwapAllowed(); +} + +uint64_t GetSwapDeviceFreeSpaceBytes() { + auto now_ticks = base::TimeTicks::Now(); + if (now_ticks - g_last_swap_device_free_space_check > + kSwapDeviceAvailableSpaceCheckInterval) { + g_last_swap_device_free_space_check = now_ticks; + g_swap_device_free_swap_bytes = SwapFile::GetBackingStoreFreeSpaceKB() + << 10; // convert to bytes. + } + + return g_swap_device_free_swap_bytes; +} + +uint64_t GetProcessNodeSwapFileUsageBytes(const ProcessNode* process_node) { + auto* data = UserspaceSwapMechanismData::Get(process_node); + if (!data || !data->swap_data) { + return 0; + } + + return data->swap_data->SwapDiskspaceUsedBytes(); +} + +uint64_t GetProcessNodeReclaimedBytes(const ProcessNode* process_node) { + auto* data = UserspaceSwapMechanismData::Get(process_node); + if (!data || !data->swap_data) { + return 0; + } + + return data->swap_data->ReclaimedBytes(); +} + +uint64_t GetTotalSwapFileUsageBytes() { + return chromeos::memory::userspace_swap::GetGlobalSwapDiskspaceUsed(); +} + +uint64_t GetTotalReclaimedBytes() { + return chromeos::memory::userspace_swap::GetGlobalMemoryReclaimed(); +} + +void SwapProcessNode(const ProcessNode* process_node) { + base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, + base::BlockingType::WILL_BLOCK); + + auto* data = UserspaceSwapMechanismData::Get(process_node); + if (!data || !data->swap_data) { + return; + } + auto& swap_data = data->swap_data; - if (!swap_data->setup_complete || !swap_data->swap_file || !swap_data->uffd) { - return false; + + // SwapProcessNode always starts by determining exactly how many regions we + // can swap based on current swapfile usage for this renderer and globally. + static const size_t kPageSize = base::GetPageSize(); + static const uint64_t kPagesPerRegion = + UserspaceSwapConfig::Get().number_of_pages_per_region; + static const uint64_t kRegionSize = kPagesPerRegion * kPageSize; + + const auto& config = UserspaceSwapConfig::Get(); + + uint64_t swap_file_disk_space_used_bytes = + swap_data->SwapDiskspaceUsedBytes(); + + // This renderer can only swap up to what's available in the global swap file + // limit or what's available in it's own swap file limit. + int64_t available_swap_bytes = std::min( + config.maximum_swap_disk_space_bytes - + chromeos::memory::userspace_swap::GetGlobalSwapDiskspaceUsed(), + config.renderer_maximum_disk_swap_file_size_bytes - + swap_file_disk_space_used_bytes); + + // We have a configurable limit to the number of regions we will consider per + // iteration and adjust based on how much disk space is actually + // available for us which was calculated before. + // Finally, we know how many regions this renderer is able to swap. + int64_t available_swap_regions = available_swap_bytes / kRegionSize; + int64_t total_regions_swapable = + std::min(static_cast<int64_t>(config.renderer_region_limit_per_swap), + available_swap_regions); + + if (total_regions_swapable <= 0) { + // We don't have enough space available to swap a single region. + return; } - return true; + // Now we know how many regions this renderer can theoretically swap after + // enforcing all configurable limits. + chromeos::memory::userspace_swap::SwapRegions(swap_data.get(), + total_regions_swapable); } UserspaceSwapInitializationImpl::UserspaceSwapInitializationImpl(
diff --git a/chrome/browser/performance_manager/mechanisms/userspace_swap_chromeos.h b/chrome/browser/performance_manager/mechanisms/userspace_swap_chromeos.h index f148006b..92601f5 100644 --- a/chrome/browser/performance_manager/mechanisms/userspace_swap_chromeos.h +++ b/chrome/browser/performance_manager/mechanisms/userspace_swap_chromeos.h
@@ -19,12 +19,35 @@ namespace mechanism { namespace userspace_swap { +// NOTE: All of the following methods MUST be called from the PM sequence. + // The policy must query the mechanism IsEligibleToSwap because the mechanism // knows things that the policy doesn't related to the swap file and // userfaultfd, this method will return false if an unexpected event that // prevents swapping occurred. bool IsEligibleToSwap(const ProcessNode* process_node); +// Swap a |process_node|. +void SwapProcessNode(const ProcessNode* process_node); + +// Returns the number of bytes available on the device which is backing the swap +// files. +uint64_t GetSwapDeviceFreeSpaceBytes(); + +// Returns the number of bytes currently in use by the swap file for +// |process_node|. +uint64_t GetProcessNodeSwapFileUsageBytes(const ProcessNode* process_node); + +// Returns the number of bytes that this process node has had reclaimed. Reclaim +// refers to physical memory which were swapped. +uint64_t GetProcessNodeReclaimedBytes(const ProcessNode* process_node); + +// Returns the total number of bytes currently in use across all swap files. +uint64_t GetTotalSwapFileUsageBytes(); + +// Returns the total number of bytes which have been reclaimed. +uint64_t GetTotalReclaimedBytes(); + class UserspaceSwapInitializationImpl : public ::userspace_swap::mojom::UserspaceSwapInitialization { public:
diff --git a/chrome/browser/performance_manager/policies/userspace_swap_policy_chromeos.cc b/chrome/browser/performance_manager/policies/userspace_swap_policy_chromeos.cc index 5a09f01..c74fd21 100644 --- a/chrome/browser/performance_manager/policies/userspace_swap_policy_chromeos.cc +++ b/chrome/browser/performance_manager/policies/userspace_swap_policy_chromeos.cc
@@ -40,12 +40,7 @@ base::TimeTicks last_swap_; }; -#ifndef NDEBUG constexpr base::TimeDelta kMetricsInterval = base::TimeDelta::FromSeconds(30); -#endif - -constexpr base::TimeDelta kSwapDeviceAvailableSpaceCheckInterval = - base::TimeDelta::FromSeconds(30); } // namespace @@ -56,14 +51,13 @@ if (base::SysInfo::IsRunningOnChromeOS()) { DCHECK(UserspaceSwapPolicy::UserspaceSwapSupportedAndEnabled()); } -#ifndef NDEBUG - if (!metrics_timer_->IsRunning()) { + + if (VLOG_IS_ON(1) && !metrics_timer_->IsRunning()) { metrics_timer_->Start( FROM_HERE, kMetricsInterval, base::BindRepeating(&UserspaceSwapPolicy::PrintAllSwapMetrics, weak_factory_.GetWeakPtr())); } -#endif // ifndef NDEBUG } UserspaceSwapPolicy::UserspaceSwapPolicy() @@ -100,7 +94,8 @@ // We don't provide a page node because the visibility requirements don't // matter on freeze. if (IsEligibleToSwap(process_node, nullptr)) { - VLOG(1) << "pid: " << process_node->GetProcessId() << " swap on freeze"; + VLOG(1) << "rphid: " << process_node->GetRenderProcessHostId() + << " pid: " << process_node->GetProcessId() << " swap on freeze"; UserspaceSwapPolicyData::EnsureForProcess(process_node)->last_swap_ = base::TimeTicks::Now(); SwapProcessNode(process_node); @@ -173,7 +168,8 @@ const ProcessNode* process_node = main_frame_node->GetProcessNode(); if (IsEligibleToSwap(process_node, page_node)) { - VLOG(1) << "pid: " << process_node->GetProcessId() + VLOG(1) << "rphid: " << process_node->GetRenderProcessHostId() + << " pid: " << process_node->GetProcessId() << " trigger swap for frame " << main_frame_node->GetURL(); UserspaceSwapPolicyData::EnsureForProcess(process_node)->last_swap_ = base::TimeTicks::Now(); @@ -222,32 +218,29 @@ } void UserspaceSwapPolicy::SwapProcessNode(const ProcessNode* process_node) { - // TODO(bgeffon): This will trigger the swap in the userspace swap mechanism - // once it has landed. + performance_manager::mechanism::userspace_swap::SwapProcessNode(process_node); } uint64_t UserspaceSwapPolicy::GetProcessNodeSwapFileUsageBytes( const ProcessNode* process_node) { - // TODO(bgeffon): Once the mechanism is landed we will query it for the swap - // file usage for a specific renderer. - return 0; + return performance_manager::mechanism::userspace_swap:: + GetProcessNodeSwapFileUsageBytes(process_node); } uint64_t UserspaceSwapPolicy::GetProcessNodeReclaimedBytes( const ProcessNode* process_node) { - // TODO(bgeffon): Once the mechanism is landed we will query it for the swap - // file usage for a specific renderer. - return 0; + return performance_manager::mechanism::userspace_swap:: + GetProcessNodeReclaimedBytes(process_node); } uint64_t UserspaceSwapPolicy::GetTotalSwapFileUsageBytes() { - // TODO(bgeffon): Once the mechanism is landed we will query it for the swap - // file usage for a specific renderer. - return 0; + return performance_manager::mechanism::userspace_swap:: + GetTotalSwapFileUsageBytes(); } uint64_t UserspaceSwapPolicy::GetSwapDeviceFreeSpaceBytes() { - return SwapFile::GetBackingStoreFreeSpaceKB() << 10; // Convert to bytes. + return performance_manager::mechanism::userspace_swap:: + GetSwapDeviceFreeSpaceBytes(); } bool UserspaceSwapPolicy::IsPageNodeLoading(const PageNode* page_node) { @@ -314,16 +307,8 @@ // available disk space for 30 seconds. But we only check if it's been // configured to enforce a swap device minimum. if (config_.minimum_swap_disk_space_available > 0) { - auto time_since_last_device_space_check = - now_ticks - last_device_space_check_; - if (time_since_last_device_space_check > - kSwapDeviceAvailableSpaceCheckInterval) { - last_device_space_check_ = now_ticks; - backing_store_available_bytes_ = GetSwapDeviceFreeSpaceBytes(); - } - // Check if we can't swap because the device is running low on space. - if (backing_store_available_bytes_ < + if (GetSwapDeviceFreeSpaceBytes() < config_.minimum_swap_disk_space_available) { return false; }
diff --git a/chrome/browser/policy/configuration_policy_handler_list_factory.cc b/chrome/browser/policy/configuration_policy_handler_list_factory.cc index bb231bf..2d29e91 100644 --- a/chrome/browser/policy/configuration_policy_handler_list_factory.cc +++ b/chrome/browser/policy/configuration_policy_handler_list_factory.cc
@@ -619,6 +619,9 @@ { key::kDNSInterceptionChecksEnabled, prefs::kDNSInterceptionChecksEnabled, base::Value::Type::BOOLEAN }, + { key::kIntranetRedirectBehavior, + prefs::kIntranetRedirectBehavior, + base::Value::Type::INTEGER }, { key::kAdvancedProtectionAllowed, prefs::kAdvancedProtectionAllowed, base::Value::Type::BOOLEAN },
diff --git a/chrome/browser/resources/chromeos/accessibility/strings/accessibility_strings_fa.xtb b/chrome/browser/resources/chromeos/accessibility/strings/accessibility_strings_fa.xtb index 425ffe2b..7c24cbf 100644 --- a/chrome/browser/resources/chromeos/accessibility/strings/accessibility_strings_fa.xtb +++ b/chrome/browser/resources/chromeos/accessibility/strings/accessibility_strings_fa.xtb
@@ -267,7 +267,7 @@ <translation id="3040901448410802366">نشانگر پیشرفت</translation> <translation id="3046838483509668188">گزینههای ChromeVox</translation> <translation id="3060756054951570867">منوی <ph name="TITLE" /> باز شد</translation> -<translation id="3060880924447482063">برای جابهجایی بین موارد، تند به راست یا چپ بکشید</translation> +<translation id="3060880924447482063">برای جابهجایی بین موارد، تند بهراست یا چپ بکشید</translation> <translation id="3070245424257836917">تند کشیدن سه انگشت به بالا</translation> <translation id="3078345202707391975">عنوان بعدی سطح ۲</translation> <translation id="3078740164268491126">جدول</translation> @@ -282,7 +282,7 @@ <translation id="3103579948980282461">ارغوانی</translation> <translation id="3104705064753753826">alrt dlg</translation> <translation id="3109724472072898302">جمع شده</translation> -<translation id="311015743332597320">با چهار انگشت تند به راست بکشید</translation> +<translation id="311015743332597320">با چهار انگشت تند بهراست بکشید</translation> <translation id="3112457281078985179">برای روشن یا خاموش کردن ChromeVox، از Control+Alt+Z استفاده کنید.</translation> <translation id="3131002934070407451">خواندن شمارهها بهصورت:</translation> <translation id="3134461040845705080">rdonly</translation> @@ -416,7 +416,7 @@ <translation id="4161104397932142764">{COUNT,plural, =1{ثانیه}one{ثانیه}other{ثانیه}}</translation> <translation id="4161663686871496107">بازخورد گفتاری ChromeVox آماده است</translation> <translation id="4176463684765177261">غیرفعال شد</translation> -<translation id="4187322598335821254">برای جابهجایی بین خطوط، تند به بالا یا پایین بکشید</translation> +<translation id="4187322598335821254">برای جابهجایی بین خطوط، تند بهبالا یا پایین بکشید</translation> <translation id="4188530942454211480">جمله قبلی</translation> <translation id="4191918948604314587">دکمه</translation> <translation id="419265409837491189">رفتن به ستون قبلی</translation> @@ -910,7 +910,7 @@ <translation id="812886159861361726">بارگیری <ph name="FILE_NAME" /> متوقف شد</translation> <translation id="8129445297241948503">سلولی در بالا وجود ندارد</translation> <translation id="8138880386467279117">لمس</translation> -<translation id="8173092779156526980">با چهار انگشت تند به چپ بکشید</translation> +<translation id="8173092779156526980">با چهار انگشت تند بهچپ بکشید</translation> <translation id="817440585505441544">{COUNT,plural, =1{زیرخط}one{# زیرخط}other{# زیرخط}}</translation> <translation id="8179976553408161302">ورود</translation> <translation id="8184828902145951186">ردیف</translation>
diff --git a/chrome/browser/resources/chromeos/accessibility/strings/accessibility_strings_kk.xtb b/chrome/browser/resources/chromeos/accessibility/strings/accessibility_strings_kk.xtb index 52ea15e..1eb1995 100644 --- a/chrome/browser/resources/chromeos/accessibility/strings/accessibility_strings_kk.xtb +++ b/chrome/browser/resources/chromeos/accessibility/strings/accessibility_strings_kk.xtb
@@ -582,7 +582,7 @@ <translation id="5455441614648621694">Қосымша</translation> <translation id="5462510922370980473">Беттер тізімі</translation> <translation id="549602578321198708">Сөз</translation> -<translation id="5513242761114685513">Мәнмәтіндік мәзір</translation> +<translation id="5513242761114685513">Контекстік мәзір</translation> <translation id="551361796444814639">Орташа көк</translation> <translation id="552195134157544755">Радио түйме</translation> <translation id="5534303576632885660">hdr</translation> @@ -643,7 +643,7 @@ <translation id="5955304353782037793">қолданба</translation> <translation id="5956928062748260866">Диалог</translation> <translation id="5963413905009737549">Бөлім</translation> -<translation id="5968607524793740041">Мәнмәтіндік мәзірді көрсету</translation> +<translation id="5968607524793740041">Контекстік мәзірді көрсету</translation> <translation id="597121107011153418">{COUNT,plural, =1{# элементі бар}other{# элементі бар}}</translation> <translation id="5981446804259161541">Ашық көк жасыл</translation> <translation id="5983179082906765664">Навигация грануляциясын арттыру</translation>
diff --git a/chrome/browser/resources/feedback/html/default.html b/chrome/browser/resources/feedback/html/default.html index 4997e95..e25e8a7 100644 --- a/chrome/browser/resources/feedback/html/default.html +++ b/chrome/browser/resources/feedback/html/default.html
@@ -30,7 +30,8 @@ </span> </div> <div id="content-pane" class="content"> - <textarea id="description-text" aria-labelledby="page-title"></textarea> + <p id="free-form-text" i18n-content="freeFormText"></p> + <textarea id="description-text" aria-labelledby="free-form-text"></textarea> <div> <p id="additional-info-label" i18n-content="additionalInfo"><p> </div>
diff --git a/chrome/browser/resources/feedback/js/feedback.js b/chrome/browser/resources/feedback/js/feedback.js index 29bf15b..4479017 100644 --- a/chrome/browser/resources/feedback/js/feedback.js +++ b/chrome/browser/resources/feedback/js/feedback.js
@@ -302,11 +302,11 @@ width = FEEDBACK_MIN_WIDTH; } - // We get the height by adding the titlebar height and the content height + - // margins. We can't get the margins for the content-pane here by using - // style.margin - the variable seems to not exist. - let height = $('title-bar').scrollHeight + $('content-pane').scrollHeight + - CONTENT_MARGIN_HEIGHT; + // Note: If the display is shorter than this (e.g. if the user has it set to + // largest display size), the chrome app api(?) will cap the height of the + // window at the height of the screen and add a scroll bar. If we switch away + // from chrome apps, make sure that this behavior is the same. + let height = document.body.scrollHeight; let minHeight = FEEDBACK_MIN_HEIGHT; if (feedbackInfo.flow == chrome.feedbackPrivate.FeedbackFlow.LOGIN) {
diff --git a/chrome/browser/resources/kaleidoscope/toolbar.html b/chrome/browser/resources/kaleidoscope/toolbar.html index e549f44e..39d800e 100644 --- a/chrome/browser/resources/kaleidoscope/toolbar.html +++ b/chrome/browser/resources/kaleidoscope/toolbar.html
@@ -8,4 +8,10 @@ z-index: 99; } </style> -<cr-toolbar id="toolbar" show-menu on-search-changed="onSearchChanged_" menu-label="[[menuLabel]]" page-name="[[pageName]]"></cr-toolbar> +<cr-toolbar id="toolbar" + show-menu + on-search-changed="onSearchChanged_" + menu-label="[[menuLabel]]" + page-name="[[pageName]]"> + <slot></slot> +</cr-toolbar>
diff --git a/chrome/browser/resources/nearby_share/nearby_share_dialog_resources.grd b/chrome/browser/resources/nearby_share/nearby_share_dialog_resources.grd index a0c59fe..e3f7357 100644 --- a/chrome/browser/resources/nearby_share/nearby_share_dialog_resources.grd +++ b/chrome/browser/resources/nearby_share/nearby_share_dialog_resources.grd
@@ -20,7 +20,7 @@ file="${root_gen_dir}/chrome/browser/ui/webui/nearby_share/nearby_share.mojom-lite.js" use_base_dir="false" type="BINDATA"/> <include name="IDR_NEARBY_SHARE_TARGET_TYPES_MOJO_JS" - file="${root_gen_dir}/chrome/services/sharing/public/mojom/nearby_share_target_types.mojom-lite.js" + file="${root_gen_dir}/chromeos/services/nearby/public/mojom/nearby_share_target_types.mojom-lite.js" use_base_dir="false" type="BINDATA"/> <include name="IDR_NEARBY_SHARE_SETTINGS_MOJOM_LITE_JS" file="${root_gen_dir}/chrome/browser/ui/webui/nearby_share/public/mojom/nearby_share_settings.mojom-lite.js"
diff --git a/chrome/browser/resources/optimize_webui.gni b/chrome/browser/resources/optimize_webui.gni index 4581e9bf..9427d71 100644 --- a/chrome/browser/resources/optimize_webui.gni +++ b/chrome/browser/resources/optimize_webui.gni
@@ -86,6 +86,14 @@ inputs += [ "//chrome/browser/resources/tools/rollup_plugin.js" ] args += [ "--js_module_in_files" ] + invoker.js_module_in_files } + + if (defined(invoker.out_manifest)) { + args += [ + "--out-manifest", + rebase_path(invoker.out_manifest, root_build_dir), + ] + outputs += [ invoker.out_manifest ] + } } }
diff --git a/chrome/browser/resources/optimize_webui.py b/chrome/browser/resources/optimize_webui.py index 4242ee7d..3f370d4 100755 --- a/chrome/browser/resources/optimize_webui.py +++ b/chrome/browser/resources/optimize_webui.py
@@ -380,6 +380,7 @@ parser.add_argument('--js_out_files', nargs='*', required=True) parser.add_argument('--out_folder', required=True) parser.add_argument('--js_module_in_files', nargs='*') + parser.add_argument('--out-manifest') parser.add_argument('--gen_dir_relpath', default='gen', help='Path of the ' 'gen directory relative to the out/. If running in the default ' 'toolchain, the path is gen, otherwise $toolchain_name/gen') @@ -411,6 +412,16 @@ 'polymer-bundler could not find files for the following URLs:\n' + '\n'.join(manifest['_missing'])) + + # Output a manifest file that will be used to auto-generate a grd file later. + if args.out_manifest: + manifest_data = {} + manifest_data['base_dir'] = '%s' % args.out_folder + manifest_data['files'] = manifest.keys() + manifest_file = open( + os.path.normpath(os.path.join(_CWD, args.out_manifest)), 'wb') + json.dump(manifest_data, manifest_file) + _update_dep_file(args.input, args, manifest)
diff --git a/chrome/browser/resources/optimize_webui_test.py b/chrome/browser/resources/optimize_webui_test.py index 6871e708..880b5a00 100755 --- a/chrome/browser/resources/optimize_webui_test.py +++ b/chrome/browser/resources/optimize_webui_test.py
@@ -3,6 +3,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import json import optimize_webui import os import shutil @@ -10,14 +11,15 @@ import unittest +_CWD = os.getcwd() _HERE_DIR = os.path.dirname(__file__) class OptimizeWebUiTest(unittest.TestCase): def setUp(self): - self._out_folder = None self._tmp_dirs = [] self._tmp_src_dir = None + self._out_folder = self._create_tmp_dir() def tearDown(self): for tmp_dir in self._tmp_dirs: @@ -45,8 +47,6 @@ return open(os.path.join(self._out_folder, file_name), 'r').read() def _run_optimize(self, input_args): - assert not self._out_folder - self._out_folder = self._create_tmp_dir() # TODO(dbeam): make it possible to _run_optimize twice? Is that useful? args = input_args + [ '--depfile', os.path.join(self._out_folder, 'depfile.d'), @@ -209,6 +209,7 @@ args = [ '--js_module_in_files', 'ui.js', 'lazy.js', '--js_out_files', 'ui.rollup.js', 'lazy.rollup.js', 'shared.rollup.js', + '--out-manifest', os.path.join(self._out_folder, 'out_manifest.json'), ] self._run_optimize(args) @@ -234,5 +235,15 @@ depfile_d = self._read_out_file('depfile.d') self.assertIn('lazy_element.js', depfile_d) + manifest = json.loads(self._read_out_file('out_manifest.json')) + self.assertEquals(3, len(manifest['files'])) + self.assertTrue('lazy.rollup.js' in manifest['files']) + self.assertTrue('ui.rollup.js' in manifest['files']) + self.assertTrue('shared.rollup.js' in manifest['files']) + + self.assertEquals( + os.path.relpath(self._out_folder, _CWD).replace('\\', '/'), + os.path.relpath(manifest['base_dir'], _CWD).replace('\\', '/')) + if __name__ == '__main__': unittest.main()
diff --git a/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar-new.html b/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar-new.html index 055a631..4d77777 100644 --- a/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar-new.html +++ b/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar-new.html
@@ -190,8 +190,8 @@ </cr-icon-button> <input type="text" value="100%" aria-label="$i18n{zoomTextInputAriaLabel}" - on-input="onZoomInput_" on-pointerup="onZoomInputPointerup_" - on-blur="onZoomInputBlur_"> + on-change="onZoomChange_" on-pointerup="onZoomInputPointerup_" + on-blur="onZoomChange_"> </input> <cr-icon-button iron-icon="pdf:add" title="$i18n{tooltipZoomIn}" aria-label="$i18n{tooltipZoomIn}" on-click="onZoomInClick_">
diff --git a/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar-new.js b/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar-new.js index 5acfccd..30dc170 100644 --- a/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar-new.js +++ b/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar-new.js
@@ -76,6 +76,8 @@ type: Number, observer: 'viewportZoomChanged_', }, + /** @type {!{min: number, max: number}} */ + zoomBounds: Object, sidenavCollapsed: Boolean, twoUpViewEnabled: Boolean, @@ -127,9 +129,6 @@ /** @private {boolean} */ this.moreMenuOpen_ = false; - - /** @private {?number} */ - this.zoomTimeout_ = null; } /** @@ -293,20 +292,25 @@ } /** @private */ - onZoomInput_() { - if (this.zoomTimeout_) { - clearTimeout(this.zoomTimeout_); + onZoomChange_() { + const input = this.getZoomInput_(); + let value = Number.parseInt(input.value, 10); + value = Math.max(Math.min(value, this.zoomBounds.max), this.zoomBounds.min); + if (this.sendZoomChanged_(value)) { + return; } - this.zoomTimeout_ = setTimeout(() => this.sendZoomChanged_(), 250); + + const zoom = Math.round(this.viewportZoom * 100); + const zoomString = `${zoom}%`; + input.value = zoomString; } /** + * @param {number} value The new zoom value * @return {boolean} Whether the zoom-changed event was sent. * @private */ - sendZoomChanged_() { - this.zoomTimeout_ = null; - const value = Number.parseInt(this.getZoomInput_().value, 10); + sendZoomChanged_(value) { if (Number.isNaN(value)) { return false; } @@ -320,21 +324,6 @@ return true; } - /** @private */ - onZoomInputBlur_() { - if (this.zoomTimeout_) { - clearTimeout(this.zoomTimeout_); - } - - if (this.sendZoomChanged_()) { - return; - } - - const zoom = Math.round(this.viewportZoom * 100); - const zoomString = `${zoom}%`; - this.getZoomInput_().value = zoomString; - } - /** * @param {!Event} e * @private
diff --git a/chrome/browser/resources/pdf/pdf_viewer.html b/chrome/browser/resources/pdf/pdf_viewer.html index bc4cdd4a..775c73e 100644 --- a/chrome/browser/resources/pdf/pdf_viewer.html +++ b/chrome/browser/resources/pdf/pdf_viewer.html
@@ -161,7 +161,7 @@ is-form-field-focused="[[isFormFieldFocused_]]" sidenav-collapsed="[[sidenavCollapsed_]]" two-up-view-enabled="[[twoUpViewEnabled_]]" - viewport-zoom="[[viewportZoom_]]" + viewport-zoom="[[viewportZoom_]]" zoom-bounds="[[zoomBounds_]]" <if expr="chromeos"> annotation-available="[[annotationAvailable_]]" ink-controller="[[inkController_]]"
diff --git a/chrome/browser/resources/pdf/pdf_viewer.js b/chrome/browser/resources/pdf/pdf_viewer.js index d7037e4..1edf4b6 100644 --- a/chrome/browser/resources/pdf/pdf_viewer.js +++ b/chrome/browser/resources/pdf/pdf_viewer.js
@@ -181,6 +181,7 @@ pdfAnnotationsEnabled_: Boolean, printingEnabled_: Boolean, viewportZoom_: Number, + zoomBounds_: Object, }; } @@ -244,6 +245,9 @@ /** @private {number} */ this.viewportZoom_ = 1; + /** @private {!{ min: number, max: number }} */ + this.zoomBounds_ = {min: 0, max: 0}; + // Non-Polymer properties /** @type {number} */ @@ -763,6 +767,10 @@ loadTimeData.getBoolean('pdfAnnotationsEnabled'); this.pdfFormSaveEnabled_ = loadTimeData.getBoolean('pdfFormSaveEnabled'); this.printingEnabled_ = loadTimeData.getBoolean('printingEnabled'); + const presetZoomFactors = this.viewport.presetZoomFactors; + this.zoomBounds_.min = Math.round(presetZoomFactors[0] * 100); + this.zoomBounds_.max = + Math.round(presetZoomFactors[presetZoomFactors.length - 1] * 100); } /** @override */
diff --git a/chrome/browser/resources/pdf/viewport.js b/chrome/browser/resources/pdf/viewport.js index 6bc964a..5d965d2 100644 --- a/chrome/browser/resources/pdf/viewport.js +++ b/chrome/browser/resources/pdf/viewport.js
@@ -501,6 +501,11 @@ return this.zoomManager_.applyBrowserZoom(this.internalZoom_); } + /** @return {!Array<number>} The preset zoom factors. */ + get presetZoomFactors() { + return this.presetZoomFactors_; + } + /** @param {!ZoomManager} manager */ setZoomManager(manager) { this.resetTracker();
diff --git a/chrome/browser/resources/sandbox_internals/sandbox_internals_win.js b/chrome/browser/resources/sandbox_internals/sandbox_internals_win.js index d810731e..89573e1 100644 --- a/chrome/browser/resources/sandbox_internals/sandbox_internals_win.js +++ b/chrome/browser/resources/sandbox_internals/sandbox_internals_win.js
@@ -232,7 +232,22 @@ new PC2Field('SPECULATIVE_STORE_BYPASS_DISABLE_RESERVED', 0x3, 0x03, 24), new PC2Field('CET_USER_SHADOW_STACKS', 0x1, 0x03, 28), new PC2Field('CET_USER_SHADOW_STACKS_ALWAYS_OFF', 0x2, 0x03, 28), - new PC2Field('CET_USER_SHADOW_STACKS_RESERVED', 0x3, 0x03, 28) + new PC2Field('CET_USER_SHADOW_STACKS_STRICT_MODE', 0x3, 0x03, 28), + new PC2Field('USER_CET_SET_CONTEXT_IP_VALIDATION', 0x1, 0x03, 32), + new PC2Field( + 'USER_CET_SET_CONTEXT_IP_VALIDATION_ALWAYS_OFF', 0x2, 0x03, 32), + new PC2Field( + 'USER_CET_SET_CONTEXT_IP_VALIDATION_RELAXED_MODE', 0x3, 0x03, 32), + new PC2Field('BLOCK_NON_CET_BINARIES', 0x1, 0x03, 36), + new PC2Field('BLOCK_NON_CET_BINARIES_ALWAYS_OFF', 0x2, 0x03, 36), + new PC2Field('BLOCK_NON_CET_BINARIES_NON_EHCONT', 0x3, 0x03, 36), + new PC2Field('XTENDED_CONTROL_FLOW_GUARD', 0x1, 0x03, 40), + new PC2Field('XTENDED_CONTROL_FLOW_GUARD_ALWAYS_OFF', 0x2, 0x03, 40), + new PC2Field('XTENDED_CONTROL_FLOW_GUARD_RESERVED', 0x3, 0x03, 40), + new PC2Field('CET_DYNAMIC_APIS_OUT_OF_PROC_ONLY', 0x1, 0x03, 48), + new PC2Field( + 'CET_DYNAMIC_APIS_OUT_OF_PROC_ONLY_ALWAYS_OFF', 0x2, 0x03, 48), + new PC2Field('CET_DYNAMIC_APIS_OUT_OF_PROC_ONLY_RESERVED', 0x3, 0x03, 48), ]; }
diff --git a/chrome/browser/resources/settings/chromeos/bluetooth_page/BUILD.gn b/chrome/browser/resources/settings/chromeos/bluetooth_page/BUILD.gn index b89d99a..6688fdca 100644 --- a/chrome/browser/resources/settings/chromeos/bluetooth_page/BUILD.gn +++ b/chrome/browser/resources/settings/chromeos/bluetooth_page/BUILD.gn
@@ -17,6 +17,7 @@ js_library("bluetooth_page") { deps = [ "..:deep_linking_behavior", + "..:metrics_recorder", "..:os_route", "../..:router", "../../prefs:prefs_behavior", @@ -94,6 +95,7 @@ deps = [ ":bluetooth_subpage.m", "..:deep_linking_behavior.m", + "..:metrics_recorder.m", "..:os_route.m", "../..:router.m", "../../prefs:prefs_behavior.m",
diff --git a/chrome/browser/resources/settings/chromeos/bluetooth_page/bluetooth_page.html b/chrome/browser/resources/settings/chromeos/bluetooth_page/bluetooth_page.html index f5d1700..5fc7b3c 100644 --- a/chrome/browser/resources/settings/chromeos/bluetooth_page/bluetooth_page.html +++ b/chrome/browser/resources/settings/chromeos/bluetooth_page/bluetooth_page.html
@@ -10,6 +10,7 @@ <link rel="import" href="../../prefs/prefs.html"> <link rel="import" href="../../prefs/prefs_behavior.html"> <link rel="import" href="../deep_linking_behavior.html"> +<link rel="import" href="../metrics_recorder.html"> <link rel="import" href="../os_route.html"> <link rel="import" href="../../router.html"> <link rel="import" href="../../settings_page/settings_animated_pages.html"> @@ -55,7 +56,8 @@ disabled$="[[!isToggleEnabled_( adapterState_, stateChangeInProgress_)]]" aria-label="$i18n{bluetoothToggleA11yLabel}" - deep-link-focus-id$="[[Setting.kBluetoothOnOff]]"> + deep-link-focus-id$="[[Setting.kBluetoothOnOff]]" + on-change="onBluetoothToggledByUser_"> </cr-toggle> </div> </template>
diff --git a/chrome/browser/resources/settings/chromeos/bluetooth_page/bluetooth_page.js b/chrome/browser/resources/settings/chromeos/bluetooth_page/bluetooth_page.js index babda63..c04234c 100644 --- a/chrome/browser/resources/settings/chromeos/bluetooth_page/bluetooth_page.js +++ b/chrome/browser/resources/settings/chromeos/bluetooth_page/bluetooth_page.js
@@ -238,6 +238,18 @@ } }, + /** + * Listens for toggle change events (rather than state changes) to handle + * just user-triggered changes to the bluetoothToggleState_. + * @private + */ + onBluetoothToggledByUser_() { + // Record that the user manually enabled/disabled Bluetooth. + settings.recordSettingChange( + chromeos.settings.mojom.Setting.kBluetoothOnOff, + {boolValue: this.bluetoothToggleState_}); + }, + /** @private */ onTap_() { if (!this.isToggleEnabled_()) {
diff --git a/chrome/browser/resources/settings/chromeos/device_page/power.html b/chrome/browser/resources/settings/chromeos/device_page/power.html index 38caedb..53919601 100644 --- a/chrome/browser/resources/settings/chromeos/device_page/power.html +++ b/chrome/browser/resources/settings/chromeos/device_page/power.html
@@ -26,13 +26,14 @@ </style> <div id="powerSourceRow" class="cr-row first" hidden$="[[!batteryStatus_.present]]"> - <div class="flex cr-padded-text" id="powerSourceLabelDiv"> - <div>[[powerSourceLabel_]]</div> - <div class="secondary">[[batteryStatus_.statusText]]</div> + <div class="flex cr-padded-text" aria-hidden="true"> + <div id="powerSourceLabel">[[powerSourceLabel_]]</div> + <div id="batteryStatus" class="secondary">[[batteryStatus_.statusText]]</div> </div> <select id="powerSource" class="md-select" hidden$="[[!showPowerSourceDropdown_]]" - aria-labelledby="powerSourceLabelDiv" + aria-labelledby="powerSourceLabel" + aria-describedby="batteryStatus" on-change="onPowerSourceChange_" deep-link-focus-id$="[[Setting.kPowerSource]]"> <option value="" selected="[[isEqual_('', selectedPowerSourceId_)]]"> @@ -45,7 +46,9 @@ </option> </template> </select> - <div hidden$="[[showPowerSourceDropdown_]]"> + <div hidden$="[[showPowerSourceDropdown_]]" + aria-labelledby="powerSourceLabel" + aria-describedby="batteryStatus"> [[powerSourceName_]] </div> </div>
diff --git a/chrome/browser/resources/settings/chromeos/metrics_recorder.html b/chrome/browser/resources/settings/chromeos/metrics_recorder.html index b3b375f..691ab6c 100644 --- a/chrome/browser/resources/settings/chromeos/metrics_recorder.html +++ b/chrome/browser/resources/settings/chromeos/metrics_recorder.html
@@ -1,5 +1,6 @@ <link rel="import" href="chrome://resources/html/cr.html"> <link rel="import" href="chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.html"> +<script src="chrome://os-settings/constants/setting.mojom-lite.js"></script> <script src="chrome://os-settings/search/user_action_recorder.mojom-lite.js"></script> <script src="metrics_recorder.js"></script>
diff --git a/chrome/browser/resources/settings/chromeos/metrics_recorder.js b/chrome/browser/resources/settings/chromeos/metrics_recorder.js index c077a40..07a8969 100644 --- a/chrome/browser/resources/settings/chromeos/metrics_recorder.js +++ b/chrome/browser/resources/settings/chromeos/metrics_recorder.js
@@ -57,8 +57,22 @@ getRecorder().recordSearch(); } - /* #export */ function recordSettingChange() { - getRecorder().recordSettingChange(); + /** + * All new code should pass a value for |opt_setting| and, if applicable, + * |opt_value|. The zero-parameter version of this function is reserved for + * legacy code which has not yet been converted. + * TODO(https://crbug.com/1133553): make |opt_setting| non-optional when + * migration is complete. + * @param {!chromeos.settings.mojom.Setting=} opt_setting + * @param {!chromeos.settings.mojom.SettingChangeValue=} opt_value + */ + /* #export */ function recordSettingChange(opt_setting, opt_value) { + if (opt_setting === undefined) { + getRecorder().recordSettingChange(); + } else { + getRecorder().recordSettingChangeWithDetails( + opt_setting, opt_value || null); + } } // #cr_define_end
diff --git a/chrome/browser/resources/settings/chromeos/os_search_page/os_search_page.html b/chrome/browser/resources/settings/chromeos/os_search_page/os_search_page.html index 403484b..e2be45c 100644 --- a/chrome/browser/resources/settings/chromeos/os_search_page/os_search_page.html +++ b/chrome/browser/resources/settings/chromeos/os_search_page/os_search_page.html
@@ -68,7 +68,8 @@ </cr-policy-pref-indicator> </template> <select class="md-select" on-change="onChange_" - aria-labelledby="searchExplanation" + aria-label="$i18n{osSearchEngineLabel} + $i18n{osSearchEngineTooltip}" disabled$="[[isDefaultSearchEngineEnforced_( prefs.default_search_provider_data.template_url_data)]]" deep-link-focus-id$="[[Setting.kPreferredSearchEngine]]">
diff --git a/chrome/browser/resources/settings/downloads_page/downloads_page.html b/chrome/browser/resources/settings/downloads_page/downloads_page.html index b455d0a..275057f6 100644 --- a/chrome/browser/resources/settings/downloads_page/downloads_page.html +++ b/chrome/browser/resources/settings/downloads_page/downloads_page.html
@@ -5,8 +5,8 @@ </style> <div class="cr-row first"> <div class="flex cr-padded-text"> - <div>$i18n{downloadLocation}</div> - <div class="secondary" id="defaultDownloadPath"> + <div id="locationLabel" aria-hidden="true">$i18n{downloadLocation}</div> + <div class="secondary" id="defaultDownloadPath" aria-hidden="true"> <if expr="not chromeos"> [[prefs.download.default_directory.value]] </if> @@ -18,6 +18,7 @@ <div class="separator"></div> <controlled-button id="changeDownloadsPath" label="$i18n{changeDownloadLocation}" + aria-labelledby="locationLabel defaultDownloadPath" on-click="selectDownloadLocation_" pref="[[prefs.download.default_directory]]" end-justified>
diff --git a/chrome/browser/share/android/BUILD.gn b/chrome/browser/share/android/BUILD.gn index 236df04..f54e0f0 100644 --- a/chrome/browser/share/android/BUILD.gn +++ b/chrome/browser/share/android/BUILD.gn
@@ -7,6 +7,7 @@ android_resources("java_resources") { sources = [ "java/res/drawable/camera_img.xml", + "java/res/drawable/custom_toast_background.xml", "java/res/drawable/delete_icon.xml", "java/res/drawable/edit_icon.xml", "java/res/drawable/generic_favicon.xml", @@ -17,6 +18,7 @@ "java/res/drawable/save_icon.xml", "java/res/drawable/share_icon.xml", "java/res/drawable/text_icon.xml", + "java/res/layout/custom_toast_layout.xml", "java/res/layout/qrcode_camera_error_layout.xml", "java/res/layout/qrcode_dialog.xml", "java/res/layout/qrcode_open_settings_layout.xml",
diff --git a/chrome/browser/share/android/java/res/drawable/custom_toast_background.xml b/chrome/browser/share/android/java/res/drawable/custom_toast_background.xml new file mode 100644 index 0000000..8339941 --- /dev/null +++ b/chrome/browser/share/android/java/res/drawable/custom_toast_background.xml
@@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright 2016 The Chromium Authors. All rights reserved. + Use of this source code is governed by a BSD-style license that can be + found in the LICENSE file. --> + +<shape + xmlns:android="http://schemas.android.com/apk/res/android"> + <corners android:radius="20dp"/> + <padding + android:left="20dp" + android:right="20dp"/> + <solid android:color="@color/modern_grey_200"/> +</shape> \ No newline at end of file
diff --git a/chrome/browser/share/android/java/res/layout/custom_toast_layout.xml b/chrome/browser/share/android/java/res/layout/custom_toast_layout.xml new file mode 100644 index 0000000..1bdb08a1 --- /dev/null +++ b/chrome/browser/share/android/java/res/layout/custom_toast_layout.xml
@@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright 2016 The Chromium Authors. All rights reserved. + Use of this source code is governed by a BSD-style license that can be + found in the LICENSE file. --> + +<TextView + xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/toast_text" + android:background="@drawable/custom_toast_background" + android:gravity="center" + android:minHeight="44dp" + android:singleLine="true" + android:textAppearance="@style/TextAppearance.TextSmall.Primary"/> \ No newline at end of file
diff --git a/chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/link_to_text/LinkToTextCoordinator.java b/chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/link_to_text/LinkToTextCoordinator.java index 3894c11..81eec08 100644 --- a/chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/link_to_text/LinkToTextCoordinator.java +++ b/chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/link_to_text/LinkToTextCoordinator.java
@@ -6,6 +6,8 @@ import android.content.Context; import android.net.Uri; +import android.view.LayoutInflater; +import android.widget.TextView; import org.chromium.blink.mojom.TextFragmentSelectorProducer; import org.chromium.chrome.R; @@ -60,9 +62,18 @@ params, new ChromeShareExtras.Builder().build(), System.currentTimeMillis()); if (selector.isEmpty()) { + // TODO(gayane): Android toast should be replace by another toast like UI which allows + // custom positioning as |setView| and |setGravity| are deprecated starting API 30. String toastMessage = mContext.getResources().getString(R.string.link_to_text_failure_toast_message); - Toast toast = Toast.makeText(mContext, toastMessage, Toast.LENGTH_SHORT); + LayoutInflater inflater = LayoutInflater.from(mContext); + TextView text = (TextView) inflater.inflate(R.layout.custom_toast_layout, null); + text.setText(toastMessage); + text.announceForAccessibility(toastMessage); + + Toast toast = new Toast(mContext); + toast.setView(text); + toast.setDuration(Toast.LENGTH_SHORT); toast.setGravity(toast.getGravity(), toast.getXOffset(), mContext.getResources().getDimensionPixelSize(R.dimen.y_offset)); toast.show();
diff --git a/chrome/browser/sharing/webrtc/ice_config_fetcher.h b/chrome/browser/sharing/webrtc/ice_config_fetcher.h index 5a8ae12..2c6ce5b 100644 --- a/chrome/browser/sharing/webrtc/ice_config_fetcher.h +++ b/chrome/browser/sharing/webrtc/ice_config_fetcher.h
@@ -13,7 +13,7 @@ #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "base/optional.h" -#include "chrome/services/sharing/public/mojom/webrtc.mojom.h" +#include "chromeos/services/nearby/public/mojom/webrtc.mojom.h" #include "url/gurl.h" namespace network {
diff --git a/chrome/browser/sharing/webrtc/sharing_mojo_service.h b/chrome/browser/sharing/webrtc/sharing_mojo_service.h index 7a76a34..9443146 100644 --- a/chrome/browser/sharing/webrtc/sharing_mojo_service.h +++ b/chrome/browser/sharing/webrtc/sharing_mojo_service.h
@@ -5,7 +5,7 @@ #ifndef CHROME_BROWSER_SHARING_WEBRTC_SHARING_MOJO_SERVICE_H_ #define CHROME_BROWSER_SHARING_WEBRTC_SHARING_MOJO_SERVICE_H_ -#include "chrome/services/sharing/public/mojom/sharing.mojom.h" +#include "chromeos/services/nearby/public/mojom/sharing.mojom.h" #include "mojo/public/cpp/bindings/pending_remote.h" namespace sharing {
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index 80bd202..7fe3b00 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -1256,8 +1256,6 @@ "thumbnails/thumbnail_scheduler.h", "thumbnails/thumbnail_scheduler_impl.cc", "thumbnails/thumbnail_scheduler_impl.h", - "thumbnails/thumbnail_stats_tracker.cc", - "thumbnails/thumbnail_stats_tracker.h", "thumbnails/thumbnail_tab_helper.cc", "thumbnails/thumbnail_tab_helper.h", "toolbar/app_menu_icon_controller.cc", @@ -4699,6 +4697,7 @@ deps += [ "//ash/public/cpp", "//chromeos/dbus", + "//chromeos/ui/base", ] }
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings.grd b/chrome/browser/ui/android/strings/android_chrome_strings.grd index ec9b211f..0d33e3df 100644 --- a/chrome/browser/ui/android/strings/android_chrome_strings.grd +++ b/chrome/browser/ui/android/strings/android_chrome_strings.grd
@@ -1851,6 +1851,9 @@ <message name="IDS_ACCESSIBILITY_TABSTRIP_TAB" desc="Content description for the tab title."> <ph name="TAB_TITLE">%1$s<ex>Welcome to Facebook</ex></ph>, tab </message> + <message name="IDS_ACCESSIBILITY_TABSTRIP_TAB_SELECTED" desc="Content description for the tab title of the currently selected tab."> + <ph name="TAB_TITLE">%1$s<ex>Welcome to Facebook</ex></ph>, tab, selected + </message> <message name="IDS_ACCESSIBILITY_TABSTRIP_BTN_CLOSE_TAB" desc="Content description for the close tab button."> Close <ph name="TAB_TITLE">%1$s<ex>Google</ex></ph> tab </message>
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_ACCESSIBILITY_TABSTRIP_TAB_SELECTED.png.sha1 b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_ACCESSIBILITY_TABSTRIP_TAB_SELECTED.png.sha1 new file mode 100644 index 0000000..20947d1 --- /dev/null +++ b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_ACCESSIBILITY_TABSTRIP_TAB_SELECTED.png.sha1
@@ -0,0 +1 @@ +fa4178c1b665588ddd798cf021812854ef9b2475 \ No newline at end of file
diff --git a/chrome/browser/ui/android/strings/translations/android_chrome_strings_af.xtb b/chrome/browser/ui/android/strings/translations/android_chrome_strings_af.xtb index ad45684e..ce440bc0 100644 --- a/chrome/browser/ui/android/strings/translations/android_chrome_strings_af.xtb +++ b/chrome/browser/ui/android/strings/translations/android_chrome_strings_af.xtb
@@ -16,7 +16,7 @@ <translation id="1105960400813249514">Skermskoot</translation> <translation id="1111673857033749125">Boekmerke wat op jou ander toestelle gestoor is, sal hier verskyn.</translation> <translation id="1113597929977215864">Wys vereenvoudigde aansig</translation> -<translation id="1126809382673880764">Beskerm jou nie teen gevaarlike webwerwe, aflaaie en uitbreidings nie. Jy sal steeds Veiligblaai-beskerming in ander Google-dienste, soos Gmail en Search, kry waar dit beskikbaar is.</translation> +<translation id="1126809382673880764">Beskerm jou nie teen gevaarlike webwerwe, aflaaie en uitbreidings nie. Jy sal steeds Veiligblaai-beskerming kry, indien beskikbaar, in ander Google-dienste, soos Gmail en Search.</translation> <translation id="1129510026454351943">Besonderhede: <ph name="ERROR_DESCRIPTION" /></translation> <translation id="1141800923049248244">{FILE_COUNT,plural, =1{1 aflaai hangende.}other{# aflaaie hangende.}}</translation> <translation id="1142732900304639782">Moenie aanbied om hierdie werwe te vertaal nie</translation> @@ -806,7 +806,7 @@ <translation id="685850645784703949">Ontdek deur Google – af</translation> <translation id="6864459304226931083">Laai prent af</translation> <translation id="6865313869410766144">Vul vormdata outomaties in</translation> -<translation id="6882836635272038266">Standaardbeskerming teen webwerwe, aflaaie en uitbreidings wat bekend is dat hulle gevaarlik is.</translation> +<translation id="6882836635272038266">Standaardbeskerming teen webwerwe, aflaaie en uitbreidings wat bekend is daarvoor dat hulle gevaarlik is.</translation> <translation id="688738109438487280">Voeg bestaande data by <ph name="TO_ACCOUNT" />.</translation> <translation id="6891726759199484455">Ontsluit om jou wagwoord te kopieer</translation> <translation id="6896758677409633944">Kopieer</translation>
diff --git a/chrome/browser/ui/android/strings/translations/android_chrome_strings_ar.xtb b/chrome/browser/ui/android/strings/translations/android_chrome_strings_ar.xtb index ea4fce1b..374dd38 100644 --- a/chrome/browser/ui/android/strings/translations/android_chrome_strings_ar.xtb +++ b/chrome/browser/ui/android/strings/translations/android_chrome_strings_ar.xtb
@@ -529,7 +529,7 @@ <translation id="4943872375798546930">لا نتائج</translation> <translation id="4961107849584082341">ترجمة هذه الصفحة إلى أي لغة</translation> <translation id="4970824347203572753">لا تتوفر هذه الميزة في موقعك الجغرافي</translation> -<translation id="4971735654804503942">يوفّر حماية استباقية سريعة من الإضافات وعمليات التنزيل والمواقع الإلكترونية الضارة. ويُحذّرك من اختراقات كلمة المرور. يتطلّب إرسال بيانات التصفّح إلى Google.</translation> +<translation id="4971735654804503942">يوفّر حماية استباقية وسريعة من الإضافات وعمليات التنزيل والمواقع الإلكترونية الضارة، ويُحذّرك من عمليات اختراق كلمة المرور. يتطلّب إرسال بيانات التصفّح إلى Google.</translation> <translation id="497421865427891073">انتقال للأمام</translation> <translation id="4988210275050210843">جارٍ تنزيل الملف (<ph name="MEGABYTES" />).</translation> <translation id="4988526792673242964">الصفحات</translation>
diff --git a/chrome/browser/ui/android/strings/translations/android_chrome_strings_bg.xtb b/chrome/browser/ui/android/strings/translations/android_chrome_strings_bg.xtb index 48d2f50..9e6041d6 100644 --- a/chrome/browser/ui/android/strings/translations/android_chrome_strings_bg.xtb +++ b/chrome/browser/ui/android/strings/translations/android_chrome_strings_bg.xtb
@@ -169,7 +169,7 @@ <translation id="2234876718134438132">Синхронизиране и услуги на Google</translation> <translation id="2239812875700136898">Контролирайте материалите от бутона „Опции за Discover“</translation> <translation id="2259659629660284697">Експортиране на паролите…</translation> -<translation id="2276696007612801991">Влезте в профила си в Google, за да се проверят паролите ви</translation> +<translation id="2276696007612801991">Влезте в профила си в Google, за да бъдат проверени паролите ви</translation> <translation id="2286841657746966508">Адрес за фактуриране</translation> <translation id="230115972905494466">Няма намерени съвместими устройства</translation> <translation id="2318045970523081853">Докоснете за извършване на обаждане</translation>
diff --git a/chrome/browser/ui/android/strings/translations/android_chrome_strings_hy.xtb b/chrome/browser/ui/android/strings/translations/android_chrome_strings_hy.xtb index fe0f46c..387bce2d 100644 --- a/chrome/browser/ui/android/strings/translations/android_chrome_strings_hy.xtb +++ b/chrome/browser/ui/android/strings/translations/android_chrome_strings_hy.xtb
@@ -71,7 +71,7 @@ <translation id="1430915738399379752">Տպում</translation> <translation id="1450753235335490080">Չհաջողվեց ուղարկել բովանդակությունը (<ph name="CONTENT_TYPE" />)</translation> <translation id="1477626028522505441"><ph name="FILE_NAME" /> ֆայլի ներբեռնումը ձախողվեց՝ սերվերի հետ կապված խնդրի պատճառով:</translation> -<translation id="1506061864768559482">Որոնիչ</translation> +<translation id="1506061864768559482">Որոնողական համակարգ</translation> <translation id="1513352483775369820">Էջանիշներ և վեբ պատմություն</translation> <translation id="1513858653616922153">Ջնջել գաղտնաբառը</translation> <translation id="1521774566618522728">Այսօր ակտիվ է եղել</translation> @@ -571,7 +571,7 @@ <translation id="5324858694974489420">Ծնողական կայանքներ</translation> <translation id="5327248766486351172">Անուն</translation> <translation id="5342314432463739672">Թույլտվությունների հարցումներ</translation> -<translation id="5355191726083956201">Լրացուցիչ պաշտպանությունը միացված է</translation> +<translation id="5355191726083956201">Բարելավված պաշտպանությունը միացված է</translation> <translation id="5357811892247919462">Դուք ներդիր եք ստացել</translation> <translation id="5368958499335451666">{OPEN_TABS,plural, =1{<ph name="OPEN_TABS_ONE" /> բացված ներդիր: Հպեք՝ ներդիրների միջև անցնելու համար։}one{<ph name="OPEN_TABS_MANY" /> բացված ներդիր։ հպեք՝ ներդիրների միջև անցնելու համար։}other{<ph name="OPEN_TABS_MANY" /> բացված ներդիրներ։ հպեք՝ ներդիրների միջև անցնելու համար։}}</translation> <translation id="5403644198645076998">Թույլատրել միայն որոշ կայքեր</translation> @@ -691,7 +691,7 @@ <translation id="6122831415929794347">Անջատե՞լ ապահով դիտարկումը</translation> <translation id="6127379762771434464">Տարրը հեռացվեց</translation> <translation id="6137022273846704445"><ph name="APP_NAME" /> հավելվածի լեզուն</translation> -<translation id="6140709049082532940">Լրացուցիչ պաշտպանություն՝</translation> +<translation id="6140709049082532940">Բարելավված պաշտպանություն՝</translation> <translation id="6140912465461743537">Երկիր/տարածաշրջան</translation> <translation id="614940544461990577">Փորձեք՝</translation> <translation id="6154478581116148741">Այս սարքից ձեր գաղտնաբառերն արտահանելու համար կարգավորումներում միացրեք էկրանի կողպումը։</translation> @@ -810,7 +810,7 @@ <translation id="688738109438487280">Ավելացնել առկա տվյալները <ph name="TO_ACCOUNT" /> հաշվում:</translation> <translation id="6891726759199484455">Գաղտնաբառը պատճենելու համար ապակողպեք էկրանը</translation> <translation id="6896758677409633944">Պատճենել</translation> -<translation id="6900532703269623216">Լրացուցիչ պաշտպանություն</translation> +<translation id="6900532703269623216">Բարելավված պաշտպանություն</translation> <translation id="6903907808598579934">Միացնել համաժամացումը</translation> <translation id="6929699136511445623">Միացնել Android համակարգի համաժամացումը</translation> <translation id="6941901516114974832">Ձեր գործողությունները ինկոգնիտո ռեժիմում <ph name="BEGIN_BOLD1" />կարող են տեսանելի լինել<ph name="END_BOLD1" /> ձեր այցելած կայքերի ադմինիստրատորներին, գործատուին կամ ուսումնական հաստատության ներկայացուցչին, ինչպես նաև ինտերնետ պրովայդերին։
diff --git a/chrome/browser/ui/android/strings/translations/android_chrome_strings_kk.xtb b/chrome/browser/ui/android/strings/translations/android_chrome_strings_kk.xtb index 34006384..be29c1b 100644 --- a/chrome/browser/ui/android/strings/translations/android_chrome_strings_kk.xtb +++ b/chrome/browser/ui/android/strings/translations/android_chrome_strings_kk.xtb
@@ -16,7 +16,7 @@ <translation id="1105960400813249514">Экранды жазып алу</translation> <translation id="1111673857033749125">Басқа құрылғыларда сақталған бетбелгілер осы жерде шығады.</translation> <translation id="1113597929977215864">Қарапайым көріністі көрсету</translation> -<translation id="1126809382673880764">Қауіпті веб-сайттардан, жүктеп алынатын файлдардан және кеңейтімдерден қорғамайды. Gmail және Search сияқты басқа Google қызметтерінде "Қауіпсіз шолу" функциясы қорғайтын болады.</translation> +<translation id="1126809382673880764">Қауіпті веб-сайттардан, жүктеп алынған файлдардан және кеңейтімдерден қорғамайды. Gmail және Search сияқты басқа Google қызметтерінде "Қауіпсіз шолу" функциясы қорғайтын болады.</translation> <translation id="1129510026454351943">Мәліметтер: <ph name="ERROR_DESCRIPTION" /></translation> <translation id="1141800923049248244">{FILE_COUNT,plural, =1{1 файл жүктеп алынбақ.}other{# файл жүктеп алынбақ.}}</translation> <translation id="1142732900304639782">Бұл сайттарды аударуды ұсынбау</translation> @@ -428,7 +428,7 @@ <translation id="4269820728363426813">Сілтеме мекенжайын көшіру</translation> <translation id="4298388696830689168">Байланыстырылған сайттар</translation> <translation id="4303044213806199882">chrome_screenshot_<ph name="CURRENT_TIMESTAMP_MS" /></translation> -<translation id="4307992518367153382">Негіздер</translation> +<translation id="4307992518367153382">Негізгілер</translation> <translation id="4314815835985389558">Синхрондауды басқару</translation> <translation id="4320177379694898372">Интернет байланысы жоқ</translation> <translation id="4321739720395210191">Камера ашылмайды. Құрылғыны қайта қосып, әрекетті қайталаңыз.</translation>
diff --git a/chrome/browser/ui/android/strings/translations/android_chrome_strings_mk.xtb b/chrome/browser/ui/android/strings/translations/android_chrome_strings_mk.xtb index b84f78b..d2c65fc 100644 --- a/chrome/browser/ui/android/strings/translations/android_chrome_strings_mk.xtb +++ b/chrome/browser/ui/android/strings/translations/android_chrome_strings_mk.xtb
@@ -126,7 +126,7 @@ <translation id="1963976881984600709">Стандардна заштита</translation> <translation id="1966710179511230534">Ажурирајте ги информациите за пријавување.</translation> <translation id="1974060860693918893">Напредни</translation> -<translation id="1984417487208496350">Нема заштита (не се препорачува)</translation> +<translation id="1984417487208496350">Без заштита (не се препорачува)</translation> <translation id="1984705450038014246">Синхронизирајте ги податоците од Chrome</translation> <translation id="1986685561493779662">Името веќе постои</translation> <translation id="1987739130650180037"><ph name="MESSAGE" /> <ph name="LINK_NAME" /> копче</translation>
diff --git a/chrome/browser/ui/android/strings/translations/android_chrome_strings_ne.xtb b/chrome/browser/ui/android/strings/translations/android_chrome_strings_ne.xtb index 136465e..67035d7 100644 --- a/chrome/browser/ui/android/strings/translations/android_chrome_strings_ne.xtb +++ b/chrome/browser/ui/android/strings/translations/android_chrome_strings_ne.xtb
@@ -178,7 +178,7 @@ <translation id="2323763861024343754">साइटको भण्डारण</translation> <translation id="2328985652426384049">साइन इन गर्न सकिएन</translation> <translation id="234265804618409743">तपाईंको क्यामेरा खोल्न सकिएन। केही चिज गडबड भयो।</translation> -<translation id="2345671828921229300">कुनै शब्दबारे जानकारी खोज्न त्यसलाई छोइराख्नुहोस्</translation> +<translation id="2345671828921229300">कुनै शब्दबारे जानकारी खोज्न त्यसलाई टच एण्ड होल्ड गर्नुहोस्</translation> <translation id="2349710944427398404">खाता, पुस्तक चिन्ह र सुरक्षित गरिएका सेटिङहरू सहित Chrome ले प्रयोग गरेको कुल डेटा</translation> <translation id="2353636109065292463">तपाईंको इन्टरनेट जडानको जाँच गर्दै</translation> <translation id="2359808026110333948">जारी राख्नुहोस्</translation> @@ -194,7 +194,7 @@ <translation id="2450083983707403292">तपाईं <ph name="FILE_NAME" /> लाई फेरि डाउनलोड गर्न चाहनुहुन्छ?</translation> <translation id="2450907520913474542">यो पृष्ठ नछोडिकन वेबसाइटहरूमा रहेका शीर्षकहरूबारे जान्नुहोस्। खोज्नका लागि छुनुहोस् नामक सुविधाले कुनै शब्द र त्यसको सन्दर्भलाई Google खोजमा पठाउँछ र उक्त शब्दको परिभाषा, त्यससँग सम्बन्धित तस्बिर, खोज परिणाम र अन्य विवरणहरू देखाउँछ। -कुनै शब्द खोज्न उक्त शब्दमा छोइराख्नुहोस्। आफ्नो खोज परिष्कृत गर्न अझ धेरै वा कम शब्दहरू चयन गर्नुहोस्। आफ्नो खोज पद सम्पादन गर्न प्यानल खोल्नुहोस्, नयाँ ट्याबमा खोल्ने आइकनमा ट्याप गर्नुहोस् र खोज बाकसमा रहेको खोज पदमा आवश्यक परिवर्तनहरू गर्नुहोस्।</translation> +कुनै शब्द खोज्न उक्त शब्दमा टच एण्ड होल्ड गर्नुहोस्। आफ्नो खोज परिष्कृत गर्न अझ धेरै वा कम शब्दहरू चयन गर्नुहोस्। आफ्नो खोज पद सम्पादन गर्न प्यानल खोल्नुहोस्, नयाँ ट्याबमा खोल्ने आइकनमा ट्याप गर्नुहोस् र खोज बाकसमा रहेको खोज पदमा आवश्यक परिवर्तनहरू गर्नुहोस्।</translation> <translation id="246532703174860178">सेयर गर्नुहोस्</translation> <translation id="2478076885740497414">एप स्थापना गर्नुहोस्</translation> <translation id="2479148705183875116">सेटिङमा जानुहोस्</translation> @@ -317,7 +317,7 @@ <translation id="3353615205017136254">Google ले प्रदान गरेको मूल पृष्ठको लाइट संस्करण। मूल पृष्ठ लोड गर्न मूल पृष्ठ लोड गर्नुहोस् नामक बटन ट्याप गर्नुहोस्।</translation> <translation id="3359667936385849800">तपाईंको हालको सेवा प्रदायक प्रयोग गर्नुहोस्</translation> <translation id="3367813778245106622">सिंक सुरु गर्न फेरि साइन इन गर्नुहोस्</translation> -<translation id="337236281855091893">कुनै शब्दबारे जानकारी खोज्न त्यसमा ट्याप गर्नुको साटो त्यसलाई छोइराख्नुहोस्</translation> +<translation id="337236281855091893">कुनै शब्दबारे जानकारी खोज्न त्यसमा ट्याप गर्नुको साटो त्यसलाई टच एण्ड होल्ड गर्नुहोस्</translation> <translation id="3373979091428520308">यो पृष्ठ अर्को यन्त्रसँग आदान प्रदान गर्न अर्को यन्त्रमा रहेको Chrome ब्राउजरको सेटिङमा गई सिंक गर्ने सुविधा सक्रिय गर्नुहोस्</translation> <translation id="3374023511497244703">अब उप्रान्त तपाईंको Google खातामा तपाईंका पुस्तक चिन्ह, इतिहास, पासवर्ड र Chrome का अन्य डेटा सिंक हुने छैनन्</translation> <translation id="3384347053049321195">छवि सेयर गर्नुहोस्</translation>
diff --git a/chrome/browser/ui/android/strings/translations/android_chrome_strings_pt-BR.xtb b/chrome/browser/ui/android/strings/translations/android_chrome_strings_pt-BR.xtb index eeaaed9d..f217d7b 100644 --- a/chrome/browser/ui/android/strings/translations/android_chrome_strings_pt-BR.xtb +++ b/chrome/browser/ui/android/strings/translations/android_chrome_strings_pt-BR.xtb
@@ -330,7 +330,7 @@ <translation id="3492207499832628349">Nova guia anônima</translation> <translation id="3493531032208478708"><ph name="BEGIN_LINK" />Saiba mais<ph name="END_LINK" /> sobre o conteúdo sugerido</translation> <translation id="3499246418971111862">chrome_qrcode_<ph name="CURRENT_TIMESTAMP_MS" /></translation> -<translation id="3507132249039706973">A "Proteção padrão" está ativada</translation> +<translation id="3507132249039706973">A Proteção padrão está ativa</translation> <translation id="3509330069915219067">Off-line. O Chrome não pode verificar se há atualizações.</translation> <translation id="3513704683820682405">Realidade aumentada</translation> <translation id="3518985090088779359">Aceitar e continuar</translation> @@ -441,6 +441,7 @@ <translation id="4405224443901389797">Mover para…</translation> <translation id="4411535500181276704">Modo Lite</translation> <translation id="4415276339145661267">Gerenciar sua Conta do Google</translation> +<translation id="4427306783828095590">A Proteção reforçada é mais eficiente no combate a golpes de phishing e malware</translation> <translation id="4440958355523780886">Página Lite exibida pelo Google. Toque para carregar a original.</translation> <translation id="4452411734226507615">Fechar guia <ph name="TAB_TITLE" /></translation> <translation id="4452548195519783679">Adicionado como favorito em <ph name="FOLDER_NAME" /></translation> @@ -572,7 +573,7 @@ <translation id="5324858694974489420">Configurações dos pais</translation> <translation id="5327248766486351172">Nome</translation> <translation id="5342314432463739672">Solicitações de permissão</translation> -<translation id="5355191726083956201">A "Proteção reforçada" está ativa</translation> +<translation id="5355191726083956201">A Proteção reforçada está ativa</translation> <translation id="5357811892247919462">Guia recebida</translation> <translation id="5368958499335451666">{OPEN_TABS,plural, =1{<ph name="OPEN_TABS_ONE" /> guia aberta, toque para alternar}one{<ph name="OPEN_TABS_MANY" /> guia aberta, toque para alternar}other{<ph name="OPEN_TABS_MANY" /> guias abertas, toque para alternar}}</translation> <translation id="5403644198645076998">Permitir apenas determinados sites</translation>
diff --git a/chrome/browser/ui/android/strings/translations/android_chrome_strings_ru.xtb b/chrome/browser/ui/android/strings/translations/android_chrome_strings_ru.xtb index d94c9dd4..e19ab86 100644 --- a/chrome/browser/ui/android/strings/translations/android_chrome_strings_ru.xtb +++ b/chrome/browser/ui/android/strings/translations/android_chrome_strings_ru.xtb
@@ -620,7 +620,7 @@ <translation id="5687809546194252819">После перезапуска в приложении "<ph name="APP_NAME" />" будет использоваться выбранный язык (<ph name="LANGUAGE" />).</translation> <translation id="5691211010013816086">Страниц в нем: <ph name="READING_LIST_COUNT" /></translation> <translation id="569536719314091526">Чтобы перевести эту страницу на какой-либо язык, нажмите кнопку "Ещё"</translation> -<translation id="5696597120588531049">Chrome поможет обеспечить защиту от утечки данных, подозрительных сайтов и других проблем с безопасностью.</translation> +<translation id="5696597120588531049">Chrome поможет защитить вас от утечки данных, подозрительных сайтов и других проблем с безопасностью.</translation> <translation id="5697688514913266141">Куда будет сохранен файл: <ph name="BEGIN_BOLD" /><ph name="DIRECTORY" /><ph name="END_BOLD" />. <ph name="BEGIN_LINK2" />Изменить<ph name="END_LINK2" /></translation> <translation id="570347048394355941">Переключиться на вкладку</translation> <translation id="572328651809341494">Недавние вкладки</translation> @@ -697,7 +697,7 @@ <translation id="6154478581116148741">Чтобы экспортировать пароли с этого устройства, включите блокировку экрана в настройках.</translation> <translation id="6157392216611456285">Выбрать <ph name="APP_NAME" /></translation> <translation id="6159335304067198720">Сэкономлено: <ph name="PERCENT" /></translation> -<translation id="6186394685773237175">Похищенных паролей не найдено.</translation> +<translation id="6186394685773237175">Раскрытых паролей не найдено.</translation> <translation id="6192907950379606605">Описывать изображения</translation> <translation id="6206830853671714236">Выберите, когда начать скачивание</translation> <translation id="6210748933810148297"><ph name="EMAIL" /> не ваш аккаунт?</translation> @@ -837,7 +837,7 @@ <translation id="707155805709242880">Выберите ниже, что нужно синхронизировать.</translation> <translation id="7077143737582773186">SD-карта</translation> <translation id="7080806333218412752">Обеспечивает отправку URL на проверку по критериям Безопасного просмотра. Кроме того с целью выявления новых угроз отправляется на анализ небольшая выборка страниц, скачанных файлов и сведений об использовании расширений, а также информация о системе. Когда выполнен вход в аккаунт Google, между этими данными и аккаунтом временно устанавливается связь, чтобы вы были защищены во время работы с различными приложениями Google.</translation> -<translation id="7088681679121566888">У вас установлена новейшая версия Chrome.</translation> +<translation id="7088681679121566888">У вас установлена последняя версия Chrome.</translation> <translation id="7106762743910369165">Этим браузером управляет ваша организация.</translation> <translation id="7121362699166175603">Удаление истории и вариантов автозаполнения в адресной строке. Информация о других ваших действиях в Интернете может также храниться на странице <ph name="BEGIN_LINK" />myactivity.google.com<ph name="END_LINK" />.</translation> <translation id="7128355412245153445">Нужные сайты и недавние статьи – одним нажатием кнопки.</translation>
diff --git a/chrome/browser/ui/android/strings/translations/android_chrome_strings_te.xtb b/chrome/browser/ui/android/strings/translations/android_chrome_strings_te.xtb index e20f8f3d2..75bfe96 100644 --- a/chrome/browser/ui/android/strings/translations/android_chrome_strings_te.xtb +++ b/chrome/browser/ui/android/strings/translations/android_chrome_strings_te.xtb
@@ -117,7 +117,7 @@ <translation id="1919130412786645364">Chrome సైన్-ఇన్ని అనుమతించండి</translation> <translation id="1922362554271624559">సూచించిన భాషలు</translation> <translation id="1925021887439448749">అనుకూల వెబ్ చిరునామాను నమోదు చేయండి</translation> -<translation id="1928696683969751773">నవీకరిస్తుంది</translation> +<translation id="1928696683969751773">అప్డేట్లు</translation> <translation id="19288952978244135">Chromeను మళ్లీ తెరవండి.</translation> <translation id="1933845786846280168">ఎంచుకున్న ట్యాబ్</translation> <translation id="1943432128510653496">పాస్వర్డ్లను సేవ్ చేయండి</translation>
diff --git a/chrome/browser/ui/android/strings/translations/android_chrome_strings_uk.xtb b/chrome/browser/ui/android/strings/translations/android_chrome_strings_uk.xtb index 41aedc0..52ce859a 100644 --- a/chrome/browser/ui/android/strings/translations/android_chrome_strings_uk.xtb +++ b/chrome/browser/ui/android/strings/translations/android_chrome_strings_uk.xtb
@@ -529,7 +529,7 @@ <translation id="4943872375798546930">Не знайдено жодного результату</translation> <translation id="4961107849584082341">Перекладіть цю сторінку будь-якою мовою</translation> <translation id="4970824347203572753">Функція недоступна у вашій країні</translation> -<translation id="4971735654804503942">Швидший активний захист від небезпечних веб-сайтів, завантажень і розширень. Попереджає про розкриття паролів через порушення безпеки даних. Вимагає надсилати в Google дані веб-перегляду.</translation> +<translation id="4971735654804503942">Швидший активний захист від небезпечних веб-сайтів, завантажень і розширень. Попереджає про розкриття паролів через порушення безпеки даних. Дані веб-перегляду потрібно надсилати в Google.</translation> <translation id="497421865427891073">Перейти вперед</translation> <translation id="4988210275050210843">Завантажується файл (<ph name="MEGABYTES" />).</translation> <translation id="4988526792673242964">Сторінки</translation> @@ -723,7 +723,7 @@ <translation id="6333140779060797560">Надіслати через <ph name="APPLICATION" /></translation> <translation id="6337234675334993532">Шифрування</translation> <translation id="6341580099087024258">Запитувати, де зберігати файли</translation> -<translation id="6342069812937806050">Лише зараз</translation> +<translation id="6342069812937806050">Щойно</translation> <translation id="6343495912647200061">{SHIPPING_ADDRESS,plural, =1{<ph name="SHIPPING_ADDRESS_PREVIEW" />\u2026 і ще <ph name="NUMBER_OF_ADDITIONAL_ADDRESSES" />}one{<ph name="SHIPPING_ADDRESS_PREVIEW" />\u2026 і ще <ph name="NUMBER_OF_ADDITIONAL_ADDRESSES" />}few{<ph name="SHIPPING_ADDRESS_PREVIEW" />\u2026 і ще <ph name="NUMBER_OF_ADDITIONAL_ADDRESSES" />}many{<ph name="SHIPPING_ADDRESS_PREVIEW" />\u2026 і ще <ph name="NUMBER_OF_ADDITIONAL_ADDRESSES" />}other{<ph name="SHIPPING_ADDRESS_PREVIEW" />\u2026 і ще <ph name="NUMBER_OF_ADDITIONAL_ADDRESSES" />}}</translation> <translation id="6345878117466430440">Позначити як прочитане</translation> <translation id="6364438453358674297">Вилучити пропозицію з історії?</translation>
diff --git a/chrome/browser/ui/android/strings/translations/android_chrome_strings_ur.xtb b/chrome/browser/ui/android/strings/translations/android_chrome_strings_ur.xtb index 1083d46..e7c761b0 100644 --- a/chrome/browser/ui/android/strings/translations/android_chrome_strings_ur.xtb +++ b/chrome/browser/ui/android/strings/translations/android_chrome_strings_ur.xtb
@@ -620,7 +620,7 @@ <translation id="5687809546194252819"><ph name="APP_NAME" /> ری سٹارٹ پر <ph name="LANGUAGE" /> استعمال کرے گا۔</translation> <translation id="5691211010013816086">آپ کے پاس <ph name="READING_LIST_COUNT" /> صفحات ہیں</translation> <translation id="569536719314091526">مزید اختیارات کے بٹن سے کسی بھی زبان میں اس صفحہ کا ترجمہ کریں</translation> -<translation id="5696597120588531049">Chrome آپ کو ڈیٹا کی خلاف ورزیوں، غیر محفوظ ویب سائٹ اور بہت کچھ سے محفوظ رکھنے میں مدد کر سکتا ہے</translation> +<translation id="5696597120588531049">Chrome آپ کو ڈیٹا کی خلاف ورزیوں، غیر محفوظ ویب سائٹوں اور مزید بہت کچھ سے محفوظ رکھنے میں مدد کر سکتا ہے</translation> <translation id="5697688514913266141">آپ کی فائل <ph name="BEGIN_BOLD" /><ph name="DIRECTORY" /><ph name="END_BOLD" /> میں محفوظ کر دی جائے گی۔ <ph name="BEGIN_LINK2" />ترمیم کریں<ph name="END_LINK2" />۔</translation> <translation id="570347048394355941">ٹیب پر سوئچ کریں</translation> <translation id="572328651809341494">حالیہ ٹیبز</translation>
diff --git a/chrome/browser/ui/android/strings/translations/android_chrome_strings_vi.xtb b/chrome/browser/ui/android/strings/translations/android_chrome_strings_vi.xtb index 8c9b6dac..b45848cc 100644 --- a/chrome/browser/ui/android/strings/translations/android_chrome_strings_vi.xtb +++ b/chrome/browser/ui/android/strings/translations/android_chrome_strings_vi.xtb
@@ -117,7 +117,7 @@ <translation id="1919130412786645364">Cho phép đăng nhập vào Chrome</translation> <translation id="1922362554271624559">Ngôn ngữ đề xuất</translation> <translation id="1925021887439448749">Nhập địa chỉ web tùy chỉnh</translation> -<translation id="1928696683969751773">Số lần cập nhật</translation> +<translation id="1928696683969751773">Bản cập nhật</translation> <translation id="19288952978244135">Mở lại Chrome.</translation> <translation id="1933845786846280168">Thẻ được chọn</translation> <translation id="1943432128510653496">Lưu mật khẩu</translation> @@ -331,7 +331,7 @@ <translation id="3493531032208478708"><ph name="BEGIN_LINK" />Tìm hiểu thêm<ph name="END_LINK" /> về nội dung đề xuất</translation> <translation id="3499246418971111862">chrome_qrcode_<ph name="CURRENT_TIMESTAMP_MS" /></translation> <translation id="3507132249039706973">Tính năng Bảo vệ thông thường đang bật</translation> -<translation id="3509330069915219067">Không có kết nối mạng. Chrome không thể kiểm tra các bản cập nhật.</translation> +<translation id="3509330069915219067">Không có kết nối mạng. Chrome không thể kiểm tra để tìm các bản cập nhật.</translation> <translation id="3513704683820682405">Thực tế tăng cường</translation> <translation id="3518985090088779359">Chấp nhận và tiếp tục</translation> <translation id="3522247891732774234">Bản cập nhật có sẵn. Tùy chọn khác</translation> @@ -615,7 +615,7 @@ <translation id="5659593005791499971">Email</translation> <translation id="5665379678064389456">Tạo sự kiện trong <ph name="APP_NAME" /></translation> <translation id="5668404140385795438">Ghi đè yêu cầu của trang web để chặn phóng to</translation> -<translation id="5683547024293500885">Chrome không thể kiểm tra các bản cập nhật</translation> +<translation id="5683547024293500885">Chrome không thể kiểm tra để tìm các bản cập nhật</translation> <translation id="5686790454216892815">Tên tệp quá dài</translation> <translation id="5687809546194252819"><ph name="APP_NAME" /> sẽ sử dụng <ph name="LANGUAGE" /> sau khi khởi động lại.</translation> <translation id="5691211010013816086">Bạn có <ph name="READING_LIST_COUNT" /> trang</translation>
diff --git a/chrome/browser/ui/ash/ash_test_util.cc b/chrome/browser/ui/ash/ash_test_util.cc index 2be6d2b..1f8801e 100644 --- a/chrome/browser/ui/ash/ash_test_util.cc +++ b/chrome/browser/ui/ash/ash_test_util.cc
@@ -5,8 +5,8 @@ #include "chrome/browser/ui/ash/ash_test_util.h" #include "ash/public/cpp/window_properties.h" -#include "ash/public/cpp/window_state_type.h" #include "base/run_loop.h" +#include "chromeos/ui/base/window_state_type.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/aura/window.h" #include "ui/aura/window_observer.h" @@ -15,11 +15,12 @@ namespace test { namespace { + // Wait until the window's state changes to given the snapped state. // The window should stay alive, so no need to observer destroying. class SnapWaiter : public aura::WindowObserver { public: - SnapWaiter(aura::Window* window, ash::WindowStateType type) + SnapWaiter(aura::Window* window, chromeos::WindowStateType type) : window_(window), type_(type) { window->AddObserver(this); } @@ -41,7 +42,7 @@ private: aura::Window* window_; - ash::WindowStateType type_; + chromeos::WindowStateType type_; base::RunLoop run_loop_; DISALLOW_COPY_AND_ASSIGN(SnapWaiter); @@ -49,7 +50,8 @@ } // namespace -void ActivateAndSnapWindow(aura::Window* window, ash::WindowStateType type) { +void ActivateAndSnapWindow(aura::Window* window, + chromeos::WindowStateType type) { DCHECK(window); if (!wm::IsActiveWindow(window)) wm::ActivateWindow(window); @@ -57,15 +59,15 @@ ASSERT_TRUE(wm::IsActiveWindow(window)); SnapWaiter snap_waiter(window, type); - ASSERT_TRUE(type == ash::WindowStateType::kRightSnapped || - type == ash::WindowStateType::kLeftSnapped); + ASSERT_TRUE(type == chromeos::WindowStateType::kRightSnapped || + type == chromeos::WindowStateType::kLeftSnapped); // Early return if it's already snapped. if (snap_waiter.IsSnapped()) return; ui_controls::SendKeyPress(window, - type == ash::WindowStateType::kLeftSnapped + type == chromeos::WindowStateType::kLeftSnapped ? ui::VKEY_OEM_4 : ui::VKEY_OEM_6, /*control=*/false,
diff --git a/chrome/browser/ui/ash/ash_test_util.h b/chrome/browser/ui/ash/ash_test_util.h index 2bf755e..861fa42 100644 --- a/chrome/browser/ui/ash/ash_test_util.h +++ b/chrome/browser/ui/ash/ash_test_util.h
@@ -5,7 +5,7 @@ #ifndef CHROME_BROWSER_UI_ASH_ASH_TEST_UTIL_H_ #define CHROME_BROWSER_UI_ASH_ASH_TEST_UTIL_H_ -namespace ash { +namespace chromeos { enum class WindowStateType; } @@ -16,7 +16,8 @@ namespace test { // The snap window. This will activate the |window|. -void ActivateAndSnapWindow(aura::Window* window, ash::WindowStateType type); +void ActivateAndSnapWindow(aura::Window* window, + chromeos::WindowStateType type); } // namespace test
diff --git a/chrome/browser/ui/ash/chrome_capture_mode_delegate.cc b/chrome/browser/ui/ash/chrome_capture_mode_delegate.cc index f1c7979..d0eb1c5 100644 --- a/chrome/browser/ui/ash/chrome_capture_mode_delegate.cc +++ b/chrome/browser/ui/ash/chrome_capture_mode_delegate.cc
@@ -6,7 +6,11 @@ #include "base/files/file_path.h" #include "base/i18n/time_formatting.h" +#include "chrome/browser/apps/app_service/app_service_proxy.h" +#include "chrome/browser/apps/app_service/app_service_proxy_factory.h" +#include "chrome/browser/apps/app_service/launch_utils.h" #include "chrome/browser/chromeos/policy/dlp/dlp_content_manager.h" +#include "chrome/browser/chromeos/web_applications/default_web_app_ids.h" #include "chrome/browser/download/download_prefs.h" #include "chrome/browser/platform_util.h" #include "chrome/browser/profiles/profile_manager.h" @@ -15,6 +19,7 @@ #include "chromeos/login/login_state/login_state.h" #include "components/prefs/pref_service.h" #include "ui/aura/window.h" +#include "ui/base/window_open_disposition.h" namespace { @@ -44,6 +49,27 @@ file_path); } +void ChromeCaptureModeDelegate::OpenScreenshotInImageEditor( + const base::FilePath& file_path) { + Profile* profile = ProfileManager::GetActiveUserProfile(); + if (!profile) + return; + + apps::AppServiceProxy* proxy = apps::AppServiceProxyFactory::GetForProfile( + profile->GetOriginalProfile()); + apps::mojom::FilePathsPtr file_paths_ptr = + apps::mojom::FilePaths::New(std::vector<base::FilePath>({file_path})); + + // open the image with Essential App: Backlight. + proxy->LaunchAppWithFiles( + chromeos::default_web_apps::kMediaAppId, + apps::mojom::LaunchContainer::kLaunchContainerWindow, + apps::GetEventFlags(apps::mojom::LaunchContainer::kLaunchContainerWindow, + WindowOpenDisposition::NEW_WINDOW, + /*preferred_container=*/true), + apps::mojom::LaunchSource::kFromFileManager, std::move(file_paths_ptr)); +} + bool ChromeCaptureModeDelegate::Uses24HourFormat() const { Profile* profile = ProfileManager::GetActiveUserProfile(); // TODO(afakhry): Consider moving |prefs::kUse24HourClock| to ash/public so
diff --git a/chrome/browser/ui/ash/chrome_capture_mode_delegate.h b/chrome/browser/ui/ash/chrome_capture_mode_delegate.h index 09aa674..1d0730d1 100644 --- a/chrome/browser/ui/ash/chrome_capture_mode_delegate.h +++ b/chrome/browser/ui/ash/chrome_capture_mode_delegate.h
@@ -20,6 +20,7 @@ // ash::CaptureModeDelegate: base::FilePath GetActiveUserDownloadsDir() const override; void ShowScreenCaptureItemInFolder(const base::FilePath& file_path) override; + void OpenScreenshotInImageEditor(const base::FilePath& file_path) override; bool Uses24HourFormat() const override; bool IsCaptureAllowed(const aura::Window* window, const gfx::Rect& bounds,
diff --git a/chrome/browser/ui/ash/launcher/app_service/app_service_app_window_launcher_item_controller.cc b/chrome/browser/ui/ash/launcher/app_service/app_service_app_window_launcher_item_controller.cc index 924e088c..c8c9f314 100644 --- a/chrome/browser/ui/ash/launcher/app_service/app_service_app_window_launcher_item_controller.cc +++ b/chrome/browser/ui/ash/launcher/app_service/app_service_app_window_launcher_item_controller.cc
@@ -5,7 +5,6 @@ #include "chrome/browser/ui/ash/launcher/app_service/app_service_app_window_launcher_item_controller.h" #include "ash/public/cpp/window_properties.h" -#include "ash/public/cpp/window_state_type.h" #include "chrome/browser/apps/app_service/app_service_proxy.h" #include "chrome/browser/apps/app_service/app_service_proxy_factory.h" #include "chrome/browser/chromeos/arc/pip/arc_pip_bridge.h" @@ -13,6 +12,7 @@ #include "chrome/browser/ui/app_list/arc/arc_app_utils.h" #include "chrome/browser/ui/ash/launcher/app_service/app_service_app_window_launcher_controller.h" #include "chrome/browser/ui/ash/launcher/chrome_launcher_controller.h" +#include "chromeos/ui/base/window_state_type.h" #include "components/favicon/content/content_favicon_driver.h" #include "components/services/app_service/public/mojom/types.mojom.h" #include "extensions/browser/app_window/app_window.h" @@ -46,7 +46,7 @@ for (ui::BaseWindow* window : windows()) { aura::Window* native_window = window->GetNativeWindow(); if (native_window->GetProperty(ash::kWindowStateTypeKey) == - ash::WindowStateType::kPip) { + chromeos::WindowStateType::kPip) { Profile* profile = ChromeLauncherController::instance()->profile(); arc::ArcPipBridge* pip_bridge = arc::ArcPipBridge::GetForBrowserContext(profile);
diff --git a/chrome/browser/ui/thumbnails/thumbnail_image.cc b/chrome/browser/ui/thumbnails/thumbnail_image.cc index daf248f..9297ca9 100644 --- a/chrome/browser/ui/thumbnails/thumbnail_image.cc +++ b/chrome/browser/ui/thumbnails/thumbnail_image.cc
@@ -11,7 +11,6 @@ #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/time/time.h" -#include "chrome/browser/ui/thumbnails/thumbnail_stats_tracker.h" #include "ui/gfx/codec/jpeg_codec.h" #include "ui/gfx/skia_util.h" @@ -36,12 +35,10 @@ DCHECK(delegate_); DCHECK(!delegate_->thumbnail_); delegate_->thumbnail_ = this; - ThumbnailStatsTracker::GetInstance().AddThumbnail(this); } ThumbnailImage::~ThumbnailImage() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - ThumbnailStatsTracker::GetInstance().RemoveThumbnail(this); if (delegate_) delegate_->thumbnail_ = nullptr; }
diff --git a/chrome/browser/ui/thumbnails/thumbnail_image.h b/chrome/browser/ui/thumbnails/thumbnail_image.h index ffe352c..00ff714 100644 --- a/chrome/browser/ui/thumbnails/thumbnail_image.h +++ b/chrome/browser/ui/thumbnails/thumbnail_image.h
@@ -94,12 +94,6 @@ // Observer::OnCompressedThumbnailDataAvailable(). void RequestCompressedThumbnailData(); - // Returns the size of the compressed data backing this thumbnail. - // This size can be 0. Additionally, since this data is refcounted, - // it's possible this returns 0 even if the data is still allocated. A - // client can hold a reference to it after |this| drops its reference. - size_t GetCompressedDataSizeInBytes() { return data_->data.size(); } - void set_async_operation_finished_callback_for_testing( base::RepeatingClosure callback) { async_operation_finished_callback_ = std::move(callback);
diff --git a/chrome/browser/ui/thumbnails/thumbnail_stats_tracker.cc b/chrome/browser/ui/thumbnails/thumbnail_stats_tracker.cc deleted file mode 100644 index 73da496..0000000 --- a/chrome/browser/ui/thumbnails/thumbnail_stats_tracker.cc +++ /dev/null
@@ -1,76 +0,0 @@ -// Copyright 2020 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/thumbnails/thumbnail_stats_tracker.h" - -#include "base/bind.h" -#include "base/location.h" -#include "base/metrics/histogram_macros.h" -#include "base/no_destructor.h" -#include "base/time/time.h" -#include "chrome/browser/ui/thumbnails/thumbnail_image.h" - -namespace { - -// Global instance. Only set once, except in tests which can reset the -// instance and create a new one. -ThumbnailStatsTracker* g_instance = nullptr; - -} // namespace - -// static -constexpr base::TimeDelta ThumbnailStatsTracker::kReportingInterval; - -// static -ThumbnailStatsTracker& ThumbnailStatsTracker::GetInstance() { - if (!g_instance) - g_instance = new ThumbnailStatsTracker; - return *g_instance; -} - -// static -void ThumbnailStatsTracker::ResetInstanceForTesting() { - delete g_instance; - g_instance = nullptr; -} - -ThumbnailStatsTracker::ThumbnailStatsTracker() { - heartbeat_timer_.Start( - FROM_HERE, kReportingInterval, - base::BindRepeating(&ThumbnailStatsTracker::RecordMetrics, - base::Unretained(this))); -} - -ThumbnailStatsTracker::~ThumbnailStatsTracker() { - // This is only called from tests. Make sure there are no thumbnails left. - DCHECK_EQ(thumbnails_.size(), 0u); -} - -void ThumbnailStatsTracker::AddThumbnail(ThumbnailImage* thumbnail) { - auto result = thumbnails_.insert(thumbnail); - DCHECK(result.second) << "Thumbnail already added"; -} - -void ThumbnailStatsTracker::RemoveThumbnail(ThumbnailImage* thumbnail) { - int removed = thumbnails_.erase(thumbnail); - DCHECK_EQ(removed, 1) << "Thumbnail not added"; -} - -void ThumbnailStatsTracker::RecordMetrics() { - size_t total_size_bytes = 0; - - for (ThumbnailImage* thumbnail : thumbnails_) { - size_t thumbnail_size_bytes = thumbnail->GetCompressedDataSizeInBytes(); - total_size_bytes += thumbnail_size_bytes; - - size_t thumbnail_size_kb = thumbnail_size_bytes / 1024; - UMA_HISTOGRAM_COUNTS_100( - "Tab.Preview.MemoryUsage.CompressedData.PerThumbnailKiB", - thumbnail_size_kb); - } - - size_t total_size_kb = total_size_bytes / 1024; - UMA_HISTOGRAM_CUSTOM_COUNTS("Tab.Preview.MemoryUsage.CompressedData.TotalKiB", - total_size_kb, 32, 8192, 100); -}
diff --git a/chrome/browser/ui/thumbnails/thumbnail_stats_tracker.h b/chrome/browser/ui/thumbnails/thumbnail_stats_tracker.h deleted file mode 100644 index 044a3b0..0000000 --- a/chrome/browser/ui/thumbnails/thumbnail_stats_tracker.h +++ /dev/null
@@ -1,56 +0,0 @@ -// Copyright 2020 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_THUMBNAILS_THUMBNAIL_STATS_TRACKER_H_ -#define CHROME_BROWSER_UI_THUMBNAILS_THUMBNAIL_STATS_TRACKER_H_ - -#include <set> - -#include "base/time/time.h" -#include "base/timer/timer.h" - -namespace base { -template <typename T> -class NoDestructor; -} // namespace base - -class ThumbnailImage; - -// Records memory metrics across all thumbnails in a browser process. -class ThumbnailStatsTracker { - private: - friend class ThumbnailImage; - friend class base::NoDestructor<ThumbnailStatsTracker>; - - friend class ThumbnailStatsTrackerTest; - - static constexpr base::TimeDelta kReportingInterval = - base::TimeDelta::FromMinutes(5); - - // Gets the global instance for this process. - static ThumbnailStatsTracker& GetInstance(); - - // This must only be called if all registered thumbnails have been - // removed. - static void ResetInstanceForTesting(); - - ThumbnailStatsTracker(); - - // Exists only for ResetInstanceForTesting(). - ~ThumbnailStatsTracker(); - - // Called from our friend, ThumbnailImage. - void AddThumbnail(ThumbnailImage* thumbnail); - void RemoveThumbnail(ThumbnailImage* thumbnail); - - // Called by |heartbeat_timer_| to record metrics at a regular - // interval. - void RecordMetrics(); - - base::RepeatingTimer heartbeat_timer_; - - std::set<ThumbnailImage*> thumbnails_; -}; - -#endif // CHROME_BROWSER_UI_THUMBNAILS_THUMBNAIL_STATS_TRACKER_H_
diff --git a/chrome/browser/ui/thumbnails/thumbnail_stats_tracker_unittest.cc b/chrome/browser/ui/thumbnails/thumbnail_stats_tracker_unittest.cc deleted file mode 100644 index 586dad8..0000000 --- a/chrome/browser/ui/thumbnails/thumbnail_stats_tracker_unittest.cc +++ /dev/null
@@ -1,165 +0,0 @@ -// Copyright 2020 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/thumbnails/thumbnail_stats_tracker.h" - -#include "base/logging.h" -#include "base/memory/scoped_refptr.h" -#include "base/rand_util.h" -#include "base/run_loop.h" -#include "base/test/metrics/histogram_tester.h" -#include "base/test/task_environment.h" -#include "base/time/time.h" -#include "chrome/browser/ui/thumbnails/thumbnail_image.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/skia/include/core/SkBitmap.h" - -namespace { - -constexpr char kPerThumbnailMemoryUsageHistogram[] = - "Tab.Preview.MemoryUsage.CompressedData.PerThumbnailKiB"; -constexpr char kTotalMemoryUsageHistogram[] = - "Tab.Preview.MemoryUsage.CompressedData.TotalKiB"; - -class StubThumbnailImageDelegate : public ThumbnailImage::Delegate { - public: - StubThumbnailImageDelegate() = default; - ~StubThumbnailImageDelegate() override = default; - - // ThumbnailImage::Delegate: - void ThumbnailImageBeingObservedChanged(bool is_being_observed) override {} -}; - -class ThumbnailOwner : public ThumbnailImage::Delegate { - public: - ThumbnailOwner() = default; - ~ThumbnailOwner() override = default; - - ThumbnailImage* Get() { return thumbnail_.get(); } - - // ThumbnailImage::Delegate: - void ThumbnailImageBeingObservedChanged(bool is_being_observed) override {} - - private: - scoped_refptr<ThumbnailImage> thumbnail_{ - base::MakeRefCounted<ThumbnailImage>(this)}; -}; - -} // namespace - -class ThumbnailStatsTrackerTest : public ::testing::Test { - protected: - void SetUp() override { - // Delete previous instance and create new one to start the timer. - ThumbnailStatsTracker::ResetInstanceForTesting(); - ThumbnailStatsTracker::GetInstance(); - } - - // A random bitmap will have roughly the same size, or even greater - // size, after compression. - SkBitmap CreateRandomBitmapOfSize(unsigned int width, unsigned int height) { - SkBitmap bitmap; - bitmap.allocN32Pixels(width, height); - for (unsigned int x = 0; x < width; ++x) { - for (unsigned int y = 0; y < height; ++y) { - *bitmap.getAddr32(x, y) = static_cast<uint32_t>(base::RandUint64()); - } - } - return bitmap; - } - - void AssignThumbnailBitmapAndWait(ThumbnailImage* thumbnail, - SkBitmap bitmap) { - base::RunLoop run_loop; - thumbnail->set_async_operation_finished_callback_for_testing( - run_loop.QuitClosure()); - thumbnail->AssignSkBitmap(bitmap); - run_loop.Run(); - - // Clear the callback since the old one will be invalid. - thumbnail->set_async_operation_finished_callback_for_testing( - base::RepeatingClosure()); - } - - void AdvanceToNextReport() { - task_environment_.FastForwardBy(ThumbnailStatsTracker::kReportingInterval); - } - - base::test::TaskEnvironment task_environment_{ - base::test::TaskEnvironment::TimeSource::MOCK_TIME}; - - base::HistogramTester histogram_tester_; - - private: - StubThumbnailImageDelegate stub_thumbnail_image_delegate_; -}; - -TEST_F(ThumbnailStatsTrackerTest, LogsMemoryMetricsAtHeartbeat) { - ThumbnailOwner thumbnail_1; - ThumbnailOwner thumbnail_2; - - AssignThumbnailBitmapAndWait(thumbnail_1.Get(), - CreateRandomBitmapOfSize(2, 2)); - AssignThumbnailBitmapAndWait(thumbnail_2.Get(), - CreateRandomBitmapOfSize(2, 2)); - - histogram_tester_.ExpectTotalCount(kPerThumbnailMemoryUsageHistogram, 0); - histogram_tester_.ExpectTotalCount(kTotalMemoryUsageHistogram, 0); - - AdvanceToNextReport(); - histogram_tester_.ExpectTotalCount(kPerThumbnailMemoryUsageHistogram, 2); - histogram_tester_.ExpectTotalCount(kTotalMemoryUsageHistogram, 1); - - AdvanceToNextReport(); - histogram_tester_.ExpectTotalCount(kPerThumbnailMemoryUsageHistogram, 4); - histogram_tester_.ExpectTotalCount(kTotalMemoryUsageHistogram, 2); -} - -TEST_F(ThumbnailStatsTrackerTest, AlwaysLogsTotal) { - histogram_tester_.ExpectTotalCount(kPerThumbnailMemoryUsageHistogram, 0); - histogram_tester_.ExpectUniqueSample(kTotalMemoryUsageHistogram, 0, 0); - - AdvanceToNextReport(); - histogram_tester_.ExpectTotalCount(kPerThumbnailMemoryUsageHistogram, 0); - histogram_tester_.ExpectUniqueSample(kTotalMemoryUsageHistogram, 0, 1); - - AdvanceToNextReport(); - histogram_tester_.ExpectTotalCount(kPerThumbnailMemoryUsageHistogram, 0); - histogram_tester_.ExpectUniqueSample(kTotalMemoryUsageHistogram, 0, 2); -} - -TEST_F(ThumbnailStatsTrackerTest, RecordedMemoryUsageIsCorrect) { - ThumbnailOwner thumbnail_1; - AssignThumbnailBitmapAndWait(thumbnail_1.Get(), - CreateRandomBitmapOfSize(200, 150)); - size_t thumbnail_1_size_kb = - thumbnail_1.Get()->GetCompressedDataSizeInBytes() / 1024; - - AdvanceToNextReport(); - histogram_tester_.ExpectBucketCount(kPerThumbnailMemoryUsageHistogram, - thumbnail_1_size_kb, 1); - histogram_tester_.ExpectBucketCount(kTotalMemoryUsageHistogram, - thumbnail_1_size_kb, 1); - - ThumbnailOwner thumbnail_2; - AssignThumbnailBitmapAndWait(thumbnail_2.Get(), - CreateRandomBitmapOfSize(100, 100)); - size_t thumbnail_2_size_kb = - thumbnail_2.Get()->GetCompressedDataSizeInBytes() / 1024; - - // This test won't work if the sizes are the same. While it's possible - // that the two randomly generated bitmaps will compress to the same - // size, the odds are astronomically low. - ASSERT_NE(thumbnail_1_size_kb, thumbnail_2_size_kb); - - AdvanceToNextReport(); - histogram_tester_.ExpectBucketCount(kPerThumbnailMemoryUsageHistogram, - thumbnail_1_size_kb, 2); - histogram_tester_.ExpectBucketCount(kPerThumbnailMemoryUsageHistogram, - thumbnail_2_size_kb, 1); - histogram_tester_.ExpectBucketCount(kTotalMemoryUsageHistogram, - thumbnail_1_size_kb, 1); - histogram_tester_.ExpectBucketCount( - kTotalMemoryUsageHistogram, thumbnail_1_size_kb + thumbnail_2_size_kb, 1); -}
diff --git a/chrome/browser/ui/views/apps/chrome_native_app_window_views_aura_ash.cc b/chrome/browser/ui/views/apps/chrome_native_app_window_views_aura_ash.cc index 3f2dabaa..f42f0dd 100644 --- a/chrome/browser/ui/views/apps/chrome_native_app_window_views_aura_ash.cc +++ b/chrome/browser/ui/views/apps/chrome_native_app_window_views_aura_ash.cc
@@ -16,7 +16,6 @@ #include "ash/public/cpp/tablet_mode.h" #include "ash/public/cpp/window_backdrop.h" #include "ash/public/cpp/window_properties.h" -#include "ash/public/cpp/window_state_type.h" #include "base/bind.h" #include "base/logging.h" #include "chrome/browser/apps/app_service/app_service_proxy.h" @@ -32,6 +31,7 @@ #include "chrome/common/chrome_features.h" #include "chrome/common/extensions/extension_constants.h" #include "chromeos/ui/base/chromeos_ui_constants.h" +#include "chromeos/ui/base/window_state_type.h" #include "components/session_manager/core/session_manager.h" #include "extensions/browser/app_window/app_delegate.h" #include "extensions/common/constants.h" @@ -205,7 +205,7 @@ if (GetNativeWindow()->GetProperty(ash::kRestoreBoundsOverrideKey)) { // If an override is given, use that restore state, unless the window is in // immersive fullscreen. - restore_state = ash::ToWindowShowState(GetNativeWindow()->GetProperty( + restore_state = chromeos::ToWindowShowState(GetNativeWindow()->GetProperty( ash::kRestoreWindowStateTypeOverrideKey)); is_fullscreen = restore_state == ui::SHOW_STATE_FULLSCREEN; } else { @@ -469,7 +469,7 @@ void ChromeNativeAppWindowViewsAuraAsh::OnPostWindowStateTypeChange( ash::WindowState* window_state, - ash::WindowStateType old_type) { + chromeos::WindowStateType old_type) { DCHECK(!IsFrameless()); DCHECK_EQ(GetNativeWindow(), window_state->window()); if (window_state->IsFullscreen() != app_window()->IsFullscreen()) {
diff --git a/chrome/browser/ui/views/apps/chrome_native_app_window_views_aura_ash.h b/chrome/browser/ui/views/apps/chrome_native_app_window_views_aura_ash.h index 5bc5bca..c95feaa 100644 --- a/chrome/browser/ui/views/apps/chrome_native_app_window_views_aura_ash.h +++ b/chrome/browser/ui/views/apps/chrome_native_app_window_views_aura_ash.h
@@ -130,7 +130,7 @@ // ash::WindowStateObserver: void OnPostWindowStateTypeChange(ash::WindowState* window_state, - ash::WindowStateType old_type) override; + chromeos::WindowStateType old_type) override; // aura::WindowObserver: void OnWindowPropertyChanged(aura::Window* window,
diff --git a/chrome/browser/ui/views/frame/browser_frame_ash.cc b/chrome/browser/ui/views/frame/browser_frame_ash.cc index 623a8d0d..36ec6e0 100644 --- a/chrome/browser/ui/views/frame/browser_frame_ash.cc +++ b/chrome/browser/ui/views/frame/browser_frame_ash.cc
@@ -7,7 +7,6 @@ #include <memory> #include "ash/public/cpp/window_properties.h" -#include "ash/public/cpp/window_state_type.h" #include "ash/shell.h" #include "ash/wm/window_properties.h" #include "ash/wm/window_state.h" @@ -18,6 +17,7 @@ #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/views/frame/browser_view.h" +#include "chromeos/ui/base/window_state_type.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/window.h" #include "ui/aura/window_observer.h" @@ -110,7 +110,7 @@ if (override_bounds && !override_bounds->IsEmpty()) { *bounds = *override_bounds; *show_state = - ash::ToWindowShowState(GetWidget()->GetNativeWindow()->GetProperty( + chromeos::ToWindowShowState(GetWidget()->GetNativeWindow()->GetProperty( ash::kRestoreWindowStateTypeOverrideKey)); } else { *bounds = GetWidget()->GetRestoredBounds();
diff --git a/chrome/browser/ui/views/frame/browser_frame_header_ash.cc b/chrome/browser/ui/views/frame/browser_frame_header_ash.cc index 07064be..90f0bdc0 100644 --- a/chrome/browser/ui/views/frame/browser_frame_header_ash.cc +++ b/chrome/browser/ui/views/frame/browser_frame_header_ash.cc
@@ -9,9 +9,9 @@ #include "ash/public/cpp/frame_utils.h" #include "ash/public/cpp/tablet_mode.h" #include "ash/public/cpp/window_properties.h" -#include "ash/public/cpp/window_state_type.h" #include "base/check.h" #include "chrome/app/vector_icons/vector_icons.h" +#include "chromeos/ui/base/window_state_type.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkColor.h" #include "third_party/skia/include/core/SkPaint.h" @@ -176,9 +176,9 @@ gfx::ImageSkia frame_overlay_image = appearance_provider_->GetFrameHeaderOverlayImage(active); - ash::WindowStateType state_type = + chromeos::WindowStateType state_type = target_widget()->GetNativeWindow()->GetProperty(ash::kWindowStateTypeKey); - int corner_radius = ash::IsNormalWindowStateType(state_type) + int corner_radius = chromeos::IsNormalWindowStateType(state_type) ? ash::kTopCornerRadiusWhenRestored : 0;
diff --git a/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.cc b/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.cc index 9978f1cf..37cd7ebc 100644 --- a/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.cc +++ b/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.cc
@@ -12,7 +12,6 @@ #include "ash/public/cpp/frame_utils.h" #include "ash/public/cpp/tablet_mode.h" #include "ash/public/cpp/window_properties.h" -#include "ash/public/cpp/window_state_type.h" #include "ash/wm/window_util.h" #include "base/metrics/user_metrics.h" #include "base/strings/utf_string_conversions.h" @@ -40,6 +39,7 @@ #include "chromeos/constants/chromeos_features.h" #include "chromeos/ui/base/chromeos_ui_constants.h" #include "chromeos/ui/base/window_properties.h" +#include "chromeos/ui/base/window_state_type.h" #include "content/public/browser/web_contents.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/accessibility/ax_enums.mojom.h"
diff --git a/chrome/browser/ui/views/frame/browser_view.cc b/chrome/browser/ui/views/frame/browser_view.cc index cd12f4c..1b79877 100644 --- a/chrome/browser/ui/views/frame/browser_view.cc +++ b/chrome/browser/ui/views/frame/browser_view.cc
@@ -3015,7 +3015,7 @@ void BrowserView::MaybeInitializeWebUITabStrip() { #if BUILDFLAG(ENABLE_WEBUI_TAB_STRIP) TRACE_EVENT0("ui", "BrowserView::MaybeInitializeWebUITabStrip"); - if (browser_->SupportsWindowFeature(Browser::FEATURE_TABSTRIP) && + if (browser_->CanSupportWindowFeature(Browser::FEATURE_TABSTRIP) && WebUITabStripContainerView::UseTouchableTabStrip(browser_.get())) { if (!webui_tab_strip_) { // We use |contents_container_| here so that enabling or disabling
diff --git a/chrome/browser/ui/views/global_media_controls/media_notification_device_selector_view.cc b/chrome/browser/ui/views/global_media_controls/media_notification_device_selector_view.cc index 58a72769..7d0adb50 100644 --- a/chrome/browser/ui/views/global_media_controls/media_notification_device_selector_view.cc +++ b/chrome/browser/ui/views/global_media_controls/media_notification_device_selector_view.cc
@@ -361,6 +361,8 @@ device_entry_ui_map_[device_entry_view->tag()] = device_entry_view.get(); device_entry_views_container_->AddChildView(std::move(device_entry_view)); } + device_entry_views_container_->Layout(); + UpdateVisibility(); }
diff --git a/chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.cc b/chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.cc index 5464968..9d744d67 100644 --- a/chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.cc +++ b/chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.cc
@@ -242,6 +242,13 @@ } OmniboxResultView* OmniboxPopupContentsView::GetSelectedResultView() { + // We can't return the native result view if we are using WebUI. + // TODO(tommycli): Ideally this is handled higher up the callstack. + // Callers to OmniboxPopupContentsView should not try to access child views, + // but rather should interact with OmniboxPopupModel instead. + if (base::FeatureList::IsEnabled(omnibox::kWebUIOmniboxPopup)) + return nullptr; + size_t selected_line = model_->selected_line(); if (selected_line == OmniboxPopupModel::kNoMatch) return nullptr;
diff --git a/chrome/browser/ui/views/tabs/tab_drag_controller.cc b/chrome/browser/ui/views/tabs/tab_drag_controller.cc index f4da075..6cb317f 100644 --- a/chrome/browser/ui/views/tabs/tab_drag_controller.cc +++ b/chrome/browser/ui/views/tabs/tab_drag_controller.cc
@@ -54,8 +54,8 @@ #include "ash/public/cpp/ash_features.h" #include "ash/public/cpp/tablet_mode.h" #include "ash/public/cpp/window_properties.h" // nogncheck -#include "ash/public/cpp/window_state_type.h" // nogncheck #include "chromeos/ui/base/window_properties.h" +#include "chromeos/ui/base/window_state_type.h" // nogncheck #include "ui/aura/window_delegate.h" #include "ui/wm/core/coordinate_conversion.h" #endif @@ -99,11 +99,11 @@ // Returns true if |context| browser window is snapped. bool IsSnapped(const TabDragContext* context) { DCHECK(context); - ash::WindowStateType type = + chromeos::WindowStateType type = GetWindowForTabDraggingProperties(context)->GetProperty( ash::kWindowStateTypeKey); - return type == ash::WindowStateType::kLeftSnapped || - type == ash::WindowStateType::kRightSnapped; + return type == chromeos::WindowStateType::kLeftSnapped || + type == chromeos::WindowStateType::kRightSnapped; } // In Chrome OS tablet mode, when dragging a tab/tabs around, the desired
diff --git a/chrome/browser/ui/views/tabs/tab_strip.cc b/chrome/browser/ui/views/tabs/tab_strip.cc index 88114a5..ae04a3a 100644 --- a/chrome/browser/ui/views/tabs/tab_strip.cc +++ b/chrome/browser/ui/views/tabs/tab_strip.cc
@@ -3646,11 +3646,19 @@ const int extra_vertical_space = GetLayoutConstant(TAB_HEIGHT) - GetLayoutConstant(TABSTRIP_TOOLBAR_OVERLAP) - NewTabButton::kButtonSize.height(); + + // Extend the border of the tab controls such that it extends to the top of + // the tabstrip bounds. This is essential to ensure they targetable on the + // edge of the screen when in fullscreen mode and ensures the buttons abide by + // the correct Fitt's Law behavior (https://crbug.com/1136557). + const gfx::Insets button_insets(extra_vertical_space / 2, 0, 0, 0); + new_tab_button_->SetBorder(views::CreateEmptyBorder(button_insets)); + if (tab_search_button_) + tab_search_button_->SetBorder(views::CreateEmptyBorder(button_insets)); + constexpr int kHorizontalInset = 8; - // TODO(tluk): Investigate whether this should apply to the |new_tab_button_| - // or the |tab_controls_container_|. - tab_controls_container_->SetBorder(views::CreateEmptyBorder(gfx::Insets( - extra_vertical_space / 2, kHorizontalInset, 0, kHorizontalInset))); + tab_controls_container_->SetBorder(views::CreateEmptyBorder( + gfx::Insets(0, kHorizontalInset, 0, kHorizontalInset))); } void TabStrip::OnTabSlotAnimationProgressed(TabSlotView* view) {
diff --git a/chrome/browser/ui/views/tabs/tab_strip_unittest.cc b/chrome/browser/ui/views/tabs/tab_strip_unittest.cc index 0ce7ae50..69757df 100644 --- a/chrome/browser/ui/views/tabs/tab_strip_unittest.cc +++ b/chrome/browser/ui/views/tabs/tab_strip_unittest.cc
@@ -138,6 +138,10 @@ return tab->icon_->ShowingAttentionIndicator(); } + views::View* tab_controls_container() { + return tab_strip_->tab_controls_container_; + } + // Checks whether |tab| contains |point_in_tabstrip_coords|, where the point // is in |tab_strip_| coordinates. bool IsPointInTab(Tab* tab, const gfx::Point& point_in_tabstrip_coords) { @@ -1336,4 +1340,31 @@ } } +// We want to make sure that the new tab button sits flush with the top of the +// tab strip. This is important in ensuring that we maximise the targetable area +// of the new tab button and users are able to hit the new tab button when the +// tab strip is flush with the top of the screen when the window is maximized +// (https://crbug.com/1136557). +TEST_P(TabStripTest, NewTabButtonFlushWithTopOfTabStrip) { + tab_strip_parent_->SetBounds(0, 0, 1000, 100); + controller_->AddTab(0, true); + + AnimateToIdealBounds(); + + // |tab_controls_container_| should sit flush with the top of the tab strip. + EXPECT_EQ(0, tab_strip_->tab_controls_container_ideal_bounds().y()); + + // The new tab button should sit flush with the top of the + // |tab_controls_container_|. + EXPECT_EQ(0, tab_strip_->new_tab_button()->bounds().y()); + + // The new tab button should be positioned flush with the top of the tab + // strip. + gfx::RectF ntb_in_child_coords_f(tab_strip_->new_tab_button()->bounds()); + views::View::ConvertRectToTarget(tab_controls_container(), tab_strip_, + &ntb_in_child_coords_f); + gfx::Rect ntb_in_child_coords = gfx::ToEnclosingRect(ntb_in_child_coords_f); + EXPECT_EQ(0, ntb_in_child_coords.y()); +} + INSTANTIATE_TEST_SUITE_P(All, TabStripTest, ::testing::Values(false, true));
diff --git a/chrome/browser/ui/webui/extensions/extensions_ui.cc b/chrome/browser/ui/webui/extensions/extensions_ui.cc index 7768fb19..91f2cd08 100644 --- a/chrome/browser/ui/webui/extensions/extensions_ui.cc +++ b/chrome/browser/ui/webui/extensions/extensions_ui.cc
@@ -59,11 +59,6 @@ constexpr char kShowActivityLogKey[] = "showActivityLog"; constexpr char kLoadTimeClassesKey[] = "loadTimeClasses"; -#if !BUILDFLAG(OPTIMIZE_WEBUI) -constexpr char kGeneratedPath[] = - "@out_folder@/gen/chrome/browser/resources/extensions/preprocessed/"; -#endif - std::string GetLoadTimeClasses(bool in_dev_mode) { return in_dev_mode ? "in-dev-mode" : std::string(); } @@ -82,7 +77,7 @@ #else webui::SetupWebUIDataSource( source, base::make_span(kExtensionsResources, kExtensionsResourcesSize), - kGeneratedPath, IDR_EXTENSIONS_EXTENSIONS_HTML); + "", IDR_EXTENSIONS_EXTENSIONS_HTML); #endif static constexpr webui::LocalizedString kLocalizedStrings[] = {
diff --git a/chrome/browser/ui/webui/nearby_internals/nearby_internals_ui_trigger_handler.cc b/chrome/browser/ui/webui/nearby_internals/nearby_internals_ui_trigger_handler.cc index 26215fcf..4bec9d0 100644 --- a/chrome/browser/ui/webui/nearby_internals/nearby_internals_ui_trigger_handler.cc +++ b/chrome/browser/ui/webui/nearby_internals/nearby_internals_ui_trigger_handler.cc
@@ -13,7 +13,7 @@ #include "chrome/browser/nearby_sharing/logging/logging.h" #include "chrome/browser/nearby_sharing/nearby_sharing_service_factory.h" #include "chrome/browser/nearby_sharing/text_attachment.h" -#include "chrome/services/sharing/public/mojom/nearby_share_target_types.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_share_target_types.mojom.h" namespace {
diff --git a/chrome/browser/ui/webui/nearby_share/BUILD.gn b/chrome/browser/ui/webui/nearby_share/BUILD.gn index 087f484..c709cfcf 100644 --- a/chrome/browser/ui/webui/nearby_share/BUILD.gn +++ b/chrome/browser/ui/webui/nearby_share/BUILD.gn
@@ -10,7 +10,7 @@ sources = [ "nearby_share.mojom" ] public_deps = [ - "//chrome/services/sharing/public/mojom:nearby_share_target_types", + "//chromeos/services/nearby/public/mojom:nearby_share_target_types", "//mojo/public/mojom/base", ]
diff --git a/chrome/browser/ui/webui/nearby_share/nearby_share.mojom b/chrome/browser/ui/webui/nearby_share/nearby_share.mojom index d657b3c..895425b 100644 --- a/chrome/browser/ui/webui/nearby_share/nearby_share.mojom +++ b/chrome/browser/ui/webui/nearby_share/nearby_share.mojom
@@ -4,7 +4,7 @@ module nearby_share.mojom; -import "chrome/services/sharing/public/mojom/nearby_share_target_types.mojom"; +import "chromeos/services/nearby/public/mojom/nearby_share_target_types.mojom"; import "mojo/public/mojom/base/unguessable_token.mojom"; // Describes a nearby device that is able to receive data via Nearby Share.
diff --git a/chrome/browser/ui/webui/print_preview/print_preview_ui.cc b/chrome/browser/ui/webui/print_preview/print_preview_ui.cc index 4845211..9b94726 100644 --- a/chrome/browser/ui/webui/print_preview/print_preview_ui.cc +++ b/chrome/browser/ui/webui/print_preview/print_preview_ui.cc
@@ -88,11 +88,6 @@ const char kBasicPrintShortcut[] = "(Ctrl+Shift+P)"; #endif -#if !BUILDFLAG(OPTIMIZE_WEBUI) -constexpr char kGeneratedPath[] = - "@out_folder@/gen/chrome/browser/resources/print_preview/preprocessed/"; -#endif - PrintPreviewUI::TestDelegate* g_test_delegate = nullptr; void StopWorker(int document_cookie) { @@ -478,8 +473,8 @@ #else webui::SetupWebUIDataSource( source, - base::make_span(kPrintPreviewResources, kPrintPreviewResourcesSize), - kGeneratedPath, IDR_PRINT_PREVIEW_PRINT_PREVIEW_HTML); + base::make_span(kPrintPreviewResources, kPrintPreviewResourcesSize), "", + IDR_PRINT_PREVIEW_PRINT_PREVIEW_HTML); #endif AddPrintPreviewStrings(source); SetupPrintPreviewPlugin(source);
diff --git a/chrome/browser/ui/webui/settings/chromeos/bluetooth_section.cc b/chrome/browser/ui/webui/settings/chromeos/bluetooth_section.cc index 473c21a2..819a030b 100644 --- a/chrome/browser/ui/webui/settings/chromeos/bluetooth_section.cc +++ b/chrome/browser/ui/webui/settings/chromeos/bluetooth_section.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/ui/webui/settings/chromeos/bluetooth_section.h" #include "base/bind.h" +#include "base/metrics/histogram_functions.h" #include "base/no_destructor.h" #include "chrome/browser/ui/webui/chromeos/bluetooth_dialog_localized_strings_provider.h" #include "chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom.h" @@ -209,8 +210,15 @@ bool BluetoothSection::LogMetric(mojom::Setting setting, base::Value& value) const { - // Unimplemented. - return false; + switch (setting) { + case mojom::Setting::kBluetoothOnOff: + base::UmaHistogramBoolean("ChromeOS.Settings.Bluetooth.BluetoothOnOff", + value.GetBool()); + return true; + + default: + return false; + } } void BluetoothSection::RegisterHierarchy(HierarchyGenerator* generator) const {
diff --git a/chrome/browser/ui/webui/settings/chromeos/fake_os_settings_section.cc b/chrome/browser/ui/webui/settings/chromeos/fake_os_settings_section.cc index 3791dd8..a954d04 100644 --- a/chrome/browser/ui/webui/settings/chromeos/fake_os_settings_section.cc +++ b/chrome/browser/ui/webui/settings/chromeos/fake_os_settings_section.cc
@@ -34,7 +34,8 @@ bool FakeOsSettingsSection::LogMetric(mojom::Setting setting, base::Value& value) const { - return false; + logged_metrics_.push_back(setting); + return true; } std::string FakeOsSettingsSection::ModifySearchResultUrl(
diff --git a/chrome/browser/ui/webui/settings/chromeos/fake_os_settings_section.h b/chrome/browser/ui/webui/settings/chromeos/fake_os_settings_section.h index 36b365f4..3fe1dde1 100644 --- a/chrome/browser/ui/webui/settings/chromeos/fake_os_settings_section.h +++ b/chrome/browser/ui/webui/settings/chromeos/fake_os_settings_section.h
@@ -5,6 +5,9 @@ #ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_FAKE_OS_SETTINGS_SECTION_H_ #define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_FAKE_OS_SETTINGS_SECTION_H_ +#include <utility> +#include <vector> + #include "base/values.h" #include "chrome/browser/ui/webui/settings/chromeos/os_settings_section.h" @@ -21,6 +24,9 @@ FakeOsSettingsSection& operator=(const FakeOsSettingsSection& other) = delete; mojom::Section section() { return section_; } + const std::vector<mojom::Setting>& logged_metrics() const { + return logged_metrics_; + } // OsSettingsSection: void AddLoadTimeData(content::WebUIDataSource* html_source) override {} @@ -50,6 +56,8 @@ private: const mojom::Section section_; + // Use mutable to modify this vector within the overridden const LogMetric. + mutable std::vector<mojom::Setting> logged_metrics_; }; } // namespace settings
diff --git a/chrome/browser/ui/webui/settings/chromeos/os_settings_manager.cc b/chrome/browser/ui/webui/settings/chromeos/os_settings_manager.cc index 47b8ccf..0c08f1e 100644 --- a/chrome/browser/ui/webui/settings/chromeos/os_settings_manager.cc +++ b/chrome/browser/ui/webui/settings/chromeos/os_settings_manager.cc
@@ -45,9 +45,10 @@ identity_manager, android_sms_service, printers_manager)), - settings_user_action_tracker_( - std::make_unique<SettingsUserActionTracker>()), hierarchy_(std::make_unique<Hierarchy>(sections_.get())), + settings_user_action_tracker_( + std::make_unique<SettingsUserActionTracker>(hierarchy_.get(), + sections_.get())), search_handler_( std::make_unique<SearchHandler>(search_tag_registry_.get(), sections_.get(), @@ -71,6 +72,7 @@ // Note: These must be deleted in the opposite order of their creation to // prevent against UAF violations. search_handler_.reset(); + settings_user_action_tracker_.reset(); hierarchy_.reset(); sections_.reset(); search_tag_registry_.reset();
diff --git a/chrome/browser/ui/webui/settings/chromeos/os_settings_manager.h b/chrome/browser/ui/webui/settings/chromeos/os_settings_manager.h index d54a01a..cea0a261 100644 --- a/chrome/browser/ui/webui/settings/chromeos/os_settings_manager.h +++ b/chrome/browser/ui/webui/settings/chromeos/os_settings_manager.h
@@ -124,8 +124,8 @@ std::unique_ptr<SearchTagRegistry> search_tag_registry_; std::unique_ptr<OsSettingsSections> sections_; - std::unique_ptr<SettingsUserActionTracker> settings_user_action_tracker_; std::unique_ptr<Hierarchy> hierarchy_; + std::unique_ptr<SettingsUserActionTracker> settings_user_action_tracker_; std::unique_ptr<SearchHandler> search_handler_; };
diff --git a/chrome/browser/ui/webui/settings/chromeos/search/user_action_recorder.mojom b/chrome/browser/ui/webui/settings/chromeos/search/user_action_recorder.mojom index 1f151fc..1deccb1 100644 --- a/chrome/browser/ui/webui/settings/chromeos/search/user_action_recorder.mojom +++ b/chrome/browser/ui/webui/settings/chromeos/search/user_action_recorder.mojom
@@ -4,6 +4,15 @@ module chromeos.settings.mojom; +import "chrome/browser/ui/webui/settings/chromeos/constants/setting.mojom"; + +// Value for the setting change; can be a bool, int, or string. +union SettingChangeValue { + bool bool_value; + int32 int_value; + string string_value; +}; + // Records user actions within OS settings. Implemented in the browser process; // intended to be called from settings JS. interface UserActionRecorder { @@ -23,6 +32,13 @@ // Records that the user has completed a search attempt. RecordSearch(); - // Records that the user has changed a setting. + // Deprecated; all new usages should use the other RecordSettingChangeValue. + // TODO(https://crbug.com/1133553): remove once migration is complete. RecordSettingChange(); + + // Records that the user has changed a |setting| and the |value| that the + // setting was changed to. |value| can be null when the corresponding + // setting doesn't actually change a value, such as the open wallpaper + // setting. + RecordSettingChangeWithDetails(Setting setting, SettingChangeValue? value); };
diff --git a/chrome/browser/ui/webui/settings/chromeos/settings_user_action_tracker.cc b/chrome/browser/ui/webui/settings/chromeos/settings_user_action_tracker.cc index 7767296..3e3f93eea 100644 --- a/chrome/browser/ui/webui/settings/chromeos/settings_user_action_tracker.cc +++ b/chrome/browser/ui/webui/settings/chromeos/settings_user_action_tracker.cc
@@ -8,11 +8,17 @@ #include <utility> #include "base/bind.h" +#include "base/metrics/histogram_functions.h" +#include "chrome/browser/ui/webui/settings/chromeos/hierarchy.h" +#include "chrome/browser/ui/webui/settings/chromeos/os_settings_sections.h" namespace chromeos { namespace settings { -SettingsUserActionTracker::SettingsUserActionTracker() = default; +SettingsUserActionTracker::SettingsUserActionTracker( + Hierarchy* hierarchy, + OsSettingsSections* sections) + : hierarchy_(hierarchy), sections_(sections) {} SettingsUserActionTracker::~SettingsUserActionTracker() = default; @@ -60,9 +66,35 @@ per_session_tracker_->RecordSearch(); } +// TODO(https://crbug.com/1133553): remove this once migration is complete. void SettingsUserActionTracker::RecordSettingChange() { per_session_tracker_->RecordSettingChange(); } +void SettingsUserActionTracker::RecordSettingChangeWithDetails( + mojom::Setting setting, + mojom::SettingChangeValuePtr value) { + per_session_tracker_->RecordSettingChange(); + + // Get the primary section location of the changed setting and log the metric. + mojom::Section section_id = + hierarchy_->GetSettingMetadata(setting).primary.first; + const OsSettingsSection* section = sections_->GetSection(section_id); + // new_value is initialized as null. Null value is used in cases that don't + // require extra metadata. + base::Value new_value; + if (value->is_bool_value()) { + new_value = base::Value(value->get_bool_value()); + } else if (value->is_int_value()) { + new_value = base::Value(value->get_int_value()); + } else if (value->is_string_value()) { + new_value = base::Value(value->get_string_value()); + } + section->LogMetric(setting, new_value); + + base::UmaHistogramSparse("ChromeOS.Settings.SettingChanged", + static_cast<int>(setting)); +} + } // namespace settings } // namespace chromeos
diff --git a/chrome/browser/ui/webui/settings/chromeos/settings_user_action_tracker.h b/chrome/browser/ui/webui/settings/chromeos/settings_user_action_tracker.h index 73e495c2..bf0fcf6 100644 --- a/chrome/browser/ui/webui/settings/chromeos/settings_user_action_tracker.h +++ b/chrome/browser/ui/webui/settings/chromeos/settings_user_action_tracker.h
@@ -7,6 +7,8 @@ #include <memory> +#include "base/optional.h" +#include "chrome/browser/ui/webui/settings/chromeos/constants/setting.mojom.h" #include "chrome/browser/ui/webui/settings/chromeos/search/per_session_settings_user_action_tracker.h" #include "chrome/browser/ui/webui/settings/chromeos/search/user_action_recorder.mojom.h" #include "mojo/public/cpp/bindings/pending_receiver.h" @@ -15,12 +17,15 @@ namespace chromeos { namespace settings { +class Hierarchy; +class OsSettingsSections; + // Records user actions within Settings. Utilizes a per session tracker that // measures the user's effort required to change a setting. Eventually uses // a per section tracker to record metrics in each section. class SettingsUserActionTracker : public mojom::UserActionRecorder { public: - SettingsUserActionTracker(); + SettingsUserActionTracker(Hierarchy* hierarchy, OsSettingsSections* sections); SettingsUserActionTracker(const SettingsUserActionTracker& other) = delete; SettingsUserActionTracker& operator=(const SettingsUserActionTracker& other) = delete; @@ -30,6 +35,12 @@ mojo::PendingReceiver<mojom::UserActionRecorder> pending_receiver); private: + // For unit tests. + // SettingsUserActionTracker(); + friend class SettingsUserActionTrackerTest; + FRIEND_TEST_ALL_PREFIXES(SettingsUserActionTrackerTest, + TestRecordSettingChanged); + // mojom::UserActionRecorder: void RecordPageFocus() override; void RecordPageBlur() override; @@ -37,12 +48,17 @@ void RecordNavigation() override; void RecordSearch() override; void RecordSettingChange() override; + void RecordSettingChangeWithDetails( + mojom::Setting setting, + mojom::SettingChangeValuePtr value) override; void EndCurrentSession(); void OnBindingDisconnected(); - std::unique_ptr<PerSessionSettingsUserActionTracker> per_session_tracker_; + Hierarchy* hierarchy_; + OsSettingsSections* sections_; + std::unique_ptr<PerSessionSettingsUserActionTracker> per_session_tracker_; mojo::Receiver<mojom::UserActionRecorder> receiver_{this}; };
diff --git a/chrome/browser/ui/webui/settings/chromeos/settings_user_action_tracker_unittest.cc b/chrome/browser/ui/webui/settings/chromeos/settings_user_action_tracker_unittest.cc new file mode 100644 index 0000000..de415ce --- /dev/null +++ b/chrome/browser/ui/webui/settings/chromeos/settings_user_action_tracker_unittest.cc
@@ -0,0 +1,67 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/settings/chromeos/settings_user_action_tracker.h" + +#include "base/test/metrics/histogram_tester.h" +#include "base/values.h" +#include "chrome/browser/ui/webui/settings/chromeos/constants/setting.mojom.h" +#include "chrome/browser/ui/webui/settings/chromeos/fake_hierarchy.h" +#include "chrome/browser/ui/webui/settings/chromeos/fake_os_settings_section.h" +#include "chrome/browser/ui/webui/settings/chromeos/fake_os_settings_sections.h" +#include "chrome/browser/ui/webui/settings/chromeos/search/per_session_settings_user_action_tracker.h" +#include "chrome/browser/ui/webui/settings/chromeos/search/user_action_recorder.mojom.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace chromeos { +namespace settings { + +class SettingsUserActionTrackerTest : public testing::Test { + protected: + SettingsUserActionTrackerTest() + : fake_hierarchy_(&fake_sections_), + tracker_(&fake_hierarchy_, &fake_sections_) { + // Initialize per_session_tracker_ manually since BindInterface is never + // called on tracker_. + tracker_.per_session_tracker_ = + std::make_unique<PerSessionSettingsUserActionTracker>(); + } + ~SettingsUserActionTrackerTest() override = default; + + // testing::Test: + void SetUp() override { + fake_hierarchy_.AddSettingMetadata(mojom::Section::kBluetooth, + mojom::Setting::kBluetoothOnOff); + } + + base::HistogramTester histogram_tester_; + FakeOsSettingsSections fake_sections_; + FakeHierarchy fake_hierarchy_; + SettingsUserActionTracker tracker_; +}; + +TEST_F(SettingsUserActionTrackerTest, TestRecordSettingChanged) { + // Record that the bluetooth enabled setting was toggled off. + tracker_.RecordSettingChangeWithDetails( + mojom::Setting::kBluetoothOnOff, + mojom::SettingChangeValue::NewBoolValue(false)); + + // The umbrella metric for which setting was changed should be updated. Note + // that kBluetoothOnOff has enum value of 100. + histogram_tester_.ExpectTotalCount("ChromeOS.Settings.SettingChanged", + /*count=*/1); + histogram_tester_.ExpectBucketCount("ChromeOS.Settings.SettingChanged", + /*sample=*/100, + /*count=*/1); + + // The LogMetric fn in the Blutooth section should have been called. + const FakeOsSettingsSection* bluetooth_section = + static_cast<const FakeOsSettingsSection*>( + fake_sections_.GetSection(mojom::Section::kBluetooth)); + EXPECT_TRUE(bluetooth_section->logged_metrics().back() == + mojom::Setting::kBluetoothOnOff); +} + +} // namespace settings. +} // namespace chromeos.
diff --git a/chrome/browser/ui/webui/settings/settings_ui.cc b/chrome/browser/ui/webui/settings/settings_ui.cc index 220cc6d..2dbe7166 100644 --- a/chrome/browser/ui/webui/settings/settings_ui.cc +++ b/chrome/browser/ui/webui/settings/settings_ui.cc
@@ -136,11 +136,6 @@ namespace settings { -#if !BUILDFLAG(OPTIMIZE_WEBUI) -constexpr char kGeneratedPath[] = - "@out_folder@/gen/chrome/browser/resources/settings/preprocessed/"; -#endif - // static void SettingsUI::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { @@ -373,7 +368,7 @@ #else webui::SetupWebUIDataSource( html_source, base::make_span(kSettingsResources, kSettingsResourcesSize), - kGeneratedPath, IDR_SETTINGS_SETTINGS_V3_HTML); + "", IDR_SETTINGS_SETTINGS_V3_HTML); #endif AddLocalizedStrings(html_source, profile, web_ui->GetWebContents());
diff --git a/chrome/browser/ui/webui/webui_util.cc b/chrome/browser/ui/webui/webui_util.cc index e27b04b..759432b 100644 --- a/chrome/browser/ui/webui/webui_util.cc +++ b/chrome/browser/ui/webui/webui_util.cc
@@ -43,9 +43,12 @@ const std::string& generated_path, int default_resource) { SetupPolymer3Defaults(source); + // TODO (crbug.com/1132403): Replace usages of |generated_path| with the new + // |resource_path| GRD property, and remove from here. + bool has_gen_path = !generated_path.empty(); for (const GritResourceMap& resource : resources) { std::string path = resource.name; - if (path.rfind(generated_path, 0) == 0) { + if (has_gen_path && path.rfind(generated_path, 0) == 0) { path = path.substr(generated_path.size()); }
diff --git a/chrome/browser/webshare/share_service_browsertest.cc b/chrome/browser/webshare/share_service_browsertest.cc index 36069f3..ff77ffe7 100644 --- a/chrome/browser/webshare/share_service_browsertest.cc +++ b/chrome/browser/webshare/share_service_browsertest.cc
@@ -13,48 +13,17 @@ #include "content/public/test/browser_test_utils.h" #include "net/test/embedded_test_server/embedded_test_server.h" -#if defined(OS_WIN) -#include "chrome/browser/webshare/win/scoped_fake_data_transfer_manager_interop.h" -#endif - class ShareServiceBrowserTest : public InProcessBrowserTest { public: ShareServiceBrowserTest() { feature_list_.InitAndEnableFeature(features::kWebShare); } -#if defined(OS_WIN) - void SetUpOnMainThread() override { - InProcessBrowserTest::SetUpOnMainThread(); - if (IsSupportedEnvironment()) { - scoped_interop_ = - std::make_unique<webshare::ScopedFakeDataTransferManagerInterop>(); - } - } -#endif - - protected: -#if defined(OS_WIN) - bool IsSupportedEnvironment() { - return webshare::ScopedFakeDataTransferManagerInterop:: - IsSupportedEnvironment(); - } -#endif - private: base::test::ScopedFeatureList feature_list_; -#if defined(OS_WIN) - std::unique_ptr<webshare::ScopedFakeDataTransferManagerInterop> - scoped_interop_; -#endif }; IN_PROC_BROWSER_TEST_F(ShareServiceBrowserTest, Text) { -#if defined(OS_WIN) - if (!IsSupportedEnvironment()) - return; -#endif - ASSERT_TRUE(embedded_test_server()->Start()); ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL("/webshare/index.html"));
diff --git a/chrome/browser/webshare/share_service_impl.cc b/chrome/browser/webshare/share_service_impl.cc index fbbcaad6..bf2a4ff 100644 --- a/chrome/browser/webshare/share_service_impl.cc +++ b/chrome/browser/webshare/share_service_impl.cc
@@ -5,7 +5,6 @@ #include "chrome/browser/webshare/share_service_impl.h" #include <algorithm> -#include <memory> #include "base/feature_list.h" #include "base/strings/string_piece.h" @@ -14,10 +13,6 @@ #include "content/public/browser/web_contents.h" #include "mojo/public/cpp/bindings/self_owned_receiver.h" -#if defined(OS_WIN) -#include "chrome/browser/webshare/win/share_operation.h" -#endif - // IsDangerousFilename() and IsDangerousMimeType() should be kept in sync with // //third_party/blink/renderer/modules/webshare/FILE_TYPES.md // //components/browser_ui/webshare/android/java/src/org/chromium/components/browser_ui/webshare/ShareServiceImpl.java @@ -170,17 +165,10 @@ #if defined(OS_CHROMEOS) sharesheet_client_.Share(title, text, share_url, std::move(files), std::move(callback)); -#elif defined(OS_WIN) - auto share_operation = std::make_unique<webshare::ShareOperation>( - title, text, share_url, std::move(files), web_contents); - share_operation->Run(base::BindOnce( - [](std::unique_ptr<webshare::ShareOperation> share_operation, - ShareCallback callback, - blink::mojom::ShareError result) { std::move(callback).Run(result); }, - std::move(share_operation), std::move(callback))); #else - NOTREACHED(); - std::move(callback).Run(blink::mojom::ShareError::INTERNAL_ERROR); + // TODO(crbug.com/1035527): Add implementation for OS_WIN + NOTIMPLEMENTED(); + std::move(callback).Run(blink::mojom::ShareError::OK); #endif }
diff --git a/chrome/browser/webshare/share_service_unittest.cc b/chrome/browser/webshare/share_service_unittest.cc index 1877fc7..4b909d2 100644 --- a/chrome/browser/webshare/share_service_unittest.cc +++ b/chrome/browser/webshare/share_service_unittest.cc
@@ -29,9 +29,6 @@ #include "chrome/browser/sharesheet/sharesheet_types.h" #include "chrome/browser/webshare/chromeos/sharesheet_client.h" #endif -#if defined(OS_WIN) -#include "chrome/browser/webshare/win/scoped_fake_data_transfer_manager_interop.h" -#endif class ShareServiceUnitTest : public ChromeRenderViewHostTestHarness { public: @@ -48,21 +45,8 @@ webshare::SharesheetClient::SetSharesheetCallbackForTesting( base::BindRepeating(&ShareServiceUnitTest::AcceptShareRequest)); #endif -#if defined(OS_WIN) - if (IsSupportedEnvironment()) { - scoped_interop_ = - std::make_unique<webshare::ScopedFakeDataTransferManagerInterop>(); - } -#endif } -#if defined(OS_WIN) - bool IsSupportedEnvironment() { - return webshare::ScopedFakeDataTransferManagerInterop:: - IsSupportedEnvironment(); - } -#endif - ShareError ShareGeneratedFileData(const std::string& extension, const std::string& content_type, unsigned file_length = 100, @@ -139,20 +123,11 @@ } #endif -#if defined(OS_WIN) - std::unique_ptr<webshare::ScopedFakeDataTransferManagerInterop> - scoped_interop_; -#endif base::test::ScopedFeatureList feature_list_; std::unique_ptr<ShareServiceImpl> share_service_; }; TEST_F(ShareServiceUnitTest, FileCount) { -#if defined(OS_WIN) - if (!IsSupportedEnvironment()) - return; -#endif - EXPECT_EQ(ShareError::OK, ShareGeneratedFileData(".txt", "text/plain", 1234, kMaxSharedFileCount)); EXPECT_EQ(ShareError::PERMISSION_DENIED, @@ -197,11 +172,6 @@ } TEST_F(ShareServiceUnitTest, PortableDocumentFormat) { -#if defined(OS_WIN) - if (!IsSupportedEnvironment()) - return; -#endif - // TODO(crbug.com/1006055): Support sharing of pdf files. // The URL will be checked using Safe Browsing. EXPECT_EQ(ShareError::PERMISSION_DENIED,
diff --git a/chrome/browser/webshare/win/fake_data_transfer_manager.cc b/chrome/browser/webshare/win/fake_data_transfer_manager.cc index aa28deb..b038bd29 100644 --- a/chrome/browser/webshare/win/fake_data_transfer_manager.cc +++ b/chrome/browser/webshare/win/fake_data_transfer_manager.cc
@@ -8,7 +8,6 @@ #include "base/bind.h" #include "base/bind_helpers.h" -#include "base/win/scoped_hstring.h" #include "testing/gtest/include/gtest/gtest.h" namespace webshare { @@ -26,8 +25,6 @@ using ABI::Windows::ApplicationModel::DataTransfer::IDataTransferManager; using ABI::Windows::Foundation::DateTime; using ABI::Windows::Foundation::IUriRuntimeClass; -using ABI::Windows::Storage::IStorageFile; -using ABI::Windows::Storage::IStorageItem; using ABI::Windows::Storage::Streams::IRandomAccessStreamReference; using Microsoft::WRL::ActivationFactory; using Microsoft::WRL::ComPtr; @@ -55,9 +52,7 @@ IDataPackagePropertySet, IDataPackagePropertySet3> { public: - FakeDataPackagePropertySet( - FakeDataTransferManager::DataRequestedContent& data_requested_content) - : data_requested_content_(data_requested_content) {} + FakeDataPackagePropertySet() = default; FakeDataPackagePropertySet(const FakeDataPackagePropertySet&) = delete; FakeDataPackagePropertySet& operator=(const FakeDataPackagePropertySet&) = delete; @@ -95,11 +90,7 @@ IFACEMETHODIMP put_Thumbnail(IRandomAccessStreamReference* value) override { return S_OK; } - IFACEMETHODIMP put_Title(HSTRING value) override { - base::win::ScopedHString wrapped_value(value); - data_requested_content_.title = wrapped_value.GetAsUTF8(); - return S_OK; - } + IFACEMETHODIMP put_Title(HSTRING value) override { return S_OK; } // IDataPackagePropertySet3 IFACEMETHODIMP get_EnterpriseId(HSTRING* value) override { @@ -107,9 +98,6 @@ return E_NOTIMPL; } IFACEMETHODIMP put_EnterpriseId(HSTRING value) override { return S_OK; } - - private: - FakeDataTransferManager::DataRequestedContent& data_requested_content_; }; class FakeDataPackage @@ -117,9 +105,7 @@ IDataPackage, IDataPackage2> { public: - FakeDataPackage( - FakeDataTransferManager::DataRequestedContent& data_requested_content) - : data_requested_content_(data_requested_content) {} + FakeDataPackage() = default; FakeDataPackage(const FakeDataPackage&) = delete; FakeDataPackage& operator=(const FakeDataPackage&) = delete; ~FakeDataPackage() override { @@ -149,7 +135,7 @@ } IFACEMETHODIMP get_Properties(IDataPackagePropertySet** value) override { if (!properties_) - properties_ = Make<FakeDataPackagePropertySet>(data_requested_content_); + properties_ = Make<FakeDataPackagePropertySet>(); *value = properties_.Get(); properties_->AddRef(); return S_OK; @@ -186,61 +172,15 @@ } IFACEMETHODIMP SetHtmlFormat(HSTRING value) override { return S_OK; } IFACEMETHODIMP SetRtf(HSTRING value) override { return S_OK; } - IFACEMETHODIMP SetText(HSTRING value) override { - base::win::ScopedHString wrapped_value(value); - data_requested_content_.text = wrapped_value.GetAsUTF8(); - return S_OK; - } + IFACEMETHODIMP SetText(HSTRING value) override { return S_OK; } IFACEMETHODIMP SetStorageItems(StorageItems* value, boolean readOnly) override { - EXPECT_TRUE(readOnly); - return SetStorageItemsReadOnly(value); + return S_OK; } IFACEMETHODIMP SetStorageItemsReadOnly(StorageItems* value) override { - ComPtr<ABI::Windows::Foundation::Collections::IIterator<IStorageItem*>> - iterator; - HRESULT hr = value->First(&iterator); - if (FAILED(hr)) - return hr; - boolean has_current; - hr = iterator->get_HasCurrent(&has_current); - if (FAILED(hr)) - return hr; - while (has_current == TRUE) { - ComPtr<IStorageItem> storage_item; - hr = iterator->get_Current(&storage_item); - if (FAILED(hr)) - return hr; - - HSTRING name; - hr = storage_item->get_Name(&name); - base::win::ScopedHString wrapped_name(name); - if (FAILED(hr)) - return hr; - - ComPtr<IStorageFile> storage_file; - hr = storage_item.As(&storage_file); - if (FAILED(hr)) - return hr; - - FakeDataTransferManager::DataRequestedFile file; - file.name = wrapped_name.GetAsUTF8(); - file.file = storage_file; - data_requested_content_.files.push_back(std::move(file)); - - hr = iterator->MoveNext(&has_current); - if (FAILED(hr)) - return hr; - } return S_OK; } - IFACEMETHODIMP SetUri(IUriRuntimeClass* value) override { - HSTRING raw_uri; - value->get_RawUri(&raw_uri); - base::win::ScopedHString wrapped_value(raw_uri); - data_requested_content_.uri = wrapped_value.GetAsUTF8(); - return S_OK; - } + IFACEMETHODIMP SetUri(IUriRuntimeClass* value) override { return S_OK; } // IDataPackage2 IFACEMETHODIMP SetApplicationLink(IUriRuntimeClass* value) override { @@ -249,37 +189,23 @@ IFACEMETHODIMP SetWebLink(IUriRuntimeClass* value) override { return S_OK; } private: - FakeDataTransferManager::DataRequestedContent& data_requested_content_; ComPtr<IDataPackagePropertySet> properties_; }; class FakeDataRequest : public RuntimeClass<RuntimeClassFlags<WinRtClassicComMix>, IDataRequest> { public: - struct FakeDataRequestDeferral - : public RuntimeClass<RuntimeClassFlags<WinRtClassicComMix>, - IDataRequestDeferral> { - public: - explicit FakeDataRequestDeferral(FakeDataRequest* data_request) - : data_request_(data_request) {} - FakeDataRequestDeferral(const FakeDataRequestDeferral&) = delete; - FakeDataRequestDeferral& operator=(const FakeDataRequestDeferral&) = delete; - - // IDataRequestDeferral - IFACEMETHODIMP Complete() override { - data_request_->RunPostDataRequestedCallbackImpl(); - return S_OK; - } - - private: - ComPtr<FakeDataRequest> data_request_; - }; - - FakeDataRequest(FakeDataTransferManager::PostDataRequestedCallback - post_data_requested_callback) - : post_data_requested_callback_(post_data_requested_callback) {} + FakeDataRequest() = default; FakeDataRequest(const FakeDataRequest&) = delete; FakeDataRequest& operator=(const FakeDataRequest&) = delete; + ~FakeDataRequest() override { + // Though it is technically legal for consuming code to hold on to the + // DataPackage past the lifetime of the DataRequest, there is no good + // reason to do so, so any lingering references presumably point to a + // coding error. + if (data_package_) + EXPECT_EQ(0u, data_package_.Reset()); + } // IDataRequest IFACEMETHODIMP FailWithDisplayText(HSTRING value) override { @@ -288,7 +214,7 @@ } IFACEMETHODIMP get_Data(IDataPackage** value) override { if (!data_package_) - data_package_ = Make<FakeDataPackage>(data_requested_content_); + data_package_ = Make<FakeDataPackage>(); *value = data_package_.Get(); data_package_->AddRef(); return S_OK; @@ -299,83 +225,53 @@ return E_NOTIMPL; } IFACEMETHODIMP GetDeferral(IDataRequestDeferral** value) override { - if (!data_request_deferral_) - data_request_deferral_ = Make<FakeDataRequestDeferral>(this); - *value = data_request_deferral_.Get(); - data_request_deferral_->AddRef(); - return S_OK; + NOTREACHED(); + return E_NOTIMPL; } IFACEMETHODIMP put_Data(IDataPackage* value) override { data_package_ = value; return S_OK; } - void RunPostDataRequestedCallback() { - // If there is not a deferral trigger the callback right away, otherwise it - // will be triggered when the deferral is complete - if (!data_request_deferral_) - RunPostDataRequestedCallbackImpl(); - } - private: - void RunPostDataRequestedCallbackImpl() { - post_data_requested_callback_.Run(data_requested_content_); - } - ComPtr<IDataPackage> data_package_; - ComPtr<FakeDataRequestDeferral> data_request_deferral_; - FakeDataTransferManager::DataRequestedContent data_requested_content_; - FakeDataTransferManager::PostDataRequestedCallback - post_data_requested_callback_; }; class FakeDataRequestedEventArgs : public RuntimeClass<RuntimeClassFlags<WinRtClassicComMix>, IDataRequestedEventArgs> { public: - FakeDataRequestedEventArgs(FakeDataTransferManager::PostDataRequestedCallback - post_data_requested_callback) - : post_data_requested_callback_(post_data_requested_callback) {} + FakeDataRequestedEventArgs() = default; FakeDataRequestedEventArgs(const FakeDataRequestedEventArgs&) = delete; FakeDataRequestedEventArgs& operator=(const FakeDataRequestedEventArgs&) = delete; + ~FakeDataRequestedEventArgs() override { + // Though it is technically legal for consuming code to hold on to the + // DataRequest past the lifetime of the DataRequestedEventArgs, there is + // no good reason to do so, so any lingering references presumably point + // to a coding error. + if (data_request_) + EXPECT_EQ(0u, data_request_.Reset()); + } // IDataRequestedEventArgs IFACEMETHODIMP get_Request(IDataRequest** value) override { if (!data_request_) - data_request_ = Make<FakeDataRequest>(post_data_requested_callback_); + data_request_ = Make<FakeDataRequest>(); *value = data_request_.Get(); data_request_->AddRef(); return S_OK; } - void RunPostDataRequestedCallback() { - if (data_request_) - data_request_->RunPostDataRequestedCallback(); - } - private: - ComPtr<FakeDataRequest> data_request_; - FakeDataTransferManager::PostDataRequestedCallback - post_data_requested_callback_; + ComPtr<IDataRequest> data_request_; }; } // namespace -FakeDataTransferManager::FakeDataTransferManager() { - post_data_requested_callback_ = base::DoNothing(); -} +FakeDataTransferManager::FakeDataTransferManager() = default; FakeDataTransferManager::~FakeDataTransferManager() = default; -FakeDataTransferManager::DataRequestedFile::DataRequestedFile() = default; -FakeDataTransferManager::DataRequestedFile::DataRequestedFile( - FakeDataTransferManager::DataRequestedFile&&) = default; -FakeDataTransferManager::DataRequestedFile::~DataRequestedFile() = default; - -FakeDataTransferManager::DataRequestedContent::DataRequestedContent() = default; -FakeDataTransferManager::DataRequestedContent::~DataRequestedContent() = - default; - IFACEMETHODIMP FakeDataTransferManager::add_DataRequested( DataRequestedEventHandler* event_handler, @@ -427,14 +323,13 @@ // Though multiple handlers may be registered for this event, only the // latest is invoked by the OS and then the event is considered handled. auto handler = data_requested_event_handlers_.back().event_handler_; - ComPtr<FakeDataTransferManager> self = this; + ComPtr<IDataTransferManager> self = this; return base::BindOnce( - [](ComPtr<FakeDataTransferManager> self, + [](ComPtr<IDataTransferManager> self, ComPtr<DataRequestedEventHandler> handler) { - auto event_args = Make<FakeDataRequestedEventArgs>( - self->post_data_requested_callback_); + ComPtr<IDataRequestedEventArgs> event_args = + Make<FakeDataRequestedEventArgs>(); handler->Invoke(self.Get(), event_args.Get()); - event_args->RunPostDataRequestedCallback(); }, self, handler); } @@ -443,11 +338,6 @@ return !data_requested_event_handlers_.empty(); } -void FakeDataTransferManager::SetPostDataRequestedCallback( - PostDataRequestedCallback post_data_requested_callback) { - post_data_requested_callback_ = std::move(post_data_requested_callback); -} - FakeDataTransferManager::DataRequestedHandlerEntry:: DataRequestedHandlerEntry() = default; FakeDataTransferManager::DataRequestedHandlerEntry::DataRequestedHandlerEntry(
diff --git a/chrome/browser/webshare/win/fake_data_transfer_manager.h b/chrome/browser/webshare/win/fake_data_transfer_manager.h index fc82453..08526a47 100644 --- a/chrome/browser/webshare/win/fake_data_transfer_manager.h +++ b/chrome/browser/webshare/win/fake_data_transfer_manager.h
@@ -9,45 +9,16 @@ #include <wrl/implements.h> #include <vector> -#include "base/callback.h" +#include "base/callback_forward.h" namespace webshare { // Provides an implementation of IDataTransferManager for use in GTests. -class __declspec(uuid("53CA4C00-6F19-40C1-A740-F66510E2DB40")) - FakeDataTransferManager +class FakeDataTransferManager : public Microsoft::WRL::RuntimeClass< Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::WinRtClassicComMix>, ABI::Windows::ApplicationModel::DataTransfer::IDataTransferManager> { public: - // Represents a file surfaced to a DataRequested event - struct DataRequestedFile { - DataRequestedFile(); - DataRequestedFile(const DataRequestedFile&) = delete; - DataRequestedFile& operator=(const DataRequestedFile&) = delete; - DataRequestedFile(DataRequestedFile&&); - ~DataRequestedFile(); - - std::string name; - Microsoft::WRL::ComPtr<ABI::Windows::Storage::IStorageFile> file; - }; - - // Represents the content surfaced to a DataRequested event - struct DataRequestedContent { - DataRequestedContent(); - DataRequestedContent(const DataRequestedContent&) = delete; - DataRequestedContent& operator=(const DataRequestedContent&) = delete; - ~DataRequestedContent(); - - std::string text; - std::string title; - std::string uri; - std::vector<DataRequestedFile> files; - }; - - using PostDataRequestedCallback = - base::RepeatingCallback<void(const DataRequestedContent&)>; - FakeDataTransferManager(); FakeDataTransferManager(const FakeDataTransferManager&) = delete; FakeDataTransferManager& operator=(const FakeDataTransferManager&) = delete; @@ -76,11 +47,6 @@ bool HasDataRequestedListener(); - // Sets a callback that will be invoked after any DataRequested event is - // triggered and passed the content supplied by the DataRequested handler - void SetPostDataRequestedCallback( - PostDataRequestedCallback post_data_requested_callback); - private: struct DataRequestedHandlerEntry { DataRequestedHandlerEntry(); @@ -95,7 +61,6 @@ std::vector<DataRequestedHandlerEntry> data_requested_event_handlers_; int64_t latest_token_value_ = 0; - PostDataRequestedCallback post_data_requested_callback_; }; } // namespace webshare
diff --git a/chrome/browser/webshare/win/scoped_fake_data_transfer_manager_interop.cc b/chrome/browser/webshare/win/scoped_fake_data_transfer_manager_interop.cc index 805a543..7dadf63 100644 --- a/chrome/browser/webshare/win/scoped_fake_data_transfer_manager_interop.cc +++ b/chrome/browser/webshare/win/scoped_fake_data_transfer_manager_interop.cc
@@ -11,7 +11,6 @@ #include "base/win/com_init_util.h" #include "base/win/core_winrt_util.h" #include "base/win/win_util.h" -#include "base/win/windows_version.h" #include "chrome/browser/webshare/win/fake_data_transfer_manager_interop.h" #include "chrome/browser/webshare/win/show_share_ui_for_window_operation.h" #include "testing/gtest/include/gtest/gtest.h" @@ -39,15 +38,6 @@ } // namespace -// static -bool ScopedFakeDataTransferManagerInterop::IsSupportedEnvironment() { - if (base::win::ResolveCoreWinRTDelayload() && - base::win::ScopedHString::ResolveCoreWinRTStringDelayload()) - return true; - EXPECT_LT(base::win::GetVersion(), base::win::Version::WIN8); - return false; -} - ScopedFakeDataTransferManagerInterop::ScopedFakeDataTransferManagerInterop() { // Initialization work is done in an independent function so that the // various test macros can be used. @@ -66,7 +56,8 @@ } void ScopedFakeDataTransferManagerInterop::Initialize() { - ASSERT_TRUE(IsSupportedEnvironment()); + ASSERT_TRUE(base::win::ResolveCoreWinRTDelayload()); + ASSERT_TRUE(base::win::ScopedHString::ResolveCoreWinRTStringDelayload()); base::win::AssertComInitialized(); instance_ = Microsoft::WRL::Make<FakeDataTransferManagerInterop>();
diff --git a/chrome/browser/webshare/win/scoped_fake_data_transfer_manager_interop.h b/chrome/browser/webshare/win/scoped_fake_data_transfer_manager_interop.h index ef0d924b..b5468b6 100644 --- a/chrome/browser/webshare/win/scoped_fake_data_transfer_manager_interop.h +++ b/chrome/browser/webshare/win/scoped_fake_data_transfer_manager_interop.h
@@ -16,8 +16,6 @@ // for the Share contract. class ScopedFakeDataTransferManagerInterop { public: - static bool IsSupportedEnvironment(); - ScopedFakeDataTransferManagerInterop(); ScopedFakeDataTransferManagerInterop( const ScopedFakeDataTransferManagerInterop&) = delete;
diff --git a/chrome/browser/webshare/win/share_operation.cc b/chrome/browser/webshare/win/share_operation.cc deleted file mode 100644 index 8f78f409..0000000 --- a/chrome/browser/webshare/win/share_operation.cc +++ /dev/null
@@ -1,607 +0,0 @@ -// Copyright 2020 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/webshare/win/share_operation.h" - -#include "base/bind.h" -#include "base/strings/utf_string_conversions.h" -#include "base/task/post_task.h" -#include "base/win/core_winrt_util.h" -#include "base/win/post_async_results.h" -#include "base/win/scoped_hstring.h" -#include "base/win/vector.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/webshare/share_service_impl.h" -#include "chrome/browser/webshare/win/show_share_ui_for_window_operation.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/web_contents.h" -#include "net/base/net_errors.h" -#include "storage/browser/blob/blob_data_handle.h" -#include "storage/browser/blob/blob_storage_context.h" -#include "storage/browser/file_system/file_stream_writer.h" -#include "storage/browser/file_system/file_writer_delegate.h" -#include "storage/common/file_system/file_system_mount_option.h" -#include "ui/views/win/hwnd_util.h" -#include "url/gurl.h" - -#include <shlobj.h> -#include <windows.applicationmodel.datatransfer.h> -#include <windows.foundation.collections.h> -#include <windows.foundation.h> -#include <windows.storage.h> -#include <windows.storage.streams.h> -#include <wininet.h> -#include <wrl/client.h> -#include <wrl/event.h> - -using ABI::Windows::ApplicationModel::DataTransfer::IDataPackage; -using ABI::Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet; -using ABI::Windows::ApplicationModel::DataTransfer::IDataRequest; -using ABI::Windows::ApplicationModel::DataTransfer::IDataRequestDeferral; -using ABI::Windows::ApplicationModel::DataTransfer::IDataRequestedEventArgs; -using ABI::Windows::Foundation::AsyncStatus; -using ABI::Windows::Foundation::IAsyncOperation; -using ABI::Windows::Foundation::IAsyncOperationCompletedHandler; -using ABI::Windows::Foundation::IClosable; -using ABI::Windows::Foundation::IUriRuntimeClass; -using ABI::Windows::Foundation::IUriRuntimeClassFactory; -using ABI::Windows::Storage::IStorageFile; -using ABI::Windows::Storage::IStorageFileStatics; -using ABI::Windows::Storage::IStorageItem; -using ABI::Windows::Storage::IStreamedFileDataRequestedHandler; -using ABI::Windows::Storage::StorageFile; -using ABI::Windows::Storage::Streams::IDataWriter; -using ABI::Windows::Storage::Streams::IDataWriterFactory; -using ABI::Windows::Storage::Streams::IOutputStream; -using Microsoft::WRL::Callback; -using Microsoft::WRL::ComPtr; -using Microsoft::WRL::Make; - -namespace ABI { -namespace Windows { -namespace Foundation { -namespace Collections { - -// Define template specializations for the types used. These uuids were randomly -// generated. -template <> -struct __declspec(uuid("CBE31E85-DEC8-4227-987F-9C63D6AA1A2E")) - IObservableVector<IStorageItem*> : IObservableVector_impl<IStorageItem*> {}; - -template <> -struct __declspec(uuid("30BE4864-5EE5-4111-916E-15126649F3C9")) - VectorChangedEventHandler<IStorageItem*> - : VectorChangedEventHandler_impl<IStorageItem*> {}; - -} // namespace Collections -} // namespace Foundation -} // namespace Windows -} // namespace ABI - -namespace webshare { -namespace { - -uint64_t g_max_file_bytes = kMaxSharedFileBytes; - -// Implements FileStreamWriter for an IDataWriter. -class DataWriterFileStreamWriter : public storage::FileStreamWriter { - public: - explicit DataWriterFileStreamWriter( - ComPtr<IDataWriter> data_writer, - scoped_refptr<base::RefCountedData<uint64_t>> file_bytes_shared) - : data_writer_(data_writer), file_bytes_shared_(file_bytes_shared) {} - - int Cancel(net::CompletionOnceCallback callback) override { - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - // If there is no async operation in progress, Cancel() should - // return net::ERR_UNEXPECTED per file_stream_header.h - if (!flush_operation_ && !write_operation_) - return net::ERR_UNEXPECTED; - - if (flush_operation_) { - flush_callback_.Reset(); - ComPtr<IAsyncInfo> async_info; - auto hr = flush_operation_.As(&async_info); - if (FAILED(hr)) - return net::ERR_UNEXPECTED; - - hr = async_info->Cancel(); - if (FAILED(hr)) - return net::ERR_UNEXPECTED; - - flush_operation_.Reset(); - } - - if (write_operation_) { - write_callback_.Reset(); - ComPtr<IAsyncInfo> async_info; - auto hr = write_operation_.As(&async_info); - if (FAILED(hr)) - return net::ERR_UNEXPECTED; - - hr = async_info->Cancel(); - if (FAILED(hr)) - return net::ERR_UNEXPECTED; - - write_operation_.Reset(); - } - return net::OK; - } - - int Flush(net::CompletionOnceCallback callback) override { - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - DCHECK(flush_callback_.is_null()); - DCHECK_EQ(flush_operation_, nullptr); - DCHECK(write_callback_.is_null()); - DCHECK_EQ(write_operation_, nullptr); - - auto hr = data_writer_->FlushAsync(&flush_operation_); - if (FAILED(hr)) - return net::ERR_UNEXPECTED; - - flush_callback_ = std::move(callback); - base::win::PostAsyncResults( - flush_operation_, - base::BindOnce(&DataWriterFileStreamWriter::OnFlushCompleted, - weak_factory_.GetWeakPtr())); - return net::ERR_IO_PENDING; - } - - int Write(net::IOBuffer* buf, - int buf_len, - net::CompletionOnceCallback callback) override { - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - DCHECK(flush_callback_.is_null()); - DCHECK_EQ(flush_operation_, nullptr); - DCHECK(write_callback_.is_null()); - DCHECK_EQ(write_operation_, nullptr); - - // Before processing the Write request, increment the total number of file - // bytes shared as part of the overall Share operation this belongs to, and - // if it has exceeded the maximum allowed, abort writing to the streamed - // file. - file_bytes_shared_->data += buf_len; - if (file_bytes_shared_->data > g_max_file_bytes) - return net::ERR_UNEXPECTED; - - auto hr = - data_writer_->WriteBytes(buf_len, reinterpret_cast<BYTE*>(buf->data())); - if (FAILED(hr)) - return net::ERR_UNEXPECTED; - - hr = data_writer_->StoreAsync(&write_operation_); - if (FAILED(hr)) - return net::ERR_UNEXPECTED; - - write_callback_ = std::move(callback); - base::win::PostAsyncResults( - write_operation_, - base::BindOnce(&DataWriterFileStreamWriter::OnWriteCompleted, - weak_factory_.GetWeakPtr())); - return net::ERR_IO_PENDING; - } - - private: - void OnFlushCompleted(boolean operation_result) { - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - DCHECK(!flush_callback_.is_null()); - DCHECK_NE(flush_operation_, nullptr); - DCHECK(write_callback_.is_null()); - DCHECK_EQ(write_operation_, nullptr); - - flush_operation_.Reset(); - int result = operation_result == TRUE ? net::OK : net::ERR_UNEXPECTED; - std::move(flush_callback_).Run(result); - } - - void OnWriteCompleted(UINT32 operation_result) { - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - DCHECK(flush_callback_.is_null()); - DCHECK_EQ(flush_operation_, nullptr); - DCHECK(!write_callback_.is_null()); - DCHECK_NE(write_operation_, nullptr); - - write_operation_.Reset(); - std::move(write_callback_).Run(operation_result); - } - - ComPtr<IDataWriter> data_writer_; - scoped_refptr<base::RefCountedData<uint64_t>> file_bytes_shared_; - net::CompletionOnceCallback flush_callback_; - ComPtr<IAsyncOperation<bool>> flush_operation_; - net::CompletionOnceCallback write_callback_; - ComPtr<IAsyncOperation<UINT32>> write_operation_; - base::WeakPtrFactory<DataWriterFileStreamWriter> weak_factory_{this}; -}; - -// Represents an ongoing operation of writing to an IOutputStream. -class OutputStreamWriteOperation - : public base::RefCounted<OutputStreamWriteOperation> { - public: - OutputStreamWriteOperation( - content::BrowserContext::BlobContextGetter blob_context_getter, - scoped_refptr<base::RefCountedData<uint64_t>> file_bytes_shared, - std::string uuid) - : blob_context_getter_(blob_context_getter), - file_bytes_shared_(file_bytes_shared), - uuid_(uuid) {} - - // Begins the write operation on the |stream|, maintaining a reference to the - // |stream| until the operation is completed, at which point it will be closed - // (if possible) and the |on_complete| callback will be invoked. The caller - // is still responsible for the lifetime of this object, but not of the - // |stream|. - void WriteStream(IOutputStream* stream, - base::OnceCallback<void()> on_complete) { - stream_ = ComPtr<IOutputStream>(stream); - on_complete_ = std::move(on_complete); - if (!base::PostTask( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&OutputStreamWriteOperation::WriteStreamOnIOThread, - weak_factory_.GetWeakPtr()))) - Complete(); - } - - private: - friend class base::RefCounted<OutputStreamWriteOperation>; - - ~OutputStreamWriteOperation() = default; - - void WriteStreamOnIOThread() { - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - - storage::BlobStorageContext* blob_storage_context = - blob_context_getter_.Run().get(); - if (!blob_storage_context) { - Complete(); - return; - } - - blob_handle_ = blob_storage_context->GetBlobDataFromUUID(uuid_); - - ComPtr<IDataWriterFactory> data_writer_factory; - auto hr = base::win::GetActivationFactory< - IDataWriterFactory, RuntimeClass_Windows_Storage_Streams_DataWriter>( - &data_writer_factory); - if (FAILED(hr)) { - Complete(); - return; - } - - ComPtr<IDataWriter> data_writer; - hr = data_writer_factory->CreateDataWriter(stream_.Get(), &data_writer); - if (FAILED(hr)) { - Complete(); - return; - } - - writer_delegate_ = std::make_unique<storage::FileWriterDelegate>( - std::make_unique<DataWriterFileStreamWriter>(std::move(data_writer), - file_bytes_shared_), - storage::FlushPolicy::FLUSH_ON_COMPLETION); - writer_delegate_->Start( - blob_handle_->CreateReader(), - base::BindRepeating(&OutputStreamWriteOperation::OnFileWritten, - weak_factory_.GetWeakPtr())); - } - - void OnFileWritten( - base::File::Error error, - int64_t bytes_wrriten, - storage::FileWriterDelegate::WriteProgressStatus write_status) { - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - // Any status other than SUCCESS_IO_PENDING indicates completion. - if (write_status != - storage::FileWriterDelegate::WriteProgressStatus::SUCCESS_IO_PENDING) { - Complete(); - } - } - - void Complete() { - // If the IOutputStream implements IClosable (e.g. the OutputStream class), - // close the stream whenever we are done with this operation, regardless of - // the outcome. - if (stream_) { - ComPtr<IClosable> closable; - if (SUCCEEDED(stream_.As(&closable))) - closable->Close(); - } - - std::move(on_complete_).Run(); - } - - content::BrowserContext::BlobContextGetter blob_context_getter_; - std::unique_ptr<storage::BlobDataHandle> blob_handle_; - scoped_refptr<base::RefCountedData<uint64_t>> file_bytes_shared_; - base::OnceCallback<void()> on_complete_; - ComPtr<IOutputStream> stream_; - const std::string uuid_; - std::unique_ptr<storage::FileWriterDelegate> writer_delegate_; - base::WeakPtrFactory<OutputStreamWriteOperation> weak_factory_{this}; -}; -} // namespace - -// static -void ShareOperation::SetMaxFileBytesForTesting(uint64_t max_file_bytes) { - g_max_file_bytes = max_file_bytes; -} - -ShareOperation::ShareOperation(const std::string& title, - const std::string& text, - const GURL& url, - std::vector<blink::mojom::SharedFilePtr> files, - content::WebContents* web_contents) - : content::WebContentsObserver(web_contents), - title_(std::move(title)), - text_(std::move(text)), - url_(std::move(url)), - files_(std::move(files)) {} - -ShareOperation::~ShareOperation() { - if (callback_) - Complete(blink::mojom::ShareError::CANCELED); -} - -base::WeakPtr<ShareOperation> ShareOperation::AsWeakPtr() { - return weak_factory_.GetWeakPtr(); -} - -void ShareOperation::Run(blink::mojom::ShareService::ShareCallback callback) { - DCHECK(!callback_); - callback_ = std::move(callback); - - // If the required WinRT functionality is not available, or the corresponding - // web_contents have already been cleaned up, cancel the operation - const bool winrt_environment_ok = - base::win::ResolveCoreWinRTDelayload() && - base::win::ScopedHString::ResolveCoreWinRTStringDelayload(); - if (!winrt_environment_ok || !web_contents()) { - Complete(blink::mojom::ShareError::CANCELED); - return; - } - - if (files_.size() > 0) { - // Determine the source for use with the OS IAttachmentExecute. - // If the source cannot be determined, does not appear to be valid, - // or is longer than the max length supported by the IAttachmentExecute - // service, use a generic value that reliably maps to the Internet zone. - GURL source_url = web_contents()->GetLastCommittedURL(); - base::string16 source = - (source_url.is_valid() && - source_url.spec().size() <= INTERNET_MAX_URL_LENGTH) - ? base::UTF8ToUTF16(source_url.spec()) - : L"about:internet"; - - // For each "file", check against the OS that it is allowed - // The same instance cannot be used to check multiple files, so this - // makes a new one per-file. For more details on this functionality, see - // https://docs.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-iattachmentexecute-checkpolicy - for (auto& file : files_) { - ComPtr<IAttachmentExecute> attachment_services; - if (FAILED(CoCreateInstance(CLSID_AttachmentServices, nullptr, CLSCTX_ALL, - IID_PPV_ARGS(&attachment_services)))) { - Complete(blink::mojom::ShareError::INTERNAL_ERROR); - return; - } - if (FAILED(attachment_services->SetSource(source.c_str()))) { - Complete(blink::mojom::ShareError::INTERNAL_ERROR); - return; - } - if (FAILED(attachment_services->SetFileName( - base::UTF8ToWide(file->name).c_str()))) { - Complete(blink::mojom::ShareError::INTERNAL_ERROR); - return; - } - if (FAILED(attachment_services->CheckPolicy())) { - Complete(blink::mojom::ShareError::PERMISSION_DENIED); - return; - } - } - } - - HWND hwnd = - views::HWNDForNativeWindow(web_contents()->GetTopLevelNativeWindow()); - show_share_ui_for_window_operation_ = - std::make_unique<ShowShareUIForWindowOperation>(hwnd); - show_share_ui_for_window_operation_->Run(base::BindOnce( - &ShareOperation::OnDataRequested, weak_factory_.GetWeakPtr())); -} - -void ShareOperation::OnDataRequested(IDataRequestedEventArgs* event_args) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - blink::mojom::ShareError share_result; - if (!event_args || !web_contents()) { - share_result = blink::mojom::ShareError::CANCELED; - } else { - if (PutShareContentInEventArgs(event_args)) { - share_result = blink::mojom::ShareError::OK; - } else { - share_result = blink::mojom::ShareError::INTERNAL_ERROR; - } - } - - // If the share operation failed or is not being deferred, mark it as complete - if (share_result != blink::mojom::ShareError::OK || !data_request_deferral_) - Complete(share_result); -} - -bool ShareOperation::PutShareContentInEventArgs( - IDataRequestedEventArgs* event_args) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - ComPtr<IDataRequest> data_request; - if (FAILED(event_args->get_Request(&data_request))) - return false; - - if (FAILED(data_request->get_Data(&data_package_))) - return false; - - ComPtr<IDataPackagePropertySet> data_prop_sets; - if (FAILED(data_package_->get_Properties(&data_prop_sets))) - return false; - - // Title is a required property for the UWP Share contract, so - // if the provided title is empty we instead use a blank value. - // https://docs.microsoft.com/en-us/windows/uwp/app-to-app/share-data - base::win::ScopedHString title_h = - base::win::ScopedHString::Create(title_.empty() ? " " : title_.c_str()); - if (FAILED(data_prop_sets->put_Title(title_h.get()))) - return false; - - return PutShareContentInDataPackage(data_request.Get()); -} - -bool ShareOperation::PutShareContentInDataPackage(IDataRequest* data_request) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - if (!text_.empty()) { - auto text_h = base::win::ScopedHString::Create(text_); - if (FAILED(data_package_->SetText(text_h.get()))) - return false; - } - - if (!url_.spec().empty()) { - ComPtr<IUriRuntimeClassFactory> uri_factory; - auto hr = - base::win::GetActivationFactory<IUriRuntimeClassFactory, - RuntimeClass_Windows_Foundation_Uri>( - &uri_factory); - if (FAILED(hr)) - return hr; - - auto url_h = base::win::ScopedHString::Create(url_.spec().c_str()); - ComPtr<IUriRuntimeClass> uri; - if (FAILED(uri_factory->CreateUri(url_h.get(), &uri))) - return false; - - if (FAILED(data_package_->SetUri(uri.Get()))) - return false; - } - - if (!files_.empty()) { - // Fetch a deferral to allow for async operations - if (FAILED(data_request->GetDeferral(&data_request_deferral_))) - return false; - - // Initialize the output collection for the async operation(s) - storage_items_ = Make<base::win::Vector<IStorageItem*>>(); - - // Create a variable to be shared between all the operations processing the - // blobs to streams. This will be used to keep a running count of total file - // bytes shared as part of this Share operation so that if the maximum - // allowed is exceeded the processing can be halted. Currently the - // ShareOperation class is not guaranteed to outlive these operations, but - // if that changes in the future it may be appropriate to make this a member - // of the ShareOperation that is shared only be reference. - auto file_bytes_shared = - base::MakeRefCounted<base::RefCountedData<uint64_t>>(0); - - ComPtr<IStorageFileStatics> storage_statics; - auto hr = base::win::GetActivationFactory< - IStorageFileStatics, RuntimeClass_Windows_Storage_StorageFile>( - &storage_statics); - if (FAILED(hr)) - return false; - - for (auto& file : files_) { - // This operation for converting the corresponding blob to a stream is - // maintained as a scoped_refptr because it may out live this - // ShareOperation instance. It is only invoked when the user has chosen a - // Share target and that target decides to start reading the contents of - // the corresponding IStorageFile. See - // https://docs.microsoft.com/en-us/uwp/api/windows.storage.storagefile.createstreamedfileasync - // If in the future the ShareOperation class is changed to live until the - // target app has finished fully processing the shared content this could - // be updated to be owned/maintained by this ShareOperation instance. - auto operation = base::MakeRefCounted<OutputStreamWriteOperation>( - content::BrowserContext::GetBlobStorageContext( - web_contents()->GetBrowserContext()), - file_bytes_shared, file->blob->uuid); - auto name_h = base::win::ScopedHString::Create(file->name); - auto raw_data_requested_callback = - Callback<IStreamedFileDataRequestedHandler>( - [operation](IOutputStream* stream) -> HRESULT { - // No additional work is needed when the write has been - // completed, but a callback is created to hold a reference - // to the |operation| until the operation has completed. - operation->WriteStream( - stream, - base::BindOnce( - base::DoNothing::Once< - scoped_refptr<OutputStreamWriteOperation>>(), - operation)); - return S_OK; - }); - // The Callback function may return null in the E_OUTOFMEMORY case - if (!raw_data_requested_callback) - return false; - ComPtr<IAsyncOperation<StorageFile*>> async_operation; - if (FAILED(storage_statics->CreateStreamedFileAsync( - name_h.get(), raw_data_requested_callback.Get(), - /*thumbnail*/ nullptr, &async_operation))) { - return false; - } - - if (FAILED(base::win::PostAsyncResults( - async_operation, - base::BindOnce(&ShareOperation::OnStreamedFileCreated, - weak_factory_.GetWeakPtr())))) - return false; - } - } - - return true; -} - -void ShareOperation::OnStreamedFileCreated(ComPtr<IStorageFile> storage_file) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - // If there is no callback this ShareOperation already completed due to an - // error, so work can be halted early. - if (!callback_) - return; - - if (!storage_file) { - Complete(blink::mojom::ShareError::INTERNAL_ERROR); - return; - } - - ComPtr<IStorageItem> storage_item; - if (FAILED(storage_file.As(&storage_item))) { - Complete(blink::mojom::ShareError::INTERNAL_ERROR); - return; - } - - if (FAILED(storage_items_->Append(storage_item.Get()))) { - Complete(blink::mojom::ShareError::INTERNAL_ERROR); - return; - } - - unsigned int size; - if (FAILED(storage_items_->get_Size(&size))) { - Complete(blink::mojom::ShareError::INTERNAL_ERROR); - return; - } - - // If this is not the final file, no more work to do - if (size != files_.size()) - return; - - if (FAILED(data_package_->SetStorageItems(storage_items_.Get(), - true /*readonly*/))) { - Complete(blink::mojom::ShareError::INTERNAL_ERROR); - return; - } - - data_request_deferral_->Complete(); - Complete(blink::mojom::ShareError::OK); - return; -} - -void ShareOperation::Complete(const blink::mojom::ShareError share_result) { - std::move(callback_).Run(share_result); -} - -} // namespace webshare
diff --git a/chrome/browser/webshare/win/share_operation.h b/chrome/browser/webshare/win/share_operation.h deleted file mode 100644 index 2ea87d3c..0000000 --- a/chrome/browser/webshare/win/share_operation.h +++ /dev/null
@@ -1,105 +0,0 @@ -// Copyright 2020 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -#ifndef CHROME_BROWSER_WEBSHARE_WIN_SHARE_OPERATION_H_ -#define CHROME_BROWSER_WEBSHARE_WIN_SHARE_OPERATION_H_ - -#include <memory> -#include <string> -#include <vector> - -#include "base/memory/weak_ptr.h" -#include "content/public/browser/web_contents_observer.h" -#include "third_party/blink/public/mojom/webshare/webshare.mojom.h" -#include "url/gurl.h" - -#include <wrl/client.h> - -namespace ABI { -namespace Windows { -namespace ApplicationModel { -namespace DataTransfer { -struct IDataPackage; -class IDataRequest; -class IDataRequestDeferral; -class IDataRequestedEventArgs; -} // namespace DataTransfer -} // namespace ApplicationModel -namespace Storage { -class IStorageFile; -class IStorageItem; -} // namespace Storage -} // namespace Windows -} // namespace ABI - -namespace base { -namespace win { -template <typename T> -class Vector; -} // namespace win -} // namespace base - -namespace webshare { - -class ShowShareUIForWindowOperation; - -class ShareOperation : content::WebContentsObserver { - public: - static void SetMaxFileBytesForTesting(uint64_t max_file_bytes); - - ShareOperation(const std::string& title, - const std::string& text, - const GURL& url, - std::vector<blink::mojom::SharedFilePtr> files, - content::WebContents* web_contents); - ShareOperation(const ShareOperation&) = delete; - ShareOperation& operator=(const ShareOperation&) = delete; - ~ShareOperation() override; - - base::WeakPtr<ShareOperation> AsWeakPtr(); - - // Starts this Windows Share operation for the previously provided content. - // The |callback| will be invoked upon completion of the operation with a - // value indicating the success of the operation, or if the returned instance - // is destroyed before the operation is completed the |callback| will be - // invoked with a CANCELLED value and the underlying Windows operation will be - // aborted. - void Run(blink::mojom::ShareService::ShareCallback callback); - - private: - void OnDataRequested( - ABI::Windows::ApplicationModel::DataTransfer::IDataRequestedEventArgs* e); - bool PutShareContentInDataPackage( - ABI::Windows::ApplicationModel::DataTransfer::IDataRequest* data_request); - bool PutShareContentInEventArgs( - ABI::Windows::ApplicationModel::DataTransfer::IDataRequestedEventArgs* e); - void OnStreamedFileCreated( - Microsoft::WRL::ComPtr<ABI::Windows::Storage::IStorageFile> storage_file); - void Complete(const blink::mojom::ShareError share_error); - - const std::string title_; - const std::string text_; - const GURL url_; - const std::vector<blink::mojom::SharedFilePtr> files_; - - blink::mojom::ShareService::ShareCallback callback_; - Microsoft::WRL::ComPtr< - ABI::Windows::ApplicationModel::DataTransfer::IDataPackage> - data_package_; - Microsoft::WRL::ComPtr< - ABI::Windows::ApplicationModel::DataTransfer::IDataRequestDeferral> - data_request_deferral_; - std::unique_ptr<ShowShareUIForWindowOperation> - show_share_ui_for_window_operation_; - // Though this Vector is declared as using a raw IStorageItem*, because - // IStorageItem implements IUnknown it will be stored internally with - // ComPtrs, so does not need to be specially handled. - Microsoft::WRL::ComPtr< - base::win::Vector<ABI::Windows::Storage::IStorageItem*>> - storage_items_; - base::WeakPtrFactory<ShareOperation> weak_factory_{this}; -}; - -} // namespace webshare - -#endif // CHROME_BROWSER_WEBSHARE_WIN_SHARE_OPERATION_H_
diff --git a/chrome/browser/webshare/win/share_operation_unittest.cc b/chrome/browser/webshare/win/share_operation_unittest.cc deleted file mode 100644 index 1f675a8..0000000 --- a/chrome/browser/webshare/win/share_operation_unittest.cc +++ /dev/null
@@ -1,446 +0,0 @@ -// Copyright 2020 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/webshare/win/share_operation.h" - -#include "base/guid.h" -#include "base/run_loop.h" -#include "base/synchronization/waitable_event.h" -#include "base/test/bind_test_util.h" -#include "base/test/scoped_feature_list.h" -#include "base/win/core_winrt_util.h" -#include "base/win/post_async_results.h" -#include "chrome/browser/webshare/share_service_impl.h" -#include "chrome/browser/webshare/win/fake_data_transfer_manager.h" -#include "chrome/browser/webshare/win/fake_data_transfer_manager_interop.h" -#include "chrome/browser/webshare/win/scoped_fake_data_transfer_manager_interop.h" -#include "chrome/common/chrome_features.h" -#include "chrome/test/base/chrome_render_view_host_test_harness.h" -#include "content/public/browser/browser_task_traits.h" -#include "storage/browser/blob/blob_data_builder.h" -#include "storage/browser/blob/blob_impl.h" -#include "storage/browser/blob/blob_storage_context.h" -#include "ui/views/win/hwnd_util.h" -#include "url/gurl.h" - -#include <wrl/event.h> - -using ABI::Windows::ApplicationModel::DataTransfer::IDataPackage; -using ABI::Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet; -using ABI::Windows::ApplicationModel::DataTransfer::IDataRequest; -using ABI::Windows::ApplicationModel::DataTransfer::IDataRequestedEventArgs; -using ABI::Windows::Foundation::IAsyncOperation; -using ABI::Windows::Foundation::IAsyncOperationCompletedHandler; -using ABI::Windows::Storage::FileAccessMode; -using ABI::Windows::Storage::IStorageFile; -using ABI::Windows::Storage::Streams::IDataReader; -using ABI::Windows::Storage::Streams::IDataReaderFactory; -using ABI::Windows::Storage::Streams::IInputStream; -using ABI::Windows::Storage::Streams::IRandomAccessStream; -using Microsoft::WRL::Callback; -using Microsoft::WRL::ComPtr; - -namespace webshare { -namespace { -constexpr base::TimeDelta kOperationWaitIncrement = - base::TimeDelta::FromMilliseconds(100); -constexpr base::TimeDelta kMaxOperationWait = base::TimeDelta::FromSeconds(10); -constexpr uint64_t kMaxSharedFileBytesForTest = 1024 * 100; -} // namespace - -class ShareOperationUnitTest : public ChromeRenderViewHostTestHarness { - public: - ShareOperationUnitTest() { - feature_list_.InitAndEnableFeature(features::kWebShare); - } - ~ShareOperationUnitTest() override = default; - - void SetUp() override { - ChromeRenderViewHostTestHarness::SetUp(); - - if (!IsSupportedEnvironment()) - return; - - scoped_interop_ = std::make_unique<ScopedFakeDataTransferManagerInterop>(); - ShareOperation::SetMaxFileBytesForTesting(kMaxSharedFileBytesForTest); - } - - void TearDown() override { - ChromeRenderViewHostTestHarness::TearDown(); - ShareOperation::SetMaxFileBytesForTesting(kMaxSharedFileBytes); - } - - protected: - // Waits/blocks for an operation to complete that involves code from the - // system and our own internal code. - template <typename T, typename TResult> - void WaitForAsyncOperationWithSystemAndInternalCode( - ComPtr<IAsyncOperation<T>>& operation, - TResult& result) { - base::WaitableEvent waitable_event; - ASSERT_HRESULT_SUCCEEDED(base::win::PostAsyncResults( - operation, base::BindLambdaForTesting( - [&result, &waitable_event](TResult returned_result) { - result = returned_result; - waitable_event.Signal(); - }))); - - base::TimeDelta time_waited; - while (!waitable_event.IsSignaled() && time_waited < kMaxOperationWait) { - task_environment()->RunUntilIdle(); - waitable_event.TimedWait(kOperationWaitIncrement); - time_waited += kOperationWaitIncrement; - } - - ASSERT_TRUE(waitable_event.IsSignaled()); - } - - void ReadFile(IStorageFile* file, std::string& result) { - ComPtr<IAsyncOperation<IRandomAccessStream*>> open_operation; - ASSERT_HRESULT_SUCCEEDED( - file->OpenAsync(FileAccessMode::FileAccessMode_Read, &open_operation)); - - ComPtr<IRandomAccessStream> stream; - ASSERT_NO_FATAL_FAILURE( - WaitForAsyncOperationWithSystemAndInternalCode(open_operation, stream)); - ASSERT_TRUE(stream); - - UINT64 size; - ASSERT_HRESULT_SUCCEEDED(stream->get_Size(&size)); - - ComPtr<IInputStream> input_stream; - ASSERT_HRESULT_SUCCEEDED(stream->GetInputStreamAt(0, &input_stream)); - - ComPtr<IDataReaderFactory> data_reader_factory; - HRESULT hr = base::win::GetActivationFactory< - IDataReaderFactory, RuntimeClass_Windows_Storage_Streams_DataReader>( - &data_reader_factory); - ASSERT_HRESULT_SUCCEEDED(hr); - - ComPtr<IDataReader> data_reader; - ASSERT_HRESULT_SUCCEEDED(data_reader_factory->CreateDataReader( - input_stream.Get(), &data_reader)); - - ComPtr<IAsyncOperation<UINT32>> load_operation; - ASSERT_HRESULT_SUCCEEDED(data_reader->LoadAsync(size, &load_operation)); - - UINT32 bytes_loaded; - ASSERT_NO_FATAL_FAILURE(WaitForAsyncOperationWithSystemAndInternalCode( - load_operation, bytes_loaded)); - ASSERT_NE(bytes_loaded, 0u); - - std::vector<unsigned char> bytes(bytes_loaded); - ASSERT_HRESULT_SUCCEEDED( - data_reader->ReadBytes(bytes_loaded, bytes.data())); - - result = std::string(bytes.begin(), bytes.end()); - } - - blink::mojom::SharedFilePtr CreateSharedFile(const std::string& name, - const std::string& content_type, - const std::string& contents) { - auto blob = blink::mojom::SerializedBlob::New(); - const std::string uuid = base::GenerateGUID(); - blob->uuid = uuid; - blob->content_type = content_type; - blob->size = contents.size(); - - base::RunLoop run_loop; - auto blob_context_getter = - content::BrowserContext::GetBlobStorageContext(browser_context()); - content::GetIOThreadTaskRunner({})->PostTaskAndReply( - FROM_HERE, - base::BindLambdaForTesting([&blob_context_getter, &blob, &uuid, - &content_type, &contents]() { - auto builder = std::make_unique<storage::BlobDataBuilder>(uuid); - builder->set_content_type(content_type); - builder->AppendData(contents); - storage::BlobImpl::Create( - blob_context_getter.Run()->AddFinishedBlob(std::move(builder)), - blob->blob.InitWithNewPipeAndPassReceiver()); - }), - base::BindLambdaForTesting([&run_loop]() { run_loop.Quit(); })); - run_loop.Run(); - return blink::mojom::SharedFile::New(name, std::move(blob)); - } - - bool IsSupportedEnvironment() { - return ScopedFakeDataTransferManagerInterop::IsSupportedEnvironment(); - } - - // Fetches the FakeDataTransferManager associated with the current context. - // Returns a non-ref-counted pointer, as the lifetime is already maintained by - // the scoped_interop_. - FakeDataTransferManager* fake_data_transfer_manager() { - if (!fake_data_transfer_manager_) { - HWND hwnd = - views::HWNDForNativeWindow(web_contents()->GetTopLevelNativeWindow()); - ComPtr<FakeDataTransferManager> fake_data_transfer_manager; - EXPECT_HRESULT_SUCCEEDED(scoped_interop_->instance().GetForWindow( - hwnd, IID_PPV_ARGS(&fake_data_transfer_manager))); - fake_data_transfer_manager_ = fake_data_transfer_manager.Get(); - } - return fake_data_transfer_manager_; - } - - private: - FakeDataTransferManager* fake_data_transfer_manager_ = nullptr; - base::test::ScopedFeatureList feature_list_; - std::unique_ptr<ScopedFakeDataTransferManagerInterop> scoped_interop_; -}; - -TEST_F(ShareOperationUnitTest, WithoutTitle) { - if (!IsSupportedEnvironment()) - return; - - bool post_data_requested_callback_invoked = false; - fake_data_transfer_manager()->SetPostDataRequestedCallback( - base::BindLambdaForTesting( - [&post_data_requested_callback_invoked]( - const FakeDataTransferManager::DataRequestedContent& - data_requested_content) { - ASSERT_FALSE(post_data_requested_callback_invoked); - post_data_requested_callback_invoked = true; - ASSERT_EQ(data_requested_content.title, " "); - ASSERT_EQ(data_requested_content.text, "shared Text"); - })); - - base::RunLoop run_loop; - std::vector<blink::mojom::SharedFilePtr> files; - ShareOperation operation{"", "shared Text", GURL::EmptyGURL(), - std::move(files), web_contents()}; - operation.Run( - base::BindLambdaForTesting([&run_loop](blink::mojom::ShareError error) { - ASSERT_EQ(error, blink::mojom::ShareError::OK); - run_loop.Quit(); - })); - run_loop.Run(); - - ASSERT_TRUE(post_data_requested_callback_invoked); -} - -TEST_F(ShareOperationUnitTest, BasicFields) { - if (!IsSupportedEnvironment()) - return; - - bool post_data_requested_callback_invoked = false; - fake_data_transfer_manager()->SetPostDataRequestedCallback( - base::BindLambdaForTesting( - [&post_data_requested_callback_invoked]( - const FakeDataTransferManager::DataRequestedContent& - data_requested_content) { - ASSERT_FALSE(post_data_requested_callback_invoked); - post_data_requested_callback_invoked = true; - ASSERT_EQ(data_requested_content.title, "shared title"); - ASSERT_EQ(data_requested_content.text, "shared text"); - ASSERT_EQ(GURL(data_requested_content.uri), - GURL("https://www.contoso.com")); - })); - - base::RunLoop run_loop; - std::vector<blink::mojom::SharedFilePtr> files; - ShareOperation operation{"shared title", "shared text", - GURL("https://www.contoso.com"), std::move(files), - web_contents()}; - operation.Run( - base::BindLambdaForTesting([&run_loop](blink::mojom::ShareError error) { - ASSERT_EQ(error, blink::mojom::ShareError::OK); - run_loop.Quit(); - })); - run_loop.Run(); - - ASSERT_TRUE(post_data_requested_callback_invoked); -} - -TEST_F(ShareOperationUnitTest, BasicFile) { - if (!IsSupportedEnvironment()) - return; - - bool post_data_requested_callback_invoked = false; - fake_data_transfer_manager()->SetPostDataRequestedCallback( - base::BindLambdaForTesting( - [&](const FakeDataTransferManager::DataRequestedContent& - data_requested_content) { - ASSERT_FALSE(post_data_requested_callback_invoked); - post_data_requested_callback_invoked = true; - ASSERT_EQ(data_requested_content.title, "shared title"); - ASSERT_EQ(data_requested_content.files.size(), 1ull); - ASSERT_EQ(data_requested_content.files[0].name, "MyFile.txt"); - std::string file_contents; - ASSERT_NO_FATAL_FAILURE(ReadFile( - data_requested_content.files[0].file.Get(), file_contents)); - ASSERT_EQ(file_contents, "Contents of the file"); - })); - - base::RunLoop run_loop; - std::vector<blink::mojom::SharedFilePtr> files; - files.push_back( - CreateSharedFile("MyFile.txt", "text/plain", "Contents of the file")); - ShareOperation operation{"shared title", "", GURL::EmptyGURL(), - std::move(files), web_contents()}; - operation.Run( - base::BindLambdaForTesting([&run_loop](blink::mojom::ShareError error) { - ASSERT_EQ(error, blink::mojom::ShareError::OK); - run_loop.Quit(); - })); - run_loop.Run(); - - ASSERT_TRUE(post_data_requested_callback_invoked); -} - -TEST_F(ShareOperationUnitTest, SingleFileAtSizeLimit) { - if (!IsSupportedEnvironment()) - return; - - bool post_data_requested_callback_invoked = false; - fake_data_transfer_manager()->SetPostDataRequestedCallback( - base::BindLambdaForTesting( - [&](const FakeDataTransferManager::DataRequestedContent& - data_requested_content) { - ASSERT_FALSE(post_data_requested_callback_invoked); - post_data_requested_callback_invoked = true; - ASSERT_EQ(data_requested_content.files.size(), 1ull); - std::string file_contents; - ASSERT_NO_FATAL_FAILURE(ReadFile( - data_requested_content.files[0].file.Get(), file_contents)); - ASSERT_EQ(file_contents.length(), kMaxSharedFileBytesForTest); - })); - - base::RunLoop run_loop; - std::vector<blink::mojom::SharedFilePtr> files; - files.push_back( - CreateSharedFile("MyFile.txt", "text/plain", - std::string(kMaxSharedFileBytesForTest, '*'))); - ShareOperation operation{"", "", GURL::EmptyGURL(), std::move(files), - web_contents()}; - operation.Run( - base::BindLambdaForTesting([&run_loop](blink::mojom::ShareError error) { - ASSERT_EQ(error, blink::mojom::ShareError::OK); - run_loop.Quit(); - })); - run_loop.Run(); - - ASSERT_TRUE(post_data_requested_callback_invoked); -} - -TEST_F(ShareOperationUnitTest, SingleFileLargerThanSizeLimit) { - if (!IsSupportedEnvironment()) - return; - - bool post_data_requested_callback_invoked = false; - fake_data_transfer_manager()->SetPostDataRequestedCallback( - base::BindLambdaForTesting( - [&](const FakeDataTransferManager::DataRequestedContent& - data_requested_content) { - ASSERT_FALSE(post_data_requested_callback_invoked); - post_data_requested_callback_invoked = true; - ASSERT_EQ(data_requested_content.files.size(), 1ull); - std::string file_contents; - ASSERT_NO_FATAL_FAILURE(ReadFile( - data_requested_content.files[0].file.Get(), file_contents)); - ASSERT_LT(file_contents.length(), kMaxSharedFileBytesForTest + 1); - })); - - base::RunLoop run_loop; - std::vector<blink::mojom::SharedFilePtr> files; - files.push_back( - CreateSharedFile("MyFile.txt", "text/plain", - std::string(kMaxSharedFileBytesForTest + 1, '*'))); - ShareOperation operation{"", "", GURL::EmptyGURL(), std::move(files), - web_contents()}; - operation.Run( - base::BindLambdaForTesting([&run_loop](blink::mojom::ShareError error) { - ASSERT_EQ(error, blink::mojom::ShareError::OK); - run_loop.Quit(); - })); - run_loop.Run(); - - ASSERT_TRUE(post_data_requested_callback_invoked); -} - -TEST_F(ShareOperationUnitTest, FilesTotallingSizeLimit) { - if (!IsSupportedEnvironment()) - return; - - bool post_data_requested_callback_invoked = false; - fake_data_transfer_manager()->SetPostDataRequestedCallback( - base::BindLambdaForTesting( - [&](const FakeDataTransferManager::DataRequestedContent& - data_requested_content) { - ASSERT_FALSE(post_data_requested_callback_invoked); - post_data_requested_callback_invoked = true; - ASSERT_EQ(data_requested_content.files.size(), 2ull); - std::string file1_contents; - ASSERT_NO_FATAL_FAILURE(ReadFile( - data_requested_content.files[0].file.Get(), file1_contents)); - std::string file2_contents; - ASSERT_NO_FATAL_FAILURE(ReadFile( - data_requested_content.files[0].file.Get(), file2_contents)); - ASSERT_EQ(file1_contents.length() + file2_contents.length(), - kMaxSharedFileBytesForTest); - })); - - base::RunLoop run_loop; - std::vector<blink::mojom::SharedFilePtr> files; - files.push_back( - CreateSharedFile("File1.txt", "text/plain", - std::string(kMaxSharedFileBytesForTest / 2, '*'))); - files.push_back( - CreateSharedFile("File2.txt", "text/plain", - std::string(kMaxSharedFileBytesForTest / 2, '*'))); - ShareOperation operation{"", "", GURL::EmptyGURL(), std::move(files), - web_contents()}; - operation.Run( - base::BindLambdaForTesting([&run_loop](blink::mojom::ShareError error) { - ASSERT_EQ(error, blink::mojom::ShareError::OK); - run_loop.Quit(); - })); - run_loop.Run(); - - ASSERT_TRUE(post_data_requested_callback_invoked); -} - -TEST_F(ShareOperationUnitTest, FilesTotallingLargerThanSizeLimit) { - if (!IsSupportedEnvironment()) - return; - - bool post_data_requested_callback_invoked = false; - fake_data_transfer_manager()->SetPostDataRequestedCallback( - base::BindLambdaForTesting( - [&](const FakeDataTransferManager::DataRequestedContent& - data_requested_content) { - ASSERT_FALSE(post_data_requested_callback_invoked); - post_data_requested_callback_invoked = true; - ASSERT_EQ(data_requested_content.files.size(), 2ull); - std::string file1_contents; - ASSERT_NO_FATAL_FAILURE(ReadFile( - data_requested_content.files[0].file.Get(), file1_contents)); - std::string file2_contents; - ASSERT_NO_FATAL_FAILURE(ReadFile( - data_requested_content.files[1].file.Get(), file2_contents)); - ASSERT_LT(file1_contents.length() + file2_contents.length(), - kMaxSharedFileBytesForTest + 1); - })); - - base::RunLoop run_loop; - std::vector<blink::mojom::SharedFilePtr> files; - files.push_back( - CreateSharedFile("File1.txt", "text/plain", - std::string(kMaxSharedFileBytesForTest / 2, '*'))); - files.push_back( - CreateSharedFile("File2.txt", "text/plain", - std::string((kMaxSharedFileBytesForTest / 2) + 1, '*'))); - ShareOperation operation{"", "", GURL::EmptyGURL(), std::move(files), - web_contents()}; - operation.Run( - base::BindLambdaForTesting([&run_loop](blink::mojom::ShareError error) { - ASSERT_EQ(error, blink::mojom::ShareError::OK); - run_loop.Quit(); - })); - run_loop.Run(); - - ASSERT_TRUE(post_data_requested_callback_invoked); -} - -} // namespace webshare
diff --git a/chrome/browser/webshare/win/show_share_ui_for_window_operation_unittest.cc b/chrome/browser/webshare/win/show_share_ui_for_window_operation_unittest.cc index 8dc7937..cd79303b 100644 --- a/chrome/browser/webshare/win/show_share_ui_for_window_operation_unittest.cc +++ b/chrome/browser/webshare/win/show_share_ui_for_window_operation_unittest.cc
@@ -40,7 +40,8 @@ enum TestCallbackState { NotRun = 0, RunWithoutValue, RunWithValue }; bool IsSupportedEnvironment() { - return ScopedFakeDataTransferManagerInterop::IsSupportedEnvironment(); + return base::win::ResolveCoreWinRTDelayload() && + base::win::ScopedHString::ResolveCoreWinRTStringDelayload(); } void SetUp() override {
diff --git a/chrome/build/linux.pgo.txt b/chrome/build/linux.pgo.txt index 175d7398..22cf1ad 100644 --- a/chrome/build/linux.pgo.txt +++ b/chrome/build/linux.pgo.txt
@@ -1 +1 @@ -chrome-linux-master-1602244639-8a31cdfac3c26c19c9de644309ff096c0a612320.profdata +chrome-linux-master-1602266368-0e61a032fa7157fa29bc804c0d7295bad87c6193.profdata
diff --git a/chrome/build/mac.pgo.txt b/chrome/build/mac.pgo.txt index 78b82f0..0cd4f90 100644 --- a/chrome/build/mac.pgo.txt +++ b/chrome/build/mac.pgo.txt
@@ -1 +1 @@ -chrome-mac-master-1602244639-6cd23926ee4e898bd11627c63cc4edf5ffd59847.profdata +chrome-mac-master-1602266368-92d2928e0040ad47ba60bbcac401f36efe1994de.profdata
diff --git a/chrome/common/extensions/chrome_extensions_client.cc b/chrome/common/extensions/chrome_extensions_client.cc index cdf3fff0..70e950a 100644 --- a/chrome/common/extensions/chrome_extensions_client.cc +++ b/chrome/common/extensions/chrome_extensions_client.cc
@@ -133,6 +133,11 @@ const Extension* extension, const APIPermissionSet& api_permissions) const { URLPatternSet hosts; + + // Do not allow any chrome-scheme hosts in MV3+ extensions. + if (extension->manifest_version() >= 3) + return hosts; + // Regular extensions are only allowed access to chrome://favicon. hosts.AddPattern(URLPattern(URLPattern::SCHEME_CHROMEUI, chrome::kChromeUIFaviconURL));
diff --git a/chrome/common/extensions/manifest_tests/extension_manifests_webview_accessible_resources_unittest.cc b/chrome/common/extensions/manifest_tests/extension_manifests_webview_accessible_resources_unittest.cc index 8d182681..c022707 100644 --- a/chrome/common/extensions/manifest_tests/extension_manifests_webview_accessible_resources_unittest.cc +++ b/chrome/common/extensions/manifest_tests/extension_manifests_webview_accessible_resources_unittest.cc
@@ -82,4 +82,18 @@ "webview_accessible_resources_invalid8.json", ErrorUtils::FormatErrorMessage(errors::kInvalidWebviewAccessibleResource, base::NumberToString(0))); + + { + // Specifying non-relative paths as accessible resources should fail. We + // raise a warning rather than a hard-error because existing apps do this + // and we don't want to break them for all existing users. + // https://crbug.com/856948. + scoped_refptr<const Extension> extension = LoadAndExpectWarning( + "webview_accessible_resources_non_relative_path.json", + ErrorUtils::FormatErrorMessage( + errors::kInvalidWebviewAccessibleResource, + base::NumberToString(0))); + EXPECT_FALSE(WebviewInfo::IsResourceWebviewAccessible( + extension.get(), "nonrelative", "a.html")); + } }
diff --git a/chrome/common/extensions/manifest_tests/permissions_parser_unittest.cc b/chrome/common/extensions/manifest_tests/permissions_parser_unittest.cc index 56a947a5..ebd4f83 100644 --- a/chrome/common/extensions/manifest_tests/permissions_parser_unittest.cc +++ b/chrome/common/extensions/manifest_tests/permissions_parser_unittest.cc
@@ -3,9 +3,15 @@ // found in the LICENSE file. #include "extensions/common/manifest_handlers/permissions_parser.h" + +#include "base/stl_util.h" +#include "base/strings/stringprintf.h" +#include "base/test/values_test_util.h" #include "chrome/common/extensions/manifest_tests/chrome_manifest_test.h" #include "extensions/common/error_utils.h" +#include "extensions/common/extension.h" #include "extensions/common/manifest_constants.h" +#include "extensions/common/permissions/permissions_data.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -152,4 +158,74 @@ EXPECT_THAT(optional_api_names, testing::UnorderedElementsAre("tabs")); } +// Test that chrome://favicon is a supported permission in MV2, but not MV3. +TEST_F(PermissionsParserTest, ChromeFavicon) { + auto get_manifest_data = [](int manifest_version, const char* permission) { + constexpr char kManifestStub[] = + R"({ + "name": "Test", + "version": "0.1", + "manifest_version": %d, + "%s": ["%s"] + })"; + + const char* permissions_key = manifest_version > 2 + ? manifest_keys::kHostPermissions + : manifest_keys::kPermissions; + base::Value manifest_value = base::test::ParseJson(base::StringPrintf( + kManifestStub, manifest_version, permissions_key, permission)); + EXPECT_EQ(base::Value::Type::DICTIONARY, manifest_value.type()); + return ManifestData(std::move(manifest_value), permission); + }; + + static constexpr char kFaviconPattern[] = "chrome://favicon/*"; + // <all_urls> implicitly includes chrome://favicon, if it's supported. + constexpr char kAllUrls[] = "<all_urls>"; + + auto has_favicon_access = [](const Extension& extension) { + const GURL favicon_url("chrome://favicon"); + return extension.permissions_data()->HasHostPermission(favicon_url); + }; + + auto has_install_warning = [](const Extension& extension) { + InstallWarning expected_warning(ErrorUtils::FormatErrorMessage( + manifest_errors::kInvalidPermissionScheme, kFaviconPattern)); + return base::Contains(extension.install_warnings(), expected_warning); + }; + + { + scoped_refptr<const Extension> extension = + LoadAndExpectSuccess(get_manifest_data(2, kFaviconPattern)); + ASSERT_TRUE(extension); + EXPECT_TRUE(has_favicon_access(*extension)); + EXPECT_FALSE(has_install_warning(*extension)); + } + + { + scoped_refptr<const Extension> extension = + LoadAndExpectSuccess(get_manifest_data(2, kAllUrls)); + ASSERT_TRUE(extension); + EXPECT_TRUE(has_favicon_access(*extension)); + EXPECT_FALSE(has_install_warning(*extension)); + } + { + scoped_refptr<const Extension> extension = + LoadAndExpectSuccess(get_manifest_data(3, kFaviconPattern)); + ASSERT_TRUE(extension); + EXPECT_FALSE(has_favicon_access(*extension)); + // Since chrome://favicon is not a valid permission in MV3, we expect a + // warning to be thrown. + EXPECT_TRUE(has_install_warning(*extension)); + } + { + scoped_refptr<const Extension> extension = + LoadAndExpectSuccess(get_manifest_data(3, kAllUrls)); + ASSERT_TRUE(extension); + EXPECT_FALSE(has_favicon_access(*extension)); + // NOTE: We don't expect an install warning here, because the <all_urls> + // permission is still supported. It just doesn't grant favicon access. + EXPECT_FALSE(has_install_warning(*extension)); + } +} + } // namespace extensions
diff --git a/chrome/common/pref_names.cc b/chrome/common/pref_names.cc index d135b4e..988a4fa 100644 --- a/chrome/common/pref_names.cc +++ b/chrome/common/pref_names.cc
@@ -1760,9 +1760,19 @@ // Boolean specifying that the intranet redirect detector should be enabled. // Defaults to true. +// Will be replaced by DNSInterceptionChecksBehavior, below; see notes for that +// function. const char kDNSInterceptionChecksEnabled[] = "browser.dns_interception_checks_enabled"; +// Enum specifying the active behavior for the intranet redirect detector. +// This will replace kDNSInterceptionChecksEnabled over time, though +// currently both policies are in use. When the Enabled policy is set to false, +// it effectively short-circuits the behavior, and it cannot be enabled by this +// Behavior policy. Alternatively the policies can be considered to AND +// together. Values are defined in IntranetRedirectDetector::RedirectorBehavior. +const char kIntranetRedirectBehavior[] = "browser.intranet_redirect_behavior"; + // An enum value of how the browser was shut down (see browser_shutdown.h). const char kShutdownType[] = "shutdown.type"; // Number of processes that were open when the user shut down.
diff --git a/chrome/common/pref_names.h b/chrome/common/pref_names.h index e90bcb6..13f9d47 100644 --- a/chrome/common/pref_names.h +++ b/chrome/common/pref_names.h
@@ -583,6 +583,7 @@ extern const char kLastKnownIntranetRedirectOrigin[]; extern const char kDNSInterceptionChecksEnabled[]; +extern const char kIntranetRedirectBehavior[]; extern const char kShutdownType[]; extern const char kShutdownNumProcesses[];
diff --git a/chrome/credential_provider/gaiacp/user_policies_manager.cc b/chrome/credential_provider/gaiacp/user_policies_manager.cc index 596538e0..da78340 100644 --- a/chrome/credential_provider/gaiacp/user_policies_manager.cc +++ b/chrome/credential_provider/gaiacp/user_policies_manager.cc
@@ -212,8 +212,10 @@ } UserPoliciesManager::UserPoliciesManager() : fetch_status_(S_OK) { - g_cloud_policies_enabled = - GetGlobalFlagOrDefault(kCloudPoliciesEnabledRegKey, 0) == 1; + std::string dm_token; + bool has_dm_token = SUCCEEDED(GetDmToken(&dm_token)) && !dm_token.empty(); + g_cloud_policies_enabled = GetGlobalFlagOrDefault(kCloudPoliciesEnabledRegKey, + has_dm_token ? 1 : 0) == 1; } UserPoliciesManager::~UserPoliciesManager() = default;
diff --git a/chrome/credential_provider/gaiacp/user_policies_manager_unittests.cc b/chrome/credential_provider/gaiacp/user_policies_manager_unittests.cc index 5da7b982..9e55bd6 100644 --- a/chrome/credential_provider/gaiacp/user_policies_manager_unittests.cc +++ b/chrome/credential_provider/gaiacp/user_policies_manager_unittests.cc
@@ -281,5 +281,46 @@ ::testing::Bool(), ::testing::Values(L"", L"valid-dm-token"))); +// Test to verify automatic enabling of cloud policies when DM token is present. +// Parameters: +// string : Value of DM Token on the device. +// int : 0 - Cloud policies disabled through registry. +// 1 - Cloud policies enabled through registry. +// 2 - Cloud policies registry flag not set. +class GcpUserPoliciesEnableOnDmTokenTest + : public GcpUserPoliciesBaseTest, + public ::testing::WithParamInterface<std::tuple<const char*, int>> {}; + +TEST_P(GcpUserPoliciesEnableOnDmTokenTest, EnableIfFound) { + std::string dm_token(std::get<0>(GetParam())); + int reg_enable_cloud_policies = std::get<1>(GetParam()); + + if (!dm_token.empty()) { + ASSERT_EQ(S_OK, SetDmTokenForTesting(dm_token)); + } + if (reg_enable_cloud_policies < 2) { + SetGlobalFlagForTesting(L"cloud_policies_enabled", + reg_enable_cloud_policies); + } + + // This is needed because we want to call the default constructor of the + // UserDeviceManager in each test. + FakeUserPoliciesManager fake_user_policies_manager; + + // Feature is enabled if it's explicitly enabled or if the flag is not set and + // a valid DM token exists. + if (reg_enable_cloud_policies == 1 || + (reg_enable_cloud_policies == 2 && !dm_token.empty())) { + ASSERT_TRUE(UserPoliciesManager::Get()->CloudPoliciesEnabled()); + } else { + ASSERT_FALSE(UserPoliciesManager::Get()->CloudPoliciesEnabled()); + } +} + +INSTANTIATE_TEST_SUITE_P(All, + GcpUserPoliciesEnableOnDmTokenTest, + ::testing::Combine(::testing::Values("", "dm-token"), + ::testing::Values(0, 1, 2))); + } // namespace testing } // namespace credential_provider
diff --git a/chrome/credential_provider/test/gcp_fakes.cc b/chrome/credential_provider/test/gcp_fakes.cc index e9a6fddc..19ec31b 100644 --- a/chrome/credential_provider/test/gcp_fakes.cc +++ b/chrome/credential_provider/test/gcp_fakes.cc
@@ -1165,6 +1165,11 @@ /////////////////////////////////////////////////////////////////////////////// +FakeUserPoliciesManager::FakeUserPoliciesManager() + : original_manager_(*GetInstanceStorage()) { + *GetInstanceStorage() = this; +} + FakeUserPoliciesManager::FakeUserPoliciesManager(bool cloud_policies_enabled) : original_manager_(*GetInstanceStorage()) { *GetInstanceStorage() = this;
diff --git a/chrome/credential_provider/test/gcp_fakes.h b/chrome/credential_provider/test/gcp_fakes.h index 8c761ca..bc2a645c 100644 --- a/chrome/credential_provider/test/gcp_fakes.h +++ b/chrome/credential_provider/test/gcp_fakes.h
@@ -599,6 +599,7 @@ class FakeUserPoliciesManager : public UserPoliciesManager { public: + explicit FakeUserPoliciesManager(); explicit FakeUserPoliciesManager(bool cloud_policies_enabled); ~FakeUserPoliciesManager() override;
diff --git a/chrome/services/sharing/BUILD.gn b/chrome/services/sharing/BUILD.gn index 4a44586..916f16a0 100644 --- a/chrome/services/sharing/BUILD.gn +++ b/chrome/services/sharing/BUILD.gn
@@ -18,7 +18,7 @@ public_deps = [ "//base", "//chrome/services/sharing/public/cpp", - "//chrome/services/sharing/public/mojom", + "//chromeos/services/nearby/public/mojom", "//mojo/public/cpp/bindings", ] }
diff --git a/chrome/services/sharing/DEPS b/chrome/services/sharing/DEPS index 0fd9d3a..cf99b74 100644 --- a/chrome/services/sharing/DEPS +++ b/chrome/services/sharing/DEPS
@@ -1,6 +1,7 @@ include_rules = [ - "+jingle/glue", + "+chromeos/services/nearby", "+device/bluetooth/public/mojom", + "+jingle/glue", "+services/network/public/cpp", "+services/network/public/mojom", "+third_party/webrtc",
diff --git a/chrome/services/sharing/nearby/BUILD.gn b/chrome/services/sharing/nearby/BUILD.gn index a1f412d..64a86aa 100644 --- a/chrome/services/sharing/nearby/BUILD.gn +++ b/chrome/services/sharing/nearby/BUILD.gn
@@ -18,7 +18,7 @@ "platform_v2", "//base", "//chrome/services/sharing/public/cpp", - "//chrome/services/sharing/public/mojom", + "//chromeos/services/nearby/public/mojom", "//mojo/public/cpp/bindings", "//third_party/nearby:core", ]
diff --git a/chrome/services/sharing/nearby/decoder/BUILD.gn b/chrome/services/sharing/nearby/decoder/BUILD.gn index f4845dc23..1248eb9 100644 --- a/chrome/services/sharing/nearby/decoder/BUILD.gn +++ b/chrome/services/sharing/nearby/decoder/BUILD.gn
@@ -4,6 +4,8 @@ import("//testing/libfuzzer/fuzzer_test.gni") +assert(is_chromeos) + source_set("decoder") { sources = [ "advertisement_decoder.cc", @@ -15,8 +17,8 @@ public_deps = [ "//base", "//chrome/services/sharing/public/cpp", - "//chrome/services/sharing/public/mojom", "//chrome/services/sharing/public/proto", + "//chromeos/services/nearby/public/mojom", "//mojo/public/cpp/bindings", ] }
diff --git a/chrome/services/sharing/nearby/decoder/nearby_decoder.cc b/chrome/services/sharing/nearby/decoder/nearby_decoder.cc index e104073..24b424c 100644 --- a/chrome/services/sharing/nearby/decoder/nearby_decoder.cc +++ b/chrome/services/sharing/nearby/decoder/nearby_decoder.cc
@@ -12,8 +12,8 @@ #include "base/optional.h" #include "chrome/services/sharing/nearby/decoder/advertisement_decoder.h" #include "chrome/services/sharing/public/cpp/advertisement.h" -#include "chrome/services/sharing/public/mojom/nearby_decoder_types.mojom.h" #include "chrome/services/sharing/public/proto/wire_format.pb.h" +#include "chromeos/services/nearby/public/mojom/nearby_decoder_types.mojom.h" namespace sharing {
diff --git a/chrome/services/sharing/nearby/decoder/nearby_decoder.h b/chrome/services/sharing/nearby/decoder/nearby_decoder.h index 5829fa14..be5f3b0 100644 --- a/chrome/services/sharing/nearby/decoder/nearby_decoder.h +++ b/chrome/services/sharing/nearby/decoder/nearby_decoder.h
@@ -7,7 +7,7 @@ #include <vector> -#include "chrome/services/sharing/public/mojom/nearby_decoder.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_decoder.mojom.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/receiver.h"
diff --git a/chrome/services/sharing/nearby/decoder/nearby_decoder_decode_advertisement_fuzzer.cc b/chrome/services/sharing/nearby/decoder/nearby_decoder_decode_advertisement_fuzzer.cc index c6f1a93f..d8f5244 100644 --- a/chrome/services/sharing/nearby/decoder/nearby_decoder_decode_advertisement_fuzzer.cc +++ b/chrome/services/sharing/nearby/decoder/nearby_decoder_decode_advertisement_fuzzer.cc
@@ -13,8 +13,8 @@ #include "base/no_destructor.h" #include "base/run_loop.h" #include "base/task/single_thread_task_executor.h" -#include "chrome/services/sharing/public/mojom/nearby_decoder.mojom.h" -#include "chrome/services/sharing/public/mojom/nearby_decoder_types.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_decoder.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_decoder_types.mojom.h" #include "mojo/core/embedder/embedder.h" #include "mojo/public/cpp/bindings/remote.h"
diff --git a/chrome/services/sharing/nearby/decoder/nearby_decoder_decode_frame_fuzzer.cc b/chrome/services/sharing/nearby/decoder/nearby_decoder_decode_frame_fuzzer.cc index cd68c0bb..c76c8ff9 100644 --- a/chrome/services/sharing/nearby/decoder/nearby_decoder_decode_frame_fuzzer.cc +++ b/chrome/services/sharing/nearby/decoder/nearby_decoder_decode_frame_fuzzer.cc
@@ -13,8 +13,8 @@ #include "base/no_destructor.h" #include "base/run_loop.h" #include "base/task/single_thread_task_executor.h" -#include "chrome/services/sharing/public/mojom/nearby_decoder.mojom.h" -#include "chrome/services/sharing/public/mojom/nearby_decoder_types.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_decoder.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_decoder_types.mojom.h" #include "mojo/core/embedder/embedder.h" #include "mojo/public/cpp/bindings/remote.h"
diff --git a/chrome/services/sharing/nearby/decoder/nearby_decoder_unittest.cc b/chrome/services/sharing/nearby/decoder/nearby_decoder_unittest.cc index 51d072d3..03187d05 100644 --- a/chrome/services/sharing/nearby/decoder/nearby_decoder_unittest.cc +++ b/chrome/services/sharing/nearby/decoder/nearby_decoder_unittest.cc
@@ -15,8 +15,8 @@ #include "base/test/task_environment.h" #include "chrome/services/sharing/public/cpp/advertisement.h" #include "chrome/services/sharing/public/cpp/conversions.h" -#include "chrome/services/sharing/public/mojom/nearby_decoder_types.mojom.h" #include "chrome/services/sharing/public/proto/wire_format.pb.h" +#include "chromeos/services/nearby/public/mojom/nearby_decoder_types.mojom.h" #include "mojo/public/cpp/bindings/remote.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/services/sharing/nearby/nearby_connections.cc b/chrome/services/sharing/nearby/nearby_connections.cc index 6bcbc39..6128553 100644 --- a/chrome/services/sharing/nearby/nearby_connections.cc +++ b/chrome/services/sharing/nearby/nearby_connections.cc
@@ -11,7 +11,7 @@ #include "chrome/browser/nearby_sharing/logging/logging.h" #include "chrome/services/sharing/nearby/nearby_connections_conversions.h" #include "chrome/services/sharing/nearby/platform_v2/input_file.h" -#include "chrome/services/sharing/public/mojom/nearby_connections_types.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_connections_types.mojom.h" namespace location { namespace nearby {
diff --git a/chrome/services/sharing/nearby/nearby_connections.h b/chrome/services/sharing/nearby/nearby_connections.h index 3b00022..6d86540 100644 --- a/chrome/services/sharing/nearby/nearby_connections.h +++ b/chrome/services/sharing/nearby/nearby_connections.h
@@ -19,8 +19,8 @@ #include "base/synchronization/lock.h" #include "base/task/post_task.h" #include "base/thread_annotations.h" -#include "chrome/services/sharing/public/mojom/nearby_connections.mojom.h" -#include "chrome/services/sharing/public/mojom/webrtc_signaling_messenger.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_connections.mojom.h" +#include "chromeos/services/nearby/public/mojom/webrtc_signaling_messenger.mojom.h" #include "device/bluetooth/public/mojom/adapter.mojom.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h"
diff --git a/chrome/services/sharing/nearby/nearby_connections_conversions.cc b/chrome/services/sharing/nearby/nearby_connections_conversions.cc index 73aa931c..9676145b 100644 --- a/chrome/services/sharing/nearby/nearby_connections_conversions.cc +++ b/chrome/services/sharing/nearby/nearby_connections_conversions.cc
@@ -8,8 +8,8 @@ #include "base/callback.h" #include "base/files/file_path.h" -#include "chrome/services/sharing/public/mojom/nearby_connections.mojom.h" -#include "chrome/services/sharing/public/mojom/nearby_connections_types.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_connections.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_connections_types.mojom.h" namespace location { namespace nearby {
diff --git a/chrome/services/sharing/nearby/nearby_connections_conversions.h b/chrome/services/sharing/nearby/nearby_connections_conversions.h index d059097..e18e801 100644 --- a/chrome/services/sharing/nearby/nearby_connections_conversions.h +++ b/chrome/services/sharing/nearby/nearby_connections_conversions.h
@@ -9,8 +9,8 @@ #include <vector> #include "base/callback_forward.h" -#include "chrome/services/sharing/public/mojom/nearby_connections.mojom-forward.h" -#include "chrome/services/sharing/public/mojom/nearby_connections_types.mojom-forward.h" +#include "chromeos/services/nearby/public/mojom/nearby_connections.mojom-forward.h" +#include "chromeos/services/nearby/public/mojom/nearby_connections_types.mojom-forward.h" #include "third_party/nearby/src/cpp/core_v2/options.h" #include "third_party/nearby/src/cpp/core_v2/params.h"
diff --git a/chrome/services/sharing/nearby/nearby_connections_unittest.cc b/chrome/services/sharing/nearby/nearby_connections_unittest.cc index 8c41065e..356ead0e 100644 --- a/chrome/services/sharing/nearby/nearby_connections_unittest.cc +++ b/chrome/services/sharing/nearby/nearby_connections_unittest.cc
@@ -20,7 +20,7 @@ #include "chrome/services/sharing/nearby/nearby_connections_conversions.h" #include "chrome/services/sharing/nearby/test_support/fake_adapter.h" #include "chrome/services/sharing/nearby/test_support/mock_webrtc_dependencies.h" -#include "chrome/services/sharing/public/mojom/nearby_decoder.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_decoder.mojom.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/bindings/self_owned_receiver.h"
diff --git a/chrome/services/sharing/nearby/platform_v2/BUILD.gn b/chrome/services/sharing/nearby/platform_v2/BUILD.gn index 2848f33..c1f86da 100644 --- a/chrome/services/sharing/nearby/platform_v2/BUILD.gn +++ b/chrome/services/sharing/nearby/platform_v2/BUILD.gn
@@ -2,6 +2,8 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +assert(is_chromeos) + source_set("platform_v2") { sources = [ "atomic_boolean.cc", @@ -53,8 +55,8 @@ deps = [ "//base", - "//chrome/services/sharing/public/mojom", "//chrome/services/sharing/webrtc", + "//chromeos/services/nearby/public/mojom", "//crypto", "//jingle:webrtc_glue", "//third_party/abseil-cpp:absl",
diff --git a/chrome/services/sharing/nearby/platform_v2/webrtc.h b/chrome/services/sharing/nearby/platform_v2/webrtc.h index 7c092d5..6d313cc 100644 --- a/chrome/services/sharing/nearby/platform_v2/webrtc.h +++ b/chrome/services/sharing/nearby/platform_v2/webrtc.h
@@ -10,8 +10,8 @@ #include <memory> #include "base/single_thread_task_runner.h" -#include "chrome/services/sharing/public/mojom/webrtc.mojom.h" -#include "chrome/services/sharing/public/mojom/webrtc_signaling_messenger.mojom.h" +#include "chromeos/services/nearby/public/mojom/webrtc.mojom.h" +#include "chromeos/services/nearby/public/mojom/webrtc_signaling_messenger.mojom.h" #include "mojo/public/cpp/bindings/shared_remote.h" #include "services/network/public/mojom/mdns_responder.mojom.h" #include "services/network/public/mojom/p2p.mojom.h"
diff --git a/chrome/services/sharing/nearby/test_support/BUILD.gn b/chrome/services/sharing/nearby/test_support/BUILD.gn index 5ad3de6a..7d5e38d 100644 --- a/chrome/services/sharing/nearby/test_support/BUILD.gn +++ b/chrome/services/sharing/nearby/test_support/BUILD.gn
@@ -2,6 +2,8 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +assert(is_chromeos) + source_set("test_support") { testonly = true @@ -14,7 +16,7 @@ deps = [ "//base/test:test_support", - "//chrome/services/sharing/public/mojom", + "//chromeos/services/nearby/public/mojom", "//testing/gmock", "//testing/gtest", ]
diff --git a/chrome/services/sharing/nearby/test_support/mock_webrtc_dependencies.h b/chrome/services/sharing/nearby/test_support/mock_webrtc_dependencies.h index fad543a..295a8a29 100644 --- a/chrome/services/sharing/nearby/test_support/mock_webrtc_dependencies.h +++ b/chrome/services/sharing/nearby/test_support/mock_webrtc_dependencies.h
@@ -5,8 +5,8 @@ #ifndef CHROME_SERVICES_SHARING_NEARBY_TEST_SUPPORT_MOCK_WEBRTC_DEPENDENCIES_H_ #define CHROME_SERVICES_SHARING_NEARBY_TEST_SUPPORT_MOCK_WEBRTC_DEPENDENCIES_H_ -#include "chrome/services/sharing/public/mojom/webrtc.mojom.h" -#include "chrome/services/sharing/public/mojom/webrtc_signaling_messenger.mojom.h" +#include "chromeos/services/nearby/public/mojom/webrtc.mojom.h" +#include "chromeos/services/nearby/public/mojom/webrtc_signaling_messenger.mojom.h" #include "mojo/public/cpp/bindings/receiver.h" #include "services/network/public/mojom/mdns_responder.mojom.h" #include "services/network/public/mojom/p2p.mojom.h"
diff --git a/chrome/services/sharing/public/cpp/BUILD.gn b/chrome/services/sharing/public/cpp/BUILD.gn index 8c23b9d..fb920e3 100644 --- a/chrome/services/sharing/public/cpp/BUILD.gn +++ b/chrome/services/sharing/public/cpp/BUILD.gn
@@ -2,6 +2,8 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +assert(is_chromeos) + source_set("cpp") { sources = [ "advertisement.cc", @@ -14,8 +16,8 @@ public_deps = [ "//base", - "//chrome/services/sharing/public/mojom", "//chrome/services/sharing/public/proto", + "//chromeos/services/nearby/public/mojom", "//mojo/public/cpp/bindings", ] }
diff --git a/chrome/services/sharing/public/cpp/advertisement.h b/chrome/services/sharing/public/cpp/advertisement.h index 4ac27c9..fa1714d 100644 --- a/chrome/services/sharing/public/cpp/advertisement.h +++ b/chrome/services/sharing/public/cpp/advertisement.h
@@ -12,7 +12,7 @@ #include "base/containers/span.h" #include "base/optional.h" -#include "chrome/services/sharing/public/mojom/nearby_share_target_types.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_share_target_types.mojom.h" namespace sharing {
diff --git a/chrome/services/sharing/public/cpp/conversions.h b/chrome/services/sharing/public/cpp/conversions.h index e08491a..065e260 100644 --- a/chrome/services/sharing/public/cpp/conversions.h +++ b/chrome/services/sharing/public/cpp/conversions.h
@@ -5,8 +5,8 @@ #ifndef CHROME_SERVICES_SHARING_PUBLIC_CPP_CONVERSIONS_H_ #define CHROME_SERVICES_SHARING_PUBLIC_CPP_CONVERSIONS_H_ -#include "chrome/services/sharing/public/mojom/nearby_decoder_types.mojom.h" #include "chrome/services/sharing/public/proto/wire_format.pb.h" +#include "chromeos/services/nearby/public/mojom/nearby_decoder_types.mojom.h" namespace sharing {
diff --git a/chrome/services/sharing/sharing_impl.cc b/chrome/services/sharing/sharing_impl.cc index e44531e..4e32f31a 100644 --- a/chrome/services/sharing/sharing_impl.cc +++ b/chrome/services/sharing/sharing_impl.cc
@@ -9,7 +9,7 @@ #include "base/callback.h" #include "chrome/services/sharing/nearby/decoder/nearby_decoder.h" #include "chrome/services/sharing/nearby/nearby_connections.h" -#include "chrome/services/sharing/public/mojom/nearby_decoder.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_decoder.mojom.h" namespace sharing {
diff --git a/chrome/services/sharing/sharing_impl.h b/chrome/services/sharing/sharing_impl.h index 56361760..c28c75ce 100644 --- a/chrome/services/sharing/sharing_impl.h +++ b/chrome/services/sharing/sharing_impl.h
@@ -12,9 +12,9 @@ #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "base/sequenced_task_runner.h" -#include "chrome/services/sharing/public/mojom/nearby_connections.mojom-forward.h" -#include "chrome/services/sharing/public/mojom/sharing.mojom.h" -#include "chrome/services/sharing/public/mojom/webrtc.mojom-forward.h" +#include "chromeos/services/nearby/public/mojom/nearby_connections.mojom-forward.h" +#include "chromeos/services/nearby/public/mojom/sharing.mojom.h" +#include "chromeos/services/nearby/public/mojom/webrtc.mojom-forward.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/receiver.h"
diff --git a/chrome/services/sharing/sharing_impl_unittest.cc b/chrome/services/sharing/sharing_impl_unittest.cc index 847010d..d38d968 100644 --- a/chrome/services/sharing/sharing_impl_unittest.cc +++ b/chrome/services/sharing/sharing_impl_unittest.cc
@@ -12,7 +12,7 @@ #include "chrome/services/sharing/nearby/nearby_connections.h" #include "chrome/services/sharing/nearby/test_support/fake_adapter.h" #include "chrome/services/sharing/nearby/test_support/mock_webrtc_dependencies.h" -#include "chrome/services/sharing/public/mojom/nearby_decoder.mojom.h" +#include "chromeos/services/nearby/public/mojom/nearby_decoder.mojom.h" #include "mojo/public/cpp/bindings/remote.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/services/sharing/webrtc/BUILD.gn b/chrome/services/sharing/webrtc/BUILD.gn index 0d6455e2..2cbf086 100644 --- a/chrome/services/sharing/webrtc/BUILD.gn +++ b/chrome/services/sharing/webrtc/BUILD.gn
@@ -2,6 +2,8 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +assert(is_chromeos) + source_set("webrtc") { sources = [ "ipc_network_manager.cc", @@ -27,7 +29,7 @@ public_deps = [ "//base", "//chrome/services/sharing/public/cpp", - "//chrome/services/sharing/public/mojom", + "//chromeos/services/nearby/public/mojom", "//mojo/public/cpp/bindings", ] }
diff --git a/chrome/services/speech/soda/BUILD.gn b/chrome/services/speech/soda/BUILD.gn index b8628fe5..6e4437d2 100644 --- a/chrome/services/speech/soda/BUILD.gn +++ b/chrome/services/speech/soda/BUILD.gn
@@ -19,6 +19,8 @@ if (enable_soda) { sources = [ "soda_client_unittest.cc" ] + data_deps = [ "//third_party/soda:soda_resources" ] + deps = [ ":soda", "//base",
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 0118af1..3c68557 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -334,7 +334,6 @@ "//components/crash/core/app", "//third_party/wtl", ] - libs = [ "runtimeobject.lib" ] } if (is_chromeos) { @@ -1610,6 +1609,7 @@ if (enable_soda) { sources += [ "../browser/speech/speech_recognition_service_browsertest.cc" ] + data_deps += [ "//third_party/soda:soda_resources" ] } if (use_ozone) { @@ -4546,7 +4546,6 @@ "../browser/ui/thumbnails/thumbnail_capture_driver_unittest.cc", "../browser/ui/thumbnails/thumbnail_image_unittest.cc", "../browser/ui/thumbnails/thumbnail_scheduler_impl_unittest.cc", - "../browser/ui/thumbnails/thumbnail_stats_tracker_unittest.cc", "../browser/ui/toolbar/app_menu_model_unittest.cc", "../browser/ui/toolbar/back_forward_menu_model_unittest.cc", "../browser/ui/toolbar/location_bar_model_unittest.cc", @@ -4670,8 +4669,6 @@ "//chrome/browser/promo_browser_command:mojo_bindings", "//chrome/browser/resource_coordinator:tab_metrics_event_proto", "//chrome/browser/resource_coordinator/tab_ranker:tab_features_test_helper", - "//chrome/services/sharing/public/cpp", - "//chrome/services/sharing/public/cpp:unit_tests", "//chrome/services/speech:unit_tests", "//components/chrome_cleaner/test:test_name_helper", "//components/enterprise", @@ -4695,6 +4692,12 @@ if (is_mac) { deps += [ ":firefox_importer_interface" ] } + if (is_chromeos) { + deps += [ + "//chrome/services/sharing/public/cpp", + "//chrome/services/sharing/public/cpp:unit_tests", + ] + } } if (!is_android) { @@ -4735,7 +4738,6 @@ "../browser/sharing/shared_clipboard/shared_clipboard_utils_unittest.cc", "../browser/sharing/sms/sms_fetch_request_handler_unittest.cc", "../browser/sharing/sms/sms_remote_fetcher_unittest.cc", - "../browser/sharing/webrtc/ice_config_fetcher_unittest.cc", "../browser/ui/autofill/address_profiles/save_address_profile_bubble_controller_unittest.cc", "../browser/ui/autofill/payments/local_card_migration_bubble_controller_impl_unittest.cc", "../browser/ui/autofill/payments/save_card_bubble_controller_impl_unittest.cc", @@ -4863,6 +4865,7 @@ "../browser/notifications/chrome_ash_message_center_client_unittest.cc", "../browser/notifications/web_page_notifier_controller_unittest.cc", "../browser/policy/printing_restrictions_policy_handler_unittest.cc", + "../browser/sharing/webrtc/ice_config_fetcher_unittest.cc", "../browser/speech/tts_chromeos_unittest.cc", "../browser/speech/tts_controller_delegate_impl_unittest.cc", "../browser/sync/sync_error_notifier_ash_unittest.cc", @@ -5804,7 +5807,6 @@ "../browser/ui/views/uninstall_view_unittest.cc", "../browser/webshare/win/fake_data_transfer_manager_interop_unittest.cc", "../browser/webshare/win/fake_data_transfer_manager_unittest.cc", - "../browser/webshare/win/share_operation_unittest.cc", "../browser/webshare/win/show_share_ui_for_window_operation_unittest.cc", ] deps += [
diff --git a/chrome/test/data/extensions/api_test/extension_action/action_persistence/background.js b/chrome/test/data/extensions/api_test/extension_action/action_persistence/background.js new file mode 100644 index 0000000..7658d95 --- /dev/null +++ b/chrome/test/data/extensions/api_test/extension_action/action_persistence/background.js
@@ -0,0 +1,27 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +chrome.storage.local.get('sentinel', (val) => { + if (val.sentinel !== undefined) { + // Note: We don't expect the event page to be invoked a second time, + // because it doesn't register for any relevant events. If it were, it would + // re-set the action properties, which would invalidate the text. + chrome.test.notifyFail('Unexpected Sentinel Value: ' + val.sentinel); + chrome.action.setTitle({title: 'FAILED'}); + return; + } + + chrome.storage.local.set({sentinel: true}, () => { + chrome.action.setPopup({popup: 'modified_popup.html'}, () => { + chrome.test.assertNoLastError(); + chrome.action.setTitle({title: 'modified title'}, () => { + chrome.test.assertNoLastError(); + chrome.action.setBadgeText({text: 'custom badge text'}, () => { + chrome.test.assertNoLastError(); + chrome.test.notifyPass(); + }); + }); + }); + }); +});
diff --git a/chrome/test/data/extensions/api_test/extension_action/action_persistence/default_popup.html b/chrome/test/data/extensions/api_test/extension_action/action_persistence/default_popup.html new file mode 100644 index 0000000..4b3b4339 --- /dev/null +++ b/chrome/test/data/extensions/api_test/extension_action/action_persistence/default_popup.html
@@ -0,0 +1,2 @@ +<!doctype html> +<html></html>
diff --git a/chrome/test/data/extensions/api_test/extension_action/action_persistence/manifest.json b/chrome/test/data/extensions/api_test/extension_action/action_persistence/manifest.json new file mode 100644 index 0000000..2240345 --- /dev/null +++ b/chrome/test/data/extensions/api_test/extension_action/action_persistence/manifest.json
@@ -0,0 +1,11 @@ +{ + "name": "Action persistence check", + "version": "0.1", + "manifest_version": 2, + "background": { "scripts": ["background.js"], "persistent": false }, + "action": { + "default_popup": "default_popup.html", + "default_title": "default title" + }, + "permissions": ["storage"] +}
diff --git a/chrome/test/data/extensions/api_test/extension_action/action_persistence/modified_popup.html b/chrome/test/data/extensions/api_test/extension_action/action_persistence/modified_popup.html new file mode 100644 index 0000000..4b3b4339 --- /dev/null +++ b/chrome/test/data/extensions/api_test/extension_action/action_persistence/modified_popup.html
@@ -0,0 +1,2 @@ +<!doctype html> +<html></html>
diff --git a/chrome/test/data/extensions/api_test/extension_action/browser_action_persistence/background.js b/chrome/test/data/extensions/api_test/extension_action/browser_action_persistence/background.js new file mode 100644 index 0000000..071d528 --- /dev/null +++ b/chrome/test/data/extensions/api_test/extension_action/browser_action_persistence/background.js
@@ -0,0 +1,27 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +chrome.storage.local.get('sentinel', (val) => { + if (val.sentinel !== undefined) { + // Note: We don't expect the event page to be invoked a second time, + // because it doesn't register for any relevant events. If it were, it would + // re-set the action properties, which would invalidate the text. + chrome.test.notifyFail('Unexpected Sentinel Value: ' + val.sentinel); + chrome.browserAction.setTitle({title: 'FAILED'}); + return; + } + + chrome.storage.local.set({sentinel: true}, () => { + chrome.browserAction.setPopup({popup: 'modified_popup.html'}, () => { + chrome.test.assertNoLastError(); + chrome.browserAction.setTitle({title: 'modified title'}, () => { + chrome.test.assertNoLastError(); + chrome.browserAction.setBadgeText({text: 'custom badge text'}, () => { + chrome.test.assertNoLastError(); + chrome.test.notifyPass(); + }); + }); + }); + }); +});
diff --git a/chrome/test/data/extensions/api_test/extension_action/browser_action_persistence/default_popup.html b/chrome/test/data/extensions/api_test/extension_action/browser_action_persistence/default_popup.html new file mode 100644 index 0000000..4b3b4339 --- /dev/null +++ b/chrome/test/data/extensions/api_test/extension_action/browser_action_persistence/default_popup.html
@@ -0,0 +1,2 @@ +<!doctype html> +<html></html>
diff --git a/chrome/test/data/extensions/api_test/extension_action/browser_action_persistence/manifest.json b/chrome/test/data/extensions/api_test/extension_action/browser_action_persistence/manifest.json new file mode 100644 index 0000000..ec203c2 --- /dev/null +++ b/chrome/test/data/extensions/api_test/extension_action/browser_action_persistence/manifest.json
@@ -0,0 +1,11 @@ +{ + "name": "Action persistence check", + "version": "0.1", + "manifest_version": 2, + "background": { "scripts": ["background.js"], "persistent": false }, + "browser_action": { + "default_popup": "default_popup.html", + "default_title": "default title" + }, + "permissions": ["storage"] +}
diff --git a/chrome/test/data/extensions/api_test/extension_action/browser_action_persistence/modified_popup.html b/chrome/test/data/extensions/api_test/extension_action/browser_action_persistence/modified_popup.html new file mode 100644 index 0000000..4b3b4339 --- /dev/null +++ b/chrome/test/data/extensions/api_test/extension_action/browser_action_persistence/modified_popup.html
@@ -0,0 +1,2 @@ +<!doctype html> +<html></html>
diff --git a/chrome/test/data/extensions/manifest_tests/webview_accessible_resources_non_relative_path.json b/chrome/test/data/extensions/manifest_tests/webview_accessible_resources_non_relative_path.json new file mode 100644 index 0000000..c159774e --- /dev/null +++ b/chrome/test/data/extensions/manifest_tests/webview_accessible_resources_non_relative_path.json
@@ -0,0 +1,21 @@ +{ + "name": "test", + "version": "2", + "manifest_version": 2, + "permissions": [ + "webview" + ], + "app": { + "background": { + "scripts": ["test.js"] + } + }, + "webview": { + "partitions": [ + { + "name": "nonrelative", + "accessible_resources": ["http://*/*"] + } + ] + } +}
diff --git a/chrome/test/data/pdf/viewer_pdf_toolbar_new_test.js b/chrome/test/data/pdf/viewer_pdf_toolbar_new_test.js index 436484555..7a028b8 100644 --- a/chrome/test/data/pdf/viewer_pdf_toolbar_new_test.js +++ b/chrome/test/data/pdf/viewer_pdf_toolbar_new_test.js
@@ -141,6 +141,7 @@ function testZoomField() { const toolbar = createToolbar(); toolbar.viewportZoom = .8; + toolbar.zoomBounds = {min: 25, max: 500}; const zoomField = toolbar.shadowRoot.querySelector('#zoom-controls input'); chrome.test.assertEq('80%', zoomField.value); @@ -148,15 +149,50 @@ toolbar.viewportZoom = .533; chrome.test.assertEq('53%', zoomField.value); - // Setting a new value sends the value in a zoom-changed event. - let sentValue = -1; - toolbar.addEventListener('zoom-changed', e => { - sentValue = e.detail; - chrome.test.assertEq(110, sentValue); - chrome.test.succeed(); - }); - zoomField.value = '110%'; - zoomField.dispatchEvent(new CustomEvent('input')); + // Setting a non-number value resets to viewport zoom. + zoomField.value = 'abc'; + zoomField.dispatchEvent(new CustomEvent('change')); + chrome.test.assertEq('53%', zoomField.value); + + // Setting a value that is over the max zoom clips to the max value. + const whenSent = eventToPromise('zoom-changed', toolbar); + zoomField.value = '90000%'; + zoomField.dispatchEvent(new CustomEvent('change')); + whenSent + .then(e => { + chrome.test.assertEq(500, e.detail); + + // This happens in the parent. + toolbar.viewportZoom = 5; + chrome.test.assertEq('500%', zoomField.value); + + // Setting a value that is over the maximum again restores the max + // value, even though no event is sent. + zoomField.value = '80000%'; + zoomField.dispatchEvent(new CustomEvent('change')); + chrome.test.assertEq('500%', zoomField.value); + + // Setting a new value sends the value in a zoom-changed event. + const whenSentNew = eventToPromise('zoom-changed', toolbar); + zoomField.value = '110%'; + zoomField.dispatchEvent(new CustomEvent('change')); + return whenSentNew; + }) + .then(e => { + chrome.test.assertEq(110, e.detail); + + // Setting a new value and blurring sends the value in a zoom-changed + // event. If the value is below the minimum, this sends the minimum + // zoom. + const whenSentFromBlur = eventToPromise('zoom-changed', toolbar); + zoomField.value = '18%'; + zoomField.dispatchEvent(new CustomEvent('blur')); + return whenSentFromBlur; + }) + .then(e => { + chrome.test.assertEq(25, e.detail); + chrome.test.succeed(); + }); }, // Test that the overflow menu closes when an action is triggered.
diff --git a/chrome/test/data/policy/policy_test_cases.json b/chrome/test/data/policy/policy_test_cases.json index 0b8d384..7815892 100644 --- a/chrome/test/data/policy/policy_test_cases.json +++ b/chrome/test/data/policy/policy_test_cases.json
@@ -3862,6 +3862,22 @@ ] }, + "IntranetRedirectBehavior": { + "os": ["chromeos", "linux", "mac", "win"], + "test_policy": { "IntranetRedirectBehavior": 0 }, + "policy_pref_mapping_test": [ + { + "policies": { "IntranetRedirectBehavior": 0 }, + "prefs": { + "browser.intranet_redirect_behavior": { + "local_state": true, + "value": 0 + } + } + } + ] + }, + "----- Chrome OS policies ------------------------------------------------": {}, "ChromeOsLockOnIdleSuspend": {
diff --git a/chrome/test/data/webui/settings/chromeos/fake_user_action_recorder.js b/chrome/test/data/webui/settings/chromeos/fake_user_action_recorder.js index 7f8291d..9b70b41 100644 --- a/chrome/test/data/webui/settings/chromeos/fake_user_action_recorder.js +++ b/chrome/test/data/webui/settings/chromeos/fake_user_action_recorder.js
@@ -46,6 +46,10 @@ recordSettingChange() { ++this.settingChangeCount; } + + recordSettingChangeWithDetails() { + ++this.settingChangeCount; + } } // #cr_define_end
diff --git a/chrome/updater/app/app_install.cc b/chrome/updater/app/app_install.cc index f50caa2..4b63401 100644 --- a/chrome/updater/app/app_install.cc +++ b/chrome/updater/app/app_install.cc
@@ -24,6 +24,7 @@ #include "chrome/updater/prefs.h" #include "chrome/updater/registration_data.h" #include "chrome/updater/setup.h" +#include "chrome/updater/tag.h" #include "chrome/updater/update_service.h" #include "chrome/updater/updater_version.h" #include "components/prefs/pref_service.h" @@ -135,12 +136,33 @@ void AppInstall::RegisterUpdaterDone(const RegistrationResponse& response) { VLOG(1) << "Updater registration complete, code = " << response.status_code; - HandleAppId(); + MaybeInstallApp(); } -void AppInstall::HandleAppId() { - const std::string app_id = - base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(kAppIdSwitch); +void AppInstall::MaybeInstallApp() { + const std::string app_id = []() { + // Returns the app id parsed from the tag, if the --tag is specified, or + // the switch value of the --app-id command line argument. + // Otherwise, returns an empty string. + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); + const std::string tag = command_line->GetSwitchValueASCII(kTagSwitch); + if (!tag.empty()) { + tagging::TagArgs tag_args; + tagging::ErrorCode error = tagging::Parse(tag, base::nullopt, &tag_args); + if (error == tagging::ErrorCode::kSuccess) { + // TODO(crbug.com/1128631): support bundles. For now, assume one app. + DCHECK_EQ(tag_args.apps.size(), size_t{1}); + const std::string& app_id = tag_args.apps.front().app_id; + if (!app_id.empty()) { + return app_id; + } + } else { + VLOG(1) << "Tag parsing returned " << static_cast<int>(error) << "."; + } + } + return command_line->GetSwitchValueASCII(kAppIdSwitch); + }(); + if (app_id.empty()) { Shutdown(0); return;
diff --git a/chrome/updater/app/app_install.h b/chrome/updater/app/app_install.h index c145f1c..05584d33 100644 --- a/chrome/updater/app/app_install.h +++ b/chrome/updater/app/app_install.h
@@ -64,9 +64,9 @@ void RegisterUpdaterDone(const RegistrationResponse& response); - // Handles the --app-id command line argument, and triggers installing of the - // corresponding app-id if the argument is present. - void HandleAppId(); + // Handles the --tag and --app-id command line arguments, and triggers + // installing of the corresponding application if either argument is present. + void MaybeInstallApp(); // Bound to the main sequence. SEQUENCE_CHECKER(sequence_checker_);
diff --git a/chrome/updater/app/app_server_unittest.cc b/chrome/updater/app/app_server_unittest.cc index e174bf3..c491e42 100644 --- a/chrome/updater/app/app_server_unittest.cc +++ b/chrome/updater/app/app_server_unittest.cc
@@ -122,28 +122,32 @@ local_prefs->SetQualified(true); PrefsCommitPendingWrites(local_prefs->GetPrefService()); } - auto app = base::MakeRefCounted<AppServerTest>(); + { + auto app = base::MakeRefCounted<AppServerTest>(); - // Expect the app to SwapRpcInterfaces and then ActiveDuty then Shutdown(0). - EXPECT_CALL(*app, ActiveDuty).Times(1); - EXPECT_CALL(*app, SwapRPCInterfaces).WillOnce(Return(true)); - EXPECT_CALL(*app, UninstallSelf).Times(0); - EXPECT_EQ(app->Run(), 0); + // Expect the app to SwapRpcInterfaces and then ActiveDuty then Shutdown(0). + EXPECT_CALL(*app, ActiveDuty).Times(1); + EXPECT_CALL(*app, SwapRPCInterfaces).WillOnce(Return(true)); + EXPECT_CALL(*app, UninstallSelf).Times(0); + EXPECT_EQ(app->Run(), 0); + } std::unique_ptr<GlobalPrefs> global_prefs = CreateGlobalPrefs(); EXPECT_FALSE(global_prefs->GetSwapping()); EXPECT_EQ(global_prefs->GetActiveVersion(), UPDATER_VERSION_STRING); } TEST_F(AppServerTestCase, InstallAutoPromotes) { - auto app = base::MakeRefCounted<AppServerTest>(); + { + auto app = base::MakeRefCounted<AppServerTest>(); - // Expect the app to SwapRpcInterfaces and then ActiveDuty then Shutdown(0). - // In this case it bypasses qualification. - EXPECT_CALL(*app, ActiveDuty).Times(1); - EXPECT_CALL(*app, SwapRPCInterfaces).WillOnce(Return(true)); - EXPECT_CALL(*app, UninstallSelf).Times(0); - EXPECT_EQ(app->Run(), 0); - EXPECT_FALSE(CreateLocalPrefs()->GetQualified()); + // Expect the app to SwapRpcInterfaces and then ActiveDuty then Shutdown(0). + // In this case it bypasses qualification. + EXPECT_CALL(*app, ActiveDuty).Times(1); + EXPECT_CALL(*app, SwapRPCInterfaces).WillOnce(Return(true)); + EXPECT_CALL(*app, UninstallSelf).Times(0); + EXPECT_EQ(app->Run(), 0); + EXPECT_FALSE(CreateLocalPrefs()->GetQualified()); + } std::unique_ptr<GlobalPrefs> global_prefs = CreateGlobalPrefs(); EXPECT_FALSE(global_prefs->GetSwapping()); EXPECT_EQ(global_prefs->GetActiveVersion(), UPDATER_VERSION_STRING); @@ -155,13 +159,15 @@ local_prefs->SetQualified(true); PrefsCommitPendingWrites(local_prefs->GetPrefService()); } - auto app = base::MakeRefCounted<AppServerTest>(); + { + auto app = base::MakeRefCounted<AppServerTest>(); - // Expect the app to SwapRpcInterfaces and then Shutdown(2). - EXPECT_CALL(*app, ActiveDuty).Times(0); - EXPECT_CALL(*app, SwapRPCInterfaces).WillOnce(Return(false)); - EXPECT_CALL(*app, UninstallSelf).Times(0); - EXPECT_EQ(app->Run(), 2); + // Expect the app to SwapRpcInterfaces and then Shutdown(2). + EXPECT_CALL(*app, ActiveDuty).Times(0); + EXPECT_CALL(*app, SwapRPCInterfaces).WillOnce(Return(false)); + EXPECT_CALL(*app, UninstallSelf).Times(0); + EXPECT_EQ(app->Run(), 2); + } std::unique_ptr<GlobalPrefs> global_prefs = CreateGlobalPrefs(); EXPECT_TRUE(global_prefs->GetSwapping()); EXPECT_EQ(global_prefs->GetActiveVersion(), "0"); @@ -176,13 +182,15 @@ local_prefs->SetQualified(true); PrefsCommitPendingWrites(local_prefs->GetPrefService()); } - auto app = base::MakeRefCounted<AppServerTest>(); + { + auto app = base::MakeRefCounted<AppServerTest>(); - // Expect the app to ActiveDuty and then Shutdown(0). - EXPECT_CALL(*app, ActiveDuty).Times(1); - EXPECT_CALL(*app, SwapRPCInterfaces).Times(0); - EXPECT_CALL(*app, UninstallSelf).Times(0); - EXPECT_EQ(app->Run(), 0); + // Expect the app to ActiveDuty and then Shutdown(0). + EXPECT_CALL(*app, ActiveDuty).Times(1); + EXPECT_CALL(*app, SwapRPCInterfaces).Times(0); + EXPECT_CALL(*app, UninstallSelf).Times(0); + EXPECT_EQ(app->Run(), 0); + } std::unique_ptr<GlobalPrefs> global_prefs = CreateGlobalPrefs(); EXPECT_FALSE(global_prefs->GetSwapping()); EXPECT_EQ(global_prefs->GetActiveVersion(), UPDATER_VERSION_STRING); @@ -198,14 +206,16 @@ local_prefs->SetQualified(true); PrefsCommitPendingWrites(local_prefs->GetPrefService()); } - auto app = base::MakeRefCounted<AppServerTest>(); + { + auto app = base::MakeRefCounted<AppServerTest>(); - // Expect the app to SwapRpcInterfaces and then ActiveDuty and then - // Shutdown(0). - EXPECT_CALL(*app, ActiveDuty).Times(1); - EXPECT_CALL(*app, SwapRPCInterfaces).WillOnce(Return(true)); - EXPECT_CALL(*app, UninstallSelf).Times(0); - EXPECT_EQ(app->Run(), 0); + // Expect the app to SwapRpcInterfaces and then ActiveDuty and then + // Shutdown(0). + EXPECT_CALL(*app, ActiveDuty).Times(1); + EXPECT_CALL(*app, SwapRPCInterfaces).WillOnce(Return(true)); + EXPECT_CALL(*app, UninstallSelf).Times(0); + EXPECT_EQ(app->Run(), 0); + } std::unique_ptr<GlobalPrefs> global_prefs = CreateGlobalPrefs(); EXPECT_FALSE(global_prefs->GetSwapping()); EXPECT_EQ(global_prefs->GetActiveVersion(), UPDATER_VERSION_STRING); @@ -221,13 +231,15 @@ local_prefs->SetQualified(true); PrefsCommitPendingWrites(local_prefs->GetPrefService()); } - auto app = base::MakeRefCounted<AppServerTest>(); + { + auto app = base::MakeRefCounted<AppServerTest>(); - // Expect the app to SwapRpcInterfaces and Shutdown(2). - EXPECT_CALL(*app, ActiveDuty).Times(0); - EXPECT_CALL(*app, SwapRPCInterfaces).WillOnce(Return(false)); - EXPECT_CALL(*app, UninstallSelf).Times(0); - EXPECT_EQ(app->Run(), 2); + // Expect the app to SwapRpcInterfaces and Shutdown(2). + EXPECT_CALL(*app, ActiveDuty).Times(0); + EXPECT_CALL(*app, SwapRPCInterfaces).WillOnce(Return(false)); + EXPECT_CALL(*app, UninstallSelf).Times(0); + EXPECT_EQ(app->Run(), 2); + } std::unique_ptr<GlobalPrefs> global_prefs = CreateGlobalPrefs(); EXPECT_TRUE(global_prefs->GetSwapping()); EXPECT_EQ(global_prefs->GetActiveVersion(), UPDATER_VERSION_STRING);
diff --git a/chrome/updater/constants.cc b/chrome/updater/constants.cc index 7c1ed0f1f..ba10ff66 100644 --- a/chrome/updater/constants.cc +++ b/chrome/updater/constants.cc
@@ -28,6 +28,7 @@ const char kAppIdSwitch[] = "app-id"; const char kAppVersionSwitch[] = "app-version"; const char kWakeSwitch[] = "wake"; +const char kTagSwitch[] = "tag"; const char kServerServiceSwitch[] = "service"; const char kServerControlServiceSwitchValue[] = "control";
diff --git a/chrome/updater/constants.h b/chrome/updater/constants.h index 2d11a38..def9771 100644 --- a/chrome/updater/constants.h +++ b/chrome/updater/constants.h
@@ -19,7 +19,6 @@ // Command line switches. // - // This switch starts the COM server. This switch is invoked by the COM runtime // when CoCreate is called on one of several CLSIDs that the server supports. // We expect to use the COM server for the following scenarios: @@ -66,6 +65,13 @@ // Installs the updater. extern const char kInstallSwitch[]; +// Contains the meta installer tag. The tag is a string of arguments, separated +// by a delimiter (in this case, the delimiter is =). The tag is typically +// embedded in the program image of the metainstaller, but for testing purposes, +// the tag could be passed directly as a command line argument. The tag is +// currently encoded as a ASCII string. +extern const char kTagSwitch[]; + #if defined(OS_WIN) // A debug switch to indicate that --install is running from the `out` directory // of the build. When this switch is present, the setup picks up the run time
diff --git a/chrome/updater/prefs_mac.mm b/chrome/updater/prefs_mac.mm index a1dcd220..7bf705db 100644 --- a/chrome/updater/prefs_mac.mm +++ b/chrome/updater/prefs_mac.mm
@@ -4,18 +4,107 @@ #include "chrome/updater/prefs_impl.h" +#include <mach/mach.h> +#include <servers/bootstrap.h> + +#include "base/logging.h" +#include "base/mac/mach_logging.h" +#include "base/threading/platform_thread.h" #include "base/time/time.h" +#include "chrome/updater/updater_version.h" + +namespace { + +// Mach service name for the global prefs lock. +constexpr char kPrefsLockMachServiceName[] = + MAC_BUNDLE_IDENTIFIER_STRING ".lock"; + +// Interval to poll for lock availability if it is not immediately available. +// Final interval will be truncated to fit the available timeout. +constexpr base::TimeDelta kPrefsLockPollingInterval = + base::TimeDelta::FromSeconds(3); + +// +// Attempts to acquire the receive right to a named Mach service. +// Single attempt, no retries. Logs errors other than "permission denied", +// since "permission denied" typically means the service receive rights have +// already been assigned. +// +// Returns a mach_port_t representing the receive right if the right was +// successfully acquired. If the right cannot be acquired for any reason, +// returns MACH_PORT_NULL instead. +mach_port_t TryAcquireReceive(const char* service_name) { + mach_port_t target_port = MACH_PORT_NULL; + kern_return_t check_in_result = + bootstrap_check_in(bootstrap_port, service_name, &target_port); + if (check_in_result != KERN_SUCCESS) { + // Log error reports for all errors other than BOOTSTRAP_NOT_PRIVILEGED. + // BOOTSTRAP_NOT_PRIVILEGED is not logged because it just means that another + // process has acquired the receive rights for this service. + if (check_in_result != BOOTSTRAP_NOT_PRIVILEGED) { + BOOTSTRAP_LOG(ERROR, check_in_result) + << "bootstrap_check_in to acquire prefs lock: " + << kPrefsLockMachServiceName; + } else { + BOOTSTRAP_VLOG(2, check_in_result) + << "Prefs lock already held: " << kPrefsLockMachServiceName; + } + return MACH_PORT_NULL; + } + return target_port; +} + +// Sleep until the lock should be retried, up to an approximate maximum of +// max_wait (within the tolerances of timing, scheduling, etc.). +void WaitToRetryLock(base::TimeDelta max_wait) { + // This is a polling implementation of Mach service locking. + // TODO(1135787): replace with a non-polling Mach notification approach. + const base::TimeDelta wait_time = max_wait < kPrefsLockPollingInterval + ? max_wait + : kPrefsLockPollingInterval; + base::PlatformThread::Sleep(wait_time); +} + +} // anonymous namespace namespace updater { class ScopedPrefsLockImpl { public: - ScopedPrefsLockImpl() = default; + // Constructs a ScopedPrefsLockImpl from a receive right. + explicit ScopedPrefsLockImpl(mach_port_t receive_port); + + // Releases the receive right (and therefore releases the lock). + ~ScopedPrefsLockImpl(); + ScopedPrefsLockImpl(const ScopedPrefsLockImpl&) = delete; ScopedPrefsLockImpl& operator=(const ScopedPrefsLockImpl&) = delete; - ~ScopedPrefsLockImpl() = default; + + private: + // The Mach port representing the held lock itself. We only care about + // service ownership; no messages are transfered with this port. + mach_port_t receive_port_; }; +ScopedPrefsLockImpl::ScopedPrefsLockImpl(mach_port_t receive_port) + : receive_port_(receive_port) { + // Verify the validity of the lock. + mach_port_type_t port_type = 0; + kern_return_t port_check_result = + mach_port_type(mach_task_self(), receive_port, &port_type); + MACH_CHECK(port_check_result == KERN_SUCCESS, port_check_result) + << "ScopedPrefsLockImpl could not verify lock port"; + CHECK(port_type & MACH_PORT_TYPE_RECEIVE) + << "ScopedPrefsLockImpl given port without receive right"; +} + +ScopedPrefsLockImpl::~ScopedPrefsLockImpl() { + kern_return_t destroy_result = + mach_port_destroy(mach_task_self(), receive_port_); + MACH_LOG_IF(ERROR, destroy_result != KERN_SUCCESS, destroy_result) + << "ScopedPrefsLockImpl could not destroy port"; +} + ScopedPrefsLock::ScopedPrefsLock(std::unique_ptr<ScopedPrefsLockImpl> impl) : impl_(std::move(impl)) {} @@ -23,9 +112,30 @@ std::unique_ptr<ScopedPrefsLock> AcquireGlobalPrefsLock( base::TimeDelta timeout) { - // TODO(crbug.com/1092936): implement the actual mutex. - return std::make_unique<ScopedPrefsLock>( - std::make_unique<ScopedPrefsLockImpl>()); + // First, try to acquire the lock. If the timeout is zero or negative, + // this is the only attempt we will make. + mach_port_t lock_port = TryAcquireReceive(kPrefsLockMachServiceName); + + // Set up time limits. + base::TimeTicks deadline = base::TimeTicks::Now() + timeout; + constexpr base::TimeDelta kDeltaZero; + + // Loop until we acquire the lock or time out. Note that we have already + // tried once to acquire the lock, so this loop will execute zero times + // if we have already succeeded (or if the timeout was zero). Therefore, + // this loop waits for retry *before* attempting to acquire the lock; + // the special case of the first try was handled outside the loop. + for (base::TimeDelta remain = deadline - base::TimeTicks::Now(); + lock_port == MACH_PORT_NULL && remain > kDeltaZero; + remain = deadline - base::TimeTicks::Now()) { + WaitToRetryLock(remain); + lock_port = TryAcquireReceive(kPrefsLockMachServiceName); + } + + return lock_port == MACH_PORT_NULL + ? nullptr + : std::make_unique<ScopedPrefsLock>( + std::make_unique<ScopedPrefsLockImpl>(lock_port)); } } // namespace updater
diff --git a/chrome/updater/prefs_unittest.cc b/chrome/updater/prefs_unittest.cc index d808a52..d1ec170 100644 --- a/chrome/updater/prefs_unittest.cc +++ b/chrome/updater/prefs_unittest.cc
@@ -33,21 +33,6 @@ PrefsCommitPendingWrites(pref.get()); } -#if defined(OS_WIN) - -TEST(PrefsTest, AcquireGlobalPrefsLock_LockAgainSameThread) { - base::test::TaskEnvironment task_environment( - base::test::SingleThreadTaskEnvironment::MainThreadType::UI); - - std::unique_ptr<ScopedPrefsLock> lock = - AcquireGlobalPrefsLock(base::TimeDelta::FromSeconds(0)); - EXPECT_TRUE(lock); - - std::unique_ptr<ScopedPrefsLock> same_thread_lock = - AcquireGlobalPrefsLock(base::TimeDelta::FromSeconds(0)); - EXPECT_TRUE(same_thread_lock); -} - TEST(PrefsTest, AcquireGlobalPrefsLock_LockThenTryLockInThreadFail) { base::test::TaskEnvironment task_environment( base::test::SingleThreadTaskEnvironment::MainThreadType::UI); @@ -93,6 +78,4 @@ EXPECT_TRUE(lock); } -#endif - } // namespace updater
diff --git a/chrome/updater/test/integration_tests_win.cc b/chrome/updater/test/integration_tests_win.cc index fcab7f4..bc8fa00 100644 --- a/chrome/updater/test/integration_tests_win.cc +++ b/chrome/updater/test/integration_tests_win.cc
@@ -20,9 +20,7 @@ #include "testing/gtest/include/gtest/gtest.h" namespace updater { - namespace test { - namespace { base::FilePath GetInstallerPath() { @@ -143,8 +141,12 @@ } void Install() { + const base::FilePath path = GetInstallerPath(); + ASSERT_FALSE(path.empty()); + base::CommandLine command_line(path); + command_line.AppendSwitch(kInstallSwitch); int exit_code = -1; - ASSERT_TRUE(Run(base::CommandLine(GetInstallerPath()), &exit_code)); + ASSERT_TRUE(Run(command_line, &exit_code)); EXPECT_EQ(0, exit_code); } @@ -159,5 +161,4 @@ } } // namespace test - } // namespace updater
diff --git a/chrome/updater/updater.cc b/chrome/updater/updater.cc index 305491b..2cdc822b 100644 --- a/chrome/updater/updater.cc +++ b/chrome/updater/updater.cc
@@ -108,7 +108,8 @@ return ServiceMain::RunComService(command_line); #endif // OS_WIN - if (command_line->HasSwitch(kInstallSwitch)) + if (command_line->HasSwitch(kInstallSwitch) || + command_line->HasSwitch(kTagSwitch)) return MakeAppInstall()->Run(); if (command_line->HasSwitch(kUninstallSwitch))
diff --git a/chrome/updater/win/BUILD.gn b/chrome/updater/win/BUILD.gn index 0bea867..027dfa0 100644 --- a/chrome/updater/win/BUILD.gn +++ b/chrome/updater/win/BUILD.gn
@@ -171,6 +171,25 @@ } } +source_set("tag_extractor") { + public = [ "tag_extractor.h" ] + + sources = [ + "tag_extractor.cc", + "tag_extractor_impl.h", + ] + + friend = [ + ":updater_tests", + ":updater_fuzzer", + ] + + # In the future, we want to rely on the base numerics headers and + # PeImageReader directly, but right now that isn't possible due to the + # visibility of the lib, so we depend on the entire base temporarily. + deps = [ "//base" ] +} + source_set("updater_tests") { testonly = true @@ -231,25 +250,6 @@ data = [ "//chrome/updater/test/data/updater.runtime_deps" ] } -source_set("tag_extractor") { - public = [ "tag_extractor.h" ] - - sources = [ - "tag_extractor.cc", - "tag_extractor_impl.h", - ] - - friend = [ - ":updater_tests", - ":updater_fuzzer", - ] - - # In the future, we want to rely on the base numerics headers and - # PeImageReader directly, but right now that isn't possible due to the - # visibility of the lib, so we depend on the entire base temporarily. - deps = [ "//base" ] -} - fuzzer_test("updater_fuzzer") { sources = [ "tag_extractor_fuzzer.cc" ]
diff --git a/chrome/updater/win/installer/BUILD.gn b/chrome/updater/win/installer/BUILD.gn index bce7288..b0e3496 100644 --- a/chrome/updater/win/installer/BUILD.gn +++ b/chrome/updater/win/installer/BUILD.gn
@@ -28,6 +28,7 @@ deps = [ "//base", "//chrome/installer/util:with_no_strings", + "//chrome/updater/win:tag_extractor", ] }
diff --git a/chrome/updater/win/installer/installer.cc b/chrome/updater/win/installer/installer.cc index 15ccdf9..66eb9ea 100644 --- a/chrome/updater/win/installer/installer.cc +++ b/chrome/updater/win/installer/installer.cc
@@ -24,15 +24,19 @@ #include <shellapi.h> #include <stddef.h> #include <stdlib.h> +#include <string.h> #include <initializer_list> +#include <string> -// TODO(sorin): remove the dependecies on //base/ to reduce the code size. +// TODO(crbug.com/1128529): remove the dependencies on //base/ to reduce the +// code size. #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/logging.h" #include "base/path_service.h" +#include "base/strings/sys_string_conversions.h" #include "chrome/installer/util/lzma_util.h" #include "chrome/installer/util/self_cleaning_temp_dir.h" #include "chrome/installer/util/util_constants.h" @@ -40,9 +44,12 @@ #include "chrome/updater/win/installer/installer_constants.h" #include "chrome/updater/win/installer/pe_resource.h" #include "chrome/updater/win/installer/regkey.h" +#include "chrome/updater/win/tag_extractor.h" namespace updater { +using PathString = StackString<MAX_PATH>; + namespace { // Initializes |temp_path| to "Temp" within the target directory, and @@ -72,9 +79,20 @@ return true; } -} // namespace +// Returns the tag if the tag can be extracted. The tag is read from the +// program file image used to create this process. Google is using UTF8 tags but +// other embedders could use UTF16. The UTF16 tag not only uses a different +// character width, but the tag is inserted in a different way.] +// The implementation of this function only handles UTF8 tags. +std::string ExtractTag() { + PathString path; + return (::GetModuleFileName(nullptr, path.get(), path.capacity()) > 0 && + ::GetLastError() == ERROR_SUCCESS) + ? ExtractTagFromFile(path.get(), TagEncoding::kUtf8) + : std::string(); +} -using PathString = StackString<MAX_PATH>; +} // namespace // This structure passes data back and forth for the processing // of resource callbacks. @@ -208,12 +226,8 @@ !cmd_line.append(L"\"")) { return ProcessExitResult(COMMAND_STRING_OVERFLOW); } - if (!cmd_line.append(L" --install --enable-logging" - L" --vmodule=*/chrome/updater/*=2")) { - return ProcessExitResult(COMMAND_STRING_OVERFLOW); - } - // Append to the command line arguments this program has been invoked with. + // Append the command line arguments this program has been invoked with. int num_args = 0; wchar_t** const arg_list = ::CommandLineToArgvW(::GetCommandLineW(), &num_args); @@ -223,6 +237,35 @@ } } + // Handle the tag. Use the tag from the --tag command line argument if such + // argument exists. If --tag is present in the arg_list, then it is going + // to be handed over to the updater, along with the other arguments. + // Otherwise, try extracting a tag embedded in the program image of the meta + // installer. + if (![arg_list, num_args]() { + // Returns true if the --tag argument is present on the command line. + constexpr wchar_t kTagSwitch[] = L"--tag="; + for (int i = 1; i != num_args; ++i) { + if (memcmp(arg_list[i], kTagSwitch, sizeof(kTagSwitch)) == 0) + return true; + } + return false; + }()) { + const std::string tag = ExtractTag(); + if (!tag.empty()) { + if (!cmd_line.append(L" --tag=") || + !cmd_line.append(base::SysUTF8ToWide(tag).c_str())) { + return ProcessExitResult(COMMAND_STRING_OVERFLOW); + } + } + } + + // Append logging-related arguments for debugging purposes, at least for + // now. + if (!cmd_line.append(L" --enable-logging --vmodule=*/chrome/updater/*=2")) { + return ProcessExitResult(COMMAND_STRING_OVERFLOW); + } + return RunProcessAndWait(setup_exe.get(), cmd_line.get()); }
diff --git a/chrome/updater/win/signing/sign.py b/chrome/updater/win/signing/sign.py index 32383f8..420fff8 100755 --- a/chrome/updater/win/signing/sign.py +++ b/chrome/updater/win/signing/sign.py
@@ -78,7 +78,7 @@ self._sign_item(os.path.join(root, f)) elif ext == '.7z': self._sign_7z(os.path.join(root, f)) - subprocess.run([self._lzma_exe, 'a', in_file, '*'], + subprocess.run([self._lzma_exe, 'a', '-mx0', in_file, '*'], check=True, cwd=tmp)
diff --git a/chrome/utility/BUILD.gn b/chrome/utility/BUILD.gn index c1d147f..1d6b82c 100644 --- a/chrome/utility/BUILD.gn +++ b/chrome/utility/BUILD.gn
@@ -170,10 +170,10 @@ deps += [ "//chrome/services/file_util", "//chrome/services/sharing", - "//chrome/services/sharing/public/mojom:mojom", "//chromeos/assistant:buildflags", "//chromeos/services/ime:lib", "//chromeos/services/ime/public/mojom", + "//chromeos/services/nearby/public/mojom:mojom", "//chromeos/services/tts", "//chromeos/services/tts/public/mojom", ]
diff --git a/chrome/utility/DEPS b/chrome/utility/DEPS index 1075c89..29b5f28c 100644 --- a/chrome/utility/DEPS +++ b/chrome/utility/DEPS
@@ -24,6 +24,7 @@ "+chromeos/services/assistant", "+chromeos/services/ime/ime_service.h", "+chromeos/services/ime/public/mojom", + "+chromeos/services/nearby", "+chromeos/services/tts", "+components/crash/core/common/crash_keys.h", "+components/mirroring/mojom",
diff --git a/chrome/utility/services.cc b/chrome/utility/services.cc index 8fd970b..0c00f9c 100644 --- a/chrome/utility/services.cc +++ b/chrome/utility/services.cc
@@ -82,11 +82,11 @@ #include "components/services/paint_preview_compositor/public/mojom/paint_preview_compositor.mojom.h" #if defined(OS_CHROMEOS) -#include "chrome/services/sharing/public/mojom/sharing.mojom.h" // nogncheck #include "chrome/services/sharing/sharing_impl.h" #include "chromeos/assistant/buildflags.h" // nogncheck #include "chromeos/services/ime/ime_service.h" #include "chromeos/services/ime/public/mojom/input_engine.mojom.h" +#include "chromeos/services/nearby/public/mojom/sharing.mojom.h" // nogncheck #include "chromeos/services/tts/public/mojom/tts_service.mojom.h" #include "chromeos/services/tts/tts_service.h"
diff --git a/chromecast/bindings/BUILD.gn b/chromecast/bindings/BUILD.gn index 6b2c0994..210771d 100644 --- a/chromecast/bindings/BUILD.gn +++ b/chromecast/bindings/BUILD.gn
@@ -65,9 +65,9 @@ "//base", "//chromecast/browser:public", "//components/cast/api_bindings:manager", + "//components/cast/message_port", "//components/cast/named_message_port_connector", "//components/on_load_script_injector/browser", - "//third_party/blink/public/common", ] } @@ -87,6 +87,7 @@ "//chromecast/bindings:bindings_manager_cast", "//chromecast/browser:browser", "//chromecast/browser:public", + "//components/cast/message_port:test_message_port_receiver", "//components/cast/named_message_port_connector:resources", "//content/public/browser", "//content/test:test_support",
diff --git a/chromecast/bindings/DEPS b/chromecast/bindings/DEPS index 3d4e6ee..6bb1e65 100644 --- a/chromecast/bindings/DEPS +++ b/chromecast/bindings/DEPS
@@ -9,7 +9,5 @@ "+fuchsia", "+mojo/public", "+net/test", - "+third_party/blink/public/common/messaging", - "+third_party/blink/public/mojom/messaging", "+ui/base/resource", ]
diff --git a/chromecast/bindings/OWNERS b/chromecast/bindings/OWNERS new file mode 100644 index 0000000..3520a47 --- /dev/null +++ b/chromecast/bindings/OWNERS
@@ -0,0 +1,4 @@ +derekjchow@chromium.org +lijiawei@chromium.org +maclellant@chromium.org +kmarshall@chromium.org
diff --git a/chromecast/bindings/bindings_manager_cast.cc b/chromecast/bindings/bindings_manager_cast.cc index f8a142f5..e162da2 100644 --- a/chromecast/bindings/bindings_manager_cast.cc +++ b/chromecast/bindings/bindings_manager_cast.cc
@@ -25,13 +25,8 @@ port_connector_ = std::make_unique<NamedMessagePortConnectorCast>(cast_web_contents_, this); - // TODO(crbug.com/1135379): Remove static_cast with deprecated OnPortConnected - // overload - port_connector_->RegisterPortHandler( - base::BindRepeating(static_cast<bool (BindingsManagerCast::*)( - base::StringPiece, blink::WebMessagePort)>( - &BindingsManagerCast::OnPortConnected), - base::Unretained(this))); + port_connector_->RegisterPortHandler(base::BindRepeating( + &BindingsManagerCast::OnPortConnected, base::Unretained(this))); } BindingsManagerCast::~BindingsManagerCast() = default;
diff --git a/chromecast/bindings/bindings_manager_cast_browsertest.cc b/chromecast/bindings/bindings_manager_cast_browsertest.cc index 04ac5e5..ba4c7054 100644 --- a/chromecast/bindings/bindings_manager_cast_browsertest.cc +++ b/chromecast/bindings/bindings_manager_cast_browsertest.cc
@@ -23,6 +23,7 @@ #include "chromecast/browser/cast_browser_context.h" #include "chromecast/browser/cast_browser_process.h" #include "chromecast/browser/cast_web_contents_impl.h" +#include "components/cast/message_port/test_message_port_receiver.h" #include "content/public/common/content_switches.h" #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_base.h" @@ -62,15 +63,6 @@ return file_path.Append(GetTestDataPath()).AppendASCII(name); } -base::Optional<std::string> ReadMessagePayloadAsUtf8( - blink::WebMessagePort::Message message) { - std::string output; - if (!base::UTF16ToUTF8(message.data.data(), message.data.size(), &output)) - return base::nullopt; - - return base::make_optional<std::string>(output); -} - class TitleChangeObserver : public CastWebContents::Observer { public: TitleChangeObserver() = default; @@ -109,119 +101,6 @@ DISALLOW_COPY_AND_ASSIGN(TitleChangeObserver); }; -// Test class for communicating with connector.html. -class TestBindingBackend : public blink::WebMessagePort::MessageReceiver { - public: - TestBindingBackend(bindings::BindingsManagerCast* bindings_manager) - : bindings_manager_(bindings_manager) { - constexpr char kPortName[] = "hello"; - bindings_manager_->RegisterPortHandler( - kPortName, base::BindRepeating(&TestBindingBackend::OnPortConnected, - base::Unretained(this))); - } - - ~TestBindingBackend() override { - port_.Reset(); - constexpr char kPortName[] = "hello"; - bindings_manager_->UnregisterPortHandler(kPortName); - } - - // Start the RunLoop until OnPortConnected. - void RunUntilPortConnected() { - if (port_.IsValid()) - return; - - base::RunLoop run_loop; - quit_closure_ = run_loop.QuitClosure(); - run_loop.Run(); - } - - // Run the callback if there is at least one available message - // cached. - void ReceiveMessage(base::OnceCallback<void(std::string)> callback) { - ASSERT_TRUE(message_received_callback_.is_null()) - << "Only one waiting event is allowed."; - - // Run the callback immediately if we have cached some messages. - if (!message_queue_.empty()) { - std::move(message_received_callback_).Run(message_queue_.front()); - message_queue_.pop_front(); - return; - } - - message_received_callback_ = std::move(callback); - } - - void SendMessageToPage(base::StringPiece message) { - if (!port_.IsValid()) - return; - - DCHECK(!message.empty()); - - blink::WebMessagePort::Message blink_message(base::UTF8ToUTF16(message)); - port_.PostMessage(std::move(blink_message)); - } - - void SetPortDisconnectedCallback( - base::OnceClosure port_disconnected_callback) { - DCHECK(!port_disconnected_callback_); - port_disconnected_callback_ = std::move(port_disconnected_callback); - } - - private: - // Called when a port was received from the page. - void OnPortConnected(blink::WebMessagePort port) { - if (!quit_closure_.is_null()) { - std::move(quit_closure_).Run(); - } - port_ = std::move(port); - port_.SetReceiver(this, base::ThreadTaskRunnerHandle::Get()); - } - - // blink::WebMessagePort::MessageReceiver implementation: - bool OnMessage(blink::WebMessagePort::Message message) override { - base::Optional<std::string> message_json = - ReadMessagePayloadAsUtf8(std::move(message)); - if (!message_json) - return false; - - if (message_received_callback_) { - // Number of cached messages must be zero in this case. - DCHECK(message_queue_.empty()); - std::move(message_received_callback_).Run(message_json.value()); - return true; - } - - // Cache received message until external caller access it - // via TestBindingBackend::ReceiveMessage - message_queue_.emplace_back(message_json.value()); - return true; - } - - // blink::WebMessagePort::MessageReceiver implementation: - // Called when the peer disconnected the port. - void OnPipeError() override { - LOG(INFO) << "TestBindingBackend port disconnected."; - port_.Reset(); - if (port_disconnected_callback_) { - std::move(port_disconnected_callback_).Run(); - } - } - - base::OnceClosure quit_closure_; - - bindings::BindingsManager* const bindings_manager_; - - // Used for sending and receiving messages over the MessagePort. - blink::WebMessagePort port_; - - base::circular_deque<std::string> message_queue_; - base::OnceCallback<void(std::string)> message_received_callback_; - base::OnceClosure port_disconnected_callback_; - - DISALLOW_COPY_AND_ASSIGN(TestBindingBackend); -}; - // ============================================================================= // Mocks // ============================================================================= @@ -316,6 +195,38 @@ DISALLOW_COPY_AND_ASSIGN(BindingsManagerCastBrowserTest); }; +// Handles connected ports from the NamedMessagePortConnector and +// provides a convenience methods for waiting for and then returning the port +// synchronously. +class MessagePortConnectionHandler { + public: + MessagePortConnectionHandler() {} + ~MessagePortConnectionHandler() {} + + cast_api_bindings::Manager::MessagePortConnectedHandler GetConnectCallback() { + return base::BindRepeating(&MessagePortConnectionHandler::OnConnect, + base::Unretained(this)); + } + + std::unique_ptr<cast_api_bindings::MessagePort> RunUntilPortConnected() { + base::RunLoop run_loop; + on_port_connected_ = run_loop.QuitClosure(); + run_loop.Run(); + return std::move(port_); + } + + private: + void OnConnect(std::unique_ptr<cast_api_bindings::MessagePort> port) { + DCHECK(on_port_connected_); + + port_ = std::move(port); + std::move(on_port_connected_).Run(); + } + + base::OnceClosure on_port_connected_; + std::unique_ptr<cast_api_bindings::MessagePort> port_; +}; + // ============================================================================= // Test cases // ============================================================================= @@ -340,57 +251,32 @@ GURL test_url = content::GetFileUrlWithQuery(GetTestDataFilePath("connector.html"), ""); - // Register test port handler. - auto test_binding_backend = - std::make_unique<TestBindingBackend>(bindings_manager_.get()); - // TestBindingBackend test_binding_backend(bindings_manager_.get()); + MessagePortConnectionHandler connect_handler; + bindings_manager_->RegisterPortHandler("hello", + connect_handler.GetConnectCallback()); // Load test page. constexpr char kTestPageTitle[] = "bindings"; cast_web_contents_->LoadUrl(test_url); title_change_observer_.RunUntilTitleEquals(kTestPageTitle); - // Start RunLoop until TestBindingBackend receives MessagePort. - test_binding_backend->RunUntilPortConnected(); + auto message_port = connect_handler.RunUntilPortConnected(); + cast_api_bindings::TestMessagePortReceiver receiver; + message_port->SetReceiver(&receiver); - // Send ping message to the test page. - test_binding_backend->SendMessageToPage("ping"); + message_port->PostMessage("ping"); // Test that message are received in order. - std::vector<std::string> test_messages = {"early 1", "early 2", "ack ping"}; - for (auto test_message : test_messages) { - base::RunLoop run_loop; - auto quit_closure = run_loop.QuitClosure(); - auto received_message_callback = base::BindOnce( - [](base::OnceClosure loop_quit_closure, std::string expected_msg, - std::string port_msg) { - EXPECT_EQ(expected_msg, port_msg); - std::move(loop_quit_closure).Run(); - }, - std::move(quit_closure), test_message); - test_binding_backend->ReceiveMessage(std::move(received_message_callback)); - run_loop.Run(); - } + receiver.RunUntilMessageCountEqual(3); + EXPECT_EQ(receiver.buffer()[0].first, "early 1"); + EXPECT_EQ(receiver.buffer()[1].first, "early 2"); + EXPECT_EQ(receiver.buffer()[2].first, "ack ping"); // Ensure that the MessagePort is dropped when navigating away. - { - base::RunLoop run_loop; + cast_web_contents_->LoadUrl(GURL(url::kAboutBlankURL)); + receiver.RunUntilDisconnected(); - auto port_disconnected_callback = base::BindOnce( - [](base::OnceClosure loop_quit_closure) { - std::move(loop_quit_closure).Run(); - }, - run_loop.QuitClosure()); - test_binding_backend->SetPortDisconnectedCallback( - std::move(port_disconnected_callback)); - - cast_web_contents_->LoadUrl(GURL(url::kAboutBlankURL)); - - run_loop.Run(); - } - - // Destruct the binding backend to unregister itself from BindingsManagerCast - test_binding_backend.reset(); + bindings_manager_->UnregisterPortHandler("hello"); } } // namespace chromecast
diff --git a/chromecast/bindings/named_message_port_connector_cast.cc b/chromecast/bindings/named_message_port_connector_cast.cc index 6f4456a15..b50694f5 100644 --- a/chromecast/bindings/named_message_port_connector_cast.cc +++ b/chromecast/bindings/named_message_port_connector_cast.cc
@@ -11,6 +11,7 @@ #include "base/strings/utf_string_conversions.h" #include "chromecast/browser/cast_web_contents.h" #include "components/cast/api_bindings/manager.h" +#include "components/cast/message_port/message_port_cast.h" #include "components/cast/named_message_port_connector/grit/named_message_port_connector_resources.h" #include "ui/base/resource/resource_bundle.h" @@ -45,10 +46,16 @@ void NamedMessagePortConnectorCast::OnPageLoaded() { // Send the port connection message to the page once it is loaded. - blink::WebMessagePort::Message connect_message = GetConnectMessage(); - cast_web_contents_->PostMessageToMainFrame( - "*", base::UTF16ToUTF8(connect_message.data), - std::move(connect_message.ports)); + std::string connect_message; + std::unique_ptr<cast_api_bindings::MessagePort> port; + GetConnectMessage(&connect_message, &port); + + std::vector<blink::WebMessagePort> ports; + ports.push_back( + cast_api_bindings::MessagePortCast::FromMessagePort(port.get()) + ->TakePort()); + cast_web_contents_->PostMessageToMainFrame("*", connect_message, + std::move(ports)); } } // namespace bindings
diff --git a/chromecast/browser/android/BUILD.gn b/chromecast/browser/android/BUILD.gn index 9c0cf707..a73b250 100644 --- a/chromecast/browser/android/BUILD.gn +++ b/chromecast/browser/android/BUILD.gn
@@ -26,7 +26,6 @@ java_cpp_template("cast_shell_build_config_gen") { sources = [ "apk/templates/BuildConfig.template" ] - package_path = "org/chromium/chromecast/shell" defines = [] if (display_web_contents_in_service) {
diff --git a/chromeos/components/phonehub/BUILD.gn b/chromeos/components/phonehub/BUILD.gn index 16980ba..c102f67 100644 --- a/chromeos/components/phonehub/BUILD.gn +++ b/chromeos/components/phonehub/BUILD.gn
@@ -134,6 +134,8 @@ sources = [ "fake_browser_tabs_metadata_fetcher.cc", "fake_browser_tabs_metadata_fetcher.h", + "fake_browser_tabs_model_provider.cc", + "fake_browser_tabs_model_provider.h", "fake_connection_manager.cc", "fake_connection_manager.h", "fake_message_receiver.h", @@ -158,6 +160,7 @@ testonly = true sources = [ + "browser_tabs_model_controller_unittest.cc", "browser_tabs_model_unittest.cc", "connection_manager_impl_unittest.cc", "connection_scheduler_impl_unittest.cc",
diff --git a/chromeos/components/phonehub/browser_tabs_model_controller.cc b/chromeos/components/phonehub/browser_tabs_model_controller.cc index 1695440..d3c0b48 100644 --- a/chromeos/components/phonehub/browser_tabs_model_controller.cc +++ b/chromeos/components/phonehub/browser_tabs_model_controller.cc
@@ -6,16 +6,25 @@ namespace chromeos { namespace phonehub { +namespace { +using multidevice_setup::mojom::Feature; +using multidevice_setup::mojom::FeatureState; +} // namespace BrowserTabsModelController::BrowserTabsModelController( + multidevice_setup::MultiDeviceSetupClient* multidevice_setup_client, BrowserTabsModelProvider* browser_tabs_model_provider, MutablePhoneModel* mutable_phone_model) - : browser_tabs_model_provider_(browser_tabs_model_provider), + : multidevice_setup_client_(multidevice_setup_client), + cached_model_(/*is_tab_sync_enabled=*/false), + browser_tabs_model_provider_(browser_tabs_model_provider), mutable_phone_model_(mutable_phone_model) { + multidevice_setup_client_->AddObserver(this); browser_tabs_model_provider_->AddObserver(this); } BrowserTabsModelController::~BrowserTabsModelController() { + multidevice_setup_client_->RemoveObserver(this); browser_tabs_model_provider_->RemoveObserver(this); } @@ -23,8 +32,23 @@ bool is_sync_enabled, const std::vector<BrowserTabsModel::BrowserTabMetadata>& browser_tabs_metadata) { - mutable_phone_model_->SetBrowserTabsModel(BrowserTabsModel( - /*is_tab_sync_enabled=*/is_sync_enabled, browser_tabs_metadata)); + cached_model_ = BrowserTabsModel(is_sync_enabled, browser_tabs_metadata); + UpdateBrowserTabsModel(); +} + +void BrowserTabsModelController::OnFeatureStatesChanged( + const multidevice_setup::MultiDeviceSetupClient::FeatureStatesMap& + feature_states_map) { + UpdateBrowserTabsModel(); +} + +void BrowserTabsModelController::UpdateBrowserTabsModel() { + FeatureState feature_state = multidevice_setup_client_->GetFeatureState( + Feature::kPhoneHubTaskContinuation); + if (feature_state == FeatureState::kEnabledByUser) + mutable_phone_model_->SetBrowserTabsModel(cached_model_); + else + mutable_phone_model_->SetBrowserTabsModel(base::nullopt); } } // namespace phonehub
diff --git a/chromeos/components/phonehub/browser_tabs_model_controller.h b/chromeos/components/phonehub/browser_tabs_model_controller.h index faf5d31..3af835d 100644 --- a/chromeos/components/phonehub/browser_tabs_model_controller.h +++ b/chromeos/components/phonehub/browser_tabs_model_controller.h
@@ -8,15 +8,19 @@ #include "chromeos/components/phonehub/browser_tabs_model.h" #include "chromeos/components/phonehub/browser_tabs_model_provider.h" #include "chromeos/components/phonehub/mutable_phone_model.h" +#include "chromeos/services/multidevice_setup/public/cpp/multidevice_setup_client.h" namespace chromeos { namespace phonehub { // This class sets a MutablePhoneModel by observing info provided by the // BrowserTabsModelProvider. -class BrowserTabsModelController : public BrowserTabsModelProvider::Observer { +class BrowserTabsModelController + : public BrowserTabsModelProvider::Observer, + public multidevice_setup::MultiDeviceSetupClient::Observer { public: BrowserTabsModelController( + multidevice_setup::MultiDeviceSetupClient* multidevice_setup_client, BrowserTabsModelProvider* browser_tabs_model_provider, MutablePhoneModel* mutable_phone_model); ~BrowserTabsModelController() override; @@ -28,6 +32,15 @@ const std::vector<BrowserTabsModel::BrowserTabMetadata>& browser_tabs_metadata) override; + // multidevice_setup::MultiDeviceSetupClient::Observer: + void OnFeatureStatesChanged( + const multidevice_setup::MultiDeviceSetupClient::FeatureStatesMap& + feature_states_map) override; + + void UpdateBrowserTabsModel(); + + multidevice_setup::MultiDeviceSetupClient* multidevice_setup_client_; + BrowserTabsModel cached_model_; BrowserTabsModelProvider* browser_tabs_model_provider_; MutablePhoneModel* mutable_phone_model_; };
diff --git a/chromeos/components/phonehub/browser_tabs_model_controller_unittest.cc b/chromeos/components/phonehub/browser_tabs_model_controller_unittest.cc new file mode 100644 index 0000000..6eb72f9 --- /dev/null +++ b/chromeos/components/phonehub/browser_tabs_model_controller_unittest.cc
@@ -0,0 +1,81 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chromeos/components/phonehub/browser_tabs_model_controller.h" + +#include "chromeos/components/phonehub/fake_browser_tabs_model_provider.h" +#include "chromeos/components/phonehub/mutable_phone_model.h" +#include "chromeos/components/phonehub/phone_model_test_util.h" +#include "chromeos/services/multidevice_setup/public/cpp/fake_multidevice_setup_client.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace chromeos { +namespace phonehub { + +using multidevice_setup::mojom::Feature; +using multidevice_setup::mojom::FeatureState; + +class BrowserTabsModelControllerTest : public testing::Test { + protected: + BrowserTabsModelControllerTest() = default; + ~BrowserTabsModelControllerTest() override = default; + + BrowserTabsModelControllerTest(const BrowserTabsModelControllerTest&) = + delete; + BrowserTabsModelControllerTest& operator=( + const BrowserTabsModelControllerTest&) = delete; + + // testing::Test: + void SetUp() override { + phone_model_ = std::make_unique<MutablePhoneModel>(); + controller_ = std::make_unique<BrowserTabsModelController>( + &fake_multidevice_setup_client_, &fake_browser_tabs_model_provider_, + phone_model_.get()); + } + + void DisableTaskContinuation() { + fake_multidevice_setup_client_.SetFeatureState( + Feature::kPhoneHubTaskContinuation, FeatureState::kDisabledByUser); + } + + void EnableTaskContinuation() { + fake_multidevice_setup_client_.SetFeatureState( + Feature::kPhoneHubTaskContinuation, FeatureState::kEnabledByUser); + } + + void NotifyBrowserTabsUpdated( + bool is_sync_enabled, + const std::vector<BrowserTabsModel::BrowserTabMetadata>& + browser_tabs_metadata) { + fake_browser_tabs_model_provider_.NotifyBrowserTabsUpdated( + is_sync_enabled, browser_tabs_metadata); + } + + MutablePhoneModel* phone_model() { return phone_model_.get(); } + + private: + std::unique_ptr<BrowserTabsModelController> controller_; + + std::unique_ptr<MutablePhoneModel> phone_model_; + multidevice_setup::FakeMultiDeviceSetupClient fake_multidevice_setup_client_; + FakeBrowserTabsModelProvider fake_browser_tabs_model_provider_; +}; + +TEST_F(BrowserTabsModelControllerTest, MutablePhoneModelProperlySet) { + // Test that the MutablePhoneModel is not updated when task continuation + // disabled. + DisableTaskContinuation(); + std::vector<BrowserTabsModel::BrowserTabMetadata> metadata; + metadata.push_back(CreateFakeBrowserTabMetadata()); + NotifyBrowserTabsUpdated(true, metadata); + EXPECT_FALSE(phone_model()->browser_tabs_model()); + + // Test that the MutablePhoneModel is updated when task continuation enabled. + EnableTaskContinuation(); + EXPECT_TRUE(phone_model()->browser_tabs_model()->is_tab_sync_enabled()); + EXPECT_EQ(phone_model()->browser_tabs_model()->most_recent_tabs().size(), 1U); +} + +} // namespace phonehub +} // namespace chromeos
diff --git a/chromeos/components/phonehub/fake_browser_tabs_model_provider.cc b/chromeos/components/phonehub/fake_browser_tabs_model_provider.cc new file mode 100644 index 0000000..2f83d62 --- /dev/null +++ b/chromeos/components/phonehub/fake_browser_tabs_model_provider.cc
@@ -0,0 +1,23 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chromeos/components/phonehub/fake_browser_tabs_model_provider.h" + +namespace chromeos { +namespace phonehub { + +FakeBrowserTabsModelProvider::FakeBrowserTabsModelProvider() = default; + +FakeBrowserTabsModelProvider::~FakeBrowserTabsModelProvider() {} + +void FakeBrowserTabsModelProvider::NotifyBrowserTabsUpdated( + bool is_sync_enabled, + const std::vector<BrowserTabsModel::BrowserTabMetadata> + browser_tabs_metadata) { + BrowserTabsModelProvider::NotifyBrowserTabsUpdated(is_sync_enabled, + browser_tabs_metadata); +} + +} // namespace phonehub +} // namespace chromeos
diff --git a/chromeos/components/phonehub/fake_browser_tabs_model_provider.h b/chromeos/components/phonehub/fake_browser_tabs_model_provider.h new file mode 100644 index 0000000..353c263c --- /dev/null +++ b/chromeos/components/phonehub/fake_browser_tabs_model_provider.h
@@ -0,0 +1,29 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROMEOS_COMPONENTS_PHONEHUB_FAKE_BROWSER_TABS_MODEL_PROVIDER_H_ +#define CHROMEOS_COMPONENTS_PHONEHUB_FAKE_BROWSER_TABS_MODEL_PROVIDER_H_ + +#include "chromeos/components/phonehub/browser_tabs_model_provider.h" + +#include "chromeos/components/phonehub/browser_tabs_model.h" + +namespace chromeos { +namespace phonehub { + +class FakeBrowserTabsModelProvider : public BrowserTabsModelProvider { + public: + FakeBrowserTabsModelProvider(); + ~FakeBrowserTabsModelProvider() override; + + void NotifyBrowserTabsUpdated( + bool is_sync_enabled, + const std::vector<BrowserTabsModel::BrowserTabMetadata> + browser_tabs_metadata); +}; + +} // namespace phonehub +} // namespace chromeos + +#endif // CHROMEOS_COMPONENTS_PHONEHUB_FAKE_BROWSER_TABS_MODEL_PROVIDER_H_
diff --git a/chromeos/components/phonehub/phone_hub_manager_impl.cc b/chromeos/components/phonehub/phone_hub_manager_impl.cc index cd83067a..b33c368 100644 --- a/chromeos/components/phonehub/phone_hub_manager_impl.cc +++ b/chromeos/components/phonehub/phone_hub_manager_impl.cc
@@ -84,6 +84,7 @@ browser_tabs_model_provider_(std::move(browser_tabs_model_provider)), browser_tabs_model_controller_( std::make_unique<BrowserTabsModelController>( + multidevice_setup_client, browser_tabs_model_provider_.get(), phone_model_.get())) {}
diff --git a/chromeos/crosapi/mojom/account_manager.mojom b/chromeos/crosapi/mojom/account_manager.mojom index 17c5179..ce80f8b 100644 --- a/chromeos/crosapi/mojom/account_manager.mojom +++ b/chromeos/crosapi/mojom/account_manager.mojom
@@ -39,7 +39,7 @@ // Interface for observers of Chrome OS Account Manager. // This interface is implemented by lacros-chrome, and is used by ash-chrome to // send account update notifications. -[Stable] +[Stable, Uuid="f75c4963-497b-411f-97ab-c53c7f6b46ed"] interface AccountManagerObserver { // Called when the token for |account| is updated/inserted. // Note: Observers which register with |AccountManager| before its @@ -67,7 +67,7 @@ // // Next version: 2 // Next method id: 2 -[Stable] +[Stable, Uuid="85b9a674-9d8e-497f-98d5-22c8dca6f2b8"] interface AccountManager { // Returns |true| if Chrome OS Account Manager has been fully initialized, and // |false| otherwise.
diff --git a/chromeos/crosapi/mojom/crosapi.mojom b/chromeos/crosapi/mojom/crosapi.mojom index c3e7e7106..57e8336b 100644 --- a/chromeos/crosapi/mojom/crosapi.mojom +++ b/chromeos/crosapi/mojom/crosapi.mojom
@@ -33,7 +33,7 @@ // // Next version: 5 // Next method id: 8 -[Stable] +[Stable, Uuid="8b79c34f-2bf8-4499-979a-b17cac522c1e"] interface AshChromeService { // Binds Chrome OS Account Manager for Identity management. // Added in M87. @@ -121,7 +121,7 @@ // LacrosChromeService defines the APIs that live in lacros-chrome and // are accessed from ash-chrome. -[Stable] +[Stable, Uuid="4e04dc16-b34c-40fd-9e3f-3c55c2c6cf91"] interface LacrosChromeService { // Ash-chrome can pass initialize parameters via this method. // The parameters are available on lacros-chrome startup.
diff --git a/chromeos/crosapi/mojom/feedback.mojom b/chromeos/crosapi/mojom/feedback.mojom index 02f3c49..3f40c60b 100644 --- a/chromeos/crosapi/mojom/feedback.mojom +++ b/chromeos/crosapi/mojom/feedback.mojom
@@ -36,7 +36,7 @@ // This interface is implemented by ash-chrome. It allows lacros-chrome to // request ash-chrome to display Feedback ui. -[Stable] +[Stable, Uuid="f95688a1-3076-484f-852f-65772f2a2f68"] interface Feedback { // Displays the Feedback ui. ShowFeedbackPage@0(FeedbackInfo feedback_info);
diff --git a/chromeos/crosapi/mojom/keystore_service.mojom b/chromeos/crosapi/mojom/keystore_service.mojom index 265360a..88553e8 100644 --- a/chromeos/crosapi/mojom/keystore_service.mojom +++ b/chromeos/crosapi/mojom/keystore_service.mojom
@@ -47,7 +47,7 @@ // This interface is implemented by ash-chrome. It provides lacros-chrome a // mechanism to modify and query the attestation-only and generate purpose // keystores. -[Stable] +[Stable, Uuid="308635fd-110b-4f24-bfa8-9f43be31c61e"] interface KeystoreService { // This API serves a challenge to a special "attestation-only" keystore. This // keystore only contains 2 private keys (1 for the user, 1 for the device).
diff --git a/chromeos/crosapi/mojom/message_center.mojom b/chromeos/crosapi/mojom/message_center.mojom index becd21c..81d212b 100644 --- a/chromeos/crosapi/mojom/message_center.mojom +++ b/chromeos/crosapi/mojom/message_center.mojom
@@ -10,7 +10,7 @@ // Handles notifications created via the Notifications web platform API and the // chrome.notifications() extension API. Shows the notifications in the // message center. Implemented in ash-chrome. -[Stable] +[Stable, Uuid="0d9c1eb6-a383-45c0-ac11-2336e1227f74"] interface MessageCenter { // Displays a notification. If the notification's ID is the same as an // existing notification, that notification is replaced. The delegate will be @@ -30,7 +30,7 @@ // Handles responses to user actions on notifications. Multiple actions may // occur on a single notification. For example, clicking a notification button // may not close the notification. Implemented in lacros-chrome. -[Stable] +[Stable, Uuid="1a850ac9-a813-4d0d-aa2d-b0d6cf10d548"] interface NotificationDelegate { // Called when a notification previously displayed by the client is closed. OnNotificationClosed@0(bool by_user);
diff --git a/chromeos/crosapi/mojom/screen_manager.mojom b/chromeos/crosapi/mojom/screen_manager.mojom index 748fcb3..a792941 100644 --- a/chromeos/crosapi/mojom/screen_manager.mojom +++ b/chromeos/crosapi/mojom/screen_manager.mojom
@@ -19,7 +19,7 @@ // This interface is used to capture bitmap snapshots of screens or windows. // See ScreenManager methods used to create instances of this interface. -[Stable] +[Stable, Uuid="90487679-7dc8-40ad-a1e4-e741def0d79f"] interface SnapshotCapturer { // Returns list of screens or windows that can be captured. [Sync] @@ -43,7 +43,7 @@ // TODO(https://crbug.com/1094460): This is a very simple interface. We will // likely want to replace it with a more feature-complete and performant // interface in the future. -[Stable] +[Stable, Uuid="95c3035c-5c63-45e3-8ec8-dd2a344c7dc2"] interface ScreenManager { // DEPRECATED. Use |GetScreenCapturer| instead. //
diff --git a/chromeos/crosapi/mojom/select_file.mojom b/chromeos/crosapi/mojom/select_file.mojom index 06ddaa2..3dcae87 100644 --- a/chromeos/crosapi/mojom/select_file.mojom +++ b/chromeos/crosapi/mojom/select_file.mojom
@@ -137,7 +137,7 @@ // Select file dialog interface. Wrapper around the C++ SelectFileDialog // class. Called from lacros-chrome. Implemented in ash-chrome using the // file manager dialog. -[Stable] +[Stable, Uuid="8c0eb5f3-4c90-4bfd-8a0f-377c99f09125"] interface SelectFile { // Selects one or more files. If the dialog is closed or canceled without // selecting a file, or if there is an error, |files| will be empty.
diff --git a/chromeos/memory/userspace_swap/userspace_swap.cc b/chromeos/memory/userspace_swap/userspace_swap.cc index 8f0bfb9..df0df62 100644 --- a/chromeos/memory/userspace_swap/userspace_swap.cc +++ b/chromeos/memory/userspace_swap/userspace_swap.cc
@@ -4,6 +4,7 @@ #include "chromeos/memory/userspace_swap/userspace_swap.h" +#include <atomic> #include <vector> #include "base/feature_list.h" @@ -63,6 +64,100 @@ &kUserspaceSwap, "UserspaceSwapDoSwapOnFreeze", true}; const base::FeatureParam<bool> kUserspaceSwapShuffleMapsOrder = { &kUserspaceSwap, "UserspaceSwapSuffleMapsOrder", true}; + +// g_global_disk_usage is the sum of all |written_to_disk| values from each +// renderer. We keep track of this number because we need to enforce the global +// total swap limit. This value is safe to be fetched from any sequence. +std::atomic<uint64_t> g_global_disk_usage_bytes = ATOMIC_VAR_INIT(0); + +// This is the sum of all |reclaimed_bytes| values from each renderer. This +// value is safe to be fetched from any sequence. +std::atomic<uint64_t> g_global_reclaimed_bytes = ATOMIC_VAR_INIT(0); + +class RendererSwapDataImpl : public RendererSwapData { + public: + RendererSwapDataImpl( + int render_process_host_id, + std::unique_ptr<chromeos::memory::userspace_swap::UserfaultFD>&& uffd, + std::unique_ptr<chromeos::memory::userspace_swap::SwapFile>&& swap_file) + : render_process_host_id_(render_process_host_id), + uffd_(std::move(uffd)), + swap_file_(std::move(swap_file)) {} + + ~RendererSwapDataImpl() override; + + // RendererSwapData impl: + int render_process_host_id() const override; + bool SwapAllowed() const override; + void DisallowSwap() override; + uint64_t SwapDiskspaceWrittenBytes() const override; + uint64_t SwapDiskspaceUsedBytes() const override; + uint64_t ReclaimedBytes() const override; + + // Account/UnaccountSwapSpace update all counters both for this renderer and + // globally to reflect the swapped space. + void AccountSwapSpace(int64_t reclaimed, int64_t swap_size); + void UnaccountSwapSpace(int64_t reclaimed, int64_t swap_size); + + private: + const int render_process_host_id_ = 0; + bool swap_allowed_ = true; + + uint64_t on_disk_bytes_ = 0; + uint64_t reclaimed_bytes_ = 0; + + std::unique_ptr<chromeos::memory::userspace_swap::UserfaultFD> uffd_; + std::unique_ptr<chromeos::memory::userspace_swap::SwapFile> swap_file_; +}; + +int RendererSwapDataImpl::render_process_host_id() const { + return render_process_host_id_; +} + +void RendererSwapDataImpl::DisallowSwap() { + swap_allowed_ = false; +} + +bool RendererSwapDataImpl::SwapAllowed() const { + return swap_allowed_; +} + +uint64_t RendererSwapDataImpl::SwapDiskspaceWrittenBytes() const { + return on_disk_bytes_; +} + +uint64_t RendererSwapDataImpl::SwapDiskspaceUsedBytes() const { + // Because punching a hole may not free the block if the region compressed + // down to a partial size, the block can only be freed when all of it has been + // punched. So we will take the larger of what we believe we've written to + // disk and what the swap file reports as being in use. + uint64_t swap_file_reported_disk_size_bytes = + swap_file_->GetUsageKB() << 10; // Convert to bytes from KB. + uint64_t swap_file_disk_space_used_bytes = + std::max(swap_file_reported_disk_size_bytes, on_disk_bytes_); + + return swap_file_disk_space_used_bytes; +} + +uint64_t RendererSwapDataImpl::ReclaimedBytes() const { + return reclaimed_bytes_; +} + +void RendererSwapDataImpl::AccountSwapSpace(int64_t reclaimed, + int64_t swap_size) { + on_disk_bytes_ += swap_size; + g_global_disk_usage_bytes += swap_size; + reclaimed_bytes_ += reclaimed; + g_global_reclaimed_bytes += reclaimed; +} + +void RendererSwapDataImpl::UnaccountSwapSpace(int64_t reclaimed, + int64_t swap_size) { + AccountSwapSpace(-reclaimed, -swap_size); +} + +RendererSwapDataImpl::~RendererSwapDataImpl() {} + } // namespace UserspaceSwapConfig::UserspaceSwapConfig() = default; @@ -178,12 +273,32 @@ return userfault_fd_supported && mremap_dontunmap_supported; } +RendererSwapData::RendererSwapData() {} +RendererSwapData::~RendererSwapData() {} + +// static +CHROMEOS_EXPORT std::unique_ptr<RendererSwapData> RendererSwapData::Create( + int render_process_host_id, + std::unique_ptr<chromeos::memory::userspace_swap::UserfaultFD> uffd, + std::unique_ptr<chromeos::memory::userspace_swap::SwapFile> swap_file) { + return std::make_unique<RendererSwapDataImpl>( + render_process_host_id, std::move(uffd), std::move(swap_file)); +} + CHROMEOS_EXPORT bool UserspaceSwapSupportedAndEnabled() { static bool enabled = UserspaceSwapConfig::Get().enabled; static bool supported = KernelSupportsUserspaceSwap(); return supported && enabled; } +CHROMEOS_EXPORT bool SwapRegions(RendererSwapData* data, int num_regions) { + // TODO(bgeffon): We need to now land all of the process specific swap code. + RendererSwapDataImpl* impl = reinterpret_cast<RendererSwapDataImpl*>(data); + VLOG(1) << "SwapRegions for rphid " << impl->render_process_host_id() + << " at most " << num_regions << " regions"; + return true; +} + CHROMEOS_EXPORT bool IsVMASwapEligible( const memory_instrumentation::mojom::VmRegionPtr& vma) { // We only conisder VMAs which are Private Anonymous @@ -239,6 +354,14 @@ return true; } +CHROMEOS_EXPORT uint64_t GetGlobalMemoryReclaimed() { + return g_global_reclaimed_bytes.load(); +} + +CHROMEOS_EXPORT uint64_t GetGlobalSwapDiskspaceUsed() { + return g_global_disk_usage_bytes.load(); +} + } // namespace userspace_swap } // namespace memory } // namespace chromeos
diff --git a/chromeos/memory/userspace_swap/userspace_swap.h b/chromeos/memory/userspace_swap/userspace_swap.h index ef90113..3b565a0 100644 --- a/chromeos/memory/userspace_swap/userspace_swap.h +++ b/chromeos/memory/userspace_swap/userspace_swap.h
@@ -25,6 +25,9 @@ namespace memory { namespace userspace_swap { +class UserfaultFD; +class SwapFile; + // UserspaceSwapConfig is a structure which contains all configuration values // for userspace swap. struct CHROMEOS_EXPORT UserspaceSwapConfig { @@ -124,6 +127,55 @@ // enabled. CHROMEOS_EXPORT bool UserspaceSwapSupportedAndEnabled(); +// GetGlobalSwapDiskspaceUsed returns the number of bytes currently on disk for +// ALL renderers. +CHROMEOS_EXPORT uint64_t GetGlobalSwapDiskspaceUsed(); + +// GetGlobalMemoryReclaimed returns the number of bytes (physical memory) which +// has been reclaimed by userspace swap. This number may not match what is on +// disk due to encryption and compression. +CHROMEOS_EXPORT uint64_t GetGlobalMemoryReclaimed(); + +// RendererSwapData is attached to a ProcessNode and owned by the ProcessNode on +// the PerformanceManager graph. +class CHROMEOS_EXPORT RendererSwapData { + public: + virtual ~RendererSwapData(); + + static std::unique_ptr<RendererSwapData> Create( + int render_process_host_id, + std::unique_ptr<chromeos::memory::userspace_swap::UserfaultFD> uffd, + std::unique_ptr<chromeos::memory::userspace_swap::SwapFile> swap_file); + + // Returns the Render Process Host ID associated with this RendererSwapData. + virtual int render_process_host_id() const = 0; + + // If true this renderer has not been disallowed swap. + virtual bool SwapAllowed() const = 0; + + // DisallowSwap prevents further swapping of this renderer. This cannot be + // unset. + virtual void DisallowSwap() = 0; + + // There is a subtle difference between SwapdiskspaceWrittenBytes and + // SwapDiskspaceUsedBytes. Because punching a hole in a file may not reclaim a + // block on disk only after the entire block has been punched will the space + // actually be reclaimed on disk. However, SwapDiskspaceWrittenBytes will + // contain the total number of bytes that we think are on disk, these numbers + // will be equal when there is no waste of block space on disk. + virtual uint64_t SwapDiskspaceWrittenBytes() const = 0; + virtual uint64_t SwapDiskspaceUsedBytes() const = 0; + + virtual uint64_t ReclaimedBytes() const = 0; + + protected: + RendererSwapData(); +}; + +// SwapRegions will swap at most |number_of_regions| on the renderer belonging +// to the associated RendererSwapData. +CHROMEOS_EXPORT bool SwapRegions(RendererSwapData* data, int number_of_regions); + // A swap eligible VMA is one that meets the required swapping criteria, // which are: // - RW protections @@ -132,13 +184,16 @@ // - Contains no locked memory // - Meets the size constraints set by vma_region_min_size_bytes // and vma_region_max_size_bytes +// +// This method is only exported for testing. CHROMEOS_EXPORT bool IsVMASwapEligible( const memory_instrumentation::mojom::VmRegionPtr& vma); // GetAllSwapEligibleVMAs will return a vector of regions which are swap -// eligible, these regions are NOT "swap region" sized they are the VMAs and as -// such must then be split in the appropriate region size by the userspace swap -// mechanism. On error it will return false and errno will be set appropriately. +// eligible, these regions are NOT "swap region" sized they are the VMAs and +// as such must then be split in the appropriate region size by the userspace +// swap mechanism. On error it will return false and errno will be set +// appropriately. // // This vector may be shuffled if shuffle_maps_on_swap has been set to true. CHROMEOS_EXPORT bool GetAllSwapEligibleVMAs(base::PlatformThreadId pid,
diff --git a/chromeos/services/nearby/OWNERS b/chromeos/services/nearby/OWNERS new file mode 100644 index 0000000..1aef20dd --- /dev/null +++ b/chromeos/services/nearby/OWNERS
@@ -0,0 +1,5 @@ +khorimoto@chromium.org +file://chrome/browser/nearby_sharing/OWNERS +file://chrome/browser/sharing/OWNERS + +# COMPONENT: OS>Systems>Multidevice>Nearby
diff --git a/chromeos/services/nearby/README.md b/chromeos/services/nearby/README.md new file mode 100644 index 0000000..f0e121f --- /dev/null +++ b/chromeos/services/nearby/README.md
@@ -0,0 +1,5 @@ +# Nearby + +This directory contains code for the utility process which runs code for both +the Nearby Connections library as well the Nearby Share feature, built on top of +Nearby Connections. \ No newline at end of file
diff --git a/chrome/services/sharing/public/mojom/BUILD.gn b/chromeos/services/nearby/public/mojom/BUILD.gn similarity index 96% rename from chrome/services/sharing/public/mojom/BUILD.gn rename to chromeos/services/nearby/public/mojom/BUILD.gn index 3e987a6..413f8689 100644 --- a/chrome/services/sharing/public/mojom/BUILD.gn +++ b/chromeos/services/nearby/public/mojom/BUILD.gn
@@ -1,5 +1,7 @@ import("//mojo/public/tools/bindings/mojom.gni") +assert(is_chromeos) + mojom("nearby_share_target_types") { sources = [ "nearby_share_target_types.mojom" ] }
diff --git a/chrome/services/sharing/public/mojom/OWNERS b/chromeos/services/nearby/public/mojom/OWNERS similarity index 100% rename from chrome/services/sharing/public/mojom/OWNERS rename to chromeos/services/nearby/public/mojom/OWNERS
diff --git a/chrome/services/sharing/public/mojom/nearby_connections.mojom b/chromeos/services/nearby/public/mojom/nearby_connections.mojom similarity index 98% rename from chrome/services/sharing/public/mojom/nearby_connections.mojom rename to chromeos/services/nearby/public/mojom/nearby_connections.mojom index 1364ced..08a40570c 100644 --- a/chrome/services/sharing/public/mojom/nearby_connections.mojom +++ b/chromeos/services/nearby/public/mojom/nearby_connections.mojom
@@ -4,13 +4,13 @@ module location.nearby.connections.mojom; -import "chrome/services/sharing/public/mojom/nearby_connections_types.mojom"; -import "chrome/services/sharing/public/mojom/webrtc_signaling_messenger.mojom"; -import "chrome/services/sharing/public/mojom/webrtc.mojom"; +import "chromeos/services/nearby/public/mojom/nearby_connections_types.mojom"; +import "chromeos/services/nearby/public/mojom/webrtc.mojom"; +import "chromeos/services/nearby/public/mojom/webrtc_signaling_messenger.mojom"; import "device/bluetooth/public/mojom/adapter.mojom"; import "mojo/public/mojom/base/file.mojom"; -import "services/network/public/mojom/p2p.mojom"; import "services/network/public/mojom/mdns_responder.mojom"; +import "services/network/public/mojom/p2p.mojom"; // Collection of dependencies required by WebRTC medium. struct WebRtcDependencies {
diff --git a/chrome/services/sharing/public/mojom/nearby_connections_types.mojom b/chromeos/services/nearby/public/mojom/nearby_connections_types.mojom similarity index 100% rename from chrome/services/sharing/public/mojom/nearby_connections_types.mojom rename to chromeos/services/nearby/public/mojom/nearby_connections_types.mojom
diff --git a/chrome/services/sharing/public/mojom/nearby_decoder.mojom b/chromeos/services/nearby/public/mojom/nearby_decoder.mojom similarity index 91% rename from chrome/services/sharing/public/mojom/nearby_decoder.mojom rename to chromeos/services/nearby/public/mojom/nearby_decoder.mojom index b8e85d95..07e245d 100644 --- a/chrome/services/sharing/public/mojom/nearby_decoder.mojom +++ b/chromeos/services/nearby/public/mojom/nearby_decoder.mojom
@@ -4,7 +4,7 @@ module sharing.mojom; -import "chrome/services/sharing/public/mojom/nearby_decoder_types.mojom"; +import "chromeos/services/nearby/public/mojom/nearby_decoder_types.mojom"; import "mojo/public/mojom/base/time.mojom"; // Decode raw data into structured. Runs in the sharing utility process.
diff --git a/chrome/services/sharing/public/mojom/nearby_decoder_types.mojom b/chromeos/services/nearby/public/mojom/nearby_decoder_types.mojom similarity index 98% rename from chrome/services/sharing/public/mojom/nearby_decoder_types.mojom rename to chromeos/services/nearby/public/mojom/nearby_decoder_types.mojom index 401b7a30..2ed665b7 100644 --- a/chrome/services/sharing/public/mojom/nearby_decoder_types.mojom +++ b/chromeos/services/nearby/public/mojom/nearby_decoder_types.mojom
@@ -4,7 +4,7 @@ module sharing.mojom; -import "chrome/services/sharing/public/mojom/nearby_share_target_types.mojom"; +import "chromeos/services/nearby/public/mojom/nearby_share_target_types.mojom"; import "mojo/public/mojom/base/time.mojom"; // An advertisement send by a device in receiving mode.
diff --git a/chrome/services/sharing/public/mojom/nearby_share_target_types.mojom b/chromeos/services/nearby/public/mojom/nearby_share_target_types.mojom similarity index 100% rename from chrome/services/sharing/public/mojom/nearby_share_target_types.mojom rename to chromeos/services/nearby/public/mojom/nearby_share_target_types.mojom
diff --git a/chrome/services/sharing/public/mojom/sharing.mojom b/chromeos/services/nearby/public/mojom/sharing.mojom similarity index 88% rename from chrome/services/sharing/public/mojom/sharing.mojom rename to chromeos/services/nearby/public/mojom/sharing.mojom index a7faeb9b..78270af 100644 --- a/chrome/services/sharing/public/mojom/sharing.mojom +++ b/chromeos/services/nearby/public/mojom/sharing.mojom
@@ -4,10 +4,10 @@ module sharing.mojom; -import "chrome/services/sharing/public/mojom/nearby_connections.mojom"; -import "chrome/services/sharing/public/mojom/nearby_decoder.mojom"; -import "services/network/public/mojom/p2p.mojom"; +import "chromeos/services/nearby/public/mojom/nearby_connections.mojom"; +import "chromeos/services/nearby/public/mojom/nearby_decoder.mojom"; import "services/network/public/mojom/mdns_responder.mojom"; +import "services/network/public/mojom/p2p.mojom"; // Interface for sharing related services. Lives in a sandboxed utility process // and is used by the browser process to offload unsafe protocol parsing.
diff --git a/chrome/services/sharing/public/mojom/webrtc.mojom b/chromeos/services/nearby/public/mojom/webrtc.mojom similarity index 100% rename from chrome/services/sharing/public/mojom/webrtc.mojom rename to chromeos/services/nearby/public/mojom/webrtc.mojom
diff --git a/chrome/services/sharing/public/mojom/webrtc_signaling_messenger.mojom b/chromeos/services/nearby/public/mojom/webrtc_signaling_messenger.mojom similarity index 100% rename from chrome/services/sharing/public/mojom/webrtc_signaling_messenger.mojom rename to chromeos/services/nearby/public/mojom/webrtc_signaling_messenger.mojom
diff --git a/chromeos/services/tts/tts_service.cc b/chromeos/services/tts/tts_service.cc index b6cd31a..bd4d9e2 100644 --- a/chromeos/services/tts/tts_service.cc +++ b/chromeos/services/tts/tts_service.cc
@@ -125,6 +125,15 @@ return; } + // For lower end devices, pre-fetching the first buffer on the main thread is + // important. Not doing so can cause us to not respond quickly enough in the + // audio rendering thread/callback below. + size_t frames = 0; + first_buf_.first.clear(); + first_buf_.first.resize(libchrometts_.GoogleTtsGetFramesInAudioBuffer()); + first_buf_.second = + libchrometts_.GoogleTtsReadBuffered(&first_buf_.first[0], &frames); + output_device_->Play(); } @@ -147,13 +156,21 @@ // can be extremely important if there's a long queue of pending Speak/Stop // pairs being processed on the main thread. This can occur if the tts api // receives lots of tts requests. - if (!state_lock_.Try()) { + if (!state_lock_.Try()) return 0; - } size_t frames = 0; - int32_t status = - libchrometts_.GoogleTtsReadBuffered(dest->channel(0), &frames); + float* channel = dest->channel(0); + int32_t status = -1; + if (got_first_buffer_) { + status = libchrometts_.GoogleTtsReadBuffered(channel, &frames); + } else { + status = first_buf_.second; + float* buf = &first_buf_.first[0]; + frames = first_buf_.first.size(); + for (size_t i = 0; i < frames; i++) + channel[i] = buf[i]; + } if (status <= 0) { // -1 means an error, 0 means done.
diff --git a/chromeos/services/tts/tts_service.h b/chromeos/services/tts/tts_service.h index 09fc3d4..0b8d0ab59 100644 --- a/chromeos/services/tts/tts_service.h +++ b/chromeos/services/tts/tts_service.h
@@ -76,6 +76,11 @@ // Tracks whether any audio data came as a result of |Speak|. Reset for every // call to |Speak|. bool got_first_buffer_ GUARDED_BY(state_lock_); + + // The first buffer; used for prefetching/warming up the engine for a new + // utterance. The first item is the audio data, the second is the status + // returned by a call to GoogleTtsReadBuffered. + std::pair<std::vector<float>, size_t> first_buf_; }; } // namespace tts
diff --git a/chromeos/ui/base/BUILD.gn b/chromeos/ui/base/BUILD.gn index 5e66a2e..e807214e 100644 --- a/chromeos/ui/base/BUILD.gn +++ b/chromeos/ui/base/BUILD.gn
@@ -15,6 +15,8 @@ "tablet_state.h", "window_properties.cc", "window_properties.h", + "window_state_type.cc", + "window_state_type.h", ] output_name = "chromeos_ui_base"
diff --git a/chromeos/ui/base/DEPS b/chromeos/ui/base/DEPS index a5392539f..7de734c 100644 --- a/chromeos/ui/base/DEPS +++ b/chromeos/ui/base/DEPS
@@ -1,5 +1,5 @@ include_rules = [ - "+ui/aura/window.h", - "+ui/base/class_property.h", + "+ui/aura", + "+ui/base", "+third_party/skia", ]
diff --git a/ash/public/cpp/window_state_type.cc b/chromeos/ui/base/window_state_type.cc similarity index 97% rename from ash/public/cpp/window_state_type.cc rename to chromeos/ui/base/window_state_type.cc index a553136a..c4847dd 100644 --- a/ash/public/cpp/window_state_type.cc +++ b/chromeos/ui/base/window_state_type.cc
@@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ash/public/cpp/window_state_type.h" +#include "chromeos/ui/base/window_state_type.h" #include "base/notreached.h" -namespace ash { +namespace chromeos { std::ostream& operator<<(std::ostream& stream, WindowStateType state) { switch (state) { @@ -120,4 +120,4 @@ value == int64_t(WindowStateType::kPip); } -} // namespace ash +} // namespace chromeos
diff --git a/ash/public/cpp/window_state_type.h b/chromeos/ui/base/window_state_type.h similarity index 63% rename from ash/public/cpp/window_state_type.h rename to chromeos/ui/base/window_state_type.h index ee2b7671..94c1080 100644 --- a/ash/public/cpp/window_state_type.h +++ b/chromeos/ui/base/window_state_type.h
@@ -2,16 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef ASH_PUBLIC_CPP_WINDOW_STATE_TYPE_H_ -#define ASH_PUBLIC_CPP_WINDOW_STATE_TYPE_H_ +#ifndef CHROMEOS_UI_BASE_WINDOW_STATE_TYPE_H_ +#define CHROMEOS_UI_BASE_WINDOW_STATE_TYPE_H_ #include <cstdint> #include <ostream> -#include "ash/public/cpp/ash_public_export.h" +#include "base/component_export.h" #include "ui/base/ui_base_types.h" -namespace ash { +namespace chromeos { // A superset of ui::WindowShowState. Ash has more states than the general // ui::WindowShowState enum. These need to be communicated back to Chrome. @@ -46,31 +46,35 @@ kPip, }; -ASH_PUBLIC_EXPORT std::ostream& operator<<(std::ostream& stream, - WindowStateType state); +COMPONENT_EXPORT(CHROMEOS_UI_BASE) +std::ostream& operator<<(std::ostream& stream, WindowStateType state); // Utility functions to convert WindowStateType <-> ui::WindowShowState. // Note: LEFT/RIGHT MAXIMIZED, AUTO_POSITIONED types will be lost when // converting to ui::WindowShowState. -ASH_PUBLIC_EXPORT WindowStateType ToWindowStateType(ui::WindowShowState state); -ASH_PUBLIC_EXPORT ui::WindowShowState ToWindowShowState(WindowStateType type); +COMPONENT_EXPORT(CHROMEOS_UI_BASE) +WindowStateType ToWindowStateType(ui::WindowShowState state); +COMPONENT_EXPORT(CHROMEOS_UI_BASE) +ui::WindowShowState ToWindowShowState(WindowStateType type); // Returns true if |type| is FULLSCREEN, PINNED, or TRUSTED_PINNED. -ASH_PUBLIC_EXPORT bool IsFullscreenOrPinnedWindowStateType( - WindowStateType type); +COMPONENT_EXPORT(CHROMEOS_UI_BASE) +bool IsFullscreenOrPinnedWindowStateType(WindowStateType type); // Returns true if |type| is MAXIMIZED, FULLSCREEN, PINNED, or TRUSTED_PINNED. -ASH_PUBLIC_EXPORT bool IsMaximizedOrFullscreenOrPinnedWindowStateType( - WindowStateType type); +COMPONENT_EXPORT(CHROMEOS_UI_BASE) +bool IsMaximizedOrFullscreenOrPinnedWindowStateType(WindowStateType type); // Returns true if |type| is MINIMIZED. -ASH_PUBLIC_EXPORT bool IsMinimizedWindowStateType(WindowStateType type); +COMPONENT_EXPORT(CHROMEOS_UI_BASE) +bool IsMinimizedWindowStateType(WindowStateType type); // Returns true if |type| is either NORMAL or DEFAULT. -ASH_PUBLIC_EXPORT bool IsNormalWindowStateType(WindowStateType type); +COMPONENT_EXPORT(CHROMEOS_UI_BASE) +bool IsNormalWindowStateType(WindowStateType type); -ASH_PUBLIC_EXPORT bool IsValidWindowStateType(int64_t value); +COMPONENT_EXPORT(CHROMEOS_UI_BASE) bool IsValidWindowStateType(int64_t value); -} // namespace ash +} // namespace chromeos -#endif // ASH_PUBLIC_CPP_WINDOW_STATE_TYPE_H_ +#endif // CHROMEOS_UI_BASE_WINDOW_STATE_TYPE_H_
diff --git a/components/autofill/core/browser/autofill_browser_util.cc b/components/autofill/core/browser/autofill_browser_util.cc index 287d2af5..7d5ab372 100644 --- a/components/autofill/core/browser/autofill_browser_util.cc +++ b/components/autofill/core/browser/autofill_browser_util.cc
@@ -10,11 +10,19 @@ namespace { // Matches the blink check for mixed content. bool IsInsecureFormAction(const GURL& action_url) { - if (action_url.SchemeIs(url::kBlobScheme) || - action_url.SchemeIs(url::kFileSystemScheme)) + // blob: and filesystem: URLs never hit the network, and access is restricted + // to same-origin contexts, so they are not blocked. Some forms use + // javascript URLs to handle submissions in JS, those don't count as mixed + // content either. + // The data scheme is explicitly allowed in order to match blink's equivalent + // check, since IsUrlPotentiallyTrustworthy excludes it. + if (action_url.SchemeIs(url::kJavaScriptScheme) || + action_url.SchemeIs(url::kBlobScheme) || + action_url.SchemeIs(url::kFileSystemScheme) || + action_url.SchemeIs(url::kDataScheme)) { return false; - return !network::IsOriginPotentiallyTrustworthy( - url::Origin::Create(action_url)); + } + return !network::IsUrlPotentiallyTrustworthy(action_url); } } // namespace
diff --git a/components/autofill/core/browser/autofill_manager_unittest.cc b/components/autofill/core/browser/autofill_manager_unittest.cc index ac03ff9c..7d296d9 100644 --- a/components/autofill/core/browser/autofill_manager_unittest.cc +++ b/components/autofill/core/browser/autofill_manager_unittest.cc
@@ -8664,6 +8664,39 @@ external_delegate_->CheckNoSuggestions(kDefaultPageID); } +// Test that we don't treat javascript scheme target URLs as mixed forms. +// Regression test for crbug.com/1135173 +TEST_F(AutofillManagerTestWithMixedForms, GetSuggestions_JavascriptUrlTarget) { + // Set up our form data, using a javascript scheme target URL. + FormData form; + form.name = ASCIIToUTF16("MyForm"); + form.url = GURL("https://myform.com/form.html"); + form.action = GURL("javascript:alert('hello');"); + FormFieldData field; + test::CreateTestFormField("Name on Card", "nameoncard", "", "text", &field); + form.fields.push_back(field); + GetAutofillSuggestions(form, form.fields[0]); + + // Check there is no warning. + EXPECT_FALSE(external_delegate_->on_suggestions_returned_seen()); +} + +// Test that we don't treat about:blank target URLs as mixed forms. +TEST_F(AutofillManagerTestWithMixedForms, GetSuggestions_AboutBlankTarget) { + // Set up our form data, using a javascript scheme target URL. + FormData form; + form.name = ASCIIToUTF16("MyForm"); + form.url = GURL("https://myform.com/form.html"); + form.action = GURL("about:blank"); + FormFieldData field; + test::CreateTestFormField("Name on Card", "nameoncard", "", "text", &field); + form.fields.push_back(field); + GetAutofillSuggestions(form, form.fields[0]); + + // Check there is no warning. + EXPECT_FALSE(external_delegate_->on_suggestions_returned_seen()); +} + // Desktop only tests. #if !defined(OS_ANDROID) && !defined(OS_IOS) class AutofillManagerTestForVirtualCardOption : public AutofillManagerTest {
diff --git a/components/browser_ui/strings/android/translations/browser_ui_strings_fa.xtb b/components/browser_ui/strings/android/translations/browser_ui_strings_fa.xtb index 3d26cc4f..3c93e842 100644 --- a/components/browser_ui/strings/android/translations/browser_ui_strings_fa.xtb +++ b/components/browser_ui/strings/android/translations/browser_ui_strings_fa.xtb
@@ -205,7 +205,7 @@ <translation id="6689172468748959065">عکسهای نمایه</translation> <translation id="6697925417670533197">بارگیریهای فعال</translation> <translation id="6746124502594467657">انتقال به پایین</translation> -<translation id="6766622839693428701">برای بستن، تند به پایین بکشید.</translation> +<translation id="6766622839693428701">برای بستن، تند بهپایین بکشید.</translation> <translation id="6790428901817661496">پخش</translation> <translation id="6818926723028410516">انتخاب موارد</translation> <translation id="6864395892908308021">این دستگاه نمیتواند NFC را بخواند</translation>
diff --git a/components/cast/api_bindings/BUILD.gn b/components/cast/api_bindings/BUILD.gn index 099adce..242673e 100644 --- a/components/cast/api_bindings/BUILD.gn +++ b/components/cast/api_bindings/BUILD.gn
@@ -15,11 +15,7 @@ deps = [ "//base", "//components/cast:export", - "//third_party/blink/public/common", ] defines = [ "CAST_COMPONENT_IMPLEMENTATION" ] - public_deps = [ - "//components/cast/message_port", - "//mojo/public/cpp/bindings", - ] + public_deps = [ "//components/cast/message_port" ] }
diff --git a/components/cast/api_bindings/DEPS b/components/cast/api_bindings/DEPS index e07691e..e69de29 100644 --- a/components/cast/api_bindings/DEPS +++ b/components/cast/api_bindings/DEPS
@@ -1,3 +0,0 @@ -include_rules = [ - "+third_party/blink/public/common/messaging", -]
diff --git a/components/cast/api_bindings/manager.cc b/components/cast/api_bindings/manager.cc index 6299560..f945167 100644 --- a/components/cast/api_bindings/manager.cc +++ b/components/cast/api_bindings/manager.cc
@@ -22,41 +22,19 @@ DCHECK(result.second); } -void Manager::RegisterPortHandler(base::StringPiece port_name, - MessagePortProxyConnectedHandler handler) { - auto result = port_proxy_handlers_.try_emplace(port_name, std::move(handler)); - DCHECK(result.second); -} - void Manager::UnregisterPortHandler(base::StringPiece port_name) { size_t deleted = port_handlers_.erase(port_name); - deleted += port_proxy_handlers_.erase(port_name); DCHECK_EQ(deleted, 1u); } -bool Manager::OnPortConnected(base::StringPiece port_name, - blink::WebMessagePort port) { - if (!port.IsValid()) - return false; - - auto handler = port_handlers_.find(port_name); - if (handler == port_handlers_.end()) { - LOG(ERROR) << "No handler found for port " << port_name << "."; - return false; - } - - handler->second.Run(std::move(port)); - return true; -} - bool Manager::OnPortConnected( base::StringPiece port_name, std::unique_ptr<cast_api_bindings::MessagePort> port) { if (!port) return false; - auto handler = port_proxy_handlers_.find(port_name); - if (handler == port_proxy_handlers_.end()) { + auto handler = port_handlers_.find(port_name); + if (handler == port_handlers_.end()) { LOG(ERROR) << "No handler found for port " << port_name << "."; return false; }
diff --git a/components/cast/api_bindings/manager.h b/components/cast/api_bindings/manager.h index 976aecb8..9f833af9 100644 --- a/components/cast/api_bindings/manager.h +++ b/components/cast/api_bindings/manager.h
@@ -13,7 +13,6 @@ #include "base/strings/string_piece.h" #include "components/cast/cast_component_export.h" #include "components/cast/message_port/message_port.h" -#include "third_party/blink/public/common/messaging/web_message_port.h" namespace cast_api_bindings { @@ -21,28 +20,18 @@ // and to register handlers for communication with the content. class CAST_COMPONENT_EXPORT Manager { public: - // TODO(crbug.com/1135379): Deprecated; remove or redefine after fixing - // downstream dependencies - using MessagePortConnectedHandler = - base::RepeatingCallback<void(blink::WebMessagePort)>; - - using MessagePortProxyConnectedHandler = base::RepeatingCallback<void( + using MessagePortConnectedHandler = base::RepeatingCallback<void( std::unique_ptr<cast_api_bindings::MessagePort>)>; Manager(); virtual ~Manager(); - // TODO(crbug.com/1135379): Deprecated; remove after fixing downstream - // dependencies - void RegisterPortHandler(base::StringPiece port_name, - MessagePortConnectedHandler handler); - // Registers a |handler| which will receive MessagePorts originating from // the frame's web content. |port_name| is an alphanumeric string that is // consistent across JS and native code. // All handlers must be Unregistered() before |this| is destroyed. void RegisterPortHandler(base::StringPiece port_name, - MessagePortProxyConnectedHandler handler); + MessagePortConnectedHandler handler); // Unregisters a previously registered handler. // The owner of Manager is responsible for ensuring that all @@ -55,10 +44,6 @@ base::StringPiece binding_script) = 0; protected: - // TODO(crbug.com/1135379): Deprecated; remove after fixing downstream - // dependencies - bool OnPortConnected(base::StringPiece port_name, blink::WebMessagePort port); - // Called by platform-specific implementations when the content requests a // connection to |port_name|. // Returns |false| if the port was invalid or not registered in advance, at @@ -67,13 +52,8 @@ std::unique_ptr<cast_api_bindings::MessagePort> port); private: - // TODO(crbug.com/1135379): Deprecated; remove after fixing downstream - // dependencies base::flat_map<std::string, MessagePortConnectedHandler> port_handlers_; - base::flat_map<std::string, MessagePortProxyConnectedHandler> - port_proxy_handlers_; - DISALLOW_COPY_AND_ASSIGN(Manager); };
diff --git a/components/cast/api_bindings/scoped_api_binding.cc b/components/cast/api_bindings/scoped_api_binding.cc index 68a5d67..30843b3 100644 --- a/components/cast/api_bindings/scoped_api_binding.cc +++ b/components/cast/api_bindings/scoped_api_binding.cc
@@ -6,6 +6,7 @@ #include <string> +#include "base/bind.h" #include "base/logging.h" #include "components/cast/api_bindings/manager.h"
diff --git a/components/cast/message_port/BUILD.gn b/components/cast/message_port/BUILD.gn index 8b6ea4d..0884ff2 100644 --- a/components/cast/message_port/BUILD.gn +++ b/components/cast/message_port/BUILD.gn
@@ -32,3 +32,15 @@ deps += [ "//third_party/blink/public/common" ] } } + +source_set("test_message_port_receiver") { + testonly = true + sources = [ + "test_message_port_receiver.cc", + "test_message_port_receiver.h", + ] + deps = [ + ":message_port", + "//base", + ] +}
diff --git a/components/cast/message_port/message_port_cast.h b/components/cast/message_port/message_port_cast.h index 650427c5..202bc174 100644 --- a/components/cast/message_port/message_port_cast.h +++ b/components/cast/message_port/message_port_cast.h
@@ -23,13 +23,13 @@ static std::unique_ptr<MessagePort> Create(blink::WebMessagePort&& port); - private: // Gets the implementation of |port| for callers who know its platform type. static MessagePortCast* FromMessagePort(MessagePort* port); // Retrieves the platform-specific port and invalidates this object. blink::WebMessagePort TakePort(); + private: // cast_api_bindings::MessagePort implementation bool PostMessage(base::StringPiece message) final; bool PostMessageWithTransferables(
diff --git a/components/cast/message_port/message_port_fuchsia.cc b/components/cast/message_port/message_port_fuchsia.cc index 9a310bc..c59c8bb 100644 --- a/components/cast/message_port/message_port_fuchsia.cc +++ b/components/cast/message_port/message_port_fuchsia.cc
@@ -5,6 +5,7 @@ #include "components/cast/message_port/message_port_fuchsia.h" #include "base/fuchsia/fuchsia_logging.h" +#include "base/notreached.h" #include "fuchsia/base/mem_buffer_util.h" #include "fuchsia/fidl/chromium/cast/cpp/fidl.h" @@ -22,13 +23,20 @@ ~MessagePortFuchsiaClient() override {} - // Invalidates the port an returns the original InterfaceHandle. - fidl::InterfaceHandle<::fuchsia::web::MessagePort> TakeHandle() { + // MessagePortFuchsia implementation. + fidl::InterfaceHandle<::fuchsia::web::MessagePort> TakeClientHandle() final { DCHECK(!receiver_); DCHECK(port_.is_bound()); return port_.Unbind(); } + fidl::InterfaceRequest<::fuchsia::web::MessagePort> TakeServiceRequest() + final { + NOTREACHED(); + return {}; + } + + // MessagePort implementation. void SetReceiver(cast_api_bindings::MessagePort::Receiver* receiver) final { DCHECK(receiver); DCHECK(!receiver_); @@ -108,13 +116,18 @@ ~MessagePortFuchsiaServer() override {} - // Invalidates the port an returns the original InterfaceRequest. - fidl::InterfaceRequest<::fuchsia::web::MessagePort> TakeRequest() { - DCHECK(!receiver_); - DCHECK(binding_.is_bound()); + // MessagePortFuchsia implementation. + fidl::InterfaceHandle<::fuchsia::web::MessagePort> TakeClientHandle() final { + NOTREACHED(); + return {}; + } + + fidl::InterfaceRequest<::fuchsia::web::MessagePort> TakeServiceRequest() + final { return binding_.Unbind(); } + // MessagePort implementation. void SetReceiver(cast_api_bindings::MessagePort::Receiver* receiver) final { DCHECK(receiver); DCHECK(!receiver_); @@ -218,12 +231,12 @@ message_fidl.set_data(cr_fuchsia::MemBufferFromString(message.as_string(), message.as_string())); if (!ports.empty()) { - PortType expected_port_type = FromMessagePort(ports[0].get())->port_type(); + PortType expected_port_type = FromMessagePort(ports[0].get())->port_type_; std::vector<fuchsia::web::IncomingTransferable> incoming_transferables; std::vector<fuchsia::web::OutgoingTransferable> receiver_transferables; for (auto& port : ports) { MessagePortFuchsia* port_fuchsia = FromMessagePort(port.get()); - PortType port_type = port_fuchsia->port_type(); + PortType port_type = port_fuchsia->port_type_; DCHECK_EQ(expected_port_type, port_type) << "Only one implementation of MessagePortFuchsia can be transmitted " @@ -237,7 +250,7 @@ fuchsia::web::IncomingTransferable in; in.set_message_port( reinterpret_cast<MessagePortFuchsiaClient*>(port_fuchsia) - ->TakeHandle()); + ->TakeClientHandle()); incoming_transferables.emplace_back(std::move(in)); break; } @@ -245,7 +258,7 @@ fuchsia::web::OutgoingTransferable out; out.set_message_port( reinterpret_cast<MessagePortFuchsiaServer*>(port_fuchsia) - ->TakeRequest()); + ->TakeServiceRequest()); receiver_transferables.emplace_back(std::move(out)); break; } @@ -263,10 +276,6 @@ : receiver_(nullptr), port_type_(port_type) {} MessagePortFuchsia::~MessagePortFuchsia() = default; -MessagePortFuchsia::PortType MessagePortFuchsia::port_type() const { - return port_type_; -} - base::Optional<fuchsia::web::FrameError> MessagePortFuchsia::ReceiveMessageFromFidl(fuchsia::web::WebMessage message) { DCHECK(receiver_); @@ -331,4 +340,5 @@ return true; } + } // namespace cast_api_bindings
diff --git a/components/cast/message_port/message_port_fuchsia.h b/components/cast/message_port/message_port_fuchsia.h index 8ec5ec8..f1b2a5e3 100644 --- a/components/cast/message_port/message_port_fuchsia.h +++ b/components/cast/message_port/message_port_fuchsia.h
@@ -30,6 +30,18 @@ static std::unique_ptr<MessagePort> Create( fidl::InterfaceRequest<::fuchsia::web::MessagePort> port); + // Gets the implementation of |port| for callers who know its platform type. + static MessagePortFuchsia* FromMessagePort(MessagePort* port); + + // Returns the platform-specific port resources and invalidates this object. + // The caller is responsible for choosing the take method which is appropriate + // to the underlying FIDL resource. Attempting to take the wrong resource will + // produce a DCHECK failure. + virtual fidl::InterfaceHandle<::fuchsia::web::MessagePort> + TakeClientHandle() = 0; + virtual fidl::InterfaceRequest<::fuchsia::web::MessagePort> + TakeServiceRequest() = 0; + protected: // Represents whether a MessagePortFuchsia was created from an InterfaceHandle // (PortType::HANDLE) or InterfaceRequest (PortType::REQUEST) @@ -38,7 +50,7 @@ REQUEST = 2, }; - MessagePortFuchsia(PortType port_type); + explicit MessagePortFuchsia(PortType port_type); // Creates a fuchsia::web::WebMessage containing |message| and transferring // |ports| @@ -54,10 +66,6 @@ base::Optional<fuchsia::web::FrameError> ReceiveMessageFromFidl( fuchsia::web::WebMessage message); - // Retrieves the platform-specific port and invalidates this object. - fidl::InterfaceHandle<::fuchsia::web::MessagePort> TakeHandle(); - fidl::InterfaceRequest<::fuchsia::web::MessagePort> TakeRequest(); - void OnZxError(zx_status_t status); void ReportPipeError(); @@ -71,11 +79,6 @@ base::circular_deque<fuchsia::web::WebMessage> message_queue_; private: - // Gets the implementation of |port| for callers who know its platform type. - static MessagePortFuchsia* FromMessagePort(MessagePort* port); - - PortType port_type() const; - const PortType port_type_; };
diff --git a/components/cast/message_port/test_message_port_receiver.cc b/components/cast/message_port/test_message_port_receiver.cc new file mode 100644 index 0000000..9755b5e --- /dev/null +++ b/components/cast/message_port/test_message_port_receiver.cc
@@ -0,0 +1,45 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/cast/message_port/test_message_port_receiver.h" + +#include "base/run_loop.h" + +namespace cast_api_bindings { + +TestMessagePortReceiver::TestMessagePortReceiver() = default; + +TestMessagePortReceiver::~TestMessagePortReceiver() = default; + +bool TestMessagePortReceiver::RunUntilMessageCountEqual(size_t message_count) { + base::RunLoop run_loop; + on_receive_satisfied_ = run_loop.QuitClosure(); + message_count_target_ = message_count; + run_loop.Run(); + return message_count_target_ == message_count; +} + +void TestMessagePortReceiver::RunUntilDisconnected() { + base::RunLoop run_loop; + on_disconnect_ = run_loop.QuitClosure(); + run_loop.Run(); +} + +bool TestMessagePortReceiver::OnMessage( + base::StringPiece message, + std::vector<std::unique_ptr<MessagePort>> ports) { + buffer_.push_back(std::make_pair(message.as_string(), std::move(ports))); + if (message_count_target_ == buffer_.size()) { + DCHECK(on_receive_satisfied_); + std::move(on_receive_satisfied_).Run(); + } + return true; +} + +void TestMessagePortReceiver::OnPipeError() { + if (on_disconnect_) + std::move(on_disconnect_).Run(); +} + +} // namespace cast_api_bindings
diff --git a/components/cast/message_port/test_message_port_receiver.h b/components/cast/message_port/test_message_port_receiver.h new file mode 100644 index 0000000..ca3f99d --- /dev/null +++ b/components/cast/message_port/test_message_port_receiver.h
@@ -0,0 +1,53 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_CAST_MESSAGE_PORT_TEST_MESSAGE_PORT_RECEIVER_H_ +#define COMPONENTS_CAST_MESSAGE_PORT_TEST_MESSAGE_PORT_RECEIVER_H_ + +#include <memory> +#include <vector> + +#include "base/callback.h" +#include "base/strings/string_piece.h" +#include "components/cast/message_port/message_port.h" + +namespace cast_api_bindings { + +class TestMessagePortReceiver + : public cast_api_bindings::MessagePort::Receiver { + public: + TestMessagePortReceiver(); + ~TestMessagePortReceiver() override; + + TestMessagePortReceiver(const TestMessagePortReceiver&) = delete; + TestMessagePortReceiver& operator=(const TestMessagePortReceiver&) = delete; + + // Spins a RunLoop until |buffer_| has |message_count| messages. + bool RunUntilMessageCountEqual(size_t message_count); + + // Spins a RunLoop until the associated MessagePort is disconnected. + void RunUntilDisconnected(); + + std::vector< + std::pair<std::string, std::vector<std::unique_ptr<MessagePort>>>>& + buffer() { + return buffer_; + } + + private: + // MessagePort::Receiver implementation. + bool OnMessage(base::StringPiece message, + std::vector<std::unique_ptr<MessagePort>> ports) final; + void OnPipeError() final; + + std::vector<std::pair<std::string, std::vector<std::unique_ptr<MessagePort>>>> + buffer_; + size_t message_count_target_ = 0; + base::OnceClosure on_receive_satisfied_; + base::OnceClosure on_disconnect_; +}; + +} // namespace cast_api_bindings + +#endif // COMPONENTS_CAST_MESSAGE_PORT_TEST_MESSAGE_PORT_RECEIVER_H_
diff --git a/components/cast/named_message_port_connector/BUILD.gn b/components/cast/named_message_port_connector/BUILD.gn index 6db6a65..25ad6c74 100644 --- a/components/cast/named_message_port_connector/BUILD.gn +++ b/components/cast/named_message_port_connector/BUILD.gn
@@ -13,12 +13,10 @@ deps = [ "//base", "//components/cast:export", + "//components/cast/message_port", ] - public_deps = [ - ":resources", - "//third_party/blink/public/common", - ] + public_deps = [ ":resources" ] } grit("resources") {
diff --git a/components/cast/named_message_port_connector/named_message_port_connector.cc b/components/cast/named_message_port_connector/named_message_port_connector.cc index 3f5c312..d989023 100644 --- a/components/cast/named_message_port_connector/named_message_port_connector.cc +++ b/components/cast/named_message_port_connector/named_message_port_connector.cc
@@ -25,35 +25,32 @@ // Receives the MessagePort and forwards ports to their corresponding binding // handlers. bool NamedMessagePortConnector::OnMessage( - blink::WebMessagePort::Message message) { - if (message.ports.size() != 1) { + base::StringPiece message, + std::vector<std::unique_ptr<MessagePort>> ports) { + if (ports.size() != 1) { DLOG(FATAL) << "Only one control port should be provided"; return false; } // Read the port ID. - base::string16 data_utf16 = std::move(message.data); - std::string binding_id; - if (!base::UTF16ToUTF8(data_utf16.data(), data_utf16.size(), &binding_id)) + if (message.empty()) { + DLOG(FATAL) << "No port ID was specified."; return false; + } - return handler_.Run(binding_id, std::move(message.ports[0])); + return handler_.Run(message, std::move(ports[0])); } -blink::WebMessagePort::Message NamedMessagePortConnector::GetConnectMessage() { +void NamedMessagePortConnector::OnPipeError() {} + +void NamedMessagePortConnector::GetConnectMessage( + std::string* message, + std::unique_ptr<MessagePort>* port) { constexpr char kControlPortConnectMessage[] = "cast.master.connect"; - - // Pass the control message port into the page as an HTML5 MessageChannel - // message. - auto port_pair = blink::WebMessagePort::CreatePair(); - - control_port_ = std::move(port_pair.first); - control_port_.SetReceiver(this, base::ThreadTaskRunnerHandle::Get()); - - blink::WebMessagePort::Message connect_message; - connect_message.data = base::UTF8ToUTF16(kControlPortConnectMessage); - connect_message.ports.push_back(std::move(port_pair.second)); - return connect_message; + std::unique_ptr<MessagePort> control_port_for_web_engine; + MessagePort::CreatePair(&control_port_, port); + *message = kControlPortConnectMessage; + control_port_->SetReceiver(this); } } // namespace cast_api_bindings
diff --git a/components/cast/named_message_port_connector/named_message_port_connector.h b/components/cast/named_message_port_connector/named_message_port_connector.h index 6ebe36e..93ce32b7 100644 --- a/components/cast/named_message_port_connector/named_message_port_connector.h +++ b/components/cast/named_message_port_connector/named_message_port_connector.h
@@ -7,7 +7,7 @@ #include "base/callback.h" #include "base/strings/string_piece.h" -#include "third_party/blink/public/common/messaging/web_message_port.h" +#include "components/cast/message_port/message_port.h" namespace cast_api_bindings { @@ -16,15 +16,13 @@ // Platform specific details, such as how the script resources are injected, and // how the connection message is posted to the page, are delegated to the // caller. -// TODO(crbug.com/1126571): Migrate off Blink::WebMessagePort to a -// platform-agnostic MessagePort abstraction. -class NamedMessagePortConnector - : public blink::WebMessagePort::MessageReceiver { +class NamedMessagePortConnector : public MessagePort::Receiver { public: // Signature of callback to be invoked when a port is connected. // The callback should return true if the connection request was valid. using PortConnectedCallback = - base::RepeatingCallback<bool(base::StringPiece, blink::WebMessagePort)>; + base::RepeatingCallback<bool(base::StringPiece, + std::unique_ptr<MessagePort>)>; NamedMessagePortConnector(); ~NamedMessagePortConnector() override; @@ -36,17 +34,20 @@ // Sets the callback which will be invoked when a port is connected. void RegisterPortHandler(PortConnectedCallback handler); - // Returns a connection message which should be posted to the page on - // every navigation. - // Calling this method will drop any preexisting connections made to the page. - blink::WebMessagePort::Message GetConnectMessage(); + // Returns a data payload and MessagePort which, when posted into a web + // content main frame, will establish a connection between |this| and the + // NamedMessagePortConnector JavaScript module. + void GetConnectMessage(std::string* message, + std::unique_ptr<MessagePort>* port); private: - // blink::WebMessagePort::MessageReceiver implementation: - bool OnMessage(blink::WebMessagePort::Message message) override; + // MessagePort::Receiver implementation. + bool OnMessage(base::StringPiece message, + std::vector<std::unique_ptr<MessagePort>> ports) final; + void OnPipeError() final; PortConnectedCallback handler_; - blink::WebMessagePort control_port_; + std::unique_ptr<MessagePort> control_port_; }; } // namespace cast_api_bindings
diff --git a/components/cronet/android/BUILD.gn b/components/cronet/android/BUILD.gn index 94b5661..7172105 100644 --- a/components/cronet/android/BUILD.gn +++ b/components/cronet/android/BUILD.gn
@@ -82,12 +82,10 @@ java_cpp_template("load_states_list") { sources = [ "java/src/org/chromium/net/impl/LoadState.template" ] inputs = [ "//net/base/load_states_list.h" ] - package_path = "org/chromium/net/impl" } java_cpp_template("integrated_mode_state") { sources = [ "java/src/org/chromium/net/impl/IntegratedModeState.template" ] - package_path = "org/chromium/net/impl" if (integrated_mode) { defines = [ "INTEGRATED_MODE" ] }
diff --git a/components/cronet/cronet_url_request_context.cc b/components/cronet/cronet_url_request_context.cc index e5eef67..012183e 100644 --- a/components/cronet/cronet_url_request_context.cc +++ b/components/cronet/cronet_url_request_context.cc
@@ -620,15 +620,15 @@ // Do nothing if already logging to a file. if (net_log_file_observer_) return; - net_log_file_observer_ = net::FileNetLogObserver::CreateUnbounded( - file_path, /*constants=*/nullptr); - CreateNetLogEntriesForActiveObjects({context_.get()}, - net_log_file_observer_.get()); + net::NetLogCaptureMode capture_mode = include_socket_bytes ? net::NetLogCaptureMode::kEverything : net::NetLogCaptureMode::kDefault; - net_log_file_observer_->StartObserving(g_net_log.Get().net_log(), - capture_mode); + net_log_file_observer_ = net::FileNetLogObserver::CreateUnbounded( + file_path, capture_mode, /*constants=*/nullptr); + CreateNetLogEntriesForActiveObjects({context_.get()}, + net_log_file_observer_.get()); + net_log_file_observer_->StartObserving(g_net_log.Get().net_log()); } void CronetURLRequestContext::NetworkTasks::StartNetLogToBoundedFile( @@ -657,17 +657,16 @@ } } + net::NetLogCaptureMode capture_mode = + include_socket_bytes ? net::NetLogCaptureMode::kEverything + : net::NetLogCaptureMode::kDefault; net_log_file_observer_ = net::FileNetLogObserver::CreateBounded( - file_path, size, /*constants=*/nullptr); + file_path, size, capture_mode, /*constants=*/nullptr); CreateNetLogEntriesForActiveObjects({context_.get()}, net_log_file_observer_.get()); - net::NetLogCaptureMode capture_mode = - include_socket_bytes ? net::NetLogCaptureMode::kEverything - : net::NetLogCaptureMode::kDefault; - net_log_file_observer_->StartObserving(g_net_log.Get().net_log(), - capture_mode); + net_log_file_observer_->StartObserving(g_net_log.Get().net_log()); } void CronetURLRequestContext::NetworkTasks::StopNetLog() { @@ -689,8 +688,7 @@ } base::Value CronetURLRequestContext::NetworkTasks::GetNetLogInfo() const { - base::Value net_info = - net::GetNetInfo(context_.get(), net::NET_INFO_ALL_SOURCES); + base::Value net_info = net::GetNetInfo(context_.get()); if (effective_experimental_options_) { net_info.SetKey("cronetExperimentalParams", effective_experimental_options_->Clone());
diff --git a/components/cronet/ios/cronet_environment.mm b/components/cronet/ios/cronet_environment.mm index c506805..dad9072 100644 --- a/components/cronet/ios/cronet_environment.mm +++ b/components/cronet/ios/cronet_environment.mm
@@ -178,9 +178,8 @@ : net::NetLogCaptureMode::kDefault; file_net_log_observer_ = - net::FileNetLogObserver::CreateUnbounded(path, nullptr); - file_net_log_observer_->StartObserving(main_context_->net_log(), - capture_mode); + net::FileNetLogObserver::CreateUnbounded(path, capture_mode, nullptr); + file_net_log_observer_->StartObserving(main_context_->net_log()); LOG(WARNING) << "Started NetLog"; } @@ -208,8 +207,7 @@ } base::Value CronetEnvironment::GetNetLogInfo() const { - base::Value net_info = - net::GetNetInfo(main_context_.get(), net::NET_INFO_ALL_SOURCES); + base::Value net_info = net::GetNetInfo(main_context_.get()); if (effective_experimental_options_) { net_info.SetKey("cronetExperimentalParams", effective_experimental_options_->Clone());
diff --git a/components/cronet/url_request_context_config.cc b/components/cronet/url_request_context_config.cc index cf082d8..51d7f42 100644 --- a/components/cronet/url_request_context_config.cc +++ b/components/cronet/url_request_context_config.cc
@@ -92,6 +92,7 @@ const char kQuicVersion[] = "quic_version"; const char kQuicObsoleteVersionsAllowed[] = "obsolete_versions_allowed"; const char kQuicFlags[] = "set_quic_flags"; +const char kQuicIOSNetworkServiceType[] = "ios_network_service_type"; // AsyncDNS experiment dictionary name. const char kAsyncDnsFieldTrialName[] = "AsyncDNS"; @@ -547,6 +548,12 @@ } } + int quic_ios_network_service_type; + if (quic_args->GetInteger(kQuicIOSNetworkServiceType, + &quic_ios_network_service_type)) { + quic_params->ios_network_service_type = quic_ios_network_service_type; + } + } else if (it.key() == kAsyncDnsFieldTrialName) { const base::DictionaryValue* async_dns_args = nullptr; if (!it.value().GetAsDictionary(&async_dns_args)) {
diff --git a/components/cronet/url_request_context_config_unittest.cc b/components/cronet/url_request_context_config_unittest.cc index ad5bb56..7dc2432 100644 --- a/components/cronet/url_request_context_config_unittest.cc +++ b/components/cronet/url_request_context_config_unittest.cc
@@ -137,6 +137,7 @@ base::Value("MAP * 127.0.0.1")); // See http://crbug.com/696569. options.SetKey("disable_ipv6_on_wifi", base::Value(true)); + options.SetPath({"QUIC", "ios_network_service_type"}, base::Value(2)); std::string options_json; EXPECT_TRUE(base::JSONWriter::Write(options, &options_json)); @@ -216,6 +217,9 @@ EXPECT_FALSE(quic_params->race_stale_dns_on_connection); EXPECT_FALSE(quic_params->go_away_on_path_degrading); + // Check network_service_type for iOS. + EXPECT_EQ(2, quic_params->ios_network_service_type); + #if defined(ENABLE_BUILT_IN_DNS) // Check AsyncDNS resolver is enabled (not supported on iOS). EXPECT_TRUE(context->host_resolver()->GetDnsConfigAsValue());
diff --git a/components/exo/BUILD.gn b/components/exo/BUILD.gn index 826c076..2ff08f53 100644 --- a/components/exo/BUILD.gn +++ b/components/exo/BUILD.gn
@@ -128,6 +128,7 @@ "//ash/public/cpp", "//chromeos/constants", "//chromeos/crosapi/cpp", + "//chromeos/ui/base", "//ui/events/ozone/layout", ] sources += [ @@ -224,6 +225,7 @@ deps += [ "//ash:test_support", "//ash/public/cpp", + "//chromeos/ui/base", ] } }
diff --git a/components/exo/DEPS b/components/exo/DEPS index 361f61bd..46b7ed2d 100644 --- a/components/exo/DEPS +++ b/components/exo/DEPS
@@ -4,6 +4,7 @@ "+chromeos/audio/chromeos_sounds.h", "+chromeos/constants/chromeos_features.h", "+chromeos/crosapi/cpp/crosapi_constants.h", + "+chromeos/ui/base/window_state_type.h", "+components/viz/common", "+components/viz/host", "+device/gamepad",
diff --git a/components/exo/client_controlled_shell_surface.cc b/components/exo/client_controlled_shell_surface.cc index 41cb88f..467443f 100644 --- a/components/exo/client_controlled_shell_surface.cc +++ b/components/exo/client_controlled_shell_surface.cc
@@ -19,7 +19,6 @@ #include "ash/public/cpp/window_backdrop.h" #include "ash/public/cpp/window_pin_type.h" #include "ash/public/cpp/window_properties.h" -#include "ash/public/cpp/window_state_type.h" #include "ash/root_window_controller.h" #include "ash/shell.h" #include "ash/wm/client_controlled_state.h" @@ -39,6 +38,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/trace_event/trace_event.h" #include "base/trace_event/traced_value.h" +#include "chromeos/ui/base/window_state_type.h" #include "components/exo/shell_surface_util.h" #include "components/exo/surface.h" #include "components/exo/wm_helper.h" @@ -62,6 +62,8 @@ namespace { +using ::chromeos::WindowStateType; + // Client controlled specific accelerators. const struct { ui::KeyboardCode keycode; @@ -106,12 +108,12 @@ // Overridden from ash::ClientControlledState::Delegate: void HandleWindowStateRequest(ash::WindowState* window_state, - ash::WindowStateType next_state) override { + chromeos::WindowStateType next_state) override { shell_surface_->OnWindowStateChangeEvent(window_state->GetStateType(), next_state); } void HandleBoundsRequest(ash::WindowState* window_state, - ash::WindowStateType requested_state, + chromeos::WindowStateType requested_state, const gfx::Rect& bounds_in_display, int64_t display_id) override { shell_surface_->OnBoundsChangeEvent( @@ -140,31 +142,31 @@ // Overridden from ash::WindowStateDelegate: bool ToggleFullscreen(ash::WindowState* window_state) override { - ash::WindowStateType next_state; + chromeos::WindowStateType next_state; aura::Window* window = window_state->window(); switch (window_state->GetStateType()) { - case ash::WindowStateType::kDefault: - case ash::WindowStateType::kNormal: + case chromeos::WindowStateType::kDefault: + case chromeos::WindowStateType::kNormal: window->SetProperty(aura::client::kPreFullscreenShowStateKey, ui::SHOW_STATE_NORMAL); - next_state = ash::WindowStateType::kFullscreen; + next_state = chromeos::WindowStateType::kFullscreen; break; - case ash::WindowStateType::kMaximized: + case chromeos::WindowStateType::kMaximized: window->SetProperty(aura::client::kPreFullscreenShowStateKey, ui::SHOW_STATE_MAXIMIZED); - next_state = ash::WindowStateType::kFullscreen; + next_state = chromeos::WindowStateType::kFullscreen; break; - case ash::WindowStateType::kFullscreen: + case chromeos::WindowStateType::kFullscreen: switch (window->GetProperty(aura::client::kPreFullscreenShowStateKey)) { case ui::SHOW_STATE_DEFAULT: case ui::SHOW_STATE_NORMAL: - next_state = ash::WindowStateType::kNormal; + next_state = chromeos::WindowStateType::kNormal; break; case ui::SHOW_STATE_MAXIMIZED: - next_state = ash::WindowStateType::kMaximized; + next_state = chromeos::WindowStateType::kMaximized; break; case ui::SHOW_STATE_MINIMIZED: - next_state = ash::WindowStateType::kMinimized; + next_state = chromeos::WindowStateType::kMinimized; break; case ui::SHOW_STATE_FULLSCREEN: case ui::SHOW_STATE_INACTIVE: @@ -175,14 +177,14 @@ return false; } break; - case ash::WindowStateType::kMinimized: { + case chromeos::WindowStateType::kMinimized: { ui::WindowShowState pre_full_state = window->GetProperty(aura::client::kPreMinimizedShowStateKey); if (pre_full_state != ui::SHOW_STATE_FULLSCREEN) { window->SetProperty(aura::client::kPreFullscreenShowStateKey, pre_full_state); } - next_state = ash::WindowStateType::kFullscreen; + next_state = chromeos::WindowStateType::kFullscreen; break; } default: @@ -382,39 +384,39 @@ void ClientControlledShellSurface::SetMaximized() { TRACE_EVENT0("exo", "ClientControlledShellSurface::SetMaximized"); - pending_window_state_ = ash::WindowStateType::kMaximized; + pending_window_state_ = chromeos::WindowStateType::kMaximized; } void ClientControlledShellSurface::SetMinimized() { TRACE_EVENT0("exo", "ClientControlledShellSurface::SetMinimized"); - pending_window_state_ = ash::WindowStateType::kMinimized; + pending_window_state_ = chromeos::WindowStateType::kMinimized; } void ClientControlledShellSurface::SetRestored() { TRACE_EVENT0("exo", "ClientControlledShellSurface::SetRestored"); - pending_window_state_ = ash::WindowStateType::kNormal; + pending_window_state_ = chromeos::WindowStateType::kNormal; } void ClientControlledShellSurface::SetFullscreen(bool fullscreen) { TRACE_EVENT1("exo", "ClientControlledShellSurface::SetFullscreen", "fullscreen", fullscreen); - pending_window_state_ = fullscreen ? ash::WindowStateType::kFullscreen - : ash::WindowStateType::kNormal; + pending_window_state_ = fullscreen ? chromeos::WindowStateType::kFullscreen + : chromeos::WindowStateType::kNormal; } void ClientControlledShellSurface::SetSnappedToLeft() { TRACE_EVENT0("exo", "ClientControlledShellSurface::SetSnappedToLeft"); - pending_window_state_ = ash::WindowStateType::kLeftSnapped; + pending_window_state_ = chromeos::WindowStateType::kLeftSnapped; } void ClientControlledShellSurface::SetSnappedToRight() { TRACE_EVENT0("exo", "ClientControlledShellSurface::SetSnappedToRight"); - pending_window_state_ = ash::WindowStateType::kRightSnapped; + pending_window_state_ = chromeos::WindowStateType::kRightSnapped; } void ClientControlledShellSurface::SetPip() { TRACE_EVENT0("exo", "ClientControlledShellSurface::SetPip"); - pending_window_state_ = ash::WindowStateType::kPip; + pending_window_state_ = chromeos::WindowStateType::kPip; } void ClientControlledShellSurface::SetPinned(ash::WindowPinType type) { @@ -509,8 +511,8 @@ } void ClientControlledShellSurface::OnWindowStateChangeEvent( - ash::WindowStateType current_state, - ash::WindowStateType next_state) { + chromeos::WindowStateType current_state, + chromeos::WindowStateType next_state) { // Android already knows this state change. Don't send state change to Android // that it is about to do anyway. if (state_changed_callback_ && pending_window_state_ != next_state) @@ -637,8 +639,8 @@ } void ClientControlledShellSurface::OnBoundsChangeEvent( - ash::WindowStateType current_state, - ash::WindowStateType requested_state, + chromeos::WindowStateType current_state, + chromeos::WindowStateType requested_state, int64_t display_id, const gfx::Rect& window_bounds, int bounds_change) { @@ -651,7 +653,7 @@ // The bounds will be provided by client when unminimized. if (geometry().IsEmpty() || window_bounds.IsEmpty() || (widget_->IsMinimized() && - requested_state == ash::WindowStateType::kMinimized) || + requested_state == chromeos::WindowStateType::kMinimized) || !bounds_changed_callback_) { return; } @@ -665,8 +667,8 @@ // the window bounds instead for maximixed state. // Snapped window states in tablet mode do not include the caption height. const bool becoming_snapped = - requested_state == ash::WindowStateType::kLeftSnapped || - requested_state == ash::WindowStateType::kRightSnapped; + requested_state == chromeos::WindowStateType::kLeftSnapped || + requested_state == chromeos::WindowStateType::kRightSnapped; const bool is_tablet_mode = WMHelper::GetInstance()->InTabletMode(); gfx::Rect client_bounds = widget_->IsMaximized() || (becoming_snapped && is_tablet_mode) @@ -1096,7 +1098,8 @@ // explicit target display. if (!pending_geometry_.IsEmpty()) origin_ = pending_geometry_.origin(); - CreateShellSurfaceWidget(ash::ToWindowShowState(pending_window_state_)); + CreateShellSurfaceWidget( + chromeos::ToWindowShowState(pending_window_state_)); } // Finish ignoring obsolete bounds update as the state changes caused by @@ -1125,14 +1128,14 @@ auto animation_type = ash::ClientControlledState::kAnimationNone; switch (pending_window_state_) { - case ash::WindowStateType::kNormal: + case chromeos::WindowStateType::kNormal: if (widget_->IsMaximized() || widget_->IsFullscreen()) { animation_type = ash::ClientControlledState::kAnimationCrossFade; } break; - case ash::WindowStateType::kMaximized: - case ash::WindowStateType::kFullscreen: + case chromeos::WindowStateType::kMaximized: + case chromeos::WindowStateType::kFullscreen: if (!window_state->IsPip()) animation_type = ash::ClientControlledState::kAnimationCrossFade; break; @@ -1141,7 +1144,7 @@ break; } - if (pending_window_state_ == ash::WindowStateType::kPip) { + if (pending_window_state_ == chromeos::WindowStateType::kPip) { if (ash::features::IsPipRoundedCornersEnabled()) { decorator_ = std::make_unique<ash::RoundedCornerDecorator>( window_state->window(), host_window(), host_window()->layer(),
diff --git a/components/exo/client_controlled_shell_surface.h b/components/exo/client_controlled_shell_surface.h index 008ba08d..c321ec7 100644 --- a/components/exo/client_controlled_shell_surface.h +++ b/components/exo/client_controlled_shell_surface.h
@@ -91,8 +91,8 @@ // Set the callback to run when the surface state changed. using StateChangedCallback = - base::RepeatingCallback<void(ash::WindowStateType old_state_type, - ash::WindowStateType new_state_type)>; + base::RepeatingCallback<void(chromeos::WindowStateType old_state_type, + chromeos::WindowStateType new_state_type)>; void set_state_changed_callback( const StateChangedCallback& state_changed_callback) { state_changed_callback_ = state_changed_callback; @@ -100,8 +100,8 @@ // Set the callback to run when the surface bounds changed. using BoundsChangedCallback = - base::RepeatingCallback<void(ash::WindowStateType current_state, - ash::WindowStateType requested_state, + base::RepeatingCallback<void(chromeos::WindowStateType current_state, + chromeos::WindowStateType requested_state, int64_t display_id, const gfx::Rect& bounds_in_display, bool is_resize, @@ -172,16 +172,16 @@ void ChangeZoomLevel(ZoomChange change); // Sends the window state change event to client. - void OnWindowStateChangeEvent(ash::WindowStateType old_state, - ash::WindowStateType next_state); + void OnWindowStateChangeEvent(chromeos::WindowStateType old_state, + chromeos::WindowStateType next_state); // Sends the window bounds change event to client. |display_id| specifies in // which display the surface should live in. |drag_bounds_change| is // a masked value of ash::WindowResizer::kBoundsChange_Xxx, and specifies // how the bounds was changed. The bounds change event may also come from a // snapped window state change |requested_state|. - void OnBoundsChangeEvent(ash::WindowStateType current_state, - ash::WindowStateType requested_state, + void OnBoundsChangeEvent(chromeos::WindowStateType current_state, + chromeos::WindowStateType requested_state, int64_t display_id, const gfx::Rect& bounds, int drag_bounds_change); @@ -340,7 +340,8 @@ ash::ClientControlledState* client_controlled_state_ = nullptr; - ash::WindowStateType pending_window_state_ = ash::WindowStateType::kNormal; + chromeos::WindowStateType pending_window_state_ = + chromeos::WindowStateType::kNormal; bool pending_always_on_top_ = false;
diff --git a/components/exo/client_controlled_shell_surface_unittest.cc b/components/exo/client_controlled_shell_surface_unittest.cc index 79728d5..1c0e2b7 100644 --- a/components/exo/client_controlled_shell_surface_unittest.cc +++ b/components/exo/client_controlled_shell_surface_unittest.cc
@@ -62,6 +62,8 @@ #include "ui/wm/core/shadow_controller.h" #include "ui/wm/core/shadow_types.h" +using chromeos::WindowStateType; + namespace exo { namespace { using ClientControlledShellSurfaceTest = test::ExoTestBase; @@ -1061,7 +1063,7 @@ ash::WindowState* window_state1 = ash::WindowState::Get(window1); ash::ClientControlledState* state1 = static_cast<ash::ClientControlledState*>( ash::WindowState::TestApi::GetStateImpl(window_state1)); - EXPECT_EQ(window_state1->GetStateType(), ash::WindowStateType::kMaximized); + EXPECT_EQ(window_state1->GetStateType(), WindowStateType::kMaximized); // Snap window to left. ash::SplitViewController* split_view_controller = @@ -1071,7 +1073,7 @@ window1->SetBounds(split_view_controller->GetSnappedWindowBoundsInScreen( ash::SplitViewController::LEFT, window1)); state1->set_bounds_locally(false); - EXPECT_EQ(window_state1->GetStateType(), ash::WindowStateType::kLeftSnapped); + EXPECT_EQ(window_state1->GetStateType(), WindowStateType::kLeftSnapped); EXPECT_EQ(shell_surface1->GetWidget()->GetWindowBoundsInScreen(), split_view_controller->GetSnappedWindowBoundsInScreen( ash::SplitViewController::LEFT, @@ -1085,7 +1087,7 @@ window1->SetBounds(split_view_controller->GetSnappedWindowBoundsInScreen( ash::SplitViewController::RIGHT, window1)); state1->set_bounds_locally(false); - EXPECT_EQ(window_state1->GetStateType(), ash::WindowStateType::kRightSnapped); + EXPECT_EQ(window_state1->GetStateType(), WindowStateType::kRightSnapped); EXPECT_EQ(shell_surface1->GetWidget()->GetWindowBoundsInScreen(), split_view_controller->GetSnappedWindowBoundsInScreen( ash::SplitViewController::RIGHT, @@ -1288,7 +1290,7 @@ shell->overview_controller()->EndOverview(); SendGestureEvents(window, gfx::Point(0, 210)); EXPECT_EQ(ash::WindowState::Get(window)->GetStateType(), - ash::WindowStateType::kLeftSnapped); + WindowStateType::kLeftSnapped); } namespace { @@ -1319,8 +1321,8 @@ } void OnBoundsChangeEvent(ClientControlledShellSurface* shell_surface, - ash::WindowStateType current_state, - ash::WindowStateType requested_state, + WindowStateType current_state, + WindowStateType requested_state, int64_t display_id, const gfx::Rect& bounds_in_display, bool is_resize, @@ -1937,8 +1939,8 @@ exo_test_helper()->CreateClientControlledShellSurface(surface.get()); gfx::Rect requested_bounds; shell_surface->set_bounds_changed_callback(base::BindRepeating( - [](gfx::Rect* dst, ash::WindowStateType current_state, - ash::WindowStateType requested_state, int64_t display_id, + [](gfx::Rect* dst, WindowStateType current_state, + WindowStateType requested_state, int64_t display_id, const gfx::Rect& bounds, bool is_resize, int bounds_change) { *dst = bounds; }, base::Unretained(&requested_bounds))); @@ -1979,7 +1981,7 @@ ash::WMEvent event(ash::WM_EVENT_SNAP_LEFT); window_state->OnWMEvent(&event); - EXPECT_EQ(window_state->GetStateType(), ash::WindowStateType::kLeftSnapped); + EXPECT_EQ(window_state->GetStateType(), WindowStateType::kLeftSnapped); ash::NonClientFrameViewAsh* frame_view = static_cast<ash::NonClientFrameViewAsh*>( @@ -2040,8 +2042,8 @@ ash::WindowState::Get(shell_surface->GetWidget()->GetNativeWindow()); int64_t display_id = window_state->GetDisplay().id(); - shell_surface->OnBoundsChangeEvent(ash::WindowStateType::kNormal, - ash::WindowStateType::kNormal, display_id, + shell_surface->OnBoundsChangeEvent(WindowStateType::kNormal, + WindowStateType::kNormal, display_id, gfx::Rect(10, 10, 100, 100), 0); ASSERT_EQ(1, bounds_change_count()); @@ -2051,14 +2053,14 @@ surface->Commit(); EXPECT_TRUE(shell_surface->GetWidget()->IsMinimized()); - shell_surface->OnBoundsChangeEvent(ash::WindowStateType::kMinimized, - ash::WindowStateType::kMinimized, - display_id, gfx::Rect(0, 0, 100, 100), 0); + shell_surface->OnBoundsChangeEvent(WindowStateType::kMinimized, + WindowStateType::kMinimized, display_id, + gfx::Rect(0, 0, 100, 100), 0); ASSERT_EQ(1, bounds_change_count()); // Send bounds change when exiting minmized. - shell_surface->OnBoundsChangeEvent(ash::WindowStateType::kMinimized, - ash::WindowStateType::kNormal, display_id, + shell_surface->OnBoundsChangeEvent(WindowStateType::kMinimized, + WindowStateType::kNormal, display_id, gfx::Rect(0, 0, 100, 100), 0); ASSERT_EQ(2, bounds_change_count()); @@ -2068,9 +2070,9 @@ shell_surface->GetWidget()->non_client_view()->frame_view()); surface->SetFrame(SurfaceFrameType::NORMAL); surface->Commit(); - shell_surface->OnBoundsChangeEvent(ash::WindowStateType::kMinimized, - ash::WindowStateType::kRightSnapped, - display_id, gfx::Rect(0, 0, 100, 100), 0); + shell_surface->OnBoundsChangeEvent(WindowStateType::kMinimized, + WindowStateType::kRightSnapped, display_id, + gfx::Rect(0, 0, 100, 100), 0); EXPECT_EQ(3, bounds_change_count()); EXPECT_EQ( frame_view->GetClientBoundsForWindowBounds(gfx::Rect(0, 0, 100, 100)), @@ -2079,9 +2081,9 @@ // Snapped, in tablet mode. EnableTabletMode(true); - shell_surface->OnBoundsChangeEvent(ash::WindowStateType::kMinimized, - ash::WindowStateType::kRightSnapped, - display_id, gfx::Rect(0, 0, 100, 100), 0); + shell_surface->OnBoundsChangeEvent(WindowStateType::kMinimized, + WindowStateType::kRightSnapped, display_id, + gfx::Rect(0, 0, 100, 100), 0); EXPECT_EQ(4, bounds_change_count()); EXPECT_EQ(gfx::Rect(0, 0, 100, 100), requested_bounds().back()); } @@ -2253,7 +2255,7 @@ exo_test_helper()->CreateClientControlledShellSurface(surface.get()); shell_surface->set_state_changed_callback( - base::BindRepeating([](ash::WindowStateType, ash::WindowStateType) { + base::BindRepeating([](WindowStateType, WindowStateType) { // This callback must not be called when a widget is created. EXPECT_TRUE(false); })); @@ -2424,8 +2426,8 @@ } void OnBoundsChangeEvent(ClientControlledShellSurface* shell_surface, - ash::WindowStateType current_state, - ash::WindowStateType requested_state, + WindowStateType current_state, + WindowStateType requested_state, int64_t display_id, const gfx::Rect& bounds_in_display, bool is_resize,
diff --git a/components/exo/shell_surface.cc b/components/exo/shell_surface.cc index 4ca1923e..901e261 100644 --- a/components/exo/shell_surface.cc +++ b/components/exo/shell_surface.cc
@@ -5,7 +5,6 @@ #include "components/exo/shell_surface.h" #include "ash/public/cpp/shell_window_ids.h" -#include "ash/public/cpp/window_state_type.h" #include "ash/scoped_animation_disabler.h" #include "ash/shell.h" #include "ash/wm/desks/desks_util.h" @@ -15,6 +14,7 @@ #include "base/bind.h" #include "base/logging.h" #include "base/strings/utf_string_conversions.h" +#include "chromeos/ui/base/window_state_type.h" #include "components/exo/shell_surface_util.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/client/cursor_client.h" @@ -386,16 +386,17 @@ //////////////////////////////////////////////////////////////////////////////// // ash::WindowStateObserver overrides: -void ShellSurface::OnPreWindowStateTypeChange(ash::WindowState* window_state, - ash::WindowStateType old_type) { - ash::WindowStateType new_type = window_state->GetStateType(); - if (ash::IsMinimizedWindowStateType(old_type) || - ash::IsMinimizedWindowStateType(new_type)) { +void ShellSurface::OnPreWindowStateTypeChange( + ash::WindowState* window_state, + chromeos::WindowStateType old_type) { + chromeos::WindowStateType new_type = window_state->GetStateType(); + if (chromeos::IsMinimizedWindowStateType(old_type) || + chromeos::IsMinimizedWindowStateType(new_type)) { return; } - if (ash::IsMaximizedOrFullscreenOrPinnedWindowStateType(old_type) || - ash::IsMaximizedOrFullscreenOrPinnedWindowStateType(new_type)) { + if (chromeos::IsMaximizedOrFullscreenOrPinnedWindowStateType(old_type) || + chromeos::IsMaximizedOrFullscreenOrPinnedWindowStateType(new_type)) { if (!widget_) return; // When transitioning in/out of maximized or fullscreen mode, we need to @@ -418,10 +419,11 @@ } } -void ShellSurface::OnPostWindowStateTypeChange(ash::WindowState* window_state, - ash::WindowStateType old_type) { - ash::WindowStateType new_type = window_state->GetStateType(); - if (ash::IsMaximizedOrFullscreenOrPinnedWindowStateType(new_type)) { +void ShellSurface::OnPostWindowStateTypeChange( + ash::WindowState* window_state, + chromeos::WindowStateType old_type) { + chromeos::WindowStateType new_type = window_state->GetStateType(); + if (chromeos::IsMaximizedOrFullscreenOrPinnedWindowStateType(new_type)) { Configure(); } @@ -557,9 +559,9 @@ GetClientViewBounds().size(), window_state->GetStateType(), IsResizing(), widget_->IsActive(), origin_offset); } else { - serial = - configure_callback_.Run(gfx::Size(), ash::WindowStateType::kNormal, - false, false, origin_offset); + serial = configure_callback_.Run(gfx::Size(), + chromeos::WindowStateType::kNormal, + false, false, origin_offset); } }
diff --git a/components/exo/shell_surface.h b/components/exo/shell_surface.h index c04db233..056114a 100644 --- a/components/exo/shell_surface.h +++ b/components/exo/shell_surface.h
@@ -43,7 +43,7 @@ // in steps of NxM pixels). using ConfigureCallback = base::RepeatingCallback<uint32_t(const gfx::Size& size, - ash::WindowStateType state_type, + chromeos::WindowStateType state_type, bool resizing, bool activated, const gfx::Vector2d& origin_offset)>; @@ -112,9 +112,9 @@ // Overridden from ash::WindowStateObserver: void OnPreWindowStateTypeChange(ash::WindowState* window_state, - ash::WindowStateType old_type) override; + chromeos::WindowStateType old_type) override; void OnPostWindowStateTypeChange(ash::WindowState* window_state, - ash::WindowStateType old_type) override; + chromeos::WindowStateType old_type) override; // Overridden from wm::ActivationChangeObserver: void OnWindowActivated(ActivationReason reason,
diff --git a/components/exo/shell_surface_base.cc b/components/exo/shell_surface_base.cc index 56b33fe..d4f38b2 100644 --- a/components/exo/shell_surface_base.cc +++ b/components/exo/shell_surface_base.cc
@@ -11,7 +11,6 @@ #include "ash/public/cpp/shell_window_ids.h" #include "ash/public/cpp/window_pin_type.h" #include "ash/public/cpp/window_properties.h" -#include "ash/public/cpp/window_state_type.h" #include "ash/shell.h" #include "ash/wm/desks/desks_util.h" #include "ash/wm/drag_window_resizer.h" @@ -27,6 +26,7 @@ #include "base/trace_event/traced_value.h" #include "cc/trees/layer_tree_frame_sink.h" #include "chromeos/crosapi/cpp/crosapi_constants.h" +#include "chromeos/ui/base/window_state_type.h" #include "components/exo/shell_surface_util.h" #include "components/exo/surface.h" #include "components/exo/wm_helper.h"
diff --git a/components/exo/shell_surface_unittest.cc b/components/exo/shell_surface_unittest.cc index 8475794..48b97a7 100644 --- a/components/exo/shell_surface_unittest.cc +++ b/components/exo/shell_surface_unittest.cc
@@ -53,11 +53,11 @@ uint32_t ConfigureFullscreen(uint32_t serial, const gfx::Size& size, - ash::WindowStateType state_type, + chromeos::WindowStateType state_type, bool resizing, bool activated, const gfx::Vector2d& origin_offset) { - EXPECT_EQ(ash::WindowStateType::kFullscreen, state_type); + EXPECT_EQ(chromeos::WindowStateType::kFullscreen, state_type); return serial; } @@ -644,11 +644,11 @@ } uint32_t Configure(gfx::Size* suggested_size, - ash::WindowStateType* has_state_type, + chromeos::WindowStateType* has_state_type, bool* is_resizing, bool* is_active, const gfx::Size& size, - ash::WindowStateType state_type, + chromeos::WindowStateType state_type, bool resizing, bool activated, const gfx::Vector2d& origin_offset) { @@ -663,7 +663,7 @@ // Must be before shell_surface so it outlives it, for shell_surface's // destructor calls Configure() referencing these 4 variables. gfx::Size suggested_size; - ash::WindowStateType has_state_type = ash::WindowStateType::kNormal; + chromeos::WindowStateType has_state_type = chromeos::WindowStateType::kNormal; bool is_resizing = false; bool is_active = false; @@ -692,7 +692,7 @@ EXPECT_FALSE(shell_surface->GetWidget()); EXPECT_TRUE(suggested_size.IsEmpty()); - EXPECT_EQ(ash::WindowStateType::kNormal, has_state_type); + EXPECT_EQ(chromeos::WindowStateType::kNormal, has_state_type); gfx::Size buffer_size(64, 64); std::unique_ptr<Buffer> buffer( @@ -704,7 +704,7 @@ display::Screen::GetScreen()->GetPrimaryDisplay().work_area(); EXPECT_TRUE(shell_surface->GetWidget()); EXPECT_EQ(maximized_bounds.size(), suggested_size); - EXPECT_EQ(ash::WindowStateType::kMaximized, has_state_type); + EXPECT_EQ(chromeos::WindowStateType::kMaximized, has_state_type); shell_surface->Restore(); shell_surface->AcknowledgeConfigure(0); // It should be restored to the original geometry size. @@ -714,7 +714,7 @@ shell_surface->AcknowledgeConfigure(0); EXPECT_EQ(GetContext()->bounds().size().ToString(), suggested_size.ToString()); - EXPECT_EQ(ash::WindowStateType::kFullscreen, has_state_type); + EXPECT_EQ(chromeos::WindowStateType::kFullscreen, has_state_type); shell_surface->SetFullscreen(false); shell_surface->AcknowledgeConfigure(0); EXPECT_EQ(geometry.size(), shell_surface->CalculatePreferredSize());
diff --git a/components/exo/test/exo_test_helper.cc b/components/exo/test/exo_test_helper.cc index f374cf7..c820d2c 100644 --- a/components/exo/test/exo_test_helper.cc +++ b/components/exo/test/exo_test_helper.cc
@@ -32,20 +32,20 @@ namespace { void HandleWindowStateRequest(ClientControlledShellSurface* shell_surface, - ash::WindowStateType old_state, - ash::WindowStateType new_state) { + chromeos::WindowStateType old_state, + chromeos::WindowStateType new_state) { switch (new_state) { - case ash::WindowStateType::kNormal: - case ash::WindowStateType::kDefault: + case chromeos::WindowStateType::kNormal: + case chromeos::WindowStateType::kDefault: shell_surface->SetRestored(); break; - case ash::WindowStateType::kMinimized: + case chromeos::WindowStateType::kMinimized: shell_surface->SetMinimized(); break; - case ash::WindowStateType::kMaximized: + case chromeos::WindowStateType::kMaximized: shell_surface->SetMaximized(); break; - case ash::WindowStateType::kFullscreen: + case chromeos::WindowStateType::kFullscreen: shell_surface->SetFullscreen(true); break; default: @@ -56,8 +56,8 @@ } void HandleBoundsChangedRequest(ClientControlledShellSurface* shell_surface, - ash::WindowStateType current_state, - ash::WindowStateType requested_state, + chromeos::WindowStateType current_state, + chromeos::WindowStateType requested_state, int64_t display_id, const gfx::Rect& bounds_in_screen, bool is_resize, @@ -88,10 +88,10 @@ shell_surface->SetBounds(display_id, bounds_in_display); if (requested_state != window_state->GetStateType()) { - DCHECK(requested_state == ash::WindowStateType::kLeftSnapped || - requested_state == ash::WindowStateType::kRightSnapped); + DCHECK(requested_state == chromeos::WindowStateType::kLeftSnapped || + requested_state == chromeos::WindowStateType::kRightSnapped); - if (requested_state == ash::WindowStateType::kLeftSnapped) + if (requested_state == chromeos::WindowStateType::kLeftSnapped) shell_surface->SetSnappedToLeft(); else shell_surface->SetSnappedToRight();
diff --git a/components/exo/test/exo_test_helper.h b/components/exo/test/exo_test_helper.h index 06ae2aa..813926b 100644 --- a/components/exo/test/exo_test_helper.h +++ b/components/exo/test/exo_test_helper.h
@@ -7,9 +7,9 @@ #include <memory> -#include "ash/public/cpp/window_state_type.h" #include "base/compiler_specific.h" #include "base/macros.h" +#include "chromeos/ui/base/window_state_type.h" #include "ui/gfx/buffer_types.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/size.h"
diff --git a/components/exo/wayland/BUILD.gn b/components/exo/wayland/BUILD.gn index 92ade79..3044611 100644 --- a/components/exo/wayland/BUILD.gn +++ b/components/exo/wayland/BUILD.gn
@@ -124,6 +124,7 @@ deps += [ "//ash", "//ash/public/cpp", + "//chromeos/ui/base", ] } }
diff --git a/components/exo/wayland/wl_shell.cc b/components/exo/wayland/wl_shell.cc index 2b4250a..167ddbd 100644 --- a/components/exo/wayland/wl_shell.cc +++ b/components/exo/wayland/wl_shell.cc
@@ -125,7 +125,7 @@ uint32_t HandleShellSurfaceConfigureCallback( wl_resource* resource, const gfx::Size& size, - ash::WindowStateType state_type, + chromeos::WindowStateType state_type, bool resizing, bool activated, const gfx::Vector2d& origin_offset) {
diff --git a/components/exo/wayland/xdg_shell.cc b/components/exo/wayland/xdg_shell.cc index 6aa2057..07abcf49 100644 --- a/components/exo/wayland/xdg_shell.cc +++ b/components/exo/wayland/xdg_shell.cc
@@ -11,9 +11,9 @@ #include "ash/public/cpp/shell_window_ids.h" #include "ash/public/cpp/window_properties.h" -#include "ash/public/cpp/window_state_type.h" #include "base/bind.h" #include "base/strings/utf_string_conversions.h" +#include "chromeos/ui/base/window_state_type.h" #include "components/exo/display.h" #include "components/exo/wayland/serial_tracker.h" #include "components/exo/wayland/server_util.h" @@ -124,7 +124,7 @@ using XdgSurfaceConfigureCallback = base::RepeatingCallback<void(const gfx::Size& size, - ash::WindowStateType state_type, + chromeos::WindowStateType state_type, bool resizing, bool activated)>; @@ -133,7 +133,7 @@ SerialTracker* serial_tracker, const XdgSurfaceConfigureCallback& callback, const gfx::Size& size, - ash::WindowStateType state_type, + chromeos::WindowStateType state_type, bool resizing, bool activated, const gfx::Vector2d& origin_offset) { @@ -301,14 +301,14 @@ } void OnConfigure(const gfx::Size& size, - ash::WindowStateType state_type, + chromeos::WindowStateType state_type, bool resizing, bool activated) { wl_array states; wl_array_init(&states); - if (state_type == ash::WindowStateType::kMaximized) + if (state_type == chromeos::WindowStateType::kMaximized) AddState(&states, XDG_TOPLEVEL_STATE_MAXIMIZED); - if (state_type == ash::WindowStateType::kFullscreen) + if (state_type == chromeos::WindowStateType::kFullscreen) AddState(&states, XDG_TOPLEVEL_STATE_FULLSCREEN); if (resizing) AddState(&states, XDG_TOPLEVEL_STATE_RESIZING); @@ -477,7 +477,7 @@ } void OnConfigure(const gfx::Size& size, - ash::WindowStateType state_type, + chromeos::WindowStateType state_type, bool resizing, bool activated) { // Nothing to do here as popups don't have additional configure state.
diff --git a/components/exo/wayland/zcr_remote_shell.cc b/components/exo/wayland/zcr_remote_shell.cc index 3746e60..bf39d888b 100644 --- a/components/exo/wayland/zcr_remote_shell.cc +++ b/components/exo/wayland/zcr_remote_shell.cc
@@ -56,6 +56,8 @@ } // namespace switches +using chromeos::WindowStateType; + // We don't send configure immediately after tablet mode switch // because layout can change due to orientation lock state or accelerometer. constexpr int kConfigureDelayAfterLayoutSwitchMs = 300; @@ -1131,8 +1133,8 @@ void HandleRemoteSurfaceBoundsChangedCallback( wl_resource* resource, - ash::WindowStateType current_state, - ash::WindowStateType requested_state, + WindowStateType current_state, + WindowStateType requested_state, int64_t display_id, const gfx::Rect& bounds_in_display, bool resize, @@ -1140,7 +1142,7 @@ zcr_remote_surface_v1_bounds_change_reason reason = ZCR_REMOTE_SURFACE_V1_BOUNDS_CHANGE_REASON_RESIZE; if (!resize) { - reason = current_state == ash::WindowStateType::kPip + reason = current_state == WindowStateType::kPip ? ZCR_REMOTE_SURFACE_V1_BOUNDS_CHANGE_REASON_MOVE_PIP : ZCR_REMOTE_SURFACE_V1_BOUNDS_CHANGE_REASON_MOVE; } @@ -1152,9 +1154,9 @@ // Override the reason only if the window enters snapped mode. If the window // resizes by dragging in snapped mode, we need to keep the original reason. if (requested_state != current_state) { - if (requested_state == ash::WindowStateType::kLeftSnapped) { + if (requested_state == WindowStateType::kLeftSnapped) { reason = ZCR_REMOTE_SURFACE_V1_BOUNDS_CHANGE_REASON_SNAP_TO_LEFT; - } else if (requested_state == ash::WindowStateType::kRightSnapped) { + } else if (requested_state == WindowStateType::kRightSnapped) { reason = ZCR_REMOTE_SURFACE_V1_BOUNDS_CHANGE_REASON_SNAP_TO_RIGHT; } } @@ -1199,10 +1201,9 @@ bounds_in_display.height(), reason); } - void HandleRemoteSurfaceStateChangedCallback( - wl_resource* resource, - ash::WindowStateType old_state_type, - ash::WindowStateType new_state_type) { + void HandleRemoteSurfaceStateChangedCallback(wl_resource* resource, + WindowStateType old_state_type, + WindowStateType new_state_type) { DCHECK_NE(old_state_type, new_state_type); LOG_IF(ERROR, pending_bounds_changes_.count(resource) > 0) << "Sending window state while there is a pending bounds change. This " @@ -1210,28 +1211,28 @@ uint32_t state_type = ZCR_REMOTE_SHELL_V1_STATE_TYPE_NORMAL; switch (new_state_type) { - case ash::WindowStateType::kMinimized: + case WindowStateType::kMinimized: state_type = ZCR_REMOTE_SHELL_V1_STATE_TYPE_MINIMIZED; break; - case ash::WindowStateType::kMaximized: + case WindowStateType::kMaximized: state_type = ZCR_REMOTE_SHELL_V1_STATE_TYPE_MAXIMIZED; break; - case ash::WindowStateType::kFullscreen: + case WindowStateType::kFullscreen: state_type = ZCR_REMOTE_SHELL_V1_STATE_TYPE_FULLSCREEN; break; - case ash::WindowStateType::kPinned: + case WindowStateType::kPinned: state_type = ZCR_REMOTE_SHELL_V1_STATE_TYPE_PINNED; break; - case ash::WindowStateType::kTrustedPinned: + case WindowStateType::kTrustedPinned: state_type = ZCR_REMOTE_SHELL_V1_STATE_TYPE_TRUSTED_PINNED; break; - case ash::WindowStateType::kLeftSnapped: + case WindowStateType::kLeftSnapped: state_type = ZCR_REMOTE_SHELL_V1_STATE_TYPE_LEFT_SNAPPED; break; - case ash::WindowStateType::kRightSnapped: + case WindowStateType::kRightSnapped: state_type = ZCR_REMOTE_SHELL_V1_STATE_TYPE_RIGHT_SNAPPED; break; - case ash::WindowStateType::kPip: + case WindowStateType::kPip: state_type = ZCR_REMOTE_SHELL_V1_STATE_TYPE_PIP; break; default:
diff --git a/components/exo/wayland/zxdg_shell.cc b/components/exo/wayland/zxdg_shell.cc index a428448..1a3e0fa4c 100644 --- a/components/exo/wayland/zxdg_shell.cc +++ b/components/exo/wayland/zxdg_shell.cc
@@ -10,9 +10,9 @@ #include "ash/public/cpp/shell_window_ids.h" #include "ash/public/cpp/window_properties.h" -#include "ash/public/cpp/window_state_type.h" #include "base/bind.h" #include "base/strings/utf_string_conversions.h" +#include "chromeos/ui/base/window_state_type.h" #include "components/exo/display.h" #include "components/exo/wayland/serial_tracker.h" #include "components/exo/wayland/server_util.h" @@ -144,7 +144,7 @@ using XdgSurfaceConfigureCallback = base::RepeatingCallback<void(const gfx::Size& size, - ash::WindowStateType state_type, + chromeos::WindowStateType state_type, bool resizing, bool activated)>; @@ -153,7 +153,7 @@ SerialTracker* serial_tracker, const XdgSurfaceConfigureCallback& callback, const gfx::Size& size, - ash::WindowStateType state_type, + chromeos::WindowStateType state_type, bool resizing, bool activated, const gfx::Vector2d& origin_offset) { @@ -290,14 +290,14 @@ } void OnConfigure(const gfx::Size& size, - ash::WindowStateType state_type, + chromeos::WindowStateType state_type, bool resizing, bool activated) { wl_array states; wl_array_init(&states); - if (state_type == ash::WindowStateType::kMaximized) + if (state_type == chromeos::WindowStateType::kMaximized) AddState(&states, ZXDG_TOPLEVEL_V6_STATE_MAXIMIZED); - if (state_type == ash::WindowStateType::kFullscreen) + if (state_type == chromeos::WindowStateType::kFullscreen) AddState(&states, ZXDG_TOPLEVEL_V6_STATE_FULLSCREEN); if (resizing) AddState(&states, ZXDG_TOPLEVEL_V6_STATE_RESIZING); @@ -467,7 +467,7 @@ } void OnConfigure(const gfx::Size& size, - ash::WindowStateType state_type, + chromeos::WindowStateType state_type, bool resizing, bool activated) { // Nothing to do here as popups don't have additional configure state.
diff --git a/components/feed/core/v2/enums.cc b/components/feed/core/v2/enums.cc index 283dad2..b502b1b1 100644 --- a/components/feed/core/v2/enums.cc +++ b/components/feed/core/v2/enums.cc
@@ -78,6 +78,8 @@ return out << "kFinishedWithoutUpdatingConsistencyToken"; case UploadActionsStatus::kAbortUploadForSignedOutUser: return out << "kAbortUploadForSignedOutUser"; + case UploadActionsStatus::kAbortUploadBecauseDisabled: + return out << "kAbortUploadBecauseDisabled"; } #else return out << (static_cast<int>(value));
diff --git a/components/feed/core/v2/enums.h b/components/feed/core/v2/enums.h index f9beb339..3a394525 100644 --- a/components/feed/core/v2/enums.h +++ b/components/feed/core/v2/enums.h
@@ -55,7 +55,8 @@ kUpdatedConsistencyToken = 4, kFinishedWithoutUpdatingConsistencyToken = 5, kAbortUploadForSignedOutUser = 6, - kMaxValue = kAbortUploadForSignedOutUser, + kAbortUploadBecauseDisabled = 7, + kMaxValue = kAbortUploadBecauseDisabled, }; // Keep this in sync with FeedUploadActionsBatchStatus in enums.xml.
diff --git a/components/feed/core/v2/feed_stream.cc b/components/feed/core/v2/feed_stream.cc index 08e1b7a5..cc3f575 100644 --- a/components/feed/core/v2/feed_stream.cc +++ b/components/feed/core/v2/feed_stream.cc
@@ -36,6 +36,7 @@ #include "components/feed/core/v2/tasks/load_stream_task.h" #include "components/feed/core/v2/tasks/upload_actions_task.h" #include "components/feed/core/v2/tasks/wait_for_store_initialize_task.h" +#include "components/feed/feed_feature_list.h" #include "components/offline_pages/core/prefetch/prefetch_service.h" #include "components/offline_pages/task/closure_task.h" #include "components/prefs/pref_service.h" @@ -174,6 +175,8 @@ // Inserting this task first ensures that |store_| is initialized before // it is used. task_queue_.AddTask(std::make_unique<WaitForStoreInitializeTask>(this)); + + UpdateCanUploadActionsWithNoticeCard(); } void FeedStream::InitializeScheduling() { @@ -220,6 +223,7 @@ } void FeedStream::OnEnterBackground() { + UpdateCanUploadActionsWithNoticeCard(); metrics_reporter_->OnEnterBackground(); if (GetFeedConfig().upload_actions_on_enter_background) { task_queue_.AddTask(std::make_unique<UploadActionsTask>( @@ -229,7 +233,7 @@ } bool FeedStream::IsActivityLoggingEnabled() const { - return is_activity_logging_enabled_; + return is_activity_logging_enabled_ && CanUploadActions(); } void FeedStream::UpdateIsActivityLoggingEnabled() { @@ -252,11 +256,13 @@ // Cancel any scheduled model unload task. ++unload_on_detach_sequence_number_; + UpdateCanUploadActionsWithNoticeCard(); } void FeedStream::DetachSurface(SurfaceInterface* surface) { metrics_reporter_->SurfaceClosed(surface->GetSurfaceId()); surface_updater_->SurfaceRemoved(surface); + UpdateCanUploadActionsWithNoticeCard(); ScheduleModelUnloadIfNoSurfacesAttached(); } @@ -397,6 +403,10 @@ } void FeedStream::ProcessViewAction(base::StringPiece data) { + if (!CanLogViews()) { + return; + } + feedwire::FeedAction msg; msg.ParseFromArray(data.data(), data.size()); UploadAction(std::move(msg), /*upload_now=*/false, @@ -592,6 +602,8 @@ // buffered events. is_activity_logging_enabled_ = false; + UpdateCanUploadActionsWithNoticeCard(); + ClearAll(); } @@ -601,6 +613,8 @@ // buffered events. is_activity_logging_enabled_ = false; + UpdateCanUploadActionsWithNoticeCard(); + ClearAll(); } @@ -713,8 +727,53 @@ void FeedStream::ReportSliceViewed(SurfaceId surface_id, const std::string& slice_id) { int index = surface_updater_->GetSliceIndexFromSliceId(slice_id); - if (index >= 0) + if (index >= 0) { + UpdateShownSlicesUploadCondition(index); metrics_reporter_->ContentSliceViewed(surface_id, index); + } +} +bool FeedStream::CanUploadActions() const { + return can_upload_actions_with_notice_card_ || + !prefs::GetLastFetchHadNoticeCard(*profile_prefs_); +} +void FeedStream::SetLastStreamLoadHadNoticeCard(bool value) { + prefs::SetLastFetchHadNoticeCard(*profile_prefs_, value); +} +bool FeedStream::HasReachedConditionsToUploadActionsWithNoticeCard() { + if (base::FeatureList::IsEnabled( + feed::kInterestFeedV2ClicksAndViewsConditionalUpload)) { + return prefs::GetHasReachedClickAndViewActionsUploadConditions( + *profile_prefs_); + } + // Consider the conditions as already reached to enable uploads when the + // feature is disabled. This will also have the effect of not updating the + // related pref. + return true; +} +void FeedStream::DeclareHasReachedConditionsToUploadActionsWithNoticeCard() { + if (base::FeatureList::IsEnabled( + feed::kInterestFeedV2ClicksAndViewsConditionalUpload)) { + prefs::SetHasReachedClickAndViewActionsUploadConditions(*profile_prefs_, + true); + } +} +void FeedStream::UpdateShownSlicesUploadCondition(int viewed_slice_index) { + constexpr int kShownSlicesThreshold = 2; + + // Don't take shown slices into consideration when the upload conditions has + // already been reached. + if (HasReachedConditionsToUploadActionsWithNoticeCard()) + return; + + if (viewed_slice_index + 1 >= kShownSlicesThreshold) + DeclareHasReachedConditionsToUploadActionsWithNoticeCard(); +} +bool FeedStream::CanLogViews() const { + return CanUploadActions(); +} +void FeedStream::UpdateCanUploadActionsWithNoticeCard() { + can_upload_actions_with_notice_card_ = + HasReachedConditionsToUploadActionsWithNoticeCard(); } void FeedStream::ReportFeedViewed(SurfaceId surface_id) { metrics_reporter_->FeedViewed(surface_id);
diff --git a/components/feed/core/v2/feed_stream.h b/components/feed/core/v2/feed_stream.h index 287d62f..27ba2b9 100644 --- a/components/feed/core/v2/feed_stream.h +++ b/components/feed/core/v2/feed_stream.h
@@ -272,6 +272,9 @@ } void SetIdleCallbackForTesting(base::RepeatingClosure idle_callback); + bool CanUploadActions() const; + void SetLastStreamLoadHadNoticeCard(bool value); + private: class OfflineSuggestionsProvider; @@ -303,6 +306,15 @@ bool IsFeedEnabledByEnterprisePolicy(); + bool HasReachedConditionsToUploadActionsWithNoticeCard(); + void DeclareHasReachedConditionsToUploadActionsWithNoticeCard(); + + void UpdateShownSlicesUploadCondition(int index); + + bool CanLogViews() const; + + void UpdateCanUploadActionsWithNoticeCard(); + // Unowned. offline_pages::PrefetchService* prefetch_service_; @@ -338,6 +350,9 @@ Metadata metadata_; int unload_on_detach_sequence_number_ = 0; bool is_activity_logging_enabled_ = false; + // Whether the feed stream can upload actions with the notice card in the + // feed. + bool can_upload_actions_with_notice_card_ = false; // To allow tests to wait on task queue idle. base::RepeatingClosure idle_callback_;
diff --git a/components/feed/core/v2/feed_stream_unittest.cc b/components/feed/core/v2/feed_stream_unittest.cc index 96fc8a13..89e006b8 100644 --- a/components/feed/core/v2/feed_stream_unittest.cc +++ b/components/feed/core/v2/feed_stream_unittest.cc
@@ -20,6 +20,7 @@ #include "base/strings/string_util.h" #include "base/test/bind_test_util.h" #include "base/test/metrics/histogram_tester.h" +#include "base/test/scoped_feature_list.h" #include "base/test/scoped_run_loop_timeout.h" #include "base/test/simple_test_clock.h" #include "base/test/simple_test_tick_clock.h" @@ -45,6 +46,7 @@ #include "components/feed/core/v2/test/callback_receiver.h" #include "components/feed/core/v2/test/proto_printer.h" #include "components/feed/core/v2/test/stream_builder.h" +#include "components/feed/feed_feature_list.h" #include "components/leveldb_proto/public/proto_database_provider.h" #include "components/offline_pages/core/client_namespace_constants.h" #include "components/offline_pages/core/page_criteria.h" @@ -132,6 +134,12 @@ return badge_serialized; } +feedwire::ThereAndBackAgainData MakeThereAndBackAgainData(int64_t id) { + feedwire::ThereAndBackAgainData msg; + *msg.mutable_action_payload() = MakeFeedAction(id).action_payload(); + return msg; +} + // This is EXPECT_EQ, but also dumps the string values for ease of reading. #define EXPECT_STRINGS_EQUAL(WANT, GOT) \ { \ @@ -545,6 +553,8 @@ class FeedStreamTest : public testing::Test, public FeedStream::Delegate { public: void SetUp() override { + SetupFeatures(); + // Reset to default config, since tests can change it. SetFeedConfigForTesting(Config()); @@ -563,6 +573,11 @@ CreateStream(); } + virtual void SetupFeatures() { + scoped_feature_list_.InitAndDisableFeature( + feed::kInterestFeedV2ClicksAndViewsConditionalUpload); + } + void TearDown() override { // Ensure the task queue can return to idle. Failure to do so may be due // to a stuck task that never called |TaskComplete()|. @@ -674,6 +689,14 @@ bool is_eula_accepted_ = true; bool is_offline_ = false; bool is_signed_in_ = true; + base::test::ScopedFeatureList scoped_feature_list_; +}; + +class FeedStreamConditionalActionsUploadTest : public FeedStreamTest { + void SetupFeatures() override { + scoped_feature_list_.InitAndEnableFeature( + feed::kInterestFeedV2ClicksAndViewsConditionalUpload); + } }; TEST_F(FeedStreamTest, IsArticlesListVisibleByDefault) { @@ -1571,6 +1594,191 @@ EXPECT_EQ(1, network_.action_request_call_count); } +TEST_F(FeedStreamTest, ActionsUploadWithoutConditionsWhenFeatureDisabled) { + response_translator_.InjectResponse(MakeTypicalInitialModelState()); + + TestSurface surface(stream_.get()); + WaitForIdleTaskQueue(); + stream_->ProcessViewAction( + feedwire::FeedAction::default_instance().SerializeAsString()); + WaitForIdleTaskQueue(); + stream_->ProcessThereAndBackAgain( + MakeThereAndBackAgainData(42ul).SerializeAsString()); + WaitForIdleTaskQueue(); + + // Verify the actions were uploaded. + ASSERT_EQ(1, network_.action_request_call_count); + EXPECT_EQ(2, network_.action_request_sent->feed_actions_size()); +} + +TEST_F(FeedStreamConditionalActionsUploadTest, + NoActionsUploadUntilReachedConditions) { + // Tests the flow where we: + // (1) Perform a ThereAndBackAgain action and a View action while upload + // isn't enabled => (2) Attempt an upload while the upload conditions aren't + // reached => (3) Reach upload conditions => (4) Perform another View action + // that should be dropped => (5) Simulate the backgrounding of the app to + // enable actions upload => (6) Trigger an upload which will upload the + // stored ThereAndBackAgain action. + response_translator_.InjectResponse(MakeTypicalInitialModelState()); + TestSurface surface(stream_.get()); + WaitForIdleTaskQueue(); + + // Process the view action and the ThereAndBackAgain action while the upload + // conditions aren't reached. + stream_->ProcessViewAction(MakeFeedAction(42ul).SerializeAsString()); + WaitForIdleTaskQueue(); + // Verify that the view action was dropped. + ASSERT_EQ(0ul, ReadStoredActions(stream_->GetStore()).size()); + + stream_->ProcessThereAndBackAgain( + MakeThereAndBackAgainData(42ul).SerializeAsString()); + WaitForIdleTaskQueue(); + // Verify that the ThereAndBackAgain action is in the action store. + ASSERT_EQ(1ul, ReadStoredActions(stream_->GetStore()).size()); + + // Attempt an upload. + stream_->OnEnterBackground(); + WaitForIdleTaskQueue(); + // Verify that no upload is done because the conditions aren't reached. + EXPECT_EQ(0, network_.action_request_call_count); + + // Reach conditions. + stream_->ReportSliceViewed( + surface.GetSurfaceId(), + surface.initial_state->updated_slices(1).slice().slice_id()); + + // Verify that the view action is still dropped because we haven't + // transitioned out of the current surface. + stream_->ProcessViewAction(MakeFeedAction(42ul).SerializeAsString()); + WaitForIdleTaskQueue(); + ASSERT_EQ(1ul, ReadStoredActions(stream_->GetStore()).size()); + + // Enable the upload bit and trigger the upload of actions. + stream_->OnEnterBackground(); + WaitForIdleTaskQueue(); + + // Verify that the ThereAndBackAgain action was uploaded but not the view + // action. + ASSERT_EQ(1, network_.action_request_call_count); + EXPECT_EQ(1, network_.action_request_sent->feed_actions_size()); +} + +TEST_F(FeedStreamConditionalActionsUploadTest, EnableUploadOnSurfaceAttached) { + response_translator_.InjectResponse(MakeTypicalInitialModelState()); + TestSurface surface(stream_.get()); + WaitForIdleTaskQueue(); + + // Perform a ThereAndBackAgain action. + stream_->ProcessThereAndBackAgain( + MakeThereAndBackAgainData(42ul).SerializeAsString()); + WaitForIdleTaskQueue(); + + // Reach conditions. + stream_->ReportSliceViewed( + surface.GetSurfaceId(), + surface.initial_state->updated_slices(1).slice().slice_id()); + + // Attach a new surface to update the bit to enable uploads. + TestSurface surface2(stream_.get()); + + // Trigger an upload through load more to isolate the effect of the on-attach + // event on enabling uploads. + response_translator_.InjectResponse(MakeTypicalNextPageState()); + stream_->LoadMore(surface.GetSurfaceId(), base::DoNothing()); + WaitForIdleTaskQueue(); + + // Verify that the ThereAndBackAgain action was uploaded. + ASSERT_EQ(1, network_.action_request_call_count); + EXPECT_EQ(1, network_.action_request_sent->feed_actions_size()); +} + +TEST_F(FeedStreamConditionalActionsUploadTest, EnableUploadOnEnterBackground) { + response_translator_.InjectResponse(MakeTypicalInitialModelState()); + TestSurface surface(stream_.get()); + WaitForIdleTaskQueue(); + + // Perform a ThereAndBackAgain action. + stream_->ProcessThereAndBackAgain( + MakeThereAndBackAgainData(42ul).SerializeAsString()); + WaitForIdleTaskQueue(); + + // Reach conditions. + stream_->ReportSliceViewed( + surface.GetSurfaceId(), + surface.initial_state->updated_slices(1).slice().slice_id()); + + stream_->OnEnterBackground(); + WaitForIdleTaskQueue(); + + // Verify that the ThereAndBackAgain action was uploaded. + ASSERT_EQ(1, network_.action_request_call_count); + EXPECT_EQ(1, network_.action_request_sent->feed_actions_size()); +} + +TEST_F(FeedStreamConditionalActionsUploadTest, + AllowActionsUploadWhenNoticeCardNotPresentRegardlessOfConditions) { + auto model_state = MakeTypicalInitialModelState(); + model_state->stream_data.set_privacy_notice_fulfilled(false); + response_translator_.InjectResponse(std::move(model_state)); + TestSurface surface(stream_.get()); + WaitForIdleTaskQueue(); + + // Process the view action and the ThereAndBackAgain action while the upload + // conditions aren't reached. + stream_->ProcessViewAction(MakeFeedAction(42ul).SerializeAsString()); + WaitForIdleTaskQueue(); + stream_->ProcessThereAndBackAgain( + MakeThereAndBackAgainData(42ul).SerializeAsString()); + WaitForIdleTaskQueue(); + + // Trigger an upload through a query. + stream_->OnEnterBackground(); + WaitForIdleTaskQueue(); + + // Verify the ThereAndBackAgain action and the view action were uploaded. + ASSERT_EQ(1, network_.action_request_call_count); + EXPECT_EQ(2, network_.action_request_sent->feed_actions_size()); +} + +TEST_F(FeedStreamConditionalActionsUploadTest, + ReupdateUploadEnableBitsOnSignIn) { + response_translator_.InjectResponse(MakeTypicalInitialModelState()); + TestSurface surface(stream_.get()); + WaitForIdleTaskQueue(); + + // Reach conditions. + stream_->ReportSliceViewed( + surface.GetSurfaceId(), + surface.initial_state->updated_slices(1).slice().slice_id()); + + // Assert that uploads are not yet enabled. + ASSERT_FALSE(stream_->CanUploadActions()); + + // Update the upload enable bits which will enable upload because the related + // pref is true. + stream_->OnSignedIn(); + + EXPECT_TRUE(stream_->CanUploadActions()); +} + +TEST_F(FeedStreamConditionalActionsUploadTest, + ResetTheUploadEnableBitsOnSignOut) { + response_translator_.InjectResponse(MakeTypicalInitialModelState()); + TestSurface surface(stream_.get()); + WaitForIdleTaskQueue(); + + // Reach conditions. + stream_->ReportSliceViewed( + surface.GetSurfaceId(), + surface.initial_state->updated_slices(1).slice().slice_id()); + + // Update the upload enable bits which will enable upload. + stream_->OnSignedOut(); + + ASSERT_TRUE(stream_->CanUploadActions()); +} + TEST_F(FeedStreamTest, LoadStreamFromNetworkUploadsActions) { stream_->UploadAction(MakeFeedAction(99ul), false, base::DoNothing()); WaitForIdleTaskQueue(); @@ -1661,6 +1869,37 @@ } } +TEST_F(FeedStreamConditionalActionsUploadTest, + LoadMoreDoesntUpdateNoticeCardPref) { + // The initial stream load has the notice card. + response_translator_.InjectResponse(MakeTypicalInitialModelState()); + TestSurface surface(stream_.get()); + WaitForIdleTaskQueue(); + + // Inject a response for the LoadMore fetch that doesn't have the notice card. + // It shouldn't overwrite the notice card pref. + response_translator_.InjectResponse(MakeTypicalNextPageState( + /* first_cluster_id= */ 0, + /* last_added_time= */ kTestTimeEpoch, + /* signed_in= */ true, + /* logging_enabled= */ true, + /* privacy_notice_fulfilled= */ false)); + stream_->LoadMore(surface.GetSurfaceId(), base::DoNothing()); + WaitForIdleTaskQueue(); + + // Process a view action that should be dropped because the upload of actions + // is still disabled because there is still a notice card. + stream_->ProcessViewAction(MakeFeedAction(42ul).SerializeAsString()); + WaitForIdleTaskQueue(); + + // Trigger an upload. + stream_->OnEnterBackground(); + WaitForIdleTaskQueue(); + + // Verify that there were no uploads. + EXPECT_EQ(0, network_.action_request_call_count); +} + TEST_F(FeedStreamTest, BackgroundingAppUploadsActions) { stream_->UploadAction(MakeFeedAction(1ul), false, base::DoNothing()); stream_->OnEnterBackground();
diff --git a/components/feed/core/v2/prefs.cc b/components/feed/core/v2/prefs.cc index 84ee668..562ff7d 100644 --- a/components/feed/core/v2/prefs.cc +++ b/components/feed/core/v2/prefs.cc
@@ -86,6 +86,26 @@ pref_service.ClearPref(feed::prefs::kClientInstanceId); } +void SetLastFetchHadNoticeCard(PrefService& pref_service, bool value) { + pref_service.SetBoolean(feed::prefs::kLastFetchHadNoticeCard, value); +} + +bool GetLastFetchHadNoticeCard(const PrefService& pref_service) { + return pref_service.GetBoolean(feed::prefs::kLastFetchHadNoticeCard); +} + +void SetHasReachedClickAndViewActionsUploadConditions(PrefService& pref_service, + bool value) { + pref_service.SetBoolean( + feed::prefs::kHasReachedClickAndViewActionsUploadConditions, value); +} + +bool GetHasReachedClickAndViewActionsUploadConditions( + const PrefService& pref_service) { + return pref_service.GetBoolean( + feed::prefs::kHasReachedClickAndViewActionsUploadConditions); +} + } // namespace prefs } // namespace feed
diff --git a/components/feed/core/v2/prefs.h b/components/feed/core/v2/prefs.h index 4b11847..634bddb1 100644 --- a/components/feed/core/v2/prefs.h +++ b/components/feed/core/v2/prefs.h
@@ -44,6 +44,14 @@ std::string GetClientInstanceId(PrefService& pref_service); void ClearClientInstanceId(PrefService& pref_service); +void SetLastFetchHadNoticeCard(PrefService& pref_service, bool value); +bool GetLastFetchHadNoticeCard(const PrefService& pref_service); + +void SetHasReachedClickAndViewActionsUploadConditions(PrefService& pref_service, + bool value); +bool GetHasReachedClickAndViewActionsUploadConditions( + const PrefService& pref_service); + } // namespace prefs } // namespace feed
diff --git a/components/feed/core/v2/tasks/load_stream_task.cc b/components/feed/core/v2/tasks/load_stream_task.cc index a9da4fc..14d75666 100644 --- a/components/feed/core/v2/tasks/load_stream_task.cc +++ b/components/feed/core/v2/tasks/load_stream_task.cc
@@ -167,6 +167,10 @@ *response_data.model_update_request), base::DoNothing()); + stream_->SetLastStreamLoadHadNoticeCard( + response_data.model_update_request->stream_data + .privacy_notice_fulfilled()); + if (load_type_ != LoadType::kBackgroundRefresh) { auto model = std::make_unique<StreamModel>(); model->Update(std::move(response_data.model_update_request));
diff --git a/components/feed/core/v2/tasks/upload_actions_task.cc b/components/feed/core/v2/tasks/upload_actions_task.cc index 0532c83d..4b51bdb 100644 --- a/components/feed/core/v2/tasks/upload_actions_task.cc +++ b/components/feed/core/v2/tasks/upload_actions_task.cc
@@ -177,6 +177,11 @@ return; } + if (!stream_->CanUploadActions()) { + Done(UploadActionsStatus::kAbortUploadBecauseDisabled); + return; + } + // If the new action was stored and upload_now was set, load all pending // actions and try to upload. ReadActions(); @@ -204,6 +209,10 @@ Done(UploadActionsStatus::kAbortUploadForSignedOutUser); return; } + if (!stream_->CanUploadActions()) { + Done(UploadActionsStatus::kAbortUploadBecauseDisabled); + return; + } UpdateAndUploadNextBatch(); }
diff --git a/components/feed/feed_feature_list.cc b/components/feed/feed_feature_list.cc index cab56346..8065e08 100644 --- a/components/feed/feed_feature_list.cc +++ b/components/feed/feed_feature_list.cc
@@ -43,6 +43,9 @@ const base::Feature kInterestFeedV1ClicksAndViewsConditionalUpload{ "InterestFeedV1ClickAndViewActionsConditionalUpload", base::FEATURE_DISABLED_BY_DEFAULT}; +const base::Feature kInterestFeedV2ClicksAndViewsConditionalUpload{ + "InterestFeedV2ClickAndViewActionsConditionalUpload", + base::FEATURE_DISABLED_BY_DEFAULT}; const char kDefaultReferrerUrl[] = "https://www.googleapis.com/auth/chrome-content-suggestions";
diff --git a/components/feed/feed_feature_list.h b/components/feed/feed_feature_list.h index 1b393c54..3fd0e3cb 100644 --- a/components/feed/feed_feature_list.h +++ b/components/feed/feed_feature_list.h
@@ -31,6 +31,7 @@ extern const base::Feature kReportFeedUserActions; extern const base::Feature kInterestFeedV1ClicksAndViewsConditionalUpload; +extern const base::Feature kInterestFeedV2ClicksAndViewsConditionalUpload; std::string GetFeedReferrerUrl();
diff --git a/components/omnibox/browser/search_provider.cc b/components/omnibox/browser/search_provider.cc index bd5cdb8..e1a27391 100644 --- a/components/omnibox/browser/search_provider.cc +++ b/components/omnibox/browser/search_provider.cc
@@ -1089,11 +1089,11 @@ // Now add the most relevant matches to |matches_|. We take up to // provider_max_matches_ suggest/navsuggest matches, regardless of origin. We - // always include in that set a legal default match if possible. If Instant - // Extended is enabled and we have server-provided (and thus hopefully more - // accurate) scores for some suggestions, we allow more of those, until we - // reach AutocompleteResult::GetDynamicMaxMatches() total matches (that is, - // enough to fill the whole popup). + // always include in that set a legal default match if possible. If we have + // server-provided (and thus hopefully more accurate) scores for some + // suggestions, we allow more of those, until we reach + // AutocompleteResult::GetDynamicMaxMatches() total matches (that is, enough + // to fill the whole popup). // // We will always return any verbatim matches, no matter how we obtained their // scores, unless we have already accepted @@ -1127,19 +1127,10 @@ // suggestion of some sort". if ((i->type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED) && (i->type != AutocompleteMatchType::SEARCH_OTHER_ENGINE)) { - // IsInstantExtendedAPIEnabled is a legacy function that we no longer want - // to affect the number of search suggestions we provide, but we want to - // understand the effect of removing this check, so its impotence is - // controlled experimentally. - bool instant_check_disabled = base::FeatureList::IsEnabled( - omnibox::kOmniboxDisableInstantExtendedLimit); - bool skip_suggestion_for_instant_disabled = - !(instant_check_disabled || search::IsInstantExtendedAPIEnabled()); // If we've already hit the limit on non-server-scored suggestions, and // this isn't a server-scored suggestion we can add, skip it. if ((num_suggestions >= provider_max_matches_) && - (skip_suggestion_for_instant_disabled || - (i->GetAdditionalInfo(kRelevanceFromServerKey) != kTrue))) { + (i->GetAdditionalInfo(kRelevanceFromServerKey) != kTrue)) { continue; }
diff --git a/components/omnibox/browser/search_provider.h b/components/omnibox/browser/search_provider.h index 2bacb18..884adf1 100644 --- a/components/omnibox/browser/search_provider.h +++ b/components/omnibox/browser/search_provider.h
@@ -110,8 +110,6 @@ DontTrimHttpsSchemeIfInputHasScheme); FRIEND_TEST_ALL_PREFIXES(SearchProviderTest, DoTrimHttpsScheme); FRIEND_TEST_ALL_PREFIXES(SearchProviderWarmUpTest, SendsWarmUpRequestOnFocus); - FRIEND_TEST_ALL_PREFIXES(InstantExtendedPrefetchTest, ClearPrefetchedResults); - FRIEND_TEST_ALL_PREFIXES(InstantExtendedPrefetchTest, SetPrefetchQuery); // Manages the providers (TemplateURLs) used by SearchProvider. Two providers // may be used:
diff --git a/components/omnibox/common/omnibox_features.cc b/components/omnibox/common/omnibox_features.cc index 8f66cb42..ecbb75c0 100644 --- a/components/omnibox/common/omnibox_features.cc +++ b/components/omnibox/common/omnibox_features.cc
@@ -116,11 +116,6 @@ const base::Feature kDocumentProvider{"OmniboxDocumentProvider", base::FEATURE_DISABLED_BY_DEFAULT}; -// Returns whether IsInstantExtendedAPIEnabled should be ignored when deciding -// the number of Google-provided search suggestions. -const base::Feature kOmniboxDisableInstantExtendedLimit{ - "OmniboxDisableInstantExtendedLimit", enabled_by_default_android_ios}; - // Show the search engine logo in the omnibox on Android (desktop already does // this). const base::Feature kOmniboxSearchEngineLogo{"OmniboxSearchEngineLogo", @@ -339,7 +334,7 @@ "OmniboxSuggestionsWrapAround", base::FEATURE_DISABLED_BY_DEFAULT}; // If enabled, uses WebUI to render the omnibox suggestions popup, similar to -// how the NTP "fakebox" is implemented. +// how the NTP "realbox" is implemented. const base::Feature kWebUIOmniboxPopup{"WebUIOmniboxPopup", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/components/omnibox/common/omnibox_features.h b/components/omnibox/common/omnibox_features.h index 844e757d..79e3d4a 100644 --- a/components/omnibox/common/omnibox_features.h +++ b/components/omnibox/common/omnibox_features.h
@@ -23,7 +23,6 @@ extern const base::Feature kUIExperimentSwapTitleAndUrl; extern const base::Feature kSpeculativeServiceWorkerStartOnQueryInput; extern const base::Feature kDocumentProvider; -extern const base::Feature kOmniboxDisableInstantExtendedLimit; extern const base::Feature kOmniboxSearchEngineLogo; extern const base::Feature kOmniboxRemoveSuggestionsFromClipboard; extern const base::Feature kDebounceDocumentProvider;
diff --git a/components/policy/proto/device_management_backend.proto b/components/policy/proto/device_management_backend.proto index 236f99f..c6d2eb57 100644 --- a/components/policy/proto/device_management_backend.proto +++ b/components/policy/proto/device_management_backend.proto
@@ -3043,6 +3043,25 @@ SEEN_BY_EXTERNAL_PROVIDER = 7; } + // Status of cache when an attempt is made to fetch the extension from it + // during the downloading process. See + // ExtensionDownloaderDelegate::CacheStatus for more details. + // ExtensionDownloaderDelegate::CacheStatus is the main enum and this is a + // copy used for reporting purposes. + enum DownloadCacheStatus { + CACHE_UNKNOWN = 0; + + CACHE_DISABLED = 1; + + CACHE_MISS = 2; + + CACHE_OUTDATED = 3; + + CACHE_HIT = 4; + + CACHE_HIT_ON_MANIFEST_FETCH_FAILURE = 5; + } + // Timestamp, in microseconds since epoch. Set for all log // events. optional int64 timestamp = 1; @@ -3087,6 +3106,9 @@ // Stage of install creation process. optional InstallCreationStage install_creation_stage = 14; + + // Status of cache during downloading process. + optional DownloadCacheStatus download_cache_status = 15; } // A single entry in the push-install log for an app.
diff --git a/components/policy/resources/policy_templates.json b/components/policy/resources/policy_templates.json index 89b7a61..1be8dbe 100644 --- a/components/policy/resources/policy_templates.json +++ b/components/policy/resources/policy_templates.json
@@ -1552,7 +1552,7 @@ }, { 'name': 'DNSInterceptionChecksEnabled', - 'owners': ['krb', 'jdonnelly'], + 'owners': ['krb@chromium.org', 'jdonnelly@chromium.org'], 'type': 'main', 'schema': { 'type': 'boolean' }, 'supported_on': ['chrome.*:80-', 'chrome_os:80-'], @@ -1571,6 +1571,52 @@ When this policy is not set, or is enabled, the DNS interception checks are performed. When explicitly disabled, they're not.''' }, { + 'name': 'IntranetRedirectBehavior', + 'owners': ['jdonnelly@chromium.org', 'tommycli@chromium.org'], + 'type': 'int-enum', + 'schema': { + 'type': 'integer', + 'enum': [ 0, 1, 2, 3 ], + }, + 'items': [ + { + 'name': 'Default', + 'value': 0, + 'caption': '''Use default browser behavior.''', + }, + { + 'name': 'DisableInterceptionChecksDisableInfobar', + 'value': 1, + 'caption': '''Disable DNS interception checks and did-you-mean "http://intranetsite/" infobars.''', + }, + { + 'name': 'DisableInterceptionChecksEnableInfobar', + 'value': 2, + 'caption': '''Disable DNS interception checks; allow did-you-mean "http://intranetsite/" infobars.''', + }, + { + 'name': 'EnableInterceptionChecksEnableInfobar', + 'value': 3, + 'caption': '''Allow DNS interception checks and did-you-mean "http://intranetsite/" infobars.''', + } + ], + 'future_on': ['chrome.*', 'chrome_os'], + 'features': { + 'dynamic_refresh': True, + 'per_profile': False, + }, + 'example_value': 1, + 'id': 792, + 'caption': '''Intranet Redirection Behavior''', + 'tags': [], + 'desc': '''This policy configures behavior for intranet redirection via DNS interception checks. The checks attempt to discover whether the browser is behind a proxy that redirects unknown host names. + + If this policy is not set, the browser will use the default behavior of DNS interception checks and intranet redirect suggestions. In M88, they are enabled by default but will be disabled by default in the future release. + + <ph name="DNS_INTERCEPTION_CHECKS_ENABLED_POLICY_NAME">DNSInterceptionChecksEnabled</ph> is a related policy that may also disable DNS interception checks; this policy is a more flexible version which may separately control intranet redirection infobars and may be expanded in the future. + If either <ph name="DNS_INTERCEPTION_CHECKS_ENABLED_POLICY_NAME">DNSInterceptionChecksEnabled</ph> or this policy requests to disable interception checks, the checks will be disabled.''' + }, + { 'name': 'Http09OnNonDefaultPortsEnabled', 'owners': ['file://components/policy/resources/OWNERS'], 'type': 'main', @@ -24462,6 +24508,6 @@ 'placeholders': [], 'deleted_policy_ids': [114, 115, 412, 476, 544, 546, 562, 569, 578], 'deleted_atomic_policy_group_ids': [], - 'highest_id_currently_used': 791, + 'highest_id_currently_used': 792, 'highest_atomic_group_id_currently_used': 40 }
diff --git a/components/policy/resources/policy_templates_es-419.xtb b/components/policy/resources/policy_templates_es-419.xtb index e3a449e..e8b53457 100644 --- a/components/policy/resources/policy_templates_es-419.xtb +++ b/components/policy/resources/policy_templates_es-419.xtb
@@ -294,7 +294,7 @@ Si la estableces, los usuarios no podrán cambiarla ni anularla.</translation> <translation id="1502843533062797703">Habilitar el bloqueo de inserción de software de terceros</translation> -<translation id="1503863096120373385">Establece la configuración histórica de los datos de navegación para <ph name="PRODUCT_NAME" />. +<translation id="1503863096120373385">Establece la configuración de la duración de los datos de navegación para <ph name="PRODUCT_NAME" />. Esta política controla la cantidad de tiempo que se almacenarán los datos de navegación seleccionados. Esta política no tendrá efecto si se habilita la sincronización. Los tipos de datos disponibles son <ph name="DATA_TYPE_BROWSING_HISTORY" />, <ph name="DATA_TYPE_DOWNLOAD_HISTORY" />, <ph name="DATA_TYPE_COOKIES_AND_OTHER_SITE_DATA" />, <ph name="DATA_TYPE_CACHED_IMAGES_AND_FILES" />, <ph name="DATA_TYPE_PASSWORD" />, <ph name="DATA_TYPE_AUTOFILL" />, <ph name="DATA_TYPE_SITE_SETTINGS" /> y <ph name="DATA_TYPE_HOSTED_APP_DATA" />. Periódicamente, Chrome quitará datos con una antigüedad mayor a <ph name="TIME_TO_LIVE_IN_HOURS" /> de los tipos seleccionados. Como esta acción se realiza a intervalos determinados, es posible que algunos datos se conserven un poco más de tiempo, pero nunca más del doble que el período de <ph name="TIME_TO_LIVE_IN_HOURS" /> esperado. @@ -2651,11 +2651,11 @@ Si no estableces la política, no se agregarán sitios web a la lista. Nota: También se pueden agregar elementos a esta lista a través de la política <ph name="EXTERNAL_SITELIST_URL_POLICY_NAME" />.</translation> -<translation id="5065753964276395784">Esta política dejó de estar disponible; usa la política <ph name="PROXY_SETTINGS_POLICY_NAME" /> en su lugar. +<translation id="5065753964276395784">Esta política no está disponible; usa <ph name="PROXY_SETTINGS_POLICY_NAME" /> en su lugar. Si estableces la política, <ph name="PRODUCT_NAME" /> omitirá cualquier proxy de la lista de hosts que se proporciona aquí. Esta política solo tendrá efecto si no se especifica la política <ph name="PROXY_SETTINGS_POLICY_NAME" /> y seleccionaste <ph name="PROXY_MODE_ENUM_FIXED_SERVERS" /> con <ph name="PROXY_MODE_POLICY_NAME" />. - No se debe establecer esta política si se seleccionó otro modo para configurar políticas de proxy. + No debes configurar esta política si seleccionaste otro modo para configurar políticas de proxy. Nota: Para obtener más ejemplos detallados, visita The Chromium Projects ( https://www.chromium.org/developers/design-documents/network-settings#TOC-Command-line-options-for-proxy-sett ).</translation> <translation id="5067143124345820993">Lista de usuarios con permiso para iniciar sesión</translation> @@ -3144,7 +3144,7 @@ <translation id="5645779841392247734">Permitir cookies en estos sitios</translation> <translation id="5646234199535103501">Política de configuración para Chrome Enterprise Connector OnBulkDataEntry</translation> <translation id="5652250453612826983">Controla las políticas de supervisión parental, que se aplican solo a las cuentas de menores de edad. - Estas políticas no se establecen en la consola del administrador; se configuran directamente en el servidor de la API de Kids.</translation> + Estas políticas no se establecen en la Consola del administrador; se configuran directamente en el servidor de la API de Kids.</translation> <translation id="5656177735561364047">Habilita la función de portapapeles compartido</translation> <translation id="5657576769650058122">Si habilitas la política, se mantendrá activado el teclado virtual en pantalla (un dispositivo de entrada del Sistema operativo Chrome). Si inhabilitas la política, se mantendrá desactivado el teclado. @@ -4066,7 +4066,7 @@ Si la estableces como <ph name="BR_UNDER_USER_CONTROL" />, los usuarios recibirán mensajes para usar la Copia de seguridad y restablecimiento. Si activan este servicio, se subirán los datos de las apps para Android a los servidores de copia de seguridad de Android. Estos datos se restablecerán cuando se reinstalen apps compatibles. Después de la configuración inicial, los usuarios podrán activar o desactivar la Copia de seguridad y restablecimiento.</translation> -<translation id="6986172482189158664">Configuración histórica de los datos de navegación</translation> +<translation id="6986172482189158664">Configuración de la duración de los datos de navegación</translation> <translation id="6994082778848658360">Especifica la forma en que los elementos de hardware de seguridad integrados se usan para la autenticación de dos factores, si son compatibles con esta función. El botón de encendido de la máquina se usa para detectar la presencia física del usuario. Si se selecciona "Inhabilitada", no se proporciona un segundo factor. @@ -4074,11 +4074,11 @@ Si se selecciona "U2F", el segundo factor integrado se comportará de acuerdo con la especificación de FIDO U2F. Si se selecciona "U2F_EXTENDED", el segundo factor integrado proporcionará funciones de U2F además de algunas extensiones para la atestación individual.</translation> -<translation id="6999948519306285655">Esta política dejó de estar disponible; usa la política <ph name="PROXY_SETTINGS_POLICY_NAME" /> en su lugar. +<translation id="6999948519306285655">Esta política no está disponible; usa <ph name="PROXY_SETTINGS_POLICY_NAME" /> en su lugar. - Si estableces la política, podrás especificar una dirección URL para el archivo de proxy en formato .pac. Esta política solo tendrá efecto si no se especifica la política <ph name="PROXY_SETTINGS_POLICY_NAME" /> y seleccionaste <ph name="PROXY_MODE_ENUM_PAC_SCRIPT" /> con <ph name="PROXY_MODE_POLICY_NAME" />. + Si configuras la política, podrás especificar una dirección URL para el archivo de proxy en formato .pac. Esta política solo tendrá efecto si no se especifica la política <ph name="PROXY_SETTINGS_POLICY_NAME" /> y si seleccionas <ph name="PROXY_MODE_ENUM_PAC_SCRIPT" /> con <ph name="PROXY_MODE_POLICY_NAME" />. - No se debe establecer esta política si se seleccionó otro modo para configurar políticas de proxy. + No debes configurar esta política si seleccionaste otro modo para configurar políticas de proxy. Nota: Para obtener ejemplos detallados, visita The Chromium Projects ( https://www.chromium.org/developers/design-documents/network-settings#TOC-Command-line-options-for-proxy-sett ).</translation> <translation id="7002040773317582266">Habilita la verificación en tiempo real de las URL del marco principal</translation> @@ -4664,11 +4664,11 @@ <translation id="7712109699186360774">Preguntar siempre que un sitio quiera acceder a la cámara o al micrófono</translation> <translation id="7713608076604149344">Restricciones de descarga</translation> <translation id="7715711044277116530">Indica el porcentaje en el que debe ajustarse la demora de inactividad de la pantalla en el modo de presentación.</translation> -<translation id="7716020145539921591">Esta política dejó de estar disponible; usa la política <ph name="PROXY_SETTINGS_POLICY_NAME" /> en su lugar. +<translation id="7716020145539921591">Esta política no está disponible; usa <ph name="PROXY_SETTINGS_POLICY_NAME" /> en su lugar. - Si estableces esta política, podrás especificar la dirección URL del servidor proxy. Esta política solo tendrá efecto si no se especifica la política <ph name="PROXY_SETTINGS_POLICY_NAME" /> y seleccionaste <ph name="PROXY_MODE_ENUM_FIXED_SERVERS" /> con <ph name="PROXY_MODE_POLICY_NAME" />. + Si configuras esta política, podrás especificar la dirección URL del servidor proxy. Esta política solo tendrá efecto si no se especifica la política <ph name="PROXY_SETTINGS_POLICY_NAME" /> y si seleccionas <ph name="PROXY_MODE_ENUM_FIXED_SERVERS" /> con <ph name="PROXY_MODE_POLICY_NAME" />. - No se debe establecer esta política si se seleccionó otro modo para configurar políticas de proxy. + No debes configurar esta política si seleccionaste otro modo para configurar políticas de proxy. Nota: Para obtener ejemplos detallados, visita The Chromium Projects ( https://www.chromium.org/developers/design-documents/network-settings#TOC-Command-line-options-for-proxy-sett ).</translation> <translation id="7717938661004793600">Permite configurar las funciones de accesibilidad de <ph name="PRODUCT_OS_NAME" />.</translation>
diff --git a/components/policy/resources/policy_templates_it.xtb b/components/policy/resources/policy_templates_it.xtb index 0b20e65..e3accf51 100644 --- a/components/policy/resources/policy_templates_it.xtb +++ b/components/policy/resources/policy_templates_it.xtb
@@ -4696,7 +4696,7 @@ <translation id="7750991880413385988">Apri pagina Nuova scheda</translation> <translation id="7754704193130578113">Chiedi dove salvare il file prima di scaricarlo</translation> <translation id="7758378441185523981">Attiva l'autenticazione ambientale in base ai tipi di profilo.</translation> -<translation id="776110834126722255">Deprecato</translation> +<translation id="776110834126722255">Deprecata</translation> <translation id="7763614521440615342">Mostra suggerimenti di contenuti nella pagina Nuova scheda</translation> <translation id="7765753178910647492">Consente di configurare un elenco di funzionalità di <ph name="PRODUCT_OS_NAME" /> da disattivare.
diff --git a/components/policy/resources/policy_templates_ja.xtb b/components/policy/resources/policy_templates_ja.xtb index b1f3d30..c584e0de 100644 --- a/components/policy/resources/policy_templates_ja.xtb +++ b/components/policy/resources/policy_templates_ja.xtb
@@ -634,7 +634,7 @@ </translation> <translation id="2030905906517501646">デフォルトの検索プロバイダのキーワード</translation> <translation id="203096360153626918">このポリシーは Android アプリには適用されません。このポリシーを <ph name="FALSE" /> に設定した場合でも、Android アプリの全画面表示は可能です。</translation> -<translation id="2037214548071298156">このポリシーを有効に設定するか未設定のままにすると、登録済みのデバイスは CPU/RAM 使用量などに関するハードウェアの統計情報を報告します。 +<translation id="2037214548071298156">このポリシーを有効にするか、未設定のままにすると、登録済みのデバイスは CPU/RAM 使用量などに関するハードウェアの統計情報を報告します。 このポリシーを無効に設定すると、登録済みのデバイスはハードウェアの統計情報を報告しません。</translation> <translation id="2040479044912658454">印刷のラスターモード</translation> @@ -1130,8 +1130,8 @@ <translation id="2710534340210290498">このポリシーが false の場合、ユーザーは画面をロックできません(ユーザー セッションからのログアウトのみ可能です)。このポリシーが true または未設定の場合、パスワードで認証されたユーザーは画面をロックできます。</translation> <translation id="2716623398185506073">このポリシーを有効に設定すると、登録済みのデバイスは電源に関連するハードウェアの統計情報と識別子を報告します。 - このポリシーを無効に設定するか未設定のままにすると、登録済みのデバイスは電源に関連する統計情報を報告しません。</translation> -<translation id="2725855586003209701">このポリシーを有効に設定するか未設定のままにすると、登録済みのデバイスは最近ログインしたデバイス ユーザーのリストを報告します。 + このポリシーを無効にするか、未設定のままにすると、登録済みのデバイスは電源に関連する統計情報を報告しません。</translation> +<translation id="2725855586003209701">このポリシーを有効にするか、未設定のままにすると、登録済みのデバイスは最近ログインしたデバイス ユーザーのリストを報告します。 このポリシーを無効に設定すると、登録済みのデバイスはユーザーのリストを報告しません。</translation> <translation id="2731627323327011390">ARC アプリで <ph name="PRODUCT_OS_NAME" /> の証明書を使用できないようにする</translation> @@ -1263,7 +1263,7 @@ このポリシーを true に設定すると、<ph name="DEVICE_USER_ALLOWLIST_POLICY_NAME" /> で定義されたアカウントに加えて、ファミリー リンクの新しいユーザー アカウントが許可されます。</translation> <translation id="2886969306951284125">Android アプリがオンになっている状態でこのポリシーを True に設定すると、登録済みのデバイスは Android ステータス情報を報告します。 - このポリシーを無効に設定するか未設定のままにすると、登録済みのデバイスは Android ステータス情報を報告しません。</translation> + このポリシーを無効するか、未設定のままにすると、登録済みのデバイスは Android ステータス情報を報告しません。</translation> <translation id="2890645751406497668">特定のベンダー ID と製品 ID を持つ USB デバイスへの接続を自動的にこれらのサイトに許可する。</translation> <translation id="2892414556511568464">両面印刷モードを制限します。ポリシーが未設定または空白に設定されている場合は、制限なしとして扱われます。</translation> <translation id="2893546967669465276">管理サーバーにシステムログを送信する</translation> @@ -1494,7 +1494,7 @@ このポリシーを設定しない場合、デフォルト値として 0 度が使用され、ユーザーはこの値を自由に変更できます。この場合、再起動時にデフォルト値が再適用されることはありません。</translation> <translation id="3264793472749429012">デフォルトの検索プロバイダのエンコード</translation> <translation id="3273221114520206906">デフォルトのJavaScript 設定</translation> -<translation id="328347261792478720">デフォルトでは、ブラウザはユーザーに合わせてパーソナライズされたおすすめメディアを表示します。このポリシーを無効に設定すると、ユーザーに対するおすすめは表示されません。このポリシーを有効に設定するか未設定のままにすると、おすすめメディアがユーザーに表示されます。</translation> +<translation id="328347261792478720">デフォルトでは、ブラウザはユーザーに合わせてパーソナライズされたおすすめメディアを表示します。このポリシーを無効に設定すると、ユーザーに対するおすすめは表示されません。このポリシーを有効にするか、未設定のままにすると、おすすめメディアがユーザーに表示されます。</translation> <translation id="3284094172359247914">WebUSB API の使用を管理する</translation> <translation id="3288595667065905535">リリース チャンネル</translation> <translation id="3292147213643666827"><ph name="CLOUD_PRINT_NAME" /> と、パソコンに接続している従来のプリンタとの間で、<ph name="PRODUCT_NAME" /> がプロキシとして動作できるようにします。 @@ -1511,7 +1511,7 @@ このポリシーは Chrome 88 で削除されます。 詳しくは、https://www.chromestatus.com/feature/4664843055398912 をご覧ください。</translation> -<translation id="3302829897293005699">このポリシーを有効に設定するか未設定のままにすると、登録済みのデバイスはアプリの ID やバージョンなどのアクティブなキオスク セッション情報を報告します。 +<translation id="3302829897293005699">このポリシーを有効にするか、未設定のままにすると、登録済みのデバイスはアプリの ID やバージョンなどのアクティブなキオスク セッション情報を報告します。 このポリシーを無効に設定すると、登録済みのデバイスはキオスク セッション情報を報告しません。</translation> <translation id="3303911765031636277">OnFileAttached Chrome Enterprise コネクタの設定ポリシー</translation> @@ -1549,7 +1549,7 @@ このポリシーを未設定のままにした場合、古いプラグインの実行の許可を確認するメッセージがユーザーに表示されます。</translation> <translation id="3348799281602260763">有効にすると、WebRTC ピア接続が TLS/DTLS プロトコルのサポートが終了したバージョン(DTLS 1.0、TLS 1.0、TLS 1.1)にダウングレードされる可能性があります。 - このポリシーを無効に設定するか未設定のままにすると、これらの TLS/DTLS バージョンは無効になります。 + このポリシーを無効にするか、未設定のままにすると、これらの TLS/DTLS バージョンは無効になります。 このポリシーは一時的なものであり、<ph name="PRODUCT_NAME" /> の将来のバージョンで削除される予定です。</translation> <translation id="3356657927302977341">Linux で <ph name="PRODUCT_NAME" /> がネイティブ通知を使用するかどうかを設定します。 @@ -1824,7 +1824,7 @@ <translation id="3715569262675717862">クライアント証明書に基づく認証</translation> <translation id="3727675072430693164">このポリシーを有効に設定すると、登録済みのデバイスは SoC コンポーネントに関するハードウェアの統計情報を報告します。 - このポリシーを無効に設定するか未設定のままにすると、登録済みのデバイスは統計情報を報告しません。</translation> + このポリシーを無効にするか、未設定のままにすると、登録済みのデバイスは統計情報を報告しません。</translation> <translation id="3736879847913515635">ユーザー管理画面でのユーザー追加を許可する</translation> <translation id="3737890474637805114">大きなファイルのダウンロードをブロックする</translation> <translation id="3748900290998155147">起動ロックを許可するかどうかを指定します。起動ロックは拡張機能から Power Management Extension API を使って、または ARC アプリからリクエストされます。 @@ -2836,7 +2836,7 @@ ポリシーが未設定の場合、<ph name="PRODUCT_NAME" /> M76 まではデフォルトの設定によりログの収集とアップロードは行えません。<ph name="PRODUCT_NAME" /> M77 以降では、クラウドベースのユーザーレベル エンタープライズ ポリシーの対象となるほとんどのプロファイルから、ログの収集とアップロードをデフォルトで行うことができます。<ph name="PRODUCT_NAME" /> M77 から M80 までは、<ph name="PRODUCT_NAME" /> オンプレミス管理の対象となるプロファイルからも、ログの収集とアップロードをデフォルトで行うことができます。</translation> <translation id="5331746669335642668"><ph name="PRODUCT_NAME" /> のクラウド ポリシーはプラットフォーム ポリシーに優先します。</translation> -<translation id="5340105431123046323">このポリシーを有効に設定するか未設定のままにすると、登録済みのデバイスはネットワーク インターフェースのリスト(タイプとハードウェア アドレスを含む)を報告します。 +<translation id="5340105431123046323">このポリシーを有効にするか、未設定のままにすると、登録済みのデバイスはネットワーク インターフェースのリスト(タイプとハードウェア アドレスを含む)を報告します。 このポリシーを無効に設定すると、登録済みのデバイスはネットワーク インターフェースを報告しません。</translation> <translation id="5346587320074666194">センサーへのアクセスをブロックするサイトを指定します</translation> @@ -3219,7 +3219,7 @@ <ph name="EXTENSION_INSTALL_BLOCKLIST_POLICY_NAME" /> はこのポリシーに優先します。つまり、このリスト上のサイトから発行されていても、拒否リストに登録されている拡張機能はインストールされません。</translation> <translation id="5860010874344790473">このポリシーを有効に設定すると、システムログが管理サーバーに送信され、管理者がシステムログをモニタリングできるようになります。 - このポリシーを無効に設定するか未設定のままにすると、システムログは報告されません。</translation> + このポリシーを無効にするか、未設定のままにすると、システムログは報告されません。</translation> <translation id="5861856285460256766">保護者のアクセスコードの設定</translation> <translation id="5868414965372171132">ユーザー レベルのネットワーク設定</translation> <translation id="587242272905978723"><ph name="PLUGIN_VM_NAME" /> に <ph name="PLUGIN_VM_NAME" /> 使用状況データの収集を許可します。 @@ -3843,7 +3843,7 @@ 管理対象のデバイスでこのポリシーを設定しない場合、デバイスで仮想マシンの実行は許可されません。管理対象以外のデバイスでは仮想マシンの実行が許可されます。</translation> <translation id="6786747875388722282">拡張機能</translation> <translation id="6786967369487349613">ローミング プロフィール ディレクトリの設定</translation> -<translation id="6789422336869764846">このポリシーを有効に設定するか未設定のままにすると、登録済みのデバイスはデバイス起動時の Dev スイッチの状態を報告します。 +<translation id="6789422336869764846">このポリシーを有効にするか、未設定のままにすると、登録済みのデバイスはデバイス起動時の Dev スイッチの状態を報告します。 このポリシーを無効に設定すると、登録済みのデバイスは Dev スイッチの状態を報告しません。</translation> <translation id="6795485990775913659">PIN なしの印刷のみを許可します</translation> @@ -4389,7 +4389,7 @@ <translation id="7458437477941640506">OS のバージョンが対象バージョンよりも新しい場合に、対象バージョンに戻さず、アップデートも行いません。</translation> <translation id="7459601923199346224">証明書管理のユーザー ポリシーとデバイス ポリシーを管理します。</translation> <translation id="7464991223784276288">一致する URL からの Cookie を現在のセッションに限定する</translation> -<translation id="7468182772656807573">このポリシーの設定により、監視ネットワーク パケットの送信間隔(ミリ秒単位)が決定されます。間隔の範囲は 30 秒~24 時間です。この範囲外の値を設定した場合、この範囲内の値に修正されます。 +<translation id="7468182772656807573">このポリシーの設定により、監視ネットワーク パケットの送信間隔(ミリ秒単位)が決定されます。間隔の範囲は 30 秒~24 時間です。範囲外の値を設定しても、範囲内の値に修正されます。 設定しなかった場合は、デフォルトの 3 分間隔が適用されます。</translation> <translation id="7469554574977894907">検索キーワード候補を有効にする</translation> @@ -4798,7 +4798,7 @@ この設定を有効にするか値を設定しない場合、ユーザーは自動入力を利用できます。ユーザーは自動入力プロフィールを設定して、自身の判断で自動入力をオンまたはオフにすることができます。</translation> <translation id="8036964468882248070">このポリシーを有効に設定すると、登録済みデバイスはストレージ デバイスに関するハードウェアの統計情報と識別子を報告します。 - このポリシーを無効に設定するか未設定のままにすると、登録済みのデバイスはストレージに関する統計情報を報告しません。</translation> + このポリシーを無効にするか、未設定のままにすると、登録済みのデバイスはストレージに関する統計情報を報告しません。</translation> <translation id="8044493735196713914">デバイス起動モードを報告する</translation> <translation id="8049769137921877885">このポリシーでは、ポリシーデータとポリシーの取得日時について、レポートを作成するかどうかを管理します。 @@ -4879,7 +4879,7 @@ このポリシーを未設定のままにした場合、カーソルによるハイライト表示が無効(初期設定)になりますが、ユーザーはいつでも有効にできます。</translation> <translation id="8164687848393015214">このポリシーを有効に設定すると、監視ネットワーク パケット(<ph name="HEARTBEATS_TERM" />)が管理サーバーに送信されてオンライン ステータスがモニタリングされ、デバイスがオフラインかどうかをサーバーが検出できるようになります。 - このポリシーを無効に設定するか未設定のままにすると、パケットは送信されません。</translation> + このポリシーを無効にするか、未設定のままにすると、パケットは送信されません。</translation> <translation id="816783746144552109">デバイスでの使用を許可する Chrome の最小バージョンを設定する。</translation> <translation id="8171924760436219650">ログイン画面でマウスのメインボタンを右に切り替える</translation> <translation id="8176035528522326671">企業ユーザーがメインのマルチプロフィール ユーザーとしてのみ操作できるようにする(企業の管理対象ユーザーに対するデフォルトの動作)</translation> @@ -5368,7 +5368,7 @@ URL パターンは、https://www.chromium.org/administrators/url-blacklist-filter-format で説明されている <ph name="URL_BLOCKLIST_POLICY_NAME" /> ポリシーと同じ形式で指定します。 </translation> -<translation id="8931555638815157255">このポリシーを有効に設定するか未設定のままにすると、登録済みのデバイスは定期的に OS とファームウェアのバージョンを報告します。 +<translation id="8931555638815157255">このポリシーを有効にするか、未設定のままにすると、登録済みのデバイスは定期的に OS とファームウェアのバージョンを報告します。 このポリシーを無効に設定すると、登録済みのデバイスはバージョン情報を報告しません。</translation> <translation id="8937282917198525844"> M81 以降、標準のフォーム コントロール要素(<select>、<button>、<input type=date> など)のデザインが一新され、ユーザー補助機能とプラットフォームの統一性が改善されました。このポリシーは古い「従来」のフォーム コントロール要素を復元します(M84 まで対応)。 @@ -5545,7 +5545,7 @@ このポリシーを未設定のままにした場合、<ph name="DEFAULT_PLUGINS_SETTING_POLICY_NAME" /> が設定されていればその設定がすべてのサイトで使用され、設定されていなければユーザーの個人設定が適用されます。 有効な URL パターンについて詳しくは、https://cloud.google.com/docs/chrome-enterprise/policies/url-patterns をご覧ください。ただし、M85 以降では、ホストに「*」と「[*.]」のワイルドカードを使用したパターンは、このポリシーでサポートされなくなります。</translation> -<translation id="9073405975862312795">このポリシーを有効に設定するか未設定のままにすると、登録済みのデバイスはユーザーがデバイス上でアクティブになっていた期間を報告します。 +<translation id="9073405975862312795">このポリシーを有効にするか、未設定のままにすると、登録済みのデバイスはユーザーがデバイス上でアクティブになっていた期間を報告します。 このポリシーを無効に設定すると、登録済みのデバイスはアクティブな期間を記録または報告しません。</translation> <translation id="9077227880520270584">デバイスのローカル アカウントの自動ログイン タイマー</translation>
diff --git a/components/policy/resources/policy_templates_uk.xtb b/components/policy/resources/policy_templates_uk.xtb index 0eefe42c..1658bf09 100644 --- a/components/policy/resources/policy_templates_uk.xtb +++ b/components/policy/resources/policy_templates_uk.xtb
@@ -2661,7 +2661,7 @@ Примітка: елементи в цей список можна також додавати за допомогою правила <ph name="EXTERNAL_SITELIST_URL_POLICY_NAME" />.</translation> <translation id="5065753964276395784">Це правило більше не підтримується. Натомість використовуйте правило <ph name="PROXY_SETTINGS_POLICY_NAME" />. - Якщо це правило налаштоване, <ph name="PRODUCT_NAME" /> обходитиме всі проксі для хостів із наведеного тут списку. Це правило діє, лише якщо правило <ph name="PROXY_SETTINGS_POLICY_NAME" /> невказане, а для правила <ph name="PROXY_MODE_POLICY_NAME" /> вибрано значення <ph name="PROXY_MODE_ENUM_FIXED_SERVERS" />. + Якщо це правило налаштоване, <ph name="PRODUCT_NAME" /> обходитиме всі проксі для хостів із наведеного тут списку. Це правило діє, лише якщо правило <ph name="PROXY_SETTINGS_POLICY_NAME" /> не вказане, а для правила <ph name="PROXY_MODE_POLICY_NAME" /> вибрано значення <ph name="PROXY_MODE_ENUM_FIXED_SERVERS" />. Якщо ви вибрали інший режим, це правило не потрібно налаштовувати. @@ -4091,7 +4091,7 @@ Якщо вибрано опцію "U2F_EXTENDED", вбудований другий фактор забезпечує функції U2F і деякі розширення для особистого підтвердження.</translation> <translation id="6999948519306285655">Це правило більше не підтримується. Натомість використовуйте правило <ph name="PROXY_SETTINGS_POLICY_NAME" />. - За допомогою налаштувань цього правила можна вказати URL-адресу файлу .pac проксі-сервера. Це правило діє, лише якщо правило <ph name="PROXY_SETTINGS_POLICY_NAME" /> невказане, а для правила <ph name="PROXY_MODE_POLICY_NAME" /> вибрано значення <ph name="PROXY_MODE_ENUM_PAC_SCRIPT" />. + За допомогою налаштувань цього правила можна вказати URL-адресу файлу .pac проксі-сервера. Це правило діє, лише якщо правило <ph name="PROXY_SETTINGS_POLICY_NAME" /> не вказане, а для правила <ph name="PROXY_MODE_POLICY_NAME" /> вибрано значення <ph name="PROXY_MODE_ENUM_PAC_SCRIPT" />. Якщо ви вибрали інший режим, це правило не потрібно налаштовувати. @@ -4683,7 +4683,7 @@ <translation id="7715711044277116530">Відсоток, за яким масштабують затримку затемнення екрана в режимі презентації</translation> <translation id="7716020145539921591">Це правило більше не підтримується. Натомість використовуйте правило <ph name="PROXY_SETTINGS_POLICY_NAME" />. - За допомогою налаштувань цього правила можна вказати URL-адресу проксі-сервера. Це правило діє, лише якщо правило <ph name="PROXY_SETTINGS_POLICY_NAME" /> невказане, а для правила <ph name="PROXY_MODE_POLICY_NAME" /> вибрано значення <ph name="PROXY_MODE_ENUM_FIXED_SERVERS" />. + За допомогою налаштувань цього правила можна вказати URL-адресу проксі-сервера. Це правило діє, лише якщо правило <ph name="PROXY_SETTINGS_POLICY_NAME" /> не вказане, а для правила <ph name="PROXY_MODE_POLICY_NAME" /> вибрано значення <ph name="PROXY_MODE_ENUM_FIXED_SERVERS" />. Якщо ви вибрали інший режим, це правило не потрібно налаштовувати.
diff --git a/components/security_interstitials/content/cert_report_helper.cc b/components/security_interstitials/content/cert_report_helper.cc index be27d75..01364e9 100644 --- a/components/security_interstitials/content/cert_report_helper.cc +++ b/components/security_interstitials/content/cert_report_helper.cc
@@ -102,6 +102,11 @@ if (!show) return; + if (metrics_helper_) { + metrics_helper_->RecordUserInteraction( + security_interstitials::MetricsHelper::SHOW_ENHANCED_PROTECTION); + } + load_time_data->SetString( security_interstitials::kEnhancedProtectionMessage, l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_ENHANCED_PROTECTION_MESSAGE));
diff --git a/components/security_interstitials/core/bad_clock_ui.cc b/components/security_interstitials/core/bad_clock_ui.cc index 42f54c5..70bd48d 100644 --- a/components/security_interstitials/core/bad_clock_ui.cc +++ b/components/security_interstitials/core/bad_clock_ui.cc
@@ -111,6 +111,8 @@ controller_->OpenExtendedReportingWhitepaper(true); break; case CMD_OPEN_ENHANCED_PROTECTION_SETTINGS: + controller_->metrics_helper()->RecordUserInteraction( + security_interstitials::MetricsHelper::OPEN_ENHANCED_PROTECTION); controller_->OpenEnhancedProtectionSettings(); break; case CMD_PROCEED:
diff --git a/components/security_interstitials/core/blocked_interception_ui.cc b/components/security_interstitials/core/blocked_interception_ui.cc index 7aefb0e9..19a85bd 100644 --- a/components/security_interstitials/core/blocked_interception_ui.cc +++ b/components/security_interstitials/core/blocked_interception_ui.cc
@@ -108,6 +108,8 @@ controller_->OpenExtendedReportingWhitepaper(true); break; case CMD_OPEN_ENHANCED_PROTECTION_SETTINGS: + controller_->metrics_helper()->RecordUserInteraction( + security_interstitials::MetricsHelper::OPEN_ENHANCED_PROTECTION); controller_->OpenEnhancedProtectionSettings(); break; case CMD_OPEN_HELP_CENTER:
diff --git a/components/security_interstitials/core/browser/resources/interstitial_ssl.css b/components/security_interstitials/core/browser/resources/interstitial_ssl.css index adcfc7b..e73b172 100644 --- a/components/security_interstitials/core/browser/resources/interstitial_ssl.css +++ b/components/security_interstitials/core/browser/resources/interstitial_ssl.css
@@ -35,7 +35,3 @@ .ssl-enhanced-protection-message .icon { background-image: url(images/light_bulb_grey.svg); } - -.ssl-enhanced-protection-message a:link { - color: blue; -}
diff --git a/components/security_interstitials/core/metrics_helper.h b/components/security_interstitials/core/metrics_helper.h index 9b060a4..4663f59 100644 --- a/components/security_interstitials/core/metrics_helper.h +++ b/components/security_interstitials/core/metrics_helper.h
@@ -53,6 +53,8 @@ EXTENDED_REPORTING_IS_ENABLED, REPORT_PHISHING_ERROR, SHOW_WHITEPAPER, + SHOW_ENHANCED_PROTECTION, + OPEN_ENHANCED_PROTECTION, MAX_INTERACTION };
diff --git a/components/security_interstitials/core/mitm_software_ui.cc b/components/security_interstitials/core/mitm_software_ui.cc index 465e61e..355d3a3 100644 --- a/components/security_interstitials/core/mitm_software_ui.cc +++ b/components/security_interstitials/core/mitm_software_ui.cc
@@ -86,6 +86,8 @@ controller_->OpenExtendedReportingWhitepaper(true); break; case CMD_OPEN_ENHANCED_PROTECTION_SETTINGS: + controller_->metrics_helper()->RecordUserInteraction( + security_interstitials::MetricsHelper::OPEN_ENHANCED_PROTECTION); controller_->OpenEnhancedProtectionSettings(); break; case CMD_DONT_PROCEED:
diff --git a/components/security_interstitials/core/safe_browsing_loud_error_ui.cc b/components/security_interstitials/core/safe_browsing_loud_error_ui.cc index 84a4b73..a5700664 100644 --- a/components/security_interstitials/core/safe_browsing_loud_error_ui.cc +++ b/components/security_interstitials/core/safe_browsing_loud_error_ui.cc
@@ -232,6 +232,8 @@ break; } case CMD_OPEN_ENHANCED_PROTECTION_SETTINGS: { + controller()->metrics_helper()->RecordUserInteraction( + security_interstitials::MetricsHelper::OPEN_ENHANCED_PROTECTION); controller()->OpenEnhancedProtectionSettings(); break; } @@ -329,6 +331,10 @@ base::DictionaryValue* load_time_data) { bool can_show_enhanced_protection_message = CanShowEnhancedProtectionMessage(); + if (can_show_enhanced_protection_message) { + controller()->metrics_helper()->RecordUserInteraction( + security_interstitials::MetricsHelper::SHOW_ENHANCED_PROTECTION); + } load_time_data->SetBoolean( security_interstitials::kDisplayEnhancedProtectionMessage, can_show_enhanced_protection_message);
diff --git a/components/security_interstitials/core/ssl_error_ui.cc b/components/security_interstitials/core/ssl_error_ui.cc index dc50b49..afa80c4 100644 --- a/components/security_interstitials/core/ssl_error_ui.cc +++ b/components/security_interstitials/core/ssl_error_ui.cc
@@ -247,6 +247,8 @@ break; } case CMD_OPEN_ENHANCED_PROTECTION_SETTINGS: { + controller_->metrics_helper()->RecordUserInteraction( + security_interstitials::MetricsHelper::OPEN_ENHANCED_PROTECTION); controller_->OpenEnhancedProtectionSettings(); break; }
diff --git a/components/strings/components_strings_ja.xtb b/components/strings/components_strings_ja.xtb index 414f7ce..e473b7a5 100644 --- a/components/strings/components_strings_ja.xtb +++ b/components/strings/components_strings_ja.xtb
@@ -1262,7 +1262,7 @@ <translation id="6051221802930200923"><ph name="SITE" /> では証明書ピンニングが使用されているため、現在アクセスできません。通常、ネットワーク エラーやネットワークへの攻撃は一時的なものです。しばらくするとページにアクセスできるようになります。</translation> <translation id="6052284303005792909">•</translation> <translation id="6053328359599022071">ご自分のアクティブ状態を共有しますか?</translation> -<translation id="6057359309778282021">管理者が <ph name="ORIGIN_NAME" /> から <ph name="VM_NAME" /> への共有をブロックしました</translation> +<translation id="6057359309778282021"><ph name="ORIGIN_NAME" /> から <ph name="VM_NAME" /> への共有は、管理者によってブロックされています</translation> <translation id="6058977677006700226">お使いのどのデバイスでも同じカードを使用できるようにしますか?</translation> <translation id="6059925163896151826">USB デバイス</translation> <translation id="6060009363608157444">無効な DnsOverHttps モードです。</translation> @@ -1874,7 +1874,7 @@ <translation id="8622948367223941507">Legal-Extra</translation> <translation id="8623885649813806493">一致するパスワードがありません。保存したパスワードをすべて表示します。</translation> <translation id="8625384913736129811">このカード情報をこのデバイスに保存する</translation> -<translation id="8657078576661269990">管理者が <ph name="ORIGIN_NAME" /> から <ph name="VM_NAME_1" /> および <ph name="VM_NAME_2" /> への共有をブロックしました</translation> +<translation id="8657078576661269990"><ph name="ORIGIN_NAME" /> から <ph name="VM_NAME_1" /> および <ph name="VM_NAME_2" /> への共有は、管理者によってブロックされています</translation> <translation id="8663226718884576429">ご注文の概要、<ph name="TOTAL_LABEL" />、その他の詳細</translation> <translation id="867224526087042813">署名</translation> <translation id="8676424191133491403">今すぐ</translation>
diff --git a/components/strings/components_strings_pt-BR.xtb b/components/strings/components_strings_pt-BR.xtb index bbb3542..4ac0d7f 100644 --- a/components/strings/components_strings_pt-BR.xtb +++ b/components/strings/components_strings_pt-BR.xtb
@@ -754,7 +754,7 @@ <translation id="4082393374666368382">Configurações: gerenciamento</translation> <translation id="4084120443451129199">Modo de pesquisa. Pressione "Enter" para pesquisar <ph name="KEYWORD_SUFFIX" /></translation> <translation id="4088981014127559358">Mudança Y no lado 1 da imagem</translation> -<translation id="4098354747657067197">Site enganoso</translation> +<translation id="4098354747657067197">Site fraudulento</translation> <translation id="4101413244023615925">Texto e gráficos</translation> <translation id="4103249731201008433">O número de série do dispositivo é inválido</translation> <translation id="4110652170750985508">Analisar seu pagamento</translation>
diff --git a/components/translate/core/browser/translate_manager.cc b/components/translate/core/browser/translate_manager.cc index c79ed76..9465177 100644 --- a/components/translate/core/browser/translate_manager.cc +++ b/components/translate/core/browser/translate_manager.cc
@@ -36,6 +36,8 @@ #include "components/translate/core/browser/translate_error_details.h" #include "components/translate/core/browser/translate_init_details.h" #include "components/translate/core/browser/translate_language_list.h" +#include "components/translate/core/browser/translate_metrics_logger.h" +#include "components/translate/core/browser/translate_metrics_logger_impl.h" #include "components/translate/core/browser/translate_prefs.h" #include "components/translate/core/browser/translate_ranker.h" #include "components/translate/core/browser/translate_script.h" @@ -137,6 +139,8 @@ translate_driver_(translate_client_->GetTranslateDriver()), translate_ranker_(translate_ranker), language_model_(language_model), + null_translate_metrics_logger_( + std::make_unique<NullTranslateMetricsLogger>()), language_state_(translate_driver_), translate_event_(std::make_unique<metrics::TranslateEventProto>()) {} @@ -1146,4 +1150,18 @@ language_state_.SetPredefinedTargetLanguage(language_code); } +TranslateMetricsLogger* TranslateManager::GetActiveTranslateMetricsLogger() { + // If |active_translate_metrics_logger_| is not null, return that. Otherwise + // return |null_translate_metrics_logger_|. This way the callee doesn't have + // to check if the returned value is null. + return active_translate_metrics_logger_ + ? active_translate_metrics_logger_.get() + : null_translate_metrics_logger_.get(); +} + +void TranslateManager::RegisterTranslateMetricsLogger( + base::WeakPtr<TranslateMetricsLogger> translate_metrics_logger) { + active_translate_metrics_logger_ = translate_metrics_logger; +} + } // namespace translate
diff --git a/components/translate/core/browser/translate_manager.h b/components/translate/core/browser/translate_manager.h index c6223f5..8620380 100644 --- a/components/translate/core/browser/translate_manager.h +++ b/components/translate/core/browser/translate_manager.h
@@ -32,10 +32,13 @@ class TranslateClient; class TranslateDriver; +class TranslateMetricsLogger; class TranslatePrefs; class TranslateRanker; struct TranslateTriggerDecision; +class NullTranslateMetricsLogger; + namespace testing { class TranslateManagerTest; } // namespace testing @@ -197,6 +200,17 @@ // Sets target language. void SetPredefinedTargetLanguage(const std::string& language_code); + // Returns a reference to |active_translate_metrics_logger_|. In the event + // that this value is null, a |NullTranslateMetricsLogger| (a null + // implementation) will be returned. This guarantees that the returned value + // is always non-null. + TranslateMetricsLogger* GetActiveTranslateMetricsLogger(); + + // Sets |active_translate_metrics_logger_| to the given + // |translate_metrics_logger|. + void RegisterTranslateMetricsLogger( + base::WeakPtr<TranslateMetricsLogger> translate_metrics_logger); + private: friend class translate::testing::TranslateManagerTest; @@ -306,6 +320,9 @@ TranslateRanker* translate_ranker_; // Weak. language::LanguageModel* language_model_; // Weak. + base::WeakPtr<TranslateMetricsLogger> active_translate_metrics_logger_; + std::unique_ptr<NullTranslateMetricsLogger> null_translate_metrics_logger_; + LanguageState language_state_; std::unique_ptr<metrics::TranslateEventProto> translate_event_;
diff --git a/components/translate/core/browser/translate_manager_unittest.cc b/components/translate/core/browser/translate_manager_unittest.cc index 33f09c7..48a0c6d 100644 --- a/components/translate/core/browser/translate_manager_unittest.cc +++ b/components/translate/core/browser/translate_manager_unittest.cc
@@ -26,6 +26,7 @@ #include "components/translate/core/browser/translate_browser_metrics.h" #include "components/translate/core/browser/translate_client.h" #include "components/translate/core/browser/translate_download_manager.h" +#include "components/translate/core/browser/translate_metrics_logger_impl.h" #include "components/translate/core/browser/translate_pref_names.h" #include "components/translate/core/browser/translate_prefs.h" #include "components/translate/core/common/translate_constants.h" @@ -180,6 +181,10 @@ translate_prefs_); } + NullTranslateMetricsLogger* null_translate_metrics_logger() { + return translate_manager_->null_translate_metrics_logger_.get(); + } + // Required to instantiate a net::test::MockNetworkChangeNotifier, because it // uses ObserverListThreadSafe. base::test::TaskEnvironment task_environment_; @@ -1081,6 +1086,42 @@ histogram_tester.ExpectTotalCount(kInitiationStatusName, 0); } +TEST_F(TranslateManagerTest, GetActiveTranslateMetricsLogger) { + PrepareTranslateManager(); + std::unique_ptr<TranslateMetricsLogger> translate_metrics_logger_a = + std::make_unique<TranslateMetricsLoggerImpl>( + translate_manager_->GetWeakPtr()); + std::unique_ptr<TranslateMetricsLogger> translate_metrics_logger_b = + std::make_unique<TranslateMetricsLoggerImpl>( + translate_manager_->GetWeakPtr()); + + // Before either |TranslateMetricsLogger| begins, we expect + // |GetActiveTranslateMetricsLogger| to return the null implementation. + EXPECT_EQ(translate_manager_->GetActiveTranslateMetricsLogger(), + null_translate_metrics_logger()); + + // Now that the page load has begun for |translate_metrics_logger_a|, we + // expect |GetActiveTranslateMetricsLogger| to return + // |translate_metrics_logger_a|. + translate_metrics_logger_a->OnPageLoadStart(true); + EXPECT_EQ(translate_manager_->GetActiveTranslateMetricsLogger(), + translate_metrics_logger_a.get()); + + // Once the page load starts for |translate_metrics_logger_b|, we + // expect |GetActiveTranslateMetricsLogger| to return + // |translate_metrics_logger_b|, even if |translate_metrics_logger_a| hasn't + // been destroyed yet. + translate_metrics_logger_b->OnPageLoadStart(true); + EXPECT_EQ(translate_manager_->GetActiveTranslateMetricsLogger(), + translate_metrics_logger_b.get()); + + // Once |translate_metrics_logger_b| is destroyed, we expect that + // |GetActiveTranslateMetricsLogger| to return the null implementation. + translate_metrics_logger_b.reset(); + EXPECT_EQ(translate_manager_->GetActiveTranslateMetricsLogger(), + null_translate_metrics_logger()); +} + } // namespace testing } // namespace translate
diff --git a/components/translate/core/browser/translate_metrics_logger.h b/components/translate/core/browser/translate_metrics_logger.h index 303d8ca..7698198 100644 --- a/components/translate/core/browser/translate_metrics_logger.h +++ b/components/translate/core/browser/translate_metrics_logger.h
@@ -7,6 +7,8 @@ namespace translate { +class TranslateManager; + // TranslateMetricsLogger tracks and logs various UKM and UMA metrics for Chrome // Translate over the course of a page load. class TranslateMetricsLogger { @@ -24,6 +26,11 @@ // Logs all stored page load metrics. If is_final is |true| then RecordMetrics // won't be called again. virtual void RecordMetrics(bool is_final) = 0; + + // TODO(curranmax): Split this into two interfaces. One for the interaction + // with the |TranslatePageLoadMetricsObserver|, and the other for the + // interaction with |TranslateManager| and the rest of the Translate code. + // https://crbug.com/1114868. }; } // namespace translate
diff --git a/components/translate/core/browser/translate_metrics_logger_impl.cc b/components/translate/core/browser/translate_metrics_logger_impl.cc index bc96ef9..30e2f9c 100644 --- a/components/translate/core/browser/translate_metrics_logger_impl.cc +++ b/components/translate/core/browser/translate_metrics_logger_impl.cc
@@ -4,9 +4,21 @@ #include "components/translate/core/browser/translate_metrics_logger_impl.h" +#include "components/translate/core/browser/translate_manager.h" + namespace translate { +TranslateMetricsLoggerImpl::TranslateMetricsLoggerImpl( + base::WeakPtr<TranslateManager> translate_manager) + : translate_manager_(translate_manager) {} + +TranslateMetricsLoggerImpl::~TranslateMetricsLoggerImpl() = default; + void TranslateMetricsLoggerImpl::OnPageLoadStart(bool is_foreground) { + if (translate_manager_) + translate_manager_->RegisterTranslateMetricsLogger( + weak_method_factory_.GetWeakPtr()); + is_foreground_ = is_foreground; }
diff --git a/components/translate/core/browser/translate_metrics_logger_impl.h b/components/translate/core/browser/translate_metrics_logger_impl.h index d9803e2..5717b370 100644 --- a/components/translate/core/browser/translate_metrics_logger_impl.h +++ b/components/translate/core/browser/translate_metrics_logger_impl.h
@@ -7,16 +7,30 @@ #include <memory> +#include "base/memory/weak_ptr.h" #include "components/translate/core/browser/translate_metrics_logger.h" namespace translate { +class NullTranslateMetricsLogger : public TranslateMetricsLogger { + public: + NullTranslateMetricsLogger() = default; + + // TranslateMetricsLogger + void OnPageLoadStart(bool is_foreground) override {} + void OnForegroundChange(bool is_foreground) override {} + void RecordMetrics(bool is_final) override {} +}; + +class TranslateManager; + // TranslateMetricsLogger tracks and logs various UKM and UMA metrics for Chrome // Translate over the course of a page load. class TranslateMetricsLoggerImpl : public TranslateMetricsLogger { public: - TranslateMetricsLoggerImpl() = default; - ~TranslateMetricsLoggerImpl() override = default; + explicit TranslateMetricsLoggerImpl( + base::WeakPtr<TranslateManager> translate_manager); + ~TranslateMetricsLoggerImpl() override; TranslateMetricsLoggerImpl(const TranslateMetricsLoggerImpl&) = delete; TranslateMetricsLoggerImpl& operator=(const TranslateMetricsLoggerImpl&) = @@ -27,11 +41,11 @@ void OnForegroundChange(bool is_foreground) override; void RecordMetrics(bool is_final) override; - // TODO(curranmax): Connect to TranslateManager so metrics can be collected - // from the rest of the Translate code. https://crbug.com/1114868. // TODO(curranmax): Add appropriate functions for the Translate code to log // relevant events. https://crbug.com/1114868. private: + base::WeakPtr<TranslateManager> translate_manager_; + // Since |RecordMetrics()| can be called multiple times, such as when Chrome // is backgrounded and reopened, we use |sequence_no_| to differentiate the // recorded UKM protos. @@ -40,6 +54,8 @@ // Tracks if the associated page is in the foreground (|true|) or the // background (|false|) bool is_foreground_{false}; + + base::WeakPtrFactory<TranslateMetricsLoggerImpl> weak_method_factory_{this}; }; } // namespace translate
diff --git a/components/viz/test/data/backdrop_filter_blur_radius_gl.png b/components/viz/test/data/backdrop_filter_blur_radius_gl.png index 078234c..25f3a631 100644 --- a/components/viz/test/data/backdrop_filter_blur_radius_gl.png +++ b/components/viz/test/data/backdrop_filter_blur_radius_gl.png Binary files differ
diff --git a/components/viz/test/data/backdrop_filter_blur_radius_skia_gl.png b/components/viz/test/data/backdrop_filter_blur_radius_skia_gl.png index 862238d..3ea0a1d 100644 --- a/components/viz/test/data/backdrop_filter_blur_radius_skia_gl.png +++ b/components/viz/test/data/backdrop_filter_blur_radius_skia_gl.png Binary files differ
diff --git a/components/viz/test/data/backdrop_filter_blur_radius_skia_vk.png b/components/viz/test/data/backdrop_filter_blur_radius_skia_vk.png index 1cca058..a9609f6 100644 --- a/components/viz/test/data/backdrop_filter_blur_radius_skia_vk.png +++ b/components/viz/test/data/backdrop_filter_blur_radius_skia_vk.png Binary files differ
diff --git a/components/viz/test/data/backdrop_filter_rotated_gl.png b/components/viz/test/data/backdrop_filter_rotated_gl.png index 0a8ddab..3b3081a 100644 --- a/components/viz/test/data/backdrop_filter_rotated_gl.png +++ b/components/viz/test/data/backdrop_filter_rotated_gl.png Binary files differ
diff --git a/components/viz/test/data/backdrop_filter_rotated_skia_gl.png b/components/viz/test/data/backdrop_filter_rotated_skia_gl.png index db56740..32416ee 100644 --- a/components/viz/test/data/backdrop_filter_rotated_skia_gl.png +++ b/components/viz/test/data/backdrop_filter_rotated_skia_gl.png Binary files differ
diff --git a/components/viz/test/data/backdrop_filter_rotated_skia_vk.png b/components/viz/test/data/backdrop_filter_rotated_skia_vk.png index d7f8c53..113d6fb 100644 --- a/components/viz/test/data/backdrop_filter_rotated_skia_vk.png +++ b/components/viz/test/data/backdrop_filter_rotated_skia_vk.png Binary files differ
diff --git a/content/browser/media/media_web_contents_observer.cc b/content/browser/media/media_web_contents_observer.cc index 309ca1f..505fd95 100644 --- a/content/browser/media/media_web_contents_observer.cc +++ b/content/browser/media/media_web_contents_observer.cc
@@ -250,6 +250,7 @@ OnAudioOutputSinkChangingDisabled) IPC_MESSAGE_HANDLER(MediaPlayerDelegateHostMsg_OnBufferUnderflow, OnBufferUnderflow) + IPC_MESSAGE_HANDLER(MediaPlayerDelegateHostMsg_OnSeek, OnSeek) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; @@ -453,6 +454,12 @@ web_contents_impl()->MediaBufferUnderflow(id); } +void MediaWebContentsObserver::OnSeek(RenderFrameHost* render_frame_host, + int delegate_id) { + const MediaPlayerId id(render_frame_host, delegate_id); + web_contents_impl()->MediaPlayerSeek(id); +} + device::mojom::WakeLock* MediaWebContentsObserver::GetAudioWakeLock() { // Here is a lazy binding, and will not reconnect after connection error. if (!audio_wake_lock_) {
diff --git a/content/browser/media/media_web_contents_observer.h b/content/browser/media/media_web_contents_observer.h index 6365fe7..852f8f4 100644 --- a/content/browser/media/media_web_contents_observer.h +++ b/content/browser/media/media_web_contents_observer.h
@@ -160,6 +160,7 @@ void OnAudioOutputSinkChangingDisabled(RenderFrameHost* render_frame_host, int delegate_id); void OnBufferUnderflow(RenderFrameHost* render_frame_host, int delegate_id); + void OnSeek(RenderFrameHost* render_frame_host, int delegate_id); device::mojom::WakeLock* GetAudioWakeLock();
diff --git a/content/browser/serial/serial_service.cc b/content/browser/serial/serial_service.cc index da4cf30..3dff58b 100644 --- a/content/browser/serial/serial_service.cc +++ b/content/browser/serial/serial_service.cc
@@ -109,12 +109,16 @@ weak_factory_.GetWeakPtr(), std::move(callback))); } -void SerialService::GetPort( +void SerialService::OpenPort( const base::UnguessableToken& token, - mojo::PendingReceiver<device::mojom::SerialPort> receiver) { + device::mojom::SerialConnectionOptionsPtr options, + mojo::PendingRemote<device::mojom::SerialPortClient> client, + OpenPortCallback callback) { SerialDelegate* delegate = GetContentClient()->browser()->GetSerialDelegate(); - if (!delegate) + if (!delegate) { + std::move(callback).Run(mojo::NullRemote()); return; + } if (watchers_.empty()) { auto* web_contents_impl = static_cast<WebContentsImpl*>( @@ -125,8 +129,8 @@ mojo::PendingRemote<device::mojom::SerialPortConnectionWatcher> watcher; watchers_.Add(this, watcher.InitWithNewPipeAndPassReceiver()); delegate->GetPortManager(render_frame_host_) - ->GetPort(token, /*use_alternate_path=*/false, std::move(receiver), - std::move(watcher)); + ->OpenPort(token, /*use_alternate_path=*/false, std::move(options), + std::move(client), std::move(watcher), std::move(callback)); } void SerialService::OnPortAdded(const device::mojom::SerialPortInfo& port) {
diff --git a/content/browser/serial/serial_service.h b/content/browser/serial/serial_service.h index 6f2acd4..25febaba 100644 --- a/content/browser/serial/serial_service.h +++ b/content/browser/serial/serial_service.h
@@ -40,9 +40,10 @@ void GetPorts(GetPortsCallback callback) override; void RequestPort(std::vector<blink::mojom::SerialPortFilterPtr> filters, RequestPortCallback callback) override; - void GetPort( - const base::UnguessableToken& token, - mojo::PendingReceiver<device::mojom::SerialPort> receiver) override; + void OpenPort(const base::UnguessableToken& token, + device::mojom::SerialConnectionOptionsPtr options, + mojo::PendingRemote<device::mojom::SerialPortClient> client, + OpenPortCallback callback) override; // SerialDelegate::Observer implementation void OnPortAdded(const device::mojom::SerialPortInfo& port) override;
diff --git a/content/browser/serial/serial_unittest.cc b/content/browser/serial/serial_unittest.cc index 71eafaf..0918101 100644 --- a/content/browser/serial/serial_unittest.cc +++ b/content/browser/serial/serial_unittest.cc
@@ -5,6 +5,7 @@ #include "base/barrier_closure.h" #include "base/command_line.h" #include "base/run_loop.h" +#include "base/test/bind_test_util.h" #include "base/test/gmock_callback_support.h" #include "content/browser/serial/serial_test_utils.h" #include "content/public/common/content_client.h" @@ -12,6 +13,7 @@ #include "content/test/test_render_view_host.h" #include "content/test/test_web_contents.h" #include "mojo/public/cpp/bindings/remote.h" +#include "services/device/public/cpp/test/fake_serial_port_client.h" #include "services/device/public/cpp/test/fake_serial_port_manager.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -42,7 +44,7 @@ return receiver_.BindNewPipeAndPassRemote(); } - // mojom::SerialPortManagerClient + // blink::mojom::SerialPortManagerClient MOCK_METHOD1(OnPortAdded, void(blink::mojom::SerialPortInfoPtr)); MOCK_METHOD1(OnPortRemoved, void(blink::mojom::SerialPortInfoPtr)); @@ -103,8 +105,17 @@ EXPECT_FALSE(contents()->IsConnectedToSerialPort()); mojo::Remote<device::mojom::SerialPort> port; - service->GetPort(token, port.BindNewPipeAndPassReceiver()); - base::RunLoop().RunUntilIdle(); + base::RunLoop loop; + service->OpenPort( + token, device::mojom::SerialConnectionOptions::New(), + device::FakeSerialPortClient::Create(), + base::BindLambdaForTesting( + [&](mojo::PendingRemote<device::mojom::SerialPort> pending_remote) { + EXPECT_TRUE(pending_remote.is_valid()); + port.Bind(std::move(pending_remote)); + loop.Quit(); + })); + loop.Run(); EXPECT_TRUE(contents()->IsConnectedToSerialPort()); port.reset(); @@ -112,6 +123,37 @@ EXPECT_FALSE(contents()->IsConnectedToSerialPort()); } +TEST_F(SerialTest, OpenFailure) { + NavigateAndCommit(GURL(kTestUrl)); + + mojo::Remote<blink::mojom::SerialService> service; + contents()->GetMainFrame()->BindSerialService( + service.BindNewPipeAndPassReceiver()); + + auto token = base::UnguessableToken::Create(); + auto port_info = device::mojom::SerialPortInfo::New(); + port_info->token = token; + port_manager()->AddPort(std::move(port_info)); + port_manager()->set_simulate_open_failure(true); + + EXPECT_FALSE(contents()->IsConnectedToSerialPort()); + + base::RunLoop loop; + service->OpenPort( + token, device::mojom::SerialConnectionOptions::New(), + device::FakeSerialPortClient::Create(), + base::BindLambdaForTesting( + [&](mojo::PendingRemote<device::mojom::SerialPort> pending_remote) { + EXPECT_FALSE(pending_remote.is_valid()); + loop.Quit(); + })); + loop.Run(); + + // Allow extra time for the watcher connection failure to propagate. + base::RunLoop().RunUntilIdle(); + EXPECT_FALSE(contents()->IsConnectedToSerialPort()); +} + TEST_F(SerialTest, OpenAndNavigateCrossOrigin) { NavigateAndCommit(GURL(kTestUrl)); @@ -127,8 +169,17 @@ EXPECT_FALSE(contents()->IsConnectedToSerialPort()); mojo::Remote<device::mojom::SerialPort> port; - service->GetPort(token, port.BindNewPipeAndPassReceiver()); - base::RunLoop().RunUntilIdle(); + base::RunLoop loop; + service->OpenPort( + token, device::mojom::SerialConnectionOptions::New(), + device::FakeSerialPortClient::Create(), + base::BindLambdaForTesting( + [&](mojo::PendingRemote<device::mojom::SerialPort> pending_remote) { + EXPECT_TRUE(pending_remote.is_valid()); + port.Bind(std::move(pending_remote)); + loop.Quit(); + })); + loop.Run(); EXPECT_TRUE(contents()->IsConnectedToSerialPort()); NavigateAndCommit(GURL(kCrossOriginTestUrl)); @@ -206,8 +257,17 @@ EXPECT_FALSE(contents()->IsConnectedToSerialPort()); mojo::Remote<device::mojom::SerialPort> port; - service->GetPort(token, port.BindNewPipeAndPassReceiver()); - base::RunLoop().RunUntilIdle(); + base::RunLoop loop; + service->OpenPort( + token, device::mojom::SerialConnectionOptions::New(), + device::FakeSerialPortClient::Create(), + base::BindLambdaForTesting( + [&](mojo::PendingRemote<device::mojom::SerialPort> pending_remote) { + EXPECT_TRUE(pending_remote.is_valid()); + port.Bind(std::move(pending_remote)); + loop.Quit(); + })); + loop.Run(); EXPECT_TRUE(contents()->IsConnectedToSerialPort()); ASSERT_TRUE(observer());
diff --git a/content/browser/service_worker/service_worker_disk_cache.cc b/content/browser/service_worker/service_worker_disk_cache.cc index b3e11a4e..7a3020e1 100644 --- a/content/browser/service_worker/service_worker_disk_cache.cc +++ b/content/browser/service_worker/service_worker_disk_cache.cc
@@ -14,9 +14,4 @@ ServiceWorkerDiskCache::ServiceWorkerDiskCache() : AppCacheDiskCache(/*use_simple_cache=*/true) {} -ServiceWorkerResponseMetadataWriter::ServiceWorkerResponseMetadataWriter( - int64_t resource_id, - base::WeakPtr<AppCacheDiskCache> disk_cache) - : AppCacheResponseMetadataWriter(resource_id, std::move(disk_cache)) {} - } // namespace content
diff --git a/content/browser/service_worker/service_worker_disk_cache.h b/content/browser/service_worker/service_worker_disk_cache.h index 22f5596..bed72d7 100644 --- a/content/browser/service_worker/service_worker_disk_cache.h +++ b/content/browser/service_worker/service_worker_disk_cache.h
@@ -5,13 +5,8 @@ #ifndef CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_DISK_CACHE_H_ #define CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_DISK_CACHE_H_ -#include <stdint.h> - -#include "base/memory/weak_ptr.h" #include "content/browser/appcache/appcache_disk_cache.h" -#include "content/browser/appcache/appcache_disk_cache_ops.h" #include "content/common/content_export.h" -#include "services/network/public/mojom/url_response_head.mojom.h" namespace content { @@ -26,19 +21,6 @@ ServiceWorkerDiskCache(); }; -// TODO(crbug.com/1117369): Migrate to -// storage::mojom::ServiceWorkerResourceMetadataWriter. -class CONTENT_EXPORT ServiceWorkerResponseMetadataWriter - : public AppCacheResponseMetadataWriter { - protected: - // Should only be constructed by the storage class. - friend class ServiceWorkerStorage; - - ServiceWorkerResponseMetadataWriter( - int64_t resource_id, - base::WeakPtr<AppCacheDiskCache> disk_cache); -}; - } // namespace content #endif // CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_DISK_CACHE_H_
diff --git a/content/browser/service_worker/service_worker_resource_ops.cc b/content/browser/service_worker/service_worker_resource_ops.cc index 9fc5381..fec55e39 100644 --- a/content/browser/service_worker/service_worker_resource_ops.cc +++ b/content/browser/service_worker/service_worker_resource_ops.cc
@@ -124,20 +124,20 @@ return std::move(buffer_); } -DiskEntryManager::DiskEntryManager(int64_t resource_id, +DiskEntryCreator::DiskEntryCreator(int64_t resource_id, base::WeakPtr<AppCacheDiskCache> disk_cache) : resource_id_(resource_id), disk_cache_(std::move(disk_cache)) { DCHECK_NE(resource_id_, blink::mojom::kInvalidServiceWorkerResourceId); DCHECK(disk_cache_); } -DiskEntryManager::~DiskEntryManager() { +DiskEntryCreator::~DiskEntryCreator() { if (entry_) { entry_->Close(); } } -void DiskEntryManager::EnsureEntryIsCreated(base::OnceClosure callback) { +void DiskEntryCreator::EnsureEntryIsCreated(base::OnceClosure callback) { DCHECK(creation_phase_ == CreationPhase::kNoAttempt || creation_phase_ == CreationPhase::kDone); DCHECK(!ensure_entry_is_created_callback_); @@ -166,22 +166,22 @@ } // static -void DiskEntryManager::DidCreateEntryForFirstAttempt( - base::WeakPtr<DiskEntryManager> entry_manager, +void DiskEntryCreator::DidCreateEntryForFirstAttempt( + base::WeakPtr<DiskEntryCreator> entry_creator, AppCacheDiskCacheEntry** entry, int rv) { - if (!entry_manager) { + if (!entry_creator) { delete entry; return; } - DCHECK_EQ(entry_manager->creation_phase_, CreationPhase::kInitialAttempt); - DCHECK(!entry_manager->entry_); + DCHECK_EQ(entry_creator->creation_phase_, CreationPhase::kInitialAttempt); + DCHECK(!entry_creator->entry_); - if (!entry_manager->disk_cache_) { + if (!entry_creator->disk_cache_) { delete entry; - entry_manager->entry_ = nullptr; - entry_manager->RunEnsureEntryIsCreatedCallback(); + entry_creator->entry_ = nullptr; + entry_creator->RunEnsureEntryIsCreatedCallback(); return; } @@ -189,89 +189,144 @@ // The first attempt to create an entry is failed. Try to overwrite the // existing entry. delete entry; - entry_manager->creation_phase_ = CreationPhase::kDoomExisting; - rv = entry_manager->disk_cache_->DoomEntry( - entry_manager->resource_id_, - base::BindOnce(&DiskEntryManager::DidDoomExistingEntry, entry_manager)); + entry_creator->creation_phase_ = CreationPhase::kDoomExisting; + rv = entry_creator->disk_cache_->DoomEntry( + entry_creator->resource_id_, + base::BindOnce(&DiskEntryCreator::DidDoomExistingEntry, entry_creator)); if (rv != net::ERR_IO_PENDING) { - DidDoomExistingEntry(entry_manager, rv); + DidDoomExistingEntry(entry_creator, rv); } return; } DCHECK(entry); - entry_manager->entry_ = *entry; + entry_creator->entry_ = *entry; delete entry; - entry_manager->RunEnsureEntryIsCreatedCallback(); + entry_creator->RunEnsureEntryIsCreatedCallback(); } // static -void DiskEntryManager::DidDoomExistingEntry( - base::WeakPtr<DiskEntryManager> entry_manager, +void DiskEntryCreator::DidDoomExistingEntry( + base::WeakPtr<DiskEntryCreator> entry_creator, int rv) { - if (!entry_manager) { + if (!entry_creator) { return; } - DCHECK_EQ(entry_manager->creation_phase_, CreationPhase::kDoomExisting); - DCHECK(!entry_manager->entry_); + DCHECK_EQ(entry_creator->creation_phase_, CreationPhase::kDoomExisting); + DCHECK(!entry_creator->entry_); - if (!entry_manager->disk_cache_) { - entry_manager->entry_ = nullptr; - entry_manager->RunEnsureEntryIsCreatedCallback(); + if (!entry_creator->disk_cache_) { + entry_creator->entry_ = nullptr; + entry_creator->RunEnsureEntryIsCreatedCallback(); return; } - entry_manager->creation_phase_ = CreationPhase::kSecondAttempt; + entry_creator->creation_phase_ = CreationPhase::kSecondAttempt; auto** entry_ptr = new AppCacheDiskCacheEntry*; - rv = entry_manager->disk_cache_->CreateEntry( - entry_manager->resource_id_, entry_ptr, - base::BindOnce(&DiskEntryManager::DidCreateEntryForSecondAttempt, - entry_manager, entry_ptr)); + rv = entry_creator->disk_cache_->CreateEntry( + entry_creator->resource_id_, entry_ptr, + base::BindOnce(&DiskEntryCreator::DidCreateEntryForSecondAttempt, + entry_creator, entry_ptr)); if (rv != net::ERR_IO_PENDING) { - DidCreateEntryForSecondAttempt(entry_manager, entry_ptr, rv); + DidCreateEntryForSecondAttempt(entry_creator, entry_ptr, rv); } } // static -void DiskEntryManager::DidCreateEntryForSecondAttempt( - base::WeakPtr<DiskEntryManager> entry_manager, +void DiskEntryCreator::DidCreateEntryForSecondAttempt( + base::WeakPtr<DiskEntryCreator> entry_creator, AppCacheDiskCacheEntry** entry, int rv) { - if (!entry_manager) { + if (!entry_creator) { delete entry; return; } - DCHECK_EQ(entry_manager->creation_phase_, CreationPhase::kSecondAttempt); + DCHECK_EQ(entry_creator->creation_phase_, CreationPhase::kSecondAttempt); - if (!entry_manager->disk_cache_) { + if (!entry_creator->disk_cache_) { delete entry; - entry_manager->entry_ = nullptr; - entry_manager->RunEnsureEntryIsCreatedCallback(); + entry_creator->entry_ = nullptr; + entry_creator->RunEnsureEntryIsCreatedCallback(); return; } if (rv != net::OK) { // The second attempt is also failed. Give up creating an entry. delete entry; - entry_manager->entry_ = nullptr; - entry_manager->RunEnsureEntryIsCreatedCallback(); + entry_creator->entry_ = nullptr; + entry_creator->RunEnsureEntryIsCreatedCallback(); return; } - DCHECK(!entry_manager->entry_); + DCHECK(!entry_creator->entry_); DCHECK(entry); - entry_manager->entry_ = *entry; - entry_manager->RunEnsureEntryIsCreatedCallback(); + entry_creator->entry_ = *entry; + entry_creator->RunEnsureEntryIsCreatedCallback(); delete entry; } -void DiskEntryManager::RunEnsureEntryIsCreatedCallback() { +void DiskEntryCreator::RunEnsureEntryIsCreatedCallback() { creation_phase_ = CreationPhase::kDone; std::move(ensure_entry_is_created_callback_).Run(); } +DiskEntryOpener::DiskEntryOpener(int64_t resource_id, + base::WeakPtr<AppCacheDiskCache> disk_cache) + : resource_id_(resource_id), disk_cache_(std::move(disk_cache)) { + DCHECK_NE(resource_id_, blink::mojom::kInvalidServiceWorkerResourceId); + DCHECK(disk_cache_); +} + +DiskEntryOpener::~DiskEntryOpener() { + if (entry_) { + entry_->Close(); + } +} + +void DiskEntryOpener::EnsureEntryIsOpen(base::OnceClosure callback) { + DCHECK(!ensure_entry_is_opened_callback_); + ensure_entry_is_opened_callback_ = std::move(callback); + + int rv; + AppCacheDiskCacheEntry** entry_ptr = nullptr; + if (entry_) { + rv = net::OK; + } else if (!disk_cache_) { + rv = net::ERR_FAILED; + } else { + entry_ptr = new AppCacheDiskCacheEntry*; + rv = disk_cache_->OpenEntry( + resource_id_, entry_ptr, + base::BindOnce(&DiskEntryOpener::DidOpenEntry, + weak_factory_.GetWeakPtr(), entry_ptr)); + } + + if (rv != net::ERR_IO_PENDING) { + DidOpenEntry(weak_factory_.GetWeakPtr(), entry_ptr, rv); + } +} + +// static +void DiskEntryOpener::DidOpenEntry(base::WeakPtr<DiskEntryOpener> entry_opener, + AppCacheDiskCacheEntry** entry, + int rv) { + if (!entry_opener) { + delete entry; + return; + } + + if (!entry_opener->entry_ && rv == net::OK) { + DCHECK(entry); + entry_opener->entry_ = *entry; + } + delete entry; + + DCHECK(entry_opener->ensure_entry_is_opened_callback_); + std::move(entry_opener->ensure_entry_is_opened_callback_).Run(); +} + class ServiceWorkerResourceReaderImpl::DataReader { public: DataReader( @@ -301,8 +356,8 @@ state_ = State::kStarted; #endif - owner_->EnsureEntryIsOpen(base::BindOnce(&DataReader::ContinueReadData, - weak_factory_.GetWeakPtr())); + owner_->entry_opener_.EnsureEntryIsOpen(base::BindOnce( + &DataReader::ContinueReadData, weak_factory_.GetWeakPtr())); } private: @@ -317,7 +372,7 @@ return; } - if (!owner_->entry_) { + if (!owner_->entry_opener_.entry()) { Complete(net::ERR_CACHE_MISS); return; } @@ -337,7 +392,7 @@ DCHECK(producer_handle_.is_valid()); DCHECK(!pending_buffer_); - if (!owner_ || !owner_->entry_) { + if (!owner_ || !owner_->entry_opener_.entry()) { Complete(net::ERR_ABORTED); return; } @@ -368,7 +423,7 @@ base::MakeRefCounted<network::NetToMojoIOBuffer>(pending_buffer_.get()); net::IOBuffer* raw_buffer = buffer.get(); - int read_bytes = owner_->entry_->Read( + int read_bytes = owner_->entry_opener_.entry()->Read( kResponseContentIndex, current_bytes_read_, raw_buffer, num_bytes, base::BindOnce(&DataReader::DidReadData, weak_factory_.GetWeakPtr(), buffer)); @@ -446,16 +501,9 @@ ServiceWorkerResourceReaderImpl::ServiceWorkerResourceReaderImpl( int64_t resource_id, base::WeakPtr<AppCacheDiskCache> disk_cache) - : resource_id_(resource_id), disk_cache_(std::move(disk_cache)) { - DCHECK_NE(resource_id_, blink::mojom::kInvalidServiceWorkerResourceId); - DCHECK(disk_cache_); -} + : entry_opener_(resource_id, std::move(disk_cache)) {} -ServiceWorkerResourceReaderImpl::~ServiceWorkerResourceReaderImpl() { - if (entry_) { - entry_->Close(); - } -} +ServiceWorkerResourceReaderImpl::~ServiceWorkerResourceReaderImpl() = default; void ServiceWorkerResourceReaderImpl::ReadResponseHead( ReadResponseHeadCallback callback) { @@ -469,7 +517,7 @@ DCHECK(!data_reader_); read_response_head_callback_ = std::move(callback); - EnsureEntryIsOpen( + entry_opener_.EnsureEntryIsOpen( base::BindOnce(&ServiceWorkerResourceReaderImpl::ContinueReadResponseHead, weak_factory_.GetWeakPtr())); } @@ -517,12 +565,12 @@ #endif DCHECK(read_response_head_callback_); - if (!entry_) { + if (!entry_opener_.entry()) { FailReadResponseHead(net::ERR_CACHE_MISS); return; } - int64_t size = entry_->GetSize(kResponseInfoIndex); + int64_t size = entry_opener_.entry()->GetSize(kResponseInfoIndex); if (size <= 0) { FailReadResponseHead(net::ERR_CACHE_MISS); return; @@ -530,7 +578,7 @@ auto buffer = base::MakeRefCounted<net::IOBuffer>(base::checked_cast<size_t>(size)); - int rv = entry_->Read( + int rv = entry_opener_.entry()->Read( kResponseInfoIndex, /*offset=*/0, buffer.get(), size, base::BindOnce(&ServiceWorkerResourceReaderImpl::DidReadHttpResponseInfo, weak_factory_.GetWeakPtr(), buffer)); @@ -547,7 +595,7 @@ state_ = State::kResponseInfoRead; #endif DCHECK(read_response_head_callback_); - DCHECK(entry_); + DCHECK(entry_opener_.entry()); if (status < 0) { FailReadResponseHead(status); @@ -565,11 +613,13 @@ } DCHECK(!response_truncated); - int64_t response_data_size = entry_->GetSize(kResponseContentIndex); + int64_t response_data_size = + entry_opener_.entry()->GetSize(kResponseContentIndex); response_head_ = ConvertHttpResponseInfo(*http_info, response_data_size); - int64_t metadata_size = entry_->GetSize(kResponseMetadataIndex); + int64_t metadata_size = + entry_opener_.entry()->GetSize(kResponseMetadataIndex); DCHECK_GE(metadata_size, 0); if (metadata_size <= 0) { CompleteReadResponseHead(status); @@ -579,7 +629,7 @@ // Read metadata. metadata_buffer_ = base::MakeRefCounted<BigIOBuffer>( mojo_base::BigBuffer(base::checked_cast<size_t>(metadata_size))); - int rv = entry_->Read( + int rv = entry_opener_.entry()->Read( kResponseMetadataIndex, /*offset=*/0, metadata_buffer_.get(), metadata_size, base::BindOnce(&ServiceWorkerResourceReaderImpl::DidReadMetadata, @@ -639,53 +689,10 @@ data_reader_.reset(); } -void ServiceWorkerResourceReaderImpl::EnsureEntryIsOpen( - base::OnceClosure callback) { - DCHECK(!open_entry_callback_); - open_entry_callback_ = std::move(callback); - - int rv; - AppCacheDiskCacheEntry** entry_ptr = nullptr; - if (entry_) { - rv = net::OK; - } else if (!disk_cache_) { - rv = net::ERR_FAILED; - } else { - entry_ptr = new AppCacheDiskCacheEntry*; - rv = disk_cache_->OpenEntry( - resource_id_, entry_ptr, - base::BindOnce(&DidOpenEntry, weak_factory_.GetWeakPtr(), entry_ptr)); - } - - if (rv != net::ERR_IO_PENDING) { - DidOpenEntry(weak_factory_.GetWeakPtr(), entry_ptr, rv); - } -} - -// static -void ServiceWorkerResourceReaderImpl::DidOpenEntry( - base::WeakPtr<ServiceWorkerResourceReaderImpl> reader, - AppCacheDiskCacheEntry** entry, - int rv) { - if (!reader) { - delete entry; - return; - } - - if (!reader->entry_ && rv == net::OK) { - DCHECK(entry); - reader->entry_ = *entry; - } - delete entry; - - DCHECK(reader->open_entry_callback_); - std::move(reader->open_entry_callback_).Run(); -} - ServiceWorkerResourceWriterImpl::ServiceWorkerResourceWriterImpl( int64_t resource_id, base::WeakPtr<AppCacheDiskCache> disk_cache) - : entry_manager_(resource_id, std::move(disk_cache)) {} + : entry_creator_(resource_id, std::move(disk_cache)) {} ServiceWorkerResourceWriterImpl::~ServiceWorkerResourceWriterImpl() = default; @@ -696,7 +703,7 @@ DCHECK_EQ(state_, State::kIdle); state_ = State::kWriteResponseHeadStarted; #endif - entry_manager_.EnsureEntryIsCreated( + entry_creator_.EnsureEntryIsCreated( base::BindOnce(&ServiceWorkerResourceWriterImpl::WriteResponseHeadToEntry, weak_factory_.GetWeakPtr(), std::move(response_head), std::move(callback))); @@ -708,7 +715,7 @@ DCHECK_EQ(state_, State::kIdle); state_ = State::kWriteDataStarted; #endif - entry_manager_.EnsureEntryIsCreated(base::BindOnce( + entry_creator_.EnsureEntryIsCreated(base::BindOnce( &ServiceWorkerResourceWriterImpl::WriteDataToEntry, weak_factory_.GetWeakPtr(), std::move(data), std::move(callback))); } @@ -720,7 +727,7 @@ DCHECK_EQ(state_, State::kWriteResponseHeadStarted); state_ = State::kWriteResponseHeadHasEntry; #endif - if (!entry_manager_.entry()) { + if (!entry_creator_.entry()) { std::move(callback).Run(net::ERR_FAILED); return; } @@ -733,7 +740,7 @@ auto buffer = base::MakeRefCounted<WrappedPickleIOBuffer>(std::move(pickle)); size_t write_amount = buffer->size(); - int rv = entry_manager_.entry()->Write( + int rv = entry_creator_.entry()->Write( kResponseInfoIndex, /*offset=*/0, buffer.get(), write_amount, base::BindOnce(&ServiceWorkerResourceWriterImpl::DidWriteResponseHead, weak_factory_.GetWeakPtr(), buffer, write_amount)); @@ -762,7 +769,7 @@ DCHECK_EQ(state_, State::kWriteDataStarted); state_ = State::kWriteDataHasEntry; #endif - if (!entry_manager_.entry()) { + if (!entry_creator_.entry()) { std::move(callback).Run(net::ERR_FAILED); return; } @@ -772,7 +779,7 @@ size_t write_amount = data.size(); auto buffer = base::MakeRefCounted<BigIOBuffer>(std::move(data)); - int rv = entry_manager_.entry()->Write( + int rv = entry_creator_.entry()->Write( kResponseContentIndex, write_position_, buffer.get(), write_amount, base::BindOnce(&ServiceWorkerResourceWriterImpl::DidWriteData, weak_factory_.GetWeakPtr(), buffer, write_amount)); @@ -799,10 +806,9 @@ ServiceWorkerResourceMetadataWriterImpl:: ServiceWorkerResourceMetadataWriterImpl( - std::unique_ptr<ServiceWorkerResponseMetadataWriter> writer) - : writer_(std::move(writer)) { - DCHECK(writer_); -} + int64_t resource_id, + base::WeakPtr<AppCacheDiskCache> disk_cache) + : entry_opener_(resource_id, std::move(disk_cache)) {} ServiceWorkerResourceMetadataWriterImpl:: ~ServiceWorkerResourceMetadataWriterImpl() = default; @@ -810,9 +816,51 @@ void ServiceWorkerResourceMetadataWriterImpl::WriteMetadata( mojo_base::BigBuffer data, WriteMetadataCallback callback) { - int buf_len = data.size(); +#if DCHECK_IS_ON() + DCHECK_EQ(state_, State::kIdle); + state_ = State::kWriteMetadataStarted; +#endif + entry_opener_.EnsureEntryIsOpen(base::BindOnce( + &ServiceWorkerResourceMetadataWriterImpl::ContinueWriteMetadata, + weak_factory_.GetWeakPtr(), std::move(data), std::move(callback))); +} + +void ServiceWorkerResourceMetadataWriterImpl::ContinueWriteMetadata( + mojo_base::BigBuffer data, + WriteMetadataCallback callback) { +#if DCHECK_IS_ON() + DCHECK_EQ(state_, State::kWriteMetadataStarted); + state_ = State::kWriteMetadataHasEntry; +#endif + if (!entry_opener_.entry()) { + std::move(callback).Run(net::ERR_FAILED); + return; + } + + DCHECK(!write_metadata_callback_); + write_metadata_callback_ = std::move(callback); + size_t write_amount = data.size(); auto buffer = base::MakeRefCounted<BigIOBuffer>(std::move(data)); - writer_->WriteMetadata(buffer.get(), buf_len, std::move(callback)); + int rv = entry_opener_.entry()->Write( + kResponseMetadataIndex, /*offset=*/0, buffer.get(), write_amount, + base::BindOnce(&ServiceWorkerResourceMetadataWriterImpl::DidWriteMetadata, + weak_factory_.GetWeakPtr(), buffer, write_amount)); + if (rv != net::ERR_IO_PENDING) { + DidWriteMetadata(std::move(buffer), write_amount, rv); + } +} + +void ServiceWorkerResourceMetadataWriterImpl::DidWriteMetadata( + scoped_refptr<net::IOBuffer> buffer, + size_t write_amount, + int rv) { +#if DCHECK_IS_ON() + DCHECK_EQ(state_, State::kWriteMetadataHasEntry); + state_ = State::kIdle; +#endif + DCHECK(rv < 0 || base::checked_cast<size_t>(rv) == write_amount); + DCHECK(write_metadata_callback_); + std::move(write_metadata_callback_).Run(rv); } } // namespace content
diff --git a/content/browser/service_worker/service_worker_resource_ops.h b/content/browser/service_worker/service_worker_resource_ops.h index a9c2b62..8edad23 100644 --- a/content/browser/service_worker/service_worker_resource_ops.h +++ b/content/browser/service_worker/service_worker_resource_ops.h
@@ -13,16 +13,15 @@ class BigIOBuffer; -// Manages a service worker disk cache entry. Creates and owns an entry. -// TODO(bashi): Used by resource writers. Use in readers as well. -class DiskEntryManager { +// Creates and owns a service worker disk cacke entry. +class DiskEntryCreator { public: - DiskEntryManager(int64_t resource_id, + DiskEntryCreator(int64_t resource_id, base::WeakPtr<AppCacheDiskCache> disk_cache); - ~DiskEntryManager(); + ~DiskEntryCreator(); - DiskEntryManager(const DiskEntryManager&) = delete; - DiskEntryManager& operator=(const DiskEntryManager&) = delete; + DiskEntryCreator(const DiskEntryCreator&) = delete; + DiskEntryCreator& operator=(const DiskEntryCreator&) = delete; // Can be nullptr when a disk cache error occurs. AppCacheDiskCacheEntry* entry() { @@ -58,14 +57,14 @@ // TODO(crbug.com/586174): Refactor service worker's disk cache to use // disk_cache::EntryResult to make these callbacks non-static. static void DidCreateEntryForFirstAttempt( - base::WeakPtr<DiskEntryManager> entry_manager, + base::WeakPtr<DiskEntryCreator> entry_creator, AppCacheDiskCacheEntry** entry, int rv); static void DidDoomExistingEntry( - base::WeakPtr<DiskEntryManager> entry_manager, + base::WeakPtr<DiskEntryCreator> entry_creator, int rv); static void DidCreateEntryForSecondAttempt( - base::WeakPtr<DiskEntryManager> entry_manager, + base::WeakPtr<DiskEntryCreator> entry_creator, AppCacheDiskCacheEntry** entry, int rv); @@ -80,7 +79,44 @@ // Stored as a data member to handle //net-style maybe-async methods. base::OnceClosure ensure_entry_is_created_callback_; - base::WeakPtrFactory<DiskEntryManager> weak_factory_{this}; + base::WeakPtrFactory<DiskEntryCreator> weak_factory_{this}; +}; + +// Opens and owns a service worker disk cache entry. +class DiskEntryOpener { + public: + DiskEntryOpener(int64_t resource_id, + base::WeakPtr<AppCacheDiskCache> disk_cache); + ~DiskEntryOpener(); + + DiskEntryOpener(const DiskEntryOpener&) = delete; + DiskEntryOpener& operator=(const DiskEntryOpener&) = delete; + + // Can be nullptr when a disk cache error occurs. + AppCacheDiskCacheEntry* entry() { return entry_; } + + // Calls the callback when entry() is opened and can be used. + // + // If necessary, opens a disk cache entry for the `resource_id` passed to the + // constructor. After the callback is called, `entry()` can be safely called + // to obtain the created entry. + void EnsureEntryIsOpen(base::OnceClosure callback); + + private: + // TODO(crbug.com/586174): Refactor service worker's disk cache to use + // disk_cache::EntryResult to make this callback non-static. + static void DidOpenEntry(base::WeakPtr<DiskEntryOpener> entry_creator, + AppCacheDiskCacheEntry** entry, + int rv); + + const int64_t resource_id_; + base::WeakPtr<AppCacheDiskCache> disk_cache_; + AppCacheDiskCacheEntry* entry_ = nullptr; + + // Stored as a data member to handle //net-style maybe-async methods. + base::OnceClosure ensure_entry_is_opened_callback_; + + base::WeakPtrFactory<DiskEntryOpener> weak_factory_{this}; }; // The implementation of storage::mojom::ServiceWorkerResourceReader. @@ -120,18 +156,7 @@ // data. void DidReadDataComplete(); - // Opens a disk cache entry associated with `resource_id_`, if it isn't - // opened yet. - void EnsureEntryIsOpen(base::OnceClosure callback); - - static void DidOpenEntry( - base::WeakPtr<ServiceWorkerResourceReaderImpl> reader, - AppCacheDiskCacheEntry** entry, - int rv); - - const int64_t resource_id_; - base::WeakPtr<AppCacheDiskCache> disk_cache_; - AppCacheDiskCacheEntry* entry_ = nullptr; + DiskEntryOpener entry_opener_; // Used to read metadata from disk cache. scoped_refptr<BigIOBuffer> metadata_buffer_; @@ -145,10 +170,6 @@ // Helper for ReadData(). std::unique_ptr<DataReader> data_reader_; - // Holds the callback of EnsureEntryIsOpen(). Stored as a data member to - // handle //net-style maybe-async methods. - base::OnceClosure open_entry_callback_; - #if DCHECK_IS_ON() enum class State { kIdle, @@ -199,7 +220,7 @@ size_t write_amount, int rv); - DiskEntryManager entry_manager_; + DiskEntryCreator entry_creator_; // Points the current write position of WriteData(). size_t write_position_ = 0; @@ -223,15 +244,12 @@ }; // The implementation of storage::mojom::ServiceWorkerResourceMetadataWriter. -// Currently this class is an adaptor that uses -// ServiceWorkerResponseMetadataWriter internally. -// TODO(crbug.com/1055677): Fork the implementation of -// ServiceWorkerResponseMetadataWriter and stop using it. class ServiceWorkerResourceMetadataWriterImpl : public storage::mojom::ServiceWorkerResourceMetadataWriter { public: - explicit ServiceWorkerResourceMetadataWriterImpl( - std::unique_ptr<ServiceWorkerResponseMetadataWriter> writer); + ServiceWorkerResourceMetadataWriterImpl( + int64_t resource_id, + base::WeakPtr<AppCacheDiskCache> disk_cache); ServiceWorkerResourceMetadataWriterImpl( const ServiceWorkerResourceMetadataWriterImpl&) = delete; @@ -240,12 +258,34 @@ ~ServiceWorkerResourceMetadataWriterImpl() override; - private: // storage::mojom::ServiceWorkerResourceMetadataWriter implementations: void WriteMetadata(mojo_base::BigBuffer data, WriteMetadataCallback callback) override; - const std::unique_ptr<ServiceWorkerResponseMetadataWriter> writer_; + private: + // Called while executing WriteMetadata(). + void ContinueWriteMetadata(mojo_base::BigBuffer data, + WriteMetadataCallback callback); + void DidWriteMetadata(scoped_refptr<net::IOBuffer> buffer, + size_t write_amount, + int rv); + + DiskEntryOpener entry_opener_; + + // Stored as a data member to handle //net-style maybe-async methods. + WriteMetadataCallback write_metadata_callback_; + +#if DCHECK_IS_ON() + enum class State { + kIdle, + kWriteMetadataStarted, + kWriteMetadataHasEntry, + }; + State state_ = State::kIdle; +#endif // DCHECK_IS_ON() + + base::WeakPtrFactory<ServiceWorkerResourceMetadataWriterImpl> weak_factory_{ + this}; }; } // namespace content
diff --git a/content/browser/service_worker/service_worker_storage.cc b/content/browser/service_worker/service_worker_storage.cc index 68d4a90..b71c3df 100644 --- a/content/browser/service_worker/service_worker_storage.cc +++ b/content/browser/service_worker/service_worker_storage.cc
@@ -598,10 +598,10 @@ resource_id, disk_cache()->GetWeakPtr()); } -std::unique_ptr<ServiceWorkerResponseMetadataWriter> -ServiceWorkerStorage::CreateResponseMetadataWriter(int64_t resource_id) { - return base::WrapUnique(new ServiceWorkerResponseMetadataWriter( - resource_id, disk_cache()->GetWeakPtr())); +std::unique_ptr<ServiceWorkerResourceMetadataWriterImpl> +ServiceWorkerStorage::CreateResourceMetadataWriter(int64_t resource_id) { + return std::make_unique<ServiceWorkerResourceMetadataWriterImpl>( + resource_id, disk_cache()->GetWeakPtr()); } void ServiceWorkerStorage::StoreUncommittedResourceId(
diff --git a/content/browser/service_worker/service_worker_storage.h b/content/browser/service_worker/service_worker_storage.h index f613554..b16f44ac 100644 --- a/content/browser/service_worker/service_worker_storage.h +++ b/content/browser/service_worker/service_worker_storage.h
@@ -38,8 +38,6 @@ namespace content { -class ServiceWorkerDiskCache; -class ServiceWorkerResponseMetadataWriter; class ServiceWorkerStorageControlImplTest; namespace service_worker_storage_unittest { @@ -188,8 +186,8 @@ int64_t resource_id); std::unique_ptr<ServiceWorkerResourceWriterImpl> CreateResourceWriter( int64_t resource_id); - std::unique_ptr<ServiceWorkerResponseMetadataWriter> - CreateResponseMetadataWriter(int64_t resource_id); + std::unique_ptr<ServiceWorkerResourceMetadataWriterImpl> + CreateResourceMetadataWriter(int64_t resource_id); // Adds |resource_id| to the set of resources that are in the disk cache // but not yet stored with a registration.
diff --git a/content/browser/service_worker/service_worker_storage_control_impl.cc b/content/browser/service_worker/service_worker_storage_control_impl.cc index 9d5f338c..6671cd4 100644 --- a/content/browser/service_worker/service_worker_storage_control_impl.cc +++ b/content/browser/service_worker/service_worker_storage_control_impl.cc
@@ -272,9 +272,7 @@ writer) { DCHECK_NE(resource_id, blink::mojom::kInvalidServiceWorkerResourceId); mojo::MakeSelfOwnedReceiver( - std::make_unique<ServiceWorkerResourceMetadataWriterImpl>( - storage_->CreateResponseMetadataWriter(resource_id)), - std::move(writer)); + storage_->CreateResourceMetadataWriter(resource_id), std::move(writer)); } void ServiceWorkerStorageControlImpl::StoreUncommittedResourceId(
diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index 5fa3aba..c9b332c 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc
@@ -8560,6 +8560,12 @@ }); } +void WebContentsImpl::MediaPlayerSeek(const MediaPlayerId& id) { + OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MediaPlayerSeek"); + observers_.ForEachObserver( + [&](WebContentsObserver* observer) { observer->MediaPlayerSeek(id); }); +} + void WebContentsImpl::MediaEffectivelyFullscreenChanged(bool is_fullscreen) { OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::MediaEffectivelyFullscreenChanged",
diff --git a/content/browser/web_contents/web_contents_impl.h b/content/browser/web_contents/web_contents_impl.h index a7e60496..a7fea8c 100644 --- a/content/browser/web_contents/web_contents_impl.h +++ b/content/browser/web_contents/web_contents_impl.h
@@ -1038,9 +1038,7 @@ bool SetDeviceEmulationSize(const gfx::Size& new_size); void ClearDeviceEmulationSize(); - AudioStreamMonitor* audio_stream_monitor() { - return &audio_stream_monitor_; - } + AudioStreamMonitor* audio_stream_monitor() { return &audio_stream_monitor_; } ForwardingAudioStreamFactory* GetAudioStreamFactory(); @@ -1062,6 +1060,9 @@ // WebContentsObserver function stubs for more details. void MediaBufferUnderflow(const MediaPlayerId& id); + // Called by MediaWebContentsObserver when player seek event occurs. + void MediaPlayerSeek(const MediaPlayerId& id); + int GetCurrentlyPlayingVideoCount() override; base::Optional<gfx::Size> GetFullscreenVideoSize() override;
diff --git a/content/common/media/media_player_delegate_messages.h b/content/common/media/media_player_delegate_messages.h index ab24603..f372c8b 100644 --- a/content/common/media/media_player_delegate_messages.h +++ b/content/common/media/media_player_delegate_messages.h
@@ -135,4 +135,7 @@ IPC_MESSAGE_ROUTED1(MediaPlayerDelegateHostMsg_OnBufferUnderflow, int /* delegate_id, distinguishes instances */) +IPC_MESSAGE_ROUTED1(MediaPlayerDelegateHostMsg_OnSeek, + int /* delegate_id, distinguishes instances */) + #endif // CONTENT_COMMON_MEDIA_MEDIA_PLAYER_DELEGATE_MESSAGES_H_
diff --git a/content/public/browser/web_contents_observer.h b/content/public/browser/web_contents_observer.h index ba438df..41c4e51 100644 --- a/content/public/browser/web_contents_observer.h +++ b/content/public/browser/web_contents_observer.h
@@ -582,6 +582,7 @@ virtual void MediaPictureInPictureChanged(bool is_picture_in_picture) {} virtual void MediaMutedStatusChanged(const MediaPlayerId& id, bool muted) {} virtual void MediaBufferUnderflow(const MediaPlayerId& id) {} + virtual void MediaPlayerSeek(const MediaPlayerId& id) {} // Invoked when the renderer process changes the page scale factor. virtual void OnPageScaleFactorChanged(float page_scale_factor) {}
diff --git a/content/renderer/accessibility/render_accessibility_impl.cc b/content/renderer/accessibility/render_accessibility_impl.cc index 50be3f15..2b28908 100644 --- a/content/renderer/accessibility/render_accessibility_impl.cc +++ b/content/renderer/accessibility/render_accessibility_impl.cc
@@ -848,7 +848,7 @@ // "ParentObject()" always gets the first ancestor that is included in tree // (ignored or unignored), so it will never return objects that are not // included in the tree at all. - if (!obj.AccessibilityIsIncludedInTree()) + if (!obj.IsDetached() && !obj.AccessibilityIsIncludedInTree()) obj = obj.ParentObject(); for (; !obj.IsDetached() && obj.AccessibilityIsIgnored(); obj = obj.ParentObject()) {
diff --git a/content/renderer/media/renderer_webmediaplayer_delegate.cc b/content/renderer/media/renderer_webmediaplayer_delegate.cc index e3f5192..e734cbd 100644 --- a/content/renderer/media/renderer_webmediaplayer_delegate.cc +++ b/content/renderer/media/renderer_webmediaplayer_delegate.cc
@@ -239,6 +239,17 @@ Send(new MediaPlayerDelegateHostMsg_OnBufferUnderflow(routing_id(), player_id)); } + +void RendererWebMediaPlayerDelegate::DidSeek(int player_id) { + // Send the seek updates to delegate only once per second. + if (last_seek_update_time_.is_null() || + (base::TimeTicks::Now() - last_seek_update_time_ >= + base::TimeDelta::FromSeconds(1))) { + last_seek_update_time_ = base::TimeTicks::Now(); + Send(new MediaPlayerDelegateHostMsg_OnSeek(routing_id(), player_id)); + } +} + void RendererWebMediaPlayerDelegate::WasHidden() { RecordAction(base::UserMetricsAction("Media.Hidden"));
diff --git a/content/renderer/media/renderer_webmediaplayer_delegate.h b/content/renderer/media/renderer_webmediaplayer_delegate.h index a2705031..b9c00dd9 100644 --- a/content/renderer/media/renderer_webmediaplayer_delegate.h +++ b/content/renderer/media/renderer_webmediaplayer_delegate.h
@@ -76,6 +76,7 @@ const std::string& hashed_device_id) override; void DidDisableAudioOutputSinkChanges(int delegate_id) override; void DidBufferUnderflow(int player_id) override; + void DidSeek(int player_id) override; // content::RenderFrameObserver overrides. void WasHidden() override; @@ -167,6 +168,9 @@ base::TimeTicks background_video_start_time_; #endif // OS_ANDROID + // Keeps track of when the player seek event was sent to the delegate. + base::TimeTicks last_seek_update_time_; + // Players with a video track. base::flat_set<int> players_with_video_;
diff --git a/content/test/gpu/gpu_tests/test_expectations/pixel_expectations.txt b/content/test/gpu/gpu_tests/test_expectations/pixel_expectations.txt index 4e8a6bc..e889ab0 100644 --- a/content/test/gpu/gpu_tests/test_expectations/pixel_expectations.txt +++ b/content/test/gpu/gpu_tests/test_expectations/pixel_expectations.txt
@@ -75,6 +75,7 @@ crbug.com/1115673 [ fuchsia ] Pixel_CanvasLowLatencyWebGLDrawImage [ Skip ] crbug.com/1115673 [ fuchsia ] Pixel_CanvasLowLatencyWebGLRoundedCorners [ Skip ] crbug.com/1115673 [ fuchsia ] Pixel_CanvasLowLatencyWebGLOccluded [ Skip ] +crbug.com/1136742 [ fuchsia no-use-skia-dawn ] Pixel_WebGLTransparentGreenTriangle_NoAlpha_ImplicitClear [ RetryOnFailure ] # Tests running with SwiftShader are skipped on platforms where SwiftShader # isn't supported.
diff --git a/device/bluetooth/public/mojom/BUILD.gn b/device/bluetooth/public/mojom/BUILD.gn index a822923..4278f46 100644 --- a/device/bluetooth/public/mojom/BUILD.gn +++ b/device/bluetooth/public/mojom/BUILD.gn
@@ -62,6 +62,6 @@ "//chrome/browser/ui/webui/bluetooth_internals:*", # Nearby Sharing feature - "//chrome/services/sharing/public/mojom:*", + "//chromeos/services/nearby/public/mojom:*", ] }
diff --git a/extensions/browser/api/serial/serial_api.cc b/extensions/browser/api/serial/serial_api.cc index 62757dd..3ac46c9 100644 --- a/extensions/browser/api/serial/serial_api.cc +++ b/extensions/browser/api/serial/serial_api.cc
@@ -142,12 +142,8 @@ auto* manager = SerialPortManager::Get(browser_context()); DCHECK(manager); - mojo::PendingRemote<device::mojom::SerialPort> serial_port; - manager->GetPort(params->path, serial_port.InitWithNewPipeAndPassReceiver()); - - connection_ = std::make_unique<SerialConnection>(extension_->id(), - std::move(serial_port)); - connection_->Open(*params->options, + connection_ = std::make_unique<SerialConnection>(extension_->id()); + connection_->Open(manager, params->path, *params->options, base::BindOnce(&SerialConnectFunction::OnConnected, this)); return RespondLater(); }
diff --git a/extensions/browser/api/serial/serial_apitest.cc b/extensions/browser/api/serial/serial_apitest.cc index d14c9a9..5ce25af 100644 --- a/extensions/browser/api/serial/serial_apitest.cc +++ b/extensions/browser/api/serial/serial_apitest.cc
@@ -77,29 +77,27 @@ ~FakeSerialPort() override = default; - const device::mojom::SerialPortInfo& info() { return *info_; } + mojo::PendingRemote<device::mojom::SerialPort> Open( + device::mojom::SerialConnectionOptionsPtr options, + mojo::PendingRemote<device::mojom::SerialPortClient> client) { + if (receiver_.is_bound()) { + // Port is already open. + return mojo::NullRemote(); + } - void Bind(mojo::PendingReceiver<device::mojom::SerialPort> receiver) { - receivers_.Add(this, std::move(receiver)); + DCHECK(!client_.is_bound()); + DCHECK(client.is_valid()); + client_.Bind(std::move(client)); + + DoConfigurePort(*options); + + return receiver_.BindNewPipeAndPassRemote(); } + const device::mojom::SerialPortInfo& info() { return *info_; } + private: // device::mojom::SerialPort methods: - void Open(device::mojom::SerialConnectionOptionsPtr options, - mojo::PendingRemote<device::mojom::SerialPortClient> client, - OpenCallback callback) override { - if (client_) { - // Port is already open. - std::move(callback).Run(false); - return; - } - - DoConfigurePort(*options); - DCHECK(client); - client_.Bind(std::move(client)); - std::move(callback).Run(true); - } - void StartWriting(mojo::ScopedDataPipeConsumerHandle consumer) override { if (in_stream_) return; @@ -172,6 +170,7 @@ out_stream_.reset(); client_.reset(); std::move(callback).Run(); + receiver_.reset(); } void DoWrite(MojoResult result, const mojo::HandleSignalsState& state) { @@ -269,7 +268,7 @@ } device::mojom::SerialPortInfoPtr info_; - mojo::ReceiverSet<device::mojom::SerialPort> receivers_; + mojo::Receiver<device::mojom::SerialPort> receiver_{this}; // Currently applied connection options. device::mojom::SerialConnectionOptions options_; @@ -312,15 +311,18 @@ std::move(callback).Run(std::move(ports)); } - void GetPort(const base::UnguessableToken& token, - bool use_alternate_path, - mojo::PendingReceiver<device::mojom::SerialPort> receiver, - mojo::PendingRemote<device::mojom::SerialPortConnectionWatcher> - watcher) override { + void OpenPort( + const base::UnguessableToken& token, + bool use_alternate_path, + device::mojom::SerialConnectionOptionsPtr options, + mojo::PendingRemote<device::mojom::SerialPortClient> client, + mojo::PendingRemote<device::mojom::SerialPortConnectionWatcher> watcher, + OpenPortCallback callback) override { DCHECK(!watcher); auto it = ports_.find(token); DCHECK(it != ports_.end()); - it->second->Bind(std::move(receiver)); + std::move(callback).Run( + it->second->Open(std::move(options), std::move(client))); } void AddPort(const base::FilePath& path) {
diff --git a/extensions/browser/api/serial/serial_connection.cc b/extensions/browser/api/serial/serial_connection.cc index 465f0abc..207f8394 100644 --- a/extensions/browser/api/serial/serial_connection.cc +++ b/extensions/browser/api/serial/serial_connection.cc
@@ -16,6 +16,7 @@ #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "extensions/browser/api/api_resource_manager.h" +#include "extensions/browser/api/serial/serial_port_manager.h" #include "extensions/common/api/serial.h" #include "mojo/public/cpp/bindings/callback_helpers.h" #include "mojo/public/cpp/bindings/pending_remote.h" @@ -159,9 +160,7 @@ return g_factory.Pointer(); } -SerialConnection::SerialConnection( - const std::string& owner_extension_id, - mojo::PendingRemote<device::mojom::SerialPort> serial_port) +SerialConnection::SerialConnection(const std::string& owner_extension_id) : ApiResource(owner_extension_id), persistent_(false), buffer_size_(kDefaultBufferSize), @@ -170,13 +169,9 @@ paused_(true), read_error_(base::nullopt), bytes_written_(0), - serial_port_(std::move(serial_port)), receive_pipe_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL), send_pipe_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL) { - DCHECK(serial_port_); - serial_port_.set_disconnect_handler(base::BindOnce( - &SerialConnection::OnConnectionError, base::Unretained(this))); } SerialConnection::~SerialConnection() {} @@ -227,9 +222,11 @@ connection_error_handler_ = std::move(connection_error_handler); } -void SerialConnection::Open(const api::serial::ConnectionOptions& options, +void SerialConnection::Open(api::SerialPortManager* port_manager, + const std::string& path, + const api::serial::ConnectionOptions& options, OpenCompleteCallback callback) { - DCHECK(serial_port_); + DCHECK(!serial_port_); DCHECK(!send_pipe_); DCHECK(!receive_pipe_); @@ -246,12 +243,13 @@ mojo::PendingRemote<device::mojom::SerialPortClient> client; auto client_receiver = client.InitWithNewPipeAndPassReceiver(); - serial_port_->Open( - device::mojom::SerialConnectionOptions::From(options), std::move(client), + port_manager->OpenPort( + path, device::mojom::SerialConnectionOptions::From(options), + std::move(client), mojo::WrapCallbackWithDefaultInvokeIfNotRun( base::BindOnce(&SerialConnection::OnOpen, weak_factory_.GetWeakPtr(), std::move(client_receiver), std::move(callback)), - false)); + mojo::NullRemote())); } void SerialConnection::CreatePipe( @@ -323,12 +321,16 @@ void SerialConnection::OnOpen( mojo::PendingReceiver<device::mojom::SerialPortClient> client_receiver, OpenCompleteCallback callback, - bool success) { - if (!success) { + mojo::PendingRemote<device::mojom::SerialPort> serial_port) { + if (!serial_port.is_valid()) { std::move(callback).Run(false); return; } + serial_port_.Bind(std::move(serial_port)); + serial_port_.set_disconnect_handler(base::BindOnce( + &SerialConnection::OnConnectionError, base::Unretained(this))); + SetUpReceiveDataPipe(); SetUpSendDataPipe(); client_receiver_.Bind(std::move(client_receiver)); @@ -519,6 +521,10 @@ mojo::WrapCallbackWithDefaultInvokeIfNotRun(std::move(callback))); } +void SerialConnection::InitSerialPortForTesting() { + ignore_result(serial_port_.BindNewPipeAndPassReceiver()); +} + void SerialConnection::SetTimeoutCallback() { if (receive_timeout_ > 0) { receive_timeout_task_.Reset(base::Bind(&SerialConnection::OnReceiveTimeout,
diff --git a/extensions/browser/api/serial/serial_connection.h b/extensions/browser/api/serial/serial_connection.h index 421ef66..50b941a 100644 --- a/extensions/browser/api/serial/serial_connection.h +++ b/extensions/browser/api/serial/serial_connection.h
@@ -31,6 +31,10 @@ namespace extensions { +namespace api { +class SerialPortManager; +} + // Encapsulates an mojo interface ptr of device::mojom::SerialPort, which // corresponds with an open serial port in remote side(Device Service). NOTE: // Instances of this object should only be constructed on the IO thread, and all @@ -38,7 +42,7 @@ class SerialConnection : public ApiResource, public device::mojom::SerialPortClient { public: - using OpenCompleteCallback = device::mojom::SerialPort::OpenCallback; + using OpenCompleteCallback = base::OnceCallback<void(bool)>; using GetInfoCompleteCallback = base::OnceCallback<void(bool, std::unique_ptr<api::serial::ConnectionInfo>)>; @@ -67,8 +71,7 @@ using SetControlSignalsCompleteCallback = device::mojom::SerialPort::SetControlSignalsCallback; - SerialConnection(const std::string& owner_extension_id, - mojo::PendingRemote<device::mojom::SerialPort> serial_port); + explicit SerialConnection(const std::string& owner_extension_id); ~SerialConnection() override; // ApiResource override. @@ -97,7 +100,9 @@ // Initiates an asynchronous Open of the device. It is the caller's // responsibility to ensure that this SerialConnection stays alive // until |callback| is run. - virtual void Open(const api::serial::ConnectionOptions& options, + virtual void Open(api::SerialPortManager* port_manager, + const std::string& path, + const api::serial::ConnectionOptions& options, OpenCompleteCallback callback); // Begins an asynchronous send operation. Calling this while a Send @@ -138,6 +143,11 @@ static const BrowserThread::ID kThreadId = BrowserThread::UI; + protected: + // Initializes |serial_port_| with a disconnected Mojo pipe for testing + // purposes. + void InitSerialPortForTesting(); + private: friend class ApiResourceManager<SerialConnection>; static const char* service_name() { return "SerialConnectionManager"; } @@ -149,7 +159,7 @@ void OnOpen( mojo::PendingReceiver<device::mojom::SerialPortClient> client_receiver, OpenCompleteCallback callback, - bool success); + mojo::PendingRemote<device::mojom::SerialPort> serial_port); // Read data from |receive_pipe_| when the data is ready or dispatch error // events in error cases.
diff --git a/extensions/browser/api/serial/serial_port_manager.cc b/extensions/browser/api/serial/serial_port_manager.cc index 9ef4614..0505494 100644 --- a/extensions/browser/api/serial/serial_port_manager.cc +++ b/extensions/browser/api/serial/serial_port_manager.cc
@@ -80,14 +80,16 @@ port_manager_->GetDevices(std::move(callback)); } -void SerialPortManager::GetPort( +void SerialPortManager::OpenPort( const std::string& path, - mojo::PendingReceiver<device::mojom::SerialPort> receiver) { + device::mojom::SerialConnectionOptionsPtr options, + mojo::PendingRemote<device::mojom::SerialPortClient> client, + OpenPortCallback callback) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); EnsureConnection(); - port_manager_->GetDevices( - base::BindOnce(&SerialPortManager::OnGotDevicesToGetPort, - weak_factory_.GetWeakPtr(), path, std::move(receiver))); + port_manager_->GetDevices(base::BindOnce( + &SerialPortManager::OnGotDevicesToGetPort, weak_factory_.GetWeakPtr(), + path, std::move(options), std::move(client), std::move(callback))); } void SerialPortManager::StartConnectionPolling(const std::string& extension_id, @@ -183,24 +185,28 @@ void SerialPortManager::OnGotDevicesToGetPort( const std::string& path, - mojo::PendingReceiver<device::mojom::SerialPort> receiver, + device::mojom::SerialConnectionOptionsPtr options, + mojo::PendingRemote<device::mojom::SerialPortClient> client, + OpenPortCallback callback, std::vector<device::mojom::SerialPortInfoPtr> devices) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); for (auto& device : devices) { if (device->path.AsUTF8Unsafe() == path) { - port_manager_->GetPort(device->token, /*use_alternate_path=*/false, - std::move(receiver), - /*watcher=*/mojo::NullRemote()); + port_manager_->OpenPort(device->token, /*use_alternate_path=*/false, + std::move(options), std::move(client), + /*watcher=*/mojo::NullRemote(), + std::move(callback)); return; } #if defined(OS_MAC) if (device->alternate_path && device->alternate_path->AsUTF8Unsafe() == path) { - port_manager_->GetPort(device->token, /*use_alternate_path=*/true, - std::move(receiver), - /*watcher=*/mojo::NullRemote()); + port_manager_->OpenPort(device->token, /*use_alternate_path=*/true, + std::move(options), std::move(client), + /*watcher=*/mojo::NullRemote(), + std::move(callback)); return; } #endif // defined(OS_MAC)
diff --git a/extensions/browser/api/serial/serial_port_manager.h b/extensions/browser/api/serial/serial_port_manager.h index 912a3dc7..78f46874 100644 --- a/extensions/browser/api/serial/serial_port_manager.h +++ b/extensions/browser/api/serial/serial_port_manager.h
@@ -32,6 +32,9 @@ // Per-browser-context dispatcher for events on serial connections. class SerialPortManager : public BrowserContextKeyedAPI { public: + using OpenPortCallback = + base::OnceCallback<void(mojo::PendingRemote<device::mojom::SerialPort>)>; + static SerialPortManager* Get(content::BrowserContext* context); // BrowserContextKeyedAPI implementation. @@ -42,9 +45,10 @@ void GetDevices( device::mojom::SerialPortManager::GetDevicesCallback callback); - - void GetPort(const std::string& path, - mojo::PendingReceiver<device::mojom::SerialPort> receiver); + void OpenPort(const std::string& path, + device::mojom::SerialConnectionOptionsPtr options, + mojo::PendingRemote<device::mojom::SerialPortClient> client, + OpenPortCallback callback); // Start the poilling process for the connection. void StartConnectionPolling(const std::string& extension_id, @@ -84,7 +88,9 @@ void EnsureConnection(); void OnGotDevicesToGetPort( const std::string& path, - mojo::PendingReceiver<device::mojom::SerialPort> receiver, + device::mojom::SerialConnectionOptionsPtr options, + mojo::PendingRemote<device::mojom::SerialPortClient> client, + OpenPortCallback callback, std::vector<device::mojom::SerialPortInfoPtr> devices); void OnPortManagerConnectionError();
diff --git a/extensions/browser/api/webcam_private/visca_webcam.cc b/extensions/browser/api/webcam_private/visca_webcam.cc index 169c4c1..550a5edf 100644 --- a/extensions/browser/api/webcam_private/visca_webcam.cc +++ b/extensions/browser/api/webcam_private/visca_webcam.cc
@@ -158,7 +158,8 @@ ViscaWebcam::~ViscaWebcam() = default; void ViscaWebcam::Open(const std::string& extension_id, - mojo::PendingRemote<device::mojom::SerialPort> port, + api::SerialPortManager* port_manager, + const std::string& path, const OpenCompleteCallback& open_callback) { api::serial::ConnectionOptions options; @@ -174,11 +175,11 @@ options.parity_bit = api::serial::PARITY_BIT_NO; options.stop_bits = api::serial::STOP_BITS_ONE; - serial_connection_ = - std::make_unique<SerialConnection>(extension_id, std::move(port)); + serial_connection_ = std::make_unique<SerialConnection>(extension_id); serial_connection_->Open( - options, base::BindOnce(&ViscaWebcam::OnConnected, base::Unretained(this), - open_callback)); + port_manager, path, options, + base::BindOnce(&ViscaWebcam::OnConnected, base::Unretained(this), + open_callback)); } void ViscaWebcam::OnConnected(const OpenCompleteCallback& open_callback,
diff --git a/extensions/browser/api/webcam_private/visca_webcam.h b/extensions/browser/api/webcam_private/visca_webcam.h index b445432..358eedd 100644 --- a/extensions/browser/api/webcam_private/visca_webcam.h +++ b/extensions/browser/api/webcam_private/visca_webcam.h
@@ -33,7 +33,8 @@ // command buffer. After these three steps completes, |open_callback| will be // called. void Open(const std::string& extension_id, - mojo::PendingRemote<device::mojom::SerialPort> port, + api::SerialPortManager* port_manager, + const std::string& path, const OpenCompleteCallback& open_callback); private:
diff --git a/extensions/browser/api/webcam_private/visca_webcam_unittest.cc b/extensions/browser/api/webcam_private/visca_webcam_unittest.cc index 1e47351d..e7209b2 100644 --- a/extensions/browser/api/webcam_private/visca_webcam_unittest.cc +++ b/extensions/browser/api/webcam_private/visca_webcam_unittest.cc
@@ -19,9 +19,9 @@ class TestSerialConnection : public SerialConnection { public: - explicit TestSerialConnection( - mojo::PendingRemote<device::mojom::SerialPort> port) - : SerialConnection("dummy_id", std::move(port)) {} + explicit TestSerialConnection() : SerialConnection("dummy_id") { + InitSerialPortForTesting(); + } ~TestSerialConnection() override {} void SetReceiveBuffer(const std::vector<uint8_t>& receive_buffer) { @@ -35,7 +35,9 @@ private: // SerialConnection: - void Open(const api::serial::ConnectionOptions& options, + void Open(api::SerialPortManager* port_manager, + const std::string& path, + const api::serial::ConnectionOptions& options, OpenCompleteCallback callback) override { NOTREACHED(); } @@ -104,11 +106,8 @@ class ViscaWebcamTest : public testing::Test { protected: ViscaWebcamTest() { - mojo::PendingRemote<device::mojom::SerialPort> port; - ignore_result(port.InitWithNewPipeAndPassReceiver()); webcam_ = new ViscaWebcam; - webcam_->OpenForTesting( - std::make_unique<TestSerialConnection>(std::move(port))); + webcam_->OpenForTesting(std::make_unique<TestSerialConnection>()); } ~ViscaWebcamTest() override {}
diff --git a/extensions/browser/api/webcam_private/webcam_private_api_chromeos.cc b/extensions/browser/api/webcam_private/webcam_private_api_chromeos.cc index 3ad5dd1..d5eaa6b0 100644 --- a/extensions/browser/api/webcam_private/webcam_private_api_chromeos.cc +++ b/extensions/browser/api/webcam_private/webcam_private_api_chromeos.cc
@@ -92,10 +92,9 @@ mojo::PendingRemote<device::mojom::SerialPort> port; auto* port_manager = api::SerialPortManager::Get(browser_context_); DCHECK(port_manager); - port_manager->GetPort(device_path, port.InitWithNewPipeAndPassReceiver()); auto visca_webcam = base::MakeRefCounted<ViscaWebcam>(); - visca_webcam->Open(extension_id, std::move(port), + visca_webcam->Open(extension_id, port_manager, device_path, base::Bind(&WebcamPrivateAPI::OnOpenSerialWebcam, weak_ptr_factory_.GetWeakPtr(), extension_id, device_path, visca_webcam, callback));
diff --git a/extensions/browser/state_store.cc b/extensions/browser/state_store.cc index c27e2ce..d6e844b 100644 --- a/extensions/browser/state_store.cc +++ b/extensions/browser/state_store.cc
@@ -135,6 +135,18 @@ observers_.RemoveObserver(observer); } +void StateStore::FlushForTesting(base::OnceClosure flushed_callback) { + // Look up a key in the database. This serves as a roundtrip to the DB and + // back; the value of the key doesn't matter. + GetExtensionValue("fake_id", "fake_key", + base::BindOnce( + [](base::OnceClosure flushed_callback, + std::unique_ptr<base::Value> ignored) { + std::move(flushed_callback).Run(); + }, + std::move(flushed_callback))); +} + bool StateStore::IsInitialized() const { return task_queue_->ready(); }
diff --git a/extensions/browser/state_store.h b/extensions/browser/state_store.h index db881ac..64434d0c 100644 --- a/extensions/browser/state_store.h +++ b/extensions/browser/state_store.h
@@ -8,6 +8,7 @@ #include <set> #include <string> +#include "base/callback.h" #include "base/files/file_path.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" @@ -82,6 +83,10 @@ void AddObserver(TestObserver* observer); void RemoveObserver(TestObserver* observer); + // Flushes the state store (finishes any pending reads and writes). Should + // only be used for testing. Invokes |flushed_callback| upon completion. + void FlushForTesting(base::OnceClosure flushed_callback); + private: class DelayedTaskQueue;
diff --git a/extensions/browser/updater/extension_downloader_delegate.h b/extensions/browser/updater/extension_downloader_delegate.h index 2e3308b..271b8185 100644 --- a/extensions/browser/updater/extension_downloader_delegate.h +++ b/extensions/browser/updater/extension_downloader_delegate.h
@@ -107,9 +107,14 @@ // Passes as an argument to OnExtensionDownloadCacheStatusRetrieved to inform // delegate about cache status. - // Note: enum used for UMA. Do NOT reorder or remove entries. Don't forget to - // update enums.xml (name: ExtensionInstallationCacheStatus) when adding new + // Note: enum used for UMA. Do NOT reorder or remove entries. + // 1) Don't forget to update enums.xml (name: + // ExtensionInstallationDownloadingCacheStatus) when adding new entries. + // 2) Don't forget to update device_management_backend.proto (name: + // ExtensionInstallReportLogEvent::DownloadCacheStatus) when adding new // entries. + // 3) Don't forget to update ConvertDownloadCacheStatusToProto method in + // ExtensionInstallEventLogCollector. enum class CacheStatus { // No information about cache status. This is never reported by // ExtensionDownloader, but may be used later in statistics.
diff --git a/extensions/common/manifest_handlers/csp_info.cc b/extensions/common/manifest_handlers/csp_info.cc index 98a8671..2b6cb61 100644 --- a/extensions/common/manifest_handlers/csp_info.cc +++ b/extensions/common/manifest_handlers/csp_info.cc
@@ -11,10 +11,8 @@ #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" -#include "components/version_info/channel.h" #include "extensions/common/csp_validator.h" #include "extensions/common/error_utils.h" -#include "extensions/common/features/feature_channel.h" #include "extensions/common/install_warning.h" #include "extensions/common/manifest_constants.h" #include "extensions/common/manifest_handlers/sandboxed_page_info.h" @@ -177,29 +175,16 @@ // "extension_pages": "", // "sandbox": "", // } + // The dictionary is supported (and mandated) for manifest v3 (and above) + // extensions. const base::Value* csp = GetManifestPath(extension, key); - - // TODO(karandeepb): Remove the channel check since we don't plan to support - // the CSP dictionary for Manifest V2. - bool csp_dictionary_supported = - extension->GetType() == Manifest::TYPE_EXTENSION && - (extension->manifest_version() >= 3 || - GetCurrentChannel() == version_info::Channel::UNKNOWN); - - if (csp_dictionary_supported) { - // CSP key as dictionary is mandatory for manifest v3 (and above) - // extensions. - if (extension->manifest_version() >= 3) { - if (csp && !csp->is_dict()) { - *error = GetInvalidManifestKeyError(key); - return false; - } - return ParseCSPDictionary(extension, error); + bool parse_as_dictionary = extension->manifest_version() >= 3; + if (parse_as_dictionary) { + if (csp && !csp->is_dict()) { + *error = GetInvalidManifestKeyError(key); + return false; } - - // CSP key as dictionary is optional for manifest v2 extensions. - if (csp && csp->is_dict()) - return ParseCSPDictionary(extension, error); + return ParseCSPDictionary(extension, error); } if (!ParseExtensionPagesCSP(extension, error, key, false /* secure_only */,
diff --git a/extensions/common/manifest_handlers/csp_info_unittest.cc b/extensions/common/manifest_handlers/csp_info_unittest.cc index 46e706d..a88d88b 100644 --- a/extensions/common/manifest_handlers/csp_info_unittest.cc +++ b/extensions/common/manifest_handlers/csp_info_unittest.cc
@@ -131,55 +131,33 @@ "worker-src 'self'; script-src; default-src 'self'"}, {"csp_empty_dictionary_valid.json", kDefaultSecureCSP}}; - // Verify that keys::kContentSecurityPolicy key can be used as a dictionary on - // trunk. - { - ScopedCurrentChannel channel(version_info::Channel::UNKNOWN); - for (const auto& test_case : cases) { - SCOPED_TRACE( - base::StringPrintf("%s on channel %s", test_case.file_name, "trunk")); - scoped_refptr<Extension> extension = - LoadAndExpectSuccess(test_case.file_name); - ASSERT_TRUE(extension.get()); - EXPECT_EQ(test_case.csp, CSPInfo::GetExtensionPagesCSP(extension.get())); - } + for (const auto& test_case : cases) { + SCOPED_TRACE(base::StringPrintf("Testing %s.", test_case.file_name)); + scoped_refptr<Extension> extension = + LoadAndExpectSuccess(test_case.file_name); + ASSERT_TRUE(extension.get()); + EXPECT_EQ(test_case.csp, CSPInfo::GetExtensionPagesCSP(extension.get())); } - // Verify that keys::kContentSecurityPolicy key can't be used as a dictionary - // on Stable. - { - ScopedCurrentChannel channel(version_info::Channel::STABLE); - for (const auto& test_case : cases) { - SCOPED_TRACE(base::StringPrintf("%s on channel %s", test_case.file_name, - "stable")); - LoadAndExpectError( - test_case.file_name, - GetInvalidManifestKeyError(keys::kContentSecurityPolicy)); - } - } - - { - ScopedCurrentChannel channel(version_info::Channel::UNKNOWN); - Testcase testcases[] = { - Testcase("csp_invalid_2.json", - GetInvalidManifestKeyError( - keys::kContentSecurityPolicy_ExtensionPagesPath)), - Testcase("csp_invalid_3.json", - GetInvalidManifestKeyError( - keys::kContentSecurityPolicy_ExtensionPagesPath)), - Testcase( - "csp_missing_src.json", - ErrorUtils::FormatErrorMessage( - errors::kInvalidCSPMissingSecureSrc, - keys::kContentSecurityPolicy_ExtensionPagesPath, "script-src")), - Testcase("csp_insecure_src.json", - ErrorUtils::FormatErrorMessage( - errors::kInvalidCSPInsecureValueError, - keys::kContentSecurityPolicy_ExtensionPagesPath, - "'unsafe-eval'", "worker-src")), - }; - RunTestcases(testcases, base::size(testcases), EXPECT_TYPE_ERROR); - } + Testcase testcases[] = { + Testcase("csp_invalid_2.json", + GetInvalidManifestKeyError( + keys::kContentSecurityPolicy_ExtensionPagesPath)), + Testcase("csp_invalid_3.json", + GetInvalidManifestKeyError( + keys::kContentSecurityPolicy_ExtensionPagesPath)), + Testcase( + "csp_missing_src.json", + ErrorUtils::FormatErrorMessage( + errors::kInvalidCSPMissingSecureSrc, + keys::kContentSecurityPolicy_ExtensionPagesPath, "script-src")), + Testcase("csp_insecure_src.json", + ErrorUtils::FormatErrorMessage( + errors::kInvalidCSPInsecureValueError, + keys::kContentSecurityPolicy_ExtensionPagesPath, + "'unsafe-eval'", "worker-src")), + }; + RunTestcases(testcases, base::size(testcases), EXPECT_TYPE_ERROR); } TEST_F(CSPInfoUnitTest, CSPDictionary_Sandbox) { @@ -251,4 +229,10 @@ } } +// Ensure the CSP dictionary is disallowed for mv2 extensions. +TEST_F(CSPInfoUnitTest, CSPDictionaryDisallowedForV2) { + LoadAndExpectError("csp_dictionary_mv2.json", + GetInvalidManifestKeyError(keys::kContentSecurityPolicy)); +} + } // namespace extensions
diff --git a/extensions/common/manifest_handlers/webview_info.cc b/extensions/common/manifest_handlers/webview_info.cc index 16b7c015..6f57fa99 100644 --- a/extensions/common/manifest_handlers/webview_info.cc +++ b/extensions/common/manifest_handlers/webview_info.cc
@@ -176,11 +176,37 @@ errors::kInvalidWebviewAccessibleResource, base::NumberToString(i)); return false; } - partition_item->AddPattern( - URLPattern(URLPattern::SCHEME_EXTENSION, - Extension::GetResourceURL(extension->url(), - url_list_view[i].GetString()) - .spec())); + + GURL pattern_url = Extension::GetResourceURL( + extension->url(), url_list_view[i].GetString()); + // If passed a non-relative URL (like http://example.com), + // Extension::GetResourceURL() will return that URL directly. (See + // https://crbug.com/1135236). Check if this happened by comparing the + // host. + if (pattern_url.host_piece() != extension->id()) { + // NOTE: Warning instead of error because there are existing apps that + // have this bug, and we don't want to hard-error on them. + // https://crbug.com/856948. + std::string warning = ErrorUtils::FormatErrorMessage( + errors::kInvalidWebviewAccessibleResource, base::NumberToString(i)); + extension->AddInstallWarning( + InstallWarning(std::move(warning), keys::kWebview)); + continue; + } + URLPattern pattern(URLPattern::SCHEME_EXTENSION); + if (pattern.Parse(pattern_url.spec()) != + URLPattern::ParseResult::kSuccess) { + // NOTE: Warning instead of error because there are existing apps that + // have this bug, and we don't want to hard-error on them. + // https://crbug.com/856948. + std::string warning = ErrorUtils::FormatErrorMessage( + errors::kInvalidWebviewAccessibleResource, base::NumberToString(i)); + extension->AddInstallWarning( + InstallWarning(std::move(warning), keys::kWebview)); + continue; + } + + partition_item->AddPattern(std::move(pattern)); } info->AddPartitionItem(std::move(partition_item)); }
diff --git a/extensions/test/data/manifest_tests/csp_dictionary_mv2.json b/extensions/test/data/manifest_tests/csp_dictionary_mv2.json new file mode 100644 index 0000000..d25a760e --- /dev/null +++ b/extensions/test/data/manifest_tests/csp_dictionary_mv2.json
@@ -0,0 +1,8 @@ +{ + "name": "test", + "version": "0.1", + "manifest_version": 2, + "content_security_policy": { + "extension_pages" : "default-src 'none'" + } +}
diff --git a/extensions/test/data/manifest_tests/csp_dictionary_valid_1.json b/extensions/test/data/manifest_tests/csp_dictionary_valid_1.json index d25a760e..a942d44 100644 --- a/extensions/test/data/manifest_tests/csp_dictionary_valid_1.json +++ b/extensions/test/data/manifest_tests/csp_dictionary_valid_1.json
@@ -1,7 +1,7 @@ { "name": "test", "version": "0.1", - "manifest_version": 2, + "manifest_version": 3, "content_security_policy": { "extension_pages" : "default-src 'none'" }
diff --git a/extensions/test/data/manifest_tests/csp_dictionary_valid_2.json b/extensions/test/data/manifest_tests/csp_dictionary_valid_2.json index 0176d232..14a477d 100644 --- a/extensions/test/data/manifest_tests/csp_dictionary_valid_2.json +++ b/extensions/test/data/manifest_tests/csp_dictionary_valid_2.json
@@ -1,7 +1,7 @@ { "name": "test", "version": "0.1", - "manifest_version": 2, + "manifest_version": 3, "content_security_policy": { "extension_pages" : "worker-src 'self'; script-src; default-src 'self'" }
diff --git a/extensions/test/data/manifest_tests/csp_empty_dictionary_valid.json b/extensions/test/data/manifest_tests/csp_empty_dictionary_valid.json index b937575..20b5189 100644 --- a/extensions/test/data/manifest_tests/csp_empty_dictionary_valid.json +++ b/extensions/test/data/manifest_tests/csp_empty_dictionary_valid.json
@@ -1,7 +1,7 @@ { "name": "test", "version": "0.1", - "manifest_version": 2, + "manifest_version": 3, "content_security_policy": { } }
diff --git a/extensions/test/data/manifest_tests/csp_insecure_src.json b/extensions/test/data/manifest_tests/csp_insecure_src.json index 7b1eb14..0d32bcfc 100644 --- a/extensions/test/data/manifest_tests/csp_insecure_src.json +++ b/extensions/test/data/manifest_tests/csp_insecure_src.json
@@ -1,7 +1,7 @@ { "name": "test", "version": "0.1", - "manifest_version": 2, + "manifest_version": 3, "content_security_policy": { "extension_pages" : "default-src 'none'; worker-src 'unsafe-eval';" }
diff --git a/extensions/test/data/manifest_tests/csp_invalid_2.json b/extensions/test/data/manifest_tests/csp_invalid_2.json index 302bfce8..0742675 100644 --- a/extensions/test/data/manifest_tests/csp_invalid_2.json +++ b/extensions/test/data/manifest_tests/csp_invalid_2.json
@@ -1,7 +1,7 @@ { "name": "test", "version": "0.1", - "manifest_version": 2, + "manifest_version": 3, "content_security_policy": { "extension_pages" : {} }
diff --git a/extensions/test/data/manifest_tests/csp_invalid_3.json b/extensions/test/data/manifest_tests/csp_invalid_3.json index 401518e0..f06437f 100644 --- a/extensions/test/data/manifest_tests/csp_invalid_3.json +++ b/extensions/test/data/manifest_tests/csp_invalid_3.json
@@ -1,7 +1,7 @@ { "name": "test", "version": "0.1", - "manifest_version": 2, + "manifest_version": 3, "content_security_policy": { "extension_pages" : "\r\n" }
diff --git a/extensions/test/data/manifest_tests/csp_missing_src.json b/extensions/test/data/manifest_tests/csp_missing_src.json index ac7c871..2ed5d824 100644 --- a/extensions/test/data/manifest_tests/csp_missing_src.json +++ b/extensions/test/data/manifest_tests/csp_missing_src.json
@@ -1,7 +1,7 @@ { "name": "test", "version": "0.1", - "manifest_version": 2, + "manifest_version": 3, "content_security_policy": { "extension_pages" : "" }
diff --git a/extensions/test/data/manifest_tests/sandbox_both_keys.json b/extensions/test/data/manifest_tests/sandbox_both_keys.json index 347809d..89760ec8 100644 --- a/extensions/test/data/manifest_tests/sandbox_both_keys.json +++ b/extensions/test/data/manifest_tests/sandbox_both_keys.json
@@ -1,7 +1,7 @@ { "name": "test", "version": "0.1", - "manifest_version": 2, + "manifest_version": 3, "sandbox": { "pages": ["test"], "content_security_policy": "sandbox;"
diff --git a/extensions/test/data/manifest_tests/sandbox_csp_with_dictionary.json b/extensions/test/data/manifest_tests/sandbox_csp_with_dictionary.json index 03b5ef9..b42f92a 100644 --- a/extensions/test/data/manifest_tests/sandbox_csp_with_dictionary.json +++ b/extensions/test/data/manifest_tests/sandbox_csp_with_dictionary.json
@@ -1,7 +1,7 @@ { "name": "test", "version": "0.1", - "manifest_version": 2, + "manifest_version": 3, "sandbox": { "pages": ["test"], "content_security_policy": "sandbox;"
diff --git a/extensions/test/data/manifest_tests/sandbox_dictionary_1.json b/extensions/test/data/manifest_tests/sandbox_dictionary_1.json index daa54d4..ee694a5 100644 --- a/extensions/test/data/manifest_tests/sandbox_dictionary_1.json +++ b/extensions/test/data/manifest_tests/sandbox_dictionary_1.json
@@ -1,7 +1,7 @@ { "name": "test", "version": "0.1", - "manifest_version": 2, + "manifest_version": 3, "sandbox": { "pages": ["test"] },
diff --git a/extensions/test/data/manifest_tests/sandbox_dictionary_2.json b/extensions/test/data/manifest_tests/sandbox_dictionary_2.json index 0c5fff5..b3702499 100644 --- a/extensions/test/data/manifest_tests/sandbox_dictionary_2.json +++ b/extensions/test/data/manifest_tests/sandbox_dictionary_2.json
@@ -1,7 +1,7 @@ { "name": "test", "version": "0.1", - "manifest_version": 2, + "manifest_version": 3, "sandbox": { "pages": ["test"] },
diff --git a/extensions/test/data/manifest_tests/sandbox_invalid_type.json b/extensions/test/data/manifest_tests/sandbox_invalid_type.json index 0f959d0..6f9f6ed 100644 --- a/extensions/test/data/manifest_tests/sandbox_invalid_type.json +++ b/extensions/test/data/manifest_tests/sandbox_invalid_type.json
@@ -1,7 +1,7 @@ { "name": "test", "version": "0.1", - "manifest_version": 2, + "manifest_version": 3, "sandbox": { "pages": ["test"] },
diff --git a/extensions/test/data/manifest_tests/unsandboxed_csp.json b/extensions/test/data/manifest_tests/unsandboxed_csp.json index 35d70e6..53846f6 100644 --- a/extensions/test/data/manifest_tests/unsandboxed_csp.json +++ b/extensions/test/data/manifest_tests/unsandboxed_csp.json
@@ -1,7 +1,7 @@ { "name": "test", "version": "0.1", - "manifest_version": 2, + "manifest_version": 3, "sandbox": { "pages": ["test"] },
diff --git a/fuchsia/engine/BUILD.gn b/fuchsia/engine/BUILD.gn index d1109dc8..3486d29 100644 --- a/fuchsia/engine/BUILD.gn +++ b/fuchsia/engine/BUILD.gn
@@ -349,7 +349,10 @@ "test_debug_listener.cc", "test_debug_listener.h", "web_engine_debug_integration_test.cc", + "web_engine_integration_logging_test.cc", "web_engine_integration_test.cc", + "web_engine_integration_test_base.cc", + "web_engine_integration_test_base.h", ] data = [ "test/data" ] deps = [
diff --git a/fuchsia/engine/browser/web_engine_net_log_observer.cc b/fuchsia/engine/browser/web_engine_net_log_observer.cc index c24b721..73c3223 100644 --- a/fuchsia/engine/browser/web_engine_net_log_observer.cc +++ b/fuchsia/engine/browser/web_engine_net_log_observer.cc
@@ -42,8 +42,8 @@ if (!log_path.empty()) { net::NetLogCaptureMode capture_mode = net::NetLogCaptureMode::kDefault; file_net_log_observer_ = net::FileNetLogObserver::CreateUnbounded( - log_path, GetWebEngineConstants()); - file_net_log_observer_->StartObserving(net::NetLog::Get(), capture_mode); + log_path, capture_mode, GetWebEngineConstants()); + file_net_log_observer_->StartObserving(net::NetLog::Get()); } }
diff --git a/fuchsia/engine/web_engine_integration_logging_test.cc b/fuchsia/engine/web_engine_integration_logging_test.cc new file mode 100644 index 0000000..5dc1be8 --- /dev/null +++ b/fuchsia/engine/web_engine_integration_logging_test.cc
@@ -0,0 +1,191 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <fuchsia/logger/cpp/fidl.h> + +#include <cstring> + +#include "base/fuchsia/fuchsia_logging.h" +#include "base/fuchsia/process_context.h" +#include "base/fuchsia/test_log_listener_safe.h" +#include "base/strings/string_piece.h" +#include "base/test/bind_test_util.h" +#include "fuchsia/base/context_provider_test_connector.h" +#include "fuchsia/base/frame_test_util.h" +#include "fuchsia/engine/web_engine_integration_test_base.h" + +namespace { + +constexpr char kLogTestPageFileName[] = "console_logging.html"; +constexpr char kWebEngineLogTag[] = "web_engine_exe"; +constexpr char kNormalizedLineNumber[] = "123"; +constexpr char kNormalizedPortNumber[] = "456"; + +} // namespace + +class WebEngineIntegrationLoggingTest : public WebEngineIntegrationTestBase { + protected: + WebEngineIntegrationLoggingTest() + : WebEngineIntegrationTestBase(), + isolated_archivist_service_dir_( + StartIsolatedArchivist(archivist_controller_.NewRequest())), + binding_(&test_log_listener_) {} + + void SetUp() override { + WebEngineIntegrationTestBase::SetUp(); + StartWebEngineForLoggingTest( + base::CommandLine(base::CommandLine::NO_PROGRAM)); + + logger_ = isolated_archivist_service_dir_.Connect<fuchsia::logger::Log>(); + logger_.set_error_handler([&](zx_status_t status) { + ZX_LOG(ERROR, status) << "fuchsia.logger.Log disconnected"; + ADD_FAILURE(); + wait_for_message_loop_.Quit(); + }); + } + + // Starts WebEngine without redirecting its logs. + void StartWebEngineForLoggingTest(base::CommandLine command_line) { + web_context_provider_ = cr_fuchsia::ConnectContextProviderForLoggingTest( + web_engine_controller_.NewRequest(), std::move(command_line)); + web_context_provider_.set_error_handler( + [](zx_status_t status) { ADD_FAILURE(); }); + } + + // Starts an isolated instance of Archivist to receive and dump log statements + // via the fuchsia.logger.Log* APIs. + fidl::InterfaceHandle<fuchsia::io::Directory> StartIsolatedArchivist( + fidl::InterfaceRequest<fuchsia::sys::ComponentController> + component_controller_request) { + const char kArchivistUrl[] = + "fuchsia-pkg://fuchsia.com/archivist-for-embedding#meta/" + "archivist-for-embedding.cmx"; + + fuchsia::sys::LaunchInfo launch_info; + launch_info.url = kArchivistUrl; + + fidl::InterfaceHandle<fuchsia::io::Directory> archivist_services_dir; + launch_info.directory_request = + archivist_services_dir.NewRequest().TakeChannel(); + + auto launcher = base::ComponentContextForProcess() + ->svc() + ->Connect<fuchsia::sys::Launcher>(); + launcher->CreateComponent(std::move(launch_info), + std::move(component_controller_request)); + + return archivist_services_dir; + } + + // Returns a CreateContextParams that has an isolated LogSink service from + // |isolated_archivist_service_dir_|. + fuchsia::web::CreateContextParams ContextParamsWithIsolatedLogSink() { + // Use a FilteredServiceDirectory in order to inject an isolated service. + fuchsia::web::CreateContextParams create_params = + ContextParamsWithFilteredServiceDirectory(); + + EXPECT_EQ(filtered_service_directory_->outgoing_directory() + ->RemovePublicService<fuchsia::logger::LogSink>(), + ZX_OK); + + EXPECT_EQ( + filtered_service_directory_->outgoing_directory()->AddPublicService( + std::make_unique<vfs::Service>( + [this](zx::channel channel, async_dispatcher_t* dispatcher) { + isolated_archivist_service_dir_.Connect( + fuchsia::logger::LogSink::Name_, std::move(channel)); + }), + fuchsia::logger::LogSink::Name_), + ZX_OK); + + return create_params; + } + + // Checks whether the expected log line has been received yet, + // and invokes DumpLogsSafe() if not. It passes itself as the completion + // callback, so that when the call completes it can check again for the + // expected message and re-invoke DumpLogsSafe(), or quit the loop, as + // appropriate. + void DumpLogs() { + // Look for kLogTestPageFileName because that string is unique to the + // console logs generated by these tests. + if (test_log_listener_.DidReceiveString(kLogTestPageFileName, + &logged_message_)) { + wait_for_message_loop_.Quit(); + return; + } + + std::unique_ptr<fuchsia::logger::LogFilterOptions> options = + std::make_unique<fuchsia::logger::LogFilterOptions>(); + options->tags = {kWebEngineLogTag}; + + test_log_listener_.set_on_dump_logs_done(base::BindOnce( + &WebEngineIntegrationLoggingTest::DumpLogs, base::Unretained(this))); + logger_->DumpLogsSafe(binding_.NewBinding(), std::move(options)); + } + + void LoadLogTestPage() { + EXPECT_TRUE(cr_fuchsia::LoadUrlAndExpectResponse( + navigation_controller_.get(), fuchsia::web::LoadUrlParams(), + embedded_test_server_.GetURL(std::string("/") + kLogTestPageFileName) + .spec())); + } + + // Replaces the line number in frame_impl.cc with kNormalizedLineNumber and + // the port with kNormalizedPortNumber to enable reliable comparison of + // console log messages. + std::string NormalizeConsoleLogMessage(base::StringPiece original) { + size_t line_number_begin = original.find("(") + 1; + size_t close_parenthesis = original.find(")", line_number_begin); + + const char kSchemePortColon[] = "http://127.0.0.1:"; + size_t port_begin = + original.find(kSchemePortColon) + strlen(kSchemePortColon); + size_t path_begin = original.find("/", port_begin); + + return original.as_string() + .replace(line_number_begin, close_parenthesis - line_number_begin, + kNormalizedLineNumber) + .replace(port_begin, path_begin - port_begin, kNormalizedPortNumber); + } + + fuchsia::sys::ComponentControllerPtr archivist_controller_; + sys::ServiceDirectory isolated_archivist_service_dir_; + + fuchsia::logger::LogPtr logger_; + base::TestLogListenerSafe test_log_listener_; + fidl::Binding<fuchsia::logger::LogListenerSafe> binding_; + + fuchsia::logger::LogMessage logged_message_; + + base::RunLoop wait_for_message_loop_; +}; + +// Verifies that calling messages from console.debug() calls go to the Fuchsia +// system log when the script log level is set to DEBUG. +TEST_F(WebEngineIntegrationLoggingTest, SetJavaScriptLogLevel_DEBUG) { + CreateContextAndFrame(ContextParamsWithIsolatedLogSink()); + + // Enable all logging. + frame_->SetJavaScriptLogLevel(fuchsia::web::ConsoleLogLevel::DEBUG); + + LoadLogTestPage(); + navigation_listener_->RunUntilTitleEquals("ended"); + + // Start the first DumpLogs() call. + DumpLogs(); + + // Run until kLogMessage is received. + wait_for_message_loop_.Run(); + + EXPECT_EQ(logged_message_.severity, + static_cast<int32_t>(fuchsia::logger::LogLevelFilter::INFO)); + ASSERT_EQ(logged_message_.tags.size(), 1u); + EXPECT_EQ(logged_message_.tags[0], kWebEngineLogTag); + EXPECT_EQ(NormalizeConsoleLogMessage(logged_message_.msg), + "frame_impl.cc(" + std::string(kNormalizedLineNumber) + + ") debug:http://127.0.0.1:" + kNormalizedPortNumber + + "/console_logging.html:8 " + ": This is a debug() message."); +}
diff --git a/fuchsia/engine/web_engine_integration_test.cc b/fuchsia/engine/web_engine_integration_test.cc index 1f6741e..18c2d9d4 100644 --- a/fuchsia/engine/web_engine_integration_test.cc +++ b/fuchsia/engine/web_engine_integration_test.cc
@@ -2,44 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include <cstring> - -#include <fuchsia/mediacodec/cpp/fidl.h> -#include <fuchsia/sys/cpp/fidl.h> -#include <fuchsia/web/cpp/fidl.h> -#include <lib/fdio/directory.h> -#include <lib/fidl/cpp/binding.h> -#include <lib/sys/cpp/component_context.h> -#include <zircon/processargs.h> - -#include "base/check.h" -#include "base/command_line.h" -#include "base/files/file_enumerator.h" -#include "base/fuchsia/file_utils.h" -#include "base/fuchsia/filtered_service_directory.h" -#include "base/fuchsia/fuchsia_logging.h" -#include "base/fuchsia/process_context.h" -#include "base/fuchsia/scoped_service_binding.h" -#include "base/fuchsia/test_log_listener_safe.h" -#include "base/macros.h" -#include "base/path_service.h" -#include "base/test/bind_test_util.h" -#include "base/test/task_environment.h" -#include "fuchsia/base/context_provider_test_connector.h" #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/web_engine_integration_test_base.h" #include "media/base/media_switches.h" #include "media/fuchsia/audio/fake_audio_consumer.h" #include "media/fuchsia/camera/fake_fuchsia_camera.h" #include "net/base/test_completion_callback.h" #include "net/http/http_request_headers.h" #include "net/socket/tcp_client_socket.h" -#include "net/test/embedded_test_server/default_handlers.h" -#include "net/test/embedded_test_server/embedded_test_server.h" -#include "testing/gtest/include/gtest/gtest.h" namespace { @@ -49,85 +22,28 @@ constexpr char kInvalidUserAgentProduct[] = "Test/Product"; constexpr char kInvalidUserAgentVersion[] = "dev/12345"; -fuchsia::web::ContentDirectoryProvider CreateTestDataDirectoryProvider() { - fuchsia::web::ContentDirectoryProvider provider; - provider.set_name("testdata"); - base::FilePath pkg_path; - CHECK(base::PathService::Get(base::DIR_ASSETS, &pkg_path)); - provider.set_directory(base::fuchsia::OpenDirectory( - pkg_path.AppendASCII("fuchsia/engine/test/data"))); - return provider; -} - } // namespace -class WebEngineIntegrationTestBase : public testing::Test { - public: - WebEngineIntegrationTestBase() - : task_environment_(base::test::TaskEnvironment::MainThreadType::IO) {} - ~WebEngineIntegrationTestBase() override = default; +// Starts a WebEngine instance before running the test. +class WebEngineIntegrationTest : public WebEngineIntegrationTestBase { + protected: + WebEngineIntegrationTest() : WebEngineIntegrationTestBase() {} void SetUp() override { - embedded_test_server_.ServeFilesFromSourceDirectory( - "fuchsia/engine/test/data"); - net::test_server::RegisterDefaultHandlers(&embedded_test_server_); - ASSERT_TRUE(embedded_test_server_.Start()); + WebEngineIntegrationTestBase::SetUp(); + + StartWebEngine(base::CommandLine(base::CommandLine::NO_PROGRAM)); } - void StartWebEngine(base::CommandLine command_line) { - web_context_provider_ = cr_fuchsia::ConnectContextProvider( - web_engine_controller_.NewRequest(), std::move(command_line)); - web_context_provider_.set_error_handler( - [](zx_status_t status) { ADD_FAILURE(); }); - } + void RunPermissionTest(bool grant); +}; - fuchsia::web::CreateContextParams DefaultContextParams() const { - fuchsia::web::CreateContextParams create_params; - auto directory = base::fuchsia::OpenDirectory( - base::FilePath(base::fuchsia::kServiceDirectoryPath)); - EXPECT_TRUE(directory.is_valid()); - create_params.set_service_directory(std::move(directory)); - return create_params; - } +class WebEngineIntegrationMediaTest : public WebEngineIntegrationTest { + protected: + WebEngineIntegrationMediaTest() : WebEngineIntegrationTest() {} - fuchsia::web::CreateContextParams DefaultContextParamsWithTestData() const { - fuchsia::web::CreateContextParams create_params = DefaultContextParams(); - - fuchsia::web::ContentDirectoryProvider provider; - provider.set_name("testdata"); - base::FilePath pkg_path; - CHECK(base::PathService::Get(base::DIR_ASSETS, &pkg_path)); - provider.set_directory(base::fuchsia::OpenDirectory( - pkg_path.AppendASCII("fuchsia/engine/test/data"))); - - create_params.mutable_content_directories()->emplace_back( - std::move(provider)); - - return create_params; - } - - fuchsia::web::CreateContextParams - ContextParamsWithFilteredServiceDirectory() { - filtered_service_directory_ = - std::make_unique<base::fuchsia::FilteredServiceDirectory>( - base::ComponentContextForProcess()->svc().get()); - fidl::InterfaceHandle<fuchsia::io::Directory> svc_dir; - filtered_service_directory_->ConnectClient(svc_dir.NewRequest()); - - // Push all services from /svc to the service directory. - base::FileEnumerator file_enum(base::FilePath("/svc"), false, - base::FileEnumerator::FILES); - for (auto file = file_enum.Next(); !file.empty(); file = file_enum.Next()) { - filtered_service_directory_->AddService(file.BaseName().value().c_str()); - } - - fuchsia::web::CreateContextParams create_params; - create_params.set_service_directory(std::move(svc_dir)); - return create_params; - } - - // Returns CreateContextParams that has AUDIO feature enabled with an injected - // FakeAudioConsumerService. + // Returns a CreateContextParams that has AUDIO feature enabled with an + // injected FakeAudioConsumerService. fuchsia::web::CreateContextParams ContextParamsWithAudio() { // Use a FilteredServiceDirectory in order to inject a fake AudioConsumer // service. @@ -152,183 +68,7 @@ return create_params; } - // Populates |navigation_listener_| with a TestNavigationListener and adds it - // to |frame|, enabling tests to monitor the state of the Frame. - // May only be called once. - void CreateNavigationListener(fuchsia::web::FramePtr* frame) { - DCHECK(!navigation_listener_); - navigation_listener_ = - std::make_unique<cr_fuchsia::TestNavigationListener>(); - navigation_listener_binding_ = - std::make_unique<fidl::Binding<fuchsia::web::NavigationEventListener>>( - navigation_listener_.get()); - (*frame)->SetNavigationEventListener( - navigation_listener_binding_->NewBinding()); - } - - // Populates |navigation_controller_| with a NavigationController for |frame|. - // May only be called once. - void AddNavigationControllerAndListenerToFrame( - fuchsia::web::FramePtr* frame) { - DCHECK(!navigation_controller_); - - (*frame)->GetNavigationController(navigation_controller_.NewRequest()); - navigation_controller_.set_error_handler( - [](zx_status_t status) { ADD_FAILURE(); }); - - CreateNavigationListener(frame); - } - - // Populates |context_| with a Context with |params|. - void CreateContext(fuchsia::web::CreateContextParams context_params) { - DCHECK(!context_); - web_context_provider_->Create(std::move(context_params), - context_.NewRequest()); - context_.set_error_handler([](zx_status_t status) { ADD_FAILURE(); }); - } - - // Returns a new Frame created from |context_|. - fuchsia::web::FramePtr CreateFrame() { - DCHECK(context_); - fuchsia::web::FramePtr frame; - context_->CreateFrame(frame.NewRequest()); - frame.set_error_handler([](zx_status_t status) { ADD_FAILURE(); }); - return frame; - } - - // Returns a new Frame with |frame_params| created from |context_|. - fuchsia::web::FramePtr CreateFrameWithParams( - fuchsia::web::CreateFrameParams frame_params) { - DCHECK(context_); - fuchsia::web::FramePtr frame; - context_->CreateFrameWithParams(std::move(frame_params), - frame.NewRequest()); - frame.set_error_handler([](zx_status_t status) { ADD_FAILURE(); }); - return frame; - } - - // Populates |context_| with a Context with |context_params|, |frame_| with a - // new Frame, |navigation_controller_| with a NavigationController request for - // |frame_|, and navigation_listener_| with a TestNavigationListener that is - // added to |frame|. - void CreateContextAndFrame(fuchsia::web::CreateContextParams context_params) { - ASSERT_FALSE(frame_); - - CreateContext(std::move(context_params)); - - frame_ = CreateFrame(); - AddNavigationControllerAndListenerToFrame(&frame_); - } - - // Same as CreateContextAndFrame() but uses |frame_params| to create the - // Frame. - void CreateContextAndFrameWithParams( - fuchsia::web::CreateContextParams context_params, - fuchsia::web::CreateFrameParams frame_params) { - ASSERT_FALSE(frame_); - - CreateContext(std::move(context_params)); - - frame_ = CreateFrameWithParams(std::move(frame_params)); - AddNavigationControllerAndListenerToFrame(&frame_); - } - - void CreateContextAndExpectError(fuchsia::web::CreateContextParams params, - zx_status_t expected_error) { - ASSERT_FALSE(context_); - web_context_provider_->Create(std::move(params), context_.NewRequest()); - base::RunLoop run_loop; - context_.set_error_handler([&run_loop, expected_error](zx_status_t status) { - EXPECT_EQ(status, expected_error); - run_loop.Quit(); - }); - run_loop.Run(); - } - - void CreateContextAndFrameAndLoadUrl(fuchsia::web::CreateContextParams params, - const GURL& url) { - CreateContextAndFrame(std::move(params)); - - // Navigate the Frame to |url| and wait for it to complete loading. - fuchsia::web::LoadUrlParams load_url_params; - ASSERT_TRUE(cr_fuchsia::LoadUrlAndExpectResponse( - navigation_controller_.get(), std::move(load_url_params), url.spec())); - - // Wait for the URL to finish loading. - navigation_listener_->RunUntilUrlEquals(url); - } - - void LoadUrlWithUserActivation(base::StringPiece url) { - EXPECT_TRUE(cr_fuchsia::LoadUrlAndExpectResponse( - navigation_controller_.get(), - cr_fuchsia::CreateLoadUrlParamsWithUserActivation(), url)); - } - - void GrantPermission(fuchsia::web::PermissionType type, - const std::string& origin) { - fuchsia::web::PermissionDescriptor permission; - permission.set_type(type); - frame_->SetPermissionState(std::move(permission), origin, - fuchsia::web::PermissionState::GRANTED); - } - - std::string ExecuteJavaScriptWithStringResult(base::StringPiece script) { - base::Optional<base::Value> value = - cr_fuchsia::ExecuteJavaScript(frame_.get(), script); - return value ? value->GetString() : std::string(); - } - - double ExecuteJavaScriptWithDoubleResult(base::StringPiece script) { - base::Optional<base::Value> value = - cr_fuchsia::ExecuteJavaScript(frame_.get(), script); - return value ? value->GetDouble() : 0.0; - } - - bool ExecuteJavaScriptWithBoolResult(base::StringPiece script) { - base::Optional<base::Value> value = - cr_fuchsia::ExecuteJavaScript(frame_.get(), script); - return value ? value->GetBool() : false; - } - - void RunCameraTest(bool grant_permission); - - protected: - void RunPermissionTest(bool grant); - - const base::test::TaskEnvironment task_environment_; - - fidl::InterfaceHandle<fuchsia::sys::ComponentController> - web_engine_controller_; - fuchsia::web::ContextProviderPtr web_context_provider_; - - net::EmbeddedTestServer embedded_test_server_; - - fuchsia::web::ContextPtr context_; - fuchsia::web::FramePtr frame_; - fuchsia::web::NavigationControllerPtr navigation_controller_; - - std::unique_ptr<cr_fuchsia::TestNavigationListener> navigation_listener_; - std::unique_ptr<fidl::Binding<fuchsia::web::NavigationEventListener>> - navigation_listener_binding_; - - std::unique_ptr<base::fuchsia::FilteredServiceDirectory> - filtered_service_directory_; - std::unique_ptr<media::FakeAudioConsumerService> fake_audio_consumer_service_; - - DISALLOW_COPY_AND_ASSIGN(WebEngineIntegrationTestBase); -}; - -// Starts a WebEngine instance before running the test. -class WebEngineIntegrationTest : public WebEngineIntegrationTestBase { - protected: - WebEngineIntegrationTest() : WebEngineIntegrationTestBase() {} - - void SetUp() override { - WebEngineIntegrationTestBase::SetUp(); - - StartWebEngine(base::CommandLine(base::CommandLine::NO_PROGRAM)); - } }; class WebEngineIntegrationUserAgentTest : public WebEngineIntegrationTest { @@ -340,101 +80,6 @@ } }; -class WebEngineIntegrationLogTest : public WebEngineIntegrationTestBase { - protected: - WebEngineIntegrationLogTest() - : WebEngineIntegrationTestBase(), binding_(&test_log_listener_) {} - void SetUp() override { - WebEngineIntegrationTestBase::SetUp(); - StartWebEngineForLoggingTest( - base::CommandLine(base::CommandLine::NO_PROGRAM)); - - logger_ = base::ComponentContextForProcess() - ->svc() - ->Connect<fuchsia::logger::Log>(); - logger_.set_error_handler([&](zx_status_t status) { - ZX_LOG(ERROR, status) << "fuchsia.logger.Log disconnected"; - ADD_FAILURE(); - wait_for_message_loop_.Quit(); - }); - } - - // Starts WebEngine without redirecting its logs. - void StartWebEngineForLoggingTest(base::CommandLine command_line) { - web_context_provider_ = cr_fuchsia::ConnectContextProviderForLoggingTest( - web_engine_controller_.NewRequest(), std::move(command_line)); - web_context_provider_.set_error_handler( - [](zx_status_t status) { ADD_FAILURE(); }); - } - - // Checks whether the expected log line has been received yet, - // and invokes DumpLogsSafe() if not. It passes itself as the completion - // callback, so that when the call completes it can check again for the - // expected message and re-invoke DumpLogsSafe(), or quit the loop, as - // appropriate. - void DumpLogs() { - // Look for kLogTestPageFileName because that string is unique to the - // console logs generated by these tests. - if (test_log_listener_.DidReceiveString(kLogTestPageFileName, - &logged_message_)) { - wait_for_message_loop_.Quit(); - return; - } - - std::unique_ptr<fuchsia::logger::LogFilterOptions> options = - std::make_unique<fuchsia::logger::LogFilterOptions>(); - options->tags = {kWebEngineLogTag}; - - test_log_listener_.set_on_dump_logs_done(base::BindOnce( - &WebEngineIntegrationLogTest::DumpLogs, base::Unretained(this))); - logger_->DumpLogsSafe(binding_.NewBinding(), std::move(options)); - } - - void LoadLogTestPage() { - EXPECT_TRUE(cr_fuchsia::LoadUrlAndExpectResponse( - navigation_controller_.get(), fuchsia::web::LoadUrlParams(), - embedded_test_server_.GetURL(std::string("/") + kLogTestPageFileName) - .spec())); - } - - // Replaces the line number in frame_impl.cc with kNormalizedLineNumber and - // the port with kNormalizedPortNumber to enable reliable comparison of - // console log messages. - std::string NormalizeConsoleLogMessage(base::StringPiece original) { - size_t line_number_begin = original.find("(") + 1; - size_t close_parenthesis = original.find(")", line_number_begin); - - const char kSchemePortColon[] = "http://127.0.0.1:"; - size_t port_begin = - original.find(kSchemePortColon) + strlen(kSchemePortColon); - size_t path_begin = original.find("/", port_begin); - - return original.as_string() - .replace(line_number_begin, close_parenthesis - line_number_begin, - kNormalizedLineNumber) - .replace(port_begin, path_begin - port_begin, kNormalizedPortNumber); - } - - static const char kLogTestPageFileName[]; - static const char kWebEngineLogTag[]; - static const char kNormalizedLineNumber[]; - static const char kNormalizedPortNumber[]; - - fuchsia::logger::LogPtr logger_; - base::TestLogListenerSafe test_log_listener_; - fidl::Binding<fuchsia::logger::LogListenerSafe> binding_; - - fuchsia::logger::LogMessage logged_message_; - - base::RunLoop wait_for_message_loop_; -}; - -const char WebEngineIntegrationLogTest::kLogTestPageFileName[] = - "console_logging.html"; -const char WebEngineIntegrationLogTest::kWebEngineLogTag[] = "web_engine_exe"; -const char WebEngineIntegrationLogTest::kNormalizedLineNumber[] = "123"; -const char WebEngineIntegrationLogTest::kNormalizedPortNumber[] = "456"; - TEST_F(WebEngineIntegrationUserAgentTest, ValidProductOnly) { // Create a Context with just an embedder product specified. fuchsia::web::CreateContextParams create_params = DefaultContextParams(); @@ -621,7 +266,7 @@ navigation_listener_->RunUntilUrlAndTitleEquals(kUrl, kTitle); } -TEST_F(WebEngineIntegrationTest, PlayAudio) { +TEST_F(WebEngineIntegrationMediaTest, PlayAudio) { CreateContextAndFrame(ContextParamsWithAudioAndTestData()); static uint16_t kTestMediaSessionId = 43; @@ -645,7 +290,7 @@ // Check that audio cannot play when the AUDIO ContextFeatureFlag is not // provided. -TEST_F(WebEngineIntegrationTest, PlayAudio_NoFlag) { +TEST_F(WebEngineIntegrationMediaTest, PlayAudio_NoFlag) { // Both FilteredServiceDirectory and test data are needed. fuchsia::web::CreateContextParams create_params = ContextParamsWithFilteredServiceDirectory(); @@ -654,12 +299,14 @@ CreateContextAndFrame(std::move(create_params)); bool is_requested = false; - filtered_service_directory_->outgoing_directory()->AddPublicService( - std::make_unique<vfs::Service>( - [&is_requested](zx::channel channel, async_dispatcher_t* dispatcher) { - is_requested = true; - }), - fuchsia::media::SessionAudioConsumerFactory::Name_); + ASSERT_EQ(filtered_service_directory_->outgoing_directory()->AddPublicService( + std::make_unique<vfs::Service>( + [&is_requested](zx::channel channel, + async_dispatcher_t* dispatcher) { + is_requested = true; + }), + fuchsia::media::SessionAudioConsumerFactory::Name_), + ZX_OK); LoadUrlWithUserActivation("fuchsia-dir://testdata/play_audio.html"); @@ -667,7 +314,7 @@ EXPECT_FALSE(is_requested); } -TEST_F(WebEngineIntegrationTest, PlayVideo) { +TEST_F(WebEngineIntegrationMediaTest, PlayVideo) { CreateContextAndFrame(ContextParamsWithAudioAndTestData()); LoadUrlWithUserActivation("fuchsia-dir://testdata/play_video.html?autoplay"); @@ -675,7 +322,7 @@ navigation_listener_->RunUntilTitleEquals("ended"); } -void WebEngineIntegrationTestBase::RunPermissionTest(bool grant) { +void WebEngineIntegrationTest::RunPermissionTest(bool grant) { CreateContextAndFrame(DefaultContextParamsWithTestData()); if (grant) { @@ -698,7 +345,7 @@ RunPermissionTest(true); } -TEST_F(WebEngineIntegrationTest, MicrophoneAccess_WithPermission) { +TEST_F(WebEngineIntegrationMediaTest, MicrophoneAccess_WithPermission) { CreateContextAndFrame(ContextParamsWithAudio()); GrantPermission(fuchsia::web::PermissionType::MICROPHONE, @@ -711,7 +358,7 @@ navigation_listener_->RunUntilTitleEquals("ended"); } -TEST_F(WebEngineIntegrationTest, MicrophoneAccess_WithoutPermission) { +TEST_F(WebEngineIntegrationMediaTest, MicrophoneAccess_WithoutPermission) { CreateContextAndFrame(ContextParamsWithAudio()); EXPECT_TRUE(cr_fuchsia::LoadUrlAndExpectResponse( @@ -721,7 +368,7 @@ navigation_listener_->RunUntilTitleEquals("ended"); } -TEST_F(WebEngineIntegrationTest, SetBlockMediaLoading_Blocked) { +TEST_F(WebEngineIntegrationMediaTest, SetBlockMediaLoading_Blocked) { CreateContextAndFrame(ContextParamsWithAudioAndTestData()); frame_->SetBlockMediaLoading(true); @@ -738,7 +385,7 @@ // Initially, set media blocking to be true. When media is unblocked, check that // it begins playing, since autoplay=true. -TEST_F(WebEngineIntegrationTest, SetBlockMediaLoading_AfterUnblock) { +TEST_F(WebEngineIntegrationMediaTest, SetBlockMediaLoading_AfterUnblock) { CreateContextAndFrame(ContextParamsWithAudioAndTestData()); frame_->SetBlockMediaLoading(true); @@ -757,7 +404,8 @@ // Check that when autoplay=false and media loading was blocked after the // element has started loading that media will play when play() is called. -TEST_F(WebEngineIntegrationTest, SetBlockMediaLoading_SetBlockedAfterLoading) { +TEST_F(WebEngineIntegrationMediaTest, + SetBlockMediaLoading_SetBlockedAfterLoading) { CreateContextAndFrame(ContextParamsWithAudioAndTestData()); LoadUrlWithUserActivation("fuchsia-dir://testdata/play_video.html"); @@ -787,7 +435,8 @@ #else #define MAYBE_VulkanWebEngineIntegrationTest VulkanWebEngineIntegrationTest #endif -class MAYBE_VulkanWebEngineIntegrationTest : public WebEngineIntegrationTest {}; +class MAYBE_VulkanWebEngineIntegrationTest + : public WebEngineIntegrationMediaTest {}; TEST_F(MAYBE_VulkanWebEngineIntegrationTest, WebGLContextPresentWithVulkanFeature) { @@ -804,7 +453,16 @@ EXPECT_EQ(navigation_listener_->title(), "present"); } -void WebEngineIntegrationTestBase::RunCameraTest(bool grant_permission) { +// Does not start WebEngine automatically as one of the tests requires manually +// starting it. +class WebEngineIntegrationCameraTest : public WebEngineIntegrationTestBase { + protected: + WebEngineIntegrationCameraTest() : WebEngineIntegrationTestBase() {} + + void RunCameraTest(bool grant_permission); +}; + +void WebEngineIntegrationCameraTest::RunCameraTest(bool grant_permission) { fuchsia::web::CreateContextParams create_params = ContextParamsWithFilteredServiceDirectory(); @@ -828,15 +486,17 @@ } // TODO(crbug.com/1104562): Flakily times-out. -TEST_F(WebEngineIntegrationTest, DISABLED_CameraAccess_WithPermission) { +TEST_F(WebEngineIntegrationCameraTest, DISABLED_CameraAccess_WithPermission) { + StartWebEngine(base::CommandLine(base::CommandLine::NO_PROGRAM)); RunCameraTest(/*grant_permission=*/true); } -TEST_F(WebEngineIntegrationTest, CameraAccess_WithoutPermission) { +TEST_F(WebEngineIntegrationCameraTest, CameraAccess_WithoutPermission) { + StartWebEngine(base::CommandLine(base::CommandLine::NO_PROGRAM)); RunCameraTest(/*grant_permission=*/false); } -TEST_F(WebEngineIntegrationTestBase, CameraNoVideoCaptureProcess) { +TEST_F(WebEngineIntegrationCameraTest, CameraNoVideoCaptureProcess) { base::CommandLine command_line(base::CommandLine::NO_PROGRAM); command_line.AppendSwitchASCII("disable-features", "MojoVideoCapture"); StartWebEngine(std::move(command_line)); @@ -859,12 +519,14 @@ // Check that the CodecFactory service is requested. bool is_requested = false; - filtered_service_directory_->outgoing_directory()->AddPublicService( - std::make_unique<vfs::Service>( - [&is_requested](zx::channel channel, async_dispatcher_t* dispatcher) { - is_requested = true; - }), - fuchsia::mediacodec::CodecFactory::Name_); + ASSERT_EQ(filtered_service_directory_->outgoing_directory()->AddPublicService( + std::make_unique<vfs::Service>( + [&is_requested](zx::channel channel, + async_dispatcher_t* dispatcher) { + is_requested = true; + }), + fuchsia::mediacodec::CodecFactory::Name_), + ZX_OK); LoadUrlWithUserActivation("fuchsia-dir://testdata/play_video.html?autoplay"); navigation_listener_->RunUntilTitleEquals("ended"); @@ -875,18 +537,20 @@ // Check that the CodecFactory service is not requested when // HARDWARE_VIDEO_DECODER is not provided. // The video should use software decoders and still play. -TEST_F(WebEngineIntegrationTest, HardwareVideoDecoderFlag_NotProvided) { +TEST_F(WebEngineIntegrationMediaTest, HardwareVideoDecoderFlag_NotProvided) { fuchsia::web::CreateContextParams create_params = ContextParamsWithAudioAndTestData(); CreateContextAndFrame(std::move(create_params)); bool is_requested = false; - filtered_service_directory_->outgoing_directory()->AddPublicService( - std::make_unique<vfs::Service>( - [&is_requested](zx::channel channel, async_dispatcher_t* dispatcher) { - is_requested = true; - }), - fuchsia::mediacodec::CodecFactory::Name_); + ASSERT_EQ(filtered_service_directory_->outgoing_directory()->AddPublicService( + std::make_unique<vfs::Service>( + [&is_requested](zx::channel channel, + async_dispatcher_t* dispatcher) { + is_requested = true; + }), + fuchsia::mediacodec::CodecFactory::Name_), + ZX_OK); LoadUrlWithUserActivation("fuchsia-dir://testdata/play_video.html?autoplay"); @@ -894,31 +558,3 @@ EXPECT_FALSE(is_requested); } - -// Verifies that calling messages from console.debug() calls go to the Fuchsia -// system log when the script log level is set to DEBUG. -TEST_F(WebEngineIntegrationLogTest, SetJavaScriptLogLevel_DEBUG) { - CreateContextAndFrame(DefaultContextParams()); - - // Enable all logging. - frame_->SetJavaScriptLogLevel(fuchsia::web::ConsoleLogLevel::DEBUG); - - LoadLogTestPage(); - navigation_listener_->RunUntilTitleEquals("ended"); - - // Start the first DumpLogs() call. - DumpLogs(); - - // Run until kLogMessage is received. - wait_for_message_loop_.Run(); - - EXPECT_EQ(logged_message_.severity, - static_cast<int32_t>(fuchsia::logger::LogLevelFilter::INFO)); - ASSERT_EQ(logged_message_.tags.size(), 1u); - EXPECT_EQ(logged_message_.tags[0], kWebEngineLogTag); - EXPECT_EQ(NormalizeConsoleLogMessage(logged_message_.msg), - "frame_impl.cc(" + std::string(kNormalizedLineNumber) + - ") debug:http://127.0.0.1:" + kNormalizedPortNumber + - "/console_logging.html:8 " - ": This is a debug() message."); -}
diff --git a/fuchsia/engine/web_engine_integration_test_base.cc b/fuchsia/engine/web_engine_integration_test_base.cc new file mode 100644 index 0000000..2b1e1f0 --- /dev/null +++ b/fuchsia/engine/web_engine_integration_test_base.cc
@@ -0,0 +1,228 @@ +// 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 "fuchsia/engine/web_engine_integration_test_base.h" + +#include <lib/fdio/directory.h> + +#include "base/files/file_enumerator.h" +#include "base/files/file_path.h" +#include "base/fuchsia/file_utils.h" +#include "base/fuchsia/process_context.h" +#include "base/path_service.h" +#include "base/strings/string_piece.h" +#include "fuchsia/base/context_provider_test_connector.h" +#include "fuchsia/base/frame_test_util.h" +#include "net/test/embedded_test_server/default_handlers.h" + +WebEngineIntegrationTestBase::WebEngineIntegrationTestBase() + : task_environment_(base::test::TaskEnvironment::MainThreadType::IO) {} + +WebEngineIntegrationTestBase::~WebEngineIntegrationTestBase() = default; + +void WebEngineIntegrationTestBase::SetUp() { + embedded_test_server_.ServeFilesFromSourceDirectory( + "fuchsia/engine/test/data"); + net::test_server::RegisterDefaultHandlers(&embedded_test_server_); + ASSERT_TRUE(embedded_test_server_.Start()); +} + +// static +fuchsia::web::ContentDirectoryProvider +WebEngineIntegrationTestBase::CreateTestDataDirectoryProvider() { + fuchsia::web::ContentDirectoryProvider provider; + provider.set_name("testdata"); + base::FilePath pkg_path; + CHECK(base::PathService::Get(base::DIR_ASSETS, &pkg_path)); + provider.set_directory(base::fuchsia::OpenDirectory( + pkg_path.AppendASCII("fuchsia/engine/test/data"))); + return provider; +} + +void WebEngineIntegrationTestBase::StartWebEngine( + base::CommandLine command_line) { + web_context_provider_ = cr_fuchsia::ConnectContextProvider( + web_engine_controller_.NewRequest(), std::move(command_line)); + web_context_provider_.set_error_handler( + [](zx_status_t status) { ADD_FAILURE(); }); +} + +fuchsia::web::CreateContextParams +WebEngineIntegrationTestBase::DefaultContextParams() const { + fuchsia::web::CreateContextParams create_params; + auto directory = base::fuchsia::OpenDirectory( + base::FilePath(base::fuchsia::kServiceDirectoryPath)); + EXPECT_TRUE(directory.is_valid()); + create_params.set_service_directory(std::move(directory)); + return create_params; +} + +fuchsia::web::CreateContextParams +WebEngineIntegrationTestBase::DefaultContextParamsWithTestData() const { + fuchsia::web::CreateContextParams create_params = DefaultContextParams(); + + fuchsia::web::ContentDirectoryProvider provider; + provider.set_name("testdata"); + base::FilePath pkg_path; + CHECK(base::PathService::Get(base::DIR_ASSETS, &pkg_path)); + provider.set_directory(base::fuchsia::OpenDirectory( + pkg_path.AppendASCII("fuchsia/engine/test/data"))); + + create_params.mutable_content_directories()->emplace_back( + std::move(provider)); + + return create_params; +} + +fuchsia::web::CreateContextParams +WebEngineIntegrationTestBase::ContextParamsWithFilteredServiceDirectory() { + filtered_service_directory_ = + std::make_unique<base::fuchsia::FilteredServiceDirectory>( + base::ComponentContextForProcess()->svc().get()); + fidl::InterfaceHandle<fuchsia::io::Directory> svc_dir; + filtered_service_directory_->ConnectClient(svc_dir.NewRequest()); + + // Push all services from /svc to the service directory. + base::FileEnumerator file_enum(base::FilePath("/svc"), false, + base::FileEnumerator::FILES); + for (auto file = file_enum.Next(); !file.empty(); file = file_enum.Next()) { + filtered_service_directory_->AddService(file.BaseName().value().c_str()); + } + + fuchsia::web::CreateContextParams create_params; + create_params.set_service_directory(std::move(svc_dir)); + return create_params; +} + +void WebEngineIntegrationTestBase::CreateNavigationListener( + fuchsia::web::FramePtr* frame) { + DCHECK(!navigation_listener_); + navigation_listener_ = std::make_unique<cr_fuchsia::TestNavigationListener>(); + navigation_listener_binding_ = + std::make_unique<fidl::Binding<fuchsia::web::NavigationEventListener>>( + navigation_listener_.get()); + (*frame)->SetNavigationEventListener( + navigation_listener_binding_->NewBinding()); +} + +void WebEngineIntegrationTestBase::AddNavigationControllerAndListenerToFrame( + fuchsia::web::FramePtr* frame) { + DCHECK(!navigation_controller_); + + (*frame)->GetNavigationController(navigation_controller_.NewRequest()); + navigation_controller_.set_error_handler( + [](zx_status_t status) { ADD_FAILURE(); }); + + CreateNavigationListener(frame); +} + +void WebEngineIntegrationTestBase::CreateContext( + fuchsia::web::CreateContextParams context_params) { + DCHECK(!context_); + web_context_provider_->Create(std::move(context_params), + context_.NewRequest()); + context_.set_error_handler([](zx_status_t status) { ADD_FAILURE(); }); +} + +fuchsia::web::FramePtr WebEngineIntegrationTestBase::CreateFrame() { + DCHECK(context_); + fuchsia::web::FramePtr frame; + context_->CreateFrame(frame.NewRequest()); + frame.set_error_handler([](zx_status_t status) { ADD_FAILURE(); }); + return frame; +} + +fuchsia::web::FramePtr WebEngineIntegrationTestBase::CreateFrameWithParams( + fuchsia::web::CreateFrameParams frame_params) { + DCHECK(context_); + fuchsia::web::FramePtr frame; + context_->CreateFrameWithParams(std::move(frame_params), frame.NewRequest()); + frame.set_error_handler([](zx_status_t status) { ADD_FAILURE(); }); + return frame; +} + +void WebEngineIntegrationTestBase::CreateContextAndFrame( + fuchsia::web::CreateContextParams context_params) { + ASSERT_FALSE(frame_); + + CreateContext(std::move(context_params)); + + frame_ = CreateFrame(); + AddNavigationControllerAndListenerToFrame(&frame_); +} + +void WebEngineIntegrationTestBase::CreateContextAndFrameWithParams( + fuchsia::web::CreateContextParams context_params, + fuchsia::web::CreateFrameParams frame_params) { + ASSERT_FALSE(frame_); + + CreateContext(std::move(context_params)); + + frame_ = CreateFrameWithParams(std::move(frame_params)); + AddNavigationControllerAndListenerToFrame(&frame_); +} + +void WebEngineIntegrationTestBase::CreateContextAndExpectError( + fuchsia::web::CreateContextParams params, + zx_status_t expected_error) { + ASSERT_FALSE(context_); + web_context_provider_->Create(std::move(params), context_.NewRequest()); + base::RunLoop run_loop; + context_.set_error_handler([&run_loop, expected_error](zx_status_t status) { + EXPECT_EQ(status, expected_error); + run_loop.Quit(); + }); + run_loop.Run(); +} + +void WebEngineIntegrationTestBase::CreateContextAndFrameAndLoadUrl( + fuchsia::web::CreateContextParams params, + const GURL& url) { + CreateContextAndFrame(std::move(params)); + + // Navigate the Frame to |url| and wait for it to complete loading. + fuchsia::web::LoadUrlParams load_url_params; + ASSERT_TRUE(cr_fuchsia::LoadUrlAndExpectResponse( + navigation_controller_.get(), std::move(load_url_params), url.spec())); + + // Wait for the URL to finish loading. + navigation_listener_->RunUntilUrlEquals(url); +} + +void WebEngineIntegrationTestBase::LoadUrlWithUserActivation( + base::StringPiece url) { + EXPECT_TRUE(cr_fuchsia::LoadUrlAndExpectResponse( + navigation_controller_.get(), + cr_fuchsia::CreateLoadUrlParamsWithUserActivation(), url)); +} + +void WebEngineIntegrationTestBase::GrantPermission( + fuchsia::web::PermissionType type, + const std::string& origin) { + fuchsia::web::PermissionDescriptor permission; + permission.set_type(type); + frame_->SetPermissionState(std::move(permission), origin, + fuchsia::web::PermissionState::GRANTED); +} + +std::string WebEngineIntegrationTestBase::ExecuteJavaScriptWithStringResult( + base::StringPiece script) { + base::Optional<base::Value> value = + cr_fuchsia::ExecuteJavaScript(frame_.get(), script); + return value ? value->GetString() : std::string(); +} + +double WebEngineIntegrationTestBase::ExecuteJavaScriptWithDoubleResult( + base::StringPiece script) { + base::Optional<base::Value> value = + cr_fuchsia::ExecuteJavaScript(frame_.get(), script); + return value ? value->GetDouble() : 0.0; +} + +bool WebEngineIntegrationTestBase::ExecuteJavaScriptWithBoolResult( + base::StringPiece script) { + base::Optional<base::Value> value = + cr_fuchsia::ExecuteJavaScript(frame_.get(), script); + return value ? value->GetBool() : false; +}
diff --git a/fuchsia/engine/web_engine_integration_test_base.h b/fuchsia/engine/web_engine_integration_test_base.h new file mode 100644 index 0000000..e0e2718e --- /dev/null +++ b/fuchsia/engine/web_engine_integration_test_base.h
@@ -0,0 +1,113 @@ +// 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 FUCHSIA_ENGINE_WEB_ENGINE_INTEGRATION_TEST_BASE_H_ +#define FUCHSIA_ENGINE_WEB_ENGINE_INTEGRATION_TEST_BASE_H_ + +#include <fuchsia/mediacodec/cpp/fidl.h> +#include <fuchsia/sys/cpp/fidl.h> +#include <fuchsia/web/cpp/fidl.h> +#include <lib/fidl/cpp/binding.h> +#include <lib/sys/cpp/component_context.h> + +#include <string> + +#include "base/command_line.h" +#include "base/fuchsia/filtered_service_directory.h" +#include "base/strings/string_piece_forward.h" +#include "base/test/task_environment.h" +#include "fuchsia/base/test_navigation_listener.h" +#include "net/test/embedded_test_server/embedded_test_server.h" +#include "testing/gtest/include/gtest/gtest.h" + +class WebEngineIntegrationTestBase : public testing::Test { + public: + WebEngineIntegrationTestBase(); + ~WebEngineIntegrationTestBase() override; + WebEngineIntegrationTestBase(const WebEngineIntegrationTestBase&) = delete; + WebEngineIntegrationTestBase& operator=(const WebEngineIntegrationTestBase&) = + delete; + + void SetUp() override; + + static fuchsia::web::ContentDirectoryProvider + CreateTestDataDirectoryProvider(); + + void StartWebEngine(base::CommandLine command_line); + + fuchsia::web::CreateContextParams DefaultContextParams() const; + + fuchsia::web::CreateContextParams DefaultContextParamsWithTestData() const; + fuchsia::web::CreateContextParams ContextParamsWithFilteredServiceDirectory(); + + // Populates |navigation_listener_| with a TestNavigationListener and adds it + // to |frame|, enabling tests to monitor the state of the Frame. + // May only be called once. + void CreateNavigationListener(fuchsia::web::FramePtr* frame); + + // Populates |navigation_controller_| with a NavigationController for |frame|. + // May only be called once. + void AddNavigationControllerAndListenerToFrame(fuchsia::web::FramePtr* frame); + + // Populates |context_| with a Context with |params|. + void CreateContext(fuchsia::web::CreateContextParams context_params); + + // Returns a new Frame created from |context_|. + fuchsia::web::FramePtr CreateFrame(); + + // Returns a new Frame with |frame_params| created from |context_|. + fuchsia::web::FramePtr CreateFrameWithParams( + fuchsia::web::CreateFrameParams frame_params); + + // Populates |context_| with a Context with |context_params|, |frame_| with a + // new Frame, |navigation_controller_| with a NavigationController request for + // |frame_|, and navigation_listener_| with a TestNavigationListener that is + // added to |frame|. + void CreateContextAndFrame(fuchsia::web::CreateContextParams context_params); + + // Same as CreateContextAndFrame() but uses |frame_params| to create the + // Frame. + void CreateContextAndFrameWithParams( + fuchsia::web::CreateContextParams context_params, + fuchsia::web::CreateFrameParams frame_params); + + void CreateContextAndExpectError(fuchsia::web::CreateContextParams params, + zx_status_t expected_error); + + void CreateContextAndFrameAndLoadUrl(fuchsia::web::CreateContextParams params, + const GURL& url); + + void LoadUrlWithUserActivation(base::StringPiece url); + + void GrantPermission(fuchsia::web::PermissionType type, + const std::string& origin); + + std::string ExecuteJavaScriptWithStringResult(base::StringPiece script); + + double ExecuteJavaScriptWithDoubleResult(base::StringPiece script); + + bool ExecuteJavaScriptWithBoolResult(base::StringPiece script); + + protected: + const base::test::TaskEnvironment task_environment_; + + fidl::InterfaceHandle<fuchsia::sys::ComponentController> + web_engine_controller_; + fuchsia::web::ContextProviderPtr web_context_provider_; + + net::EmbeddedTestServer embedded_test_server_; + + fuchsia::web::ContextPtr context_; + fuchsia::web::FramePtr frame_; + fuchsia::web::NavigationControllerPtr navigation_controller_; + + std::unique_ptr<cr_fuchsia::TestNavigationListener> navigation_listener_; + std::unique_ptr<fidl::Binding<fuchsia::web::NavigationEventListener>> + navigation_listener_binding_; + + std::unique_ptr<base::fuchsia::FilteredServiceDirectory> + filtered_service_directory_; +}; + +#endif // FUCHSIA_ENGINE_WEB_ENGINE_INTEGRATION_TEST_BASE_H_
diff --git a/fuchsia/runners/BUILD.gn b/fuchsia/runners/BUILD.gn index bf57ca8..b14d810 100644 --- a/fuchsia/runners/BUILD.gn +++ b/fuchsia/runners/BUILD.gn
@@ -64,6 +64,8 @@ "cast/cast_runner_switches.h", "cast/cast_streaming.cc", "cast/cast_streaming.h", + "cast/create_web_message.cc", + "cast/create_web_message.h", "cast/named_message_port_connector_fuchsia.cc", "cast/named_message_port_connector_fuchsia.h", "cast/pending_cast_component.cc", @@ -76,6 +78,7 @@ ] deps = [ "//base", + "//components/cast/message_port", "//components/cast/named_message_port_connector:named_message_port_connector", "//fuchsia/base", "//fuchsia/base:modular", @@ -85,16 +88,18 @@ "//url", ] - # TODO(crbug.com/1131102): Remove dep when MessagePortProxy lands, and add assertions to ensure - # that Blink indirect deps don't creep back in. - deps += [ "//fuchsia/base:message_port" ] - public_deps = [ ":common", "//fuchsia:cast_fidl", "//third_party/fuchsia-sdk/sdk/fidl/fuchsia.legacymetrics", "//third_party/fuchsia-sdk/sdk/fidl/fuchsia.web", ] + + # Keep CastRunner trim by ensuring that large browser dependencies don't creep in. + assert_no_deps = [ + "//content/public/common", + "//third_party/blink/public/common", + ] visibility = [ ":*" ] } @@ -106,8 +111,6 @@ ":common", "//base", "//fuchsia/base", - "//mojo/core/embedder", # TODO(crbug.com/1126571): Remove when - # MessagePortProxy lands. ] data_deps = [ ":cast_runner_core" ] @@ -118,18 +121,6 @@ binary = ":cast_runner_exe" package_name_override = "cast_runner" manifest = "cast/cast_runner.cmx" - - # TODO(crbug.com/1131102): Remove these exclusions when MessagePortProxy lands. - excluded_files = [ - "lib/libEGL.so", - "lib/libfuchsia_egl.so", - "lib/libGLESv2.so", - "lib/libswiftshader_libEGL.so", - "lib/libswiftshader_libGLESv2.so", - "lib/libtrace-engine.so", - "lib/libvulkan.so", - "lib/VkLayer_image_pipe_swapchain.so", - ] } fuchsia_package_runner("cast_runner") { @@ -185,9 +176,8 @@ ":cast_runner_test_core", "//base/test:run_all_unittests", "//base/test:test_support", + "//components/cast/message_port", "//fuchsia/base:test_support", - "//mojo/core/embedder", # TODO(crbug.com/1126571): Remove when - # MessagePortProxy lands. "//net:test_support", "//testing/gtest", "//third_party/fuchsia-sdk/sdk/fidl/fuchsia.camera3", @@ -220,10 +210,11 @@ ":cast_runner_core", ":cast_runner_test_core", "//base/test:test_support", + "//components/cast/message_port", + "//components/cast/message_port:test_message_port_receiver", "//content/public/browser", "//content/test:test_support", "//fuchsia/base", - "//fuchsia/base:message_port", "//fuchsia/base:test_support", "//fuchsia/engine:browsertest_core", "//testing/gmock", @@ -265,6 +256,7 @@ "//base", "//base/test:run_all_unittests", "//base/test:test_support", + "//components/cast/message_port", "//fuchsia/base:modular", "//net:test_support", "//testing/gtest",
diff --git a/fuchsia/runners/cast/DEPS b/fuchsia/runners/cast/DEPS index 001879a..8129faaf 100644 --- a/fuchsia/runners/cast/DEPS +++ b/fuchsia/runners/cast/DEPS
@@ -1,5 +1,5 @@ include_rules = [ + "+components/cast/message_port", "+components/cast/named_message_port_connector", "+content/public/test", - "+mojo/core/embedder", ]
diff --git a/fuchsia/runners/cast/api_bindings_client.cc b/fuchsia/runners/cast/api_bindings_client.cc index 88f02f8a..809a119d 100644 --- a/fuchsia/runners/cast/api_bindings_client.cc +++ b/fuchsia/runners/cast/api_bindings_client.cc
@@ -9,7 +9,7 @@ #include "base/bind.h" #include "base/fuchsia/fuchsia_logging.h" #include "base/strings/string_piece.h" -#include "fuchsia/base/message_port.h" +#include "components/cast/message_port/message_port_fuchsia.h" namespace { @@ -89,14 +89,16 @@ return bindings_.has_value(); } -bool ApiBindingsClient::OnPortConnected(base::StringPiece port_name, - blink::WebMessagePort port) { +bool ApiBindingsClient::OnPortConnected( + base::StringPiece port_name, + std::unique_ptr<cast_api_bindings::MessagePort> port) { if (!bindings_service_) return false; bindings_service_->Connect( port_name.as_string(), - cr_fuchsia::FidlMessagePortFromBlink(std::move(port))); + cast_api_bindings::MessagePortFuchsia::FromMessagePort(port.get()) + ->TakeClientHandle()); return true; }
diff --git a/fuchsia/runners/cast/api_bindings_client.h b/fuchsia/runners/cast/api_bindings_client.h index 7ca8c1a..fa4e82e 100644 --- a/fuchsia/runners/cast/api_bindings_client.h +++ b/fuchsia/runners/cast/api_bindings_client.h
@@ -10,6 +10,7 @@ #include "base/macros.h" #include "base/optional.h" +#include "components/cast/message_port/message_port.h" #include "components/cast/named_message_port_connector/named_message_port_connector.h" #include "fuchsia/fidl/chromium/cast/cpp/fidl.h" @@ -45,7 +46,8 @@ // TODO(crbug.com/1082821): Move this method back to private once the Cast // Streaming Receiver component has been implemented. // Called when |connector_| has connected a port. - bool OnPortConnected(base::StringPiece port_name, blink::WebMessagePort port); + bool OnPortConnected(base::StringPiece port_name, + std::unique_ptr<cast_api_bindings::MessagePort> port); private: // Called when ApiBindings::GetAll() has responded.
diff --git a/fuchsia/runners/cast/api_bindings_client_browsertest.cc b/fuchsia/runners/cast/api_bindings_client_browsertest.cc index 031bab0..a818504 100644 --- a/fuchsia/runners/cast/api_bindings_client_browsertest.cc +++ b/fuchsia/runners/cast/api_bindings_client_browsertest.cc
@@ -10,15 +10,16 @@ #include "base/files/file_util.h" #include "base/path_service.h" #include "base/test/bind_test_util.h" +#include "components/cast/message_port/message_port_fuchsia.h" #include "content/public/test/browser_test.h" #include "fuchsia/base/fit_adapter.h" #include "fuchsia/base/frame_test_util.h" #include "fuchsia/base/mem_buffer_util.h" -#include "fuchsia/base/message_port.h" #include "fuchsia/base/result_receiver.h" #include "fuchsia/base/test_navigation_listener.h" #include "fuchsia/engine/test/web_engine_browser_test.h" #include "fuchsia/runners/cast/api_bindings_client.h" +#include "fuchsia/runners/cast/create_web_message.h" #include "fuchsia/runners/cast/named_message_port_connector_fuchsia.h" #include "fuchsia/runners/cast/test_api_bindings.h" #include "testing/gtest/include/gtest/gtest.h" @@ -101,15 +102,17 @@ EXPECT_TRUE(cr_fuchsia::LoadUrlAndExpectResponse( controller_.get(), fuchsia::web::LoadUrlParams(), test_url.spec())); navigation_listener_.RunUntilUrlEquals(test_url); - frame_->PostMessage("*", - std::move(*cr_fuchsia::FidlWebMessageFromBlink( - connector_->GetConnectMessage(), - cr_fuchsia::TransferableHostType::kRemote)), - [&post_message_response_closure]( - fuchsia::web::Frame_PostMessage_Result result) { - ASSERT_TRUE(result.is_response()); - post_message_response_closure.Run(); - }); + + std::string connect_message; + std::unique_ptr<cast_api_bindings::MessagePort> connect_port; + connector_->GetConnectMessage(&connect_message, &connect_port); + frame_->PostMessage( + "*", CreateWebMessage(connect_message, std::move(connect_port)), + [&post_message_response_closure]( + fuchsia::web::Frame_PostMessage_Result result) { + ASSERT_TRUE(result.is_response()); + post_message_response_closure.Run(); + }); // Connect to the echo service hosted by the page and send a ping to it. fuchsia::web::WebMessage message;
diff --git a/fuchsia/runners/cast/cast_component.cc b/fuchsia/runners/cast/cast_component.cc index a0e98425..728205d 100644 --- a/fuchsia/runners/cast/cast_component.cc +++ b/fuchsia/runners/cast/cast_component.cc
@@ -16,12 +16,13 @@ #include "base/fuchsia/fuchsia_logging.h" #include "base/path_service.h" #include "base/task/current_thread.h" +#include "components/cast/message_port/message_port_fuchsia.h" #include "fuchsia/base/agent_manager.h" #include "fuchsia/base/mem_buffer_util.h" -#include "fuchsia/base/message_port.h" #include "fuchsia/fidl/chromium/cast/cpp/fidl.h" #include "fuchsia/runners/cast/cast_runner.h" #include "fuchsia/runners/cast/cast_streaming.h" +#include "fuchsia/runners/cast/create_web_message.h" #include "fuchsia/runners/common/web_component.h" namespace { @@ -100,26 +101,21 @@ // component has been implemented. // Register the MessagePort for the Cast Streaming Receiver. - fidl::InterfaceHandle<fuchsia::web::MessagePort> message_port; - fuchsia::web::WebMessage message; - message.set_data(cr_fuchsia::MemBufferFromString("", "empty_message")); - fuchsia::web::OutgoingTransferable outgoing_transferable; - outgoing_transferable.set_message_port(message_port.NewRequest()); - std::vector<fuchsia::web::OutgoingTransferable> outgoing_transferables; - outgoing_transferables.push_back(std::move(outgoing_transferable)); - message.set_outgoing_transfer(std::move(outgoing_transferables)); - + std::unique_ptr<cast_api_bindings::MessagePort> message_port_for_web_engine; + std::unique_ptr<cast_api_bindings::MessagePort> message_port_for_agent; + cast_api_bindings::MessagePort::CreatePair(&message_port_for_agent, + &message_port_for_web_engine); frame()->PostMessage( - kCastStreamingMessagePortOrigin, std::move(message), + kCastStreamingMessagePortOrigin, + CreateWebMessage("", std::move(message_port_for_web_engine)), [this](fuchsia::web::Frame_PostMessage_Result result) { if (result.is_err()) { DestroyComponent(kBindingsFailureExitCode, fuchsia::sys::TerminationReason::INTERNAL_ERROR); } }); - api_bindings_client_->OnPortConnected( - kCastStreamingMessagePortName, - cr_fuchsia::BlinkMessagePortFromFidl(std::move(message_port))); + api_bindings_client_->OnPortConnected(kCastStreamingMessagePortName, + std::move(message_port_for_agent)); } api_bindings_client_->AttachToFrame( @@ -187,14 +183,16 @@ OnNavigationStateChangedCallback callback) { if (change.has_is_main_document_loaded() && change.is_main_document_loaded()) { + std::string connect_message; + std::unique_ptr<cast_api_bindings::MessagePort> connect_port; + connector_->GetConnectMessage(&connect_message, &connect_port); + // Send the NamedMessagePortConnector handshake to the page. - frame()->PostMessage("*", - *cr_fuchsia::FidlWebMessageFromBlink( - connector_->GetConnectMessage(), - cr_fuchsia::TransferableHostType::kRemote), - [](fuchsia::web::Frame_PostMessage_Result result) { - DCHECK(result.is_response()); - }); + frame()->PostMessage( + "*", CreateWebMessage(connect_message, std::move(connect_port)), + [](fuchsia::web::Frame_PostMessage_Result result) { + DCHECK(result.is_response()); + }); } WebComponent::OnNavigationStateChanged(std::move(change),
diff --git a/fuchsia/runners/cast/cast_runner_integration_test.cc b/fuchsia/runners/cast/cast_runner_integration_test.cc index 4e9e32b..ee1b7563 100644 --- a/fuchsia/runners/cast/cast_runner_integration_test.cc +++ b/fuchsia/runners/cast/cast_runner_integration_test.cc
@@ -43,7 +43,6 @@ #include "fuchsia/runners/cast/cast_runner_switches.h" #include "fuchsia/runners/cast/fake_application_config_manager.h" #include "fuchsia/runners/cast/test_api_bindings.h" -#include "mojo/core/embedder/embedder.h" #include "net/test/embedded_test_server/default_handlers.h" #include "net/test/embedded_test_server/http_request.h" #include "testing/gtest/include/gtest/gtest.h" @@ -256,8 +255,6 @@ CastRunnerIntegrationTest& operator=(const CastRunnerIntegrationTest&) = delete; - void SetUp() override { mojo::core::Init(); } - void TearDown() override { if (component_controller_) ShutdownComponent();
diff --git a/fuchsia/runners/cast/create_web_message.cc b/fuchsia/runners/cast/create_web_message.cc new file mode 100644 index 0000000..53d4349 --- /dev/null +++ b/fuchsia/runners/cast/create_web_message.cc
@@ -0,0 +1,25 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "fuchsia/runners/cast/create_web_message.h" + +#include "components/cast/message_port/message_port_fuchsia.h" +#include "fuchsia/base/mem_buffer_util.h" + +fuchsia::web::WebMessage CreateWebMessage( + base::StringPiece message, + std::unique_ptr<cast_api_bindings::MessagePort> port) { + fuchsia::web::WebMessage web_message; + web_message.set_data(cr_fuchsia::MemBufferFromString(message, "msg")); + if (port) { + fuchsia::web::OutgoingTransferable outgoing_transferable; + outgoing_transferable.set_message_port( + cast_api_bindings::MessagePortFuchsia::FromMessagePort(port.get()) + ->TakeServiceRequest()); + std::vector<fuchsia::web::OutgoingTransferable> outgoing_transferables; + outgoing_transferables.push_back(std::move(outgoing_transferable)); + web_message.set_outgoing_transfer(std::move(outgoing_transferables)); + } + return web_message; +}
diff --git a/fuchsia/runners/cast/create_web_message.h b/fuchsia/runners/cast/create_web_message.h new file mode 100644 index 0000000..0be842d --- /dev/null +++ b/fuchsia/runners/cast/create_web_message.h
@@ -0,0 +1,20 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FUCHSIA_RUNNERS_CAST_CREATE_WEB_MESSAGE_H_ +#define FUCHSIA_RUNNERS_CAST_CREATE_WEB_MESSAGE_H_ + +#include <fuchsia/web/cpp/fidl.h> +#include <memory> + +#include "base/strings/string_piece.h" +#include "components/cast/message_port/message_port.h" + +// Utility function for creating a fuchsia.web.WebMessage with the payload +// |message| and an optional transferred |port|. +fuchsia::web::WebMessage CreateWebMessage( + base::StringPiece message, + std::unique_ptr<cast_api_bindings::MessagePort> port); + +#endif // FUCHSIA_RUNNERS_CAST_CREATE_WEB_MESSAGE_H_
diff --git a/fuchsia/runners/cast/main.cc b/fuchsia/runners/cast/main.cc index 88677d1..cfa18ae 100644 --- a/fuchsia/runners/cast/main.cc +++ b/fuchsia/runners/cast/main.cc
@@ -20,7 +20,6 @@ #include "fuchsia/base/inspect.h" #include "fuchsia/runners/cast/cast_runner.h" #include "fuchsia/runners/cast/cast_runner_switches.h" -#include "mojo/core/embedder/embedder.h" namespace { @@ -68,8 +67,6 @@ *base::CommandLine::ForCurrentProcess())) << "Failed to initialize logging."; - mojo::core::Init(); - cr_fuchsia::RegisterFuchsiaDirScheme(); sys::OutgoingDirectory* const outgoing_directory =
diff --git a/fuchsia/runners/cast/named_message_port_connector_fuchsia_browsertest.cc b/fuchsia/runners/cast/named_message_port_connector_fuchsia_browsertest.cc index 147ad1ab9..54252ed 100644 --- a/fuchsia/runners/cast/named_message_port_connector_fuchsia_browsertest.cc +++ b/fuchsia/runners/cast/named_message_port_connector_fuchsia_browsertest.cc
@@ -9,20 +9,26 @@ #include "base/files/file_util.h" #include "base/macros.h" #include "base/path_service.h" +#include "components/cast/message_port/message_port_fuchsia.h" +#include "components/cast/message_port/test_message_port_receiver.h" #include "content/public/test/browser_test.h" #include "fuchsia/base/fit_adapter.h" #include "fuchsia/base/frame_test_util.h" #include "fuchsia/base/mem_buffer_util.h" -#include "fuchsia/base/message_port.h" #include "fuchsia/base/result_receiver.h" #include "fuchsia/base/test_navigation_listener.h" #include "fuchsia/engine/test/web_engine_browser_test.h" +#include "fuchsia/runners/cast/create_web_message.h" #include "fuchsia/runners/cast/named_message_port_connector_fuchsia.h" #include "testing/gmock/include/gmock/gmock-matchers.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/url_constants.h" +using CastMessagePort = std::unique_ptr<cast_api_bindings::MessagePort>; + +namespace { + class NamedMessagePortConnectorFuchsiaTest : public cr_fuchsia::WebEngineBrowserTest { public: @@ -52,13 +58,14 @@ callback) { if (change.has_is_main_document_loaded() && change.is_main_document_loaded()) { - frame_->PostMessage("*", - std::move(*cr_fuchsia::FidlWebMessageFromBlink( - connector_->GetConnectMessage(), - cr_fuchsia::TransferableHostType::kRemote)), - [](fuchsia::web::Frame_PostMessage_Result result) { - DCHECK(result.is_response()); - }); + std::string connect_message; + CastMessagePort connect_port; + connector_->GetConnectMessage(&connect_message, &connect_port); + frame_->PostMessage( + "*", CreateWebMessage(connect_message, std::move(connect_port)), + [](fuchsia::web::Frame_PostMessage_Result result) { + DCHECK(result.is_response()); + }); } // Allow the TestNavigationListener's usual navigation event processing flow @@ -82,15 +89,14 @@ frame_->GetNavigationController(controller.NewRequest()); std::string received_port_name; - fidl::InterfaceHandle<fuchsia::web::MessagePort> received_port; + CastMessagePort received_port; base::RunLoop receive_port_run_loop; connector_->RegisterPortHandler(base::BindRepeating( - [](std::string* received_port_name, - fidl::InterfaceHandle<fuchsia::web::MessagePort>* received_port, + [](std::string* received_port_name, CastMessagePort* received_port, base::RunLoop* receive_port_run_loop, base::StringPiece port_name, - blink::WebMessagePort port) -> bool { + CastMessagePort port) -> bool { *received_port_name = port_name.as_string(); - *received_port = cr_fuchsia::FidlMessagePortFromBlink(std::move(port)); + *received_port = std::move(port); receive_port_run_loop->Quit(); return true; }, @@ -105,43 +111,23 @@ receive_port_run_loop.Run(); EXPECT_EQ(received_port_name, "echo"); - fuchsia::web::MessagePortPtr message_port = received_port.Bind(); + cast_api_bindings::TestMessagePortReceiver test_receiver; + received_port->SetReceiver(&test_receiver); + received_port->PostMessage("ping"); - fuchsia::web::WebMessage msg; - msg.set_data(cr_fuchsia::MemBufferFromString("ping", "test")); - cr_fuchsia::ResultReceiver<fuchsia::web::MessagePort_PostMessage_Result> - post_result; - message_port->PostMessage( - std::move(msg), - cr_fuchsia::CallbackToFitFunction(post_result.GetReceiveCallback())); + ASSERT_TRUE(test_receiver.RunUntilMessageCountEqual(3)); + EXPECT_EQ(test_receiver.buffer()[0].first, "early 1"); + EXPECT_EQ(test_receiver.buffer()[1].first, "early 2"); + EXPECT_EQ(test_receiver.buffer()[2].first, "ack ping"); - std::vector<std::string> test_messages = {"early 1", "early 2", "ack ping"}; - for (std::string expected_msg : test_messages) { - base::RunLoop run_loop; - cr_fuchsia::ResultReceiver<fuchsia::web::WebMessage> message_receiver( - run_loop.QuitClosure()); - message_port->ReceiveMessage(cr_fuchsia::CallbackToFitFunction( - message_receiver.GetReceiveCallback())); - run_loop.Run(); - - std::string data; - ASSERT_TRUE(message_receiver->has_data()); - ASSERT_TRUE( - cr_fuchsia::StringFromMemBuffer(message_receiver->data(), &data)); - EXPECT_EQ(data, expected_msg); - } + EXPECT_TRUE(received_port->CanPostMessage()); // Ensure that the MessagePort is dropped when navigating away. - { - base::RunLoop run_loop; - message_port.set_error_handler([&run_loop](zx_status_t status) { - EXPECT_EQ(ZX_ERR_PEER_CLOSED, status); - run_loop.Quit(); - }); - EXPECT_TRUE(cr_fuchsia::LoadUrlAndExpectResponse( - controller.get(), fuchsia::web::LoadUrlParams(), "about:blank")); - run_loop.Run(); - } + EXPECT_TRUE(cr_fuchsia::LoadUrlAndExpectResponse( + controller.get(), fuchsia::web::LoadUrlParams(), "about:blank")); + + test_receiver.RunUntilDisconnected(); + EXPECT_FALSE(received_port->CanPostMessage()); } // Tests that the NamedMessagePortConnectorFuchsia can receive more than one @@ -156,50 +142,34 @@ fuchsia::web::NavigationControllerPtr controller; frame_->GetNavigationController(controller.NewRequest()); - std::vector<fidl::InterfaceHandle<fuchsia::web::MessagePort>> received_ports; - base::RunLoop receive_ports_run_loop; + std::vector<CastMessagePort> received_ports; + base::RunLoop receive_port_run_loop; connector_->RegisterPortHandler(base::BindRepeating( - [](std::vector<fidl::InterfaceHandle<fuchsia::web::MessagePort>>* - received_ports, - base::RunLoop* receive_ports_run_loop, base::StringPiece, - blink::WebMessagePort port) -> bool { - received_ports->push_back( - cr_fuchsia::FidlMessagePortFromBlink(std::move(port))); + [](std::vector<CastMessagePort>* received_ports, + base::RunLoop* receive_port_run_loop, base::StringPiece port_name, + CastMessagePort port) -> bool { + received_ports->push_back(std::move(port)); if (received_ports->size() == kExpectedPortCount) - receive_ports_run_loop->Quit(); + receive_port_run_loop->Quit(); return true; }, base::Unretained(&received_ports), - base::Unretained(&receive_ports_run_loop))); + base::Unretained(&receive_port_run_loop))); EXPECT_TRUE(cr_fuchsia::LoadUrlAndExpectResponse( controller.get(), fuchsia::web::LoadUrlParams(), test_url.spec())); - navigation_listener_.RunUntilUrlEquals(test_url); - receive_ports_run_loop.Run(); + receive_port_run_loop.Run(); - for (fidl::InterfaceHandle<fuchsia::web::MessagePort>& message_port : - received_ports) { - fuchsia::web::MessagePortPtr port = message_port.Bind(); - fuchsia::web::WebMessage msg; - msg.set_data(cr_fuchsia::MemBufferFromString("ping", "test")); - cr_fuchsia::ResultReceiver<fuchsia::web::MessagePort_PostMessage_Result> - post_result; - port->PostMessage(std::move(msg), cr_fuchsia::CallbackToFitFunction( - post_result.GetReceiveCallback())); - - base::RunLoop run_loop; - cr_fuchsia::ResultReceiver<fuchsia::web::WebMessage> message_receiver( - run_loop.QuitClosure()); - port->ReceiveMessage(cr_fuchsia::CallbackToFitFunction( - message_receiver.GetReceiveCallback())); - run_loop.Run(); - - std::string data; - ASSERT_TRUE(message_receiver->has_data()); - ASSERT_TRUE( - cr_fuchsia::StringFromMemBuffer(message_receiver->data(), &data)); - EXPECT_EQ(data, "ack ping"); + ASSERT_EQ(received_ports.size(), kExpectedPortCount); + for (CastMessagePort& message_port : received_ports) { + cast_api_bindings::TestMessagePortReceiver test_receiver; + message_port->SetReceiver(&test_receiver); + message_port->PostMessage("ping"); + test_receiver.RunUntilMessageCountEqual(1); + EXPECT_EQ(test_receiver.buffer()[0].first, "ack ping"); } } + +} // namespace
diff --git a/google_apis/gcm/tools/mcs_probe.cc b/google_apis/gcm/tools/mcs_probe.cc index 1ec4f02..ce04cac6 100644 --- a/google_apis/gcm/tools/mcs_probe.cc +++ b/google_apis/gcm/tools/mcs_probe.cc
@@ -338,10 +338,11 @@ void MCSProbe::InitializeNetworkState() { if (command_line_.HasSwitch(kLogFileSwitch)) { base::FilePath log_path = command_line_.GetSwitchValuePath(kLogFileSwitch); - logger_ = net::FileNetLogObserver::CreateUnbounded(log_path, nullptr); net::NetLogCaptureMode capture_mode = net::NetLogCaptureMode::kIncludeSensitive; - logger_->StartObserving(net_log_, capture_mode); + logger_ = net::FileNetLogObserver::CreateUnbounded(log_path, capture_mode, + nullptr); + logger_->StartObserving(net_log_); } net::URLRequestContextBuilder builder;
diff --git a/infra/config/chromium-header.textpb b/infra/config/chromium-header.textpb deleted file mode 100644 index f75968f..0000000 --- a/infra/config/chromium-header.textpb +++ /dev/null
@@ -1,265 +0,0 @@ -oncalls { - name: "Chromium" - url: "https://chrome-ops-rotation-proxy.appspot.com/current/oncallator:chrome-build-sheriff" -} -oncalls { - name: "Android" - url: "https://chrome-ops-rotation-proxy.appspot.com/current/oncallator:chrome-android-sheriff" -} -oncalls { - name: "iOS" - url: "https://rota-ng.appspot.com/legacy/sheriff_ios.json" -} -oncalls { - name: "ChromeOS" - url: "https://chrome-ops-rotation-proxy.appspot.com/current/oncallator:chromeos-gardeners" -} -oncalls { - name: "GPU" - url: "https://rota-ng.appspot.com/legacy/sheriff_gpu.json" -} -oncalls { - name: "Angle" - url: "https://rota-ng.appspot.com/legacy/sheriff_angle.json" -} -oncalls { - name: "Perf" - url: "https://rota-ng.appspot.com/legacy/sheriff_perf.json" -} -oncalls { - name: "Perfbot" - url: "https://rota-ng.appspot.com/legacy/sheriff_perfbot.json" -} -oncalls { - name: "Trooper" - url: "https://chrome-ops-rotation-proxy.appspot.com/current/oncallator:chrome-ops-client-infra" - show_primary_secondary_labels: true -} -links { - name: "Builds" - links { - text: "continuous" - url: "https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html" - alt: "Continuous browser snapshots" - } - links { - text: "symbols" - url: "https://www.chromium.org/developers/how-tos/debugging-on-windows" - alt: "Windows Symbols" - } - links { - text: "status" - url: "https://chromium-status.appspot.com/" - alt: "Current tree status" - } -} -links { - name: "Dashboards" - links { - text: "perf" - url: "https://chromeperf.appspot.com/" - alt: "Chrome perf dashboard" - } - links { - text: "flake-portal" - url: "https://analysis.chromium.org/p/chromium/flake-portal" - alt: "New flake portal" - } - links { - text: "legacy-flakiness" - url: "https://test-results.appspot.com/dashboards/flakiness_dashboard.html" - alt: "Legacy flakiness dashboard" - } -} -links { - name: "Chromium" - links { - text: "source" - url: "https://chromium.googlesource.com/chromium/src" - alt: "Chromium source code repository" - } - links { - text: "reviews" - url: "https://chromium-review.googlesource.com" - alt: "Chromium code review tool" - } - links { - text: "bugs" - url: "https://crbug.com" - alt: "Chromium bug tracker" - } - links { - text: "coverage" - url: "https://analysis.chromium.org/p/chromium/coverage" - alt: "Chromium code coverage dashboard" - } - links { - text: "dev" - url: "https://dev.chromium.org/Home" - alt: "Chromium developer home page" - } - links { - text: "support" - url: "https://support.google.com/chrome/#topic=7438008" - alt: "Google Chrome help center" - } -} -links { - name: "Consoles" - links { - text: "android" - url: "/p/chromium/g/chromium.android" - alt: "Chromium Android console" - } - links { - text: "clang" - url: "/p/chromium/g/chromium.clang" - alt: "Chromium Clang console" - } - links { - text: "dawn" - url: "/p/chromium/g/chromium.dawn" - alt: "Chromium Dawn console" - } - links { - text: "fuzz" - url: "/p/chromium/g/chromium.fuzz" - alt: "Chromium Fuzz console" - } - links { - text: "fyi" - url: "/p/chromium/g/chromium.fyi" - alt: "Chromium FYI console" - } - links { - text: "gpu" - url: "/p/chromium/g/chromium.gpu" - alt: "Chromium GPU console" - } - links { - text: "perf" - url: "/p/chrome/g/chrome.perf/console" - alt: "Chromium Perf console" - } - links { - text: "perf.fyi" - url: "/p/chrome/g/chrome.perf.fyi/console" - alt: "Chromium Perf FYI console" - } - links { - text: "swangle" - url: "/p/chromium/g/chromium.swangle" - alt: "Chromium SWANGLE console" - } - links { - text: "webrtc" - url: "/p/chromium/g/chromium.webrtc" - alt: "Chromium WebRTC console" - } - links { - text: "chromiumos" - url: "/p/chromium/g/chromium.chromiumos" - alt: "ChromiumOS console" - } -} -links { - name: "Branch Consoles" - links { - text: "m87" - url: "/p/chromium-m87/g/main/console" - alt: "Beta branch console" - } - links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { - text: "trunk" - url: "/p/chromium/g/main/console" - alt: "Trunk (ToT) console" - } -} -links { - name: "Tryservers" - links { - text: "android" - url: "/p/chromium/g/tryserver.chromium.android/builders" - alt: "Android" - } - links { - text: "angle" - url: "/p/chromium/g/tryserver.chromium.angle/builders" - alt: "Angle" - } - links { - text: "blink" - url: "/p/chromium/g/tryserver.blink/builders" - alt: "Blink" - } - links { - text: "chrome" - url: "/p/chrome/g/tryserver.chrome/builders" - alt: "Chrome" - } - links { - text: "chromiumos" - url: "/p/chromium/g/tryserver.chromium.chromiumos/builders" - alt: "ChromiumOS" - } - links { - text: "linux" - url: "/p/chromium/g/tryserver.chromium.linux/builders" - alt: "Linux" - } - links { - text: "mac" - url: "/p/chromium/g/tryserver.chromium.mac/builders" - alt: "Mac" - } - links { - text: "swangle" - url: "/p/chromium/g/tryserver.chromium.swangle/builders" - alt: "SWANGLE" - } - links { - text: "win" - url: "/p/chromium/g/tryserver.chromium.win/builders" - alt: "Win" - } -} -links { - name: "Navigate" - links { - text: "about" - url: "http://dev.chromium.org/developers/testing/chromium-build-infrastructure/tour-of-the-chromium-buildbot" - alt: "Tour of the console" - } - links { - text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" - alt: "Customize this console" - } -} -console_groups { - title { - text: "Tree Closers" - url: "https://chromium-status.appspot.com/" - } - console_ids: "chromium/chromium" - console_ids: "chromium/chromium.win" - console_ids: "chromium/chromium.mac" - console_ids: "chromium/chromium.linux" - console_ids: "chromium/chromium.chromiumos" - console_ids: "chrome/chrome" - console_ids: "chromium/chromium.memory" - console_ids: "chromium/chromium.gpu" -} -console_groups { - console_ids: "chromium/chromium.android" - console_ids: "chrome/chrome.perf" - console_ids: "chromium/chromium.gpu.fyi" - console_ids: "chromium/chromium.swangle" - console_ids: "chromium/chromium.fuzz" -} -tree_status_host: "chromium-status.appspot.com"
diff --git a/infra/config/console-header.star b/infra/config/console-header.star new file mode 100644 index 0000000..03d67a3 --- /dev/null +++ b/infra/config/console-header.star
@@ -0,0 +1,400 @@ +# Copyright 2020 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +load("//lib/branches.star", "branches") +load(".//project.star", "ACTIVE_MILESTONES", "settings") + +def _remove_none(l): + return [e for e in l if e != None] + +def _remove_none_values(d): + return {k: v for k, v in d.items() if v != None} + +def _oncall(*, name, url, show_primary_secondary_labels = None, branch_selector = branches.MAIN): + if not branches.matches(branch_selector): + return None + return _remove_none_values(dict( + name = name, + url = url, + show_primary_secondary_labels = show_primary_secondary_labels, + )) + +def _link(*, url, text, alt, branch_selector = branches.MAIN): + if not branches.matches(branch_selector): + return None + return _remove_none_values(dict( + url = url, + text = text, + alt = alt, + )) + +def _link_group(*, name, links): + links = _remove_none(links) + if not links: + return None + return _remove_none_values(dict( + name = name, + links = links, + )) + +def _console_group_title(*, text, url): + return _remove_none_values(dict( + text = text, + url = url, + )) + +def _console_group(*, console_ids, title = None, branch_selector = branches.MAIN): + if not branches.matches(branch_selector): + return None + console_ids = _remove_none(console_ids) + if not console_ids: + return None + return _remove_none_values(dict( + title = title, + console_ids = console_ids, + )) + +def _header(*, oncalls, link_groups, console_groups, tree_status_host): + return _remove_none_values(dict( + oncalls = _remove_none(oncalls), + links = _remove_none(link_groups), + console_groups = _remove_none(console_groups), + tree_status_host = tree_status_host, + )) + +HEADER = _header( + oncalls = [ + _oncall( + name = "Chromium", + url = "https://chrome-ops-rotation-proxy.appspot.com/current/oncallator:chrome-build-sheriff", + ), + _oncall( + name = "Chromium Branches", + branch_selector = branches.NOT_MAIN, + url = "https://chrome-ops-rotation-proxy.appspot.com/current/oncallator:chrome-branch-sheriff", + ), + _oncall( + name = "Android", + url = "https://chrome-ops-rotation-proxy.appspot.com/current/oncallator:chrome-android-sheriff", + ), + _oncall( + name = "iOS", + url = "https://rota-ng.appspot.com/legacy/sheriff_ios.json", + ), + _oncall( + name = "ChromeOS", + url = "https://chrome-ops-rotation-proxy.appspot.com/current/oncallator:chromeos-gardeners", + ), + _oncall( + name = "GPU", + url = "https://rota-ng.appspot.com/legacy/sheriff_gpu.json", + ), + _oncall( + name = "Angle", + url = "https://rota-ng.appspot.com/legacy/sheriff_angle.json", + ), + _oncall( + name = "Perf", + url = "https://rota-ng.appspot.com/legacy/sheriff_perf.json", + ), + _oncall( + name = "Perfbot", + url = "https://rota-ng.appspot.com/legacy/sheriff_perfbot.json", + ), + _oncall( + name = "Trooper", + branch_selector = branches.ALL_BRANCHES, + url = "https://chrome-ops-rotation-proxy.appspot.com/current/oncallator:chrome-ops-client-infra", + show_primary_secondary_labels = True, + ), + ], + link_groups = [ + _link_group( + name = "Builds", + links = [ + _link( + text = "continuous", + branch_selector = branches.ALL_BRANCHES, + url = "https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html", + alt = "Continuous browser snapshots", + ), + _link( + text = "symbols", + branch_selector = branches.ALL_BRANCHES, + url = "https://www.chromium.org/developers/how-tos/debugging-on-windows", + alt = "Windows Symbols", + ), + _link( + text = "status", + url = "https://chromium-status.appspot.com/", + alt = "Current tree status", + ), + ], + ), + _link_group( + name = "Dashboards", + links = [ + _link( + text = "perf", + branch_selector = branches.ALL_BRANCHES, + url = "https://chromeperf.appspot.com/", + alt = "Chrome perf dashboard", + ), + _link( + text = "flake-portal", + branch_selector = branches.ALL_BRANCHES, + url = "https://analysis.chromium.org/p/chromium/flake-portal", + alt = "New flake portal", + ), + _link( + text = "legacy-flakiness", + branch_selector = branches.ALL_BRANCHES, + url = "https://test-results.appspot.com/dashboards/flakiness_dashboard.html", + alt = "Legacy flakiness dashboard", + ), + ], + ), + _link_group( + name = "Chromium", + links = [ + _link( + text = "source", + branch_selector = branches.ALL_BRANCHES, + url = branches.value( + for_main = "https://chromium.googlesource.com/chromium/src", + for_branches = "https://chromium.googlesource.com/chromium/src/+/{}".format(settings.ref), + ), + alt = "Chromium source code repository", + ), + _link( + text = "reviews", + branch_selector = branches.ALL_BRANCHES, + url = "https://chromium-review.googlesource.com", + alt = "Chromium code review tool", + ), + _link( + text = "bugs", + branch_selector = branches.ALL_BRANCHES, + url = "https://crbug.com", + alt = "Chromium bug tracker", + ), + _link( + text = "coverage", + branch_selector = branches.ALL_BRANCHES, + url = "https://analysis.chromium.org/p/chromium/coverage", + alt = "Chromium code coverage dashboard", + ), + _link( + text = "dev", + branch_selector = branches.ALL_BRANCHES, + url = "https://dev.chromium.org/Home", + alt = "Chromium developer home page", + ), + _link( + text = "support", + branch_selector = branches.ALL_BRANCHES, + url = "https://support.google.com/chrome/#topic=7438008", + alt = "Google Chrome help center", + ), + ], + ), + _link_group( + name = "Consoles", + links = [ + _link( + text = "android", + branch_selector = branches.ALL_BRANCHES, + url = "/p/{}/g/chromium.android".format(settings.project), + alt = "Chromium Android console", + ), + _link( + text = "clang", + url = "/p/{}/g/chromium.clang".format(settings.project), + alt = "Chromium Clang console", + ), + _link( + text = "dawn", + branch_selector = branches.ALL_BRANCHES, + url = "/p/{}/g/chromium.dawn".format(settings.project), + alt = "Chromium Dawn console", + ), + _link( + text = "fuzz", + url = "/p/{}/g/chromium.fuzz".format(settings.project), + alt = "Chromium Fuzz console", + ), + _link( + text = "fyi", + branch_selector = branches.ALL_BRANCHES, + url = "/p/{}/g/chromium.fyi".format(settings.project), + alt = "Chromium FYI console", + ), + _link( + text = "gpu", + branch_selector = branches.ALL_BRANCHES, + url = "/p/{}/g/chromium.gpu".format(settings.project), + alt = "Chromium GPU console", + ), + _link( + text = "perf", + url = "/p/chrome/g/chrome.perf/console", + alt = "Chromium Perf console", + ), + _link( + text = "perf.fyi", + url = "/p/chrome/g/chrome.perf.fyi/console", + alt = "Chromium Perf FYI console", + ), + _link( + text = "swangle", + url = "/p/{}/g/chromium.swangle".format(settings.project), + alt = "Chromium SWANGLE console", + ), + _link( + text = "webrtc", + url = "/p/{}/g/chromium.webrtc".format(settings.project), + alt = "Chromium WebRTC console", + ), + _link( + text = "chromiumos", + branch_selector = branches.ALL_BRANCHES, + url = "/p/{}/g/chromium.chromiumos".format(settings.project), + alt = "ChromiumOS console", + ), + ], + ), + _link_group( + name = "Branch Consoles", + links = [ + _link( + text = milestone, + url = "/p/{}/g/main/console".format(details.project), + alt = "{} branch console".format(details.channel), + ) + for milestone, details in sorted(ACTIVE_MILESTONES.items()) + ] + [ + _link( + text = "trunk", + branch_selector = branches.ALL_BRANCHES, + url = "/p/chromium/g/main/console", + alt = "Trunk (ToT) console", + ), + ], + ), + _link_group( + name = "Tryservers", + links = [ + _link( + text = "android", + branch_selector = branches.ALL_BRANCHES, + url = "/p/{}/g/tryserver.chromium.android/builders".format(settings.project), + alt = "Android", + ), + _link( + text = "angle", + url = "/p/{}/g/tryserver.chromium.angle/builders".format(settings.project), + alt = "Angle", + ), + _link( + text = "blink", + branch_selector = branches.ALL_BRANCHES, + url = "/p/{}/g/tryserver.blink/builders".format(settings.project), + alt = "Blink", + ), + _link( + text = "chrome", + url = "/p/chrome/g/tryserver.chrome/builders", + alt = "Chrome", + ), + _link( + text = "chromiumos", + branch_selector = branches.ALL_BRANCHES, + url = "/p/{}/g/tryserver.chromium.chromiumos/builders".format(settings.project), + alt = "ChromiumOS", + ), + _link( + text = "linux", + branch_selector = branches.ALL_BRANCHES, + url = "/p/{}/g/tryserver.chromium.linux/builders".format(settings.project), + alt = "Linux", + ), + _link( + text = "mac", + branch_selector = branches.ALL_BRANCHES, + url = "/p/{}/g/tryserver.chromium.mac/builders".format(settings.project), + alt = "Mac", + ), + _link( + text = "swangle", + url = "/p/{}/g/tryserver.chromium.swangle/builders".format(settings.project), + alt = "SWANGLE", + ), + _link( + text = "win", + branch_selector = branches.ALL_BRANCHES, + url = "/p/{}/g/tryserver.chromium.win/builders".format(settings.project), + alt = "Win", + ), + ], + ), + _link_group( + name = "Navigate", + links = [ + _link( + text = "about", + branch_selector = branches.ALL_BRANCHES, + url = "http://dev.chromium.org/developers/testing/chromium-build-infrastructure/tour-of-the-chromium-buildbot", + alt = "Tour of the console", + ), + _link( + text = "customize", + branch_selector = branches.ALL_BRANCHES, + url = "https://chromium.googlesource.com/chromium/src/+/{}/infra/config/generated/luci-milo.cfg".format(settings.ref), + alt = "Customize this console", + ), + ], + ), + ], + console_groups = [ + _console_group( + title = _console_group_title( + text = "Tree Closers", + url = "https://chromium-status.appspot.com/", + ), + console_ids = [ + "chromium/chromium", + "chromium/chromium.win", + "chromium/chromium.mac", + "chromium/chromium.linux", + "chromium/chromium.chromiumos", + "chrome/chrome", + "chromium/chromium.memory", + "chromium/chromium.gpu", + ], + ), + _console_group( + console_ids = [ + "chromium/chromium.android", + "chrome/chrome.perf", + "chromium/chromium.gpu.fyi", + "chromium/chromium.swangle", + "chromium/chromium.fuzz", + ], + ), + _console_group( + branch_selector = branches.NOT_MAIN, + console_ids = ["{}/{}".format(settings.project, c) for c in [ + "chromium", + "chromium.win", + "chromium.mac", + "chromium.linux", + "chromium.chromiumos", + "chromium.memory", + "chromium.gpu", + "chromium.android", + ]], + ), + ], + tree_status_host = settings.tree_status_host, +)
diff --git a/infra/config/generated/commit-queue.cfg b/infra/config/generated/commit-queue.cfg index 18a7f3d..49ee9fb1 100644 --- a/infra/config/generated/commit-queue.cfg +++ b/infra/config/generated/commit-queue.cfg
@@ -26,7 +26,7 @@ dry_run_access_list: "project-chromium-tryjob-access" } tree_status { - url: "https://chromium-status.appspot.com/" + url: "https://chromium-status.appspot.com" } tryjob { builders {
diff --git a/infra/config/generated/luci-milo.cfg b/infra/config/generated/luci-milo.cfg index a48f8fe5..442a2921 100644 --- a/infra/config/generated/luci-milo.cfg +++ b/infra/config/generated/luci-milo.cfg
@@ -668,16 +668,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -740,7 +740,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } } @@ -1362,16 +1362,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -1434,7 +1434,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } } @@ -1671,16 +1671,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -1743,7 +1743,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } } @@ -2118,16 +2118,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -2190,7 +2190,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } } @@ -2462,16 +2462,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -2534,7 +2534,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } } @@ -2950,16 +2950,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -3022,7 +3022,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } } @@ -3254,16 +3254,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -3326,7 +3326,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } } @@ -3593,16 +3593,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -3665,7 +3665,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } } @@ -4076,16 +4076,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -4148,7 +4148,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } } @@ -4475,16 +4475,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -4547,7 +4547,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } } @@ -4903,16 +4903,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -4975,7 +4975,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } } @@ -5559,16 +5559,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -5631,7 +5631,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } } @@ -5930,16 +5930,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -6002,7 +6002,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } } @@ -6318,16 +6318,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -6390,7 +6390,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } } @@ -6653,16 +6653,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -6725,7 +6725,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } } @@ -7342,16 +7342,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -7414,7 +7414,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } } @@ -7716,16 +7716,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -7788,7 +7788,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } } @@ -8060,16 +8060,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -8132,7 +8132,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } } @@ -8429,16 +8429,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -8501,7 +8501,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } } @@ -8727,16 +8727,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -8799,7 +8799,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } } @@ -9076,16 +9076,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -9148,7 +9148,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } } @@ -9400,16 +9400,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -9472,7 +9472,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } } @@ -9764,16 +9764,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -9836,7 +9836,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } } @@ -10098,16 +10098,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -10170,7 +10170,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } } @@ -10507,16 +10507,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -10579,7 +10579,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } } @@ -10837,16 +10837,16 @@ links { name: "Branch Consoles" links { + text: "m86" + url: "/p/chromium-m86/g/main/console" + alt: "Stable branch console" + } + links { text: "m87" url: "/p/chromium-m87/g/main/console" alt: "Beta branch console" } links { - text: "m86" - url: "/p/chromium/g/main-m86/console" - alt: "Stable branch console" - } - links { text: "trunk" url: "/p/chromium/g/main/console" alt: "Trunk (ToT) console" @@ -10909,7 +10909,7 @@ } links { text: "customize" - url: "https://chromium.googlesource.com/chromium/src/+/master/infra/config/luci-milo.cfg" + url: "https://chromium.googlesource.com/chromium/src/+/refs/heads/master/infra/config/generated/luci-milo.cfg" alt: "Customize this console" } }
diff --git a/infra/config/lib/ci.star b/infra/config/lib/ci.star index 1ebbb4d..5be49c0 100644 --- a/infra/config/lib/ci.star +++ b/infra/config/lib/ci.star
@@ -69,7 +69,6 @@ ci.overview_console_view( name = name, branch_selector = branch_selector, - header = "//chromium-header.textpb", repo = "https://chromium.googlesource.com/chromium/src", refs = [milestone_vars.ref], title = title, @@ -103,7 +102,6 @@ cpu = builders.cpu.X86_64, executable = "recipe:chromium", execution_timeout = 3 * time.hour, - header = "//chromium-header.textpb", os = builders.os.LINUX_DEFAULT, pool = "luci.chromium.ci", project_trigger_overrides = {"chromium": settings.project} if not settings.is_master else None,
diff --git a/infra/config/project.star b/infra/config/project.star index 7ff3b9f7..75ba6c9 100644 --- a/infra/config/project.star +++ b/infra/config/project.star
@@ -22,7 +22,7 @@ main_list_view_name = "try", main_list_view_title = "Chromium CQ console", # Switch this to None for branches - tree_status_host = "chromium-status.appspot.com/", + tree_status_host = "chromium-status.appspot.com", ) def _validate_settings(): @@ -47,12 +47,37 @@ lucicfg.generator(_generate_project_pyl) +def _milestone_details(*, project, ref, channel): + """Define the details for an active milestone. + + Args: + * project - The name of the LUCI project that is configured for the + milestone. + * ref - The ref in the git repository that contains the code for the + milestone. + * channel - The name of the release channel the milestone is in (used for + identifying the milestone in the console header). + """ + return struct( + project = project, + ref = ref, + channel = channel, + ) + # The milestone names and branch numbers of branches that we have builders # running for (including milestone-specific projects) # Branch numbers and milestones can be viewed in the chromium column at # https://chromiumdash.appspot.com/branches # The 2 highest milestones will be the ones with active branches -ACTIVE_BRANCHES = [ - ("m86", 4240), - ("m87", 4280), -] +ACTIVE_MILESTONES = { + "m86": _milestone_details( + project = "chromium-m86", + ref = "refs/branch-heads/4240", + channel = "Stable", + ), + "m87": _milestone_details( + project = "chromium-m87", + ref = "refs/branch-heads/4280", + channel = "Beta", + ), +}
diff --git a/infra/config/subprojects/chromium/ci.star b/infra/config/subprojects/chromium/ci.star index a6baf65..a2569f22 100644 --- a/infra/config/subprojects/chromium/ci.star +++ b/infra/config/subprojects/chromium/ci.star
@@ -5,6 +5,7 @@ load("//lib/branches.star", "branches") load("//lib/builders.star", "builder_name", "cpu", "goma", "os", "xcode_cache") load("//lib/ci.star", "ci") +load("//console-header.star", "HEADER") load("//project.star", "settings") def main_console_if_on_branch(): @@ -13,6 +14,7 @@ ci.set_defaults( settings, add_to_console_view = True, + header = HEADER, ) ci.declare_bucket(settings, branch_selector = branches.ALL_BRANCHES)
diff --git a/infra/config/subprojects/chromium/consoles/android.packager.star b/infra/config/subprojects/chromium/consoles/android.packager.star index a99a5f24..56c88db 100644 --- a/infra/config/subprojects/chromium/consoles/android.packager.star +++ b/infra/config/subprojects/chromium/consoles/android.packager.star
@@ -2,9 +2,11 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +load("//console-header.star", "HEADER") + luci.console_view( name = "android.packager", - header = "//chromium-header.textpb", + header = HEADER, repo = "https://chromium.googlesource.com/chromium/src", entries = [ luci.console_view_entry(
diff --git a/infra/config/subprojects/chromium/consoles/sheriff.ios.star b/infra/config/subprojects/chromium/consoles/sheriff.ios.star index 34f0276..f0b22099 100644 --- a/infra/config/subprojects/chromium/consoles/sheriff.ios.star +++ b/infra/config/subprojects/chromium/consoles/sheriff.ios.star
@@ -2,9 +2,11 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +load("//console-header.star", "HEADER") + luci.console_view( name = "sheriff.ios", - header = "//chromium-header.textpb", + header = HEADER, repo = "https://chromium.googlesource.com/chromium/src", title = "iOS Sheriff Console", entries = [
diff --git a/infra/config/subprojects/chromium/fallback-cq.star b/infra/config/subprojects/chromium/fallback-cq.star index 4919e92..79a2ff6 100644 --- a/infra/config/subprojects/chromium/fallback-cq.star +++ b/infra/config/subprojects/chromium/fallback-cq.star
@@ -2,7 +2,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -load("//project.star", "ACTIVE_BRANCHES") +load("//project.star", "ACTIVE_MILESTONES") # Declare a CQ group that watches all branch heads, excluding the active # branches. We won't add any builders, but SUBMIT TO CQ fails on Gerrit if there @@ -14,8 +14,8 @@ repo = "https://chromium.googlesource.com/chromium/src", refs = ["refs/branch-heads/.*"], refs_exclude = [ - "refs/branch-heads/{}".format(branch_name) - for _, branch_name in ACTIVE_BRANCHES + details.ref + for details in ACTIVE_MILESTONES.values() ], ), acls = [
diff --git a/infra/config/subprojects/goma/consoles/chromium.goma.fyi.star b/infra/config/subprojects/goma/consoles/chromium.goma.fyi.star index 9ace3a66..f1588ce 100644 --- a/infra/config/subprojects/goma/consoles/chromium.goma.fyi.star +++ b/infra/config/subprojects/goma/consoles/chromium.goma.fyi.star
@@ -2,9 +2,11 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +load("//console-header.star", "HEADER") + luci.console_view( name = "chromium.goma.fyi", - header = "//chromium-header.textpb", + header = HEADER, include_experimental_builds = True, repo = "https://chromium.googlesource.com/chromium/src", entries = [
diff --git a/infra/config/subprojects/goma/consoles/chromium.goma.star b/infra/config/subprojects/goma/consoles/chromium.goma.star index 8c03e4f..5cdd0cd 100644 --- a/infra/config/subprojects/goma/consoles/chromium.goma.star +++ b/infra/config/subprojects/goma/consoles/chromium.goma.star
@@ -2,9 +2,11 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +load("//console-header.star", "HEADER") + luci.console_view( name = "chromium.goma", - header = "//chromium-header.textpb", + header = HEADER, include_experimental_builds = True, repo = "https://chromium.googlesource.com/chromium/src", entries = [
diff --git a/infra/config/subprojects/goma/consoles/goma.latest.star b/infra/config/subprojects/goma/consoles/goma.latest.star index f64d8a0..4bf267b 100644 --- a/infra/config/subprojects/goma/consoles/goma.latest.star +++ b/infra/config/subprojects/goma/consoles/goma.latest.star
@@ -2,9 +2,11 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +load("//console-header.star", "HEADER") + luci.console_view( name = "goma.latest", - header = "//chromium-header.textpb", + header = HEADER, repo = "https://chromium.googlesource.com/chromium/src", entries = [ luci.console_view_entry(
diff --git a/infra/config/subprojects/goma/consoles/luci.chromium.goma.star b/infra/config/subprojects/goma/consoles/luci.chromium.goma.star index 4caec56b..dee42df 100644 --- a/infra/config/subprojects/goma/consoles/luci.chromium.goma.star +++ b/infra/config/subprojects/goma/consoles/luci.chromium.goma.star
@@ -2,9 +2,11 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +load("//console-header.star", "HEADER") + luci.console_view( name = "luci.chromium.goma", - header = "//chromium-header.textpb", + header = HEADER, include_experimental_builds = True, repo = "https://chromium.googlesource.com/chromium/src", entries = [
diff --git a/infra/config/subprojects/webrtc/consoles/chromium.webrtc.fyi.star b/infra/config/subprojects/webrtc/consoles/chromium.webrtc.fyi.star index a5b390c..cd5f7e3 100644 --- a/infra/config/subprojects/webrtc/consoles/chromium.webrtc.fyi.star +++ b/infra/config/subprojects/webrtc/consoles/chromium.webrtc.fyi.star
@@ -2,9 +2,11 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +load("//console-header.star", "HEADER") + luci.console_view( name = "chromium.webrtc.fyi", - header = "//chromium-header.textpb", + header = HEADER, repo = "https://webrtc.googlesource.com/src", entries = [ luci.console_view_entry(
diff --git a/infra/config/subprojects/webrtc/consoles/chromium.webrtc.star b/infra/config/subprojects/webrtc/consoles/chromium.webrtc.star index e5d92b63..dddc534 100644 --- a/infra/config/subprojects/webrtc/consoles/chromium.webrtc.star +++ b/infra/config/subprojects/webrtc/consoles/chromium.webrtc.star
@@ -2,9 +2,11 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +load("//console-header.star", "HEADER") + luci.console_view( name = "chromium.webrtc", - header = "//chromium-header.textpb", + header = HEADER, repo = "https://chromium.googlesource.com/chromium/src", entries = [ luci.console_view_entry(
diff --git a/infra/config/swarming.star b/infra/config/swarming.star index f035bfcc..ca00e46 100644 --- a/infra/config/swarming.star +++ b/infra/config/swarming.star
@@ -8,7 +8,7 @@ """ load("//lib/swarming.star", "swarming") -load("//project.star", "ACTIVE_BRANCHES") +load("//project.star", "ACTIVE_MILESTONES") # Set up permissions that apply to all Chromium pools. swarming.root_permissions() @@ -58,7 +58,7 @@ # projects). swarming.pool_realm( name = "pools/ci", - projects = ["chromium-%s" % m for m, _ in ACTIVE_BRANCHES], + projects = [details.project for details in ACTIVE_MILESTONES.values()], ) # Realm with bots that run try builds. @@ -66,7 +66,7 @@ # The tasks here are also triggered via Buildbucket. See comment above. swarming.pool_realm( name = "pools/try", - projects = ["chromium-%s" % m for m, _ in ACTIVE_BRANCHES], + projects = [details.project for details in ACTIVE_MILESTONES.values()], ) # LED users that can trigger try builds via LED.
diff --git a/ios/chrome/app/strings/resources/ios_chromium_strings_ne.xtb b/ios/chrome/app/strings/resources/ios_chromium_strings_ne.xtb index 9940ab41..2bc28e7 100644 --- a/ios/chrome/app/strings/resources/ios_chromium_strings_ne.xtb +++ b/ios/chrome/app/strings/resources/ios_chromium_strings_ne.xtb
@@ -37,7 +37,7 @@ <translation id="5224391634244552924">कुनै पनि पासवर्ड सुरक्षित गरिएको छैन। तपाईंले आफ्ना पासवर्डहरू सुरक्षित गर्नुभएको छ भने मात्र Chromium ले तिनको जाँच गर्न सक्छ।</translation> <translation id="5308226104666789935">Chromium ले अपडेटहरू उपलब्ध छन् कि छैनन् भन्ने कुरा जाँच गर्न सकेन</translation> <translation id="5521125884468363740">आफूले Chromium प्रयोग गर्ने सबै यन्त्रमा खोलिएका ट्याबहरू हेर्न साइन इन गर्नुहोस् र सिंक गर्ने सुविधा अन गर्नुहोस्</translation> -<translation id="5573014823074921752">Chromium सम्बन्धी सुझाव। ट्याबसम्बन्धी थप विकल्पहरू हेर्न तपाईंको स्क्रिनको सिरान वा पुछारमा रहेको उपकरणपट्टीमा ट्याबहरू देखाउनुहोस् नामक बटनमा छोइराख्नुहोस्।</translation> +<translation id="5573014823074921752">Chromium सम्बन्धी सुझाव। ट्याबसम्बन्धी थप विकल्पहरू हेर्न तपाईंको स्क्रिनको सिरान वा पुछारमा रहेको उपकरणपट्टीमा ट्याबहरू देखाउनुहोस् नामक बटनमा टच एण्ड होल्ड गर्नुहोस्।</translation> <translation id="5700709190537129682">Chromium ले तपाईंका पासवर्डहरू जाँच्न सकेन</translation> <translation id="5777187867430702742">Chromium को पृष्ठ</translation> <translation id="5862307444128926510">Chromium मा स्वागतम्</translation>
diff --git a/ios/chrome/app/strings/resources/ios_google_chrome_strings_ne.xtb b/ios/chrome/app/strings/resources/ios_google_chrome_strings_ne.xtb index 93820b4..dde8d0d9 100644 --- a/ios/chrome/app/strings/resources/ios_google_chrome_strings_ne.xtb +++ b/ios/chrome/app/strings/resources/ios_google_chrome_strings_ne.xtb
@@ -35,7 +35,7 @@ <translation id="415767770115540173">तपाईंको स्थानमा आधारित Chrome मा उत्तम Google अनुभव प्राप्त गर्नुहोस्।</translation> <translation id="417201473131094001">Chrome क्यानेरीमा प्रयोग गर्न मिल्दैन</translation> <translation id="424864128008805179">Chrome बाट साइन आउट गर्ने हो?</translation> -<translation id="4249068189593983585">Chrome सम्बन्धी सुझाव। ट्यापसम्बन्धी थप विकल्पहरू हेर्न, तपाईंको स्क्रिनको सिरान वा पुछारमा रहेको उपकरणपट्टीमा ट्याबहरू देखाउनुहोस् नामक बटनमा छोइराख्नुहोस्।</translation> +<translation id="4249068189593983585">Chrome सम्बन्धी सुझाव। ट्यापसम्बन्धी थप विकल्पहरू हेर्न, तपाईंको स्क्रिनको सिरान वा पुछारमा रहेको उपकरणपट्टीमा ट्याबहरू देखाउनुहोस् नामक बटनमा टच एण्ड होल्ड गर्नुहोस्।</translation> <translation id="4523886039239821078">केही एड्-अनहरूले गर्दा Chrome लाई क्र्याश गराउँछ। कृपया विस्थापन गर्नुहोस्:</translation> <translation id="4633328489441962921">Chrome ले अपडेटहरू उपलब्ध छन् कि छैनन् भन्ने कुरा जाँच गर्न सकेन</translation> <translation id="4698415050768537821">Chrome ले सबै पासवर्डहरू जाँच्न सकेन। भोलि फेरि प्रयास गर्नुहोस् वा <ph name="BEGIN_LINK" />आफ्नो Google खातामा रहेका पासवर्डहरू जाँच्नुहोस्<ph name="END_LINK" /></translation>
diff --git a/ios/chrome/app/strings/resources/ios_google_chrome_strings_ru.xtb b/ios/chrome/app/strings/resources/ios_google_chrome_strings_ru.xtb index 69b40c5..ef82eb6 100644 --- a/ios/chrome/app/strings/resources/ios_google_chrome_strings_ru.xtb +++ b/ios/chrome/app/strings/resources/ios_google_chrome_strings_ru.xtb
@@ -40,7 +40,7 @@ <translation id="4633328489441962921">Браузеру Chrome не удается проверить наличие обновлений</translation> <translation id="4698415050768537821">Браузеру Chrome не удается проверить все пароли. Повторите попытку завтра или <ph name="BEGIN_LINK" />проверьте пароли в аккаунте Google<ph name="END_LINK" />.</translation> <translation id="484033449593719797">Проверка не поддерживается в бета-версии Chrome</translation> -<translation id="5030102366287574140">Chrome поможет обеспечить защиту от утечки данных, подозрительных сайтов и других проблем с безопасностью.</translation> +<translation id="5030102366287574140">Chrome поможет защитить вас от утечки данных, подозрительных сайтов и других проблем с безопасностью.</translation> <translation id="5162467219239570114">Версия Chrome устарела. Если в <ph name="BEGIN_LINK" />App Store<ph name="END_LINK" /> нет обновлений, возможно, ваше устройство не поддерживает новые версии Chrome.</translation> <translation id="5389212809648216794">Google Chrome не может получить доступ к камере, поскольку она используется другим приложением.</translation> <translation id="5639704535586432836">Откройте "Настройки > Конфиденциальность > Камера > Chrome" и включите камеру.</translation> @@ -55,7 +55,7 @@ <translation id="6648150602980899529">Вы входите в аккаунт, которым управляет администратор домена <ph name="DOMAIN" />. Он может контролировать ваши данные Chrome, причем теперь они будут связаны с управляемым аккаунтом. При выходе из системы все данные Chrome, хранящиеся на этом устройстве, будут удалены, но останутся в вашем аккаунте Google.</translation> <translation id="6676840375528380067">Удалить данные Chrome с этого устройства?</translation> <translation id="6822673484890854830">Браузеру Chrome не удается проверить все пароли. Повторите попытку позже.</translation> -<translation id="7161390184744336561">Версия Google Chrome устарела</translation> +<translation id="7161390184744336561">Версия Google Chrome устарела.</translation> <translation id="7165736900384873061">Используйте QR-сканер в Google Chrome</translation> <translation id="7172660552945675509">Совет. <ph name="BEGIN_LINK" />Добавьте Chrome в Dock.<ph name="END_LINK" /></translation> <translation id="7173660919484573146">Чтобы исключить несанкционированный доступ к паролям, Chrome использует функцию Face ID.</translation>
diff --git a/ios/chrome/app/strings/resources/ios_google_chrome_strings_ur.xtb b/ios/chrome/app/strings/resources/ios_google_chrome_strings_ur.xtb index 82e1a2e..ec72367e 100644 --- a/ios/chrome/app/strings/resources/ios_google_chrome_strings_ur.xtb +++ b/ios/chrome/app/strings/resources/ios_google_chrome_strings_ur.xtb
@@ -40,7 +40,7 @@ <translation id="4633328489441962921">Chrome اپ ڈیٹس چیک نہیں کر سکتا ہے</translation> <translation id="4698415050768537821">Chrome سبھی پاس ورڈز چیک نہیں کر سکا۔ آئندہ کل دوبارہ کوشش کریں یا <ph name="BEGIN_LINK" />اپنے Google اکاؤنٹ میں پاس ورڈز چیک کریں۔<ph name="END_LINK" /></translation> <translation id="484033449593719797">Chrome بی ٹا پر تعاون یافتہ نہیں ہے</translation> -<translation id="5030102366287574140">Chrome آپ کو ڈیٹا کی خلاف ورزیوں، غیر محفوظ ویب سائٹس اور بہت کچھ سے محفوظ رکھنے میں مدد کر سکتا ہے</translation> +<translation id="5030102366287574140">Chrome آپ کو ڈیٹا کی خلاف ورزیوں، غیر محفوظ ویب سائٹوں اور مزید بہت کچھ سے محفوظ رکھنے میں مدد کر سکتا ہے</translation> <translation id="5162467219239570114">Chrome پرانا ہے۔ اگر کوئی اپ ڈیٹ <ph name="BEGIN_LINK" />App اسٹور<ph name="END_LINK" /> میں دستیاب نہیں ہے تو یہ ممکن ہے کہ آپ کا آلہ مزید Chrome کے نئے ورژنز کو سپورٹ نہیں کرتا ہے۔</translation> <translation id="5389212809648216794">Google Chrome آپ کا کیمرا استعمال نہیں کر سکتا ہے کیونکہ یہ کسی دوسری ایپلیکیشن کے زیر استعمال ہے</translation> <translation id="5639704535586432836">ترتیبات > رازداری > کیمرا > Google Chrome کھولیں اور کیمرا آن کریں۔</translation>
diff --git a/ios/chrome/app/strings/resources/ios_strings_kk.xtb b/ios/chrome/app/strings/resources/ios_strings_kk.xtb index 6222072..81723e3 100644 --- a/ios/chrome/app/strings/resources/ios_strings_kk.xtb +++ b/ios/chrome/app/strings/resources/ios_strings_kk.xtb
@@ -129,7 +129,7 @@ <translation id="236977714248711277">Сайттар шолуды жақсарту (мысалы, есептік жазбадан шығармау не сатып алу себетіңіздегі нәрселерді есте сақтау) үшін cookie файлдарын пайдалана алмайды. Сайттар түрлі сайттардағы браузерді қолдану мәліметін көру үшін (мысалы, жарнамаларды жеке қажеттіліктерге бейімдеу мақсатында) cookie файлдарын пайдалана алмайды.</translation> -<translation id="2381405137052800939">Негіздер</translation> +<translation id="2381405137052800939">Негізгілер</translation> <translation id="2386793615875593361">1 таңдалды</translation> <translation id="2421004566762153674">Үшінші тараптың cookie файлдарын бөгеу</translation> <translation id="2421044535038393232">Өзгерте беру</translation>
diff --git a/ios/chrome/app/strings/resources/ios_strings_ne.xtb b/ios/chrome/app/strings/resources/ios_strings_ne.xtb index 3a5773d..9ebb9ac 100644 --- a/ios/chrome/app/strings/resources/ios_strings_ne.xtb +++ b/ios/chrome/app/strings/resources/ios_strings_ne.xtb
@@ -663,7 +663,7 @@ <translation id="8281781826761538115">पूर्वनिर्धारित - <ph name="DEFAULT_LOCALE" /></translation> <translation id="8299417921174340354">पासवर्डहरू प्रयोग गर्न सर्वप्रथम तपाईंले आफ्नो यन्त्रमा अनिवार्य रूपमा कुनै पासकोड सेट गर्नु पर्छ।</translation> <translation id="8319076807703933069">नयाँ खोज</translation> -<translation id="8323906514956095947">ट्याबसम्बन्धी थप विकल्पहरू हेर्न छोइराख्नुहोस्</translation> +<translation id="8323906514956095947">ट्याबसम्बन्धी थप विकल्पहरू हेर्न टच एण्ड होल्ड गर्नुहोस्</translation> <translation id="8328777765163860529">सबै बन्द गर्नुहोस्</translation> <translation id="8386068868580335421">रिसेट गर्नुहोस्</translation> <translation id="8407669440184693619">यो साइटका लागि कुनै पनि पासवर्ड फेला परेन</translation>
diff --git a/ios/chrome/app/strings/resources/ios_strings_pt-BR.xtb b/ios/chrome/app/strings/resources/ios_strings_pt-BR.xtb index 33683d6..7290891f 100644 --- a/ios/chrome/app/strings/resources/ios_strings_pt-BR.xtb +++ b/ios/chrome/app/strings/resources/ios_strings_pt-BR.xtb
@@ -7,7 +7,7 @@ <translation id="1044891598689252897">Os sites funcionarão normalmente</translation> <translation id="1047726139967079566">Adicionar esta página aos favoritos...</translation> <translation id="1049743911850919806">Modo anônimo</translation> -<translation id="105093091697134113">As contas a seguir usam senhas que foram expostas em uma violação de dados de terceiros ou inseridas em um site enganoso. Mude as senhas imediatamente para manter suas contas seguras.</translation> +<translation id="105093091697134113">As contas a seguir usam senhas que foram expostas em uma violação de dados de terceiros ou inseridas em um site fraudulento. Mude as senhas imediatamente para manter suas contas seguras.</translation> <translation id="1063454504051558093">Usar outra senha...</translation> <translation id="1066060668811609597">Gerenciar sincronização</translation> <translation id="1076421457278169141">Código lido</translation>
diff --git a/ios/chrome/app/strings/resources/ios_strings_uk.xtb b/ios/chrome/app/strings/resources/ios_strings_uk.xtb index 3aad825..b2ca2d4 100644 --- a/ios/chrome/app/strings/resources/ios_strings_uk.xtb +++ b/ios/chrome/app/strings/resources/ios_strings_uk.xtb
@@ -479,7 +479,7 @@ <translation id="6324669097367352121">Налаштування входу</translation> <translation id="6337234675334993532">Шифрування</translation> <translation id="633809752005859102">Сталася помилка. Ми виправимо її.</translation> -<translation id="6342069812937806050">Лише зараз</translation> +<translation id="6342069812937806050">Щойно</translation> <translation id="6344783595350022745">Очистити текст</translation> <translation id="6346549652287021269">Почати нове завантаження?</translation> <translation id="6362362396625799311">Немає анонімних вкладок</translation>
diff --git a/ios/chrome/browser/ui/tab_grid/grid/grid_view_controller.h b/ios/chrome/browser/ui/tab_grid/grid/grid_view_controller.h index e37ecca..5b37b03 100644 --- a/ios/chrome/browser/ui/tab_grid/grid/grid_view_controller.h +++ b/ios/chrome/browser/ui/tab_grid/grid/grid_view_controller.h
@@ -27,6 +27,10 @@ // |gridViewController|. - (void)gridViewController:(GridViewController*)gridViewController didCloseItemWithID:(NSString*)itemID; +// Tells the delegate that the plus sign was tapped in |gridViewController|, +// i.e., there was an intention to create a new item. +- (void)didTapPlusSignInGridViewController: + (GridViewController*)gridViewController; // Tells the delegate that the item at |sourceIndex| was moved to // |destinationIndex|. - (void)gridViewController:(GridViewController*)gridViewController
diff --git a/ios/chrome/browser/ui/tab_grid/grid/grid_view_controller_unittest.mm b/ios/chrome/browser/ui/tab_grid/grid/grid_view_controller_unittest.mm index 9049b28..8f3f223 100644 --- a/ios/chrome/browser/ui/tab_grid/grid/grid_view_controller_unittest.mm +++ b/ios/chrome/browser/ui/tab_grid/grid/grid_view_controller_unittest.mm
@@ -51,6 +51,11 @@ // No-op for unittests. This is only called when a user taps to close a cell, // not generically when items are removed from the data source. } +- (void)didTapPlusSignInGridViewController: + (GridViewController*)gridViewController { + // No-op for unittests. This is only called when a user taps on a + // plus sign cell, not generically when items are added to the data source. +} @end class GridViewControllerTest : public RootViewControllerTest {
diff --git a/ios/chrome/browser/ui/tab_grid/tab_grid_view_controller.mm b/ios/chrome/browser/ui/tab_grid/tab_grid_view_controller.mm index 1466e2bf..5f014fd 100644 --- a/ios/chrome/browser/ui/tab_grid/tab_grid_view_controller.mm +++ b/ios/chrome/browser/ui/tab_grid/tab_grid_view_controller.mm
@@ -140,6 +140,9 @@ BOOL scrollViewAnimatingContentOffset; @property(nonatomic, assign) PageChangeInteraction pageChangeInteraction; +// UIView whose background color changes to create a fade-in / fade-out effect +// when revealing / hiding the Thumb Strip. +@property(nonatomic, weak) UIView* foregroundView; @end @implementation TabGridViewController @@ -170,6 +173,9 @@ [self setupRemoteTabsViewController]; [self setupTopToolbar]; [self setupBottomToolbar]; + if (IsThumbStripEnabled()) { + [self setupForegroundView]; + } // Hide the toolbars and the floating button, so they can fade in the first // time there's a transition into this view controller. @@ -442,6 +448,15 @@ } - (void)animateViewReveal:(ViewRevealState)viewRevealState { + switch (viewRevealState) { + case ViewRevealState::Hidden: + self.foregroundView.alpha = 1; + break; + case ViewRevealState::Peeked: + case ViewRevealState::Revealed: + self.foregroundView.alpha = 0; + break; + } } - (void)didAnimateViewReveal:(ViewRevealState)viewRevealState { @@ -835,6 +850,17 @@ action:@selector(newTabButtonTapped:)]; } +// Adds the foreground view and sets constraints. +- (void)setupForegroundView { + UIView* foregroundView = [[UIView alloc] init]; + self.foregroundView = foregroundView; + foregroundView.translatesAutoresizingMaskIntoConstraints = NO; + foregroundView.userInteractionEnabled = NO; + foregroundView.backgroundColor = [UIColor blackColor]; + [self.view addSubview:foregroundView]; + AddSameConstraints(foregroundView, self.view); +} + - (void)configureViewControllerForCurrentSizeClassesAndPage { self.configuration = TabGridConfigurationFloatingButton; if (self.traitCollection.verticalSizeClass == @@ -1165,6 +1191,17 @@ } } +- (void)didTapPlusSignInGridViewController: + (GridViewController*)gridViewController { + if (gridViewController == self.regularTabsViewController) { + [self.regularTabsDelegate addNewItem]; + // TODO(crbug.com/1135329): Record when a new regular tab is opened. + } else if (gridViewController == self.incognitoTabsViewController) { + [self.incognitoTabsDelegate addNewItem]; + // TODO(crbug.com/1135329): Record when a new incognito tab is opened. + } +} + - (void)gridViewController:(GridViewController*)gridViewController didMoveItemWithID:(NSString*)itemID toIndex:(NSUInteger)destinationIndex {
diff --git a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.arm64.zip.sha1 b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.arm64.zip.sha1 index c476ac77..5d1973ca 100644 --- a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.arm64.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.arm64.zip.sha1
@@ -1 +1 @@ -28b2106df9d2a38fec59c248711a76bb430d4f0d \ No newline at end of file +d197a3a59d58f21d676c122cbf07014e26a5a2c5 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.x64.zip.sha1 b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.x64.zip.sha1 index abbfceb..cdddfb8 100644 --- a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.x64.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.x64.zip.sha1
@@ -1 +1 @@ -be31f8ea962de5c1d6e2cdb1757d508dc9fdb2d1 \ No newline at end of file +3f46e3c72fd4a0b953fa39a301dd57f8d60e85e4 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.arm64.zip.sha1 b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.arm64.zip.sha1 index 4055682..d14a35f 100644 --- a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.arm64.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.arm64.zip.sha1
@@ -1 +1 @@ -ab3de4df04cd62ac97f93bd24f3705f70fa125a1 \ No newline at end of file +ebcdef0f6b320efb61eff802c1eea98d9e07ce69 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.x64.zip.sha1 b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.x64.zip.sha1 index 67313ad..4726eabfb 100644 --- a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.x64.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.x64.zip.sha1
@@ -1 +1 @@ -e458d6b0584e01ebaf5a173f850ffa20403e1678 \ No newline at end of file +f3e4eeb0c4b99fdd668a763002f995745e18ee78 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.arm64.zip.sha1 b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.arm64.zip.sha1 index 9e2fbde3..61b1d99 100644 --- a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.arm64.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.arm64.zip.sha1
@@ -1 +1 @@ -c9afb8f24090ebebc483ae24a784c6914ceebe05 \ No newline at end of file +968775bc0020cfc9d317d5391cfbf112edfcd540 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.x64.zip.sha1 b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.x64.zip.sha1 index 1654c1f..b965f22 100644 --- a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.x64.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.x64.zip.sha1
@@ -1 +1 @@ -31dd7e6eb63a2fc62ab0971f4c855cd51b38ab3e \ No newline at end of file +4d87b3d11fc9be5f90248d01e22b369808e2a9ff \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.arm64.zip.sha1 b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.arm64.zip.sha1 index b8e58d0c..09d0bf9 100644 --- a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.arm64.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.arm64.zip.sha1
@@ -1 +1 @@ -d4475d08709c03c0054061a2b4731ca93cb036ef \ No newline at end of file +4de2901ca4eb1136131e2b88026537ed3aa11a4e \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.x64.zip.sha1 b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.x64.zip.sha1 index df16f0d..4fc6fa17 100644 --- a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.x64.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.x64.zip.sha1
@@ -1 +1 @@ -eef8bb868bee080cb2b55b0302b17eef85fb48c7 \ No newline at end of file +63fea9288610814e72c1a9cc12ac760164f734be \ No newline at end of file
diff --git a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.arm64.zip.sha1 b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.arm64.zip.sha1 index b10a7fe..dfaade87 100644 --- a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.arm64.zip.sha1 +++ b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.arm64.zip.sha1
@@ -1 +1 @@ -96c904017cf111c644f5b49c6ca9da7e778df8ff \ No newline at end of file +dcc174d3ec0250665b01c8b71ae3451679026e56 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.x64.zip.sha1 b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.x64.zip.sha1 index 668a773..c0821b1 100644 --- a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.x64.zip.sha1 +++ b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.x64.zip.sha1
@@ -1 +1 @@ -d7703bf998c51d49459e8d9442a6234eb83af263 \ No newline at end of file +62da03440236a10e7ca329ef88dbe623ed1c74ee \ No newline at end of file
diff --git a/media/blink/webmediaplayer_impl.cc b/media/blink/webmediaplayer_impl.cc index effd342..128ba69 100644 --- a/media/blink/webmediaplayer_impl.cc +++ b/media/blink/webmediaplayer_impl.cc
@@ -976,6 +976,11 @@ if (watch_time_reporter_) watch_time_reporter_->OnSeeking(); + // Send the seek updates only when the seek pipeline hasn't started, + // OnPipelineSeeked is not called yet. + if (!seeking_) + delegate_->DidSeek(delegate_id_); + // TODO(sandersd): Move |seeking_| to PipelineController. // TODO(sandersd): Do we want to reset the idle timer here? delegate_->SetIdle(delegate_id_, false);
diff --git a/media/blink/webmediaplayer_impl_unittest.cc b/media/blink/webmediaplayer_impl_unittest.cc index 3fb0d5e..834f74a 100644 --- a/media/blink/webmediaplayer_impl_unittest.cc +++ b/media/blink/webmediaplayer_impl_unittest.cc
@@ -249,6 +249,8 @@ DCHECK_EQ(player_id_, player_id); } + void DidSeek(int player_id) override { DCHECK_EQ(player_id_, player_id); } + bool IsFrameHidden() override { return is_hidden_; } bool IsFrameClosed() override { return is_closed_; }
diff --git a/media/gpu/windows/supported_profile_helpers.cc b/media/gpu/windows/supported_profile_helpers.cc index 7d8622286..76a557d 100644 --- a/media/gpu/windows/supported_profile_helpers.cc +++ b/media/gpu/windows/supported_profile_helpers.cc
@@ -163,7 +163,8 @@ ID3D11VideoDevice* video_device, const GUID& decoder_guid, const std::vector<gfx::Size>& resolutions_to_test, - DXGI_FORMAT format = DXGI_FORMAT_NV12) { + DXGI_FORMAT format = DXGI_FORMAT_NV12, + const gfx::Size& min_resolution = kMinResolution) { media::SupportedResolutionRange result; // Verify input is in ascending order by height. @@ -191,7 +192,7 @@ } if (!result.max_landscape_resolution.IsEmpty()) - result.min_resolution = kMinResolution; + result.min_resolution = min_resolution; return result; } @@ -299,10 +300,15 @@ if (!workarounds.disable_accelerated_vp8_decode && profile_id == D3D11_DECODER_PROFILE_VP8_VLD && base::FeatureList::IsEnabled(kMediaFoundationVP8Decoding)) { - supported_resolutions[VP8PROFILE_ANY] = - GetResolutionsForGUID(video_device.Get(), profile_id, - {gfx::Size(4096, 2160), gfx::Size(4096, 2304), - gfx::Size(4096, 4096)}); + // VP8 decoding is cheap on modern devices compared to other codecs, so + // much so that hardware decoding performance is actually worse at low + // resolutions than software decoding. See https://crbug.com/1136495. + constexpr gfx::Size kMinVp8Resolution = gfx::Size(640, 480); + + supported_resolutions[VP8PROFILE_ANY] = GetResolutionsForGUID( + video_device.Get(), profile_id, + {gfx::Size(4096, 2160), gfx::Size(4096, 2304), gfx::Size(4096, 4096)}, + DXGI_FORMAT_NV12, kMinVp8Resolution); continue; }
diff --git a/media/gpu/windows/supported_profile_helpers_unittest.cc b/media/gpu/windows/supported_profile_helpers_unittest.cc index 70c9203..31a4fc6 100644 --- a/media/gpu/windows/supported_profile_helpers_unittest.cc +++ b/media/gpu/windows/supported_profile_helpers_unittest.cc
@@ -219,7 +219,19 @@ base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndEnableFeature(kMediaFoundationVP8Decoding); - TestDecoderSupport(D3D11_DECODER_PROFILE_VP8_VLD, VP8PROFILE_ANY); + + EnableDecoders({D3D11_DECODER_PROFILE_VP8_VLD}); + SetMaxResolution(D3D11_DECODER_PROFILE_VP8_VLD, kSquare4k); + + const auto supported_resolutions = GetSupportedD3D11VideoDecoderResolutions( + mock_d3d11_device_, gpu_workarounds_); + auto it = supported_resolutions.find(VP8PROFILE_ANY); + ASSERT_NE(it, supported_resolutions.end()); + EXPECT_EQ(kSquare4k, it->second.max_landscape_resolution); + EXPECT_EQ(kSquare4k, it->second.max_portrait_resolution); + + constexpr gfx::Size kMinVp8Resolution = gfx::Size(640, 480); + EXPECT_EQ(kMinVp8Resolution, it->second.min_resolution); } TEST_F(SupportedResolutionResolverTest, VP9Profile0Supports8k) {
diff --git a/mojo/public/DEPS b/mojo/public/DEPS index 1855390..8bed1ad 100644 --- a/mojo/public/DEPS +++ b/mojo/public/DEPS
@@ -9,4 +9,5 @@ # Temporary until mojom [Native] is gone. "+ipc/ipc_param_traits.h", + "+third_party/perfetto/protos/perfetto/trace/track_event", ]
diff --git a/mojo/public/cpp/bindings/connector.h b/mojo/public/cpp/bindings/connector.h index 1616f1bf..905829cd 100644 --- a/mojo/public/cpp/bindings/connector.h +++ b/mojo/public/cpp/bindings/connector.h
@@ -85,7 +85,7 @@ Connector(ScopedMessagePipeHandle message_pipe, ConnectorConfig config, scoped_refptr<base::SequencedTaskRunner> runner, - const char* heap_profiler_tag = "unknown interface"); + const char* interface_name = "unknown interface"); ~Connector() override; // Sets outgoing serialization mode. @@ -306,7 +306,7 @@ // The tag used to track heap allocations that originated from a Watcher // notification. - const char* heap_profiler_tag_ = "unknown interface"; + const char* interface_name_ = "unknown interface"; // A cached pointer to the RunLoopNestingObserver for the thread on which this // Connector was created.
diff --git a/mojo/public/cpp/bindings/lib/connector.cc b/mojo/public/cpp/bindings/lib/connector.cc index 93ea250..ebed370 100644 --- a/mojo/public/cpp/bindings/lib/connector.cc +++ b/mojo/public/cpp/bindings/lib/connector.cc
@@ -21,6 +21,7 @@ #include "base/task/current_thread.h" #include "base/threading/sequence_local_storage_slot.h" #include "base/trace_event/trace_event.h" +#include "base/trace_event/typed_macros.h" #include "mojo/public/c/system/quota.h" #include "mojo/public/cpp/bindings/features.h" #include "mojo/public/cpp/bindings/lib/may_auto_lock.h" @@ -29,6 +30,7 @@ #include "mojo/public/cpp/bindings/mojo_buildflags.h" #include "mojo/public/cpp/bindings/sync_handle_watcher.h" #include "mojo/public/cpp/system/wait.h" +#include "third_party/perfetto/protos/perfetto/trace/track_event/chrome_mojo_event_info.pbzero.h" #if defined(ENABLE_IPC_FUZZER) #include "mojo/public/cpp/bindings/message_dumper.h" @@ -145,14 +147,14 @@ Connector::Connector(ScopedMessagePipeHandle message_pipe, ConnectorConfig config, scoped_refptr<base::SequencedTaskRunner> runner, - const char* heap_profiler_tag) + const char* interface_name) : message_pipe_(std::move(message_pipe)), task_runner_(std::move(runner)), error_(false), force_immediate_dispatch_(!EnableTaskPerMessage()), outgoing_serialization_mode_(g_default_outgoing_serialization_mode), incoming_serialization_mode_(g_default_incoming_serialization_mode), - heap_profiler_tag_(heap_profiler_tag), + interface_name_(interface_name), nesting_observer_(RunLoopNestingObserver::GetForThread()) { if (config == MULTI_THREADED_SEND) lock_.emplace(); @@ -410,7 +412,7 @@ DCHECK(task_runner_->RunsTasksInCurrentSequence()); handle_watcher_ = std::make_unique<SimpleWatcher>( FROM_HERE, SimpleWatcher::ArmingPolicy::MANUAL, task_runner_, - heap_profiler_tag_); + interface_name_); MojoResult rv = handle_watcher_->Watch( message_pipe_.get(), MOJO_HANDLE_SIGNAL_READABLE, base::BindRepeating(&Connector::OnWatcherHandleReady, @@ -459,11 +461,11 @@ // was a problem extracting handles from it. We treat this essentially as // a bad IPC because we don't really have a better option. // - // We include |heap_profiler_tag_| in the error message since it usually + // We include |interface_name_| in the error message since it usually // (via this Connector's owner) provides useful information about which // binding interface is using this Connector. NotifyBadMessage(handle.get(), - std::string(heap_profiler_tag_) + + std::string(interface_name_) + "One or more handle attachments were invalid."); return MOJO_RESULT_ABORTED; } @@ -494,7 +496,12 @@ TRACE_EVENT_FLAG_FLOW_IN); #if !BUILDFLAG(MOJO_TRACE_ENABLED) // This emits just full class name, and is inferior to mojo tracing. - TRACE_EVENT0("mojom", heap_profiler_tag_); + TRACE_EVENT("toplevel", "Connector::DispatchMessage", + [this](perfetto::EventContext ctx) { + ctx.event() + ->set_chrome_mojo_event_info() + ->set_watcher_notify_interface_tag(interface_name_); + }); #endif if (connection_group_)
diff --git a/mojo/public/cpp/bindings/struct_ptr.h b/mojo/public/cpp/bindings/struct_ptr.h index e76c341..af192d3 100644 --- a/mojo/public/cpp/bindings/struct_ptr.h +++ b/mojo/public/cpp/bindings/struct_ptr.h
@@ -171,7 +171,11 @@ DCHECK(state_ == VALID); return &value_; } - Struct* get() const { return &value_; } + Struct* get() const { + if (state_ == NIL) + return nullptr; + return &value_; + } void Swap(InlinedStructPtr* other) { std::swap(value_, other->value_);
diff --git a/mojo/public/cpp/system/simple_watcher.cc b/mojo/public/cpp/system/simple_watcher.cc index f34b90e..1d7644c 100644 --- a/mojo/public/cpp/system/simple_watcher.cc +++ b/mojo/public/cpp/system/simple_watcher.cc
@@ -13,7 +13,9 @@ #include "base/threading/thread_task_runner_handle.h" #include "base/trace_event/heap_profiler.h" #include "base/trace_event/trace_event.h" +#include "base/trace_event/typed_macros.h" #include "mojo/public/c/system/trap.h" +#include "third_party/perfetto/protos/perfetto/trace/track_event/chrome_mojo_event_info.pbzero.h" namespace mojo { @@ -32,9 +34,9 @@ MojoTriggerCondition condition, int watch_id, MojoResult* result, - const char* heap_profiler_tag) { + const char* handler_tag) { scoped_refptr<Context> context = - new Context(watcher, task_runner, watch_id, heap_profiler_tag); + new Context(watcher, task_runner, watch_id, handler_tag); // If MojoAddTrigger succeeds, it effectively assumes ownership of a // reference to |context|. In that case, this reference is balanced in @@ -70,11 +72,11 @@ Context(base::WeakPtr<SimpleWatcher> weak_watcher, scoped_refptr<base::SequencedTaskRunner> task_runner, int watch_id, - const char* heap_profiler_tag) + const char* handler_tag) : weak_watcher_(weak_watcher), task_runner_(task_runner), watch_id_(watch_id), - heap_profiler_tag_(heap_profiler_tag) {} + handler_tag_(handler_tag) {} ~Context() = default; @@ -92,10 +94,8 @@ weak_watcher_->OnHandleReady(watch_id_, result, state); } else { { - // Annotate the posted task with |heap_profiler_tag_| as the IPC - // interface. - base::TaskAnnotator::ScopedSetIpcHash scoped_set_ipc_hash( - heap_profiler_tag_); + // Annotate the posted task with |handler_tag_| as the IPC interface. + base::TaskAnnotator::ScopedSetIpcHash scoped_set_ipc_hash(handler_tag_); task_runner_->PostTask( FROM_HERE, base::BindOnce(&SimpleWatcher::OnHandleReady, weak_watcher_, watch_id_, result, state)); @@ -106,7 +106,7 @@ const base::WeakPtr<SimpleWatcher> weak_watcher_; const scoped_refptr<base::SequencedTaskRunner> task_runner_; const int watch_id_; - const char* heap_profiler_tag_ = nullptr; + const char* handler_tag_ = nullptr; DISALLOW_COPY_AND_ASSIGN(Context); }; @@ -114,14 +114,13 @@ SimpleWatcher::SimpleWatcher(const base::Location& from_here, ArmingPolicy arming_policy, scoped_refptr<base::SequencedTaskRunner> runner, - const char* heap_profiler_tag) + const char* handler_tag) : arming_policy_(arming_policy), task_runner_(std::move(runner)), is_default_task_runner_(base::ThreadTaskRunnerHandle::IsSet() && task_runner_ == base::ThreadTaskRunnerHandle::Get()), - heap_profiler_tag_(heap_profiler_tag ? heap_profiler_tag - : from_here.file_name()) { + handler_tag_(handler_tag ? handler_tag : from_here.file_name()) { MojoResult rv = CreateTrap(&Context::CallNotify, &trap_handle_); DCHECK_EQ(MOJO_RESULT_OK, rv); DCHECK(task_runner_->RunsTasksInCurrentSequence()); @@ -152,7 +151,7 @@ MojoResult result = MOJO_RESULT_UNKNOWN; context_ = Context::Create(weak_factory_.GetWeakPtr(), task_runner_, trap_handle_.get(), handle_, signals, condition, - watch_id_, &result, heap_profiler_tag_); + watch_id_, &result, handler_tag_); if (!context_) { handle_.set_value(kInvalidHandleValue); callback_.Reset(); @@ -230,9 +229,8 @@ DCHECK_EQ(MOJO_RESULT_FAILED_PRECONDITION, rv); { - // Annotate the posted task with |heap_profiler_tag_| as the IPC interface. - base::TaskAnnotator::ScopedSetIpcHash scoped_set_ipc_hash( - heap_profiler_tag_); + // Annotate the posted task with |handler_tag_| as the IPC interface. + base::TaskAnnotator::ScopedSetIpcHash scoped_set_ipc_hash(handler_tag_); task_runner_->PostTask(FROM_HERE, base::BindOnce(&SimpleWatcher::OnHandleReady, weak_factory_.GetWeakPtr(), watch_id_, @@ -261,12 +259,16 @@ // NOTE: It's legal for |callback| to delete |this|. if (!callback.is_null()) { - TRACE_HEAP_PROFILER_API_SCOPED_TASK_EXECUTION event(heap_profiler_tag_); + TRACE_HEAP_PROFILER_API_SCOPED_TASK_EXECUTION event(handler_tag_); // Lot of janks caused are grouped to OnHandleReady tasks. This trace event - // helps identify the cause of janks. It is ok to pass |heap_profiler_tag_| + // helps identify the cause of janks. It is ok to pass |handler_tag_| // here since it is a string literal. - // TODO(927206): Consider renaming |heap_profiler_tag_|. - TRACE_EVENT0("toplevel", heap_profiler_tag_); + TRACE_EVENT("toplevel", "SimpleWatcher::OnHandleReady", + [this](perfetto::EventContext ctx) { + ctx.event() + ->set_chrome_mojo_event_info() + ->set_watcher_notify_interface_tag(handler_tag_); + }); base::WeakPtr<SimpleWatcher> weak_self = weak_factory_.GetWeakPtr(); callback.Run(result, state);
diff --git a/mojo/public/cpp/system/simple_watcher.h b/mojo/public/cpp/system/simple_watcher.h index 24123bc..3ccec253 100644 --- a/mojo/public/cpp/system/simple_watcher.h +++ b/mojo/public/cpp/system/simple_watcher.h
@@ -90,7 +90,7 @@ ArmingPolicy arming_policy, scoped_refptr<base::SequencedTaskRunner> runner = base::SequencedTaskRunnerHandle::Get(), - const char* heap_profiler_tag = nullptr); + const char* handler_tag = nullptr); ~SimpleWatcher(); // Indicates if the SimpleWatcher is currently watching a handle. @@ -226,7 +226,7 @@ // Tag used to ID memory allocations that originated from notifications in // this watcher. - const char* heap_profiler_tag_ = nullptr; + const char* handler_tag_ = nullptr; base::WeakPtrFactory<SimpleWatcher> weak_factory_{this};
diff --git a/net/OWNERS b/net/OWNERS index 2ee09fd..09c12b5 100644 --- a/net/OWNERS +++ b/net/OWNERS
@@ -1,6 +1,7 @@ agl@chromium.org asanka@chromium.org davidben@chromium.org +dschinazi@chromium.org ericorth@chromium.org eroman@chromium.org jkarlin@chromium.org
diff --git a/net/android/BUILD.gn b/net/android/BUILD.gn index c8c9afb..ff9c6688 100644 --- a/net/android/BUILD.gn +++ b/net/android/BUILD.gn
@@ -197,7 +197,6 @@ } java_cpp_template("net_errors_java") { - package_path = "org/chromium/net" sources = [ "java/NetError.template" ] inputs = [ "../base/net_error_list.h" ] }
diff --git a/net/base/net_info_source_list.h b/net/base/net_info_source_list.h index 1f754f2..40223c3 100644 --- a/net/base/net_info_source_list.h +++ b/net/base/net_info_source_list.h
@@ -2,24 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// This file intentionally does not have header guards, it's included -// inside a macro to generate enum values. The following line silences a -// presubmit and Tricium warning that would otherwise be triggered by this: -// no-include-guard-because-multiply-included -// NOLINT(build/header_guard) +#ifndef NET_LOG_NET_INFO_SOURCE_LIST_H_ +#define NET_LOG_NET_INFO_SOURCE_LIST_H_ -// Flags used to request different types of information about the current state -// of a URLRequestContext. -// -// The strings don't match the enums for historical reasons. +// NetInfo Sources written to NetLog JSON files. +const char kNetInfoProxySettings[] = "proxySettings"; +const char kNetInfoBadProxies[] = "badProxies"; +const char kNetInfoHostResolver[] = "hostResolverInfo"; +const char kNetInfoSocketPool[] = "socketPoolInfo"; +const char kNetInfoQuic[] = "quicInfo"; +const char kNetInfoSpdySessions[] = "spdySessionInfo"; +const char kNetInfoSpdyStatus[] = "spdyStatus"; +const char kNetInfoAltSvcMappings[] = "altSvcMappings"; +const char kNetInfoHTTPCache[] = "httpCacheInfo"; +const char kNetInfoReporting[] = "reportingInfo"; -NET_INFO_SOURCE(PROXY_SETTINGS, "proxySettings", 1 << 0) -NET_INFO_SOURCE(BAD_PROXIES, "badProxies", 1 << 1) -NET_INFO_SOURCE(HOST_RESOLVER, "hostResolverInfo", 1 << 2) -NET_INFO_SOURCE(SOCKET_POOL, "socketPoolInfo", 1 << 3) -NET_INFO_SOURCE(QUIC, "quicInfo", 1 << 4) -NET_INFO_SOURCE(SPDY_SESSIONS, "spdySessionInfo", 1 << 5) -NET_INFO_SOURCE(SPDY_STATUS, "spdyStatus", 1 << 6) -NET_INFO_SOURCE(ALT_SVC_MAPPINGS, "altSvcMappings", 1 << 7) -NET_INFO_SOURCE(HTTP_CACHE, "httpCacheInfo", 1 << 8) -NET_INFO_SOURCE(REPORTING, "reportingInfo", 1 << 9) +#endif
diff --git a/net/log/file_net_log_observer.cc b/net/log/file_net_log_observer.cc index b557312..337ff2a 100644 --- a/net/log/file_net_log_observer.cc +++ b/net/log/file_net_log_observer.cc
@@ -333,17 +333,19 @@ std::unique_ptr<FileNetLogObserver> FileNetLogObserver::CreateBounded( const base::FilePath& log_path, uint64_t max_total_size, + NetLogCaptureMode capture_mode, std::unique_ptr<base::Value> constants) { return CreateInternal(log_path, SiblingInprogressDirectory(log_path), base::nullopt, max_total_size, kDefaultNumFiles, - std::move(constants)); + capture_mode, std::move(constants)); } std::unique_ptr<FileNetLogObserver> FileNetLogObserver::CreateUnbounded( const base::FilePath& log_path, + NetLogCaptureMode capture_mode, std::unique_ptr<base::Value> constants) { return CreateInternal(log_path, base::FilePath(), base::nullopt, kNoLimit, - kDefaultNumFiles, std::move(constants)); + kDefaultNumFiles, capture_mode, std::move(constants)); } std::unique_ptr<FileNetLogObserver> @@ -351,19 +353,23 @@ const base::FilePath& inprogress_dir_path, base::File output_file, uint64_t max_total_size, + NetLogCaptureMode capture_mode, std::unique_ptr<base::Value> constants) { return CreateInternal(base::FilePath(), inprogress_dir_path, base::make_optional<base::File>(std::move(output_file)), - max_total_size, kDefaultNumFiles, std::move(constants)); + max_total_size, kDefaultNumFiles, capture_mode, + std::move(constants)); } std::unique_ptr<FileNetLogObserver> FileNetLogObserver::CreateUnboundedPreExisting( base::File output_file, + NetLogCaptureMode capture_mode, std::unique_ptr<base::Value> constants) { return CreateInternal(base::FilePath(), base::FilePath(), base::make_optional<base::File>(std::move(output_file)), - kNoLimit, kDefaultNumFiles, std::move(constants)); + kNoLimit, kDefaultNumFiles, capture_mode, + std::move(constants)); } FileNetLogObserver::~FileNetLogObserver() { @@ -378,9 +384,8 @@ file_task_runner_->DeleteSoon(FROM_HERE, file_writer_.release()); } -void FileNetLogObserver::StartObserving(NetLog* net_log, - NetLogCaptureMode capture_mode) { - net_log->AddObserver(this, capture_mode); +void FileNetLogObserver::StartObserving(NetLog* net_log) { + net_log->AddObserver(this, capture_mode_); } void FileNetLogObserver::StopObserving(std::unique_ptr<base::Value> polled_data, @@ -425,10 +430,11 @@ const base::FilePath& log_path, uint64_t max_total_size, size_t total_num_event_files, + NetLogCaptureMode capture_mode, std::unique_ptr<base::Value> constants) { return CreateInternal(log_path, SiblingInprogressDirectory(log_path), base::nullopt, max_total_size, total_num_event_files, - std::move(constants)); + capture_mode, std::move(constants)); } std::unique_ptr<FileNetLogObserver> FileNetLogObserver::CreateInternal( @@ -437,6 +443,7 @@ base::Optional<base::File> pre_existing_log_file, uint64_t max_total_size, size_t total_num_event_files, + NetLogCaptureMode capture_mode, std::unique_ptr<base::Value> constants) { DCHECK_GT(total_num_event_files, 0u); @@ -469,25 +476,43 @@ return base::WrapUnique(new FileNetLogObserver( file_task_runner, std::move(file_writer), base::WrapRefCounted(new WriteQueue(write_queue_memory_max)), - std::move(constants))); + capture_mode, std::move(constants))); } FileNetLogObserver::FileNetLogObserver( scoped_refptr<base::SequencedTaskRunner> file_task_runner, std::unique_ptr<FileWriter> file_writer, scoped_refptr<WriteQueue> write_queue, + NetLogCaptureMode capture_mode, std::unique_ptr<base::Value> constants) : file_task_runner_(std::move(file_task_runner)), write_queue_(std::move(write_queue)), - file_writer_(std::move(file_writer)) { + file_writer_(std::move(file_writer)), + capture_mode_(capture_mode) { if (!constants) constants = base::Value::ToUniquePtrValue(GetNetConstants()); + + DCHECK(!constants->FindKey("logCaptureMode")); + constants->SetStringKey("logCaptureMode", CaptureModeToString(capture_mode)); file_task_runner_->PostTask( FROM_HERE, base::BindOnce(&FileNetLogObserver::FileWriter::Initialize, base::Unretained(file_writer_.get()), std::move(constants))); } +std::string FileNetLogObserver::CaptureModeToString(NetLogCaptureMode mode) { + switch (mode) { + case NetLogCaptureMode::kDefault: + return "Default"; + case NetLogCaptureMode::kIncludeSensitive: + return "IncludeSensitive"; + case NetLogCaptureMode::kEverything: + return "Everything"; + } + NOTREACHED(); + return "UNKNOWN"; +} + FileNetLogObserver::WriteQueue::WriteQueue(uint64_t memory_max) : memory_(0), memory_max_(memory_max) {}
diff --git a/net/log/file_net_log_observer.h b/net/log/file_net_log_observer.h index 05943c1..2ed9862b 100644 --- a/net/log/file_net_log_observer.h +++ b/net/log/file_net_log_observer.h
@@ -58,11 +58,13 @@ static std::unique_ptr<FileNetLogObserver> CreateBounded( const base::FilePath& log_path, uint64_t max_total_size, + NetLogCaptureMode capture_mode, std::unique_ptr<base::Value> constants); // Shortcut for calling CreateBounded() with kNoLimit. static std::unique_ptr<FileNetLogObserver> CreateUnbounded( const base::FilePath& log_path, + NetLogCaptureMode capture_mode, std::unique_ptr<base::Value> constants); // Creates a bounded log that writes to a pre-existing file (truncating @@ -73,18 +75,20 @@ const base::FilePath& inprogress_dir_path, base::File output_file, uint64_t max_total_size, + NetLogCaptureMode capture_mode, std::unique_ptr<base::Value> constants); // Creates an unbounded log that writes to a pre-existing file (truncating // it to start with, and closing it upon completion). static std::unique_ptr<FileNetLogObserver> CreateUnboundedPreExisting( base::File output_file, + NetLogCaptureMode capture_mode, std::unique_ptr<base::Value> constants); ~FileNetLogObserver() override; // Attaches this observer to |net_log| and begins observing events. - void StartObserving(NetLog* net_log, NetLogCaptureMode capture_mode); + void StartObserving(NetLog* net_log); // Stops observing net_log() and closes the output file(s). Must be called // after StartObserving. Should be called before destruction of the @@ -112,6 +116,7 @@ const base::FilePath& log_path, uint64_t max_total_size, size_t total_num_event_files, + NetLogCaptureMode capture_mode, std::unique_ptr<base::Value> constants); private: @@ -124,13 +129,17 @@ base::Optional<base::File> pre_existing_out_file, uint64_t max_total_size, size_t total_num_event_files, + NetLogCaptureMode capture_mode, std::unique_ptr<base::Value> constants); FileNetLogObserver(scoped_refptr<base::SequencedTaskRunner> file_task_runner, std::unique_ptr<FileWriter> file_writer, scoped_refptr<WriteQueue> write_queue, + NetLogCaptureMode capture_mode, std::unique_ptr<base::Value> constants); + static std::string CaptureModeToString(NetLogCaptureMode mode); + scoped_refptr<base::SequencedTaskRunner> file_task_runner_; // The |write_queue_| object is shared between the file task runner and the @@ -147,6 +156,8 @@ // finished (since it is posted using base::Unretained()). std::unique_ptr<FileWriter> file_writer_; + const NetLogCaptureMode capture_mode_; + DISALLOW_COPY_AND_ASSIGN(FileNetLogObserver); };
diff --git a/net/log/file_net_log_observer_unittest.cc b/net/log/file_net_log_observer_unittest.cc index c4ae9cd..611266e2d 100644 --- a/net/log/file_net_log_observer_unittest.cc +++ b/net/log/file_net_log_observer_unittest.cc
@@ -234,16 +234,19 @@ bool IsBounded() const { return GetParam(); } - void CreateAndStartObserving(std::unique_ptr<base::Value> constants) { + void CreateAndStartObserving( + std::unique_ptr<base::Value> constants, + NetLogCaptureMode capture_mode = NetLogCaptureMode::kDefault) { if (IsBounded()) { logger_ = FileNetLogObserver::CreateBoundedForTests( - log_path_, kLargeFileSize, kTotalNumFiles, std::move(constants)); + log_path_, kLargeFileSize, kTotalNumFiles, capture_mode, + std::move(constants)); } else { - logger_ = - FileNetLogObserver::CreateUnbounded(log_path_, std::move(constants)); + logger_ = FileNetLogObserver::CreateUnbounded(log_path_, capture_mode, + std::move(constants)); } - logger_->StartObserving(&net_log_, NetLogCaptureMode::kDefault); + logger_->StartObserving(&net_log_); } void CreateAndStartObservingPreExisting( @@ -259,13 +262,13 @@ if (IsBounded()) { logger_ = FileNetLogObserver::CreateBoundedPreExisting( scratch_dir_.GetPath(), std::move(file), kLargeFileSize, - std::move(constants)); + NetLogCaptureMode::kDefault, std::move(constants)); } else { logger_ = FileNetLogObserver::CreateUnboundedPreExisting( - std::move(file), std::move(constants)); + std::move(file), NetLogCaptureMode::kDefault, std::move(constants)); } - logger_->StartObserving(&net_log_, NetLogCaptureMode::kDefault); + logger_->StartObserving(&net_log_); } bool LogFileExists() { @@ -303,8 +306,9 @@ uint64_t total_file_size, int num_files) { logger_ = FileNetLogObserver::CreateBoundedForTests( - log_path_, total_file_size, num_files, std::move(constants)); - logger_->StartObserving(&net_log_, NetLogCaptureMode::kDefault); + log_path_, total_file_size, num_files, NetLogCaptureMode::kDefault, + std::move(constants)); + logger_->StartObserving(&net_log_); } // Returns the path for an internally directory created for bounded logs (this @@ -486,11 +490,12 @@ EXPECT_FALSE(file.IsValid()); if (IsBounded()) logger_ = FileNetLogObserver::CreateBoundedPreExisting( - scratch_dir_.GetPath(), std::move(file), kLargeFileSize, nullptr); + scratch_dir_.GetPath(), std::move(file), kLargeFileSize, + NetLogCaptureMode::kDefault, nullptr); else - logger_ = FileNetLogObserver::CreateUnboundedPreExisting(std::move(file), - nullptr); - logger_->StartObserving(&net_log_, NetLogCaptureMode::kDefault); + logger_ = FileNetLogObserver::CreateUnboundedPreExisting( + std::move(file), NetLogCaptureMode::kDefault, nullptr); + logger_->StartObserving(&net_log_); // Send dummy event. AddEntries(logger_.get(), 1, kDummyEventSize); @@ -551,6 +556,28 @@ kDummyPolledDataString); } +// Ensure that the Capture Mode is recorded as a constant in the NetLog. +TEST_P(FileNetLogObserverTest, LogModeRecorded) { + struct TestCase { + NetLogCaptureMode capture_mode; + const char* expected_value; + } test_cases[] = {// Challenges that result in success results. + {NetLogCaptureMode::kEverything, "Everything"}, + {NetLogCaptureMode::kIncludeSensitive, "IncludeSensitive"}, + {NetLogCaptureMode::kDefault, "Default"}}; + + TestClosure closure; + for (const auto& test_case : test_cases) { + CreateAndStartObserving(nullptr, test_case.capture_mode); + logger_->StopObserving(nullptr, closure.closure()); + closure.WaitForResult(); + std::unique_ptr<ParsedNetLog> log = ReadNetLogFromDisk(log_path_); + ASSERT_TRUE(log); + ExpectDictionaryContainsProperty(log->constants, "logCaptureMode", + test_case.expected_value); + } +} + // Adds events concurrently from several different threads. The exact order of // events seen by this test is non-deterministic. TEST_P(FileNetLogObserverTest, AddEventsFromMultipleThreads) { @@ -946,8 +973,9 @@ file.Write(0, "not json", 8); logger_ = FileNetLogObserver::CreateBoundedPreExisting( - scratch_dir.GetPath(), std::move(file), kLargeFileSize, nullptr); - logger_->StartObserving(&net_log_, NetLogCaptureMode::kDefault); + scratch_dir.GetPath(), std::move(file), kLargeFileSize, + NetLogCaptureMode::kDefault, nullptr); + logger_->StartObserving(&net_log_); base::ThreadPoolInstance::Get()->FlushForTesting(); EXPECT_TRUE(base::PathExists(log_path_));
diff --git a/net/log/net_log_util.cc b/net/log/net_log_util.cc index 7510d79..513b12c2 100644 --- a/net/log/net_log_util.cc +++ b/net/log/net_log_util.cc
@@ -19,6 +19,7 @@ #include "net/base/address_family.h" #include "net/base/load_states.h" #include "net/base/net_errors.h" +#include "net/base/net_info_source_list.h" #include "net/cert/cert_verifier.h" #include "net/cert/internal/simple_path_builder_delegate.h" #include "net/cert/internal/trust_store.h" @@ -123,19 +124,6 @@ } // namespace -const char* NetInfoSourceToString(NetInfoSource source) { - switch (source) { -#define NET_INFO_SOURCE(label, string, value) \ - case NET_INFO_##label: \ - return string; -#include "net/base/net_info_source_list.h" -#undef NET_INFO_SOURCE - case NET_INFO_ALL_SOURCES: - return "All"; - } - return "?"; -} - base::Value GetNetConstants() { base::Value constants_dict(base::Value::Type::DICTIONARY); @@ -231,15 +219,6 @@ constants_dict.SetKey("loadState", std::move(dict)); } - { - base::Value dict(base::Value::Type::DICTIONARY); -#define NET_INFO_SOURCE(label, string, value) \ - dict.SetIntKey(string, NET_INFO_##label); -#include "net/base/net_info_source_list.h" -#undef NET_INFO_SOURCE - constants_dict.SetKey("netInfoSources", std::move(dict)); - } - // Add information on the relationship between net error codes and their // symbolic names. { @@ -353,15 +332,15 @@ return constants_dict; } -NET_EXPORT base::Value GetNetInfo(URLRequestContext* context, - int info_sources) { +NET_EXPORT base::Value GetNetInfo(URLRequestContext* context) { // May only be called on the context's thread. context->AssertCalledOnValidThread(); base::Value net_info_dict = - context->proxy_resolution_service()->GetProxyNetLogValues(info_sources); + context->proxy_resolution_service()->GetProxyNetLogValues(); - if (info_sources & NET_INFO_HOST_RESOLVER) { + // Log Host Resolver info. + { HostResolver* host_resolver = context->host_resolver(); DCHECK(host_resolver); HostCache* cache = host_resolver->GetHostCache(); @@ -384,28 +363,30 @@ cache_info_dict.SetKey("entries", std::move(cache_contents_list)); dict.SetKey("cache", std::move(cache_info_dict)); - net_info_dict.SetKey(NetInfoSourceToString(NET_INFO_HOST_RESOLVER), - std::move(dict)); + net_info_dict.SetKey(kNetInfoHostResolver, std::move(dict)); } } HttpNetworkSession* http_network_session = context->http_transaction_factory()->GetSession(); - if (info_sources & NET_INFO_SOCKET_POOL) { - net_info_dict.SetKey(NetInfoSourceToString(NET_INFO_SOCKET_POOL), + // Log Socket Pool info. + { + net_info_dict.SetKey(kNetInfoSocketPool, base::Value::FromUniquePtrValue( http_network_session->SocketPoolInfoToValue())); } - if (info_sources & NET_INFO_SPDY_SESSIONS) { + // Log SPDY Sessions. + { net_info_dict.SetKey( - NetInfoSourceToString(NET_INFO_SPDY_SESSIONS), + kNetInfoSpdySessions, base::Value::FromUniquePtrValue( http_network_session->SpdySessionPoolInfoToValue())); } - if (info_sources & NET_INFO_SPDY_STATUS) { + // Log SPDY status. + { base::Value status_dict(base::Value::Type::DICTIONARY); status_dict.SetBoolKey("enable_http2", @@ -423,26 +404,28 @@ status_dict.SetStringKey("alpn_protos", next_protos_string); } - net_info_dict.SetKey(NetInfoSourceToString(NET_INFO_SPDY_STATUS), - std::move(status_dict)); + net_info_dict.SetKey(kNetInfoSpdyStatus, std::move(status_dict)); } - if (info_sources & NET_INFO_ALT_SVC_MAPPINGS) { + // Log ALT_SVC mappings. + { const HttpServerProperties& http_server_properties = *context->http_server_properties(); net_info_dict.SetKey( - NetInfoSourceToString(NET_INFO_ALT_SVC_MAPPINGS), + kNetInfoAltSvcMappings, base::Value::FromUniquePtrValue( http_server_properties.GetAlternativeServiceInfoAsValue())); } - if (info_sources & NET_INFO_QUIC) { - net_info_dict.SetKey(NetInfoSourceToString(NET_INFO_QUIC), + // Log QUIC info. + { + net_info_dict.SetKey(kNetInfoQuic, base::Value::FromUniquePtrValue( http_network_session->QuicInfoToValue())); } - if (info_sources & NET_INFO_HTTP_CACHE) { + // Log HTTP Cache info. + { base::Value info_dict(base::Value::Type::DICTIONARY); base::Value stats_dict(base::Value::Type::DICTIONARY); @@ -458,11 +441,11 @@ } info_dict.SetKey("stats", std::move(stats_dict)); - net_info_dict.SetKey(NetInfoSourceToString(NET_INFO_HTTP_CACHE), - std::move(info_dict)); + net_info_dict.SetKey(kNetInfoHTTPCache, std::move(info_dict)); } - if (info_sources & NET_INFO_REPORTING) { + // Log Reporting API info. + { #if BUILDFLAG(ENABLE_REPORTING) ReportingService* reporting_service = context->reporting_service(); if (reporting_service) { @@ -473,20 +456,17 @@ reporting_dict.SetKey("networkErrorLogging", network_error_logging_service->StatusAsValue()); } - net_info_dict.SetKey(NetInfoSourceToString(NET_INFO_REPORTING), - std::move(reporting_dict)); + net_info_dict.SetKey(kNetInfoReporting, std::move(reporting_dict)); } else { base::Value reporting_dict(base::Value::Type::DICTIONARY); reporting_dict.SetKey("reportingEnabled", base::Value(false)); - net_info_dict.SetKey(NetInfoSourceToString(NET_INFO_REPORTING), - std::move(reporting_dict)); + net_info_dict.SetKey(kNetInfoReporting, std::move(reporting_dict)); } #else // BUILDFLAG(ENABLE_REPORTING) base::Value reporting_dict(base::Value::Type::DICTIONARY); reporting_dict.SetKey("reportingEnabled", base::Value(false)); - net_info_dict.SetKey(NetInfoSourceToString(NET_INFO_REPORTING), - std::move(reporting_dict)); + net_info_dict.SetKey(kNetInfoReporting, std::move(reporting_dict)); #endif // BUILDFLAG(ENABLE_REPORTING) }
diff --git a/net/log/net_log_util.h b/net/log/net_log_util.h index 5de85dc..569be89 100644 --- a/net/log/net_log_util.h +++ b/net/log/net_log_util.h
@@ -15,30 +15,16 @@ class URLRequestContext; -// A set of flags that can be OR'd together to request specific information -// about the current state of the URLRequestContext. See GetNetInfo, below. -enum NetInfoSource { -#define NET_INFO_SOURCE(label, string, value) NET_INFO_##label = value, -#include "net/base/net_info_source_list.h" -#undef NET_INFO_SOURCE - NET_INFO_ALL_SOURCES = -1, -}; - // Utility methods for creating NetLog dumps. -// Returns a friendly string to use for a given NetInfoSource in the net log. -NET_EXPORT const char* NetInfoSourceToString(NetInfoSource source); - // Creates a dictionary containing a legend for net/ constants. NET_EXPORT base::Value GetNetConstants(); // Retrieves a dictionary containing information about the current state of -// |context|. |info_sources| is a set of NetInfoSources OR'd together, -// indicating just what information is being requested. Each NetInfoSource adds -// one top-level entry to the returned dictionary. +// |context|. // // May only be called on |context|'s thread. -NET_EXPORT base::Value GetNetInfo(URLRequestContext* context, int info_sources); +NET_EXPORT base::Value GetNetInfo(URLRequestContext* context); // Takes in a set of contexts and a NetLog::Observer, and passes in // NetLog::Entries to the observer for certain NetLogSources with pending
diff --git a/net/log/net_log_util_unittest.cc b/net/log/net_log_util_unittest.cc index 2189cd5..ac8cbc5 100644 --- a/net/log/net_log_util_unittest.cc +++ b/net/log/net_log_util_unittest.cc
@@ -40,8 +40,7 @@ // Get NetInfo when there's no cache backend (It's only created on first use). EXPECT_FALSE(http_cache->GetCurrentBackend()); - base::Value net_info_without_cache( - GetNetInfo(&context, NET_INFO_ALL_SOURCES)); + base::Value net_info_without_cache(GetNetInfo(&context)); EXPECT_FALSE(http_cache->GetCurrentBackend()); EXPECT_GT(net_info_without_cache.DictSize(), 0u); @@ -50,7 +49,7 @@ EXPECT_EQ(OK, context.http_transaction_factory()->GetCache()->GetBackend( &backend, TestCompletionCallback().callback())); EXPECT_TRUE(http_cache->GetCurrentBackend()); - base::Value net_info_with_cache = GetNetInfo(&context, NET_INFO_ALL_SOURCES); + base::Value net_info_with_cache = GetNetInfo(&context); EXPECT_GT(net_info_with_cache.DictSize(), 0u); EXPECT_EQ(net_info_without_cache.DictSize(), net_info_with_cache.DictSize());
diff --git a/net/proxy_resolution/configured_proxy_resolution_service.cc b/net/proxy_resolution/configured_proxy_resolution_service.cc index 7a7ca75..854f9878 100644 --- a/net/proxy_resolution/configured_proxy_resolution_service.cc +++ b/net/proxy_resolution/configured_proxy_resolution_service.cc
@@ -21,6 +21,7 @@ #include "base/values.h" #include "build/build_config.h" #include "net/base/net_errors.h" +#include "net/base/net_info_source_list.h" #include "net/base/network_isolation_key.h" #include "net/base/proxy_delegate.h" #include "net/base/url_util.h" @@ -1347,22 +1348,22 @@ ApplyProxyConfigIfAvailable(); } -base::Value ConfiguredProxyResolutionService::GetProxyNetLogValues( - int info_sources) { +base::Value ConfiguredProxyResolutionService::GetProxyNetLogValues() { base::Value net_info_dict(base::Value::Type::DICTIONARY); - if (info_sources & NET_INFO_PROXY_SETTINGS) { + // Log Proxy Settings. + { base::Value dict(base::Value::Type::DICTIONARY); if (fetched_config_) dict.SetKey("original", fetched_config_->value().ToValue()); if (config_) dict.SetKey("effective", config_->value().ToValue()); - net_info_dict.SetKey(NetInfoSourceToString(NET_INFO_PROXY_SETTINGS), - std::move(dict)); + net_info_dict.SetKey(kNetInfoProxySettings, std::move(dict)); } - if (info_sources & NET_INFO_BAD_PROXIES) { + // Log Bad Proxies. + { base::Value list(base::Value::Type::LIST); for (const auto& it : proxy_retry_info_) { @@ -1377,8 +1378,7 @@ list.Append(std::move(dict)); } - net_info_dict.SetKey(NetInfoSourceToString(NET_INFO_BAD_PROXIES), - std::move(list)); + net_info_dict.SetKey(kNetInfoBadProxies, std::move(list)); } return net_info_dict;
diff --git a/net/proxy_resolution/configured_proxy_resolution_service.h b/net/proxy_resolution/configured_proxy_resolution_service.h index d2ea1194..b5ee794 100644 --- a/net/proxy_resolution/configured_proxy_resolution_service.h +++ b/net/proxy_resolution/configured_proxy_resolution_service.h
@@ -171,7 +171,7 @@ void ForceReloadProxyConfig(); // ProxyResolutionService - base::Value GetProxyNetLogValues(int info_sources) override; + base::Value GetProxyNetLogValues() override; // ProxyResolutionService bool CastToConfiguredProxyResolutionService(
diff --git a/net/proxy_resolution/proxy_resolution_service.h b/net/proxy_resolution/proxy_resolution_service.h index 93673f7..3caac54c 100644 --- a/net/proxy_resolution/proxy_resolution_service.h +++ b/net/proxy_resolution/proxy_resolution_service.h
@@ -93,9 +93,8 @@ virtual const ProxyRetryInfoMap& proxy_retry_info() const = 0; // Returns proxy related debug information to be included in the NetLog. The - // data should be appropriate for any capture mode. |info_sources| is a bit - // field of NET_INFO_SOURCE. - virtual base::Value GetProxyNetLogValues(int info_sources) = 0; + // data should be appropriate for any capture mode (sensitivity level). + virtual base::Value GetProxyNetLogValues() = 0; // Returns true if |this| is an instance of ConfiguredProxyResolutionService // and assigns |this| to the out parameter. Otherwise returns false and sets
diff --git a/net/proxy_resolution/win/windows_system_proxy_resolution_service.cc b/net/proxy_resolution/win/windows_system_proxy_resolution_service.cc index 1dcf0964..64f9bc6 100644 --- a/net/proxy_resolution/win/windows_system_proxy_resolution_service.cc +++ b/net/proxy_resolution/win/windows_system_proxy_resolution_service.cc
@@ -139,8 +139,7 @@ return proxy_retry_info_; } -base::Value WindowsSystemProxyResolutionService::GetProxyNetLogValues( - int info_sources) { +base::Value WindowsSystemProxyResolutionService::GetProxyNetLogValues() { // TODO (https://crbug.com/1032820): Implement net logs. base::Value net_info_dict(base::Value::Type::DICTIONARY); return net_info_dict;
diff --git a/net/proxy_resolution/win/windows_system_proxy_resolution_service.h b/net/proxy_resolution/win/windows_system_proxy_resolution_service.h index 1e82a11..b994b99 100644 --- a/net/proxy_resolution/win/windows_system_proxy_resolution_service.h +++ b/net/proxy_resolution/win/windows_system_proxy_resolution_service.h
@@ -66,7 +66,7 @@ const NetLogWithSource& net_log) override; void ClearBadProxiesCache() override; const ProxyRetryInfoMap& proxy_retry_info() const override; - base::Value GetProxyNetLogValues(int info_sources) override; + base::Value GetProxyNetLogValues() override; bool CastToConfiguredProxyResolutionService( ConfiguredProxyResolutionService** configured_proxy_resolution_service) override WARN_UNUSED_RESULT;
diff --git a/net/quic/quic_context.h b/net/quic/quic_context.h index d89ec0f..b622ead 100644 --- a/net/quic/quic_context.h +++ b/net/quic/quic_context.h
@@ -174,6 +174,9 @@ bool disable_tls_zero_rtt = false; // If true, gQUIC requests will always require confirmation. bool disable_gquic_zero_rtt = false; + // Network Service Type of the socket for iOS. Default is NET_SERVICE_TYPE_BE + // (best effort). + int ios_network_service_type = 0; }; // QuicContext contains QUIC-related variables that are shared across all of the
diff --git a/net/quic/quic_stream_factory.cc b/net/quic/quic_stream_factory.cc index dabd78c..a5b79f0 100644 --- a/net/quic/quic_stream_factory.cc +++ b/net/quic/quic_stream_factory.cc
@@ -1462,6 +1462,9 @@ DatagramSocket::DEFAULT_BIND, net_log, source); if (params_.enable_socket_recv_optimization) socket->EnableRecvOptimization(); + if (params_.ios_network_service_type > 0) { + socket->SetIOSNetworkServiceType(params_.ios_network_service_type); + } return socket; }
diff --git a/net/socket/datagram_client_socket.h b/net/socket/datagram_client_socket.h index ae34402..9ec3482 100644 --- a/net/socket/datagram_client_socket.h +++ b/net/socket/datagram_client_socket.h
@@ -132,6 +132,10 @@ // ConnectUsingDefaultNetwork(). // Returns a network error code. virtual int SetMulticastInterface(uint32_t interface_index) = 0; + + // Set iOS Network Service Type for socket option SO_NET_SERVICE_TYPE. + // No-op by default. + virtual void SetIOSNetworkServiceType(int ios_network_service_type) {} }; } // namespace net
diff --git a/net/socket/udp_client_socket.cc b/net/socket/udp_client_socket.cc index a0709a0..928a045 100644 --- a/net/socket/udp_client_socket.cc +++ b/net/socket/udp_client_socket.cc
@@ -189,4 +189,10 @@ #endif } +void UDPClientSocket::SetIOSNetworkServiceType(int ios_network_service_type) { +#if defined(OS_POSIX) + socket_.SetIOSNetworkServiceType(ios_network_service_type); +#endif +} + } // namespace net
diff --git a/net/socket/udp_client_socket.h b/net/socket/udp_client_socket.h index 585f684c..d8a7348c 100644 --- a/net/socket/udp_client_socket.h +++ b/net/socket/udp_client_socket.h
@@ -73,6 +73,7 @@ void SetSendmmsgEnabled(bool enabled) override; void SetWriteBatchingActive(bool active) override; int SetMulticastInterface(uint32_t interface_index) override; + void SetIOSNetworkServiceType(int ios_network_service_type) override; private: UDPSocket socket_;
diff --git a/net/socket/udp_socket_posix.cc b/net/socket/udp_socket_posix.cc index 7126556..525307c 100644 --- a/net/socket/udp_socket_posix.cc +++ b/net/socket/udp_socket_posix.cc
@@ -1450,4 +1450,17 @@ return bytes; } +int UDPSocketPosix::SetIOSNetworkServiceType(int ios_network_service_type) { + if (ios_network_service_type == 0) { + return OK; + } +#if defined(OS_IOS) + if (setsockopt(socket_, SOL_SOCKET, SO_NET_SERVICE_TYPE, + &ios_network_service_type, sizeof(ios_network_service_type))) { + return MapSystemError(errno); + } +#endif // defined(OS_IOS) + return OK; +} + } // namespace net
diff --git a/net/socket/udp_socket_posix.h b/net/socket/udp_socket_posix.h index 8fecbc9c..ba011e7 100644 --- a/net/socket/udp_socket_posix.h +++ b/net/socket/udp_socket_posix.h
@@ -388,6 +388,9 @@ experimental_recv_optimization_enabled_ = true; } + // Sets iOS Network Service Type for option SO_NET_SERVICE_TYPE. + int SetIOSNetworkServiceType(int ios_network_service_type); + protected: // WriteAsync batching etc. are to improve throughput of large high // bandwidth uploads.
diff --git a/services/device/public/cpp/BUILD.gn b/services/device/public/cpp/BUILD.gn index 9c31fcd..d2221b9c 100644 --- a/services/device/public/cpp/BUILD.gn +++ b/services/device/public/cpp/BUILD.gn
@@ -33,6 +33,8 @@ sources = [ "test/fake_sensor_and_provider.cc", "test/fake_sensor_and_provider.h", + "test/fake_serial_port_client.cc", + "test/fake_serial_port_client.h", "test/fake_serial_port_manager.cc", "test/fake_serial_port_manager.h", "test/fake_usb_device.cc",
diff --git a/services/device/public/cpp/test/fake_serial_port_client.cc b/services/device/public/cpp/test/fake_serial_port_client.cc new file mode 100644 index 0000000..4782c81 --- /dev/null +++ b/services/device/public/cpp/test/fake_serial_port_client.cc
@@ -0,0 +1,27 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "services/device/public/cpp/test/fake_serial_port_client.h" + +#include "mojo/public/cpp/bindings/self_owned_receiver.h" + +namespace device { + +FakeSerialPortClient::FakeSerialPortClient() = default; + +FakeSerialPortClient::~FakeSerialPortClient() = default; + +// static +mojo::PendingRemote<mojom::SerialPortClient> FakeSerialPortClient::Create() { + mojo::PendingRemote<mojom::SerialPortClient> remote; + mojo::MakeSelfOwnedReceiver(std::make_unique<FakeSerialPortClient>(), + remote.InitWithNewPipeAndPassReceiver()); + return remote; +} + +void FakeSerialPortClient::OnReadError(mojom::SerialReceiveError error) {} + +void FakeSerialPortClient::OnSendError(mojom::SerialSendError error) {} + +} // namespace device
diff --git a/services/device/public/cpp/test/fake_serial_port_client.h b/services/device/public/cpp/test/fake_serial_port_client.h new file mode 100644 index 0000000..b58a105 --- /dev/null +++ b/services/device/public/cpp/test/fake_serial_port_client.h
@@ -0,0 +1,29 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef SERVICES_DEVICE_PUBLIC_CPP_TEST_FAKE_SERIAL_PORT_CLIENT_H_ +#define SERVICES_DEVICE_PUBLIC_CPP_TEST_FAKE_SERIAL_PORT_CLIENT_H_ + +#include "mojo/public/cpp/bindings/pending_remote.h" +#include "services/device/public/mojom/serial.mojom.h" + +namespace device { + +class FakeSerialPortClient : public mojom::SerialPortClient { + public: + FakeSerialPortClient(); + FakeSerialPortClient(FakeSerialPortClient&) = delete; + FakeSerialPortClient& operator=(FakeSerialPortClient&) = delete; + ~FakeSerialPortClient() override; + + static mojo::PendingRemote<mojom::SerialPortClient> Create(); + + // device::mojom::SerialPortClient + void OnReadError(mojom::SerialReceiveError error) override; + void OnSendError(mojom::SerialSendError error) override; +}; + +} // namespace device + +#endif // SERVICES_DEVICE_PUBLIC_CPP_TEST_FAKE_SERIAL_PORT_CLIENT_H_
diff --git a/services/device/public/cpp/test/fake_serial_port_manager.cc b/services/device/public/cpp/test/fake_serial_port_manager.cc index d943da5..83d3df5 100644 --- a/services/device/public/cpp/test/fake_serial_port_manager.cc +++ b/services/device/public/cpp/test/fake_serial_port_manager.cc
@@ -20,25 +20,23 @@ class FakeSerialPort : public mojom::SerialPort { public: FakeSerialPort( - mojo::PendingReceiver<mojom::SerialPort> receiver, + mojo::PendingRemote<mojom::SerialPortClient> client, mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher) - : receiver_(this, std::move(receiver)), watcher_(std::move(watcher)) { - receiver_.set_disconnect_handler(base::BindOnce( - [](FakeSerialPort* self) { delete self; }, base::Unretained(this))); + : watcher_(std::move(watcher)), client_(std::move(client)) { watcher_.set_disconnect_handler(base::BindOnce( [](FakeSerialPort* self) { delete self; }, base::Unretained(this))); } ~FakeSerialPort() override = default; - // mojom::SerialPort - void Open(mojom::SerialConnectionOptionsPtr options, - mojo::PendingRemote<mojom::SerialPortClient> client, - OpenCallback callback) override { - client_.Bind(std::move(client)); - std::move(callback).Run(true); + mojo::PendingRemote<mojom::SerialPort> BindNewPipeAndPassRemote() { + auto remote = receiver_.BindNewPipeAndPassRemote(); + receiver_.set_disconnect_handler(base::BindOnce( + [](FakeSerialPort* self) { delete self; }, base::Unretained(this))); + return remote; } + // mojom::SerialPort void StartWriting(mojo::ScopedDataPipeConsumerHandle consumer) override { in_stream_ = std::move(consumer); } @@ -73,7 +71,7 @@ void Close(CloseCallback callback) override { std::move(callback).Run(); } private: - mojo::Receiver<mojom::SerialPort> receiver_; + mojo::Receiver<mojom::SerialPort> receiver_{this}; mojo::Remote<mojom::SerialPortConnectionWatcher> watcher_; // Mojo handles to keep open in order to simulate an active connection. @@ -125,14 +123,22 @@ std::move(callback).Run(std::move(ports)); } -void FakeSerialPortManager::GetPort( +void FakeSerialPortManager::OpenPort( const base::UnguessableToken& token, bool use_alternate_path, - mojo::PendingReceiver<mojom::SerialPort> receiver, - mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher) { - // The new FakeSerialPort instance is owned by the |receiver| and |watcher| - // pipes. - new FakeSerialPort(std::move(receiver), std::move(watcher)); + device::mojom::SerialConnectionOptionsPtr options, + mojo::PendingRemote<mojom::SerialPortClient> client, + mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher, + OpenPortCallback callback) { + if (simulate_open_failure_) { + std::move(callback).Run(mojo::NullRemote()); + return; + } + + // This FakeSerialPort is owned by |receiver_| and |watcher_| and will + // self-destruct on close. + auto* port = new FakeSerialPort(std::move(client), std::move(watcher)); + std::move(callback).Run(port->BindNewPipeAndPassRemote()); } } // namespace device
diff --git a/services/device/public/cpp/test/fake_serial_port_manager.h b/services/device/public/cpp/test/fake_serial_port_manager.h index 448593dd..1b3b0ef9 100644 --- a/services/device/public/cpp/test/fake_serial_port_manager.h +++ b/services/device/public/cpp/test/fake_serial_port_manager.h
@@ -26,20 +26,26 @@ void AddPort(mojom::SerialPortInfoPtr port); void RemovePort(base::UnguessableToken token); + void set_simulate_open_failure(bool simulate_open_failure) { + simulate_open_failure_ = simulate_open_failure; + } + // mojom::SerialPortManager void SetClient( mojo::PendingRemote<mojom::SerialPortManagerClient> client) override; void GetDevices(GetDevicesCallback callback) override; - void GetPort( - const base::UnguessableToken& token, - bool use_alternate_path, - mojo::PendingReceiver<mojom::SerialPort> receiver, - mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher) override; + void OpenPort(const base::UnguessableToken& token, + bool use_alternate_path, + device::mojom::SerialConnectionOptionsPtr options, + mojo::PendingRemote<mojom::SerialPortClient> client, + mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher, + OpenPortCallback callback) override; private: std::map<base::UnguessableToken, mojom::SerialPortInfoPtr> ports_; mojo::ReceiverSet<mojom::SerialPortManager> receivers_; mojo::RemoteSet<mojom::SerialPortManagerClient> clients_; + bool simulate_open_failure_ = false; DISALLOW_COPY_AND_ASSIGN(FakeSerialPortManager); };
diff --git a/services/device/public/mojom/hid.mojom b/services/device/public/mojom/hid.mojom index 8229a5c..b93b66c 100644 --- a/services/device/public/mojom/hid.mojom +++ b/services/device/public/mojom/hid.mojom
@@ -345,7 +345,7 @@ // A client interface for receiving a notification when HID devices are // physically connected or disconnected. -[Stable] +[Stable, Uuid="1b9b8008-dcf3-4c2e-9d68-ca3c47778817"] interface HidManagerClient { // Notifies the client that a device is added. DeviceAdded@0(HidDeviceInfo device_info); @@ -358,7 +358,7 @@ // Provides an interface for enumerating available HID devices, registering for // device connection and disconnection notifications, and opening a connection // for reading from and writing to a HID device. -[Stable] +[Stable, Uuid="9e931765-42c9-4afd-9dc5-9086621b7bb6"] interface HidManager { // Enumerates available devices and set as a client of HidManager. // The implementation of HidManager guarantees that the returned callback @@ -392,7 +392,7 @@ // allows a device to define its own packet formats (reports) for sending or // receiving data. The methods in HidConnection send or receive data and specify // which report is used. -[Stable] +[Stable, Uuid="1b9b8008-dcf3-4c2e-9d68-ca3c47778817"] interface HidConnection { // A |report_id| of 0 is returned via callback if report IDs are not // supported by the device. @@ -412,7 +412,7 @@ // A client interface for receiving a notification when input reports are // received. -[Stable] +[Stable, Uuid="11f949ed-fa57-4a94-a433-90b72a2d2b63"] interface HidConnectionClient { // Notifies the client that an input report was received. A |report_id| of 0 // is passed if report IDs are not used by the device. @@ -429,6 +429,6 @@ // itself as a watcher so it can be notified when the connection is closed. This // allows the service to keep track of whether there are open connections for // the purpose of drawing an indicator icon when a tab is using a HID device. -[Stable] +[Stable, Uuid="8af071b5-0994-4af7-9c3f-6025d7f9e9d0"] interface HidConnectionWatcher { };
diff --git a/services/device/public/mojom/serial.mojom b/services/device/public/mojom/serial.mojom index bb5f27e..881421a 100644 --- a/services/device/public/mojom/serial.mojom +++ b/services/device/public/mojom/serial.mojom
@@ -147,14 +147,17 @@ // Returns the list of serial ports currently available on the host. GetDevices() => (array<SerialPortInfo> devices); - // Creates a SerialPort instance attached to the port represented by |token|. - // If |use_alternate_path| is specified then the |alternate_path| for the - // port will be used instead. When the pipe passed in |port_receiver| is - // closed the optional pipe passed in |watcher| will also be closed. - GetPort(mojo_base.mojom.UnguessableToken token, - bool use_alternate_path, - pending_receiver<SerialPort> port_receiver, - pending_remote<SerialPortConnectionWatcher>? watcher); + // Opens the port represented by |token| using |options| and returns a + // connection to it as |port|. If |use_alternate_path| is specified then the + // |alternate_path| for the port will be used instead. When the pipe returned + // in |port| is closed the optional pipe passed in |watcher| will also be + // closed and vice a versa. + OpenPort(mojo_base.mojom.UnguessableToken token, + bool use_alternate_path, + SerialConnectionOptions options, + pending_remote<SerialPortClient> client, + pending_remote<SerialPortConnectionWatcher>? watcher) + => (pending_remote<SerialPort>? port); }; // Client interface for SerialPortManager. @@ -168,10 +171,6 @@ // Performs asynchronous I/O on serial devices. interface SerialPort { - // Initiates an Open of the device then returns result. - Open(SerialConnectionOptions options, - pending_remote<SerialPortClient> client) => (bool success); - // Start writing data from |consumer| to the port. This should be called after // Open() or to restart data flow after when SerialPortClient#OnSendError is // called on |client| to indicate an error. @@ -201,8 +200,8 @@ // Performs a platform-specific port configuration query and returns got info. GetPortInfo() => (SerialConnectionInfo info); - // Closes the connection created by Open(). Once this returns no more data - // will be sent or received on |in_stream| or |out_stream|. + // Closes the port and this pipe. Once this returns no more data will be sent + // or received on |in_stream| or |out_stream|. Close() => (); };
diff --git a/services/device/serial/bluetooth_serial_port_impl.cc b/services/device/serial/bluetooth_serial_port_impl.cc index 3d8d293..fe527d00 100644 --- a/services/device/serial/bluetooth_serial_port_impl.cc +++ b/services/device/serial/bluetooth_serial_port_impl.cc
@@ -13,33 +13,37 @@ namespace device { // static -void BluetoothSerialPortImpl::Create( +void BluetoothSerialPortImpl::Open( scoped_refptr<BluetoothAdapter> adapter, const std::string& address, - mojo::PendingReceiver<mojom::SerialPort> receiver, - mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher) { + mojom::SerialConnectionOptionsPtr options, + mojo::PendingRemote<mojom::SerialPortClient> client, + mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher, + OpenCallback callback) { DCHECK(base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableBluetoothSerialPortProfileInSerialApi)); - // This BluetoothSerialPortImpl is owned by |receiver| and |watcher|. - new BluetoothSerialPortImpl(std::move(adapter), address, std::move(receiver), - std::move(watcher)); + // This BluetoothSerialPortImpl is owned by its |receiver_| and |watcher_| and + // will self-destruct on connection failure. + auto* port = new BluetoothSerialPortImpl( + std::move(adapter), address, std::move(options), std::move(client), + std::move(watcher)); + port->OpenSocket(std::move(callback)); } BluetoothSerialPortImpl::BluetoothSerialPortImpl( scoped_refptr<BluetoothAdapter> adapter, const std::string& address, - mojo::PendingReceiver<mojom::SerialPort> receiver, + mojom::SerialConnectionOptionsPtr options, + mojo::PendingRemote<mojom::SerialPortClient> client, mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher) - : receiver_(this, std::move(receiver)), - watcher_(std::move(watcher)), + : watcher_(std::move(watcher)), + client_(std::move(client)), in_stream_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL), out_stream_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL), bluetooth_adapter_(std::move(adapter)), - address_(address) { - receiver_.set_disconnect_handler( - base::BindOnce([](BluetoothSerialPortImpl* self) { delete self; }, - base::Unretained(this))); + address_(address), + options_(std::move(options)) { if (watcher_.is_bound()) { watcher_.set_disconnect_handler( base::BindOnce([](BluetoothSerialPortImpl* self) { delete self; }, @@ -52,17 +56,14 @@ bluetooth_socket_->Close(); } -void BluetoothSerialPortImpl::Open( - mojom::SerialConnectionOptionsPtr options, - mojo::PendingRemote<mojom::SerialPortClient> client, - OpenCallback callback) { - if (client) - client_.Bind(std::move(client)); +void BluetoothSerialPortImpl::OpenSocket(OpenCallback callback) { BluetoothDevice* device = bluetooth_adapter_->GetDevice(address_); if (!device) { - std::move(callback).Run(false); + std::move(callback).Run(mojo::NullRemote()); + delete this; return; } + BluetoothDevice::UUIDSet device_uuids = device->GetUUIDs(); if (base::Contains(device_uuids, GetSerialPortProfileUUID())) { auto copyable_callback = @@ -75,7 +76,9 @@ weak_ptr_factory_.GetWeakPtr(), copyable_callback)); return; } - std::move(callback).Run(false); + + std::move(callback).Run(mojo::NullRemote()); + delete this; } void BluetoothSerialPortImpl::OnSocketConnected( @@ -83,13 +86,19 @@ scoped_refptr<BluetoothSocket> socket) { DCHECK(socket); bluetooth_socket_ = std::move(socket); - std::move(callback).Run(true); + mojo::PendingRemote<mojom::SerialPort> port = + receiver_.BindNewPipeAndPassRemote(); + receiver_.set_disconnect_handler( + base::BindOnce([](BluetoothSerialPortImpl* self) { delete self; }, + base::Unretained(this))); + std::move(callback).Run(std::move(port)); } void BluetoothSerialPortImpl::OnSocketConnectedError( OpenCallback callback, const std::string& message) { - std::move(callback).Run(false); + std::move(callback).Run(mojo::NullRemote()); + delete this; } void BluetoothSerialPortImpl::StartWriting( @@ -378,12 +387,8 @@ } void BluetoothSerialPortImpl::Close(CloseCallback callback) { - client_.reset(); - if (bluetooth_socket_) { - bluetooth_socket_->Close(); - bluetooth_socket_.reset(); - } std::move(callback).Run(); + delete this; } } // namespace device
diff --git a/services/device/serial/bluetooth_serial_port_impl.h b/services/device/serial/bluetooth_serial_port_impl.h index 46e0840d7..69bdb68 100644 --- a/services/device/serial/bluetooth_serial_port_impl.h +++ b/services/device/serial/bluetooth_serial_port_impl.h
@@ -22,19 +22,25 @@ // which is closed upon error in any of the interface functions. class BluetoothSerialPortImpl : public mojom::SerialPort { public: + using OpenCallback = + base::OnceCallback<void(mojo::PendingRemote<mojom::SerialPort>)>; + // Creates of instance of BluetoothSerialPortImpl using a Bluetooth // adapter, a Bluetooth device address and a receiver/watcher to // create a pipe. The receiver and watcher will own this object. - static void Create( + static void Open( scoped_refptr<BluetoothAdapter> adapter, const std::string& address, - mojo::PendingReceiver<mojom::SerialPort> receiver, - mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher); + mojom::SerialConnectionOptionsPtr options, + mojo::PendingRemote<mojom::SerialPortClient> client, + mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher, + OpenCallback callback); BluetoothSerialPortImpl( scoped_refptr<BluetoothAdapter> adapter, const std::string& address, - mojo::PendingReceiver<mojom::SerialPort> receiver, + mojom::SerialConnectionOptionsPtr options, + mojo::PendingRemote<mojom::SerialPortClient> client, mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher); BluetoothSerialPortImpl(const BluetoothSerialPortImpl&) = delete; BluetoothSerialPortImpl& operator=(const BluetoothSerialPortImpl&) = delete; @@ -42,9 +48,6 @@ private: // mojom::SerialPort methods: - void Open(mojom::SerialConnectionOptionsPtr options, - mojo::PendingRemote<mojom::SerialPortClient> client, - OpenCallback callback) override; void StartWriting(mojo::ScopedDataPipeConsumerHandle consumer) override; void StartReading(mojo::ScopedDataPipeProducerHandle producer) override; void Flush(mojom::SerialPortFlushMode mode, FlushCallback callback) override; @@ -57,6 +60,7 @@ void GetPortInfo(GetPortInfoCallback callback) override; void Close(CloseCallback callback) override; + void OpenSocket(OpenCallback callback); void WriteToSocket(MojoResult result, const mojo::HandleSignalsState& state); void ReadFromSocketAndWriteOut(MojoResult result, const mojo::HandleSignalsState& state); @@ -78,7 +82,7 @@ void OnBluetoothSocketSend(int num_bytes_sent); void OnBluetoothSocketSendError(const std::string& error_message); - mojo::Receiver<mojom::SerialPort> receiver_; + mojo::Receiver<mojom::SerialPort> receiver_{this}; mojo::Remote<mojom::SerialPortConnectionWatcher> watcher_; mojo::Remote<mojom::SerialPortClient> client_;
diff --git a/services/device/serial/bluetooth_serial_port_impl_unittest.cc b/services/device/serial/bluetooth_serial_port_impl_unittest.cc index b74b85e..dec10c6 100644 --- a/services/device/serial/bluetooth_serial_port_impl_unittest.cc +++ b/services/device/serial/bluetooth_serial_port_impl_unittest.cc
@@ -21,6 +21,7 @@ #include "net/base/io_buffer.h" #include "services/device/public/cpp/bluetooth/bluetooth_utils.h" #include "services/device/public/cpp/serial/serial_switches.h" +#include "services/device/public/cpp/test/fake_serial_port_client.h" #include "services/device/public/mojom/serial.mojom.h" #include "services/device/serial/buffer.h" #include "testing/gmock/include/gmock/gmock.h" @@ -73,35 +74,18 @@ ConnectToService(GetSerialPortProfileUUID(), _, _)) .WillOnce(RunOnceCallback<1>(mock_socket_)); - BluetoothSerialPortImpl::Create(std::move(adapter), kDeviceAddress, - port->BindNewPipeAndPassReceiver(), - std::move(watcher_remote)); - } - - void CreatePortWithSocketError( - mojo::Remote<mojom::SerialPort>* port, - mojo::SelfOwnedReceiverRef<mojom::SerialPortConnectionWatcher>* watcher) { - mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher_remote; - *watcher = mojo::MakeSelfOwnedReceiver( - std::make_unique<mojom::SerialPortConnectionWatcher>(), - watcher_remote.InitWithNewPipeAndPassReceiver()); - - scoped_refptr<MockBluetoothAdapter> adapter = - base::MakeRefCounted<MockBluetoothAdapter>(); - device::BluetoothAdapterFactory::SetAdapterForTesting(adapter); - mock_device_ = std::make_unique<MockBluetoothDevice>( - adapter.get(), 0, "Test Device", kDeviceAddress, false, false); - mock_device_->AddUUID(GetSerialPortProfileUUID()); - - EXPECT_CALL(*adapter, GetDevice(kDeviceAddress)) - .WillOnce(Return(mock_device_.get())); - EXPECT_CALL(*mock_device_, - ConnectToService(GetSerialPortProfileUUID(), _, _)) - .WillOnce(RunOnceCallback<2>("Error")); - - BluetoothSerialPortImpl::Create(std::move(adapter), kDeviceAddress, - port->BindNewPipeAndPassReceiver(), - std::move(watcher_remote)); + base::RunLoop loop; + BluetoothSerialPortImpl::Open( + std::move(adapter), kDeviceAddress, + mojom::SerialConnectionOptions::New(), FakeSerialPortClient::Create(), + std::move(watcher_remote), + base::BindLambdaForTesting( + [&](mojo::PendingRemote<mojom::SerialPort> remote) { + EXPECT_TRUE(remote.is_valid()); + port->Bind(std::move(remote)); + loop.Quit(); + })); + loop.Run(); } void CreateDataPipe(mojo::ScopedDataPipeProducerHandle* producer, @@ -126,58 +110,34 @@ base::test::SingleThreadTaskEnvironment task_environment_; }; -class FakeSerialPortClient : public mojom::SerialPortClient { - public: - FakeSerialPortClient() = default; - FakeSerialPortClient(FakeSerialPortClient&) = delete; - FakeSerialPortClient& operator=(FakeSerialPortClient&) = delete; - ~FakeSerialPortClient() override = default; - - void Bind(mojo::PendingReceiver<device::mojom::SerialPortClient> receiver) { - receiver_.Bind(std::move(receiver)); - } - - // mojom::SerialPortClient - void OnReadError(mojom::SerialReceiveError error) override {} - void OnSendError(mojom::SerialSendError error) override {} - - private: - mojo::Receiver<mojom::SerialPortClient> receiver_{this}; -}; - } // namespace -TEST_F(BluetoothSerialPortImplTest, NullSocketTest) { - mojo::Remote<mojom::SerialPort> serial_port; - mojo::SelfOwnedReceiverRef<mojom::SerialPortConnectionWatcher> watcher; - CreatePortWithSocketError(&serial_port, &watcher); +TEST_F(BluetoothSerialPortImplTest, OpenFailure) { + scoped_refptr<MockBluetoothAdapter> adapter = + base::MakeRefCounted<MockBluetoothAdapter>(); + device::BluetoothAdapterFactory::SetAdapterForTesting(adapter); + auto mock_device = std::make_unique<MockBluetoothDevice>( + adapter.get(), 0, "Test Device", kDeviceAddress, false, false); + mock_device->AddUUID(GetSerialPortProfileUUID()); - mojo::ScopedDataPipeProducerHandle producer; - mojo::ScopedDataPipeConsumerHandle consumer; - CreateDataPipe(&producer, &consumer); - - auto options = mojom::SerialConnectionOptions::New(); - mojo::PendingRemote<mojom::SerialPortClient> client; - FakeSerialPortClient serial_client; - serial_client.Bind(client.InitWithNewPipeAndPassReceiver()); - base::RunLoop loop; - serial_port->Open(std::move(options), std::move(client), - base::BindLambdaForTesting([&loop](bool success) { - EXPECT_FALSE(success); - loop.Quit(); - })); - loop.Run(); + EXPECT_CALL(*adapter, GetDevice(kDeviceAddress)) + .WillOnce(Return(mock_device.get())); + EXPECT_CALL(*mock_device, ConnectToService(GetSerialPortProfileUUID(), _, _)) + .WillOnce(RunOnceCallback<2>("Error")); EXPECT_CALL(mock_socket(), Receive(_, _, _)).Times(0); EXPECT_CALL(mock_socket(), Close()).Times(0); - serial_port->StartReading(std::move(producer)); - - base::RunLoop disconnect_loop; - watcher->set_connection_error_handler(disconnect_loop.QuitClosure()); - - serial_port.reset(); - disconnect_loop.Run(); + base::RunLoop loop; + BluetoothSerialPortImpl::Open( + std::move(adapter), kDeviceAddress, mojom::SerialConnectionOptions::New(), + FakeSerialPortClient::Create(), mojo::NullRemote(), + base::BindLambdaForTesting( + [&](mojo::PendingRemote<mojom::SerialPort> remote) { + EXPECT_FALSE(remote.is_valid()); + loop.Quit(); + })); + loop.Run(); } TEST_F(BluetoothSerialPortImplTest, StartWritingTest) { @@ -189,18 +149,6 @@ mojo::ScopedDataPipeConsumerHandle consumer; CreateDataPipe(&producer, &consumer); - auto options = mojom::SerialConnectionOptions::New(); - mojo::PendingRemote<mojom::SerialPortClient> client; - FakeSerialPortClient serial_client; - serial_client.Bind(client.InitWithNewPipeAndPassReceiver()); - base::RunLoop loop; - serial_port->Open(std::move(options), std::move(client), - base::BindLambdaForTesting([&loop](bool success) { - EXPECT_TRUE(success); - loop.Quit(); - })); - loop.Run(); - uint32_t bytes_read = std::char_traits<char>::length(kBuffer); auto write_buffer = base::MakeRefCounted<net::StringIOBuffer>(kBuffer); @@ -244,18 +192,6 @@ mojo::ScopedDataPipeConsumerHandle consumer; CreateDataPipe(&producer, &consumer); - auto options = mojom::SerialConnectionOptions::New(); - mojo::PendingRemote<mojom::SerialPortClient> client; - FakeSerialPortClient serial_client; - serial_client.Bind(client.InitWithNewPipeAndPassReceiver()); - base::RunLoop loop; - serial_port->Open(std::move(options), std::move(client), - base::BindLambdaForTesting([&loop](bool success) { - EXPECT_TRUE(success); - loop.Quit(); - })); - loop.Run(); - uint32_t bytes_read = std::char_traits<char>::length(kBuffer); auto write_buffer = base::MakeRefCounted<net::StringIOBuffer>(kBuffer); @@ -295,18 +231,6 @@ mojo::ScopedDataPipeConsumerHandle consumer; CreateDataPipe(&producer, &consumer); - auto options = mojom::SerialConnectionOptions::New(); - mojo::PendingRemote<mojom::SerialPortClient> client; - FakeSerialPortClient serial_client; - serial_client.Bind(client.InitWithNewPipeAndPassReceiver()); - base::RunLoop loop; - serial_port->Open(std::move(options), std::move(client), - base::BindLambdaForTesting([&loop](bool success) { - EXPECT_TRUE(success); - loop.Quit(); - })); - loop.Run(); - serial_port->StartWriting(std::move(consumer)); producer.reset(); @@ -331,17 +255,6 @@ mojo::ScopedDataPipeConsumerHandle consumer; CreateDataPipe(&producer, &consumer); - auto options = mojom::SerialConnectionOptions::New(); - mojo::PendingRemote<mojom::SerialPortClient> client; - FakeSerialPortClient serial_client; - serial_client.Bind(client.InitWithNewPipeAndPassReceiver()); - base::RunLoop loop; - serial_port->Open( - std::move(options), std::move(client), - base::BindOnce([](base::RunLoop* loop, bool success) { loop->Quit(); }, - &loop)); - loop.Run(); - EXPECT_CALL(mock_socket(), Close()); base::RunLoop close_loop;
diff --git a/services/device/serial/serial_port_impl.cc b/services/device/serial/serial_port_impl.cc index 01058c9..203ae289 100644 --- a/services/device/serial/serial_port_impl.cc +++ b/services/device/serial/serial_port_impl.cc
@@ -16,39 +16,45 @@ namespace device { // static -void SerialPortImpl::Create( +void SerialPortImpl::Open( const base::FilePath& path, - mojo::PendingReceiver<mojom::SerialPort> receiver, + mojom::SerialConnectionOptionsPtr options, + mojo::PendingRemote<mojom::SerialPortClient> client, mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher, - scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner) { - // This SerialPortImpl is owned by |receiver| and |watcher|. - new SerialPortImpl( + scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner, + OpenCallback callback) { + // This SerialPortImpl is owned by |receiver_| and |watcher_| and will + // self-destruct on close. + auto* port = new SerialPortImpl( device::SerialIoHandler::Create(path, std::move(ui_task_runner)), - std::move(receiver), std::move(watcher)); + std::move(client), std::move(watcher)); + port->OpenPort(*options, std::move(callback)); } // static -void SerialPortImpl::CreateForTesting( +void SerialPortImpl::OpenForTesting( scoped_refptr<SerialIoHandler> io_handler, - mojo::PendingReceiver<mojom::SerialPort> receiver, - mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher) { - // This SerialPortImpl is owned by |receiver| and |watcher|. - new SerialPortImpl(std::move(io_handler), std::move(receiver), - std::move(watcher)); + mojom::SerialConnectionOptionsPtr options, + mojo::PendingRemote<mojom::SerialPortClient> client, + mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher, + OpenCallback callback) { + // This SerialPortImpl is owned by |receiver| and |watcher| and will + // self-destruct on close. + auto* port = new SerialPortImpl(std::move(io_handler), std::move(client), + std::move(watcher)); + port->OpenPort(*options, std::move(callback)); } SerialPortImpl::SerialPortImpl( scoped_refptr<SerialIoHandler> io_handler, - mojo::PendingReceiver<mojom::SerialPort> receiver, + mojo::PendingRemote<mojom::SerialPortClient> client, mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher) - : receiver_(this, std::move(receiver)), - io_handler_(std::move(io_handler)), + : io_handler_(std::move(io_handler)), + client_(std::move(client)), watcher_(std::move(watcher)), in_stream_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL), out_stream_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL) { - receiver_.set_disconnect_handler(base::BindOnce( - [](SerialPortImpl* self) { delete self; }, base::Unretained(this))); if (watcher_.is_bound()) { watcher_.set_disconnect_handler(base::BindOnce( [](SerialPortImpl* self) { delete self; }, base::Unretained(this))); @@ -60,13 +66,25 @@ io_handler_->Close(base::DoNothing()); } -void SerialPortImpl::Open(mojom::SerialConnectionOptionsPtr options, - mojo::PendingRemote<mojom::SerialPortClient> client, - OpenCallback callback) { - if (client) - client_.Bind(std::move(client)); +void SerialPortImpl::OpenPort(const mojom::SerialConnectionOptions& options, + OpenCallback callback) { + io_handler_->Open( + options, base::BindOnce(&SerialPortImpl::PortOpened, + weak_factory_.GetWeakPtr(), std::move(callback))); +} - io_handler_->Open(*options, std::move(callback)); +void SerialPortImpl::PortOpened(OpenCallback callback, bool success) { + mojo::PendingRemote<SerialPort> port; + if (success) { + port = receiver_.BindNewPipeAndPassRemote(); + receiver_.set_disconnect_handler(base::BindOnce( + [](SerialPortImpl* self) { delete self; }, base::Unretained(this))); + } + + std::move(callback).Run(std::move(port)); + + if (!success) + delete this; } void SerialPortImpl::StartWriting(mojo::ScopedDataPipeConsumerHandle consumer) { @@ -183,7 +201,9 @@ } void SerialPortImpl::Close(CloseCallback callback) { - io_handler_->Close(std::move(callback)); + io_handler_->Close(base::BindOnce(&SerialPortImpl::PortClosed, + weak_factory_.GetWeakPtr(), + std::move(callback))); } void SerialPortImpl::WriteToPort(MojoResult result, @@ -300,4 +320,9 @@ out_stream_watcher_.ArmOrNotify(); } +void SerialPortImpl::PortClosed(CloseCallback callback) { + std::move(callback).Run(); + delete this; +} + } // namespace device
diff --git a/services/device/serial/serial_port_impl.h b/services/device/serial/serial_port_impl.h index 1757a55..db7016d 100644 --- a/services/device/serial/serial_port_impl.h +++ b/services/device/serial/serial_port_impl.h
@@ -33,28 +33,32 @@ // This class must be constructed and run on IO thread. class SerialPortImpl : public mojom::SerialPort { public: - static void Create( - const base::FilePath& path, - mojo::PendingReceiver<mojom::SerialPort> receiver, - mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher, - scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner); + using OpenCallback = + base::OnceCallback<void(mojo::PendingRemote<mojom::SerialPort>)>; - static void CreateForTesting( + static void Open( + const base::FilePath& path, + mojom::SerialConnectionOptionsPtr options, + mojo::PendingRemote<mojom::SerialPortClient> client, + mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher, + scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner, + OpenCallback callback); + + static void OpenForTesting( scoped_refptr<SerialIoHandler> io_handler, - mojo::PendingReceiver<mojom::SerialPort> receiver, - mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher); + mojom::SerialConnectionOptionsPtr options, + mojo::PendingRemote<mojom::SerialPortClient> client, + mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher, + OpenCallback callback); private: SerialPortImpl( scoped_refptr<SerialIoHandler> io_handler, - mojo::PendingReceiver<mojom::SerialPort> receiver, + mojo::PendingRemote<mojom::SerialPortClient> client, mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher); ~SerialPortImpl() override; // mojom::SerialPort methods: - void Open(mojom::SerialConnectionOptionsPtr options, - mojo::PendingRemote<mojom::SerialPortClient> client, - OpenCallback callback) override; void StartWriting(mojo::ScopedDataPipeConsumerHandle consumer) override; void StartReading(mojo::ScopedDataPipeProducerHandle producer) override; void Flush(mojom::SerialPortFlushMode mode, FlushCallback callback) override; @@ -67,6 +71,9 @@ void GetPortInfo(GetPortInfoCallback callback) override; void Close(CloseCallback callback) override; + void OpenPort(const mojom::SerialConnectionOptions& options, + OpenCallback callback); + void PortOpened(OpenCallback callback, bool success); void WriteToPort(MojoResult result, const mojo::HandleSignalsState& state); void OnWriteToPortCompleted(uint32_t bytes_expected, uint32_t bytes_sent, @@ -74,8 +81,9 @@ void ReadFromPortAndWriteOut(MojoResult result, const mojo::HandleSignalsState& state); void WriteToOutStream(uint32_t bytes_read, mojom::SerialReceiveError error); + void PortClosed(CloseCallback callback); - mojo::Receiver<mojom::SerialPort> receiver_; + mojo::Receiver<mojom::SerialPort> receiver_{this}; // Underlying connection to the serial port. scoped_refptr<SerialIoHandler> io_handler_;
diff --git a/services/device/serial/serial_port_impl_unittest.cc b/services/device/serial/serial_port_impl_unittest.cc index fdd0374..d0a60b1 100644 --- a/services/device/serial/serial_port_impl_unittest.cc +++ b/services/device/serial/serial_port_impl_unittest.cc
@@ -79,9 +79,18 @@ *watcher = mojo::MakeSelfOwnedReceiver( std::make_unique<mojom::SerialPortConnectionWatcher>(), watcher_remote.InitWithNewPipeAndPassReceiver()); - SerialPortImpl::CreateForTesting( + base::RunLoop loop; + SerialPortImpl::OpenForTesting( base::MakeRefCounted<FakeSerialIoHandler>(), - port->BindNewPipeAndPassReceiver(), std::move(watcher_remote)); + mojom::SerialConnectionOptions::New(), mojo::NullRemote(), + std::move(watcher_remote), + base::BindLambdaForTesting( + [&](mojo::PendingRemote<mojom::SerialPort> pending_remote) { + EXPECT_TRUE(pending_remote.is_valid()); + port->Bind(std::move(pending_remote)); + loop.Quit(); + })); + loop.Run(); } void CreateDataPipe(mojo::ScopedDataPipeProducerHandle* producer, @@ -115,32 +124,6 @@ } }; -TEST_F(SerialPortImplTest, StartIoBeforeOpen) { - mojo::Remote<mojom::SerialPort> serial_port; - mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher_remote; - mojo::SelfOwnedReceiverRef<mojom::SerialPortConnectionWatcher> watcher = - mojo::MakeSelfOwnedReceiver( - std::make_unique<mojom::SerialPortConnectionWatcher>(), - watcher_remote.InitWithNewPipeAndPassReceiver()); - SerialPortImpl::Create( - base::FilePath(FILE_PATH_LITERAL("/dev/fakeserialmojo")), - serial_port.BindNewPipeAndPassReceiver(), std::move(watcher_remote), - task_environment_.GetMainThreadTaskRunner()); - - mojo::ScopedDataPipeConsumerHandle consumer = StartReading(serial_port.get()); - mojo::ScopedDataPipeProducerHandle producer = StartWriting(serial_port.get()); - - // Write some data so that StartWriting() will cause a call to Write(). - static const char kBuffer[] = "test"; - uint32_t bytes_written = base::size(kBuffer); - MojoResult result = - producer->WriteData(&kBuffer, &bytes_written, MOJO_WRITE_DATA_FLAG_NONE); - DCHECK_EQ(result, MOJO_RESULT_OK); - DCHECK_EQ(bytes_written, base::size(kBuffer)); - - base::RunLoop().RunUntilIdle(); -} - TEST_F(SerialPortImplTest, WatcherClosedWhenPortClosed) { mojo::Remote<mojom::SerialPort> serial_port; mojo::SelfOwnedReceiverRef<mojom::SerialPortConnectionWatcher> watcher;
diff --git a/services/device/serial/serial_port_manager_impl.cc b/services/device/serial/serial_port_manager_impl.cc index e16d374d..06df5ae 100644 --- a/services/device/serial/serial_port_manager_impl.cc +++ b/services/device/serial/serial_port_manager_impl.cc
@@ -20,6 +20,17 @@ namespace device { +namespace { + +void OnPortOpened(mojom::SerialPortManager::OpenPortCallback callback, + const scoped_refptr<base::TaskRunner>& task_runner, + mojo::PendingRemote<mojom::SerialPort> port) { + task_runner->PostTask(FROM_HERE, + base::BindOnce(std::move(callback), std::move(port))); +} + +} // namespace + SerialPortManagerImpl::SerialPortManagerImpl( scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner) @@ -75,11 +86,13 @@ std::move(callback).Run(std::move(devices)); } -void SerialPortManagerImpl::GetPort( +void SerialPortManagerImpl::OpenPort( const base::UnguessableToken& token, bool use_alternate_path, - mojo::PendingReceiver<mojom::SerialPort> receiver, - mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher) { + device::mojom::SerialConnectionOptionsPtr options, + mojo::PendingRemote<mojom::SerialPortClient> client, + mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher, + OpenPortCallback callback) { if (!enumerator_) { enumerator_ = SerialDeviceEnumerator::Create(ui_task_runner_); observed_enumerator_.Add(enumerator_.get()); @@ -89,8 +102,10 @@ if (path) { io_task_runner_->PostTask( FROM_HERE, - base::BindOnce(&SerialPortImpl::Create, *path, std::move(receiver), - std::move(watcher), ui_task_runner_)); + base::BindOnce(&SerialPortImpl::Open, *path, std::move(options), + std::move(client), std::move(watcher), ui_task_runner_, + base::BindOnce(&OnPortOpened, std::move(callback), + base::SequencedTaskRunnerHandle::Get()))); return; } @@ -106,11 +121,17 @@ if (address) { ui_task_runner_->PostTask( FROM_HERE, - base::BindOnce(&BluetoothSerialPortImpl::Create, - bluetooth_enumerator_->GetAdapter(), *address, - std::move(receiver), std::move(watcher))); + base::BindOnce( + &BluetoothSerialPortImpl::Open, + bluetooth_enumerator_->GetAdapter(), *address, std::move(options), + std::move(client), std::move(watcher), + base::BindOnce(&OnPortOpened, std::move(callback), + base::SequencedTaskRunnerHandle::Get()))); + return; } } + + std::move(callback).Run(mojo::NullRemote()); } void SerialPortManagerImpl::OnPortAdded(const mojom::SerialPortInfo& port) {
diff --git a/services/device/serial/serial_port_manager_impl.h b/services/device/serial/serial_port_manager_impl.h index 7e91871..9b92c30 100644 --- a/services/device/serial/serial_port_manager_impl.h +++ b/services/device/serial/serial_port_manager_impl.h
@@ -48,11 +48,12 @@ void SetClient( mojo::PendingRemote<mojom::SerialPortManagerClient> client) override; void GetDevices(GetDevicesCallback callback) override; - void GetPort( - const base::UnguessableToken& token, - bool use_alternate_path, - mojo::PendingReceiver<mojom::SerialPort> receiver, - mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher) override; + void OpenPort(const base::UnguessableToken& token, + bool use_alternate_path, + device::mojom::SerialConnectionOptionsPtr options, + mojo::PendingRemote<mojom::SerialPortClient> client, + mojo::PendingRemote<mojom::SerialPortConnectionWatcher> watcher, + OpenPortCallback callback) override; // SerialDeviceEnumerator::Observer methods: void OnPortAdded(const mojom::SerialPortInfo& port) override;
diff --git a/services/device/serial/serial_port_manager_impl_unittest.cc b/services/device/serial/serial_port_manager_impl_unittest.cc index ce92f74..d2afe20 100644 --- a/services/device/serial/serial_port_manager_impl_unittest.cc +++ b/services/device/serial/serial_port_manager_impl_unittest.cc
@@ -28,6 +28,7 @@ #include "services/device/device_service_test_base.h" #include "services/device/public/cpp/bluetooth/bluetooth_utils.h" #include "services/device/public/cpp/serial/serial_switches.h" +#include "services/device/public/cpp/test/fake_serial_port_client.h" #include "services/device/public/mojom/serial.mojom.h" #include "services/device/serial/bluetooth_serial_device_enumerator.h" #include "services/device/serial/fake_serial_device_enumerator.h" @@ -68,25 +69,6 @@ mojo::Receiver<mojom::SerialPortManagerClient> receiver_{this}; }; -class FakeSerialPortClient : public mojom::SerialPortClient { - public: - FakeSerialPortClient() = default; - FakeSerialPortClient(FakeSerialPortClient&) = delete; - FakeSerialPortClient& operator=(FakeSerialPortClient&) = delete; - ~FakeSerialPortClient() override = default; - - void Bind(mojo::PendingReceiver<device::mojom::SerialPortClient> receiver) { - receiver_.Bind(std::move(receiver)); - } - - // mojom::SerialPortClient - void OnReadError(mojom::SerialReceiveError error) override {} - void OnSendError(mojom::SerialSendError error) override {} - - private: - mojo::Receiver<mojom::SerialPortClient> receiver_{this}; -}; - } // namespace class SerialPortManagerImplTest : public DeviceServiceTestBase { @@ -178,7 +160,7 @@ // This is to simply test that we can enumerate devices on the platform without // hanging or crashing. -TEST_F(SerialPortManagerImplTest, SimpleConnectTest) { +TEST_F(SerialPortManagerImplTest, SimpleEnumerationTest) { // DeviceService has its own instance of SerialPortManagerImpl that is used to // bind the receiver over the one created for this test. mojo::Remote<mojom::SerialPortManager> port_manager; @@ -188,17 +170,6 @@ base::RunLoop loop; port_manager->GetDevices(base::BindLambdaForTesting( [&](std::vector<mojom::SerialPortInfoPtr> results) { - for (auto& device : results) { - mojo::Remote<mojom::SerialPort> serial_port; - port_manager->GetPort(device->token, - /*use_alternate_path=*/false, - serial_port.BindNewPipeAndPassReceiver(), - /*watcher=*/mojo::NullRemote()); - // Send a message on the pipe and wait for the response to make sure - // that the interface request was bound successfully. - serial_port.FlushForTesting(); - EXPECT_TRUE(serial_port.is_connected()); - } loop.Quit(); })); loop.Run(); @@ -225,17 +196,22 @@ loop.Run(); } -TEST_F(SerialPortManagerImplTest, GetUnknownPort) { +TEST_F(SerialPortManagerImplTest, OpenUnknownPort) { mojo::Remote<mojom::SerialPortManager> port_manager; Bind(port_manager.BindNewPipeAndPassReceiver()); - mojo::Remote<mojom::SerialPort> serial_port; - port_manager->GetPort(base::UnguessableToken::Create(), - /*use_alternate_path=*/false, - serial_port.BindNewPipeAndPassReceiver(), - /*watcher=*/mojo::NullRemote()); - serial_port.FlushForTesting(); - EXPECT_FALSE(serial_port.is_connected()); + base::RunLoop loop; + port_manager->OpenPort( + base::UnguessableToken::Create(), + /*use_alternate_path=*/false, mojom::SerialConnectionOptions::New(), + FakeSerialPortClient::Create(), + /*watcher=*/mojo::NullRemote(), + base::BindLambdaForTesting( + [&](mojo::PendingRemote<mojom::SerialPort> pending_remote) { + EXPECT_FALSE(pending_remote.is_valid()); + loop.Quit(); + })); + loop.Run(); } TEST_F(SerialPortManagerImplTest, PortRemovedAndAdded) { @@ -288,31 +264,7 @@ } } -TEST_F(SerialPortManagerImplTest, GetPort) { - SetupBluetoothEnumerator(); - mojo::Remote<mojom::SerialPortManager> port_manager; - Bind(port_manager.BindNewPipeAndPassReceiver()); - - base::RunLoop loop; - port_manager->GetDevices(base::BindLambdaForTesting( - [&](std::vector<mojom::SerialPortInfoPtr> results) { - EXPECT_GT(results.size(), 0u); - - mojo::Remote<mojom::SerialPort> serial_port; - port_manager->GetPort(results[0]->token, - /*use_alternate_path=*/false, - serial_port.BindNewPipeAndPassReceiver(), - /*watcher=*/mojo::NullRemote()); - // Send a message on the pipe and wait for the response to make sure - // that the interface request was bound successfully. - serial_port.FlushForTesting(); - EXPECT_TRUE(serial_port.is_connected()); - loop.Quit(); - })); - loop.Run(); -} - -TEST_F(SerialPortManagerImplTest, GetBluetoothDevicePort) { +TEST_F(SerialPortManagerImplTest, OpenBluetoothDevicePort) { SetupBluetoothEnumeratorWithExpectations(); mojo::Remote<mojom::SerialPortManager> port_manager; Bind(port_manager.BindNewPipeAndPassReceiver()); @@ -321,11 +273,6 @@ mojo::MakeSelfOwnedReceiver( std::make_unique<mojom::SerialPortConnectionWatcher>(), watcher_remote.InitWithNewPipeAndPassReceiver()); - auto options = mojom::SerialConnectionOptions::New(); - mojo::PendingRemote<mojom::SerialPortClient> client; - FakeSerialPortClient serial_client; - serial_client.Bind(client.InitWithNewPipeAndPassReceiver()); - mojo::Remote<mojom::SerialPort> serial_port; // Since we only want to use devices enumerated by the Bluetooth // enumerator, we can remove the devices that are not. @@ -335,6 +282,7 @@ const std::set<base::FilePath> expected_paths = { base::FilePath::FromUTF8Unsafe(kDeviceAddress)}; + mojo::Remote<mojom::SerialPort> serial_port; base::RunLoop loop; port_manager->GetDevices(base::BindLambdaForTesting( [&](std::vector<mojom::SerialPortInfoPtr> results) { @@ -344,15 +292,16 @@ actual_paths.insert(results[i]->path); EXPECT_EQ(expected_paths, actual_paths); - port_manager->GetPort(results[0]->token, - /*use_alternate_path=*/false, - serial_port.BindNewPipeAndPassReceiver(), - /*watcher=*/std::move(watcher_remote)); - serial_port->Open(std::move(options), std::move(client), - base::BindLambdaForTesting([&loop](bool success) { - EXPECT_TRUE(success); - loop.Quit(); - })); + port_manager->OpenPort( + results[0]->token, + /*use_alternate_path=*/false, mojom::SerialConnectionOptions::New(), + FakeSerialPortClient::Create(), std::move(watcher_remote), + base::BindLambdaForTesting( + [&](mojo::PendingRemote<mojom::SerialPort> pending_remote) { + serial_port.Bind(std::move(pending_remote)); + EXPECT_TRUE(serial_port.is_connected()); + loop.Quit(); + })); })); loop.Run();
diff --git a/services/device/time_zone_monitor/time_zone_monitor_fuchsia.cc b/services/device/time_zone_monitor/time_zone_monitor_fuchsia.cc index fb508ea..6c99389 100644 --- a/services/device/time_zone_monitor/time_zone_monitor_fuchsia.cc +++ b/services/device/time_zone_monitor/time_zone_monitor_fuchsia.cc
@@ -48,7 +48,7 @@ UpdateIcuAndNotifyClients(std::move(new_zone)); } - base::fuchsia::IntlProfileWatcher watcher_; + base::FuchsiaIntlProfileWatcher watcher_; }; } // namespace
diff --git a/services/network/net_log_exporter.cc b/services/network/net_log_exporter.cc index d5694be..32ffd1a 100644 --- a/services/network/net_log_exporter.cc +++ b/services/network/net_log_exporter.cc
@@ -90,8 +90,8 @@ return; } - base::Value net_info = net::GetNetInfo( - network_context_->url_request_context(), net::NET_INFO_ALL_SOURCES); + base::Value net_info = + net::GetNetInfo(network_context_->url_request_context()); if (polled_data) net_info.MergeDictionary(polled_data); @@ -185,12 +185,12 @@ if (max_file_size != kUnlimitedFileSize) { file_net_observer_ = net::FileNetLogObserver::CreateBoundedPreExisting( - scratch_dir_path, std::move(destination_), max_file_size, + scratch_dir_path, std::move(destination_), max_file_size, capture_mode, std::move(constants)); } else { DCHECK(scratch_dir_path.empty()); file_net_observer_ = net::FileNetLogObserver::CreateUnboundedPreExisting( - std::move(destination_), std::move(constants)); + std::move(destination_), capture_mode, std::move(constants)); } // There might not be a NetworkService object e.g. on iOS; in that case @@ -206,7 +206,7 @@ } file_net_observer_->StartObserving( - network_context_->url_request_context()->net_log(), capture_mode); + network_context_->url_request_context()->net_log()); std::move(callback).Run(net::OK); }
diff --git a/services/network/network_service.cc b/services/network/network_service.cc index da36edb..a4a2209c 100644 --- a/services/network/network_service.cc +++ b/services/network/network_service.cc
@@ -482,8 +482,8 @@ constants->MergeDictionary(&client_constants); file_net_log_observer_ = net::FileNetLogObserver::CreateUnboundedPreExisting( - std::move(file), std::move(constants)); - file_net_log_observer_->StartObserving(net_log_, capture_mode); + std::move(file), capture_mode, std::move(constants)); + file_net_log_observer_->StartObserving(net_log_); } void NetworkService::AttachNetLogProxy(
diff --git a/services/tracing/perfetto/privacy_filtered_fields-inl.h b/services/tracing/perfetto/privacy_filtered_fields-inl.h index cea7bd7..a7bcc238 100644 --- a/services/tracing/perfetto/privacy_filtered_fields-inl.h +++ b/services/tracing/perfetto/privacy_filtered_fields-inl.h
@@ -170,10 +170,15 @@ constexpr int kChromeMessagePumpIndices[] = {1, -1}; constexpr MessageInfo kChromeMessagePump = {kChromeMessagePumpIndices, nullptr}; +// Proto Message: ChromeMojoEventInfo +constexpr int kChromeMojoEventInfoIndices[] = {1, -1}; +constexpr MessageInfo kChromeMojoEventInfo = {kChromeMojoEventInfoIndices, + nullptr}; + // Proto Message: TrackEvent -constexpr int kTrackEventIndices[] = {1, 2, 3, 5, 6, 9, 10, 11, - 12, 16, 17, 24, 25, 26, 27, 28, - 29, 30, 31, 32, 33, 34, 35, -1}; +constexpr int kTrackEventIndices[] = {1, 2, 3, 5, 6, 9, 10, 11, 12, + 16, 17, 24, 25, 26, 27, 28, 29, 30, + 31, 32, 33, 34, 35, 38, -1}; constexpr MessageInfo const* kTrackEventComplexMessages[] = { nullptr, nullptr, @@ -197,7 +202,8 @@ &kChromeFrameReporter, &kSourceLocation, nullptr, - &kChromeMessagePump}; + &kChromeMessagePump, + &kChromeMojoEventInfo}; constexpr MessageInfo kTrackEvent = {kTrackEventIndices, kTrackEventComplexMessages};
diff --git a/skia/config/SkUserConfig.h b/skia/config/SkUserConfig.h index cd937a008..9d61d12 100644 --- a/skia/config/SkUserConfig.h +++ b/skia/config/SkUserConfig.h
@@ -212,12 +212,6 @@ #define SK_DISABLE_REDUCE_OPLIST_SPLITTING #endif -// Many layout tests and unit tests need to updated/rebased to move to less -// buggy GPU blur. -#ifndef SK_USE_LEGACY_GPU_BLUR -#define SK_USE_LEGACY_GPU_BLUR -#endif - // Max. verb count for paths rendered by the edge-AA tessellating path renderer. #define GR_AA_TESSELLATOR_MAX_VERB_COUNT 100
diff --git a/testing/buildbot/chromium.mac.json b/testing/buildbot/chromium.mac.json index 7b80fb4..5ffd4d9 100644 --- a/testing/buildbot/chromium.mac.json +++ b/testing/buildbot/chromium.mac.json
@@ -6560,6 +6560,9 @@ "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, + "precommit_args": [ + "--gtest_filter=-*" + ], "swarming": { "can_use_on_swarming_builders": true, "dimension_sets": [
diff --git a/testing/buildbot/test_suite_exceptions.pyl b/testing/buildbot/test_suite_exceptions.pyl index 90c3003..9ce1a40c 100644 --- a/testing/buildbot/test_suite_exceptions.pyl +++ b/testing/buildbot/test_suite_exceptions.pyl
@@ -2515,6 +2515,12 @@ 'shards': 6, }, }, + # TODO(crbug.com/1131588) Tests are flaky only on CQ. + 'Mac10.13 Tests': { + 'precommit_args': [ + '--gtest_filter=-*', + ], + }, 'ToTLinuxTSan': { 'swarming': { 'shards': 6,
diff --git a/testing/scripts/representative_perf_test_data/representatives_frame_times_upper_limit.json b/testing/scripts/representative_perf_test_data/representatives_frame_times_upper_limit.json index 1c35fe4..ad6e2167 100644 --- a/testing/scripts/representative_perf_test_data/representatives_frame_times_upper_limit.json +++ b/testing/scripts/representative_perf_test_data/representatives_frame_times_upper_limit.json
@@ -33,7 +33,9 @@ "aquarium_20k": { "ci_095": 45.797, "avg": 139.949, - "cpu_wall_time_ratio": 0.455 + "cpu_wall_time_ratio": 0.455, + "experimental": true, + "_comment": "crbug.com/1134251" }, "balls_css_transition_2_properties": { "ci_095": 7.166,
diff --git a/third_party/blink/public/common/privacy_budget/identifiable_surface.h b/third_party/blink/public/common/privacy_budget/identifiable_surface.h index f066592..1bb0f368 100644 --- a/third_party/blink/public/common/privacy_budget/identifiable_surface.h +++ b/third_party/blink/public/common/privacy_budget/identifiable_surface.h
@@ -171,7 +171,7 @@ // FontSelectionRequest (i.e. weight, width and slope). kLocalFontLookupByFallbackCharacter = 13, - // Represents loading a font locally as a last resort. Input is the + // Represents looking up a font locally as a last resort. Input is the // FontSelectionRequest (i.e. weight, width and slope). kLocalFontLookupAsLastResort = 14, @@ -201,6 +201,9 @@ // the hint parameter. kNavigatorUAData_GetHighEntropyValues = 24, + // Represents loading a font locally. Input is the PostScript name. + kLocalFontLoadPostScriptName = 29, + // We can use values up to and including |kMax|. kMax = (1 << kTypeBits) - 1 };
diff --git a/third_party/blink/public/mojom/serial/serial.mojom b/third_party/blink/public/mojom/serial/serial.mojom index daccaaf9..912fd44 100644 --- a/third_party/blink/public/mojom/serial/serial.mojom +++ b/third_party/blink/public/mojom/serial/serial.mojom
@@ -39,10 +39,12 @@ // Requests permission to access a port. RequestPort(array<SerialPortFilter> filters) => (SerialPortInfo? port); - // Connects an instance of the SerialPort interface attached to the serial - // port identified by |token|. - GetPort(mojo_base.mojom.UnguessableToken token, - pending_receiver<device.mojom.SerialPort> port_receiver); + // Opens the port represented by |token| using |options| and returns a + // connection to it in |port|. + OpenPort(mojo_base.mojom.UnguessableToken token, + device.mojom.SerialConnectionOptions options, + pending_remote<device.mojom.SerialPortClient> client) + => (pending_remote<device.mojom.SerialPort>? port); }; // Client interface for receiving events from SerialService.
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 3259e61..7cbeab18 100644 --- a/third_party/blink/public/mojom/web_feature/web_feature.mojom +++ b/third_party/blink/public/mojom/web_feature/web_feature.mojom
@@ -2728,9 +2728,9 @@ kMediaRecorder_MimeType = 3399, kMediaRecorder_VideoBitsPerSecond = 3400, kMediaRecorder_AudioBitsPerSecond = 3401, - kBluetoothRemoteGATTCharacteristic_Uuid = 3402, - kBluetoothRemoteGATTDescriptor_Uuid = 3403, - kBluetoothRemoteGATTService_Uuid = 3404, + kOBSOLETE_BluetoothRemoteGATTCharacteristic_Uuid = 3402, + kOBSOLETE_BluetoothRemoteGATTDescriptor_Uuid = 3403, + kOBSOLETE_BluetoothRemoteGATTService_Uuid = 3404, kGPUAdapter_Name = 3405, kWindowScreenInternal = 3406, kWindowScreenPrimary = 3407,
diff --git a/third_party/blink/public/platform/media/webmediaplayer_delegate.h b/third_party/blink/public/platform/media/webmediaplayer_delegate.h index 39528c8..f48f9a3f 100644 --- a/third_party/blink/public/platform/media/webmediaplayer_delegate.h +++ b/third_party/blink/public/platform/media/webmediaplayer_delegate.h
@@ -142,6 +142,9 @@ // Notify that a buffer underflow event happened for the media player. virtual void DidBufferUnderflow(int player_id) = 0; + // Notify that a playback seek event happened for the media player. + virtual void DidSeek(int player_id) = 0; + // Notify that playback is stopped. This will drop wake locks and remove any // external controls. //
diff --git a/third_party/blink/public/strings/translations/blink_strings_kk.xtb b/third_party/blink/public/strings/translations/blink_strings_kk.xtb index 9058914..f39a8d8 100644 --- a/third_party/blink/public/strings/translations/blink_strings_kk.xtb +++ b/third_party/blink/public/strings/translations/blink_strings_kk.xtb
@@ -228,7 +228,7 @@ <translation id="7673697353781729403">Сағаттар</translation> <translation id="7681220483256441252">индекс</translation> <translation id="7740050170769002709">HTML мазмұны</translation> -<translation id="7745230546936012372">Жеткіліксіз сурет сипаттамаларын алу үшін мәнмәтіндік мәзірді ашыңыз.</translation> +<translation id="7745230546936012372">Жеткіліксіз сурет сипаттамаларын алу үшін контекстік мәзірді ашыңыз.</translation> <translation id="7750228210027921155">Суреттегі сурет</translation> <translation id="775297008183122718">Жазба жарамсыз.</translation> <translation id="7789962463072032349">кідірту</translation>
diff --git a/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_characteristic.idl b/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_characteristic.idl index edb467dc..da8d2fa 100644 --- a/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_characteristic.idl +++ b/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_characteristic.idl
@@ -11,7 +11,7 @@ SecureContext ] interface BluetoothRemoteGATTCharacteristic : EventTarget { [SameObject] readonly attribute BluetoothRemoteGATTService service; - [HighEntropy=Direct, MeasureAs=BluetoothRemoteGATTCharacteristic_Uuid] readonly attribute UUID uuid; + readonly attribute UUID uuid; readonly attribute BluetoothCharacteristicProperties properties; readonly attribute DataView? value; [RaisesException, CallWith=ScriptState, MeasureAs=WebBluetoothRemoteCharacteristicGetDescriptor] Promise<BluetoothRemoteGATTDescriptor> getDescriptor(BluetoothDescriptorUUID descriptor);
diff --git a/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_descriptor.idl b/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_descriptor.idl index f6ad62c..8d5faa4 100644 --- a/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_descriptor.idl +++ b/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_descriptor.idl
@@ -12,7 +12,7 @@ SecureContext ] interface BluetoothRemoteGATTDescriptor { [SameObject] readonly attribute BluetoothRemoteGATTCharacteristic characteristic; - [HighEntropy=Direct, MeasureAs=BluetoothRemoteGATTDescriptor_Uuid] readonly attribute UUID uuid; + readonly attribute UUID uuid; readonly attribute DataView? value; [CallWith=ScriptState, RaisesException, MeasureAs=WebBluetoothRemoteDescriptorReadValue] Promise<DataView> readValue(); [CallWith=ScriptState, RaisesException, MeasureAs=WebBluetoothRemoteDescriptorWriteValue] Promise<void> writeValue(BufferSource value);
diff --git a/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_service.idl b/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_service.idl index 1cddb9a..62de0fa 100644 --- a/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_service.idl +++ b/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_service.idl
@@ -10,7 +10,7 @@ SecureContext ] interface BluetoothRemoteGATTService { [SameObject] readonly attribute BluetoothDevice device; - [HighEntropy=Direct, MeasureAs=BluetoothRemoteGATTService_Uuid] readonly attribute UUID uuid; + readonly attribute UUID uuid; readonly attribute boolean isPrimary; [RaisesException, CallWith=ScriptState, MeasureAs=WebBluetoothRemoteServiceGetCharacteristic] Promise<BluetoothRemoteGATTCharacteristic> getCharacteristic(BluetoothCharacteristicUUID characteristic); [RaisesException, CallWith=ScriptState, MeasureAs=WebBluetoothRemoteServiceGetCharacteristics] Promise<sequence<BluetoothRemoteGATTCharacteristic>> getCharacteristics(optional BluetoothCharacteristicUUID characteristic);
diff --git a/third_party/blink/renderer/modules/mediastream/webmediaplayer_ms_test.cc b/third_party/blink/renderer/modules/mediastream/webmediaplayer_ms_test.cc index 3dedcae..c3550ee 100644 --- a/third_party/blink/renderer/modules/mediastream/webmediaplayer_ms_test.cc +++ b/third_party/blink/renderer/modules/mediastream/webmediaplayer_ms_test.cc
@@ -134,6 +134,10 @@ EXPECT_EQ(delegate_id_, delegate_id); } + void DidSeek(int delegate_id) override { + EXPECT_EQ(delegate_id_, delegate_id); + } + void PlayerGone(int delegate_id) override { EXPECT_EQ(delegate_id_, delegate_id); is_gone_ = true;
diff --git a/third_party/blink/renderer/modules/serial/serial.cc b/third_party/blink/renderer/modules/serial/serial.cc index e8c393e..957d0f988 100644 --- a/third_party/blink/renderer/modules/serial/serial.cc +++ b/third_party/blink/renderer/modules/serial/serial.cc
@@ -157,11 +157,14 @@ return resolver->Promise(); } -void Serial::GetPort( +void Serial::OpenPort( const base::UnguessableToken& token, - mojo::PendingReceiver<device::mojom::blink::SerialPort> receiver) { + device::mojom::blink::SerialConnectionOptionsPtr options, + mojo::PendingRemote<device::mojom::blink::SerialPortClient> client, + mojom::blink::SerialService::OpenPortCallback callback) { EnsureServiceConnection(); - service_->GetPort(token, std::move(receiver)); + service_->OpenPort(token, std::move(options), std::move(client), + std::move(callback)); } void Serial::Trace(Visitor* visitor) const {
diff --git a/third_party/blink/renderer/modules/serial/serial.h b/third_party/blink/renderer/modules/serial/serial.h index 3728a1d..ea0032d 100644 --- a/third_party/blink/renderer/modules/serial/serial.h +++ b/third_party/blink/renderer/modules/serial/serial.h
@@ -52,9 +52,11 @@ const SerialPortRequestOptions*, ExceptionState&); - void GetPort( + void OpenPort( const base::UnguessableToken& token, - mojo::PendingReceiver<device::mojom::blink::SerialPort> receiver); + device::mojom::blink::SerialConnectionOptionsPtr options, + mojo::PendingRemote<device::mojom::blink::SerialPortClient> client, + mojom::blink::SerialService::OpenPortCallback callback); void Trace(Visitor*) const override; protected:
diff --git a/third_party/blink/renderer/modules/serial/serial_port.cc b/third_party/blink/renderer/modules/serial/serial_port.cc index 989104ef..3f4286a8 100644 --- a/third_party/blink/renderer/modules/serial/serial_port.cc +++ b/third_party/blink/renderer/modules/serial/serial_port.cc
@@ -259,18 +259,13 @@ mojo_options->cts_flow_control = options->flowControl() == "hardware"; mojo::PendingRemote<device::mojom::blink::SerialPortClient> client; - parent_->GetPort( - info_->token, - port_.BindNewPipeAndPassReceiver( - GetExecutionContext()->GetTaskRunner(TaskType::kMiscPlatformAPI))); - port_.set_disconnect_handler( - WTF::Bind(&SerialPort::OnConnectionError, WrapWeakPersistent(this))); - open_resolver_ = MakeGarbageCollected<ScriptPromiseResolver>(script_state); auto callback = WTF::Bind(&SerialPort::OnOpen, WrapPersistent(this), client.InitWithNewPipeAndPassReceiver()); - port_->Open(std::move(mojo_options), std::move(client), std::move(callback)); + parent_->OpenPort(info_->token, std::move(mojo_options), std::move(client), + std::move(callback)); + return open_resolver_->Promise(); } @@ -579,12 +574,12 @@ void SerialPort::OnOpen( mojo::PendingReceiver<device::mojom::blink::SerialPortClient> client_receiver, - bool success) { + mojo::PendingRemote<device::mojom::blink::SerialPort> port) { ScriptState* script_state = open_resolver_->GetScriptState(); if (!script_state->ContextIsValid()) return; - if (!success) { + if (!port) { ScriptPromiseResolver* resolver = open_resolver_; open_resolver_ = nullptr; resolver->Reject(MakeGarbageCollected<DOMException>( @@ -592,9 +587,14 @@ return; } + port_.Bind(std::move(port), + GetExecutionContext()->GetTaskRunner(TaskType::kMiscPlatformAPI)); + port_.set_disconnect_handler( + WTF::Bind(&SerialPort::OnConnectionError, WrapWeakPersistent(this))); client_receiver_.Bind( std::move(client_receiver), GetExecutionContext()->GetTaskRunner(TaskType::kMiscPlatformAPI)); + open_resolver_->Resolve(); open_resolver_ = nullptr; }
diff --git a/third_party/blink/renderer/modules/serial/serial_port.h b/third_party/blink/renderer/modules/serial/serial_port.h index fbc45be..1d1e00bd 100644 --- a/third_party/blink/renderer/modules/serial/serial_port.h +++ b/third_party/blink/renderer/modules/serial/serial_port.h
@@ -83,7 +83,7 @@ mojo::ScopedDataPipeConsumerHandle* consumer); void OnConnectionError(); void OnOpen(mojo::PendingReceiver<device::mojom::blink::SerialPortClient>, - bool success); + mojo::PendingRemote<device::mojom::blink::SerialPort>); void OnGetSignals(ScriptPromiseResolver*, device::mojom::blink::SerialPortControlSignalsPtr); void OnSetSignals(ScriptPromiseResolver*, bool success);
diff --git a/third_party/blink/renderer/platform/fonts/font_global_context.cc b/third_party/blink/renderer/platform/fonts/font_global_context.cc index 3e80b587..05d13203 100644 --- a/third_party/blink/renderer/platform/fonts/font_global_context.cc +++ b/third_party/blink/renderer/platform/fonts/font_global_context.cc
@@ -7,12 +7,13 @@ #include "third_party/blink/renderer/platform/fonts/font_cache.h" #include "third_party/blink/renderer/platform/fonts/font_unique_name_lookup.h" #include "third_party/blink/renderer/platform/fonts/shaping/harfbuzz_font_cache.h" +#include "third_party/blink/renderer/platform/privacy_budget/identifiability_digest_helpers.h" #include "third_party/blink/renderer/platform/wtf/thread_specific.h" -// While the size of this cache should usually be small (up to tens), we protect -// against the possibility of it growing quickly to thousands when animating -// variable font parameters. -static constexpr size_t kTypefaceDigestCacheMaxSize = 250; +// While the size of these caches should usually be small (up to tens), we +// protect against the possibility of it growing quickly to thousands when +// animating variable font parameters. +static constexpr size_t kCachesMaxSize = 250; namespace blink { @@ -28,7 +29,8 @@ FontGlobalContext::FontGlobalContext() : harfbuzz_font_funcs_skia_advances_(nullptr), harfbuzz_font_funcs_harfbuzz_advances_(nullptr), - typeface_digest_cache_(kTypefaceDigestCacheMaxSize) {} + typeface_digest_cache_(kCachesMaxSize), + postscript_name_digest_cache_(kCachesMaxSize) {} FontGlobalContext::~FontGlobalContext() = default; @@ -67,12 +69,33 @@ return *cached_value; } +IdentifiableToken FontGlobalContext::GetOrComputePostScriptNameDigest( + const FontPlatformData& source) { + SkTypeface* typeface = source.Typeface(); + if (!typeface) + return IdentifiableToken(); + + SkFontID font_id = typeface->uniqueID(); + + IdentifiableToken* cached_value = postscript_name_digest_cache_.Get(font_id); + if (!cached_value) { + postscript_name_digest_cache_.Put( + font_id, IdentifiabilityBenignStringToken(source.GetPostScriptName())); + cached_value = postscript_name_digest_cache_.Get(font_id); + } else { + DCHECK(*cached_value == + IdentifiabilityBenignStringToken(source.GetPostScriptName())); + } + return *cached_value; +} + void FontGlobalContext::ClearMemory() { if (!Get(kDoNotCreate)) return; GetFontCache().Invalidate(); Get()->typeface_digest_cache_.Clear(); + Get()->postscript_name_digest_cache_.Clear(); } } // namespace blink
diff --git a/third_party/blink/renderer/platform/fonts/font_global_context.h b/third_party/blink/renderer/platform/fonts/font_global_context.h index 11f9697..e2c8361 100644 --- a/third_party/blink/renderer/platform/fonts/font_global_context.h +++ b/third_party/blink/renderer/platform/fonts/font_global_context.h
@@ -59,6 +59,8 @@ static FontUniqueNameLookup* GetFontUniqueNameLookup(); IdentifiableToken GetOrComputeTypefaceDigest(const FontPlatformData& source); + IdentifiableToken GetOrComputePostScriptNameDigest( + const FontPlatformData& source); // Called by MemoryPressureListenerRegistry to clear memory. static void ClearMemory(); @@ -75,6 +77,7 @@ hb_font_funcs_t* harfbuzz_font_funcs_harfbuzz_advances_; std::unique_ptr<FontUniqueNameLookup> font_unique_name_lookup_; WTF::LruCache<SkFontID, IdentifiableToken> typeface_digest_cache_; + WTF::LruCache<SkFontID, IdentifiableToken> postscript_name_digest_cache_; DISALLOW_COPY_AND_ASSIGN(FontGlobalContext); };
diff --git a/third_party/blink/renderer/platform/fonts/font_matching_metrics.cc b/third_party/blink/renderer/platform/fonts/font_matching_metrics.cc index 63ef79a..f70006b 100644 --- a/third_party/blink/renderer/platform/fonts/font_matching_metrics.cc +++ b/third_party/blink/renderer/platform/fonts/font_matching_metrics.cc
@@ -109,6 +109,12 @@ return; IdentifiableToken output_token(GetHashForFontData(font_data)); hash_map.insert(input_key, output_token); + + if (!font_data) + return; + IdentifiableTokenKey postscript_name_key( + GetPostScriptNameTokenForFontData(font_data)); + font_load_postscript_name_.insert(postscript_name_key, output_token); } IdentifiableTokenBuilder @@ -245,6 +251,8 @@ IdentifiableSurface::Type::kLocalFontLookupAsLastResort}, {&generic_font_lookups_, IdentifiableSurface::Type::kGenericFontLookup}, + {&font_load_postscript_name_, + IdentifiableSurface::Type::kLocalFontLoadPostScriptName}, }; for (const auto& surface_entry : hash_maps_with_corresponding_surface_types) { @@ -310,4 +318,11 @@ : 0; } +IdentifiableToken FontMatchingMetrics::GetPostScriptNameTokenForFontData( + SimpleFontData* font_data) { + DCHECK(font_data); + return FontGlobalContext::Get()->GetOrComputePostScriptNameDigest( + font_data->PlatformData()); +} + } // namespace blink
diff --git a/third_party/blink/renderer/platform/fonts/font_matching_metrics.h b/third_party/blink/renderer/platform/fonts/font_matching_metrics.h index 175d193f..17d136c 100644 --- a/third_party/blink/renderer/platform/fonts/font_matching_metrics.h +++ b/third_party/blink/renderer/platform/fonts/font_matching_metrics.h
@@ -193,7 +193,9 @@ IdentifiableTokenKeyHashTraits>; // Adds a digest of the |font_data|'s typeface to |hash_map| using the key - // |input_key|, unless that key is already present. + // |input_key|, unless that key is already present. If |font_data| is not + // nullptr, then the typeface digest will also be saved with its PostScript + // name in |font_load_postscript_name_|. void InsertFontHashIntoMap(IdentifiableTokenKey input_key, SimpleFontData* font_data, TokenToTokenHashMap hash_map); @@ -208,6 +210,11 @@ void Initialize(); + // Get a token that uniquely represents the typeface's PostScript name. May + // represent the empty string if no PostScript name was found. + IdentifiableToken GetPostScriptNameTokenForFontData( + SimpleFontData* font_data); + // Font family names successfully matched. HashSet<AtomicString> successful_font_families_; @@ -235,6 +242,7 @@ TokenToTokenHashMap font_lookups_by_fallback_character_; TokenToTokenHashMap font_lookups_as_last_resort_; TokenToTokenHashMap generic_font_lookups_; + TokenToTokenHashMap font_load_postscript_name_; ukm::UkmRecorder* const ukm_recorder_; const ukm::SourceId source_id_;
diff --git a/third_party/blink/renderer/platform/fonts/font_platform_data.cc b/third_party/blink/renderer/platform/fonts/font_platform_data.cc index fc5e804c..f96cee1 100644 --- a/third_party/blink/renderer/platform/fonts/font_platform_data.cc +++ b/third_party/blink/renderer/platform/fonts/font_platform_data.cc
@@ -338,4 +338,13 @@ return builder.GetToken(); // hasher.GetHash(); } +String FontPlatformData::GetPostScriptName() const { + if (!typeface_) + return String(); + + SkString postscript_name; + bool success = typeface_->getPostScriptName(&postscript_name); + return success ? postscript_name.c_str() : String(); +} + } // namespace blink
diff --git a/third_party/blink/renderer/platform/fonts/font_platform_data.h b/third_party/blink/renderer/platform/fonts/font_platform_data.h index c5836d9..b10ff2e8b 100644 --- a/third_party/blink/renderer/platform/fonts/font_platform_data.h +++ b/third_party/blink/renderer/platform/fonts/font_platform_data.h
@@ -145,6 +145,9 @@ // the fingerprinting algorithm. IdentifiableToken ComputeTypefaceDigest() const; + // Gets the postscript name from the typeface. + String GetPostScriptName() const; + private: #if !defined(OS_WIN) && !defined(OS_MAC) WebFontRenderStyle QuerySystemRenderStyle(const std::string& family,
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 9968714..9a32c5b7 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -2567,6 +2567,8 @@ crbug.com/958381 [ Mac ] external/wpt/css/CSS2/tables/table-anonymous-objects-206.xht [ Failure ] # ====== New tests from wpt-importer added here ====== +crbug.com/626703 external/wpt/infrastructure/testdriver/actions/iframe.html [ Timeout ] +crbug.com/626703 external/wpt/infrastructure/testdriver/actions/crossOrigin.sub.html [ Timeout ] crbug.com/626703 external/wpt/css/css-color/predefined-008.html [ Failure ] crbug.com/626703 virtual/system-color-compute/external/wpt/css/css-color/predefined-010.html [ Failure ] crbug.com/626703 external/wpt/css/css-color/predefined-015.html [ Failure ]
diff --git a/third_party/blink/web_tests/compositing/culling/filter-occlusion-blur-large-expected.png b/third_party/blink/web_tests/compositing/culling/filter-occlusion-blur-large-expected.png index 5338936..80db4c7 100644 --- a/third_party/blink/web_tests/compositing/culling/filter-occlusion-blur-large-expected.png +++ b/third_party/blink/web_tests/compositing/culling/filter-occlusion-blur-large-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/css3/filters/backdrop-filter-basic-blur-expected.png b/third_party/blink/web_tests/css3/filters/backdrop-filter-basic-blur-expected.png deleted file mode 100644 index cb19a6e9..0000000 --- a/third_party/blink/web_tests/css3/filters/backdrop-filter-basic-blur-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/css3/filters/backdrop-filter-edge-clipping-2-expected.png b/third_party/blink/web_tests/css3/filters/backdrop-filter-edge-clipping-2-expected.png index 7a94de0..767306a 100644 --- a/third_party/blink/web_tests/css3/filters/backdrop-filter-edge-clipping-2-expected.png +++ b/third_party/blink/web_tests/css3/filters/backdrop-filter-edge-clipping-2-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/css3/filters/backdrop-filter-edge-pixels-expected.png b/third_party/blink/web_tests/css3/filters/backdrop-filter-edge-pixels-expected.png index f8bda03..7247e04 100644 --- a/third_party/blink/web_tests/css3/filters/backdrop-filter-edge-pixels-expected.png +++ b/third_party/blink/web_tests/css3/filters/backdrop-filter-edge-pixels-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/css3/filters/effect-all-on-background-hw-expected.png b/third_party/blink/web_tests/css3/filters/effect-all-on-background-hw-expected.png index 096a98f..d5546d38 100644 --- a/third_party/blink/web_tests/css3/filters/effect-all-on-background-hw-expected.png +++ b/third_party/blink/web_tests/css3/filters/effect-all-on-background-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/css3/filters/effect-blur-hw-expected.png b/third_party/blink/web_tests/css3/filters/effect-blur-hw-expected.png index 94574ae..f292fdd7 100644 --- a/third_party/blink/web_tests/css3/filters/effect-blur-hw-expected.png +++ b/third_party/blink/web_tests/css3/filters/effect-blur-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/css3/filters/effect-reference-hidpi-hw-expected.png b/third_party/blink/web_tests/css3/filters/effect-reference-hidpi-hw-expected.png index 08bad9d..10c080f 100644 --- a/third_party/blink/web_tests/css3/filters/effect-reference-hidpi-hw-expected.png +++ b/third_party/blink/web_tests/css3/filters/effect-reference-hidpi-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/css3/filters/effect-reference-ordering-hw-expected.png b/third_party/blink/web_tests/css3/filters/effect-reference-ordering-hw-expected.png index 7b1bf753..fbd99c9 100644 --- a/third_party/blink/web_tests/css3/filters/effect-reference-ordering-hw-expected.png +++ b/third_party/blink/web_tests/css3/filters/effect-reference-ordering-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/css3/filters/effect-reference-zoom-hw-expected.png b/third_party/blink/web_tests/css3/filters/effect-reference-zoom-hw-expected.png deleted file mode 100644 index 7e4d4423..0000000 --- a/third_party/blink/web_tests/css3/filters/effect-reference-zoom-hw-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/css3/filters/filter-change-repaint-composited-expected.png b/third_party/blink/web_tests/css3/filters/filter-change-repaint-composited-expected.png index 2dcaceb..515d4d7 100644 --- a/third_party/blink/web_tests/css3/filters/filter-change-repaint-composited-expected.png +++ b/third_party/blink/web_tests/css3/filters/filter-change-repaint-composited-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/css3/filters/filter-change-repaint-expected.png b/third_party/blink/web_tests/css3/filters/filter-change-repaint-expected.png index c1910585..2681919 100644 --- a/third_party/blink/web_tests/css3/filters/filter-change-repaint-expected.png +++ b/third_party/blink/web_tests/css3/filters/filter-change-repaint-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/css3/filters/filter-repaint-composited-fallback-crash-expected.png b/third_party/blink/web_tests/css3/filters/filter-repaint-composited-fallback-crash-expected.png index 85fde79..e7165f5 100644 --- a/third_party/blink/web_tests/css3/filters/filter-repaint-composited-fallback-crash-expected.png +++ b/third_party/blink/web_tests/css3/filters/filter-repaint-composited-fallback-crash-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/css3/filters/filter-repaint-composited-fallback-expected.png b/third_party/blink/web_tests/css3/filters/filter-repaint-composited-fallback-expected.png index 85fde79..e7165f5 100644 --- a/third_party/blink/web_tests/css3/filters/filter-repaint-composited-fallback-expected.png +++ b/third_party/blink/web_tests/css3/filters/filter-repaint-composited-fallback-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json index bd54b4d..19155fb1 100644 --- a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json +++ b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json
@@ -162331,6 +162331,19 @@ {} ] ], + "markers-orient-002.svg": [ + "f371784e2acb70fde4b6d6f0837652322900dc25", + [ + null, + [ + [ + "/svg/pservers/reftests/reference/green-100x100.svg", + "==" + ] + ], + {} + ] + ], "paint-context-001.svg": [ "fd58d9b790a512940e2d8244148a3c62fb107898", [ @@ -210020,7 +210033,7 @@ [] ], "testdriver.md": [ - "8eec38729f41b40a5e1cf073c9e8bba99c6f5efc", + "fd87f355bc3055b97aa876c82ebfe7c7ccdf1816", [] ], "testharness-api.md": [ @@ -230065,12 +230078,28 @@ "OWNERS": [ "6aa7ab767945e24c2f7ed7c144d85af33b1fd15e", [] + ], + "crossOriginChild.html": [ + "48e37e233e14f690e6464257a22f70528edf720d", + [] + ], + "iframeChild.html": [ + "a46c54a7b7b51fec65d335ad54fc8fb4ca4c2050", + [] ] }, "click_child.html": [ "5899841c4c1bcc9181f71b4b8699ded57cfe93fd", [] ], + "click_child_crossorigin.html": [ + "6a8c6840a25cb621736379677f3bb7713d6b88f6", + [] + ], + "click_child_testdriver.html": [ + "2c26a963f4a9691cbe83a7da0d2233fa5d96c3bc", + [] + ], "click_nested-expected.txt": [ "4396eb3f18a9019f35fb5f59f619c3a9fdbb955e", [] @@ -230079,6 +230108,10 @@ "ae4944635f00fb400fa8345a77bfb3b62766bc49", [] ], + "click_outer_child.sub.html": [ + "8e72223f9153d16e061482a5adf272a0e5e46112", + [] + ], "click_window-expected.txt": [ "ed125b6e9febcf10d0fe5d2e926f0576c34fc46f", [] @@ -237129,7 +237162,7 @@ [] ], "testdriver-actions.js": [ - "b6030bf121388d5f4e33fbc31f8680fb6f58344b", + "f3e6388e8acd1998d89750150e0779df327a5417", [] ], "testdriver-vendor.js": [ @@ -237141,7 +237174,7 @@ [] ], "testdriver.js": [ - "165147d1430bfe990da2c8d3d601267dbe5143af", + "c53b24136c091f05e4ffbe286d060aba0fa66cdf", [] ], "testdriver.js.headers": [ @@ -237202,6 +237235,10 @@ "c5a213156a161824a4e5c6b96257d131ffb7212c", [] ], + "sanitizer-config.tentative-expected.txt": [ + "8e126d403b820266ce1fd19ebdcddd6a7f0c3f52", + [] + ], "support": { "testcases.sub.js": [ "029d30bcf54779dae702e85ee36fe5ef3cdb5a06", @@ -242439,7 +242476,7 @@ [] ], "sink_task.py": [ - "ba76d27640c86197736d7edc9e8ed86fe8ec4bd0", + "1efcd4225cd2fb6352fe02c5f7197eb522f29292", [] ], "taskgraph.py": [ @@ -242448,7 +242485,7 @@ ], "tasks": { "test.yml": [ - "78891bf302373168f7dd806fc332a3886538802d", + "4fa69e871bc19249d138531eaa9b7ccff458c582", [] ] }, @@ -248640,7 +248677,7 @@ [] ], "base.py": [ - "0247b3feed2b00d8de7da1dbc1c0da4f3841e5bd", + "4c3891c1cb67ba0a3d92e49860741569664ec784", [] ], "executorchrome.py": [ @@ -248660,7 +248697,7 @@ [] ], "executormarionette.py": [ - "e7c9726974b31118bb1dc6027feb9f817dd37563", + "7e2cc8e38a44c06a0d6c726fc917ca36776c0861", [] ], "executoropera.py": [ @@ -248672,7 +248709,7 @@ [] ], "executorselenium.py": [ - "82ab6f25560e67ee3a3877b6ee4af8b6cc200e3a", + "ff26351f84ed8d2e00d82d76570208a5947086cc", [] ], "executorservo.py": [ @@ -248680,11 +248717,11 @@ [] ], "executorservodriver.py": [ - "dbed2fedbdf1c686dda800bf182fbfc2ee6e0dd2", + "2cd1dbf3ad06f41b9555dad64d6d0c0a86537260", [] ], "executorwebdriver.py": [ - "139c475ce44ed29608d68509a88ba1b4c4aa932c", + "bad5fd072237bce2b826dde77b413bcabbcca990", [] ], "executorwebkit.py": [ @@ -248696,7 +248733,7 @@ [] ], "protocol.py": [ - "1c85c0f8b963482e8da72e7a793830e0d49b29be", + "bd768b1073c748fdb860745f1bf9442f5b415c3b", [] ], "pytestrunner": { @@ -248807,7 +248844,7 @@ [] ], "testdriver-extra.js": [ - "241fc83395152fc9188b791e1f8e1ab9a3d3a542", + "9c0c69af3a3f278e8053b0a9907cd1dd7cae9dbc", [] ], "testdriver-vendor.js": [ @@ -248827,7 +248864,7 @@ [] ], "testharnessreport.js": [ - "29fc0e9873188223ac3783a8c622bbbe21ec5af5", + "9cd680e14aed3b6f7b8ee23aa5d2a5624cbe1fd2", [] ], "testloader.py": [ @@ -291205,6 +291242,13 @@ {} ] ], + "overflow-clip-hit-testing.html": [ + "b22497601c2af66492958703df8f46c6756724ac", + [ + null, + {} + ] + ], "overflow-codependent-scrollbars.html": [ "eb0e4f5ea2ed9a97c0931c2c53de5e62e72ba1dd", [ @@ -353678,6 +353722,15 @@ ] ] }, + "the-details-element": { + "details-blockification.html": [ + "cc94e92fe0cdfb69c6d81f9406a58dd24a96a5fa", + [ + null, + {} + ] + ] + }, "unmapped-attributes.html": [ "5824f836f0d654c116a55a252dfbda5fc6e5bbc8", [ @@ -368634,6 +368687,15 @@ } ] ], + "crossOrigin.sub.html": [ + "38b3610af655a10f580c7f1fdb4621e4354deb82", + [ + null, + { + "testdriver": true + } + ] + ], "elementPosition.html": [ "145852e7b51bd0cdc9e7b4ef5ebddcbf1c0235c5", [ @@ -368661,6 +368723,15 @@ } ] ], + "iframe.html": [ + "6c64d6f49abc14cb03c5173536bb2d38c6d16e5d", + [ + null, + { + "testdriver": true + } + ] + ], "multiDevice.html": [ "6bc0fa218d8953093e583622264bdf02b73c78bb", [ @@ -368744,7 +368815,7 @@ ] }, "bless.html": [ - "b8a1c2e7d6000050351453a14a8bfb80d8af0c76", + "12257df01b7193c2a70bde1bedaa8e1d7e1ff2f7", [ null, { @@ -368770,6 +368841,15 @@ } ] ], + "click_iframe_crossorigin.sub.html": [ + "01833dc23d4e9f2c5033dfbc052a4decbca02161", + [ + null, + { + "testdriver": true + } + ] + ], "click_nested.html": [ "378b9e8c0f1411afdf7b93f7e93c03d05af227c7", [ @@ -368779,6 +368859,15 @@ } ] ], + "click_nested_crossorigin.sub.html": [ + "af90951df17804fd4ec18b99edc7165af989401a", + [ + null, + { + "testdriver": true + } + ] + ], "click_window.html": [ "614a92478e07d51e48c420d5fa253338a87378b2", [
diff --git a/third_party/blink/web_tests/external/wpt/docs/writing-tests/testdriver.md b/third_party/blink/web_tests/external/wpt/docs/writing-tests/testdriver.md index 8eec387..fd87f355b 100644 --- a/third_party/blink/web_tests/external/wpt/docs/writing-tests/testdriver.md +++ b/third_party/blink/web_tests/external/wpt/docs/writing-tests/testdriver.md
@@ -13,9 +13,6 @@ testdriver.js exposes its API through the `test_driver` variable in the global scope. -NB: presently, testdriver.js only works in the top-level test browsing -context (and not therefore in any frame or window opened from it). - ### Actions Usage: ``` @@ -25,12 +22,17 @@ actions.send() ``` -Test authors are encouraged to use the builder API to generate the sequence of actions. The builder -API can be accessed via the `new test_driver.Actions()` object, and actions are defined in [testdriver-actions.js](https://github.com/web-platform-tests/wpt/blob/master/resources/testdriver-actions.js) +Test authors are encouraged to use the builder API to generate the +sequence of actions. The builder API can be accessed via the `new +test_driver.Actions()` object, and actions are defined in +[testdriver-actions.js](https://github.com/web-platform-tests/wpt/blob/master/resources/testdriver-actions.js) -The `actions.send()` function causes the sequence of actions to be sent to the browser. It is based on the [WebDriver API](https://w3c.github.io/webdriver/#actions). -The action can be a keyboard action, a pointer action or a pause. It returns a promise that -resolves after the actions have been sent, or rejects if an error was thrown. +The `actions.send()` function causes the sequence of actions to be +sent to the browser. It is based on the [WebDriver +API](https://w3c.github.io/webdriver/#actions). The action can be a +keyboard action, a pointer action or a pause. It returns a promise +that resolves after the actions have been sent, or rejects if an error +was thrown. Example: @@ -49,7 +51,13 @@ actions.send(); ``` -Calling into `send()` is going to dispatch the action sequence (via `test_driver.action_sequence`) and also returns a promise which should be handled however is appropriate in the test. The other functions in the `Actions()` object are going to modify the state of the object by adding a new action in the sequence and returning the same object. So the functions can be easily chained, as shown in the example above. Here is a list of helper functions in the `Actions` class: +Calling into `send()` is going to dispatch the action sequence (via +`test_driver.action_sequence`) and also returns a promise which should +be handled however is appropriate in the test. The other functions in +the `Actions()` object are going to modify the state of the object by +adding a new action in the sequence and returning the same object. So +the functions can be easily chained, as shown in the example +above. Here is a list of helper functions in the `Actions` class: ``` pointerDown: Create a pointerDown event for the current default pointer source @@ -143,7 +151,7 @@ ### set_permission -Usage: `test_driver.set_permission(descriptor, state, one_realm)` +Usage: `test_driver.set_permission(descriptor, state, one_realm, context=null)` * _descriptor_: a [PermissionDescriptor](https://w3c.github.io/permissions/#dictdef-permissiondescriptor) or derived object @@ -152,6 +160,7 @@ value * _one_realm_: a boolean that indicates whether the permission settings apply to only one realm + * context: a WindowProxy for the browsing context in which to perform the call This function causes permission requests and queries for the status of a certain permission type (e.g. "push", or "background-fetch") to always @@ -164,3 +173,63 @@ await test_driver.set_permission({ name: "background-fetch" }, "denied"); await test_driver.set_permission({ name: "push", userVisibleOnly: true }, "granted", true); ``` + +## Using testdriver in Other Browsing Contexts + +Testdriver can be used in browsing contexts (i.e. windows or frames) +from which it's possible to get a reference to the top-level test +context. There are two basic approaches depending on whether the +context in which testdriver is used is same-origin with the test +context, or different origin. + +For same-origin contexts, the context can be passed directly into the +testdriver API calls. For functions that take an element argument this +is done implicitly using the owner document of the element. For +functions that don't take an element, this is done via an explicit +context argument, which takes a WindowProxy object. + +Example: +``` +let win = window.open("example.html") +win.onload = () => { + await test_driver.set_permission({ name: "background-fetch" }, "denied", win); +} +``` + +For the actions API, the context can be set using the `setContext` +method on the builder: + +``` +let actions = new test_driver.Actions() + .setContext(frames[0]) + .keyDown("p") + .keyUp("p"); +actions.send(); +``` + +Note that if an action uses an element reference, the context will be +derived from that element, and must match any explictly set +context. Using elements in multiple contexts in a single action chain +is not supported. + + +For cross-origin cases, passing in the context id doesn't work because +of limitations in the WebDriver protocol used to implement testdriver +in a cross-browser fashion. Instead one may include the testdriver +scripts directly in the relevant document, and use the +`set_test_context` API to specify the browsing context containing +testharness.js. Commands are then sent via postMessage to the test +context. For convenience there is also a `message_test` function that +can be used to send arbitary messages to the test window. For example, +in an auxillary browsing context: + + +``` +testdriver.set_test_context(window.opener) +await testdriver.click(document.getElementsByTagName("button")[0]) +testdriver.message_test("click complete") +``` + +The requirement to have a handle to the test window does mean it's +currently not possible to write tests where such handles can't be +obtained e.g. in the case of `rel=noopener`.
diff --git a/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/actions/crossOrigin.sub.html b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/actions/crossOrigin.sub.html new file mode 100644 index 0000000..38b3610a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/actions/crossOrigin.sub.html
@@ -0,0 +1,20 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>Actions in cross-origin iframe</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/resources/testdriver.js"></script> +<script src="/resources/testdriver-vendor.js"></script> + +<iframe src="https://{{host}}:{{ports[https][1]}}/infrastructure/testdriver/actions/crossOriginChild.html"></iframe> + +<script> +setup({single_test: true}); +addEventListener("message", (msg) => { + if (msg.data === "PASS") { + done(); + } else if (msg.data === "FAIL") { + assert_unreached("actions failed") + } +}); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/actions/crossOriginChild.html b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/actions/crossOriginChild.html new file mode 100644 index 0000000..48e37e23 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/actions/crossOriginChild.html
@@ -0,0 +1,32 @@ +<!doctype html> +<script src="/resources/testdriver.js"></script> +<script src="/resources/testdriver-vendor.js"></script> +<script src="/resources/testdriver-actions.js"></script> + +<input type=text> +<script> +let input = document.getElementsByTagName("input")[0]; +addEventListener("load", async () => { + test_driver.set_test_context(parent); + await new test_driver.Actions() + .pointerMove(0, 0, {origin: input}) + .pointerDown() + .pointerUp() + .send(); + await new test_driver.Actions() + .keyDown("P") + .keyUp("P") + .keyDown("A") + .keyUp("A") + .keyDown("S") + .keyUp("S") + .keyDown("S") + .keyUp("S") + .send(); + if (input.value === "PASS") { + test_driver.message_test("PASS", "*") + } else { + test_driver.message_test("FAIL", "*") + } +}); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/actions/iframe.html b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/actions/iframe.html new file mode 100644 index 0000000..6c64d6f4 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/actions/iframe.html
@@ -0,0 +1,35 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>TestDriver actions on a document in an iframe</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/resources/testdriver.js"></script> +<script src="/resources/testdriver-vendor.js"></script> +<script src="/resources/testdriver-actions.js"></script> + +<iframe src="iframeChild.html"></iframe> + +<script> +setup({single_test: true}); +addEventListener("load", async () => { + let input = frames[0].document.getElementsByTagName("input")[0]; + await new test_driver.Actions() + .pointerMove(0, 0, {origin: input}) + .pointerDown() + .pointerUp() + .send(); + await new test_driver.Actions() + .setContext(frames[0]) + .keyDown("P") + .keyUp("P") + .keyDown("A") + .keyUp("A") + .keyDown("S") + .keyUp("S") + .keyDown("S") + .keyUp("S") + .send(); + assert_equals(input.value, "PASS"); + done(); +}); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/actions/iframeChild.html b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/actions/iframeChild.html new file mode 100644 index 0000000..a46c54a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/actions/iframeChild.html
@@ -0,0 +1,2 @@ +<!doctype html> +<input type=text>
diff --git a/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/bless.html b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/bless.html index b8a1c2e..12257df0 100644 --- a/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/bless.html +++ b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/bless.html
@@ -43,7 +43,7 @@ promise_test(() => { return test_driver.bless('demonstrates return value without action') .then((value) => { - assert_equals(value, undefined); + assert_equals(value, null); }); }, 'no action function provided');
diff --git a/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/click_child_crossorigin.html b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/click_child_crossorigin.html new file mode 100644 index 0000000..6a8c684 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/click_child_crossorigin.html
@@ -0,0 +1,18 @@ +<!doctype html> +<script src="/resources/testdriver.js"></script> +<script src="/resources/testdriver-vendor.js"></script> + +<button id="button">Button</button> +<div id="log">FAIL</div> +<script> +let button = document.getElementById("button"); +button.addEventListener("click", () => + document.getElementById("log").textContent = "PASS"); + +addEventListener("load", () => { + test_driver.set_test_context(parent.opener); + test_driver.click(button) + .then(() => test_driver.message_test("PASS", "*")) + .catch(() => test_driver.message_test("FAIL", "*")); +}); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/click_child_testdriver.html b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/click_child_testdriver.html new file mode 100644 index 0000000..2c26a963 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/click_child_testdriver.html
@@ -0,0 +1,18 @@ +<!doctype html> +<script src="/resources/testdriver.js"></script> +<script src="/resources/testdriver-vendor.js"></script> + +<button id="button">Button</button> +<div id="log">FAIL</div> +<script> +let button = document.getElementById("button"); +button.addEventListener("click", () => + document.getElementById("log").textContent = "PASS"); + +addEventListener("load", () => { + test_driver.set_test_context(parent); + test_driver.click(button) + .then(() => test_driver.message_test("PASS", "*")) + .catch(() => test_driver.message_test("FAIL", "*")); +}); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/click_iframe_crossorigin.sub.html b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/click_iframe_crossorigin.sub.html new file mode 100644 index 0000000..01833dc --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/click_iframe_crossorigin.sub.html
@@ -0,0 +1,20 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>TestDriver click on a document in an iframe</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/resources/testdriver.js"></script> +<script src="/resources/testdriver-vendor.js"></script> + +<iframe src="https://{{host}}:{{ports[https][1]}}/infrastructure/testdriver/click_child_testdriver.html"></iframe> + +<script> +setup({single_test: true}); +addEventListener("message", (msg) => { + if (msg.data === "PASS") { + done(); + } else if (msg.data === "FAIL") { + assert_unreached("click failed") + } +}); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/click_nested_crossorigin.sub.html b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/click_nested_crossorigin.sub.html new file mode 100644 index 0000000..af90951 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/click_nested_crossorigin.sub.html
@@ -0,0 +1,25 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>TestDriver click method with multiple windows and nested iframe</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/resources/testdriver.js"></script> +<script src="/resources/testdriver-vendor.js"></script> + +<iframe src="about:blank"></iframe> + +<script> +setup({single_test: true}); + +window.open("about:blank") +var child = window.open("https://{{host}}:{{ports[https][0]}}/infrastructure/testdriver/click_outer_child.sub.html") +window.open("about:blank") + +addEventListener("message", (msg) => { + if (msg.data === "PASS") { + done(); + } else if (msg.data === "FAIL") { + assert_unreached("click failed") + } +}); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/click_outer_child.sub.html b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/click_outer_child.sub.html new file mode 100644 index 0000000..8e72223 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/click_outer_child.sub.html
@@ -0,0 +1,4 @@ +<!doctype html> +<iframe src="about:blank"></iframe> +<iframe src="about:blank"></iframe> +<iframe src="https://{{host}}:{{ports[https][1]}}/infrastructure/testdriver/click_child_crossorigin.html"></iframe>
diff --git a/third_party/blink/web_tests/external/wpt/resources/testdriver-actions.js b/third_party/blink/web_tests/external/wpt/resources/testdriver-actions.js index b6030bf..f3e6388 100644 --- a/third_party/blink/web_tests/external/wpt/resources/testdriver-actions.js +++ b/third_party/blink/web_tests/external/wpt/resources/testdriver-actions.js
@@ -23,6 +23,7 @@ this.createSource("none"); this.tickIdx = 0; this.defaultTickDuration = defaultTickDuration; + this.context = null; } Actions.prototype = { @@ -66,7 +67,17 @@ } catch(e) { return Promise.reject(e); } - return test_driver.action_sequence(actions); + return test_driver.action_sequence(actions, this.context); + }, + + /** + * Set the context for the actions + * + * @param {WindowProxy} context - Context in which to run the action sequence + */ + setContext: function(context) { + this.context = context; + return this; }, /**
diff --git a/third_party/blink/web_tests/external/wpt/resources/testdriver.js b/third_party/blink/web_tests/external/wpt/resources/testdriver.js index 165147d..c53b241 100644 --- a/third_party/blink/web_tests/external/wpt/resources/testdriver.js +++ b/third_party/blink/web_tests/external/wpt/resources/testdriver.js
@@ -1,6 +1,7 @@ (function() { "use strict"; var idCounter = 0; + let testharness_context = null; function getInViewCenterPoint(rect) { var left = Math.max(0, rect.left); @@ -49,6 +50,31 @@ */ window.test_driver = { /** + * Set the context in which testharness.js is loaded + * + * @param {WindowProxy} context - the window containing testharness.js + **/ + set_test_context: function(context) { + if (window.test_driver_internal.set_test_context) { + window.test_driver_internal.set_test_context(context); + } + testharness_context = context; + }, + + /** + * postMessage to the context containing testharness.js + * + * @param {Object} msg - the data to POST + **/ + message_test: function(msg) { + let target = testharness_context; + if (testharness_context === null) { + target = window; + } + target.postMessage(msg, "*"); + }, + + /** * Trigger user interaction in order to grant additional privileges to * a provided function. * @@ -57,30 +83,35 @@ * @param {String} intent - a description of the action which much be * triggered by user interaction * @param {Function} action - code requiring escalated privileges + * @param {WindowProxy} context - Browsing context in which + * to run the call, or null for the current + * browsing context. * * @returns {Promise} fulfilled following user interaction and * execution of the provided `action` function; * rejected if interaction fails or the provided * function throws an error */ - bless: function(intent, action) { - var button = document.createElement("button"); + bless: function(intent, action, context=null) { + let contextDocument = context ? context.document : document; + var button = contextDocument.createElement("button"); button.innerHTML = "This test requires user interaction.<br />" + "Please click here to allow " + intent + "."; button.id = "wpt-test-driver-bless-" + (idCounter += 1); - const elem = document.body || document.documentElement; + const elem = contextDocument.body || contextDocument.documentElement; elem.appendChild(button); - return new Promise(function(resolve, reject) { - button.addEventListener("click", resolve); + let wait_click = new Promise(resolve => button.addEventListener("click", resolve)); - test_driver.click(button).catch(reject); - }).then(function() { + return test_driver.click(button) + .then(wait_click) + .then(function() { button.remove(); if (typeof action === "function") { return action(); } + return null; }); }, @@ -151,10 +182,14 @@ * https://github.com/WICG/page-lifecycle/blob/master/README.md|Lifecycle API * for Web Pages} * + * @param {WindowProxy} context - Browsing context in which + * to run the call, or null for the current + * browsing context. + * * @returns {Promise} fulfilled after the freeze request is sent, or rejected * in case the WebDriver command errors */ - freeze: function() { + freeze: function(context=null) { return window.test_driver_internal.freeze(); }, @@ -166,19 +201,23 @@ * https://w3c.github.io/webdriver/#actions|WebDriver Actions Command} * * @param {Array} actions - an array of actions. The format is the same as the actions - property of the WebDriver command {@link - https://w3c.github.io/webdriver/#perform-actions|Perform - Actions} command. Each element is an object representing an - input source and each input source itself has an actions - property detailing the behaviour of that source at each timestep - (or tick). Authors are not expected to construct the actions - sequence by hand, but to use the builder api provided in - testdriver-actions.js + * property of the WebDriver command {@link + * https://w3c.github.io/webdriver/#perform-actions|Perform + * Actions} command. Each element is an object representing an + * input source and each input source itself has an actions + * property detailing the behaviour of that source at each timestep + * (or tick). Authors are not expected to construct the actions + * sequence by hand, but to use the builder api provided in + * testdriver-actions.js + * @param {WindowProxy} context - Browsing context in which + * to run the call, or null for the current + * browsing context. + * * @returns {Promise} fufiled after the actions are performed, or rejected in * the cases the WebDriver command errors */ - action_sequence: function(actions) { - return window.test_driver_internal.action_sequence(actions); + action_sequence: function(actions, context=null) { + return window.test_driver_internal.action_sequence(actions, context); }, /** @@ -188,11 +227,15 @@ * by ReportingObserver) for testing purposes, as described in * {@link https://w3c.github.io/reporting/#generate-test-report-command} * + * @param {WindowProxy} context - Browsing context in which + * to run the call, or null for the current + * browsing context. + * * @returns {Promise} fulfilled after the report is generated, or * rejected if the report generation fails */ - generate_test_report: function(message) { - return window.test_driver_internal.generate_test_report(message); + generate_test_report: function(message, context=null) { + return window.test_driver_internal.generate_test_report(message, context); }, /** @@ -206,6 +249,9 @@ * object * @param {String} state - the state of the permission * @param {boolean} one_realm - Optional. Whether the permission applies to only one realm + * @param {WindowProxy} context - Browsing context in which + * to run the call, or null for the current + * browsing context. * * The above params are used to create a [PermissionSetParameters]{@link * https://w3c.github.io/permissions/#dictdef-permissionsetparameters} object @@ -213,13 +259,13 @@ * @returns {Promise} fulfilled after the permission is set, or rejected if setting the * permission fails */ - set_permission: function(descriptor, state, one_realm) { + set_permission: function(descriptor, state, one_realm, context=null) { let permission_params = { descriptor, state, oneRealm: one_realm, }; - return window.test_driver_internal.set_permission(permission_params); + return window.test_driver_internal.set_permission(permission_params, context); }, /** @@ -232,12 +278,16 @@ * @param {Object} config - an [Authenticator Configuration]{@link * https://w3c.github.io/webauthn/#authenticator-configuration} * object + * @param {WindowProxy} context - Browsing context in which + * to run the call, or null for the current + * browsing context. + * * @returns {Promise} fulfilled after the authenticator is added, or * rejected in the cases the WebDriver command * errors. Returns the ID of the authenticator */ - add_virtual_authenticator: function(config) { - return window.test_driver_internal.add_virtual_authenticator(config); + add_virtual_authenticator: function(config, context=null) { + return window.test_driver_internal.add_virtual_authenticator(config, context); }, /** @@ -249,13 +299,16 @@ * * @param {String} authenticator_id - the ID of the authenticator to be * removed. + * @param {WindowProxy} context - Browsing context in which + * to run the call, or null for the current + * browsing context. * * @returns {Promise} fulfilled after the authenticator is removed, or * rejected in the cases the WebDriver command * errors */ - remove_virtual_authenticator: function(authenticator_id) { - return window.test_driver_internal.remove_virtual_authenticator(authenticator_id); + remove_virtual_authenticator: function(authenticator_id, context=null) { + return window.test_driver_internal.remove_virtual_authenticator(authenticator_id, context); }, /** @@ -267,13 +320,16 @@ * @param {Object} credential - A [Credential Parameters]{@link * https://w3c.github.io/webauthn/#credential-parameters} * object + * @param {WindowProxy} context - Browsing context in which + * to run the call, or null for the current + * browsing context. * * @returns {Promise} fulfilled after the credential is added, or * rejected in the cases the WebDriver command * errors */ - add_credential: function(authenticator_id, credential) { - return window.test_driver_internal.add_credential(authenticator_id, credential); + add_credential: function(authenticator_id, credential, context=null) { + return window.test_driver_internal.add_credential(authenticator_id, credential, context); }, /** @@ -285,6 +341,9 @@ * https://w3c.github.io/webauthn/#sctn-automation-get-credentials * * @param {String} authenticator_id - the ID of the authenticator + * @param {WindowProxy} context - Browsing context in which + * to run the call, or null for the current + * browsing context. * * @returns {Promise} fulfilled after the credentials are returned, or * rejected in the cases the WebDriver command @@ -292,8 +351,8 @@ * Parameters]{@link * https://w3c.github.io/webauthn/#credential-parameters} */ - get_credentials: function(authenticator_id) { - return window.test_driver_internal.get_credentials(authenticator_id); + get_credentials: function(authenticator_id, context=null) { + return window.test_driver_internal.get_credentials(authenticator_id, context=null); }, /** @@ -303,13 +362,16 @@ * * @param {String} authenticator_id - the ID of the authenticator * @param {String} credential_id - the ID of the credential + * @param {WindowProxy} context - Browsing context in which + * to run the call, or null for the current + * browsing context. * * @returns {Promise} fulfilled after the credential is removed, or * rejected in the cases the WebDriver command * errors. */ - remove_credential: function(authenticator_id, credential_id) { - return window.test_driver_internal.remove_credential(authenticator_id, credential_id); + remove_credential: function(authenticator_id, credential_id, context=null) { + return window.test_driver_internal.remove_credential(authenticator_id, credential_id, context); }, /** @@ -318,13 +380,16 @@ * https://w3c.github.io/webauthn/#sctn-automation-remove-all-credentials * * @param {String} authenticator_id - the ID of the authenticator + * @param {WindowProxy} context - Browsing context in which + * to run the call, or null for the current + * browsing context. * * @returns {Promise} fulfilled after the credentials are removed, or * rejected in the cases the WebDriver command * errors. */ - remove_all_credentials: function(authenticator_id) { - return window.test_driver_internal.remove_all_credentials(authenticator_id); + remove_all_credentials: function(authenticator_id, context=null) { + return window.test_driver_internal.remove_all_credentials(authenticator_id, context); }, /** @@ -336,9 +401,12 @@ * * @param {String} authenticator_id - the ID of the authenticator * @param {boolean} uv - the User Verified flag + * @param {WindowProxy} context - Browsing context in which + * to run the call, or null for the current + * browsing context. */ - set_user_verified: function(authenticator_id, uv) { - return window.test_driver_internal.set_user_verified(authenticator_id, uv); + set_user_verified: function(authenticator_id, uv, context=null) { + return window.test_driver_internal.set_user_verified(authenticator_id, uv, context); }, /** @@ -355,16 +423,19 @@ * May be "*" to indicate all origins. * @param {String} state - The storage access setting. * Must be either "allowed" or "blocked". + * @param {WindowProxy} context - Browsing context in which + * to run the call, or null for the current + * browsing context. * * @returns {Promise} Fulfilled after the storage access rule has been * set, or rejected if setting the rule fails. */ - set_storage_access: function(origin, embedding_origin, state) { + set_storage_access: function(origin, embedding_origin, state, context=null) { if (state !== "allowed" && state !== "blocked") { throw new Error("storage access status must be 'allowed' or 'blocked'"); } const blocked = state === "blocked"; - return window.test_driver_internal.set_storage_access(origin, embedding_origin, blocked); + return window.test_driver_internal.set_storage_access(origin, embedding_origin, blocked, context); }, }; @@ -377,13 +448,6 @@ */ in_automation: false, - /** - * Waits for a user-initiated click - * - * @param {Element} element - element to be clicked - * @param {{x: number, y: number} coords - viewport coordinates to click at - * @returns {Promise} fulfilled after click occurs - */ click: function(element, coords) { if (this.in_automation) { return Promise.reject(new Error('Not implemented')); @@ -394,14 +458,6 @@ }); }, - /** - * Waits for an element to receive a series of key presses - * - * @param {Element} element - element which should receve key presses - * @param {String} keys - keys to expect - * @returns {Promise} fulfilled after keys are received or rejected if - * an incorrect key sequence is received - */ send_keys: function(element, keys) { if (this.in_automation) { return Promise.reject(new Error('Not implemented')); @@ -434,158 +490,52 @@ }); }, - /** - * Freeze the current page - * - * @returns {Promise} fulfilled after freeze request is sent, otherwise - * it gets rejected - */ - freeze: function() { + freeze: function(context=null) { return Promise.reject(new Error("unimplemented")); }, - /** - * Send a sequence of pointer actions - * - * @returns {Promise} fufilled after actions are sent, rejected if any actions - * fail - */ - action_sequence: function(actions) { + action_sequence: function(actions, context=null) { return Promise.reject(new Error("unimplemented")); }, - /** - * Generates a test report on the current page - * - * @param {String} message - the message to be contained in the report - * @returns {Promise} fulfilled after the report is generated, or - * rejected if the report generation fails - */ - generate_test_report: function(message) { + generate_test_report: function(message, context=null) { return Promise.reject(new Error("unimplemented")); }, - /** - * Sets the state of a permission - * - * This function simulates a user setting a permission into a particular state as described - * in {@link https://w3c.github.io/permissions/#set-permission-command} - * - * @param {Object} permission_params - a [PermissionSetParameters]{@lint - * https://w3c.github.io/permissions/#dictdef-permissionsetparameters} - * object - * @returns {Promise} fulfilled after the permission is set, or rejected if setting the - * permission fails - */ - set_permission: function(permission_params) { + set_permission: function(permission_params, context=null) { return Promise.reject(new Error("unimplemented")); }, - /** - * Creates a virtual authenticator - * - * @param {Object} config - the authenticator configuration - * @returns {Promise} fulfilled after the authenticator is added, or - * rejected in the cases the WebDriver command - * errors. - */ - add_virtual_authenticator: function(config) { + add_virtual_authenticator: function(config, context=null) { return Promise.reject(new Error("unimplemented")); }, - /** - * Removes a virtual authenticator - * - * @param {String} authenticator_id - the ID of the authenticator to be - * removed. - * - * @returns {Promise} fulfilled after the authenticator is removed, or - * rejected in the cases the WebDriver command - * errors - */ - remove_virtual_authenticator: function(authenticator_id) { + remove_virtual_authenticator: function(authenticator_id, context=null) { return Promise.reject(new Error("unimplemented")); }, - /** - * Adds a credential to a virtual authenticator - * - * @param {String} authenticator_id - the ID of the authenticator - * @param {Object} credential - A [Credential Parameters]{@link - * https://w3c.github.io/webauthn/#credential-parameters} - * object - * - * @returns {Promise} fulfilled after the credential is added, or - * rejected in the cases the WebDriver command - * errors - * - */ - add_credential: function(authenticator_id, credential) { + add_credential: function(authenticator_id, credential, context=null) { return Promise.reject(new Error("unimplemented")); }, - /** - * Gets all the credentials stored in an authenticator - * - * @param {String} authenticator_id - the ID of the authenticator - * - * @returns {Promise} fulfilled after the credentials are returned, or - * rejected in the cases the WebDriver command - * errors. Returns an array of [Credential - * Parameters]{@link - * https://w3c.github.io/webauthn/#credential-parameters} - * - */ - get_credentials: function(authenticator_id) { + get_credentials: function(authenticator_id, context=null) { return Promise.reject(new Error("unimplemented")); }, - /** - * Remove a credential stored in an authenticator - * - * @param {String} authenticator_id - the ID of the authenticator - * @param {String} credential_id - the ID of the credential - * - * @returns {Promise} fulfilled after the credential is removed, or - * rejected in the cases the WebDriver command - * errors. - * - */ - remove_credential: function(authenticator_id, credential_id) { + remove_credential: function(authenticator_id, credential_id, context=null) { return Promise.reject(new Error("unimplemented")); }, - /** - * Removes all the credentials stored in a virtual authenticator - * - * @param {String} authenticator_id - the ID of the authenticator - * - * @returns {Promise} fulfilled after the credentials are removed, or - * rejected in the cases the WebDriver command - * errors. - * - */ - remove_all_credentials: function(authenticator_id) { + remove_all_credentials: function(authenticator_id, context=null) { return Promise.reject(new Error("unimplemented")); }, - /** - * Sets the User Verified flag on an authenticator - * - * @param {String} authenticator_id - the ID of the authenticator - * @param {boolean} uv - the User Verified flag - * - */ - set_user_verified: function(authenticator_id, uv) { + set_user_verified: function(authenticator_id, uv, context=null) { return Promise.reject(new Error("unimplemented")); }, - /** - * Sets the storage access policy for a third-party origin when loaded - * in the current first party context - */ - set_storage_access: function(origin, embedding_origin, blocked) { + set_storage_access: function(origin, embedding_origin, blocked, context=null) { return Promise.reject(new Error("unimplemented")); }, };
diff --git a/third_party/blink/web_tests/external/wpt/tools/ci/tc/sink_task.py b/third_party/blink/web_tests/external/wpt/tools/ci/tc/sink_task.py index ba76d27..1efcd42 100644 --- a/third_party/blink/web_tests/external/wpt/tools/ci/tc/sink_task.py +++ b/third_party/blink/web_tests/external/wpt/tools/ci/tc/sink_task.py
@@ -2,40 +2,63 @@ import logging import os +from six import ensure_text import taskcluster +from .github_checks_output import get_gh_checks_outputter + logging.basicConfig() logger = logging.getLogger() -def check_task_statuses(task_ids): +def check_task_statuses(task_ids, github_checks_outputter): """Verifies whether a set of Taskcluster tasks completed successfully or not. Returns 0 if all tasks passed completed successfully, 1 otherwise.""" queue = taskcluster.Queue({'rootUrl': os.environ['TASKCLUSTER_ROOT_URL']}) - success = True + failed_tasks = [] for task in task_ids: status = queue.status(task) state = status['status']['state'] if state == 'failed' or state == 'exception': logger.error('Task {0} failed with state "{1}"'.format(task, state)) - success = False + failed_tasks.append(status) elif state != 'completed': logger.error('Task {0} had unexpected state "{1}"'.format(task, state)) - success = False - if success: + failed_tasks.append(status) + + if failed_tasks and github_checks_outputter: + github_checks_outputter.output('Failed tasks:') + for task in failed_tasks: + # We need to make an additional call to get the task name. + task_id = task['status']['taskId'] + task_name = queue.task(task_id)['metadata']['name'] + github_checks_outputter.output('* `{}` failed with status `{}`'.format(task_name, task['status']['state'])) + else: logger.info('All tasks completed successfully') - return 0 if success else 1 + if github_checks_outputter: + github_checks_outputter.output('All tasks completed successfully') + return 1 if failed_tasks else 0 def get_parser(): parser = argparse.ArgumentParser() + parser.add_argument("--github-checks-text-file", type=ensure_text, + help="Path to GitHub checks output file for Taskcluster runs") parser.add_argument("tasks", nargs="+", help="A set of Taskcluster task ids to verify the state of.") return parser def run(venv, **kwargs): - return check_task_statuses(kwargs['tasks']) + github_checks_outputter = get_gh_checks_outputter(kwargs["github_checks_text_file"]) + + if github_checks_outputter: + github_checks_outputter.output( + "This check acts as a 'sink' for all other Taskcluster-based checks. " + "A failure here means that some other check has failed, which is the " + "real blocker.\n" + ) + return check_task_statuses(kwargs['tasks'], github_checks_outputter)
diff --git a/third_party/blink/web_tests/external/wpt/tools/ci/tc/tasks/test.yml b/third_party/blink/web_tests/external/wpt/tools/ci/tc/tasks/test.yml index 78891bf..4fa69e8 100644 --- a/third_party/blink/web_tests/external/wpt/tools/ci/tc/tasks/test.yml +++ b/third_party/blink/web_tests/external/wpt/tools/ci/tc/tasks/test.yml
@@ -591,5 +591,5 @@ use: - wpt-base - trigger-pr - command: "./wpt tc-sink-task" + command: "./wpt tc-sink-task --github-checks-text-file=/home/test/artifacts/checkrun.md" requires: all-resolved
diff --git a/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/base.py b/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/base.py index 0247b3fe..4c3891c1 100644 --- a/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/base.py +++ b/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/base.py
@@ -691,6 +691,9 @@ def set_window(self, handle): pass + def window_handles(self): + return [] + class ConnectionlessProtocol(Protocol): implements = [ConnectionlessBaseProtocolPart] @@ -787,6 +790,7 @@ def process_action(self, url, payload): action = payload["action"] + cmd_id = payload["id"] self.logger.debug("Got action: %s" % action) try: action_handler = self.actions[action] @@ -797,21 +801,21 @@ result = action_handler(payload) except self.unimplemented_exc: self.logger.warning("Action %s not implemented" % action) - self._send_message("complete", "error", "Action %s not implemented" % action) + self._send_message(cmd_id, "complete", "error", "Action %s not implemented" % action) except Exception: self.logger.warning("Action %s failed" % action) self.logger.warning(traceback.format_exc()) - self._send_message("complete", "error") + self._send_message(cmd_id, "complete", "error") raise else: self.logger.debug("Action %s completed with result %s" % (action, result)) return_message = {"result": result} - self._send_message("complete", "success", json.dumps(return_message)) + self._send_message(cmd_id, "complete", "success", json.dumps(return_message)) return False, None - def _send_message(self, message_type, status, message=None): - self.protocol.testdriver.send_message(message_type, status, message=message) + def _send_message(self, cmd_id, message_type, status, message=None): + self.protocol.testdriver.send_message(cmd_id, message_type, status, message=message) class ActionContext(object): @@ -820,28 +824,20 @@ self.protocol = protocol self.context = context self.initial_window = None - self.switched_frame = False def __enter__(self): if self.context is None: return - window_id = self.context[0] - if window_id: - self.initial_window = self.protocol.base.current_window - self.logger.debug("Switching to window %s" % window_id) - self.protocol.testdriver.switch_to_window(window_id) - - for frame_id in self.context[1:]: - self.switched_frame = True - self.logger.debug("Switching to frame %s" % frame_id) - self.protocol.testdriver.switch_to_frame(frame_id) + self.initial_window = self.protocol.base.current_window + self.logger.debug("Switching to window %s" % self.context) + self.protocol.testdriver.switch_to_window(self.context) def __exit__(self, *args): - if self.initial_window is not None: - self.logger.debug("Switching back to initial window") - self.protocol.base.set_window(self.initial_window) - self.initial_window = None - elif self.switched_frame: - self.protocol.testdriver.switch_to_frame(None) - self.switched_frame = False + if self.context is None: + return + + self.logger.debug("Switching back to initial window") + self.protocol.base.set_window(self.initial_window) + self.protocol.testdriver._switch_to_frame(None) + self.initial_window = None
diff --git a/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/executormarionette.py b/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/executormarionette.py index e7c9726..7e2cc8e 100644 --- a/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/executormarionette.py +++ b/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/executormarionette.py
@@ -103,6 +103,9 @@ def set_window(self, handle): _switch_to_window(self.marionette, handle) + def window_handles(self): + return self.marionette.window_handles + def load(self, url): self.marionette.navigate(url) @@ -460,8 +463,9 @@ def setup(self): self.marionette = self.parent.marionette - def send_message(self, message_type, status, message=None): + def send_message(self, cmd_id, message_type, status, message=None): obj = { + "cmd_id": cmd_id, "type": "testdriver-%s" % str(message_type), "status": str(status) } @@ -469,24 +473,12 @@ obj["message"] = str(message) self.parent.base.execute_script("window.postMessage(%s, '*')" % json.dumps(obj)) - def switch_to_window(self, window_id): - if window_id is None: - return - - for window_handle in self.marionette.window_handles: - _switch_to_window(self.marionette, window_handle) - try: - handle_window_id = self.marionette.execute_script("return window.name") - except errors.JavascriptException: - continue - if str(handle_window_id) == window_id: - return - - raise Exception("Window with id %s not found" % window_id) - - def switch_to_frame(self, frame_number): + def _switch_to_frame(self, frame_number): self.marionette.switch_to_frame(frame_number) + def _switch_to_parent_frame(self): + self.marionette.switch_to_parent_frame() + class MarionetteCoverageProtocolPart(CoverageProtocolPart): def setup(self):
diff --git a/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/executorselenium.py b/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/executorselenium.py index 82ab6f25..ff26351f8 100644 --- a/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/executorselenium.py +++ b/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/executorselenium.py
@@ -61,6 +61,9 @@ def set_window(self, handle): self.webdriver.switch_to_window(handle) + def window_handles(self): + return self.webdriver.window_handles + def load(self, url): self.webdriver.get(url) @@ -200,8 +203,9 @@ def setup(self): self.webdriver = self.parent.webdriver - def send_message(self, message_type, status, message=None): + def send_message(self, cmd_id, message_type, status, message=None): obj = { + "cmd_id": cmd_id, "type": "testdriver-%s" % str(message_type), "status": str(status) }
diff --git a/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/executorservodriver.py b/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/executorservodriver.py index dbed2fed..2cd1dbf3a 100644 --- a/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/executorservodriver.py +++ b/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/executorservodriver.py
@@ -76,6 +76,9 @@ def set_window(self, handle): pass + def window_handles(self): + return [] + def load(self, url): pass
diff --git a/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/executorwebdriver.py b/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/executorwebdriver.py index 139c475..bad5fd0 100644 --- a/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/executorwebdriver.py +++ b/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/executorwebdriver.py
@@ -61,6 +61,9 @@ def set_window(self, handle): self.webdriver.window_handle = handle + def window_handles(self): + return self.webdriver.handles + def load(self, url): self.webdriver.url = url @@ -214,8 +217,9 @@ def setup(self): self.webdriver = self.parent.webdriver - def send_message(self, message_type, status, message=None): + def send_message(self, cmd_id, message_type, status, message=None): obj = { + "cmd_id": cmd_id, "type": "testdriver-%s" % str(message_type), "status": str(status) } @@ -223,24 +227,12 @@ obj["message"] = str(message) self.webdriver.execute_script("window.postMessage(%s, '*')" % json.dumps(obj)) - def switch_to_window(self, window_id): - if window_id is None: - return - - for window_handle in self.webdriver.handles: - self.webdriver.window_handle = window_handle - try: - handle_window_id = self.webdriver.execute_script("return window.name") - except client.JavascriptErrorException: - continue - if str(handle_window_id) == window_id: - return - - raise Exception("Window with id %s not found" % window_id) - - def switch_to_frame(self, frame_number): + def _switch_to_frame(self, frame_number): self.webdriver.switch_frame(frame_number) + def _switch_to_parent_frame(self): + self.webdriver.switch_frame("parent") + class WebDriverGenerateTestReportProtocolPart(GenerateTestReportProtocolPart): def setup(self):
diff --git a/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/protocol.py b/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/protocol.py index 1c85c0f..bd768b10 100644 --- a/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/protocol.py +++ b/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/protocol.py
@@ -147,6 +147,11 @@ pass @abstractmethod + def window_handles(self): + """Get a list of handles to top-level browsing contexts""" + pass + + @abstractmethod def load(self, url): """Load a url in the current browsing context @@ -343,9 +348,10 @@ name = "testdriver" @abstractmethod - def send_message(self, message_type, status, message=None): + def send_message(self, cmd_id, message_type, status, message=None): """Send a testdriver message to the browser. + :param int cmd_id: The id of the command to which we're responding :param str message_type: The kind of the message. :param str status: Either "failure" or "success" depending on whether the previous command succeeded. @@ -356,14 +362,46 @@ """Switch to a window given a wptrunner window id :param str wptrunner_id: window id""" - pass + if wptrunner_id is None: + return - def switch_to_frame(self, index): + stack = [str(item) for item in self.parent.base.window_handles()] + while stack: + item = stack.pop() + if item is None: + self._switch_to_parent_frame() + continue + elif isinstance(item, str): + self.parent.base.set_window(item) + else: + self._switch_to_frame(item) + + try: + handle_window_id = self.parent.base.execute_script("return window.__wptrunner_id") + if str(handle_window_id) == wptrunner_id: + return + except Exception: + pass + frame_count = self.parent.base.execute_script("return window.length") + # None here makes us switch back to the parent after we've processed all the subframes + stack.append(None) + if frame_count: + stack.extend(reversed(range(0, frame_count))) + + raise Exception("Window with id %s not found" % wptrunner_id) + + @abstractmethod + def _switch_to_frame(self, index): """Switch to a frame in the current window :param int index: Frame id""" pass + @abstractmethod + def _switch_to_parent_frame(self): + """Switch to the parent of the current frame""" + pass + class AssertsProtocolPart(ProtocolPart): """ProtocolPart that implements the functionality required to get a count of non-fatal
diff --git a/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/testdriver-extra.js b/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/testdriver-extra.js index 241fc83..9c0c69a 100644 --- a/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/testdriver-extra.js +++ b/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/testdriver-extra.js
@@ -1,9 +1,13 @@ "use strict"; -(function(){ - let pending_resolve = null; - let pending_reject = null; +(function() { + const is_test_context = window.__wptrunner_message_queue !== undefined; + const pending = new Map(); + let result = null; + let ctx_cmd_id = 0; + let testharness_context = null; + window.addEventListener("message", function(event) { const data = event.data; @@ -11,29 +15,70 @@ return; } - if (data.type !== "testdriver-complete") { - return; - } - - if (data.status === "success") { - result = JSON.parse(data.message).result; - pending_resolve(result); - } else { - pending_reject(`${data.status}: ${data.message}`); + if (is_test_context && data.type === "testdriver-command") { + const command = data.message; + const ctx_id = command.cmd_id; + delete command.cmd_id; + const cmd_id = window.__wptrunner_message_queue.push(command); + let on_success = (data) => { + data.type = "testdriver-complete"; + data.cmd_id = ctx_id; + event.source.postMessage(data, "*"); + }; + let on_failure = (data) => { + data.type = "testdriver-complete"; + data.cmd_id = ctx_id; + event.source.postMessage(data, "*"); + }; + pending.set(cmd_id, [on_success, on_failure]); + } else if (data.type === "testdriver-complete") { + const cmd_id = data.cmd_id; + const [on_success, on_failure] = pending.get(cmd_id); + pending.clear(cmd_id); + const resolver = data.status === "success" ? on_success : on_failure; + resolver(data); + if (is_test_context) { + window.__wptrunner_process_next_event(); + } } }); - let last_window_id = 0; + // Code copied from /common/utils.js + function rand_int(bits) { + if (bits < 1 || bits > 53) { + throw new TypeError(); + } else { + if (bits >= 1 && bits <= 30) { + return 0 | ((1 << bits) * Math.random()); + } else { + var high = (0 | ((1 << (bits - 30)) * Math.random())) * (1 << 30); + var low = 0 | ((1 << 30) * Math.random()); + return high + low; + } + } + } + + function to_hex(x, length) { + var rv = x.toString(16); + while (rv.length < length) { + rv = "0" + rv; + } + return rv; + } + function get_window_id(win) { - if (win === window) { + if (win == window && is_test_context) { return null; } - // This is a hack until some implementations support proper window ids - // It won't work cross-frame - if (!win.name) { - win.name = "__wptrunner_window " + last_window_id++; + if (!win.__wptrunner_id) { + // generate a uuid + win.__wptrunner_id = [to_hex(rand_int(32), 8), + to_hex(rand_int(16), 4), + to_hex(0x4000 | rand_int(12), 4), + to_hex(0x8000 | rand_int(14), 4), + to_hex(rand_int(48), 12)].join("-"); } - return win.name; + return win.__wptrunner_id; } const get_context = function(element) { @@ -44,23 +89,7 @@ if (!elementWindow) { throw new Error("Browsing context for element was detached"); } - let top = elementWindow.top; - if (elementWindow === window) { - if (top !== window) { - throw new Error("Can't load testdriver in a frame"); - } - // For the current window just return null - return null; - } - let rv = []; - let currentWindow = elementWindow; - while (currentWindow !== top) { - rv.push(Array.prototype.indexOf.call(currentWindow.parent.frames, currentWindow)); - currentWindow = currentWindow.parent; - } - rv.push(top !== window ? get_window_id(top) : null); - rv.reverse(); - return rv; + return elementWindow; }; const get_selector = function(element) { @@ -93,43 +122,60 @@ return selector; }; + const create_action = function(name, props) { + let cmd_id; + const action_msg = {type: "action", + action: name, + ...props}; + if (action_msg.context) { + action_msg.context = get_window_id(action_msg.context); + } + if (is_test_context) { + cmd_id = window.__wptrunner_message_queue.push(action_msg); + } else { + if (testharness_context === null) { + throw new Error("Tried to run in a non-testharness window without a call to set_test_context"); + } + cmd_id = ctx_cmd_id++; + action_msg.cmd_id = cmd_id; + window.test_driver.message_test({type: "testdriver-command", + message: action_msg}); + } + const pending_promise = new Promise(function(resolve, reject) { + const on_success = data => { + result = JSON.parse(data.message).result; + resolve(result); + }; + const on_failure = data => { + reject(`${data.status}: ${data.message}`); + }; + pending.set(cmd_id, [on_success, on_failure]); + }); + return pending_promise; + }; + window.test_driver_internal.in_automation = true; + window.test_driver_internal.set_test_context = function(context) { + if (window.__wptrunner_message_queue) { + throw new Error("Tried to set testharness context in a window containing testharness.js"); + } + testharness_context = context; + }; + window.test_driver_internal.click = function(element) { - const context = get_context(element); const selector = get_selector(element); - const pending_promise = new Promise(function(resolve, reject) { - pending_resolve = resolve; - pending_reject = reject; - }); - window.__wptrunner_message_queue.push({"type": "action", - "action": "click", - selector, - context}); - return pending_promise; + const context = get_context(element); + return create_action("click", {selector, context}); }; window.test_driver_internal.send_keys = function(element, keys) { const selector = get_selector(element); const context = get_context(element); - const pending_promise = new Promise(function(resolve, reject) { - pending_resolve = resolve; - pending_reject = reject; - }); - window.__wptrunner_message_queue.push({"type": "action", - "action": "send_keys", - selector, - keys, - context}); - return pending_promise; + return create_action("send_keys", {selector, keys, context}); }; - window.test_driver_internal.action_sequence = function(actions) { - const pending_promise = new Promise(function(resolve, reject) { - pending_resolve = resolve; - pending_reject = reject; - }); - let context = null; + window.test_driver_internal.action_sequence = function(actions, context=null) { for (let actionSequence of actions) { if (actionSequence.type == "pointer") { for (let action of actionSequence.actions) { @@ -145,111 +191,42 @@ } } } - window.__wptrunner_message_queue.push({type: "action", - action: "action_sequence", - actions, - context}); - return pending_promise; + return create_action("action_sequence", {actions, context}); }; - window.test_driver_internal.generate_test_report = function(message) { - const pending_promise = new Promise(function(resolve, reject) { - pending_resolve = resolve; - pending_reject = reject; - }); - window.__wptrunner_message_queue.push({"type": "action", - "action": "generate_test_report", - message}); - return pending_promise; + window.test_driver_internal.generate_test_report = function(message, context=null) { + return create_action("generate_test_report", {message, context}); }; - window.test_driver_internal.set_permission = function(permission_params) { - const pending_promise = new Promise(function(resolve, reject) { - pending_resolve = resolve; - pending_reject = reject; - }); - window.__wptrunner_message_queue.push({"type": "action", - "action": "set_permission", - permission_params}); - return pending_promise; + window.test_driver_internal.set_permission = function(permission_params, context=null) { + return create_action("set_permission", {permission_params, context}); }; - window.test_driver_internal.add_virtual_authenticator = function(config) { - const pending_promise = new Promise(function(resolve, reject) { - pending_resolve = resolve; - pending_reject = reject; - }); - window.__wptrunner_message_queue.push({"type": "action", - "action": "add_virtual_authenticator", - config}); - return pending_promise; + window.test_driver_internal.add_virtual_authenticator = function(config, context=null) { + return create_action("add_virtual_authenticator", {config, context}); }; - window.test_driver_internal.remove_virtual_authenticator = function(authenticator_id) { - const pending_promise = new Promise(function(resolve, reject) { - pending_resolve = resolve; - pending_reject = reject; - }); - window.__wptrunner_message_queue.push({"type": "action", - "action": "remove_virtual_authenticator", - authenticator_id}); - return pending_promise; + window.test_driver_internal.remove_virtual_authenticator = function(authenticator_id, context=null) { + return create_action("remove_virtual_authenticator", {authenticator_id, context}); }; - window.test_driver_internal.add_credential = function(authenticator_id, credential) { - const pending_promise = new Promise(function(resolve, reject) { - pending_resolve = resolve; - pending_reject = reject; - }); - window.__wptrunner_message_queue.push({"type": "action", - "action": "add_credential", - authenticator_id, credential}); - return pending_promise; + window.test_driver_internal.add_credential = function(authenticator_id, credential, context=null) { + return create_action("add_credential", {authenticator_id, credential, context}); }; - window.test_driver_internal.get_credentials = function(authenticator_id) { - const pending_promise = new Promise(function(resolve, reject) { - pending_resolve = resolve; - pending_reject = reject; - }); - window.__wptrunner_message_queue.push({"type": "action", - "action": "get_credentials", - authenticator_id}); - return pending_promise; + window.test_driver_internal.get_credentials = function(authenticator_id, context=null) { + return create_action("get_credentials", {authenticator_id, context}); }; - window.test_driver_internal.remove_credential = function(authenticator_id, credential_id) { - const pending_promise = new Promise(function(resolve, reject) { - pending_resolve = resolve; - pending_reject = reject; - }); - window.__wptrunner_message_queue.push({"type": "action", - "action": "remove_credential", - authenticator_id, - credential_id}); - return pending_promise; + window.test_driver_internal.remove_credential = function(authenticator_id, credential_id, context=null) { + return create_action("remove_credential", {authenticator_id, credential_id, context}); }; - window.test_driver_internal.remove_all_credentials = function(authenticator_id) { - const pending_promise = new Promise(function(resolve, reject) { - pending_resolve = resolve; - pending_reject = reject; - }); - window.__wptrunner_message_queue.push({"type": "action", - "action": "remove_all_credentials", - authenticator_id}); - return pending_promise; + window.test_driver_internal.remove_all_credentials = function(authenticator_id, context=null) { + return create_action("remove_all_credentials", {authenticator_id, context}); }; - window.test_driver_internal.set_user_verified = function(authenticator_id, uv) { - const pending_promise = new Promise(function(resolve, reject) { - pending_resolve = resolve; - pending_reject = reject; - }); - window.__wptrunner_message_queue.push({"type": "action", - "action": "set_user_verified", - authenticator_id, - uv}); - return pending_promise; + window.test_driver_internal.set_user_verified = function(authenticator_id, uv, context=null) { + return create_action("set_user_verified", {authenticator_id, uv, context}); }; })();
diff --git a/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/testharnessreport.js b/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/testharnessreport.js index 29fc0e9..9cd680e1 100644 --- a/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/testharnessreport.js +++ b/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/testharnessreport.js
@@ -1,11 +1,15 @@ class MessageQueue { constructor() { + this.item_id = 0; this._queue = []; } push(item) { + let cmd_id = this.item_id++; + item.id = cmd_id; this._queue.push(item); __wptrunner_process_next_event(); + return cmd_id; } shift() {
diff --git a/third_party/blink/web_tests/fast/canvas/canvas-shadow-source-in-expected.png b/third_party/blink/web_tests/fast/canvas/canvas-shadow-source-in-expected.png deleted file mode 100644 index b49882c..0000000 --- a/third_party/blink/web_tests/fast/canvas/canvas-shadow-source-in-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/composite-after-paint/css3/filters/filter-repaint-composited-fallback-crash-expected.png b/third_party/blink/web_tests/flag-specific/composite-after-paint/css3/filters/filter-repaint-composited-fallback-crash-expected.png index 74e4f89..d4b2992 100644 --- a/third_party/blink/web_tests/flag-specific/composite-after-paint/css3/filters/filter-repaint-composited-fallback-crash-expected.png +++ b/third_party/blink/web_tests/flag-specific/composite-after-paint/css3/filters/filter-repaint-composited-fallback-crash-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/composite-after-paint/css3/filters/filter-repaint-composited-fallback-expected.png b/third_party/blink/web_tests/flag-specific/composite-after-paint/css3/filters/filter-repaint-composited-fallback-expected.png index 74e4f89..d4b2992 100644 --- a/third_party/blink/web_tests/flag-specific/composite-after-paint/css3/filters/filter-repaint-composited-fallback-expected.png +++ b/third_party/blink/web_tests/flag-specific/composite-after-paint/css3/filters/filter-repaint-composited-fallback-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/composite-after-paint/virtual/scalefactor200/css3/filters/filter-repaint-composited-fallback-crash-expected.png b/third_party/blink/web_tests/flag-specific/composite-after-paint/virtual/scalefactor200/css3/filters/filter-repaint-composited-fallback-crash-expected.png index 6ce97dc..6dc1a36 100644 --- a/third_party/blink/web_tests/flag-specific/composite-after-paint/virtual/scalefactor200/css3/filters/filter-repaint-composited-fallback-crash-expected.png +++ b/third_party/blink/web_tests/flag-specific/composite-after-paint/virtual/scalefactor200/css3/filters/filter-repaint-composited-fallback-crash-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/composite-after-paint/virtual/scalefactor200/css3/filters/filter-repaint-composited-fallback-expected.png b/third_party/blink/web_tests/flag-specific/composite-after-paint/virtual/scalefactor200/css3/filters/filter-repaint-composited-fallback-expected.png index 6ce97dc..6dc1a36 100644 --- a/third_party/blink/web_tests/flag-specific/composite-after-paint/virtual/scalefactor200/css3/filters/filter-repaint-composited-fallback-expected.png +++ b/third_party/blink/web_tests/flag-specific/composite-after-paint/virtual/scalefactor200/css3/filters/filter-repaint-composited-fallback-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/enable-gpu-rasterization/compositing/overflow/border-radius-above-composited-subframe-expected.png b/third_party/blink/web_tests/flag-specific/enable-gpu-rasterization/compositing/overflow/border-radius-above-composited-subframe-expected.png index cc6f5f9..9420be9 100644 --- a/third_party/blink/web_tests/flag-specific/enable-gpu-rasterization/compositing/overflow/border-radius-above-composited-subframe-expected.png +++ b/third_party/blink/web_tests/flag-specific/enable-gpu-rasterization/compositing/overflow/border-radius-above-composited-subframe-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/enable-gpu-rasterization/compositing/overflow/border-radius-composited-subframe-expected.png b/third_party/blink/web_tests/flag-specific/enable-gpu-rasterization/compositing/overflow/border-radius-composited-subframe-expected.png index d3e02133..957a113 100644 --- a/third_party/blink/web_tests/flag-specific/enable-gpu-rasterization/compositing/overflow/border-radius-composited-subframe-expected.png +++ b/third_party/blink/web_tests/flag-specific/enable-gpu-rasterization/compositing/overflow/border-radius-composited-subframe-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/enable-gpu-rasterization/css3/filters/effect-blur-expected.png b/third_party/blink/web_tests/flag-specific/enable-gpu-rasterization/css3/filters/effect-blur-expected.png index ad9e9fe..e8d6380 100644 --- a/third_party/blink/web_tests/flag-specific/enable-gpu-rasterization/css3/filters/effect-blur-expected.png +++ b/third_party/blink/web_tests/flag-specific/enable-gpu-rasterization/css3/filters/effect-blur-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/enable-gpu-rasterization/css3/filters/filter-repaint-expected.png b/third_party/blink/web_tests/flag-specific/enable-gpu-rasterization/css3/filters/filter-repaint-expected.png index bb2f462b..3487462 100644 --- a/third_party/blink/web_tests/flag-specific/enable-gpu-rasterization/css3/filters/filter-repaint-expected.png +++ b/third_party/blink/web_tests/flag-specific/enable-gpu-rasterization/css3/filters/filter-repaint-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/compositing/culling/filter-occlusion-blur-expected.png b/third_party/blink/web_tests/platform/linux/compositing/culling/filter-occlusion-blur-expected.png new file mode 100644 index 0000000..d1f2bb31 --- /dev/null +++ b/third_party/blink/web_tests/platform/linux/compositing/culling/filter-occlusion-blur-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/compositing/masks/mask-with-added-filters-expected.png b/third_party/blink/web_tests/platform/linux/compositing/masks/mask-with-added-filters-expected.png index 882272c..5b4bfc7 100644 --- a/third_party/blink/web_tests/platform/linux/compositing/masks/mask-with-added-filters-expected.png +++ b/third_party/blink/web_tests/platform/linux/compositing/masks/mask-with-added-filters-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/gpu/fast/canvas/canvas-shadow-source-in-expected.png b/third_party/blink/web_tests/platform/linux/virtual/gpu/fast/canvas/canvas-shadow-source-in-expected.png index 36e326a..ddebd76 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/gpu/fast/canvas/canvas-shadow-source-in-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/gpu/fast/canvas/canvas-shadow-source-in-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/backdrop-filter-boundary-expected.png b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/backdrop-filter-boundary-expected.png index b25843b..3e77df4 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/backdrop-filter-boundary-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/backdrop-filter-boundary-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-brightness-clamping-hw-expected.png b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-brightness-clamping-hw-expected.png index 501f090..2cc3a801 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-brightness-clamping-hw-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-brightness-clamping-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-combined-hw-expected.png b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-combined-hw-expected.png index d554f28c..e8f25ee 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-combined-hw-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-combined-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-drop-shadow-hw-expected.png b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-drop-shadow-hw-expected.png index 181a6b6f..9759644c 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-drop-shadow-hw-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-drop-shadow-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-colorspace-hw-expected.png b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-colorspace-hw-expected.png index 46150c1..dfad762 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-colorspace-hw-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-colorspace-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-hw-expected.png b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-hw-expected.png index 1ad8859e..4407c67 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-hw-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-subregion-hw-expected.png b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-subregion-hw-expected.png index 8bc3444..7bfc3b9 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-subregion-hw-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-subregion-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-zoom-hw-expected.png b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-zoom-hw-expected.png index 1ecea2f..6fbe2234 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-zoom-hw-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/scalefactor200/css3/filters/effect-reference-zoom-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/compositing/culling/filter-occlusion-blur-expected.png b/third_party/blink/web_tests/platform/mac/compositing/culling/filter-occlusion-blur-expected.png new file mode 100644 index 0000000..d1f2bb31 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac/compositing/culling/filter-occlusion-blur-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/compositing/masks/mask-with-added-filters-expected.png b/third_party/blink/web_tests/platform/mac/compositing/masks/mask-with-added-filters-expected.png index 2f2cc7e..1c91b8a 100644 --- a/third_party/blink/web_tests/platform/mac/compositing/masks/mask-with-added-filters-expected.png +++ b/third_party/blink/web_tests/platform/mac/compositing/masks/mask-with-added-filters-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/css3/filters/backdrop-filter-basic-blur-expected.png b/third_party/blink/web_tests/platform/mac/css3/filters/backdrop-filter-basic-blur-expected.png new file mode 100644 index 0000000..14d2acd --- /dev/null +++ b/third_party/blink/web_tests/platform/mac/css3/filters/backdrop-filter-basic-blur-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/css3/filters/backdrop-filter-boundary-expected.png b/third_party/blink/web_tests/platform/mac/css3/filters/backdrop-filter-boundary-expected.png index 5327b3c..5039974a 100644 --- a/third_party/blink/web_tests/platform/mac/css3/filters/backdrop-filter-boundary-expected.png +++ b/third_party/blink/web_tests/platform/mac/css3/filters/backdrop-filter-boundary-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/css3/filters/effect-brightness-clamping-hw-expected.png b/third_party/blink/web_tests/platform/mac/css3/filters/effect-brightness-clamping-hw-expected.png index d472be5..32fa074 100644 --- a/third_party/blink/web_tests/platform/mac/css3/filters/effect-brightness-clamping-hw-expected.png +++ b/third_party/blink/web_tests/platform/mac/css3/filters/effect-brightness-clamping-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/css3/filters/effect-drop-shadow-hw-expected.png b/third_party/blink/web_tests/platform/mac/css3/filters/effect-drop-shadow-hw-expected.png index 30c7859..01cb9f8 100644 --- a/third_party/blink/web_tests/platform/mac/css3/filters/effect-drop-shadow-hw-expected.png +++ b/third_party/blink/web_tests/platform/mac/css3/filters/effect-drop-shadow-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/css3/filters/effect-reference-colorspace-hw-expected.png b/third_party/blink/web_tests/platform/mac/css3/filters/effect-reference-colorspace-hw-expected.png index 7accaf9..209eabd 100644 --- a/third_party/blink/web_tests/platform/mac/css3/filters/effect-reference-colorspace-hw-expected.png +++ b/third_party/blink/web_tests/platform/mac/css3/filters/effect-reference-colorspace-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/css3/filters/effect-reference-hidpi-hw-expected.png b/third_party/blink/web_tests/platform/mac/css3/filters/effect-reference-hidpi-hw-expected.png deleted file mode 100644 index 08bad9d..0000000 --- a/third_party/blink/web_tests/platform/mac/css3/filters/effect-reference-hidpi-hw-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/css3/filters/effect-reference-hw-expected.png b/third_party/blink/web_tests/platform/mac/css3/filters/effect-reference-hw-expected.png index 29002ac..b837d48 100644 --- a/third_party/blink/web_tests/platform/mac/css3/filters/effect-reference-hw-expected.png +++ b/third_party/blink/web_tests/platform/mac/css3/filters/effect-reference-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/css3/filters/effect-reference-subregion-hw-expected.png b/third_party/blink/web_tests/platform/mac/css3/filters/effect-reference-subregion-hw-expected.png index 310a0f6..91fe78d 100644 --- a/third_party/blink/web_tests/platform/mac/css3/filters/effect-reference-subregion-hw-expected.png +++ b/third_party/blink/web_tests/platform/mac/css3/filters/effect-reference-subregion-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/css3/filters/effect-reference-zoom-hw-expected.png b/third_party/blink/web_tests/platform/mac/css3/filters/effect-reference-zoom-hw-expected.png new file mode 100644 index 0000000..b2cafa7 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac/css3/filters/effect-reference-zoom-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/virtual/gpu/fast/canvas/canvas-shadow-source-in-expected.png b/third_party/blink/web_tests/platform/mac/virtual/gpu/fast/canvas/canvas-shadow-source-in-expected.png index bf73a7d..0bf8a29 100644 --- a/third_party/blink/web_tests/platform/mac/virtual/gpu/fast/canvas/canvas-shadow-source-in-expected.png +++ b/third_party/blink/web_tests/platform/mac/virtual/gpu/fast/canvas/canvas-shadow-source-in-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/backdrop-filter-basic-blur-expected.png b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/backdrop-filter-basic-blur-expected.png new file mode 100644 index 0000000..1ddbae082a --- /dev/null +++ b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/backdrop-filter-basic-blur-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/backdrop-filter-boundary-expected.png b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/backdrop-filter-boundary-expected.png index b25843b..3e77df4 100644 --- a/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/backdrop-filter-boundary-expected.png +++ b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/backdrop-filter-boundary-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/backdrop-filter-edge-pixels-expected.png b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/backdrop-filter-edge-pixels-expected.png index f1e91c8..e6e7e27 100644 --- a/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/backdrop-filter-edge-pixels-expected.png +++ b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/backdrop-filter-edge-pixels-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-all-on-background-hw-expected.png b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-all-on-background-hw-expected.png new file mode 100644 index 0000000..b4379337 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-all-on-background-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-brightness-clamping-hw-expected.png b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-brightness-clamping-hw-expected.png new file mode 100644 index 0000000..44ad0889 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-brightness-clamping-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-combined-hw-expected.png b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-combined-hw-expected.png new file mode 100644 index 0000000..40d1b32 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-combined-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-drop-shadow-hw-expected.png b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-drop-shadow-hw-expected.png index 181a6b6f..9759644c 100644 --- a/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-drop-shadow-hw-expected.png +++ b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-drop-shadow-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-reference-colorspace-hw-expected.png b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-reference-colorspace-hw-expected.png index 3632d3f..e2a7618 100644 --- a/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-reference-colorspace-hw-expected.png +++ b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-reference-colorspace-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-reference-hw-expected.png b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-reference-hw-expected.png index 59187dc..4a32771 100644 --- a/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-reference-hw-expected.png +++ b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-reference-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-reference-subregion-hw-expected.png b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-reference-subregion-hw-expected.png index a9e57caa..ef35d15 100644 --- a/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-reference-subregion-hw-expected.png +++ b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-reference-subregion-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-reference-zoom-hw-expected.png b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-reference-zoom-hw-expected.png index ba09a548..f988089b 100644 --- a/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-reference-zoom-hw-expected.png +++ b/third_party/blink/web_tests/platform/mac/virtual/scalefactor200/css3/filters/effect-reference-zoom-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/compositing/masks/mask-with-added-filters-expected.png b/third_party/blink/web_tests/platform/win/compositing/masks/mask-with-added-filters-expected.png index dc4aeba..58dbaf5 100644 --- a/third_party/blink/web_tests/platform/win/compositing/masks/mask-with-added-filters-expected.png +++ b/third_party/blink/web_tests/platform/win/compositing/masks/mask-with-added-filters-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/css3/filters/backdrop-filter-basic-blur-expected.png b/third_party/blink/web_tests/platform/win/css3/filters/backdrop-filter-basic-blur-expected.png index c54dd913..ac1bb69 100644 --- a/third_party/blink/web_tests/platform/win/css3/filters/backdrop-filter-basic-blur-expected.png +++ b/third_party/blink/web_tests/platform/win/css3/filters/backdrop-filter-basic-blur-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/css3/filters/backdrop-filter-boundary-expected.png b/third_party/blink/web_tests/platform/win/css3/filters/backdrop-filter-boundary-expected.png index 43b42ae..8c65207 100644 --- a/third_party/blink/web_tests/platform/win/css3/filters/backdrop-filter-boundary-expected.png +++ b/third_party/blink/web_tests/platform/win/css3/filters/backdrop-filter-boundary-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/css3/filters/effect-brightness-clamping-hw-expected.png b/third_party/blink/web_tests/platform/win/css3/filters/effect-brightness-clamping-hw-expected.png index 279df41..40cbdbf9 100644 --- a/third_party/blink/web_tests/platform/win/css3/filters/effect-brightness-clamping-hw-expected.png +++ b/third_party/blink/web_tests/platform/win/css3/filters/effect-brightness-clamping-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/css3/filters/effect-drop-shadow-hw-expected.png b/third_party/blink/web_tests/platform/win/css3/filters/effect-drop-shadow-hw-expected.png index 3a264bf1..11abf63 100644 --- a/third_party/blink/web_tests/platform/win/css3/filters/effect-drop-shadow-hw-expected.png +++ b/third_party/blink/web_tests/platform/win/css3/filters/effect-drop-shadow-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/css3/filters/effect-reference-colorspace-hw-expected.png b/third_party/blink/web_tests/platform/win/css3/filters/effect-reference-colorspace-hw-expected.png index 5b04ab45..8c7dffb 100644 --- a/third_party/blink/web_tests/platform/win/css3/filters/effect-reference-colorspace-hw-expected.png +++ b/third_party/blink/web_tests/platform/win/css3/filters/effect-reference-colorspace-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/css3/filters/effect-reference-hw-expected.png b/third_party/blink/web_tests/platform/win/css3/filters/effect-reference-hw-expected.png index 00a8698..3c015c0 100644 --- a/third_party/blink/web_tests/platform/win/css3/filters/effect-reference-hw-expected.png +++ b/third_party/blink/web_tests/platform/win/css3/filters/effect-reference-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/css3/filters/effect-reference-subregion-hw-expected.png b/third_party/blink/web_tests/platform/win/css3/filters/effect-reference-subregion-hw-expected.png index ae534a2..862f967e 100644 --- a/third_party/blink/web_tests/platform/win/css3/filters/effect-reference-subregion-hw-expected.png +++ b/third_party/blink/web_tests/platform/win/css3/filters/effect-reference-subregion-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/css3/filters/effect-reference-zoom-hw-expected.png b/third_party/blink/web_tests/platform/win/css3/filters/effect-reference-zoom-hw-expected.png index 5cf6c25..2f9a8a12 100644 --- a/third_party/blink/web_tests/platform/win/css3/filters/effect-reference-zoom-hw-expected.png +++ b/third_party/blink/web_tests/platform/win/css3/filters/effect-reference-zoom-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/gpu/fast/canvas/canvas-shadow-source-in-expected.png b/third_party/blink/web_tests/platform/win/virtual/gpu/fast/canvas/canvas-shadow-source-in-expected.png index 3b33dcd..4ed3d43e 100644 --- a/third_party/blink/web_tests/platform/win/virtual/gpu/fast/canvas/canvas-shadow-source-in-expected.png +++ b/third_party/blink/web_tests/platform/win/virtual/gpu/fast/canvas/canvas-shadow-source-in-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/backdrop-filter-basic-blur-expected.png b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/backdrop-filter-basic-blur-expected.png index d91dbe77..9b3b040 100644 --- a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/backdrop-filter-basic-blur-expected.png +++ b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/backdrop-filter-basic-blur-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/backdrop-filter-boundary-expected.png b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/backdrop-filter-boundary-expected.png index 76217679..fd27e32 100644 --- a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/backdrop-filter-boundary-expected.png +++ b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/backdrop-filter-boundary-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/backdrop-filter-edge-pixels-expected.png b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/backdrop-filter-edge-pixels-expected.png index aaf28fe..220876a 100644 --- a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/backdrop-filter-edge-pixels-expected.png +++ b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/backdrop-filter-edge-pixels-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-all-on-background-hw-expected.png b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-all-on-background-hw-expected.png index dcca347..b5935ee0 100644 --- a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-all-on-background-hw-expected.png +++ b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-all-on-background-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-blur-hw-expected.png b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-blur-hw-expected.png index cfd9c58..1878c10 100644 --- a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-blur-hw-expected.png +++ b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-blur-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-brightness-clamping-hw-expected.png b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-brightness-clamping-hw-expected.png index 416be47..3bf1454 100644 --- a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-brightness-clamping-hw-expected.png +++ b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-brightness-clamping-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-combined-hw-expected.png b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-combined-hw-expected.png index b259b05..a61e756 100644 --- a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-combined-hw-expected.png +++ b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-combined-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-drop-shadow-hw-expected.png b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-drop-shadow-hw-expected.png index 9c968c85..3f6e10e6 100644 --- a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-drop-shadow-hw-expected.png +++ b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-drop-shadow-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-reference-colorspace-hw-expected.png b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-reference-colorspace-hw-expected.png index 8e43506..139ea8c4 100644 --- a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-reference-colorspace-hw-expected.png +++ b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-reference-colorspace-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-reference-hw-expected.png b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-reference-hw-expected.png index 1e7ca9ae..9ce0142 100644 --- a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-reference-hw-expected.png +++ b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-reference-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-reference-subregion-hw-expected.png b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-reference-subregion-hw-expected.png index 06584ca..a724b54 100644 --- a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-reference-subregion-hw-expected.png +++ b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-reference-subregion-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-reference-zoom-hw-expected.png b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-reference-zoom-hw-expected.png index 7c282583..5516872 100644 --- a/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-reference-zoom-hw-expected.png +++ b/third_party/blink/web_tests/platform/win/virtual/scalefactor200/css3/filters/effect-reference-zoom-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/virtual/gpu/fast/canvas/canvas-shadow-source-in-expected.png b/third_party/blink/web_tests/virtual/gpu/fast/canvas/canvas-shadow-source-in-expected.png deleted file mode 100644 index 36e326a..0000000 --- a/third_party/blink/web_tests/virtual/gpu/fast/canvas/canvas-shadow-source-in-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/backdrop-filter-basic-blur-expected.png b/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/backdrop-filter-basic-blur-expected.png deleted file mode 100644 index 24a2623..0000000 --- a/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/backdrop-filter-basic-blur-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/backdrop-filter-edge-clipping-2-expected.png b/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/backdrop-filter-edge-clipping-2-expected.png index 186e8a1..00cc84a7 100644 --- a/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/backdrop-filter-edge-clipping-2-expected.png +++ b/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/backdrop-filter-edge-clipping-2-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/effect-all-on-background-hw-expected.png b/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/effect-all-on-background-hw-expected.png deleted file mode 100644 index 32f7cc4..0000000 --- a/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/effect-all-on-background-hw-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/effect-brightness-clamping-hw-expected.png b/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/effect-brightness-clamping-hw-expected.png deleted file mode 100644 index 428a809..0000000 --- a/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/effect-brightness-clamping-hw-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/effect-combined-hw-expected.png b/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/effect-combined-hw-expected.png deleted file mode 100644 index deb7ab0..0000000 --- a/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/effect-combined-hw-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/effect-reference-hidpi-hw-expected.png b/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/effect-reference-hidpi-hw-expected.png deleted file mode 100644 index 08bad9d..0000000 --- a/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/effect-reference-hidpi-hw-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/effect-reference-ordering-hw-expected.png b/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/effect-reference-ordering-hw-expected.png index cc83415d..d47701c 100644 --- a/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/effect-reference-ordering-hw-expected.png +++ b/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/effect-reference-ordering-hw-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/filter-change-repaint-composited-expected.png b/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/filter-change-repaint-composited-expected.png index fdeb602..f4d15dce 100644 --- a/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/filter-change-repaint-composited-expected.png +++ b/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/filter-change-repaint-composited-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/filter-change-repaint-expected.png b/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/filter-change-repaint-expected.png index 0ce12565..ca5c1fa7 100644 --- a/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/filter-change-repaint-expected.png +++ b/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/filter-change-repaint-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/filter-repaint-composited-fallback-crash-expected.png b/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/filter-repaint-composited-fallback-crash-expected.png index 659a5071..40e8bcb 100644 --- a/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/filter-repaint-composited-fallback-crash-expected.png +++ b/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/filter-repaint-composited-fallback-crash-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/filter-repaint-composited-fallback-expected.png b/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/filter-repaint-composited-fallback-expected.png index 659a5071..40e8bcb 100644 --- a/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/filter-repaint-composited-fallback-expected.png +++ b/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/filter-repaint-composited-fallback-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/wpt_internal/serial/resources/automation.js b/third_party/blink/web_tests/wpt_internal/serial/resources/automation.js index 26053d1..5eec2f4 100644 --- a/third_party/blink/web_tests/wpt_internal/serial/resources/automation.js +++ b/third_party/blink/web_tests/wpt_internal/serial/resources/automation.js
@@ -114,13 +114,25 @@ }; } - bind(request) { - assert_equals(this.binding, undefined, 'Port is still open'); - this.binding = new mojo.Binding(device.mojom.SerialPort, - this, request); - this.binding.setConnectionErrorHandler(() => { + open(options, client) { + if (this.binding_ !== undefined) { + // Port already open. + return null; + } + + let portPtr = new device.mojom.SerialPortPtr(); + this.binding_ = new mojo.Binding( + device.mojom.SerialPort, this, mojo.makeRequest(portPtr)); + this.binding_.setConnectionErrorHandler(() => { this.close(); }); + + this.options_ = options; + this.client_ = client; + // OS typically sets DTR on open. + this.outputSignals_.dataTerminalReady = true; + + return portPtr; } write(data) { @@ -202,14 +214,6 @@ return this.readablePromise_; } - async open(options, client) { - this.options_ = options; - this.client_ = client; - // OS typically sets DTR on open. - this.outputSignals_.dataTerminalReady = true; - return { success: true }; - } - async startWriting(in_stream) { this.readable_ = new ReadableStream(new DataPipeSource(in_stream)); this.reader_ = this.readable_.getReader(); @@ -298,7 +302,11 @@ this.writer_ = undefined; } this.writable_ = undefined; - this.binding = undefined; + + if (this.binding_) { + this.binding_.close(); + this.binding_ = undefined; + } return {}; } } @@ -402,12 +410,12 @@ return { port: null }; } - async getPort(token, port_receiver) { + async openPort(token, options, client) { let record = this.ports_.get(token.low); if (record !== undefined) { - record.fakePort.bind(port_receiver); + return {port: record.fakePort.open(options, client)}; } else { - port_receiver.close(); + return {port: null}; } } }
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 97d0f47..4e4e308 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -22236,6 +22236,7 @@ <int value="789" label="DeviceFamilyLinkAccountsAllowed"/> <int value="790" label="EduCoexistenceToSVersion"/> <int value="791" label="BrowsingDataLifetime"/> + <int value="792" label="IntranetRedirectBehavior"/> </enum> <enum name="EnterprisePolicyDeviceIdValidity"> @@ -29600,9 +29601,9 @@ <int value="3399" label="MediaRecorder_MimeType"/> <int value="3400" label="MediaRecorder_VideoBitsPerSecond"/> <int value="3401" label="MediaRecorder_AudioBitsPerSecond"/> - <int value="3402" label="BluetoothRemoteGATTCharacteristic_Uuid"/> - <int value="3403" label="BluetoothRemoteGATTDescriptor_Uuid"/> - <int value="3404" label="BluetoothRemoteGATTService_Uuid"/> + <int value="3402" label="OBSOLETE_BluetoothRemoteGATTCharacteristic_Uuid"/> + <int value="3403" label="OBSOLETE_BluetoothRemoteGATTDescriptor_Uuid"/> + <int value="3404" label="OBSOLETE_BluetoothRemoteGATTService_Uuid"/> <int value="3405" label="GPUAdapter_Name"/> <int value="3406" label="WindowScreenInternal"/> <int value="3407" label="WindowScreenPrimary"/> @@ -30169,6 +30170,7 @@ without receiving a new consistency token"/> <int value="6" label="Upload attempt was aborted because the account is now signed-out"/> + <int value="7" label="Could not upload because does not meet conditions"/> </enum> <enum name="FeedUserActionType"> @@ -43689,6 +43691,7 @@ <int value="125934378" label="enable-password-link"/> <int value="127789400" label="PrivacyElevatedAndroid:enabled"/> <int value="128086566" label="D3D11VideoDecoder:enabled"/> + <int value="128323385" label="WebUIOmniboxPopup:enabled"/> <int value="129458360" label="LiteVideo:disabled"/> <int value="131881947" label="D3DVsync:enabled"/> <int value="132560299" @@ -44046,6 +44049,7 @@ <int value="513356954" label="InstantTethering:disabled"/> <int value="513372959" label="ViewsProfileChooser:enabled"/> <int value="513728926" label="OsSettingsPolymer3:enabled"/> + <int value="514406112" label="WebUIOmniboxPopup:disabled"/> <int value="514569020" label="RemoteCopyImageNotification:enabled"/> <int value="516603570" label="QuickAnswersRichUi:disabled"/> <int value="517429103" label="AutofillImportDynamicForms:enabled"/> @@ -65085,6 +65089,8 @@ <int value="9" label="EXTENDED_REPORTING_IS_ENABLED"/> <int value="10" label="REPORT_PHISHING_ERROR"/> <int value="11" label="SHOW_WHITEPAPER"/> + <int value="12" label="SHOW_ENHANCED_PROTECTION"/> + <int value="13" label="OPEN_ENHANCED_PROTECTION"/> </enum> <enum name="SecurityLevel">
diff --git a/tools/metrics/histograms/histograms_xml/chromeos/histograms.xml b/tools/metrics/histograms/histograms_xml/chromeos/histograms.xml index 350d650..cf53e4ab 100644 --- a/tools/metrics/histograms/histograms_xml/chromeos/histograms.xml +++ b/tools/metrics/histograms/histograms_xml/chromeos/histograms.xml
@@ -528,6 +528,16 @@ </summary> </histogram> +<histogram name="ChromeOS.Settings.Bluetooth.BluetoothOnOff" + enum="BooleanToggled" expires_after="2021-09-30"> + <owner>khorimoto@chromium.org</owner> + <owner>hsuregan@chromium.org</owner> + <owner>cros-customization@google.com</owner> + <summary> + Records when users change the kBluetoothOnOff setting on the Bluetooth page. + </summary> +</histogram> + <histogram name="ChromeOS.Settings.BlurredWindowDuration" units="ms" expires_after="2020-12-01"> <owner>khorimoto@chromium.org</owner> @@ -778,6 +788,19 @@ </summary> </histogram> +<histogram name="ChromeOS.Settings.SettingChanged" enum="OsSetting" + expires_after="2021-09-29"> + <owner>khorimoto@chromium.org</owner> + <owner>hsuregan@chromium.org</owner> + <owner>cros-customization@google.com</owner> + <summary> + Records the the setting id when the user changes a setting. Note that some + of the values of the OsSetting enum aren't strictly settings (such as + kKeyboardShortcuts, which is just a hyperlink). All of the recorded values + appear in the settings page. + </summary> +</histogram> + <histogram base="true" name="ChromeOS.Settings.TimeUntilChange" units="ms" expires_after="2021-04-04"> <!-- Name completed by histogram_suffixes name="OsSettingsChangeType" -->
diff --git a/tools/metrics/histograms/histograms_xml/service/histograms.xml b/tools/metrics/histograms/histograms_xml/service/histograms.xml index b53bb69..bf97b12b7 100644 --- a/tools/metrics/histograms/histograms_xml/service/histograms.xml +++ b/tools/metrics/histograms/histograms_xml/service/histograms.xml
@@ -387,7 +387,7 @@ </summary> </histogram> -<histogram name="ServiceWorker.InstallEvent.All.FetchCount" units="ms" +<histogram name="ServiceWorker.InstallEvent.All.FetchCount" units="fetches" expires_after="2021-10-01"> <owner>wanderview@chromium.org</owner> <owner>chrome-worker@google.com</owner>
diff --git a/tools/metrics/histograms/histograms_xml/tab/histograms.xml b/tools/metrics/histograms/histograms_xml/tab/histograms.xml index 24b16e37..04a9ddd5 100644 --- a/tools/metrics/histograms/histograms_xml/tab/histograms.xml +++ b/tools/metrics/histograms/histograms_xml/tab/histograms.xml
@@ -159,27 +159,6 @@ <summary>Records how a tab preview image was generated.</summary> </histogram> -<histogram name="Tab.Preview.MemoryUsage.CompressedData.PerThumbnailKiB" - units="KB" expires_after="M92"> - <owner>dfried@chromium.org</owner> - <owner>collinbaker@chromium.org</owner> - <summary> - Memory used by compressed thumbnails. Recorded once per thumbnail every 5 - minutes. - </summary> -</histogram> - -<histogram name="Tab.Preview.MemoryUsage.CompressedData.TotalKiB" units="KB" - expires_after="M92"> - <owner>dfried@chromium.org</owner> - <owner>collinbaker@chromium.org</owner> - <summary> - Memory used by compressed thumbnails. Recorded once every 5 minutes at the - same time as Tab.Preview.MemoryUsage.CompressedData.PerThumbnailKiB. Each - sample is the sum of the corresponding samples in PerThumbnailKiB. - </summary> -</histogram> - <histogram name="Tab.Preview.TimeToFirstUsableFrameAfterStartCapture" units="ms" expires_after="2020-12-15"> <owner>dfried@chromium.org</owner>
diff --git a/tools/perf/core/perfetto_binary_roller/binary_deps.json b/tools/perf/core/perfetto_binary_roller/binary_deps.json index 2741b26..2f71dcdb 100644 --- a/tools/perf/core/perfetto_binary_roller/binary_deps.json +++ b/tools/perf/core/perfetto_binary_roller/binary_deps.json
@@ -6,11 +6,11 @@ }, "mac": { "hash": "002f2269c464fd57c15cac6a921fad003228af1e", - "remote_path": "perfetto_binaries/trace_processor_shell/mac/0ad07c924552f3fb777e79ae04c5b3e925926388/trace_processor_shell" + "remote_path": "perfetto_binaries/trace_processor_shell/mac/815983783a765fa04e31bb514020fd1c55291a71/trace_processor_shell" }, "linux": { "hash": "5ee28a927ebcff327e0ef054a0fc33ea07dca9f7", - "remote_path": "perfetto_binaries/trace_processor_shell/linux/0ad07c924552f3fb777e79ae04c5b3e925926388/trace_processor_shell" + "remote_path": "perfetto_binaries/trace_processor_shell/linux/815983783a765fa04e31bb514020fd1c55291a71/trace_processor_shell" } }, "power_profile.sql": {
diff --git a/tools/perf/page_sets/rendering/simple_canvas_cases.py b/tools/perf/page_sets/rendering/simple_canvas_cases.py index a8af34f..a35815f 100644 --- a/tools/perf/page_sets/rendering/simple_canvas_cases.py +++ b/tools/perf/page_sets/rendering/simple_canvas_cases.py
@@ -164,7 +164,26 @@ class VideoToSubTexture(SimpleCanvasPage): BASE_NAME = 'video_to_sub_texture' - URL = 'file://../simple_canvas/video_to_sub_texture.html' + # pylint: disable=line-too-long + URL = 'file://../simple_canvas/video_to_sub_texture.html?flip_y=false&premult=false' + + +class VideoToSubTextureFlipY(SimpleCanvasPage): + BASE_NAME = 'video_to_sub_texture_flip_y' + # pylint: disable=line-too-long + URL = 'file://../simple_canvas/video_to_sub_texture.html?flip_y=true&premult=false' + + +class VideoToSubTexturePremultiply(SimpleCanvasPage): + BASE_NAME = 'video_to_sub_texture_premultiply' + # pylint: disable=line-too-long + URL = 'file://../simple_canvas/video_to_sub_texture.html?flip_y=false&premult=true' + + +class VideoToSubTextureFlipAndPremultiply(SimpleCanvasPage): + BASE_NAME = 'video_to_sub_texture_flip_and_premultiply' + # pylint: disable=line-too-long + URL = 'file://../simple_canvas/video_to_sub_texture.html?flip_y=true&premult=true' class VideoToTexture(SimpleCanvasPage):
diff --git a/tools/perf/page_sets/simple_canvas/video_to_sub_texture.html b/tools/perf/page_sets/simple_canvas/video_to_sub_texture.html index 6a5dc8d8..81c376ba8 100644 --- a/tools/perf/page_sets/simple_canvas/video_to_sub_texture.html +++ b/tools/perf/page_sets/simple_canvas/video_to_sub_texture.html
@@ -19,39 +19,39 @@ canvas3D.height = height; } +function getArgValue(argname) { + const queryString = window.location.search; + const urlParams = new URLSearchParams(queryString); + var result = urlParams.get(argname); + if (!result) { + return false; + } + return result === "true"; +} + function startPerfTest() { preRun(); perfTest(); } function perfTest() { - for (i = 0; i < 10; i++) { - doRun(); - } + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiply); + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, videoElement); gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4)); requestAnimationFrame(perfTest); } -var flipYAndPremultipyAlphas = - [[ false, false ], - [ false, true ], - [ true, false ], - [ true, true ]]; -var optionIndex = 0; +var flipY = false; +var premultiply = false; var tex = null; function preRun() { tex = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, tex); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, videoElement.videoWidth, videoElement.videoHeight, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); - optionIndex = 0; -} - -function doRun() { - var i = optionIndex++ % flipYAndPremultipyAlphas.length; - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipYAndPremultipyAlphas[i][0]); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, flipYAndPremultipyAlphas[i][1]); - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, videoElement); + flipY = getArgValue('flip_y'); + premultiply = getArgValue('premult'); } window.onload = function () {
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_kk.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_kk.xtb index 34843b8d..cb9fa99 100644 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_kk.xtb +++ b/ui/accessibility/extensions/strings/accessibility_extensions_strings_kk.xtb
@@ -64,5 +64,5 @@ <translation id="8321034316479930120">Анимация саясаты</translation> <translation id="8480209185614411573">Жоғары контраст</translation> <translation id="8609925175482059018">Белсенді курсор режимін іске қосу үшін <span class='key'>F7</span> басыңыз. Оны өшіру үшін осы пернені қайта басыңыз.</translation> -<translation id="894241283505723656">Мәнмәтіндік мәзірдегі ұзақ сипаттамалар</translation> +<translation id="894241283505723656">Контекстік мәзірдегі ұзақ сипаттамалар</translation> </translationbundle> \ No newline at end of file
diff --git a/ui/gl/direct_composition_child_surface_win.cc b/ui/gl/direct_composition_child_surface_win.cc index ee62906..5ec0bad 100644 --- a/ui/gl/direct_composition_child_surface_win.cc +++ b/ui/gl/direct_composition_child_surface_win.cc
@@ -7,6 +7,8 @@ #include <d3d11_1.h> #include <dcomptypes.h> +#include "base/debug/alias.h" +#include "base/debug/dump_without_crashing.h" #include "base/macros.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" @@ -199,8 +201,12 @@ base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED); hr = dxgi_device2->EnqueueSetEvent(event.handle()); - DCHECK(SUCCEEDED(hr)); - event.Wait(); + if (SUCCEEDED(hr)) { + event.Wait(); + } else { + base::debug::Alias(&hr); + base::debug::DumpWithoutCrashing(); + } } } }
diff --git a/ui/gl/swap_chain_presenter.cc b/ui/gl/swap_chain_presenter.cc index fb357a0..b0f4a37 100644 --- a/ui/gl/swap_chain_presenter.cc +++ b/ui/gl/swap_chain_presenter.cc
@@ -7,6 +7,8 @@ #include <d3d11_1.h> #include <d3d11_4.h> +#include "base/debug/alias.h" +#include "base/debug/dump_without_crashing.h" #include "base/feature_list.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" @@ -889,8 +891,12 @@ base::WaitableEvent event(base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED); hr = dxgi_device2->EnqueueSetEvent(event.handle()); - DCHECK(SUCCEEDED(hr)); - event.Wait(); + if (SUCCEEDED(hr)) { + event.Wait(); + } else { + base::debug::Alias(&hr); + base::debug::DumpWithoutCrashing(); + } } const bool use_swap_chain_tearing = DirectCompositionSurfaceWin::AllowTearing();
diff --git a/ui/views/view_unittest.cc b/ui/views/view_unittest.cc index bdb839da..a62995b 100644 --- a/ui/views/view_unittest.cc +++ b/ui/views/view_unittest.cc
@@ -2417,90 +2417,6 @@ } #endif // OS_APPLE -// TODO(crbug.com/667757): these tests were initially commented out when getting -// aura to run. Figure out if still valuable and either nuke or fix. -#if 0 -//////////////////////////////////////////////////////////////////////////////// -// Mouse-wheel message rerouting -//////////////////////////////////////////////////////////////////////////////// -class ScrollableTestView : public View { - public: - ScrollableTestView() { } - - virtual gfx::Size GetPreferredSize() { - return gfx::Size(100, 10000); - } - - virtual void Layout() { - SizeToPreferredSize(); - } -}; - -class TestViewWithControls : public View { - public: - TestViewWithControls() { - text_field_ = new Textfield(); - AddChildView(text_field_); - } - - Textfield* text_field_; -}; - -class SimpleWidgetDelegate : public WidgetDelegate { - public: - explicit SimpleWidgetDelegate(View* contents) : contents_(contents) { } - - virtual void DeleteDelegate() { delete this; } - - virtual View* GetContentsView() { return contents_; } - - virtual Widget* GetWidget() { return contents_->GetWidget(); } - virtual const Widget* GetWidget() const { return contents_->GetWidget(); } - - private: - View* contents_; -}; - -// Tests that the mouse-wheel messages are correctly rerouted to the window -// under the mouse. -// TODO(jcampan): http://crbug.com/10572 Disabled as it fails on the Vista build -// bot. -// Note that this fails for a variety of reasons: -// - focused view is apparently reset across window activations and never -// properly restored -// - this test depends on you not having any other window visible open under the -// area that it opens the test windows. --beng -TEST_F(ViewTest, DISABLED_RerouteMouseWheelTest) { - TestViewWithControls* view_with_controls = new TestViewWithControls(); - Widget* window1 = Widget::CreateWindowWithBounds( - new SimpleWidgetDelegate(view_with_controls), - gfx::Rect(0, 0, 100, 100)); - window1->Show(); - ScrollView* scroll_view = new ScrollView(); - scroll_view->SetContents(new ScrollableTestView()); - Widget* window2 = Widget::CreateWindowWithBounds( - new SimpleWidgetDelegate(scroll_view), - gfx::Rect(200, 200, 100, 100)); - window2->Show(); - EXPECT_EQ(0, scroll_view->GetVisibleRect().y()); - - // Make the window1 active, as this is what it would be in real-world. - window1->Activate(); - - // Let's send a mouse-wheel message to the different controls and check that - // it is rerouted to the window under the mouse (effectively scrolling the - // scroll-view). - - // First to the Window's HWND. - ::SendMessage(view_with_controls->GetWidget()->GetNativeView(), - WM_MOUSEWHEEL, MAKEWPARAM(0, -20), MAKELPARAM(250, 250)); - EXPECT_EQ(20, scroll_view->GetVisibleRect().y()); - - window1->CloseNow(); - window2->CloseNow(); -} -#endif // 0 - //////////////////////////////////////////////////////////////////////////////// // Native view hierachy ////////////////////////////////////////////////////////////////////////////////
diff --git a/ui/views/widget/native_widget_mac_unittest.mm b/ui/views/widget/native_widget_mac_unittest.mm index f2f744f..41ef0a06 100644 --- a/ui/views/widget/native_widget_mac_unittest.mm +++ b/ui/views/widget/native_widget_mac_unittest.mm
@@ -401,56 +401,6 @@ DISALLOW_COPY_AND_ASSIGN(PaintCountView); }; -// Test for correct child window restore when parent window is minimized -// and restored using -makeKeyAndOrderFront:. -// Parent-child window relationships in AppKit are not supported when window -// visibility changes. -// Disabled because it relies on cocoa occlusion APIs -// and state changes that are unavoidably flaky. -TEST_F(NativeWidgetMacTest, DISABLED_OrderFrontAfterMiniaturize) { - Widget* widget = CreateTopLevelPlatformWidget(); - NSWindow* ns_window = widget->GetNativeWindow().GetNativeNSWindow(); - - Widget* child_widget = CreateChildPlatformWidget(widget->GetNativeView()); - NSWindow* child_ns_window = - child_widget->GetNativeWindow().GetNativeNSWindow(); - - // Set parent bounds that overlap child. - widget->SetBounds(gfx::Rect(100, 100, 300, 300)); - child_widget->SetBounds(gfx::Rect(110, 110, 100, 100)); - - widget->Show(); - base::RunLoop().RunUntilIdle(); - - EXPECT_FALSE(widget->IsMinimized()); - - // Minimize parent. - [ns_window performMiniaturize:nil]; - base::RunLoop().RunUntilIdle(); - - EXPECT_TRUE(widget->IsMinimized()); - EXPECT_FALSE(widget->IsVisible()); - EXPECT_FALSE(child_widget->IsVisible()); - - // Restore parent window as AppController does. - [ns_window makeKeyAndOrderFront:nil]; - - // Wait and check that child is really visible. - // TODO(kirr): remove the fixed delay. - base::RunLoop run_loop; - base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, run_loop.QuitWhenIdleClosure(), - base::TimeDelta::FromSeconds(2)); - run_loop.Run(); - - EXPECT_FALSE(widget->IsMinimized()); - EXPECT_TRUE(widget->IsVisible()); - EXPECT_TRUE(child_widget->IsVisible()); - // Check that child window is visible. - EXPECT_TRUE([child_ns_window occlusionState] & NSWindowOcclusionStateVisible); - EXPECT_TRUE(IsWindowStackedAbove(child_widget, widget)); - widget->Close(); -} // Test that a child widget is only added to its parent NSWindow when the // parent is on the active space. Otherwise, it may cause a space transition. @@ -879,26 +829,6 @@ EXPECT_TRUE(native_parent_dealloced); } -// Tests visibility for child of native NSWindow, reshowing after -[NSApp hide]. -// Occasionally flaky (maybe due to [NSApp hide]). See https://crbug.com/777247. -TEST_F(NativeWidgetMacTest, DISABLED_VisibleAfterNativeParentShow) { - NSWindow* native_parent = MakeBorderlessNativeParent(); - Widget* child = AttachPopupToNativeParent(native_parent); - child->Show(); - EXPECT_TRUE(child->IsVisible()); - - WidgetChangeObserver child_observer(child); - [NSApp hide:nil]; - child_observer.WaitForVisibleCounts(0, 1); - EXPECT_FALSE(child->IsVisible()); - - [native_parent makeKeyAndOrderFront:nil]; - child_observer.WaitForVisibleCounts(1, 1); - EXPECT_TRUE(child->IsVisible()); - - [native_parent close]; -} - // Tests visibility for a child of a native NSWindow, reshowing after a // deminiaturize on the parent window (after attempting to show the child while // the parent was miniaturized).
diff --git a/ui/webui/resources/tools/generate_grd.gni b/ui/webui/resources/tools/generate_grd.gni index 405871b..1caec6f 100644 --- a/ui/webui/resources/tools/generate_grd.gni +++ b/ui/webui/resources/tools/generate_grd.gni
@@ -11,6 +11,10 @@ } inputs = invoker.manifest_files + if (defined(invoker.input_files)) { + inputs += invoker.input_files + } + outputs = [ invoker.out_grd ] args = [ @@ -22,5 +26,13 @@ rebase_path(root_gen_dir, root_build_dir), "--manifest-files", ] + rebase_path(invoker.manifest_files, root_build_dir) + + if (defined(invoker.input_files)) { + args += [ + "--input-files-base-dir", + invoker.input_files_base_dir, + ] + args += [ "--input-files" ] + invoker.input_files + } } }
diff --git a/ui/webui/resources/tools/generate_grd.py b/ui/webui/resources/tools/generate_grd.py index 8a70741..e48369e 100644 --- a/ui/webui/resources/tools/generate_grd.py +++ b/ui/webui/resources/tools/generate_grd.py
@@ -29,6 +29,14 @@ # from the root generated directory for setting file paths, as grd files # with generated file paths must specify these paths as # "${root_gen_dir}/<path_to_file>" +# +# input_files: +# List of file paths (from |input_files_base_dir|) that are not included in +# any manifest files, but should be added to the grd. +# +# input_files_base_dir: +# The base directory for the paths in |input_files|. |input_files| and +# |input_files_base_dir| must either both be provided or both be omitted. import argparse import json @@ -56,38 +64,65 @@ ' <includes>\n' GRD_INCLUDE_TEMPLATE = ' <include name="{name}" ' \ - 'file="${{root_gen_dir}}/{path_from_gen}" ' \ - 'resource_path="{path}" use_base_dir="false" ' \ - 'type="BINDATA" />\n' + 'file="{file}" resource_path="{path}" ' \ + 'use_base_dir="false" type="{type}" />\n' GRD_END_TEMPLATE = ' </includes>\n'\ ' </release>\n'\ '</grit>\n' + +# Generates an <include .... /> row for the given file. +def _generate_include_row(grd_prefix, filename, pathname): + name_suffix = filename.upper().replace('/', '_').replace('.', '_') + name = 'IDR_%s_%s' % (grd_prefix.upper(), name_suffix) + extension = os.path.splitext(filename)[1] + type = 'chrome_html' if extension == '.html' or extension == '.js' \ + else 'BINDATA' + resource_path = filename + # Remove 'rollup' from *.rollup.js paths, except for shared.rollup.js. + # Possibly pass such replacements from the gni file, if this ends up not being + # sufficient for all cases. + if ('rollup' in resource_path and 'shared' not in resource_path): + resource_path = resource_path.replace('rollup.', '') + return GRD_INCLUDE_TEMPLATE.format( + file=pathname, + path=resource_path, + name=name, + type=type) + + def main(argv): parser = argparse.ArgumentParser() parser.add_argument('--manifest-files', required=True, nargs="*") parser.add_argument('--out-grd', required=True) parser.add_argument('--grd-prefix', required=True) parser.add_argument('--root-gen-dir', required=True) + parser.add_argument('--input-files', nargs="*") + parser.add_argument('--input-files-base-dir') args = parser.parse_args(argv) grd_file = open(os.path.normpath(os.path.join(_CWD, args.out_grd)), 'w') grd_file.write(GRD_BEGIN_TEMPLATE.format(prefix=args.grd_prefix)) + if args.input_files != None: + assert(args.input_files_base_dir) + for filename in args.input_files: + filepath = os.path.join( + args.input_files_base_dir, filename).replace('\\', '/') + grd_file.write(_generate_include_row( + args.grd_prefix, filename, '${root_src_dir}/' + filepath)) + for manifest_file in args.manifest_files: manifest_path = os.path.normpath(os.path.join(_CWD, manifest_file)) with open(manifest_path, 'r') as f: data = json.load(f) base_dir= os.path.normpath(os.path.join(_CWD, data['base_dir'])) for filename in data['files']: - name_suffix = filename.upper().replace('/', '_').replace('.', '_') - name = 'IDR_%s_%s' % (args.grd_prefix.upper(), name_suffix) filepath = os.path.join(base_dir, filename).replace('\\', '/') rebased_path = os.path.relpath(filepath, args.root_gen_dir) - grd_file.write(GRD_INCLUDE_TEMPLATE.format(name=name, - path=filename, - path_from_gen=rebased_path)) + grd_file.write(_generate_include_row( + args.grd_prefix, filename, '${root_gen_dir}/' + rebased_path)) grd_file.write(GRD_END_TEMPLATE) return
diff --git a/ui/webui/resources/tools/generate_grd_test.py b/ui/webui/resources/tools/generate_grd_test.py index 3549cdc..ed0a161 100755 --- a/ui/webui/resources/tools/generate_grd_test.py +++ b/ui/webui/resources/tools/generate_grd_test.py
@@ -26,7 +26,8 @@ assert self._out_folder return open(os.path.join(self._out_folder, file_name), 'rb').read() - def _run_test_(self, manifest_files, grd_expected): + def _run_test_(self, grd_expected, manifest_files, input_files=None, + input_files_base_dir=None): assert not self._out_folder self._out_folder = tempfile.mkdtemp(dir=_HERE_DIR) args = [ @@ -36,6 +37,14 @@ '--manifest-files', ] + manifest_files + if (input_files_base_dir): + args += [ + '--input-files-base-dir', + input_files_base_dir, + '--input-files', + ] + args += input_files + generate_grd.main(args) actual_grd = self._read_out_file('test_resources.grd') @@ -44,10 +53,23 @@ self.assertEquals(expected_grd, actual_grd) def testSuccess(self): - self._run_test_([ + self._run_test_( + 'expected_grd.grd', + [ os.path.join(pathToHere, 'tests', 'test_manifest_1.json'), os.path.join(pathToHere, 'tests', 'test_manifest_2.json'), - ], 'expected_grd.grd') + ]) + + def testSuccessWithInputFiles(self): + self._run_test_( + 'expected_grd_with_input_files.grd', + [ + os.path.join(pathToHere, 'tests', 'test_manifest_1.json'), + os.path.join(pathToHere, 'tests', 'test_manifest_2.json'), + ], + [ 'images/test_svg.svg', 'test_html_in_src.html' ], + 'test_src_dir') + if __name__ == '__main__': unittest.main()
diff --git a/ui/webui/resources/tools/tests/expected_grd.grd b/ui/webui/resources/tools/tests/expected_grd.grd index ea0e2642..c739e85 100644 --- a/ui/webui/resources/tools/tests/expected_grd.grd +++ b/ui/webui/resources/tools/tests/expected_grd.grd
@@ -12,12 +12,13 @@ </outputs> <release seq="1"> <includes> - <include name="IDR_TEST_TEST_HTML" file="${root_gen_dir}/preprocessed/test.html" resource_path="test.html" use_base_dir="false" type="BINDATA" /> - <include name="IDR_TEST_TEST_JS" file="${root_gen_dir}/preprocessed/test.js" resource_path="test.js" use_base_dir="false" type="BINDATA" /> - <include name="IDR_TEST_DIR_ELEMENT_IN_DIR_JS" file="${root_gen_dir}/preprocessed/dir/element_in_dir.js" resource_path="dir/element_in_dir.js" use_base_dir="false" type="BINDATA" /> - <include name="IDR_TEST_TEST_UI_JS" file="${root_gen_dir}/preprocessed/test_ui.js" resource_path="test_ui.js" use_base_dir="false" type="BINDATA" /> - <include name="IDR_TEST_TEST_PROXY_JS" file="${root_gen_dir}/preprocessed/test_proxy.js" resource_path="test_proxy.js" use_base_dir="false" type="BINDATA" /> - <include name="IDR_TEST_DIR_ANOTHER_ELEMENT_IN_DIR_JS" file="${root_gen_dir}/preprocessed/dir/another_element_in_dir.js" resource_path="dir/another_element_in_dir.js" use_base_dir="false" type="BINDATA" /> + <include name="IDR_TEST_TEST_HTML" file="${root_gen_dir}/preprocessed/test.html" resource_path="test.html" use_base_dir="false" type="chrome_html" /> + <include name="IDR_TEST_TEST_ROLLUP_JS" file="${root_gen_dir}/preprocessed/test.rollup.js" resource_path="test.js" use_base_dir="false" type="chrome_html" /> + <include name="IDR_TEST_DIR_ELEMENT_IN_DIR_JS" file="${root_gen_dir}/preprocessed/dir/element_in_dir.js" resource_path="dir/element_in_dir.js" use_base_dir="false" type="chrome_html" /> + <include name="IDR_TEST_DIR_TEST_SVG_SVG" file="${root_gen_dir}/preprocessed/dir/test_svg.svg" resource_path="dir/test_svg.svg" use_base_dir="false" type="BINDATA" /> + <include name="IDR_TEST_TEST_UI_JS" file="${root_gen_dir}/preprocessed/test_ui.js" resource_path="test_ui.js" use_base_dir="false" type="chrome_html" /> + <include name="IDR_TEST_TEST_PROXY_JS" file="${root_gen_dir}/preprocessed/test_proxy.js" resource_path="test_proxy.js" use_base_dir="false" type="chrome_html" /> + <include name="IDR_TEST_DIR_ANOTHER_ELEMENT_IN_DIR_JS" file="${root_gen_dir}/preprocessed/dir/another_element_in_dir.js" resource_path="dir/another_element_in_dir.js" use_base_dir="false" type="chrome_html" /> </includes> </release> </grit>
diff --git a/ui/webui/resources/tools/tests/expected_grd_with_input_files.grd b/ui/webui/resources/tools/tests/expected_grd_with_input_files.grd new file mode 100644 index 0000000..0ea27c8 --- /dev/null +++ b/ui/webui/resources/tools/tests/expected_grd_with_input_files.grd
@@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<grit latest_public_release="0" current_release="1" output_all_resource_defines="false"> + <outputs> + <output filename="grit/test_resources.h" type="rc_header"> + <emit emit_type='prepend'></emit> + </output> + <output filename="grit/test_resources_map.cc" + type="resource_file_map_source" /> + <output filename="grit/test_resources_map.h" + type="resource_map_header" /> + <output filename="test_resources.pak" type="data_package" /> + </outputs> + <release seq="1"> + <includes> + <include name="IDR_TEST_IMAGES_TEST_SVG_SVG" file="${root_src_dir}/test_src_dir/images/test_svg.svg" resource_path="images/test_svg.svg" use_base_dir="false" type="BINDATA" /> + <include name="IDR_TEST_TEST_HTML_IN_SRC_HTML" file="${root_src_dir}/test_src_dir/test_html_in_src.html" resource_path="test_html_in_src.html" use_base_dir="false" type="chrome_html" /> + <include name="IDR_TEST_TEST_HTML" file="${root_gen_dir}/preprocessed/test.html" resource_path="test.html" use_base_dir="false" type="chrome_html" /> + <include name="IDR_TEST_TEST_ROLLUP_JS" file="${root_gen_dir}/preprocessed/test.rollup.js" resource_path="test.js" use_base_dir="false" type="chrome_html" /> + <include name="IDR_TEST_DIR_ELEMENT_IN_DIR_JS" file="${root_gen_dir}/preprocessed/dir/element_in_dir.js" resource_path="dir/element_in_dir.js" use_base_dir="false" type="chrome_html" /> + <include name="IDR_TEST_DIR_TEST_SVG_SVG" file="${root_gen_dir}/preprocessed/dir/test_svg.svg" resource_path="dir/test_svg.svg" use_base_dir="false" type="BINDATA" /> + <include name="IDR_TEST_TEST_UI_JS" file="${root_gen_dir}/preprocessed/test_ui.js" resource_path="test_ui.js" use_base_dir="false" type="chrome_html" /> + <include name="IDR_TEST_TEST_PROXY_JS" file="${root_gen_dir}/preprocessed/test_proxy.js" resource_path="test_proxy.js" use_base_dir="false" type="chrome_html" /> + <include name="IDR_TEST_DIR_ANOTHER_ELEMENT_IN_DIR_JS" file="${root_gen_dir}/preprocessed/dir/another_element_in_dir.js" resource_path="dir/another_element_in_dir.js" use_base_dir="false" type="chrome_html" /> + </includes> + </release> +</grit>
diff --git a/ui/webui/resources/tools/tests/test_manifest_1.json b/ui/webui/resources/tools/tests/test_manifest_1.json index e78390e4..d6771e4 100644 --- a/ui/webui/resources/tools/tests/test_manifest_1.json +++ b/ui/webui/resources/tools/tests/test_manifest_1.json
@@ -1 +1 @@ -{"files": ["test.html", "test.js", "dir/element_in_dir.js"], "base_dir": "tools/tests/preprocessed" } +{"files": ["test.html", "test.rollup.js", "dir/element_in_dir.js", "dir/test_svg.svg"], "base_dir": "tools/tests/preprocessed" }
diff --git a/weblayer/browser/java/BUILD.gn b/weblayer/browser/java/BUILD.gn index ef3cee8f..52cc7e5 100644 --- a/weblayer/browser/java/BUILD.gn +++ b/weblayer/browser/java/BUILD.gn
@@ -51,7 +51,6 @@ java_cpp_template("resource_id_javagen") { sources = [ "ResourceId.template" ] - package_path = "org/chromium/weblayer_private/resources" inputs = [ "//components/resources/android/blocked_content_resource_id.h", "//components/resources/android/page_info_resource_id.h",
diff --git a/weblayer/browser/java/org/chromium/weblayer_private/BrowserImpl.java b/weblayer/browser/java/org/chromium/weblayer_private/BrowserImpl.java index f9996627..4ad1e97 100644 --- a/weblayer/browser/java/org/chromium/weblayer_private/BrowserImpl.java +++ b/weblayer/browser/java/org/chromium/weblayer_private/BrowserImpl.java
@@ -240,8 +240,10 @@ @Override public TabImpl createTab() { - TabImpl tab = new TabImpl(mProfile, mWindowAndroid); - addTab(tab); + TabImpl tab = new TabImpl(this, mProfile, mWindowAndroid); + // This needs |alwaysAdd| set to true as the Tab is created with the Browser already set to + // this. + addTab(tab, /* alwaysAdd */ true); return tab; } @@ -291,14 +293,17 @@ @Override public void addTab(ITab iTab) { StrictModeWorkaround.apply(); - TabImpl tab = (TabImpl) iTab; - if (tab.getBrowser() == this) return; + addTab((TabImpl) iTab, /* alwaysAdd */ false); + } + + private void addTab(TabImpl tab, boolean alwaysAdd) { + if (!alwaysAdd && tab.getBrowser() == this) return; BrowserImplJni.get().addTab(mNativeBrowser, tab.getNativeTab()); } @CalledByNative private void createJavaTabForNativeTab(long nativeTab) { - new TabImpl(mProfile, mWindowAndroid, nativeTab); + new TabImpl(this, mProfile, mWindowAndroid, nativeTab); } private void checkPreferences() { @@ -365,36 +370,23 @@ } @CalledByNative - private void onTabAdded(TabImpl tab) { + private void onTabAdded(TabImpl tab) throws RemoteException { tab.attachToBrowser(this); - try { - if (mClient != null) mClient.onTabAdded(tab); - } catch (RemoteException e) { - throw new APICallException(e); - } + if (mClient != null) mClient.onTabAdded(tab); } @CalledByNative - private void onActiveTabChanged(TabImpl tab) { + private void onActiveTabChanged(TabImpl tab) throws RemoteException { if (mViewController != null) mViewController.setActiveTab(tab); - if (mInDestroy) return; - try { - if (mClient != null) { - mClient.onActiveTabChanged(tab != null ? tab.getId() : 0); - } - } catch (RemoteException e) { - throw new APICallException(e); + if (!mInDestroy && mClient != null) { + mClient.onActiveTabChanged(tab != null ? tab.getId() : 0); } } @CalledByNative - private void onTabRemoved(TabImpl tab) { + private void onTabRemoved(TabImpl tab) throws RemoteException { if (mInDestroy) return; - try { - if (mClient != null) mClient.onTabRemoved(tab.getId()); - } catch (RemoteException e) { - throw new APICallException(e); - } + if (mClient != null) mClient.onTabRemoved(tab.getId()); // This doesn't reset state on TabImpl as |browser| is either about to be // destroyed, or switching to a different fragment. }
diff --git a/weblayer/browser/java/org/chromium/weblayer_private/CookieManagerImpl.java b/weblayer/browser/java/org/chromium/weblayer_private/CookieManagerImpl.java index e2c56cc..ba3e80a 100644 --- a/weblayer/browser/java/org/chromium/weblayer_private/CookieManagerImpl.java +++ b/weblayer/browser/java/org/chromium/weblayer_private/CookieManagerImpl.java
@@ -11,7 +11,6 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.NativeMethods; -import org.chromium.weblayer_private.interfaces.APICallException; import org.chromium.weblayer_private.interfaces.CookieChangeCause; import org.chromium.weblayer_private.interfaces.ICookieChangedCallbackClient; import org.chromium.weblayer_private.interfaces.ICookieManager; @@ -73,13 +72,9 @@ } @CalledByNative - private static void onCookieChange( - ICookieChangedCallbackClient callback, String cookie, int cause) { - try { - callback.onCookieChanged(cookie, mojoCauseToJavaType(cause)); - } catch (RemoteException e) { - throw new APICallException(e); - } + private static void onCookieChange(ICookieChangedCallbackClient callback, String cookie, + int cause) throws RemoteException { + callback.onCookieChanged(cookie, mojoCauseToJavaType(cause)); } @CookieChangeCause
diff --git a/weblayer/browser/java/org/chromium/weblayer_private/TabImpl.java b/weblayer/browser/java/org/chromium/weblayer_private/TabImpl.java index abd41af..5f862a7 100644 --- a/weblayer/browser/java/org/chromium/weblayer_private/TabImpl.java +++ b/weblayer/browser/java/org/chromium/weblayer_private/TabImpl.java
@@ -19,6 +19,7 @@ import android.view.autofill.AutofillValue; import android.webkit.ValueCallback; +import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; @@ -101,9 +102,8 @@ private FullscreenCallbackProxy mFullscreenCallbackProxy; private TabViewAndroidDelegate mViewAndroidDelegate; private GoogleAccountsCallbackProxy mGoogleAccountsCallbackProxy; - // BrowserImpl this TabImpl is in. This is null before attached to a Browser. While this is null - // before attached, there are code paths that may trigger calling methods before set. - @Nullable + // BrowserImpl this TabImpl is in. + @NonNull private BrowserImpl mBrowser; private LoginPrompt mLoginPrompt; /** @@ -238,7 +238,8 @@ return sTabMap.get(tabId); } - public TabImpl(ProfileImpl profile, WindowAndroid windowAndroid) { + public TabImpl(BrowserImpl browser, ProfileImpl profile, WindowAndroid windowAndroid) { + mBrowser = browser; mId = ++sNextId; init(profile, windowAndroid, TabImplJni.get().createTab(profile.getNativeProfile(), this)); } @@ -247,8 +248,10 @@ * This constructor is called when the native side triggers creation of a TabImpl * (as happens with popups and other scenarios). */ - public TabImpl(ProfileImpl profile, WindowAndroid windowAndroid, long nativeTab) { + public TabImpl( + BrowserImpl browser, ProfileImpl profile, WindowAndroid windowAndroid, long nativeTab) { mId = ++sNextId; + mBrowser = browser; TabImplJni.get().setJavaImpl(nativeTab, TabImpl.this); init(profile, windowAndroid, nativeTab); } @@ -336,6 +339,9 @@ * Sets the BrowserImpl this TabImpl is contained in. */ public void attachToBrowser(BrowserImpl browser) { + // NOTE: during tab creation this is called with |mBrowser| set to |browser|. This happens + // because the tab is created with |mBrowser| already set (to avoid having a bunch of null + // checks). mBrowser = browser; updateFromBrowser(); } @@ -418,7 +424,6 @@ public void onAttachedToViewController( long topControlsContainerViewHandle, long bottomControlsContainerViewHandle) { // attachToFragment() must be called before activate(). - assert mBrowser != null; TabImplJni.get().setBrowserControlsContainerViews( mNativeTab, topControlsContainerViewHandle, bottomControlsContainerViewHandle); mInfoBarContainer.onTabAttachedToViewController(); @@ -459,7 +464,7 @@ } private boolean isActiveTab() { - return mBrowser != null && mBrowser.getActiveTab() == this; + return mBrowser.getActiveTab() == this; } private void updateWebContentsVisibility() { @@ -799,16 +804,12 @@ } @CalledByNative - private void onFindResultAvailable( - int numberOfMatches, int activeMatchOrdinal, boolean finalUpdate) { - try { - if (mFindInPageCallbackClient != null) { - // The WebLayer API deals in indices instead of ordinals. - mFindInPageCallbackClient.onFindResult( - numberOfMatches, activeMatchOrdinal - 1, finalUpdate); - } - } catch (RemoteException e) { - throw new AndroidRuntimeException(e); + private void onFindResultAvailable(int numberOfMatches, int activeMatchOrdinal, + boolean finalUpdate) throws RemoteException { + if (mFindInPageCallbackClient != null) { + // The WebLayer API deals in indices instead of ordinals. + mFindInPageCallbackClient.onFindResult( + numberOfMatches, activeMatchOrdinal - 1, finalUpdate); } if (mFindResultBar != null) { @@ -1043,8 +1044,6 @@ } private void onBrowserControlsConstraintUpdated(int constraint) { - // WARNING: this may be called before attached. This means |mBrowser| may be null. - // If something has overridden the FIP's SHOWN constraint, cancel FIP. This causes FIP to // dismiss when entering fullscreen. if (constraint != BrowserControlsState.SHOWN) {
diff --git a/weblayer/browser/java/org/chromium/weblayer_private/WebMessageReplyProxyImpl.java b/weblayer/browser/java/org/chromium/weblayer_private/WebMessageReplyProxyImpl.java index d639a42..980275d0e 100644 --- a/weblayer/browser/java/org/chromium/weblayer_private/WebMessageReplyProxyImpl.java +++ b/weblayer/browser/java/org/chromium/weblayer_private/WebMessageReplyProxyImpl.java
@@ -44,22 +44,14 @@ } @CalledByNative - private void onNativeDestroyed() { + private void onNativeDestroyed() throws RemoteException { mNativeWebMessageReplyProxyImpl = 0; - try { - mClient.onReplyProxyDestroyed(mId); - } catch (RemoteException e) { - throw new APICallException(e); - } + mClient.onReplyProxyDestroyed(mId); } @CalledByNative - private void onPostMessage(String message) { - try { - mClient.onPostMessage(mId, message); - } catch (RemoteException e) { - throw new APICallException(e); - } + private void onPostMessage(String message) throws RemoteException { + mClient.onPostMessage(mId, message); } @Override