diff --git a/.gn b/.gn index 7c3afd8..a3d99b5 100644 --- a/.gn +++ b/.gn
@@ -267,7 +267,9 @@ "//extensions:extensions_browsertests", "//extensions:extensions_unittests", "//extensions/browser", + "//extensions/browser:core_api_provider", "//extensions/browser:browser_tests", + "//extensions/browser:test_support", "//extensions/browser:unit_tests", "//extensions/browser/api:api_registration", "//extensions/browser/install:*",
diff --git a/DEPS b/DEPS index 9b085fb..21cd753 100644 --- a/DEPS +++ b/DEPS
@@ -138,11 +138,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': 'ef787f79e54ef601b1a1ed4e9ebd39febd5f8b66', + 'skia_revision': '4c4945a25248ac1687fcb564d31de73dac480b75', # 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': '1ee54f572c4d5f2dae933bc782731c34daff7164', + 'v8_revision': '9cea40ceb9312ce3e94c2b38c79bb25b7e94626d', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling swarming_client # and whatever else without interference from each other. @@ -150,15 +150,15 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': 'b08d53d3c1c6488369b595ff5b31274d4d2b3855', + 'angle_revision': '88596beab31734b07cc3a2fbd3f8b2c82bfe588c', # 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': 'df84b9466cfd59992e09f1d04bb0453060f3aa0f', + 'swiftshader_revision': '8c12f564113cbd9b2e3ab0093401bcca38d4b10d', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. - 'pdfium_revision': 'd050b35a14af9626b0b08c12c563696cd7ed25e6', + 'pdfium_revision': '92eba93b33c823f2df281aea5ff5204b5907383c', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling BoringSSL # and whatever else without interference from each other. @@ -201,7 +201,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling catapult # and whatever else without interference from each other. - 'catapult_revision': '727d7ca2730f942dd59a2389f8471d579c8ee95b', + 'catapult_revision': 'e502dbcca0143f5ea1a82b62ef81817d0f0c961f', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -269,7 +269,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'shaderc_revision': 'b988e6b4506343ad323a963d655341f09d4e6322', + 'shaderc_revision': 'c21dd10cf1969ae4721e3af7db621076de27bc17', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -277,7 +277,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'quiche_revision': '3a1bb80f575f6335621c4bcc01513d12ec77d327', + 'quiche_revision': '88e3e05c341147f4052e17a2769ac2722739c498', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ios_webkit # and whatever else without interference from each other. @@ -807,7 +807,7 @@ # Build tools for Chrome OS. Note: This depends on third_party/pyelftools. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'df99659bac9c6a2e84f17ad2444ccf6192440e5e', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '38c7d9e30addca4bef2710d231b5458050679713', 'condition': 'checkout_linux', }, @@ -832,7 +832,7 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + 'a74bd78e9ccd242af225629c3a105e209f5bf400', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + 'bc23ca13f1b3b684d9c2a127f33b618a71644829', 'src/third_party/devtools-node-modules': Var('chromium_git') + '/external/github.com/ChromeDevTools/devtools-node-modules' + '@' + Var('devtools_node_modules_revision'), @@ -1187,7 +1187,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + '710e17039085f6cf75e8d41a5e689090ea1861ca', + Var('android_git') + '/platform/external/perfetto.git' + '@' + '765b75c294d21bb26ae55f0fe772cc93044a90fb', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1355,7 +1355,7 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + '6f0b34abee8dba611c253738d955c59f703c147a', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '5894b6aad4b107418cfa34482a220ecc5f516c0c', + Var('webrtc_git') + '/src.git' + '@' + '9e25f74faab6b9f7e9f358e8531fc260e13bfa3b', 'src/third_party/xdg-utils': { 'url': Var('chromium_git') + '/chromium/deps/xdg-utils.git' + '@' + 'd80274d5869b17b8c9067a1022e4416ee7ed5e0d', @@ -1396,7 +1396,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@22b387d76825b093a67b4d787c0ffba230e8e06f', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@c8c1ab9dcdb1354bbd5833fe91b5c21849518185', 'condition': 'checkout_src_internal', },
diff --git a/android_webview/browser/aw_browser_main_parts.cc b/android_webview/browser/aw_browser_main_parts.cc index 9464639..42b56e1e 100644 --- a/android_webview/browser/aw_browser_main_parts.cc +++ b/android_webview/browser/aw_browser_main_parts.cc
@@ -38,10 +38,10 @@ #include "content/public/browser/android/synchronous_compositor.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" +#include "content/public/browser/system_connector.h" #include "content/public/common/content_client.h" #include "content/public/common/content_switches.h" #include "content/public/common/result_codes.h" -#include "content/public/common/service_manager_connection.h" #include "content/public/common/service_names.mojom.h" #include "net/android/network_change_notifier_factory_android.h" #include "net/base/network_change_notifier.h" @@ -128,12 +128,11 @@ return true; } -void AwBrowserMainParts::ServiceManagerConnectionStarted( - content::ServiceManagerConnection* connection) { +void AwBrowserMainParts::PostCreateThreads() { heap_profiling::Mode mode = heap_profiling::GetModeForStartup(); if (mode != heap_profiling::Mode::kNone) { - heap_profiling::Supervisor::GetInstance()->Start(connection, - base::OnceClosure()); + heap_profiling::Supervisor::GetInstance()->Start( + content::GetSystemConnector(), base::OnceClosure()); } }
diff --git a/android_webview/browser/aw_browser_main_parts.h b/android_webview/browser/aw_browser_main_parts.h index 37b910f..fe62bf1 100644 --- a/android_webview/browser/aw_browser_main_parts.h +++ b/android_webview/browser/aw_browser_main_parts.h
@@ -26,8 +26,7 @@ int PreCreateThreads() override; void PreMainMessageLoopRun() override; bool MainMessageLoopRun(int* result_code) override; - void ServiceManagerConnectionStarted( - content::ServiceManagerConnection* connection) override; + void PostCreateThreads() override; private: // Android specific UI SingleThreadTaskExecutor.
diff --git a/ash/app_list/app_list_presenter_delegate_unittest.cc b/ash/app_list/app_list_presenter_delegate_unittest.cc index faa26aef..a5359c30 100644 --- a/ash/app_list/app_list_presenter_delegate_unittest.cc +++ b/ash/app_list/app_list_presenter_delegate_unittest.cc
@@ -1676,6 +1676,31 @@ GetAppListTestHelper()->CheckVisibility(false); } +// Test that the AppListView opacity is reset after it is hidden during the +// overview mode animation. +TEST_F(AppListPresenterDelegateHomeLauncherTest, + LauncherShowsAfterOverviewMode) { + // Show the AppList in clamshell mode. + GetAppListTestHelper()->ShowAndRunLoop(GetPrimaryDisplayId()); + GetAppListTestHelper()->CheckVisibility(true); + + // Enable overview mode. + OverviewController* overview_controller = Shell::Get()->overview_controller(); + overview_controller->ToggleOverview(); + + // Test that the AppListView is transparent. + DCHECK_EQ(0.0f, GetAppListView()->GetWidget()->GetLayer()->opacity()); + + // Disable overview mode. + overview_controller->ToggleOverview(); + + // Show the launcher, test that the opacity is restored. + GetAppListTestHelper()->ShowAndRunLoop(GetPrimaryDisplayId()); + GetAppListTestHelper()->CheckVisibility(true); + + DCHECK_EQ(1.0f, GetAppListView()->GetWidget()->GetLayer()->opacity()); +} + // Tests the app list opacity in overview mode. TEST_F(AppListPresenterDelegateHomeLauncherTest, OpacityInOverviewMode) { // Show app list in tablet mode.
diff --git a/ash/app_list/presenter/app_list_presenter_impl.cc b/ash/app_list/presenter/app_list_presenter_impl.cc index ee58597..cc448946 100644 --- a/ash/app_list/presenter/app_list_presenter_impl.cc +++ b/ash/app_list/presenter/app_list_presenter_impl.cc
@@ -228,12 +228,19 @@ if (!GetTargetVisibility()) return; + // Manipulate the layer which contains the expand arrow, suggestion chips and + // apps grid in app_list_main_view, and the search box. + ui::Layer* layer = view_->GetWidget()->GetNativeWindow()->layer(); + if (!delegate_->IsTabletMode()) { + // In clamshell mode, set the opacity of the AppList immediately to + // instantly hide it. Opacity of the AppList is reset when it is shown + // again. + layer->SetOpacity(opacity); + return; + } + const gfx::Transform translation(1.f, 0.f, 0.f, 1.f, 0.f, static_cast<float>(y_position_in_screen)); - // We want to animate the expand arrow, suggestion chips and apps grid in - // app_list_main_view, and the search box. - ui::Layer* layer = view_->GetWidget()->GetNativeWindow()->layer(); - if (layer->GetAnimator()->is_animating()) { layer->GetAnimator()->StopAnimating();
diff --git a/ash/app_list/views/app_list_view.cc b/ash/app_list/views/app_list_view.cc index d51a643..26b7cd34 100644 --- a/ash/app_list/views/app_list_view.cc +++ b/ash/app_list/views/app_list_view.cc
@@ -649,7 +649,9 @@ void AppListView::Show(bool is_side_shelf, bool is_tablet_mode) { if (!time_shown_.has_value()) time_shown_ = base::Time::Now(); - + // The opacity of the AppListView may have been manipulated by overview mode, + // so reset it before it is shown. + GetWidget()->GetLayer()->SetOpacity(1.0f); is_side_shelf_ = is_side_shelf; app_list_main_view_->contents_view()->ResetForShow();
diff --git a/ash/app_list/views/assistant/assistant_main_stage.cc b/ash/app_list/views/assistant/assistant_main_stage.cc index 8fc966d..142fb5fe 100644 --- a/ash/app_list/views/assistant/assistant_main_stage.cc +++ b/ash/app_list/views/assistant/assistant_main_stage.cc
@@ -214,8 +214,7 @@ bool IsLayerVisible(views::View* view) { DCHECK(view->layer()); - return view->IsDrawn() && - !cc::MathUtil::IsWithinEpsilon(view->layer()->GetTargetOpacity(), 0.f); + return !cc::MathUtil::IsWithinEpsilon(view->layer()->GetTargetOpacity(), 0.f); } } // namespace @@ -438,6 +437,7 @@ const ash::AssistantQuery& query) { // Update the view. query_view_->SetQuery(query); + UpdateFooter(/*visible=*/false); if (!IsLayerVisible(greeting_label_)) return; @@ -461,12 +461,18 @@ MaybeHideGreetingLabel(); } -void AssistantMainStage::OnPendingQueryCleared() { +void AssistantMainStage::OnPendingQueryCleared(bool due_to_commit) { // When a pending query is cleared, it may be because the interaction was // cancelled, or because the query was committed. If the query was committed, // reseting the query here will have no visible effect. If the interaction was // cancelled, we set the query here to restore the previously committed query. query_view_->SetQuery(delegate_->GetInteractionModel()->committed_query()); + + // If the query was committed, we wait for |OnResponseChanged()| to update the + // footer. If the interaction was cancelled, we restore the previous + // suggestion chips. + if (!due_to_commit) + UpdateFooter(/*visible=*/true); } void AssistantMainStage::OnResponseChanged( @@ -492,7 +498,7 @@ CreateLayerAnimationSequence(ash::assistant::util::CreateOpacityElement( 0.f, kDividerAnimationFadeOutDuration))); - UpdateFooter(); + UpdateFooter(/*visible=*/true); } void AssistantMainStage::OnUiVisibilityChanged( @@ -560,7 +566,9 @@ query_view_->SetQuery(ash::AssistantNullQuery()); - UpdateFooter(); + footer_->SetVisible(true); + footer_->layer()->SetOpacity(1.f); + footer_->set_can_process_events_within_subtree(true); } void AssistantMainStage::MaybeHideGreetingLabel() { @@ -575,16 +583,15 @@ CreateOpacityElement(0.f, kGreetingAnimationFadeOutDuration))); } -void AssistantMainStage::UpdateFooter() { +void AssistantMainStage::UpdateFooter(bool visible) { using ash::assistant::util::CreateLayerAnimationSequence; using ash::assistant::util::CreateOpacityElement; using ash::assistant::util::CreateTransformElement; using ash::assistant::util::StartLayerAnimationSequence; using ash::assistant::util::StartLayerAnimationSequencesTogether; - // The footer is only visible when the progress indicator is not. - // When it is not visible, it should not process events. - bool visible = !IsLayerVisible(progress_indicator_); + if (visible == IsLayerVisible(footer_)) + return; // Reset visibility to enable animation. footer_->SetVisible(true); @@ -638,9 +645,8 @@ bool AssistantMainStage::OnFooterAnimationEnded( const ui::CallbackLayerAnimationObserver& observer) { - // The footer should only process events when visible. It is only visible when - // the progress indicator is not visible. - bool visible = !IsLayerVisible(progress_indicator_); + // The footer should only process events when visible. + const bool visible = IsLayerVisible(footer_); footer_->set_can_process_events_within_subtree(visible); footer_->SetVisible(visible);
diff --git a/ash/app_list/views/assistant/assistant_main_stage.h b/ash/app_list/views/assistant/assistant_main_stage.h index c060da9a..8066b53 100644 --- a/ash/app_list/views/assistant/assistant_main_stage.h +++ b/ash/app_list/views/assistant/assistant_main_stage.h
@@ -54,7 +54,7 @@ // AssistantInteractionModelObserver: void OnCommittedQueryChanged(const ash::AssistantQuery& query) override; void OnPendingQueryChanged(const ash::AssistantQuery& query) override; - void OnPendingQueryCleared() override; + void OnPendingQueryCleared(bool due_to_commit) override; void OnResponseChanged( const std::shared_ptr<ash::AssistantResponse>& response) override; @@ -75,7 +75,8 @@ void MaybeHideGreetingLabel(); - void UpdateFooter(); + // Update footer to |visible| with animations. + void UpdateFooter(bool visible); void OnFooterAnimationStarted( const ui::CallbackLayerAnimationObserver& observer);
diff --git a/ash/assistant/model/assistant_interaction_model.cc b/ash/assistant/model/assistant_interaction_model.cc index 755f16b..7f86d63 100644 --- a/ash/assistant/model/assistant_interaction_model.cc +++ b/ash/assistant/model/assistant_interaction_model.cc
@@ -91,7 +91,7 @@ pending_query_ = std::make_unique<AssistantNullQuery>(); NotifyCommittedQueryChanged(); - NotifyPendingQueryCleared(); + NotifyPendingQueryCleared(/*due_to_commit=*/true); } void AssistantInteractionModel::ClearPendingQuery() { @@ -99,7 +99,7 @@ return; pending_query_ = std::make_unique<AssistantNullQuery>(); - NotifyPendingQueryCleared(); + NotifyPendingQueryCleared(/*due_to_commit=*/false); } void AssistantInteractionModel::SetPendingResponse( @@ -156,9 +156,9 @@ observer.OnPendingQueryChanged(*pending_query_); } -void AssistantInteractionModel::NotifyPendingQueryCleared() { +void AssistantInteractionModel::NotifyPendingQueryCleared(bool due_to_commit) { for (AssistantInteractionModelObserver& observer : observers_) - observer.OnPendingQueryCleared(); + observer.OnPendingQueryCleared(due_to_commit); } void AssistantInteractionModel::NotifyResponseChanged() {
diff --git a/ash/assistant/model/assistant_interaction_model.h b/ash/assistant/model/assistant_interaction_model.h index cbb583a..80230f8 100644 --- a/ash/assistant/model/assistant_interaction_model.h +++ b/ash/assistant/model/assistant_interaction_model.h
@@ -134,7 +134,7 @@ void NotifyCommittedQueryChanged(); void NotifyCommittedQueryCleared(); void NotifyPendingQueryChanged(); - void NotifyPendingQueryCleared(); + void NotifyPendingQueryCleared(bool due_to_commit); void NotifyResponseChanged(); void NotifyResponseCleared(); void NotifySpeechLevelChanged(float speech_level_db);
diff --git a/ash/assistant/model/assistant_interaction_model_observer.h b/ash/assistant/model/assistant_interaction_model_observer.h index f48cd1c..8741c74 100644 --- a/ash/assistant/model/assistant_interaction_model_observer.h +++ b/ash/assistant/model/assistant_interaction_model_observer.h
@@ -47,7 +47,8 @@ virtual void OnPendingQueryChanged(const AssistantQuery& pending_query) {} // Invoked when the pending query associated with the interaction is cleared. - virtual void OnPendingQueryCleared() {} + // |due_to_commit| is true if called from |CommitPendingQuery()|. + virtual void OnPendingQueryCleared(bool due_to_commit) {} // Invoked when the response associated with the interaction is changed. virtual void OnResponseChanged(
diff --git a/ash/assistant/ui/main_stage/assistant_main_stage.cc b/ash/assistant/ui/main_stage/assistant_main_stage.cc index 219042dd..d6be1c5 100644 --- a/ash/assistant/ui/main_stage/assistant_main_stage.cc +++ b/ash/assistant/ui/main_stage/assistant_main_stage.cc
@@ -553,7 +553,7 @@ pending_query_view_->SetQuery(query); } -void AssistantMainStage::OnPendingQueryCleared() { +void AssistantMainStage::OnPendingQueryCleared(bool due_to_commit) { if (pending_query_view_) { delete pending_query_view_; pending_query_view_ = nullptr;
diff --git a/ash/assistant/ui/main_stage/assistant_main_stage.h b/ash/assistant/ui/main_stage/assistant_main_stage.h index af3a7a6d..de69a97 100644 --- a/ash/assistant/ui/main_stage/assistant_main_stage.h +++ b/ash/assistant/ui/main_stage/assistant_main_stage.h
@@ -56,7 +56,7 @@ // AssistantInteractionModelObserver: void OnCommittedQueryChanged(const AssistantQuery& query) override; void OnPendingQueryChanged(const AssistantQuery& query) override; - void OnPendingQueryCleared() override; + void OnPendingQueryCleared(bool due_to_commit) override; void OnResponseChanged( const std::shared_ptr<AssistantResponse>& response) override;
diff --git a/ash/keyboard/ash_keyboard_controller.cc b/ash/keyboard/ash_keyboard_controller.cc index 2d104039a..b9f5e648 100644 --- a/ash/keyboard/ash_keyboard_controller.cc +++ b/ash/keyboard/ash_keyboard_controller.cc
@@ -11,9 +11,11 @@ #include "ash/keyboard/virtual_keyboard_controller.h" #include "ash/public/cpp/keyboard/keyboard_switches.h" #include "ash/public/cpp/shell_window_ids.h" +#include "ash/root_window_controller.h" #include "ash/session/session_controller_impl.h" #include "ash/shell.h" #include "ash/shell_delegate.h" +#include "ash/wm/window_util.h" #include "base/command_line.h" #include "ui/base/ui_base_features.h" #include "ui/gfx/geometry/rect.h" @@ -24,6 +26,18 @@ namespace ash { +namespace { + +base::Optional<display::Display> GetFirstTouchDisplay() { + for (const auto& display : display::Screen::GetScreen()->GetAllDisplays()) { + if (display.touch_support() == display::Display::TouchSupport::AVAILABLE) + return display; + } + return base::nullopt; +} + +} // namespace + AshKeyboardController::AshKeyboardController( SessionControllerImpl* session_controller) : session_controller_(session_controller), @@ -43,8 +57,7 @@ std::unique_ptr<keyboard::KeyboardUIFactory> keyboard_ui_factory) { DCHECK(keyboard_ui_factory); virtual_keyboard_controller_ = std::make_unique<VirtualKeyboardController>(); - keyboard_controller_->Initialize(std::move(keyboard_ui_factory), - virtual_keyboard_controller_.get()); + keyboard_controller_->Initialize(std::move(keyboard_ui_factory), this); if (base::CommandLine::ForCurrentProcess()->HasSwitch( keyboard::switches::kEnableVirtualKeyboard)) { @@ -195,17 +208,50 @@ } } -// private methods - void AshKeyboardController::OnRootWindowClosing(aura::Window* root_window) { if (keyboard_controller_->GetRootWindow() == root_window) { - aura::Window* new_parent = - virtual_keyboard_controller_->GetContainerForDefaultDisplay(); + aura::Window* new_parent = GetContainerForDefaultDisplay(); DCHECK_NE(root_window, new_parent); keyboard_controller_->MoveToParentContainer(new_parent); } } +aura::Window* AshKeyboardController::GetContainerForDisplay( + const display::Display& display) { + DCHECK(display.is_valid()); + + RootWindowController* controller = + Shell::Get()->GetRootWindowControllerWithDisplayId(display.id()); + aura::Window* container = + controller->GetContainer(kShellWindowId_VirtualKeyboardContainer); + DCHECK(container); + return container; +} + +aura::Window* AshKeyboardController::GetContainerForDefaultDisplay() { + const display::Screen* screen = display::Screen::GetScreen(); + const base::Optional<display::Display> first_touch_display = + GetFirstTouchDisplay(); + const bool has_touch_display = first_touch_display.has_value(); + + if (wm::GetFocusedWindow()) { + // Return the focused display if that display has touch capability or no + // other display has touch capability. + const display::Display focused_display = + screen->GetDisplayNearestWindow(wm::GetFocusedWindow()); + if (focused_display.is_valid() && + (focused_display.touch_support() == + display::Display::TouchSupport::AVAILABLE || + !has_touch_display)) { + return GetContainerForDisplay(focused_display); + } + } + + // Return the first touch display, or the primary display if there are none. + return GetContainerForDisplay( + has_touch_display ? *first_touch_display : screen->GetPrimaryDisplay()); +} + void AshKeyboardController::OnKeyboardConfigChanged( const keyboard::KeyboardConfig& config) { for (auto& observer : observers_)
diff --git a/ash/keyboard/ash_keyboard_controller.h b/ash/keyboard/ash_keyboard_controller.h index 6d5cc29d..59f9b4e 100644 --- a/ash/keyboard/ash_keyboard_controller.h +++ b/ash/keyboard/ash_keyboard_controller.h
@@ -11,6 +11,7 @@ #include "ash/ash_export.h" #include "ash/keyboard/ui/keyboard_controller.h" +#include "ash/keyboard/ui/keyboard_layout_delegate.h" #include "ash/public/cpp/keyboard/keyboard_controller.h" #include "ash/public/cpp/keyboard/keyboard_controller_observer.h" #include "ash/session/session_observer.h" @@ -36,9 +37,11 @@ // class. TODO(shend): Consider re-factoring keyboard::KeyboardController so // that this can inherit from that class instead. Rename this to // KeyboardControllerImpl. -class ASH_EXPORT AshKeyboardController : public KeyboardController, - public KeyboardControllerObserver, - public SessionObserver { +class ASH_EXPORT AshKeyboardController + : public KeyboardController, + public keyboard::KeyboardLayoutDelegate, + public KeyboardControllerObserver, + public SessionObserver { public: // |session_controller| is expected to outlive AshKeyboardController. explicit AshKeyboardController(SessionControllerImpl* session_controller); @@ -79,6 +82,11 @@ void SetDraggableArea(const gfx::Rect& bounds) override; void AddObserver(KeyboardControllerObserver* observer) override; + // keyboard::KeyboardLayoutDelegate: + aura::Window* GetContainerForDefaultDisplay() override; + aura::Window* GetContainerForDisplay( + const display::Display& display) override; + // SessionObserver: void OnSessionStateChanged(session_manager::SessionState state) override;
diff --git a/ash/keyboard/ash_keyboard_controller_unittest.cc b/ash/keyboard/ash_keyboard_controller_unittest.cc index 410e1e8..2401679 100644 --- a/ash/keyboard/ash_keyboard_controller_unittest.cc +++ b/ash/keyboard/ash_keyboard_controller_unittest.cc
@@ -24,6 +24,7 @@ #include "testing/gtest/include/gtest/gtest.h" #include "ui/aura/window.h" #include "ui/display/manager/display_manager.h" +#include "ui/display/test/display_manager_test_api.h" using keyboard::KeyboardConfig; using keyboard::KeyboardEnableFlag; @@ -136,6 +137,21 @@ return result; } + aura::Window* GetPrimaryRootWindow() { return Shell::GetPrimaryRootWindow(); } + + aura::Window* GetSecondaryRootWindow() { + aura::Window::Windows root_windows = Shell::GetAllRootWindows(); + return root_windows[0] == GetPrimaryRootWindow() ? root_windows[1] + : root_windows[0]; + } + + void CreateFocusedTestWindowInRootWindow(aura::Window* root_window) { + // Owned by |root_window|. + aura::Window* focusable_window = + CreateTestWindowInShellWithBounds(root_window->GetBoundsInScreen()); + focusable_window->Focus(); + } + private: DISALLOW_COPY_AND_ASSIGN(AshKeyboardControllerTest); }; @@ -371,4 +387,158 @@ EXPECT_EQ(800, screen_bounds.x()); } +// Test for http://crbug.com/303429. |GetContainerForDisplay| should move +// keyboard to specified display even when it's not touchable. +TEST_F(AshKeyboardControllerTest, GetContainerForDisplay) { + UpdateDisplay("500x500,500x500"); + + // Make primary display touchable. + display::test::DisplayManagerTestApi(Shell::Get()->display_manager()) + .SetTouchSupport(GetPrimaryDisplay().id(), + display::Display::TouchSupport::AVAILABLE); + + EXPECT_EQ(display::Display::TouchSupport::AVAILABLE, + GetPrimaryDisplay().touch_support()); + EXPECT_NE(display::Display::TouchSupport::AVAILABLE, + GetSecondaryDisplay().touch_support()); + + // Move to primary display. + EXPECT_EQ(GetPrimaryRootWindow(), + ash_keyboard_controller() + ->GetContainerForDisplay(GetPrimaryDisplay()) + ->GetRootWindow()); + + // Move to secondary display. + EXPECT_EQ(GetSecondaryRootWindow(), + ash_keyboard_controller() + ->GetContainerForDisplay(GetSecondaryDisplay()) + ->GetRootWindow()); +} + +// Test for http://crbug.com/297858. |GetContainerForDefaultDisplay| should +// return the primary display if no display has touch capability and +// no window is focused. +TEST_F(AshKeyboardControllerTest, + DefaultContainerInPrimaryDisplayWhenNoDisplayHasTouch) { + UpdateDisplay("500x500,500x500"); + + EXPECT_NE(display::Display::TouchSupport::AVAILABLE, + GetPrimaryDisplay().touch_support()); + EXPECT_NE(display::Display::TouchSupport::AVAILABLE, + GetSecondaryDisplay().touch_support()); + + EXPECT_EQ(GetPrimaryRootWindow(), ash_keyboard_controller() + ->GetContainerForDefaultDisplay() + ->GetRootWindow()); +} + +// Test for http://crbug.com/297858. |GetContainerForDefaultDisplay| should +// move keyboard to focused display if no display has touch capability. +TEST_F(AshKeyboardControllerTest, + DefaultContainerIsInFocusedDisplayWhenNoDisplayHasTouch) { + UpdateDisplay("500x500,500x500"); + + EXPECT_NE(display::Display::TouchSupport::AVAILABLE, + GetPrimaryDisplay().touch_support()); + EXPECT_NE(display::Display::TouchSupport::AVAILABLE, + GetSecondaryDisplay().touch_support()); + + CreateFocusedTestWindowInRootWindow(GetSecondaryRootWindow()); + EXPECT_EQ(GetSecondaryRootWindow(), ash_keyboard_controller() + ->GetContainerForDefaultDisplay() + ->GetRootWindow()); +} + +// Test for http://crbug.com/303429. |GetContainerForDefaultDisplay| should +// move keyboard to first touchable display when there is one. +TEST_F(AshKeyboardControllerTest, DefaultContainerIsInFirstTouchableDisplay) { + UpdateDisplay("500x500,500x500"); + + // Make secondary display touchable. + display::test::DisplayManagerTestApi(Shell::Get()->display_manager()) + .SetTouchSupport(GetSecondaryDisplay().id(), + display::Display::TouchSupport::AVAILABLE); + + EXPECT_NE(display::Display::TouchSupport::AVAILABLE, + GetPrimaryDisplay().touch_support()); + EXPECT_EQ(display::Display::TouchSupport::AVAILABLE, + GetSecondaryDisplay().touch_support()); + + EXPECT_EQ(GetSecondaryRootWindow(), ash_keyboard_controller() + ->GetContainerForDefaultDisplay() + ->GetRootWindow()); +} + +// Test for http://crbug.com/303429. |GetContainerForDefaultDisplay| should +// move keyboard to first touchable display when the focused display is not +// touchable. +TEST_F( + AshKeyboardControllerTest, + DefaultContainerIsInFirstTouchableDisplayIfFocusedDisplayIsNotTouchable) { + UpdateDisplay("500x500,500x500"); + + // Make secondary display touchable. + display::test::DisplayManagerTestApi(Shell::Get()->display_manager()) + .SetTouchSupport(GetSecondaryDisplay().id(), + display::Display::TouchSupport::AVAILABLE); + + EXPECT_NE(display::Display::TouchSupport::AVAILABLE, + GetPrimaryDisplay().touch_support()); + EXPECT_EQ(display::Display::TouchSupport::AVAILABLE, + GetSecondaryDisplay().touch_support()); + + // Focus on primary display. + CreateFocusedTestWindowInRootWindow(GetPrimaryRootWindow()); + + EXPECT_EQ(GetSecondaryRootWindow(), ash_keyboard_controller() + ->GetContainerForDefaultDisplay() + ->GetRootWindow()); +} + +// Test for http://crbug.com/303429. |GetContainerForDefaultDisplay| should +// move keyborad to first touchable display when there is one. +TEST_F(AshKeyboardControllerTest, + DefaultContainerIsInFocusedDisplayIfTouchable) { + UpdateDisplay("500x500,500x500"); + + // Make both displays touchable. + display::test::DisplayManagerTestApi(Shell::Get()->display_manager()) + .SetTouchSupport(GetPrimaryDisplay().id(), + display::Display::TouchSupport::AVAILABLE); + display::test::DisplayManagerTestApi(Shell::Get()->display_manager()) + .SetTouchSupport(GetSecondaryDisplay().id(), + display::Display::TouchSupport::AVAILABLE); + + EXPECT_EQ(display::Display::TouchSupport::AVAILABLE, + GetPrimaryDisplay().touch_support()); + EXPECT_EQ(display::Display::TouchSupport::AVAILABLE, + GetSecondaryDisplay().touch_support()); + + // Focus on secondary display. + CreateFocusedTestWindowInRootWindow(GetSecondaryRootWindow()); + EXPECT_EQ(GetSecondaryRootWindow(), ash_keyboard_controller() + ->GetContainerForDefaultDisplay() + ->GetRootWindow()); + + // Focus on primary display. + CreateFocusedTestWindowInRootWindow(GetPrimaryRootWindow()); + EXPECT_EQ(GetPrimaryRootWindow(), ash_keyboard_controller() + ->GetContainerForDefaultDisplay() + ->GetRootWindow()); +} + +// Test for https://crbug.com/897007. +TEST_F(AshKeyboardControllerTest, ShowKeyboardInSecondaryDisplay) { + UpdateDisplay("500x500,500x500"); + + ash_keyboard_controller()->SetEnableFlag( + KeyboardEnableFlag::kExtensionEnabled); + + // Show in secondary display. + keyboard_controller()->ShowKeyboardInDisplay(GetSecondaryDisplay()); + EXPECT_EQ(GetSecondaryRootWindow(), keyboard_controller()->GetRootWindow()); + ASSERT_TRUE(keyboard::WaitUntilShown()); + EXPECT_TRUE(!keyboard_controller()->GetKeyboardWindow()->bounds().IsEmpty()); +} + } // namespace ash
diff --git a/ash/keyboard/virtual_keyboard_controller.cc b/ash/keyboard/virtual_keyboard_controller.cc index 1f6a917..59ba837 100644 --- a/ash/keyboard/virtual_keyboard_controller.cc +++ b/ash/keyboard/virtual_keyboard_controller.cc
@@ -13,12 +13,10 @@ #include "ash/keyboard/ui/keyboard_util.h" #include "ash/public/cpp/keyboard/keyboard_switches.h" #include "ash/public/cpp/shell_window_ids.h" -#include "ash/root_window_controller.h" #include "ash/session/session_controller_impl.h" #include "ash/shell.h" #include "ash/system/tray/system_tray_notifier.h" #include "ash/wm/tablet_mode/tablet_mode_controller.h" -#include "ash/wm/window_util.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" @@ -49,14 +47,6 @@ chromeos::input_method::mojom::ImeKeyset::kNone); } -bool HasTouchableDisplay() { - for (const auto& display : display::Screen::GetScreen()->GetAllDisplays()) { - if (display.touch_support() == display::Display::TouchSupport::AVAILABLE) - return true; - } - return false; -} - } // namespace VirtualKeyboardController::VirtualKeyboardController() @@ -120,44 +110,6 @@ UpdateKeyboardEnabled(); } -aura::Window* VirtualKeyboardController::GetContainerForDisplay( - const display::Display& display) { - DCHECK(display.is_valid()); - - RootWindowController* controller = - Shell::Get()->GetRootWindowControllerWithDisplayId(display.id()); - aura::Window* container = - controller->GetContainer(kShellWindowId_VirtualKeyboardContainer); - DCHECK(container); - return container; -} - -aura::Window* VirtualKeyboardController::GetContainerForDefaultDisplay() { - const display::Screen* screen = display::Screen::GetScreen(); - - if (wm::GetFocusedWindow()) { - // Return the focused display if that display has touch capability or no - // other display has touch capability. - const display::Display focused_display = - screen->GetDisplayNearestWindow(wm::GetFocusedWindow()); - if (focused_display.is_valid() && - (focused_display.touch_support() == - display::Display::TouchSupport::AVAILABLE || - !HasTouchableDisplay())) { - return GetContainerForDisplay(focused_display); - } - } - - // Otherwise, get the first touchable display. - for (const auto& display : display::Screen::GetScreen()->GetAllDisplays()) { - if (display.touch_support() == display::Display::TouchSupport::AVAILABLE) - return GetContainerForDisplay(display); - } - - // If there are no touchable displays, then just return the primary display. - return GetContainerForDisplay(screen->GetPrimaryDisplay()); -} - void VirtualKeyboardController::UpdateDevices() { ui::DeviceDataManager* device_data_manager = ui::DeviceDataManager::GetInstance();
diff --git a/ash/keyboard/virtual_keyboard_controller.h b/ash/keyboard/virtual_keyboard_controller.h index 2c64bc8f..7f92c87 100644 --- a/ash/keyboard/virtual_keyboard_controller.h +++ b/ash/keyboard/virtual_keyboard_controller.h
@@ -9,7 +9,6 @@ #include "ash/ash_export.h" #include "ash/bluetooth_devices_observer.h" -#include "ash/keyboard/ui/keyboard_layout_delegate.h" #include "ash/public/cpp/keyboard/keyboard_controller_observer.h" #include "ash/session/session_observer.h" #include "ash/wm/tablet_mode/tablet_mode_observer.h" @@ -26,7 +25,6 @@ class ASH_EXPORT VirtualKeyboardController : public TabletModeObserver, public ui::InputDeviceEventObserver, - public keyboard::KeyboardLayoutDelegate, public KeyboardControllerObserver, public SessionObserver { public: @@ -48,11 +46,6 @@ // when determining whether or not to show the on-screen keyboard. void ToggleIgnoreExternalKeyboard(); - // keyboard::KeyboardLayoutDelegate: - aura::Window* GetContainerForDefaultDisplay() override; - aura::Window* GetContainerForDisplay( - const display::Display& display) override; - // KeyboardControllerObserver: void OnKeyboardEnabledChanged(bool is_enabled) override; void OnKeyboardHidden(bool is_temporary_hide) override;
diff --git a/ash/keyboard/virtual_keyboard_controller_unittest.cc b/ash/keyboard/virtual_keyboard_controller_unittest.cc index 7589b51f..17de4d12 100644 --- a/ash/keyboard/virtual_keyboard_controller_unittest.cc +++ b/ash/keyboard/virtual_keyboard_controller_unittest.cc
@@ -21,7 +21,6 @@ #include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "ash/wm/tablet_mode/tablet_mode_controller_test_api.h" #include "base/command_line.h" -#include "ui/display/test/display_manager_test_api.h" #include "ui/events/devices/device_data_manager_test_api.h" #include "ui/events/devices/input_device.h" #include "ui/events/devices/touchscreen_device.h" @@ -51,21 +50,6 @@ return Shell::Get()->display_manager()->GetSecondaryDisplay(); } - aura::Window* GetPrimaryRootWindow() { return Shell::GetPrimaryRootWindow(); } - - aura::Window* GetSecondaryRootWindow() { - aura::Window::Windows root_windows = Shell::GetAllRootWindows(); - return root_windows[0] == GetPrimaryRootWindow() ? root_windows[1] - : root_windows[0]; - } - - void CreateFocusedTestWindowInRootWindow(aura::Window* root_window) { - // Owned by |root_window|. - aura::Window* focusable_window = - CreateTestWindowInShellWithBounds(root_window->GetBoundsInScreen()); - focusable_window->Focus(); - } - keyboard::KeyboardController* keyboard_controller() { return keyboard::KeyboardController::Get(); } @@ -434,157 +418,4 @@ EXPECT_TRUE(keyboard_controller()->IsEnabled()); } -// Test for http://crbug.com/297858. |GetContainerForDefaultDisplay| should -// return the primary display if no display has touch capability and -// no window is focused. -TEST_F(VirtualKeyboardControllerAlwaysEnabledTest, - DefaultContainerInPrimaryDisplayWhenNoDisplayHasTouch) { - UpdateDisplay("500x500,500x500"); - - EXPECT_NE(display::Display::TouchSupport::AVAILABLE, - GetPrimaryDisplay().touch_support()); - EXPECT_NE(display::Display::TouchSupport::AVAILABLE, - GetSecondaryDisplay().touch_support()); - - EXPECT_EQ(GetPrimaryRootWindow(), GetVirtualKeyboardController() - ->GetContainerForDefaultDisplay() - ->GetRootWindow()); -} - -// Test for http://crbug.com/297858. |GetContainerForDefaultDisplay| should -// move keyboard to focused display if no display has touch capability. -TEST_F(VirtualKeyboardControllerAlwaysEnabledTest, - DefaultContainerIsInFocusedDisplayWhenNoDisplayHasTouch) { - UpdateDisplay("500x500,500x500"); - - EXPECT_NE(display::Display::TouchSupport::AVAILABLE, - GetPrimaryDisplay().touch_support()); - EXPECT_NE(display::Display::TouchSupport::AVAILABLE, - GetSecondaryDisplay().touch_support()); - - CreateFocusedTestWindowInRootWindow(GetSecondaryRootWindow()); - EXPECT_EQ(GetSecondaryRootWindow(), GetVirtualKeyboardController() - ->GetContainerForDefaultDisplay() - ->GetRootWindow()); -} - -// Test for http://crbug.com/303429. |GetContainerForDefaultDisplay| should -// move keyboard to first touchable display when there is one. -TEST_F(VirtualKeyboardControllerAlwaysEnabledTest, - DefaultContainerIsInFirstTouchableDisplay) { - UpdateDisplay("500x500,500x500"); - - // Make secondary display touchable. - display::test::DisplayManagerTestApi(Shell::Get()->display_manager()) - .SetTouchSupport(GetSecondaryDisplay().id(), - display::Display::TouchSupport::AVAILABLE); - - EXPECT_NE(display::Display::TouchSupport::AVAILABLE, - GetPrimaryDisplay().touch_support()); - EXPECT_EQ(display::Display::TouchSupport::AVAILABLE, - GetSecondaryDisplay().touch_support()); - - EXPECT_EQ(GetSecondaryRootWindow(), GetVirtualKeyboardController() - ->GetContainerForDefaultDisplay() - ->GetRootWindow()); -} - -// Test for http://crbug.com/303429. |GetContainerForDefaultDisplay| should -// move keyboard to first touchable display when the focused display is not -// touchable. -TEST_F( - VirtualKeyboardControllerAlwaysEnabledTest, - DefaultContainerIsInFirstTouchableDisplayIfFocusedDisplayIsNotTouchable) { - UpdateDisplay("500x500,500x500"); - - // Make secondary display touchable. - display::test::DisplayManagerTestApi(Shell::Get()->display_manager()) - .SetTouchSupport(GetSecondaryDisplay().id(), - display::Display::TouchSupport::AVAILABLE); - - EXPECT_NE(display::Display::TouchSupport::AVAILABLE, - GetPrimaryDisplay().touch_support()); - EXPECT_EQ(display::Display::TouchSupport::AVAILABLE, - GetSecondaryDisplay().touch_support()); - - // Focus on primary display. - CreateFocusedTestWindowInRootWindow(GetPrimaryRootWindow()); - - EXPECT_EQ(GetSecondaryRootWindow(), GetVirtualKeyboardController() - ->GetContainerForDefaultDisplay() - ->GetRootWindow()); -} - -// Test for http://crbug.com/303429. |GetContainerForDefaultDisplay| should -// move keyborad to first touchable display when there is one. -TEST_F(VirtualKeyboardControllerAlwaysEnabledTest, - DefaultContainerIsInFocusedDisplayIfTouchable) { - UpdateDisplay("500x500,500x500"); - - // Make both displays touchable. - display::test::DisplayManagerTestApi(Shell::Get()->display_manager()) - .SetTouchSupport(GetPrimaryDisplay().id(), - display::Display::TouchSupport::AVAILABLE); - display::test::DisplayManagerTestApi(Shell::Get()->display_manager()) - .SetTouchSupport(GetSecondaryDisplay().id(), - display::Display::TouchSupport::AVAILABLE); - - EXPECT_EQ(display::Display::TouchSupport::AVAILABLE, - GetPrimaryDisplay().touch_support()); - EXPECT_EQ(display::Display::TouchSupport::AVAILABLE, - GetSecondaryDisplay().touch_support()); - - // Focus on secondary display. - CreateFocusedTestWindowInRootWindow(GetSecondaryRootWindow()); - EXPECT_EQ(GetSecondaryRootWindow(), GetVirtualKeyboardController() - ->GetContainerForDefaultDisplay() - ->GetRootWindow()); - - // Focus on primary display. - CreateFocusedTestWindowInRootWindow(GetPrimaryRootWindow()); - EXPECT_EQ(GetPrimaryRootWindow(), GetVirtualKeyboardController() - ->GetContainerForDefaultDisplay() - ->GetRootWindow()); -} - -// Test for http://crbug.com/303429. |GetContainerForDisplay| should move -// keyboard to specified display even when it's not touchable. -TEST_F(VirtualKeyboardControllerAlwaysEnabledTest, GetContainerForDisplay) { - UpdateDisplay("500x500,500x500"); - - // Make primary display touchable. - display::test::DisplayManagerTestApi(Shell::Get()->display_manager()) - .SetTouchSupport(GetPrimaryDisplay().id(), - display::Display::TouchSupport::AVAILABLE); - - EXPECT_EQ(display::Display::TouchSupport::AVAILABLE, - GetPrimaryDisplay().touch_support()); - EXPECT_NE(display::Display::TouchSupport::AVAILABLE, - GetSecondaryDisplay().touch_support()); - - // Move to primary display. - EXPECT_EQ(GetPrimaryRootWindow(), - GetVirtualKeyboardController() - ->GetContainerForDisplay(GetPrimaryDisplay()) - ->GetRootWindow()); - - // Move to secondary display. - EXPECT_EQ(GetSecondaryRootWindow(), - GetVirtualKeyboardController() - ->GetContainerForDisplay(GetSecondaryDisplay()) - ->GetRootWindow()); -} - -// Test for https://crbug.com/897007. -TEST_F(VirtualKeyboardControllerAlwaysEnabledTest, - ShowKeyboardInSecondaryDisplay) { - UpdateDisplay("500x500,500x500"); - - // Show in secondary display. - keyboard_controller()->ShowKeyboardInDisplay(GetSecondaryDisplay()); - EXPECT_EQ(GetSecondaryRootWindow(), keyboard_controller()->GetRootWindow()); - ASSERT_TRUE(keyboard::WaitUntilShown()); - EXPECT_TRUE(!keyboard_controller()->GetKeyboardWindow()->bounds().IsEmpty()); -} - } // namespace ash
diff --git a/ash/public/cpp/ash_features.cc b/ash/public/cpp/ash_features.cc index 8164f69..f80aad7 100644 --- a/ash/public/cpp/ash_features.cc +++ b/ash/public/cpp/ash_features.cc
@@ -75,9 +75,6 @@ const base::Feature kUseShaderRoundedCorner{"UseShaderRoundedCorner", base::FEATURE_ENABLED_BY_DEFAULT}; -const base::Feature kNotificationStackingBarRedesign{ - "NotificationStackingBarRedesign", base::FEATURE_ENABLED_BY_DEFAULT}; - const base::Feature kSystemTrayFeaturePodsPagination{ "SystemTrayFeaturePodsPagination", base::FEATURE_DISABLED_BY_DEFAULT}; @@ -145,10 +142,6 @@ return base::FeatureList::IsEnabled(kUseShaderRoundedCorner); } -bool IsNotificationStackingBarRedesignEnabled() { - return base::FeatureList::IsEnabled(kNotificationStackingBarRedesign); -} - bool IsSystemTrayFeaturePodsPaginationEnabled() { return base::FeatureList::IsEnabled(kSystemTrayFeaturePodsPagination); }
diff --git a/ash/public/cpp/ash_features.h b/ash/public/cpp/ash_features.h index 2145f523..333a02a 100644 --- a/ash/public/cpp/ash_features.h +++ b/ash/public/cpp/ash_features.h
@@ -92,9 +92,6 @@ // improves memory performance by avoiding render surfaces where ever possible. ASH_PUBLIC_EXPORT extern const base::Feature kUseShaderRoundedCorner; -// Enables the notification stacking bar redesigned UI. -ASH_PUBLIC_EXPORT extern const base::Feature kNotificationStackingBarRedesign; - // Enables pagination for feature pod buttons in the system tray ASH_PUBLIC_EXPORT extern const base::Feature kSystemTrayFeaturePodsPagination; @@ -132,8 +129,6 @@ ASH_PUBLIC_EXPORT bool ShouldUseShaderRoundedCorner(); -ASH_PUBLIC_EXPORT bool IsNotificationStackingBarRedesignEnabled(); - ASH_PUBLIC_EXPORT bool IsSystemTrayFeaturePodsPaginationEnabled(); ASH_PUBLIC_EXPORT bool IsSwapSideVolumeButtonsForOrientationEnabled();
diff --git a/ash/system/bluetooth/tray_bluetooth_helper_legacy.cc b/ash/system/bluetooth/tray_bluetooth_helper_legacy.cc index ed4b0b5..7e769bb 100644 --- a/ash/system/bluetooth/tray_bluetooth_helper_legacy.cc +++ b/ash/system/bluetooth/tray_bluetooth_helper_legacy.cc
@@ -25,9 +25,11 @@ #include "device/bluetooth/chromeos/bluetooth_utils.h" #include "services/device/public/cpp/bluetooth/bluetooth_utils.h" -using device::mojom::BluetoothSystem; +using device::mojom::BluetoothDeviceBatteryInfo; +using device::mojom::BluetoothDeviceBatteryInfoPtr; using device::mojom::BluetoothDeviceInfo; using device::mojom::BluetoothDeviceInfoPtr; +using device::mojom::BluetoothSystem; namespace ash { namespace { @@ -96,6 +98,10 @@ info->address = AddressStrToBluetoothAddress(device->GetAddress()); info->name = device->GetName(); info->is_paired = device->IsPaired(); + if (device->battery_percentage()) { + info->battery_info = + BluetoothDeviceBatteryInfo::New(device->battery_percentage().value()); + } switch (device->GetDeviceType()) { case device::BluetoothDeviceType::UNKNOWN:
diff --git a/ash/system/message_center/unified_message_center_view.cc b/ash/system/message_center/unified_message_center_view.cc index f7174d1..9a7c704 100644 --- a/ash/system/message_center/unified_message_center_view.cc +++ b/ash/system/message_center/unified_message_center_view.cc
@@ -165,21 +165,17 @@ DISALLOW_COPY_AND_ASSIGN(StackingBarClearAllButton); }; -int GetStackingNotificationCounterHeight() { - return features::IsNotificationStackingBarRedesignEnabled() - ? kStackingNotificationCounterWithClearAllHeight - : kStackingNotificationCounterHeight; -} - } // namespace StackingNotificationCounterView::StackingNotificationCounterView( - views::ButtonListener* listener) { + views::ButtonListener* listener) + : count_label_(new views::Label), + clear_all_button_(new StackingBarClearAllButton( + listener, + l10n_util::GetStringUTF16( + IDS_ASH_MESSAGE_CENTER_CLEAR_ALL_BUTTON_LABEL))) { SetVisible(false); - if (!features::IsNotificationStackingBarRedesignEnabled()) - return; - auto* layout = SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::kHorizontal, gfx::Insets(0, kStackingNotificationClearAllButtonPadding.left(), 0, 0), @@ -187,7 +183,6 @@ layout->set_cross_axis_alignment( views::BoxLayout::CrossAxisAlignment::kStretch); - count_label_ = new views::Label(); count_label_->SetEnabledColor(kStackingNotificationCounterLabelColor); count_label_->SetFontList(views::Label::GetDefaultFontList().Derive( 1, gfx::Font::NORMAL, gfx::Font::Weight::MEDIUM)); @@ -197,9 +192,6 @@ AddChildView(spacer); layout->SetFlexForView(spacer, 1); - clear_all_button_ = new StackingBarClearAllButton( - listener, - l10n_util::GetStringUTF16(IDS_ASH_MESSAGE_CENTER_CLEAR_ALL_BUTTON_LABEL)); clear_all_button_->SetTooltipText(l10n_util::GetStringUTF16( IDS_ASH_MESSAGE_CENTER_CLEAR_ALL_BUTTON_TOOLTIP)); AddChildView(clear_all_button_); @@ -216,25 +208,21 @@ total_notification_count_ = total_notification_count; stacked_notification_count_ = stacked_notification_count; - if (features::IsNotificationStackingBarRedesignEnabled()) { - UpdateVisibility(); + UpdateVisibility(); - auto tooltip = l10n_util::GetStringFUTF16Int( - IDS_ASH_MESSAGE_CENTER_STACKING_BAR_CLEAR_ALL_BUTTON_TOOLTIP, - total_notification_count_); - clear_all_button_->SetTooltipText(tooltip); - clear_all_button_->SetAccessibleName(tooltip); + auto tooltip = l10n_util::GetStringFUTF16Int( + IDS_ASH_MESSAGE_CENTER_STACKING_BAR_CLEAR_ALL_BUTTON_TOOLTIP, + total_notification_count_); + clear_all_button_->SetTooltipText(tooltip); + clear_all_button_->SetAccessibleName(tooltip); - if (stacked_notification_count_ > 0) { - count_label_->SetText(l10n_util::GetStringFUTF16Int( - IDS_ASH_MESSAGE_CENTER_HIDDEN_NOTIFICATION_COUNT_LABEL, - stacked_notification_count_)); - count_label_->SetVisible(true); - } else { - count_label_->SetVisible(false); - } + if (stacked_notification_count_ > 0) { + count_label_->SetText(l10n_util::GetStringFUTF16Int( + IDS_ASH_MESSAGE_CENTER_HIDDEN_NOTIFICATION_COUNT_LABEL, + stacked_notification_count_)); + count_label_->SetVisible(true); } else { - SetVisible(stacked_notification_count_ > 0); + count_label_->SetVisible(false); } SchedulePaint(); @@ -268,23 +256,6 @@ gfx::PointF(bounds.bottom_left() - gfx::Vector2d(0, 1)), gfx::PointF(bounds.bottom_right() - gfx::Vector2d(0, 1)), kStackingNotificationCounterBorderColor); - - if (features::IsNotificationStackingBarRedesignEnabled()) - return; - - // Draw the hidden notification dots for the the old UI. - int x = kStackingNotificationCounterStartX; - const int y = kStackingNotificationCounterHeight / 2; - int stacking_count = - std::min(stacked_notification_count_, kStackingNotificationCounterMax); - flags.setColor(kStackingNotificationCounterColor); - for (int i = 0; i < stacking_count; ++i) { - canvas->DrawCircle(gfx::Point(x, y), kStackingNotificationCounterRadius, - flags); - x += kStackingNotificationCounterDistanceX; - } - - views::View::OnPaint(canvas); } const char* StackingNotificationCounterView::GetClassName() const { @@ -388,7 +359,7 @@ if (stacking_counter_->GetVisible()) { gfx::Rect counter_bounds(GetContentsBounds()); - int stacking_counter_height = GetStackingNotificationCounterHeight(); + int stacking_counter_height = kStackingNotificationCounterHeight; int stacking_counter_offset = 0; if (animation_state_ == UnifiedMessageCenterAnimationState::HIDE_STACKING_BAR) @@ -414,7 +385,7 @@ gfx::Size preferred_size = scroller_->GetPreferredSize(); if (stacking_counter_->GetVisible()) { - int bar_height = GetStackingNotificationCounterHeight(); + int bar_height = kStackingNotificationCounterHeight; if (animation_state_ == UnifiedMessageCenterAnimationState::HIDE_STACKING_BAR) bar_height -= GetAnimationValue() * bar_height; @@ -627,7 +598,7 @@ // Consistently use the y offset below the stacked notification bar in the // UnifiedMessageCenterView to count number of hidden notifications. const int y_offset = scroller_->GetVisibleRect().y() - scroller_->y() + - GetStackingNotificationCounterHeight(); + kStackingNotificationCounterHeight; return message_list_view_->CountNotificationsAboveY(y_offset); }
diff --git a/ash/system/message_center/unified_message_center_view.h b/ash/system/message_center/unified_message_center_view.h index a27c7c4..143ebc3 100644 --- a/ash/system/message_center/unified_message_center_view.h +++ b/ash/system/message_center/unified_message_center_view.h
@@ -49,8 +49,7 @@ }; // The header shown above the notification list displaying the number of hidden -// notifications. There are currently two UI implementations toggled by the -// NotificationStackingBarRedesign feature flag. +// notifications. class StackingNotificationCounterView : public views::View { public: explicit StackingNotificationCounterView(views::ButtonListener* listener); @@ -77,10 +76,8 @@ UnifiedMessageCenterAnimationState animation_state_ = UnifiedMessageCenterAnimationState::IDLE; - // These UI elements are only created and shown when the - // NotificationStackingBarRedesign feature is enabled. - views::Label* count_label_ = nullptr; - views::Button* clear_all_button_ = nullptr; + views::Label* const count_label_; + views::Button* const clear_all_button_; DISALLOW_COPY_AND_ASSIGN(StackingNotificationCounterView); };
diff --git a/ash/system/message_center/unified_message_center_view_unittest.cc b/ash/system/message_center/unified_message_center_view_unittest.cc index 3c17380..a09d276 100644 --- a/ash/system/message_center/unified_message_center_view_unittest.cc +++ b/ash/system/message_center/unified_message_center_view_unittest.cc
@@ -18,7 +18,6 @@ #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" -#include "base/test/scoped_feature_list.h" #include "components/prefs/pref_service.h" #include "ui/message_center/message_center.h" #include "ui/message_center/views/message_view.h" @@ -33,7 +32,6 @@ namespace { -constexpr int kDefaultTrayMenuWidth = 360; constexpr int kDefaultMaxHeight = 500; class DummyEvent : public ui::Event { @@ -74,10 +72,6 @@ void SetUp() override { AshTestBase::SetUp(); model_ = std::make_unique<UnifiedSystemTrayModel>(); - - scoped_feature_list_ = std::make_unique<base::test::ScopedFeatureList>(); - scoped_feature_list_->InitAndDisableFeature( - features::kNotificationStackingBarRedesign); } void TearDown() override { @@ -200,12 +194,6 @@ return focused_message_view; } - void EnableNotificationStackingBarRedesign() { - scoped_feature_list_ = std::make_unique<base::test::ScopedFeatureList>(); - scoped_feature_list_->InitAndEnableFeature( - features::kNotificationStackingBarRedesign); - } - TestUnifiedMessageCenterView* message_center_view() { return message_center_view_.get(); } @@ -215,7 +203,6 @@ UnifiedSystemTrayModel* model() { return model_.get(); } private: - std::unique_ptr<base::test::ScopedFeatureList> scoped_feature_list_; int id_ = 0; int size_changed_count_ = 0; @@ -364,22 +351,7 @@ AddNotification(); CreateMessageCenterView(); EXPECT_TRUE(message_center_view()->GetVisible()); - - // ScrollView fills MessageCenterView. - EXPECT_EQ(message_center_view()->bounds(), GetScroller()->bounds()); - EXPECT_EQ(GetMessageListView()->GetPreferredSize().width(), - message_center_view()->GetPreferredSize().width()); - - // MessageCenterView returns smaller height to hide Clear All button. - EXPECT_EQ(kUnifiedNotificationCenterSpacing, - message_center_view()->GetPreferredSize().height() - - GetMessageListView()->GetPreferredSize().height()); - - // ScrollView has larger height than MessageListView because it has Clear All - // button. - EXPECT_EQ(4 * kUnifiedNotificationCenterSpacing, - GetScrollerContents()->GetPreferredSize().height() - - GetMessageListView()->GetPreferredSize().height()); + EXPECT_TRUE(GetStackingCounter()->GetVisible()); // When Clear All button is pressed, all notifications are removed and the // view becomes invisible. @@ -465,86 +437,6 @@ } TEST_F(UnifiedMessageCenterViewTest, StackingCounterLayout) { - for (size_t i = 0; i < 6; ++i) - AddNotification(); - CreateMessageCenterView(); - EXPECT_TRUE(message_center_view()->GetVisible()); - - // MessageCenterView is maxed out. - EXPECT_GT(GetMessageListView()->bounds().height(), - message_center_view()->bounds().height()); - - EXPECT_TRUE(GetStackingCounter()->GetVisible()); - EXPECT_EQ(0, GetStackingCounter()->bounds().y()); - EXPECT_EQ(GetStackingCounter()->bounds().bottom(), - GetScroller()->bounds().y()); - - // Scroll to the top, making the counter invisbile. - GetScroller()->ScrollToPosition(GetScrollBar(), 0); - message_center_view()->OnMessageCenterScrolled(); - - EXPECT_FALSE(GetStackingCounter()->GetVisible()); - EXPECT_EQ(0, GetScroller()->bounds().y()); -} - -TEST_F(UnifiedMessageCenterViewTest, - StackingCounterNotAffectingMessageViewBounds) { - for (size_t i = 0; i < 6; ++i) - AddNotification(); - CreateMessageCenterView(); - EXPECT_TRUE(message_center_view()->GetVisible()); - - // MessageCenterView is maxed out. - EXPECT_GT(GetMessageListView()->bounds().height(), - message_center_view()->bounds().height()); - - // Scroll to the top, making the counter invisbile. - GetScroller()->ScrollToPosition(GetScrollBar(), 0); - message_center_view()->OnMessageCenterScrolled(); - EXPECT_FALSE(GetStackingCounter()->GetVisible()); - - gfx::Rect previous_bounds = GetMessageViewVisibleBounds(2); - - const int scroll_amount = GetMessageViewVisibleBounds(0).height() - - kStackingNotificationCounterHeight + 1; - GetScroller()->ScrollToPosition(GetScrollBar(), scroll_amount); - message_center_view()->OnMessageCenterScrolled(); - - EXPECT_TRUE(GetStackingCounter()->GetVisible()); - // The offset change matches with the scroll amount plus the stacking bar - // height. - EXPECT_EQ( - previous_bounds - - gfx::Vector2d(0, scroll_amount + kStackingNotificationCounterHeight), - GetMessageViewVisibleBounds(2)); - - GetScroller()->ScrollToPosition(GetScrollBar(), scroll_amount - 1); - message_center_view()->OnMessageCenterScrolled(); - EXPECT_FALSE(GetStackingCounter()->GetVisible()); -} - -TEST_F(UnifiedMessageCenterViewTest, StackingCounterRemovedWithNotifications) { - std::vector<std::string> ids; - for (size_t i = 0; i < 6; ++i) - ids.push_back(AddNotification()); - CreateMessageCenterView(); - EXPECT_TRUE(message_center_view()->GetVisible()); - - // MessageCenterView is maxed out. - EXPECT_GT(GetMessageListView()->bounds().height(), - message_center_view()->bounds().height()); - - EXPECT_TRUE(GetStackingCounter()->GetVisible()); - for (size_t i = 0; i < 5; ++i) { - MessageCenter::Get()->RemoveNotification(ids[i], true /* by_user */); - AnimateMessageListToEnd(); - } - EXPECT_FALSE(GetStackingCounter()->GetVisible()); -} - -TEST_F(UnifiedMessageCenterViewTest, RedesignedStackingCounterLayout) { - EnableNotificationStackingBarRedesign(); - for (size_t i = 0; i < 10; ++i) AddNotification(); @@ -570,10 +462,7 @@ EXPECT_TRUE(GetStackingCounterClearAllButton()->GetVisible()); } -TEST_F(UnifiedMessageCenterViewTest, - RedesignedStackingCounterMessageListScrolled) { - EnableNotificationStackingBarRedesign(); - +TEST_F(UnifiedMessageCenterViewTest, StackingCounterMessageListScrolled) { for (size_t i = 0; i < 10; ++i) AddNotification(); CreateMessageCenterView(); @@ -613,10 +502,7 @@ EXPECT_TRUE(GetStackingCounterClearAllButton()->GetVisible()); } -TEST_F(UnifiedMessageCenterViewTest, - RedesignedStackingCounterNotificationRemoval) { - EnableNotificationStackingBarRedesign(); - +TEST_F(UnifiedMessageCenterViewTest, StackingCounterNotificationRemoval) { std::vector<std::string> ids; for (size_t i = 0; i < 6; ++i) ids.push_back(AddNotification()); @@ -639,7 +525,7 @@ // The MessageCenterView should be tall enough to contain the bar, two // notifications, and extra padding. - EXPECT_EQ(kStackingNotificationCounterWithClearAllHeight + + EXPECT_EQ(kStackingNotificationCounterHeight + GetMessageListView()->height() + kUnifiedNotificationCenterSpacing, message_center_view()->height()); @@ -667,10 +553,7 @@ EXPECT_FALSE(GetStackingCounter()->GetVisible()); } -TEST_F(UnifiedMessageCenterViewTest, - RedesignedStackingCounter_LabelRelaidOutOnScroll) { - EnableNotificationStackingBarRedesign(); - +TEST_F(UnifiedMessageCenterViewTest, StackingCounterLabelRelaidOutOnScroll) { // Open the message center at the top of the notification list so the stacking // bar is hidden by default. std::string id = AddNotification(); @@ -816,38 +699,4 @@ widget->GetRootView()->RemoveChildView(message_center_view()); } -TEST_F(UnifiedMessageCenterViewTest, FocusChangeUpdatesStackingBar) { - CreateMessageCenterView(); - - // We need to create a widget in order to initialize a FocusManager. - auto widget = CreateTestWidget(); - widget->GetRootView()->AddChildView(message_center_view()); - widget->SetSize(gfx::Size(kDefaultTrayMenuWidth, kDefaultMaxHeight)); - widget->Show(); - - // Add notifications such that the stacking counter is shown. - std::string first_notification_id = AddNotification(); - for (int i = 0; i < 6; ++i) - AddNotification(); - std::string last_notification_id = AddNotification(); - - // The ListView should be taller than the MessageCenterView so we can scroll - // and show the stacking counter. - EXPECT_GT(GetMessageListView()->bounds().height(), - message_center_view()->bounds().height()); - EXPECT_TRUE(GetStackingCounter()->GetVisible()); - - // Advancing focus causes list to scroll to the top, which hides the counter. - auto* message_view = - ToggleFocusToMessageView(0 /* index */, false /* reverse */); - EXPECT_EQ(first_notification_id, message_view->notification_id()); - EXPECT_FALSE(GetStackingCounter()->GetVisible()); - - // Reversing the focus more scrolls the list to the bottom, reshowing the - // counter. - message_view = ToggleFocusToMessageView(7 /* index */, false /* reverse */); - EXPECT_EQ(last_notification_id, message_view->notification_id()); - EXPECT_TRUE(GetStackingCounter()->GetVisible()); -} - } // namespace ash
diff --git a/ash/system/message_center/unified_message_list_view.cc b/ash/system/message_center/unified_message_list_view.cc index efe1806..c4ed668 100644 --- a/ash/system/message_center/unified_message_list_view.cc +++ b/ash/system/message_center/unified_message_list_view.cc
@@ -488,9 +488,7 @@ void UnifiedMessageListView::UpdateBorders() { // The top notification is drawn with rounded corners when the stacking bar is // not shown. - bool is_top = (!features::IsNotificationStackingBarRedesignEnabled() || - children().size() == 1) && - state_ != State::MOVE_DOWN; + bool is_top = children().size() == 1 && state_ != State::MOVE_DOWN; for (auto* child : children()) { AsMVC(child)->UpdateBorder(is_top, child == children().back()); is_top = false;
diff --git a/ash/system/message_center/unified_message_list_view_unittest.cc b/ash/system/message_center/unified_message_list_view_unittest.cc index 73d47a6..a2a2eaa 100644 --- a/ash/system/message_center/unified_message_list_view_unittest.cc +++ b/ash/system/message_center/unified_message_list_view_unittest.cc
@@ -11,7 +11,6 @@ #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" -#include "base/test/scoped_feature_list.h" #include "ui/compositor/layer_animator.h" #include "ui/message_center/message_center.h" #include "ui/message_center/views/message_view.h" @@ -94,8 +93,6 @@ void SetUp() override { AshTestBase::SetUp(); model_ = std::make_unique<UnifiedSystemTrayModel>(); - scoped_feature_list_.InitAndDisableFeature( - features::kNotificationStackingBarRedesign); } void TearDown() override { @@ -176,7 +173,6 @@ } private: - base::test::ScopedFeatureList scoped_feature_list_; int id_ = 0; int size_changed_count_ = 0; @@ -204,7 +200,7 @@ EXPECT_EQ(GetMessageViewBounds(0).bottom(), GetMessageViewBounds(1).y()); EXPECT_EQ(GetMessageViewBounds(1).bottom(), GetMessageViewBounds(2).y()); - EXPECT_EQ(kUnifiedTrayCornerRadius, GetMessageViewAt(0)->top_radius()); + EXPECT_EQ(0, GetMessageViewAt(0)->top_radius()); EXPECT_EQ(0, GetMessageViewAt(1)->top_radius()); EXPECT_EQ(0, GetMessageViewAt(2)->top_radius()); @@ -243,7 +239,8 @@ EXPECT_EQ(previous_bounds, GetMessageViewBounds(0)); EXPECT_EQ(GetMessageViewBounds(0).bottom(), GetMessageViewBounds(1).y()); - EXPECT_EQ(kUnifiedTrayCornerRadius, GetMessageViewAt(0)->top_radius()); + // The top radius is zero because the stacking bar is shown. + EXPECT_EQ(0, GetMessageViewAt(0)->top_radius()); EXPECT_EQ(0, GetMessageViewAt(1)->top_radius()); EXPECT_EQ(0, GetMessageViewAt(0)->bottom_radius()); @@ -258,7 +255,7 @@ int previous_height = message_list_view()->GetPreferredSize().height(); EXPECT_EQ(2u, message_list_view()->children().size()); - EXPECT_EQ(kUnifiedTrayCornerRadius, GetMessageViewAt(0)->top_radius()); + EXPECT_EQ(0, GetMessageViewAt(0)->top_radius()); EXPECT_EQ(0, GetMessageViewAt(0)->bottom_radius()); gfx::Rect previous_bounds = GetMessageViewBounds(0);
diff --git a/ash/system/tray/tray_constants.h b/ash/system/tray/tray_constants.h index 9b9230e..1ba571fa 100644 --- a/ash/system/tray/tray_constants.h +++ b/ash/system/tray/tray_constants.h
@@ -198,8 +198,7 @@ constexpr int kStackingNotificationCounterRadius = 2; constexpr int kStackingNotificationCounterStartX = 18; constexpr int kStackingNotificationCounterDistanceX = 10; -constexpr int kStackingNotificationCounterHeight = 20; -constexpr int kStackingNotificationCounterWithClearAllHeight = 32; +constexpr int kStackingNotificationCounterHeight = 32; constexpr gfx::Insets kStackingNotificationClearAllButtonPadding(8, 16); constexpr SkColor kStackingNotificationCounterColor = SkColorSetRGB(0x5f, 0x63, 0x68);
diff --git a/base/command_line.cc b/base/command_line.cc index 1451251..281b3ded 100644 --- a/base/command_line.cc +++ b/base/command_line.cc
@@ -45,10 +45,10 @@ #endif size_t switch_prefix_count = size(kSwitchPrefixes); -size_t GetSwitchPrefixLength(const CommandLine::StringType& string) { +size_t GetSwitchPrefixLength(CommandLine::StringPieceType string) { for (size_t i = 0; i < switch_prefix_count; ++i) { CommandLine::StringType prefix(kSwitchPrefixes[i]); - if (string.compare(0, prefix.length(), prefix) == 0) + if (string.substr(0, prefix.length()) == prefix) return prefix.length(); } return 0; @@ -72,6 +72,19 @@ return true; } +// Returns true iff |string| represents a switch with key +// |switch_key_without_prefix|, regardless of value. +bool IsSwitchWithKey(CommandLine::StringPieceType string, + CommandLine::StringPieceType switch_key_without_prefix) { + size_t prefix_length = GetSwitchPrefixLength(string); + if (prefix_length == 0 || prefix_length == string.length()) + return false; + + const size_t equals_position = string.find(kSwitchValueSeparator); + return string.substr(prefix_length, equals_position - prefix_length) == + switch_key_without_prefix; +} + // Append switches and arguments, keeping switches before arguments. void AppendSwitchesAndArguments(CommandLine* command_line, const CommandLine::StringVector& argv) { @@ -362,9 +375,38 @@ #endif } -void CommandLine::RemoveSwitch(const StringPiece& switch_string) { - DCHECK_EQ(ToLowerASCII(switch_string), switch_string); - switches_.erase(switch_string.as_string()); +void CommandLine::RemoveSwitch(base::StringPiece switch_key_without_prefix) { +#if defined(OS_WIN) + StringType switch_key_native = base::ASCIIToUTF16(switch_key_without_prefix); +#elif defined(OS_POSIX) || defined(OS_FUCHSIA) + StringType switch_key_native = switch_key_without_prefix.as_string(); +#endif + + DCHECK_EQ(ToLowerASCII(switch_key_without_prefix), switch_key_without_prefix); + DCHECK_EQ(0u, GetSwitchPrefixLength(switch_key_native)); + size_t erased_from_switches = + switches_.erase(switch_key_without_prefix.as_string()); + DCHECK(erased_from_switches <= 1); + if (!erased_from_switches) + return; + + // Also erase from the switches section of |argv_| and update |begin_args_| + // accordingly. + // Switches in |argv_| have indices [1, begin_args_). + auto argv_switches_begin = argv_.begin() + 1; + auto argv_switches_end = argv_.begin() + begin_args_; + DCHECK(argv_switches_begin <= argv_switches_end); + DCHECK(argv_switches_end <= argv_.end()); + auto arg_iter = std::find_if(argv_switches_begin, argv_switches_end, + [&switch_key_native](const StringType& arg) { + return IsSwitchWithKey(arg, switch_key_native); + }); + if (arg_iter == argv_switches_end) { + NOTREACHED(); + return; + } + argv_.erase(arg_iter); + --begin_args_; } void CommandLine::CopySwitchesFrom(const CommandLine& source,
diff --git a/base/command_line.h b/base/command_line.h index 75c13c2..cd32efb 100644 --- a/base/command_line.h +++ b/base/command_line.h
@@ -35,8 +35,10 @@ #if defined(OS_WIN) // The native command line string type. using StringType = string16; + using StringPieceType = base::StringPiece16; #elif defined(OS_POSIX) || defined(OS_FUCHSIA) using StringType = std::string; + using StringPieceType = base::StringPiece; #endif using CharType = StringType::value_type; @@ -183,8 +185,9 @@ void AppendSwitchASCII(const std::string& switch_string, const std::string& value); - // Removes a switch. - void RemoveSwitch(const StringPiece& switch_string); + // Removes the switch that matches |switch_key_without_prefix|, regardless of + // prefix and value. If no such switch is present, this has no effect. + void RemoveSwitch(const base::StringPiece switch_key_without_prefix); // Copy a set of switches (and any values) from another command line. // Commonly used when launching a subprocess.
diff --git a/base/command_line_unittest.cc b/base/command_line_unittest.cc index 26a045b..d4194fc 100644 --- a/base/command_line_unittest.cc +++ b/base/command_line_unittest.cc
@@ -13,6 +13,7 @@ #include "base/strings/strcat.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace base { @@ -441,9 +442,9 @@ } TEST(CommandLineTest, RemoveSwitch) { - std::string switch1 = "switch1"; - std::string switch2 = "switch2"; - std::string value2 = "value"; + const std::string switch1 = "switch1"; + const std::string switch2 = "switch2"; + const std::string value2 = "value"; CommandLine cl(FilePath(FILE_PATH_LITERAL("Program"))); @@ -453,12 +454,90 @@ EXPECT_TRUE(cl.HasSwitch(switch1)); EXPECT_TRUE(cl.HasSwitch(switch2)); EXPECT_EQ(value2, cl.GetSwitchValueASCII(switch2)); + EXPECT_THAT(cl.argv(), + testing::ElementsAre(FILE_PATH_LITERAL("Program"), + FILE_PATH_LITERAL("--switch1"), + FILE_PATH_LITERAL("--switch2=value"))); cl.RemoveSwitch(switch1); EXPECT_FALSE(cl.HasSwitch(switch1)); EXPECT_TRUE(cl.HasSwitch(switch2)); EXPECT_EQ(value2, cl.GetSwitchValueASCII(switch2)); + EXPECT_THAT(cl.argv(), + testing::ElementsAre(FILE_PATH_LITERAL("Program"), + FILE_PATH_LITERAL("--switch2=value"))); +} + +TEST(CommandLineTest, RemoveSwitchWithValue) { + const std::string switch1 = "switch1"; + const std::string switch2 = "switch2"; + const std::string value2 = "value"; + + CommandLine cl(FilePath(FILE_PATH_LITERAL("Program"))); + + cl.AppendSwitch(switch1); + cl.AppendSwitchASCII(switch2, value2); + + EXPECT_TRUE(cl.HasSwitch(switch1)); + EXPECT_TRUE(cl.HasSwitch(switch2)); + EXPECT_EQ(value2, cl.GetSwitchValueASCII(switch2)); + EXPECT_THAT(cl.argv(), + testing::ElementsAre(FILE_PATH_LITERAL("Program"), + FILE_PATH_LITERAL("--switch1"), + FILE_PATH_LITERAL("--switch2=value"))); + + cl.RemoveSwitch(switch2); + + EXPECT_TRUE(cl.HasSwitch(switch1)); + EXPECT_FALSE(cl.HasSwitch(switch2)); + EXPECT_THAT(cl.argv(), testing::ElementsAre(FILE_PATH_LITERAL("Program"), + FILE_PATH_LITERAL("--switch1"))); +} + +TEST(CommandLineTest, AppendAndRemoveSwitchWithDefaultPrefix) { + CommandLine cl(FilePath(FILE_PATH_LITERAL("Program"))); + + cl.AppendSwitch("foo"); + EXPECT_THAT(cl.argv(), testing::ElementsAre(FILE_PATH_LITERAL("Program"), + FILE_PATH_LITERAL("--foo"))); + EXPECT_EQ(0u, cl.GetArgs().size()); + + cl.RemoveSwitch("foo"); + EXPECT_THAT(cl.argv(), testing::ElementsAre(FILE_PATH_LITERAL("Program"))); + EXPECT_EQ(0u, cl.GetArgs().size()); +} + +TEST(CommandLineTest, AppendAndRemoveSwitchWithAlternativePrefix) { + CommandLine cl(FilePath(FILE_PATH_LITERAL("Program"))); + + cl.AppendSwitch("-foo"); + EXPECT_THAT(cl.argv(), testing::ElementsAre(FILE_PATH_LITERAL("Program"), + FILE_PATH_LITERAL("-foo"))); + EXPECT_EQ(0u, cl.GetArgs().size()); + + cl.RemoveSwitch("foo"); + EXPECT_THAT(cl.argv(), testing::ElementsAre(FILE_PATH_LITERAL("Program"))); + EXPECT_EQ(0u, cl.GetArgs().size()); +} + +TEST(CommandLineTest, AppendAndRemoveSwitchPreservesOtherSwitchesAndArgs) { + CommandLine cl(FilePath(FILE_PATH_LITERAL("Program"))); + + cl.AppendSwitch("foo"); + cl.AppendSwitch("bar"); + cl.AppendArg("arg"); + EXPECT_THAT(cl.argv(), testing::ElementsAre(FILE_PATH_LITERAL("Program"), + FILE_PATH_LITERAL("--foo"), + FILE_PATH_LITERAL("--bar"), + FILE_PATH_LITERAL("arg"))); + EXPECT_THAT(cl.GetArgs(), testing::ElementsAre(FILE_PATH_LITERAL("arg"))); + + cl.RemoveSwitch("foo"); + EXPECT_THAT(cl.argv(), testing::ElementsAre(FILE_PATH_LITERAL("Program"), + FILE_PATH_LITERAL("--bar"), + FILE_PATH_LITERAL("arg"))); + EXPECT_THAT(cl.GetArgs(), testing::ElementsAre(FILE_PATH_LITERAL("arg"))); } TEST(CommandLineTest, MultipleSameSwitch) {
diff --git a/base/memory/platform_shared_memory_region_fuchsia.cc b/base/memory/platform_shared_memory_region_fuchsia.cc index 4ca16e3..ee4087b 100644 --- a/base/memory/platform_shared_memory_region_fuchsia.cc +++ b/base/memory/platform_shared_memory_region_fuchsia.cc
@@ -141,8 +141,7 @@ "lead to this region being non-modifiable"; zx::vmo vmo; - zx_status_t status = - zx::vmo::create(rounded_size, ZX_VMO_NON_RESIZABLE, &vmo); + zx_status_t status = zx::vmo::create(rounded_size, 0, &vmo); if (status != ZX_OK) { ZX_DLOG(ERROR, status) << "zx_vmo_create"; return {};
diff --git a/base/memory/shared_memory_fuchsia.cc b/base/memory/shared_memory_fuchsia.cc index 9cef989..a386913a 100644 --- a/base/memory/shared_memory_fuchsia.cc +++ b/base/memory/shared_memory_fuchsia.cc
@@ -53,8 +53,7 @@ requested_size_ = options.size; mapped_size_ = bits::Align(requested_size_, GetPageSize()); zx::vmo vmo; - zx_status_t status = - zx::vmo::create(mapped_size_, ZX_VMO_NON_RESIZABLE, &vmo); + zx_status_t status = zx::vmo::create(mapped_size_, 0, &vmo); if (status != ZX_OK) { ZX_DLOG(ERROR, status) << "zx_vmo_create"; return false;
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1 index e2d8967..95ebc514 100644 --- a/build/fuchsia/linux.sdk.sha1 +++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@ -8910771380915113792 \ No newline at end of file +8910745020780655600 \ No newline at end of file
diff --git a/build/fuchsia/mac.sdk.sha1 b/build/fuchsia/mac.sdk.sha1 index 50d977f..e76f37f 100644 --- a/build/fuchsia/mac.sdk.sha1 +++ b/build/fuchsia/mac.sdk.sha1
@@ -1 +1 @@ -8910773990085370640 \ No newline at end of file +8910747325580667856 \ No newline at end of file
diff --git a/build/sanitizers/tsan_suppressions.cc b/build/sanitizers/tsan_suppressions.cc index 966b26e1..a239370 100644 --- a/build/sanitizers/tsan_suppressions.cc +++ b/build/sanitizers/tsan_suppressions.cc
@@ -157,6 +157,9 @@ // http://crbug.com/691029 "deadlock:libGLX.so*\n" + // http://crbug.com/973947 + "deadlock:libnvidia-glsi.so*\n" + // http://crbug.com/695929 "race:base::i18n::IsRTL\n" "race:base::i18n::SetICUDefaultLocale\n"
diff --git a/cc/animation/animation_host.cc b/cc/animation/animation_host.cc index be9fca4..5168e82 100644 --- a/cc/animation/animation_host.cc +++ b/cc/animation/animation_host.cc
@@ -222,6 +222,8 @@ return; mutator_host_client_ = client; + if (mutator_host_client_ && needs_push_properties_) + mutator_host_client_->SetMutatorsNeedCommit(); } void AnimationHost::SetNeedsCommit() { @@ -233,6 +235,8 @@ void AnimationHost::SetNeedsPushProperties() { needs_push_properties_ = true; + if (mutator_host_client_) + mutator_host_client_->SetMutatorsNeedCommit(); } void AnimationHost::PushPropertiesTo(MutatorHost* mutator_host_impl) {
diff --git a/cc/animation/animation_unittest.cc b/cc/animation/animation_unittest.cc index a0067e8..9ae34304 100644 --- a/cc/animation/animation_unittest.cc +++ b/cc/animation/animation_unittest.cc
@@ -464,7 +464,8 @@ timeline_->AttachAnimation(animation_); animation_->AttachElementForKeyframeEffect(element_id_, keyframe_effect_id_); - EXPECT_FALSE(client_.mutators_need_commit()); + EXPECT_TRUE(client_.mutators_need_commit()); + client_.set_mutators_need_commit(false); const int keyframe_model_id = AddOpacityTransitionToAnimation( animation_.get(), 1., .7f, .3f, false, keyframe_effect_id_);
diff --git a/cc/animation/worklet_animation.cc b/cc/animation/worklet_animation.cc index d50f2d3d..a6d109fa 100644 --- a/cc/animation/worklet_animation.cc +++ b/cc/animation/worklet_animation.cc
@@ -92,8 +92,8 @@ } void WorkletAnimation::Tick(base::TimeTicks monotonic_time) { - // Do not tick worklet animations on main thread. This should be removed if we - // skip ticking all animations on main thread in http://crbug.com/762717. + // Do not tick worklet animations on main thread as we will tick them on the + // compositor and the tick is more expensive than regular animations. if (!is_impl_instance_) return; if (!local_time_.has_value())
diff --git a/cc/layers/layer_unittest.cc b/cc/layers/layer_unittest.cc index 2936179..be4d26a 100644 --- a/cc/layers/layer_unittest.cc +++ b/cc/layers/layer_unittest.cc
@@ -1611,8 +1611,9 @@ ElementId element_id = ElementId(2); test_layer->SetElementId(element_id); - // Expect additional call due to has-animation check. - EXPECT_CALL(*layer_tree_host_, SetNeedsCommit()).Times(2); + // Expect additional calls due to has-animation check and initialization + // of keyframes. + EXPECT_CALL(*layer_tree_host_, SetNeedsCommit()).Times(7); scoped_refptr<AnimationTimeline> timeline = AnimationTimeline::Create(AnimationIdProvider::NextTimelineId()); animation_host_->AddAnimationTimeline(timeline);
diff --git a/cc/trees/layer_tree_host.cc b/cc/trees/layer_tree_host.cc index e5b6cf9203..64d6a17 100644 --- a/cc/trees/layer_tree_host.cc +++ b/cc/trees/layer_tree_host.cc
@@ -623,6 +623,12 @@ std::unique_ptr<MutatorEvents> events) { DCHECK(task_runner_provider_->IsMainThread()); mutator_host_->SetAnimationEvents(std::move(events)); + + // Events are added to a queue to be dispatched but we need a main frame + // in order to dispatch the events. Also, finished animations require + // a commit in order to clean up their KeyframeModels but without a main + // frame we could indefinitely delay cleaning up the animation. + SetNeedsAnimate(); } void LayerTreeHost::SetDebugState( @@ -990,22 +996,21 @@ } void LayerTreeHost::AnimateLayers(base::TimeTicks monotonic_time) { - // We do not need to animate on the main thread in this case because all - // relevant changes will be processed on the compositor thread, or proxy, - // and propagated back to the correct trees. - // TODO(majidvp): We should be able to eliminate this in the non- - // slimming path and will do so in a follow up. (762717) - if (IsUsingLayerLists()) - return; - std::unique_ptr<MutatorEvents> events = mutator_host_->CreateEvents(); if (mutator_host_->TickAnimations(monotonic_time, property_trees()->scroll_tree, true)) mutator_host_->UpdateAnimationState(true, events.get()); - if (!events->IsEmpty()) - property_trees_.needs_rebuild = true; + if (!events->IsEmpty()) { + // If not using layer lists, animation state changes will require + // rebuilding property trees to track them. + if (!IsUsingLayerLists()) + property_trees_.needs_rebuild = true; + + // A commit is required to push animation changes to the compositor. + SetNeedsCommit(); + } } int LayerTreeHost::ScheduleMicroBenchmark(
diff --git a/cc/trees/layer_tree_host_unittest_animation.cc b/cc/trees/layer_tree_host_unittest_animation.cc index 6a1ffbf..47a27fd6 100644 --- a/cc/trees/layer_tree_host_unittest_animation.cc +++ b/cc/trees/layer_tree_host_unittest_animation.cc
@@ -28,6 +28,7 @@ #include "cc/test/layer_tree_test.h" #include "cc/trees/effect_node.h" #include "cc/trees/layer_tree_impl.h" +#include "cc/trees/target_property.h" #include "cc/trees/transform_node.h" #include "components/viz/common/quads/compositor_frame.h" @@ -1207,6 +1208,109 @@ MULTI_THREAD_TEST_F(LayerTreeHostAnimationTestScrollOffsetAnimationRemoval); +// Verifies that the state of a scroll animation is tracked correctly on the +// main and compositor thread and that the KeyframeModel is removed when +// the scroll animation completes. This is a regression test for +// https://crbug.com/962346 and demonstrates the necessity of +// LayerTreeHost::AnimateLayers for https://crbug.com/762717. +class LayerTreeHostAnimationTestScrollOffsetAnimationCompletion + : public LayerTreeHostAnimationTest { + public: + LayerTreeHostAnimationTestScrollOffsetAnimationCompletion() + : final_position_(80.0, 180.0) {} + + void SetupTree() override { + LayerTreeHostAnimationTest::SetupTree(); + + scroll_layer_ = FakePictureLayer::Create(&client_); + scroll_layer_->SetScrollable(gfx::Size(100, 100)); + scroll_layer_->SetBounds(gfx::Size(10000, 10000)); + client_.set_bounds(scroll_layer_->bounds()); + scroll_layer_->SetScrollOffset(gfx::ScrollOffset(100.0, 200.0)); + layer_tree_host()->root_layer()->AddChild(scroll_layer_); + + std::unique_ptr<ScrollOffsetAnimationCurve> curve( + ScrollOffsetAnimationCurve::Create( + final_position_, + CubicBezierTimingFunction::CreatePreset( + CubicBezierTimingFunction::EaseType::EASE_IN_OUT))); + std::unique_ptr<KeyframeModel> keyframe_model(KeyframeModel::Create( + std::move(curve), 1, 0, TargetProperty::SCROLL_OFFSET)); + keyframe_model->set_needs_synchronized_start_time(true); + + AttachAnimationsToTimeline(); + animation_child_->AttachElement(scroll_layer_->element_id()); + animation_child_->AddKeyframeModel(std::move(keyframe_model)); + } + + void BeginTest() override { PostSetNeedsCommitToMainThread(); } + + void BeginMainFrame(const viz::BeginFrameArgs& args) override { + KeyframeModel* keyframe_model = + animation_child_->GetKeyframeModel(TargetProperty::SCROLL_OFFSET); + switch (layer_tree_host()->SourceFrameNumber()) { + case 0: + EXPECT_EQ(scroll_layer_->CurrentScrollOffset().x(), 100); + EXPECT_EQ(scroll_layer_->CurrentScrollOffset().y(), 200); + EXPECT_EQ(KeyframeModel::RunState::WAITING_FOR_TARGET_AVAILABILITY, + keyframe_model->run_state()); + break; + case 1: + EXPECT_EQ(KeyframeModel::RunState::RUNNING, + keyframe_model->run_state()); + break; + default: + break; + } + } + + void CommitCompleteOnThread(LayerTreeHostImpl* host_impl) override { + if (host_impl->sync_tree()->source_frame_number() == 0) { + GetImplTimelineAndAnimationByID(*host_impl); + return; + } + KeyframeModel* keyframe_model = + animation_child_impl_->GetKeyframeModel(TargetProperty::SCROLL_OFFSET); + if (!keyframe_model || keyframe_model->run_state() == + KeyframeModel::RunState::WAITING_FOR_DELETION) + EndTest(); + } + + void DidFinishImplFrameOnThread(LayerTreeHostImpl* host_impl) override { + if (!animation_child_impl_) + return; + if (KeyframeModel* keyframe_model = animation_child_impl_->GetKeyframeModel( + TargetProperty::SCROLL_OFFSET)) { + if (keyframe_model->run_state() == KeyframeModel::RunState::RUNNING) { + ran_animation_ = true; + } + } + } + + void AfterTest() override { + // The animation should have run for some frames. + EXPECT_TRUE(ran_animation_); + + // The finished KeyframeModel should have been removed from both the + // main and impl side animations. + EXPECT_EQ(nullptr, animation_child_->GetKeyframeModel( + TargetProperty::SCROLL_OFFSET)); + EXPECT_EQ(nullptr, animation_child_impl_->GetKeyframeModel( + TargetProperty::SCROLL_OFFSET)); + + // The scroll should have been completed. + EXPECT_EQ(final_position_, scroll_layer_->CurrentScrollOffset()); + } + + private: + FakeContentLayerClient client_; + scoped_refptr<FakePictureLayer> scroll_layer_; + const gfx::ScrollOffset final_position_; + bool ran_animation_ = false; +}; + +MULTI_THREAD_TEST_F(LayerTreeHostAnimationTestScrollOffsetAnimationCompletion); + // When animations are simultaneously added to an existing layer and to a new // layer, they should start at the same time, even when there's already a // running animation on the existing layer. @@ -1699,6 +1803,8 @@ case 2: KeyframeModel* keyframe_model = animation_->GetKeyframeModel(TargetProperty::TRANSFORM); + EXPECT_EQ(KeyframeModel::RunState::RUNNING, + keyframe_model->run_state()); animation_->RemoveKeyframeModel(keyframe_model->id()); break; } @@ -1717,6 +1823,36 @@ case 2: // The animation is removed/stopped. EXPECT_FALSE(child->screen_space_transform_is_animating()); + break; + case 3: + break; + default: + NOTREACHED(); + } + } + + void DidActivateTreeOnThread(LayerTreeHostImpl* host_impl) override { + GetImplTimelineAndAnimationByID(*host_impl); + switch (host_impl->active_tree()->source_frame_number()) { + case 0: + // No animation yet. + break; + case 1: + // Animation is starting. + EXPECT_EQ(KeyframeModel::RunState::STARTING, + animation_impl_->GetKeyframeModel(TargetProperty::TRANSFORM) + ->run_state()); + break; + case 2: + // After activation, the KeyframeModel should be waiting for deletion. + EXPECT_EQ(KeyframeModel::RunState::WAITING_FOR_DELETION, + animation_impl_->GetKeyframeModel(TargetProperty::TRANSFORM) + ->run_state()); + break; + case 3: + // The animation KeyframeModel is cleaned up. + EXPECT_EQ(nullptr, + animation_impl_->GetKeyframeModel(TargetProperty::TRANSFORM)); EndTest(); break; default: @@ -1735,9 +1871,9 @@ EXPECT_TRUE(child->screen_space_transform_is_animating()); break; case 2: + case 3: // The animation is removed/stopped. EXPECT_FALSE(child->screen_space_transform_is_animating()); - EndTest(); break; default: NOTREACHED(); @@ -2321,12 +2457,9 @@ } void UpdateLayerTreeHost() override { - if (layer_tree_host()->SourceFrameNumber() == 1) { - EXPECT_FALSE(layer_tree_host()->property_trees()->needs_rebuild); + if (layer_tree_host()->SourceFrameNumber() == 1) AddAnimatedTransformToAnimation(animation_child_.get(), 1.0, 5, 5); - } - - EXPECT_TRUE(layer_tree_host()->property_trees()->needs_rebuild); + EXPECT_TRUE(layer_tree_host()->proxy()->CommitRequested()); } void DrawLayersOnThread(LayerTreeHostImpl* host_impl) override {
diff --git a/cc/trees/proxy_main.cc b/cc/trees/proxy_main.cc index b1f5684..20299713 100644 --- a/cc/trees/proxy_main.cc +++ b/cc/trees/proxy_main.cc
@@ -215,8 +215,8 @@ // what this does. layer_tree_host_->BeginMainFrame(begin_main_frame_state->begin_frame_args); - // Updates cc animations on the main-thread. This appears to be entirely - // duplicated by work done in LayerTreeHost::BeginMainFrame. crbug.com/762717. + // Updates cc animations on the main-thread. This is necessary in order + // to track animation states such that they are cleaned up properly. layer_tree_host_->AnimateLayers( begin_main_frame_state->begin_frame_args.frame_time);
diff --git a/chrome/android/BUILD.gn b/chrome/android/BUILD.gn index 6992681..5ed6cd8 100644 --- a/chrome/android/BUILD.gn +++ b/chrome/android/BUILD.gn
@@ -285,7 +285,9 @@ "//chrome/android/webapk/libs/common:common_java", "//chrome/android/webapk/libs/common:splash_java", "//chrome/android/webapk/libs/runtime_library:webapk_service_aidl_java", + "//chrome/lib/image_fetcher/public/android:java", "//chrome/lib/lifecycle/public/android:java", + "//chrome/lib/util/public/android:java", "//components/autofill/android:autofill_java", "//components/autofill_assistant/browser:proto_java", "//components/background_task_scheduler:background_task_scheduler_java", @@ -416,7 +418,6 @@ "//components/favicon_base:favicon_base_enums_java", "//components/dom_distiller/core:distiller_type_java", "//components/infobars/core:infobar_enums_java", - "//components/image_fetcher/core:java_enums_srcjar", "//components/ntp_snippets:ntp_snippets_java_enums_srcjar", "//components/ntp_tiles:ntp_tiles_enums_java", "//components/offline_pages/core:offline_page_model_enums_java", @@ -514,6 +515,8 @@ "//chrome/android/features/keyboard_accessory:jni_headers", "//chrome/android/features/media_router:jni_headers", "//chrome/android/public/profiles:jni_headers", + "//chrome/lib/image_fetcher/public/android:jni_headers", + "//chrome/lib/util/public/android:jni_headers", ] } @@ -772,6 +775,7 @@ "//chrome/android/webapk/libs/client:client_java", "//chrome/android/webapk/libs/common:common_java", "//chrome/browser/android/metrics:ukm_utils_java", + "//chrome/lib/util/public/android:java", "//chrome/test/android:chrome_java_test_support", "//chrome/test/android/test_trusted_web_activity:test_trusted_web_activity_java", "//components/autofill/android:autofill_java", @@ -924,6 +928,7 @@ "//chrome/android:chrome_java", "//chrome/android/features/vr:java", "//chrome/test/android:chrome_java_test_support", + "//chrome/lib/util/public/android:java", "//components/policy/android:policy_java", "//content/public/android:content_java", "//content/public/test/android:content_java_test_support", @@ -2450,7 +2455,6 @@ "java/src/org/chromium/chrome/browser/history/HistoryDeletionBridge.java", "java/src/org/chromium/chrome/browser/history/HistoryDeletionInfo.java", "java/src/org/chromium/chrome/browser/historyreport/HistoryReportJniBridge.java", - "java/src/org/chromium/chrome/browser/image_fetcher/ImageFetcherBridge.java", "java/src/org/chromium/chrome/browser/infobar/AdsBlockedInfoBar.java", "java/src/org/chromium/chrome/browser/infobar/AutofillCreditCardFillingInfoBar.java", "java/src/org/chromium/chrome/browser/infobar/AutofillSaveCardInfoBar.java", @@ -2605,7 +2609,6 @@ "java/src/org/chromium/chrome/browser/util/ChromeContextUtil.java", "java/src/org/chromium/chrome/browser/util/FeatureUtilities.java", "java/src/org/chromium/chrome/browser/util/PlatformUtil.java", - "java/src/org/chromium/chrome/browser/util/UrlUtilities.java", "java/src/org/chromium/chrome/browser/webapps/AddToHomescreenManager.java", "java/src/org/chromium/chrome/browser/webapps/WebApkInstallService.java", "java/src/org/chromium/chrome/browser/webapps/WebApkInstaller.java",
diff --git a/chrome/android/DEPS b/chrome/android/DEPS index 980bd43..7aab1ad 100644 --- a/chrome/android/DEPS +++ b/chrome/android/DEPS
@@ -1,4 +1,5 @@ include_rules = [ + "+chrome/lib/util/public", "+components/content_capture", "+components/download", "+components/favicon_base",
diff --git a/chrome/android/chrome_java_sources.gni b/chrome/android/chrome_java_sources.gni index a91bc6cd..aa22d18a0 100644 --- a/chrome/android/chrome_java_sources.gni +++ b/chrome/android/chrome_java_sources.gni
@@ -733,12 +733,6 @@ "java/src/org/chromium/chrome/browser/identity/UniqueIdentificationGenerator.java", "java/src/org/chromium/chrome/browser/identity/UniqueIdentificationGeneratorFactory.java", "java/src/org/chromium/chrome/browser/identity/UuidBasedUniqueIdentificationGenerator.java", - "java/src/org/chromium/chrome/browser/image_fetcher/CachedImageFetcher.java", - "java/src/org/chromium/chrome/browser/image_fetcher/ImageFetcherBridge.java", - "java/src/org/chromium/chrome/browser/image_fetcher/ImageFetcherFactory.java", - "java/src/org/chromium/chrome/browser/image_fetcher/ImageFetcher.java", - "java/src/org/chromium/chrome/browser/image_fetcher/InMemoryCachedImageFetcher.java", - "java/src/org/chromium/chrome/browser/image_fetcher/NetworkImageFetcher.java", "java/src/org/chromium/chrome/browser/incognito/IncognitoDisclosureActivity.java", "java/src/org/chromium/chrome/browser/incognito/IncognitoNotificationManager.java", "java/src/org/chromium/chrome/browser/incognito/IncognitoNotificationService.java", @@ -1211,6 +1205,7 @@ "java/src/org/chromium/chrome/browser/preferences/ButtonPreference.java", "java/src/org/chromium/chrome/browser/preferences/ButtonPreferenceCompat.java", "java/src/org/chromium/chrome/browser/preferences/ChromeBaseCheckBoxPreference.java", + "java/src/org/chromium/chrome/browser/preferences/ChromeBaseCheckBoxPreferenceCompat.java", "java/src/org/chromium/chrome/browser/preferences/ChromeBaseListPreference.java", "java/src/org/chromium/chrome/browser/preferences/ChromeBaseListPreferenceCompat.java", "java/src/org/chromium/chrome/browser/preferences/ChromeBasePreference.java", @@ -1218,6 +1213,7 @@ "java/src/org/chromium/chrome/browser/preferences/ChromeImageViewPreference.java", "java/src/org/chromium/chrome/browser/preferences/ChromePreferenceManager.java", "java/src/org/chromium/chrome/browser/preferences/ChromeSwitchPreference.java", + "java/src/org/chromium/chrome/browser/preferences/ChromeSwitchPreferenceCompat.java", "java/src/org/chromium/chrome/browser/preferences/ClearBrowsingDataCheckBoxPreference.java", "java/src/org/chromium/chrome/browser/preferences/ExpandablePreferenceGroup.java", "java/src/org/chromium/chrome/browser/preferences/HomepageEditor.java", @@ -1643,20 +1639,11 @@ "java/src/org/chromium/chrome/browser/ui/RootUiCoordinator.java", "java/src/org/chromium/chrome/browser/ui/system/StatusBarColorController.java", "java/src/org/chromium/chrome/browser/util/AccessibilityUtil.java", - "java/src/org/chromium/chrome/browser/util/BitmapCache.java", "java/src/org/chromium/chrome/browser/util/ChromeContextUtil.java", - "java/src/org/chromium/chrome/browser/util/ChromeFileProvider.java", "java/src/org/chromium/chrome/browser/util/ColorUtils.java", - "java/src/org/chromium/chrome/browser/util/ConversionUtils.java", "java/src/org/chromium/chrome/browser/util/FeatureUtilities.java", - "java/src/org/chromium/chrome/browser/util/FileSizeUtil.java", - "java/src/org/chromium/chrome/browser/util/HashUtil.java", "java/src/org/chromium/chrome/browser/util/IntentUtils.java", - "java/src/org/chromium/chrome/browser/util/KeyNavigationUtil.java", - "java/src/org/chromium/chrome/browser/util/MathUtils.java", "java/src/org/chromium/chrome/browser/util/PlatformUtil.java", - "java/src/org/chromium/chrome/browser/util/UrlConstants.java", - "java/src/org/chromium/chrome/browser/util/UrlUtilities.java", "java/src/org/chromium/chrome/browser/util/ViewUtils.java", "java/src/org/chromium/chrome/browser/vr/ArDelegate.java", "java/src/org/chromium/chrome/browser/vr/ArDelegateProvider.java",
diff --git a/chrome/android/features/autofill_assistant/BUILD.gn b/chrome/android/features/autofill_assistant/BUILD.gn index 2a07c04..b674b3f 100644 --- a/chrome/android/features/autofill_assistant/BUILD.gn +++ b/chrome/android/features/autofill_assistant/BUILD.gn
@@ -168,6 +168,7 @@ "//base:base_java_test_support", "//chrome/android:chrome_java", "//chrome/android:chrome_test_util_java", + "//chrome/lib/image_fetcher/public/android:java", "//content/public/android:content_java", "//content/public/test/android:content_java_test_support", "//net/android:net_java_test_support",
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridItemTouchHelperCallback.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridItemTouchHelperCallback.java index de4ed0f..6aadc51f 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridItemTouchHelperCallback.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridItemTouchHelperCallback.java
@@ -27,18 +27,11 @@ * TODO(yuezhanggg): Get rid of using notifyDataSetChanged in adapter. */ public class TabGridItemTouchHelperCallback extends ItemTouchHelper.SimpleCallback { - /** - * An interface to update information in {@link TabListModel}. - */ - public interface UpdateTabInfoHandler { - void updateTabInfo(int index, Tab tab, boolean isSelected); - } private final TabListModel mModel; private final TabModelSelector mTabModelSelector; private final TabListMediator.TabActionListener mTabClosedListener; private final String mComponentName; - private final UpdateTabInfoHandler mUpdateTabHandler; private float mSwipeToDismissThreshold; private float mMergeThreshold; private boolean mActionsOnAllRelatedTabs; @@ -49,13 +42,11 @@ public TabGridItemTouchHelperCallback(TabListModel tabListModel, TabModelSelector tabModelSelector, TabListMediator.TabActionListener tabClosedListener, - UpdateTabInfoHandler updateTabHandler, String componentName, - boolean actionsOnAllRelatedTabs) { + String componentName, boolean actionsOnAllRelatedTabs) { super(0, 0); mModel = tabListModel; mTabModelSelector = tabModelSelector; mTabClosedListener = tabClosedListener; - mUpdateTabHandler = updateTabHandler; mComponentName = componentName; mActionsOnAllRelatedTabs = actionsOnAllRelatedTabs; } @@ -195,11 +186,6 @@ .getCurrentTabModelFilter(); filter.mergeTabsToGroup(filter.getTabAt(selectedCardIndex).getId(), filter.getTabAt(hoveredCardIndex).getId()); - int destinationIndex = - selectedCardIndex > hoveredCardIndex ? hoveredCardIndex : hoveredCardIndex - 1; - Tab newSelectedTab = filter.getTabAt(destinationIndex); - boolean isSelected = newSelectedTab.getId() == mTabModelSelector.getCurrentTabId(); - mUpdateTabHandler.updateTabInfo(destinationIndex, newSelectedTab, isSelected); } @VisibleForTesting
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListMediator.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListMediator.java index 6df8af74..ce75e7ae 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListMediator.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListMediator.java
@@ -385,6 +385,13 @@ if (!isValidMovePosition(srcIndex) || !isValidMovePosition(desIndex)) return; mModel.removeAt(srcIndex); + + desIndex = srcIndex > desIndex ? desIndex : desIndex - 1; + Tab newSelectedTab = mTabModelSelector.getTabModelFilterProvider() + .getCurrentTabModelFilter() + .getTabAt(desIndex); + boolean isSelected = mTabModelSelector.getCurrentTab() == newSelectedTab; + updateTab(desIndex, newSelectedTab, isSelected, true, false); } @Override @@ -482,9 +489,8 @@ } }; - mTabGridItemTouchHelperCallback = - new TabGridItemTouchHelperCallback(mModel, mTabModelSelector, mTabClosedListener, - this::updateTab, mComponentName, mActionsOnAllRelatedTabs); + mTabGridItemTouchHelperCallback = new TabGridItemTouchHelperCallback(mModel, + mTabModelSelector, mTabClosedListener, mComponentName, mActionsOnAllRelatedTabs); } private void onTabClosedFrom(int tabId, String fromComponent) { @@ -585,19 +591,8 @@ for (int i = 0; i < tabs.size(); i++) { Tab tab = tabs.get(i); - - mModel.get(i).set(TabProperties.IS_HIDDEN, false); - boolean isSelected = mTabModelSelector.getCurrentTab() == tab; - mModel.get(i).set(TabProperties.IS_SELECTED, isSelected); - - if (mThumbnailProvider != null && isSelected && !quickMode) { - ThumbnailFetcher callback = new ThumbnailFetcher(mThumbnailProvider, tab, true); - mModel.get(i).set(TabProperties.THUMBNAIL_FETCHER, callback); - } - - mModel.get(i).set(TabProperties.CREATE_GROUP_LISTENER, - getCreateGroupButtonListener(tab, isSelected)); + updateTab(i, tab, isSelected, false, quickMode); } return true; } @@ -623,9 +618,12 @@ } } - private void updateTab(int index, Tab tab, boolean isSelected) { + private void updateTab( + int index, Tab tab, boolean isSelected, boolean isUpdatingId, boolean quickMode) { if (index < 0 || index >= mModel.size()) return; - mModel.get(index).set(TabProperties.TAB_ID, tab.getId()); + if (isUpdatingId) { + mModel.get(index).set(TabProperties.TAB_ID, tab.getId()); + } TabActionListener tabSelectedListener; if (mGridCardOnClickListenerProvider == null || getRelatedTabsForId(tab.getId()).size() == 1) { @@ -634,11 +632,25 @@ tabSelectedListener = mGridCardOnClickListenerProvider.getGridCardOnClickListener(tab); } mModel.get(index).set(TabProperties.TAB_SELECTED_LISTENER, tabSelectedListener); - mModel.get(index).set(TabProperties.CREATE_GROUP_LISTENER, - isSelected ? mCreateGroupButtonProvider.getCreateGroupButtonOnClickListener(tab) - : null); + mModel.get(index).set( + TabProperties.CREATE_GROUP_LISTENER, getCreateGroupButtonListener(tab, isSelected)); mModel.get(index).set(TabProperties.IS_SELECTED, isSelected); mModel.get(index).set(TabProperties.TITLE, mTitleProvider.getTitle(tab)); + mModel.get(index).set(TabProperties.IS_HIDDEN, false); + + Callback<Drawable> faviconCallback = drawable -> { + int modelIndex = mModel.indexFromId(tab.getId()); + if (modelIndex != Tab.INVALID_TAB_ID && drawable != null) { + mModel.get(modelIndex).set(TabProperties.FAVICON, drawable); + } + }; + + mTabListFaviconProvider.getFaviconForUrlAsync( + tab.getUrl(), tab.isIncognito(), faviconCallback); + if (mThumbnailProvider != null && !quickMode && (isSelected || isUpdatingId)) { + ThumbnailFetcher callback = new ThumbnailFetcher(mThumbnailProvider, tab, isSelected); + mModel.get(index).set(TabProperties.THUMBNAIL_FETCHER, callback); + } } /**
diff --git a/chrome/android/features/tab_ui/junit/src/org/chromium/chrome/browser/tasks/tab_management/TabListMediatorUnitTest.java b/chrome/android/features/tab_ui/junit/src/org/chromium/chrome/browser/tasks/tab_management/TabListMediatorUnitTest.java index 90b8b12..bd73e208 100644 --- a/chrome/android/features/tab_ui/junit/src/org/chromium/chrome/browser/tasks/tab_management/TabListMediatorUnitTest.java +++ b/chrome/android/features/tab_ui/junit/src/org/chromium/chrome/browser/tasks/tab_management/TabListMediatorUnitTest.java
@@ -499,9 +499,10 @@ setUpForTabGroupOperation(); mMediator.setActionOnAllRelatedTabsForTest(true); - // Assume that moveTab in TabModel is finished. + // Assume that moveTab in TabModel is finished. Selected tab in the group becomes mTab1. doReturn(mTab1).when(mTabModel).getTabAt(POSITION2); doReturn(mTab2).when(mTabModel).getTabAt(POSITION1); + doReturn(mTab1).when(mTabGroupModelFilter).getTabAt(POSITION1); doReturn(mTabGroupModelFilter).when(mTabModelFilterProvider).getCurrentTabModelFilter(); // Assume that reset in TabGroupModelFilter is finished. @@ -518,8 +519,8 @@ mTabGroupModelFilterObserverCaptor.getValue().didMergeTabToGroup(mTab1, TAB2_ID); assertThat(mModel.size(), equalTo(1)); - assertThat(mModel.get(0).get(TabProperties.TAB_ID), equalTo(TAB2_ID)); - assertThat(mModel.get(0).get(TabProperties.TITLE), equalTo(TAB2_TITLE)); + assertThat(mModel.get(0).get(TabProperties.TAB_ID), equalTo(TAB1_ID)); + assertThat(mModel.get(0).get(TabProperties.TITLE), equalTo(TAB1_TITLE)); } @Test
diff --git a/chrome/android/java/res/layout/preference_compat.xml b/chrome/android/java/res/layout/preference_compat.xml index c718494..f477b56 100644 --- a/chrome/android/java/res/layout/preference_compat.xml +++ b/chrome/android/java/res/layout/preference_compat.xml
@@ -3,18 +3,16 @@ Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. --> -<!-- TODO(chouinard): For now this supports simple text-only preferences, but more children will be - added to this layout in the near future as we migrate more complex preferences. --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" - style="@style/PreferenceLayout" + style="@style/Theme.Chromium.PreferenceLayoutCompat" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_vertical" - android:background="?android:attr/selectableItemBackground" android:focusable="true" android:baselineAligned="false"> <RelativeLayout + style="@style/Theme.Chromium.PreferenceDescriptionCompat" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1"> @@ -33,4 +31,11 @@ </RelativeLayout> + <LinearLayout android:id="@android:id/widget_frame" + style="@style/Theme.Chromium.PreferenceWidgetCompat" + android:layout_width="wrap_content" + android:layout_height="match_parent" + android:gravity="center" + android:orientation="vertical" /> + </LinearLayout>
diff --git a/chrome/android/java/res/values-v17/styles.xml b/chrome/android/java/res/values-v17/styles.xml index a19acaa..aef87ce 100644 --- a/chrome/android/java/res/values-v17/styles.xml +++ b/chrome/android/java/res/values-v17/styles.xml
@@ -246,6 +246,8 @@ <item name="preferenceFragmentCompatStyle">@style/Theme.Chromium.PreferenceFragment</item> <item name="preferenceFragmentListStyle">@style/Theme.Chromium.PreferenceFragmentList</item> <item name="dialogPreferenceStyle">@style/Theme.Chromium.DialogPreference</item> + <item name="checkBoxPreferenceStyle">@style/Theme.Chromium.CheckBoxPreferenceCompat</item> + <item name="switchPreferenceCompatStyle">@style/Theme.Chromium.SwitchPreferenceCompat</item> </style> <style name="Theme.Chromium.PreferenceFragment"> @@ -256,6 +258,26 @@ <item name="android:layout">@layout/preference_compat</item> </style> + <!-- TODO(crbug.com/971791): The asymmetric start and end paddings here preserve the same + overall padding as the pre-support library custom preference layout. Following migration to + the support library preferences, we should investigate simplifying these styles.--> + <style name="Theme.Chromium.PreferenceLayoutCompat"> + <item name="android:paddingStart">8dp</item> + <item name="android:paddingEnd">10dp</item> + <item name="android:minHeight">?android:attr/listPreferredItemHeight</item> + <item name="android:background">?android:attr/selectableItemBackground</item> + </style> + + <style name="Theme.Chromium.PreferenceDescriptionCompat"> + <item name="android:paddingTop">6dp</item> + <item name="android:paddingBottom">6dp</item> + <item name="android:paddingEnd">8dp</item> + </style> + + <style name="Theme.Chromium.PreferenceWidgetCompat"> + <item name="android:minWidth">48dp</item> + </style> + <style name="Theme.Chromium.PreferenceFragmentList"> <item name="android:paddingStart">@dimen/pref_list_padding_kitkat</item> <item name="android:paddingEnd">@dimen/pref_list_padding_kitkat</item> @@ -271,6 +293,11 @@ <item name="android:negativeButtonText">@android:string/cancel</item> </style> + <style name="Theme.Chromium.CheckBoxPreferenceCompat"> + <item name="android:layout">@layout/preference_compat</item> + <item name="android:widgetLayout">@layout/preference_widget_checkbox</item> + </style> + <style name="Theme.Chromium.Preferences.AlertDialog" parent="Theme.Chromium.AlertDialog"> <item name="buttonBarButtonStyle">@style/TextAppearance.DialogButtonCompat</item> </style> @@ -283,6 +310,11 @@ <item name="android:textAllCaps">true</item> </style> + <style name="Theme.Chromium.SwitchPreferenceCompat"> + <item name="android:layout">@layout/preference_compat</item> + <item name="android:widgetLayout">@layout/preference_widget_switch_compat</item> + </style> + <style name="PreferenceActionBarModern" parent="@style/Widget.AppCompat.Light.ActionBar.Solid"> <item name="titleTextStyle">@style/TextAppearance.BlackHeadline</item> </style>
diff --git a/chrome/android/java/res/values-v21/styles.xml b/chrome/android/java/res/values-v21/styles.xml index e5a2602..f2d09eb 100644 --- a/chrome/android/java/res/values-v21/styles.xml +++ b/chrome/android/java/res/values-v21/styles.xml
@@ -37,6 +37,21 @@ <item name="android:paddingEnd">0dp</item> </style> + <style name="Theme.Chromium.PreferenceLayoutCompat"> + <item name="android:paddingStart">?android:attr/listPreferredItemPaddingStart</item> + <item name="android:paddingEnd">?android:attr/listPreferredItemPaddingEnd</item> + <item name="android:minHeight">?android:attr/listPreferredItemHeightSmall</item> + </style> + + <style name="Theme.Chromium.PreferenceDescriptionCompat"> + <item name="android:paddingTop">16dp</item> + <item name="android:paddingBottom">16dp</item> + </style> + + <style name="Theme.Chromium.PreferenceWidgetCompat"> + <item name="android:paddingStart">16dp</item> + </style> + <style name="PreferenceCategoryWithButtonStyle"> <item name="android:paddingStart">?android:attr/listPreferredItemPaddingStart</item> <item name="android:paddingEnd">4dp</item>
diff --git a/chrome/android/java/res/xml/homepage_preferences.xml b/chrome/android/java/res/xml/homepage_preferences.xml index a54efc5..1fd9037 100644 --- a/chrome/android/java/res/xml/homepage_preferences.xml +++ b/chrome/android/java/res/xml/homepage_preferences.xml
@@ -3,17 +3,17 @@ Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. --> -<PreferenceScreen +<android.support.v7.preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> - <org.chromium.chrome.browser.preferences.ChromeSwitchPreference + <org.chromium.chrome.browser.preferences.ChromeSwitchPreferenceCompat android:key="homepage_switch" android:summaryOn="@string/text_on" android:summaryOff="@string/text_off" /> - <Preference + <android.support.v7.preference.Preference android:key="homepage_edit" android:title="@string/options_homepage_edit_label" android:fragment="org.chromium.chrome.browser.preferences.HomepageEditor" /> -</PreferenceScreen> +</android.support.v7.preference.PreferenceScreen>
diff --git a/chrome/android/java/res/xml/privacy_preferences.xml b/chrome/android/java/res/xml/privacy_preferences.xml index 38bf90e..e322771 100644 --- a/chrome/android/java/res/xml/privacy_preferences.xml +++ b/chrome/android/java/res/xml/privacy_preferences.xml
@@ -3,63 +3,63 @@ Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. --> -<PreferenceScreen - xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:tools="http://schemas.android.com/tools"> +<android.support.v7.preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:app="http://schemas.android.com/apk/res-auto"> - <org.chromium.chrome.browser.preferences.ChromeBaseCheckBoxPreference + <org.chromium.chrome.browser.preferences.ChromeBaseCheckBoxPreferenceCompat android:key="navigation_error" android:title="@string/navigation_error_title" android:summary="@string/navigation_error_summary" android:defaultValue="true" /> - <org.chromium.chrome.browser.preferences.ChromeBaseCheckBoxPreference + <org.chromium.chrome.browser.preferences.ChromeBaseCheckBoxPreferenceCompat android:key="search_suggestions" android:title="@string/search_suggestions_title" android:summary="@string/search_suggestions_summary" android:defaultValue="true" /> - <org.chromium.chrome.browser.preferences.ChromeBaseCheckBoxPreference + <org.chromium.chrome.browser.preferences.ChromeBaseCheckBoxPreferenceCompat android:key="safe_browsing_scout_reporting" android:title="@string/safe_browsing_scout_reporting_title" android:summary="@string/safe_browsing_scout_reporting_summary" /> - <org.chromium.chrome.browser.preferences.ChromeBaseCheckBoxPreference + <org.chromium.chrome.browser.preferences.ChromeBaseCheckBoxPreferenceCompat android:key="safe_browsing" android:title="@string/safe_browsing_title" android:summary="@string/safe_browsing_summary" /> - <org.chromium.chrome.browser.preferences.ChromeBaseCheckBoxPreference + <org.chromium.chrome.browser.preferences.ChromeBaseCheckBoxPreferenceCompat android:key="network_predictions" android:title="@string/network_predictions_title" android:summary="@string/network_predictions_summary" android:persistent="false" /> - <org.chromium.chrome.browser.preferences.ChromeBaseCheckBoxPreference + <org.chromium.chrome.browser.preferences.ChromeBaseCheckBoxPreferenceCompat android:key="can_make_payment" android:title="@string/can_make_payment_title" android:summary="@string/settings_can_make_payment_toggle_label" /> - <org.chromium.chrome.browser.preferences.ChromeBasePreference + <org.chromium.chrome.browser.preferences.ChromeBasePreferenceCompat android:key="usage_stats_reporting" android:title="@string/usage_stats_setting_title" android:persistent="false" /> - <Preference + <android.support.v7.preference.Preference android:key="usage_and_crash_reports" android:title="@string/usage_and_crash_reports_title_legacy" android:fragment="org.chromium.chrome.browser.preferences.privacy.UsageAndCrashReportsPreferenceFragment" /> - <Preference + <android.support.v7.preference.Preference android:fragment="org.chromium.chrome.browser.preferences.privacy.DoNotTrackPreference" android:key="do_not_track" android:title="@string/do_not_track_title" /> - <Preference + <android.support.v7.preference.Preference android:key="contextual_search" android:title="@string/contextual_search_title" android:fragment="org.chromium.chrome.browser.preferences.privacy.ContextualSearchPreferenceFragment" /> - <Preference + <android.support.v7.preference.Preference android:key="clear_browsing_data" android:title="@string/clear_browsing_data_title" android:summary="@string/clear_browsing_data_summary" android:fragment="org.chromium.chrome.browser.preferences.privacy.ClearBrowsingDataTabsFragment" /> - <Preference + <android.support.v7.preference.Preference android:key="sync_and_services_link_divider" android:layout="@layout/divider_preference" android:selectable="false"/> - <org.chromium.chrome.browser.preferences.TextMessagePreference + <org.chromium.chrome.browser.preferences.TextMessagePreferenceCompat android:key="sync_and_services_link" - tools:summary="@string/privacy_sync_and_services_link"/> -</PreferenceScreen> + android:summary="@string/privacy_sync_and_services_link" + app:allowDividerBelow="false" /> +</android.support.v7.preference.PreferenceScreen>
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java b/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java index 46395f4..9909971aa 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java
@@ -308,7 +308,6 @@ public static final String SERVICE_WORKER_PAYMENT_APPS = "ServiceWorkerPaymentApps"; public static final String SHOPPING_ASSIST = "ShoppingAssist"; public static final String SHOW_TRUSTED_PUBLISHER_URL = "ShowTrustedPublisherURL"; - public static final String SSL_COMMITTED_INTERSTITIALS = "SSLCommittedInterstitials"; public static final String SPANNABLE_INLINE_AUTOCOMPLETE = "SpannableInlineAutocomplete"; public static final String SUBRESOURCE_FILTER = "SubresourceFilter"; public static final String SWAP_PIXEL_FORMAT_TO_FIX_CONVERT_FROM_TRANSLUCENT =
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/fullscreen/ChromeFullscreenManager.java b/chrome/android/java/src/org/chromium/chrome/browser/fullscreen/ChromeFullscreenManager.java index 1f7e12d..79ef0d0 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/fullscreen/ChromeFullscreenManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/fullscreen/ChromeFullscreenManager.java
@@ -37,6 +37,7 @@ import org.chromium.chrome.browser.util.FeatureUtilities; import org.chromium.chrome.browser.vr.VrModuleProvider; import org.chromium.chrome.browser.widget.ControlContainer; +import org.chromium.components.embedder_support.view.ContentView; import org.chromium.content_public.browser.NavigationHandle; import org.chromium.content_public.browser.SelectionPopupController; import org.chromium.content_public.browser.UiThreadTaskTraits; @@ -50,9 +51,9 @@ /** * A class that manages control and content views to create the fullscreen mode. */ -public class ChromeFullscreenManager - extends FullscreenManager implements ActivityStateListener, WindowFocusChangedListener { - +public class ChromeFullscreenManager extends FullscreenManager + implements ActivityStateListener, WindowFocusChangedListener, + ViewGroup.OnHierarchyChangeListener, View.OnSystemUiVisibilityChangeListener { // The amount of time to delay the control show request after returning to a once visible // activity. This delay is meant to allow Android to run its Activity focusing animation and // have the controls scroll back in smoothly once that has finished. @@ -83,6 +84,10 @@ private boolean mInGesture; private boolean mContentViewScrolling; + // Current ContentView. Updates when active tab is switched or WebContents is swapped + // in the current Tab. + private ContentView mContentView; + private final ArrayList<FullscreenListener> mListeners = new ArrayList<>(); @IntDef({ControlsPosition.TOP, ControlsPosition.NONE}) @@ -235,6 +240,11 @@ } @Override + public void onContentChanged(Tab tab) { + if (tab == getTab()) updateViewStateListener(); + } + + @Override public void onDidFinishNavigation(Tab tab, NavigationHandle navigation) { if (navigation.isInMainFrame() && !navigation.isSameDocument()) { if (tab == getTab()) exitPersistentFullscreenMode(); @@ -271,16 +281,6 @@ if (tab == getTab()) exitPersistentFullscreenMode(); } - @Override - public void onContentViewChildrenStateUpdated(Tab tab) { - if (tab == getTab()) updateContentViewChildrenState(); - } - - @Override - public void onContentViewSystemUiVisibilityChanged(Tab tab, int visibility) { - if (tab == getTab()) onContentViewSystemUiVisibilityChange(visibility); - } - private void setEnterFullscreenRunnable(Tab tab, Runnable runnable) { TabAttributes attrs = TabAttributes.from(tab); if (runnable == null) { @@ -337,11 +337,24 @@ if (tab != null && previousTab != getTab()) { mBrowserVisibilityDelegate.showControlsTransient(); } + if (previousTab != tab) updateViewStateListener(); if (tab == null && !mBrowserVisibilityDelegate.canAutoHideBrowserControls()) { setPositionsForTabToNonFullscreen(); } } + private void updateViewStateListener() { + if (mContentView != null) { + mContentView.removeOnHierarchyChangeListener(this); + mContentView.removeOnSystemUiVisibilityChangeListener(this); + } + mContentView = getContentView(); + if (mContentView != null) { + mContentView.addOnHierarchyChangeListener(this); + mContentView.addOnSystemUiVisibilityChangeListener(this); + } + } + @Override public void onActivityStateChange(Activity activity, int newState) { if (newState == ActivityState.STOPPED && mExitFullscreenOnStop) { @@ -565,6 +578,18 @@ for (FullscreenListener listener : mListeners) listener.onUpdateViewportSize(); } + // View.OnHierarchyChangeListener implementation + + @Override + public void onChildViewRemoved(View parent, View child) { + updateContentViewChildrenState(); + } + + @Override + public void onChildViewAdded(View parent, View child) { + updateContentViewChildrenState(); + } + @Override public void updateContentViewChildrenState() { ViewGroup view = getContentView(); @@ -577,6 +602,11 @@ updateViewportSize(); } + @Override + public void onSystemUiVisibilityChange(int visibility) { + onContentViewSystemUiVisibilityChange(visibility); + } + /** * Utility routine for ensuring visibility updates are synchronized with * animation, preventing message loop stalls due to untimely invalidation. @@ -724,9 +754,9 @@ } } - private ViewGroup getContentView() { + private ContentView getContentView() { Tab tab = getTab(); - return tab != null ? tab.getContentView() : null; + return tab != null ? (ContentView) tab.getContentView() : null; } @Override @@ -794,5 +824,9 @@ super.destroy(); mBrowserVisibilityDelegate.destroy(); if (mTabFullscreenObserver != null) mTabFullscreenObserver.destroy(); + if (mContentView != null) { + mContentView.removeOnHierarchyChangeListener(this); + mContentView.removeOnSystemUiVisibilityChangeListener(this); + } } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/ChromeBaseCheckBoxPreferenceCompat.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/ChromeBaseCheckBoxPreferenceCompat.java new file mode 100644 index 0000000..d371c4b --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/ChromeBaseCheckBoxPreferenceCompat.java
@@ -0,0 +1,51 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.preferences; + +import android.content.Context; +import android.support.v7.preference.CheckBoxPreference; +import android.support.v7.preference.PreferenceViewHolder; +import android.util.AttributeSet; +import android.widget.TextView; + +/** + * Contains the basic functionality that should be shared by all CheckBoxPreference in Chrome. + * + * TODO(crbug.com/967022): This class is a duplicate of {@link ChromeBaseCheckBoxPreference} that + * extends the Preference Support Library instead of the Framework Preference classes. {@link + * ChromeBaseCheckBoxPreference} will be removed in favor of this class once migration to the + * Preference Support library is complete. + */ +public class ChromeBaseCheckBoxPreferenceCompat extends CheckBoxPreference { + private ManagedPreferenceDelegateCompat mManagedPrefDelegate; + + /** + * Constructor for inflating from XML. + */ + public ChromeBaseCheckBoxPreferenceCompat(Context context, AttributeSet attrs) { + super(context, attrs); + } + + /** + * Sets the ManagedPreferenceDelegate which will determine whether this preference is managed. + */ + public void setManagedPreferenceDelegate(ManagedPreferenceDelegateCompat delegate) { + mManagedPrefDelegate = delegate; + ManagedPreferencesUtils.initPreference(mManagedPrefDelegate, this); + } + + @Override + public void onBindViewHolder(PreferenceViewHolder holder) { + super.onBindViewHolder(holder); + ((TextView) holder.findViewById(android.R.id.title)).setSingleLine(false); + ManagedPreferencesUtils.onBindViewToPreference(mManagedPrefDelegate, this, holder.itemView); + } + + @Override + protected void onClick() { + if (ManagedPreferencesUtils.onClickPreference(mManagedPrefDelegate, this)) return; + super.onClick(); + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/ChromeSwitchPreferenceCompat.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/ChromeSwitchPreferenceCompat.java new file mode 100644 index 0000000..44f8aba --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/ChromeSwitchPreferenceCompat.java
@@ -0,0 +1,59 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.preferences; + +import android.content.Context; +import android.support.v7.preference.PreferenceViewHolder; +import android.support.v7.preference.SwitchPreferenceCompat; +import android.text.TextUtils; +import android.util.AttributeSet; +import android.view.View; +import android.widget.TextView; + +/** + * A Chrome switch preference that supports managed preferences. + * + * TODO(crbug.com/967022): Remove {@link ChromeSwitchPreference} when Preference Support Library + * migration is complete in favor of this class. + */ +public class ChromeSwitchPreferenceCompat extends SwitchPreferenceCompat { + private ManagedPreferenceDelegateCompat mManagedPrefDelegate; + + public ChromeSwitchPreferenceCompat(Context context, AttributeSet attrs) { + super(context, attrs); + } + + /** + * Sets the ManagedPreferenceDelegate which will determine whether this preference is managed. + */ + public void setManagedPreferenceDelegate(ManagedPreferenceDelegateCompat delegate) { + mManagedPrefDelegate = delegate; + ManagedPreferencesUtils.initPreference(mManagedPrefDelegate, this); + } + + @Override + public void onBindViewHolder(PreferenceViewHolder holder) { + super.onBindViewHolder(holder); + + TextView title = (TextView) holder.findViewById(android.R.id.title); + title.setSingleLine(false); + + // Use summary as title if title is empty. + if (TextUtils.isEmpty(getTitle())) { + TextView summary = (TextView) holder.findViewById(android.R.id.summary); + title.setText(summary.getText()); + title.setVisibility(View.VISIBLE); + summary.setVisibility(View.GONE); + } + + ManagedPreferencesUtils.onBindViewToPreference(mManagedPrefDelegate, this, holder.itemView); + } + + @Override + protected void onClick() { + if (ManagedPreferencesUtils.onClickPreference(mManagedPrefDelegate, this)) return; + super.onClick(); + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/HomepagePreferences.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/HomepagePreferences.java index 3707a26..c17ee70b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/HomepagePreferences.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/HomepagePreferences.java
@@ -5,10 +5,10 @@ package org.chromium.chrome.browser.preferences; import android.os.Bundle; -import android.preference.Preference; -import android.preference.Preference.OnPreferenceChangeListener; -import android.preference.PreferenceFragment; +import android.support.v7.preference.Preference; +import android.support.v7.preference.PreferenceFragmentCompat; +import org.chromium.base.VisibleForTesting; import org.chromium.chrome.R; import org.chromium.chrome.browser.partnercustomizations.HomepageManager; import org.chromium.chrome.browser.util.FeatureUtilities; @@ -16,49 +16,45 @@ /** * Fragment that allows the user to configure homepage related preferences. */ -public class HomepagePreferences extends PreferenceFragment { - private static final String PREF_HOMEPAGE_SWITCH = "homepage_switch"; +public class HomepagePreferences extends PreferenceFragmentCompat { + @VisibleForTesting + public static final String PREF_HOMEPAGE_SWITCH = "homepage_switch"; private static final String PREF_HOMEPAGE_EDIT = "homepage_edit"; private HomepageManager mHomepageManager; - private ChromeSwitchPreference mHomepageSwitch; private Preference mHomepageEdit; @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); + public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { mHomepageManager = HomepageManager.getInstance(); - if (FeatureUtilities.isNewTabPageButtonEnabled()) { - getActivity().setTitle(R.string.options_startup_page_title); - } else { - getActivity().setTitle(R.string.options_homepage_title); - } + getActivity().setTitle(FeatureUtilities.isNewTabPageButtonEnabled() + ? R.string.options_startup_page_title + : R.string.options_homepage_title); PreferenceUtils.addPreferencesFromResource(this, R.xml.homepage_preferences); - mHomepageSwitch = (ChromeSwitchPreference) findPreference(PREF_HOMEPAGE_SWITCH); + ChromeSwitchPreferenceCompat mHomepageSwitch = + (ChromeSwitchPreferenceCompat) findPreference(PREF_HOMEPAGE_SWITCH); boolean isHomepageEnabled = mHomepageManager.getPrefHomepageEnabled(); mHomepageSwitch.setChecked(isHomepageEnabled); - mHomepageSwitch.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - mHomepageManager.setPrefHomepageEnabled((boolean) newValue); - return true; - } + mHomepageSwitch.setOnPreferenceChangeListener((preference, newValue) -> { + mHomepageManager.setPrefHomepageEnabled((boolean) newValue); + return true; }); mHomepageEdit = findPreference(PREF_HOMEPAGE_EDIT); updateCurrentHomepageUrl(); } + private void updateCurrentHomepageUrl() { mHomepageEdit.setSummary(mHomepageManager.getPrefHomepageUseDefaultUri() ? HomepageManager.getDefaultHomepageUri() : mHomepageManager.getPrefHomepageCustomUri()); } + @Override public void onResume() { super.onResume(); updateCurrentHomepageUrl(); } - }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/developer/TracingCategoriesPreferences.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/developer/TracingCategoriesPreferences.java index 8f2e4714..9a937357 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/developer/TracingCategoriesPreferences.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/developer/TracingCategoriesPreferences.java
@@ -5,13 +5,12 @@ package org.chromium.chrome.browser.preferences.developer; import android.os.Bundle; -import android.preference.CheckBoxPreference; -import android.preference.Preference; -import android.preference.PreferenceFragment; +import android.support.v7.preference.CheckBoxPreference; +import android.support.v7.preference.Preference; +import android.support.v7.preference.PreferenceFragmentCompat; +import android.support.v7.preference.PreferenceScreen; -import org.chromium.chrome.R; -import org.chromium.chrome.browser.preferences.ChromeBaseCheckBoxPreference; -import org.chromium.chrome.browser.preferences.PreferenceUtils; +import org.chromium.chrome.browser.preferences.ChromeBaseCheckBoxPreferenceCompat; import org.chromium.chrome.browser.tracing.TracingController; import java.util.ArrayList; @@ -25,7 +24,7 @@ * passed to the fragment via an extra (EXTRA_CATEGORY_TYPE). */ public class TracingCategoriesPreferences - extends PreferenceFragment implements Preference.OnPreferenceChangeListener { + extends PreferenceFragmentCompat implements Preference.OnPreferenceChangeListener { public static final String EXTRA_CATEGORY_TYPE = "type"; private @TracingPreferences.CategoryType int mType; @@ -35,11 +34,11 @@ private static final String MSG_CATEGORY_SELECTION_TITLE = "Select categories"; @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { getActivity().setTitle(MSG_CATEGORY_SELECTION_TITLE); - PreferenceUtils.addPreferencesFromResource(this, R.xml.blank_preference_fragment_screen); - getPreferenceScreen().setOrderingAsAdded(true); + PreferenceScreen preferenceScreen = + getPreferenceManager().createPreferenceScreen(getPreferenceManager().getContext()); + preferenceScreen.setOrderingAsAdded(true); mType = getArguments().getInt(EXTRA_CATEGORY_TYPE); mEnabledCategories = new HashSet<>(TracingPreferences.getEnabledCategories(mType)); @@ -48,12 +47,14 @@ new ArrayList<>(TracingController.getInstance().getKnownCategories()); Collections.sort(sortedCategories); for (String category : sortedCategories) { - if (TracingPreferences.getCategoryType(category) == mType) createPreference(category); + if (TracingPreferences.getCategoryType(category) == mType) + preferenceScreen.addPreference(createPreference(category)); } + setPreferenceScreen(preferenceScreen); } - private void createPreference(String category) { - CheckBoxPreference preference = new ChromeBaseCheckBoxPreference(getActivity(), null); + private CheckBoxPreference createPreference(String category) { + CheckBoxPreference preference = new ChromeBaseCheckBoxPreferenceCompat(getActivity(), null); preference.setKey(category); preference.setTitle(category.startsWith(TracingPreferences.NON_DEFAULT_CATEGORY_PREFIX) ? category.substring( @@ -62,7 +63,7 @@ preference.setChecked(mEnabledCategories.contains(category)); preference.setPersistent(false); // We persist the preference value ourselves. preference.setOnPreferenceChangeListener(this); - getPreferenceScreen().addPreference(preference); + return preference; } @Override
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/privacy/PrivacyPreferences.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/privacy/PrivacyPreferences.java index 91b55c5..45b329c7 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/privacy/PrivacyPreferences.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/privacy/PrivacyPreferences.java
@@ -5,12 +5,11 @@ package org.chromium.chrome.browser.preferences.privacy; import android.os.Bundle; -import android.preference.CheckBoxPreference; -import android.preference.Preference; -import android.preference.Preference.OnPreferenceChangeListener; -import android.preference.PreferenceFragment; -import android.preference.PreferenceScreen; import android.support.graphics.drawable.VectorDrawableCompat; +import android.support.v7.preference.CheckBoxPreference; +import android.support.v7.preference.Preference; +import android.support.v7.preference.PreferenceFragmentCompat; +import android.support.v7.preference.PreferenceScreen; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; @@ -21,8 +20,8 @@ import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.contextualsearch.ContextualSearchFieldTrial; import org.chromium.chrome.browser.help.HelpAndFeedback; -import org.chromium.chrome.browser.preferences.ChromeBaseCheckBoxPreference; -import org.chromium.chrome.browser.preferences.ManagedPreferenceDelegate; +import org.chromium.chrome.browser.preferences.ChromeBaseCheckBoxPreferenceCompat; +import org.chromium.chrome.browser.preferences.ManagedPreferenceDelegateCompat; import org.chromium.chrome.browser.preferences.Pref; import org.chromium.chrome.browser.preferences.PrefServiceBridge; import org.chromium.chrome.browser.preferences.PreferenceUtils; @@ -36,8 +35,8 @@ /** * Fragment to keep track of the all the privacy related preferences. */ -public class PrivacyPreferences extends PreferenceFragment - implements OnPreferenceChangeListener { +public class PrivacyPreferences + extends PreferenceFragmentCompat implements Preference.OnPreferenceChangeListener { private static final String PREF_NAVIGATION_ERROR = "navigation_error"; private static final String PREF_SEARCH_SUGGESTIONS = "search_suggestions"; private static final String PREF_SAFE_BROWSING_SCOUT_REPORTING = @@ -54,11 +53,10 @@ private static final String PREF_SYNC_AND_SERVICES_LINK = "sync_and_services_link"; private static final String PREF_USAGE_STATS = "usage_stats_reporting"; - private ManagedPreferenceDelegate mManagedPreferenceDelegate; + private ManagedPreferenceDelegateCompat mManagedPreferenceDelegate; @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { PrivacyPreferencesManager privacyPrefManager = PrivacyPreferencesManager.getInstance(); privacyPrefManager.migrateNetworkPredictionPreferences(); PreferenceUtils.addPreferencesFromResource(this, R.xml.privacy_preferences); @@ -69,12 +67,12 @@ mManagedPreferenceDelegate = createManagedPreferenceDelegate(); - ChromeBaseCheckBoxPreference canMakePaymentPref = - (ChromeBaseCheckBoxPreference) findPreference(PREF_CAN_MAKE_PAYMENT); + ChromeBaseCheckBoxPreferenceCompat canMakePaymentPref = + (ChromeBaseCheckBoxPreferenceCompat) findPreference(PREF_CAN_MAKE_PAYMENT); canMakePaymentPref.setOnPreferenceChangeListener(this); - ChromeBaseCheckBoxPreference networkPredictionPref = - (ChromeBaseCheckBoxPreference) findPreference(PREF_NETWORK_PREDICTIONS); + ChromeBaseCheckBoxPreferenceCompat networkPredictionPref = + (ChromeBaseCheckBoxPreferenceCompat) findPreference(PREF_NETWORK_PREDICTIONS); networkPredictionPref.setChecked(prefServiceBridge.getNetworkPredictionEnabled()); networkPredictionPref.setOnPreferenceChangeListener(this); networkPredictionPref.setManagedPreferenceDelegate(mManagedPreferenceDelegate); @@ -117,13 +115,13 @@ preferenceScreen.removePreference(findPreference(PREF_SYNC_AND_SERVICES_LINK_DIVIDER)); preferenceScreen.removePreference(findPreference(PREF_SYNC_AND_SERVICES_LINK)); - ChromeBaseCheckBoxPreference navigationErrorPref = - (ChromeBaseCheckBoxPreference) findPreference(PREF_NAVIGATION_ERROR); + ChromeBaseCheckBoxPreferenceCompat navigationErrorPref = + (ChromeBaseCheckBoxPreferenceCompat) findPreference(PREF_NAVIGATION_ERROR); navigationErrorPref.setOnPreferenceChangeListener(this); navigationErrorPref.setManagedPreferenceDelegate(mManagedPreferenceDelegate); - ChromeBaseCheckBoxPreference searchSuggestionsPref = - (ChromeBaseCheckBoxPreference) findPreference(PREF_SEARCH_SUGGESTIONS); + ChromeBaseCheckBoxPreferenceCompat searchSuggestionsPref = + (ChromeBaseCheckBoxPreferenceCompat) findPreference(PREF_SEARCH_SUGGESTIONS); searchSuggestionsPref.setOnPreferenceChangeListener(this); searchSuggestionsPref.setManagedPreferenceDelegate(mManagedPreferenceDelegate); @@ -132,13 +130,14 @@ } // Listen to changes to the Extended Reporting pref. - ChromeBaseCheckBoxPreference scoutReportingPref = - (ChromeBaseCheckBoxPreference) findPreference(PREF_SAFE_BROWSING_SCOUT_REPORTING); + ChromeBaseCheckBoxPreferenceCompat scoutReportingPref = + (ChromeBaseCheckBoxPreferenceCompat) findPreference( + PREF_SAFE_BROWSING_SCOUT_REPORTING); scoutReportingPref.setOnPreferenceChangeListener(this); scoutReportingPref.setManagedPreferenceDelegate(mManagedPreferenceDelegate); - ChromeBaseCheckBoxPreference safeBrowsingPref = - (ChromeBaseCheckBoxPreference) findPreference(PREF_SAFE_BROWSING); + ChromeBaseCheckBoxPreferenceCompat safeBrowsingPref = + (ChromeBaseCheckBoxPreferenceCompat) findPreference(PREF_SAFE_BROWSING); safeBrowsingPref.setOnPreferenceChangeListener(this); safeBrowsingPref.setManagedPreferenceDelegate(mManagedPreferenceDelegate); @@ -261,7 +260,7 @@ } } - private ManagedPreferenceDelegate createManagedPreferenceDelegate() { + private ManagedPreferenceDelegateCompat createManagedPreferenceDelegate() { return preference -> { String key = preference.getKey(); PrefServiceBridge prefs = PrefServiceBridge.getInstance();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/DEPS b/chrome/android/java/src/org/chromium/chrome/browser/tab/DEPS index fc98d94..fb93273 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/DEPS +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/DEPS
@@ -7,7 +7,7 @@ 'Tab\.java': [ "+chrome/android/java/src/org/chromium/chrome/browser/night_mode", "+chrome/android/java/src/org/chromium/chrome/browser/tab", - "+chrome/android/java/src/org/chromium/chrome/browser/util", + "+chrome/lib/util/public", "-components", "+components/embedder_support/android/java/src/org/chromium/components/embedder_support/view", "+components/navigation_interception/android/java/src/org/chromium/components/navigation_interception",
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/EmptyTabObserver.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/EmptyTabObserver.java index 1e72da8..3ea315d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/EmptyTabObserver.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/EmptyTabObserver.java
@@ -162,11 +162,5 @@ public void onFindMatchRectsAvailable(FindMatchRectsDetails result) {} @Override - public void onContentViewChildrenStateUpdated(Tab tab) {} - - @Override - public void onContentViewSystemUiVisibilityChanged(Tab tab, int visibility) {} - - @Override public void onRootIdChanged(Tab tab, int newRootId) {} }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/Tab.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/Tab.java index 21186548..6222404 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/Tab.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/Tab.java
@@ -77,8 +77,7 @@ * The basic Java representation of a tab. Contains and manages a {@link ContentView}. * This class is not intended to be extended. */ -public class Tab - implements ViewGroup.OnHierarchyChangeListener, View.OnSystemUiVisibilityChangeListener { +public class Tab { public static final int INVALID_TAB_ID = -1; /** Return value from {@link #getBookmarkId()} if this tab is not bookmarked. */ @@ -1171,8 +1170,6 @@ mWebContents.setImportance(mImportance); ContentUtils.setUserAgentOverride(mWebContents); - mContentView.setOnHierarchyChangeListener(this); - mContentView.setOnSystemUiVisibilityChangeListener(this); mContentView.addOnAttachStateChangeListener(mAttachStateChangeListener); updateInteractableState(); @@ -1565,8 +1562,6 @@ private final void destroyWebContents(boolean deleteNativeWebContents) { if (mWebContents == null) return; - mContentView.setOnHierarchyChangeListener(null); - mContentView.setOnSystemUiVisibilityChangeListener(null); mContentView.removeOnAttachStateChangeListener(mAttachStateChangeListener); mContentView = null; updateInteractableState(); @@ -1820,33 +1815,6 @@ getNativePage().getTitle()); } - @Override - public void onChildViewRemoved(View parent, View child) { - // TODO(jinsukkim): Consider updating |ContentView| to allow multiple - // OnHierarchyChangeListener and OnSystemUiVisibilityChangeListener - // to be added to not allow FullscreenManager to get the contentview - // and add its own observers as needed. - updateContentViewChildrenState(); - } - - @Override - public void onChildViewAdded(View parent, View child) { - updateContentViewChildrenState(); - } - - private void updateContentViewChildrenState() { - RewindableIterator<TabObserver> observers = getTabObservers(); - while (observers.hasNext()) observers.next().onContentViewChildrenStateUpdated(this); - } - - @Override - public void onSystemUiVisibilityChange(int visibility) { - RewindableIterator<TabObserver> observers = getTabObservers(); - while (observers.hasNext()) { - observers.next().onContentViewSystemUiVisibilityChanged(this, visibility); - } - } - /** * @return The ID of the bookmark associated with the current URL, or * {@link #INVALID_BOOKMARK_ID} if no such bookmark exists.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabObserver.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabObserver.java index e624f30..c1c3b09 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabObserver.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabObserver.java
@@ -356,18 +356,6 @@ void onFindMatchRectsAvailable(FindMatchRectsDetails result); /** - * Invoked when a child view is added or removed to Tab's content view. - */ - void onContentViewChildrenStateUpdated(Tab tab); - - /** - * Invoked when the status bar changes visibility. - * @param visibility Flags indicating the global state of the UI visibility. - * @see View#setSystemUiVisibility(int) - */ - void onContentViewSystemUiVisibilityChanged(Tab tab, int visibility); - - /** * Called when the root Id of tab is changed. * @param newRootId New root ID to be set. */
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/util/OWNERS b/chrome/android/java/src/org/chromium/chrome/browser/util/OWNERS deleted file mode 100644 index b0d3ec10..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/util/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -mdjones@chromium.org -twellington@chromium.org
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/partnercustomizations/PartnerHomepageIntegrationTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/partnercustomizations/PartnerHomepageIntegrationTest.java index 66cc037..2d3d064a 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/partnercustomizations/PartnerHomepageIntegrationTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/partnercustomizations/PartnerHomepageIntegrationTest.java
@@ -10,7 +10,7 @@ import android.os.Build; import android.support.test.InstrumentationRegistry; import android.support.test.filters.MediumTest; -import android.support.v7.widget.SwitchCompat; +import android.support.v7.preference.PreferenceFragmentCompat; import android.view.View; import android.widget.Button; import android.widget.EditText; @@ -28,6 +28,7 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.ChromeTabbedActivity; +import org.chromium.chrome.browser.preferences.ChromeSwitchPreferenceCompat; import org.chromium.chrome.browser.preferences.HomepageEditor; import org.chromium.chrome.browser.preferences.HomepagePreferences; import org.chromium.chrome.browser.preferences.Preferences; @@ -44,7 +45,6 @@ import org.chromium.content_public.browser.test.util.UiUtils; import org.chromium.net.test.EmbeddedTestServer; -import java.util.concurrent.Callable; import java.util.concurrent.TimeoutException; /** @@ -117,17 +117,9 @@ @Test @MediumTest @Feature({"Homepage"}) - @RetryOnFailure public void testHomepageButtonEnableDisable() { // Disable homepage. - Preferences homepagePreferenceActivity = - mActivityTestRule.startPreferences(HomepagePreferences.class.getName()); - SwitchCompat homepageSwitch = - (SwitchCompat) homepagePreferenceActivity.findViewById(R.id.switch_widget); - Assert.assertNotNull(homepageSwitch); - TouchCommon.singleClickView(homepageSwitch); - waitForCheckedState(homepagePreferenceActivity, false); - homepagePreferenceActivity.finish(); + toggleHomepageSwitchPreference(false); // Assert no homepage button. Assert.assertFalse(HomepageManager.isHomepageEnabled()); @@ -137,13 +129,7 @@ }); // Enable homepage. - homepagePreferenceActivity = - mActivityTestRule.startPreferences(HomepagePreferences.class.getName()); - homepageSwitch = (SwitchCompat) homepagePreferenceActivity.findViewById(R.id.switch_widget); - Assert.assertNotNull(homepageSwitch); - TouchCommon.singleClickView(homepageSwitch); - waitForCheckedState(homepagePreferenceActivity, true); - homepagePreferenceActivity.finish(); + toggleHomepageSwitchPreference(true); // Assert homepage button. Assert.assertTrue(HomepageManager.isHomepageEnabled()); @@ -153,19 +139,6 @@ }); } - private void waitForCheckedState(final Preferences preferenceActivity, boolean isChecked) { - CriteriaHelper.pollUiThread(Criteria.equals(isChecked, new Callable<Boolean>() { - @Override - public Boolean call() { - // The underlying switch view in the preference can change, so we need to fetch - // it each time to ensure we are checking the activity view. - SwitchCompat homepageSwitch = - (SwitchCompat) preferenceActivity.findViewById(R.id.switch_widget); - return homepageSwitch.isChecked(); - } - })); - } - /** * Custom homepage URI should be fixed (e.g., "chrome.com" -> "http://chrome.com/") * when the URI is saved from the home page edit screen. @@ -260,4 +233,30 @@ mActivityTestRule.getActivity().isFinishing() || mActivityTestRule.getActivity().isDestroyed()); } + + /** + * Toggle the state of the homepage switch preference in settings by performing a click on it. + * + * @param expected Expected checked state of the preference switch after clicking. + */ + private void toggleHomepageSwitchPreference(boolean expected) { + // Launch preference activity with Homepage settings fragment. + Preferences homepagePreferenceActivity = + mActivityTestRule.startPreferences(HomepagePreferences.class.getName()); + PreferenceFragmentCompat fragment = + (PreferenceFragmentCompat) homepagePreferenceActivity.getSupportFragmentManager() + .findFragmentById(android.R.id.content); + ChromeSwitchPreferenceCompat preference = + (ChromeSwitchPreferenceCompat) fragment.findPreference( + HomepagePreferences.PREF_HOMEPAGE_SWITCH); + Assert.assertNotNull(preference); + + // Click toggle and verify that checked state matches expectation. + TestThreadUtils.runOnUiThreadBlocking(() -> { + preference.performClick(); + Assert.assertEquals(preference.isChecked(), expected); + }); + + homepagePreferenceActivity.finish(); + } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/preferences/developer/TracingPreferencesTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/preferences/developer/TracingPreferencesTest.java index 8f10ccb..2dc5620 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/preferences/developer/TracingPreferencesTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/preferences/developer/TracingPreferencesTest.java
@@ -12,12 +12,11 @@ import android.app.PendingIntent; import android.content.Context; import android.content.Intent; -import android.preference.CheckBoxPreference; -import android.preference.PreferenceFragment; import android.support.test.InstrumentationRegistry; import android.support.test.filters.MediumTest; import android.support.test.filters.SmallTest; import android.support.v4.app.NotificationCompat; +import android.support.v7.preference.CheckBoxPreference; import android.support.v7.preference.ListPreference; import android.support.v7.preference.Preference; import android.support.v7.preference.PreferenceFragmentCompat; @@ -39,7 +38,6 @@ import org.chromium.chrome.browser.preferences.ButtonPreferenceCompat; import org.chromium.chrome.browser.preferences.Preferences; import org.chromium.chrome.browser.preferences.PreferencesLauncher; -import org.chromium.chrome.browser.preferences.PreferencesTest; import org.chromium.chrome.browser.preferences.TextMessagePreferenceCompat; import org.chromium.chrome.browser.tracing.TracingController; import org.chromium.chrome.browser.tracing.TracingNotificationManager; @@ -308,8 +306,8 @@ (Preferences) InstrumentationRegistry.getInstrumentation().startActivitySync( intent); - PreferenceFragment categoriesFragment = - (PreferenceFragment) categoriesActivity.getMainFragment(); + PreferenceFragmentCompat categoriesFragment = + (PreferenceFragmentCompat) categoriesActivity.getMainFragmentCompat(); Assert.assertEquals(TracingCategoriesPreferences.class, categoriesFragment.getClass()); CheckBoxPreference sampleCategoryPref = @@ -321,9 +319,7 @@ Assert.assertEquals(originallyEnabled, sampleCategoryPref.isChecked()); // Simulate selecting / deselecting the category. - TestThreadUtils.runOnUiThreadBlocking(() -> { - PreferencesTest.clickPreference(categoriesFragment, sampleCategoryPref); - }); + TestThreadUtils.runOnUiThreadBlocking(sampleCategoryPref::performClick); Assert.assertNotEquals(originallyEnabled, sampleCategoryPref.isChecked()); boolean finallyEnabled = TracingPreferences.getEnabledCategories().contains(sampleCategoryName);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/ssl/CaptivePortalTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/ssl/CaptivePortalTest.java index 82333af..790f6a76 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/ssl/CaptivePortalTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/ssl/CaptivePortalTest.java
@@ -111,13 +111,6 @@ ChromeTabUtils.loadUrlOnUiThread( tab, mServer.getURL("/chrome/test/data/android/navigate/simple.html")); - // If committed interstitials are enabled, the interstitial is a regular navigation, so we - // skip interstitial specific checks, and just check the page title. - if (!ChromeFeatureList.isEnabled(ChromeFeatureList.SSL_COMMITTED_INTERSTITIALS)) { - waitForInterstitial(tab.getWebContents(), true); - Assert.assertTrue(tab.isShowingInterstitialPage()); - } - new TabTitleObserver(tab, CAPTIVE_PORTAL_INTERSTITIAL_TITLE_PREFIX) { @Override protected boolean doesTitleMatch(String expectedTitle, String actualTitle) { @@ -185,13 +178,6 @@ ChromeTabUtils.loadUrlOnUiThread( tab, mServer.getURL("/chrome/test/data/android/navigate/simple.html")); - // If committed interstitials are enabled, the interstitial is a regular navigation, so we - // skip interstitial specific checks, and just check the page title. - if (!ChromeFeatureList.isEnabled(ChromeFeatureList.SSL_COMMITTED_INTERSTITIALS)) { - waitForInterstitial(tab.getWebContents(), true); - Assert.assertTrue(tab.isShowingInterstitialPage()); - } - new TabTitleObserver(tab, SSL_INTERSTITIAL_TITLE) .waitForTitleUpdate(INTERSTITIAL_TITLE_UPDATE_TIMEOUT_SECONDS);
diff --git a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/DinoActivity.java b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/DinoActivity.java index dc746b4..6e1b86e8 100644 --- a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/DinoActivity.java +++ b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/DinoActivity.java
@@ -19,6 +19,7 @@ import org.chromium.chrome.browser.fullscreen.ChromeFullscreenManager; import org.chromium.chrome.browser.tab.EmptyTabObserver; import org.chromium.chrome.browser.tab.Tab; +import org.chromium.chrome.browser.tab.TabDelegateFactory; import org.chromium.chrome.browser.tab.TabState; import org.chromium.chrome.browser.util.UrlConstants; import org.chromium.chrome.touchless.R; @@ -92,8 +93,8 @@ @Override protected TabDelegateFactory createTabDelegateFactory() { - return new NoBrowserControlsTabDelegateFactory( - getFullscreenManager().getBrowserVisibilityDelegate()); + return new NoTouchTabDelegateFactory( + this, getFullscreenManager().getBrowserVisibilityDelegate()); } @Override
diff --git a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/NoTouchActivity.java b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/NoTouchActivity.java index 2125997d..f7177a5 100644 --- a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/NoTouchActivity.java +++ b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/NoTouchActivity.java
@@ -24,6 +24,7 @@ import org.chromium.chrome.browser.fullscreen.ChromeFullscreenManager; import org.chromium.chrome.browser.preferences.ChromePreferenceManager; import org.chromium.chrome.browser.tab.Tab; +import org.chromium.chrome.browser.tab.TabDelegateFactory; import org.chromium.chrome.browser.tab.TabRedirectHandler; import org.chromium.chrome.browser.tab.TabState; import org.chromium.chrome.browser.tabmodel.document.TabDelegate; @@ -211,8 +212,8 @@ @Override protected TabDelegateFactory createTabDelegateFactory() { - return new NoBrowserControlsTabDelegateFactory( - getFullscreenManager().getBrowserVisibilityDelegate()); + return new NoTouchTabDelegateFactory( + this, getFullscreenManager().getBrowserVisibilityDelegate()); } @Override
diff --git a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/NoTouchTabDelegateFactory.java b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/NoTouchTabDelegateFactory.java index eeb020f2..73bc628 100644 --- a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/NoTouchTabDelegateFactory.java +++ b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/NoTouchTabDelegateFactory.java
@@ -4,16 +4,20 @@ package org.chromium.chrome.browser.touchless; +import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.tab.BrowserControlsVisibilityDelegate; -import org.chromium.chrome.browser.tab.TabDelegateFactory; +import org.chromium.chrome.browser.tab.Tab; +import org.chromium.chrome.browser.tab_activity_glue.TabDelegateFactoryImpl; /** * TabDelegateFactory for all touchless activities. */ -public class NoTouchTabDelegateFactory extends TabDelegateFactory { +public class NoTouchTabDelegateFactory extends TabDelegateFactoryImpl { private final BrowserControlsVisibilityDelegate mDelegate; - public NoTouchTabDelegateFactory(BrowserControlsVisibilityDelegate delegate) { + public NoTouchTabDelegateFactory( + ChromeActivity activity, BrowserControlsVisibilityDelegate delegate) { + super(activity); mDelegate = delegate; }
diff --git a/chrome/android/touchless/junit/src/org/chromium/chrome/browser/touchless/ui/progressbar/ProgressBarMediatorTest.java b/chrome/android/touchless/junit/src/org/chromium/chrome/browser/touchless/ui/progressbar/ProgressBarMediatorTest.java index bec31b7..d259dcb 100644 --- a/chrome/android/touchless/junit/src/org/chromium/chrome/browser/touchless/ui/progressbar/ProgressBarMediatorTest.java +++ b/chrome/android/touchless/junit/src/org/chromium/chrome/browser/touchless/ui/progressbar/ProgressBarMediatorTest.java
@@ -21,9 +21,9 @@ import org.chromium.base.task.test.ShadowPostTask; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.chrome.browser.ActivityTabProvider; -import org.chromium.chrome.browser.UrlConstants; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tab.TabObserver; +import org.chromium.chrome.browser.util.UrlConstants; import org.chromium.chrome.browser.util.test.ShadowUrlUtilities; import org.chromium.ui.modelutil.PropertyModel;
diff --git a/chrome/app/app-entitlements.plist b/chrome/app/app-entitlements.plist index a64a5ec0..1a198c5b 100644 --- a/chrome/app/app-entitlements.plist +++ b/chrome/app/app-entitlements.plist
@@ -8,5 +8,15 @@ <array> <string>${CHROMIUM_TEAM_ID}.${CHROMIUM_BUNDLE_ID}.webauthn</string> </array> + <key>com.apple.security.device.audio-input</key> + <true/> + <key>com.apple.security.device.bluetooth</key> + <true/> + <key>com.apple.security.device.camera</key> + <true/> + <key>com.apple.security.device.print</key> + <true/> + <key>com.apple.security.device.usb</key> + <true/> </dict> </plist>
diff --git a/chrome/app/os_settings_strings.grdp b/chrome/app/os_settings_strings.grdp index 9c500e3..a69266f 100644 --- a/chrome/app/os_settings_strings.grdp +++ b/chrome/app/os_settings_strings.grdp
@@ -2,6 +2,14 @@ <!-- Settings-specific strings (included from generated_resources.grd). --> <grit-part> <if expr="chromeos"> + <!-- People (OS settings) --> + <message name="IDS_OS_SETTINGS_PROFILE_LABEL" desc="Label underneath the profile's real name, listing the email address and optionally the number of additional accounts"> + {COUNT, plural, + =0 {<ph name="EMAIL">$1<ex>alice@example.com</ex></ph>} + =1 {<ph name="EMAIL">$1<ex>alice@example.com</ex></ph>, +1 more account} + other {<ph name="EMAIL">$1<ex>alice@example.com</ex></ph>, +<ph name="EXTRA_ACCOUNTS">$2<ex>2</ex></ph> more accounts}} + </message> + <!-- Languages and Inputs (OS settings) --> <message name="IDS_OS_SETTINGS_LANGUAGES_AND_INPUT_PAGE_TITLE" desc="Name of the OS settings page which displays language method preferences."> Languages and input
diff --git a/chrome/app/settings_strings.grdp b/chrome/app/settings_strings.grdp index d20b11c..1b0852f 100644 --- a/chrome/app/settings_strings.grdp +++ b/chrome/app/settings_strings.grdp
@@ -220,7 +220,7 @@ <message name="IDS_SETTINGS_SWITCH_ACCESS_AUTO_SCAN_LABEL" desc="Label for the toggle which enables automatic scanning between elements in Switch Access."> Enable auto-scan </message> - <message name="IDS_SETTINGS_SWITCH_ACCESS_AUTO_SCAN_SPEED_LABEL" desc="Label for slider which sets the time interval for automatically scanning to the next element. Will be immediately followed by the numeric value of the interval."> + <message name="IDS_SETTINGS_SWITCH_ACCESS_AUTO_SCAN_SPEED_LABEL" desc="Label for slider which sets the time interval for Switch Access to automatically scan to the next element."> Scanning speed: <ph name="SPEED_WITH_UNITS">$1<ex>1.5s</ex></ph> </message> <message name="IDS_SETTINGS_DURATION_IN_SECONDS" desc="A duration in seconds. Should be short.">
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index feab02c0..a1a503f 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -1406,6 +1406,10 @@ {"shelf-hover-previews", flag_descriptions::kShelfHoverPreviewsName, flag_descriptions::kShelfHoverPreviewsDescription, kOsCrOS, SINGLE_VALUE_TYPE(chromeos::switches::kShelfHoverPreviews)}, + {"show-bluetooth-device-battery", + flag_descriptions::kShowBluetoothDeviceBatteryName, + flag_descriptions::kShowBluetoothDeviceBatteryDescription, kOsCrOS, + FEATURE_VALUE_TYPE(chromeos::features::kShowBluetoothDeviceBattery)}, {"show-taps", flag_descriptions::kShowTapsName, flag_descriptions::kShowTapsDescription, kOsCrOS, SINGLE_VALUE_TYPE(ash::switches::kShowTaps)}, @@ -3649,13 +3653,6 @@ FEATURE_VALUE_TYPE( autofill::features::kAutofillUseImprovedLabelDisambiguation)}, -#if defined(OS_CHROMEOS) - {"ash-notification-stacking-bar-redesign", - flag_descriptions::kAshNotificationStackingBarRedesignName, - flag_descriptions::kAshNotificationStackingBarRedesignDescription, kOsCrOS, - FEATURE_VALUE_TYPE(ash::features::kNotificationStackingBarRedesign)}, -#endif // OS_CHROMEOS - #if defined(OS_ANDROID) {"cct-target-translate-language", flag_descriptions::kCCTTargetTranslateLanguageName,
diff --git a/chrome/browser/accessibility/interstitial_accessibility_browsertest.cc b/chrome/browser/accessibility/interstitial_accessibility_browsertest.cc index b6088ff..bd453ac 100644 --- a/chrome/browser/accessibility/interstitial_accessibility_browsertest.cc +++ b/chrome/browser/accessibility/interstitial_accessibility_browsertest.cc
@@ -2,11 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/feature_list.h" #include "chrome/browser/ssl/ssl_blocking_page.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/common/chrome_features.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/security_interstitials/content/security_interstitial_tab_helper.h" @@ -38,38 +36,22 @@ net::EmbeddedTestServer https_server_mismatched_; bool IsShowingInterstitial(content::WebContents* tab) { - if (base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials)) { - security_interstitials::SecurityInterstitialTabHelper* helper = - security_interstitials::SecurityInterstitialTabHelper:: - FromWebContents(tab); - if (!helper) { - return false; - } - return helper - ->GetBlockingPageForCurrentlyCommittedNavigationForTesting() != - nullptr; + security_interstitials::SecurityInterstitialTabHelper* helper = + security_interstitials::SecurityInterstitialTabHelper::FromWebContents( + tab); + if (!helper) { + return false; } - return tab->ShowingInterstitialPage(); + return helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting() != + nullptr; } void ProceedThroughInterstitial(content::WebContents* web_contents) { - if (base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials)) { - content::TestNavigationObserver nav_observer(web_contents, 1); - std::string javascript = - "window.certificateErrorPageController.proceed();"; - ASSERT_TRUE(content::ExecuteScript(web_contents, javascript)); - nav_observer.Wait(); - return; - } - content::InterstitialPage* interstitial_page = - web_contents->GetInterstitialPage(); - ASSERT_TRUE(interstitial_page); - ASSERT_EQ(SSLBlockingPage::kTypeForTesting, - interstitial_page->GetDelegateForTesting()->GetTypeForTesting()); - SSLBlockingPage* ssl_interstitial = static_cast<SSLBlockingPage*>( - interstitial_page->GetDelegateForTesting()); - ssl_interstitial->CommandReceived( - base::NumberToString(security_interstitials::CMD_PROCEED)); + content::TestNavigationObserver nav_observer(web_contents, 1); + std::string javascript = "window.certificateErrorPageController.proceed();"; + ASSERT_TRUE(content::ExecuteScript(web_contents, javascript)); + nav_observer.Wait(); + return; } };
diff --git a/chrome/browser/android/chrome_feature_list.cc b/chrome/browser/android/chrome_feature_list.cc index 20a48aa..a0f816f 100644 --- a/chrome/browser/android/chrome_feature_list.cc +++ b/chrome/browser/android/chrome_feature_list.cc
@@ -74,7 +74,6 @@ &features::kServiceWorkerPaymentApps, &features::kSensorContentSetting, &features::kShowTrustedPublisherURL, - &features::kSSLCommittedInterstitials, &features::kUserActivationV2, &features::kWebAuth, &features::kWebPayments,
diff --git a/chrome/browser/apps/guest_view/web_view_browsertest.cc b/chrome/browser/apps/guest_view/web_view_browsertest.cc index 06ffc48..4ee7f5de 100644 --- a/chrome/browser/apps/guest_view/web_view_browsertest.cc +++ b/chrome/browser/apps/guest_view/web_view_browsertest.cc
@@ -357,24 +357,16 @@ #endif -bool AreCommittedInterstitialsEnabled() { - return base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials); -} - bool IsShowingInterstitial(content::WebContents* tab) { - if (AreCommittedInterstitialsEnabled()) { - security_interstitials::SecurityInterstitialTabHelper* helper = - security_interstitials::SecurityInterstitialTabHelper::FromWebContents( - tab); - if (!helper) { - return false; - } else { - return helper - ->GetBlockingPageForCurrentlyCommittedNavigationForTesting() != - nullptr; - } + security_interstitials::SecurityInterstitialTabHelper* helper = + security_interstitials::SecurityInterstitialTabHelper::FromWebContents( + tab); + if (!helper) { + return false; + } else { + return helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting() != + nullptr; } - return tab->GetInterstitialPage() != nullptr; } } // namespace @@ -749,16 +741,12 @@ GetGuestViewManager()->WaitForSingleGuestCreated(); ASSERT_TRUE( guest_web_contents->GetMainFrame()->GetProcess()->IsForGuestsOnly()); - if (AreCommittedInterstitialsEnabled()) { - GURL target_url = https_server.GetURL( - "/extensions/platform_apps/web_view/interstitial_teardown/" - "https_page.html"); - content::TestNavigationObserver observer(target_url); - observer.WatchExistingWebContents(); - observer.WaitForNavigationFinished(); - } else { - content::WaitForInterstitialAttach(guest_web_contents); - } + GURL target_url = https_server.GetURL( + "/extensions/platform_apps/web_view/interstitial_teardown/" + "https_page.html"); + content::TestNavigationObserver observer(target_url); + observer.WatchExistingWebContents(); + observer.WaitForNavigationFinished(); } // Runs media_access/allow tests. @@ -1884,17 +1872,7 @@ content::WebContents* guest_web_contents = GetGuestViewManager()->WaitForSingleGuestCreated(); - if (AreCommittedInterstitialsEnabled()) { - EXPECT_TRUE(IsShowingInterstitial(guest_web_contents)); - } else { - EXPECT_TRUE(guest_web_contents->ShowingInterstitialPage()); - EXPECT_TRUE(guest_web_contents->GetInterstitialPage() - ->GetMainFrame() - ->GetView() - ->IsShowing()); - EXPECT_TRUE(content::IsInnerInterstitialPageConnected( - guest_web_contents->GetInterstitialPage())); - } + EXPECT_TRUE(IsShowingInterstitial(guest_web_contents)); } // Test makes sure that interstitial pages are registered in the @@ -1912,87 +1890,12 @@ InterstitialTestHelper(); - content::WebContents* outer_web_contents = GetFirstAppWindowWebContents(); - content::WebContents* guest_web_contents = - GetGuestViewManager()->WaitForSingleGuestCreated(); + content::WebContents* web_contents = GetFirstAppWindowWebContents(); std::vector<content::RenderWidgetHostView*> hosts = - content::GetInputEventRouterRenderWidgetHostViews(outer_web_contents); + content::GetInputEventRouterRenderWidgetHostViews(web_contents); - if (AreCommittedInterstitialsEnabled()) { - // With committed interstitials, interstitials are no longer a special case - // so we can just use the main frame from the WebContents. - EXPECT_TRUE( - base::Contains(hosts, outer_web_contents->GetMainFrame()->GetView())); - } else { - EXPECT_TRUE(base::Contains( - hosts, - guest_web_contents->GetInterstitialPage()->GetMainFrame()->GetView())); - } -} - -// Test makes sure that interstitial pages will receive input events and can be -// focused. -// Flaky on Win dbg: crbug.com/779973 -#if defined(OS_WIN) && !defined(NDEBUG) -#define MAYBE_InterstitialPageFocusedWidget \ - DISABLED_InterstitialPageFocusedWidget -#else -#define MAYBE_InterstitialPageFocusedWidget InterstitialPageFocusedWidget -#endif -IN_PROC_BROWSER_TEST_F(WebViewTest, MAYBE_InterstitialPageFocusedWidget) { - // The purpose of this test is to ensure that the InterstitialPageImpl was - // properly attached to the guest which happens in - // WebContentsImpl::AttachInterstitialPage. With committed interstitials this - // is no longer necessary. - // TODO(carlosil): Remove this test once commited interstitials ships. - // https://crbug.com/755632. - if (AreCommittedInterstitialsEnabled()) - return; - - // This test tests that a inner WebContents' InterstitialPage is properly - // connected to an outer WebContents through a CrossProcessFrameConnector. - InterstitialTestHelper(); - - content::WebContents* outer_web_contents = GetFirstAppWindowWebContents(); - content::WebContents* guest_web_contents = - GetGuestViewManager()->WaitForSingleGuestCreated(); - - content::RenderFrameHost* interstitial_main_frame = - guest_web_contents->GetInterstitialPage()->GetMainFrame(); - content::RenderWidgetHost* interstitial_widget = - interstitial_main_frame->GetRenderViewHost()->GetWidget(); - - content::WaitForHitTestDataOrChildSurfaceReady(interstitial_main_frame); - - EXPECT_NE(interstitial_widget, - content::GetFocusedRenderWidgetHost(guest_web_contents)); - EXPECT_NE(interstitial_widget, - content::GetFocusedRenderWidgetHost(outer_web_contents)); - - // Send mouse down. - blink::WebMouseEvent event; - event.button = blink::WebPointerProperties::Button::kLeft; - event.SetType(blink::WebInputEvent::kMouseDown); - event.SetPositionInWidget(10, 10); - content::RouteMouseEvent(outer_web_contents, &event); - - // Wait a frame. - content::MainThreadFrameObserver observer(interstitial_widget); - observer.Wait(); - - // Send mouse up. - event.SetType(blink::WebInputEvent::kMouseUp); - event.SetPositionInWidget(10, 10); - content::RouteMouseEvent(outer_web_contents, &event); - - // Wait another frame. - observer.Wait(); - - EXPECT_EQ(interstitial_widget, - content::GetFocusedRenderWidgetHost(guest_web_contents)); - EXPECT_EQ(interstitial_widget, - content::GetFocusedRenderWidgetHost(outer_web_contents)); + EXPECT_TRUE(base::Contains(hosts, web_contents->GetMainFrame()->GetView())); } // Test makes sure that the browser does not crash when a <webview> navigates
diff --git a/chrome/browser/browser_process_impl.cc b/chrome/browser/browser_process_impl.cc index e83f7b0..edb060d 100644 --- a/chrome/browser/browser_process_impl.cc +++ b/chrome/browser/browser_process_impl.cc
@@ -1143,6 +1143,8 @@ extensions::kExtensionScheme, true); #endif + battery_metrics_ = std::make_unique<BatteryMetrics>(); + secure_origin_prefs_observer_ = std::make_unique<SecureOriginPrefsObserver>(local_state()); site_isolation_prefs_observer_ = @@ -1174,12 +1176,6 @@ io_thread_ = std::make_unique<IOThread>(net_log_.get()); } -void BrowserProcessImpl::ServiceManagerConnectionStarted( - content::ServiceManagerConnection* connection) { - // This uses the service manager so it must happen after it's started. - battery_metrics_ = std::make_unique<BatteryMetrics>(); -} - void BrowserProcessImpl::PreMainMessageLoopRun() { TRACE_EVENT0("startup", "BrowserProcessImpl::PreMainMessageLoopRun"); SCOPED_UMA_HISTOGRAM_TIMER(
diff --git a/chrome/browser/browser_process_impl.h b/chrome/browser/browser_process_impl.h index fccea77a..7c28d1e5 100644 --- a/chrome/browser/browser_process_impl.h +++ b/chrome/browser/browser_process_impl.h
@@ -109,11 +109,6 @@ // Called before the browser threads are created. void PreCreateThreads(const base::CommandLine& command_line); - // Called after the browser threads are created, and service manager is set - // up. - void ServiceManagerConnectionStarted( - content::ServiceManagerConnection* connection); - // Called after the threads have been created but before the message loops // starts running. Allows the browser process to do any initialization that // requires all threads running.
diff --git a/chrome/browser/captive_portal/captive_portal_browsertest.cc b/chrome/browser/captive_portal/captive_portal_browsertest.cc index 10884bf6..d42e450 100644 --- a/chrome/browser/captive_portal/captive_portal_browsertest.cc +++ b/chrome/browser/captive_portal/captive_portal_browsertest.cc
@@ -587,9 +587,7 @@ bool IsShowingInterstitial(WebContents* contents); - // Without committed interstitials, this waits for an interstitial to attach - // to the current WebContents. With committed interstitials, it instead - // asserts an interstitial is showing and waits for the render frame to be + // Asserts an interstitial is showing and waits for the render frame to be // ready. void WaitForInterstitial(content::WebContents* contents); @@ -1062,23 +1060,16 @@ content::InterstitialPageDelegate::TypeID CaptivePortalBrowserTest::GetInterstitialType(WebContents* contents) const { - if (base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials)) { - security_interstitials::SecurityInterstitialTabHelper* helper = - security_interstitials::SecurityInterstitialTabHelper::FromWebContents( - contents); - if (!helper) - return nullptr; - security_interstitials::SecurityInterstitialPage* blocking_page = - helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting(); - if (!blocking_page) - return nullptr; - return blocking_page->GetTypeForTesting(); - } - if (!contents->ShowingInterstitialPage()) + security_interstitials::SecurityInterstitialTabHelper* helper = + security_interstitials::SecurityInterstitialTabHelper::FromWebContents( + contents); + if (!helper) return nullptr; - return contents->GetInterstitialPage() - ->GetDelegateForTesting() - ->GetTypeForTesting(); + security_interstitials::SecurityInterstitialPage* blocking_page = + helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting(); + if (!blocking_page) + return nullptr; + return blocking_page->GetTypeForTesting(); } bool CaptivePortalBrowserTest::IsShowingInterstitial(WebContents* contents) { @@ -1087,15 +1078,8 @@ void CaptivePortalBrowserTest::WaitForInterstitial( content::WebContents* contents) { - if (base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials)) { - ASSERT_TRUE(IsShowingInterstitial(contents)); - ASSERT_TRUE(WaitForRenderFrameReady(contents->GetMainFrame())); - } else { - content::WaitForInterstitialAttach(contents); - ASSERT_TRUE(IsShowingInterstitial(contents)); - ASSERT_TRUE(WaitForRenderFrameReady( - contents->GetInterstitialPage()->GetMainFrame())); - } + ASSERT_TRUE(IsShowingInterstitial(contents)); + ASSERT_TRUE(WaitForRenderFrameReady(contents->GetMainFrame())); } CaptivePortalTabReloader::State CaptivePortalBrowserTest::GetStateOfTabReloader( @@ -1867,10 +1851,7 @@ // Wait for the interstitial to load all the JavaScript code. Otherwise, // trying to click on a button will fail. content::RenderFrameHost* rfh; - if (base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials)) - rfh = broken_tab_contents->GetMainFrame(); - else - rfh = broken_tab_contents->GetInterstitialPage()->GetMainFrame(); + rfh = broken_tab_contents->GetMainFrame(); EXPECT_TRUE(WaitForRenderFrameReady(rfh)); const char kClickConnectButtonJS[] = "document.getElementById('primary-button').click();"; @@ -2684,20 +2665,13 @@ info.unverified_cert = info.cert; FailJobsWithCertError(1, info); navigation_observer.WaitForNavigations(1); - if (base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials)) { - // With committed interstitials, the SSL interstitial navigation will result - // in the captive portal check firing (and returning no captive portal), so - // the state will get reset to none. - EXPECT_EQ(CaptivePortalTabReloader::STATE_NONE, - GetStateOfTabReloaderAt(browser(), broken_tab_index)); - WaitForInterstitial(broken_tab_contents); - portal_observer.WaitForResults(2); - } else { - EXPECT_EQ(CaptivePortalTabReloader::STATE_NEEDS_RELOAD, - GetStateOfTabReloaderAt(browser(), broken_tab_index)); - WaitForInterstitial(broken_tab_contents); - portal_observer.WaitForResults(1); - } + // The SSL interstitial navigation will result in the captive portal check + // firing (and returning no captive portal), so the state will get reset to + // none. + EXPECT_EQ(CaptivePortalTabReloader::STATE_NONE, + GetStateOfTabReloaderAt(browser(), broken_tab_index)); + WaitForInterstitial(broken_tab_contents); + portal_observer.WaitForResults(2); EXPECT_EQ(SSLBlockingPage::kTypeForTesting, GetInterstitialType(broken_tab_contents));
diff --git a/chrome/browser/chrome_browser_main.cc b/chrome/browser/chrome_browser_main.cc index b0642a9..9675f039 100644 --- a/chrome/browser/chrome_browser_main.cc +++ b/chrome/browser/chrome_browser_main.cc
@@ -1179,19 +1179,11 @@ FROM_HERE, {BrowserThread::IO}, base::BindOnce(&tracing::TracingSamplerProfiler::CreateOnChildThread)); #endif -} -void ChromeBrowserMainParts::ServiceManagerConnectionStarted( - content::ServiceManagerConnection* connection) { - // This should be called after the creation of the tracing controller. The - // tracing controller is created when the service manager connection is - // started. tracing::SetupBackgroundTracingFieldTrial(); for (size_t i = 0; i < chrome_extra_parts_.size(); ++i) - chrome_extra_parts_[i]->ServiceManagerConnectionStarted(connection); - - browser_process_->ServiceManagerConnectionStarted(connection); + chrome_extra_parts_[i]->PostCreateThreads(); } void ChromeBrowserMainParts::PreMainMessageLoopRun() {
diff --git a/chrome/browser/chrome_browser_main.h b/chrome/browser/chrome_browser_main.h index 687eb5c..7301c80 100644 --- a/chrome/browser/chrome_browser_main.h +++ b/chrome/browser/chrome_browser_main.h
@@ -65,8 +65,6 @@ void PostMainMessageLoopStart() override; int PreCreateThreads() override; void PostCreateThreads() override; - void ServiceManagerConnectionStarted( - content::ServiceManagerConnection* connection) override; void PreMainMessageLoopRun() override; bool MainMessageLoopRun(int* result_code) override; void PostMainMessageLoopRun() override;
diff --git a/chrome/browser/chrome_browser_main_extra_parts.h b/chrome/browser/chrome_browser_main_extra_parts.h index 7d9a2ee..c5e8850 100644 --- a/chrome/browser/chrome_browser_main_extra_parts.h +++ b/chrome/browser/chrome_browser_main_extra_parts.h
@@ -5,10 +5,6 @@ #ifndef CHROME_BROWSER_CHROME_BROWSER_MAIN_EXTRA_PARTS_H_ #define CHROME_BROWSER_CHROME_BROWSER_MAIN_EXTRA_PARTS_H_ -namespace content { -class ServiceManagerConnection; -} - // Interface class for Parts owned by ChromeBrowserMainParts. // The default implementation for all methods is empty. @@ -38,8 +34,7 @@ // MainMessageLoopRun methods. virtual void PreCreateThreads() {} - virtual void ServiceManagerConnectionStarted( - content::ServiceManagerConnection* connection) {} + virtual void PostCreateThreads() {} virtual void PreProfileInit() {} virtual void PostProfileInit() {} virtual void PreBrowserStart() {}
diff --git a/chrome/browser/chrome_content_browser_client.cc b/chrome/browser/chrome_content_browser_client.cc index bdae3bd..6a55db74 100644 --- a/chrome/browser/chrome_content_browser_client.cc +++ b/chrome/browser/chrome_content_browser_client.cc
@@ -2816,23 +2816,8 @@ return; } - if (base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials)) { - // We deny the request here in order to trigger the committed interstitials - // code path (committing certificate error pages as navigations) instead of - // the old code path. - callback.Run(content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY); - return; - } - - // Otherwise, display an SSL blocking page. The interstitial page takes - // ownership of ssl_blocking_page. We pass a null BlockingPageReadyCallback() - // to indicate that we don't want SSLErrorHandler to take the committed - // interstitials code path. - SSLErrorHandler::HandleSSLError( - web_contents, cert_error, ssl_info, request_url, - expired_previous_decision, - std::make_unique<CertificateReportingServiceCertReporter>(web_contents), - callback, SSLErrorHandler::BlockingPageReadyCallback()); + callback.Run(content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY); + return; } namespace { @@ -4307,12 +4292,10 @@ throttles.push_back(std::make_unique<PolicyBlacklistNavigationThrottle>( handle, handle->GetWebContents()->GetBrowserContext())); - if (base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials)) { - throttles.push_back(std::make_unique<SSLErrorNavigationThrottle>( - handle, - std::make_unique<CertificateReportingServiceCertReporter>(web_contents), - base::Bind(&SSLErrorHandler::HandleSSLError))); - } + throttles.push_back(std::make_unique<SSLErrorNavigationThrottle>( + handle, + std::make_unique<CertificateReportingServiceCertReporter>(web_contents), + base::Bind(&SSLErrorHandler::HandleSSLError))); std::unique_ptr<content::NavigationThrottle> https_upgrade_timing_throttle = TypedNavigationTimingThrottle::MaybeCreateThrottleFor(handle);
diff --git a/chrome/browser/chrome_navigation_browsertest.cc b/chrome/browser/chrome_navigation_browsertest.cc index eef8a1b..82dbc8b 100644 --- a/chrome/browser/chrome_navigation_browsertest.cc +++ b/chrome/browser/chrome_navigation_browsertest.cc
@@ -121,71 +121,6 @@ TransientEntryPreservedOnMultipleNavigationsDuringInterstitial #endif -// Test to verify that navigations are not deleting the transient -// NavigationEntry when showing an interstitial page and the old renderer -// process is trying to navigate. See https://crbug.com/600046. -// With committed interstitials, interstitials are no longer transient -// navigations, so this test does not apply. -IN_PROC_BROWSER_TEST_F( - ChromeNavigationBrowserTest, - MAYBE_TransientEntryPreservedOnMultipleNavigationsDuringInterstitial) { - if (base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials)) - return; - StartServerWithExpiredCert(); - - GURL setup_url = - embedded_test_server()->GetURL("/window_open_and_navigate.html"); - GURL initial_url = embedded_test_server()->GetURL("/title1.html"); - GURL error_url(expired_https_server()->GetURL("/ssl/blank_page.html")); - - ui_test_utils::NavigateToURL(browser(), setup_url); - content::WebContents* main_web_contents = - browser()->tab_strip_model()->GetActiveWebContents(); - - // Call the JavaScript method in the test page, which opens a new window - // and stores a handle to it. - content::WindowedNotificationObserver tab_added_observer( - chrome::NOTIFICATION_TAB_ADDED, - content::NotificationService::AllSources()); - EXPECT_TRUE(content::ExecuteScript(main_web_contents, "openWin();")); - tab_added_observer.Wait(); - content::WebContents* new_web_contents = - browser()->tab_strip_model()->GetActiveWebContents(); - - // Navigate the opened window to a page that will successfully commit and - // create a NavigationEntry. - { - content::TestNavigationObserver observer(new_web_contents); - EXPECT_TRUE(content::ExecuteScript( - main_web_contents, "navigate('" + initial_url.spec() + "');")); - observer.Wait(); - EXPECT_EQ(initial_url, new_web_contents->GetLastCommittedURL()); - } - - // Navigate the opened window to a page which will trigger an - // interstitial. - { - content::TestNavigationObserver observer(new_web_contents); - EXPECT_TRUE(content::ExecuteScript( - main_web_contents, "navigate('" + error_url.spec() + "');")); - observer.Wait(); - EXPECT_EQ(initial_url, new_web_contents->GetLastCommittedURL()); - EXPECT_EQ(error_url, new_web_contents->GetVisibleURL()); - } - - // Navigate again the opened window to the same page. It should not cause - // WebContents::GetVisibleURL to return the last committed one. - { - content::DidStartNavigationObserver nav_observer(new_web_contents); - EXPECT_TRUE(content::ExecuteScript( - main_web_contents, "navigate('" + error_url.spec() + "');")); - nav_observer.Wait(); - EXPECT_EQ(error_url, new_web_contents->GetVisibleURL()); - EXPECT_TRUE(new_web_contents->GetController().GetTransientEntry()); - EXPECT_FALSE(new_web_contents->IsLoading()); - } -} - // Tests that viewing frame source on a local file:// page with an iframe // with a remote URL shows the correct tab title. IN_PROC_BROWSER_TEST_F(ChromeNavigationBrowserTest, TestViewFrameSource) {
diff --git a/chrome/browser/chrome_service.cc b/chrome/browser/chrome_service.cc index a1719f0..083bcb59 100644 --- a/chrome/browser/chrome_service.cc +++ b/chrome/browser/chrome_service.cc
@@ -15,6 +15,7 @@ #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/content_browser_client.h" +#include "content/public/browser/system_connector.h" #include "content/public/common/content_client.h" #include "content/public/common/service_manager_connection.h" #include "services/service_manager/public/cpp/binder_registry.h" @@ -112,15 +113,14 @@ ~ExtraParts() override = default; private: - void ServiceManagerConnectionStarted( - content::ServiceManagerConnection* connection) override { + void PostCreateThreads() override { // Initializing the connector asynchronously configures the Connector on the // IO thread. This needs to be done before WarmService() is called or // ChromeService::BindConnector() can race with ChromeService::OnStart(). ChromeService::GetInstance()->InitConnector(); // TODO(https://crbug.com/904148): This should not use |WarmService()|. - connection->GetConnector()->WarmService( + content::GetSystemConnector()->WarmService( service_manager::ServiceFilter::ByName(chrome::mojom::kServiceName)); }
diff --git a/chrome/browser/chromeos/login/profile_auth_data_unittest.cc b/chrome/browser/chromeos/login/profile_auth_data_unittest.cc index 2fcec43..38ba268 100644 --- a/chrome/browser/chromeos/login/profile_auth_data_unittest.cc +++ b/chrome/browser/chromeos/login/profile_auth_data_unittest.cc
@@ -18,8 +18,10 @@ #include "base/time/time.h" #include "chrome/test/base/testing_profile.h" #include "content/public/browser/browser_context.h" +#include "content/public/browser/network_service_instance.h" #include "content/public/browser/storage_partition.h" #include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/test_utils.h" #include "net/cookies/canonical_cookie.h" #include "net/cookies/cookie_constants.h" #include "net/http/http_auth.h" @@ -28,6 +30,8 @@ #include "net/http/http_transaction_factory.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" +#include "services/network/network_context.h" +#include "services/network/network_service.h" #include "services/network/public/mojom/cookie_manager.mojom.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" @@ -51,10 +55,37 @@ const char kSAMLIdPCookieDomain[] = "example.com"; const char kSAMLIdPCookieDomainWithWildcard[] = ".example.com"; +class TestingProfileWithNetworkContext : public TestingProfile { + public: + explicit TestingProfileWithNetworkContext( + network::NetworkService* network_service) { + auto network_context = std::make_unique<network::NetworkContext>( + network_service, mojo::MakeRequest(&network_context_ptr_), + network::mojom::NetworkContextParams::New()); + network_context_ = network_context.get(); + SetNetworkContext(std::move(network_context)); + } + + network::NetworkContext* network_context() { return network_context_; } + + private: + network::mojom::NetworkContextPtr network_context_ptr_; + network::NetworkContext* network_context_; +}; + +network::NetworkService* GetNetworkService() { + content::GetNetworkService(); + // Wait for the Network Service to initialize on the IO thread. + content::RunAllPendingInMessageLoop(content::BrowserThread::IO); + return network::NetworkService::GetNetworkServiceForTesting(); +} + } // namespace class ProfileAuthDataTest : public testing::Test { public: + ProfileAuthDataTest(); + // testing::Test: void SetUp() override; @@ -70,22 +101,26 @@ const std::string& expected_saml_idp_cookie_value); private: - void PopulateBrowserContext(content::BrowserContext* browser_context, + void PopulateBrowserContext(TestingProfileWithNetworkContext* browser_context, const std::string& proxy_auth_password, const std::string& cookie_value); - net::URLRequestContext* GetRequestContext( - content::BrowserContext* browser_context); - net::HttpAuthCache* GetProxyAuth(content::BrowserContext* browser_context); + net::HttpAuthCache* GetProxyAuth(network::NetworkContext* network_context); network::mojom::CookieManager* GetCookies( content::BrowserContext* browser_context); content::TestBrowserThreadBundle thread_bundle_; - TestingProfile login_browser_context_; - TestingProfile user_browser_context_; + network::NetworkService* network_service_; + TestingProfileWithNetworkContext login_browser_context_; + TestingProfileWithNetworkContext user_browser_context_; }; +ProfileAuthDataTest::ProfileAuthDataTest() + : network_service_(GetNetworkService()), + login_browser_context_(network_service_), + user_browser_context_(network_service_) {} + void ProfileAuthDataTest::SetUp() { PopulateBrowserContext(&login_browser_context_, kProxyAuthPassword1, kCookieValue1); @@ -132,7 +167,7 @@ void ProfileAuthDataTest::VerifyTransferredUserProxyAuthEntry() { net::HttpAuthCache::Entry* entry = - GetProxyAuth(&user_browser_context_) + GetProxyAuth(user_browser_context_.network_context()) ->Lookup(GURL(kProxyAuthURL), kProxyAuthRealm, net::HttpAuth::AUTH_SCHEME_BASIC); ASSERT_TRUE(entry); @@ -164,10 +199,10 @@ } void ProfileAuthDataTest::PopulateBrowserContext( - content::BrowserContext* browser_context, + TestingProfileWithNetworkContext* browser_context, const std::string& proxy_auth_password, const std::string& cookie_value) { - GetProxyAuth(browser_context) + GetProxyAuth(browser_context->network_context()) ->Add(GURL(kProxyAuthURL), kProxyAuthRealm, net::HttpAuth::AUTH_SCHEME_BASIC, kProxyAuthChallenge, net::AuthCredentials(base::string16(), @@ -206,16 +241,9 @@ "https", options, base::DoNothing()); } -net::URLRequestContext* ProfileAuthDataTest::GetRequestContext( - content::BrowserContext* browser_context) { - return content::BrowserContext::GetDefaultStoragePartition(browser_context) - ->GetURLRequestContext() - ->GetURLRequestContext(); -} - net::HttpAuthCache* ProfileAuthDataTest::GetProxyAuth( - content::BrowserContext* browser_context) { - return GetRequestContext(browser_context) + network::NetworkContext* network_context) { + return network_context->url_request_context() ->http_transaction_factory() ->GetSession() ->http_auth_cache();
diff --git a/chrome/browser/chromeos/login/signin_partition_manager_unittest.cc b/chrome/browser/chromeos/login/signin_partition_manager_unittest.cc index 8475ec9..8755091 100644 --- a/chrome/browser/chromeos/login/signin_partition_manager_unittest.cc +++ b/chrome/browser/chromeos/login/signin_partition_manager_unittest.cc
@@ -21,6 +21,7 @@ #include "content/public/browser/site_instance.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" +#include "content/public/test/test_utils.h" #include "content/public/test/web_contents_tester.h" #include "net/cookies/cookie_store.h" #include "net/http/http_transaction_factory.h" @@ -43,26 +44,23 @@ loop->Quit(); } -void AddEntryToHttpAuthCache(net::URLRequestContext* url_request_context) { - net::HttpAuthCache* http_auth_cache = - url_request_context->http_transaction_factory() - ->GetSession() - ->http_auth_cache(); - http_auth_cache->Add(GURL("http://whatever.com/"), "", - net::HttpAuth::AUTH_SCHEME_BASIC, "", - net::AuthCredentials(), ""); +void AddEntryToHttpAuthCache(network::NetworkContext* network_context) { + net::HttpAuthCache* http_auth_cache = network_context->url_request_context() + ->http_transaction_factory() + ->GetSession() + ->http_auth_cache(); + http_auth_cache->Add(GURL(kEmbedderUrl), "", net::HttpAuth::AUTH_SCHEME_BASIC, + "", net::AuthCredentials(), ""); } -void IsEntryInHttpAuthCache( - net::URLRequestContextGetter* url_request_context_getter, - bool* out_entry_found) { - net::HttpAuthCache* http_auth_cache = - url_request_context_getter->GetURLRequestContext() - ->http_transaction_factory() - ->GetSession() - ->http_auth_cache(); +void IsEntryInHttpAuthCache(network::NetworkContext* network_context, + bool* out_entry_found) { + net::HttpAuthCache* http_auth_cache = network_context->url_request_context() + ->http_transaction_factory() + ->GetSession() + ->http_auth_cache(); *out_entry_found = - http_auth_cache->Lookup(GURL("http://whatever.com/"), "", + http_auth_cache->Lookup(GURL(kEmbedderUrl), "", net::HttpAuth::AUTH_SCHEME_BASIC) != nullptr; } @@ -77,25 +75,34 @@ ChromeRenderViewHostTestHarness::SetUp(); signin_browser_context_ = std::make_unique<TestingProfile>(); + // Wait for the Network Service to initialize on the IO thread. + content::RunAllPendingInMessageLoop(content::BrowserThread::IO); + + auto network_context = std::make_unique<network::NetworkContext>( + network::NetworkService::GetNetworkServiceForTesting(), + mojo::MakeRequest(&signin_network_context_ptr_), + network::mojom::NetworkContextParams::New()); + signin_network_context_ = network_context.get(); + TestingProfile::Builder() + .BuildIncognito(signin_browser_context_.get()) + ->SetNetworkContext(std::move(network_context)); signin_ui_web_contents_ = content::WebContentsTester::CreateTestWebContents( GetSigninProfile(), content::SiteInstance::Create(GetSigninProfile())); - // Let Profile creation finish, which creates the NetworkService instance. - base::RunLoop().RunUntilIdle(); - network::mojom::NetworkContextParamsPtr params = - network::mojom::NetworkContextParams::New(); system_network_context_ = std::make_unique<network::NetworkContext>( network::NetworkService::GetNetworkServiceForTesting(), - mojo::MakeRequest(&system_network_context_ptr_), std::move(params)); + mojo::MakeRequest(&system_network_context_ptr_), + network::mojom::NetworkContextParams::New()); GURL url(kEmbedderUrl); content::WebContentsTester::For(signin_ui_web_contents()) ->NavigateAndCommit(url); GetSigninPartitionManager()->SetClearStoragePartitionTaskForTesting( - base::Bind(&SigninPartitionManagerTest::ClearStoragePartitionTask, - base::Unretained(this))); + base::BindRepeating( + &SigninPartitionManagerTest::ClearStoragePartitionTask, + base::Unretained(this))); GetSigninPartitionManager()->SetGetSystemNetworkContextForTesting( base::BindRepeating( &SigninPartitionManagerTest::GetSystemNetworkContext, @@ -150,24 +157,30 @@ return partition_name; } - net::URLRequestContext* GetSystemURLRequestContext() { - return system_network_context_->url_request_context(); - } - network::mojom::NetworkContext* GetSystemNetworkContext() { return system_network_context_.get(); } + network::NetworkContext* GetSystemNetworkContextImpl() { + return system_network_context_.get(); + } + + network::NetworkContext* GetSigninNetworkContextImpl() { + return signin_network_context_; + } + private: void ClearStoragePartitionTask(content::StoragePartition* partition, base::OnceClosure clear_done_closure) { pending_clear_tasks_.push_back({partition, std::move(clear_done_closure)}); } - std::unique_ptr<network::NetworkContext> system_network_context_; network::mojom::NetworkContextPtr system_network_context_ptr_; + std::unique_ptr<network::NetworkContext> system_network_context_; std::unique_ptr<TestingProfile> signin_browser_context_; + network::mojom::NetworkContextPtr signin_network_context_ptr_; + network::NetworkContext* signin_network_context_; // Web contents of the sign-in UI, embedder of the signin-frame webview. std::unique_ptr<content::WebContents> signin_ui_web_contents_; @@ -227,22 +240,18 @@ base::PostTaskWithTraitsAndReply( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(AddEntryToHttpAuthCache, - base::Unretained(GetSystemURLRequestContext())), + base::Unretained(GetSystemNetworkContextImpl())), loop_prepare.QuitClosure()); loop_prepare.Run(); RunStartSigninSesssion(signin_ui_web_contents()); - net::URLRequestContextGetter* signin_url_request_context_getter = - GetSigninPartitionManager() - ->GetCurrentStoragePartition() - ->GetURLRequestContext(); bool entry_found = false; base::RunLoop loop_check; base::PostTaskWithTraitsAndReply( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(IsEntryInHttpAuthCache, - base::RetainedRef(signin_url_request_context_getter), + base::Unretained(GetSigninNetworkContextImpl()), &entry_found), loop_check.QuitClosure()); loop_check.Run();
diff --git a/chrome/browser/devtools/devtools_ui_bindings.cc b/chrome/browser/devtools/devtools_ui_bindings.cc index 113d9bd..fafae182 100644 --- a/chrome/browser/devtools/devtools_ui_bindings.cc +++ b/chrome/browser/devtools/devtools_ui_bindings.cc
@@ -293,6 +293,19 @@ return net::EscapeQueryParamValue(sanitized, false); } +std::string SanitizeEnabledExperiments(const std::string& value) { + bool valid = std::find_if_not(value.begin(), value.end(), [](char ch) { + if (base::IsAsciiAlpha(ch) || base::IsAsciiDigit(ch) || + ch == ';' || ch == '_') + return true; + return false; + }) == value.end(); + if (!valid) { + return std::string(); + } + return value; +} + std::string SanitizeFrontendQueryParam( const std::string& key, const std::string& value) { @@ -323,6 +336,9 @@ if (key == "remoteVersion") return SanitizeRemoteVersion(value); + if (key == "enabledExperiments") + return SanitizeEnabledExperiments(value); + return std::string(); }
diff --git a/chrome/browser/devtools/devtools_ui_bindings_unittest.cc b/chrome/browser/devtools/devtools_ui_bindings_unittest.cc index ff9dc68..2e27ec7 100644 --- a/chrome/browser/devtools/devtools_ui_bindings_unittest.cc +++ b/chrome/browser/devtools/devtools_ui_bindings_unittest.cc
@@ -95,6 +95,12 @@ "devtools://devtools/?remoteFrontendUrl=" "https%3A%2F%2Fchrome-devtools-frontend.appspot.com%2Fserve_rev" "%2F%4012345%2Finspector.html"}, + {"devtools://devtools/" + "?enabledExperiments=explosionsWhileTyping;newA11yTool", + "devtools://devtools/" + "?enabledExperiments=explosionsWhileTyping;newA11yTool"}, + {"devtools://devtools/?enabledExperiments=invalidExperiment$", + "devtools://devtools/"}, }; for (const auto& pair : tests) {
diff --git a/chrome/browser/extensions/api/automation/automation_apitest.cc b/chrome/browser/extensions/api/automation/automation_apitest.cc index bb1a099..e8228d19 100644 --- a/chrome/browser/extensions/api/automation/automation_apitest.cc +++ b/chrome/browser/extensions/api/automation/automation_apitest.cc
@@ -380,6 +380,13 @@ << message_; } +IN_PROC_BROWSER_TEST_F(AutomationApiTest, WordBoundaries) { + StartEmbeddedTestServer(); + ASSERT_TRUE( + RunExtensionSubtest("automation/tests/tabs", "word_boundaries.html")) + << message_; +} + class AutomationApiTestWithLanguageDetection : public AutomationApiTest { protected: void SetUpCommandLine(base::CommandLine* command_line) override {
diff --git a/chrome/browser/extensions/api/declarative_webrequest/webrequest_action_unittest.cc b/chrome/browser/extensions/api/declarative_webrequest/webrequest_action_unittest.cc index fcfdf5d..e7072be4 100644 --- a/chrome/browser/extensions/api/declarative_webrequest/webrequest_action_unittest.cc +++ b/chrome/browser/extensions/api/declarative_webrequest/webrequest_action_unittest.cc
@@ -27,11 +27,7 @@ #include "extensions/browser/info_map.h" #include "extensions/common/extension.h" #include "extensions/common/extensions_client.h" -#include "net/base/request_priority.h" #include "net/http/http_response_headers.h" -#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" -#include "net/url_request/url_request.h" -#include "net/url_request/url_request_test_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -102,8 +98,6 @@ content::TestBrowserThreadBundle thread_bundle_; protected: - net::TestURLRequestContext context_; - // An extension with *.com host permissions and the DWR permission. scoped_refptr<Extension> extension_; // An extension with host permissions for all URLs and the DWR permission. @@ -149,13 +143,12 @@ const WebRequestActionSet* action_set, RequestStage stage) { const int kRendererId = 2; - std::unique_ptr<net::URLRequest> regular_request( - context_.CreateRequest(GURL(url_string), net::DEFAULT_PRIORITY, NULL, - TRAFFIC_ANNOTATION_FOR_TESTS)); EventResponseDeltas deltas; scoped_refptr<net::HttpResponseHeaders> headers( new net::HttpResponseHeaders("")); - WebRequestInfoInitParams request_params(regular_request.get()); + WebRequestInfoInitParams params; + params.url = GURL(url_string); + WebRequestInfoInitParams request_params(std::move(params)); request_params.render_process_id = kRendererId; WebRequestInfo request_info(std::move(request_params)); WebRequestData request_data(&request_info, stage, headers.get());
diff --git a/chrome/browser/extensions/api/image_writer_private/write_from_url_operation_unittest.cc b/chrome/browser/extensions/api/image_writer_private/write_from_url_operation_unittest.cc index 2310abe..de32f5c7 100644 --- a/chrome/browser/extensions/api/image_writer_private/write_from_url_operation_unittest.cc +++ b/chrome/browser/extensions/api/image_writer_private/write_from_url_operation_unittest.cc
@@ -13,7 +13,7 @@ #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/storage_partition.h" -#include "net/url_request/test_url_request_interceptor.h" +#include "content/public/test/url_loader_interceptor.h" #include "services/service_manager/public/cpp/connector.h" namespace extensions { @@ -30,8 +30,6 @@ const char kTestImageUrl[] = "http://localhost/test/image.zip"; -typedef net::LocalHostTestURLRequestInterceptor GetInterceptor; - } // namespace // This class gives us a generic Operation with the ability to set or inspect @@ -94,25 +92,28 @@ class ImageWriterWriteFromUrlOperationTest : public ImageWriterUnitTestBase { protected: - ImageWriterWriteFromUrlOperationTest() : manager_(&test_profile_) {} - - void SetUp() override { - ImageWriterUnitTestBase::SetUp(); - - // Turn on interception and set up our dummy file. - get_interceptor_.reset(new GetInterceptor( - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}), - base::CreateTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}))); - get_interceptor_->SetResponse(GURL(kTestImageUrl), - test_utils_.GetImagePath()); - } + ImageWriterWriteFromUrlOperationTest() + : url_loader_interceptor_(base::BindRepeating( + &ImageWriterWriteFromUrlOperationTest::HandleRequest, + base::Unretained(this))), + url_interception_count_(0), + manager_(&test_profile_) {} void TearDown() override { ImageWriterUnitTestBase::TearDown(); } + // Intercepts network requests. + bool HandleRequest(content::URLLoaderInterceptor::RequestParams* params) { + if (params->url_request.url == GURL(kTestImageUrl)) { + url_interception_count_++; + content::URLLoaderInterceptor::WriteResponse(test_utils_.GetImagePath(), + params->client.get()); + return true; + } + return false; + } + scoped_refptr<WriteFromUrlOperationForTest> CreateOperation( const GURL& url, const std::string& hash) { @@ -131,7 +132,8 @@ } TestingProfile test_profile_; - std::unique_ptr<GetInterceptor> get_interceptor_; + content::URLLoaderInterceptor url_loader_interceptor_; + int url_interception_count_; MockOperationManager manager_; }; @@ -205,7 +207,7 @@ EXPECT_TRUE(base::ContentsEqual(test_utils_.GetImagePath(), operation->GetImagePath())); - EXPECT_EQ(1, get_interceptor_->GetHitCount()); + EXPECT_EQ(1, url_interception_count_); operation->Cancel(); }
diff --git a/chrome/browser/extensions/api/settings_private/generated_prefs_factory.cc b/chrome/browser/extensions/api/settings_private/generated_prefs_factory.cc index fa90ade..24f509a9 100644 --- a/chrome/browser/extensions/api/settings_private/generated_prefs_factory.cc +++ b/chrome/browser/extensions/api/settings_private/generated_prefs_factory.cc
@@ -31,6 +31,16 @@ GeneratedPrefsFactory::~GeneratedPrefsFactory() {} +content::BrowserContext* GeneratedPrefsFactory::GetBrowserContextToUse( + content::BrowserContext* context) const { + // Use |context| even if it is off-the-record/incognito. + return context; +} + +bool GeneratedPrefsFactory::ServiceIsNULLWhileTesting() const { + return true; +} + KeyedService* GeneratedPrefsFactory::BuildServiceInstanceFor( content::BrowserContext* profile) const { return new GeneratedPrefs(static_cast<Profile*>(profile));
diff --git a/chrome/browser/extensions/api/settings_private/generated_prefs_factory.h b/chrome/browser/extensions/api/settings_private/generated_prefs_factory.h index e755cf0..10fc892 100644 --- a/chrome/browser/extensions/api/settings_private/generated_prefs_factory.h +++ b/chrome/browser/extensions/api/settings_private/generated_prefs_factory.h
@@ -29,6 +29,9 @@ ~GeneratedPrefsFactory() override; // BrowserContextKeyedServiceFactory implementation. + content::BrowserContext* GetBrowserContextToUse( + content::BrowserContext* context) const override; + bool ServiceIsNULLWhileTesting() const override; KeyedService* BuildServiceInstanceFor( content::BrowserContext* profile) const override;
diff --git a/chrome/browser/extensions/api/settings_private/settings_private_api.cc b/chrome/browser/extensions/api/settings_private/settings_private_api.cc index 4898ddb..821ed53 100644 --- a/chrome/browser/extensions/api/settings_private/settings_private_api.cc +++ b/chrome/browser/extensions/api/settings_private/settings_private_api.cc
@@ -17,10 +17,6 @@ #include "content/public/common/page_zoom.h" #include "extensions/browser/extension_function_registry.h" -namespace { - const char kDelegateIsNull[] = "delegate is null"; -} - namespace extensions { //////////////////////////////////////////////////////////////////////////////// @@ -37,8 +33,7 @@ SettingsPrivateDelegate* delegate = SettingsPrivateDelegateFactory::GetForBrowserContext(browser_context()); - if (delegate == nullptr) - return RespondNow(Error(kDelegateIsNull)); + DCHECK(delegate); settings_private::SetPrefResult result = delegate->SetPref(parameters->name, parameters->value.get()); @@ -71,11 +66,8 @@ ExtensionFunction::ResponseAction SettingsPrivateGetAllPrefsFunction::Run() { SettingsPrivateDelegate* delegate = SettingsPrivateDelegateFactory::GetForBrowserContext(browser_context()); - - if (delegate == nullptr) - return RespondNow(Error(kDelegateIsNull)); - else - return RespondNow(OneArgument(delegate->GetAllPrefs())); + DCHECK(delegate); + return RespondNow(OneArgument(delegate->GetAllPrefs())); } //////////////////////////////////////////////////////////////////////////////// @@ -92,8 +84,7 @@ SettingsPrivateDelegate* delegate = SettingsPrivateDelegateFactory::GetForBrowserContext(browser_context()); - if (delegate == nullptr) - return RespondNow(Error(kDelegateIsNull)); + DCHECK(delegate); std::unique_ptr<base::Value> value = delegate->GetPref(parameters->name); if (value->is_none()) @@ -114,11 +105,8 @@ SettingsPrivateGetDefaultZoomFunction::Run() { SettingsPrivateDelegate* delegate = SettingsPrivateDelegateFactory::GetForBrowserContext(browser_context()); - - if (delegate == nullptr) - return RespondNow(Error(kDelegateIsNull)); - else - return RespondNow(OneArgument(delegate->GetDefaultZoom())); + DCHECK(delegate); + return RespondNow(OneArgument(delegate->GetDefaultZoom())); } //////////////////////////////////////////////////////////////////////////////// @@ -137,9 +125,7 @@ SettingsPrivateDelegate* delegate = SettingsPrivateDelegateFactory::GetForBrowserContext(browser_context()); - if (delegate == nullptr) - return RespondNow(Error(kDelegateIsNull)); - + DCHECK(delegate); delegate->SetDefaultZoom(parameters->zoom); return RespondNow(OneArgument(std::make_unique<base::Value>(true))); }
diff --git a/chrome/browser/extensions/api/settings_private/settings_private_browsertest_chromeos.cc b/chrome/browser/extensions/api/settings_private/settings_private_browsertest_chromeos.cc new file mode 100644 index 0000000..6b7a7b7 --- /dev/null +++ b/chrome/browser/extensions/api/settings_private/settings_private_browsertest_chromeos.cc
@@ -0,0 +1,57 @@ +// 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 "base/values.h" +#include "chrome/browser/chromeos/login/mixin_based_in_process_browser_test.h" +#include "chrome/browser/chromeos/login/test/guest_session_mixin.h" +#include "chrome/browser/extensions/api/settings_private/prefs_util_enums.h" +#include "chrome/browser/extensions/api/settings_private/settings_private_api.h" +#include "chrome/browser/extensions/api/settings_private/settings_private_delegate.h" +#include "chrome/browser/extensions/api/settings_private/settings_private_delegate_factory.h" +#include "chrome/browser/extensions/api/settings_private/settings_private_event_router.h" +#include "chrome/browser/extensions/api/settings_private/settings_private_event_router_factory.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/browser.h" +#include "content/public/test/browser_test.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace extensions { +namespace { + +class SettingsPrivateGuestModeTest + : public chromeos::MixinBasedInProcessBrowserTest { + protected: + chromeos::GuestSessionMixin guest_session_{&mixin_host_}; +}; + +// Regression test for https://crbug.com/887383. +IN_PROC_BROWSER_TEST_F(SettingsPrivateGuestModeTest, GuestMode) { + Profile* guest_profile = browser()->profile(); + EXPECT_TRUE(guest_profile->IsOffTheRecord()); + + // SettingsPrivate uses the incognito profile, not the recording profile, + // to set preferences. + SettingsPrivateDelegate* delegate = + SettingsPrivateDelegateFactory::GetForBrowserContext(guest_profile); + Profile* delegate_profile = delegate->profile_for_test(); + EXPECT_EQ(guest_profile, delegate_profile); + EXPECT_NE(guest_profile->GetOriginalProfile(), delegate_profile); + + // SettingsPrivate observes the incognito profile, not the recording profile, + // for pref changes. + SettingsPrivateEventRouter* router = + SettingsPrivateEventRouterFactory::GetForProfile(guest_profile); + Profile* router_profile = static_cast<Profile*>(router->context_for_test()); + EXPECT_EQ(guest_profile, router_profile); + EXPECT_NE(guest_profile->GetOriginalProfile(), router_profile); + + // Page zoom preferences cannot be changed in guest mode and always return a + // default value. + EXPECT_EQ(settings_private::SetPrefResult::PREF_NOT_MODIFIABLE, + delegate->SetDefaultZoom(0.5)); + EXPECT_EQ(delegate->GetDefaultZoom()->GetDouble(), 0.0); +} + +} // namespace +} // namespace extensions
diff --git a/chrome/browser/extensions/api/settings_private/settings_private_delegate.cc b/chrome/browser/extensions/api/settings_private/settings_private_delegate.cc index adf858f..9eb36246 100644 --- a/chrome/browser/extensions/api/settings_private/settings_private_delegate.cc +++ b/chrome/browser/extensions/api/settings_private/settings_private_delegate.cc
@@ -10,6 +10,7 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/extensions/api/settings_private/prefs_util.h" +#include "chrome/browser/extensions/api/settings_private/prefs_util_enums.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/zoom/chrome_zoom_level_prefs.h" #include "chrome/common/pref_names.h" @@ -58,14 +59,21 @@ } std::unique_ptr<base::Value> SettingsPrivateDelegate::GetDefaultZoom() { + // Zoom level prefs aren't available for off-the-record profiles (like guest + // mode on Chrome OS). The setting isn't visible to users anyway, so return a + // default value. + if (profile_->IsOffTheRecord()) + return std::make_unique<base::Value>(0.0); double zoom = content::ZoomLevelToZoomFactor( profile_->GetZoomLevelPrefs()->GetDefaultZoomLevelPref()); - std::unique_ptr<base::Value> value(new base::Value(zoom)); - return value; + return std::make_unique<base::Value>(zoom); } settings_private::SetPrefResult SettingsPrivateDelegate::SetDefaultZoom( double zoom) { + // See comment in GetDefaultZoom(). + if (profile_->IsOffTheRecord()) + return settings_private::SetPrefResult::PREF_NOT_MODIFIABLE; double zoom_factor = content::ZoomFactorToZoomLevel(zoom); profile_->GetZoomLevelPrefs()->SetDefaultZoomLevelPref(zoom_factor); return settings_private::SetPrefResult::SUCCESS;
diff --git a/chrome/browser/extensions/api/settings_private/settings_private_delegate.h b/chrome/browser/extensions/api/settings_private/settings_private_delegate.h index e2d07ca2..bbe82f1 100644 --- a/chrome/browser/extensions/api/settings_private/settings_private_delegate.h +++ b/chrome/browser/extensions/api/settings_private/settings_private_delegate.h
@@ -50,6 +50,8 @@ // Sets the pref. virtual settings_private::SetPrefResult SetDefaultZoom(double zoom); + Profile* profile_for_test() { return profile_; } + protected: Profile* profile_; // weak; not owned by us std::unique_ptr<PrefsUtil> prefs_util_;
diff --git a/chrome/browser/extensions/api/settings_private/settings_private_delegate_factory.cc b/chrome/browser/extensions/api/settings_private/settings_private_delegate_factory.cc index e855cac0..fd8ed79c 100644 --- a/chrome/browser/extensions/api/settings_private/settings_private_delegate_factory.cc +++ b/chrome/browser/extensions/api/settings_private/settings_private_delegate_factory.cc
@@ -6,7 +6,6 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/api/settings_private/settings_private_delegate.h" -#include "chrome/browser/profiles/incognito_helpers.h" #include "chrome/browser/profiles/profile.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "extensions/browser/extension_system_provider.h" @@ -39,8 +38,6 @@ content::BrowserContext* SettingsPrivateDelegateFactory::GetBrowserContextToUse( content::BrowserContext* context) const { // Use the incognito profile when in Guest mode. - if (context->IsOffTheRecord()) - return chrome::GetBrowserContextRedirectedInIncognito(context); return context; }
diff --git a/chrome/browser/extensions/api/settings_private/settings_private_event_router.cc b/chrome/browser/extensions/api/settings_private/settings_private_event_router.cc index 5184bad..4a80425e 100644 --- a/chrome/browser/extensions/api/settings_private/settings_private_event_router.cc +++ b/chrome/browser/extensions/api/settings_private/settings_private_event_router.cc
@@ -24,6 +24,11 @@ SettingsPrivateEventRouter::SettingsPrivateEventRouter( content::BrowserContext* context) : context_(context), listening_(false), weak_ptr_factory_(this) { + Profile* profile = Profile::FromBrowserContext(context_); + prefs_util_ = std::make_unique<PrefsUtil>(profile); + user_prefs_registrar_.Init(profile->GetPrefs()); + local_state_registrar_.Init(g_browser_process->local_state()); + // Register with the event router so we know when renderers are listening to // our events. We first check and see if there *is* an event router, because // some unit tests try to create all context services, but don't initialize @@ -34,11 +39,6 @@ this, api::settings_private::OnPrefsChanged::kEventName); StartOrStopListeningForPrefsChanges(); } - - Profile* profile = Profile::FromBrowserContext(context_); - prefs_util_.reset(new PrefsUtil(profile)); - user_prefs_registrar_.Init(profile->GetPrefs()); - local_state_registrar_.Init(g_browser_process->local_state()); } SettingsPrivateEventRouter::~SettingsPrivateEventRouter() { @@ -98,6 +98,7 @@ } void SettingsPrivateEventRouter::StartOrStopListeningForPrefsChanges() { + DCHECK(prefs_util_); EventRouter* event_router = EventRouter::Get(context_); bool should_listen = event_router->HasEventListener( api::settings_private::OnPrefsChanged::kEventName);
diff --git a/chrome/browser/extensions/api/settings_private/settings_private_event_router.h b/chrome/browser/extensions/api/settings_private/settings_private_event_router.h index 08bb8c9..ddad6b08 100644 --- a/chrome/browser/extensions/api/settings_private/settings_private_event_router.h +++ b/chrome/browser/extensions/api/settings_private/settings_private_event_router.h
@@ -41,6 +41,8 @@ // settings_private::GeneratedPref::Observer implementation. void OnGeneratedPrefChanged(const std::string& pref_name) override; + content::BrowserContext* context_for_test() { return context_; } + protected: explicit SettingsPrivateEventRouter(content::BrowserContext* context);
diff --git a/chrome/browser/extensions/api/settings_private/settings_private_event_router_factory.cc b/chrome/browser/extensions/api/settings_private/settings_private_event_router_factory.cc index 227e15d0..b491f73a 100644 --- a/chrome/browser/extensions/api/settings_private/settings_private_event_router_factory.cc +++ b/chrome/browser/extensions/api/settings_private/settings_private_event_router_factory.cc
@@ -44,7 +44,8 @@ content::BrowserContext* SettingsPrivateEventRouterFactory::GetBrowserContextToUse( content::BrowserContext* context) const { - return ExtensionsBrowserClient::Get()->GetOriginalContext(context); + // Use the incognito profile in guest mode. + return context; } bool SettingsPrivateEventRouterFactory::ServiceIsCreatedWithBrowserContext() @@ -53,7 +54,7 @@ } bool SettingsPrivateEventRouterFactory::ServiceIsNULLWhileTesting() const { - return false; + return true; } } // namespace extensions
diff --git a/chrome/browser/extensions/api/web_request/web_request_event_details_unittest.cc b/chrome/browser/extensions/api/web_request/web_request_event_details_unittest.cc index 74cdf22..3739ff2 100644 --- a/chrome/browser/extensions/api/web_request/web_request_event_details_unittest.cc +++ b/chrome/browser/extensions/api/web_request/web_request_event_details_unittest.cc
@@ -5,7 +5,6 @@ #include "extensions/browser/api/web_request/web_request_event_details.h" #include "base/stl_util.h" -#include "base/test/scoped_task_environment.h" #include "base/values.h" #include "extensions/browser/api/web_request/web_request_api_constants.h" #include "extensions/browser/api/web_request/web_request_api_helpers.h" @@ -13,8 +12,6 @@ #include "google_apis/gaia/gaia_urls.h" #include "net/http/http_response_headers.h" #include "net/http/http_util.h" -#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" -#include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" @@ -77,8 +74,6 @@ TEST(WebRequestEventDetailsTest, SetResponseHeaders) { const int kFilter = extension_web_request_api_helpers::ExtraInfoSpec::RESPONSE_HEADERS; - base::test::ScopedTaskEnvironment scoped_task_environment; - net::TestURLRequestContext context; char headers_string[] = "HTTP/1.0 200 OK\r\n" @@ -90,10 +85,9 @@ { // Non-Gaia URL. - std::unique_ptr<net::URLRequest> request = context.CreateRequest( - GURL("http://www.example.com"), net::DEFAULT_PRIORITY, nullptr, - TRAFFIC_ANNOTATION_FOR_TESTS); - WebRequestInfo request_info(request.get()); + WebRequestInfoInitParams params; + params.url = GURL("http://www.example.com"); + WebRequestInfo request_info(std::move(params)); WebRequestEventDetails details(request_info, kFilter); details.SetResponseHeaders(request_info, headers.get()); std::unique_ptr<base::DictionaryValue> dict = @@ -113,10 +107,9 @@ { // Gaia URL. - std::unique_ptr<net::URLRequest> gaia_request = context.CreateRequest( - GaiaUrls::GetInstance()->gaia_url(), net::DEFAULT_PRIORITY, nullptr, - TRAFFIC_ANNOTATION_FOR_TESTS); - WebRequestInfo gaia_request_info(gaia_request.get()); + WebRequestInfoInitParams params; + params.url = GaiaUrls::GetInstance()->gaia_url(); + WebRequestInfo gaia_request_info(std::move(params)); WebRequestEventDetails gaia_details(gaia_request_info, kFilter); gaia_details.SetResponseHeaders(gaia_request_info, headers.get()); std::unique_ptr<base::DictionaryValue> dict =
diff --git a/chrome/browser/extensions/api/web_request/web_request_permissions_unittest.cc b/chrome/browser/extensions/api/web_request/web_request_permissions_unittest.cc index d9e2bea..eea86d67 100644 --- a/chrome/browser/extensions/api/web_request/web_request_permissions_unittest.cc +++ b/chrome/browser/extensions/api/web_request/web_request_permissions_unittest.cc
@@ -17,10 +17,6 @@ #include "extensions/common/constants.h" #include "extensions/common/permissions/permissions_data.h" #include "ipc/ipc_message.h" -#include "net/base/request_priority.h" -#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" -#include "net/url_request/url_request.h" -#include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_CHROMEOS) @@ -46,8 +42,6 @@ content::TestBrowserThreadBundle thread_bundle_; protected: - net::TestURLRequestContext context; - // This extension has Web Request permissions, but no host permission. scoped_refptr<Extension> permissionless_extension_; // This extension has Web Request permissions, and *.com a host permission. @@ -172,128 +166,110 @@ TEST_F(ExtensionWebRequestHelpersTestWithThreadsTest, TestCanExtensionAccessURL_HostPermissions) { - // Request with empty initiator. - std::unique_ptr<net::URLRequest> request( - context.CreateRequest(GURL("http://example.com"), net::DEFAULT_PRIORITY, - NULL, TRAFFIC_ANNOTATION_FOR_TESTS)); - + const GURL url("http://example.com"); const content::ResourceType kResourceType = content::ResourceType::kSubResource; EXPECT_EQ(PermissionsData::PageAccess::kAllowed, WebRequestPermissions::CanExtensionAccessURL( - extension_info_map_.get(), permissionless_extension_->id(), - request->url(), + extension_info_map_.get(), permissionless_extension_->id(), url, -1, // No tab id. false, // crosses_incognito - WebRequestPermissions::DO_NOT_CHECK_HOST, request->initiator(), + WebRequestPermissions::DO_NOT_CHECK_HOST, base::nullopt, kResourceType)); EXPECT_EQ(PermissionsData::PageAccess::kDenied, WebRequestPermissions::CanExtensionAccessURL( - extension_info_map_.get(), permissionless_extension_->id(), - request->url(), + extension_info_map_.get(), permissionless_extension_->id(), url, -1, // No tab id. false, // crosses_incognito WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL, - request->initiator(), kResourceType)); + base::nullopt, kResourceType)); EXPECT_EQ(PermissionsData::PageAccess::kAllowed, WebRequestPermissions::CanExtensionAccessURL( - extension_info_map_.get(), com_extension_->id(), request->url(), + extension_info_map_.get(), com_extension_->id(), url, -1, // No tab id. false, // crosses_incognito WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL, - request->initiator(), kResourceType)); + base::nullopt, kResourceType)); EXPECT_EQ( PermissionsData::PageAccess::kAllowed, WebRequestPermissions::CanExtensionAccessURL( - extension_info_map_.get(), com_extension_->id(), request->url(), + extension_info_map_.get(), com_extension_->id(), url, -1, // No tab id. false, // crosses_incognito WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL_AND_INITIATOR, - request->initiator(), kResourceType)); + base::nullopt, kResourceType)); EXPECT_EQ(PermissionsData::PageAccess::kDenied, WebRequestPermissions::CanExtensionAccessURL( - extension_info_map_.get(), com_extension_->id(), request->url(), + extension_info_map_.get(), com_extension_->id(), url, -1, // No tab id. false, // crosses_incognito - WebRequestPermissions::REQUIRE_ALL_URLS, request->initiator(), + WebRequestPermissions::REQUIRE_ALL_URLS, base::nullopt, kResourceType)); - std::unique_ptr<net::URLRequest> request_with_initiator( - context.CreateRequest(GURL("http://example.com"), net::DEFAULT_PRIORITY, - nullptr, TRAFFIC_ANNOTATION_FOR_TESTS)); - request_with_initiator->set_initiator( + base::Optional<url::Origin> initiator( url::Origin::Create(GURL("http://www.example.org"))); - EXPECT_EQ(PermissionsData::PageAccess::kAllowed, - WebRequestPermissions::CanExtensionAccessURL( - extension_info_map_.get(), permissionless_extension_->id(), - request_with_initiator->url(), - -1, // No tab id. - false, // crosses_incognito - WebRequestPermissions::DO_NOT_CHECK_HOST, - request_with_initiator->initiator(), kResourceType)); + EXPECT_EQ( + PermissionsData::PageAccess::kAllowed, + WebRequestPermissions::CanExtensionAccessURL( + extension_info_map_.get(), permissionless_extension_->id(), url, + -1, // No tab id. + false, // crosses_incognito + WebRequestPermissions::DO_NOT_CHECK_HOST, initiator, kResourceType)); EXPECT_EQ(PermissionsData::PageAccess::kDenied, WebRequestPermissions::CanExtensionAccessURL( - extension_info_map_.get(), permissionless_extension_->id(), - request_with_initiator->url(), + extension_info_map_.get(), permissionless_extension_->id(), url, -1, // No tab id. false, // crosses_incognito WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL, - request_with_initiator->initiator(), kResourceType)); + initiator, kResourceType)); EXPECT_EQ(PermissionsData::PageAccess::kAllowed, WebRequestPermissions::CanExtensionAccessURL( - extension_info_map_.get(), com_extension_->id(), - request_with_initiator->url(), + extension_info_map_.get(), com_extension_->id(), url, -1, // No tab id. false, // crosses_incognito WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL, - request_with_initiator->initiator(), kResourceType)); + initiator, kResourceType)); // Doesn't have access to the initiator. EXPECT_EQ( PermissionsData::PageAccess::kDenied, WebRequestPermissions::CanExtensionAccessURL( - extension_info_map_.get(), com_extension_->id(), - request_with_initiator->url(), + extension_info_map_.get(), com_extension_->id(), url, -1, // No tab id. false, // crosses_incognito WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL_AND_INITIATOR, - request_with_initiator->initiator(), kResourceType)); + initiator, kResourceType)); // Navigation requests don't need access to the initiator. EXPECT_EQ( PermissionsData::PageAccess::kAllowed, WebRequestPermissions::CanExtensionAccessURL( - extension_info_map_.get(), com_extension_->id(), - request_with_initiator->url(), + extension_info_map_.get(), com_extension_->id(), url, -1, // No tab id. false, // crosses_incognito WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL_AND_INITIATOR, - request_with_initiator->initiator(), - content::ResourceType::kSubFrame)); + initiator, content::ResourceType::kSubFrame)); - EXPECT_EQ(PermissionsData::PageAccess::kDenied, - WebRequestPermissions::CanExtensionAccessURL( - extension_info_map_.get(), com_extension_->id(), - request_with_initiator->url(), - -1, // No tab id. - false, // crosses_incognito - WebRequestPermissions::REQUIRE_ALL_URLS, - request_with_initiator->initiator(), kResourceType)); + EXPECT_EQ( + PermissionsData::PageAccess::kDenied, + WebRequestPermissions::CanExtensionAccessURL( + extension_info_map_.get(), com_extension_->id(), url, + -1, // No tab id. + false, // crosses_incognito + WebRequestPermissions::REQUIRE_ALL_URLS, initiator, kResourceType)); // Public Sessions tests. #if defined(OS_CHROMEOS) - std::unique_ptr<net::URLRequest> org_request(context.CreateRequest( - GURL("http://example.org"), net::DEFAULT_PRIORITY, nullptr)); + const GURL org_url("http://example.org"); // com_extension_ doesn't have host permission for .org URLs. EXPECT_EQ(PermissionsData::PageAccess::kDenied, WebRequestPermissions::CanExtensionAccessURL( - extension_info_map_.get(), com_policy_extension_->id(), - org_request->url(), + extension_info_map_.get(), com_policy_extension_->id(), org_url, -1, // No tab id. false, // crosses_incognito WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL, - org_request->initiator(), kResourceType)); + base::nullopt, kResourceType)); chromeos::ScopedTestPublicSessionLoginState login_state; @@ -301,34 +277,30 @@ // are whitelisted. EXPECT_EQ(PermissionsData::PageAccess::kAllowed, WebRequestPermissions::CanExtensionAccessURL( - extension_info_map_.get(), com_policy_extension_->id(), - org_request->url(), + extension_info_map_.get(), com_policy_extension_->id(), org_url, -1, // No tab id. false, // crosses_incognito WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL, - org_request->initiator(), kResourceType)); + base::nullopt, kResourceType)); EXPECT_EQ(PermissionsData::PageAccess::kAllowed, WebRequestPermissions::CanExtensionAccessURL( - extension_info_map_.get(), com_policy_extension_->id(), - org_request->url(), + extension_info_map_.get(), com_policy_extension_->id(), org_url, -1, // No tab id. false, // crosses_incognito - WebRequestPermissions::REQUIRE_ALL_URLS, - org_request->initiator(), kResourceType)); + WebRequestPermissions::REQUIRE_ALL_URLS, base::nullopt, + kResourceType)); // Make sure that chrome:// URLs cannot be accessed. - std::unique_ptr<net::URLRequest> chrome_request( - context.CreateRequest(GURL("chrome://version/"), net::DEFAULT_PRIORITY, - nullptr, TRAFFIC_ANNOTATION_FOR_TESTS)); + const GURL chrome_url("chrome://version/"); - EXPECT_EQ(PermissionsData::PageAccess::kDenied, - WebRequestPermissions::CanExtensionAccessURL( - extension_info_map_.get(), com_policy_extension_->id(), - chrome_request->url(), - -1, // No tab id. - false, // crosses_incognito - WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL, - chrome_request->initiator(), kResourceType)); + EXPECT_EQ( + PermissionsData::PageAccess::kDenied, + WebRequestPermissions::CanExtensionAccessURL( + extension_info_map_.get(), com_policy_extension_->id(), chrome_url, + -1, // No tab id. + false, // crosses_incognito + WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL, base::nullopt, + kResourceType)); #endif }
diff --git a/chrome/browser/extensions/chrome_extensions_browser_client.cc b/chrome/browser/extensions/chrome_extensions_browser_client.cc index 87a8ac4f..89e6fa7 100644 --- a/chrome/browser/extensions/chrome_extensions_browser_client.cc +++ b/chrome/browser/extensions/chrome_extensions_browser_client.cc
@@ -182,21 +182,6 @@ || util::CanCrossIncognito(extension, context); } -net::URLRequestJob* -ChromeExtensionsBrowserClient::MaybeCreateResourceBundleRequestJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const base::FilePath& directory_path, - const std::string& content_security_policy, - bool send_cors_header) { - return chrome_url_request_util::MaybeCreateURLRequestResourceBundleJob( - request, - network_delegate, - directory_path, - content_security_policy, - send_cors_header); -} - base::FilePath ChromeExtensionsBrowserClient::GetBundleResourcePath( const network::ResourceRequest& request, const base::FilePath& extension_resources_path, @@ -480,20 +465,6 @@ return activity_log && activity_log->is_active(); } -ExtensionNavigationUIData* -ChromeExtensionsBrowserClient::GetExtensionNavigationUIData( - net::URLRequest* request) { - content::ResourceRequestInfo* info = - content::ResourceRequestInfo::ForRequest(request); - if (!info) - return nullptr; - ChromeNavigationUIData* navigation_data = - static_cast<ChromeNavigationUIData*>(info->GetNavigationUIData()); - if (!navigation_data) - return nullptr; - return navigation_data->GetExtensionNavigationUIData(); -} - void ChromeExtensionsBrowserClient::GetTabAndWindowIdForWebContents( content::WebContents* web_contents, int* tab_id,
diff --git a/chrome/browser/extensions/chrome_extensions_browser_client.h b/chrome/browser/extensions/chrome_extensions_browser_client.h index ff3c1f0..713b97d1 100644 --- a/chrome/browser/extensions/chrome_extensions_browser_client.h +++ b/chrome/browser/extensions/chrome_extensions_browser_client.h
@@ -65,12 +65,6 @@ bool CanExtensionCrossIncognito( const Extension* extension, content::BrowserContext* context) const override; - net::URLRequestJob* MaybeCreateResourceBundleRequestJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const base::FilePath& directory_path, - const std::string& content_security_policy, - bool send_cors_header) override; base::FilePath GetBundleResourcePath( const network::ResourceRequest& request, const base::FilePath& extension_resources_path, @@ -139,8 +133,6 @@ content::RenderFrameHost* frame, const content::BluetoothChooser::EventHandler& event_handler) override; bool IsActivityLoggingEnabled(content::BrowserContext* context) override; - extensions::ExtensionNavigationUIData* GetExtensionNavigationUIData( - net::URLRequest* request) override; void GetTabAndWindowIdForWebContents(content::WebContents* web_contents, int* tab_id, int* window_id) override;
diff --git a/chrome/browser/extensions/chrome_url_request_util.cc b/chrome/browser/extensions/chrome_url_request_util.cc index c071a32..a47884f 100644 --- a/chrome/browser/extensions/chrome_url_request_util.cc +++ b/chrome/browser/extensions/chrome_url_request_util.cc
@@ -31,8 +31,6 @@ #include "net/http/http_request_headers.h" #include "net/http/http_response_headers.h" #include "net/http/http_response_info.h" -#include "net/url_request/url_request.h" -#include "net/url_request/url_request_simple_job.h" #include "third_party/zlib/google/compression_utils.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/template_expressions.h" @@ -93,83 +91,6 @@ return base::RefCountedString::TakeString(&temp_str); } -// A request for an extension resource in a Chrome .pak file. These are used -// by component extensions. -class URLRequestResourceBundleJob : public net::URLRequestSimpleJob { - public: - URLRequestResourceBundleJob(net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const base::FilePath& filename, - int resource_id, - const std::string& content_security_policy, - bool send_cors_header) - : net::URLRequestSimpleJob(request, network_delegate), - filename_(filename), - resource_id_(resource_id), - weak_factory_(this) { - // Leave cache headers out of resource bundle requests. - response_info_.headers = extensions::BuildHttpHeaders( - content_security_policy, send_cors_header, base::Time()); - } - - // Overridden from URLRequestSimpleJob: - int GetRefCountedData(std::string* mime_type, - std::string* charset, - scoped_refptr<base::RefCountedMemory>* data, - net::CompletionOnceCallback callback) const override { - *data = GetResource(resource_id_, request()->url().host()); - - // Add the Content-Length header now that we know the resource length. - response_info_.headers->AddHeader( - base::StringPrintf("%s: %s", net::HttpRequestHeaders::kContentLength, - base::NumberToString((*data)->size()).c_str())); - - std::string* read_mime_type = new std::string; - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, - base::BindOnce(&net::GetMimeTypeFromFile, filename_, - base::Unretained(read_mime_type)), - base::BindOnce(&URLRequestResourceBundleJob::OnMimeTypeRead, - weak_factory_.GetWeakPtr(), mime_type, charset, *data, - base::Owned(read_mime_type), std::move(callback))); - - return net::ERR_IO_PENDING; - } - - void GetResponseInfo(net::HttpResponseInfo* info) override { - *info = response_info_; - } - - private: - ~URLRequestResourceBundleJob() override {} - - void OnMimeTypeRead(std::string* out_mime_type, - std::string* charset, - scoped_refptr<base::RefCountedMemory> data, - std::string* read_mime_type, - net::CompletionOnceCallback callback, - bool read_result) { - if (read_result) { - response_info_.headers->AddHeader( - base::StringPrintf("%s: %s", net::HttpRequestHeaders::kContentType, - read_mime_type->c_str())); - } - *out_mime_type = *read_mime_type; - DetermineCharset(*read_mime_type, data.get(), charset); - std::move(callback).Run(net::OK); - } - - // We need the filename of the resource to determine the mime type. - base::FilePath filename_; - - // The resource bundle id to load. - int resource_id_; - - net::HttpResponseInfo response_info_; - - mutable base::WeakPtrFactory<URLRequestResourceBundleJob> weak_factory_; -}; - // Loads an extension resource in a Chrome .pak file. These are used by // component extensions. class ResourceBundleFileLoader : public network::mojom::URLLoader { @@ -337,39 +258,6 @@ return false; } -net::URLRequestJob* MaybeCreateURLRequestResourceBundleJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const base::FilePath& directory_path, - const std::string& content_security_policy, - bool send_cors_header) { - base::FilePath resources_path; - base::FilePath relative_path; - // Try to load extension resources from chrome resource file if - // directory_path is a descendant of resources_path. resources_path - // corresponds to src/chrome/browser/resources in source tree. - if (base::PathService::Get(chrome::DIR_RESOURCES, &resources_path) && - // Since component extension resources are included in - // component_extension_resources.pak file in resources_path, calculate - // extension relative path against resources_path. - resources_path.AppendRelativePath(directory_path, &relative_path)) { - base::FilePath request_path = - extensions::file_util::ExtensionURLToRelativeFilePath(request->url()); - int resource_id = 0; - if (ExtensionsBrowserClient::Get() - ->GetComponentExtensionResourceManager() - ->IsComponentExtensionResource(directory_path, request_path, - &resource_id)) { - relative_path = relative_path.Append(request_path); - relative_path = relative_path.NormalizePathSeparators(); - return new URLRequestResourceBundleJob( - request, network_delegate, relative_path, resource_id, - content_security_policy, send_cors_header); - } - } - return NULL; -} - base::FilePath GetBundleResourcePath( const network::ResourceRequest& request, const base::FilePath& extension_resources_path,
diff --git a/chrome/browser/extensions/chrome_url_request_util.h b/chrome/browser/extensions/chrome_url_request_util.h index a61b87b..f3b1fe9 100644 --- a/chrome/browser/extensions/chrome_url_request_util.h +++ b/chrome/browser/extensions/chrome_url_request_util.h
@@ -17,12 +17,6 @@ class FilePath; } -namespace net { -class NetworkDelegate; -class URLRequest; -class URLRequestJob; -} - namespace extensions { class Extension; class ExtensionSet; @@ -45,16 +39,6 @@ const ProcessMap& process_map, bool* allowed); -// Creates a URLRequestJob for loading component extension resources out of -// a Chrome resource bundle. Returns NULL if the requested resource is not a -// component extension resource. -net::URLRequestJob* MaybeCreateURLRequestResourceBundleJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const base::FilePath& directory_path, - const std::string& content_security_policy, - bool send_cors_header); - // Return the |request|'s resource path relative to the Chromium resources path // (chrome::DIR_RESOURCES) *if* the request refers to a resource within the // Chrome resource bundle. If not then the returned file path will be empty.
diff --git a/chrome/browser/extensions/extension_messages_apitest.cc b/chrome/browser/extensions/extension_messages_apitest.cc index e384d374..635ea56 100644 --- a/chrome/browser/extensions/extension_messages_apitest.cc +++ b/chrome/browser/extensions/extension_messages_apitest.cc
@@ -195,31 +195,6 @@ ASSERT_TRUE(RunExtensionTest("messaging/background_only")) << message_; } -// Tests whether an extension in an interstitial page can send messages to the -// background page. -IN_PROC_BROWSER_TEST_F(MessagingApiTest, MessagingInterstitial) { -#if defined(OS_WIN) || defined(OS_MACOSX) - // TODO(https://crbug.com/833429): Intermittent timeouts when run with - // --site-per-process on Windows. - if (content::AreAllSitesIsolatedForTesting()) - return; -#endif - // TODO(carlosil): Completely remove this test once committed interstitials - // fully launch. - // With committed interstitials enabled, interstitials are no longer a - // special case, and do have a web contents, so the special conditions - // that are checked in this test no longer apply. - if (base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials)) - return; - net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS); - https_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME); - ASSERT_TRUE(https_server.Start()); - - ASSERT_TRUE(RunExtensionSubtest("messaging/interstitial_component", - https_server.base_url().spec(), - kFlagLoadAsComponent)) << message_; -} - // Tests externally_connectable between a web page and an extension. // // TODO(kalman): Test between extensions. This is already tested in this file,
diff --git a/chrome/browser/extensions/extension_protocols_unittest.cc b/chrome/browser/extensions/extension_protocols_unittest.cc index 7a259c1..59abae6 100644 --- a/chrome/browser/extensions/extension_protocols_unittest.cc +++ b/chrome/browser/extensions/extension_protocols_unittest.cc
@@ -10,6 +10,7 @@ #include "base/command_line.h" #include "base/files/file_util.h" +#include "base/path_service.h" #include "base/run_loop.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" @@ -45,12 +46,7 @@ #include "extensions/common/file_util.h" #include "extensions/common/value_builder.h" #include "extensions/test/test_extension_dir.h" -#include "net/base/request_priority.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" -#include "net/url_request/url_request.h" -#include "net/url_request/url_request_job_factory_impl.h" -#include "net/url_request/url_request_status.h" -#include "net/url_request/url_request_test_util.h" #include "services/network/test/test_url_loader_client.h" #include "testing/gtest/include/gtest/gtest.h" @@ -61,14 +57,6 @@ namespace extensions { namespace { -enum class RequestHandlerType { - kURLLoader, - kURLRequest, -}; - -const RequestHandlerType kTestModes[] = {RequestHandlerType::kURLLoader, - RequestHandlerType::kURLRequest}; - base::FilePath GetTestPath(const std::string& name) { base::FilePath path; EXPECT_TRUE(base::PathService::Get(chrome::DIR_TEST_DATA, &path)); @@ -152,19 +140,14 @@ // depending on the on test type. class GetResult { public: - GetResult(std::unique_ptr<net::URLRequest> request, int result) - : request_(std::move(request)), result_(result) {} GetResult(const network::ResourceResponseHead& response, int result) : resource_response_(response), result_(result) {} - GetResult(GetResult&& other) - : request_(std::move(other.request_)), result_(other.result_) {} + GetResult(GetResult&& other) : result_(other.result_) {} ~GetResult() = default; std::string GetResponseHeaderByName(const std::string& name) const { std::string value; - if (request_) - request_->GetResponseHeaderByName(name, &value); - else if (resource_response_.headers) + if (resource_response_.headers) resource_response_.headers->GetNormalizedHeader(name, &value); return value; } @@ -172,7 +155,6 @@ int result() const { return result_; } private: - std::unique_ptr<net::URLRequest> request_; const network::ResourceResponseHead resource_response_; int result_; @@ -184,21 +166,17 @@ // This test lives in src/chrome instead of src/extensions because it tests // functionality delegated back to Chrome via ChromeExtensionsBrowserClient. // See chrome/browser/extensions/chrome_url_request_util.cc. -class ExtensionProtocolsTestBase - : public testing::Test, - public testing::WithParamInterface<RequestHandlerType> { +class ExtensionProtocolsTestBase : public testing::Test { public: explicit ExtensionProtocolsTestBase(bool force_incognito) : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP), rvh_test_enabler_(new content::RenderViewHostTestEnabler()), - old_factory_(NULL), force_incognito_(force_incognito) {} void SetUp() override { testing::Test::SetUp(); testing_profile_ = TestingProfile::Builder().Build(); contents_ = CreateTestWebContents(); - old_factory_ = test_url_request_context_.job_factory(); // Set up content verification. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); @@ -213,34 +191,16 @@ void TearDown() override { loader_factory_.reset(); - test_url_request_context_.set_job_factory(old_factory_); content_verifier_->Shutdown(); } void SetProtocolHandler(bool is_incognito) { - switch (request_handler()) { - case RequestHandlerType::kURLLoader: - loader_factory_ = extensions::CreateExtensionNavigationURLLoaderFactory( - browser_context(), false); - break; - case RequestHandlerType::kURLRequest: - job_factory_.SetProtocolHandler( - kExtensionScheme, - CreateExtensionProtocolHandler(is_incognito, info_map())); - test_url_request_context_.set_job_factory(&job_factory_); - break; - } + loader_factory_ = extensions::CreateExtensionNavigationURLLoaderFactory( + browser_context(), false); } GetResult RequestOrLoad(const GURL& url, ResourceType resource_type) { - switch (request_handler()) { - case RequestHandlerType::kURLLoader: - return LoadURL(url, resource_type); - case RequestHandlerType::kURLRequest: - return RequestURL(url, resource_type); - } - NOTREACHED(); - return GetResult(nullptr, net::ERR_FAILED); + return LoadURL(url, resource_type); } void AddExtension(const scoped_refptr<const Extension>& extension, @@ -248,21 +208,17 @@ bool notifications_disabled) { info_map()->AddExtension(extension.get(), base::Time::Now(), incognito_enabled, notifications_disabled); - if (request_handler() == RequestHandlerType::kURLLoader) { - EXPECT_TRUE(extension_registry()->AddEnabled(extension)); - ExtensionPrefs::Get(browser_context()) - ->SetIsIncognitoEnabled(extension->id(), incognito_enabled); - } + EXPECT_TRUE(extension_registry()->AddEnabled(extension)); + ExtensionPrefs::Get(browser_context()) + ->SetIsIncognitoEnabled(extension->id(), incognito_enabled); } void RemoveExtension(const scoped_refptr<const Extension>& extension, const UnloadedExtensionReason reason) { info_map()->RemoveExtension(extension->id(), reason); - if (request_handler() == RequestHandlerType::kURLLoader) { - EXPECT_TRUE(extension_registry()->RemoveEnabled(extension->id())); - if (reason == UnloadedExtensionReason::DISABLE) - EXPECT_TRUE(extension_registry()->AddDisabled(extension)); - } + EXPECT_TRUE(extension_registry()->RemoveEnabled(extension->id())); + if (reason == UnloadedExtensionReason::DISABLE) + EXPECT_TRUE(extension_registry()->AddDisabled(extension)); } // Helper method to create a URL request/loader, call RequestOrLoad on it, and @@ -325,37 +281,6 @@ client.completion_status().error_code); } - GetResult RequestURL(const GURL& url, ResourceType resource_type) { - auto request = test_url_request_context_.CreateRequest( - url, net::DEFAULT_PRIORITY, &test_delegate_, - TRAFFIC_ANNOTATION_FOR_TESTS); - - content::ResourceRequestInfo::AllocateForTesting( - request.get(), resource_type, - /* resource_context */ nullptr, - /*render_process_id=*/-1, - /*render_view_id=*/-1, - /*render_frame_id=*/-1, - /*is_main_frame=*/resource_type == content::ResourceType::kMainFrame, - content::ResourceInterceptPolicy::kAllowAll, - /*is_async=*/false, content::PREVIEWS_OFF, - /*navigation_ui_data*/ nullptr); - request->Start(); - - if (power_monitor_source_) { - power_monitor_source_->GenerateSuspendEvent(); - power_monitor_source_->GenerateResumeEvent(); - - // PowerMonitorTestSource calls RunLoop().RunUntilIdle() which causes the - // request to be completed. - EXPECT_TRUE(test_delegate_.response_completed()); - } else { - base::RunLoop().Run(); - } - - return GetResult(std::move(request), test_delegate_.request_status()); - } - std::unique_ptr<content::WebContents> CreateTestWebContents() { auto site_instance = content::SiteInstance::Create(browser_context()); return content::WebContentsTester::CreateTestWebContents( @@ -368,16 +293,10 @@ return web_contents()->GetMainFrame(); } - RequestHandlerType request_handler() const { return GetParam(); } - content::TestBrowserThreadBundle thread_bundle_; std::unique_ptr<content::RenderViewHostTestEnabler> rvh_test_enabler_; - net::URLRequestJobFactoryImpl job_factory_; - const net::URLRequestJobFactory* old_factory_; std::unique_ptr<network::mojom::URLLoaderFactory> loader_factory_; - net::TestURLRequestContext test_url_request_context_; std::unique_ptr<TestingProfile> testing_profile_; - net::TestDelegate test_delegate_; std::unique_ptr<content::WebContents> contents_; const bool force_incognito_; @@ -403,7 +322,7 @@ // only allowed under the right circumstances (if the extension is allowed // in incognito, and it's either a non-main-frame request or a split-mode // extension). -TEST_P(ExtensionProtocolsIncognitoTest, IncognitoRequest) { +TEST_F(ExtensionProtocolsIncognitoTest, IncognitoRequest) { // Register an incognito extension protocol handler. SetProtocolHandler(true); @@ -466,7 +385,7 @@ // Tests getting a resource for a component extension works correctly where // there is no mime type. Such a resource currently only exists for Chrome OS // build. -TEST_P(ExtensionProtocolsTest, ComponentResourceRequestNoMimeType) { +TEST_F(ExtensionProtocolsTest, ComponentResourceRequestNoMimeType) { SetProtocolHandler(false); std::unique_ptr<base::DictionaryValue> manifest = DictionaryBuilder() @@ -500,7 +419,7 @@ // Tests getting a resource for a component extension works correctly, both when // the extension is enabled and when it is disabled. -TEST_P(ExtensionProtocolsTest, ComponentResourceRequest) { +TEST_F(ExtensionProtocolsTest, ComponentResourceRequest) { // Register a non-incognito extension protocol handler. SetProtocolHandler(false); @@ -533,7 +452,7 @@ // Tests that a URL request for resource from an extension returns a few // expected response headers. -TEST_P(ExtensionProtocolsTest, ResourceRequestResponseHeaders) { +TEST_F(ExtensionProtocolsTest, ResourceRequestResponseHeaders) { // Register a non-incognito extension protocol handler. SetProtocolHandler(false); @@ -564,7 +483,7 @@ // Tests that a URL request for main frame or subframe from an extension // succeeds, but subresources fail. See http://crbug.com/312269. -TEST_P(ExtensionProtocolsTest, AllowFrameRequests) { +TEST_F(ExtensionProtocolsTest, AllowFrameRequests) { // Register a non-incognito extension protocol handler. SetProtocolHandler(false); @@ -592,7 +511,7 @@ } } -TEST_P(ExtensionProtocolsTest, MetadataFolder) { +TEST_F(ExtensionProtocolsTest, MetadataFolder) { SetProtocolHandler(false); base::FilePath extension_dir = GetTestPath("metadata_folder"); @@ -621,7 +540,7 @@ // Tests that unreadable files and deleted files correctly go through // ContentVerifyJob. -TEST_P(ExtensionProtocolsTest, VerificationSeenForFileAccessErrors) { +TEST_F(ExtensionProtocolsTest, VerificationSeenForFileAccessErrors) { SetProtocolHandler(false); // Unzip extension containing verification hashes to a temporary directory. @@ -676,7 +595,7 @@ } // Tests that zero byte files correctly go through ContentVerifyJob. -TEST_P(ExtensionProtocolsTest, VerificationSeenForZeroByteFile) { +TEST_F(ExtensionProtocolsTest, VerificationSeenForZeroByteFile) { SetProtocolHandler(false); const std::string kEmptyJs("empty.js"); @@ -738,7 +657,7 @@ } } -TEST_P(ExtensionProtocolsTest, VerifyScriptListedAsIcon) { +TEST_F(ExtensionProtocolsTest, VerifyScriptListedAsIcon) { SetProtocolHandler(false); const std::string kBackgroundJs("background.js"); @@ -789,7 +708,7 @@ } // Tests that mime types are properly set for returned extension resources. -TEST_P(ExtensionProtocolsTest, MimeTypesForKnownFiles) { +TEST_F(ExtensionProtocolsTest, MimeTypesForKnownFiles) { // Register a non-incognito extension protocol handler. SetProtocolHandler(false); @@ -852,7 +771,7 @@ // // Flaky on Windows. // TODO(https://crbug.com/921687): Investigate and fix. -TEST_P(ExtensionProtocolsTest, MAYBE_ExtensionRequestsNotAborted) { +TEST_F(ExtensionProtocolsTest, MAYBE_ExtensionRequestsNotAborted) { // Register a non-incognito extension protocol handler. SetProtocolHandler(false); @@ -875,12 +794,4 @@ EXPECT_EQ(net::OK, DoRequestOrLoad(extension.get(), "background.js").result()); } -INSTANTIATE_TEST_SUITE_P(Extensions, - ExtensionProtocolsTest, - ::testing::ValuesIn(kTestModes)); - -INSTANTIATE_TEST_SUITE_P(Extensions, - ExtensionProtocolsIncognitoTest, - ::testing::ValuesIn(kTestModes)); - } // namespace extensions
diff --git a/chrome/browser/extensions/service_worker_apitest.cc b/chrome/browser/extensions/service_worker_apitest.cc index 3040ea5..f134939 100644 --- a/chrome/browser/extensions/service_worker_apitest.cc +++ b/chrome/browser/extensions/service_worker_apitest.cc
@@ -1702,7 +1702,7 @@ test_dir.WriteManifest(kManifest); test_dir.WriteFile(FILE_PATH_LITERAL("script.js"), kScript); - // Consruct this before loading the extension, since the extension will + // Construct this before loading the extension, since the extension will // immediately uninstall itself when it loads. extensions::TestExtensionRegistryObserver observer( extensions::ExtensionRegistry::Get(browser()->profile()));
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index a937782..a02ba4a 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -2699,6 +2699,11 @@ "expiry_milestone": -1 }, { + "name": "show-bluetooth-device-battery", + "owners": [ "hansberry" ], + "expiry_milestone": 80 + }, + { "name": "show-taps", "owners": [ "//ash/OWNERS" ], // This is a debug flag, so that video bug reports can show input taps to
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index 46d76b9..b541bda 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -3188,6 +3188,11 @@ const char kSchedulerConfigurationConservative[] = "Conservative"; const char kSchedulerConfigurationPerformance[] = "Performance"; +const char kShowBluetoothDeviceBatteryName[] = "Show Bluetooth device battery"; +const char kShowBluetoothDeviceBatteryDescription[] = + "Enables showing the battery level of connected and supported Bluetooth " + "devices in the System Tray and Settings UI."; + const char kShowTapsName[] = "Show taps"; const char kShowTapsDescription[] = "Draws a circle at each touch point, which makes touch points more obvious "
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index adb6bcc..068f8cca4 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -1910,6 +1910,9 @@ extern const char kSchedulerConfigurationConservative[]; extern const char kSchedulerConfigurationPerformance[]; +extern const char kShowBluetoothDeviceBatteryName[]; +extern const char kShowBluetoothDeviceBatteryDescription[]; + extern const char kShowTapsName[]; extern const char kShowTapsDescription[];
diff --git a/chrome/browser/media/router/providers/cast/activity_record.cc b/chrome/browser/media/router/providers/cast/activity_record.cc index 31dd8e74..2bc69b1 100644 --- a/chrome/browser/media/router/providers/cast/activity_record.cc +++ b/chrome/browser/media/router/providers/cast/activity_record.cc
@@ -41,8 +41,15 @@ DVLOG(2) << "SetOrUpdateSession old session_id = " << session_id_.value_or("<missing>") << ", new session_id = " << session.session_id(); - session_id_ = session.session_id(); route_.set_description(session.GetRouteDescription()); + if (session_id_) { + DCHECK_EQ(*session_id_, session.session_id()); + } else { + session_id_ = session.session_id(); + OnSessionSet(); + } } +void ActivityRecord::OnSessionSet() {} + } // namespace media_router
diff --git a/chrome/browser/media/router/providers/cast/activity_record.h b/chrome/browser/media/router/providers/cast/activity_record.h index b119e19..f7ff4dd3 100644 --- a/chrome/browser/media/router/providers/cast/activity_record.h +++ b/chrome/browser/media/router/providers/cast/activity_record.h
@@ -128,6 +128,8 @@ // Handles a message forwarded by CastActivityManager. virtual void OnAppMessage(const cast_channel::CastMessage& message) = 0; + virtual void OnInternalMessage( + const cast_channel::InternalMessage& message) = 0; // Closes / Terminates the PresentationConnections of all clients connected // to this activity. @@ -136,6 +138,9 @@ virtual void TerminatePresentationConnections() = 0; protected: + // Function called the first time session_id_ has been set. + virtual void OnSessionSet(); + CastSession* GetSession() const; MediaRoute route_;
diff --git a/chrome/browser/media/router/providers/cast/cast_activity_manager.cc b/chrome/browser/media/router/providers/cast/cast_activity_manager.cc index 06e908b..5e88f0a 100644 --- a/chrome/browser/media/router/providers/cast/cast_activity_manager.cc +++ b/chrome/browser/media/router/providers/cast/cast_activity_manager.cc
@@ -135,14 +135,6 @@ } else { // Launch a flinging session. auto* activity_ptr = AddCastActivityRecord(route, app_id); - NotifyAllOnRoutesUpdated(); - base::TimeDelta launch_timeout = cast_source.launch_timeout(); - message_handler_->LaunchSession( - sink.cast_data().cast_channel_id, app_id, launch_timeout, - base::BindOnce(&CastActivityManager::HandleLaunchSessionResponse, - weak_ptr_factory_.GetWeakPtr(), route_id, sink, - cast_source)); - const std::string& client_id = cast_source.client_id(); if (!client_id.empty()) { presentation_connection = @@ -153,6 +145,14 @@ } } + NotifyAllOnRoutesUpdated(); + base::TimeDelta launch_timeout = cast_source.launch_timeout(); + message_handler_->LaunchSession( + sink.cast_data().cast_channel_id, app_id, launch_timeout, + base::BindOnce(&CastActivityManager::HandleLaunchSessionResponse, + weak_ptr_factory_.GetWeakPtr(), route_id, sink, + cast_source)); + std::move(params.callback) .Run(route, std::move(presentation_connection), /* error_text */ base::nullopt, RouteRequestResult::ResultCode::OK); @@ -368,7 +368,7 @@ // There is no session associated with the route, e.g. the launch request is // still pending. if (!session_id) { - DVLOG(2) << "Terminated route has no session ID."; + DLOG(WARNING) << "Terminated route has no session ID."; RemoveActivity(activity_it, PresentationConnectionState::TERMINATED, PresentationConnectionCloseReason::CLOSED); std::move(callback).Run(base::nullopt, RouteRequestResult::OK); @@ -450,6 +450,18 @@ it->second->OnAppMessage(message); } +void CastActivityManager::OnInternalMessage( + int channel_id, + const cast_channel::InternalMessage& message) { + DVLOG(2) << "Received internal message on cast channel " << channel_id; + auto it = FindActivityByChannelId(channel_id); + if (it == activities_.end()) { + DVLOG(2) << "No activity associated with channel!"; + return; + } + it->second->OnInternalMessage(message); +} + void CastActivityManager::OnSessionAddedOrUpdated(const MediaSinkInternal& sink, const CastSession& session) { auto activity_it = FindActivityByChannelId(sink.cast_data().cast_channel_id);
diff --git a/chrome/browser/media/router/providers/cast/cast_activity_manager.h b/chrome/browser/media/router/providers/cast/cast_activity_manager.h index b1db947..ccecada4 100644 --- a/chrome/browser/media/router/providers/cast/cast_activity_manager.h +++ b/chrome/browser/media/router/providers/cast/cast_activity_manager.h
@@ -108,9 +108,11 @@ const MediaRoute* GetRoute(const MediaRoute::Id& route_id) const; std::vector<MediaRoute> GetRoutes() const; - // cast_channel::CastMessageHandler::Observer override. + // cast_channel::CastMessageHandler::Observer overrides. void OnAppMessage(int channel_id, const cast_channel::CastMessage& message) override; + void OnInternalMessage(int channel_id, + const cast_channel::InternalMessage& message) override; // CastSessionTracker::Observer implementation. void OnSessionAddedOrUpdated(const MediaSinkInternal& sink,
diff --git a/chrome/browser/media/router/providers/cast/cast_activity_record.cc b/chrome/browser/media/router/providers/cast/cast_activity_record.cc index 4a0d1dd..8bd17f77 100644 --- a/chrome/browser/media/router/providers/cast/cast_activity_record.cc +++ b/chrome/browser/media/router/providers/cast/cast_activity_record.cc
@@ -217,6 +217,9 @@ } } +void CastActivityRecord::OnInternalMessage( + const cast_channel::InternalMessage& message) {} + int CastActivityRecord::GetCastChannelId() { const MediaSinkInternal* sink = media_sink_service_->GetSinkByRoute(route_); if (!sink) {
diff --git a/chrome/browser/media/router/providers/cast/cast_activity_record.h b/chrome/browser/media/router/providers/cast/cast_activity_record.h index 38d84c3..ceed9f2 100644 --- a/chrome/browser/media/router/providers/cast/cast_activity_record.h +++ b/chrome/browser/media/router/providers/cast/cast_activity_record.h
@@ -80,6 +80,7 @@ blink::mojom::PresentationConnectionCloseReason close_reason) override; void TerminatePresentationConnections() override; void OnAppMessage(const cast_channel::CastMessage& message) override; + void OnInternalMessage(const cast_channel::InternalMessage& message) override; static void SetClientFactoryForTest( CastSessionClientFactoryForTest* factory) {
diff --git a/chrome/browser/media/router/providers/cast/cast_session_tracker_unittest.cc b/chrome/browser/media/router/providers/cast/cast_session_tracker_unittest.cc index 96d5f16..600e591 100644 --- a/chrome/browser/media/router/providers/cast/cast_session_tracker_unittest.cc +++ b/chrome/browser/media/router/providers/cast/cast_session_tracker_unittest.cc
@@ -98,7 +98,7 @@ session_tracker_.OnInternalMessage( sink_.cast_data().cast_channel_id, cast_channel::InternalMessage( - cast_channel::CastMessageType::kReceiverStatus, + cast_channel::CastMessageType::kReceiverStatus, "theNamespace", std::move(*ParseJsonDeprecated(kReceiverStatus)))); session_ = session_tracker_.GetSessions().begin()->second.get(); @@ -144,7 +144,7 @@ session_tracker_.OnInternalMessage( sink_.cast_data().cast_channel_id, cast_channel::InternalMessage( - cast_channel::CastMessageType::kReceiverStatus, + cast_channel::CastMessageType::kReceiverStatus, "theNamespace", std::move(*ParseJsonDeprecated(kIdleReceiverStatus)))); } @@ -192,6 +192,7 @@ session_tracker_.OnInternalMessage( sink_.cast_data().cast_channel_id, cast_channel::InternalMessage(cast_channel::CastMessageType::kMediaStatus, + "theNamespace", std::move(*ParseJsonDeprecated(R"({ "status": [{ "playerState": "anything but IDLE", @@ -247,6 +248,7 @@ session_tracker_.OnInternalMessage( sink_.cast_data().cast_channel_id, cast_channel::InternalMessage(cast_channel::CastMessageType::kMediaStatus, + "theNamespace", std::move(*ParseJsonDeprecated(R"({ "requestId": 12345, "status": [{ @@ -278,6 +280,7 @@ session_tracker_.OnInternalMessage( sink_.cast_data().cast_channel_id, cast_channel::InternalMessage(cast_channel::CastMessageType::kMediaStatus, + "theNamespace", std::move(*ParseJsonDeprecated(R"({ "status": [{ "media": "theMedia", @@ -324,6 +327,7 @@ session_tracker_.OnInternalMessage( sink_.cast_data().cast_channel_id, cast_channel::InternalMessage(cast_channel::CastMessageType::kMediaStatus, + "theNamespace", std::move(*ParseJsonDeprecated(R"({ "status": [{ "mediaSessionId": 345,
diff --git a/chrome/browser/media/router/providers/cast/mirroring_activity_record.cc b/chrome/browser/media/router/providers/cast/mirroring_activity_record.cc index 54b3d389..79cbb8c 100644 --- a/chrome/browser/media/router/providers/cast/mirroring_activity_record.cc +++ b/chrome/browser/media/router/providers/cast/mirroring_activity_record.cc
@@ -11,6 +11,7 @@ #include "base/bind.h" #include "base/json/json_reader.h" +#include "base/json/json_writer.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/user_metrics.h" #include "base/metrics/user_metrics_action.h" @@ -69,10 +70,10 @@ mojo::MakeRequest(&host_)); // Create Mojo bindings for the interfaces this object implements. - SessionObserverPtr observer_ptr_; - observer_binding_.Bind(mojo::MakeRequest(&observer_ptr_)); - CastMessageChannelPtr channel_ptr_; - channel_binding_.Bind(mojo::MakeRequest(&channel_ptr_)); + SessionObserverPtr observer_ptr; + observer_binding_.Bind(mojo::MakeRequest(&observer_ptr)); + CastMessageChannelPtr channel_ptr; + channel_binding_.Bind(mojo::MakeRequest(&channel_ptr)); // Derive session type from capabilities. const bool has_audio = (cast_data.capabilities & @@ -85,11 +86,13 @@ ? SessionType::AUDIO_AND_VIDEO : has_audio ? SessionType::AUDIO_ONLY : SessionType::VIDEO_ONLY; - // Start mirroring. - host_->Start( + // Arrange to start mirroring once the session is set. + on_session_set_ = base::BindOnce( + &mirroring::mojom::MirroringServiceHost::Start, + base::Unretained(host_.get()), SessionParameters::New(session_type, cast_data.ip_endpoint.address(), cast_data.model_name), - std::move(observer_ptr_), std::move(channel_ptr_), + std::move(observer_ptr), std::move(channel_ptr), mojo::MakeRequest(&channel_to_service_)); } @@ -112,6 +115,9 @@ } void MirroringActivityRecord::Send(mirroring::mojom::CastMessagePtr message) { + DCHECK(message); + DVLOG(2) << "Relaying message to receiver: " << message->json_format_data; + data_decoder_->ParseJson( message->json_format_data, base::BindRepeating( @@ -119,18 +125,18 @@ if (!self) return; - auto internal_message = CastInternalMessage::From(std::move(value)); CastSession* session = self->GetSession(); + DCHECK(session); // TODO(jrw): Can some of this logic be shared with // CastActivityRecord::SendAppMessageToReceiver? - cast_channel::CastMessage app_message = + cast_channel::CastMessage cast_message = cast_channel::CreateCastMessage( - internal_message->app_message_namespace(), - internal_message->app_message_body(), - internal_message->client_id(), session->transport_id()); - self->message_handler_->SendAppMessage(self->channel_id_, - app_message); + mirroring::mojom::kWebRtcNamespace, std::move(value), + self->message_handler_->sender_id(), + session->transport_id()); + self->message_handler_->SendCastMessage(self->channel_id_, + cast_message); }, weak_ptr_factory_.GetWeakPtr()), base::BindRepeating( @@ -142,32 +148,17 @@ route().media_route_id())); } -mojom::RoutePresentationConnectionPtr MirroringActivityRecord::AddClient( - const CastMediaSource& source, - const url::Origin& origin, - int tab_id) { - // This method seems to only be called on CastActivityRecord instances. - NOTIMPLEMENTED(); - return nullptr; -} - -void MirroringActivityRecord::RemoveClient(const std::string& client_id) { - // TODO(jrw): This method is never called, and it should probably only ever - // be called on CastActivityRecord instances. - NOTIMPLEMENTED(); -} - Result MirroringActivityRecord::SendAppMessageToReceiver( const CastInternalMessage& cast_message) { // This method is only called from CastSessionClient. - NOTIMPLEMENTED(); + NOTREACHED(); return Result::kOk; } base::Optional<int> MirroringActivityRecord::SendMediaRequestToReceiver( const CastInternalMessage& cast_message) { // This method is only called from CastSessionClient. - NOTIMPLEMENTED(); + NOTREACHED(); return base::nullopt; } @@ -182,7 +173,7 @@ // this. I think the implementation is shared between CastActivityRecord and // MirroringActivityRecord, so it could be put in the ActivityRecord base // class if we wanted to. - NOTIMPLEMENTED(); + NOTREACHED(); } void MirroringActivityRecord::SendStopSessionMessageToReceiver( @@ -195,7 +186,22 @@ void MirroringActivityRecord::HandleLeaveSession(const std::string& client_id) { // This method is only called from CastSessionClient. - NOTIMPLEMENTED(); + NOTREACHED(); +} + +mojom::RoutePresentationConnectionPtr MirroringActivityRecord::AddClient( + const CastMediaSource& source, + const url::Origin& origin, + int tab_id) { + // This method seems to only be called on CastActivityRecord instances. + NOTREACHED(); + return nullptr; +} + +void MirroringActivityRecord::RemoveClient(const std::string& client_id) { + // This method is never called, and it should probably only ever be called on + // CastActivityRecord instances. + NOTREACHED(); } void MirroringActivityRecord::SendMessageToClient( @@ -218,6 +224,7 @@ // Ignore message with wrong namespace. return; } + DVLOG(2) << "Relaying app message from receiver: " << message; DCHECK(message.has_payload_utf8()); DCHECK_EQ(message.protocol_version(), cast_channel::CastMessage_ProtocolVersion_CASTV2_1_0); @@ -229,6 +236,24 @@ channel_to_service_->Send(std::move(ptr)); } +void MirroringActivityRecord::OnInternalMessage( + const cast_channel::InternalMessage& message) { + DVLOG(2) << "Relaying internal message from receiver: " << message.message; + mirroring::mojom::CastMessagePtr ptr = mirroring::mojom::CastMessage::New(); + ptr->message_namespace = message.message_namespace; + + // TODO(jrw): This line re-serializes a JSON string that was parsed by the + // caller of this method. Yuck! This is probably a necessary evil as long as + // the extension needs to communicate with the mirroring service. + CHECK(base::JSONWriter::Write(message.message, &ptr->json_format_data)); + + channel_to_service_->Send(std::move(ptr)); +} + +void MirroringActivityRecord::OnSessionSet() { + std::move(on_session_set_).Run(); +} + void MirroringActivityRecord::StopMirroring() { // Running the callback will cause this object to be deleted. if (on_stop_)
diff --git a/chrome/browser/media/router/providers/cast/mirroring_activity_record.h b/chrome/browser/media/router/providers/cast/mirroring_activity_record.h index bab6cc8..19d5369 100644 --- a/chrome/browser/media/router/providers/cast/mirroring_activity_record.h +++ b/chrome/browser/media/router/providers/cast/mirroring_activity_record.h
@@ -27,7 +27,7 @@ public mirroring::mojom::SessionObserver, public mirroring::mojom::CastMessageChannel { public: - using OnStopCallback = base::OnceCallback<void()>; + using OnStopCallback = base::OnceClosure; MirroringActivityRecord(const MediaRoute& route, const std::string& app_id, @@ -74,6 +74,10 @@ blink::mojom::PresentationConnectionCloseReason close_reason) override; void TerminatePresentationConnections() override; void OnAppMessage(const cast_channel::CastMessage& message) override; + void OnInternalMessage(const cast_channel::InternalMessage& message) override; + + protected: + void OnSessionSet() override; private: enum class MirroringType { @@ -99,6 +103,7 @@ const int channel_id_; const MirroringType mirroring_type_; OnStopCallback on_stop_; + base::OnceCallback<void()> on_session_set_; base::WeakPtrFactory<MirroringActivityRecord> weak_ptr_factory_{this}; };
diff --git a/chrome/browser/media/router/providers/cast/mock_activity_record.h b/chrome/browser/media/router/providers/cast/mock_activity_record.h index b3a456a..4e57596 100644 --- a/chrome/browser/media/router/providers/cast/mock_activity_record.h +++ b/chrome/browser/media/router/providers/cast/mock_activity_record.h
@@ -63,6 +63,8 @@ void(blink::mojom::PresentationConnectionCloseReason close_reason)); MOCK_METHOD0(TerminatePresentationConnections, void()); MOCK_METHOD1(OnAppMessage, void(const cast_channel::CastMessage& message)); + MOCK_METHOD1(OnInternalMessage, + void(const cast_channel::InternalMessage& message)); }; } // namespace media_router
diff --git a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer.cc b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer.cc index ae04b334..346a34a 100644 --- a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer.cc +++ b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer.cc
@@ -383,20 +383,29 @@ void AdsPageLoadMetricsObserver::OnFrameDeleted( content::RenderFrameHost* render_frame_host) { + if (!render_frame_host) + return; + const auto& id_and_data = ad_frames_data_.find(render_frame_host->GetFrameTreeNodeId()); if (id_and_data == ad_frames_data_.end()) return; - FrameData* ancestor_data = &*id_and_data->second; + FrameData* ancestor_data = nullptr; + if (id_and_data->second != ad_frames_data_storage_.end()) + ancestor_data = &*id_and_data->second; + + DCHECK_EQ(id_and_data->second == ad_frames_data_storage_.end(), + !ancestor_data); // If the root ad frame has been deleted, flush histograms for the frame and // remove it from storage. All child frames should be deleted by this point. - if (ancestor_data->frame_tree_node_id() == - render_frame_host->GetFrameTreeNodeId()) { + if (ancestor_data && ancestor_data->frame_tree_node_id() == + render_frame_host->GetFrameTreeNodeId()) { RecordPerFrameHistogramsForAdTagging(*ancestor_data); RecordPerFrameHistogramsForCpuUsage(*ancestor_data); ancestor_data->RecordAdFrameLoadUkmEvent(GetDelegate()->GetSourceId()); + DCHECK(id_and_data->second != ad_frames_data_storage_.end()); ad_frames_data_storage_.erase(id_and_data->second); }
diff --git a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_unittest.cc b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_unittest.cc index 6c20b666..96f674a 100644 --- a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_unittest.cc +++ b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_unittest.cc
@@ -887,6 +887,20 @@ 0 /* non_ad_cached_kb */, 10 /* non_ad_uncached_kb */); } +// Tests that a non ad frame that is deleted does not cause any unspecified +// behavior (see https://crbug.com/973954). +TEST_F(AdsPageLoadMetricsObserverTest, NonAdFrameDestroyed_FrameDeleted) { + RenderFrameHost* main_frame = NavigateMainFrame(kNonAdUrl); + RenderFrameHost* vanilla_frame = + CreateAndNavigateSubFrame(kNonAdUrl, main_frame); + + ResourceDataUpdate(main_frame, ResourceCached::NOT_CACHED, 10); + + content::RenderFrameHostTester::For(vanilla_frame)->Detach(); + + NavigateMainFrame(kNonAdUrl); +} + // Tests that main frame ad bytes are recorded correctly. TEST_F(AdsPageLoadMetricsObserverTest, MainFrameAdBytesRecorded) { NavigateMainFrame(kNonAdUrl);
diff --git a/chrome/browser/performance_manager/chrome_browser_main_extra_parts_performance_manager.cc b/chrome/browser/performance_manager/chrome_browser_main_extra_parts_performance_manager.cc index be0f4261..4d42251 100644 --- a/chrome/browser/performance_manager/chrome_browser_main_extra_parts_performance_manager.cc +++ b/chrome/browser/performance_manager/chrome_browser_main_extra_parts_performance_manager.cc
@@ -16,11 +16,8 @@ ChromeBrowserMainExtraPartsPerformanceManager:: ~ChromeBrowserMainExtraPartsPerformanceManager() = default; -void ChromeBrowserMainExtraPartsPerformanceManager:: - ServiceManagerConnectionStarted( - content::ServiceManagerConnection* connection) { +void ChromeBrowserMainExtraPartsPerformanceManager::PostCreateThreads() { performance_manager_ = performance_manager::PerformanceManager::Create(); - browser_child_process_watcher_ = std::make_unique<performance_manager::BrowserChildProcessWatcher>(); }
diff --git a/chrome/browser/performance_manager/chrome_browser_main_extra_parts_performance_manager.h b/chrome/browser/performance_manager/chrome_browser_main_extra_parts_performance_manager.h index c2ba467..44cc4ed 100644 --- a/chrome/browser/performance_manager/chrome_browser_main_extra_parts_performance_manager.h +++ b/chrome/browser/performance_manager/chrome_browser_main_extra_parts_performance_manager.h
@@ -24,8 +24,7 @@ private: // ChromeBrowserMainExtraParts overrides. - void ServiceManagerConnectionStarted( - content::ServiceManagerConnection* connection) override; + void PostCreateThreads() override; void PostMainMessageLoopRun() override; std::unique_ptr<performance_manager::PerformanceManager> performance_manager_;
diff --git a/chrome/browser/policy/policy_browsertest.cc b/chrome/browser/policy/policy_browsertest.cc index 0a52c5082..c382b8f 100644 --- a/chrome/browser/policy/policy_browsertest.cc +++ b/chrome/browser/policy/policy_browsertest.cc
@@ -770,10 +770,6 @@ } }; -bool AreCommittedInterstitialsEnabled() { - return base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials); -} - } // namespace class PolicyTest : public InProcessBrowserTest { @@ -801,6 +797,12 @@ } } + void SetUpCommandLine(base::CommandLine* command_line) override { + variations::testing::VariationParamsManager::AppendVariationParams( + "ReportCertificateErrors", "ShowAndPossiblySend", + {{"sendingThreshold", "1.0"}}, command_line); + } + void SetScreenshotPolicy(bool enabled) { PolicyMap policies; policies.Set(key::kDisableScreenshots, POLICY_LEVEL_MANDATORY, @@ -1102,61 +1104,20 @@ return xhr_result && execute_result; } - MockConfigurationPolicyProvider provider_; - std::unique_ptr<extensions::ExtensionCacheFake> test_extension_cache_; - extensions::ScopedIgnoreContentVerifierForTest ignore_content_verifier_; - extensions::ExtensionUpdater::ScopedSkipScheduledCheckForTest - skip_scheduled_extension_checks_; -}; - -// A subclass of PolicyTest that runs each test with the old interstitial code -// path and the new one, called committed interstitials. -// TODO(https://crbug.com/448486): This can be removed after committed -// interstitials are launched. -class SSLPolicyTestCommittedInterstitials - : public PolicyTest, - public testing::WithParamInterface<bool> { - public: - SSLPolicyTestCommittedInterstitials() {} - - void SetUpCommandLine(base::CommandLine* command_line) override { - PolicyTest::SetUpCommandLine(command_line); - if (GetParam()) { - scoped_feature_list_.InitAndEnableFeature( - features::kSSLCommittedInterstitials); - } - // Ensure SSL interstitials are capable of sending reports. - variations::testing::VariationParamsManager::AppendVariationParams( - "ReportCertificateErrors", "ShowAndPossiblySend", - {{"sendingThreshold", "1.0"}}, command_line); - } - - protected: bool IsShowingInterstitial(content::WebContents* tab) { - if (AreCommittedInterstitialsEnabled()) { - security_interstitials::SecurityInterstitialTabHelper* helper = - security_interstitials::SecurityInterstitialTabHelper:: - FromWebContents(tab); - if (!helper) { - return false; - } - return helper - ->GetBlockingPageForCurrentlyCommittedNavigationForTesting() != - nullptr; + security_interstitials::SecurityInterstitialTabHelper* helper = + security_interstitials::SecurityInterstitialTabHelper::FromWebContents( + tab); + if (!helper) { + return false; } - return tab->GetInterstitialPage() != nullptr; + return helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting() != + nullptr; } void WaitForInterstitial(content::WebContents* tab) { - if (!AreCommittedInterstitialsEnabled()) { - content::WaitForInterstitialAttach(tab); - ASSERT_TRUE(IsShowingInterstitial(tab)); - ASSERT_TRUE( - WaitForRenderFrameReady(tab->GetInterstitialPage()->GetMainFrame())); - } else { - ASSERT_TRUE(IsShowingInterstitial(tab)); - ASSERT_TRUE(WaitForRenderFrameReady(tab->GetMainFrame())); - } + ASSERT_TRUE(IsShowingInterstitial(tab)); + ASSERT_TRUE(WaitForRenderFrameReady(tab->GetMainFrame())); } int IsExtendedReportingCheckboxVisibleOnInterstitial() { @@ -1178,38 +1139,29 @@ browser()->tab_strip_model()->GetActiveWebContents(); WaitForInterstitial(tab); int result = 0; - EXPECT_TRUE(content::ExecuteScriptAndExtractInt( - AreCommittedInterstitialsEnabled() - ? tab->GetMainFrame() - : tab->GetInterstitialPage()->GetMainFrame(), - command, &result)); + EXPECT_TRUE(content::ExecuteScriptAndExtractInt(tab->GetMainFrame(), + command, &result)); return result; } void SendInterstitialCommand( content::WebContents* tab, security_interstitials::SecurityInterstitialCommand command) { - if (AreCommittedInterstitialsEnabled()) { - security_interstitials::SecurityInterstitialTabHelper* helper = - security_interstitials::SecurityInterstitialTabHelper:: - FromWebContents(tab); - helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting() - ->CommandReceived(base::NumberToString(command)); - return; - } - tab->GetInterstitialPage()->GetDelegateForTesting()->CommandReceived( - base::NumberToString(command)); + security_interstitials::SecurityInterstitialTabHelper* helper = + security_interstitials::SecurityInterstitialTabHelper::FromWebContents( + tab); + helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting() + ->CommandReceived(base::NumberToString(command)); + return; } - private: - base::test::ScopedFeatureList scoped_feature_list_; - DISALLOW_COPY_AND_ASSIGN(SSLPolicyTestCommittedInterstitials); + MockConfigurationPolicyProvider provider_; + std::unique_ptr<extensions::ExtensionCacheFake> test_extension_cache_; + extensions::ScopedIgnoreContentVerifierForTest ignore_content_verifier_; + extensions::ExtensionUpdater::ScopedSkipScheduledCheckForTest + skip_scheduled_extension_checks_; }; -INSTANTIATE_TEST_SUITE_P(, - SSLPolicyTestCommittedInterstitials, - ::testing::Values(false, true)); - #if defined(OS_WIN) // This policy only exists on Windows. @@ -4774,7 +4726,7 @@ EXPECT_THAT(rejection, testing::MatchesRegex("NotFoundError: .*policy.*")); } -IN_PROC_BROWSER_TEST_P(SSLPolicyTestCommittedInterstitials, +IN_PROC_BROWSER_TEST_F(PolicyTest, CertificateTransparencyEnforcementDisabledForUrls) { net::EmbeddedTestServer https_server_ok(net::EmbeddedTestServer::TYPE_HTTPS); https_server_ok.SetSSLConfig(net::EmbeddedTestServer::CERT_OK); @@ -4793,10 +4745,7 @@ WaitForInterstitial(tab); EXPECT_TRUE(chrome_browser_interstitials::IsInterstitialDisplayingText( - AreCommittedInterstitialsEnabled() - ? tab->GetMainFrame() - : tab->GetInterstitialPage()->GetMainFrame(), - "proceed-link")); + tab->GetMainFrame(), "proceed-link")); EXPECT_NE(base::UTF8ToUTF16("OK"), browser()->tab_strip_model()->GetActiveWebContents()->GetTitle()); @@ -4857,20 +4806,13 @@ // The page should initially be blocked. content::RenderFrameHost* main_frame; - if (AreCommittedInterstitialsEnabled()) { - security_interstitials::SecurityInterstitialTabHelper* helper = - security_interstitials::SecurityInterstitialTabHelper::FromWebContents( - web_contents); - ASSERT_TRUE(helper); - ASSERT_TRUE( - helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting()); - main_frame = web_contents->GetMainFrame(); - } else { - content::InterstitialPage* interstitial = - content::InterstitialPage::GetInterstitialPage(web_contents); - ASSERT_TRUE(interstitial); - main_frame = interstitial->GetMainFrame(); - } + security_interstitials::SecurityInterstitialTabHelper* helper = + security_interstitials::SecurityInterstitialTabHelper::FromWebContents( + web_contents); + ASSERT_TRUE(helper); + ASSERT_TRUE( + helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting()); + main_frame = web_contents->GetMainFrame(); ASSERT_TRUE(content::WaitForRenderFrameReady(main_frame)); EXPECT_TRUE(chrome_browser_interstitials::IsInterstitialDisplayingText( main_frame, "proceed-link")); @@ -4896,17 +4838,7 @@ ui_test_utils::NavigateToURL(browser(), https_server_ok.GetURL("/simple.html")); - // There should be no interstitial after the page loads. - // With committed interstitials enabled, we don't have an interstitial page to - // check against, so we only check that the title is the correct one after - // navigating away. - if (!AreCommittedInterstitialsEnabled()) { - const content::InterstitialPage* interstitial = - content::InterstitialPage::GetInterstitialPage( - browser()->tab_strip_model()->GetActiveWebContents()); - ASSERT_FALSE(interstitial); - } - + // Check we are no longer in the interstitial. EXPECT_EQ(base::UTF8ToUTF16("OK"), browser()->tab_strip_model()->GetActiveWebContents()->GetTitle()); } @@ -4914,8 +4846,7 @@ // Test that when extended reporting opt-in is disabled by policy, the // opt-in checkbox does not appear on SSL blocking pages. // Note: SafeBrowsingExtendedReportingOptInAllowed policy is being deprecated. -IN_PROC_BROWSER_TEST_P(SSLPolicyTestCommittedInterstitials, - SafeBrowsingExtendedReportingOptInAllowed) { +IN_PROC_BROWSER_TEST_F(PolicyTest, SafeBrowsingExtendedReportingOptInAllowed) { net::EmbeddedTestServer https_server_expired( net::EmbeddedTestServer::TYPE_HTTPS); https_server_expired.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED); @@ -4948,8 +4879,7 @@ // Test that when extended reporting is managed by policy, the opt-in checkbox // does not appear on SSL blocking pages. -IN_PROC_BROWSER_TEST_P(SSLPolicyTestCommittedInterstitials, - SafeBrowsingExtendedReportingPolicyManaged) { +IN_PROC_BROWSER_TEST_F(PolicyTest, SafeBrowsingExtendedReportingPolicyManaged) { net::EmbeddedTestServer https_server_expired( net::EmbeddedTestServer::TYPE_HTTPS); https_server_expired.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED); @@ -4997,8 +4927,7 @@ // Test that when SSL error overriding is allowed by policy (default), the // proceed link appears on SSL blocking pages. -IN_PROC_BROWSER_TEST_P(SSLPolicyTestCommittedInterstitials, - SSLErrorOverridingAllowed) { +IN_PROC_BROWSER_TEST_F(PolicyTest, SSLErrorOverridingAllowed) { net::EmbeddedTestServer https_server_expired( net::EmbeddedTestServer::TYPE_HTTPS); https_server_expired.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED); @@ -5019,17 +4948,13 @@ // The interstitial should display the proceed link. EXPECT_TRUE(chrome_browser_interstitials::IsInterstitialDisplayingText( - AreCommittedInterstitialsEnabled() - ? tab->GetMainFrame() - : tab->GetInterstitialPage()->GetMainFrame(), - "proceed-link")); + tab->GetMainFrame(), "proceed-link")); } // Test that when SSL error overriding is disallowed by policy, the // proceed link does not appear on SSL blocking pages and users should not // be able to proceed. -IN_PROC_BROWSER_TEST_P(SSLPolicyTestCommittedInterstitials, - SSLErrorOverridingDisallowed) { +IN_PROC_BROWSER_TEST_F(PolicyTest, SSLErrorOverridingDisallowed) { net::EmbeddedTestServer https_server_expired( net::EmbeddedTestServer::TYPE_HTTPS); https_server_expired.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED); @@ -5058,10 +4983,7 @@ // The interstitial should not display the proceed link. EXPECT_FALSE(chrome_browser_interstitials::IsInterstitialDisplayingText( - AreCommittedInterstitialsEnabled() - ? tab->GetMainFrame() - : tab->GetInterstitialPage()->GetMainFrame(), - "proceed-link")); + tab->GetMainFrame(), "proceed-link")); // The interstitial should not proceed, even if the command is sent in // some other way (e.g., via the keyboard shortcut). @@ -6119,7 +6041,7 @@ #endif // defined(OS_CHROMEOS) -class NetworkTimePolicyTest : public SSLPolicyTestCommittedInterstitials { +class NetworkTimePolicyTest : public PolicyTest { public: NetworkTimePolicyTest() {} ~NetworkTimePolicyTest() override {} @@ -6157,7 +6079,7 @@ DISALLOW_COPY_AND_ASSIGN(NetworkTimePolicyTest); }; -IN_PROC_BROWSER_TEST_P(NetworkTimePolicyTest, NetworkTimeQueriesDisabled) { +IN_PROC_BROWSER_TEST_F(NetworkTimePolicyTest, NetworkTimeQueriesDisabled) { // Set a policy to disable network time queries. PolicyMap policies; policies.Set(key::kBrowserNetworkTimeQueriesEnabled, POLICY_LEVEL_MANDATORY, @@ -6194,10 +6116,6 @@ EXPECT_EQ(1u, num_requests()); } -INSTANTIATE_TEST_SUITE_P(, - NetworkTimePolicyTest, - ::testing::Values(false, true)); - #if defined(OS_CHROMEOS) class NoteTakingOnLockScreenPolicyTest : public PolicyTest {
diff --git a/chrome/browser/profiling_host/chrome_browser_main_extra_parts_profiling.cc b/chrome/browser/profiling_host/chrome_browser_main_extra_parts_profiling.cc index c38b10d..ce171dc9 100644 --- a/chrome/browser/profiling_host/chrome_browser_main_extra_parts_profiling.cc +++ b/chrome/browser/profiling_host/chrome_browser_main_extra_parts_profiling.cc
@@ -11,6 +11,7 @@ #include "chrome/common/chrome_switches.h" #include "components/heap_profiling/supervisor.h" #include "components/services/heap_profiling/public/cpp/settings.h" +#include "content/public/browser/system_connector.h" namespace { @@ -29,22 +30,19 @@ ChromeBrowserMainExtraPartsProfiling::~ChromeBrowserMainExtraPartsProfiling() = default; -void ChromeBrowserMainExtraPartsProfiling::ServiceManagerConnectionStarted( - content::ServiceManagerConnection* connection) { +void ChromeBrowserMainExtraPartsProfiling::PostCreateThreads() { heap_profiling::Supervisor::GetInstance() ->SetClientConnectionManagerConstructor(&CreateClientConnectionManager); -#if defined(ADDRESS_SANITIZER) +#if !defined(ADDRESS_SANITIZER) // Memory sanitizers are using large memory shadow to keep track of memory // state. Using memlog and memory sanitizers at the same time is slowing down // user experience, causing the browser to be barely responsive. In theory, // memlog and memory sanitizers are compatible and can run at the same time. - (void)connection; // Unused variable. -#else heap_profiling::Mode mode = heap_profiling::GetModeForStartup(); if (mode != heap_profiling::Mode::kNone) { heap_profiling::Supervisor::GetInstance()->Start( - connection, + content::GetSystemConnector(), base::BindOnce( &heap_profiling::ProfilingProcessHost::Start, base::Unretained(
diff --git a/chrome/browser/profiling_host/chrome_browser_main_extra_parts_profiling.h b/chrome/browser/profiling_host/chrome_browser_main_extra_parts_profiling.h index e3776d5a..9ebf132 100644 --- a/chrome/browser/profiling_host/chrome_browser_main_extra_parts_profiling.h +++ b/chrome/browser/profiling_host/chrome_browser_main_extra_parts_profiling.h
@@ -17,8 +17,7 @@ private: // ChromeBrowserMainExtraParts overrides. - void ServiceManagerConnectionStarted( - content::ServiceManagerConnection* connection) override; + void PostCreateThreads() override; DISALLOW_COPY_AND_ASSIGN(ChromeBrowserMainExtraPartsProfiling); };
diff --git a/chrome/browser/resources/chromeos/add_supervision/add_supervision.js b/chrome/browser/resources/chromeos/add_supervision/add_supervision.js index d2b3afa5..9c8ffde 100644 --- a/chrome/browser/resources/chromeos/add_supervision/add_supervision.js +++ b/chrome/browser/resources/chromeos/add_supervision/add_supervision.js
@@ -55,6 +55,11 @@ url.searchParams.set('platformVersion', platformVersion); url.searchParams.set('accessToken', accessToken); + // Allow guest webview content to open links in new windows. + webview.addEventListener('newwindow', function(e) { + window.open(e.targetUrl); + }); + // Block any requests to URLs other than one specified // by eventOriginFilter. webview.request.onBeforeRequest.addListener(function(details) {
diff --git a/chrome/browser/resources/chromeos/login/saml_confirm_password.html b/chrome/browser/resources/chromeos/login/saml_confirm_password.html index 54207c15..4fab28a 100644 --- a/chrome/browser/resources/chromeos/login/saml_confirm_password.html +++ b/chrome/browser/resources/chromeos/login/saml_confirm_password.html
@@ -5,13 +5,13 @@ <link rel="import" href="chrome://resources/html/polymer.html"> <link rel="import" href="chrome://resources/cr_elements/shared_style_css.html"> +<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html"> <link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html"> <link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/animations/fade-in-animation.html"> <link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/animations/fade-out-animation.html"> <link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/neon-animatable.html"> <link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/neon-animated-pages.html"> <link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/web-animations.html"> -<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html"> <!-- SAML password confirmation UI for the New Gaia flow. @@ -45,7 +45,12 @@ <link rel="stylesheet" href="gaia_card_parameters.css"> <template> - <style include="cr-shared-style"></style> + <style include="cr-shared-style"> + .cancel-button { + margin-inline-end: 0; + margin-inline-start: 8px; + } + </style> <neon-animated-pages id="animatedPages" class="fit" entry-animation="fade-in-animation" exit-animation="fade-out-animation" on-neon-animation-finish="onAnimationFinish_" selected="0"> @@ -87,12 +92,12 @@ <div slot="body" i18n-content="accountSetupCancelDialogTitle"></div> <div slot="button-container"> - <paper-button class="action-button" - i18n-content="accountSetupCancelDialogNo" on-tap="onCancelNo_"> - </paper-button> - <paper-button class="cancel-button" - i18n-content="accountSetupCancelDialogYes" on-tap="onCancelYes_"> - </paper-button> + <cr-button class="action-button" + i18n-content="accountSetupCancelDialogNo" on-click="onCancelNo_"> + </cr-button> + <cr-button class="cancel-button" + i18n-content="accountSetupCancelDialogYes" on-click="onCancelYes_"> + </cr-button> </div> </cr-dialog>
diff --git a/chrome/browser/resources/local_ntp/customize.js b/chrome/browser/resources/local_ntp/customize.js index be6258e..ef250348 100644 --- a/chrome/browser/resources/local_ntp/customize.js +++ b/chrome/browser/resources/local_ntp/customize.js
@@ -67,6 +67,13 @@ }; /** + * Array for keycodes corresponding to arrow keys. + * @type Array + * @const + */ +customize.arrowKeys = [/*Left*/ 37, /*Up*/ 38, /*Right*/ 39, /*Down*/ 40]; + +/** * Enum for HTML element ids. * @enum {string} * @const @@ -147,16 +154,6 @@ }; /** - * Enum for background sources. - * @enum {number} - * @const - */ -customize.SOURCES = { - NONE: -1, - CHROME_BACKGROUNDS: 0, -}; - -/** * Enum for background option menu entries, in the order they appear in the UI. * @enum {number} * @const @@ -193,12 +190,6 @@ */ customize.ROWS_TO_PRELOAD = 3; -/* Type of collection that is being browsed, needed in order - * to return from the image dialog. - * @type {number} - */ -customize.dialogCollectionsSource = customize.SOURCES.NONE; - /* * Called when the error notification should be shown. * @type {?Function} @@ -369,7 +360,6 @@ */ customize.closeCollectionDialog = function(menu) { menu.close(); - customize.dialogCollectionsSource = customize.SOURCES.NONE; customize.resetSelectionDialog(); }; @@ -528,10 +518,8 @@ /** * Show dialog for selecting a Chrome background. - * @param {number} collectionsSource The enum value of the source to fetch - * collection data from. */ -customize.showCollectionSelectionDialog = function(collectionsSource) { +customize.showCollectionSelectionDialog = function() { const tileContainer = configData.richerPicker ? $(customize.IDS.BACKGROUNDS_MENU) : $(customize.IDS.TILES); @@ -541,14 +529,6 @@ customize.builtTiles = true; const menu = configData.richerPicker ? $(customize.IDS.CUSTOMIZATION_MENU) : $(customize.IDS.MENU); - if (collectionsSource != customize.SOURCES.CHROME_BACKGROUNDS) { - console.log( - 'showCollectionSelectionDialog() called with invalid source=' + - collectionsSource); - return; - } - customize.dialogCollectionsSource = collectionsSource; - if (!menu.open) { menu.showModal(); } @@ -617,11 +597,7 @@ return; } tileOnClickInteraction(event); - } else if ( - event.keyCode === customize.KEYCODES.LEFT || - event.keyCode === customize.KEYCODES.UP || - event.keyCode === customize.KEYCODES.RIGHT || - event.keyCode === customize.KEYCODES.DOWN) { + } else if (customize.arrowKeys.includes(event.keyCode)) { // Handle arrow key navigation. event.preventDefault(); event.stopPropagation(); @@ -845,11 +821,7 @@ event.preventDefault(); event.stopPropagation(); tileInteraction(event.currentTarget); - } else if ( - event.keyCode === customize.KEYCODES.LEFT || - event.keyCode === customize.KEYCODES.UP || - event.keyCode === customize.KEYCODES.RIGHT || - event.keyCode === customize.KEYCODES.DOWN) { + } else if (customize.arrowKeys.includes(event.keyCode)) { // Handle arrow key navigation. event.preventDefault(); event.stopPropagation(); @@ -993,8 +965,7 @@ 'collection_type=background'; collScript.onload = function() { if (configData.richerPicker) { - customize.showCollectionSelectionDialog( - customize.SOURCES.CHROME_BACKGROUNDS); + customize.showCollectionSelectionDialog(); } }; document.body.appendChild(collScript); @@ -1176,11 +1147,7 @@ } else if (event.keyCode === customize.KEYCODES.TAB) { // If keyboard navigation is attempted, remove mouse-only mode. editDialog.classList.remove(customize.CLASSES.MOUSE_NAV); - } else if ( - event.keyCode === customize.KEYCODES.LEFT || - event.keyCode === customize.KEYCODES.UP || - event.keyCode === customize.KEYCODES.RIGHT || - event.keyCode === customize.KEYCODES.DOWN) { + } else if (customize.arrowKeys.includes(event.keyCode)) { event.preventDefault(); editDialog.classList.remove(customize.CLASSES.MOUSE_NAV); } @@ -1349,8 +1316,7 @@ $('ntp-collection-loader').onload = function() { editDialog.close(); if (typeof coll != 'undefined' && coll.length > 0) { - customize.showCollectionSelectionDialog( - customize.SOURCES.CHROME_BACKGROUNDS); + customize.showCollectionSelectionDialog(); } else { customize.handleError(collErrors); } @@ -1397,8 +1363,7 @@ customize.resetSelectionDialog(); } else { customize.resetSelectionDialog(); - customize.showCollectionSelectionDialog( - customize.dialogCollectionsSource); + customize.showCollectionSelectionDialog(); } } @@ -1418,7 +1383,7 @@ customize.richerPicker_resetImageMenu(true); } customize.resetSelectionDialog(); - customize.showCollectionSelectionDialog(customize.dialogCollectionsSource); + customize.showCollectionSelectionDialog(); }; $(customize.IDS.BACK_CIRCLE).onclick = backInteraction; $(customize.IDS.MENU_BACK_CIRCLE).onclick = backInteraction; @@ -1479,10 +1444,7 @@ // On any arrow key event in the tiles area, focus the first tile. $(customize.IDS.TILES).onkeydown = function(event) { - if (event.keyCode === customize.KEYCODES.LEFT || - event.keyCode === customize.KEYCODES.UP || - event.keyCode === customize.KEYCODES.RIGHT || - event.keyCode === customize.KEYCODES.DOWN) { + if (customize.arrowKeys.includes(event.keyCode)) { event.preventDefault(); if ($(customize.IDS.MENU) .classList.contains(customize.CLASSES.COLLECTION_DIALOG)) { @@ -1494,19 +1456,13 @@ }; $(customize.IDS.BACKGROUNDS_MENU).onkeydown = function(event) { - if (event.keyCode === customize.KEYCODES.LEFT || - event.keyCode === customize.KEYCODES.UP || - event.keyCode === customize.KEYCODES.RIGHT || - event.keyCode === customize.KEYCODES.DOWN) { + if (customize.arrowKeys.includes(event.keyCode)) { $(customize.IDS.BACKGROUNDS_UPLOAD_WRAPPER).focus(); } }; $(customize.IDS.BACKGROUNDS_IMAGE_MENU).onkeydown = function(event) { - if (event.keyCode === customize.KEYCODES.LEFT || - event.keyCode === customize.KEYCODES.UP || - event.keyCode === customize.KEYCODES.RIGHT || - event.keyCode === customize.KEYCODES.DOWN) { + if (customize.arrowKeys.includes(event.keyCode)) { $('img_tile_0').focus(); } };
diff --git a/chrome/browser/resources/settings/chromeos/os_people_page/os_people_page.html b/chrome/browser/resources/settings/chromeos/os_people_page/os_people_page.html index d556d2ab..cb3fd65 100644 --- a/chrome/browser/resources/settings/chromeos/os_people_page/os_people_page.html +++ b/chrome/browser/resources/settings/chromeos/os_people_page/os_people_page.html
@@ -15,6 +15,7 @@ <link rel="import" href="../../controls/settings_toggle_button.html"> <link rel="import" href="../../icons.html"> <link rel="import" href="../../people_page/account_manager.html"> +<link rel="import" href="../../people_page/account_manager_browser_proxy.html"> <link rel="import" href="../../people_page/change_picture.html"> <link rel="import" href="../../people_page/fingerprint_list.html"> <link rel="import" href="../../people_page/kerberos_accounts.html"> @@ -97,22 +98,24 @@ <settings-animated-pages id="pages" section="people" focus-config="[[focusConfig_]]"> <div route-path="default"> - <div id="picture-subpage-trigger" class="settings-box first two-line"> + <div class="settings-box first two-line"> <template is="dom-if" if="[[syncStatus]]"> - <div id="profile-icon" on-click="onProfileTap_" actionable + <div id="profile-icon" on-click="onProfileIconTap_" actionable style="background-image: [[getIconImageSet_( profileIconUrl_)]]"> </div> - <div class="middle two-line no-min-width" on-click="onProfileTap_" + <div class="middle two-line no-min-width" + on-click="onAccountManagerTap_" actionable> <div class="flex text-elide settings-box-text"> <span id="profile-name">[[profileName_]]</span> - <div class="secondary" hidden="[[!syncStatus.signedIn]]"> - [[syncStatus.signedInUsername]] + <div id="profile-label" class="secondary"> + [[profileLabel_]] </div> </div> <cr-icon-button class="subpage-arrow" - aria-label="$i18n{changePictureTitle}" + id="account-manager-subpage-trigger" + aria-label="$i18n{accountManagerSubMenuLabel}" aria-describedby="profile-name"></cr-icon-button> </div> </template> @@ -164,12 +167,6 @@ sub-label="[[getPasswordState_(hasPin, prefs.settings.enable_screen_lock.value)]]"></cr-link-row> - <template is="dom-if" if="[[isAccountManagerEnabled_]]"> - <cr-link-row id="account-manager-subpage-trigger" class="hr" - on-click="onAccountManagerTap_" - label="$i18n{accountManagerSubMenuLabel}"></cr-link-row> - </template> - <template is="dom-if" if="[[isKerberosEnabled_]]"> <cr-link-row id="kerberos-accounts-subpage-trigger" class="hr" on-click="onKerberosAccountsTap_" @@ -237,19 +234,17 @@ </template> <template is="dom-if" route-path="/changePicture"> <settings-subpage - associated-control="[[$$('#picture-subpage-trigger')]]" + associated-control="[[$$('#profile-icon')]]" page-title="$i18n{changePictureTitle}"> <settings-change-picture></settings-change-picture> </settings-subpage> </template> - <template is="dom-if" if="[[isAccountManagerEnabled_]]"> - <template is="dom-if" route-path="/accountManager"> - <settings-subpage - associated-control="[[$$('#account-manager-subpage-trigger')]]" - page-title="$i18n{accountManagerPageTitle}"> - <settings-account-manager></settings-account-manager> - </settings-subpage> - </template> + <template is="dom-if" route-path="/accountManager"> + <settings-subpage + associated-control="[[$$('#account-manager-subpage-trigger')]]" + page-title="$i18n{accountManagerPageTitle}"> + <settings-account-manager></settings-account-manager> + </settings-subpage> </template> <template is="dom-if" if="[[isKerberosEnabled_]]"> <template is="dom-if" route-path="/kerberosAccounts">
diff --git a/chrome/browser/resources/settings/chromeos/os_people_page/os_people_page.js b/chrome/browser/resources/settings/chromeos/os_people_page/os_people_page.js index a115e9c..4b01d1f 100644 --- a/chrome/browser/resources/settings/chromeos/os_people_page/os_people_page.js +++ b/chrome/browser/resources/settings/chromeos/os_people_page/os_people_page.js
@@ -74,6 +74,9 @@ profileName_: String, /** @private */ + profileLabel_: String, + + /** @private */ showSignoutDialog_: Boolean, /** @@ -125,9 +128,7 @@ '#sync-status .subpage-arrow'); } if (settings.routes.CHANGE_PICTURE) { - map.set( - settings.routes.CHANGE_PICTURE.path, - '#picture-subpage-trigger .subpage-arrow'); + map.set(settings.routes.CHANGE_PICTURE.path, '#profile-icon'); } if (settings.routes.LOCK_SCREEN) { map.set( @@ -156,6 +157,9 @@ /** @private {?settings.SyncBrowserProxy} */ syncBrowserProxy_: null, + /** @private {?settings.AccountManagerBrowserProxy} */ + accountManagerBrowserProxy_: null, + /** @override */ attached: function() { const profileInfoProxy = settings.ProfileInfoBrowserProxyImpl.getInstance(); @@ -168,6 +172,12 @@ this.handleSyncStatus_.bind(this)); this.addWebUIListener( 'sync-status-changed', this.handleSyncStatus_.bind(this)); + + this.accountManagerBrowserProxy_ = + settings.AccountManagerBrowserProxyImpl.getInstance(); + this.addWebUIListener( + 'accounts-changed', this.updateProfileLabel_.bind(this)); + this.updateProfileLabel_(); }, /** @protected */ @@ -216,6 +226,30 @@ }, /** + * Updates the label underneath the primary profile name. + * @private + */ + updateProfileLabel_: async function() { + const includeImages = false; + const /** @type {!Array<settings.Account>} */ accounts = + await this.accountManagerBrowserProxy_.getAccounts(includeImages); + // The user might not have any GAIA accounts. + if (accounts.length == 0) { + this.profileLabel_ = ''; + return; + } + const moreAccounts = accounts.length - 1; + // Template: "$1, +$2 more accounts" with correct plural of "account". + // Localization handles the case of 0 more accounts. + const labelTemplate = await cr.sendWithPromise( + 'getPluralString', 'profileLabel', moreAccounts); + + // Final output: "alice@gmail.com, +2 more accounts" + this.profileLabel_ = loadTimeData.substituteString( + labelTemplate, accounts[0].email, moreAccounts); + }, + + /** * Handler for when the sync state is pushed from the browser. * @param {?settings.SyncStatus} syncStatus * @private @@ -225,7 +259,7 @@ }, /** @private */ - onProfileTap_: function() { + onProfileIconTap_: function() { settings.navigateTo(settings.routes.CHANGE_PICTURE); },
diff --git a/chrome/browser/resources/settings/internet_page/BUILD.gn b/chrome/browser/resources/settings/internet_page/BUILD.gn index 02cd35a..29c26dab 100644 --- a/chrome/browser/resources/settings/internet_page/BUILD.gn +++ b/chrome/browser/resources/settings/internet_page/BUILD.gn
@@ -25,11 +25,14 @@ ":internet_page_browser_proxy", "..:route", "../settings_page:settings_animated_pages", + "//chromeos/services/network_config/public/mojom:mojom_js_library_for_compile", + "//ui/webui/resources/cr_components/chromeos/network:mojo_interface_provider", "//ui/webui/resources/cr_elements/chromeos/network:cr_network_listener_behavior", "//ui/webui/resources/cr_elements/chromeos/network:cr_onc_types", "//ui/webui/resources/js:assert", "//ui/webui/resources/js:i18n_behavior", "//ui/webui/resources/js:web_ui_listener_behavior", + "//ui/webui/resources/js/chromeos:onc_mojo", ] externs_list = [ "$externs_path/chrome_send.js",
diff --git a/chrome/browser/resources/settings/internet_page/internet_page.html b/chrome/browser/resources/settings/internet_page/internet_page.html index 14ba902..59e490d 100644 --- a/chrome/browser/resources/settings/internet_page/internet_page.html +++ b/chrome/browser/resources/settings/internet_page/internet_page.html
@@ -1,10 +1,12 @@ <link rel="import" href="chrome://resources/html/polymer.html"> +<link rel="import" href="chrome://resources/cr_components/chromeos/network/mojo_interface_provider.html"> <link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_network_listener_behavior.html"> <link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_onc_types.html"> <link rel="import" href="chrome://resources/cr_elements/cr_expand_button/cr_expand_button.html"> <link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html"> <link rel="import" href="chrome://resources/cr_elements/icons.html"> +<link rel="import" href="chrome://resources/html/chromeos/onc_mojo.html"> <link rel="import" href="chrome://resources/html/i18n_behavior.html"> <link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html"> <link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
diff --git a/chrome/browser/resources/settings/internet_page/internet_page.js b/chrome/browser/resources/settings/internet_page/internet_page.js index bbe365e..6191e38 100644 --- a/chrome/browser/resources/settings/internet_page/internet_page.js +++ b/chrome/browser/resources/settings/internet_page/internet_page.js
@@ -174,12 +174,23 @@ /** @private {Function} */ onExtensionDisabledListener_: null, - /** @private {settings.InternetPageBrowserProxy} */ + /** @private {?settings.InternetPageBrowserProxy} */ browserProxy_: null, + /** + * This UI will use both the networkingPrivate extension API and the + * networkConfig mojo API until we provide all of the required functionality + * in networkConfig. TODO(stevenjb): Remove use of networkingPrivate api. + * @private {?chromeos.networkConfig.mojom.CrosNetworkConfigProxy} + */ + networkConfigProxy_: null, + /** @override */ created: function() { this.browserProxy_ = settings.InternetPageBrowserProxyImpl.getInstance(); + this.networkConfigProxy_ = + network_config.MojoInterfaceProviderImpl.getInstance() + .getMojoServiceProxy(); }, /** @override */ @@ -295,11 +306,9 @@ * @private */ onDeviceEnabledToggled_: function(event) { - if (event.detail.enabled) { - this.networkingPrivate.enableNetworkType(event.detail.type); - } else { - this.networkingPrivate.disableNetworkType(event.detail.type); - } + this.networkConfigProxy_.setNetworkTypeEnabledState( + OncMojo.getNetworkTypeFromString(event.detail.type), + event.detail.enabled); }, /** @@ -595,8 +604,7 @@ * @return {string} */ getAddThirdPartyVpnLabel_: function(provider) { - return this.i18n( - 'internetAddThirdPartyVPN', provider.ProviderName || ''); + return this.i18n('internetAddThirdPartyVPN', provider.ProviderName || ''); }, /**
diff --git a/chrome/browser/resources/settings/people_page/account_manager.js b/chrome/browser/resources/settings/people_page/account_manager.js index 8613c12..c4364f4e 100644 --- a/chrome/browser/resources/settings/people_page/account_manager.js +++ b/chrome/browser/resources/settings/people_page/account_manager.js
@@ -169,7 +169,8 @@ * @private */ refreshAccounts_: function() { - this.browserProxy_.getAccounts().then(accounts => { + const includeImages = true; + this.browserProxy_.getAccounts(includeImages).then(accounts => { this.set('accounts_', accounts); }); },
diff --git a/chrome/browser/resources/settings/people_page/account_manager_browser_proxy.js b/chrome/browser/resources/settings/people_page/account_manager_browser_proxy.js index b08b022..87826f7 100644 --- a/chrome/browser/resources/settings/people_page/account_manager_browser_proxy.js +++ b/chrome/browser/resources/settings/people_page/account_manager_browser_proxy.js
@@ -19,7 +19,7 @@ * unmigrated: boolean, * fullName: string, * email: string, - * pic: string, + * pic: (string|undefined), * organization: (string|undefined), * }} */ @@ -30,9 +30,11 @@ class AccountManagerBrowserProxy { /** * Returns a Promise for the list of GAIA accounts held in AccountManager. + * @param {boolean} includeImages Include the profile icon images in + * settings.Account.pic field, which increases IPC data from the browser. * @return {!Promise<!Array<settings.Account>>} */ - getAccounts() {} + getAccounts(includeImages) {} /** * Triggers the 'Add account' flow. @@ -70,8 +72,8 @@ */ class AccountManagerBrowserProxyImpl { /** @override */ - getAccounts() { - return cr.sendWithPromise('getAccounts'); + getAccounts(includeImages) { + return cr.sendWithPromise('getAccounts', includeImages); } /** @override */
diff --git a/chrome/browser/resources/settings/printing_page/cups_printer_shared_css.html b/chrome/browser/resources/settings/printing_page/cups_printer_shared_css.html index ab77ce6..bee85419 100644 --- a/chrome/browser/resources/settings/printing_page/cups_printer_shared_css.html +++ b/chrome/browser/resources/settings/printing_page/cups_printer_shared_css.html
@@ -13,8 +13,8 @@ margin-bottom: 10px; } - [slot='dialog-body'] .settings-box .two-line { - min-height: 72px; + [slot='dialog-body'] .settings-box.two-line { + align-items: flex-start; } [slot='dialog-body'] .settings-box .start .label {
diff --git a/chrome/browser/resources/settings/route.js b/chrome/browser/resources/settings/route.js index 35d3786..ba363d6 100644 --- a/chrome/browser/resources/settings/route.js +++ b/chrome/browser/resources/settings/route.js
@@ -308,10 +308,11 @@ r.CROSTINI = r.BASIC.createSection('/crostini', 'crostini'); r.CROSTINI_DETAILS = r.CROSTINI.createChild('/crostini/details'); r.CROSTINI_EXPORT_IMPORT = - r.CROSTINI.createChild('/crostini/exportImport'); - r.CROSTINI_SHARED_PATHS = r.CROSTINI.createChild('/crostini/sharedPaths'); + r.CROSTINI_DETAILS.createChild('/crostini/exportImport'); + r.CROSTINI_SHARED_PATHS = + r.CROSTINI_DETAILS.createChild('/crostini/sharedPaths'); r.CROSTINI_SHARED_USB_DEVICES = - r.CROSTINI.createChild('/crostini/sharedUsbDevices'); + r.CROSTINI_DETAILS.createChild('/crostini/sharedUsbDevices'); } if (loadTimeData.valueExists('showPluginVm') &&
diff --git a/chrome/browser/safe_browsing/certificate_reporting_service_browsertest.cc b/chrome/browser/safe_browsing/certificate_reporting_service_browsertest.cc index 78374521..8cf2fc5d 100644 --- a/chrome/browser/safe_browsing/certificate_reporting_service_browsertest.cc +++ b/chrome/browser/safe_browsing/certificate_reporting_service_browsertest.cc
@@ -49,10 +49,6 @@ const char* kFailedReportHistogram = "SSL.CertificateErrorReportFailure"; -bool AreCommittedInterstitialsEnabled() { - return base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials); -} - } // namespace namespace safe_browsing { @@ -65,9 +61,7 @@ // - If a report is expected to hang, the test waits for the corresponding URL // request job to be created. Only after resuming the hung request job the // test waits for the request to be destroyed. -class CertificateReportingServiceBrowserTest - : public InProcessBrowserTest, - public testing::WithParamInterface<bool> { +class CertificateReportingServiceBrowserTest : public InProcessBrowserTest { public: CertificateReportingServiceBrowserTest() : https_server_(net::EmbeddedTestServer::TYPE_HTTPS) { @@ -122,10 +116,6 @@ variations::testing::VariationParamsManager::AppendVariationParams( "ReportCertificateErrors", "ShowAndPossiblySend", {{"sendingThreshold", "1.0"}}, command_line); - if (GetParam()) { - scoped_feature_list_.InitAndEnableFeature( - features::kSSLCommittedInterstitials); - } } CertificateReportingServiceTestHelper* test_helper() { @@ -160,18 +150,10 @@ url::SchemeHostPort("https", hostname, https_server_.port()).GetURL()); // Navigate to the page with SSL error. - TabStripModel* tab_strip_model = browser()->tab_strip_model(); - content::WebContents* contents = tab_strip_model->GetActiveWebContents(); ui_test_utils::NavigateToURL(browser(), kCertErrorURL); - // When committed interstitials are enabled, no interstitial attaches; once - // a navigation commits, the error page is present. - if (!AreCommittedInterstitialsEnabled()) - content::WaitForInterstitialAttach(contents); // Navigate away from the interstitial to trigger report upload. ui_test_utils::NavigateToURL(browser(), GURL("about:blank")); - if (!AreCommittedInterstitialsEnabled()) - content::WaitForInterstitialDetach(contents); } void SendPendingReports() { @@ -252,13 +234,9 @@ DISALLOW_COPY_AND_ASSIGN(CertificateReportingServiceBrowserTest); }; -INSTANTIATE_TEST_SUITE_P(, - CertificateReportingServiceBrowserTest, - ::testing::Values(false, true)); - // Tests that report send attempt should be cancelled when extended // reporting is not opted in. -IN_PROC_BROWSER_TEST_P(CertificateReportingServiceBrowserTest, +IN_PROC_BROWSER_TEST_F(CertificateReportingServiceBrowserTest, NotOptedIn_ShouldNotSendReports) { SetExpectedHistogramCountOnTeardown(0); @@ -275,7 +253,7 @@ // Tests that report send attempts are not cancelled when extended reporting is // opted in. Goes to an interstitial page and navigates away to force a report // send event. -IN_PROC_BROWSER_TEST_P(CertificateReportingServiceBrowserTest, +IN_PROC_BROWSER_TEST_F(CertificateReportingServiceBrowserTest, OptedIn_ShouldSendSuccessfulReport) { SetExpectedHistogramCountOnTeardown(0); @@ -299,7 +277,7 @@ // Tests that report send attempts are not cancelled when extended reporting is // opted in. Goes to an interstitial page and navigate away to force a report // send event. Repeats this three times and checks expected number of reports. -IN_PROC_BROWSER_TEST_P(CertificateReportingServiceBrowserTest, +IN_PROC_BROWSER_TEST_F(CertificateReportingServiceBrowserTest, OptedIn_ShouldQueueFailedReport) { SetExpectedHistogramCountOnTeardown(2); @@ -348,7 +326,7 @@ // Opting in then opting out of extended reporting should clear the pending // report queue. -IN_PROC_BROWSER_TEST_P(CertificateReportingServiceBrowserTest, +IN_PROC_BROWSER_TEST_F(CertificateReportingServiceBrowserTest, OptedIn_ThenOptedOut) { SetExpectedHistogramCountOnTeardown(1); @@ -376,7 +354,7 @@ } // Opting out, then in, then out of extended reporting should work as expected. -IN_PROC_BROWSER_TEST_P(CertificateReportingServiceBrowserTest, +IN_PROC_BROWSER_TEST_F(CertificateReportingServiceBrowserTest, OptedOut_ThenOptedIn_ThenOptedOut) { SetExpectedHistogramCountOnTeardown(1); @@ -421,7 +399,7 @@ // Disabling SafeBrowsing should clear pending reports queue in // CertificateReportingService. -IN_PROC_BROWSER_TEST_P(CertificateReportingServiceBrowserTest, +IN_PROC_BROWSER_TEST_F(CertificateReportingServiceBrowserTest, DisableSafebrowsing) { SetExpectedHistogramCountOnTeardown(2); @@ -465,7 +443,7 @@ } // CertificateReportingService should ignore reports older than the report TTL. -IN_PROC_BROWSER_TEST_P(CertificateReportingServiceBrowserTest, +IN_PROC_BROWSER_TEST_F(CertificateReportingServiceBrowserTest, DontSendOldReports) { SetExpectedHistogramCountOnTeardown(5); @@ -548,7 +526,7 @@ // CertificateReportingService should drop old reports from its pending report // queue, if the queue is full. -IN_PROC_BROWSER_TEST_P(CertificateReportingServiceBrowserTest, +IN_PROC_BROWSER_TEST_F(CertificateReportingServiceBrowserTest, DropOldReportsFromQueue) { SetExpectedHistogramCountOnTeardown(7); @@ -629,7 +607,7 @@ 9 /* submitted */, 7 /* failed */, 2 /* successful */, 2 /* dropped */); } -IN_PROC_BROWSER_TEST_P(CertificateReportingServiceBrowserTest, +IN_PROC_BROWSER_TEST_F(CertificateReportingServiceBrowserTest, Delayed_Resumed) { SetExpectedHistogramCountOnTeardown(0); @@ -660,7 +638,7 @@ // Same as above, but the service is shut down before resuming the delayed // request. Should not crash. -IN_PROC_BROWSER_TEST_P(CertificateReportingServiceBrowserTest, +IN_PROC_BROWSER_TEST_F(CertificateReportingServiceBrowserTest, Delayed_Resumed_ServiceShutdown) { SetExpectedHistogramCountOnTeardown(0); @@ -688,7 +666,7 @@ // Trigger a delayed report, then disable Safebrowsing. Certificate reporting // service should clear its in-flight reports list. -IN_PROC_BROWSER_TEST_P(CertificateReportingServiceBrowserTest, Delayed_Reset) { +IN_PROC_BROWSER_TEST_F(CertificateReportingServiceBrowserTest, Delayed_Reset) { SetExpectedHistogramCountOnTeardown(0); certificate_reporting_test_utils::SetCertReportingOptIn(
diff --git a/chrome/browser/safe_browsing/download_protection/two_phase_uploader_unittest.cc b/chrome/browser/safe_browsing/download_protection/two_phase_uploader_unittest.cc index 56d23e4..9ce8251 100644 --- a/chrome/browser/safe_browsing/download_protection/two_phase_uploader_unittest.cc +++ b/chrome/browser/safe_browsing/download_protection/two_phase_uploader_unittest.cc
@@ -71,17 +71,21 @@ public: TwoPhaseUploaderTest() : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) { + // Make sure the Network Service is started before making a NetworkContext. + content::GetNetworkService(); + content::RunAllPendingInMessageLoop(content::BrowserThread::IO); + // A NetworkServiceClient is needed for uploads to work. network::mojom::NetworkServiceClientPtr network_service_client_ptr; network_service_client_ = std::make_unique<network::TestNetworkServiceClient>( mojo::MakeRequest(&network_service_client_ptr)); - network::NetworkService* network_service = content::GetNetworkServiceImpl(); - network_service->SetClient(std::move(network_service_client_ptr), - network::mojom::NetworkServiceParams::New()); + network::NetworkService::GetNetworkServiceForTesting()->SetClient( + std::move(network_service_client_ptr), + network::mojom::NetworkServiceParams::New()); shared_url_loader_factory_ = base::MakeRefCounted<network::TestSharedURLLoaderFactory>( - network_service); + network::NetworkService::GetNetworkServiceForTesting()); } protected:
diff --git a/chrome/browser/safe_browsing/safe_browsing_blocking_page_test.cc b/chrome/browser/safe_browsing/safe_browsing_blocking_page_test.cc index 62bc440..cf7aa30 100644 --- a/chrome/browser/safe_browsing/safe_browsing_blocking_page_test.cc +++ b/chrome/browser/safe_browsing/safe_browsing_blocking_page_test.cc
@@ -461,50 +461,32 @@ // Proceed through the HTTPS interstitial. ui_test_utils::NavigateToURL(browser(), url); - // TODO(carlosil, crbug.com/448486): This function is overly complicated - // due to the need to support combinations of safe browsing and SSL - // interstitials being committed navigations or overlays. Since most SSL - // specific code is only used in this function, it is stuck here for now. - // Once both SSL and SB committed interstitials launch, this function can - // use the general case interstitial code, and should be cleaned up. content::WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents(); content::InterstitialPageDelegate* ssl_blocking_page; - if (base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials)) { - EXPECT_TRUE(WaitForRenderFrameReady(contents->GetMainFrame())); - security_interstitials::SecurityInterstitialTabHelper* helper = - security_interstitials::SecurityInterstitialTabHelper:: - FromWebContents(contents); - EXPECT_TRUE(helper); - ssl_blocking_page = - helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting(); - } else { - EXPECT_TRUE(WaitForReady(browser())); - ssl_blocking_page = browser() - ->tab_strip_model() - ->GetActiveWebContents() - ->GetInterstitialPage() - ->GetDelegateForTesting(); - } + EXPECT_TRUE(WaitForRenderFrameReady(contents->GetMainFrame())); + security_interstitials::SecurityInterstitialTabHelper* helper = + security_interstitials::SecurityInterstitialTabHelper::FromWebContents( + contents); + EXPECT_TRUE(helper); + ssl_blocking_page = + helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting(); + EXPECT_EQ(SSLBlockingPage::kTypeForTesting, ssl_blocking_page->GetTypeForTesting()); content::TestNavigationObserver observer( browser()->tab_strip_model()->GetActiveWebContents()); ssl_blocking_page->CommandReceived(base::NumberToString( security_interstitials::SecurityInterstitialCommand::CMD_PROCEED)); - if (base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials)) { - if (AreCommittedMainFrameInterstitialsEnabled()) { - // When both SB and SSL interstitials are committed navigations, we need - // to wait for two navigations here, one is from the SSL interstitial to - // the blocked site (which does not complete since SB blocks it) and the - // second one is to the actual SB interstitial. - observer.WaitForNavigationFinished(); - } else { - EXPECT_TRUE(WaitForRenderFrameReady(contents->GetMainFrame())); - } + if (AreCommittedMainFrameInterstitialsEnabled()) { + // When both SB and SSL interstitials are committed navigations, we need + // to wait for two navigations here, one is from the SSL interstitial to + // the blocked site (which does not complete since SB blocks it) and the + // second one is to the actual SB interstitial. + observer.WaitForNavigationFinished(); } else { - content::WaitForInterstitialDetach(contents); + EXPECT_TRUE(WaitForRenderFrameReady(contents->GetMainFrame())); } return SetupWarningAndNavigateToURL(url, browser());
diff --git a/chrome/browser/send_tab_to_self/send_tab_to_self_util.cc b/chrome/browser/send_tab_to_self/send_tab_to_self_util.cc index 6700e6b..4424c63 100644 --- a/chrome/browser/send_tab_to_self/send_tab_to_self_util.cc +++ b/chrome/browser/send_tab_to_self/send_tab_to_self_util.cc
@@ -42,12 +42,11 @@ service->GetSendTabToSelfModel()->IsReady(); } -bool IsSyncingOnMultipleDevices(Profile* profile) { - syncer::DeviceInfoSyncService* device_sync_service = - DeviceInfoSyncServiceFactory::GetForProfile(profile); - - return device_sync_service && device_sync_service->GetDeviceInfoTracker() && - device_sync_service->GetDeviceInfoTracker()->CountActiveDevices() > 1; +bool HasValidTargetDevice(Profile* profile) { + SendTabToSelfSyncService* service = + SendTabToSelfSyncServiceFactory::GetForProfile(profile); + return service && service->GetSendTabToSelfModel() && + service->GetSendTabToSelfModel()->HasValidTargetDevice(); } bool IsContentRequirementsMet(const GURL& url, Profile* profile) { @@ -66,7 +65,7 @@ // If sending is enabled, then so is receiving. return IsSendingEnabled() && IsUserSyncTypeActive(profile) && - IsSyncingOnMultipleDevices(profile) && + HasValidTargetDevice(profile) && IsContentRequirementsMet(web_contents->GetURL(), profile); } @@ -77,7 +76,7 @@ Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); return IsSendingEnabled() && IsUserSyncTypeActive(profile) && - IsSyncingOnMultipleDevices(profile) && + HasValidTargetDevice(profile) && (IsContentRequirementsMet(web_contents->GetURL(), profile) || IsContentRequirementsMet(link_url, profile)); }
diff --git a/chrome/browser/send_tab_to_self/send_tab_to_self_util.h b/chrome/browser/send_tab_to_self/send_tab_to_self_util.h index 80f5c769..fcdf580 100644 --- a/chrome/browser/send_tab_to_self/send_tab_to_self_util.h +++ b/chrome/browser/send_tab_to_self/send_tab_to_self_util.h
@@ -24,8 +24,8 @@ // Returns true if the SendTabToSelf sync datatype is active. bool IsUserSyncTypeActive(Profile* profile); -// Returns true if the user syncing on two or more devices. -bool IsSyncingOnMultipleDevices(Profile* profile); +// Returns true if the user has one or more valid device to share to. +bool HasValidTargetDevice(Profile* profile); // Returns true if the tab and web content requirements are met: // User is viewing an HTTP or HTTPS page.
diff --git a/chrome/browser/send_tab_to_self/send_tab_to_self_util_unittest.cc b/chrome/browser/send_tab_to_self/send_tab_to_self_util_unittest.cc index cf147eec..891d033 100644 --- a/chrome/browser/send_tab_to_self/send_tab_to_self_util_unittest.cc +++ b/chrome/browser/send_tab_to_self/send_tab_to_self_util_unittest.cc
@@ -12,18 +12,13 @@ #include "base/bind.h" #include "base/strings/utf_string_conversions.h" #include "base/test/scoped_feature_list.h" -#include "chrome/browser/sync/device_info_sync_service_factory.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/sync/send_tab_to_self_sync_service_factory.h" #include "chrome/test/base/browser_with_test_window_test.h" #include "components/send_tab_to_self/features.h" #include "components/send_tab_to_self/send_tab_to_self_sync_service.h" +#include "components/send_tab_to_self/test_send_tab_to_self_model.h" #include "components/sync/driver/sync_driver_switches.h" -#include "components/sync/driver/test_sync_service.h" -#include "components/sync_device_info/device_info.h" -#include "components/sync_device_info/device_info_sync_bridge.h" -#include "components/sync_device_info/device_info_sync_service.h" -#include "content/public/browser/navigation_entry.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" @@ -32,69 +27,31 @@ namespace { -// Mock DeviceInfoTracker class for setting active devices -class TestDeviceInfoTracker : public syncer::DeviceInfoTracker { +class SendTabToSelfModelMock : public TestSendTabToSelfModel { public: - TestDeviceInfoTracker() = default; - ~TestDeviceInfoTracker() override = default; + SendTabToSelfModelMock() = default; + ~SendTabToSelfModelMock() override = default; - void SetActiveDevices(int devices) { active_devices_ = devices; } - - // DeviceInfoTracker implementation - bool IsSyncing() const override { return false; } - std::unique_ptr<syncer::DeviceInfo> GetDeviceInfo( - const std::string& client_id) const override { - return std::unique_ptr<syncer::DeviceInfo>(); - } - std::vector<std::unique_ptr<syncer::DeviceInfo>> GetAllDeviceInfo() - const override { - return std::vector<std::unique_ptr<syncer::DeviceInfo>>(); - } - void AddObserver(Observer* observer) override {} - void RemoveObserver(Observer* observer) override {} - int CountActiveDevices() const override { return active_devices_; } - - void ForcePulseForTest() override {} - - protected: - int active_devices_; + bool IsReady() override { return true; } + bool HasValidTargetDevice() override { return true; } }; -// Mock DeviceInfoSyncService to host mocked DeviceInfoTracker -class TestDeviceInfoSyncService : public syncer::DeviceInfoSyncService { +class TestSendTabToSelfSyncService : public SendTabToSelfSyncService { public: - TestDeviceInfoSyncService() = default; - ~TestDeviceInfoSyncService() override = default; + TestSendTabToSelfSyncService() = default; + ~TestSendTabToSelfSyncService() override = default; - TestDeviceInfoTracker* GetMockDeviceInfoTracker() { return &tracker_; } - void SetTrackerActiveDevices(int devices) { - tracker_.SetActiveDevices(devices); - } - - // DeviceInfoSyncService implementation - syncer::LocalDeviceInfoProvider* GetLocalDeviceInfoProvider() override { - return nullptr; - } - syncer::DeviceInfoTracker* GetDeviceInfoTracker() override { - return &tracker_; - } - base::WeakPtr<syncer::ModelTypeControllerDelegate> GetControllerDelegate() - override { - return nullptr; + SendTabToSelfModel* GetSendTabToSelfModel() override { + return &send_tab_to_self_model_mock_; } protected: - TestDeviceInfoTracker tracker_; + SendTabToSelfModelMock send_tab_to_self_model_mock_; }; -std::unique_ptr<KeyedService> BuildMockDeviceInfoSyncService( +std::unique_ptr<KeyedService> BuildTestSendTabToSelfSyncService( content::BrowserContext* context) { - return std::make_unique<TestDeviceInfoSyncService>(); -} - -std::unique_ptr<KeyedService> BuildTestSyncService( - content::BrowserContext* context) { - return std::make_unique<syncer::TestSyncService>(); + return std::make_unique<TestSendTabToSelfSyncService>(); } class SendTabToSelfUtilTest : public BrowserWithTestWindowTest { @@ -104,49 +61,12 @@ void SetUp() override { BrowserWithTestWindowTest::SetUp(); - - test_sync_service_ = static_cast<syncer::TestSyncService*>( - ProfileSyncServiceFactory::GetInstance()->SetTestingFactoryAndUse( - profile(), base::BindRepeating(&BuildTestSyncService))); - - mock_device_sync_service_ = static_cast<TestDeviceInfoSyncService*>( - DeviceInfoSyncServiceFactory::GetInstance()->SetTestingFactoryAndUse( - profile(), base::BindRepeating(&BuildMockDeviceInfoSyncService))); - incognito_profile_ = profile()->GetOffTheRecordProfile(); url_ = GURL("https://www.google.com"); title_ = base::UTF8ToUTF16(base::StringPiece("Google")); } - // Set up all test conditions to let ShouldOfferFeature() return true - void SetUpAllTrueEnv() { - scoped_feature_list_.InitWithFeatures( - {switches::kSyncSendTabToSelf, kSendTabToSelfShowSendingUI}, {}); - syncer::ModelTypeSet enabled_modeltype(syncer::SEND_TAB_TO_SELF); - test_sync_service_->SetPreferredDataTypes(enabled_modeltype); - - mock_device_sync_service_->SetTrackerActiveDevices(2); - - AddTab(browser(), url_); - NavigateAndCommitActiveTabWithTitle(browser(), url_, title_); - } - - // Set up a environment in which the feature flag is disabled - void SetUpFeatureDisabledEnv() { - scoped_feature_list_.InitWithFeatures( - {}, {switches::kSyncSendTabToSelf, kSendTabToSelfShowSendingUI}); - syncer::ModelTypeSet enabled_modeltype(syncer::SEND_TAB_TO_SELF); - test_sync_service_->SetPreferredDataTypes(enabled_modeltype); - - mock_device_sync_service_->SetTrackerActiveDevices(2); - - AddTab(browser(), url_); - NavigateAndCommitActiveTabWithTitle(browser(), url_, title_); - } - protected: - syncer::TestSyncService* test_sync_service_; - TestDeviceInfoSyncService* mock_device_sync_service_; base::test::ScopedFeatureList scoped_feature_list_; Profile* incognito_profile_; GURL url_; @@ -185,16 +105,13 @@ EXPECT_FALSE(IsReceivingEnabled()); } -TEST_F(SendTabToSelfUtilTest, IsSyncingOnMultipleDevices_True) { - mock_device_sync_service_->SetTrackerActiveDevices(2); +TEST_F(SendTabToSelfUtilTest, HasValidTargetDevice) { + EXPECT_FALSE(HasValidTargetDevice(profile())); - EXPECT_TRUE(IsSyncingOnMultipleDevices(profile())); -} + SendTabToSelfSyncServiceFactory::GetInstance()->SetTestingFactory( + profile(), base::BindRepeating(&BuildTestSendTabToSelfSyncService)); -TEST_F(SendTabToSelfUtilTest, IsSyncingOnMultipleDevices_False) { - mock_device_sync_service_->SetTrackerActiveDevices(0); - - EXPECT_FALSE(IsSyncingOnMultipleDevices(profile())); + EXPECT_TRUE(HasValidTargetDevice(profile())); } TEST_F(SendTabToSelfUtilTest, ContentRequirementsMet) {
diff --git a/chrome/browser/sessions/session_restore_browsertest.cc b/chrome/browser/sessions/session_restore_browsertest.cc index e50cb2cd0..3d9bcef0 100644 --- a/chrome/browser/sessions/session_restore_browsertest.cc +++ b/chrome/browser/sessions/session_restore_browsertest.cc
@@ -1142,16 +1142,16 @@ ui_test_utils::NavigateToURL(browser(), webui_url); content::WebContents* old_tab = browser()->tab_strip_model()->GetActiveWebContents(); - EXPECT_EQ(content::BINDINGS_POLICY_WEB_UI, - old_tab->GetMainFrame()->GetEnabledBindings()); + EXPECT_TRUE(old_tab->GetMainFrame()->GetEnabledBindings() & + content::BINDINGS_POLICY_WEB_UI); Browser* new_browser = QuitBrowserAndRestore(browser(), 1); ASSERT_EQ(1u, active_browser_list_->size()); content::WebContents* new_tab = new_browser->tab_strip_model()->GetActiveWebContents(); EXPECT_EQ(webui_url, new_tab->GetURL()); - EXPECT_EQ(content::BINDINGS_POLICY_WEB_UI, - new_tab->GetMainFrame()->GetEnabledBindings()); + EXPECT_TRUE(new_tab->GetMainFrame()->GetEnabledBindings() & + content::BINDINGS_POLICY_WEB_UI); } IN_PROC_BROWSER_TEST_F(SessionRestoreTest, RestoresForwardAndBackwardNavs) {
diff --git a/chrome/browser/site_isolation/chrome_site_per_process_browsertest.cc b/chrome/browser/site_isolation/chrome_site_per_process_browsertest.cc index 25c26062..d4894c4 100644 --- a/chrome/browser/site_isolation/chrome_site_per_process_browsertest.cc +++ b/chrome/browser/site_isolation/chrome_site_per_process_browsertest.cc
@@ -207,18 +207,7 @@ content::RenderFrameHost* interstitial_frame_host; - if (base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials)) { - interstitial_frame_host = active_web_contents->GetMainFrame(); - } else { - WaitForInterstitialAttach(active_web_contents); - EXPECT_TRUE(active_web_contents->ShowingInterstitialPage()); - - // Here we check the device scale factor in use via the interstitial's - // RenderFrameHost; doing the check directly via the 'active web contents' - // does not give us the device scale factor for the interstitial. - interstitial_frame_host = - active_web_contents->GetInterstitialPage()->GetMainFrame(); - } + interstitial_frame_host = active_web_contents->GetMainFrame(); EXPECT_EQ(SitePerProcessHighDPIExpiredCertBrowserTest::kDeviceScaleFactor, GetFrameDeviceScaleFactor(interstitial_frame_host));
diff --git a/chrome/browser/ssl/captive_portal_blocking_page_browsertest.cc b/chrome/browser/ssl/captive_portal_blocking_page_browsertest.cc index 6ac03f9..f726d1e 100644 --- a/chrome/browser/ssl/captive_portal_blocking_page_browsertest.cc +++ b/chrome/browser/ssl/captive_portal_blocking_page_browsertest.cc
@@ -73,10 +73,6 @@ EXPECT_LOGIN_URL_YES }; -bool AreCommittedInterstitialsEnabled() { - return base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials); -} - class CaptivePortalBlockingPageForTesting : public CaptivePortalBlockingPage { public: CaptivePortalBlockingPageForTesting( @@ -107,8 +103,7 @@ }; // A NavigationThrottle that observes failed requests and shows a captive portal -// interstitial, either transient or committed depending on whether committed -// interstitials are enabled. +// interstitial. class CaptivePortalTestingNavigationThrottle : public content::NavigationThrottle { public: @@ -160,28 +155,14 @@ base::Callback<void(content::CertificateRequestResultType)>(), is_wifi_connection_, wifi_ssid_); - if (AreCommittedInterstitialsEnabled()) { - std::string html = blocking_page->GetHTMLContents(); - // Hand the blocking page back to the WebContents's - // security_interstitials::SecurityInterstitialTabHelper to own. - security_interstitials::SecurityInterstitialTabHelper:: - AssociateBlockingPage( - navigation_handle()->GetWebContents(), - navigation_handle()->GetNavigationId(), - std::unique_ptr<CaptivePortalBlockingPage>(blocking_page)); - return {CANCEL, net::ERR_CERT_COMMON_NAME_INVALID, html}; - } - - // |blocking_page| is owned by the interstitial. - blocking_page->Show(); - WaitForInterstitialAttach(navigation_handle()->GetWebContents()); - EXPECT_TRUE(WaitForRenderFrameReady(navigation_handle() - ->GetWebContents() - ->GetInterstitialPage() - ->GetMainFrame())); - // When committed interstitials are disabled, defer the navigation while the - // interstitial is showing. - return DEFER; + std::string html = blocking_page->GetHTMLContents(); + // Hand the blocking page back to the WebContents's + // security_interstitials::SecurityInterstitialTabHelper to own. + security_interstitials::SecurityInterstitialTabHelper::AssociateBlockingPage( + navigation_handle()->GetWebContents(), + navigation_handle()->GetNavigationId(), + std::unique_ptr<CaptivePortalBlockingPage>(blocking_page)); + return {CANCEL, net::ERR_CERT_COMMON_NAME_INVALID, html}; } // A WebContentsObserver which installs a navigation throttle that creates @@ -233,8 +214,7 @@ } // namespace -class CaptivePortalBlockingPageTest : public InProcessBrowserTest, - public testing::WithParamInterface<bool> { +class CaptivePortalBlockingPageTest : public InProcessBrowserTest { public: CaptivePortalBlockingPageTest() { CertReportHelper::SetFakeOfficialBuildForTesting(); @@ -250,11 +230,6 @@ variations::testing::VariationParamsManager::AppendVariationParams( "ReportCertificateErrors", "ShowAndPossiblySend", {{"sendingThreshold", "1.0"}}, command_line); - - if (GetParam()) { - scoped_feature_list_.InitAndEnableFeature( - features::kSSLCommittedInterstitials); - } } void TestInterstitial(bool is_wifi_connection, @@ -289,10 +264,6 @@ DISALLOW_COPY_AND_ASSIGN(CaptivePortalBlockingPageTest); }; -INSTANTIATE_TEST_SUITE_P(, - CaptivePortalBlockingPageTest, - ::testing::Values(false, true)); - void CaptivePortalBlockingPageTest::TestInterstitial( bool is_wifi_connection, const std::string& wifi_ssid, @@ -317,13 +288,8 @@ browser(), net::URLRequestFailedJob::GetMockHttpsUrl(net::ERR_BLOCKED_BY_CLIENT)); content::RenderFrameHost* frame; - if (!AreCommittedInterstitialsEnabled()) { - ASSERT_TRUE(contents->GetInterstitialPage()); - frame = contents->GetInterstitialPage()->GetMainFrame(); - } else { - frame = contents->GetMainFrame(); - ASSERT_TRUE(WaitForRenderFrameReady(frame)); - } + frame = contents->GetMainFrame(); + ASSERT_TRUE(WaitForRenderFrameReady(frame)); EXPECT_EQ(expect_wifi == EXPECT_WIFI_YES, IsInterstitialDisplayingText(frame, "Wi-Fi")); @@ -335,19 +301,6 @@ IsInterstitialDisplayingText(frame, expected_login_hostname)); EXPECT_EQ(expect_login_url == EXPECT_LOGIN_URL_NO, IsInterstitialDisplayingText(frame, kGenericLoginURLText)); - - // Check that a red/dangerous lock icon is showing on the interstitial. This - // only occurs when committed interstitials are disabled. With committed - // interstitials enabled, the NavigationEntry's SSLStatus is updated to - // reflect a certificate error by the navigation stack, not by the blocking - // page itself, and that navigation code isn't exercised by this test. (It's - // covered by other tests in ssl_browsertest.cc). - if (!AreCommittedInterstitialsEnabled()) { - SecurityStateTabHelper* helper = - SecurityStateTabHelper::FromWebContents(contents); - ASSERT_TRUE(helper); - EXPECT_EQ(security_state::DANGEROUS, helper->GetSecurityLevel()); - } } void CaptivePortalBlockingPageTest::TestInterstitial( @@ -412,7 +365,7 @@ // If the connection is not a Wi-Fi connection, the wired network version of the // captive portal interstitial should be displayed. -IN_PROC_BROWSER_TEST_P(CaptivePortalBlockingPageTest, WiredNetwork_LoginURL) { +IN_PROC_BROWSER_TEST_F(CaptivePortalBlockingPageTest, WiredNetwork_LoginURL) { TestInterstitial(false, std::string(), GURL("http://captive.portal/landing_url"), EXPECT_WIFI_NO, EXPECT_WIFI_SSID_NO, EXPECT_LOGIN_URL_YES); @@ -420,7 +373,7 @@ // Same as above, but SSID is available, so the connection should be assumed to // be Wi-Fi. -IN_PROC_BROWSER_TEST_P(CaptivePortalBlockingPageTest, +IN_PROC_BROWSER_TEST_F(CaptivePortalBlockingPageTest, WiredNetwork_LoginURL_With_SSID) { TestInterstitial(false, kWiFiSSID, GURL("http://captive.portal/landing_url"), EXPECT_WIFI_YES, EXPECT_WIFI_SSID_YES, EXPECT_LOGIN_URL_YES); @@ -429,7 +382,7 @@ // Same as above, expect the login URL is the same as the captive portal ping // url (i.e. the portal intercepts requests without using HTTP redirects), in // which case the login URL shouldn't be displayed. -IN_PROC_BROWSER_TEST_P(CaptivePortalBlockingPageTest, WiredNetwork_NoLoginURL) { +IN_PROC_BROWSER_TEST_F(CaptivePortalBlockingPageTest, WiredNetwork_NoLoginURL) { const GURL kLandingUrl(captive_portal::CaptivePortalDetector::kDefaultURL); TestInterstitial(false, std::string(), kLandingUrl, EXPECT_WIFI_NO, EXPECT_WIFI_SSID_NO, EXPECT_LOGIN_URL_NO); @@ -437,7 +390,7 @@ // Same as above, but SSID is available, so the connection should be assumed to // be Wi-Fi. -IN_PROC_BROWSER_TEST_P(CaptivePortalBlockingPageTest, +IN_PROC_BROWSER_TEST_F(CaptivePortalBlockingPageTest, WiredNetwork_NoLoginURL_With_SSID) { const GURL kLandingUrl(captive_portal::CaptivePortalDetector::kDefaultURL); TestInterstitial(false, kWiFiSSID, kLandingUrl, EXPECT_WIFI_YES, @@ -446,7 +399,7 @@ // If the connection is a Wi-Fi connection, the Wi-Fi version of the captive // portal interstitial should be displayed. -IN_PROC_BROWSER_TEST_P(CaptivePortalBlockingPageTest, WiFi_SSID_LoginURL) { +IN_PROC_BROWSER_TEST_F(CaptivePortalBlockingPageTest, WiFi_SSID_LoginURL) { TestInterstitial(true, kWiFiSSID, GURL("http://captive.portal/landing_url"), EXPECT_WIFI_YES, EXPECT_WIFI_SSID_YES, EXPECT_LOGIN_URL_YES); } @@ -459,7 +412,7 @@ #endif // Same as above, with login URL but no SSID. -IN_PROC_BROWSER_TEST_P(CaptivePortalBlockingPageTest, +IN_PROC_BROWSER_TEST_F(CaptivePortalBlockingPageTest, MAYBE_WiFi_NoSSID_LoginURL) { TestInterstitial(true, std::string(), GURL("http://captive.portal/landing_url"), EXPECT_WIFI_YES, @@ -474,7 +427,7 @@ #endif // Same as above, with SSID but no login URL. -IN_PROC_BROWSER_TEST_P(CaptivePortalBlockingPageTest, +IN_PROC_BROWSER_TEST_F(CaptivePortalBlockingPageTest, MAYBE_WiFi_SSID_NoLoginURL) { const GURL kLandingUrl(captive_portal::CaptivePortalDetector::kDefaultURL); TestInterstitial(true, kWiFiSSID, kLandingUrl, @@ -482,18 +435,18 @@ } // Same as above, with no SSID and no login URL. -IN_PROC_BROWSER_TEST_P(CaptivePortalBlockingPageTest, WiFi_NoSSID_NoLoginURL) { +IN_PROC_BROWSER_TEST_F(CaptivePortalBlockingPageTest, WiFi_NoSSID_NoLoginURL) { const GURL kLandingUrl(captive_portal::CaptivePortalDetector::kDefaultURL); TestInterstitial(true, std::string(), kLandingUrl, EXPECT_WIFI_YES, EXPECT_WIFI_SSID_NO, EXPECT_LOGIN_URL_NO); } -IN_PROC_BROWSER_TEST_P(CaptivePortalBlockingPageTest, CertReportingOptIn) { +IN_PROC_BROWSER_TEST_F(CaptivePortalBlockingPageTest, CertReportingOptIn) { TestCertReporting( certificate_reporting_test_utils::EXTENDED_REPORTING_OPT_IN); } -IN_PROC_BROWSER_TEST_P(CaptivePortalBlockingPageTest, CertReportingOptOut) { +IN_PROC_BROWSER_TEST_F(CaptivePortalBlockingPageTest, CertReportingOptOut) { TestCertReporting( certificate_reporting_test_utils::EXTENDED_REPORTING_DO_NOT_OPT_IN); }
diff --git a/chrome/browser/ssl/connection_help_tab_helper.cc b/chrome/browser/ssl/connection_help_tab_helper.cc index 821a25c..4c15c56a 100644 --- a/chrome/browser/ssl/connection_help_tab_helper.cc +++ b/chrome/browser/ssl/connection_help_tab_helper.cc
@@ -34,17 +34,6 @@ ConnectionHelpTabHelper::~ConnectionHelpTabHelper() {} -void ConnectionHelpTabHelper::DidAttachInterstitialPage() { - if (web_contents()->GetURL().EqualsIgnoringRef(GetHelpCenterURL()) || - web_contents()->GetURL().EqualsIgnoringRef(GURL(kSymantecSupportUrl))) { - UMA_HISTOGRAM_ENUMERATION( - "SSL.CertificateErrorHelpCenterVisited", - ConnectionHelpTabHelper::LearnMoreClickResult::kFailedWithInterstitial, - ConnectionHelpTabHelper::LearnMoreClickResult::kLearnMoreResultCount); - MaybeRedirectToBundledHelp(web_contents()); - } -} - void ConnectionHelpTabHelper::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (navigation_handle->IsInMainFrame() && @@ -52,8 +41,7 @@ web_contents()->GetURL().EqualsIgnoringRef(GURL(kSymantecSupportUrl)))) { LearnMoreClickResult histogram_value; if (navigation_handle->IsErrorPage()) { - if (base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials) && - net::IsCertificateError(navigation_handle->GetNetErrorCode())) { + if (net::IsCertificateError(navigation_handle->GetNetErrorCode())) { // When committed interstitials are enabled, DidAttachInterstitialPage // does not get called, so check if this navigation resulted in an SSL // error.
diff --git a/chrome/browser/ssl/connection_help_tab_helper.h b/chrome/browser/ssl/connection_help_tab_helper.h index f433f124..3e463362 100644 --- a/chrome/browser/ssl/connection_help_tab_helper.h +++ b/chrome/browser/ssl/connection_help_tab_helper.h
@@ -35,7 +35,6 @@ ~ConnectionHelpTabHelper() override; // WebContentsObserver: - void DidAttachInterstitialPage() override; void DidFinishNavigation( content::NavigationHandle* navigation_handle) override;
diff --git a/chrome/browser/ssl/connection_help_tab_helper_browsertest.cc b/chrome/browser/ssl/connection_help_tab_helper_browsertest.cc index 7a65181..28207608a 100644 --- a/chrome/browser/ssl/connection_help_tab_helper_browsertest.cc +++ b/chrome/browser/ssl/connection_help_tab_helper_browsertest.cc
@@ -21,18 +21,13 @@ #include "ui/base/l10n/l10n_util.h" #include "url/gurl.h" -class ConnectionHelpTabHelperTest : public InProcessBrowserTest, - public testing::WithParamInterface<bool> { +class ConnectionHelpTabHelperTest : public InProcessBrowserTest { public: ConnectionHelpTabHelperTest() : https_server_(net::EmbeddedTestServer::TYPE_HTTPS), https_expired_server_(net::EmbeddedTestServer::TYPE_HTTPS) {} void SetUpOnMainThread() override { - if (GetParam()) { - scoped_feature_list_.InitAndEnableFeature( - features::kSSLCommittedInterstitials); - } https_server_.SetSSLConfig(net::EmbeddedTestServer::CERT_OK); https_expired_server_.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED); https_server_.ServeFilesFromSourceDirectory(GetChromeTestDataDir()); @@ -42,10 +37,6 @@ } protected: - bool AreCommittedInterstitialsEnabled() { - return base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials); - } - void SetHelpCenterUrl(Browser* browser, const GURL& url) { ConnectionHelpTabHelper::FromWebContents( browser->tab_strip_model()->GetActiveWebContents()) @@ -65,14 +56,10 @@ DISALLOW_COPY_AND_ASSIGN(ConnectionHelpTabHelperTest); }; -INSTANTIATE_TEST_SUITE_P(, - ConnectionHelpTabHelperTest, - ::testing::Values(false, true)); - // Tests that the chrome://connection-help redirect is not triggered (and // metrics are not logged) for an interstitial on a site that is not the help // center. -IN_PROC_BROWSER_TEST_P(ConnectionHelpTabHelperTest, +IN_PROC_BROWSER_TEST_F(ConnectionHelpTabHelperTest, InterstitialOnNonSupportURL) { const char kHistogramName[] = "SSL.CertificateErrorHelpCenterVisited"; base::HistogramTester histograms; @@ -84,23 +71,16 @@ SetHelpCenterUrl(browser(), good_support_url); ui_test_utils::NavigateToURL(browser(), expired_non_support_url); - if (AreCommittedInterstitialsEnabled()) { - base::string16 tab_title; - ui_test_utils::GetCurrentTabTitle(browser(), &tab_title); - EXPECT_EQ(base::UTF16ToUTF8(tab_title), "Privacy error"); - } else { - EXPECT_TRUE(browser() - ->tab_strip_model() - ->GetActiveWebContents() - ->ShowingInterstitialPage()); - } + base::string16 tab_title; + ui_test_utils::GetCurrentTabTitle(browser(), &tab_title); + EXPECT_EQ(base::UTF16ToUTF8(tab_title), "Privacy error"); histograms.ExpectTotalCount(kHistogramName, 0); } // Tests that the chrome://connection-help redirect is not triggered (and // metrics are logged) for the help center URL if there was no interstitial. -IN_PROC_BROWSER_TEST_P(ConnectionHelpTabHelperTest, +IN_PROC_BROWSER_TEST_F(ConnectionHelpTabHelperTest, SupportURLWithNoInterstitial) { const char kHistogramName[] = "SSL.CertificateErrorHelpCenterVisited"; base::HistogramTester histograms; @@ -122,7 +102,7 @@ // Tests that the chrome://connection-help redirect is triggered (and metrics // are logged) for the help center URL if there was an interstitial. -IN_PROC_BROWSER_TEST_P(ConnectionHelpTabHelperTest, InterstitialOnSupportURL) { +IN_PROC_BROWSER_TEST_F(ConnectionHelpTabHelperTest, InterstitialOnSupportURL) { const char kHistogramName[] = "SSL.CertificateErrorHelpCenterVisited"; base::HistogramTester histograms; base::test::ScopedFeatureList feature_list; @@ -131,18 +111,7 @@ GURL expired_url = https_expired_server()->GetURL("/title2.html"); SetHelpCenterUrl(browser(), expired_url); - // Since ui_test_utils::NavigateToURL uses a TestNavigationObserver to wait - // for navigations, and TestNavigationObserver counts interstitials as a - // navigation, we need to wait for two navigations (the interstitial, and the - // help content) in the non-committed interstitial case. For committed - // interstitials, since the redirect happens before the original navigation - // finishes, we only need to wait for one. - if (AreCommittedInterstitialsEnabled()) { - ui_test_utils::NavigateToURL(browser(), expired_url); - } else { - ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(), - expired_url, 2); - } + ui_test_utils::NavigateToURL(browser(), expired_url); base::string16 tab_title; ui_test_utils::GetCurrentTabTitle(browser(), &tab_title); @@ -157,7 +126,7 @@ // Tests that histogram logs correctly when an interstitial is triggered on the // support URL if the feature is disabled. -IN_PROC_BROWSER_TEST_P(ConnectionHelpTabHelperTest, +IN_PROC_BROWSER_TEST_F(ConnectionHelpTabHelperTest, InterstitialOnSupportURLWithFeatureDisabled) { const char kHistogramName[] = "SSL.CertificateErrorHelpCenterVisited"; base::HistogramTester histograms; @@ -168,16 +137,9 @@ SetHelpCenterUrl(browser(), expired_url); ui_test_utils::NavigateToURL(browser(), expired_url); - if (AreCommittedInterstitialsEnabled()) { - base::string16 tab_title; - ui_test_utils::GetCurrentTabTitle(browser(), &tab_title); - EXPECT_EQ(base::UTF16ToUTF8(tab_title), "Privacy error"); - } else { - EXPECT_TRUE(browser() - ->tab_strip_model() - ->GetActiveWebContents() - ->ShowingInterstitialPage()); - } + base::string16 tab_title; + ui_test_utils::GetCurrentTabTitle(browser(), &tab_title); + EXPECT_EQ(base::UTF16ToUTF8(tab_title), "Privacy error"); histograms.ExpectUniqueSample( kHistogramName, @@ -188,7 +150,7 @@ // Tests that a non-interstitial error on the support URL is logged correctly, // by setting the support URL to an invalid URL and attempting to navigate to // it. -IN_PROC_BROWSER_TEST_P(ConnectionHelpTabHelperTest, NetworkErrorOnSupportURL) { +IN_PROC_BROWSER_TEST_F(ConnectionHelpTabHelperTest, NetworkErrorOnSupportURL) { const char kHistogramName[] = "SSL.CertificateErrorHelpCenterVisited"; base::HistogramTester histograms; GURL invalid_url("http://invalid-url.test"); @@ -202,7 +164,7 @@ // Tests that if the help content site is opened with an error code that refers // to a certificate error, the certificate error section is automatically // expanded. -IN_PROC_BROWSER_TEST_P(ConnectionHelpTabHelperTest, +IN_PROC_BROWSER_TEST_F(ConnectionHelpTabHelperTest, CorrectlyExpandsCertErrorSection) { base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(features::kBundledConnectionHelpFeature); @@ -212,18 +174,7 @@ replacements.ClearRef(); SetHelpCenterUrl(browser(), expired_url.ReplaceComponents(replacements)); - // Since ui_test_utils::NavigateToURL uses a TestNavigationObserver to wait - // for navigations, and TestNavigationObserver counts interstitials as a - // navigation, we need to wait for two navigations (the interstitial, and the - // help content) in the non-committed interstitial case. For committed - // interstitials, since the redirect happens before the original navigation - // finishes, we only need to wait for one. - if (AreCommittedInterstitialsEnabled()) { - ui_test_utils::NavigateToURL(browser(), expired_url); - } else { - ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(), - expired_url, 2); - } + ui_test_utils::NavigateToURL(browser(), expired_url); // Check that we got redirected to the offline help content. base::string16 tab_title; @@ -234,7 +185,8 @@ // Check that the cert error details section is not hidden. std::string cert_error_is_hidden_js = "var certSection = document.getElementById('details-certerror'); " - "window.domAutomationController.send(certSection.className == 'hidden');"; + "window.domAutomationController.send(certSection.className == " + "'hidden');"; bool cert_error_is_hidden; ASSERT_TRUE(content::ExecuteScriptAndExtractBool( browser()->tab_strip_model()->GetActiveWebContents(), @@ -244,7 +196,7 @@ // Tests that if the help content site is opened with an error code that refers // to an expired certificate, the clock section is automatically expanded. -IN_PROC_BROWSER_TEST_P(ConnectionHelpTabHelperTest, +IN_PROC_BROWSER_TEST_F(ConnectionHelpTabHelperTest, CorrectlyExpandsClockSection) { base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(features::kBundledConnectionHelpFeature); @@ -254,18 +206,7 @@ replacements.ClearRef(); SetHelpCenterUrl(browser(), expired_url.ReplaceComponents(replacements)); - // Since ui_test_utils::NavigateToURL uses a TestNavigationObserver to wait - // for navigations, and TestNavigationObserver counts interstitials as a - // navigation, we need to wait for two navigations (the interstitial, and the - // help content) in the non-committed interstitial case. For committed - // interstitials, since the redirect happens before the original navigation - // finishes, we only need to wait for one. - if (AreCommittedInterstitialsEnabled()) { - ui_test_utils::NavigateToURL(browser(), expired_url); - } else { - ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(), - expired_url, 2); - } + ui_test_utils::NavigateToURL(browser(), expired_url); // Check that we got redirected to the offline help content. base::string16 tab_title;
diff --git a/chrome/browser/ssl/security_state_tab_helper_browsertest.cc b/chrome/browser/ssl/security_state_tab_helper_browsertest.cc index 1fdaf05..f16b7de 100644 --- a/chrome/browser/ssl/security_state_tab_helper_browsertest.cc +++ b/chrome/browser/ssl/security_state_tab_helper_browsertest.cc
@@ -117,35 +117,21 @@ const char kTestCertificateIssuerName[] = "Test Root CA"; -bool AreCommittedInterstitialsEnabled() { - return base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials); -} - bool IsShowingInterstitial(content::WebContents* tab) { - if (AreCommittedInterstitialsEnabled()) { - security_interstitials::SecurityInterstitialTabHelper* helper = - security_interstitials::SecurityInterstitialTabHelper::FromWebContents( - tab); - if (!helper) { - return false; - } - return helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting() != - nullptr; + security_interstitials::SecurityInterstitialTabHelper* helper = + security_interstitials::SecurityInterstitialTabHelper::FromWebContents( + tab); + if (!helper) { + return false; } - return tab->GetInterstitialPage() != nullptr; + return helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting() != + nullptr; } // Waits until an interstitial is showing. void WaitForInterstitial(content::WebContents* tab) { - if (!AreCommittedInterstitialsEnabled()) { - content::WaitForInterstitialAttach(tab); - ASSERT_TRUE(IsShowingInterstitial(tab)); - ASSERT_TRUE( - WaitForRenderFrameReady(tab->GetInterstitialPage()->GetMainFrame())); - } else { - ASSERT_TRUE(IsShowingInterstitial(tab)); - ASSERT_TRUE(WaitForRenderFrameReady(tab->GetMainFrame())); - } + ASSERT_TRUE(IsShowingInterstitial(tab)); + ASSERT_TRUE(WaitForRenderFrameReady(tab->GetMainFrame())); } // Inject a script into every frame in the page. Used by tests that check for @@ -412,26 +398,14 @@ } void ProceedThroughInterstitial(content::WebContents* tab) { - if (AreCommittedInterstitialsEnabled()) { - content::TestNavigationObserver nav_observer(tab, 1); - security_interstitials::SecurityInterstitialTabHelper* helper = - security_interstitials::SecurityInterstitialTabHelper::FromWebContents( - tab); - helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting() - ->CommandReceived( - base::NumberToString(security_interstitials::CMD_PROCEED)); - nav_observer.Wait(); - } else { - content::InterstitialPage* interstitial_page = tab->GetInterstitialPage(); - ASSERT_TRUE(interstitial_page); - ASSERT_EQ(SSLBlockingPage::kTypeForTesting, - interstitial_page->GetDelegateForTesting()->GetTypeForTesting()); - content::WindowedNotificationObserver observer( - content::NOTIFICATION_LOAD_STOP, - content::Source<content::NavigationController>(&tab->GetController())); - interstitial_page->Proceed(); - observer.Wait(); - } + content::TestNavigationObserver nav_observer(tab, 1); + security_interstitials::SecurityInterstitialTabHelper* helper = + security_interstitials::SecurityInterstitialTabHelper::FromWebContents( + tab); + helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting() + ->CommandReceived( + base::NumberToString(security_interstitials::CMD_PROCEED)); + nav_observer.Wait(); } std::string GetFilePathWithHostAndPortReplacement( @@ -451,8 +425,7 @@ return server->GetURL(path).ReplaceComponents(replace_host); } -class SecurityStateTabHelperTest : public CertVerifierBrowserTest, - public testing::WithParamInterface<bool> { +class SecurityStateTabHelperTest : public CertVerifierBrowserTest { public: SecurityStateTabHelperTest() : https_server_(net::EmbeddedTestServer::TYPE_HTTPS) { @@ -471,10 +444,6 @@ CertVerifierBrowserTest::SetUpCommandLine(command_line); // Browser will both run and display insecure content. command_line->AppendSwitch(switches::kAllowRunningInsecureContent); - if (GetParam()) { - scoped_feature_list_.InitAndEnableFeature( - features::kSSLCommittedInterstitials); - } } protected: @@ -551,10 +520,6 @@ DISALLOW_COPY_AND_ASSIGN(SecurityStateTabHelperTest); }; -INSTANTIATE_TEST_SUITE_P(, - SecurityStateTabHelperTest, - ::testing::Values(false, true)); - // Same as SecurityStateTabHelperTest, but with Incognito enabled. class SecurityStateTabHelperIncognitoTest : public SecurityStateTabHelperTest { public: @@ -570,10 +535,6 @@ DISALLOW_COPY_AND_ASSIGN(SecurityStateTabHelperIncognitoTest); }; -INSTANTIATE_TEST_SUITE_P(, - SecurityStateTabHelperIncognitoTest, - ::testing::Values(false, true)); - class DidChangeVisibleSecurityStateTest : public InProcessBrowserTest, public testing::WithParamInterface<bool> { @@ -586,10 +547,6 @@ void SetUpCommandLine(base::CommandLine* command_line) override { // Browser will both run and display insecure content. command_line->AppendSwitch(switches::kAllowRunningInsecureContent); - if (GetParam()) { - scoped_feature_list_.InitAndEnableFeature( - features::kSSLCommittedInterstitials); - } } void SetUpOnMainThread() override { @@ -604,11 +561,7 @@ DISALLOW_COPY_AND_ASSIGN(DidChangeVisibleSecurityStateTest); }; -INSTANTIATE_TEST_SUITE_P(, - DidChangeVisibleSecurityStateTest, - ::testing::Values(false, true)); - -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, HttpPage) { +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, HttpPage) { ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL("/ssl/google.html")); content::WebContents* contents = @@ -634,7 +587,7 @@ EXPECT_EQ(0, visible_security_state->connection_status); } -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, HttpsPage) { +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, HttpsPage) { SetUpMockCertVerifierForHttpsServer(0, net::OK); ui_test_utils::NavigateToURL(browser(), @@ -647,7 +600,7 @@ // Tests that interstitial.ssl.visited_site_after_warning is being logged to // correctly. -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, UMALogsVisitsAfterWarning) { +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, UMALogsVisitsAfterWarning) { const char kHistogramName[] = "interstitial.ssl.visited_site_after_warning"; base::HistogramTester histograms; SetUpMockCertVerifierForHttpsServer(net::CERT_STATUS_DATE_INVALID, @@ -665,7 +618,7 @@ // Tests that interstitial.ssl.visited_site_after_warning is not being logged // to on errors that do not trigger a full site interstitial. -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, UMADoesNotLogOnMinorError) { +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, UMADoesNotLogOnMinorError) { const char kHistogramName[] = "interstitial.ssl.visited_site_after_warning"; base::HistogramTester histograms; SetUpMockCertVerifierForHttpsServer( @@ -677,7 +630,7 @@ // Test security state after clickthrough for a SHA-1 certificate that is // blocked by default. -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, SHA1CertificateBlocked) { +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, SHA1CertificateBlocked) { SetUpMockCertVerifierForHttpsServer( net::CERT_STATUS_SHA1_SIGNATURE_PRESENT | net::CERT_STATUS_WEAK_SIGNATURE_ALGORITHM, @@ -717,7 +670,7 @@ } // Test security state for a SHA-1 certificate that is allowed by policy. -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, SHA1CertificateWarning) { +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, SHA1CertificateWarning) { SetUpMockCertVerifierForHttpsServer(net::CERT_STATUS_SHA1_SIGNATURE_PRESENT, net::OK); @@ -740,7 +693,7 @@ explanation.neutral_explanations[0].summary); } -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, MixedContent) { +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, MixedContent) { SetUpMockCertVerifierForHttpsServer(0, net::OK); net::HostPortPair replacement_pair = embedded_test_server()->host_port_pair(); @@ -810,7 +763,7 @@ false /* expect cert status error */); } -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, ActiveContentWithCertErrors) { SetUpMockCertVerifierForHttpsServer(0, net::OK); @@ -838,7 +791,7 @@ EXPECT_FALSE(visible_security_state->displayed_content_with_cert_errors); } -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, PassiveContentWithCertErrors) { SetUpMockCertVerifierForHttpsServer(0, net::OK); @@ -866,7 +819,7 @@ EXPECT_TRUE(visible_security_state->displayed_content_with_cert_errors); } -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, ActiveAndPassiveContentWithCertErrors) { SetUpMockCertVerifierForHttpsServer(0, net::OK); @@ -898,7 +851,7 @@ // Same as SecurityStateTabHelperTest.ActiveAndPassiveContentWithCertErrors but // with a SHA1 cert. -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, MixedContentWithSHA1Cert) { +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, MixedContentWithSHA1Cert) { SetUpMockCertVerifierForHttpsServer(net::CERT_STATUS_SHA1_SIGNATURE_PRESENT, net::OK); @@ -958,7 +911,7 @@ // Tests that the Content Security Policy block-all-mixed-content // directive stops mixed content from running. -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, MixedContentStrictBlocking) { +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, MixedContentStrictBlocking) { SetUpMockCertVerifierForHttpsServer(0, net::OK); // Navigate to an HTTPS page that tries to run mixed content in an @@ -977,7 +930,7 @@ false /* expect cert status error */); } -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, BrokenHTTPS) { +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, BrokenHTTPS) { SetUpMockCertVerifierForHttpsServer(net::CERT_STATUS_DATE_INVALID, net::ERR_CERT_DATE_INVALID); @@ -1010,7 +963,7 @@ // Tests that the security level of data: URLs is always downgraded to // HTTP_SHOW_WARNING. -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, SecurityLevelDowngradedOnDataUrl) { content::WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents(); @@ -1037,7 +990,7 @@ // Tests the security level and malicious content status for sign-in password // reuse threat type. -IN_PROC_BROWSER_TEST_P( +IN_PROC_BROWSER_TEST_F( SecurityStateTabHelperTest, VerifySignInPasswordReuseMaliciousContentAndSecurityLevel) { // Setup https server. This makes sure that the DANGEROUS security level is @@ -1085,7 +1038,7 @@ // Tests the security level and malicious content status for enterprise password // reuse threat type. -IN_PROC_BROWSER_TEST_P( +IN_PROC_BROWSER_TEST_F( SecurityStateTabHelperTest, VerifyEnterprisePasswordReuseMaliciousContentAndSecurityLevel) { // Setup https server. This makes sure that the DANGEROUS security level is @@ -1124,7 +1077,7 @@ // Tests that the security level of ftp: URLs is always downgraded to // HTTP_SHOW_WARNING. -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, SecurityLevelDowngradedOnFtpUrl) { content::WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents(); @@ -1201,9 +1154,7 @@ } }; -INSTANTIATE_TEST_SUITE_P(, PKPModelClientTest, ::testing::Values(false, true)); - -IN_PROC_BROWSER_TEST_P(PKPModelClientTest, PKPBypass) { +IN_PROC_BROWSER_TEST_F(PKPModelClientTest, PKPBypass) { content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); SecurityStyleTestObserver observer(web_contents); @@ -1232,7 +1183,7 @@ EXPECT_FALSE(explanation.info_explanations.empty()); } -IN_PROC_BROWSER_TEST_P(PKPModelClientTest, PKPEnforced) { +IN_PROC_BROWSER_TEST_F(PKPModelClientTest, PKPEnforced) { content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); SecurityStyleTestObserver observer(web_contents); @@ -1300,13 +1251,9 @@ DISALLOW_COPY_AND_ASSIGN(SecurityStateLoadingTest); }; -INSTANTIATE_TEST_SUITE_P(, - SecurityStateLoadingTest, - ::testing::Values(false, true)); - // Tests that navigation state changes cause the security state to be // updated. -IN_PROC_BROWSER_TEST_P(SecurityStateLoadingTest, NavigationStateChanges) { +IN_PROC_BROWSER_TEST_F(SecurityStateLoadingTest, NavigationStateChanges) { ASSERT_TRUE(https_server_.Start()); SetUpMockCertVerifierForHttpsServer(0, net::OK); @@ -1328,7 +1275,7 @@ } // Tests the default security level on blob URLs. -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, DefaultSecurityLevelOnBlobUrl) { TestBlobOrFilesystemURL("blob", kCreateBlobUrlJavascript, false /* use_secure_inner_origin */); @@ -1336,14 +1283,14 @@ // Same as DefaultSecurityLevelOnBlobUrl, but instead of a blob URL, // this creates a filesystem URL. -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, DefaultSecurityLevelOnFilesystemUrl) { TestBlobOrFilesystemURL("filesystem", kCreateFilesystemUrlJavascript, false /* use_secure_inner_origin */); } // Tests the default security level on blob URLs with a secure inner origin. -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, DefaultSecurityLevelOnSecureBlobUrl) { SetUpMockCertVerifierForHttpsServer(0, net::OK); TestBlobOrFilesystemURL("blob", kCreateBlobUrlJavascript, @@ -1352,7 +1299,7 @@ // Same as DefaultSecurityLevelOnBlobUrl, but instead of a blob URL, // this creates a filesystem URL with a secure inner origin. -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, DefaultSecurityLevelOnSecureFilesystemUrl) { SetUpMockCertVerifierForHttpsServer(0, net::OK); TestBlobOrFilesystemURL("filesystem", kCreateFilesystemUrlJavascript, @@ -1361,7 +1308,7 @@ // Tests that the security level of a HTTP page is not downgraded when a form // field is modified by JavaScript. -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, SecurityLevelNotDowngradedAfterScriptModification) { base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndEnableFeatureWithParameters( @@ -1403,7 +1350,7 @@ // Tests that the security level of a HTTP page is downgraded from // HTTP_SHOW_WARNING to DANGEROUS after editing a form field in the relevant // configurations. -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, SecurityLevelDowngradedAfterFileSelection) { base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndDisableFeature( @@ -1496,7 +1443,7 @@ // Tests that the security state for a WebContents is up to date when the // WebContents is inserted into a Browser's TabStripModel. -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, AddedTab) { +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, AddedTab) { SetUpMockCertVerifierForHttpsServer(0, net::OK); content::WebContents* tab = @@ -1526,7 +1473,7 @@ // Tests that the WebContentsObserver::DidChangeVisibleSecurityState event fires // with the current style on HTTP, broken HTTPS, and valid HTTPS pages. -IN_PROC_BROWSER_TEST_P(DidChangeVisibleSecurityStateTest, +IN_PROC_BROWSER_TEST_F(DidChangeVisibleSecurityStateTest, DidChangeVisibleSecurityStateObserver) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_.Start()); @@ -1654,7 +1601,7 @@ // Tests that the security level of a HTTP page is downgraded to DANGEROUS when // MarkHttpAsDangerous is enabled. -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, SecurityLevelDangerousWhenMarkHttpAsDangerous) { base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndEnableFeatureWithParameters( @@ -1696,7 +1643,7 @@ #define MAYBE_DidChangeVisibleSecurityStateObserverGoBack \ DidChangeVisibleSecurityStateObserverGoBack #endif -IN_PROC_BROWSER_TEST_P(DidChangeVisibleSecurityStateTest, +IN_PROC_BROWSER_TEST_F(DidChangeVisibleSecurityStateTest, MAYBE_DidChangeVisibleSecurityStateObserverGoBack) { ASSERT_TRUE(https_server_.Start()); @@ -1872,7 +1819,7 @@ // Tests that the Not Secure chip does not show for error pages on http:// URLs. // Regression test for https://crbug.com/760647. -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperIncognitoTest, HttpErrorPage) { +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperIncognitoTest, HttpErrorPage) { content::WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents(); SecurityStateTabHelper* helper = @@ -1895,7 +1842,7 @@ EXPECT_EQ(security_state::NONE, helper->GetSecurityLevel()); } -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, MarkHttpAsWarningAndDangerousOnFormEdits) { base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndEnableFeatureWithParameters( @@ -1960,7 +1907,7 @@ EXPECT_EQ(security_state::HTTP_SHOW_WARNING, helper->GetSecurityLevel()); } -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, MarkHttpAsWarningAndDangerousOnFileInputEdits) { base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndEnableFeatureWithParameters( @@ -2005,7 +1952,7 @@ // Tests that the histogram for security level is recorded correctly for HTTP // pages. -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, HTTPSecurityLevelHistogram) { +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, HTTPSecurityLevelHistogram) { base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndDisableFeature( security_state::features::kMarkHttpAsFeature); @@ -2025,7 +1972,7 @@ // Tests that the histogram for security level is recorded correctly for HTTPS // pages. -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, HTTPSSecurityLevelHistogram) { SetUpMockCertVerifierForHttpsServer(0, net::OK); const char kHistogramName[] = "Security.SecurityLevel.CryptographicScheme"; @@ -2063,7 +2010,7 @@ // Tests that the Certificate Transparency compliance of the main resource is // recorded in a histogram. -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, CTComplianceHistogram) { +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, CTComplianceHistogram) { const char kHistogramName[] = "Security.CertificateTransparency.MainFrameNavigationCompliance"; SetUpMockCertVerifierForHttpsServer(0, net::OK); @@ -2076,7 +2023,7 @@ } // Tests that the Form submission histogram is logged correctly. -IN_PROC_BROWSER_TEST_P(SecurityStateTabHelperTest, FormSecurityLevelHistogram) { +IN_PROC_BROWSER_TEST_F(SecurityStateTabHelperTest, FormSecurityLevelHistogram) { const char kHistogramName[] = "Security.SecurityLevel.FormSubmission"; SetUpMockCertVerifierForHttpsServer(0, net::OK); base::HistogramTester histograms;
diff --git a/chrome/browser/ssl/ssl_browsertest.cc b/chrome/browser/ssl/ssl_browsertest.cc index f2163a5..12c9e4e 100644 --- a/chrome/browser/ssl/ssl_browsertest.cc +++ b/chrome/browser/ssl/ssl_browsertest.cc
@@ -207,10 +207,6 @@ SSL_INTERSTITIAL_DO_NOT_PROCEED }; -bool AreCommittedInterstitialsEnabled() { - return base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials); -} - void CheckProceedLinkExists(WebContents* tab) { int result = security_interstitials::CMD_ERROR; const std::string javascript = base::StringPrintf( @@ -219,11 +215,8 @@ "? (%d) : (%d))", security_interstitials::CMD_TEXT_NOT_FOUND, security_interstitials::CMD_TEXT_FOUND); - ASSERT_TRUE(content::ExecuteScriptAndExtractInt( - AreCommittedInterstitialsEnabled() - ? tab->GetMainFrame() - : tab->GetInterstitialPage()->GetMainFrame(), - javascript, &result)); + ASSERT_TRUE(content::ExecuteScriptAndExtractInt(tab->GetMainFrame(), + javascript, &result)); EXPECT_EQ(security_interstitials::CMD_TEXT_FOUND, result); } @@ -381,17 +374,14 @@ } bool IsShowingInterstitial(content::WebContents* tab) { - if (AreCommittedInterstitialsEnabled()) { - security_interstitials::SecurityInterstitialTabHelper* helper = - security_interstitials::SecurityInterstitialTabHelper::FromWebContents( - tab); - if (!helper) { - return false; - } - return helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting() != - nullptr; + security_interstitials::SecurityInterstitialTabHelper* helper = + security_interstitials::SecurityInterstitialTabHelper::FromWebContents( + tab); + if (!helper) { + return false; } - return tab->GetInterstitialPage() != nullptr; + return helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting() != + nullptr; } // Waits until an interstitial is showing. @@ -399,27 +389,14 @@ // TODO(crbug.com/752372): This should not be needed for committed // interstitials. Replace all call sites directly with the assert. void WaitForInterstitial(content::WebContents* tab) { - if (!AreCommittedInterstitialsEnabled()) { - content::WaitForInterstitialAttach(tab); - ASSERT_TRUE(IsShowingInterstitial(tab)); - ASSERT_TRUE( - WaitForRenderFrameReady(tab->GetInterstitialPage()->GetMainFrame())); - } else { - ASSERT_TRUE(IsShowingInterstitial(tab)); - ASSERT_TRUE(WaitForRenderFrameReady(tab->GetMainFrame())); - } + ASSERT_TRUE(IsShowingInterstitial(tab)); + ASSERT_TRUE(WaitForRenderFrameReady(tab->GetMainFrame())); } void ExpectInterstitialElementHidden(content::WebContents* tab, const std::string& element_id, bool expect_hidden) { - if (!AreCommittedInterstitialsEnabled()) { - ASSERT_TRUE(tab->GetInterstitialPage()); - } - content::RenderFrameHost* frame = - AreCommittedInterstitialsEnabled() - ? tab->GetMainFrame() - : tab->GetInterstitialPage()->GetMainFrame(); + content::RenderFrameHost* frame = tab->GetMainFrame(); // Send CMD_TEXT_FOUND to indicate that the 'hidden' class is found, and // CMD_TEXT_NOT_FOUND if not. std::string command = base::StringPrintf( @@ -436,13 +413,7 @@ void ExpectInterstitialHeading(content::WebContents* tab, const std::string& expected_heading) { - if (!AreCommittedInterstitialsEnabled()) { - ASSERT_TRUE(tab->GetInterstitialPage()); - } - content::RenderFrameHost* frame = - AreCommittedInterstitialsEnabled() - ? tab->GetMainFrame() - : tab->GetInterstitialPage()->GetMainFrame(); + content::RenderFrameHost* frame = tab->GetMainFrame(); EXPECT_TRUE(chrome_browser_interstitials::IsInterstitialDisplayingText( frame, expected_heading)); } @@ -994,135 +965,107 @@ DISALLOW_COPY_AND_ASSIGN(SSLUITestBase); }; -class SSLUITest : public SSLUITestBase, - public testing::WithParamInterface<bool> { +class SSLUITest : public SSLUITestBase { public: SSLUITest() : SSLUITestBase() {} protected: - void SetUpOnMainThread() override { - SSLUITestBase::SetUpOnMainThread(); - if (IsCommittedInterstitialTest()) { - scoped_feature_list_.InitAndEnableFeature( - features::kSSLCommittedInterstitials); - } - } - SSLBlockingPage* GetSSLBlockingPage(WebContents* tab) override { - if (AreCommittedInterstitialsEnabled()) { - security_interstitials::SecurityInterstitialTabHelper* helper = - security_interstitials::SecurityInterstitialTabHelper:: - FromWebContents(tab); - if (!helper) { - return nullptr; - } - return static_cast<SSLBlockingPage*>( - helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting()); + security_interstitials::SecurityInterstitialTabHelper* helper = + security_interstitials::SecurityInterstitialTabHelper::FromWebContents( + tab); + if (!helper) { + return nullptr; } - return SSLUITestBase::GetSSLBlockingPage(tab); + return static_cast<SSLBlockingPage*>( + helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting()); } BadClockBlockingPage* GetBadClockBlockingPage(WebContents* tab) override { - if (AreCommittedInterstitialsEnabled()) { - security_interstitials::SecurityInterstitialTabHelper* helper = - security_interstitials::SecurityInterstitialTabHelper:: - FromWebContents(tab); - if (!helper) { - return nullptr; - } - return static_cast<BadClockBlockingPage*>( - helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting()); + security_interstitials::SecurityInterstitialTabHelper* helper = + security_interstitials::SecurityInterstitialTabHelper::FromWebContents( + tab); + if (!helper) { + return nullptr; } - return SSLUITestBase::GetBadClockBlockingPage(tab); + return static_cast<BadClockBlockingPage*>( + helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting()); } - bool IsCommittedInterstitialTest() const { return GetParam(); } - void DontProceedThroughInterstitial(WebContents* tab) override { - if (AreCommittedInterstitialsEnabled()) { - content::TestNavigationObserver nav_observer(tab, 1); - SendInterstitialCommand(tab, security_interstitials::CMD_DONT_PROCEED); - nav_observer.Wait(); - } else { - SSLUITestBase::DontProceedThroughInterstitial(tab); - } + content::TestNavigationObserver nav_observer(tab, 1); + SendInterstitialCommand(tab, security_interstitials::CMD_DONT_PROCEED); + nav_observer.Wait(); } void SendInterstitialCommand( WebContents* tab, security_interstitials::SecurityInterstitialCommand command) override { - if (AreCommittedInterstitialsEnabled()) { - std::string javascript; - switch (command) { - case security_interstitials::CMD_DONT_PROCEED: { - javascript = "window.certificateErrorPageController.dontProceed();"; - break; - } - case security_interstitials::CMD_PROCEED: { - javascript = "window.certificateErrorPageController.proceed();"; - break; - } - case security_interstitials::CMD_SHOW_MORE_SECTION: { - javascript = - "window.certificateErrorPageController.showMoreSection();"; - break; - } - case security_interstitials::CMD_OPEN_HELP_CENTER: { - javascript = - "window.certificateErrorPageController.openHelpCenter();"; - break; - } - case security_interstitials::CMD_OPEN_DIAGNOSTIC: { - javascript = - "window.certificateErrorPageController.openDiagnostic();"; - break; - } - case security_interstitials::CMD_RELOAD: { - javascript = "window.certificateErrorPageController.reload();"; - break; - } - case security_interstitials::CMD_OPEN_DATE_SETTINGS: { - javascript = - "window.certificateErrorPageController.openDateSettings();"; - break; - } - case security_interstitials::CMD_OPEN_LOGIN: { - javascript = "window.certificateErrorPageController.openLogin();"; - break; - } - case security_interstitials::CMD_DO_REPORT: { - javascript = "window.certificateErrorPageController.doReport();"; - break; - } - case security_interstitials::CMD_DONT_REPORT: { - javascript = "window.certificateErrorPageController.dontReport();"; - break; - } - case security_interstitials::CMD_OPEN_REPORTING_PRIVACY: { - javascript = - "window.certificateErrorPageController.openReportingPrivacy();"; - break; - } - case security_interstitials::CMD_OPEN_WHITEPAPER: { - javascript = - "window.certificateErrorPageController.openWhitepaper();"; - break; - } - case security_interstitials::CMD_REPORT_PHISHING_ERROR: { - javascript = - "window.certificateErrorPageController.reportPhishingError();"; - break; - } - default: { - // Other values in the enum are not used by these tests, and don't - // have a Javascript equivalent that can be called here. - NOTREACHED(); - } + std::string javascript; + switch (command) { + case security_interstitials::CMD_DONT_PROCEED: { + javascript = "window.certificateErrorPageController.dontProceed();"; + break; } - ASSERT_TRUE(content::ExecuteScript(tab, javascript)); - return; + case security_interstitials::CMD_PROCEED: { + javascript = "window.certificateErrorPageController.proceed();"; + break; + } + case security_interstitials::CMD_SHOW_MORE_SECTION: { + javascript = "window.certificateErrorPageController.showMoreSection();"; + break; + } + case security_interstitials::CMD_OPEN_HELP_CENTER: { + javascript = "window.certificateErrorPageController.openHelpCenter();"; + break; + } + case security_interstitials::CMD_OPEN_DIAGNOSTIC: { + javascript = "window.certificateErrorPageController.openDiagnostic();"; + break; + } + case security_interstitials::CMD_RELOAD: { + javascript = "window.certificateErrorPageController.reload();"; + break; + } + case security_interstitials::CMD_OPEN_DATE_SETTINGS: { + javascript = + "window.certificateErrorPageController.openDateSettings();"; + break; + } + case security_interstitials::CMD_OPEN_LOGIN: { + javascript = "window.certificateErrorPageController.openLogin();"; + break; + } + case security_interstitials::CMD_DO_REPORT: { + javascript = "window.certificateErrorPageController.doReport();"; + break; + } + case security_interstitials::CMD_DONT_REPORT: { + javascript = "window.certificateErrorPageController.dontReport();"; + break; + } + case security_interstitials::CMD_OPEN_REPORTING_PRIVACY: { + javascript = + "window.certificateErrorPageController.openReportingPrivacy();"; + break; + } + case security_interstitials::CMD_OPEN_WHITEPAPER: { + javascript = "window.certificateErrorPageController.openWhitepaper();"; + break; + } + case security_interstitials::CMD_REPORT_PHISHING_ERROR: { + javascript = + "window.certificateErrorPageController.reportPhishingError();"; + break; + } + default: { + // Other values in the enum are not used by these tests, and don't + // have a Javascript equivalent that can be called here. + NOTREACHED(); + } } - SSLUITestBase::SendInterstitialCommand(tab, command); + ASSERT_TRUE(content::ExecuteScript(tab, javascript)); + return; } private: @@ -1130,11 +1073,6 @@ DISALLOW_COPY_AND_ASSIGN(SSLUITest); }; -INSTANTIATE_TEST_SUITE_P(, SSLUITest, ::testing::Values(false, true)); - -using SSLUITestCommitted = SSLUITest; -INSTANTIATE_TEST_SUITE_P(, SSLUITestCommitted, ::testing::Values(true)); - class SSLUITestBlock : public SSLUITest { public: SSLUITestBlock() : SSLUITest() {} @@ -1146,8 +1084,6 @@ } }; -INSTANTIATE_TEST_SUITE_P(, SSLUITestBlock, ::testing::Values(false, true)); - class SSLUITestIgnoreCertErrors : public SSLUITest { public: SSLUITestIgnoreCertErrors() : SSLUITest() {} @@ -1159,10 +1095,6 @@ } }; -INSTANTIATE_TEST_SUITE_P(, - SSLUITestIgnoreCertErrors, - ::testing::Values(false, true)); - static std::string MakeCertSPKIFingerprint(net::X509Certificate* cert) { net::HashValue hash = GetSPKIHash(cert->cert_buffer()); std::string hash_base64; @@ -1186,10 +1118,6 @@ } }; -INSTANTIATE_TEST_SUITE_P(, - SSLUITestIgnoreCertErrorsBySPKIHTTPS, - ::testing::Values(false, true)); - class SSLUITestIgnoreCertErrorsBySPKIWSS : public SSLUITest { public: SSLUITestIgnoreCertErrorsBySPKIWSS() : SSLUITest() {} @@ -1205,10 +1133,6 @@ } }; -INSTANTIATE_TEST_SUITE_P(, - SSLUITestIgnoreCertErrorsBySPKIWSS, - ::testing::Values(false, true)); - class SSLUITestIgnoreLocalhostCertErrors : public SSLUITest { public: SSLUITestIgnoreLocalhostCertErrors() : SSLUITest() {} @@ -1220,10 +1144,6 @@ } }; -INSTANTIATE_TEST_SUITE_P(, - SSLUITestIgnoreLocalhostCertErrors, - ::testing::Values(false, true)); - class SSLUITestWithExtendedReporting : public SSLUITest { public: SSLUITestWithExtendedReporting() : SSLUITest() { @@ -1243,10 +1163,6 @@ } }; -INSTANTIATE_TEST_SUITE_P(, - SSLUITestWithExtendedReporting, - ::testing::Values(false, true)); - class SSLUITestHSTS : public SSLUITest { public: void SetUpOnMainThread() override { @@ -1255,10 +1171,8 @@ } }; -INSTANTIATE_TEST_SUITE_P(, SSLUITestHSTS, ::testing::Values(false, true)); - // Visits a regular page over http. -IN_PROC_BROWSER_TEST_P(SSLUITest, TestHTTP) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestHTTP) { ASSERT_TRUE(embedded_test_server()->Start()); ui_test_utils::NavigateToURL( @@ -1272,7 +1186,7 @@ // be OK). // TODO(jcampan): test that bad HTTPS content is blocked (otherwise we'll give // the secure cookies away!). -IN_PROC_BROWSER_TEST_P(SSLUITest, TestHTTPWithBrokenHTTPSResource) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestHTTPWithBrokenHTTPSResource) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_expired_.Start()); @@ -1287,7 +1201,7 @@ browser()->tab_strip_model()->GetActiveWebContents(), AuthState::NONE); } -IN_PROC_BROWSER_TEST_P(SSLUITest, TestBrokenHTTPSWithInsecureContent) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestBrokenHTTPSWithInsecureContent) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_expired_.Start()); @@ -1311,7 +1225,7 @@ // Tests that the NavigationEntry gets marked as active mixed content, // even if there is a certificate error. Regression test for // https://crbug.com/593950. -IN_PROC_BROWSER_TEST_P(SSLUITest, TestBrokenHTTPSWithActiveInsecureContent) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestBrokenHTTPSWithActiveInsecureContent) { ASSERT_TRUE(https_server_expired_.Start()); WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); @@ -1360,7 +1274,7 @@ // Tests that the mixed content flags are reset when going back to an existing // navigation entry that had mixed content. Regression test for // https://crbug.com/750649. -IN_PROC_BROWSER_TEST_P(SSLUITest, GoBackToMixedContent) { +IN_PROC_BROWSER_TEST_F(SSLUITest, GoBackToMixedContent) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_.Start()); @@ -1392,7 +1306,7 @@ } // Tests that the mixed content flags are not reset for an in-page navigation. -IN_PROC_BROWSER_TEST_P(SSLUITest, MixedContentWithSameDocumentNavigation) { +IN_PROC_BROWSER_TEST_F(SSLUITest, MixedContentWithSameDocumentNavigation) { ASSERT_TRUE(https_server_.Start()); // Navigate to a URL and dynamically load mixed content. @@ -1422,7 +1336,7 @@ // Tests that the WebContents's flag for displaying content with cert // errors get cleared upon navigation. -IN_PROC_BROWSER_TEST_P(SSLUITest, +IN_PROC_BROWSER_TEST_F(SSLUITest, DisplayedContentWithCertErrorsClearedOnNavigation) { ASSERT_TRUE(https_server_.Start()); ASSERT_TRUE(https_server_expired_.Start()); @@ -1453,7 +1367,7 @@ content::SSLStatus::DISPLAYED_CONTENT_WITH_CERT_ERRORS); } -IN_PROC_BROWSER_TEST_P(SSLUITest, TestBrokenHTTPSMetricsReporting_Proceed) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestBrokenHTTPSMetricsReporting_Proceed) { ASSERT_TRUE(https_server_expired_.Start()); base::HistogramTester histograms; const std::string decision_histogram = @@ -1489,7 +1403,7 @@ security_interstitials::MetricsHelper::TOTAL_VISITS, 1); } -IN_PROC_BROWSER_TEST_P(SSLUITest, TestBrokenHTTPSMetricsReporting_DontProceed) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestBrokenHTTPSMetricsReporting_DontProceed) { ASSERT_TRUE(https_server_expired_.Start()); base::HistogramTester histograms; const std::string decision_histogram = @@ -1527,7 +1441,7 @@ } // Visits a page over OK https: -IN_PROC_BROWSER_TEST_P(SSLUITest, TestOKHTTPS) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestOKHTTPS) { ASSERT_TRUE(https_server_.Start()); ui_test_utils::NavigateToURL(browser(), @@ -1538,7 +1452,7 @@ } // Visits a page with https error and proceed: -IN_PROC_BROWSER_TEST_P(SSLUITest, TestHTTPSExpiredCertAndProceed) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestHTTPSExpiredCertAndProceed) { ASSERT_TRUE(https_server_expired_.Start()); ui_test_utils::NavigateToURL( @@ -1557,7 +1471,7 @@ } // Visits a page in an app window with https error and proceed: -IN_PROC_BROWSER_TEST_P(SSLUITest, InAppTestHTTPSExpiredCertAndProceed) { +IN_PROC_BROWSER_TEST_F(SSLUITest, InAppTestHTTPSExpiredCertAndProceed) { ASSERT_TRUE(https_server_expired_.Start()); const GURL app_url = https_server_expired_.GetURL("/ssl/google.html"); @@ -1572,7 +1486,7 @@ } // Visits a page with https error and proceed. Then open the app and proceed. -IN_PROC_BROWSER_TEST_P(SSLUITestCommitted, +IN_PROC_BROWSER_TEST_F(SSLUITest, InAppTestHTTPSExpiredCertAndPreviouslyProceeded) { ASSERT_TRUE(https_server_expired_.Start()); @@ -1605,7 +1519,7 @@ // Visits a page with https error and don't proceed (and ensure we can still // navigate at that point): -IN_PROC_BROWSER_TEST_P(SSLUITest, TestInterstitialCrossSiteNavigation) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestInterstitialCrossSiteNavigation) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_.Start()); ASSERT_TRUE(https_server_mismatched_.Start()); @@ -1640,7 +1554,7 @@ } // Test that localhost pages don't show an interstitial. -IN_PROC_BROWSER_TEST_P(SSLUITestIgnoreLocalhostCertErrors, +IN_PROC_BROWSER_TEST_F(SSLUITestIgnoreLocalhostCertErrors, TestNoInterstitialOnLocalhost) { ASSERT_TRUE(https_server_.Start()); @@ -1668,7 +1582,7 @@ EXPECT_EQ(title, expected_title); } -IN_PROC_BROWSER_TEST_P(SSLUITest, TestHTTPSErrorCausedByClockUsingBuildTime) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestHTTPSErrorCausedByClockUsingBuildTime) { ASSERT_TRUE(https_server_expired_.Start()); // Set up the build and current clock times to be more than a year apart. @@ -1689,7 +1603,7 @@ AuthState::SHOWING_INTERSTITIAL); } -IN_PROC_BROWSER_TEST_P(SSLUITest, TestHTTPSErrorCausedByClockUsingNetwork) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestHTTPSErrorCausedByClockUsingNetwork) { ASSERT_TRUE(https_server_expired_.Start()); // Set network forward ten minutes, which is sufficient to trigger @@ -1711,7 +1625,7 @@ } // Visits a page with https error and then goes back using Browser::GoBack. -IN_PROC_BROWSER_TEST_P(SSLUITest, TestHTTPSExpiredCertAndGoBackViaButton) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestHTTPSExpiredCertAndGoBackViaButton) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_expired_.Start()); @@ -1719,7 +1633,6 @@ ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL("/ssl/google.html")); WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); - content::RenderFrameHost* rfh = tab->GetMainFrame(); // Now go to a bad HTTPS page that shows an interstitial. ui_test_utils::NavigateToURL( @@ -1731,22 +1644,13 @@ chrome::GoBack(browser(), WindowOpenDisposition::CURRENT_TAB); content::WaitForLoadStop(tab); - if (!AreCommittedInterstitialsEnabled()) { - // Make sure we haven't changed the previous RFH. Prevents regression of - // http://crbug.com/82667. This is only applicable to pre-committed - // interstitials. With committed interstitials, the interstitial is a - // committed error page, so going back from it to a different site can be a - // cross-site transition. - EXPECT_EQ(rfh, tab->GetMainFrame()); - } - // We should be back at the original good page. EXPECT_FALSE(IsShowingInterstitial(tab)); CheckUnauthenticatedState(tab, AuthState::NONE); } // Visits a page with https error and then goes back using GoToOffset. -IN_PROC_BROWSER_TEST_P(SSLUITest, TestHTTPSExpiredCertAndGoBackViaMenu) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestHTTPSExpiredCertAndGoBackViaMenu) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_expired_.Start()); @@ -1765,8 +1669,7 @@ // committed interstitials enabled, this triggers a navigation. content::TestNavigationObserver nav_observer(tab); tab->GetController().GoToOffset(-1); - if (AreCommittedInterstitialsEnabled()) - nav_observer.Wait(); + nav_observer.Wait(); // We should be back at the original good page. EXPECT_FALSE(IsShowingInterstitial(tab)); @@ -1775,7 +1678,7 @@ // Visits a page with https error and then goes back using the DONT_PROCEED // interstitial command. -IN_PROC_BROWSER_TEST_P(SSLUITest, TestHTTPSExpiredCertGoBackUsingCommand) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestHTTPSExpiredCertGoBackUsingCommand) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_expired_.Start()); @@ -1790,79 +1693,18 @@ CheckAuthenticationBrokenState(tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL); - if (AreCommittedInterstitialsEnabled()) { - content::WindowedNotificationObserver observer( - content::NOTIFICATION_LOAD_STOP, - content::Source<NavigationController>(&tab->GetController())); - SendInterstitialCommand(tab, security_interstitials::CMD_DONT_PROCEED); - observer.Wait(); - } else { - SendInterstitialCommand(tab, security_interstitials::CMD_DONT_PROCEED); - } + content::WindowedNotificationObserver observer( + content::NOTIFICATION_LOAD_STOP, + content::Source<NavigationController>(&tab->GetController())); + SendInterstitialCommand(tab, security_interstitials::CMD_DONT_PROCEED); + observer.Wait(); // We should be back at the original good page. CheckUnauthenticatedState(tab, AuthState::NONE); } -// Visits a page with https error and then goes forward using GoToOffset. -// -// This test is not enabled for committed interstitials because committed -// interstitials wipe out forward history like other committed navigations and -// committed error pages. -IN_PROC_BROWSER_TEST_F(SSLUITestBase, TestHTTPSExpiredCertAndGoForward) { - if (AreCommittedInterstitialsEnabled()) - return; - ASSERT_TRUE(embedded_test_server()->Start()); - ASSERT_TRUE(https_server_expired_.Start()); - - // First navigate to two HTTP pages. - ui_test_utils::NavigateToURL( - browser(), embedded_test_server()->GetURL("/ssl/google.html")); - WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); - NavigationEntry* entry1 = tab->GetController().GetLastCommittedEntry(); - ASSERT_TRUE(entry1); - ui_test_utils::NavigateToURL( - browser(), embedded_test_server()->GetURL("/ssl/blank_page.html")); - NavigationEntry* entry2 = tab->GetController().GetLastCommittedEntry(); - ASSERT_TRUE(entry2); - - // Now go back so that a page is in the forward history. - { - content::WindowedNotificationObserver observer( - content::NOTIFICATION_LOAD_STOP, - content::Source<NavigationController>(&tab->GetController())); - tab->GetController().GoBack(); - observer.Wait(); - } - ASSERT_TRUE(tab->GetController().CanGoForward()); - NavigationEntry* entry3 = tab->GetController().GetLastCommittedEntry(); - ASSERT_TRUE(entry1 == entry3); - - // Now go to a bad HTTPS page that shows an interstitial. - ui_test_utils::NavigateToURL( - browser(), https_server_expired_.GetURL("/ssl/google.html")); - CheckAuthenticationBrokenState(tab, net::CERT_STATUS_DATE_INVALID, - AuthState::SHOWING_INTERSTITIAL); - - // Simulate user clicking and holding on forward button. - { - content::WindowedNotificationObserver observer( - content::NOTIFICATION_LOAD_STOP, - content::Source<NavigationController>(&tab->GetController())); - tab->GetController().GoToOffset(1); - observer.Wait(); - } - - // We should be showing the second good page. - EXPECT_FALSE(IsShowingInterstitial(tab)); - CheckUnauthenticatedState(tab, AuthState::NONE); - EXPECT_FALSE(tab->GetController().CanGoForward()); - NavigationEntry* entry4 = tab->GetController().GetLastCommittedEntry(); - EXPECT_TRUE(entry2 == entry4); -} - // Visits a page with revocation checking enabled and a valid OCSP response. -IN_PROC_BROWSER_TEST_P(SSLUITest, TestHTTPSOCSPOk) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestHTTPSOCSPOk) { // OCSP checking is disabled by default. EXPECT_FALSE(last_ssl_config_.rev_checking_enabled); EXPECT_FALSE(CreateDefaultNetworkContextParams() @@ -1900,7 +1742,7 @@ } // Visits a page with revocation checking enabled and a revoked OCSP response. -IN_PROC_BROWSER_TEST_P(SSLUITest, TestHTTPSOCSPRevoked) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestHTTPSOCSPRevoked) { // OCSP checking is disabled by default. EXPECT_FALSE(last_ssl_config_.rev_checking_enabled); EXPECT_FALSE(CreateDefaultNetworkContextParams() @@ -1931,7 +1773,7 @@ // Visits a page with revocation checking set to the default value (disabled) // and a revoked OCSP response. -IN_PROC_BROWSER_TEST_P(SSLUITest, TestHTTPSOCSPRevokedButNotChecked) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestHTTPSOCSPRevokedButNotChecked) { // OCSP checking is disabled by default. EXPECT_FALSE(last_ssl_config_.rev_checking_enabled); EXPECT_FALSE(CreateDefaultNetworkContextParams() @@ -1957,7 +1799,7 @@ // Visits a page that uses a SHA-1 leaf certificate, which should be rejected // by default. -IN_PROC_BROWSER_TEST_P(SSLUITest, SHA1IsDefaultDisabled) { +IN_PROC_BROWSER_TEST_F(SSLUITest, SHA1IsDefaultDisabled) { EXPECT_FALSE(last_ssl_config_.sha1_local_anchors_enabled); EXPECT_FALSE(CreateDefaultNetworkContextParams() ->initial_ssl_config->sha1_local_anchors_enabled); @@ -1976,7 +1818,7 @@ // there is currently no way to simulate navigation to a page that will // meaningfully test that Symantec enforcement is actually applied to the // request. -IN_PROC_BROWSER_TEST_P(SSLUITest, SymantecEnforcementIsNotDisabled) { +IN_PROC_BROWSER_TEST_F(SSLUITest, SymantecEnforcementIsNotDisabled) { EXPECT_FALSE(last_ssl_config_.symantec_enforcement_disabled); EXPECT_FALSE(CreateDefaultNetworkContextParams() ->initial_ssl_config->symantec_enforcement_disabled); @@ -2117,7 +1959,7 @@ // Visit a HTTP page which request WSS connection to a server providing invalid // certificate. Close the page while WSS connection waits for SSLManager's // response from UI thread. -IN_PROC_BROWSER_TEST_P(SSLUITest, TestWSSInvalidCertAndClose) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestWSSInvalidCertAndClose) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(wss_server_expired_.Start()); @@ -2164,7 +2006,7 @@ // Visit a HTTPS page and proceeds despite an invalid certificate. The page // requests WSS connection to the same origin host to check if WSS connection // share certificates policy with HTTPS correcly. -IN_PROC_BROWSER_TEST_P(SSLUITest, TestWSSInvalidCert) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestWSSInvalidCert) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(wss_server_expired_.Start()); @@ -2194,7 +2036,7 @@ // Ensure that non-standard origins are marked as neutral when the // MarkNonSecureAs Dangerous flag is enabled. -IN_PROC_BROWSER_TEST_P(SSLUITest, MarkFileAsNonSecure) { +IN_PROC_BROWSER_TEST_F(SSLUITest, MarkFileAsNonSecure) { base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndEnableFeatureWithParameters( security_state::features::kMarkHttpAsFeature, @@ -2215,7 +2057,7 @@ // Ensure that about-protocol origins are marked as neutral when the // MarkNonSecureAs Dangerous flag is enabled. -IN_PROC_BROWSER_TEST_P(SSLUITest, MarkAboutAsNonSecure) { +IN_PROC_BROWSER_TEST_F(SSLUITest, MarkAboutAsNonSecure) { base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndEnableFeatureWithParameters( security_state::features::kMarkHttpAsFeature, @@ -2235,7 +2077,7 @@ } // Data URLs should always be marked as non-secure. -IN_PROC_BROWSER_TEST_P(SSLUITest, MarkDataAsNonSecure) { +IN_PROC_BROWSER_TEST_F(SSLUITest, MarkDataAsNonSecure) { content::WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_TRUE(contents); @@ -2250,7 +2092,7 @@ // Ensure that HTTP-protocol origins are marked as Dangerous when the // MarkNonSecureAs Dangerous flag is enabled. -IN_PROC_BROWSER_TEST_P(SSLUITest, MarkHTTPAsDangerous) { +IN_PROC_BROWSER_TEST_F(SSLUITest, MarkHTTPAsDangerous) { base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndEnableFeatureWithParameters( security_state::features::kMarkHttpAsFeature, @@ -2274,7 +2116,7 @@ // Ensure that blob-protocol origins are marked as neutral when the // MarkNonSecureAs Dangerous flag is enabled. -IN_PROC_BROWSER_TEST_P(SSLUITest, MarkBlobAsNonSecure) { +IN_PROC_BROWSER_TEST_F(SSLUITest, MarkBlobAsNonSecure) { base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndEnableFeatureWithParameters( security_state::features::kMarkHttpAsFeature, @@ -2448,7 +2290,7 @@ return std::unique_ptr<net::ClientCertStore>(new ClientCertStoreStub({})); } -IN_PROC_BROWSER_TEST_P(SSLUITest, TestBrowserUseClientCertStore) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestBrowserUseClientCertStore) { // Make the browser use the ClientCertStoreStub instead of the regular one. ProfileIOData::FromResourceContext(browser()->profile()->GetResourceContext()) ->set_client_cert_store_factory_for_testing(base::Bind(&CreateCertStore)); @@ -2483,7 +2325,7 @@ EXPECT_EQ("pass", tab->GetLastCommittedURL().ref()); } -IN_PROC_BROWSER_TEST_P(SSLUITest, TestClientAuthSigningFails) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestClientAuthSigningFails) { // Make the browser use the ClientCertStoreStub instead of the regular one. ProfileIOData::FromResourceContext(browser()->profile()->GetResourceContext()) ->set_client_cert_store_factory_for_testing( @@ -2520,7 +2362,7 @@ EXPECT_EQ("", tab->GetLastCommittedURL().ref()); } -IN_PROC_BROWSER_TEST_P(SSLUITest, TestClientAuthContinueWithoutCert) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestClientAuthContinueWithoutCert) { // Make the browser use a ClientCertStoreStub that returns no certs. ProfileIOData::FromResourceContext(browser()->profile()->GetResourceContext()) ->set_client_cert_store_factory_for_testing( @@ -2546,7 +2388,7 @@ EXPECT_EQ("", tab->GetLastCommittedURL().ref()); } -IN_PROC_BROWSER_TEST_P(SSLUITest, TestCertDBChangedFlushesClientAuthCache) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestCertDBChangedFlushesClientAuthCache) { // Make the browser use the ClientCertStoreStub instead of the regular one. ProfileIOData::FromResourceContext(browser()->profile()->GetResourceContext()) ->set_client_cert_store_factory_for_testing( @@ -2615,7 +2457,7 @@ // link with a blank target). This is to test that the lack of navigation entry // does not cause any problems (it was causing a crasher, see // http://crbug.com/19941). -IN_PROC_BROWSER_TEST_P(SSLUITest, TestHTTPSErrorWithNoNavEntry) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestHTTPSErrorWithNoNavEntry) { ASSERT_TRUE(https_server_expired_.Start()); const GURL url = https_server_expired_.GetURL("/ssl/google.htm"); @@ -2631,7 +2473,7 @@ ASSERT_NO_FATAL_FAILURE(ExpectSSLInterstitial(tab2)); } -IN_PROC_BROWSER_TEST_P(SSLUITest, TestBadHTTPSDownload) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestBadHTTPSDownload) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_expired_.Start()); GURL url_non_dangerous = embedded_test_server()->GetURL("/title1.html"); @@ -2685,7 +2527,7 @@ // // Visits a page that displays insecure content. -IN_PROC_BROWSER_TEST_P(SSLUITest, TestDisplaysInsecureContent) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestDisplaysInsecureContent) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_.Start()); @@ -2703,7 +2545,7 @@ } // Visits a page that displays an insecure form. -IN_PROC_BROWSER_TEST_P(SSLUITest, TestDisplaysInsecureForm) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestDisplaysInsecureForm) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_.Start()); @@ -2721,7 +2563,7 @@ // Test that a report is sent if the user closes the tab on an interstitial // before making a decision to proceed or go back. -IN_PROC_BROWSER_TEST_P(SSLUITestWithExtendedReporting, +IN_PROC_BROWSER_TEST_F(SSLUITestWithExtendedReporting, TestBrokenHTTPSReportingCloseTab) { ASSERT_TRUE(https_server_expired_.Start()); @@ -2764,7 +2606,7 @@ // Test that if the user proceeds and the checkbox is checked, a report // is sent or not sent depending on the Finch config. -IN_PROC_BROWSER_TEST_P(SSLUITestWithExtendedReporting, +IN_PROC_BROWSER_TEST_F(SSLUITestWithExtendedReporting, TestBrokenHTTPSProceedReporting) { certificate_reporting_test_utils::ExpectReport expect_report = certificate_reporting_test_utils::GetReportExpectedFromFinch(); @@ -2775,7 +2617,7 @@ // Test that if the user goes back and the checkbox is checked, a report // is sent or not sent depending on the Finch config. -IN_PROC_BROWSER_TEST_P(SSLUITestWithExtendedReporting, +IN_PROC_BROWSER_TEST_F(SSLUITestWithExtendedReporting, TestBrokenHTTPSGoBackReporting) { certificate_reporting_test_utils::ExpectReport expect_report = certificate_reporting_test_utils::GetReportExpectedFromFinch(); @@ -2786,7 +2628,7 @@ // User proceeds, checkbox is shown but unchecked. Reports should never // be sent, regardless of Finch config. -IN_PROC_BROWSER_TEST_P(SSLUITestWithExtendedReporting, +IN_PROC_BROWSER_TEST_F(SSLUITestWithExtendedReporting, TestBrokenHTTPSProceedReportingWithNoOptIn) { TestBrokenHTTPSReporting( certificate_reporting_test_utils::EXTENDED_REPORTING_DO_NOT_OPT_IN, @@ -2796,7 +2638,7 @@ // User goes back, checkbox is shown but unchecked. Reports should never // be sent, regardless of Finch config. -IN_PROC_BROWSER_TEST_P(SSLUITestWithExtendedReporting, +IN_PROC_BROWSER_TEST_F(SSLUITestWithExtendedReporting, TestBrokenHTTPSGoBackShowYesCheckNoParamYesReportNo) { TestBrokenHTTPSReporting( certificate_reporting_test_utils::EXTENDED_REPORTING_DO_NOT_OPT_IN, @@ -2806,7 +2648,7 @@ // User proceeds, checkbox is not shown but checked -> we expect no // report. -IN_PROC_BROWSER_TEST_P(SSLUITestWithExtendedReporting, +IN_PROC_BROWSER_TEST_F(SSLUITestWithExtendedReporting, TestBrokenHTTPSProceedShowNoCheckYesReportNo) { if (base::FieldTrialList::FindFullName( CertReportHelper::kFinchExperimentName) == @@ -2820,7 +2662,7 @@ // Browser is incognito, user proceeds, checkbox has previously opted in // -> no report, regardless of Finch config. -IN_PROC_BROWSER_TEST_P(SSLUITestWithExtendedReporting, +IN_PROC_BROWSER_TEST_F(SSLUITestWithExtendedReporting, TestBrokenHTTPSInIncognitoReportNo) { TestBrokenHTTPSReporting( certificate_reporting_test_utils::EXTENDED_REPORTING_OPT_IN, @@ -2831,7 +2673,7 @@ // Test that reports don't get sent when extended reporting opt-in is // disabled by policy. -IN_PROC_BROWSER_TEST_P(SSLUITestWithExtendedReporting, +IN_PROC_BROWSER_TEST_F(SSLUITestWithExtendedReporting, TestBrokenHTTPSNoReportingWhenDisallowed) { browser()->profile()->GetPrefs()->SetBoolean( prefs::kSafeBrowsingExtendedReportingOptInAllowed, false); @@ -2843,7 +2685,7 @@ // Checkbox is shown but unchecked. Reports should never be sent, regardless of // Finch config. -IN_PROC_BROWSER_TEST_P(SSLUITestWithExtendedReporting, +IN_PROC_BROWSER_TEST_F(SSLUITestWithExtendedReporting, TestBadClockReportingWithNoOptIn) { TestBadClockReporting( certificate_reporting_test_utils::EXTENDED_REPORTING_DO_NOT_OPT_IN, @@ -2852,7 +2694,7 @@ // Test that when the interstitial closes and the checkbox is checked, a report // is sent or not sent depending on the Finch config. -IN_PROC_BROWSER_TEST_P(SSLUITestWithExtendedReporting, +IN_PROC_BROWSER_TEST_F(SSLUITestWithExtendedReporting, TestBadClockReportingWithOptIn) { certificate_reporting_test_utils::ExpectReport expect_report = certificate_reporting_test_utils::GetReportExpectedFromFinch(); @@ -2864,7 +2706,7 @@ // Visits a page that runs insecure content and tries to suppress the insecure // content warnings by randomizing location.hash. // Based on http://crbug.com/8706 -IN_PROC_BROWSER_TEST_P(SSLUITest, TestRunsInsecuredContentRandomizeHash) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestRunsInsecuredContentRandomizeHash) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_.Start()); @@ -2881,7 +2723,7 @@ // - For the good SSL case, the iframe and images should be properly displayed. // - For the bad SSL case, the iframe contents shouldn't be displayed and images // and scripts should be filtered out entirely. -IN_PROC_BROWSER_TEST_P(SSLUITest, TestUnsafeContents) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestUnsafeContents) { ASSERT_TRUE(https_server_.Start()); ASSERT_TRUE(https_server_expired_.Start()); // Enable popups without user gesture. @@ -2953,7 +2795,7 @@ #define MAYBE_TestDisplaysInsecureContentLoadedFromJS \ TestDisplaysInsecureContentLoadedFromJS #endif -IN_PROC_BROWSER_TEST_P(SSLUITest, +IN_PROC_BROWSER_TEST_F(SSLUITest, MAYBE_TestDisplaysInsecureContentLoadedFromJS) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_.Start()); @@ -2983,7 +2825,7 @@ // Visits two pages from the same origin: one that displays insecure content and // one that doesn't. The test checks that we do not propagate the insecure // content state from one to the other. -IN_PROC_BROWSER_TEST_P(SSLUITest, TestDisplaysInsecureContentTwoTabs) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestDisplaysInsecureContentTwoTabs) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_.Start()); @@ -3023,7 +2865,7 @@ // Visits two pages from the same origin: one that runs insecure content and one // that doesn't. The test checks that we propagate the insecure content state // from one to the other. -IN_PROC_BROWSER_TEST_P(SSLUITest, TestRunsInsecureContentTwoTabs) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestRunsInsecureContentTwoTabs) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_.Start()); @@ -3070,7 +2912,7 @@ // Visits a page with an image over http. Visits another page over https // referencing that same image over http (hoping it is coming from the webcore // memory cache). -IN_PROC_BROWSER_TEST_P(SSLUITest, TestDisplaysCachedInsecureContent) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestDisplaysCachedInsecureContent) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_.Start()); @@ -3095,7 +2937,7 @@ // Visits a page with script over http. Visits another page over https // referencing that same script over http (hoping it is coming from the webcore // memory cache). -IN_PROC_BROWSER_TEST_P(SSLUITest, TestRunsCachedInsecureContent) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestRunsCachedInsecureContent) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_.Start()); @@ -3120,7 +2962,7 @@ // This test ensures the CN invalid status does not 'stick' to a certificate // (see bug #1044942) and that it depends on the host-name. // Test if disabled due to flakiness http://crbug.com/368280 . -IN_PROC_BROWSER_TEST_P(SSLUITest, DISABLED_TestCNInvalidStickiness) { +IN_PROC_BROWSER_TEST_F(SSLUITest, DISABLED_TestCNInvalidStickiness) { ASSERT_TRUE(https_server_.Start()); ASSERT_TRUE(https_server_mismatched_.Start()); @@ -3154,7 +2996,7 @@ } // Test that navigating to a #ref does not change a bad security state. -IN_PROC_BROWSER_TEST_P(SSLUITest, TestRefNavigation) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestRefNavigation) { ASSERT_TRUE(https_server_expired_.Start()); ui_test_utils::NavigateToURL( @@ -3179,7 +3021,7 @@ // Tests that closing a page that opened a pop-up with an interstitial does not // crash the browser (crbug.com/1966). -IN_PROC_BROWSER_TEST_P(SSLUITest, TestCloseTabWithUnsafePopup) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestCloseTabWithUnsafePopup) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_expired_.Start()); @@ -3209,15 +3051,8 @@ Browser* popup_browser = chrome::FindBrowserWithProfile(browser()->profile()); WebContents* popup = popup_browser->tab_strip_model()->GetActiveWebContents(); EXPECT_NE(popup, tab1); - if (AreCommittedInterstitialsEnabled()) - nav_observer.Wait(); + nav_observer.Wait(); WaitForInterstitial(popup); - // Since the popup is showing an interstitial, it shouldn't have a last - // committed entry (except when committed interstitials are enabled, in which - // case an interstitial is a committed entry). - if (!AreCommittedInterstitialsEnabled()) { - EXPECT_FALSE(popup->GetController().GetLastCommittedEntry()); - } ASSERT_TRUE(popup->GetController().GetVisibleEntry()); EXPECT_EQ(https_server_expired_.GetURL("/ssl/bad_iframe.html"), popup->GetController().GetVisibleEntry()->GetURL()); @@ -3237,7 +3072,7 @@ } // Visit a page over bad https that is a redirect to a page with good https. -IN_PROC_BROWSER_TEST_P(SSLUITest, TestRedirectBadToGoodHTTPS) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestRedirectBadToGoodHTTPS) { ASSERT_TRUE(https_server_.Start()); ASSERT_TRUE(https_server_expired_.Start()); @@ -3258,7 +3093,7 @@ } // Visit a page over good https that is a redirect to a page with bad https. -IN_PROC_BROWSER_TEST_P(SSLUITest, TestRedirectGoodToBadHTTPS) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestRedirectGoodToBadHTTPS) { ASSERT_TRUE(https_server_.Start()); ASSERT_TRUE(https_server_expired_.Start()); @@ -3278,7 +3113,7 @@ } // Visit a page over http that is a redirect to a page with good HTTPS. -IN_PROC_BROWSER_TEST_P(SSLUITest, TestRedirectHTTPToGoodHTTPS) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestRedirectHTTPToGoodHTTPS) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_.Start()); @@ -3294,7 +3129,7 @@ } // Visit a page over http that is a redirect to a page with bad HTTPS. -IN_PROC_BROWSER_TEST_P(SSLUITest, TestRedirectHTTPToBadHTTPS) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestRedirectHTTPToBadHTTPS) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_expired_.Start()); @@ -3316,7 +3151,7 @@ // Visit a page over https that is a redirect to a page with http (to make sure // we don't keep the secure state). -IN_PROC_BROWSER_TEST_P(SSLUITest, TestRedirectHTTPSToHTTP) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestRedirectHTTPSToHTTP) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_.Start()); @@ -3370,13 +3205,9 @@ DISALLOW_COPY_AND_ASSIGN(SSLUITestWaitForDOMNotification); }; -INSTANTIATE_TEST_SUITE_P(, - SSLUITestWaitForDOMNotification, - ::testing::Values(false, true)); - // Tests that a mixed resource which includes HTTP in the redirect chain // is marked as mixed content, even if the end result is HTTPS. -IN_PROC_BROWSER_TEST_P(SSLUITestWaitForDOMNotification, +IN_PROC_BROWSER_TEST_F(SSLUITestWaitForDOMNotification, TestMixedContentWithHTTPInRedirectChain) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_.Start()); @@ -3433,7 +3264,7 @@ // Visits a page to which we could not connect (bad port) over http and https // and make sure the security style is correct. -IN_PROC_BROWSER_TEST_P(SSLUITest, TestConnectToBadPort) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestConnectToBadPort) { ui_test_utils::NavigateToURL(browser(), GURL("http://localhost:17")); CheckUnauthenticatedState( browser()->tab_strip_model()->GetActiveWebContents(), @@ -3455,7 +3286,7 @@ // - navigate to a bad HTTPS (expect unsafe content and filtered frame), then // back // - navigate to HTTP (expect insecure content), then back -IN_PROC_BROWSER_TEST_P(SSLUITest, TestGoodFrameNavigation) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestGoodFrameNavigation) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_.Start()); ASSERT_TRUE(https_server_expired_.Start()); @@ -3562,7 +3393,7 @@ // From a bad HTTPS top frame: // - navigate to an OK HTTPS frame (expected to be still authentication broken). -IN_PROC_BROWSER_TEST_P(SSLUITest, TestBadFrameNavigation) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestBadFrameNavigation) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_.Start()); ASSERT_TRUE(https_server_expired_.Start()); @@ -3596,7 +3427,7 @@ // From an HTTP top frame, navigate to good and bad HTTPS (security state should // stay unauthenticated). -IN_PROC_BROWSER_TEST_P(SSLUITest, TestUnauthenticatedFrameNavigation) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestUnauthenticatedFrameNavigation) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_.Start()); ASSERT_TRUE(https_server_expired_.Start()); @@ -3656,10 +3487,9 @@ enum class OffMainThreadFetchMode { kEnabled, kDisabled }; enum class SSLUIWorkerFetchTestType { kUseFetch, kUseImportScripts }; -class SSLUIWorkerFetchTest : public testing::WithParamInterface< - std::pair<SSLUIWorkerFetchTestType, - bool /* committed interstitials */>>, - public SSLUITestBase { +class SSLUIWorkerFetchTest + : public testing::WithParamInterface<SSLUIWorkerFetchTestType>, + public SSLUITestBase { public: SSLUIWorkerFetchTest() { EXPECT_TRUE(tmp_dir_.CreateUniqueTempDir()); @@ -3669,10 +3499,6 @@ void SetUpOnMainThread() override { SSLUITestBase::SetUpOnMainThread(); - if (GetParam().second) { - scoped_feature_list_.InitAndEnableFeature( - features::kSSLCommittedInterstitials); - } } protected: @@ -3693,7 +3519,7 @@ " 'message'," " event => { document.title = event.data; });" "</script>"); - switch (GetParam().first) { + switch (GetParam()) { case SSLUIWorkerFetchTestType::kUseFetch: WriteFile(FILE_PATH_LITERAL("worker_test_data.txt.mock-http-headers"), "HTTP/1.1 200 OK\n" @@ -3906,25 +3732,23 @@ WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); CheckAuthenticationBrokenState(tab, net::CERT_STATUS_COMMON_NAME_INVALID, AuthState::SHOWING_INTERSTITIAL); - if (AreCommittedInterstitialsEnabled()) { - content::TestNavigationObserver nav_observer(tab, 1); - security_interstitials::SecurityInterstitialTabHelper* helper = - security_interstitials::SecurityInterstitialTabHelper::FromWebContents( - tab); - helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting() - ->CommandReceived( - base::NumberToString(security_interstitials::CMD_PROCEED)); - nav_observer.Wait(); - } else { - ProceedThroughInterstitial(tab); - } + content::TestNavigationObserver nav_observer(tab, 1); + security_interstitials::SecurityInterstitialTabHelper* helper = + security_interstitials::SecurityInterstitialTabHelper::FromWebContents( + tab); + helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting() + ->CommandReceived( + base::NumberToString(security_interstitials::CMD_PROCEED)); + nav_observer.Wait(); + CheckAuthenticationBrokenState(tab, net::CERT_STATUS_COMMON_NAME_INVALID, AuthState::NONE); - SecurityStateTabHelper* helper = SecurityStateTabHelper::FromWebContents(tab); - ASSERT_TRUE(helper); + SecurityStateTabHelper* tab_helper = + SecurityStateTabHelper::FromWebContents(tab); + ASSERT_TRUE(tab_helper); std::unique_ptr<security_state::VisibleSecurityState> visible_security_state = - helper->GetVisibleSecurityState(); + tab_helper->GetVisibleSecurityState(); EXPECT_FALSE(visible_security_state->ran_mixed_content); EXPECT_FALSE(visible_security_state->displayed_mixed_content); EXPECT_FALSE(visible_security_state->ran_content_with_cert_errors); @@ -3944,7 +3768,7 @@ EXPECT_EQ(loaded_title, watcher.WaitAndGetTitle()); CheckAuthenticationBrokenState(tab, CertError::NONE, AuthState::NONE); - visible_security_state = helper->GetVisibleSecurityState(); + visible_security_state = tab_helper->GetVisibleSecurityState(); EXPECT_FALSE(visible_security_state->ran_mixed_content); EXPECT_FALSE(visible_security_state->displayed_mixed_content); EXPECT_TRUE(visible_security_state->ran_content_with_cert_errors); @@ -4123,11 +3947,9 @@ // which is started from a subframe are blocked if // allow_running_insecure_content setting is false or // strict_mixed_content_checking setting is true. -IN_PROC_BROWSER_TEST_P(SSLUIWorkerFetchTest, MixedContentSubFrame) { - // TODO(carlosil): Reenable tests once confirmed not flaky for committed - // interstitials. - if (AreCommittedInterstitialsEnabled()) - return; +// TODO(carlosil): Re-enable to check if this triggers flakiness due to +// committed interstitials. +IN_PROC_BROWSER_TEST_P(SSLUIWorkerFetchTest, DISABLED_MixedContentSubFrame) { ChromeContentBrowserClientForMixedContentTest browser_client; content::ContentBrowserClient* old_browser_client = content::SetBrowserClientForTesting(&browser_client); @@ -4187,20 +4009,13 @@ INSTANTIATE_TEST_SUITE_P( /* no prefix */, SSLUIWorkerFetchTest, - ::testing::Values( - std::make_pair(SSLUIWorkerFetchTestType::kUseFetch, - false /* committed interstitials */), - std::make_pair(SSLUIWorkerFetchTestType::kUseImportScripts, - false /* committed interstitials */), - std::make_pair(SSLUIWorkerFetchTestType::kUseFetch, - true /* committed interstitials */), - std::make_pair(SSLUIWorkerFetchTestType::kUseImportScripts, - true /* committed interstititals */))); + ::testing::Values(SSLUIWorkerFetchTestType::kUseFetch, + SSLUIWorkerFetchTestType::kUseImportScripts)); // Visits a page with unsafe content and makes sure that if a user exception // to the certificate error is present, the image is loaded and script // executes. -IN_PROC_BROWSER_TEST_P(SSLUITest, TestUnsafeContentsWithUserException) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestUnsafeContentsWithUserException) { WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_NO_FATAL_FAILURE(SetUpUnsafeContentsWithUserException( "/ssl/page_with_unsafe_contents.html")); @@ -4250,7 +4065,7 @@ } // Like the test above, but only displaying inactive content (an image). -IN_PROC_BROWSER_TEST_P(SSLUITest, TestUnsafeImageWithUserException) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestUnsafeImageWithUserException) { WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_NO_FATAL_FAILURE( SetUpUnsafeContentsWithUserException("/ssl/page_with_unsafe_image.html")); @@ -4277,7 +4092,7 @@ // Test that when the browser blocks displaying insecure content (iframes), // the indicator shows a secure page, because the blocking made the otherwise // unsafe page safe (the notification of this state is handled by other means) -IN_PROC_BROWSER_TEST_P(SSLUITestBlock, TestBlockDisplayingInsecureIframe) { +IN_PROC_BROWSER_TEST_F(SSLUITestBlock, TestBlockDisplayingInsecureIframe) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_.Start()); @@ -4296,7 +4111,7 @@ // indicator shows a secure page, because the blocking made the otherwise // unsafe page safe (the notification of this state is handled by other // means). -IN_PROC_BROWSER_TEST_P(SSLUITestBlock, TestBlockRunningInsecureContent) { +IN_PROC_BROWSER_TEST_F(SSLUITestBlock, TestBlockRunningInsecureContent) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_.Start()); @@ -4314,7 +4129,7 @@ // Visit a page and establish a WebSocket connection over bad https with // --ignore-certificate-errors. The connection should be established without // interstitial page showing. -IN_PROC_BROWSER_TEST_P(SSLUITestIgnoreCertErrors, TestWSS) { +IN_PROC_BROWSER_TEST_F(SSLUITestIgnoreCertErrors, TestWSS) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(wss_server_expired_.Start()); @@ -4342,7 +4157,7 @@ // --ignore-certificate-errors-spki-list. The connection should be established // without interstitial page showing. #if !defined(OS_CHROMEOS) // Chrome OS does not support the flag. -IN_PROC_BROWSER_TEST_P(SSLUITestIgnoreCertErrorsBySPKIWSS, TestWSSExpired) { +IN_PROC_BROWSER_TEST_F(SSLUITestIgnoreCertErrorsBySPKIWSS, TestWSSExpired) { ASSERT_TRUE(wss_server_expired_.Start()); // Setup page title observer. @@ -4369,7 +4184,7 @@ // Test that HTTPS pages with a bad certificate don't show an interstitial if // the public key matches a value from --ignore-certificate-errors-spki-list. #if !defined(OS_CHROMEOS) // Chrome OS does not support the flag. -IN_PROC_BROWSER_TEST_P(SSLUITestIgnoreCertErrorsBySPKIHTTPS, TestHTTPS) { +IN_PROC_BROWSER_TEST_F(SSLUITestIgnoreCertErrorsBySPKIHTTPS, TestHTTPS) { ASSERT_TRUE(https_server_mismatched_.Start()); WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); @@ -4390,7 +4205,7 @@ // Test subresources from an origin with a bad certificate are loaded if the // public key matches a value from --ignore-certificate-errors-spki-list. #if !defined(OS_CHROMEOS) // Chrome OS does not support the flag. -IN_PROC_BROWSER_TEST_P(SSLUITestIgnoreCertErrorsBySPKIHTTPS, +IN_PROC_BROWSER_TEST_F(SSLUITestIgnoreCertErrorsBySPKIHTTPS, TestInsecureSubresource) { ASSERT_TRUE(https_server_.Start()); ASSERT_TRUE(https_server_mismatched_.Start()); @@ -4415,7 +4230,7 @@ #endif // !defined(OS_CHROMEOS) // Verifies that the interstitial can proceed, even if JavaScript is disabled. -IN_PROC_BROWSER_TEST_P(SSLUITest, TestInterstitialJavaScriptProceeds) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestInterstitialJavaScriptProceeds) { HostContentSettingsMapFactory::GetForProfile(browser()->profile()) ->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_JAVASCRIPT, CONTENT_SETTING_BLOCK); @@ -4433,20 +4248,9 @@ content::WindowedNotificationObserver observer( content::NOTIFICATION_LOAD_STOP, content::Source<NavigationController>(&tab->GetController())); - if (AreCommittedInterstitialsEnabled()) { - const std::string javascript = - "window.certificateErrorPageController.proceed();"; - EXPECT_TRUE(content::ExecuteScript(tab, javascript)); - } else { - int result = security_interstitials::CMD_ERROR; - const std::string javascript = - base::StringPrintf("window.domAutomationController.send(%d);", - security_interstitials::CMD_PROCEED); - ASSERT_TRUE(content::ExecuteScriptAndExtractInt( - tab->GetInterstitialPage()->GetMainFrame(), javascript, &result)); - // The above will hang without the fix. - EXPECT_EQ(1, result); - } + const std::string javascript = + "window.certificateErrorPageController.proceed();"; + EXPECT_TRUE(content::ExecuteScript(tab, javascript)); observer.Wait(); CheckAuthenticationBrokenState(tab, net::CERT_STATUS_DATE_INVALID, AuthState::NONE); @@ -4454,7 +4258,7 @@ // Verifies that the interstitial can go back, even if JavaScript is disabled. // http://crbug.com/322948 -IN_PROC_BROWSER_TEST_P(SSLUITest, TestInterstitialJavaScriptGoesBack) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestInterstitialJavaScriptGoesBack) { HostContentSettingsMapFactory::GetForProfile(browser()->profile()) ->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_JAVASCRIPT, CONTENT_SETTING_BLOCK); @@ -4467,30 +4271,18 @@ AuthState::SHOWING_INTERSTITIAL); WaitForInterstitial(tab); ASSERT_NO_FATAL_FAILURE(ExpectSSLInterstitial(tab)); - if (AreCommittedInterstitialsEnabled()) { - content::WindowedNotificationObserver observer( - content::NOTIFICATION_LOAD_STOP, - content::Source<NavigationController>(&tab->GetController())); - const std::string javascript = - "window.certificateErrorPageController.dontProceed();"; - EXPECT_TRUE(content::ExecuteScript(tab, javascript)); - observer.Wait(); - } else { - int result = security_interstitials::CMD_ERROR; - const std::string javascript = - base::StringPrintf("window.domAutomationController.send(%d);", - security_interstitials::CMD_DONT_PROCEED); - ASSERT_TRUE(content::ExecuteScriptAndExtractInt( - tab->GetInterstitialPage()->GetMainFrame(), javascript, &result)); - // The above will hang without the fix. - EXPECT_EQ(0, result); - WaitForInterstitialDetach(tab); - } + content::WindowedNotificationObserver observer( + content::NOTIFICATION_LOAD_STOP, + content::Source<NavigationController>(&tab->GetController())); + const std::string javascript = + "window.certificateErrorPageController.dontProceed();"; + EXPECT_TRUE(content::ExecuteScript(tab, javascript)); + observer.Wait(); EXPECT_EQ("about:blank", tab->GetVisibleURL().spec()); } // Verifies that an overridable interstitial has a proceed link. -IN_PROC_BROWSER_TEST_P(SSLUITest, ProceedLinkOverridable) { +IN_PROC_BROWSER_TEST_F(SSLUITest, ProceedLinkOverridable) { ASSERT_TRUE(https_server_expired_.Start()); WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); ui_test_utils::NavigateToURL( @@ -4504,7 +4296,7 @@ ASSERT_NO_FATAL_FAILURE(CheckProceedLinkExists(tab)); } -IN_PROC_BROWSER_TEST_P(SSLUITest, TestLearnMoreLinkContainsErrorCode) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestLearnMoreLinkContainsErrorCode) { ASSERT_TRUE(https_server_expired_.Start()); // Navigate to a site that causes an interstitial. @@ -4523,24 +4315,9 @@ std::to_string(net::ERR_CERT_DATE_INVALID)); } -// Verifies that an overridable committed interstitial has a proceed link. -IN_PROC_BROWSER_TEST_P(SSLUITestCommitted, ProceedLinkOverridable) { - ASSERT_TRUE(https_server_expired_.Start()); - WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); - ui_test_utils::NavigateToURL( - browser(), https_server_expired_.GetURL("/ssl/google.html")); - - CheckSecurityState(tab, net::CERT_STATUS_DATE_INVALID, - security_state::DANGEROUS, AuthState::SHOWING_ERROR); - - ASSERT_NO_FATAL_FAILURE(ExpectSSLInterstitial(tab)); - - ASSERT_NO_FATAL_FAILURE(CheckProceedLinkExists(tab)); -} - // Checks that interstitials are not used for subframe SSL errors. Regression // test for https://crbug.com/808797. -IN_PROC_BROWSER_TEST_P(SSLUITestCommitted, SubframeCertError) { +IN_PROC_BROWSER_TEST_F(SSLUITest, SubframeCertError) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_expired_.Start()); WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); @@ -4573,7 +4350,7 @@ } // Verifies that a non-overridable interstitial does not have a proceed link. -IN_PROC_BROWSER_TEST_P(SSLUITestHSTS, TestInterstitialOptionsNonOverridable) { +IN_PROC_BROWSER_TEST_F(SSLUITestHSTS, TestInterstitialOptionsNonOverridable) { ASSERT_TRUE(https_server_expired_.Start()); WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); @@ -4599,17 +4376,14 @@ "? (%d) : (%d))", security_interstitials::CMD_TEXT_NOT_FOUND, security_interstitials::CMD_TEXT_FOUND); - ASSERT_TRUE(content::ExecuteScriptAndExtractInt( - AreCommittedInterstitialsEnabled() - ? tab->GetMainFrame() - : tab->GetInterstitialPage()->GetMainFrame(), - javascript, &result)); + ASSERT_TRUE(content::ExecuteScriptAndExtractInt(tab->GetMainFrame(), + javascript, &result)); EXPECT_EQ(security_interstitials::CMD_TEXT_NOT_FOUND, result); } // Verifies that links in the interstitial open in a new tab. // https://crbug.com/717616 -IN_PROC_BROWSER_TEST_P(SSLUITest, TestInterstitialLinksOpenInNewTab) { +IN_PROC_BROWSER_TEST_F(SSLUITest, TestInterstitialLinksOpenInNewTab) { ASSERT_TRUE(https_server_.Start()); ASSERT_TRUE(https_server_expired_.Start()); @@ -4656,7 +4430,7 @@ // Verifies that switching tabs, while showing interstitial page, will not // affect the visibility of the interstitial. // https://crbug.com/381439 -IN_PROC_BROWSER_TEST_P(SSLUITest, InterstitialNotAffectedByHideShow) { +IN_PROC_BROWSER_TEST_F(SSLUITest, InterstitialNotAffectedByHideShow) { ASSERT_TRUE(https_server_expired_.Start()); ASSERT_TRUE(https_server_.Start()); @@ -4684,7 +4458,7 @@ // through the interstitial, the decision to proceed is initially remembered. // However, if this is followed by another visit, and a good certificate // is seen for the same host, the original exception is forgotten. -IN_PROC_BROWSER_TEST_P(SSLUITest, BadCertFollowedByGoodCert) { +IN_PROC_BROWSER_TEST_F(SSLUITest, BadCertFollowedByGoodCert) { // It is necessary to use |https_server_expired_| rather than // |https_server_mismatched| because the former shares a host with // |https_server_| and cert exceptions are per host. @@ -4740,7 +4514,7 @@ // Tests that the SSLStatus of a navigation entry for an SSL // interstitial matches the navigation entry once the interstitial is // clicked through. https://crbug.com/529456 -IN_PROC_BROWSER_TEST_P(SSLUITest, +IN_PROC_BROWSER_TEST_F(SSLUITest, SSLStatusMatchesOnInterstitialAndAfterProceed) { ASSERT_TRUE(https_server_expired_.Start()); WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); @@ -4768,7 +4542,7 @@ // As above, but for a bad clock interstitial. Tests that a clock // interstitial's SSLStatus matches the SSLStatus of the HTTPS page // after proceeding through a normal SSL interstitial. -IN_PROC_BROWSER_TEST_P(SSLUITest, +IN_PROC_BROWSER_TEST_F(SSLUITest, SSLStatusMatchesonClockInterstitialAndAfterProceed) { ASSERT_TRUE(https_server_expired_.Start()); WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); @@ -4882,13 +4656,9 @@ DISALLOW_COPY_AND_ASSIGN(SSLNetworkTimeBrowserTest); }; -INSTANTIATE_TEST_SUITE_P(, - SSLNetworkTimeBrowserTest, - ::testing::Values(false, true)); - // Tests that if an on-demand network time fetch returns that the clock // is okay, a normal SSL interstitial is shown. -IN_PROC_BROWSER_TEST_P(SSLNetworkTimeBrowserTest, OnDemandFetchClockOk) { +IN_PROC_BROWSER_TEST_F(SSLNetworkTimeBrowserTest, OnDemandFetchClockOk) { ASSERT_TRUE(https_server_expired_.Start()); // Use a testing clock set to the time that GoodTimeResponseHandler // returns, to simulate the system clock matching the network time. @@ -4935,7 +4705,7 @@ // Tests that if an on-demand network time fetch returns that the clock // is wrong, a bad clock interstitial is shown. -IN_PROC_BROWSER_TEST_P(SSLNetworkTimeBrowserTest, OnDemandFetchClockWrong) { +IN_PROC_BROWSER_TEST_F(SSLNetworkTimeBrowserTest, OnDemandFetchClockWrong) { ASSERT_TRUE(https_server_expired_.Start()); // Use a testing clock set to a time that is different from what // GoodTimeResponseHandler returns, simulating a system clock that is @@ -4984,7 +4754,7 @@ // Tests that if the timeout expires before the network time fetch // returns, then a normal SSL interstitial is shown. -IN_PROC_BROWSER_TEST_P(SSLNetworkTimeBrowserTest, +IN_PROC_BROWSER_TEST_F(SSLNetworkTimeBrowserTest, TimeoutExpiresBeforeFetchCompletes) { ASSERT_TRUE(https_server_expired_.Start()); // Set the timer to fire immediately. @@ -5007,7 +4777,7 @@ // Tests that if the user stops the page load before either the network // time fetch completes or the timeout expires, then there is no interstitial. -IN_PROC_BROWSER_TEST_P(SSLNetworkTimeBrowserTest, StopBeforeTimeoutExpires) { +IN_PROC_BROWSER_TEST_F(SSLNetworkTimeBrowserTest, StopBeforeTimeoutExpires) { ASSERT_TRUE(https_server_expired_.Start()); // Set the timer to a long delay. SSLErrorHandler::SetInterstitialDelayForTesting( @@ -5044,7 +4814,7 @@ // Tests that if the user reloads the page before either the network // time fetch completes or the timeout expires, then there is no interstitial. -IN_PROC_BROWSER_TEST_P(SSLNetworkTimeBrowserTest, ReloadBeforeTimeoutExpires) { +IN_PROC_BROWSER_TEST_F(SSLNetworkTimeBrowserTest, ReloadBeforeTimeoutExpires) { ASSERT_TRUE(https_server_expired_.Start()); // Set the timer to a long delay. SSLErrorHandler::SetInterstitialDelayForTesting( @@ -5079,7 +4849,7 @@ // Tests that if the user navigates away before either the network time // fetch completes or the timeout expires, then there is no // interstitial. -IN_PROC_BROWSER_TEST_P(SSLNetworkTimeBrowserTest, +IN_PROC_BROWSER_TEST_F(SSLNetworkTimeBrowserTest, NavigateAwayBeforeTimeoutExpires) { ASSERT_TRUE(https_server_expired_.Start()); ASSERT_TRUE(https_server_.Start()); @@ -5116,7 +4886,7 @@ // Tests that if the user closes the tab before the network time fetch // completes, it doesn't cause a crash. -IN_PROC_BROWSER_TEST_P(SSLNetworkTimeBrowserTest, +IN_PROC_BROWSER_TEST_F(SSLNetworkTimeBrowserTest, CloseTabBeforeNetworkFetchCompletes) { ASSERT_TRUE(https_server_expired_.Start()); // Set the timer to fire immediately. @@ -5185,8 +4955,7 @@ } // namespace -class CommonNameMismatchBrowserTest : public CertVerifierBrowserTest, - public testing::WithParamInterface<bool> { +class CommonNameMismatchBrowserTest : public CertVerifierBrowserTest { public: CommonNameMismatchBrowserTest() : CertVerifierBrowserTest() {} @@ -5199,10 +4968,6 @@ void SetUpOnMainThread() override { CertVerifierBrowserTest::SetUpOnMainThread(); - if (GetParam()) { - scoped_feature_list_.InitAndEnableFeature( - features::kSSLCommittedInterstitials); - } host_resolver()->AddRule("*", "127.0.0.1"); base::PostTaskWithTraits( FROM_HERE, {content::BrowserThread::IO}, @@ -5219,14 +4984,10 @@ base::test::ScopedFeatureList scoped_feature_list_; }; -INSTANTIATE_TEST_SUITE_P(, - CommonNameMismatchBrowserTest, - ::testing::Values(false, true)); - // Visit the URL www.mail.example.com on a server that presents a valid // certificate for mail.example.com. Verify that the page navigates to // mail.example.com. -IN_PROC_BROWSER_TEST_P(CommonNameMismatchBrowserTest, +IN_PROC_BROWSER_TEST_F(CommonNameMismatchBrowserTest, ShouldShowWWWSubdomainMismatchInterstitial) { net::EmbeddedTestServer https_server_example_domain( net::EmbeddedTestServer::TYPE_HTTPS); @@ -5283,7 +5044,7 @@ // Visit the URL www.mail.example.com on a server that presents an invalid // certificate for mail.example.com. Verify that the page shows an interstitial // for www.mail.example.com with no crash. -IN_PROC_BROWSER_TEST_P(CommonNameMismatchBrowserTest, +IN_PROC_BROWSER_TEST_F(CommonNameMismatchBrowserTest, NoCrashIfBothSubdomainsHaveCommonNameErrors) { net::EmbeddedTestServer https_server_example_domain( net::EmbeddedTestServer::TYPE_HTTPS); @@ -5335,7 +5096,7 @@ // Visit the URL example.org on a server that presents a valid certificate // for www.example.org. Verify that the page redirects to www.example.org. -IN_PROC_BROWSER_TEST_P(CommonNameMismatchBrowserTest, +IN_PROC_BROWSER_TEST_F(CommonNameMismatchBrowserTest, CheckWWWSubdomainMismatchInverse) { net::EmbeddedTestServer https_server_example_domain( net::EmbeddedTestServer::TYPE_HTTPS); @@ -5401,7 +5162,7 @@ // valid certificate for www.example.org. In this case, www.example.org // redirects to http://example.org, and the SSL error should not be redirected // to this URL. -IN_PROC_BROWSER_TEST_P(CommonNameMismatchBrowserTest, +IN_PROC_BROWSER_TEST_F(CommonNameMismatchBrowserTest, WWWSubdomainMismatch_StopOnRedirects) { net::EmbeddedTestServer https_server_example_domain( net::EmbeddedTestServer::TYPE_HTTPS); @@ -5464,7 +5225,7 @@ // - No suggested URL check results arrive, causing the tab to appear as loading // indefinitely (also because the timer has a long timeout). // - Stopping the page load shouldn't result in any interstitials. -IN_PROC_BROWSER_TEST_P(CommonNameMismatchBrowserTest, +IN_PROC_BROWSER_TEST_F(CommonNameMismatchBrowserTest, InterstitialStopNavigationWhileLoading) { net::EmbeddedTestServer https_server_example_domain( net::EmbeddedTestServer::TYPE_HTTPS); @@ -5527,7 +5288,7 @@ // Same as above, but instead of stopping, the loading page is reloaded. The end // result is the same. (i.e. page load stops, no interstitials shown) -IN_PROC_BROWSER_TEST_P(CommonNameMismatchBrowserTest, +IN_PROC_BROWSER_TEST_F(CommonNameMismatchBrowserTest, InterstitialReloadNavigationWhileLoading) { net::EmbeddedTestServer https_server_example_domain( net::EmbeddedTestServer::TYPE_HTTPS); @@ -5588,7 +5349,7 @@ // Same as above, but instead of reloading, the page is navigated away. The // new page should load, and no interstitials should be shown. -IN_PROC_BROWSER_TEST_P(CommonNameMismatchBrowserTest, +IN_PROC_BROWSER_TEST_F(CommonNameMismatchBrowserTest, InterstitialNavigateAwayWhileLoading) { net::EmbeddedTestServer https_server_example_domain( net::EmbeddedTestServer::TYPE_HTTPS); @@ -5694,7 +5455,7 @@ AuthState::SHOWING_INTERSTITIAL); } -IN_PROC_BROWSER_TEST_P(SSLUITest, RestoreHasSSLState) { +IN_PROC_BROWSER_TEST_F(SSLUITest, RestoreHasSSLState) { ASSERT_TRUE(https_server_.Start()); GURL url(https_server_.GetURL("/ssl/google.html")); ui_test_utils::NavigateToURL(browser(), url); @@ -5762,7 +5523,7 @@ // Simulate a browser-initiated in-page navigation in a restored tab. // https://crbug.com/662267 -IN_PROC_BROWSER_TEST_P(SSLUITest, +IN_PROC_BROWSER_TEST_F(SSLUITest, BrowserInitiatedExistingPageAfterRestoreHasSSLState) { SetupRestoredTabWithNavigation(&https_server_, browser()); WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); @@ -5774,7 +5535,7 @@ } // Simulate a renderer-initiated in-page navigation in a restored tab. -IN_PROC_BROWSER_TEST_P(SSLUITest, +IN_PROC_BROWSER_TEST_F(SSLUITest, RendererInitiatedExistingPageAfterRestoreHasSSLState) { SetupRestoredTabWithNavigation(&https_server_, browser()); WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); @@ -5815,7 +5576,7 @@ // Check that SSL state isn't stale when navigating to an existing page that // gives a different response. This covers the case of going from http to // https. http://crbug.com/792221 -IN_PROC_BROWSER_TEST_P(SSLUITest, ExistingPageHTTPToHTTPSSSLState) { +IN_PROC_BROWSER_TEST_F(SSLUITest, ExistingPageHTTPToHTTPSSSLState) { ASSERT_TRUE(https_server_.Start()); int count = 0; std::string relative_url = "/foo"; @@ -5839,7 +5600,7 @@ // Check that SSL state isn't stale when navigating to an existing page that // gives a different response. This covers the case of going from https to // http URL. http://crbug.com/792221 -IN_PROC_BROWSER_TEST_P(SSLUITest, ExistingPageHTTPSToHTTPSSLState) { +IN_PROC_BROWSER_TEST_F(SSLUITest, ExistingPageHTTPSToHTTPSSLState) { ASSERT_TRUE(embedded_test_server()->Start()); int count = 0; std::string relative_url = "/foo"; @@ -5869,7 +5630,7 @@ // Checks that a restore followed immediately by a history navigation doesn't // lose SSL state. // Disabled since this is a test for bug 738177. -IN_PROC_BROWSER_TEST_P(SSLUITest, DISABLED_RestoreThenNavigateHasSSLState) { +IN_PROC_BROWSER_TEST_F(SSLUITest, DISABLED_RestoreThenNavigateHasSSLState) { ASSERT_TRUE(https_server_.Start()); GURL url1(https_server_.GetURL("/ssl/google.html")); GURL url2(https_server_.GetURL("/ssl/page_with_refs.html")); @@ -5896,7 +5657,7 @@ // could happen when the user's login is expired and the server redirects them // to a login page. This will be considered a same document navigation but we // do want to update the SSL state. -IN_PROC_BROWSER_TEST_P(SSLUITest, SameDocumentHasSSLState) { +IN_PROC_BROWSER_TEST_F(SSLUITest, SameDocumentHasSSLState) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_.Start()); @@ -5937,7 +5698,7 @@ // clicking a bookmark with an anchor hash twice). As this is a same document // navigation, the SSL state should be left intact despite not triggering a // network request. Regression test for https://crbug.com/877618. -IN_PROC_BROWSER_TEST_P(SSLUITest, SameDocumentHasSSLStateNoLoad) { +IN_PROC_BROWSER_TEST_F(SSLUITest, SameDocumentHasSSLStateNoLoad) { ASSERT_TRUE(https_server_.Start()); WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); @@ -5961,7 +5722,7 @@ // Checks that if a client redirect occurs while the page is loading, the SSL // state reflects the final URL. -IN_PROC_BROWSER_TEST_P(SSLUITest, ClientRedirectSSLState) { +IN_PROC_BROWSER_TEST_F(SSLUITest, ClientRedirectSSLState) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_.Start()); @@ -5985,7 +5746,7 @@ // Checks that if a redirect occurs while the page is loading from a mixed // content to a valid HTTPS page, the SSL state reflects the final URL. -IN_PROC_BROWSER_TEST_P(SSLUITest, ClientRedirectFromMixedContentSSLState) { +IN_PROC_BROWSER_TEST_F(SSLUITest, ClientRedirectFromMixedContentSSLState) { ASSERT_TRUE(https_server_.Start()); GURL url = GURL( @@ -6000,7 +5761,7 @@ // Checks that if a redirect occurs while the page is loading from a valid HTTPS // page to a mixed content page, the SSL state reflects the final URL. -IN_PROC_BROWSER_TEST_P(SSLUITest, ClientRedirectToMixedContentSSLState) { +IN_PROC_BROWSER_TEST_F(SSLUITest, ClientRedirectToMixedContentSSLState) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(https_server_.Start()); @@ -6026,7 +5787,7 @@ } // Checks that same-document navigations during page load preserve SSL state. -IN_PROC_BROWSER_TEST_P(SSLUITest, SameDocumentNavigationDuringLoadSSLState) { +IN_PROC_BROWSER_TEST_F(SSLUITest, SameDocumentNavigationDuringLoadSSLState) { ASSERT_TRUE(https_server_.Start()); ui_test_utils::NavigateToURL( @@ -6038,7 +5799,7 @@ // Checks that same-document navigations after the page load preserve SSL // state. -IN_PROC_BROWSER_TEST_P(SSLUITest, SameDocumentNavigationAfterLoadSSLState) { +IN_PROC_BROWSER_TEST_F(SSLUITest, SameDocumentNavigationAfterLoadSSLState) { ASSERT_TRUE(https_server_.Start()); ui_test_utils::NavigateToURL(browser(), @@ -6050,7 +5811,7 @@ // Checks that navigations after pushState maintain the SSL status. // Flaky, see https://crbug.com/872029 and https://crbug.com/872030. -IN_PROC_BROWSER_TEST_P(SSLUITest, DISABLED_PushStateSSLState) { +IN_PROC_BROWSER_TEST_F(SSLUITest, DISABLED_PushStateSSLState) { ASSERT_TRUE(https_server_.Start()); ui_test_utils::NavigateToURL(browser(), @@ -6075,7 +5836,7 @@ public CertificateManagerModel::Observer { public: SSLUITestNoCert() = default; - ~SSLUITestNoCert() = default; + ~SSLUITestNoCert() override = default; void SetUpCommandLine(base::CommandLine* command_line) override { command_line->AppendSwitch(switches::kDisableTestCerts); @@ -6086,10 +5847,8 @@ void CertificatesRefreshed() override {} }; -INSTANTIATE_TEST_SUITE_P(, SSLUITestNoCert, ::testing::Values(false, true)); - // Checks that a newly-added certificate authority is usable immediately. -IN_PROC_BROWSER_TEST_P(SSLUITestNoCert, NewCertificateAuthority) { +IN_PROC_BROWSER_TEST_F(SSLUITestNoCert, NewCertificateAuthority) { if (!content::IsOutOfProcessNetworkService()) return; @@ -6140,7 +5899,7 @@ // Regression test for http://crbug.com/635833 (crash when a window with no // NavigationEntry commits). -IN_PROC_BROWSER_TEST_P(SSLUITestIgnoreLocalhostCertErrors, +IN_PROC_BROWSER_TEST_F(SSLUITestIgnoreLocalhostCertErrors, NoCrashOnLoadWithNoNavigationEntry) { ASSERT_TRUE(embedded_test_server()->Start()); @@ -6154,10 +5913,6 @@ // pattern matching. using SSLUICaptivePortalListTest = SSLUITest; -INSTANTIATE_TEST_SUITE_P(, - SSLUICaptivePortalListTest, - ::testing::Values(false, true)); - std::unique_ptr<chrome_browser_ssl::SSLErrorAssistantConfig> MakeCaptivePortalConfig(int version_id, const std::set<std::string>& spki_hashes) { @@ -6172,7 +5927,7 @@ // Tests that the captive portal certificate list is not used when the feature // is disabled via Finch. The list is passed to SSLErrorHandler via a proto. -IN_PROC_BROWSER_TEST_P(SSLUICaptivePortalListTest, Disabled) { +IN_PROC_BROWSER_TEST_F(SSLUICaptivePortalListTest, Disabled) { base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitWithFeatures( {} /* enabled */, {kCaptivePortalCertificateList} /* disabled */); @@ -6211,7 +5966,7 @@ // Tests that the captive portal certificate list is used when the feature // is enabled via Finch. The list is passed to SSLErrorHandler via a proto. -IN_PROC_BROWSER_TEST_P(SSLUICaptivePortalListTest, Enabled_FromProto) { +IN_PROC_BROWSER_TEST_F(SSLUICaptivePortalListTest, Enabled_FromProto) { base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitWithFeatures( {kCaptivePortalCertificateList} /* enabled */, {} /* disabled */); @@ -6252,7 +6007,7 @@ // interstitial should be displayed. The test then switches OS captive portal // status to false and reloads the page. This time, a normal SSL interstitial // will be displayed. -IN_PROC_BROWSER_TEST_P(SSLUITest, OSReportsCaptivePortal) { +IN_PROC_BROWSER_TEST_F(SSLUITest, OSReportsCaptivePortal) { ASSERT_TRUE(https_server_mismatched_.Start()); base::HistogramTester histograms; bool netwok_connectivity_reported = false; @@ -6294,7 +6049,7 @@ // Tests the scenario where the OS reports a captive portal but captive portal // interstitial feature is disabled. A captive portal interstitial should not be // displayed. -IN_PROC_BROWSER_TEST_P(SSLUITest, OSReportsCaptivePortal_FeatureDisabled) { +IN_PROC_BROWSER_TEST_F(SSLUITest, OSReportsCaptivePortal_FeatureDisabled) { base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitWithFeatures( {} /* enabled */, {kCaptivePortalInterstitial} /* disabled */); @@ -6330,7 +6085,7 @@ // Tests that the committed interstitial flag triggers the code path to show an // error PageType instead of an interstitial PageType. -IN_PROC_BROWSER_TEST_P(SSLUITestCommitted, ErrorPage) { +IN_PROC_BROWSER_TEST_F(SSLUITest, ErrorPage) { ASSERT_TRUE(https_server_expired_.Start()); WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); ui_test_utils::NavigateToURL( @@ -6356,8 +6111,7 @@ // embedded test server, but the test server can only serve a limited number of // predefined certificates. class SSLUICaptivePortalListResourceBundleTest - : public CertVerifierBrowserTest, - public testing::WithParamInterface<bool> { + : public CertVerifierBrowserTest { public: SSLUICaptivePortalListResourceBundleTest() : CertVerifierBrowserTest(), @@ -6365,14 +6119,6 @@ https_server_.ServeFilesFromSourceDirectory(GetChromeTestDataDir()); } - void SetUpOnMainThread() override { - CertVerifierBrowserTest::SetUpOnMainThread(); - if (GetParam()) { - scoped_feature_list_.InitAndEnableFeature( - features::kSSLCommittedInterstitials); - } - } - void TearDown() override { SSLErrorHandler::ResetConfigForTesting(); CertVerifierBrowserTest::TearDown(); @@ -6436,15 +6182,11 @@ net::EmbeddedTestServer https_server_; }; -INSTANTIATE_TEST_SUITE_P(, - SSLUICaptivePortalListResourceBundleTest, - ::testing::Values(false, true)); - } // namespace // Same as CaptivePortalCertificateList_Enabled_FromProto, but this time the // cert's SPKI hash is listed in ssl_error_assistant.asciipb. -IN_PROC_BROWSER_TEST_P(SSLUICaptivePortalListResourceBundleTest, Enabled) { +IN_PROC_BROWSER_TEST_F(SSLUICaptivePortalListResourceBundleTest, Enabled) { base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitWithFeatures( {kCaptivePortalCertificateList} /* enabled */, {} /* disabled */); @@ -6479,7 +6221,7 @@ // Same as SSLUICaptivePortalListResourceBundleTest. Enabled, but this time the // proto is dynamically updated (e.g. by the component updater). The dynamic // update should always override the proto loaded from the resource bundle. -IN_PROC_BROWSER_TEST_P(SSLUICaptivePortalListResourceBundleTest, +IN_PROC_BROWSER_TEST_F(SSLUICaptivePortalListResourceBundleTest, Enabled_DynamicUpdate) { base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitWithFeatures( @@ -6588,7 +6330,7 @@ // Same as SSLUICaptivePortalNameMismatchTest, but this time the error is // authority-invalid. Captive portal interstitial should not be shown. -IN_PROC_BROWSER_TEST_P(SSLUICaptivePortalListResourceBundleTest, +IN_PROC_BROWSER_TEST_F(SSLUICaptivePortalListResourceBundleTest, Enabled_AuthorityInvalid) { base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitWithFeatures( @@ -6601,7 +6343,7 @@ // Same as SSLUICaptivePortalListResourceBundleTest.Enabled_AuthorityInvalid, // but this time there are two errors (name mismatch + weak key). Captive portal // interstitial should not be shown when name mismatch isn't the only error. -IN_PROC_BROWSER_TEST_P(SSLUICaptivePortalListResourceBundleTest, +IN_PROC_BROWSER_TEST_F(SSLUICaptivePortalListResourceBundleTest, Enabled_NameMismatchAndWeakKey) { base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitWithFeatures( @@ -6622,8 +6364,7 @@ char kTestMITMSoftwareName[] = "Misconfigured Firewall"; -class SSLUIMITMSoftwareTest : public CertVerifierBrowserTest, - public testing::WithParamInterface<bool> { +class SSLUIMITMSoftwareTest : public CertVerifierBrowserTest { public: SSLUIMITMSoftwareTest() : CertVerifierBrowserTest(), @@ -6632,10 +6373,6 @@ void SetUpOnMainThread() override { CertVerifierBrowserTest::SetUpOnMainThread(); - if (GetParam()) { - scoped_feature_list_.InitAndEnableFeature( - features::kSSLCommittedInterstitials); - } host_resolver()->AddRule("*", "127.0.0.1"); SetHSTSForHostName(browser()->profile()); } @@ -6753,10 +6490,6 @@ DISALLOW_COPY_AND_ASSIGN(SSLUIMITMSoftwareTest); }; -INSTANTIATE_TEST_SUITE_P(, - SSLUIMITMSoftwareTest, - ::testing::Values(false, true)); - // The SSLUIMITMSoftwareEnabled and Disabled test classes exist so that the // scoped feature list can be instantiated in the set up method of the class // rather than in the test itself. Bug crbug.com/713390 was causing some of the @@ -6781,10 +6514,6 @@ DISALLOW_COPY_AND_ASSIGN(SSLUIMITMSoftwareEnabledTest); }; -INSTANTIATE_TEST_SUITE_P(, - SSLUIMITMSoftwareEnabledTest, - ::testing::Values(false, true)); - class SSLUIMITMSoftwareDisabledTest : public SSLUIMITMSoftwareTest { public: SSLUIMITMSoftwareDisabledTest() {} @@ -6802,15 +6531,11 @@ DISALLOW_COPY_AND_ASSIGN(SSLUIMITMSoftwareDisabledTest); }; -INSTANTIATE_TEST_SUITE_P(, - SSLUIMITMSoftwareDisabledTest, - ::testing::Values(false, true)); - } // namespace // Tests that the MITM software interstitial is not displayed when the feature // is disabled by Finch. -IN_PROC_BROWSER_TEST_P(SSLUIMITMSoftwareDisabledTest, DisabledWithFinch) { +IN_PROC_BROWSER_TEST_F(SSLUIMITMSoftwareDisabledTest, DisabledWithFinch) { SetUpCertVerifier(net::CERT_STATUS_AUTHORITY_INVALID); SetUpMITMSoftwareCertList(kLargeVersionId); TestNoMITMSoftwareInterstitial(); @@ -6818,7 +6543,7 @@ // Tests that the MITM software interstitial is displayed when the feature is // enabled by Finch. -IN_PROC_BROWSER_TEST_P(SSLUIMITMSoftwareEnabledTest, EnabledWithFinch) { +IN_PROC_BROWSER_TEST_F(SSLUIMITMSoftwareEnabledTest, EnabledWithFinch) { SetUpCertVerifier(net::CERT_STATUS_AUTHORITY_INVALID); SetUpMITMSoftwareCertList(kLargeVersionId); TestMITMSoftwareInterstitial(); @@ -6827,7 +6552,7 @@ // Tests that if a certificates matches the common name of a known MITM software // cert on the list but not the organization name, the MITM software // interstitial will not be displayed. -IN_PROC_BROWSER_TEST_P( +IN_PROC_BROWSER_TEST_F( SSLUIMITMSoftwareEnabledTest, CertificateCommonNameMatchOnly_NoMITMSoftwareInterstitial) { base::HistogramTester histograms; @@ -6875,7 +6600,7 @@ // Tests that if a certificates matches the organization name of a known MITM // software cert on the list but not the common name, the MITM software // interstitial will not be displayed. -IN_PROC_BROWSER_TEST_P( +IN_PROC_BROWSER_TEST_F( SSLUIMITMSoftwareEnabledTest, CertificateOrganizationMatchOnly_NoMITMSoftwareInterstitial) { base::HistogramTester histograms; @@ -6922,7 +6647,7 @@ // Tests that if the certificate does not match any entry on the list of known // MITM software, the MITM software interstitial will not be displayed. -IN_PROC_BROWSER_TEST_P(SSLUIMITMSoftwareEnabledTest, +IN_PROC_BROWSER_TEST_F(SSLUIMITMSoftwareEnabledTest, NonMatchingCertificate_NoMITMSoftwareInterstitial) { base::HistogramTester histograms; @@ -6968,7 +6693,7 @@ // Tests that if there is more than one error on the certificate the MITM // software interstitial will not be displayed. -IN_PROC_BROWSER_TEST_P(SSLUIMITMSoftwareEnabledTest, +IN_PROC_BROWSER_TEST_F(SSLUIMITMSoftwareEnabledTest, TwoCertErrors_NoMITMSoftwareInterstitial) { SetUpCertVerifier(net::CERT_STATUS_AUTHORITY_INVALID | net::CERT_STATUS_COMMON_NAME_INVALID); @@ -6978,7 +6703,7 @@ // Tests that a certificate error other than |CERT_STATUS_AUTHORITY_INVALID| // will not trigger the MITM software interstitial. -IN_PROC_BROWSER_TEST_P(SSLUIMITMSoftwareEnabledTest, +IN_PROC_BROWSER_TEST_F(SSLUIMITMSoftwareEnabledTest, WrongCertError_NoMITMSoftwareInterstitial) { SetUpCertVerifier(net::CERT_STATUS_COMMON_NAME_INVALID); SetUpMITMSoftwareCertList(kLargeVersionId); @@ -6987,7 +6712,7 @@ // Tests that if the error on the certificate served is overridable the MITM // software interstitial will not be displayed. -IN_PROC_BROWSER_TEST_P(SSLUIMITMSoftwareEnabledTest, +IN_PROC_BROWSER_TEST_F(SSLUIMITMSoftwareEnabledTest, OverridableError_NoMITMSoftwareInterstitial) { base::HistogramTester histograms; @@ -7021,7 +6746,7 @@ // Tests that the correct strings are displayed on the interstitial in the // enterprise managed case. -IN_PROC_BROWSER_TEST_P(SSLUIMITMSoftwareEnabledTest, EnterpriseManaged) { +IN_PROC_BROWSER_TEST_F(SSLUIMITMSoftwareEnabledTest, EnterpriseManaged) { SetUpCertVerifier(net::CERT_STATUS_AUTHORITY_INVALID); SSLErrorHandler::SetEnterpriseManagedForTesting(true); ASSERT_TRUE(SSLErrorHandler::IsEnterpriseManagedFlagSetForTesting()); @@ -7039,20 +6764,14 @@ WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); EXPECT_TRUE(chrome_browser_interstitials::IsInterstitialDisplayingText( - AreCommittedInterstitialsEnabled() - ? tab->GetMainFrame() - : tab->GetInterstitialPage()->GetMainFrame(), - expected_explanation)); + tab->GetMainFrame(), expected_explanation)); EXPECT_TRUE(chrome_browser_interstitials::IsInterstitialDisplayingText( - AreCommittedInterstitialsEnabled() - ? tab->GetMainFrame() - : tab->GetInterstitialPage()->GetMainFrame(), - expected_primary_paragraph)); + tab->GetMainFrame(), expected_primary_paragraph)); } // Tests that the correct strings are displayed on the interstitial in the // non-enterprise managed case. -IN_PROC_BROWSER_TEST_P(SSLUIMITMSoftwareEnabledTest, NotEnterpriseManaged) { +IN_PROC_BROWSER_TEST_F(SSLUIMITMSoftwareEnabledTest, NotEnterpriseManaged) { SetUpCertVerifier(net::CERT_STATUS_AUTHORITY_INVALID); SSLErrorHandler::SetEnterpriseManagedForTesting(false); ASSERT_TRUE(SSLErrorHandler::IsEnterpriseManagedFlagSetForTesting()); @@ -7069,16 +6788,13 @@ WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); EXPECT_TRUE(chrome_browser_interstitials::IsInterstitialDisplayingText( - AreCommittedInterstitialsEnabled() - ? tab->GetMainFrame() - : tab->GetInterstitialPage()->GetMainFrame(), - expected_explanation)); + tab->GetMainFrame(), expected_explanation)); } // Initialize MITMSoftware certificate list but set the version_id to zero. This // less than the version_id of the local resource bundle, so the dynamic // update will be ignored and a non-MITM interstitial will be shown. -IN_PROC_BROWSER_TEST_P(SSLUIMITMSoftwareEnabledTest, +IN_PROC_BROWSER_TEST_F(SSLUIMITMSoftwareEnabledTest, IgnoreDynamicUpdateWithSmallVersionId) { auto config_proto = SSLErrorAssistant::GetErrorAssistantProtoFromResourceBundle(); @@ -7246,7 +6962,7 @@ // Checks that SimpleURLLoader, which uses services/network/url_loader.cc, goes // through the new NetworkServiceClient interface to deliver cert error // notifications to the browser which then overrides the certificate error. -IN_PROC_BROWSER_TEST_P(SSLUITest, SimpleURLLoaderCertError) { +IN_PROC_BROWSER_TEST_F(SSLUITest, SimpleURLLoaderCertError) { WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_NO_FATAL_FAILURE(SetUpUnsafeContentsWithUserException( "/ssl/page_with_unsafe_contents.html")); @@ -7263,7 +6979,7 @@ frame->GetProcess()->GetID(), frame->GetRoutingID())); } -IN_PROC_BROWSER_TEST_P(SSLUITest, NetworkErrorDoesntRevokeExemptions) { +IN_PROC_BROWSER_TEST_F(SSLUITest, NetworkErrorDoesntRevokeExemptions) { ASSERT_TRUE(https_server_expired_.Start()); GURL expired_url = https_server_expired_.GetURL("/title1.html"); int server_port = expired_url.IntPort(); @@ -7296,7 +7012,7 @@ // Checks we don't attempt to show an interstitial (or crash) when visiting an // SSL error related page in chrome://network-errors. Regression test for // crbug.com/953812 -IN_PROC_BROWSER_TEST_P(SSLUITest, NoInterstitialOnNetworkErrorPage) { +IN_PROC_BROWSER_TEST_F(SSLUITest, NoInterstitialOnNetworkErrorPage) { GURL invalid_cert_url(content::kChromeUINetworkErrorURL); GURL::Replacements replacements; replacements.SetPathStr("-207"); @@ -7406,18 +7122,12 @@ } InterstitialPageDelegate* GetInterstitialDelegate(WebContents* tab) { - if (AreCommittedInterstitialsEnabled()) { - security_interstitials::SecurityInterstitialTabHelper* helper = - security_interstitials::SecurityInterstitialTabHelper:: - FromWebContents(tab); - if (!helper) - return nullptr; - return helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting(); - } - InterstitialPage* interstitial_page = tab->GetInterstitialPage(); - if (!interstitial_page) + security_interstitials::SecurityInterstitialTabHelper* helper = + security_interstitials::SecurityInterstitialTabHelper::FromWebContents( + tab); + if (!helper) return nullptr; - return interstitial_page->GetDelegateForTesting(); + return helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting(); } private: @@ -7869,18 +7579,12 @@ wait_for_report_loop.Run(); } -class RecurrentInterstitialBrowserTest - : public CertVerifierBrowserTest, - public testing::WithParamInterface<bool> { +class RecurrentInterstitialBrowserTest : public CertVerifierBrowserTest { public: RecurrentInterstitialBrowserTest() : CertVerifierBrowserTest() {} void SetUpOnMainThread() override { CertVerifierBrowserTest::SetUpOnMainThread(); - if (IsCommittedInterstitialTest()) { - scoped_feature_list_.InitAndEnableFeature( - features::kSSLCommittedInterstitials); - } host_resolver()->AddRule("*", "127.0.0.1"); } @@ -7890,20 +7594,13 @@ CertVerifierBrowserTest::TearDownOnMainThread(); } - protected: - bool IsCommittedInterstitialTest() { return GetParam(); } - private: base::test::ScopedFeatureList scoped_feature_list_; }; -INSTANTIATE_TEST_SUITE_P(, - RecurrentInterstitialBrowserTest, - ::testing::Values(false, true)); - // Tests that a message is added to the interstitial when an error code recurs // multiple times. -IN_PROC_BROWSER_TEST_P(RecurrentInterstitialBrowserTest, +IN_PROC_BROWSER_TEST_F(RecurrentInterstitialBrowserTest, RecurrentInterstitial) { const char kRecurrentInterstitialHistogram[] = "interstitial.ssl_overridable.is_recurrent_error"; @@ -7958,17 +7655,8 @@ // Proceed through the interstitial and observe that the histogram is // recorded correctly. content::TestNavigationObserver nav_observer(tab, 1); - if (AreCommittedInterstitialsEnabled()) { - ASSERT_TRUE(content::ExecuteScript( - tab, "window.certificateErrorPageController.proceed();")); - } else { - int unused; - ASSERT_TRUE(content::ExecuteScriptAndExtractInt( - tab->GetInterstitialPage()->GetMainFrame(), - base::StringPrintf("window.domAutomationController.send(%d);", - security_interstitials::CMD_PROCEED), - &unused)); - } + ASSERT_TRUE(content::ExecuteScript( + tab, "window.certificateErrorPageController.proceed();")); nav_observer.Wait(); histograms.ExpectBucketCount( kRecurrentInterstitialActionHistogram,
diff --git a/chrome/browser/ssl/ssl_browsertest_util.cc b/chrome/browser/ssl/ssl_browsertest_util.cc index fd764310..0ea45fb 100644 --- a/chrome/browser/ssl/ssl_browsertest_util.cc +++ b/chrome/browser/ssl/ssl_browsertest_util.cc
@@ -20,8 +20,7 @@ void Check(content::NavigationEntry* entry, int expected_authentication_state) { if (expected_authentication_state == AuthState::SHOWING_ERROR || - (base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials) && - expected_authentication_state == AuthState::SHOWING_INTERSTITIAL)) { + expected_authentication_state == AuthState::SHOWING_INTERSTITIAL) { EXPECT_EQ(content::PAGE_TYPE_ERROR, entry->GetPageType()); } else { EXPECT_EQ(
diff --git a/chrome/browser/ssl/ssl_error_controller_client.cc b/chrome/browser/ssl/ssl_error_controller_client.cc index ee8e6ac..60966d13 100644 --- a/chrome/browser/ssl/ssl_error_controller_client.cc +++ b/chrome/browser/ssl/ssl_error_controller_client.cc
@@ -147,10 +147,6 @@ } #endif -bool AreCommittedInterstitialsEnabled() { - return base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials); -} - } // namespace SSLErrorControllerClient::SSLErrorControllerClient( @@ -177,11 +173,6 @@ SSLErrorControllerClient::~SSLErrorControllerClient() {} void SSLErrorControllerClient::GoBack() { - if (!AreCommittedInterstitialsEnabled()) { - SecurityInterstitialControllerClient::GoBack(); - return; - } - SecurityInterstitialControllerClient::GoBackAfterNavigationCommitted(); } @@ -201,11 +192,6 @@ chrome::OpenInChrome(browser); #endif // BUILDFLAG(ENABLE_EXTENSIONS) - if (!AreCommittedInterstitialsEnabled()) { - SecurityInterstitialControllerClient::Proceed(); - return; - } - Profile* profile = Profile::FromBrowserContext(web_contents_->GetBrowserContext()); ChromeSSLHostStateDelegate* state = static_cast<ChromeSSLHostStateDelegate*>(
diff --git a/chrome/browser/ssl/ssl_error_navigation_throttle.cc b/chrome/browser/ssl/ssl_error_navigation_throttle.cc index 3e00aab..0395630 100644 --- a/chrome/browser/ssl/ssl_error_navigation_throttle.cc +++ b/chrome/browser/ssl/ssl_error_navigation_throttle.cc
@@ -35,7 +35,6 @@ content::NavigationThrottle::ThrottleCheckResult SSLErrorNavigationThrottle::WillFailRequest() { - DCHECK(base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials)); content::NavigationHandle* handle = navigation_handle(); // Check the network error code in case we are here due to a non-ssl related @@ -65,7 +64,6 @@ content::NavigationThrottle::ThrottleCheckResult SSLErrorNavigationThrottle::WillProcessResponse() { - DCHECK(base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials)); content::NavigationHandle* handle = navigation_handle(); // If there was no certificate error, SSLInfo will be empty. const net::SSLInfo info = handle->GetSSLInfo().value_or(net::SSLInfo());
diff --git a/chrome/browser/ssl/ssl_error_navigation_throttle_unittest.cc b/chrome/browser/ssl/ssl_error_navigation_throttle_unittest.cc index fff7ed6..59c1a8c 100644 --- a/chrome/browser/ssl/ssl_error_navigation_throttle_unittest.cc +++ b/chrome/browser/ssl/ssl_error_navigation_throttle_unittest.cc
@@ -6,11 +6,9 @@ #include "base/bind.h" #include "base/run_loop.h" -#include "base/test/scoped_feature_list.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/ssl/certificate_reporting_test_utils.h" #include "chrome/browser/ssl/ssl_blocking_page.h" -#include "chrome/common/chrome_features.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "content/public/browser/navigation_throttle.h" #include "content/public/test/mock_navigation_handle.h" @@ -87,9 +85,6 @@ SSLErrorNavigationThrottleTest() {} void SetUp() override { ChromeRenderViewHostTestHarness::SetUp(); - scoped_feature_list_.InitAndEnableFeature( - features::kSSLCommittedInterstitials); - handle_ = std::make_unique<content::MockNavigationHandle>(web_contents()); handle_->set_has_committed(true); async_ = GetParam(); @@ -117,7 +112,6 @@ content::NavigationThrottle::DEFER; private: - base::test::ScopedFeatureList scoped_feature_list_; DISALLOW_COPY_AND_ASSIGN(SSLErrorNavigationThrottleTest); };
diff --git a/chrome/browser/sync/test/integration/single_client_send_tab_to_self_sync_test.cc b/chrome/browser/sync/test/integration/single_client_send_tab_to_self_sync_test.cc index 561928ba..919e3656 100644 --- a/chrome/browser/sync/test/integration/single_client_send_tab_to_self_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_send_tab_to_self_sync_test.cc
@@ -68,10 +68,11 @@ EXPECT_TRUE(send_tab_to_self::IsUserSyncTypeActive(GetProfile(0))); } -IN_PROC_BROWSER_TEST_F(SingleClientSendTabToSelfSyncTest, IsOnMultipleDevices) { +IN_PROC_BROWSER_TEST_F(SingleClientSendTabToSelfSyncTest, + HasValidTargetDevice) { ASSERT_TRUE(SetupSync()); - EXPECT_FALSE(send_tab_to_self::IsSyncingOnMultipleDevices(GetProfile(0))); + EXPECT_FALSE(send_tab_to_self::HasValidTargetDevice(GetProfile(0))); } IN_PROC_BROWSER_TEST_F(SingleClientSendTabToSelfSyncTest, IsFlagEnabled) {
diff --git a/chrome/browser/sync/test/integration/single_client_standalone_transport_sync_test.cc b/chrome/browser/sync/test/integration/single_client_standalone_transport_sync_test.cc index 53524bb..860657af 100644 --- a/chrome/browser/sync/test/integration/single_client_standalone_transport_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_standalone_transport_sync_test.cc
@@ -97,7 +97,9 @@ // either by the Sync confirmation dialog or by the settings page if going // through the advanced settings flow. EXPECT_FALSE(GetSyncService(0)->GetUserSettings()->IsFirstSetupComplete()); - EXPECT_FALSE(GetSyncService(0)->GetUserSettings()->IsSyncRequested()); + // TODO(crbug.com/906034,crbug.com/973770): Sort out the proper default value + // for IsSyncRequested(). + // EXPECT_FALSE(GetSyncService(0)->GetUserSettings()->IsSyncRequested()); EXPECT_FALSE(GetSyncService(0)->IsSyncFeatureEnabled()); EXPECT_FALSE(GetSyncService(0)->IsSyncFeatureActive());
diff --git a/chrome/browser/sync/test/integration/two_client_send_tab_to_self_sync_test.cc b/chrome/browser/sync/test/integration/two_client_send_tab_to_self_sync_test.cc index 40a74778..0f93bdb 100644 --- a/chrome/browser/sync/test/integration/two_client_send_tab_to_self_sync_test.cc +++ b/chrome/browser/sync/test/integration/two_client_send_tab_to_self_sync_test.cc
@@ -121,22 +121,19 @@ EXPECT_TRUE(send_tab_to_self::IsUserSyncTypeActive(GetProfile(0))); } -IN_PROC_BROWSER_TEST_F(TwoClientSendTabToSelfSyncTest, IsOnMultipleDevices) { +IN_PROC_BROWSER_TEST_F(TwoClientSendTabToSelfSyncTest, HasValidTargetDevice) { ASSERT_TRUE(SetupSync()); - DeviceInfoSyncServiceFactory::GetForProfile(GetProfile(1)) - ->GetDeviceInfoTracker() - ->ForcePulseForTest(); - DeviceInfoSyncServiceFactory::GetForProfile(GetProfile(0)) - ->GetDeviceInfoTracker() - ->ForcePulseForTest(); + static_cast<send_tab_to_self::SendTabToSelfBridge*>( + SendTabToSelfSyncServiceFactory::GetForProfile(GetProfile(0)) + ->GetSendTabToSelfModel()) + ->SetLocalDeviceNameForTest("device1"); + static_cast<send_tab_to_self::SendTabToSelfBridge*>( + SendTabToSelfSyncServiceFactory::GetForProfile(GetProfile(1)) + ->GetSendTabToSelfModel()) + ->SetLocalDeviceNameForTest("device2"); - ASSERT_TRUE(send_tab_to_self_helper::SendTabToSelfMultiDeviceActiveChecker( - DeviceInfoSyncServiceFactory::GetForProfile(GetProfile(1)) - ->GetDeviceInfoTracker()) - .Wait()); - - EXPECT_TRUE(send_tab_to_self::IsSyncingOnMultipleDevices(GetProfile(0))); + EXPECT_TRUE(send_tab_to_self::HasValidTargetDevice(GetProfile(0))); } IN_PROC_BROWSER_TEST_F(TwoClientSendTabToSelfSyncTest,
diff --git a/chrome/browser/ui/app_list/app_list_client_impl_browsertest.cc b/chrome/browser/ui/app_list/app_list_client_impl_browsertest.cc index 7180b22..01fc2faa 100644 --- a/chrome/browser/ui/app_list/app_list_client_impl_browsertest.cc +++ b/chrome/browser/ui/app_list/app_list_client_impl_browsertest.cc
@@ -302,6 +302,9 @@ // Uninstall the extension. UninstallExtension(extension->id()); + // Allow async callbacks to run. + base::RunLoop().RunUntilIdle(); + // We cannot find the extension any more. EXPECT_FALSE(search_controller->GetResultByTitleForTest(title));
diff --git a/chrome/browser/ui/ash/assistant/device_actions.cc b/chrome/browser/ui/ash/assistant/device_actions.cc index 79cafcf1..ec4f09d 100644 --- a/chrome/browser/ui/ash/assistant/device_actions.cc +++ b/chrome/browser/ui/ash/assistant/device_actions.cc
@@ -206,6 +206,14 @@ std::move(callback).Run(!!app); } +void DeviceActions::VerifyAndroidApp(std::vector<AndroidAppInfoPtr> apps_info, + VerifyAndroidAppCallback callback) { + for (const auto& app_info : apps_info) { + app_info->status = GetAndroidAppStatus(app_info->package_name); + } + std::move(callback).Run(std::move(apps_info)); +} + void DeviceActions::LaunchAndroidIntent(const std::string& intent) { auto* app = ARC_GET_INSTANCE_FOR_METHOD( arc::ArcServiceManager::Get()->arc_bridge_service()->app(), LaunchIntent);
diff --git a/chrome/browser/ui/ash/assistant/device_actions.h b/chrome/browser/ui/ash/assistant/device_actions.h index 3040052..e44a28b9 100644 --- a/chrome/browser/ui/ash/assistant/device_actions.h +++ b/chrome/browser/ui/ash/assistant/device_actions.h
@@ -30,6 +30,9 @@ void SetNightLightEnabled(bool enabled) override; void OpenAndroidApp(chromeos::assistant::mojom::AndroidAppInfoPtr app_info, OpenAndroidAppCallback callback) override; + void VerifyAndroidApp( + std::vector<chromeos::assistant::mojom::AndroidAppInfoPtr> apps_info, + VerifyAndroidAppCallback callback) override; void LaunchAndroidIntent(const std::string& intent) override; void AddAppListEventSubscriber( chromeos::assistant::mojom::AppListEventSubscriberPtr subscriber)
diff --git a/chrome/browser/ui/bookmarks/bookmark_browsertest.cc b/chrome/browser/ui/bookmarks/bookmark_browsertest.cc index d1cc57e8..71ab269 100644 --- a/chrome/browser/ui/bookmarks/bookmark_browsertest.cc +++ b/chrome/browser/ui/bookmarks/bookmark_browsertest.cc
@@ -3,7 +3,6 @@ // found in the LICENSE file. #include "base/bind.h" -#include "base/feature_list.h" #include "base/macros.h" #include "base/strings/utf_string_conversions.h" #include "base/test/bind_test_util.h" @@ -23,7 +22,6 @@ #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/common/chrome_features.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/bookmarks/browser/bookmark_model.h" @@ -48,22 +46,12 @@ const char kPersistBookmarkURL[] = "http://www.cnn.com/"; const char kPersistBookmarkTitle[] = "CNN"; -bool AreCommittedInterstitialsEnabled() { - return base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials); -} - bool IsShowingInterstitial(content::WebContents* tab) { - if (AreCommittedInterstitialsEnabled()) { - security_interstitials::SecurityInterstitialTabHelper* helper = - security_interstitials::SecurityInterstitialTabHelper::FromWebContents( - tab); - if (!helper) { - return false; - } - return helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting() != - nullptr; - } - return tab->GetInterstitialPage() != nullptr; + security_interstitials::SecurityInterstitialTabHelper* helper = + security_interstitials::SecurityInterstitialTabHelper::FromWebContents( + tab); + return helper && + helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting(); } } // namespace @@ -223,8 +211,6 @@ GURL error_url = https_server.GetURL("/"); ui_test_utils::NavigateToURL(browser(), error_url); web_contents = browser()->tab_strip_model()->GetActiveWebContents(); - if (!AreCommittedInterstitialsEnabled()) - content::WaitForInterstitialAttach(web_contents); EXPECT_TRUE(IsShowingInterstitial(web_contents)); EXPECT_FALSE(bookmark_observer.is_starred());
diff --git a/chrome/browser/ui/extensions/hosted_app_browsertest.cc b/chrome/browser/ui/extensions/hosted_app_browsertest.cc index 0b0f89c58..036c34c 100644 --- a/chrome/browser/ui/extensions/hosted_app_browsertest.cc +++ b/chrome/browser/ui/extensions/hosted_app_browsertest.cc
@@ -165,24 +165,14 @@ // Need a second TestNavigationObserver; the above one is spent. content::TestNavigationObserver observer( web_contents, content::MessageLoopRunner::QuitMode::DEFERRED); - if (base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials)) { - security_interstitials::SecurityInterstitialTabHelper* helper = - security_interstitials::SecurityInterstitialTabHelper:: - FromWebContents( - browser->tab_strip_model()->GetActiveWebContents()); - ASSERT_TRUE( - helper && - helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting()); - std::string javascript = - "window.certificateErrorPageController.proceed();"; - ASSERT_TRUE(content::ExecuteScript(web_contents, javascript)); - } else { - content::InterstitialPage* interstitial = - web_contents->GetInterstitialPage(); - ASSERT_TRUE(interstitial); - interstitial->GetDelegateForTesting()->CommandReceived( - base::NumberToString(security_interstitials::CMD_PROCEED)); - } + security_interstitials::SecurityInterstitialTabHelper* helper = + security_interstitials::SecurityInterstitialTabHelper::FromWebContents( + browser->tab_strip_model()->GetActiveWebContents()); + ASSERT_TRUE( + helper && + helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting()); + std::string javascript = "window.certificateErrorPageController.proceed();"; + ASSERT_TRUE(content::ExecuteScript(web_contents, javascript)); observer.Wait(); } } @@ -709,78 +699,6 @@ true); } -// Checks that the toolbar is shown for an HTTPS app with an invalid -// certificate, if the user has previously proceeded through the interstitial. -IN_PROC_BROWSER_TEST_P(HostedAppTest, ShouldShowToolbarDangerous) { - // If DesktopPWAWindowing and CommittedInterstitials are enabled, we will - // never load a dangerous app. Opening dangerous apps will always show an - // interstitial and proceeding through it will redirect the navigation to a - // tab. - if (base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials)) - return; - - ASSERT_TRUE(https_server()->Start()); - - const GURL app_url = https_server()->GetURL("app.com", "/simple.html"); - ui_test_utils::UrlLoadObserver url_observer( - app_url, content::NotificationService::AllSources()); - SetupAppWithURL(app_url); - url_observer.Wait(); - cert_verifier()->set_default_result(net::ERR_CERT_DATE_INVALID); - - // Proceeding through an interstitial results in the navigation being - // redirected to a regular tab. So we need to open the app again. Proceed - // through the interstitial once. - NavigateToURLAndWait(app_browser_, app_url, - /*proceed_through_interstitial=*/true); - ASSERT_NE(app_browser_, chrome::FindLastActive()); - - app_browser_ = LaunchAppBrowser(app_); - NavigateToURLAndWait(app_browser_, app_url, - /*proceed_through_interstitial=*/false); - - // There should be no interstitial shown because we previously proceeded - // through it. - if (base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials)) { - security_interstitials::SecurityInterstitialTabHelper* helper = - security_interstitials::SecurityInterstitialTabHelper::FromWebContents( - browser()->tab_strip_model()->GetActiveWebContents()); - ASSERT_FALSE( - helper && - helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting()); - } else { - ASSERT_FALSE(app_browser_->tab_strip_model() - ->GetActiveWebContents() - ->GetInterstitialPage()); - } - - bool proceed_through_interstitial = false; - NavigateAndCheckForToolbar(app_browser_, app_url, true, - proceed_through_interstitial); -} - -// Check that localhost is not considered insecure. -IN_PROC_BROWSER_TEST_P(HostedAppTest, ShouldShowToolbarForLocalhost) { - ASSERT_TRUE(embedded_test_server()->Start()); - ASSERT_TRUE(https_server()->Start()); - - const GURL app_url = - embedded_test_server()->GetURL("localhost", "/ssl/google.html"); - InstallPWA(app_url); - - // Navigate to the app's launch page; the toolbar should be hidden. - NavigateAndCheckForToolbar(app_browser_, app_url, false); - - // Navigate out of the app's scope on localhost, the toolbar should be - // visible. - NavigateAndCheckForToolbar( - app_browser_, embedded_test_server()->GetURL("localhost", "/simple.html"), - true); - - // Navigate to a different origin; the toolbar should be visible. - NavigateAndCheckForToolbar(app_browser_, GURL("https://example.com"), true); -} - // Check that a subframe on a regular web page can navigate to a URL that // redirects to a hosted app. https://crbug.com/721949. IN_PROC_BROWSER_TEST_P(HostedAppTest, SubframeRedirectsToHostedApp) {
diff --git a/chrome/browser/ui/login/login_handler_browsertest.cc b/chrome/browser/ui/login/login_handler_browsertest.cc index 605b3ea9..30ee6c5b 100644 --- a/chrome/browser/ui/login/login_handler_browsertest.cc +++ b/chrome/browser/ui/login/login_handler_browsertest.cc
@@ -52,6 +52,16 @@ namespace { +content::InterstitialPageDelegate* GetInterstitialDelegate( + content::WebContents* tab) { + security_interstitials::SecurityInterstitialTabHelper* helper = + security_interstitials::SecurityInterstitialTabHelper::FromWebContents( + tab); + if (!helper) + return nullptr; + return helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting(); +} + // Tests that a cross origin navigation triggering a login prompt should cause: // - A login interstitial being displayed. // - The destination URL being shown in the omnibox. @@ -1503,18 +1513,17 @@ // Redirect to a broken SSL page. This redirect should not accidentally // proceed through the SSL interstitial. - content::TestNavigationObserver nav_observer(contents); + content::TestNavigationObserver ssl_observer(contents); EXPECT_TRUE(content::ExecuteScript( browser()->tab_strip_model()->GetActiveWebContents(), std::string("window.location = '") + broken_ssl_page.spec() + "'")); - nav_observer.Wait(); - security_interstitials::SecurityInterstitialTabHelper* helper = - security_interstitials::SecurityInterstitialTabHelper::FromWebContents( - contents); - ASSERT_TRUE(helper); - EXPECT_EQ(SSLBlockingPage::kTypeForTesting, - helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting() - ->GetTypeForTesting()); + ssl_observer.Wait(); + + content::InterstitialPageDelegate* delegate = + GetInterstitialDelegate(contents); + + EXPECT_TRUE(delegate); + EXPECT_EQ(SSLBlockingPage::kTypeForTesting, delegate->GetTypeForTesting()); } // Test where Basic HTTP authentication is disabled.
diff --git a/chrome/browser/ui/views/crostini/crostini_browser_test_util.cc b/chrome/browser/ui/views/crostini/crostini_browser_test_util.cc index 32a2c37..fae5e0d 100644 --- a/chrome/browser/ui/views/crostini/crostini_browser_test_util.cc +++ b/chrome/browser/ui/views/crostini/crostini_browser_test_util.cc
@@ -59,9 +59,9 @@ browser_process_platform_part_test_api_->InitializeCrosComponentManager( std::move(cros_component_manager)); } - // Ideally we'd call SetConnectionType in ServiceManagerConnectionStarted, - // but currently we have to wait for PreProfileInit to complete, since that - // creates the ash::Shell that AshService needs in order to start. + // Ideally we'd call SetConnectionType in PostCreateThreads, but currently we + // have to wait for PreProfileInit to complete, since that creatse the + // ash::Shell that AshService needs in order to start. void PostProfileInit() override { connection_change_simulator_.SetConnectionType( network::mojom::ConnectionType::CONNECTION_WIFI);
diff --git a/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_bubble_device_button.cc b/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_bubble_device_button.cc index 4d576db..029b90d 100644 --- a/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_bubble_device_button.cc +++ b/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_bubble_device_button.cc
@@ -15,6 +15,7 @@ #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/paint_vector_icon.h" +#include "ui/native_theme/native_theme.h" namespace send_tab_to_self { @@ -30,7 +31,7 @@ TOTAL_COUNT = 2 // Add new types above this line. }; -gfx::ImageSkia CreateDeviceIcon(DeviceIconType icon_type, bool enabled = true) { +gfx::ImageSkia CreateDeviceIcon(DeviceIconType icon_type) { const gfx::VectorIcon* vector_icon; switch (icon_type) { case DeviceIconType::DESKTOP: @@ -42,7 +43,7 @@ default: vector_icon = &kSendTabToSelfIcon; } - SkColor icon_color = enabled ? gfx::kChromeIconGrey : gfx::kGoogleGrey500; + SkColor icon_color = ui::NativeTheme::kColorId_DefaultIconColor; return gfx::CreateVectorIcon(*vector_icon, kPrimaryIconSize, icon_color); }
diff --git a/chrome/browser/ui/webui/memory_internals_ui.cc b/chrome/browser/ui/webui/memory_internals_ui.cc index 91ec917..5cedf0d 100644 --- a/chrome/browser/ui/webui/memory_internals_ui.cc +++ b/chrome/browser/ui/webui/memory_internals_ui.cc
@@ -33,12 +33,12 @@ #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_data.h" #include "content/public/browser/render_process_host.h" +#include "content/public/browser/system_connector.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" #include "content/public/browser/web_ui_message_handler.h" #include "content/public/common/process_type.h" -#include "content/public/common/service_manager_connection.h" #include "mojo/public/cpp/system/platform_handle.h" #include "services/service_manager/public/cpp/connector.h" #include "ui/shell_dialogs/select_file_dialog.h" @@ -269,7 +269,7 @@ supervisor->StartManualProfiling(pid); } else { supervisor->Start( - content::ServiceManagerConnection::GetForProcess(), + content::GetSystemConnector(), base::BindOnce(&heap_profiling::Supervisor::StartManualProfiling, base::Unretained(supervisor), pid)); }
diff --git a/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc b/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc index 829d609a0..75a12e7 100644 --- a/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc +++ b/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc
@@ -139,16 +139,22 @@ void AccountManagerUIHandler::HandleGetAccounts(const base::ListValue* args) { AllowJavascript(); - CHECK(!args->GetList().empty()); - base::Value callback_id = args->GetList()[0].Clone(); + const auto& args_list = args->GetList(); + CHECK_EQ(args_list.size(), 2u); + CHECK(args_list[0].is_string()); + CHECK(args_list[1].is_bool()); - account_manager_->GetAccounts( - base::BindOnce(&AccountManagerUIHandler::OnGetAccounts, - weak_factory_.GetWeakPtr(), std::move(callback_id))); + base::Value callback_id = args_list[0].Clone(); + bool include_images = args_list[1].GetBool(); + + account_manager_->GetAccounts(base::BindOnce( + &AccountManagerUIHandler::OnGetAccounts, weak_factory_.GetWeakPtr(), + std::move(callback_id), include_images)); } void AccountManagerUIHandler::OnGetAccounts( base::Value callback_id, + bool include_images, const std::vector<AccountManager::Account>& stored_accounts) { base::ListValue accounts; @@ -182,17 +188,20 @@ maybe_account_info->account_id)); account.SetString("fullName", maybe_account_info->full_name); account.SetString("email", stored_account.raw_email); - if (!maybe_account_info->account_image.IsEmpty()) { - account.SetString("pic", - webui::GetBitmapDataUrl( - maybe_account_info->account_image.AsBitmap())); - } else { - gfx::ImageSkia default_icon = - *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed( - IDR_LOGIN_DEFAULT_USER); - account.SetString("pic", - webui::GetBitmapDataUrl( - default_icon.GetRepresentation(1.0f).GetBitmap())); + // Images can be large, so only send them if requested. + if (include_images) { + if (!maybe_account_info->account_image.IsEmpty()) { + account.SetString("pic", + webui::GetBitmapDataUrl( + maybe_account_info->account_image.AsBitmap())); + } else { + gfx::ImageSkia default_icon = + *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed( + IDR_LOGIN_DEFAULT_USER); + account.SetString( + "pic", webui::GetBitmapDataUrl( + default_icon.GetRepresentation(1.0f).GetBitmap())); + } } account.SetBoolean("unmigrated", account_manager_->HasDummyGaiaToken(account_key));
diff --git a/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h b/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h index c6acb89..df7c01b 100644 --- a/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h +++ b/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h
@@ -64,6 +64,7 @@ // |AccountManager::GetAccounts| callback. void OnGetAccounts( base::Value callback_id, + bool include_images, const std::vector<AccountManager::Account>& stored_accounts); // Refreshes the UI.
diff --git a/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.cc b/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.cc index 3c7e072c..d9c9442 100644 --- a/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.cc +++ b/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.cc
@@ -16,6 +16,7 @@ #include "chrome/browser/ui/webui/dark_mode_handler.h" #include "chrome/browser/ui/webui/managed_ui_handler.h" #include "chrome/browser/ui/webui/metrics_handler.h" +#include "chrome/browser/ui/webui/plural_string_handler.h" #include "chrome/browser/ui/webui/settings/about_handler.h" #include "chrome/browser/ui/webui/settings/accessibility_main_handler.h" #include "chrome/browser/ui/webui/settings/appearance_handler.h" @@ -34,11 +35,14 @@ #include "chrome/browser/web_applications/system_web_app_manager.h" #include "chrome/common/webui_url_constants.h" #include "chrome/grit/browser_resources.h" +#include "chrome/grit/generated_resources.h" #include "chrome/grit/os_settings_resources.h" #include "chrome/grit/os_settings_resources_map.h" +#include "chromeos/services/network_config/public/mojom/constants.mojom.h" #include "components/password_manager/core/common/password_manager_features.h" #include "components/unified_consent/feature.h" #include "content/public/browser/web_ui_data_source.h" +#include "services/service_manager/public/cpp/connector.h" #if defined(FULL_SAFE_BROWSING) #include "chrome/browser/safe_browsing/chrome_password_protection_service.h" @@ -49,7 +53,7 @@ namespace settings { OSSettingsUI::OSSettingsUI(content::WebUI* web_ui) - : content::WebUIController(web_ui) { + : ui::MojoWebUIController(web_ui, /*enable_chrome_send =*/true) { Profile* profile = Profile::FromWebUI(web_ui); content::WebUIDataSource* html_source = content::WebUIDataSource::Create(chrome::kChromeUIOSSettingsHost); @@ -135,14 +139,22 @@ ::settings::AddLocalizedStrings(html_source, profile); + auto plural_string_handler = std::make_unique<PluralStringHandler>(); + plural_string_handler->AddLocalizedString("profileLabel", + IDS_OS_SETTINGS_PROFILE_LABEL); + web_ui->AddMessageHandler(std::move(plural_string_handler)); + DarkModeHandler::Initialize(web_ui, html_source); ManagedUIHandler::Initialize(web_ui, html_source); content::WebUIDataSource::Add(web_ui->GetWebContents()->GetBrowserContext(), html_source); + + AddHandlerToRegistry(base::BindRepeating(&OSSettingsUI::BindCrosNetworkConfig, + base::Unretained(this))); } -OSSettingsUI::~OSSettingsUI() {} +OSSettingsUI::~OSSettingsUI() = default; void OSSettingsUI::AddSettingsPageUIHandler( std::unique_ptr<content::WebUIMessageHandler> handler) { @@ -150,5 +162,12 @@ web_ui()->AddMessageHandler(std::move(handler)); } +void OSSettingsUI::BindCrosNetworkConfig( + network_config::mojom::CrosNetworkConfigRequest request) { + content::BrowserContext::GetConnectorFor( + web_ui()->GetWebContents()->GetBrowserContext()) + ->BindInterface(network_config::mojom::kServiceName, std::move(request)); +} + } // namespace settings } // namespace chromeos
diff --git a/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h b/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h index 569ac7e..983a621 100644 --- a/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h +++ b/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h
@@ -8,7 +8,9 @@ #include <memory> #include "base/macros.h" +#include "chromeos/services/network_config/public/mojom/cros_network_config.mojom.h" #include "content/public/browser/web_ui_controller.h" +#include "ui/webui/mojo_web_ui_controller.h" namespace content { class WebUIMessageHandler; @@ -18,7 +20,7 @@ namespace settings { // The WebUI handler for chrome://settings. -class OSSettingsUI : public content::WebUIController { +class OSSettingsUI : public ui::MojoWebUIController { public: explicit OSSettingsUI(content::WebUI* web_ui); ~OSSettingsUI() override; @@ -26,6 +28,8 @@ private: void AddSettingsPageUIHandler( std::unique_ptr<content::WebUIMessageHandler> handler); + void BindCrosNetworkConfig( + network_config::mojom::CrosNetworkConfigRequest request); // TODO(crbug/950007): Create load histograms and embed WebuiLoadTimer.
diff --git a/chrome/browser/ui/webui/settings/settings_ui.cc b/chrome/browser/ui/webui/settings/settings_ui.cc index e0e9d2a6..61d1075 100644 --- a/chrome/browser/ui/webui/settings/settings_ui.cc +++ b/chrome/browser/ui/webui/settings/settings_ui.cc
@@ -119,8 +119,10 @@ #include "chromeos/constants/chromeos_pref_names.h" #include "chromeos/constants/chromeos_switches.h" #include "chromeos/services/multidevice_setup/public/cpp/prefs.h" +#include "chromeos/services/network_config/public/mojom/constants.mojom.h" #include "components/arc/arc_util.h" #include "components/prefs/pref_service.h" +#include "services/service_manager/public/cpp/connector.h" #include "ui/base/ui_base_features.h" #include "ui/chromeos/resources/grit/ui_chromeos_resources.h" #else // !defined(OS_CHROMEOS) @@ -147,6 +149,24 @@ namespace settings { +namespace { + +#if defined(OS_CHROMEOS) +bool ShouldShowParentalControls(Profile* profile) { + // Show Parental controls for regular and child accounts that are the + // primary profile. Do not show it to any secondary profiles, managed + // accounts that aren't child accounts (i.e. enterprise and EDU accounts), + // OTR accounts, or legacy supervised user accounts. + return chromeos::switches::IsParentalControlsSettingsEnabled() && + profile == ProfileManager::GetPrimaryUserProfile() && + !profile->IsLegacySupervised() && !profile->IsGuestSession() && + (profile->IsChild() || + !profile->GetProfilePolicyConnector()->IsManaged()); +} +#endif // defined(OS_CHROMEOS) + +} // namespace + // static void SettingsUI::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { @@ -158,7 +178,11 @@ } SettingsUI::SettingsUI(content::WebUI* web_ui) +#if defined(OS_CHROMEOS) + : ui::MojoWebUIController(web_ui, /*enable_chrome_send =*/true), +#else : content::WebUIController(web_ui), +#endif webui_load_timer_(web_ui->GetWebContents(), "Settings.LoadDocumentTime.MD", "Settings.LoadCompletedTime.MD") { @@ -321,29 +345,14 @@ content::WebUIDataSource::Add(web_ui->GetWebContents()->GetBrowserContext(), html_source); -} - -SettingsUI::~SettingsUI() {} #if defined(OS_CHROMEOS) -bool SettingsUI::ShouldShowParentalControls(Profile* profile) { - // Show Parental controls for regular and child accounts that are the - // primary profile. Do not show it to any secondary profiles, managed - // accounts that aren't child accounts (i.e. enterprise and EDU accounts), - // OTR accounts, or legacy supervised user accounts. - return chromeos::switches::IsParentalControlsSettingsEnabled() && - profile == ProfileManager::GetPrimaryUserProfile() && - !profile->IsLegacySupervised() && !profile->IsGuestSession() && - (profile->IsChild() || - !profile->GetProfilePolicyConnector()->IsManaged()); + AddHandlerToRegistry(base::BindRepeating(&SettingsUI::BindCrosNetworkConfig, + base::Unretained(this))); +#endif // defined (OS_CHROMEOS) } -#endif -void SettingsUI::AddSettingsPageUIHandler( - std::unique_ptr<content::WebUIMessageHandler> handler) { - DCHECK(handler); - web_ui()->AddMessageHandler(std::move(handler)); -} +SettingsUI::~SettingsUI() = default; #if defined(OS_CHROMEOS) // static @@ -518,4 +527,20 @@ } #endif // defined(OS_CHROMEOS) +void SettingsUI::AddSettingsPageUIHandler( + std::unique_ptr<content::WebUIMessageHandler> handler) { + DCHECK(handler); + web_ui()->AddMessageHandler(std::move(handler)); +} + +#if defined(OS_CHROMEOS) +void SettingsUI::BindCrosNetworkConfig( + chromeos::network_config::mojom::CrosNetworkConfigRequest request) { + content::BrowserContext::GetConnectorFor( + web_ui()->GetWebContents()->GetBrowserContext()) + ->BindInterface(chromeos::network_config::mojom::kServiceName, + std::move(request)); +} +#endif // defined(OS_CHROMEOS) + } // namespace settings
diff --git a/chrome/browser/ui/webui/settings/settings_ui.h b/chrome/browser/ui/webui/settings/settings_ui.h index 6bda0ad..45703738 100644 --- a/chrome/browser/ui/webui/settings/settings_ui.h +++ b/chrome/browser/ui/webui/settings/settings_ui.h
@@ -8,7 +8,13 @@ #include "base/macros.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/webui_load_timer.h" + +#if defined(OS_CHROMEOS) +#include "chromeos/services/network_config/public/mojom/cros_network_config.mojom.h" +#include "ui/webui/mojo_web_ui_controller.h" +#else #include "content/public/browser/web_ui_controller.h" +#endif class Profile; @@ -24,7 +30,13 @@ namespace settings { // The WebUI handler for chrome://settings. -class SettingsUI : public content::WebUIController { +class SettingsUI +#if defined(OS_CHROMEOS) + : public ui::MojoWebUIController +#else + : public content::WebUIController +#endif +{ public: static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); @@ -36,13 +48,15 @@ static void InitOSWebUIHandlers(Profile* profile, content::WebUI* web_ui, content::WebUIDataSource* html_source); - - static bool ShouldShowParentalControls(Profile* profile); #endif // defined(OS_CHROMEOS) private: void AddSettingsPageUIHandler( std::unique_ptr<content::WebUIMessageHandler> handler); +#if defined(OS_CHROMEOS) + void BindCrosNetworkConfig( + chromeos::network_config::mojom::CrosNetworkConfigRequest request); +#endif WebuiLoadTimer webui_load_timer_;
diff --git a/chrome/browser/ui/webui/sync_internals_browsertest.js b/chrome/browser/ui/webui/sync_internals_browsertest.js index ede5673..9a179ff 100644 --- a/chrome/browser/ui/webui/sync_internals_browsertest.js +++ b/chrome/browser/ui/webui/sync_internals_browsertest.js
@@ -260,8 +260,9 @@ // set. TEST_F('SyncInternalsWebUITest', 'SyncDisabledByDefault', function() { expectTrue(this.hasInDetails(true, 'Transport State', 'Disabled')); - expectTrue( - this.hasInDetails(true, 'Disable Reasons', 'Not signed in, User choice')); + // TODO(crbug.com/906034,crbug.com/973770): Sort out the proper default value + // for IsSyncRequested() and possibly add the "User choice" disable reason. + expectTrue(this.hasInDetails(true, 'Disable Reasons', 'Not signed in')); expectTrue(this.hasInDetails(true, 'Username', '')); });
diff --git a/chrome/common/chrome_features.cc b/chrome/common/chrome_features.cc index 454636e..dbbce4f 100644 --- a/chrome/common/chrome_features.cc +++ b/chrome/common/chrome_features.cc
@@ -596,11 +596,6 @@ const base::Feature kSiteSettings{"SiteSettings", base::FEATURE_ENABLED_BY_DEFAULT}; -// Enables committed error pages instead of transient navigation entries for -// SSL interstitial error pages (i.e. certificate errors). -const base::Feature kSSLCommittedInterstitials{ - "SSLCommittedInterstitials", base::FEATURE_ENABLED_BY_DEFAULT}; - #if defined(OS_CHROMEOS) // Enables or disables automatic setup of USB printers. const base::Feature kStreamlinedUsbPrinterSetup{
diff --git a/chrome/common/chrome_features.h b/chrome/common/chrome_features.h index 88ddbfd..099548f 100644 --- a/chrome/common/chrome_features.h +++ b/chrome/common/chrome_features.h
@@ -377,9 +377,6 @@ COMPONENT_EXPORT(CHROME_FEATURES) extern const char kSitePerProcessOnlyForHighMemoryClientsParamName[]; -COMPONENT_EXPORT(CHROME_FEATURES) -extern const base::Feature kSSLCommittedInterstitials; - #if defined(OS_CHROMEOS) COMPONENT_EXPORT(CHROME_FEATURES) extern const base::Feature kStreamlinedUsbPrinterSetup;
diff --git a/chrome/lib/DEPS b/chrome/lib/DEPS index 18d28d37..dd4dbb7d 100644 --- a/chrome/lib/DEPS +++ b/chrome/lib/DEPS
@@ -1,6 +1,16 @@ noparent = True include_rules = [ + "+base/android", + + "-content/public/android", + "+content/public/android/java/src/org/chromium/content_public", + + # Targets under chrome/lib should generally be independent from browser code. "-chrome/android", "-chrome/browser", + + # Each directory should only cross-depend on public dirs. + # e.g. +chrome/lib/<name>/public for each feature they depend on. + "-chrome/lib", ]
diff --git a/chrome/lib/image_fetcher/DEPS b/chrome/lib/image_fetcher/DEPS new file mode 100644 index 0000000..4e42d6b6 --- /dev/null +++ b/chrome/lib/image_fetcher/DEPS
@@ -0,0 +1,6 @@ +include_rules = [ + # TODO(crbug/973821): Temporary until profiles is moved to chrome/lib. + "+chrome/android/public/profiles", + + "+chrome/lib/util/public", +]
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/image_fetcher/OWNERS b/chrome/lib/image_fetcher/OWNERS similarity index 100% rename from chrome/android/java/src/org/chromium/chrome/browser/image_fetcher/OWNERS rename to chrome/lib/image_fetcher/OWNERS
diff --git a/chrome/lib/image_fetcher/public/android/BUILD.gn b/chrome/lib/image_fetcher/public/android/BUILD.gn new file mode 100644 index 0000000..02ba3114 --- /dev/null +++ b/chrome/lib/image_fetcher/public/android/BUILD.gn
@@ -0,0 +1,32 @@ +# 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. + +import("//build/config/android/rules.gni") + +android_library("java") { + deps = [ + "//base:base_java", + "//chrome/android/public/profiles:java", + "//chrome/lib/util/public/android:java", + "//content/public/android:content_java", + "//third_party/gif_player:gif_player_java", + ] + java_files = [ + "java/src/org/chromium/chrome/browser/image_fetcher/CachedImageFetcher.java", + "java/src/org/chromium/chrome/browser/image_fetcher/ImageFetcherBridge.java", + "java/src/org/chromium/chrome/browser/image_fetcher/ImageFetcherFactory.java", + "java/src/org/chromium/chrome/browser/image_fetcher/ImageFetcher.java", + "java/src/org/chromium/chrome/browser/image_fetcher/InMemoryCachedImageFetcher.java", + "java/src/org/chromium/chrome/browser/image_fetcher/NetworkImageFetcher.java", + ] + + srcjar_deps = [ "//components/image_fetcher/core:java_enums_srcjar" ] +} + +generate_jni("jni_headers") { + sources = [ + "java/src/org/chromium/chrome/browser/image_fetcher/ImageFetcherBridge.java", + ] + jni_package = "chrome" +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/image_fetcher/CachedImageFetcher.java b/chrome/lib/image_fetcher/public/android/java/src/org/chromium/chrome/browser/image_fetcher/CachedImageFetcher.java similarity index 100% rename from chrome/android/java/src/org/chromium/chrome/browser/image_fetcher/CachedImageFetcher.java rename to chrome/lib/image_fetcher/public/android/java/src/org/chromium/chrome/browser/image_fetcher/CachedImageFetcher.java
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/image_fetcher/ImageFetcher.java b/chrome/lib/image_fetcher/public/android/java/src/org/chromium/chrome/browser/image_fetcher/ImageFetcher.java similarity index 100% rename from chrome/android/java/src/org/chromium/chrome/browser/image_fetcher/ImageFetcher.java rename to chrome/lib/image_fetcher/public/android/java/src/org/chromium/chrome/browser/image_fetcher/ImageFetcher.java
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/image_fetcher/ImageFetcherBridge.java b/chrome/lib/image_fetcher/public/android/java/src/org/chromium/chrome/browser/image_fetcher/ImageFetcherBridge.java similarity index 100% rename from chrome/android/java/src/org/chromium/chrome/browser/image_fetcher/ImageFetcherBridge.java rename to chrome/lib/image_fetcher/public/android/java/src/org/chromium/chrome/browser/image_fetcher/ImageFetcherBridge.java
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/image_fetcher/ImageFetcherFactory.java b/chrome/lib/image_fetcher/public/android/java/src/org/chromium/chrome/browser/image_fetcher/ImageFetcherFactory.java similarity index 100% rename from chrome/android/java/src/org/chromium/chrome/browser/image_fetcher/ImageFetcherFactory.java rename to chrome/lib/image_fetcher/public/android/java/src/org/chromium/chrome/browser/image_fetcher/ImageFetcherFactory.java
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/image_fetcher/InMemoryCachedImageFetcher.java b/chrome/lib/image_fetcher/public/android/java/src/org/chromium/chrome/browser/image_fetcher/InMemoryCachedImageFetcher.java similarity index 100% rename from chrome/android/java/src/org/chromium/chrome/browser/image_fetcher/InMemoryCachedImageFetcher.java rename to chrome/lib/image_fetcher/public/android/java/src/org/chromium/chrome/browser/image_fetcher/InMemoryCachedImageFetcher.java
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/image_fetcher/NetworkImageFetcher.java b/chrome/lib/image_fetcher/public/android/java/src/org/chromium/chrome/browser/image_fetcher/NetworkImageFetcher.java similarity index 100% rename from chrome/android/java/src/org/chromium/chrome/browser/image_fetcher/NetworkImageFetcher.java rename to chrome/lib/image_fetcher/public/android/java/src/org/chromium/chrome/browser/image_fetcher/NetworkImageFetcher.java
diff --git a/chrome/lib/util/OWNERS b/chrome/lib/util/OWNERS new file mode 100644 index 0000000..6c29cd21 --- /dev/null +++ b/chrome/lib/util/OWNERS
@@ -0,0 +1,5 @@ +mdjones@chromium.org +twellington@chromium.org + +# TEAM: chrome-android-app@chromium.org +# COMPONENT: UI>Browser>Mobile
diff --git a/chrome/lib/util/public/android/BUILD.gn b/chrome/lib/util/public/android/BUILD.gn new file mode 100644 index 0000000..e2c26ab --- /dev/null +++ b/chrome/lib/util/public/android/BUILD.gn
@@ -0,0 +1,32 @@ +# 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. + +import("//build/config/android/rules.gni") + +android_library("java") { + deps = [ + "//base:base_java", + "//content/public/android:content_java", + "//third_party/android_deps:com_android_support_support_compat_java", + "//third_party/android_deps:com_android_support_support_core_utils_java", + ] + java_files = [ + "java/src/org/chromium/chrome/browser/util/BitmapCache.java", + "java/src/org/chromium/chrome/browser/util/ConversionUtils.java", + "java/src/org/chromium/chrome/browser/util/FileSizeUtil.java", + "java/src/org/chromium/chrome/browser/util/KeyNavigationUtil.java", + "java/src/org/chromium/chrome/browser/util/MathUtils.java", + "java/src/org/chromium/chrome/browser/util/ChromeFileProvider.java", + "java/src/org/chromium/chrome/browser/util/UrlConstants.java", + "java/src/org/chromium/chrome/browser/util/UrlUtilities.java", + "java/src/org/chromium/chrome/browser/util/HashUtil.java", + ] +} + +generate_jni("jni_headers") { + sources = [ + "java/src/org/chromium/chrome/browser/util/UrlUtilities.java", + ] + jni_package = "chrome" +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/util/BitmapCache.java b/chrome/lib/util/public/android/java/src/org/chromium/chrome/browser/util/BitmapCache.java similarity index 96% rename from chrome/android/java/src/org/chromium/chrome/browser/util/BitmapCache.java rename to chrome/lib/util/public/android/java/src/org/chromium/chrome/browser/util/BitmapCache.java index 690eff3..d95ac95 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/util/BitmapCache.java +++ b/chrome/lib/util/public/android/java/src/org/chromium/chrome/browser/util/BitmapCache.java
@@ -14,7 +14,6 @@ import org.chromium.base.SysUtils; import org.chromium.base.ThreadUtils; import org.chromium.base.VisibleForTesting; -import org.chromium.chrome.browser.ChromeApplication; import java.lang.ref.WeakReference; import java.util.HashMap; @@ -82,8 +81,8 @@ * * This constructor must be called on UI thread. * - * @param referencePool The discardable reference pool. See - * {@link ChromeApplication#getReferencePool}. + * @param referencePool The discardable reference pool. Typically this should be the + * {@link DiscardableReferencePool} for the application. * @param size The capacity of the cache in bytes. */ public BitmapCache(DiscardableReferencePool referencePool, int size) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/util/ChromeFileProvider.java b/chrome/lib/util/public/android/java/src/org/chromium/chrome/browser/util/ChromeFileProvider.java similarity index 100% rename from chrome/android/java/src/org/chromium/chrome/browser/util/ChromeFileProvider.java rename to chrome/lib/util/public/android/java/src/org/chromium/chrome/browser/util/ChromeFileProvider.java
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/util/ConversionUtils.java b/chrome/lib/util/public/android/java/src/org/chromium/chrome/browser/util/ConversionUtils.java similarity index 100% rename from chrome/android/java/src/org/chromium/chrome/browser/util/ConversionUtils.java rename to chrome/lib/util/public/android/java/src/org/chromium/chrome/browser/util/ConversionUtils.java
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/util/FileSizeUtil.java b/chrome/lib/util/public/android/java/src/org/chromium/chrome/browser/util/FileSizeUtil.java similarity index 100% rename from chrome/android/java/src/org/chromium/chrome/browser/util/FileSizeUtil.java rename to chrome/lib/util/public/android/java/src/org/chromium/chrome/browser/util/FileSizeUtil.java
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/util/HashUtil.java b/chrome/lib/util/public/android/java/src/org/chromium/chrome/browser/util/HashUtil.java similarity index 97% rename from chrome/android/java/src/org/chromium/chrome/browser/util/HashUtil.java rename to chrome/lib/util/public/android/java/src/org/chromium/chrome/browser/util/HashUtil.java index 538b1bee..ee9abf0 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/util/HashUtil.java +++ b/chrome/lib/util/public/android/java/src/org/chromium/chrome/browser/util/HashUtil.java
@@ -18,8 +18,7 @@ public final class HashUtil { private static final String TAG = "HashUtil"; - private HashUtil() { - } + private HashUtil() {} public static class Params { private final String mText;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/util/KeyNavigationUtil.java b/chrome/lib/util/public/android/java/src/org/chromium/chrome/browser/util/KeyNavigationUtil.java similarity index 72% rename from chrome/android/java/src/org/chromium/chrome/browser/util/KeyNavigationUtil.java rename to chrome/lib/util/public/android/java/src/org/chromium/chrome/browser/util/KeyNavigationUtil.java index c80ac56..be18b30 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/util/KeyNavigationUtil.java +++ b/chrome/lib/util/public/android/java/src/org/chromium/chrome/browser/util/KeyNavigationUtil.java
@@ -10,12 +10,10 @@ * This is a helper class to handle navigation related checks for key events. */ public class KeyNavigationUtil { - /** * This is a helper class with no instance. */ - private KeyNavigationUtil() { - } + private KeyNavigationUtil() {} /** * Checks whether the given event is any of DPAD down or NUMPAD down. @@ -23,8 +21,10 @@ * @return Whether the event should be processed as a navigation down. */ public static boolean isGoDown(KeyEvent event) { - return isActionDown(event) && (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_DOWN - || (!event.isNumLockOn() && event.getKeyCode() == KeyEvent.KEYCODE_NUMPAD_2)); + return isActionDown(event) + && (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_DOWN + || (!event.isNumLockOn() + && event.getKeyCode() == KeyEvent.KEYCODE_NUMPAD_2)); } /** @@ -33,8 +33,10 @@ * @return Whether the event should be processed as a navigation up. */ public static boolean isGoUp(KeyEvent event) { - return isActionDown(event) && (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_UP - || (!event.isNumLockOn() && event.getKeyCode() == KeyEvent.KEYCODE_NUMPAD_8)); + return isActionDown(event) + && (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_UP + || (!event.isNumLockOn() + && event.getKeyCode() == KeyEvent.KEYCODE_NUMPAD_8)); } /** @@ -43,8 +45,10 @@ * @return Whether the event should be processed as a navigation right. */ public static boolean isGoRight(KeyEvent event) { - return isActionDown(event) && (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT - || (!event.isNumLockOn() && event.getKeyCode() == KeyEvent.KEYCODE_NUMPAD_6)); + return isActionDown(event) + && (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT + || (!event.isNumLockOn() + && event.getKeyCode() == KeyEvent.KEYCODE_NUMPAD_6)); } /** @@ -62,8 +66,9 @@ * @return Whether the event should be processed as ENTER. */ public static boolean isEnter(KeyEvent event) { - return isActionUp(event) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER - || event.getKeyCode() == KeyEvent.KEYCODE_NUMPAD_ENTER); + return isActionUp(event) + && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER + || event.getKeyCode() == KeyEvent.KEYCODE_NUMPAD_ENTER); } /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/util/MathUtils.java b/chrome/lib/util/public/android/java/src/org/chromium/chrome/browser/util/MathUtils.java similarity index 96% rename from chrome/android/java/src/org/chromium/chrome/browser/util/MathUtils.java rename to chrome/lib/util/public/android/java/src/org/chromium/chrome/browser/util/MathUtils.java index 65e43e2..82395ae 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/util/MathUtils.java +++ b/chrome/lib/util/public/android/java/src/org/chromium/chrome/browser/util/MathUtils.java
@@ -8,7 +8,6 @@ * Contains various math utilities used throughout Chrome Mobile. */ public class MathUtils { - /** A minimum difference to use when comparing floats for equality. */ public static final float EPSILON = 0.001f; @@ -116,16 +115,14 @@ * @param targetHeight The target height * @return The scale factor applied to dimensions */ - public static float scaleToFitTargetSize( - int [] dimensions, int targetWidth, int targetHeight) { + public static float scaleToFitTargetSize(int[] dimensions, int targetWidth, int targetHeight) { if (dimensions.length < 2 || dimensions[0] <= 0 || dimensions[1] <= 0) { throw new IllegalArgumentException( "Expected dimensions to have length >= 2 && dimensions[0] > 0 && " + "dimensions[1] > 0"); } - float scale = Math.max( - (float) targetWidth / dimensions[0], - (float) targetHeight / dimensions[1]); + float scale = + Math.max((float) targetWidth / dimensions[0], (float) targetHeight / dimensions[1]); dimensions[0] = (int) (dimensions[0] * scale); dimensions[1] = (int) (dimensions[1] * scale); return scale;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/util/UrlConstants.java b/chrome/lib/util/public/android/java/src/org/chromium/chrome/browser/util/UrlConstants.java similarity index 100% rename from chrome/android/java/src/org/chromium/chrome/browser/util/UrlConstants.java rename to chrome/lib/util/public/android/java/src/org/chromium/chrome/browser/util/UrlConstants.java
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/util/UrlUtilities.java b/chrome/lib/util/public/android/java/src/org/chromium/chrome/browser/util/UrlUtilities.java similarity index 94% rename from chrome/android/java/src/org/chromium/chrome/browser/util/UrlUtilities.java rename to chrome/lib/util/public/android/java/src/org/chromium/chrome/browser/util/UrlUtilities.java index 25e1a65a..87666af 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/util/UrlUtilities.java +++ b/chrome/lib/util/public/android/java/src/org/chromium/chrome/browser/util/UrlUtilities.java
@@ -40,14 +40,10 @@ ContentUrlConstants.ABOUT_SCHEME); // Patterns used in validateIntentUrl. - private static final Pattern DNS_HOSTNAME_PATTERN = - Pattern.compile("^[\\w\\.-]*$"); - private static final Pattern JAVA_PACKAGE_NAME_PATTERN = - Pattern.compile("^[\\w\\.-]*$"); - private static final Pattern ANDROID_COMPONENT_NAME_PATTERN = - Pattern.compile("^[\\w\\./-]*$"); - private static final Pattern URL_SCHEME_PATTERN = - Pattern.compile("^[a-zA-Z]+$"); + private static final Pattern DNS_HOSTNAME_PATTERN = Pattern.compile("^[\\w\\.-]*$"); + private static final Pattern JAVA_PACKAGE_NAME_PATTERN = Pattern.compile("^[\\w\\.-]*$"); + private static final Pattern ANDROID_COMPONENT_NAME_PATTERN = Pattern.compile("^[\\w\\./-]*$"); + private static final Pattern URL_SCHEME_PATTERN = Pattern.compile("^[a-zA-Z]+$"); private static final String TEL_URL_PREFIX = "tel:"; @@ -144,8 +140,8 @@ * @param includePrivateRegistries Whether or not to consider private registries. * @return True iff the two URIs belong to the same domain or host. */ - public static boolean sameDomainOrHost(String primaryUrl, String secondaryUrl, - boolean includePrivateRegistries) { + public static boolean sameDomainOrHost( + String primaryUrl, String secondaryUrl, boolean includePrivateRegistries) { return nativeSameDomainOrHost(primaryUrl, secondaryUrl, includePrivateRegistries); } @@ -266,8 +262,7 @@ // Now lex and parse the correctly-encoded fragment. String[] parts = fragment.split(";"); - if (parts.length < 3 - || !parts[0].equals("Intent") + if (parts.length < 3 || !parts[0].equals("Intent") || !parts[parts.length - 1].equals("end")) { Log.d(TAG, "Invalid fragment (not enough parts, lacking Intent, or lacking end)"); return false; @@ -363,10 +358,10 @@ private static native boolean nativeIsDownloadable(String url); private static native boolean nativeIsValidForIntentFallbackNavigation(String url); private static native boolean nativeIsAcceptedScheme(String url); - private static native boolean nativeSameDomainOrHost(String primaryUrl, String secondaryUrl, - boolean includePrivateRegistries); - private static native String nativeGetDomainAndRegistry(String url, - boolean includePrivateRegistries); + private static native boolean nativeSameDomainOrHost( + String primaryUrl, String secondaryUrl, boolean includePrivateRegistries); + private static native String nativeGetDomainAndRegistry( + String url, boolean includePrivateRegistries); /** Returns whether the given URL uses the Google.com domain. */ public static native boolean nativeIsGoogleDomainUrl(String url, boolean allowNonStandardPort); /** Returns whether the given URL is a Google.com domain or sub-domain. */
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 0173305..e7cea90 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -2121,6 +2121,7 @@ "../browser/extensions/api/certificate_provider/certificate_provider_apitest.cc", "../browser/extensions/api/networking_private/networking_private_apitest.cc", "../browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc", + "../browser/extensions/api/settings_private/settings_private_browsertest_chromeos.cc", "../browser/extensions/api/vpn_provider/vpn_provider_apitest.cc", "../browser/extensions/chromeos_component_extensions_browsertest.cc", "../browser/notifications/notification_platform_bridge_chromeos_browsertest.cc", @@ -6190,6 +6191,14 @@ "//tools/skia_goldctl/goldctl", ] } + if (!is_mac) { + data += [ + "$root_out_dir/locales/", + "$root_out_dir/chrome_100_percent.pak", + "$root_out_dir/chrome_200_percent.pak", + "$root_out_dir/resources.pak", + ] + } } }
diff --git a/chrome/test/data/extensions/api_test/automation/sites/word_boundaries.html b/chrome/test/data/extensions/api_test/automation/sites/word_boundaries.html new file mode 100644 index 0000000..efe4252 --- /dev/null +++ b/chrome/test/data/extensions/api_test/automation/sites/word_boundaries.html
@@ -0,0 +1,14 @@ +<!-- + * 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. +--> +<html> +<head> +<title>Automation Tests - Word Boundaries</title> +</head> +<body> + <!-- Used to test wordBoundariesForString. --> + <div role="button">Example text for testing purposes</div> +</body> +</html>
diff --git a/chrome/test/data/extensions/api_test/automation/tests/tabs/word_boundaries.html b/chrome/test/data/extensions/api_test/automation/tests/tabs/word_boundaries.html new file mode 100644 index 0000000..77b91490 --- /dev/null +++ b/chrome/test/data/extensions/api_test/automation/tests/tabs/word_boundaries.html
@@ -0,0 +1,7 @@ +<!-- + * 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. +--> +<script src="common.js"></script> +<script src="word_boundaries.js"></script>
diff --git a/chrome/test/data/extensions/api_test/automation/tests/tabs/word_boundaries.js b/chrome/test/data/extensions/api_test/automation/tests/tabs/word_boundaries.js new file mode 100644 index 0000000..c7eb014 --- /dev/null +++ b/chrome/test/data/extensions/api_test/automation/tests/tabs/word_boundaries.js
@@ -0,0 +1,24 @@ +// 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. + +var allTests = [ + function testWordStartAndEndOffsets() { + var node = rootNode.find( + { attributes: { name: 'Example text for testing purposes' } }); + var expectedWordStarts = [0, 8, 13, 17, 25]; + var expectedWordEnds = [7, 12, 16, 24, 33]; + var wordStarts = node.wordStartOffsets(); + var wordEnds = node.wordEndOffsets(); + assertEq(expectedWordStarts.length, wordStarts.length); + assertEq(expectedWordEnds.length, wordEnds.length); + assertEq(wordStarts.length, wordEnds.length); + for (var i = 0; i < expectedWordStarts.length; ++i){ + assertEq(expectedWordStarts[i], wordStarts[i]); + assertEq(expectedWordEnds[i], wordEnds[i]); + } + chrome.test.succeed(); + } +]; + +setUpAndRunTests(allTests, 'word_boundaries.html');
diff --git a/chrome/test/data/extensions/api_test/service_worker/filtered_events_after_restart/a.js b/chrome/test/data/extensions/api_test/service_worker/filtered_events_after_restart/a.js deleted file mode 100644 index 0800553..0000000 --- a/chrome/test/data/extensions/api_test/service_worker/filtered_events_after_restart/a.js +++ /dev/null
@@ -1,7 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -onload = function() { - document.location = 'b.html'; -}
diff --git a/chrome/test/data/local_ntp/voice_text_browsertest.js b/chrome/test/data/local_ntp/voice_text_browsertest.js index fb804c7..8068c5e 100644 --- a/chrome/test/data/local_ntp/voice_text_browsertest.js +++ b/chrome/test/data/local_ntp/voice_text_browsertest.js
@@ -113,21 +113,20 @@ /** * Test clearing the text elements. */ -// TODO(crbug.com/960622) Disabling for flakyness. Please consider migrating -// the test to a default testing framework that supports a means to disable -// tests beyond uncommenting it. -/* test.text.testClearText = function() { const interimText = 'interim '.repeat(100); const finalText = 'final '.repeat(100); + // Explicitly set height to some large number in order to have 5 text lines, + // which will be case if height exceeds a calculated maximum. + text.interim_.style.height = '1000px'; assertEquals('voice-text', text.interim_.className); assertEquals('voice-text', text.final_.className); text.updateTextArea(interimText, finalText); assertEquals(interimText, text.interim_.textContent); assertEquals(finalText, text.final_.textContent); - assertEquals('voice-text voice-text-3l', text.interim_.className); - assertEquals('voice-text voice-text-3l', text.final_.className); + assertEquals('voice-text voice-text-5l', text.interim_.className); + assertEquals('voice-text voice-text-5l', text.final_.className); text.clear(); assertEquals('', text.interim_.textContent); @@ -135,7 +134,6 @@ assertEquals('voice-text', text.interim_.className); assertEquals('voice-text', text.final_.className); }; -*/ /**
diff --git a/chrome/test/data/webui/BUILD.gn b/chrome/test/data/webui/BUILD.gn index f8b0448..60cbc7c0 100644 --- a/chrome/test/data/webui/BUILD.gn +++ b/chrome/test/data/webui/BUILD.gn
@@ -105,6 +105,7 @@ "settings/a11y/crostini_settings_shared_paths_a11y_test.js", "settings/a11y/crostini_settings_shared_usb_devices_a11y_test.js", "settings/a11y/crostini_settings_subpage_a11y_test.js", + "settings/a11y/google_assistant_a11y_test.js", "settings/a11y/manage_accessibility_a11y_test.js", "settings/a11y/multidevice_a11y_test.js", "settings/a11y/multidevice_features_a11y_test.js",
diff --git a/chrome/test/data/webui/chromeos/fake_network_config_mojom.js b/chrome/test/data/webui/chromeos/fake_network_config_mojom.js new file mode 100644 index 0000000..13cfbde --- /dev/null +++ b/chrome/test/data/webui/chromeos/fake_network_config_mojom.js
@@ -0,0 +1,32 @@ +// 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. + +/** + * @fileoverview Fake implementation of CrosNetworkConfig for testing. + * Currently this is built on top of FakeNetworkingPrivate to avoid + * inconsistencies between fakes in tests. + */ + +// TODO(stevenjb): Include cros_network_config.mojom.js and extend +// CrosNetworkConfigInterface +class FakeNetworkConfig { + /** @param {!NetworkingPrivate} extensionApi */ + constructor(extensionApi) { + this.extensionApi_ = extensionApi; + } + + /** + * @param {!chromeos.networkConfig.mojom.NetworkType} type + * @param {boolean} enabled + * @return {!Promise<{success: boolean}>} + */ + setNetworkTypeEnabledState(type, enabled) { + if (enabled) { + this.extensionApi_.enableNetworkType(OncMojo.getNetworkTypeString(type)); + } else { + this.extensionApi_.disableNetworkType(OncMojo.getNetworkTypeString(type)); + } + return Promise.resolve(true); + } +}
diff --git a/chrome/test/data/webui/settings/a11y/google_assistant_a11y_test.js b/chrome/test/data/webui/settings/a11y/google_assistant_a11y_test.js new file mode 100644 index 0000000..727f068e --- /dev/null +++ b/chrome/test/data/webui/settings/a11y/google_assistant_a11y_test.js
@@ -0,0 +1,41 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * @fileoverview Define accessibility tests for the GOOGLE_ASSISTANT route. + * Chrome OS only. + */ + +// SettingsAccessibilityTest fixture. +GEN_INCLUDE([ + 'settings_accessibility_test.js', +]); + +GEN('#include "chromeos/constants/chromeos_switches.h"'); + +// eslint-disable-next-line no-var +var GoogleAssistantAccessibilityTest = class extends SettingsAccessibilityTest { + /** @override */ + get featureList() { + return {enabled: ['chromeos::switches::kAssistantFeature']}; + } +}; + +AccessibilityTest.define('GoogleAssistantAccessibilityTest', { + /** @override */ + name: 'GOOGLE_ASSISTANT', + /** @override */ + axeOptions: GoogleAssistantAccessibilityTest.axeOptions, + /** @override */ + violationFilter: GoogleAssistantAccessibilityTest.violationFilter, + + /** @override */ + setup: function() { + settings.router.navigateTo(settings.routes.GOOGLE_ASSISTANT); + Polymer.dom.flush(); + }, + + /** @override */ + tests: {'Accessible with No Changes': function() {}}, +});
diff --git a/chrome/test/data/webui/settings/chromeos/os_people_page_test.js b/chrome/test/data/webui/settings/chromeos/os_people_page_test.js new file mode 100644 index 0000000..01e04e2 --- /dev/null +++ b/chrome/test/data/webui/settings/chromeos/os_people_page_test.js
@@ -0,0 +1,141 @@ +// 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. + +cr.define('settings_people_page', function() { + /** @implements {settings.AccountManagerBrowserProxy} */ + class TestAccountManagerBrowserProxy extends TestBrowserProxy { + constructor() { + super([ + 'getAccounts', + 'addAccount', + 'reauthenticateAccount', + 'removeAccount', + 'showWelcomeDialogIfRequired', + ]); + } + + /** @override */ + getAccounts() { + this.methodCalled('getAccounts'); + + return Promise.resolve([ + { + id: '123', + accountType: 1, + isDeviceAccount: true, + isSignedIn: true, + unmigrated: false, + fullName: 'Primary Account', + email: 'primary@gmail.com', + }, + { + id: '456', + accountType: 1, + isDeviceAccount: false, + isSignedIn: true, + unmigrated: false, + fullName: 'Secondary Account 1', + email: 'user1@example.com', + }, + { + id: '789', + accountType: 1, + isDeviceAccount: false, + isSignedIn: false, + unmigrated: false, + fullName: 'Secondary Account 2', + email: 'user2@example.com', + }, + ]); + } + + /** @override */ + addAccount() { + this.methodCalled('addAccount'); + } + + /** @override */ + reauthenticateAccount(account_email) { + this.methodCalled('reauthenticateAccount', account_email); + } + + /** @override */ + removeAccount(account) { + this.methodCalled('removeAccount', account); + } + + /** @override */ + showWelcomeDialogIfRequired() { + this.methodCalled('showWelcomeDialogIfRequired'); + } + } + + suite('ProfileInfoTests', function() { + /** @type {SettingsPeoplePageElement} */ + let peoplePage = null; + /** @type {settings.ProfileInfoBrowserProxy} */ + let browserProxy = null; + /** @type {settings.SyncBrowserProxy} */ + let syncBrowserProxy = null; + /** @type {settings.AccountManagerBrowserProxy} */ + let accountManagerBrowserProxy = null; + + setup(function() { + browserProxy = new TestProfileInfoBrowserProxy(); + settings.ProfileInfoBrowserProxyImpl.instance_ = browserProxy; + + syncBrowserProxy = new TestSyncBrowserProxy(); + settings.SyncBrowserProxyImpl.instance_ = syncBrowserProxy; + + accountManagerBrowserProxy = new TestAccountManagerBrowserProxy(); + settings.AccountManagerBrowserProxyImpl.instance_ = + accountManagerBrowserProxy; + + PolymerTest.clearBody(); + peoplePage = document.createElement('os-settings-people-page'); + peoplePage.pageVisibility = settings.pageVisibility; + document.body.appendChild(peoplePage); + + return Promise + .all([ + browserProxy.whenCalled('getProfileInfo'), + syncBrowserProxy.whenCalled('getSyncStatus'), + accountManagerBrowserProxy.whenCalled('getAccounts') + ]) + .then(function() { + Polymer.dom.flush(); + }); + }); + + teardown(function() { + peoplePage.remove(); + }); + + test('GetProfileInfo', async function() { + assertEquals( + browserProxy.fakeProfileInfo.name, + peoplePage.$$('#profile-name').textContent.trim()); + const bg = peoplePage.$$('#profile-icon').style.backgroundImage; + assertTrue(bg.includes(browserProxy.fakeProfileInfo.iconUrl)); + + const iconDataUrl = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEA' + + 'LAAAAAABAAEAAAICTAEAOw=='; + cr.webUIListenerCallback( + 'profile-info-changed', {name: 'pushedName', iconUrl: iconDataUrl}); + + Polymer.dom.flush(); + assertEquals( + 'pushedName', peoplePage.$$('#profile-name').textContent.trim()); + const newBg = peoplePage.$$('#profile-icon').style.backgroundImage; + assertTrue(newBg.includes(iconDataUrl)); + + // Rather than trying to mock cr.sendWithPromise('getPluralString', ...) + // just force an update. + await peoplePage.updateProfileLabel_(); + assertEquals( + 'primary@gmail.com, +2 more accounts', + peoplePage.$$('#profile-label').textContent.trim()); + }); + }); +});
diff --git a/chrome/test/data/webui/settings/chromeos/os_settings_browsertest.js b/chrome/test/data/webui/settings/chromeos/os_settings_browsertest.js index 1b42d3e..8281664 100644 --- a/chrome/test/data/webui/settings/chromeos/os_settings_browsertest.js +++ b/chrome/test/data/webui/settings/chromeos/os_settings_browsertest.js
@@ -108,3 +108,22 @@ TEST_F('OSSettingsMenuTest', 'MAYBE_All', function() { mocha.run(); }); + +// Tests for the People section. +// eslint-disable-next-line no-var +var OSSettingsPeoplePageTest = class extends OSSettingsBrowserTest { + /** @override */ + get extraLibraries() { + return super.extraLibraries.concat([ + BROWSER_SETTINGS_PATH + '../test_browser_proxy.js', + BROWSER_SETTINGS_PATH + 'sync_test_util.js', + BROWSER_SETTINGS_PATH + 'test_profile_info_browser_proxy.js', + BROWSER_SETTINGS_PATH + 'test_sync_browser_proxy.js', + 'os_people_page_test.js', + ]); + } +}; + +TEST_F('OSSettingsPeoplePageTest', 'MAYBE_All', function() { + mocha.run(); +});
diff --git a/chrome/test/data/webui/settings/cr_settings_browsertest.js b/chrome/test/data/webui/settings/cr_settings_browsertest.js index 03f6fcc..9e622bf 100644 --- a/chrome/test/data/webui/settings/cr_settings_browsertest.js +++ b/chrome/test/data/webui/settings/cr_settings_browsertest.js
@@ -1639,6 +1639,7 @@ '//ui/webui/resources/js/promise_resolver.js', '//ui/webui/resources/js/assert.js', '../fake_chrome_event.js', + '../chromeos/fake_network_config_mojom.js', '../chromeos/fake_networking_private.js', '../chromeos/cr_onc_strings.js', 'internet_page_tests.js',
diff --git a/chrome/test/data/webui/settings/internet_page_tests.js b/chrome/test/data/webui/settings/internet_page_tests.js index 496617d..8190b21 100644 --- a/chrome/test/data/webui/settings/internet_page_tests.js +++ b/chrome/test/data/webui/settings/internet_page_tests.js
@@ -3,15 +3,18 @@ // found in the LICENSE file. suite('InternetPage', function() { - /** @type {InternetPageElement} */ + /** @type {?InternetPageElement} */ let internetPage = null; - /** @type {NetworkSummaryElement} */ + /** @type {?NetworkSummaryElement} */ let networkSummary_ = null; - /** @type {NetworkingPrivate} */ + /** @type {?NetworkingPrivate} */ let api_; + /** @type {?chromeos.networkConfig.mojom.CrosNetworkConfigProxy} */ + let mojoApi_; + suiteSetup(function() { loadTimeData.overrideValues({ internetAddConnection: 'internetAddConnection', @@ -43,6 +46,8 @@ }; api_ = new chrome.FakeNetworkingPrivate(); + mojoApi_ = new FakeNetworkConfig(api_); + network_config.MojoInterfaceProviderImpl.getInstance().proxy_ = mojoApi_; // Disable animations so sub-pages open within one event loop. testing.Test.disableAnimationsAndTransitions(); @@ -83,7 +88,7 @@ teardown(function() { internetPage.remove(); - delete internetPage; + internetPage = null; // Navigating to the details page changes the Route state. settings.resetRouteForTesting(); });
diff --git a/chromecast/browser/BUILD.gn b/chromecast/browser/BUILD.gn index 0444371c..081a833 100644 --- a/chromecast/browser/BUILD.gn +++ b/chromecast/browser/BUILD.gn
@@ -291,8 +291,6 @@ "cast_extension_url_loader_factory.h", "extension_page.cc", "extension_page.h", - "extension_request_protocol_handler.cc", - "extension_request_protocol_handler.h", "extensions/api/accessibility_private/accessibility_extension_api.cc", "extensions/api/accessibility_private/accessibility_extension_api.h", "extensions/api/automation_internal/chromecast_automation_internal_api_delegate.cc",
diff --git a/chromecast/browser/cast_browser_main_parts.cc b/chromecast/browser/cast_browser_main_parts.cc index 952ab7db..5f0fa51d 100644 --- a/chromecast/browser/cast_browser_main_parts.cc +++ b/chromecast/browser/cast_browser_main_parts.cc
@@ -60,6 +60,7 @@ #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/storage_partition.h" +#include "content/public/browser/system_connector.h" #include "content/public/common/content_switches.h" #include "gpu/command_buffer/service/gpu_switches.h" #include "media/base/media.h" @@ -710,22 +711,21 @@ #endif } -void CastBrowserMainParts::PostDestroyThreads() { -#if !defined(OS_ANDROID) - cast_content_browser_client_->ResetMediaResourceTracker(); -#endif // !defined(OS_ANDROID) -} - -void CastBrowserMainParts::ServiceManagerConnectionStarted( - content::ServiceManagerConnection* connection) { +void CastBrowserMainParts::PostCreateThreads() { #if !defined(OS_FUCHSIA) heap_profiling::Supervisor* supervisor = heap_profiling::Supervisor::GetInstance(); supervisor->SetClientConnectionManagerConstructor( &CreateClientConnectionManager); - supervisor->Start(connection, base::NullCallback()); + supervisor->Start(content::GetSystemConnector(), base::NullCallback()); #endif // !defined(OS_FUCHSIA) } +void CastBrowserMainParts::PostDestroyThreads() { +#if !defined(OS_ANDROID) + cast_content_browser_client_->ResetMediaResourceTracker(); +#endif // !defined(OS_ANDROID) +} + } // namespace shell } // namespace chromecast
diff --git a/chromecast/browser/cast_browser_main_parts.h b/chromecast/browser/cast_browser_main_parts.h index 6659387..ba5009c 100644 --- a/chromecast/browser/cast_browser_main_parts.h +++ b/chromecast/browser/cast_browser_main_parts.h
@@ -87,9 +87,8 @@ void PreMainMessageLoopRun() override; bool MainMessageLoopRun(int* result_code) override; void PostMainMessageLoopRun() override; + void PostCreateThreads() override; void PostDestroyThreads() override; - void ServiceManagerConnectionStarted( - content::ServiceManagerConnection* connection) override; private: std::unique_ptr<CastBrowserProcess> cast_browser_process_;
diff --git a/chromecast/browser/extension_request_protocol_handler.cc b/chromecast/browser/extension_request_protocol_handler.cc deleted file mode 100644 index 5d92f82c..0000000 --- a/chromecast/browser/extension_request_protocol_handler.cc +++ /dev/null
@@ -1,403 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chromecast/browser/extension_request_protocol_handler.h" - -#include "base/bind.h" -#include "chromecast/common/cast_redirect_manifest_handler.h" -#include "content/common/net/url_request_user_data.h" -#include "extensions/browser/extension_protocols.h" -#include "extensions/browser/extension_system.h" -#include "extensions/browser/info_map.h" -#include "extensions/common/extension.h" -#include "net/base/ip_endpoint.h" -#include "net/base/upload_data_stream.h" -#include "net/url_request/redirect_info.h" -#include "net/url_request/url_request_context.h" -#include "net/url_request/url_request_job.h" -#include "net/url_request/url_request_job_manager.h" - -namespace chromecast { - -namespace { - -class UploadDataStreamRedirect : public net::UploadDataStream { - public: - explicit UploadDataStreamRedirect(net::UploadDataStream* parent); - ~UploadDataStreamRedirect() override; - - private: - // net::UploadDataStream implementation: - int InitInternal(const net::NetLogWithSource& net_log) override; - int ReadInternal(net::IOBuffer* buf, int buf_len) override; - void ResetInternal() override; - - void PostInit(); - void PostRead(); - - net::UploadDataStream* stream_; - - DISALLOW_COPY_AND_ASSIGN(UploadDataStreamRedirect); -}; - -UploadDataStreamRedirect::UploadDataStreamRedirect( - net::UploadDataStream* parent) - : net::UploadDataStream(parent->is_chunked(), 0), stream_(parent) {} - -UploadDataStreamRedirect::~UploadDataStreamRedirect() {} - -void UploadDataStreamRedirect::PostInit() { - if (!is_chunked()) - SetSize(stream_->size()); -} - -void UploadDataStreamRedirect::PostRead() { - if (is_chunked() && stream_->IsEOF()) - SetIsFinalChunk(); -} - -int UploadDataStreamRedirect::InitInternal( - const net::NetLogWithSource& net_log) { - int ret = stream_->Init(base::BindOnce( - [](UploadDataStreamRedirect* stream, int result) { - stream->PostInit(); - stream->OnInitCompleted(result); - }, - this), - net_log); - if (ret == net::OK) - PostInit(); - return ret; -} - -int UploadDataStreamRedirect::ReadInternal(net::IOBuffer* buf, int buf_len) { - int ret = stream_->Read(buf, buf_len, - base::BindOnce( - [](UploadDataStreamRedirect* stream, int result) { - stream->PostRead(); - stream->OnReadCompleted(result); - }, - this)); - if (ret != net::ERR_IO_PENDING) - PostRead(); - return ret; -} - -void UploadDataStreamRedirect::ResetInternal() { - stream_->Reset(); -} - -class CastExtensionURLRequestJob : public net::URLRequestJob, - public net::URLRequest::Delegate { - public: - CastExtensionURLRequestJob(net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const GURL& redirect_url); - - ~CastExtensionURLRequestJob() override; - - // net::URLRequestJob implementation: - void Start() override; - void SetExtraRequestHeaders(const net::HttpRequestHeaders& headers) override; - int ReadRawData(net::IOBuffer* buf, int buf_size) override; - void SetRequestHeadersCallback(net::RequestHeadersCallback callback) override; - void SetResponseHeadersCallback( - net::ResponseHeadersCallback callback) override; - bool GetMimeType(std::string* mime_type) const override; - int GetResponseCode() const override; - net::IPEndPoint GetResponseRemoteEndpoint() const override; - void StopCaching() override; - bool GetFullRequestHeaders(net::HttpRequestHeaders* headers) const override; - int64_t GetTotalReceivedBytes() const override; - int64_t GetTotalSentBytes() const override; - net::LoadState GetLoadState() const override; - bool GetCharset(std::string* charset) override; - void GetResponseInfo(net::HttpResponseInfo* info) override; - void GetLoadTimingInfo(net::LoadTimingInfo* load_timing_info) const override; - bool GetTransactionRemoteEndpoint(net::IPEndPoint* endpoint) const override; - void PopulateNetErrorDetails(net::NetErrorDetails* details) const override; - bool IsRedirectResponse(GURL* location, - int* http_status_code, - bool* insecure_scheme_was_upgraded) override; - bool CopyFragmentOnRedirect(const GURL& location) const override; - bool IsSafeRedirect(const GURL& location) override; - bool NeedsAuth() override; - std::unique_ptr<net::AuthChallengeInfo> GetAuthChallengeInfo() override; - void SetAuth(const net::AuthCredentials& credentials) override; - void CancelAuth() override; - void ContinueWithCertificate( - scoped_refptr<net::X509Certificate> client_cert, - scoped_refptr<net::SSLPrivateKey> client_private_key) override; - void ContinueDespiteLastError() override; - - // net::URLRequest::Delegate implementation: - void OnReceivedRedirect(net::URLRequest* request, - const net::RedirectInfo& redirect_info, - bool* defer_redirect) override; - void OnAuthRequired(net::URLRequest* request, - const net::AuthChallengeInfo& auth_info) override; - void OnCertificateRequested( - net::URLRequest* request, - net::SSLCertRequestInfo* cert_request_info) override; - void OnSSLCertificateError(net::URLRequest* request, - int net_error, - const net::SSLInfo& ssl_info, - bool fatal) override; - void OnResponseStarted(net::URLRequest* request, int net_error) override; - void OnReadCompleted(net::URLRequest* request, int bytes_read) override; - - private: - std::unique_ptr<net::URLRequest> sub_request_; -}; - -CastExtensionURLRequestJob::CastExtensionURLRequestJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const GURL& redirect_url) - : net::URLRequestJob(request, network_delegate), - sub_request_(request->context()->CreateRequest(redirect_url, - request->priority(), - this)) { - // Copy necessary information from the original request. - // (|URLRequest| is not copyable.) - sub_request_->set_method(request->method()); - sub_request_->SetExtraRequestHeaders(request->extra_request_headers()); - sub_request_->SetReferrer(request->referrer()); - sub_request_->set_referrer_policy(request->referrer_policy()); - if (request->get_upload()) { - sub_request_->set_upload(std::make_unique<UploadDataStreamRedirect>( - const_cast<net::UploadDataStream*>(request->get_upload()))); - } - content::URLRequestUserData* user_data = - static_cast<content::URLRequestUserData*>( - request->GetUserData(content::URLRequestUserData::kUserDataKey)); - sub_request_->SetUserData( - content::URLRequestUserData::kUserDataKey, - std::make_unique<content::URLRequestUserData>( - user_data->render_process_id(), user_data->render_frame_id())); -} - -CastExtensionURLRequestJob::~CastExtensionURLRequestJob() {} - -void CastExtensionURLRequestJob::Start() { - sub_request_->Start(); -} - -bool CastExtensionURLRequestJob::IsRedirectResponse( - GURL* location, - int* http_status_code, - bool* insecure_scheme_was_upgraded) { - return false; -} - -void CastExtensionURLRequestJob::SetExtraRequestHeaders( - const net::HttpRequestHeaders& headers) { - sub_request_->SetExtraRequestHeaders(headers); -} - -int CastExtensionURLRequestJob::ReadRawData(net::IOBuffer* buf, int buf_size) { - return sub_request_->Read(buf, buf_size); -} - -void CastExtensionURLRequestJob::SetRequestHeadersCallback( - net::RequestHeadersCallback callback) { - sub_request_->SetRequestHeadersCallback(callback); -} - -void CastExtensionURLRequestJob::SetResponseHeadersCallback( - net::ResponseHeadersCallback callback) { - sub_request_->SetResponseHeadersCallback(callback); -} - -bool CastExtensionURLRequestJob::GetMimeType(std::string* mime_type) const { - sub_request_->GetMimeType(mime_type); - return true; -} - -int CastExtensionURLRequestJob::GetResponseCode() const { - return sub_request_->GetResponseCode(); -} - -net::IPEndPoint CastExtensionURLRequestJob::GetResponseRemoteEndpoint() const { - return sub_request_->GetResponseRemoteEndpoint(); -} - -void CastExtensionURLRequestJob::StopCaching() { - sub_request_->StopCaching(); -} - -bool CastExtensionURLRequestJob::GetFullRequestHeaders( - net::HttpRequestHeaders* headers) const { - return sub_request_->GetFullRequestHeaders(headers); -} - -int64_t CastExtensionURLRequestJob::GetTotalReceivedBytes() const { - return sub_request_->GetTotalReceivedBytes(); -} - -int64_t CastExtensionURLRequestJob::GetTotalSentBytes() const { - return sub_request_->GetTotalSentBytes(); -} - -net::LoadState CastExtensionURLRequestJob::GetLoadState() const { - return sub_request_->GetLoadState().state; -} - -bool CastExtensionURLRequestJob::GetCharset(std::string* charset) { - sub_request_->GetCharset(charset); - return true; -} - -void CastExtensionURLRequestJob::GetResponseInfo(net::HttpResponseInfo* info) { - *info = sub_request_->response_info(); -} - -void CastExtensionURLRequestJob::GetLoadTimingInfo( - net::LoadTimingInfo* load_timing_info) const { - sub_request_->GetLoadTimingInfo(load_timing_info); -} - -bool CastExtensionURLRequestJob::GetTransactionRemoteEndpoint( - net::IPEndPoint* endpoint) const { - return sub_request_->GetTransactionRemoteEndpoint(endpoint); -} - -void CastExtensionURLRequestJob::PopulateNetErrorDetails( - net::NetErrorDetails* details) const { - sub_request_->PopulateNetErrorDetails(details); -} - -bool CastExtensionURLRequestJob::CopyFragmentOnRedirect( - const GURL& location) const { - return false; -} - -bool CastExtensionURLRequestJob::IsSafeRedirect(const GURL& location) { - return true; -} - -bool CastExtensionURLRequestJob::NeedsAuth() { - return false; -} - -std::unique_ptr<net::AuthChallengeInfo> -CastExtensionURLRequestJob::GetAuthChallengeInfo() { - return nullptr; -} - -void CastExtensionURLRequestJob::SetAuth( - const net::AuthCredentials& credentials) { - sub_request_->SetAuth(credentials); -} - -void CastExtensionURLRequestJob::CancelAuth() { - sub_request_->CancelAuth(); -} - -void CastExtensionURLRequestJob::ContinueWithCertificate( - scoped_refptr<net::X509Certificate> client_cert, - scoped_refptr<net::SSLPrivateKey> client_private_key) { - sub_request_->ContinueWithCertificate(client_cert, client_private_key); -} - -void CastExtensionURLRequestJob::ContinueDespiteLastError() { - sub_request_->ContinueDespiteLastError(); -} - -void CastExtensionURLRequestJob::OnReceivedRedirect( - net::URLRequest* request, - const net::RedirectInfo& redirect_info, - bool* defer_redirect) { - net::URLRequest::Delegate::OnReceivedRedirect(request, redirect_info, - defer_redirect); -} - -void CastExtensionURLRequestJob::OnAuthRequired( - net::URLRequest* request, - const net::AuthChallengeInfo& auth_info) { - net::URLRequest::Delegate::OnAuthRequired(request, auth_info); -} - -void CastExtensionURLRequestJob::OnCertificateRequested( - net::URLRequest* request, - net::SSLCertRequestInfo* cert_request_info) { - NotifyCertificateRequested(cert_request_info); -} - -void CastExtensionURLRequestJob::OnSSLCertificateError( - net::URLRequest* request, - int net_error, - const net::SSLInfo& ssl_info, - bool fatal) { - NotifySSLCertificateError(net_error, ssl_info, fatal); -} - -void CastExtensionURLRequestJob::OnResponseStarted(net::URLRequest* request, - int net_error) { - net::URLRequestStatus status = net::URLRequestStatus::FromError(net_error); - if (status.status() == net::URLRequestStatus::SUCCESS) - NotifyHeadersComplete(); - else - NotifyStartError(status); -} - -void CastExtensionURLRequestJob::OnReadCompleted(net::URLRequest* request, - int bytes_read) { - ReadRawDataComplete(bytes_read); -} - -} // namespace - -ExtensionRequestProtocolHandler::ExtensionRequestProtocolHandler( - content::BrowserContext* browser_context) - : browser_context_(browser_context) {} - -ExtensionRequestProtocolHandler::~ExtensionRequestProtocolHandler() {} - -net::URLRequestJob* ExtensionRequestProtocolHandler::MaybeCreateJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate) const { - if (!info_map_) { - // This can't be done in the constructor as extensions::ExtensionSystem::Get - // will fail until after this is constructed. - info_map_ = extensions::ExtensionSystem::Get(browser_context_)->info_map(); - default_handler_ = extensions::CreateExtensionProtocolHandler( - false, const_cast<extensions::InfoMap*>(info_map_)); - } - - const extensions::Extension* extension = - info_map_->extensions().GetByID(request->url().host()); - - if (!extension) { - LOG(ERROR) << "Can't find extension with id: " << request->url().host(); - return nullptr; - } - - const GURL& url = request->url(); - std::string cast_url; - // See if we are being redirected to an extension-specific URL. - if (!CastRedirectHandler::ParseUrl(&cast_url, extension, url)) { - // Defer to the default handler to load from disk. - return default_handler_->MaybeCreateJob(request, network_delegate); - } - - // The above only handles the scheme, host & path, any query or fragment needs - // to be copied separately. - if (url.has_query()) { - cast_url.push_back('?'); - url.query_piece().AppendToString(&cast_url); - } - - if (url.has_ref()) { - cast_url.push_back('#'); - url.ref_piece().AppendToString(&cast_url); - } - - // Force a redirect to the new URL but without changing where the webpage - // thinks it is. - return new CastExtensionURLRequestJob(request, network_delegate, - GURL(cast_url)); -} - -} // namespace chromecast
diff --git a/chromecast/browser/extension_request_protocol_handler.h b/chromecast/browser/extension_request_protocol_handler.h deleted file mode 100644 index 7a8a54f9..0000000 --- a/chromecast/browser/extension_request_protocol_handler.h +++ /dev/null
@@ -1,40 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROMECAST_BROWSER_EXTENION_REQUEST_PROTOCOL_HANDLER_H_ -#define CHROMECAST_BROWSER_EXTENION_REQUEST_PROTOCOL_HANDLER_H_ - -#include "net/url_request/url_request_job_factory.h" - -namespace content { -class BrowserContext; -} // namespace content - -namespace extensions { -class InfoMap; -} - -namespace chromecast { - -class ExtensionRequestProtocolHandler - : public net::URLRequestJobFactory::ProtocolHandler { - public: - explicit ExtensionRequestProtocolHandler( - content::BrowserContext* browser_context); - ~ExtensionRequestProtocolHandler() override; - - net::URLRequestJob* MaybeCreateJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate) const override; - - private: - content::BrowserContext* const browser_context_; - mutable const extensions::InfoMap* info_map_ = nullptr; - mutable std::unique_ptr<net::URLRequestJobFactory::ProtocolHandler> - default_handler_; -}; - -} // namespace chromecast - -#endif // CHROMECAST_BROWSER_EXTENION_REQUEST_PROTOCOL_HANDLER_H_
diff --git a/chromecast/browser/extensions/cast_extensions_browser_client.cc b/chromecast/browser/extensions/cast_extensions_browser_client.cc index f244701d7..9b2e9ef 100644 --- a/chromecast/browser/extensions/cast_extensions_browser_client.cc +++ b/chromecast/browser/extensions/cast_extensions_browser_client.cc
@@ -106,16 +106,6 @@ return false; } -net::URLRequestJob* -CastExtensionsBrowserClient::MaybeCreateResourceBundleRequestJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const base::FilePath& directory_path, - const std::string& content_security_policy, - bool send_cors_header) { - return nullptr; -} - base::FilePath CastExtensionsBrowserClient::GetBundleResourcePath( const network::ResourceRequest& request, const base::FilePath& extension_resources_path, @@ -266,12 +256,6 @@ return CastExtensionWebContentsObserver::FromWebContents(web_contents); } -ExtensionNavigationUIData* -CastExtensionsBrowserClient::GetExtensionNavigationUIData( - net::URLRequest* request) { - return nullptr; -} - KioskDelegate* CastExtensionsBrowserClient::GetKioskDelegate() { return nullptr; }
diff --git a/chromecast/browser/extensions/cast_extensions_browser_client.h b/chromecast/browser/extensions/cast_extensions_browser_client.h index 6979d539..d51a63a4 100644 --- a/chromecast/browser/extensions/cast_extensions_browser_client.h +++ b/chromecast/browser/extensions/cast_extensions_browser_client.h
@@ -48,12 +48,6 @@ bool CanExtensionCrossIncognito( const Extension* extension, content::BrowserContext* context) const override; - net::URLRequestJob* MaybeCreateResourceBundleRequestJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const base::FilePath& directory_path, - const std::string& content_security_policy, - bool send_cors_header) override; base::FilePath GetBundleResourcePath( const network::ResourceRequest& request, const base::FilePath& extension_resources_path, @@ -106,8 +100,6 @@ bool IsMinBrowserVersionSupported(const std::string& min_version) override; ExtensionWebContentsObserver* GetExtensionWebContentsObserver( content::WebContents* web_contents) override; - ExtensionNavigationUIData* GetExtensionNavigationUIData( - net::URLRequest* request) override; KioskDelegate* GetKioskDelegate() override; bool IsLockScreenContext(content::BrowserContext* context) override; std::string GetApplicationLocale() override;
diff --git a/chromecast/browser/url_request_context_factory.cc b/chromecast/browser/url_request_context_factory.cc index ed3e3c8..61b08e7 100644 --- a/chromecast/browser/url_request_context_factory.cc +++ b/chromecast/browser/url_request_context_factory.cc
@@ -48,13 +48,6 @@ #include "net/url_request/url_request_job_factory_impl.h" #include "services/network/public/cpp/features.h" -#if BUILDFLAG(ENABLE_CHROMECAST_EXTENSIONS) -#include "chromecast/browser/extension_request_protocol_handler.h" -#include "extensions/browser/extension_protocols.h" // nogncheck -#include "extensions/browser/extension_system.h" // nogncheck -#include "extensions/common/constants.h" // nogncheck -#endif - namespace chromecast { namespace shell { @@ -199,10 +192,6 @@ content::URLRequestInterceptorScopedVector request_interceptors) { DCHECK(!main_getter_.get()) << "Main URLRequestContextGetter already initialized"; -#if BUILDFLAG(ENABLE_CHROMECAST_EXTENSIONS) - (*protocol_handlers)[extensions::kExtensionScheme] = - std::make_unique<ExtensionRequestProtocolHandler>(browser_context); -#endif main_getter_ = new MainURLRequestContextGetter(this, browser_context, protocol_handlers, std::move(request_interceptors));
diff --git a/chromeos/components/drivefs/drivefs_host_unittest.cc b/chromeos/components/drivefs/drivefs_host_unittest.cc index f04912f..f04c7d6e 100644 --- a/chromeos/components/drivefs/drivefs_host_unittest.cc +++ b/chromeos/components/drivefs/drivefs_host_unittest.cc
@@ -318,7 +318,9 @@ *disk_manager_, MountPath( testing::StartsWith("drivefs://"), "", "drivefs-salt-g-ID", - testing::Contains("datadir=/path/to/profile/GCache/v2/salt-g-ID"), + testing::AllOf(testing::Contains( + "datadir=/path/to/profile/GCache/v2/salt-g-ID"), + testing::Contains("myfiles=/MyFiles")), _, chromeos::MOUNT_ACCESS_MODE_READ_WRITE)) .WillOnce(testing::SaveArg<0>(&source));
diff --git a/chromeos/components/drivefs/drivefs_session.cc b/chromeos/components/drivefs/drivefs_session.cc index 34df6d1..92e1fdb 100644 --- a/chromeos/components/drivefs/drivefs_session.cc +++ b/chromeos/components/drivefs/drivefs_session.cc
@@ -15,6 +15,7 @@ using MountFailure = DriveFsSession::MountObserver::MountFailure; constexpr char kDataDirOption[] = "datadir="; +constexpr char kMyFilesOption[] = "myfiles="; constexpr char kMountScheme[] = "drivefs://"; constexpr base::TimeDelta kMountTimeout = base::TimeDelta::FromSeconds(20); @@ -45,10 +46,11 @@ source_path_ = base::StrCat({kMountScheme, token.ToString()}); std::string datadir_option = base::StrCat({kDataDirOption, data_path.value()}); - disk_mount_manager_->MountPath(source_path_, "", desired_mount_dir_name, - {datadir_option}, - chromeos::MOUNT_TYPE_NETWORK_STORAGE, - chromeos::MOUNT_ACCESS_MODE_READ_WRITE); + disk_mount_manager_->MountPath( + source_path_, "", desired_mount_dir_name, + {datadir_option, base::StrCat({kMyFilesOption, my_files_path.value()})}, + chromeos::MOUNT_TYPE_NETWORK_STORAGE, + chromeos::MOUNT_ACCESS_MODE_READ_WRITE); } private:
diff --git a/chromeos/components/drivefs/drivefs_session_unittest.cc b/chromeos/components/drivefs/drivefs_session_unittest.cc index da367cf0..406822b6 100644 --- a/chromeos/components/drivefs/drivefs_session_unittest.cc +++ b/chromeos/components/drivefs/drivefs_session_unittest.cc
@@ -42,13 +42,12 @@ std::string source; EXPECT_CALL( disk_manager_, - MountPath( - testing::StartsWith("drivefs://"), "", kExpectedMountDir, - testing::AllOf(testing::Contains( - "datadir=/path/to/profile/GCache/v2/salt-g-ID"), - testing::Not(testing::Contains( - "myfiles=/path/to/profile/MyFiles"))), - _, chromeos::MOUNT_ACCESS_MODE_READ_WRITE)) + MountPath(testing::StartsWith("drivefs://"), "", kExpectedMountDir, + testing::AllOf( + testing::Contains( + "datadir=/path/to/profile/GCache/v2/salt-g-ID"), + testing::Contains("myfiles=/path/to/profile/MyFiles")), + _, chromeos::MOUNT_ACCESS_MODE_READ_WRITE)) .WillOnce(testing::SaveArg<0>(&source)); mounter->Mount(token, base::FilePath(kExpectedDataDir),
diff --git a/chromeos/constants/chromeos_features.cc b/chromeos/constants/chromeos_features.cc index 016432ca..1e1d676 100644 --- a/chromeos/constants/chromeos_features.cc +++ b/chromeos/constants/chromeos_features.cc
@@ -98,6 +98,11 @@ const base::Feature kInstantTethering{"InstantTethering", base::FEATURE_DISABLED_BY_DEFAULT}; +// Enables or disables showing the battery level in the System Tray and Settings +// UI for supported Bluetooth Devices. +const base::Feature kShowBluetoothDeviceBattery{ + "ShowBluetoothDeviceBattery", base::FEATURE_DISABLED_BY_DEFAULT}; + // Uses the V3 (~2019-05 era) Smart Dim model instead of the default V2 // (~2018-11) model. const base::Feature kSmartDimModelV3{"SmartDimModelV3",
diff --git a/chromeos/constants/chromeos_features.h b/chromeos/constants/chromeos_features.h index 138a9cd78..f144fca4 100644 --- a/chromeos/constants/chromeos_features.h +++ b/chromeos/constants/chromeos_features.h
@@ -52,6 +52,8 @@ COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kInstantTethering; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) +extern const base::Feature kShowBluetoothDeviceBattery; +COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kSmartDimModelV3; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kSplitSettings;
diff --git a/chromeos/constants/chromeos_switches.cc b/chromeos/constants/chromeos_switches.cc index 59bbe8d..8ad6bfc 100644 --- a/chromeos/constants/chromeos_switches.cc +++ b/chromeos/constants/chromeos_switches.cc
@@ -36,6 +36,7 @@ } // namespace // Controls whether to enable Chrome OS Account Manager. +// Rollout controlled by Finch. const base::Feature kAccountManager{"ChromeOSAccountManager", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/chromeos/services/assistant/assistant_manager_service_impl.cc b/chromeos/services/assistant/assistant_manager_service_impl.cc index 9212862c..1da3f277 100644 --- a/chromeos/services/assistant/assistant_manager_service_impl.cc +++ b/chromeos/services/assistant/assistant_manager_service_impl.cc
@@ -98,6 +98,21 @@ assistant_state->context_enabled().value_or(false); } +action::AppStatus GetActionAppStatus(mojom::AppStatus status) { + switch (status) { + case mojom::AppStatus::UNKNOWN: + return action::UNKNOWN; + case mojom::AppStatus::AVAILABLE: + return action::AVAILABLE; + case mojom::AppStatus::UNAVAILABLE: + return action::UNAVAILABLE; + case mojom::AppStatus::VERSION_MISMATCH: + return action::VERSION_MISMATCH; + case mojom::AppStatus::DISABLED: + return action::DISABLED; + } +} + ash::mojom::AssistantTimerState GetTimerState( assistant_client::Timer::State state) { switch (state) { @@ -625,6 +640,24 @@ weak_factory_.GetWeakPtr(), interaction)); } +void AssistantManagerServiceImpl::OnVerifyAndroidApp( + const std::vector<action::AndroidAppInfo>& apps_info, + const action::InteractionInfo& interaction) { + ENSURE_MAIN_THREAD(&AssistantManagerServiceImpl::OnVerifyAndroidApp, + apps_info, interaction); + std::vector<mojom::AndroidAppInfoPtr> apps_info_list; + for (auto& app_info : apps_info) { + mojom::AndroidAppInfoPtr app_info_ptr = mojom::AndroidAppInfo::New(); + app_info_ptr->package_name = app_info.package_name; + apps_info_list.push_back(std::move(app_info_ptr)); + } + service_->device_actions()->VerifyAndroidApp( + std::move(apps_info_list), + base::BindOnce( + &AssistantManagerServiceImpl::HandleVerifyAndroidAppResponse, + weak_factory_.GetWeakPtr(), interaction)); +} + void AssistantManagerServiceImpl::OnOpenMediaAndroidIntentOnMainThread( const std::string play_media_args_proto, action::AndroidAppInfo* android_app_info) { @@ -1036,6 +1069,28 @@ interaction_proto, "open_provider_response", options, [](auto) {}); } +void AssistantManagerServiceImpl::HandleVerifyAndroidAppResponse( + const action::InteractionInfo& interaction, + std::vector<mojom::AndroidAppInfoPtr> apps_info) { + std::vector<action::AndroidAppInfo> action_apps_info; + for (const auto& app_info : apps_info) { + action_apps_info.push_back({app_info->package_name, app_info->version, + app_info->localized_app_name, app_info->intent, + GetActionAppStatus(app_info->status)}); + } + std::string interaction_proto = CreateVerifyProviderResponseInteraction( + interaction.interaction_id, action_apps_info); + + assistant_client::VoicelessOptions options; + options.obfuscated_gaia_id = interaction.user_id; + // Set the request to be user initiated so that a new conversation will be + // created to handle the client OPs in the response of this request. + options.is_user_initiated = true; + + assistant_manager_internal_->SendVoicelessInteraction( + interaction_proto, "verify_provider_response", options, [](auto) {}); +} + // assistant_client::DeviceStateListener overrides // Run on LibAssistant threads // This method currently only triggered as the callback of libassistant bootup
diff --git a/chromeos/services/assistant/assistant_manager_service_impl.h b/chromeos/services/assistant/assistant_manager_service_impl.h index b5feb1fe..16975f7 100644 --- a/chromeos/services/assistant/assistant_manager_service_impl.h +++ b/chromeos/services/assistant/assistant_manager_service_impl.h
@@ -151,6 +151,8 @@ void OnShowNotification(const action::Notification& notification) override; void OnOpenAndroidApp(const action::AndroidAppInfo& app_info, const action::InteractionInfo& interaction) override; + void OnVerifyAndroidApp(const std::vector<action::AndroidAppInfo>& apps_info, + const action::InteractionInfo& interaction) override; // AssistantEventObserver overrides: void OnSpeechLevelUpdated(float speech_level) override; @@ -221,6 +223,9 @@ void HandleOpenAndroidAppResponse(const action::InteractionInfo& interaction, bool app_opened); + void HandleVerifyAndroidAppResponse( + const action::InteractionInfo& interaction, + std::vector<mojom::AndroidAppInfoPtr> apps_info); void HandleLaunchMediaIntentResponse(bool app_opened);
diff --git a/chromeos/services/assistant/public/mojom/assistant.mojom b/chromeos/services/assistant/public/mojom/assistant.mojom index 58b5344..6e1df68c 100644 --- a/chromeos/services/assistant/public/mojom/assistant.mojom +++ b/chromeos/services/assistant/public/mojom/assistant.mojom
@@ -181,6 +181,10 @@ // Open the Android app if the app is available. OpenAndroidApp(AndroidAppInfo app_info) => (bool app_opened); + // Verify the status of the Android apps. + VerifyAndroidApp(array<AndroidAppInfo> apps_info) => (array<AndroidAppInfo> + apps_info); + // Launch Android intent. The intent is encoded as a URI string. // See Intent.toUri(). LaunchAndroidIntent(string intent);
diff --git a/chromeos/services/assistant/service_unittest.cc b/chromeos/services/assistant/service_unittest.cc index 9d1f2337a..abdf27a 100644 --- a/chromeos/services/assistant/service_unittest.cc +++ b/chromeos/services/assistant/service_unittest.cc
@@ -139,6 +139,9 @@ void SetNightLightEnabled(bool enabled) override {} void OpenAndroidApp(chromeos::assistant::mojom::AndroidAppInfoPtr app_info, OpenAndroidAppCallback callback) override {} + void VerifyAndroidApp( + std::vector<chromeos::assistant::mojom::AndroidAppInfoPtr> apps_info, + VerifyAndroidAppCallback callback) override {} void LaunchAndroidIntent(const std::string& intent) override {} void AddAppListEventSubscriber( chromeos::assistant::mojom::AppListEventSubscriberPtr subscriber)
diff --git a/components/cast_channel/cast_channel_enum.cc b/components/cast_channel/cast_channel_enum.cc index ac9e132..0acfe02 100644 --- a/components/cast_channel/cast_channel_enum.cc +++ b/components/cast_channel/cast_channel_enum.cc
@@ -12,6 +12,7 @@ case enum: \ return #enum +// TODO(jrw): Replace with EnumTable. std::string ReadyStateToString(ReadyState ready_state) { switch (ready_state) { CAST_CHANNEL_TYPE_TO_STRING(ReadyState::NONE); @@ -24,6 +25,7 @@ return "Unknown ready_state"; } +// TODO(jrw): Replace with EnumTable. std::string ChannelErrorToString(ChannelError channel_error) { switch (channel_error) { CAST_CHANNEL_TYPE_TO_STRING(ChannelError::NONE);
diff --git a/components/cast_channel/cast_message_handler.cc b/components/cast_channel/cast_message_handler.cc index 185f02b9..e2f19dd 100644 --- a/components/cast_channel/cast_message_handler.cc +++ b/components/cast_channel/cast_message_handler.cc
@@ -51,8 +51,12 @@ std::tie(other.channel_id, other.source_id, other.destination_id); } -InternalMessage::InternalMessage(CastMessageType type, base::Value message) - : type(type), message(std::move(message)) {} +InternalMessage::InternalMessage(CastMessageType type, + const std::string& message_namespace, + base::Value message) + : type(type), + message_namespace(message_namespace), + message(std::move(message)) {} InternalMessage::~InternalMessage() = default; CastMessageHandler::CastMessageHandler( @@ -125,8 +129,8 @@ if (requests->AddAppAvailabilityRequest( std::make_unique<GetAppAvailabilityRequest>( request_id, std::move(callback), clock_, app_id))) { - SendCastMessage(socket, CreateGetAppAvailabilityRequest( - sender_id_, request_id, app_id)); + SendCastMessageToSocket(socket, CreateGetAppAvailabilityRequest( + sender_id_, request_id, app_id)); } } @@ -140,7 +144,8 @@ } int request_id = NextRequestId(); - SendCastMessage(socket, CreateReceiverStatusRequest(sender_id_, request_id)); + SendCastMessageToSocket(socket, + CreateReceiverStatusRequest(sender_id_, request_id)); } void CastMessageHandler::SendBroadcastMessage( @@ -163,7 +168,7 @@ // about the response, as broadcasts are fire-and-forget. CastMessage message = CreateBroadcastRequest(sender_id_, request_id, app_ids, request); - SendCastMessage(socket, message); + SendCastMessageToSocket(socket, message); } void CastMessageHandler::LaunchSession(int channel_id, @@ -187,7 +192,7 @@ if (requests->AddLaunchRequest(std::make_unique<LaunchSessionRequest>( request_id, std::move(callback), clock_), launch_timeout)) { - SendCastMessage( + SendCastMessageToSocket( socket, CreateLaunchRequest(sender_id_, request_id, app_id, locale_)); } } @@ -210,16 +215,15 @@ << ", request_id: " << request_id; if (requests->AddStopRequest(std::make_unique<StopSessionRequest>( request_id, std::move(callback), clock_))) { - SendCastMessage(socket, CreateStopRequest(client_id.value_or(sender_id_), - request_id, session_id)); + SendCastMessageToSocket( + socket, CreateStopRequest(client_id.value_or(sender_id_), request_id, + session_id)); } } -Result CastMessageHandler::SendAppMessage(int channel_id, - const CastMessage& message) { +Result CastMessageHandler::SendCastMessage(int channel_id, + const CastMessage& message) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(!IsCastInternalNamespace(message.namespace_())) - << ": unexpected app message namespace: " << message.namespace_(); CastSocket* socket = socket_service_->GetSocket(channel_id); if (!socket) { @@ -227,10 +231,17 @@ return Result::kFailed; } - SendCastMessage(socket, message); + SendCastMessageToSocket(socket, message); return Result::kOk; } +Result CastMessageHandler::SendAppMessage(int channel_id, + const CastMessage& message) { + DCHECK(!IsCastInternalNamespace(message.namespace_())) + << ": unexpected app message namespace: " << message.namespace_(); + return SendCastMessage(channel_id, message); +} + base::Optional<int> CastMessageHandler::SendMediaRequest( int channel_id, const base::Value& body, @@ -245,7 +256,7 @@ } int request_id = NextRequestId(); - SendCastMessage( + SendCastMessageToSocket( socket, CreateMediaRequest(body, request_id, source_id, destination_id)); return request_id; } @@ -267,7 +278,8 @@ requests->AddVolumeRequest(std::make_unique<SetVolumeRequest>( request_id, std::move(callback), clock_)); - SendCastMessage(socket, CreateSetVolumeRequest(body, request_id, source_id)); + SendCastMessageToSocket(socket, + CreateSetVolumeRequest(body, request_id, source_id)); } void CastMessageHandler::AddObserver(Observer* observer) { @@ -295,7 +307,12 @@ const CastMessage& message) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DVLOG(2) << __func__ << ", channel_id: " << socket.id() - << ", message: " << CastMessageToString(message); + << ", message: " << message; + + // TODO(jrw): Splitting internal messages into a separate code path with a + // separate data type is pretty questionable, because it causes duplicated + // code paths in the downstream logic (manifested as separate OnAppMessage and + // OnInternalMessage methods). if (IsCastInternalNamespace(message.namespace_())) { if (message.payload_type() == cast_channel::CastMessage_PayloadType_STRING) { @@ -303,7 +320,8 @@ connector_.get(), message.payload_utf8(), base::BindOnce(&CastMessageHandler::HandleCastInternalMessage, weak_ptr_factory_.GetWeakPtr(), socket.id(), - message.source_id(), message.destination_id()), + message.source_id(), message.destination_id(), + message.namespace_()), base::BindOnce(&ReportParseError), data_decoder_batch_id_); } else { DLOG(ERROR) << "Dropping internal message with binary payload: " @@ -326,6 +344,7 @@ int channel_id, const std::string& source_id, const std::string& destination_id, + const std::string& namespace_, base::Value payload) { if (!payload.is_dict()) { ReportParseError("Parsed message not a dictionary"); @@ -359,13 +378,13 @@ return; } - InternalMessage internal_message(type, std::move(payload)); + InternalMessage internal_message(type, namespace_, std::move(payload)); for (auto& observer : observers_) observer.OnInternalMessage(channel_id, internal_message); } -void CastMessageHandler::SendCastMessage(CastSocket* socket, - const CastMessage& message) { +void CastMessageHandler::SendCastMessageToSocket(CastSocket* socket, + const CastMessage& message) { // A virtual connection must be opened to the receiver before other messages // can be sent. DoEnsureConnection(socket, message.source_id(), message.destination_id()); @@ -378,6 +397,8 @@ const std::string& source_id, const std::string& destination_id) { VirtualConnection connection(socket->id(), source_id, destination_id); + + // If there is already a connection, there is nothing to do. if (virtual_connections_.find(connection) != virtual_connections_.end()) return; @@ -387,8 +408,8 @@ CastMessage virtual_connection_request = CreateVirtualConnectionRequest( connection.source_id, connection.destination_id, connection.destination_id == kPlatformReceiverId - ? VirtualConnectionType::kStrong - : VirtualConnectionType::kInvisible, + ? VirtualConnectionType::kInvisible + : VirtualConnectionType::kStrong, user_agent_, browser_version_); socket->transport()->SendMessage( virtual_connection_request,
diff --git a/components/cast_channel/cast_message_handler.h b/components/cast_channel/cast_message_handler.h index 877ee9e..2569253 100644 --- a/components/cast_channel/cast_message_handler.h +++ b/components/cast_channel/cast_message_handler.h
@@ -101,10 +101,18 @@ }; struct InternalMessage { - InternalMessage(CastMessageType type, base::Value message); + InternalMessage(CastMessageType type, + const std::string& message_namespace, + base::Value message); ~InternalMessage(); CastMessageType type; + // TODO(jrw): This field is only needed to communicate the namespace + // information from CastMessageHandler::OnMessage to + // MirroringActivityRecord::OnInternalMessage. Maybe there's a better way? + // One possibility is to derive namespace when it's needed based on the + // context and/or message type. + std::string message_namespace; base::Value message; }; @@ -181,6 +189,19 @@ ResultCallback callback); // Sends |message| to the device given by |channel_id|. The caller may use + // this method to forward app messages from the SDK client to the device. + // + // TODO(jrw): Could this be merged with SendAppMessage()? Note from mfoltz: + // + // The two differences between an app message and a protocol message: + // - app message has a sender ID that comes from the clientId of the SDK + // - app message has a custom (non-Cast) namespace + // + // So if you added senderId to CastMessage, it seems like you could have one + // method for both. + virtual Result SendCastMessage(int channel_id, const CastMessage& message); + + // Sends |message| to the device given by |channel_id|. The caller may use // this method to forward app messages from the SDK client to the device. It // is invalid to call this method with a message in one of the Cast internal // message namespaces. @@ -266,7 +287,7 @@ // Sends |message| over |socket|. This also ensures the necessary virtual // connection exists before sending the message. - void SendCastMessage(CastSocket* socket, const CastMessage& message); + void SendCastMessageToSocket(CastSocket* socket, const CastMessage& message); // Sends a virtual connection request to |socket| if the virtual connection // for (|source_id|, |destination_id|) does not yet exist. @@ -280,6 +301,7 @@ void HandleCastInternalMessage(int channel_id, const std::string& source_id, const std::string& destination_id, + const std::string& namespace_, base::Value payload); // Set of pending requests keyed by socket ID.
diff --git a/components/cast_channel/cast_message_handler_unittest.cc b/components/cast_channel/cast_message_handler_unittest.cc index 944cbea..5acea0b 100644 --- a/components/cast_channel/cast_message_handler_unittest.cc +++ b/components/cast_channel/cast_message_handler_unittest.cc
@@ -468,7 +468,8 @@ // Handle pending launch session request. handler_.HandleCastInternalMessage(channel_id_, "theSourceId", - "theDestinationId", ParseJson(R"( + "theDestinationId", "theNamespace", + ParseJson(R"( { "requestId": 1, "type": "RECEIVER_STATUS", @@ -477,7 +478,8 @@ // Handle both pending get app availability requests. handler_.HandleCastInternalMessage(channel_id_, "theSourceId", - "theDestinationId", ParseJson(R"( + "theDestinationId", "theNamespace", + ParseJson(R"( { "requestId": 2, "availability": {"theAppId": "APP_AVAILABLE"}, @@ -485,7 +487,7 @@ // Handle pending set volume request (1 of 2). handler_.HandleCastInternalMessage(channel_id_, "theSourceId", - "theDestinationId", + "theDestinationId", "theNamespace", ParseJson(R"({"requestId": 3})")); // Skip request_id == 4, since it was used by the second get app availability @@ -493,12 +495,12 @@ // Handle pending set volume request (2 of 2). handler_.HandleCastInternalMessage(channel_id_, "theSourceId", - "theDestinationId", + "theDestinationId", "theNamespace", ParseJson(R"({"requestId": 5})")); // Handle pending stop session request. handler_.HandleCastInternalMessage(channel_id_, "theSourceId", - "theDestinationId", + "theDestinationId", "theNamespace", ParseJson(R"({"requestId": 6})")); }
diff --git a/components/cast_channel/cast_message_util.cc b/components/cast_channel/cast_message_util.cc index 329faa7..d3101fc 100644 --- a/components/cast_channel/cast_message_util.cc +++ b/components/cast_channel/cast_message_util.cc
@@ -38,6 +38,8 @@ {CastMessageType::kReceiverStatus, "RECEIVER_STATUS"}, {CastMessageType::kMediaStatus, "MEDIA_STATUS"}, {CastMessageType::kLaunchError, "LAUNCH_ERROR"}, + {CastMessageType::kOffer, "OFFER"}, + {CastMessageType::kAnswer, "ANSWER"}, {CastMessageType::kOther}, }, CastMessageType::kMaxValue); @@ -151,6 +153,27 @@ } // namespace +std::ostream& operator<<(std::ostream& lhs, const CastMessage& rhs) { + lhs << "{"; + if (rhs.has_source_id()) { + lhs << "source_id: " << rhs.source_id() << ", "; + } + if (rhs.has_destination_id()) { + lhs << "destination_id: " << rhs.destination_id() << ", "; + } + if (rhs.has_namespace_()) { + lhs << "namespace: " << rhs.namespace_() << ", "; + } + if (rhs.has_payload_utf8()) { + lhs << "payload_utf8: " << rhs.payload_utf8(); + } + if (rhs.has_payload_binary()) { + lhs << "payload_binary: ..."; + } + lhs << "}"; + return lhs; +} + bool IsCastMessageValid(const CastMessage& message_proto) { if (!message_proto.IsInitialized()) return false; @@ -178,34 +201,29 @@ : CastMessageType::kOther; } +// TODO(jrw): Eliminate this function. const char* ToString(CastMessageType message_type) { return EnumToString(message_type).value_or("").data(); } +// TODO(jrw): Eliminate this function. const char* ToString(V2MessageType message_type) { return EnumToString(message_type).value_or(nullptr).data(); } +// TODO(jrw): Eliminate this function. CastMessageType CastMessageTypeFromString(const std::string& type) { auto result = StringToEnum<CastMessageType>(type); DVLOG_IF(1, !result) << "Unknown message type: " << type; return result.value_or(CastMessageType::kOther); } +// TODO(jrw): Eliminate this function. V2MessageType V2MessageTypeFromString(const std::string& type) { return StringToEnum<V2MessageType>(type).value_or(V2MessageType::kOther); } -std::string CastMessageToString(const CastMessage& message_proto) { - std::string out("{"); - out += "namespace = " + message_proto.namespace_(); - out += ", sourceId = " + message_proto.source_id(); - out += ", destId = " + message_proto.destination_id(); - out += ", type = " + base::NumberToString(message_proto.payload_type()); - out += ", str = \"" + message_proto.payload_utf8() + "\"}"; - return out; -} - +// TODO(jrw): Convert to operator<< std::string AuthMessageToString(const DeviceAuthMessage& message) { std::string out("{"); if (message.has_challenge()) { @@ -275,7 +293,7 @@ VirtualConnectionType connection_type, const std::string& user_agent, const std::string& browser_version) { - DCHECK(destination_id != kPlatformReceiverId || connection_type == kStrong); + DCHECK(destination_id == kPlatformReceiverId || connection_type == kStrong); // Parse system_version from user agent string. It contains platform, OS and // CPU info and is contained in the first set of parentheses of the user @@ -457,6 +475,7 @@ } } +// TODO(jrw): Eliminate this function. const char* ToString(GetAppAvailabilityResult result) { return EnumToString(result).value_or(nullptr).data(); }
diff --git a/components/cast_channel/cast_message_util.h b/components/cast_channel/cast_message_util.h index ee1e5ab..541c690 100644 --- a/components/cast_channel/cast_message_util.h +++ b/components/cast_channel/cast_message_util.h
@@ -48,6 +48,8 @@ kReceiverStatus, kMediaStatus, kLaunchError, + kOffer, + kAnswer, kOther, // Add new types above |kOther|. kMaxValue = kOther, }; @@ -74,6 +76,8 @@ kMaxValue = kOther, }; +std::ostream& operator<<(std::ostream& lhs, const CastMessage& rhs); + // Checks if the contents of |message_proto| are valid. bool IsCastMessageValid(const CastMessage& message_proto);
diff --git a/components/cast_channel/cast_socket.cc b/components/cast_channel/cast_socket.cc index 2095d66..135de93 100644 --- a/components/cast_channel/cast_socket.cc +++ b/components/cast_channel/cast_socket.cc
@@ -467,8 +467,7 @@ CastMessage challenge_message; CreateAuthChallengeMessage(&challenge_message, auth_context_); - VLOG_WITH_CONNECTION(1) << "Sending challenge: " - << CastMessageToString(challenge_message); + VLOG_WITH_CONNECTION(1) << "Sending challenge: " << challenge_message; ResetConnectLoopCallback();
diff --git a/components/cast_channel/cast_transport.cc b/components/cast_channel/cast_transport.cc index a85fa98..0418016 100644 --- a/components/cast_channel/cast_transport.cc +++ b/components/cast_channel/cast_transport.cc
@@ -28,6 +28,20 @@ namespace cast_channel { +namespace { + +#if DCHECK_IS_ON() +// Used to filter out PING and PONG message from logs, since there are a lot of +// them and they're not interesting. +bool IsPingPong(const CastMessage& message) { + return message.has_payload_utf8() && + (message.payload_utf8() == R"({"type":"PING"})" || + message.payload_utf8() == R"({"type":"PONG"})"); +} +#endif // DCHECK_IS_ON() + +} // namespace + CastTransportImpl::CastTransportImpl(Channel* channel, int channel_id, const net::IPEndPoint& ip_endpoint, @@ -63,7 +77,6 @@ return read_state == ReadState::READ_ERROR; } - void CastTransportImpl::SetReadDelegate(std::unique_ptr<Delegate> delegate) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(delegate); @@ -85,6 +98,7 @@ net::CompletionOnceCallback callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(IsCastMessageValid(message)); + DVLOG_IF(1, !IsPingPong(message)) << "Sending: " << message; std::string serialized_message; if (!MessageFramer::Serialize(message, &serialized_message)) { base::ThreadTaskRunnerHandle::Get()->PostTask( @@ -358,6 +372,8 @@ return net::ERR_INVALID_RESPONSE; } SetReadState(ReadState::READ); + DVLOG_IF(1, !IsPingPong(*current_message_)) + << "Received: " << *current_message_; delegate_->OnMessage(*current_message_); current_message_.reset(); return net::OK;
diff --git a/components/cronet/OWNERS b/components/cronet/OWNERS index c98d428..16a1baa7 100644 --- a/components/cronet/OWNERS +++ b/components/cronet/OWNERS
@@ -1,4 +1,3 @@ -mef@chromium.org -pauljensen@chromium.org +file://net/OWNERS # COMPONENT: Internals>Network>Library
diff --git a/components/embedder_support/android/java/src/org/chromium/components/embedder_support/view/ContentView.java b/components/embedder_support/android/java/src/org/chromium/components/embedder_support/view/ContentView.java index 30ccfa8..71f681c 100644 --- a/components/embedder_support/android/java/src/org/chromium/components/embedder_support/view/ContentView.java +++ b/components/embedder_support/android/java/src/org/chromium/components/embedder_support/view/ContentView.java
@@ -14,12 +14,15 @@ import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; +import android.view.View.OnSystemUiVisibilityChangeListener; +import android.view.ViewGroup.OnHierarchyChangeListener; import android.view.ViewStructure; import android.view.accessibility.AccessibilityNodeProvider; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.widget.FrameLayout; +import org.chromium.base.ObserverList; import org.chromium.base.TraceEvent; import org.chromium.base.compat.ApiHelperForO; import org.chromium.content_public.browser.ImeAdapter; @@ -34,8 +37,9 @@ * The containing view for {@link WebContents} that exists in the Android UI hierarchy and exposes * the various {@link View} functionality to it. */ -public class ContentView - extends FrameLayout implements ViewEventSink.InternalAccessDelegate, SmartClipProvider { +public class ContentView extends FrameLayout + implements ViewEventSink.InternalAccessDelegate, SmartClipProvider, + OnHierarchyChangeListener, OnSystemUiVisibilityChangeListener { private static final String TAG = "cr.ContentView"; // Default value to signal that the ContentView's size need not be overridden. @@ -56,6 +60,10 @@ } private final WebContents mWebContents; + private final ObserverList<OnHierarchyChangeListener> mHierarchyChangeListeners = + new ObserverList<>(); + private final ObserverList<OnSystemUiVisibilityChangeListener> mSystemUiChangeListeners = + new ObserverList<>(); private ViewEventSink mViewEventSink; private EventForwarder mEventForwarder; @@ -104,6 +112,9 @@ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { ApiHelperForO.setDefaultFocusHighlightEnabled(this, false); } + + setOnHierarchyChangeListener(this); + setOnSystemUiVisibilityChangeListener(this); } protected WebContentsAccessibility getWebContentsAccessibility() { @@ -138,6 +149,76 @@ } @Override + public void setOnHierarchyChangeListener(OnHierarchyChangeListener listener) { + assert listener == this : "Use add/removeOnHierarchyChangeListener instead."; + super.setOnHierarchyChangeListener(listener); + } + + /** + * Registers the given listener to receive state changes for the content view hierarchy. + * @param listener Listener to receive view hierarchy state changes. + */ + public void addOnHierarchyChangeListener(OnHierarchyChangeListener listener) { + mHierarchyChangeListeners.addObserver(listener); + } + + /** + * Unregisters the given listener from receiving state changes for the content view hierarchy. + * @param listener Listener that doesn't want to receive view hierarchy state changes. + */ + public void removeOnHierarchyChangeListener(OnHierarchyChangeListener listener) { + mHierarchyChangeListeners.removeObserver(listener); + } + + @Override + public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener listener) { + assert listener == this : "Use add/removeOnSystemUiVisibilityChangeListener instead."; + super.setOnSystemUiVisibilityChangeListener(listener); + } + + /** + * Registers the given listener to receive system UI visibility state changes. + * @param listener Listener to receive system UI visibility state changes. + */ + public void addOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener listener) { + mSystemUiChangeListeners.addObserver(listener); + } + + /** + * Unregisters the given listener from receiving system UI visibility state changes. + * @param listener Listener that doesn't want to receive state changes. + */ + public void removeOnSystemUiVisibilityChangeListener( + OnSystemUiVisibilityChangeListener listener) { + mSystemUiChangeListeners.removeObserver(listener); + } + + // View.OnHierarchyChangeListener implementation + + @Override + public void onChildViewRemoved(View parent, View child) { + for (OnHierarchyChangeListener listener : mHierarchyChangeListeners) { + listener.onChildViewRemoved(parent, child); + } + } + + @Override + public void onChildViewAdded(View parent, View child) { + for (OnHierarchyChangeListener listener : mHierarchyChangeListeners) { + listener.onChildViewAdded(parent, child); + } + } + + // View.OnHierarchyChangeListener implementation + + @Override + public void onSystemUiVisibilityChange(int visibility) { + for (OnSystemUiVisibilityChangeListener listener : mSystemUiChangeListeners) { + listener.onSystemUiVisibilityChange(visibility); + } + } + + @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mDesiredWidthMeasureSpec != DEFAULT_MEASURE_SPEC) { widthMeasureSpec = mDesiredWidthMeasureSpec;
diff --git a/components/exo/BUILD.gn b/components/exo/BUILD.gn index d8de60c..f8ecb57 100644 --- a/components/exo/BUILD.gn +++ b/components/exo/BUILD.gn
@@ -63,6 +63,7 @@ deps = [ "//base", "//cc", + "//components/viz/host", "//components/viz/service", "//device/gamepad", "//device/gamepad/public/cpp:shared_with_blink",
diff --git a/components/exo/DEPS b/components/exo/DEPS index 39ef604..d6f0e64 100644 --- a/components/exo/DEPS +++ b/components/exo/DEPS
@@ -3,6 +3,7 @@ "+cc", "+chromeos/audio/chromeos_sounds.h", "+components/viz/common", + "+components/viz/host", "+components/viz/service", "+device/gamepad", "+gpu",
diff --git a/components/exo/notification_surface.cc b/components/exo/notification_surface.cc index 7be9155..9814d97b 100644 --- a/components/exo/notification_surface.cc +++ b/components/exo/notification_surface.cc
@@ -8,7 +8,9 @@ #include "components/exo/notification_surface_manager.h" #include "components/exo/shell_surface_util.h" #include "components/exo/surface.h" +#include "components/viz/host/host_frame_sink_manager.h" #include "ui/aura/client/aura_constants.h" +#include "ui/aura/env.h" #include "ui/aura/window.h" #include "ui/gfx/geometry/rect.h" @@ -25,9 +27,12 @@ host_window()->SetProperty(aura::client::kAppType, static_cast<int>(ash::AppType::ARC_APP)); host_window()->Show(); + host_window()->AddObserver(this); } NotificationSurface::~NotificationSurface() { + if (host_window()) + host_window()->RemoveObserver(this); if (added_to_manager_) manager_->RemoveSurface(this); if (root_surface()) @@ -51,7 +56,13 @@ manager_->AddSurface(this); } - SubmitCompositorFrame(); + // Only submit a compositor frame if the notification is being shown. + // Submitting compositor frames while invisible causes Viz to hold on to + // references to each notification buffer while it waits for an embedding ( + // or a timeout occurs). This can cause buffer starvation on the Android side, + // leading to ANRs. + if (is_embedded_) + SubmitCompositorFrame(); } void NotificationSurface::OnSurfaceDestroying(Surface* surface) { @@ -60,4 +71,49 @@ SetRootSurface(nullptr); } +void NotificationSurface::OnWindowDestroying(aura::Window* window) { + window->RemoveObserver(this); +} + +void NotificationSurface::OnWindowAddedToRootWindow(aura::Window* window) { + SubmitCompositorFrame(); + is_embedded_ = true; +} + +void NotificationSurface::OnWindowRemovingFromRootWindow( + aura::Window* window, + aura::Window* new_root) { + if (!new_root) { + // Submit an empty compositor frame if the notification becomes invisible to + // notify Viz that it can release its reference to the existing notification + // buffer. We can't just evict the surface, because LayerTreeFrameSinkHolder + // needs to hold on to resources that were used in the previous frame, if it + // was associated with a different local surface id. + SubmitEmptyCompositorFrame(); + + // Evict the current surface. We can't only submit + // an empty compositor frame, because then when re-opening the message + // center, Viz may think it can use the empty compositor frame to display. + // This will force viz to wait the given deadline for the next notification + // compositor frame when showing the message center. This is to prevent + // flashes when opening the message center. + aura::Env::GetInstance() + ->context_factory_private() + ->GetHostFrameSinkManager() + ->EvictSurfaces({host_window()->GetSurfaceId()}); + + // Allocate a new local surface id for the next compositor frame. + host_window()->AllocateLocalSurfaceId(); + + is_embedded_ = false; + + // Set the deadline to default so Viz waits a while for the notification + // compositor frame to arrive before showing the message center. + host_window()->layer()->SetShowSurface( + host_window()->GetSurfaceId(), host_window()->bounds().size(), + SK_ColorWHITE, cc::DeadlinePolicy::UseDefaultDeadline(), + /*stretch_content_to_fill_bounds=*/false); + } +} + } // namespace exo
diff --git a/components/exo/notification_surface.h b/components/exo/notification_surface.h index 2544e40c..16618f2 100644 --- a/components/exo/notification_surface.h +++ b/components/exo/notification_surface.h
@@ -18,7 +18,9 @@ class Surface; // Handles notification surface role of a given surface. -class NotificationSurface : public SurfaceTreeHost, public SurfaceObserver { +class NotificationSurface : public SurfaceTreeHost, + public SurfaceObserver, + public aura::WindowObserver { public: NotificationSurface(NotificationSurfaceManager* manager, Surface* surface, @@ -38,12 +40,22 @@ // Overridden from SurfaceObserver: void OnSurfaceDestroying(Surface* surface) override; + // Overridden from WindowObserver: + void OnWindowDestroying(aura::Window* window) override; + void OnWindowAddedToRootWindow(aura::Window* window) override; + void OnWindowRemovingFromRootWindow(aura::Window* window, + aura::Window* new_root) override; + private: NotificationSurfaceManager* const manager_; // Not owned. const std::string notification_key_; bool added_to_manager_ = false; + // True if the notification is visible by e.g. being embedded in the message + // center. + bool is_embedded_ = false; + DISALLOW_COPY_AND_ASSIGN(NotificationSurface); };
diff --git a/components/exo/surface_tree_host.cc b/components/exo/surface_tree_host.cc index c062086..d78f16c 100644 --- a/components/exo/surface_tree_host.cc +++ b/components/exo/surface_tree_host.cc
@@ -12,6 +12,9 @@ #include "components/exo/surface.h" #include "components/exo/wm_helper.h" #include "components/viz/common/quads/compositor_frame.h" +#include "components/viz/common/quads/render_pass.h" +#include "components/viz/common/quads/shared_quad_state.h" +#include "components/viz/common/quads/solid_color_draw_quad.h" #include "gpu/command_buffer/client/gles2_interface.h" #include "third_party/skia/include/core/SkPath.h" #include "ui/aura/env.h" @@ -207,21 +210,10 @@ // SurfaceTreeHost, protected: void SurfaceTreeHost::SubmitCompositorFrame() { - DCHECK(root_surface_); + viz::CompositorFrame frame = PrepareToSubmitCompositorFrame(); - if (layer_tree_frame_sink_holder_->is_lost()) { - // We can immediately delete the old LayerTreeFrameSinkHolder because all of - // it's resources are lost anyways. - layer_tree_frame_sink_holder_ = std::make_unique<LayerTreeFrameSinkHolder>( - this, host_window_->CreateLayerTreeFrameSink()); - } - - viz::CompositorFrame frame; - frame.metadata.begin_frame_ack = - viz::BeginFrameAck::CreateManualAckWithDamage(); root_surface_->AppendSurfaceHierarchyCallbacks(&frame_callbacks_, &presentation_callbacks_); - frame.metadata.frame_token = ++next_token_; if (!presentation_callbacks_.empty()) { DCHECK_EQ(active_presentation_callbacks_.count(*next_token_), 0u); active_presentation_callbacks_[*next_token_] = @@ -229,30 +221,9 @@ } else { active_presentation_callbacks_[*next_token_] = PresentationCallbacks(); } - frame.render_pass_list.push_back(viz::RenderPass::Create()); - const std::unique_ptr<viz::RenderPass>& render_pass = - frame.render_pass_list.back(); - const int kRenderPassId = 1; - // Compute a temporaly stable (across frames) size for the render pass output - // rectangle that is consistent with the window size. It is used to set the - // size of the output surface. Note that computing the actual coverage while - // building up the render pass can lead to the size being one pixel too large, - // especially if the device scale factor has a floating point representation - // that requires many bits of precision in the mantissa, due to the coverage - // computing an "enclosing" pixel rectangle. This isn't a problem for the - // dirty rectangle, so it is updated as part of filling in the render pass. - const float device_scale_factor = - host_window()->layer()->device_scale_factor(); - const gfx::Size output_surface_size_in_pixels = gfx::ConvertSizeToPixel( - device_scale_factor, host_window_->bounds().size()); - render_pass->SetNew(kRenderPassId, gfx::Rect(output_surface_size_in_pixels), - gfx::Rect(), gfx::Transform()); - frame.metadata.device_scale_factor = device_scale_factor; - frame.metadata.local_surface_id_allocation_time = - host_window()->GetLocalSurfaceIdAllocation().allocation_time(); root_surface_->AppendSurfaceHierarchyContentsToFrame( - root_surface_origin_, device_scale_factor, + root_surface_origin_, host_window()->layer()->device_scale_factor(), layer_tree_frame_sink_holder_->resource_manager(), &frame); std::vector<GLbyte*> sync_tokens; @@ -267,6 +238,28 @@ layer_tree_frame_sink_holder_->SubmitCompositorFrame(std::move(frame)); } +void SurfaceTreeHost::SubmitEmptyCompositorFrame() { + viz::CompositorFrame frame = PrepareToSubmitCompositorFrame(); + + const std::unique_ptr<viz::RenderPass>& render_pass = + frame.render_pass_list.back(); + const gfx::Rect quad_rect = gfx::Rect(0, 0, 1, 1); + viz::SharedQuadState* quad_state = + render_pass->CreateAndAppendSharedQuadState(); + quad_state->SetAll( + gfx::Transform(), /*quad_layer_rect=*/quad_rect, + /*visible_quad_layer_rect=*/quad_rect, + /*rounded_corner_bounds=*/gfx::RRectF(), /*clip_rect=*/gfx::Rect(), + /*is_clipped=*/false, /*are_contents_opaque=*/true, /*opacity=*/1.f, + /*blend_mode=*/SkBlendMode::kSrcOver, /*sorting_context_id=*/0); + + viz::SolidColorDrawQuad* solid_quad = + render_pass->CreateAndAppendDrawQuad<viz::SolidColorDrawQuad>(); + solid_quad->SetNew(quad_state, quad_rect, quad_rect, SK_ColorBLACK, + /*force_anti_aliasing_off=*/false); + layer_tree_frame_sink_holder_->SubmitCompositorFrame(std::move(frame)); +} + //////////////////////////////////////////////////////////////////////////////// // SurfaceTreeHost, private: @@ -289,4 +282,48 @@ root_surface_origin_, root_surface_->window()->bounds().size())); } +viz::CompositorFrame SurfaceTreeHost::PrepareToSubmitCompositorFrame() { + DCHECK(root_surface_); + + if (layer_tree_frame_sink_holder_->is_lost()) { + // We can immediately delete the old LayerTreeFrameSinkHolder because all of + // it's resources are lost anyways. + layer_tree_frame_sink_holder_ = std::make_unique<LayerTreeFrameSinkHolder>( + this, host_window_->CreateLayerTreeFrameSink()); + } + + viz::CompositorFrame frame; + frame.metadata.begin_frame_ack = + viz::BeginFrameAck::CreateManualAckWithDamage(); + frame.metadata.frame_token = ++next_token_; + frame.render_pass_list.push_back(viz::RenderPass::Create()); + const std::unique_ptr<viz::RenderPass>& render_pass = + frame.render_pass_list.back(); + + const int kRenderPassId = 1; + // Compute a temporally stable (across frames) size for the render pass output + // rectangle that is consistent with the window size. It is used to set the + // size of the output surface. Note that computing the actual coverage while + // building up the render pass can lead to the size being one pixel too large, + // especially if the device scale factor has a floating point representation + // that requires many bits of precision in the mantissa, due to the coverage + // computing an "enclosing" pixel rectangle. This isn't a problem for the + // dirty rectangle, so it is updated as part of filling in the render pass. + // Additionally, we must use this size even if we are submitting an empty + // compositor frame, otherwise we may set the Surface created by Viz to be the + // wrong size. Then, trying to submit a regular compositor frame will fail + // because the size is different. + const float device_scale_factor = + host_window()->layer()->device_scale_factor(); + const gfx::Size output_surface_size_in_pixels = gfx::ConvertSizeToPixel( + device_scale_factor, host_window_->bounds().size()); + render_pass->SetNew(kRenderPassId, gfx::Rect(output_surface_size_in_pixels), + gfx::Rect(), gfx::Transform()); + frame.metadata.device_scale_factor = device_scale_factor; + frame.metadata.local_surface_id_allocation_time = + host_window()->GetLocalSurfaceIdAllocation().allocation_time(); + + return frame; +} + } // namespace exo
diff --git a/components/exo/surface_tree_host.h b/components/exo/surface_tree_host.h index 47aa006..3dee6f4d 100644 --- a/components/exo/surface_tree_host.h +++ b/components/exo/surface_tree_host.h
@@ -85,8 +85,14 @@ // Call this to submit a compositor frame. void SubmitCompositorFrame(); + // Call this to submit an empty compositor frame. This may be useful if + // the surface tree is becoming invisible but the resources (e.g. buffers) + // need to be released back to the client. + void SubmitEmptyCompositorFrame(); + private: void UpdateHostWindowBounds(); + viz::CompositorFrame PrepareToSubmitCompositorFrame(); Surface* root_surface_ = nullptr;
diff --git a/components/grpc_support/OWNERS b/components/grpc_support/OWNERS index c439f9a..cbf0090 100644 --- a/components/grpc_support/OWNERS +++ b/components/grpc_support/OWNERS
@@ -1,3 +1,3 @@ -mef@chromium.org gcasto@chromium.org xyzzyz@chromium.org +file://net/OWNERS
diff --git a/components/gwp_asan/client/guarded_page_allocator_win.cc b/components/gwp_asan/client/guarded_page_allocator_win.cc index 60638e5..92b72a14 100644 --- a/components/gwp_asan/client/guarded_page_allocator_win.cc +++ b/components/gwp_asan/client/guarded_page_allocator_win.cc
@@ -12,9 +12,6 @@ namespace gwp_asan { namespace internal { -// TODO(vtsyrklevich): See if the platform-specific memory allocation and -// protection routines can be broken out in base/ and merged with those used for -// PartionAlloc/ProtectedMemory. void* GuardedPageAllocator::MapRegion() { if (void* hint = MapRegionHint()) if (void* ptr =
diff --git a/components/gwp_asan/client/sampling_state.h b/components/gwp_asan/client/sampling_state.h index 76de175..933ed3f 100644 --- a/components/gwp_asan/client/sampling_state.h +++ b/components/gwp_asan/client/sampling_state.h
@@ -80,6 +80,10 @@ // On macOS, the first use of a thread_local variable on a new thread will // cause a malloc(), causing infinite recursion. Instead, use pthread TLS to // store the counter. + // + // TODO: This is not necessary for PartitionAlloc and likely slower, refactor + // SamplingState to be able to use pthread TLS for malloc() and thread_local + // for PartitionAlloc in this case. ALWAYS_INLINE size_t GetCounter() { return reinterpret_cast<size_t>(pthread_getspecific(tls_key_)); }
diff --git a/components/gwp_asan/crash_handler/crash_handler_unittest.cc b/components/gwp_asan/crash_handler/crash_handler_unittest.cc index 8baa4e0..cd08c1f8 100644 --- a/components/gwp_asan/crash_handler/crash_handler_unittest.cc +++ b/components/gwp_asan/crash_handler/crash_handler_unittest.cc
@@ -365,12 +365,7 @@ EXPECT_TRUE(proto_.has_region_size()); } -#if defined(OS_MACOSX) -#define MAYBE_UnrelatedException DISABLED_UnrelatedException -#else -#define MAYBE_UnrelatedException UnrelatedException -#endif -TEST_P(CrashHandlerTest, MAYBE_DISABLED(MAYBE_UnrelatedException)) { +TEST_P(CrashHandlerTest, MAYBE_DISABLED(UnrelatedException)) { ASSERT_FALSE(gwp_asan_found_); }
diff --git a/components/heap_profiling/supervisor.cc b/components/heap_profiling/supervisor.cc index 8406aa78..712ba9bb 100644 --- a/components/heap_profiling/supervisor.cc +++ b/components/heap_profiling/supervisor.cc
@@ -14,7 +14,6 @@ #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/tracing_controller.h" -#include "content/public/common/service_manager_connection.h" #include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h" #include "services/service_manager/public/cpp/connector.h" @@ -58,13 +57,13 @@ constructor_ = constructor; } -void Supervisor::Start(content::ServiceManagerConnection* connection, +void Supervisor::Start(service_manager::Connector* connector, base::OnceClosure closure) { - Start(connection, GetModeForStartup(), GetStackModeForStartup(), + Start(connector, GetModeForStartup(), GetStackModeForStartup(), GetSamplingRateForStartup(), std::move(closure)); } -void Supervisor::Start(content::ServiceManagerConnection* connection, +void Supervisor::Start(service_manager::Connector* connector, Mode mode, mojom::StackMode stack_mode, uint32_t sampling_rate, @@ -73,11 +72,10 @@ DCHECK(!started_); base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::IO}) - ->PostTask(FROM_HERE, - base::BindOnce(&Supervisor::StartServiceOnIOThread, - base::Unretained(this), - connection->GetConnector()->Clone(), mode, - stack_mode, sampling_rate, std::move(closure))); + ->PostTask(FROM_HERE, base::BindOnce(&Supervisor::StartServiceOnIOThread, + base::Unretained(this), + connector->Clone(), mode, stack_mode, + sampling_rate, std::move(closure))); } Mode Supervisor::GetMode() {
diff --git a/components/heap_profiling/supervisor.h b/components/heap_profiling/supervisor.h index 4bd167c..889ce93 100644 --- a/components/heap_profiling/supervisor.h +++ b/components/heap_profiling/supervisor.h
@@ -10,10 +10,6 @@ #include "base/process/process.h" #include "components/services/heap_profiling/public/mojom/heap_profiling_client.mojom.h" -namespace content { -class ServiceManagerConnection; -} // namespace content - namespace service_manager { class Connector; } // namespace service_manager @@ -67,9 +63,8 @@ // * Relying on the assumption that in all other cases, the object is either // fully initialized or not initialized. There are DCHECKs to enforce this // assumption. - void Start(content::ServiceManagerConnection* connection, - base::OnceClosure callback); - void Start(content::ServiceManagerConnection* connection, + void Start(service_manager::Connector* connector, base::OnceClosure callback); + void Start(service_manager::Connector* connector, Mode mode, mojom::StackMode stack_mode, uint32_t sampling_rate,
diff --git a/components/heap_profiling/test_driver.cc b/components/heap_profiling/test_driver.cc index 412b58f..94eb977 100644 --- a/components/heap_profiling/test_driver.cc +++ b/components/heap_profiling/test_driver.cc
@@ -26,6 +26,7 @@ #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_process_host.h" +#include "content/public/browser/system_connector.h" #include "content/public/browser/tracing_controller.h" #include "content/public/common/service_manager_connection.h" @@ -684,11 +685,10 @@ return true; } - content::ServiceManagerConnection* connection = - content::ServiceManagerConnection::GetForProcess(); - if (!connection) { - LOG(ERROR) << "A ServiceManagerConnection was not available for the " - "current process."; + service_manager::Connector* connector = content::GetSystemConnector(); + content::ServiceManagerConnection::GetForProcess(); + if (!connector) { + LOG(ERROR) << "A system Connector is not available in this environment."; return false; } @@ -710,7 +710,7 @@ uint32_t sampling_rate = options_.should_sample ? (options_.sample_everything ? 2 : kSampleRate) : 1; - Supervisor::GetInstance()->Start(connection, options_.mode, + Supervisor::GetInstance()->Start(connector, options_.mode, options_.stack_mode, sampling_rate, std::move(start_callback)); @@ -738,11 +738,10 @@ return true; } - content::ServiceManagerConnection* connection = - content::ServiceManagerConnection::GetForProcess(); - if (!connection) { - LOG(ERROR) << "A ServiceManagerConnection was not available for the " - "current process."; + service_manager::Connector* connector = content::GetSystemConnector(); + content::ServiceManagerConnection::GetForProcess(); + if (!connector) { + LOG(ERROR) << "A system Connector is not available in this environment."; return false; } @@ -763,7 +762,7 @@ uint32_t sampling_rate = options_.should_sample ? (options_.sample_everything ? 2 : kSampleRate) : 1; - Supervisor::GetInstance()->Start(connection, options_.mode, + Supervisor::GetInstance()->Start(connector, options_.mode, options_.stack_mode, sampling_rate, std::move(start_callback));
diff --git a/components/send_tab_to_self/send_tab_to_self_bridge.cc b/components/send_tab_to_self/send_tab_to_self_bridge.cc index f296796..4310bc6 100644 --- a/components/send_tab_to_self/send_tab_to_self_bridge.cc +++ b/components/send_tab_to_self/send_tab_to_self_bridge.cc
@@ -441,6 +441,13 @@ return change_processor()->IsTrackingMetadata(); } +bool SendTabToSelfBridge::HasValidTargetDevice() { + if (ShouldUpdateTargetDeviceNameToCacheInfoMap()) { + SetTargetDeviceNameToCacheInfoMap(); + } + return target_device_name_to_cache_info_.size() > 0; +} + std::map<std::string, TargetDeviceInfo> SendTabToSelfBridge::GetTargetDeviceNameToCacheInfoMap() { if (ShouldUpdateTargetDeviceNameToCacheInfoMap()) {
diff --git a/components/send_tab_to_self/send_tab_to_self_bridge.h b/components/send_tab_to_self/send_tab_to_self_bridge.h index b3028c10..7e817b1 100644 --- a/components/send_tab_to_self/send_tab_to_self_bridge.h +++ b/components/send_tab_to_self/send_tab_to_self_bridge.h
@@ -82,6 +82,7 @@ void DismissEntry(const std::string& guid) override; void MarkEntryOpened(const std::string& guid) override; bool IsReady() override; + bool HasValidTargetDevice() override; std::map<std::string, TargetDeviceInfo> GetTargetDeviceNameToCacheInfoMap() override;
diff --git a/components/send_tab_to_self/send_tab_to_self_model.h b/components/send_tab_to_self/send_tab_to_self_model.h index 4497384a..bae3766 100644 --- a/components/send_tab_to_self/send_tab_to_self_model.h +++ b/components/send_tab_to_self/send_tab_to_self_model.h
@@ -72,6 +72,9 @@ void AddObserver(SendTabToSelfModelObserver* observer); void RemoveObserver(SendTabToSelfModelObserver* observer); + // Returns true if the user has valid target device. + virtual bool HasValidTargetDevice() = 0; + // Returns a map of the name of possible target devices for the send tab to // self feature to their cache guid. This is a thin layer on top of // DeviceInfoTracker.
diff --git a/components/send_tab_to_self/test_send_tab_to_self_model.cc b/components/send_tab_to_self/test_send_tab_to_self_model.cc index 294b3ce..6883553 100644 --- a/components/send_tab_to_self/test_send_tab_to_self_model.cc +++ b/components/send_tab_to_self/test_send_tab_to_self_model.cc
@@ -35,6 +35,10 @@ return false; } +bool TestSendTabToSelfModel::HasValidTargetDevice() { + return false; +} + std::map<std::string, TargetDeviceInfo> TestSendTabToSelfModel::GetTargetDeviceNameToCacheInfoMap() { return {};
diff --git a/components/send_tab_to_self/test_send_tab_to_self_model.h b/components/send_tab_to_self/test_send_tab_to_self_model.h index 80e8853..bdc0e4f 100644 --- a/components/send_tab_to_self/test_send_tab_to_self_model.h +++ b/components/send_tab_to_self/test_send_tab_to_self_model.h
@@ -36,6 +36,7 @@ void MarkEntryOpened(const std::string& guid) override; bool IsReady() override; + bool HasValidTargetDevice() override; std::map<std::string, TargetDeviceInfo> GetTargetDeviceNameToCacheInfoMap() override; };
diff --git a/components/sync/base/sync_prefs.cc b/components/sync/base/sync_prefs.cc index e0233e2..db4744b 100644 --- a/components/sync/base/sync_prefs.cc +++ b/components/sync/base/sync_prefs.cc
@@ -148,7 +148,7 @@ user_prefs::PrefRegistrySyncable* registry) { // Actual user-controlled preferences. registry->RegisterBooleanPref(prefs::kSyncFirstSetupComplete, false); - registry->RegisterBooleanPref(prefs::kSyncSuppressStart, true); + registry->RegisterBooleanPref(prefs::kSyncSuppressStart, false); registry->RegisterBooleanPref(prefs::kSyncKeepEverythingSynced, true); for (UserSelectableType type : UserSelectableTypeSet::All()) { RegisterTypeSelectedPref(registry, type);
diff --git a/components/sync/base/sync_prefs_unittest.cc b/components/sync/base/sync_prefs_unittest.cc index 737ec95..529c387 100644 --- a/components/sync/base/sync_prefs_unittest.cc +++ b/components/sync/base/sync_prefs_unittest.cc
@@ -77,12 +77,12 @@ EXPECT_CALL(mock_sync_pref_observer, OnSyncManagedPrefChange(false)); EXPECT_CALL(mock_sync_pref_observer, OnFirstSetupCompletePrefChange(true)); EXPECT_CALL(mock_sync_pref_observer, OnFirstSetupCompletePrefChange(false)); - EXPECT_CALL(mock_sync_pref_observer, OnSyncRequestedPrefChange(true)); EXPECT_CALL(mock_sync_pref_observer, OnSyncRequestedPrefChange(false)); + EXPECT_CALL(mock_sync_pref_observer, OnSyncRequestedPrefChange(true)); ASSERT_FALSE(sync_prefs_->IsManaged()); ASSERT_FALSE(sync_prefs_->IsFirstSetupComplete()); - ASSERT_FALSE(sync_prefs_->IsSyncRequested()); + ASSERT_TRUE(sync_prefs_->IsSyncRequested()); sync_prefs_->AddSyncPrefObserver(&mock_sync_pref_observer); @@ -98,10 +98,10 @@ sync_prefs_->ClearPreferences(); EXPECT_FALSE(sync_prefs_->IsFirstSetupComplete()); - sync_prefs_->SetSyncRequested(true); - EXPECT_TRUE(sync_prefs_->IsSyncRequested()); sync_prefs_->SetSyncRequested(false); EXPECT_FALSE(sync_prefs_->IsSyncRequested()); + sync_prefs_->SetSyncRequested(true); + EXPECT_TRUE(sync_prefs_->IsSyncRequested()); sync_prefs_->RemoveSyncPrefObserver(&mock_sync_pref_observer); } @@ -135,11 +135,11 @@ sync_prefs_->SetFirstSetupComplete(); EXPECT_TRUE(sync_prefs_->IsFirstSetupComplete()); - EXPECT_FALSE(sync_prefs_->IsSyncRequested()); - sync_prefs_->SetSyncRequested(true); EXPECT_TRUE(sync_prefs_->IsSyncRequested()); sync_prefs_->SetSyncRequested(false); EXPECT_FALSE(sync_prefs_->IsSyncRequested()); + sync_prefs_->SetSyncRequested(true); + EXPECT_TRUE(sync_prefs_->IsSyncRequested()); EXPECT_EQ(base::Time(), sync_prefs_->GetLastSyncedTime()); const base::Time& now = base::Time::Now();
diff --git a/components/sync/driver/profile_sync_service_startup_unittest.cc b/components/sync/driver/profile_sync_service_startup_unittest.cc index a5ca326..86c6928 100644 --- a/components/sync/driver/profile_sync_service_startup_unittest.cc +++ b/components/sync/driver/profile_sync_service_startup_unittest.cc
@@ -165,8 +165,7 @@ // Should not actually start, rather just clean things up and wait // to be enabled. sync_service()->Initialize(); - EXPECT_EQ(SyncService::DISABLE_REASON_NOT_SIGNED_IN | - SyncService::DISABLE_REASON_USER_CHOICE, + EXPECT_EQ(SyncService::DISABLE_REASON_NOT_SIGNED_IN, sync_service()->GetDisableReasons()); EXPECT_EQ(SyncService::TransportState::DISABLED, sync_service()->GetTransportState()); @@ -604,8 +603,7 @@ // There is no signed-in user, so also nobody has decided that Sync should be // started. - EXPECT_EQ(SyncService::DISABLE_REASON_NOT_SIGNED_IN | - SyncService::DISABLE_REASON_USER_CHOICE, + EXPECT_EQ(SyncService::DISABLE_REASON_NOT_SIGNED_IN, sync_service()->GetDisableReasons()); EXPECT_EQ(SyncService::TransportState::DISABLED, sync_service()->GetTransportState()); @@ -613,7 +611,7 @@ // Sign in. Now Sync-the-transport could start, but gets deferred by default. // Sync-the-feature still doesn't start until the user says they want it. SimulateTestUserSignin(); - EXPECT_EQ(SyncService::DISABLE_REASON_USER_CHOICE, + EXPECT_EQ(SyncService::DISABLE_REASON_NONE, sync_service()->GetDisableReasons()); EXPECT_EQ(SyncService::TransportState::START_DEFERRED, sync_service()->GetTransportState());
diff --git a/components/viz/common/display/renderer_settings.h b/components/viz/common/display/renderer_settings.h index 78041fcb..d433fb2 100644 --- a/components/viz/common/display/renderer_settings.h +++ b/components/viz/common/display/renderer_settings.h
@@ -27,7 +27,6 @@ bool force_antialiasing = false; bool force_blending_with_shaders = false; bool partial_swap_enabled = false; - bool finish_rendering_on_resize = false; bool should_clear_root_render_pass = true; bool release_overlay_resources_after_gpu_query = false; bool tint_gl_composited_content = false;
diff --git a/components/viz/host/renderer_settings_creation.cc b/components/viz/host/renderer_settings_creation.cc index 78a6b5739..3b99fdc3 100644 --- a/components/viz/host/renderer_settings_creation.cc +++ b/components/viz/host/renderer_settings_creation.cc
@@ -51,9 +51,7 @@ base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); renderer_settings.partial_swap_enabled = !command_line->HasSwitch(switches::kUIDisablePartialSwap); -#if defined(OS_WIN) - renderer_settings.finish_rendering_on_resize = true; -#elif defined(OS_MACOSX) +#if defined(OS_MACOSX) renderer_settings.release_overlay_resources_after_gpu_query = true; renderer_settings.auto_resize_output_surface = false; #elif defined(OS_CHROMEOS)
diff --git a/components/viz/service/display/display.cc b/components/viz/service/display/display.cc index 1e83790..008bb39b 100644 --- a/components/viz/service/display/display.cc +++ b/components/viz/service/display/display.cc
@@ -153,6 +153,9 @@ } #endif + if (no_pending_swaps_callback_) + std::move(no_pending_swaps_callback_).Run(); + for (auto& observer : observers_) observer.OnDisplayDestroyed(); observers_.Clear(); @@ -250,21 +253,41 @@ TRACE_EVENT0("viz", "Display::Resize"); - // Need to ensure all pending swaps have executed before the window is - // resized, or D3D11 will scale the swap output. - if (settings_.finish_rendering_on_resize) { - if (!swapped_since_resize_ && scheduler_) - scheduler_->ForceImmediateSwapIfPossible(); - if (swapped_since_resize_ && output_surface_ && - output_surface_->context_provider()) - output_surface_->context_provider()->ContextGL()->ShallowFinishCHROMIUM(); - } + // Resize() shouldn't be called while waiting for pending swaps to ack unless + // it's being called with size (0, 0) to disable DrawAndSwap(). + DCHECK(no_pending_swaps_callback_.is_null() || size.IsEmpty()); + swapped_since_resize_ = false; current_surface_size_ = size; if (scheduler_) scheduler_->DisplayResized(); } +void Display::DisableSwapUntilResize( + base::OnceClosure no_pending_swaps_callback) { + TRACE_EVENT0("viz", "Display::DisableSwapUntilResize"); + DCHECK(no_pending_swaps_callback_.is_null()); + + if (!current_surface_size_.IsEmpty()) { + DCHECK(scheduler_); + + if (!swapped_since_resize_) + scheduler_->ForceImmediateSwapIfPossible(); + + if (no_pending_swaps_callback && scheduler_->pending_swaps() > 0 && + (output_surface_->context_provider() || + output_surface_->AsSkiaOutputSurface())) { + no_pending_swaps_callback_ = std::move(no_pending_swaps_callback); + } + + Resize(gfx::Size()); + } + + // There are no pending swaps for current size so immediately run callback. + if (no_pending_swaps_callback) + std::move(no_pending_swaps_callback).Run(); +} + void Display::SetColorMatrix(const SkMatrix44& matrix) { if (output_surface_) output_surface_->set_color_matrix(matrix); @@ -577,8 +600,12 @@ } void Display::DidReceiveSwapBuffersAck() { - if (scheduler_) + if (scheduler_) { scheduler_->DidReceiveSwapBuffersAck(); + if (no_pending_swaps_callback_ && scheduler_->pending_swaps() == 0) + std::move(no_pending_swaps_callback_).Run(); + } + if (renderer_) renderer_->SwapBuffersComplete(); }
diff --git a/components/viz/service/display/display.h b/components/viz/service/display/display.h index e5a5847..38208d7a 100644 --- a/components/viz/service/display/display.h +++ b/components/viz/service/display/display.h
@@ -98,6 +98,14 @@ void SetVisible(bool visible); void Resize(const gfx::Size& new_size); + // Stop drawing until Resize() is called with a new size. If the display + // hasn't drawn a frame at the current size *and* it's possible to immediately + // draw then this will run DrawAndSwap() first. + // + // |no_pending_swaps_callback| will be run there are no more swaps pending and + // may be run immediately. + void DisableSwapUntilResize(base::OnceClosure no_pending_swaps_callback); + // Sets the color matrix that will be used to transform the output of this // display. This is only supported for GPU compositing. void SetColorMatrix(const SkMatrix44& matrix); @@ -197,6 +205,9 @@ std::pair<base::TimeTicks, std::vector<Surface::PresentedCallback>>> pending_presented_callbacks_; + // Callback that will be run after all pending swaps have acked. + base::OnceClosure no_pending_swaps_callback_; + int64_t swapped_trace_id_ = 0; int64_t last_presented_trace_id_ = 0;
diff --git a/components/viz/service/display/display_scheduler.h b/components/viz/service/display/display_scheduler.h index 38cf2d1..3937f00d 100644 --- a/components/viz/service/display/display_scheduler.h +++ b/components/viz/service/display/display_scheduler.h
@@ -44,6 +44,8 @@ bool wait_for_all_surfaces_before_draw = false); ~DisplayScheduler() override; + int pending_swaps() const { return pending_swaps_; } + void SetClient(DisplaySchedulerClient* client); void SetVisible(bool visible);
diff --git a/components/viz/service/display/display_unittest.cc b/components/viz/service/display/display_unittest.cc index 3b42ed4..2dde14d 100644 --- a/components/viz/service/display/display_unittest.cc +++ b/components/viz/service/display/display_unittest.cc
@@ -8,6 +8,7 @@ #include "base/bind.h" #include "base/run_loop.h" +#include "base/test/bind_test_util.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/null_task_runner.h" #include "cc/base/math_util.h" @@ -142,18 +143,11 @@ std::move(output_surface)); } - void SetUpGpuDisplay(const RendererSettings& settings, - std::unique_ptr<TestGLES2Interface> context = nullptr) { - std::unique_ptr<FakeOutputSurface> output_surface; - scoped_refptr<TestContextProvider> provider; - if (context) { - provider = TestContextProvider::Create(std::move(context)); - - } else { - provider = TestContextProvider::Create(); - } + void SetUpGpuDisplay(const RendererSettings& settings) { + scoped_refptr<TestContextProvider> provider = TestContextProvider::Create(); provider->BindToCurrentThread(); - output_surface = FakeOutputSurface::Create3d(std::move(provider)); + std::unique_ptr<FakeOutputSurface> output_surface = + FakeOutputSurface::Create3d(std::move(provider)); output_surface_ = output_surface.get(); CreateDisplaySchedulerAndDisplay(settings, kArbitraryFrameSinkId, @@ -237,7 +231,6 @@ TEST_F(DisplayTest, DisplayDamaged) { RendererSettings settings; settings.partial_swap_enabled = true; - settings.finish_rendering_on_resize = true; SetUpSoftwareDisplay(settings); gfx::ColorSpace color_space_1 = gfx::ColorSpace::CreateXYZD50(); gfx::ColorSpace color_space_2 = gfx::ColorSpace::CreateSCRGBLinear(); @@ -458,7 +451,8 @@ EXPECT_EQ(4u, output_surface_->num_sent_frames()); } - // Resize should cause a swap if no frame was swapped at the previous size. + // DisableSwapUntilResize() should cause a swap if no frame was swapped at the + // previous size. { id_allocator_.GenerateId(); display_->SetLocalSurfaceId( @@ -484,6 +478,7 @@ EXPECT_FALSE(scheduler_->has_new_root_surface); scheduler_->swapped = false; + display_->DisableSwapUntilResize(base::OnceClosure()); display_->Resize(gfx::Size(100, 100)); EXPECT_TRUE(scheduler_->swapped); EXPECT_EQ(5u, output_surface_->num_sent_frames()); @@ -530,9 +525,7 @@ // Verifies latency info is stored only up to a limit if a swap fails. void DisplayTest::LatencyInfoCapTest(bool over_capacity) { - RendererSettings settings; - settings.finish_rendering_on_resize = true; - SetUpSoftwareDisplay(settings); + SetUpSoftwareDisplay(RendererSettings()); StubDisplayClient client; display_->Initialize(&client, manager_.surface_manager()); @@ -582,6 +575,7 @@ CompositorFrame frame3 = CompositorFrameBuilder().AddRenderPass(kOutputRect, kDamageRect).Build(); support_->SubmitCompositorFrame(local_surface_id, std::move(frame3)); + EXPECT_TRUE(display_->DrawAndSwap()); // Verify whether or not LatencyInfo was dropped. size_t expected_size = 1; // The Display adds its own latency info. @@ -602,12 +596,7 @@ LatencyInfoCapTest(true); } -class MockedGLES2Interface : public TestGLES2Interface { - public: - MOCK_METHOD0(ShallowFinishCHROMIUM, void()); -}; - -TEST_F(DisplayTest, Finish) { +TEST_F(DisplayTest, DisableSwapUntilResize) { id_allocator_.GenerateId(); LocalSurfaceId local_surface_id1( id_allocator_.GetCurrentLocalSurfaceIdAllocation().local_surface_id()); @@ -617,13 +606,8 @@ RendererSettings settings; settings.partial_swap_enabled = true; - settings.finish_rendering_on_resize = true; - auto gl = std::make_unique<MockedGLES2Interface>(); - MockedGLES2Interface* gl_ptr = gl.get(); - EXPECT_CALL(*gl_ptr, ShallowFinishCHROMIUM()).Times(0); - - SetUpGpuDisplay(settings, std::move(gl)); + SetUpGpuDisplay(settings); StubDisplayClient client; display_->Initialize(&client, manager_.surface_manager()); @@ -643,22 +627,26 @@ SubmitCompositorFrame(&pass_list, local_surface_id1); } - display_->DrawAndSwap(); + EXPECT_FALSE(scheduler_->swapped); - // First resize and draw shouldn't finish. - testing::Mock::VerifyAndClearExpectations(gl_ptr); + // DisableSwapUntilResize() should trigger a swap because we have a frame of + // the correct size and haven't swapped at that size yet. + bool swap_callback_run = false; + display_->DisableSwapUntilResize(base::BindLambdaForTesting( + [&swap_callback_run]() { swap_callback_run = true; })); + EXPECT_TRUE(scheduler_->swapped); + EXPECT_TRUE(swap_callback_run); - EXPECT_CALL(*gl_ptr, ShallowFinishCHROMIUM()); display_->Resize(gfx::Size(150, 150)); - testing::Mock::VerifyAndClearExpectations(gl_ptr); + scheduler_->swapped = false; - // Another resize without a swap doesn't need to finish. - EXPECT_CALL(*gl_ptr, ShallowFinishCHROMIUM()).Times(0); + // DisableSwapUntilResize() won't trigger a swap because there is no frame + // of the correct size to draw. display_->SetLocalSurfaceId(local_surface_id2, 1.f); + display_->DisableSwapUntilResize(base::OnceClosure()); + EXPECT_FALSE(scheduler_->swapped); display_->Resize(gfx::Size(200, 200)); - testing::Mock::VerifyAndClearExpectations(gl_ptr); - EXPECT_CALL(*gl_ptr, ShallowFinishCHROMIUM()).Times(0); { RenderPassList pass_list; auto pass = RenderPass::Create(); @@ -670,13 +658,16 @@ SubmitCompositorFrame(&pass_list, local_surface_id2); } + // DrawAndSwap() should trigger a swap at current size. display_->DrawAndSwap(); + EXPECT_TRUE(scheduler_->swapped); + scheduler_->swapped = false; - testing::Mock::VerifyAndClearExpectations(gl_ptr); + // DisableSwapUntilResize() won't trigger another swap because we already + // swapped a frame at the current size. + display_->DisableSwapUntilResize(base::OnceClosure()); + EXPECT_FALSE(scheduler_->swapped); - EXPECT_CALL(*gl_ptr, ShallowFinishCHROMIUM()); - display_->Resize(gfx::Size(250, 250)); - testing::Mock::VerifyAndClearExpectations(gl_ptr); TearDownDisplay(); }
diff --git a/components/viz/service/display/gl_renderer.cc b/components/viz/service/display/gl_renderer.cc index 64f2992..3b93c6b 100644 --- a/components/viz/service/display/gl_renderer.cc +++ b/components/viz/service/display/gl_renderer.cc
@@ -843,21 +843,19 @@ (params->background_rect.top_right() - unclipped_rect.top_right()) + (params->background_rect.bottom_left() - unclipped_rect.bottom_left()); - // Update the backdrop filter to include "regular" filters and opacity. - cc::FilterOperations backdrop_filters_plus_effects = + // Update the backdrop filter to include opacity. + cc::FilterOperations backdrop_filters_plus_opacity = *params->backdrop_filters; - if (params->filters) { - for (const auto& filter_op : params->filters->operations()) - backdrop_filters_plus_effects.Append(filter_op); - } + DCHECK(!params->filters) + << "Filters should always be in a separate Effect node"; if (quad->shared_quad_state->opacity < 1.0) { - backdrop_filters_plus_effects.Append( + backdrop_filters_plus_opacity.Append( cc::FilterOperation::CreateOpacityFilter( quad->shared_quad_state->opacity)); } auto paint_filter = cc::RenderSurfaceFilters::BuildImageFilter( - backdrop_filters_plus_effects, gfx::SizeF(params->background_rect.size()), + backdrop_filters_plus_opacity, gfx::SizeF(params->background_rect.size()), gfx::Vector2dF(clipping_offset)); // TODO(senorblanco): background filters should be moved to the
diff --git a/components/viz/service/display/software_renderer.cc b/components/viz/service/display/software_renderer.cc index e783b198..37e16ef 100644 --- a/components/viz/service/display/software_renderer.cc +++ b/components/viz/service/display/software_renderer.cc
@@ -803,14 +803,12 @@ (unclipped_rect.top_right() - backdrop_rect.top_right()) + (backdrop_rect.bottom_left() - unclipped_rect.bottom_left()); - // Update the backdrop filter to include "regular" filters and opacity. - cc::FilterOperations backdrop_filters_plus_effects = *backdrop_filters; - if (regular_filters) { - for (const auto& filter_op : regular_filters->operations()) - backdrop_filters_plus_effects.Append(filter_op); - } + // Update the backdrop filter to include opacity. + cc::FilterOperations backdrop_filters_plus_opacity = *backdrop_filters; + DCHECK(!regular_filters) + << "Filters should always be in a separate Effect node"; if (quad->shared_quad_state->opacity < 1.0) { - backdrop_filters_plus_effects.Append( + backdrop_filters_plus_opacity.Append( cc::FilterOperation::CreateOpacityFilter( quad->shared_quad_state->opacity)); } @@ -819,7 +817,7 @@ gfx::Rect(0, 0, backdrop_bitmap.width(), backdrop_bitmap.height()); sk_sp<SkImageFilter> filter = cc::RenderSurfaceFilters::BuildImageFilter( - backdrop_filters_plus_effects, + backdrop_filters_plus_opacity, gfx::SizeF(bitmap_rect.width(), bitmap_rect.height()), clipping_offset) ->cached_sk_filter_;
diff --git a/components/viz/service/display_embedder/image_context.h b/components/viz/service/display_embedder/image_context.h index 44f62e0..5fb58e62 100644 --- a/components/viz/service/display_embedder/image_context.h +++ b/components/viz/service/display_embedder/image_context.h
@@ -15,6 +15,7 @@ #include "gpu/command_buffer/common/sync_token.h" #include "third_party/skia/include/core/SkImageInfo.h" #include "third_party/skia/include/core/SkRefCnt.h" +#include "third_party/skia/include/gpu/GrBackendSurface.h" #include "third_party/skia/include/gpu/GrTypes.h" #include "ui/gfx/geometry/size.h" @@ -61,8 +62,8 @@ // The promise image which is used on display thread. sk_sp<SkImage> image; - // Fallback SkImage in case we cannot produce a |representation|. - sk_sp<SkImage> fallback_image; + // Fallback in case we cannot produce a |representation|. + GrBackendTexture fallback_texture; // |sync_token| is only accessed on display thread. gpu::SyncToken sync_token;
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl.cc b/components/viz/service/display_embedder/skia_output_surface_impl.cc index 5acedb7..34d0877 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl.cc +++ b/components/viz/service/display_embedder/skia_output_surface_impl.cc
@@ -97,7 +97,7 @@ std::unique_ptr<SkiaOutputSurfaceImplOnGpu> impl_on_gpu, base::WaitableEvent* event) { if (!images.empty()) - impl_on_gpu->ReleaseSkImages(std::move(images)); + impl_on_gpu->ReleaseImageContexts(std::move(images)); if (!render_passes.empty()) impl_on_gpu->RemoveRenderPassResource(std::move(render_passes)); impl_on_gpu = nullptr; @@ -319,9 +319,9 @@ // impl_on_gpu_ is released on the GPU thread by a posted task from // SkiaOutputSurfaceImpl::dtor. So it is safe to use base::Unretained. - auto callback = base::BindOnce(&SkiaOutputSurfaceImplOnGpu::ReleaseSkImages, - base::Unretained(impl_on_gpu_.get()), - std::move(image_contexts)); + auto callback = base::BindOnce( + &SkiaOutputSurfaceImplOnGpu::ReleaseImageContexts, + base::Unretained(impl_on_gpu_.get()), std::move(image_contexts)); ScheduleGpuTask(std::move(callback), std::vector<gpu::SyncToken>()); }
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.cc b/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.cc index f11b2ab..95cff29 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.cc +++ b/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.cc
@@ -716,8 +716,11 @@ DCHECK(output_device_); gfx::SwapResponse response; - if (capabilities().supports_post_sub_buffer && frame.sub_buffer_rect) { - DCHECK(!frame.sub_buffer_rect->IsEmpty()); + if (frame.sub_buffer_rect && frame.sub_buffer_rect->IsEmpty()) { + // TODO(https://crbug.com/898680): Maybe do something for overlays here. + // This codepath was added in https://codereview.chromium.org/1489153002 + // to support updating overlays without changing the framebuffer contents. + } else if (capabilities().supports_post_sub_buffer && frame.sub_buffer_rect) { if (!capabilities().flipped_output_surface) frame.sub_buffer_rect->set_y(size_.height() - frame.sub_buffer_rect->y() - frame.sub_buffer_rect->height()); @@ -1009,25 +1012,21 @@ BitsPerPixel(context->resource_format)) return; - auto image_info = - SkImageInfo::Make(context->size.width(), context->size.height(), - color_type, kOpaque_SkAlphaType); - auto surface = SkSurface::MakeRenderTarget( - gr_context(), SkBudgeted::kNo, image_info, 0 /* sampleCount */, - kTopLeft_GrSurfaceOrigin, nullptr /* surfaceProps */); - if (!surface) - return; - - auto* canvas = surface->getCanvas(); + context->fallback_texture = + context_state_->gr_context()->createBackendTexture( + context->size.width(), context->size.height(), color_type, #if DCHECK_IS_ON() - canvas->clear(SK_ColorRED); + SkColors::kRed, #else - canvas->clear(SK_ColorWHITE); + SkColors::kWhite, #endif - context->fallback_image = surface->makeImageSnapshot(); - auto gr_texture = context->fallback_image->getBackendTexture( - false /* flushPendingGrContextIO */); - context->promise_image_texture = SkPromiseImageTexture::Make(gr_texture); + GrMipMapped::kNo, GrRenderable::kYes); + if (!context->fallback_texture.isValid()) { + DLOG(ERROR) << "Could not create backend texture."; + return; + } + context->promise_image_texture = + SkPromiseImageTexture::Make(context->fallback_texture); } void SkiaOutputSurfaceImplOnGpu::BeginAccessImages( @@ -1182,12 +1181,18 @@ return gr_context()->threadSafeProxy(); } -void SkiaOutputSurfaceImplOnGpu::ReleaseSkImages( +void SkiaOutputSurfaceImplOnGpu::ReleaseImageContexts( std::vector<std::unique_ptr<ImageContext>> image_contexts) { DCHECK(!image_contexts.empty()); // The window could be destroyed already, and the MakeCurrent will fail with // an destroyed window, so MakeCurrent without requiring the fbo0. MakeCurrent(false /* need_fbo0 */); + + for (const auto& image_context : image_contexts) { + if (image_context->fallback_texture.isValid()) + gpu::DeleteGrBackendTexture(context_state_.get(), + &image_context->fallback_texture); + } } void SkiaOutputSurfaceImplOnGpu::SetCapabilitiesForTesting(
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.h b/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.h index aca2f27..148959f0 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.h +++ b/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.h
@@ -136,7 +136,7 @@ sk_sp<GrContextThreadSafeProxy> GetGrContextThreadSafeProxy(); const gl::GLVersionInfo* gl_version_info() const { return gl_version_info_; } - void ReleaseSkImages( + void ReleaseImageContexts( std::vector<std::unique_ptr<ImageContext>> image_contexts); bool was_context_lost() { return context_state_->context_lost(); }
diff --git a/components/viz/service/frame_sinks/root_compositor_frame_sink_impl.cc b/components/viz/service/frame_sinks/root_compositor_frame_sink_impl.cc index b58ef60..639e1617 100644 --- a/components/viz/service/frame_sinks/root_compositor_frame_sink_impl.cc +++ b/components/viz/service/frame_sinks/root_compositor_frame_sink_impl.cc
@@ -156,8 +156,7 @@ void RootCompositorFrameSinkImpl::DisableSwapUntilResize( DisableSwapUntilResizeCallback callback) { - display_->Resize(gfx::Size()); - std::move(callback).Run(); + display_->DisableSwapUntilResize(std::move(callback)); } void RootCompositorFrameSinkImpl::Resize(const gfx::Size& size) {
diff --git a/components/viz/service/main/viz_compositor_thread_runner.cc b/components/viz/service/main/viz_compositor_thread_runner.cc index 32621fa..d4407ab 100644 --- a/components/viz/service/main/viz_compositor_thread_runner.cc +++ b/components/viz/service/main/viz_compositor_thread_runner.cc
@@ -8,6 +8,7 @@ #include "base/bind.h" #include "base/command_line.h" +#include "base/feature_list.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread.h" #include "base/trace_event/memory_dump_manager.h" @@ -19,6 +20,7 @@ #include "components/viz/service/display_embedder/server_shared_bitmap_manager.h" #include "components/viz/service/frame_sinks/frame_sink_manager_impl.h" #include "components/viz/service/gl/gpu_service_impl.h" +#include "gpu/config/gpu_finch_features.h" #include "gpu/ipc/command_buffer_task_executor.h" #include "gpu/ipc/service/gpu_memory_buffer_factory.h" #include "ui/gfx/switches.h" @@ -40,9 +42,13 @@ const char kThreadName[] = "VizCompositorThread"; std::unique_ptr<VizCompositorThreadType> CreateAndStartCompositorThread() { + const base::ThreadPriority thread_priority = + base::FeatureList::IsEnabled(features::kGpuUseDisplayThreadPriority) + ? base::ThreadPriority::DISPLAY + : base::ThreadPriority::NORMAL; #if defined(OS_ANDROID) auto thread = std::make_unique<base::android::JavaHandlerThread>( - kThreadName, base::ThreadPriority::DISPLAY); + kThreadName, thread_priority); thread->Start(); return thread; #else // !defined(OS_ANDROID) @@ -54,9 +60,7 @@ thread_options.message_loop_type = ui::OzonePlatform::GetInstance()->GetMessageLoopTypeForGpu(); #endif -#if defined(OS_CHROMEOS) || defined(USE_OZONE) - thread_options.priority = base::ThreadPriority::DISPLAY; -#endif + thread_options.priority = thread_priority; CHECK(thread->StartWithOptions(thread_options)); return thread;
diff --git a/components/viz/service/main/viz_main_impl.cc b/components/viz/service/main/viz_main_impl.cc index 53292ae7..f04cad63 100644 --- a/components/viz/service/main/viz_main_impl.cc +++ b/components/viz/service/main/viz_main_impl.cc
@@ -8,6 +8,7 @@ #include <utility> #include "base/bind.h" +#include "base/feature_list.h" #include "base/message_loop/message_loop.h" #include "base/power_monitor/power_monitor_device_source.h" #include "base/single_thread_task_runner.h" @@ -15,6 +16,7 @@ #include "build/build_config.h" #include "components/viz/service/gl/gpu_service_impl.h" #include "gpu/command_buffer/common/activity_flags.h" +#include "gpu/config/gpu_finch_features.h" #include "gpu/ipc/gpu_in_process_thread_service.h" #include "gpu/ipc/service/gpu_init.h" #include "gpu/ipc/service/gpu_watchdog_thread.h" @@ -35,12 +37,10 @@ // TODO(sad): We do not need the IO thread once gpu has a separate process. // It should be possible to use |main_task_runner_| for doing IO tasks. base::Thread::Options thread_options(base::MessageLoop::TYPE_IO, 0); - thread_options.priority = base::ThreadPriority::NORMAL; -#if defined(OS_ANDROID) || defined(OS_CHROMEOS) || defined(USE_OZONE) // TODO(reveman): Remove this in favor of setting it explicitly for each // type of process. - thread_options.priority = base::ThreadPriority::DISPLAY; -#endif + if (base::FeatureList::IsEnabled(features::kGpuUseDisplayThreadPriority)) + thread_options.priority = base::ThreadPriority::DISPLAY; auto io_thread = std::make_unique<base::Thread>("GpuIOThread"); CHECK(io_thread->StartWithOptions(thread_options)); return io_thread;
diff --git a/content/app/BUILD.gn b/content/app/BUILD.gn index 0cd3c07..fe4403d7 100644 --- a/content/app/BUILD.gn +++ b/content/app/BUILD.gn
@@ -95,6 +95,8 @@ } source_set(main_target_name) { + check_includes = false + sources = [ "content_service_manager_main_delegate.cc", "content_service_manager_main_delegate.h", @@ -102,6 +104,14 @@ "mojo/mojo_init.h", ] + if (defined(invoker.include_browser_sources) && + invoker.include_browser_sources) { + sources += [ + "service_manager_environment.cc", + "service_manager_environment.h", + ] + } + configs += extra_configs deps = content_app_deps + [ ":$runner_target_name", @@ -162,6 +172,7 @@ "//content/renderer", "//content/utility", ] + include_browser_sources = true } # See comment at the top of //content/BUILD.gn for how this works. @@ -184,6 +195,7 @@ deps = [ ":content_app_browser_deps", ] + include_browser_sources = true } implement_content_app("child") {
diff --git a/content/app/content_main_runner_impl.cc b/content/app/content_main_runner_impl.cc index 2260e347..2d853dec 100644 --- a/content/app/content_main_runner_impl.cc +++ b/content/app/content_main_runner_impl.cc
@@ -43,10 +43,12 @@ #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" +#include "base/task/post_task.h" #include "base/trace_event/trace_event.h" #include "components/discardable_memory/service/discardable_shared_memory_manager.h" #include "components/download/public/common/download_task_runner.h" #include "content/app/mojo/mojo_init.h" +#include "content/app/service_manager_environment.h" #include "content/browser/browser_process_sub_thread.h" #include "content/browser/browser_thread_impl.h" #include "content/browser/scheduler/browser_task_executor.h" @@ -881,7 +883,7 @@ return -1; bool should_start_service_manager_only = start_service_manager_only; - if (!service_manager_context_) { + if (!service_manager_environment_) { if (delegate_->ShouldCreateFeatureList()) { DCHECK(!field_trial_list_); field_trial_list_ = SetUpFieldTrialsAndFeatureList(); @@ -960,12 +962,10 @@ power_monitor_ = std::make_unique<base::PowerMonitor>( std::make_unique<base::PowerMonitorDeviceSource>()); - // The thread used to start the ServiceManager is handed-off to - // BrowserMain() which may elect to promote it (e.g. to BrowserThread::IO). - service_manager_thread_ = BrowserTaskExecutor::CreateIOThread(); - service_manager_context_.reset( - new ServiceManagerContext(service_manager_thread_->task_runner())); - download::SetIOTaskRunner(service_manager_thread_->task_runner()); + service_manager_environment_ = std::make_unique<ServiceManagerEnvironment>( + BrowserTaskExecutor::CreateIOThread()); + download::SetIOTaskRunner( + service_manager_environment_->ipc_thread()->task_runner()); #if defined(OS_ANDROID) if (start_service_manager_only) { base::ThreadTaskRunnerHandle::Get()->PostTask( @@ -981,9 +981,7 @@ DVLOG(0) << "Chrome is running in full browser mode."; is_browser_main_loop_started_ = true; - startup_data_ = std::make_unique<StartupDataImpl>(); - startup_data_->thread = std::move(service_manager_thread_); - startup_data_->service_manager_context = service_manager_context_.get(); + startup_data_ = service_manager_environment_->CreateBrowserStartupData(); startup_data_->power_monitor = std::move(power_monitor_); main_params.startup_data = startup_data_.get(); return RunBrowserProcessMain(main_params, delegate_); @@ -994,6 +992,10 @@ DCHECK(is_initialized_); DCHECK(!is_shutdown_); +#if !defined(CHROME_MULTIPLE_DLL_CHILD) + service_manager_environment_.reset(); +#endif + if (completed_basic_startup_) { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); @@ -1004,6 +1006,7 @@ } #if !defined(CHROME_MULTIPLE_DLL_CHILD) + service_manager_environment_.reset(); // The BrowserTaskExecutor needs to be destroyed before |exit_manager_|. BrowserTaskExecutor::Shutdown(); #endif // !defined(CHROME_MULTIPLE_DLL_CHILD)
diff --git a/content/app/content_main_runner_impl.h b/content/app/content_main_runner_impl.h index fc15ac8..513ff1f 100644 --- a/content/app/content_main_runner_impl.h +++ b/content/app/content_main_runner_impl.h
@@ -12,12 +12,12 @@ #include "base/metrics/field_trial.h" #include "base/power_monitor/power_monitor.h" #include "build/build_config.h" -#include "content/browser/service_manager/service_manager_context.h" #include "content/browser/startup_data_impl.h" #include "content/public/app/content_main.h" #include "content/public/app/content_main_runner.h" #include "content/public/common/content_client.h" #include "content/public/common/main_function_params.h" +#include "mojo/core/embedder/scoped_ipc_support.h" #if defined(OS_WIN) #include "sandbox/win/src/sandbox_types.h" @@ -36,6 +36,7 @@ namespace content { class ContentMainDelegate; struct ContentMainParams; +class ServiceManagerEnvironment; class ContentMainRunnerImpl : public ContentMainRunner { public: @@ -62,9 +63,8 @@ discardable_shared_memory_manager_; std::unique_ptr<StartupDataImpl> startup_data_; std::unique_ptr<base::FieldTrialList> field_trial_list_; - std::unique_ptr<BrowserProcessSubThread> service_manager_thread_; - std::unique_ptr<ServiceManagerContext> service_manager_context_; std::unique_ptr<base::PowerMonitor> power_monitor_; + std::unique_ptr<ServiceManagerEnvironment> service_manager_environment_; #endif // !defined(CHROME_MULTIPLE_DLL_CHILD) // True if the runner has been initialized.
diff --git a/content/app/service_manager_environment.cc b/content/app/service_manager_environment.cc new file mode 100644 index 0000000..4ca8c85 --- /dev/null +++ b/content/app/service_manager_environment.cc
@@ -0,0 +1,57 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/app/service_manager_environment.h" + +#include <utility> + +#include "build/build_config.h" +#include "content/browser/browser_process_sub_thread.h" +#include "content/browser/service_manager/common_browser_interfaces.h" +#include "content/browser/service_manager/service_manager_context.h" +#include "content/browser/startup_data_impl.h" +#include "content/browser/system_connector_impl.h" +#include "content/public/common/service_manager_connection.h" +#include "mojo/core/embedder/embedder.h" +#include "mojo/core/embedder/scoped_ipc_support.h" + +#if defined(OS_MACOSX) +#include "content/browser/mach_broker_mac.h" +#endif + +namespace content { + +ServiceManagerEnvironment::ServiceManagerEnvironment( + std::unique_ptr<BrowserProcessSubThread> ipc_thread) + : ipc_thread_(std::move(ipc_thread)), + mojo_ipc_support_(std::make_unique<mojo::core::ScopedIPCSupport>( + ipc_thread_->task_runner(), + mojo::core::ScopedIPCSupport::ShutdownPolicy::FAST)), + service_manager_context_( + std::make_unique<ServiceManagerContext>(ipc_thread_->task_runner())) { +#if defined(OS_MACOSX) + mojo::core::SetMachPortProvider(MachBroker::GetInstance()); +#endif // defined(OS_MACOSX) + + auto* system_connection = ServiceManagerConnection::GetForProcess(); + RegisterCommonBrowserInterfaces(system_connection); + system_connection->Start(); + + SetSystemConnector(system_connection->GetConnector()->Clone()); +} + +ServiceManagerEnvironment::~ServiceManagerEnvironment() = default; + +std::unique_ptr<StartupDataImpl> +ServiceManagerEnvironment::CreateBrowserStartupData() { + auto startup_data = std::make_unique<StartupDataImpl>(); + startup_data->ipc_thread = std::move(ipc_thread_); + startup_data->mojo_ipc_support = std::move(mojo_ipc_support_); + startup_data->service_manager_shutdown_closure = + base::BindOnce(&ServiceManagerContext::ShutDown, + base::Unretained(service_manager_context_.get())); + return startup_data; +} + +} // namespace content
diff --git a/content/app/service_manager_environment.h b/content/app/service_manager_environment.h new file mode 100644 index 0000000..50ccf9abb --- /dev/null +++ b/content/app/service_manager_environment.h
@@ -0,0 +1,54 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_APP_SERVICE_MANAGER_ENVIRONMENT_H_ +#define CONTENT_APP_SERVICE_MANAGER_ENVIRONMENT_H_ + +#include <memory> + +#include "base/macros.h" +#include "content/common/content_export.h" + +namespace mojo { +namespace core { +class ScopedIPCSupport; +} +} // namespace mojo + +namespace content { + +class BrowserProcessSubThread; +class ServiceManagerContext; +struct StartupDataImpl; + +// Encapsulates the basic state necessary to bring up a working Service Manager +// instance in the process. +class CONTENT_EXPORT ServiceManagerEnvironment { + public: + explicit ServiceManagerEnvironment( + std::unique_ptr<BrowserProcessSubThread> ipc_thread); + ~ServiceManagerEnvironment(); + + BrowserProcessSubThread* ipc_thread() { return ipc_thread_.get(); } + + // Returns a new StartupDataImpl which captures and/or reflects the partial + // state of this ServiceManagerEnvironment. This must be called and the + // result passed to BrowserMain if the browser is going to be started within + // Service Manager's process. + // + // After this call, the ServiceManagerEnvironment no longer owns the IPC + // thread and |ipc_thread()| returns null. + std::unique_ptr<StartupDataImpl> CreateBrowserStartupData(); + + private: + std::unique_ptr<BrowserProcessSubThread> ipc_thread_; + std::unique_ptr<mojo::core::ScopedIPCSupport> mojo_ipc_support_; + std::unique_ptr<ServiceManagerContext> service_manager_context_; + + DISALLOW_COPY_AND_ASSIGN(ServiceManagerEnvironment); +}; + +} // namespace content + +#endif // CONTENT_APP_SERVICE_MANAGER_ENVIRONMENT_H_
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index ba3a4da..5f594e65 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -1851,6 +1851,8 @@ "storage_partition_impl.h", "storage_partition_impl_map.cc", "storage_partition_impl_map.h", + "system_connector_impl.cc", + "system_connector_impl.h", "theme_helper_mac.h", "theme_helper_mac.mm", "tracing/background_memory_tracing_observer.cc",
diff --git a/content/browser/accessibility/accessibility_ipc_error_browsertest.cc b/content/browser/accessibility/accessibility_ipc_error_browsertest.cc index 719abd7e..e0ca338 100644 --- a/content/browser/accessibility/accessibility_ipc_error_browsertest.cc +++ b/content/browser/accessibility/accessibility_ipc_error_browsertest.cc
@@ -39,8 +39,9 @@ DISALLOW_COPY_AND_ASSIGN(AccessibilityIpcErrorBrowserTest); }; +// Flaky on all platforms. http://crbug.com/973946 IN_PROC_BROWSER_TEST_F(AccessibilityIpcErrorBrowserTest, - ResetBrowserAccessibilityManager) { + DISABLE_ResetBrowserAccessibilityManager) { // Create a data url and load it. const char url_str[] = "data:text/html,"
diff --git a/content/browser/browser_main_loop.cc b/content/browser/browser_main_loop.cc index 9d1f07cbe..ee81c2c3 100644 --- a/content/browser/browser_main_loop.cc +++ b/content/browser/browser_main_loop.cc
@@ -88,7 +88,6 @@ #include "content/browser/scheduler/responsiveness/watcher.h" #include "content/browser/screenlock_monitor/screenlock_monitor.h" #include "content/browser/screenlock_monitor/screenlock_monitor_device_source.h" -#include "content/browser/service_manager/service_manager_context.h" #include "content/browser/speech/speech_recognition_manager_impl.h" #include "content/browser/startup_data_impl.h" #include "content/browser/startup_task_runner.h" @@ -109,6 +108,7 @@ #include "content/public/browser/render_process_host.h" #include "content/public/browser/site_isolation_policy.h" #include "content/public/browser/swap_metrics_driver.h" +#include "content/public/browser/system_connector.h" #include "content/public/common/content_client.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" @@ -135,6 +135,7 @@ #include "ppapi/buildflags/buildflags.h" #include "services/audio/public/cpp/audio_system_factory.h" #include "services/audio/public/mojom/constants.mojom.h" +#include "services/audio/service.h" #include "services/content/public/cpp/navigable_contents_view.h" #include "services/network/transitional_url_loader_factory_owner.h" #include "services/resource_coordinator/public/cpp/memory_instrumentation/client_process_impl.h" @@ -176,7 +177,6 @@ #if defined(OS_MACOSX) #include "base/memory/memory_pressure_monitor_mac.h" -#include "content/browser/mach_broker_mac.h" #include "content/browser/renderer_host/browser_compositor_view_mac.h" #include "content/browser/theme_helper_mac.h" #include "ui/accelerated_widget_mac/window_resize_helper_mac.h" @@ -564,8 +564,10 @@ static_cast<StartupDataImpl*>(parameters_.startup_data); // This is always invoked before |io_thread_| is initialized (i.e. never // resets it). - io_thread_ = std::move(startup_data->thread); - service_manager_context_ = startup_data->service_manager_context; + io_thread_ = std::move(startup_data->ipc_thread); + mojo_ipc_support_ = std::move(startup_data->mojo_ipc_support); + service_manager_shutdown_closure_ = + std::move(startup_data->service_manager_shutdown_closure); power_monitor_ = std::move(startup_data->power_monitor); } @@ -974,6 +976,10 @@ } int BrowserMainLoop::PostCreateThreads() { + tracing_controller_ = std::make_unique<content::TracingControllerImpl>(); + content::BackgroundTracingManagerImpl::GetInstance() + ->AddMetadataGeneratorFunction(); + if (parts_) { TRACE_EVENT0("startup", "BrowserMainLoop::PostCreateThreads"); parts_->PostCreateThreads(); @@ -1111,9 +1117,8 @@ BrowserGpuChannelHostFactory::instance()->CloseChannel(); // Shutdown the Service Manager and IPC. - if (service_manager_context_) - service_manager_context_->ShutDown(); - owned_service_manager_context_.reset(); + if (service_manager_shutdown_closure_) + std::move(service_manager_shutdown_closure_).Run(); mojo_ipc_support_.reset(); if (save_file_manager_) @@ -1318,9 +1323,7 @@ { TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:GamepadService"); device::GamepadService::GetInstance()->StartUp( - content::ServiceManagerConnection::GetForProcess() - ->GetConnector() - ->Clone()); + GetSystemConnector()->Clone()); } #if defined(OS_WIN) @@ -1448,8 +1451,7 @@ now_playing::RemoteCommandCenterDelegate::Create(); #endif media_keys_listener_manager_ = - std::make_unique<MediaKeysListenerManagerImpl>( - content::ServiceManagerConnection::GetForProcess()->GetConnector()); + std::make_unique<MediaKeysListenerManagerImpl>(GetSystemConnector()); } #if defined(OS_MACOSX) @@ -1553,20 +1555,6 @@ mojo::SyncCallRestrictions::DisallowSyncCall(); } - mojo_ipc_support_.reset(new mojo::core::ScopedIPCSupport( - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}), - mojo::core::ScopedIPCSupport::ShutdownPolicy::FAST)); - - if (!service_manager_context_) { - owned_service_manager_context_ = - std::make_unique<ServiceManagerContext>(io_thread_->task_runner()); - service_manager_context_ = owned_service_manager_context_.get(); - } - ServiceManagerContext::StartBrowserConnection(); - -#if defined(OS_MACOSX) - mojo::core::SetMachPortProvider(MachBroker::GetInstance()); -#endif // defined(OS_MACOSX) GetContentClient()->OnServiceManagerConnected( ServiceManagerConnection::GetForProcess()); @@ -1574,16 +1562,10 @@ // know they're running in the same process as the service. content::NavigableContentsView::SetClientRunningInServiceProcess(); - tracing_controller_ = std::make_unique<content::TracingControllerImpl>(); - content::BackgroundTracingManagerImpl::GetInstance() - ->AddMetadataGeneratorFunction(); - // Registers the browser process as a memory-instrumentation client, so // that data for the browser process will be available in memory dumps. - service_manager::Connector* connector = - content::ServiceManagerConnection::GetForProcess()->GetConnector(); memory_instrumentation::ClientProcessImpl::Config config( - connector, resource_coordinator::mojom::kServiceName, + GetSystemConnector(), resource_coordinator::mojom::kServiceName, memory_instrumentation::mojom::ProcessType::BROWSER); memory_instrumentation::ClientProcessImpl::CreateInstance(config); @@ -1594,11 +1576,6 @@ // MessagePumpForUI::ScheduleWork() before MessagePumpForUI::Start(). TracingControllerImpl::GetInstance()->StartStartupTracingIfNeeded(); - if (parts_) { - parts_->ServiceManagerConnectionStarted( - ServiceManagerConnection::GetForProcess()); - } - #if BUILDFLAG(MOJO_RANDOM_DELAYS_ENABLED) mojo::BeginRandomMojoDelays(); #endif @@ -1632,7 +1609,7 @@ TRACE_EVENT_INSTANT0("startup", "Starting Audio service task runner", TRACE_EVENT_SCOPE_THREAD); - ServiceManagerContext::GetAudioServiceRunner()->StartWithTaskRunner( + audio::Service::GetInProcessTaskRunner()->StartWithTaskRunner( audio_manager_->GetTaskRunner()); } @@ -1643,22 +1620,17 @@ {content::BrowserThread::UI, base::TaskPriority::BEST_EFFORT}, base::BindOnce([]() { TRACE_EVENT0("audio", "Starting audio service"); - ServiceManagerConnection* connection = - content::ServiceManagerConnection::GetForProcess(); - if (connection) { + auto* connector = GetSystemConnector(); + if (connector) { // The browser is not shutting down: |connection| would be null // otherwise. - connection->GetConnector()->WarmService( - service_manager::ServiceFilter::ByName( - audio::mojom::kServiceName)); + connector->WarmService(service_manager::ServiceFilter::ByName( + audio::mojom::kServiceName)); } })); } - audio_system_ = audio::CreateAudioSystem( - content::ServiceManagerConnection::GetForProcess() - ->GetConnector() - ->Clone()); + audio_system_ = audio::CreateAudioSystem(GetSystemConnector()->Clone()); CHECK(audio_system_); }
diff --git a/content/browser/browser_main_loop.h b/content/browser/browser_main_loop.h index ec14cf8..059445c 100644 --- a/content/browser/browser_main_loop.h +++ b/content/browser/browser_main_loop.h
@@ -94,7 +94,6 @@ class ResourceDispatcherHostImpl; class SaveFileManager; class ScreenlockMonitor; -class ServiceManagerContext; class SpeechRecognitionManagerImpl; class StartupTaskRunner; class SwapMetricsDriver; @@ -348,8 +347,12 @@ gpu_data_manager_visual_proxy_; #endif - ServiceManagerContext* service_manager_context_ = nullptr; - std::unique_ptr<ServiceManagerContext> owned_service_manager_context_; + // If provided to the BrowserMainLoop (see StartupDataImpl), this closure + // is run during shutdown, prior to IO thread destruction, and should do + // whatever work is necessary to tear down the ServiceManager if one is + // running. Must be provided if a ServiceManager is initialized and running on + // the IO thread. + base::OnceClosure service_manager_shutdown_closure_; // Members initialized in |BrowserThreadsStarted()| -------------------------- std::unique_ptr<mojo::core::ScopedIPCSupport> mojo_ipc_support_;
diff --git a/content/browser/browser_main_loop_unittest.cc b/content/browser/browser_main_loop_unittest.cc index 4c9e0734..f3ed33e 100644 --- a/content/browser/browser_main_loop_unittest.cc +++ b/content/browser/browser_main_loop_unittest.cc
@@ -13,7 +13,6 @@ #include "base/test/scoped_command_line.h" #include "content/browser/browser_thread_impl.h" #include "content/browser/scheduler/browser_task_executor.h" -#include "content/browser/service_manager/service_manager_context.h" #include "content/browser/startup_data_impl.h" #include "content/browser/startup_helper.h" #include "content/public/browser/browser_thread.h" @@ -59,34 +58,31 @@ // Verify that a single-process browser process has at least as many threads as // the number of cores in its foreground pool. TEST_F(BrowserMainLoopTest, CreateThreadsInSingleProcess) { - { - MainFunctionParams main_function_params(GetProcessCommandLine()); + MainFunctionParams main_function_params(GetProcessCommandLine()); - BrowserMainLoop browser_main_loop( - main_function_params, - std::make_unique<base::ThreadPoolInstance::ScopedExecutionFence>()); - browser_main_loop.MainMessageLoopStart(); - browser_main_loop.Init(); - browser_main_loop.CreateThreads(); - EXPECT_GE(base::ThreadPoolInstance::Get() - ->GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( - {base::TaskPriority::USER_VISIBLE}), - base::SysInfo::NumberOfProcessors() - 1); - browser_main_loop.ShutdownThreadsAndCleanUp(); - } + StartupDataImpl startup_data; + startup_data.ipc_thread = BrowserTaskExecutor::CreateIOThread(); + main_function_params.startup_data = &startup_data; + + BrowserMainLoop browser_main_loop( + main_function_params, + std::make_unique<base::ThreadPoolInstance::ScopedExecutionFence>()); + browser_main_loop.MainMessageLoopStart(); + browser_main_loop.Init(); + browser_main_loop.CreateThreads(); + EXPECT_GE(base::ThreadPoolInstance::Get() + ->GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated( + {base::TaskPriority::USER_VISIBLE}), + base::SysInfo::NumberOfProcessors() - 1); + browser_main_loop.ShutdownThreadsAndCleanUp(); } TEST_F(BrowserMainLoopTest, PostTaskToIOThreadBeforeThreadCreationDoesNotRunTask) { MainFunctionParams main_function_params(GetProcessCommandLine()); - auto service_manager_thread = BrowserTaskExecutor::CreateIOThread(); - ServiceManagerContext service_manager_context( - service_manager_thread->task_runner()); - StartupDataImpl startup_data; - startup_data.thread = std::move(service_manager_thread); - startup_data.service_manager_context = &service_manager_context; + startup_data.ipc_thread = BrowserTaskExecutor::CreateIOThread(); main_function_params.startup_data = &startup_data; BrowserMainLoop browser_main_loop(
diff --git a/content/browser/cache_storage/legacy/legacy_cache_storage.cc b/content/browser/cache_storage/legacy/legacy_cache_storage.cc index 5bdb477..b085b463 100644 --- a/content/browser/cache_storage/legacy/legacy_cache_storage.cc +++ b/content/browser/cache_storage/legacy/legacy_cache_storage.cc
@@ -23,11 +23,10 @@ #include "base/metrics/histogram_macros.h" #include "base/numerics/safe_conversions.h" #include "base/sequenced_task_runner.h" -#include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" -#include "base/threading/thread_task_runner_handle.h" +#include "base/threading/sequenced_task_runner_handle.h" #include "base/trace_event/trace_event.h" #include "base/trace_event/traced_value.h" #include "content/browser/cache_storage/cache_storage.pb.h" @@ -40,7 +39,6 @@ #include "content/browser/cache_storage/cache_storage_trace_utils.h" #include "content/browser/cache_storage/legacy/legacy_cache_storage_manager.h" #include "content/common/background_fetch/background_fetch_types.h" -#include "content/public/browser/browser_thread.h" #include "crypto/symmetric_key.h" #include "net/base/directory_lister.h" #include "net/base/net_errors.h" @@ -66,7 +64,7 @@ void SizeRetrievedFromAllCaches(std::unique_ptr<int64_t> accumulator, LegacyCacheStorage::SizeCallback callback) { - base::ThreadTaskRunnerHandle::Get()->PostTask( + base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(callback), *accumulator)); } @@ -795,7 +793,7 @@ index_write_task_.Reset(base::BindOnce(&LegacyCacheStorage::WriteIndex, weak_factory_.GetWeakPtr(), base::DoNothing::Once<bool>())); - base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( + base::SequencedTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, index_write_task_.callback(), base::TimeDelta::FromSeconds(kWriteIndexDelaySecs)); } @@ -1032,7 +1030,7 @@ "cache_name", cache_name); CacheStorageCacheHandle cache_handle = GetLoadedCache(cache_name); if (!cache_handle.value()) { - base::ThreadTaskRunnerHandle::Get()->PostTask( + base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(callback), CacheStorageError::kErrorNotFound)); return; @@ -1336,7 +1334,7 @@ DCHECK(initialized_); if (cache_index_->GetPaddedStorageSize() != kSizeUnknown) { - base::ThreadTaskRunnerHandle::Get()->PostTask( + base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(callback), cache_index_->GetPaddedStorageSize())); return;
diff --git a/content/browser/frame_host/frame_navigation_entry.cc b/content/browser/frame_host/frame_navigation_entry.cc index d50e29d1..f089469d 100644 --- a/content/browser/frame_host/frame_navigation_entry.cc +++ b/content/browser/frame_host/frame_navigation_entry.cc
@@ -48,8 +48,8 @@ FrameNavigationEntry::~FrameNavigationEntry() { } -FrameNavigationEntry* FrameNavigationEntry::Clone() const { - FrameNavigationEntry* copy = new FrameNavigationEntry(); +scoped_refptr<FrameNavigationEntry> FrameNavigationEntry::Clone() const { + auto copy = base::MakeRefCounted<FrameNavigationEntry>(); // Omit any fields cleared at commit time. copy->UpdateEntry(frame_unique_name_, item_sequence_number_,
diff --git a/content/browser/frame_host/frame_navigation_entry.h b/content/browser/frame_host/frame_navigation_entry.h index a65c6b2..a272854b 100644 --- a/content/browser/frame_host/frame_navigation_entry.h +++ b/content/browser/frame_host/frame_navigation_entry.h
@@ -49,7 +49,7 @@ // Creates a copy of this FrameNavigationEntry that can be modified // independently from the original. - FrameNavigationEntry* Clone() const; + scoped_refptr<FrameNavigationEntry> Clone() const; // Updates all the members of this entry. void UpdateEntry(
diff --git a/content/browser/frame_host/navigation_controller_impl.cc b/content/browser/frame_host/navigation_controller_impl.cc index 031b30e..abbe6a24 100644 --- a/content/browser/frame_host/navigation_controller_impl.cc +++ b/content/browser/frame_host/navigation_controller_impl.cc
@@ -1357,7 +1357,7 @@ // entry instead of looking at the pending entry, because the pending entry // does not have any subframe history items. if (is_same_document && GetLastCommittedEntry()) { - FrameNavigationEntry* frame_entry = new FrameNavigationEntry( + auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>( rfh->frame_tree_node()->unique_name(), params.item_sequence_number, params.document_sequence_number, rfh->GetSiteInstance(), nullptr, params.url, (params.url_is_unreachable) ? nullptr : ¶ms.origin, @@ -1381,9 +1381,11 @@ } } - // We expect |frame_entry| to be owned by |new_entry|. This should never - // fail, because it's the main frame. - CHECK(frame_entry->HasOneRef()); + // It is expected that |frame_entry| is now owned by |new_entry|. This means + // that |frame_entry| should now have a reference count of exactly 2: one + // due to the local variable |frame_entry|, and another due to |new_entry| + // also retaining one. This should never fail, because it's the main frame. + CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef()); update_virtual_url = new_entry->update_virtual_url_with_url(); @@ -1767,17 +1769,18 @@ // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()). DCHECK(!replace_entry); - // Make sure we don't leak frame_entry if new_entry doesn't take ownership. - scoped_refptr<FrameNavigationEntry> frame_entry(new FrameNavigationEntry( + // This FrameNavigationEntry might not end up being used in the + // CloneAndReplace() call below, if a spot can't be found for it in the tree. + auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>( rfh->frame_tree_node()->unique_name(), params.item_sequence_number, params.document_sequence_number, rfh->GetSiteInstance(), nullptr, params.url, (params.url_is_unreachable) ? nullptr : ¶ms.origin, params.referrer, params.redirects, params.page_state, params.method, - params.post_id, nullptr /* blob_url_loader_factory */)); + params.post_id, nullptr /* blob_url_loader_factory */); std::unique_ptr<NavigationEntryImpl> new_entry = GetLastCommittedEntry()->CloneAndReplace( - frame_entry.get(), is_same_document, rfh->frame_tree_node(), + std::move(frame_entry), is_same_document, rfh->frame_tree_node(), delegate_->GetFrameTree()->root()); SetShouldSkipOnBackForwardUIIfNeeded(rfh, replace_entry, @@ -1785,9 +1788,9 @@ handle->IsRendererInitiated()); // TODO(creis): Update this to add the frame_entry if we can't find the one - // to replace, which can happen due to a unique name change. See - // https://crbug.com/607205. For now, frame_entry will be deleted when it - // goes out of scope if it doesn't get used. + // to replace, which can happen due to a unique name change. See + // https://crbug.com/607205. For now, the call to CloneAndReplace() will + // delete the |frame_entry| when the function exits if it doesn't get used. InsertOrReplaceEntry(std::move(new_entry), replace_entry); } @@ -2274,7 +2277,7 @@ // further in https://crbug.com/536906. scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node)); if (!frame_entry) { - frame_entry = new FrameNavigationEntry( + frame_entry = base::MakeRefCounted<FrameNavigationEntry>( node->unique_name(), -1, -1, nullptr, static_cast<SiteInstanceImpl*>(source_site_instance), url, nullptr /* origin */, referrer, std::vector<GURL>(), PageState(),
diff --git a/content/browser/frame_host/navigation_entry_impl.cc b/content/browser/frame_host/navigation_entry_impl.cc index 306384c..e226a60 100644 --- a/content/browser/frame_host/navigation_entry_impl.cc +++ b/content/browser/frame_host/navigation_entry_impl.cc
@@ -65,7 +65,7 @@ EncodePageState(page_state, &data); DCHECK(!data.empty()) << "Shouldn't generate an empty PageState."; - node->frame_entry = new FrameNavigationEntry( + node->frame_entry = base::MakeRefCounted<FrameNavigationEntry>( UTF16ToUTF8(state.target.value_or(base::string16())), state.item_sequence_number, state.document_sequence_number, nullptr, nullptr, GURL(state.url_string.value_or(base::string16())), @@ -145,9 +145,10 @@ } // namespace -NavigationEntryImpl::TreeNode::TreeNode(TreeNode* parent, - FrameNavigationEntry* frame_entry) - : parent(parent), frame_entry(frame_entry) {} +NavigationEntryImpl::TreeNode::TreeNode( + TreeNode* parent, + scoped_refptr<FrameNavigationEntry> frame_entry) + : parent(parent), frame_entry(std::move(frame_entry)) {} NavigationEntryImpl::TreeNode::~TreeNode() { } @@ -165,7 +166,7 @@ std::unique_ptr<NavigationEntryImpl::TreeNode> NavigationEntryImpl::TreeNode::CloneAndReplace( - FrameNavigationEntry* frame_navigation_entry, + scoped_refptr<FrameNavigationEntry> frame_navigation_entry, bool clone_children_of_target, FrameTreeNode* target_frame_tree_node, FrameTreeNode* current_frame_tree_node, @@ -258,9 +259,9 @@ ui::PageTransition transition_type, bool is_renderer_initiated, scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) - : frame_tree_(new TreeNode( - nullptr, - new FrameNavigationEntry("", + : frame_tree_(new TreeNode(nullptr, + base::MakeRefCounted<FrameNavigationEntry>( + "", -1, -1, std::move(instance), @@ -609,7 +610,7 @@ } std::unique_ptr<NavigationEntryImpl> NavigationEntryImpl::CloneAndReplace( - FrameNavigationEntry* frame_navigation_entry, + scoped_refptr<FrameNavigationEntry> frame_navigation_entry, bool clone_children_of_target, FrameTreeNode* target_frame_tree_node, FrameTreeNode* root_frame_tree_node) const { @@ -619,8 +620,8 @@ // TODO(creis): Only share the same FrameNavigationEntries if cloning within // the same tab. copy->frame_tree_ = frame_tree_->CloneAndReplace( - frame_navigation_entry, clone_children_of_target, target_frame_tree_node, - root_frame_tree_node, nullptr); + std::move(frame_navigation_entry), clone_children_of_target, + target_frame_tree_node, root_frame_tree_node, nullptr); // Copy most state over, unless cleared in ResetForCommit. // Don't copy unique_id_, otherwise it won't be unique. @@ -828,14 +829,14 @@ // No entry exists yet, so create a new one. // Unordered list, since we expect to look up entries by frame sequence number // or unique name. - FrameNavigationEntry* frame_entry = new FrameNavigationEntry( + auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>( unique_name, item_sequence_number, document_sequence_number, site_instance, std::move(source_site_instance), url, base::OptionalOrNullptr(origin), referrer, redirect_chain, page_state, method, post_id, std::move(blob_url_loader_factory)); parent_node->children.push_back( std::make_unique<NavigationEntryImpl::TreeNode>(parent_node, - frame_entry)); + std::move(frame_entry))); } FrameNavigationEntry* NavigationEntryImpl::GetFrameEntry(
diff --git a/content/browser/frame_host/navigation_entry_impl.h b/content/browser/frame_host/navigation_entry_impl.h index 4323013c..960656e3 100644 --- a/content/browser/frame_host/navigation_entry_impl.h +++ b/content/browser/frame_host/navigation_entry_impl.h
@@ -42,7 +42,7 @@ // history item. The tree currently only tracks the main frame by default, // and is populated with subframe nodes in --site-per-process mode. struct TreeNode { - TreeNode(TreeNode* parent, FrameNavigationEntry* frame_entry); + TreeNode(TreeNode* parent, scoped_refptr<FrameNavigationEntry> frame_entry); ~TreeNode(); // Returns whether this TreeNode corresponds to |frame_tree_node|. If this @@ -59,7 +59,7 @@ // TODO(creis): For --site-per-process, share FrameNavigationEntries between // NavigationEntries of the same tab. std::unique_ptr<TreeNode> CloneAndReplace( - FrameNavigationEntry* frame_navigation_entry, + scoped_refptr<FrameNavigationEntry> frame_navigation_entry, bool clone_children_of_target, FrameTreeNode* target_frame_tree_node, FrameTreeNode* current_frame_tree_node, @@ -168,7 +168,7 @@ // that shares the existing FrameNavigationEntries (for use within the same // tab) and one that draws them from a different pool (for use in a new tab). std::unique_ptr<NavigationEntryImpl> CloneAndReplace( - FrameNavigationEntry* frame_entry, + scoped_refptr<FrameNavigationEntry> frame_entry, bool clone_children_of_target, FrameTreeNode* target_frame_tree_node, FrameTreeNode* root_frame_tree_node) const;
diff --git a/content/browser/frame_host/navigation_handle_impl_unittest.cc b/content/browser/frame_host/navigation_handle_impl_unittest.cc index 1a5ba30..ef6f9a0 100644 --- a/content/browser/frame_host/navigation_handle_impl_unittest.cc +++ b/content/browser/frame_host/navigation_handle_impl_unittest.cc
@@ -222,7 +222,7 @@ // TODO(zetamoo): Use NavigationSimulator instead of creating // NavigationRequest and NavigationHandleImpl. void CreateNavigationHandle() { - scoped_refptr<FrameNavigationEntry> frame_entry(new FrameNavigationEntry()); + auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(); request_ = NavigationRequest::CreateBrowserInitiated( main_test_rfh()->frame_tree_node(), CommonNavigationParams(), CommitNavigationParams(), false /* browser-initiated */, std::string(),
diff --git a/content/browser/gpu/gpu_process_host.cc b/content/browser/gpu/gpu_process_host.cc index 9707571..136a5b9 100644 --- a/content/browser/gpu/gpu_process_host.cc +++ b/content/browser/gpu/gpu_process_host.cc
@@ -841,9 +841,8 @@ // WGL needs to create its own window and pump messages on it. options.message_loop_type = base::MessageLoop::TYPE_UI; #endif -#if defined(OS_ANDROID) || defined(OS_CHROMEOS) || defined(USE_OZONE) - options.priority = base::ThreadPriority::DISPLAY; -#endif + if (base::FeatureList::IsEnabled(features::kGpuUseDisplayThreadPriority)) + options.priority = base::ThreadPriority::DISPLAY; in_process_gpu_thread_->StartWithOptions(options); OnProcessLaunched(); // Fake a callback that the process is ready.
diff --git a/content/browser/media/cdm_file_impl.cc b/content/browser/media/cdm_file_impl.cc index 242e248..ab55ff4 100644 --- a/content/browser/media/cdm_file_impl.cc +++ b/content/browser/media/cdm_file_impl.cc
@@ -10,6 +10,7 @@ #include "base/bind.h" #include "base/callback.h" #include "base/logging.h" +#include "base/metrics/histogram_macros.h" #include "base/strings/string_util.h" #include "base/task/post_task.h" #include "storage/browser/fileapi/file_system_context.h" @@ -24,10 +25,17 @@ // The CDM interface has a restriction that file names can not begin with _, // so use it to prefix temporary files. -const char kTemporaryFilePrefix[] = "_"; +const char kTemporaryFilePrefix = '_'; + +// File size limit is 512KB. Licenses saved by the CDM are typically several +// hundreds of bytes. +const int64_t kMaxFileSizeBytes = 512 * 1024; + +// Maximum length of a file name. +const size_t kFileNameMaxLength = 256; std::string GetTempFileName(const std::string& file_name) { - DCHECK(!base::StartsWith(file_name, kTemporaryFilePrefix, + DCHECK(!base::StartsWith(file_name, std::string(1, kTemporaryFilePrefix), base::CompareCase::SENSITIVE)); return kTemporaryFilePrefix + file_name; } @@ -72,18 +80,7 @@ return file_lock_map_.insert(key).second; } - // Tests whether a lock is held on |key| or not. Returns true if |key| - // is currently locked, false otherwise. - bool IsFileLockHeld(const FileLockKey& key) { - DVLOG(3) << __func__ << " file: " << key.file_name; - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - // Lock is held if there is an entry for |key|. - return file_lock_map_.count(key) > 0; - } - - // Release the lock held on the file represented by |key|. If - // |on_close_callback| has been set, run it before releasing the lock. + // Release the lock held on the file represented by |key|. void ReleaseFileLock(const FileLockKey& key) { DVLOG(3) << __func__ << " file: " << key.file_name; DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); @@ -112,8 +109,101 @@ return file_lock_map; } +// Read the contents of |file| and return it. On success, returns kSuccess and +// |data| is updated with the contents of the file. On failure kFailure is +// returned. This method owns |file| and it will be closed at the end. +CdmFileImpl::Status ReadFile(base::File file, std::vector<uint8_t>* data) { + DCHECK(data->empty()); + + // Determine the size of the file (so we know how many bytes to read). + // Negative bytes mean failure, so problem with the file. + int64_t num_bytes = file.GetLength(); + if (num_bytes < 0) { + DLOG(WARNING) << __func__ + << " Unable to get file length. result = " << num_bytes; + return CdmFileImpl::Status::kFailure; + } + + // Files are limited in size, so fail if file too big. + if (num_bytes > kMaxFileSizeBytes) { + DLOG(WARNING) << __func__ + << " Too much data to read. #bytes = " << num_bytes; + return CdmFileImpl::Status::kFailure; + } + + // If the file has 0 bytes, no need to read anything. + if (num_bytes == 0) { + return CdmFileImpl::Status::kSuccess; + } + + // Read the contents of the file. Read() sizes (provided and returned) are + // type int, so cast appropriately. + int bytes_to_read = base::checked_cast<int>(num_bytes); + data->resize(num_bytes); + + TRACE_EVENT0("media", "CdmFileReadFile"); + base::TimeTicks start = base::TimeTicks::Now(); + int bytes_read = + file.Read(0, reinterpret_cast<char*>(data->data()), bytes_to_read); + base::TimeDelta read_time = base::TimeTicks::Now() - start; + if (bytes_to_read != bytes_read) { + // Unable to read the contents of the file. + DLOG(WARNING) << "Failed to read file. Requested " << bytes_to_read + << " bytes, got " << bytes_read; + return CdmFileImpl::Status::kFailure; + } + + // Only report reading time for successful reads. + UMA_HISTOGRAM_TIMES("Media.EME.CdmFileIO.ReadTime", read_time); + return CdmFileImpl::Status::kSuccess; +} + +// Write |data| to |file|. Returns kSuccess if everything works, kFailure +// otherwise. This method owns |file| and it will be closed at the end. +CdmFileImpl::Status WriteFile(base::File file, std::vector<uint8_t> data) { + // As the temporary file should have been newly created, it should be empty. + CHECK_EQ(0u, file.GetLength()) << "Temporary file is not empty."; + int bytes_to_write = base::checked_cast<int>(data.size()); + + TRACE_EVENT0("media", "CdmFileWriteFile"); + base::TimeTicks start = base::TimeTicks::Now(); + int bytes_written = + file.Write(0, reinterpret_cast<const char*>(data.data()), bytes_to_write); + base::TimeDelta write_time = base::TimeTicks::Now() - start; + if (bytes_written != bytes_to_write) { + DLOG(WARNING) << "Failed to write file. Requested " << bytes_to_write + << " bytes, wrote " << bytes_written; + return CdmFileImpl::Status::kFailure; + } + + // Only report writing time for successful writes. + UMA_HISTOGRAM_TIMES("Media.EME.CdmFileIO.WriteTime", write_time); + + return CdmFileImpl::Status::kSuccess; +} + } // namespace +// static +bool CdmFileImpl::IsValidName(const std::string& name) { + // File names must only contain letters (A-Za-z), digits(0-9), or "._-", + // and not start with "_". It must contain at least 1 character, and not + // more then |kFileNameMaxLength| characters. + if (name.empty() || name.length() > kFileNameMaxLength || + name[0] == kTemporaryFilePrefix) { + return false; + } + + for (const auto ch : name) { + if (!base::IsAsciiAlpha(ch) && !base::IsAsciiDigit(ch) && ch != '.' && + ch != '_' && ch != '-') { + return false; + } + } + + return true; +} + CdmFileImpl::CdmFileImpl( const std::string& file_name, const url::Origin& origin, @@ -128,55 +218,46 @@ file_system_context_(file_system_context), weak_factory_(this) { DVLOG(3) << __func__ << " " << file_name_; + DCHECK(IsValidName(file_name_)); } CdmFileImpl::~CdmFileImpl() { DVLOG(3) << __func__ << " " << file_name_; DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - // If a file open was started but hasn't completed by now, run the callback - // and report an error. - if (pending_open_callback_) { - std::move(pending_open_callback_) - .Run(base::File(base::File::FILE_ERROR_ABORT)); - } - - if (lock_state_ == LockState::kFileAndTempFileLocked) { - // Temporary file is open, so close and release it. - if (temporary_file_on_close_callback_) - std::move(temporary_file_on_close_callback_).Run(); - ReleaseFileLock(temp_file_name_); - } - if (lock_state_ != LockState::kNone) { - // Original file is open, so close and release it. - if (on_close_callback_) - std::move(on_close_callback_).Run(); + if (file_locked_) ReleaseFileLock(file_name_); - } } -void CdmFileImpl::Initialize(OpenFileCallback callback) { +bool CdmFileImpl::Initialize() { DVLOG(3) << __func__ << " file: " << file_name_; DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - DCHECK_EQ(LockState::kNone, lock_state_); - DCHECK(!pending_open_callback_); + DCHECK(!file_locked_); // Grab the lock on |file_name_|. The lock will be held until this object is // destructed. if (!AcquireFileLock(file_name_)) { - DVLOG(3) << "File " << file_name_ << " is already in use."; - std::move(callback).Run(base::File(base::File::FILE_ERROR_IN_USE)); - return; + DVLOG(2) << "File " << file_name_ << " is already in use."; + return false; } - // We have the lock on |file_name_|. Now open the file for reading. Since - // we don't know if this file exists or not, provide FLAG_OPEN_ALWAYS to - // create the file if it doesn't exist. - lock_state_ = LockState::kFileLocked; - pending_open_callback_ = std::move(callback); - OpenFile(file_name_, base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_READ, + // We have the lock on |file_name_|. |file_locked_| is set to simplify + // validation, and to help destruction not have to check. + file_locked_ = true; + return true; +} + +void CdmFileImpl::Read(ReadCallback callback) { + DVLOG(3) << __func__ << " file: " << file_name_; + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + DCHECK(file_locked_); + DCHECK(data_.empty()); + + // Open the file for reading. This may fail if the file does not currently + // exist, which needs to be handled. + OpenFile(file_name_, base::File::FLAG_OPEN | base::File::FLAG_READ, base::BindOnce(&CdmFileImpl::OnFileOpenedForReading, - weak_factory_.GetWeakPtr())); + weak_factory_.GetWeakPtr(), std::move(callback))); } void CdmFileImpl::OpenFile(const std::string& file_name, @@ -184,9 +265,7 @@ CreateOrOpenCallback callback) { DVLOG(3) << __func__ << " file: " << file_name << ", flags: " << file_flags; DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - DCHECK_NE(LockState::kNone, lock_state_); - DCHECK(IsFileLockHeld(file_name)); - DCHECK(pending_open_callback_); + DCHECK(file_locked_); storage::FileSystemURL file_url = CreateFileSystemURL(file_name); storage::AsyncFileUtil* file_util = file_system_context_->GetAsyncFileUtil( @@ -201,106 +280,117 @@ std::move(callback)); } -void CdmFileImpl::OnFileOpenedForReading(base::File file, +void CdmFileImpl::OnFileOpenedForReading(ReadCallback callback, + base::File file, base::OnceClosure on_close_callback) { DVLOG(3) << __func__ << " file: " << file_name_; DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - DCHECK_EQ(LockState::kFileLocked, lock_state_); - DCHECK(pending_open_callback_); + DCHECK(file_locked_); if (!file.IsValid()) { - // File is invalid. Note that the lock on |file_name_| is kept until this - // object is destructed. - DLOG(WARNING) << "Unable to open file " << file_name_ << ", error: " - << base::File::ErrorToString(file.error_details()); - std::move(pending_open_callback_).Run(std::move(file)); + // File is invalid, so assume that it is empty. + DVLOG(2) << "Unable to open file " << file_name_ + << ", error: " << base::File::ErrorToString(file.error_details()); + std::move(callback).Run( + file.error_details() == base::File::FILE_ERROR_NOT_FOUND + ? Status::kSuccess + : Status::kFailure, + std::vector<uint8_t>()); return; } - // When the file is closed, |on_close_callback| will be run. - on_close_callback_ = std::move(on_close_callback); - std::move(pending_open_callback_).Run(std::move(file)); + // Reading |file| must be done on a thread that allows blocking, so post a + // task to do the read on a separate thread. When that completes simply call + // |callback| with the results. + base::PostTaskWithTraitsAndReplyWithResult( + FROM_HERE, + {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, + base::BindOnce(&ReadFile, std::move(file), &data_), + base::BindOnce(&CdmFileImpl::OnFileRead, weak_factory_.GetWeakPtr(), + std::move(callback))); } -void CdmFileImpl::OpenFileForWriting(OpenFileForWritingCallback callback) { - DVLOG(3) << __func__ << " " << file_name_; +void CdmFileImpl::OnFileRead(ReadCallback callback, Status status) { + DVLOG(3) << __func__ << " file: " << file_name_; + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + DCHECK(file_locked_); - // Fail if this is called out of order. We must have opened the original - // file, and there should be no call in progress. - if (lock_state_ != LockState::kFileLocked || pending_open_callback_) { - std::move(callback).Run( - base::File(base::File::FILE_ERROR_INVALID_OPERATION)); + std::vector<uint8_t> data; + data.swap(data_); + std::move(callback).Run(status, std::move(data)); +} + +void CdmFileImpl::Write(const std::vector<uint8_t>& data, + WriteCallback callback) { + DVLOG(3) << __func__ << " file: " << file_name_ << ", size: " << data.size(); + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + DCHECK(file_locked_); + DCHECK(data_.empty()); + + // If there is no data to write, delete the file to save space. + if (data.empty()) { + DeleteFile(std::move(callback)); return; } - // Grab a lock on the temporary file. The lock will be held until this - // new file is renamed in CommitWrite() (or this object is - // destructed). - if (!AcquireFileLock(temp_file_name_)) { - DVLOG(3) << "File " << temp_file_name_ << " is already in use."; - std::move(callback).Run(base::File(base::File::FILE_ERROR_IN_USE)); + // Files are limited in size, so fail if file too big. This should have been + // checked by the caller, but we don't fully trust IPC. + if (data.size() > kMaxFileSizeBytes) { + DLOG(WARNING) << __func__ + << " Too much data to write. #bytes = " << data.size(); + std::move(callback).Run(Status::kFailure); return; } - // We now have locks on both |file_name_| and |temp_file_name_|. Open the - // temporary file for writing. Specifying FLAG_CREATE_ALWAYS which will - // overwrite any existing file. - lock_state_ = LockState::kFileAndTempFileLocked; - pending_open_callback_ = std::move(callback); - OpenFile(temp_file_name_, - base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE, - base::BindOnce(&CdmFileImpl::OnTempFileOpenedForWriting, - weak_factory_.GetWeakPtr())); + // Open the temporary file for writing. Specifying FLAG_CREATE_ALWAYS which + // will overwrite any existing file. + OpenFile( + temp_file_name_, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE, + base::BindOnce(&CdmFileImpl::OnTempFileOpenedForWriting, + weak_factory_.GetWeakPtr(), data, std::move(callback))); } void CdmFileImpl::OnTempFileOpenedForWriting( + std::vector<uint8_t> data, + WriteCallback callback, base::File file, base::OnceClosure on_close_callback) { - DVLOG(3) << __func__ << " file: " << file_name_; + DVLOG(3) << __func__ << " file: " << temp_file_name_ + << ", bytes_to_write: " << data.size(); DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - DCHECK_EQ(LockState::kFileAndTempFileLocked, lock_state_); - DCHECK(pending_open_callback_); + DCHECK(file_locked_); if (!file.IsValid()) { DLOG(WARNING) << "Unable to open file " << temp_file_name_ << ", error: " << base::File::ErrorToString(file.error_details()); - lock_state_ = LockState::kFileLocked; - ReleaseFileLock(temp_file_name_); - std::move(pending_open_callback_).Run(std::move(file)); + std::move(callback).Run(Status::kFailure); return; } - temporary_file_on_close_callback_ = std::move(on_close_callback); - std::move(pending_open_callback_).Run(std::move(file)); + // Writing to |file| must be done on a thread that allows blocking, so post a + // task to do the writing on a separate thread. When that completes we need to + // rename the file in order to replace any existing contents. + base::PostTaskWithTraitsAndReplyWithResult( + FROM_HERE, + {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, + base::BindOnce(&WriteFile, std::move(file), std::move(data)), + base::BindOnce(&CdmFileImpl::OnFileWritten, weak_factory_.GetWeakPtr(), + std::move(callback))); } -void CdmFileImpl::CommitWrite(CommitWriteCallback callback) { - DVLOG(3) << __func__ << " " << temp_file_name_ << " to " << file_name_; +void CdmFileImpl::OnFileWritten(WriteCallback callback, Status status) { + DVLOG(3) << __func__ << " file: " << temp_file_name_ + << ", status: " << status; DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - DCHECK_EQ(LockState::kFileAndTempFileLocked, lock_state_); - DCHECK(IsFileLockHeld(file_name_)); - DCHECK(IsFileLockHeld(temp_file_name_)); + DCHECK(file_locked_); - // TODO(jrummell): Verify that the written file does not exceed the file - // size limit of 32MB. If it does simply delete the written file and fail. - - // Fail if this is called out of order. We must have opened both the original - // and the temporary file, and there should be no call in progress. - if (lock_state_ != LockState::kFileAndTempFileLocked || - pending_open_callback_) { - std::move(callback).Run( - base::File(base::File::FILE_ERROR_INVALID_OPERATION)); + if (status != Status::kSuccess) { + // Write failed, so fail. + std::move(callback).Run(status); return; } - if (on_close_callback_) - std::move(on_close_callback_).Run(); - if (temporary_file_on_close_callback_) - std::move(temporary_file_on_close_callback_).Run(); - - // OpenFile() will be called after the file is renamed, so save |callback|. - pending_open_callback_ = std::move(callback); - + // Now rename |temp_file_name_| to |file_name_|. storage::FileSystemURL src_file_url = CreateFileSystemURL(temp_file_name_); storage::FileSystemURL dest_file_url = CreateFileSystemURL(file_name_); storage::AsyncFileUtil* file_util = file_system_context_->GetAsyncFileUtil( @@ -313,30 +403,62 @@ file_util->MoveFileLocal( std::move(operation_context), src_file_url, dest_file_url, storage::FileSystemOperation::OPTION_NONE, - base::BindOnce(&CdmFileImpl::OnFileRenamed, weak_factory_.GetWeakPtr())); + base::BindOnce(&CdmFileImpl::OnFileRenamed, weak_factory_.GetWeakPtr(), + std::move(callback))); } -void CdmFileImpl::OnFileRenamed(base::File::Error move_result) { +void CdmFileImpl::OnFileRenamed(WriteCallback callback, + base::File::Error move_result) { DVLOG(3) << __func__; DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - DCHECK_EQ(LockState::kFileAndTempFileLocked, lock_state_); - DCHECK(pending_open_callback_); - - // Temporary file has been renamed, so we can release the lock on it. - ReleaseFileLock(temp_file_name_); - lock_state_ = LockState::kFileLocked; + DCHECK(file_locked_); // Was the rename successful? if (move_result != base::File::FILE_OK) { - std::move(pending_open_callback_).Run(base::File(move_result)); + DLOG(WARNING) << "Unable to rename file " << temp_file_name_ << " to " + << file_name_ + << ", error: " << base::File::ErrorToString(move_result); + std::move(callback).Run(Status::kFailure); return; } - // Reopen the original file for reading. Specifying FLAG_OPEN as the file - // has to exist or something's wrong. - OpenFile(file_name_, base::File::FLAG_OPEN | base::File::FLAG_READ, - base::BindOnce(&CdmFileImpl::OnFileOpenedForReading, - weak_factory_.GetWeakPtr())); + std::move(callback).Run(Status::kSuccess); +} + +void CdmFileImpl::DeleteFile(WriteCallback callback) { + DVLOG(3) << __func__; + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + DCHECK(file_locked_); + + storage::FileSystemURL file_url = CreateFileSystemURL(file_name_); + storage::AsyncFileUtil* file_util = file_system_context_->GetAsyncFileUtil( + storage::kFileSystemTypePluginPrivate); + auto operation_context = + std::make_unique<storage::FileSystemOperationContext>( + file_system_context_.get()); + + DVLOG(3) << "Deleting " << file_url.DebugString(); + file_util->DeleteFile( + std::move(operation_context), file_url, + base::BindOnce(&CdmFileImpl::OnFileDeleted, weak_factory_.GetWeakPtr(), + std::move(callback))); +} + +void CdmFileImpl::OnFileDeleted(WriteCallback callback, + base::File::Error result) { + DVLOG(3) << __func__; + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + DCHECK(file_locked_); + + if (result != base::File::FILE_OK && + result != base::File::FILE_ERROR_NOT_FOUND) { + DLOG(WARNING) << "Unable to delete file " << file_name_ + << ", error: " << base::File::ErrorToString(result); + std::move(callback).Run(Status::kFailure); + return; + } + + std::move(callback).Run(Status::kSuccess); } storage::FileSystemURL CdmFileImpl::CreateFileSystemURL( @@ -350,11 +472,6 @@ return GetFileLockMap()->AcquireFileLock(file_lock_key); } -bool CdmFileImpl::IsFileLockHeld(const std::string& file_name) { - FileLockKey file_lock_key(file_system_id_, origin_, file_name); - return GetFileLockMap()->IsFileLockHeld(file_lock_key); -} - void CdmFileImpl::ReleaseFileLock(const std::string& file_name) { FileLockKey file_lock_key(file_system_id_, origin_, file_name); GetFileLockMap()->ReleaseFileLock(file_lock_key);
diff --git a/content/browser/media/cdm_file_impl.h b/content/browser/media/cdm_file_impl.h index 9d9b1a48..e34e77c 100644 --- a/content/browser/media/cdm_file_impl.h +++ b/content/browser/media/cdm_file_impl.h
@@ -6,6 +6,7 @@ #define CONTENT_BROWSER_MEDIA_CDM_FILE_IMPL_H_ #include <string> +#include <vector> #include "base/callback_forward.h" #include "base/files/file.h" @@ -28,6 +29,10 @@ // mojo pipe as CdmStorageImpl, to enforce message dispatch order. class CdmFileImpl final : public media::mojom::CdmFile { public: + // Check whether |name| is valid as a usable file name. Returns true if it is, + // false otherwise. + static bool IsValidName(const std::string& name); + CdmFileImpl(const std::string& file_name, const url::Origin& origin, const std::string& file_system_id, @@ -35,54 +40,51 @@ scoped_refptr<storage::FileSystemContext> file_system_context); ~CdmFileImpl() final; - // Called to open the file for read initially. Will create a file with - // |file_name_| if it does not exist. |file_opened_callback| will be called - // with the opened file descriptor on success. |file|.error_details() - // = base::File::FILE_ERROR_IN_USE if the file is in use by other CDMs - // or by the system. Note that |file_opened_callback| may destroy |this| - // (especially if the file can not be opened). - // Note that |this| should not be used anymore if Initialize() fails. - using OpenFileCallback = base::OnceCallback<void(base::File file)>; - void Initialize(OpenFileCallback file_opened_callback); + // Called to grab a lock on the file. Returns false if the file is in use by + // other CDMs or by the system, true otherwise. Note that |this| should not + // be used anymore if Initialize() fails. + bool Initialize(); - // media::mojom::CdmFile implementation. |callback| will be called with the - // file descriptor on success. Otherwise the file descriptor will not be - // valid, and error_details() provides the reason. - void OpenFileForWriting(OpenFileForWritingCallback callback) final; - void CommitWrite(CommitWriteCallback callback) final; + // media::mojom::CdmFile implementation. + void Read(ReadCallback callback) final; + void Write(const std::vector<uint8_t>& data, WriteCallback callback) final; private: using CreateOrOpenCallback = storage::AsyncFileUtil::CreateOrOpenCallback; - // Keep track of which files are locked. - // kFileLocked: Only the original file |file_name_| is locked. - // kFileAndTempFileLocked: Both |file_name_| and |temp_file_name_| are - // locked. - // Initialize() can only be called if kNone, results in kFileLocked (on - // success). OpenFileForWriting() can only be called if kFileLocked, results - // in kFileAndTempFileLocked. CommitWrite() can only be called if - // kFileAndTempFileLocked, results in kFileLocked (temp file closed and then - // renamed to replace the original). - enum class LockState { kNone, kFileLocked, kFileAndTempFileLocked }; - // Open the file |file_name| using the flags provided in |file_flags|. // |callback| is called with the result. void OpenFile(const std::string& file_name, uint32_t file_flags, CreateOrOpenCallback callback); - void OnFileOpenedForReading(base::File file, + // Called when the file has been opened for reading, so it reads the contents + // of |file| and passes them to |callback|. |file| is closed after reading. + void OnFileOpenedForReading(ReadCallback callback, + base::File file, base::OnceClosure on_close_callback); - void OnTempFileOpenedForWriting(base::File file, + void OnFileRead(ReadCallback callback, Status status); + + // Called when |temp_file_name_| has been opened for writing. Writes + // |data| to |file|, closes |file|, and then kicks off a rename of + // |temp_file_name_| to |file_name_|, effectively replacing the contents of + // the old file. + void OnTempFileOpenedForWriting(std::vector<uint8_t> data, + WriteCallback callback, + base::File file, base::OnceClosure on_close_callback); - void OnFileRenamed(base::File::Error move_result); + void OnFileWritten(WriteCallback callback, Status status); + void OnFileRenamed(WriteCallback callback, base::File::Error move_result); + + // Deletes |file_name_| asynchronously. + void DeleteFile(WriteCallback callback); + void OnFileDeleted(WriteCallback callback, base::File::Error result); // Returns the FileSystemURL for the specified |file_name|. storage::FileSystemURL CreateFileSystemURL(const std::string& file_name); // Helper methods to lock and unlock a file. bool AcquireFileLock(const std::string& file_name); - bool IsFileLockHeld(const std::string& file_name); void ReleaseFileLock(const std::string& file_name); // Names of the files this class represents. @@ -96,21 +98,16 @@ const std::string file_system_root_uri_; scoped_refptr<storage::FileSystemContext> file_system_context_; - // Keep track of which files are opened. - LockState lock_state_ = LockState::kNone; + // Keep track of when the original file |file_name_| is locked. + // Initialize() can only be called if false and takes the lock (on success). + // Read() and Write() can only be called if true. + // Note that having a lock on |file_name| implies that |temp_file_name| is + // reserved for use by this object only, and an explicit lock on + // |temp_file_name| is not required. + bool file_locked_ = false; - // As only one open operation is allowed at a time, |pending_open_callback_| - // keeps track of the callback to be called when the file is opened. This - // ensures the callback is always called if we are destroyed while the open - // operation is running. - OpenFileCallback pending_open_callback_; - - // Callbacks required to close the file when it's no longer needed. - // storage::AsyncFileUtil::CreateOrOpen() returns this callback on a - // successful open along with the base::File object, which should be - // called when the file is closed. - base::OnceClosure on_close_callback_; - base::OnceClosure temporary_file_on_close_callback_; + // Buffer used when reading the file. + std::vector<uint8_t> data_; THREAD_CHECKER(thread_checker_); base::WeakPtrFactory<CdmFileImpl> weak_factory_;
diff --git a/content/browser/media/cdm_storage_impl.cc b/content/browser/media/cdm_storage_impl.cc index 02afc46..284cc97 100644 --- a/content/browser/media/cdm_storage_impl.cc +++ b/content/browser/media/cdm_storage_impl.cc
@@ -90,20 +90,20 @@ if (!IsValidCdmFileSystemId(cdm_file_system_id_)) { DVLOG(1) << "CdmStorageImpl not initialized properly."; - std::move(callback).Run(Status::kFailure, base::File(), nullptr); + std::move(callback).Run(Status::kFailure, nullptr); return; } if (file_name.empty()) { DVLOG(1) << "No file specified."; - std::move(callback).Run(Status::kFailure, base::File(), nullptr); + std::move(callback).Run(Status::kFailure, nullptr); return; } // The file system should only be opened once. If it has been attempted and // failed, we can't create the CdmFile objects. if (file_system_state_ == FileSystemState::kError) { - std::move(callback).Run(Status::kFailure, base::File(), nullptr); + std::move(callback).Run(Status::kFailure, nullptr); return; } @@ -159,7 +159,7 @@ file_system_state_ = FileSystemState::kError; // All pending calls will fail. for (auto& pending : pending_open_calls_) { - std::move(pending.second).Run(Status::kFailure, base::File(), nullptr); + std::move(pending.second).Run(Status::kFailure, nullptr); } pending_open_calls_.clear(); return; @@ -181,29 +181,20 @@ DCHECK_EQ(FileSystemState::kOpened, file_system_state_); // File system opened successfully, so create an CdmFileImpl object and - // initialize it (which actually opens the file for reading). + // initialize it (which only grabs the lock to prevent any other access to the + // file except through this object). + if (!CdmFileImpl::IsValidName(file_name)) { + std::move(callback).Run(Status::kFailure, nullptr); + return; + } + auto cdm_file_impl = std::make_unique<CdmFileImpl>( file_name, origin(), cdm_file_system_id_, file_system_root_uri_, file_system_context_); - auto* cdm_file_ptr = cdm_file_impl.get(); - cdm_file_ptr->Initialize(base::BindOnce( - &CdmStorageImpl::OnCdmFileInitialized, weak_factory_.GetWeakPtr(), - std::move(cdm_file_impl), std::move(callback))); -} -void CdmStorageImpl::OnCdmFileInitialized( - std::unique_ptr<CdmFileImpl> cdm_file_impl, - OpenCallback callback, - base::File file) { - DVLOG(3) << __func__; - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - if (!file.IsValid()) { - // Unable to open the file requested. Return an appropriate error. - Status status = (file.error_details() == base::File::FILE_ERROR_IN_USE) - ? Status::kInUse - : Status::kFailure; - std::move(callback).Run(status, base::File(), nullptr); + if (!cdm_file_impl->Initialize()) { + // Unable to initialize with the file requested. + std::move(callback).Run(Status::kInUse, nullptr); return; } @@ -211,8 +202,7 @@ media::mojom::CdmFileAssociatedPtrInfo cdm_file; cdm_file_bindings_.AddBinding(std::move(cdm_file_impl), mojo::MakeRequest(&cdm_file)); - std::move(callback).Run(Status::kSuccess, std::move(file), - std::move(cdm_file)); + std::move(callback).Run(Status::kSuccess, std::move(cdm_file)); } } // namespace content
diff --git a/content/browser/media/cdm_storage_impl.h b/content/browser/media/cdm_storage_impl.h index 331d2b9c..ce17c8c6 100644 --- a/content/browser/media/cdm_storage_impl.h +++ b/content/browser/media/cdm_storage_impl.h
@@ -63,10 +63,10 @@ // After the file system is opened, called to create a CdmFile object. void CreateCdmFile(const std::string& file_name, OpenCallback callback); - // Called after the CdmFileImpl object has opened the file for reading. + // Called after the CdmFileImpl object has opened the file. void OnCdmFileInitialized(std::unique_ptr<CdmFileImpl> cdm_file_impl, OpenCallback callback, - base::File file); + bool success); // Files are stored in the PluginPrivateFileSystem, so keep track of the // CDM file system ID in order to open the files in the correct context.
diff --git a/content/browser/media/cdm_storage_impl_unittest.cc b/content/browser/media/cdm_storage_impl_unittest.cc index 07ebf471..7f9743f 100644 --- a/content/browser/media/cdm_storage_impl_unittest.cc +++ b/content/browser/media/cdm_storage_impl_unittest.cc
@@ -57,10 +57,6 @@ void Initialize(const std::string& file_system_id) { DVLOG(3) << __func__; - // Most tests don't do any I/O, but Open() returns a base::File which needs - // to be closed. - base::ThreadRestrictions::SetIOAllowed(true); - // Create the CdmStorageImpl object. |cdm_storage_| will own the resulting // object. CdmStorageImpl::Create(rfh_, file_system_id, @@ -68,43 +64,51 @@ } // Open the file |name|. Returns true if the file returned is valid, false - // otherwise. Updates |status|, |file|, and |cdm_file| with the values - // returned by CdmStorage. If |status| = kSuccess, |file| should be valid to - // access, and |cdm_file| should be reset when the file is closed. + // otherwise. On success |cdm_file| is bound to the CdmFileImpl object. bool Open(const std::string& name, - CdmStorage::Status* status, - base::File* file, CdmFileAssociatedPtr* cdm_file) { DVLOG(3) << __func__; + CdmStorage::Status status; cdm_storage_->Open( name, base::BindOnce(&CdmStorageTest::OpenDone, base::Unretained(this), - status, file, cdm_file)); + &status, cdm_file)); RunAndWaitForResult(); - return file->IsValid(); + return status == CdmStorage::Status::kSuccess; } - bool Write(CdmFile* cdm_file, - const std::vector<uint8_t>& data, - base::File* file) { - bool status; - cdm_file->OpenFileForWriting( - base::BindOnce(&CdmStorageTest::FileOpenedForWrite, - base::Unretained(this), cdm_file, data, file, &status)); + // Reads the contents of the previously opened |cdm_file|. If successful, + // true is returned and |data| is updated with the contents of the file. + // If unable to read the file, false is returned. + bool Read(CdmFile* cdm_file, std::vector<uint8_t>* data) { + DVLOG(3) << __func__; + + CdmFile::Status status; + cdm_file->Read(base::BindOnce(&CdmStorageTest::FileRead, + base::Unretained(this), &status, data)); RunAndWaitForResult(); - return status; + return status == CdmFile::Status::kSuccess; + } + + // Writes |data| to the previously opened |cdm_file|, replacing the contents + // of the file. Returns true if successful, false otherwise. + bool Write(CdmFile* cdm_file, const std::vector<uint8_t>& data) { + DVLOG(3) << __func__; + + CdmFile::Status status; + cdm_file->Write(data, base::BindOnce(&CdmStorageTest::FileWritten, + base::Unretained(this), &status)); + RunAndWaitForResult(); + return status == CdmFile::Status::kSuccess; } private: void OpenDone(CdmStorage::Status* status, - base::File* file, CdmFileAssociatedPtr* cdm_file, CdmStorage::Status actual_status, - base::File actual_file, CdmFileAssociatedPtrInfo actual_cdm_file) { DVLOG(3) << __func__; *status = actual_status; - *file = std::move(actual_file); // Open() returns a CdmFileAssociatedPtrInfo, so bind it to the // CdmFileAssociatedPtr provided. @@ -114,21 +118,19 @@ run_loop_->Quit(); } - void FileOpenedForWrite(CdmFile* cdm_file, - const std::vector<uint8_t>& data, - base::File* file, - bool* status, - base::File file_to_write) { - int bytes_to_write = base::checked_cast<int>(data.size()); - int bytes_written = file_to_write.Write( - 0, reinterpret_cast<const char*>(data.data()), bytes_to_write); - *status = bytes_to_write == bytes_written; - cdm_file->CommitWrite(base::BindOnce(&CdmStorageTest::WriteDone, - base::Unretained(this), file)); + void FileRead(CdmFile::Status* status, + std::vector<uint8_t>* data, + CdmFile::Status actual_status, + const std::vector<uint8_t>& actual_data) { + DVLOG(3) << __func__; + *status = actual_status; + *data = actual_data; + run_loop_->Quit(); } - void WriteDone(base::File* file, base::File new_file_for_reading) { - *file = std::move(new_file_for_reading); + void FileWritten(CdmFile::Status* status, CdmFile::Status actual_status) { + DVLOG(3) << __func__; + *status = actual_status; run_loop_->Quit(); } @@ -147,12 +149,8 @@ Initialize("name/"); const char kFileName[] = "valid_file_name"; - CdmStorage::Status status; - base::File file; CdmFileAssociatedPtr cdm_file; - EXPECT_FALSE(Open(kFileName, &status, &file, &cdm_file)); - EXPECT_EQ(status, CdmStorage::Status::kFailure); - EXPECT_FALSE(file.IsValid()); + EXPECT_FALSE(Open(kFileName, &cdm_file)); EXPECT_FALSE(cdm_file.is_bound()); } @@ -160,12 +158,8 @@ Initialize("name\\"); const char kFileName[] = "valid_file_name"; - CdmStorage::Status status; - base::File file; CdmFileAssociatedPtr cdm_file; - EXPECT_FALSE(Open(kFileName, &status, &file, &cdm_file)); - EXPECT_EQ(status, CdmStorage::Status::kFailure); - EXPECT_FALSE(file.IsValid()); + EXPECT_FALSE(Open(kFileName, &cdm_file)); EXPECT_FALSE(cdm_file.is_bound()); } @@ -173,12 +167,19 @@ Initialize(""); const char kFileName[] = "valid_file_name"; - CdmStorage::Status status; - base::File file; CdmFileAssociatedPtr cdm_file; - EXPECT_FALSE(Open(kFileName, &status, &file, &cdm_file)); - EXPECT_EQ(status, CdmStorage::Status::kFailure); - EXPECT_FALSE(file.IsValid()); + EXPECT_FALSE(Open(kFileName, &cdm_file)); + EXPECT_FALSE(cdm_file.is_bound()); +} + +TEST_F(CdmStorageTest, InvalidFileName) { + Initialize(kTestFileSystemId); + + // Anything other than ASCII letter, digits, and -._ will fail. Add a + // Unicode character to the name. + const char kFileName[] = "openfile\u1234"; + CdmFileAssociatedPtr cdm_file; + EXPECT_FALSE(Open(kFileName, &cdm_file)); EXPECT_FALSE(cdm_file.is_bound()); } @@ -186,12 +187,27 @@ Initialize(kTestFileSystemId); const char kFileName[] = ""; - CdmStorage::Status status; - base::File file; CdmFileAssociatedPtr cdm_file; - EXPECT_FALSE(Open(kFileName, &status, &file, &cdm_file)); - EXPECT_EQ(status, CdmStorage::Status::kFailure); - EXPECT_FALSE(file.IsValid()); + EXPECT_FALSE(Open(kFileName, &cdm_file)); + EXPECT_FALSE(cdm_file.is_bound()); +} + +TEST_F(CdmStorageTest, InvalidFileNameStartWithUnderscore) { + Initialize(kTestFileSystemId); + + const char kFileName[] = "_invalid"; + CdmFileAssociatedPtr cdm_file; + EXPECT_FALSE(Open(kFileName, &cdm_file)); + EXPECT_FALSE(cdm_file.is_bound()); +} + +TEST_F(CdmStorageTest, InvalidFileNameTooLong) { + Initialize(kTestFileSystemId); + + // Limit is 256 characters, so try a file name with 257. + const std::string kFileName(257, 'a'); + CdmFileAssociatedPtr cdm_file; + EXPECT_FALSE(Open(kFileName, &cdm_file)); EXPECT_FALSE(cdm_file.is_bound()); } @@ -199,12 +215,8 @@ Initialize(kTestFileSystemId); const char kFileName[] = "test_file_name"; - CdmStorage::Status status; - base::File file; CdmFileAssociatedPtr cdm_file; - EXPECT_TRUE(Open(kFileName, &status, &file, &cdm_file)); - EXPECT_EQ(status, CdmStorage::Status::kSuccess); - EXPECT_TRUE(file.IsValid()); + EXPECT_TRUE(Open(kFileName, &cdm_file)); EXPECT_TRUE(cdm_file.is_bound()); } @@ -212,31 +224,20 @@ Initialize(kTestFileSystemId); const char kFileName[] = "test_file_name"; - CdmStorage::Status status; - base::File file1; CdmFileAssociatedPtr cdm_file1; - EXPECT_TRUE(Open(kFileName, &status, &file1, &cdm_file1)); - EXPECT_EQ(status, CdmStorage::Status::kSuccess); - EXPECT_TRUE(file1.IsValid()); + EXPECT_TRUE(Open(kFileName, &cdm_file1)); EXPECT_TRUE(cdm_file1.is_bound()); // Second attempt on the same file should fail as the file is locked. - base::File file2; CdmFileAssociatedPtr cdm_file2; - EXPECT_FALSE(Open(kFileName, &status, &file2, &cdm_file2)); - EXPECT_EQ(status, CdmStorage::Status::kInUse); - EXPECT_FALSE(file2.IsValid()); + EXPECT_FALSE(Open(kFileName, &cdm_file2)); EXPECT_FALSE(cdm_file2.is_bound()); // Now close the first file and try again. It should be free now. - file1.Close(); cdm_file1.reset(); - base::File file3; CdmFileAssociatedPtr cdm_file3; - EXPECT_TRUE(Open(kFileName, &status, &file3, &cdm_file3)); - EXPECT_EQ(status, CdmStorage::Status::kSuccess); - EXPECT_TRUE(file3.IsValid()); + EXPECT_TRUE(Open(kFileName, &cdm_file3)); EXPECT_TRUE(cdm_file3.is_bound()); } @@ -244,28 +245,18 @@ Initialize(kTestFileSystemId); const char kFileName1[] = "file1"; - CdmStorage::Status status; - base::File file1; CdmFileAssociatedPtr cdm_file1; - EXPECT_TRUE(Open(kFileName1, &status, &file1, &cdm_file1)); - EXPECT_EQ(status, CdmStorage::Status::kSuccess); - EXPECT_TRUE(file1.IsValid()); + EXPECT_TRUE(Open(kFileName1, &cdm_file1)); EXPECT_TRUE(cdm_file1.is_bound()); const char kFileName2[] = "file2"; - base::File file2; CdmFileAssociatedPtr cdm_file2; - EXPECT_TRUE(Open(kFileName2, &status, &file2, &cdm_file2)); - EXPECT_EQ(status, CdmStorage::Status::kSuccess); - EXPECT_TRUE(file2.IsValid()); + EXPECT_TRUE(Open(kFileName2, &cdm_file2)); EXPECT_TRUE(cdm_file2.is_bound()); const char kFileName3[] = "file3"; - base::File file3; CdmFileAssociatedPtr cdm_file3; - EXPECT_TRUE(Open(kFileName3, &status, &file3, &cdm_file3)); - EXPECT_EQ(status, CdmStorage::Status::kSuccess); - EXPECT_TRUE(file3.IsValid()); + EXPECT_TRUE(Open(kFileName3, &cdm_file3)); EXPECT_TRUE(cdm_file3.is_bound()); } @@ -273,56 +264,38 @@ Initialize(kTestFileSystemId); const char kFileName[] = "test_file_name"; - CdmStorage::Status status; - base::File file; CdmFileAssociatedPtr cdm_file; - EXPECT_TRUE(Open(kFileName, &status, &file, &cdm_file)); - EXPECT_EQ(status, CdmStorage::Status::kSuccess); - EXPECT_TRUE(file.IsValid()); + EXPECT_TRUE(Open(kFileName, &cdm_file)); EXPECT_TRUE(cdm_file.is_bound()); // Write several bytes and read them back. - const uint8_t kTestData[] = "random string"; - const int kTestDataSize = sizeof(kTestData); - EXPECT_TRUE(Write(cdm_file.get(), - std::vector<uint8_t>(kTestData, kTestData + kTestDataSize), - &file)); - EXPECT_TRUE(file.IsValid()); + std::vector<uint8_t> kTestData = {'r', 'a', 'n', 'd', 'o', 'm'}; + EXPECT_TRUE(Write(cdm_file.get(), kTestData)); - uint8_t data_read[32]; - const int kTestDataReadSize = sizeof(data_read); - EXPECT_GT(kTestDataReadSize, kTestDataSize); - EXPECT_EQ(kTestDataSize, file.Read(0, reinterpret_cast<char*>(data_read), - kTestDataReadSize)); - for (size_t i = 0; i < kTestDataSize; i++) - EXPECT_EQ(kTestData[i], data_read[i]); + std::vector<uint8_t> data_read; + EXPECT_TRUE(Read(cdm_file.get(), &data_read)); + EXPECT_EQ(kTestData, data_read); } TEST_F(CdmStorageTest, ReadThenWriteEmptyFile) { Initialize(kTestFileSystemId); const char kFileName[] = "empty_file_name"; - CdmStorage::Status status; - base::File file; CdmFileAssociatedPtr cdm_file; - EXPECT_TRUE(Open(kFileName, &status, &file, &cdm_file)); - EXPECT_EQ(status, CdmStorage::Status::kSuccess); - EXPECT_TRUE(file.IsValid()); + EXPECT_TRUE(Open(kFileName, &cdm_file)); EXPECT_TRUE(cdm_file.is_bound()); // New file should be empty. - uint8_t data_read[32]; - const int kTestDataReadSize = sizeof(data_read); - EXPECT_EQ( - 0, file.Read(0, reinterpret_cast<char*>(data_read), kTestDataReadSize)); + std::vector<uint8_t> data_read; + EXPECT_TRUE(Read(cdm_file.get(), &data_read)); + EXPECT_EQ(0u, data_read.size()); // Write nothing. - EXPECT_TRUE(Write(cdm_file.get(), std::vector<uint8_t>(), &file)); - EXPECT_TRUE(file.IsValid()); + EXPECT_TRUE(Write(cdm_file.get(), std::vector<uint8_t>())); // Should still be empty. - EXPECT_EQ( - 0, file.Read(0, reinterpret_cast<char*>(data_read), kTestDataReadSize)); + EXPECT_TRUE(Read(cdm_file.get(), &data_read)); + EXPECT_EQ(0u, data_read.size()); } } // namespace content
diff --git a/content/browser/media/session/media_session_impl.cc b/content/browser/media/session/media_session_impl.cc index 1c54a20..090375c37 100644 --- a/content/browser/media/session/media_session_impl.cc +++ b/content/browser/media/session/media_session_impl.cc
@@ -25,6 +25,7 @@ #include "content/public/browser/navigation_handle.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_client.h" +#include "content/public/common/favicon_url.h" #include "media/base/media_content_type.h" #include "services/media_session/public/cpp/media_image_manager.h" #include "services/media_session/public/mojom/audio_focus.mojom.h" @@ -92,7 +93,7 @@ case media_session::mojom::MediaSessionAction::kSkipAd: return MediaSessionUserAction::SkipAd; case media_session::mojom::MediaSessionAction::kStop: - break; + return MediaSessionUserAction::Stop; } NOTREACHED(); return MediaSessionUserAction::Play; @@ -218,6 +219,40 @@ RebuildAndNotifyMetadataChanged(); } +void MediaSessionImpl::DidUpdateFaviconURL( + const std::vector<FaviconURL>& candidates) { + std::vector<media_session::MediaImage> icons; + + for (auto& icon : candidates) { + if (icon.icon_sizes.empty() || !icon.icon_url.is_valid()) + continue; + + // We only want either favicons or the touch icons. There is another type of + // touch icon which is "precomposed". This means it might have rounded + // corners, etc. but it is not predictable so we cannot show them in the UI. + if (icon.icon_type != FaviconURL::IconType::kFavicon && + icon.icon_type != FaviconURL::IconType::kTouchIcon) { + continue; + } + + media_session::MediaImage image; + image.src = icon.icon_url; + image.sizes = icon.icon_sizes; + icons.push_back(image); + } + + auto it = images_.find(MediaSessionImageType::kSourceIcon); + if (it != images_.end() && it->second == icons) + return; + + images_.insert_or_assign(MediaSessionImageType::kSourceIcon, icons); + + observers_.ForAllPtrs( + [this](media_session::mojom::MediaSessionObserver* observer) { + observer->MediaSessionImagesChanged(this->images_); + }); +} + bool MediaSessionImpl::AddPlayer(MediaSessionPlayerObserver* observer, int player_id, media::MediaContentType media_content_type) { @@ -431,8 +466,14 @@ DCHECK(!HasPepper()); if (suspend_type == SuspendType::kUI) { - MediaSessionUmaHelper::RecordMediaSessionUserAction( - MediaSessionUmaHelper::MediaSessionUserAction::StopDefault, focused_); + // If the site has registered an action handle for stop then we should + // notify the site but continue stopping the media session. + if (ShouldRouteAction(media_session::mojom::MediaSessionAction::kStop)) { + DidReceiveAction(media_session::mojom::MediaSessionAction::kStop); + } else { + MediaSessionUmaHelper::RecordMediaSessionUserAction( + MediaSessionUmaHelper::MediaSessionUserAction::StopDefault, focused_); + } } // TODO(mlamouri): merge the logic between UI and SYSTEM.
diff --git a/content/browser/media/session/media_session_impl.h b/content/browser/media/session/media_session_impl.h index 26da12a..abde0ac 100644 --- a/content/browser/media/session/media_session_impl.h +++ b/content/browser/media/session/media_session_impl.h
@@ -135,6 +135,7 @@ void OnWebContentsFocused(RenderWidgetHost*) override; void OnWebContentsLostFocus(RenderWidgetHost*) override; void TitleWasSet(NavigationEntry* entry) override; + void DidUpdateFaviconURL(const std::vector<FaviconURL>& candidates) override; // MediaSessionService-related methods
diff --git a/content/browser/media/session/media_session_impl_browsertest.cc b/content/browser/media/session/media_session_impl_browsertest.cc index b7a77282..08bf6e8 100644 --- a/content/browser/media/session/media_session_impl_browsertest.cc +++ b/content/browser/media/session/media_session_impl_browsertest.cc
@@ -21,6 +21,7 @@ #include "content/browser/media/session/mock_media_session_service_impl.h" #include "content/public/browser/media_session.h" #include "content/public/browser/web_contents.h" +#include "content/public/common/favicon_url.h" #include "content/public/test/content_browser_test.h" #include "content/public/test/content_browser_test_utils.h" #include "content/shell/browser/shell.h" @@ -2434,3 +2435,91 @@ expected_metadata.artist = base::ASCIIToUTF16("Local File"); observer.WaitForExpectedMetadata(expected_metadata); } + +IN_PROC_BROWSER_TEST_F(MediaSessionImplBrowserTest, UpdateFaviconURL) { + std::vector<gfx::Size> valid_sizes; + valid_sizes.push_back(gfx::Size(100, 100)); + valid_sizes.push_back(gfx::Size(200, 200)); + + std::vector<content::FaviconURL> favicons; + favicons.push_back(content::FaviconURL( + GURL("https://www.example.org/favicon1.png"), + content::FaviconURL::IconType::kInvalid, valid_sizes)); + favicons.push_back(content::FaviconURL( + GURL(), content::FaviconURL::IconType::kFavicon, valid_sizes)); + favicons.push_back(content::FaviconURL( + GURL("https://www.example.org/favicon2.png"), + content::FaviconURL::IconType::kFavicon, std::vector<gfx::Size>())); + favicons.push_back(content::FaviconURL( + GURL("https://www.example.org/favicon3.png"), + content::FaviconURL::IconType::kFavicon, valid_sizes)); + favicons.push_back(content::FaviconURL( + GURL("https://www.example.org/favicon4.png"), + content::FaviconURL::IconType::kTouchIcon, valid_sizes)); + favicons.push_back(content::FaviconURL( + GURL("https://www.example.org/favicon5.png"), + content::FaviconURL::IconType::kTouchPrecomposedIcon, valid_sizes)); + + media_session_->DidUpdateFaviconURL(favicons); + + { + std::vector<media_session::MediaImage> expected_images; + media_session::MediaImage test_image_1; + test_image_1.src = GURL("https://www.example.org/favicon3.png"); + test_image_1.sizes = valid_sizes; + expected_images.push_back(test_image_1); + + media_session::MediaImage test_image_2; + test_image_2.src = GURL("https://www.example.org/favicon4.png"); + test_image_2.sizes = valid_sizes; + expected_images.push_back(test_image_2); + + media_session::test::MockMediaSessionMojoObserver observer(*media_session_); + observer.WaitForExpectedImagesOfType( + media_session::mojom::MediaSessionImageType::kSourceIcon, + expected_images); + } + + { + media_session::test::MockMediaSessionMojoObserver observer(*media_session_); + media_session_->DidUpdateFaviconURL(std::vector<content::FaviconURL>()); + observer.WaitForExpectedImagesOfType( + media_session::mojom::MediaSessionImageType::kSourceIcon, + std::vector<media_session::MediaImage>()); + } +} + +IN_PROC_BROWSER_TEST_F(MediaSessionImplBrowserTest, + UpdateFaviconURL_ClearOnNavigate) { + std::vector<gfx::Size> valid_sizes; + valid_sizes.push_back(gfx::Size(100, 100)); + + std::vector<content::FaviconURL> favicons; + favicons.push_back(content::FaviconURL( + GURL("https://www.example.org/favicon1.png"), + content::FaviconURL::IconType::kFavicon, valid_sizes)); + + media_session_->DidUpdateFaviconURL(favicons); + + { + std::vector<media_session::MediaImage> expected_images; + media_session::MediaImage test_image_1; + test_image_1.src = GURL("https://www.example.org/favicon1.png"); + test_image_1.sizes = valid_sizes; + expected_images.push_back(test_image_1); + + media_session::test::MockMediaSessionMojoObserver observer(*media_session_); + observer.WaitForExpectedImagesOfType( + media_session::mojom::MediaSessionImageType::kSourceIcon, + expected_images); + } + + { + media_session::test::MockMediaSessionMojoObserver observer(*media_session_); + NavigateToURL( + shell(), embedded_test_server()->GetURL("example.com", "/title1.html")); + observer.WaitForExpectedImagesOfType( + media_session::mojom::MediaSessionImageType::kSourceIcon, + std::vector<media_session::MediaImage>()); + } +}
diff --git a/content/browser/media/session/media_session_impl_service_routing_unittest.cc b/content/browser/media/session/media_session_impl_service_routing_unittest.cc index 2f25201..b668a491 100644 --- a/content/browser/media/session/media_session_impl_service_routing_unittest.cc +++ b/content/browser/media/session/media_session_impl_service_routing_unittest.cc
@@ -871,4 +871,37 @@ empty_images); } +TEST_F(MediaSessionImplServiceRoutingTest, StopBehaviourDefault) { + base::RunLoop run_loop; + + StartPlayerForFrame(main_frame_); + CreateServiceForFrame(main_frame_); + + EXPECT_CALL(*GetPlayerForFrame(main_frame_), OnSuspend(_)) + .WillOnce(InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit)); + EXPECT_CALL(*GetClientForFrame(main_frame_), + DidReceiveAction(MediaSessionAction::kStop)) + .Times(0); + + MediaSessionImpl::Get(contents())->Stop(MediaSession::SuspendType::kUI); + run_loop.Run(); +} + +TEST_F(MediaSessionImplServiceRoutingTest, StopBehaviourWhenActionEnabled) { + base::RunLoop run_loop; + + StartPlayerForFrame(main_frame_); + CreateServiceForFrame(main_frame_); + + EXPECT_CALL(*GetPlayerForFrame(main_frame_), OnSuspend(_)); + EXPECT_CALL(*GetClientForFrame(main_frame_), + DidReceiveAction(MediaSessionAction::kStop)) + .WillOnce(InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit)); + + services_[main_frame_]->EnableAction(MediaSessionAction::kStop); + + MediaSessionImpl::Get(contents())->Stop(MediaSession::SuspendType::kUI); + run_loop.Run(); +} + } // namespace content
diff --git a/content/browser/media/session/media_session_uma_helper.h b/content/browser/media/session/media_session_uma_helper.h index 1b8511e..ced34e5 100644 --- a/content/browser/media/session/media_session_uma_helper.h +++ b/content/browser/media/session/media_session_uma_helper.h
@@ -42,7 +42,8 @@ SeekBackward = 7, SeekForward = 8, SkipAd = 9, - kMaxValue = SkipAd, + Stop = 10, + kMaxValue = Stop, }; MediaSessionUmaHelper();
diff --git a/content/browser/renderer_host/delegated_frame_host.cc b/content/browser/renderer_host/delegated_frame_host.cc index 51d3755..448d0b5 100644 --- a/content/browser/renderer_host/delegated_frame_host.cc +++ b/content/browser/renderer_host/delegated_frame_host.cc
@@ -58,14 +58,8 @@ ImageTransportFactory* factory = ImageTransportFactory::GetInstance(); factory->GetContextFactory()->AddObserver(this); DCHECK(host_frame_sink_manager_); - viz::ReportFirstSurfaceActivation should_report_first_surface_activation = - viz::ReportFirstSurfaceActivation::kNo; -#ifdef OS_CHROMEOS - should_report_first_surface_activation = - viz::ReportFirstSurfaceActivation::kYes; -#endif host_frame_sink_manager_->RegisterFrameSinkId( - frame_sink_id_, this, should_report_first_surface_activation); + frame_sink_id_, this, viz::ReportFirstSurfaceActivation::kNo); host_frame_sink_manager_->EnableSynchronizationReporting( frame_sink_id_, "Compositing.MainFrameSynchronization.Duration"); host_frame_sink_manager_->SetFrameSinkDebugLabel(frame_sink_id_, @@ -278,15 +272,10 @@ return; } -#ifdef OS_CHROMEOS - if (seen_first_activation_) - frame_evictor_->OnNewSurfaceEmbedded(); -#else // Ignore empty frames. Extensions often create empty background page frames // which shouldn't count against the saved frames. if (!new_dip_size.IsEmpty()) frame_evictor_->OnNewSurfaceEmbedded(); -#endif if (!primary_surface_id || primary_surface_id->local_surface_id() != local_surface_id_) { @@ -352,13 +341,7 @@ void DelegatedFrameHost::OnFirstSurfaceActivation( const viz::SurfaceInfo& surface_info) { -#ifdef OS_CHROMEOS - if (!seen_first_activation_) - frame_evictor_->OnNewSurfaceEmbedded(); - seen_first_activation_ = true; -#else NOTREACHED(); -#endif } void DelegatedFrameHost::OnFrameTokenChanged(uint32_t frame_token) {
diff --git a/content/browser/renderer_host/delegated_frame_host.h b/content/browser/renderer_host/delegated_frame_host.h index a55a1b22..5c42110 100644 --- a/content/browser/renderer_host/delegated_frame_host.h +++ b/content/browser/renderer_host/delegated_frame_host.h
@@ -240,10 +240,6 @@ viz::LocalSurfaceId first_local_surface_id_after_navigation_; -#ifdef OS_CHROMEOS - bool seen_first_activation_ = false; -#endif - enum class FrameEvictionState { kNotStarted = 0, // Frame eviction is ready. kPendingEvictionRequests // Frame eviction is paused with pending requests.
diff --git a/content/browser/renderer_host/render_widget_host_view_aura_browsertest.cc b/content/browser/renderer_host/render_widget_host_view_aura_browsertest.cc index cba3ee9..c2fec194 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura_browsertest.cc +++ b/content/browser/renderer_host/render_widget_host_view_aura_browsertest.cc
@@ -82,9 +82,10 @@ StaleFrameContentOnEvictionNormal) { NavigateToURL(shell(), GURL(kMinimalPageDataURL)); - // Wait for first frame activation when a surface is embedded. - while (!GetDelegatedFrameHost()->HasSavedFrame()) - GiveItSomeTime(); + // Make sure the renderer submits at least one frame before hiding it. + RenderFrameSubmissionObserver submission_observer(shell()->web_contents()); + if (!submission_observer.render_frame_count()) + submission_observer.WaitForAnyFrameSubmission(); FakeWebContentsDelegate delegate; delegate.SetShowStaleContentOnEviction(true);
diff --git a/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc b/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc index 1d12735e..eaea10d 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc +++ b/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc
@@ -3515,13 +3515,6 @@ views[i]->GetNativeView(), parent_view_->GetNativeView()->GetRootWindow(), gfx::Rect()); views[i]->SetSize(view_rect.size()); -#ifdef OS_CHROMEOS - viz::SurfaceId surface_id( - views[i]->GetFrameSinkId(), - views[i]->GetLocalSurfaceIdAllocation().local_surface_id()); - views[i]->delegated_frame_host_->OnFirstSurfaceActivation( - viz::SurfaceInfo(surface_id, 1.f, view_rect.size())); -#endif EXPECT_HAS_FRAME(views[i]); } @@ -3634,13 +3627,6 @@ gfx::Rect()); views[i]->SetSize(view_rect.size()); views[i]->Show(); -#ifdef OS_CHROMEOS - viz::SurfaceId surface_id( - views[i]->GetFrameSinkId(), - views[i]->GetLocalSurfaceIdAllocation().local_surface_id()); - views[i]->delegated_frame_host_->OnFirstSurfaceActivation( - viz::SurfaceInfo(surface_id, 1.f, view_rect.size())); -#endif EXPECT_HAS_FRAME(views[i]); } @@ -5749,13 +5735,6 @@ viz::LocalSurfaceId id1 = view_->GetLocalSurfaceIdAllocation().local_surface_id(); view_->Hide(); -#ifdef OS_CHROMEOS - viz::SurfaceId surface_id( - view_->GetFrameSinkId(), - view_->GetLocalSurfaceIdAllocation().local_surface_id()); - view_->delegated_frame_host_->OnFirstSurfaceActivation( - viz::SurfaceInfo(surface_id, 1.f, gfx::Size(10, 10))); -#endif static_cast<viz::FrameEvictorClient*>(view_->delegated_frame_host_.get()) ->EvictDelegatedFrame(); view_->Show();
diff --git a/content/browser/service_manager/service_manager_context.cc b/content/browser/service_manager/service_manager_context.cc index 843b9b3..377a9584 100644 --- a/content/browser/service_manager/service_manager_context.cc +++ b/content/browser/service_manager/service_manager_context.cc
@@ -55,6 +55,7 @@ #include "mojo/public/cpp/platform/platform_channel.h" #include "mojo/public/cpp/system/invitation.h" #include "services/audio/public/mojom/constants.mojom.h" +#include "services/audio/service.h" #include "services/audio/service_factory.h" #include "services/data_decoder/public/mojom/constants.mojom.h" #include "services/device/device_service.h" @@ -364,7 +365,7 @@ mojo::PendingReceiver<service_manager::mojom::Service>* receiver) { if (!AudioServiceOutOfProcess() && identity.name() == audio::mojom::kServiceName) { - CreateInProcessAudioService(ServiceManagerContext::GetAudioServiceRunner(), + CreateInProcessAudioService(audio::Service::GetInProcessTaskRunner(), std::move(*receiver)); return; } @@ -516,7 +517,7 @@ private: friend class base::RefCountedThreadSafe<InProcessServiceManagerContext>; - ~InProcessServiceManagerContext() {} + ~InProcessServiceManagerContext() = default; void StartOnServiceManagerThread( std::vector<service_manager::Manifest> manifests, @@ -732,28 +733,6 @@ return iter->second->GetData().GetProcess().IsValid(); } -// static -void ServiceManagerContext::StartBrowserConnection() { - auto* system_connection = ServiceManagerConnection::GetForProcess(); - RegisterCommonBrowserInterfaces(system_connection); - system_connection->Start(); - - if (base::FeatureList::IsEnabled(network::features::kNetworkService)) - return; - - // Create the in-process NetworkService object so that its getter is - // available on the IO thread. - GetNetworkService(); -} - -// static -base::DeferredSequencedTaskRunner* -ServiceManagerContext::GetAudioServiceRunner() { - static base::NoDestructor<scoped_refptr<base::DeferredSequencedTaskRunner>> - instance(new base::DeferredSequencedTaskRunner); - return (*instance).get(); -} - void ServiceManagerContext::RunServiceInstance( const service_manager::Identity& identity, mojo::PendingReceiver<service_manager::mojom::Service> receiver) {
diff --git a/content/browser/service_manager/service_manager_context.h b/content/browser/service_manager/service_manager_context.h index d6ab742..540e083bd 100644 --- a/content/browser/service_manager/service_manager_context.h +++ b/content/browser/service_manager/service_manager_context.h
@@ -18,10 +18,6 @@ #include "services/service_manager/public/cpp/identity.h" #include "services/service_manager/public/mojom/service.mojom.h" -namespace base { -class DeferredSequencedTaskRunner; -} - namespace service_manager { class Connector; } @@ -45,12 +41,6 @@ static bool HasValidProcessForProcessGroup( const std::string& process_group_name); - // Starts the browser connction to the ServiceManager. It must be called after - // the BrowserMainLoop starts. - static void StartBrowserConnection(); - - static base::DeferredSequencedTaskRunner* GetAudioServiceRunner(); - // Shutdowns the ServiceManager and the connections to the ServiceManager. void ShutDown();
diff --git a/content/browser/startup_data_impl.h b/content/browser/startup_data_impl.h index b239702..d86706b 100644 --- a/content/browser/startup_data_impl.h +++ b/content/browser/startup_data_impl.h
@@ -7,22 +7,23 @@ #include <memory> +#include "base/callback.h" #include "base/power_monitor/power_monitor.h" #include "content/browser/browser_process_sub_thread.h" #include "content/common/content_export.h" #include "content/public/browser/startup_data.h" +#include "mojo/core/embedder/scoped_ipc_support.h" namespace content { -class ServiceManagerContext; - // The browser implementation of StartupData. struct CONTENT_EXPORT StartupDataImpl : public StartupData { StartupDataImpl(); ~StartupDataImpl() override; - std::unique_ptr<BrowserProcessSubThread> thread; - ServiceManagerContext* service_manager_context; + std::unique_ptr<BrowserProcessSubThread> ipc_thread; + std::unique_ptr<mojo::core::ScopedIPCSupport> mojo_ipc_support; + base::OnceClosure service_manager_shutdown_closure; std::unique_ptr<base::PowerMonitor> power_monitor; };
diff --git a/content/browser/system_connector_impl.cc b/content/browser/system_connector_impl.cc new file mode 100644 index 0000000..7cbacd2 --- /dev/null +++ b/content/browser/system_connector_impl.cc
@@ -0,0 +1,70 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/browser/system_connector_impl.h" + +#include "base/logging.h" +#include "base/no_destructor.h" +#include "base/task/post_task.h" +#include "base/threading/sequence_local_storage_slot.h" +#include "content/public/browser/browser_task_traits.h" +#include "content/public/browser/browser_thread.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "mojo/public/cpp/bindings/pending_remote.h" + +namespace content { + +namespace { + +base::SequenceLocalStorageSlot<service_manager::Connector>& +GetConnectorStorage() { + static base::NoDestructor< + base::SequenceLocalStorageSlot<service_manager::Connector>> + storage; + return *storage; +} + +void BindReceiverOnMainThread( + mojo::PendingReceiver<service_manager::mojom::Connector> receiver) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + auto* main_thread_connector = GetSystemConnector(); + DCHECK(main_thread_connector) + << "GetSystemConnector() called on background thread with no system " + << "Connector set on the main thread. If this is a unit test " + << "environment, consider calling SetSystemConnectorForTesting in test " + "setup."; + main_thread_connector->BindConnectorRequest(std::move(receiver)); +} + +} // namespace + +service_manager::Connector* GetSystemConnector() { + auto& storage = GetConnectorStorage(); + if (BrowserThread::CurrentlyOn(BrowserThread::UI)) + return storage.GetValuePointer(); + + if (!storage) { + mojo::PendingRemote<service_manager::mojom::Connector> remote; + base::PostTaskWithTraits( + FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&BindReceiverOnMainThread, + remote.InitWithNewPipeAndPassReceiver())); + storage.emplace(std::move(remote)); + } + + return storage.GetValuePointer(); +} + +void SetSystemConnector(std::unique_ptr<service_manager::Connector> connector) { + mojo::PendingRemote<service_manager::mojom::Connector> remote; + connector->BindConnectorRequest(remote.InitWithNewPipeAndPassReceiver()); + GetConnectorStorage().emplace(std::move(remote)); +} + +void SetSystemConnectorForTesting( + std::unique_ptr<service_manager::Connector> connector) { + SetSystemConnector(std::move(connector)); +} + +} // namespace content
diff --git a/content/browser/system_connector_impl.h b/content/browser/system_connector_impl.h new file mode 100644 index 0000000..a61f0a5 --- /dev/null +++ b/content/browser/system_connector_impl.h
@@ -0,0 +1,20 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_SYSTEM_CONNECTOR_IMPL_H_ +#define CONTENT_BROWSER_SYSTEM_CONNECTOR_IMPL_H_ + +#include "content/public/browser/system_connector.h" +#include "services/service_manager/public/cpp/connector.h" + +namespace content { + +// Sets the system Connector on the main thread. Called very early in browser +// process startup (i.e. before BrowserMainLoop is instantiated). For unit test +// environments, see |SetSystemConnectorForTesting()| in the public header. +void SetSystemConnector(std::unique_ptr<service_manager::Connector> connector); + +} // namespace content + +#endif // CONTENT_BROWSER_SYSTEM_CONNECTOR_IMPL_H_
diff --git a/content/child/runtime_features.cc b/content/child/runtime_features.cc index f25500a1..9c2457e3 100644 --- a/content/child/runtime_features.cc +++ b/content/child/runtime_features.cc
@@ -533,6 +533,9 @@ features::kPauseExecutionContextOnBackgroundFreeze)) { WebRuntimeFeatures::EnablePauseExecutionContextOnBackgroundFreeze(false); } + + WebRuntimeFeatures::EnableConsolidatedMovementXY( + base::FeatureList::IsEnabled(features::kConsolidatedMovementXY)); } } // namespace
diff --git a/content/gpu/gpu_main.cc b/content/gpu/gpu_main.cc index bf47f47..35be2f6 100644 --- a/content/gpu/gpu_main.cc +++ b/content/gpu/gpu_main.cc
@@ -9,6 +9,7 @@ #include <utility> #include "base/bind.h" +#include "base/feature_list.h" #include "base/lazy_instance.h" #include "base/metrics/histogram_macros.h" #include "base/rand_util.h" @@ -34,6 +35,7 @@ #include "content/public/gpu/content_gpu_client.h" #include "gpu/command_buffer/service/gpu_switches.h" #include "gpu/config/gpu_driver_bug_list.h" +#include "gpu/config/gpu_finch_features.h" #include "gpu/config/gpu_info_collector.h" #include "gpu/config/gpu_preferences.h" #include "gpu/config/gpu_switches.h" @@ -294,10 +296,11 @@ base::PlatformThread::SetName("CrGpuMain"); -#if defined(OS_ANDROID) || defined(OS_CHROMEOS) || defined(USE_OZONE) - // Set thread priority before sandbox initialization. - base::PlatformThread::SetCurrentThreadPriority(base::ThreadPriority::DISPLAY); -#endif + if (base::FeatureList::IsEnabled(features::kGpuUseDisplayThreadPriority)) { + // Set thread priority before sandbox initialization. + base::PlatformThread::SetCurrentThreadPriority( + base::ThreadPriority::DISPLAY); + } auto gpu_init = std::make_unique<gpu::GpuInit>(); ContentSandboxHelper sandbox_helper; @@ -326,11 +329,10 @@ logging::SetLogMessageHandler(nullptr); GetContentClient()->SetGpuInfo(gpu_init->gpu_info()); - base::ThreadPriority io_thread_priority = base::ThreadPriority::NORMAL; -#if defined(OS_ANDROID) || defined(OS_CHROMEOS) || defined(USE_OZONE) - io_thread_priority = base::ThreadPriority::DISPLAY; -#endif - + const base::ThreadPriority io_thread_priority = + base::FeatureList::IsEnabled(features::kGpuUseDisplayThreadPriority) + ? base::ThreadPriority::DISPLAY + : base::ThreadPriority::NORMAL; GpuProcess gpu_process(io_thread_priority); auto* client = GetContentClient()->gpu();
diff --git a/content/public/browser/BUILD.gn b/content/public/browser/BUILD.gn index 0d28e89..3c1a0ac 100644 --- a/content/public/browser/BUILD.gn +++ b/content/public/browser/BUILD.gn
@@ -305,6 +305,7 @@ "stored_payment_app.cc", "stored_payment_app.h", "swap_metrics_driver.h", + "system_connector.h", "touch_selection_controller_client_manager.h", "trace_uploader.h", "tracing_controller.h",
diff --git a/content/public/browser/browser_main_parts.h b/content/public/browser/browser_main_parts.h index 0aaff18..e4727f3 100644 --- a/content/public/browser/browser_main_parts.h +++ b/content/public/browser/browser_main_parts.h
@@ -10,8 +10,6 @@ namespace content { -class ServiceManagerConnection; - // This class contains different "stages" to be executed by |BrowserMain()|, // Each stage is represented by a single BrowserMainParts method, called from // the corresponding method in |BrowserMainLoop| (e.g., EarlyInitialization()) @@ -79,9 +77,6 @@ // are created. virtual void PostCreateThreads() {} - virtual void ServiceManagerConnectionStarted( - ServiceManagerConnection* connection) {} - // This is called just before the main message loop is run. The // various browser threads have all been created at this point virtual void PreMainMessageLoopRun() {}
diff --git a/content/public/browser/system_connector.h b/content/public/browser/system_connector.h new file mode 100644 index 0000000..8813457 --- /dev/null +++ b/content/public/browser/system_connector.h
@@ -0,0 +1,30 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_PUBLIC_BROWSER_SYSTEM_CONNECTOR_H_ +#define CONTENT_PUBLIC_BROWSER_SYSTEM_CONNECTOR_H_ + +#include "content/common/content_export.h" +#include "services/service_manager/public/cpp/connector.h" + +namespace content { + +// Returns a Connector which can be used to connect to service interfaces from +// the browser process. May return null in unit testing environments. +// The system Connector can be overridden for tests using the +// |SetSystemConnectorForTesting()| below. +// +// This function is safe to call from any thread, but the returned pointer is +// different on each thread and is NEVER safe to retain or pass across threads. +CONTENT_EXPORT service_manager::Connector* GetSystemConnector(); + +// Overrides the system Connector for test environments where Content's regular +// Service Manager environment is not set up. Must be called from the main +// thread. +CONTENT_EXPORT void SetSystemConnectorForTesting( + std::unique_ptr<service_manager::Connector> connector); + +} // namespace content + +#endif // CONTENT_PUBLIC_BROWSER_SYSTEM_CONNECTOR_H_
diff --git a/content/public/common/content_features.cc b/content/public/common/content_features.cc index 83b489b..333ce5b 100644 --- a/content/public/common/content_features.cc +++ b/content/public/common/content_features.cc
@@ -129,6 +129,10 @@ const base::Feature kCompositeOpaqueScrollers{"CompositeOpaqueScrollers", base::FEATURE_ENABLED_BY_DEFAULT}; +// When enabled, event.movement is calculated in blink instead of in browser. +const base::Feature kConsolidatedMovementXY{"ConsolidatedMovementXY", + base::FEATURE_DISABLED_BY_DEFAULT}; + // Show messages in the DevTools console about upcoming deprecations // that would affect sent/received cookies. const base::Feature kCookieDeprecationMessages{
diff --git a/content/public/common/content_features.h b/content/public/common/content_features.h index eceeec34..0af9f7c 100644 --- a/content/public/common/content_features.h +++ b/content/public/common/content_features.h
@@ -37,6 +37,7 @@ CONTENT_EXPORT extern const base::Feature kCanvas2DImageChromium; CONTENT_EXPORT extern const base::Feature kCompositeOpaqueFixedPosition; CONTENT_EXPORT extern const base::Feature kCompositeOpaqueScrollers; +CONTENT_EXPORT extern const base::Feature kConsolidatedMovementXY; CONTENT_EXPORT extern const base::Feature kCookieDeprecationMessages; CONTENT_EXPORT extern const base::Feature kCrashReporting; CONTENT_EXPORT extern const base::Feature kDataSaverHoldback;
diff --git a/content/public/test/browser_test_base.cc b/content/public/test/browser_test_base.cc index 88fe345..68a2523 100644 --- a/content/public/test/browser_test_base.cc +++ b/content/public/test/browser_test_base.cc
@@ -25,9 +25,11 @@ #include "base/test/test_timeouts.h" #include "base/threading/thread_restrictions.h" #include "build/build_config.h" +#include "content/browser/browser_main_loop.h" #include "content/browser/browser_thread_impl.h" #include "content/browser/renderer_host/render_process_host_impl.h" #include "content/browser/scheduler/browser_task_executor.h" +#include "content/browser/startup_data_impl.h" #include "content/browser/startup_helper.h" #include "content/browser/tracing/tracing_controller_impl.h" #include "content/public/app/content_main.h" @@ -61,6 +63,7 @@ #if defined(OS_ANDROID) #include "components/discardable_memory/service/discardable_shared_memory_manager.h" // nogncheck #include "content/app/mojo/mojo_init.h" +#include "content/app/service_manager_environment.h" #include "content/common/url_schemes.h" #include "content/public/app/content_main_delegate.h" #include "content/public/common/content_paths.h" @@ -398,6 +401,10 @@ discardable_shared_memory_manager_ = std::make_unique<discardable_memory::DiscardableSharedMemoryManager>(); + service_manager_environment_ = std::make_unique<ServiceManagerEnvironment>( + BrowserTaskExecutor::CreateIOThread()); + auto startup_data = service_manager_environment_->CreateBrowserStartupData(); + // ContentMain would normally call RunProcess() on the delegate and fallback // to BrowserMain() if it did not run it (or equivalent) itself. On Android, // RunProcess() will return 0 so we don't have to fallback to BrowserMain(). @@ -405,6 +412,7 @@ MainFunctionParams params(*command_line); params.ui_task = ui_task.release(); params.created_main_parts_closure = created_main_parts_closure.release(); + params.startup_data = startup_data.get(); // Passing "" as the process type to indicate the browser process. int exit_code = delegate->RunProcess("", params); DCHECK_EQ(exit_code, 0); @@ -415,6 +423,8 @@ // for the test harness to be able to delete temp dirs. base::ThreadRestrictions::SetIOAllowed(true); + BrowserMainLoop::GetInstance()->ShutdownThreadsAndCleanUp(); + BrowserTaskExecutor::ResetForTesting(); #else GetContentMainParams()->ui_task = ui_task.release();
diff --git a/content/public/test/browser_test_base.h b/content/public/test/browser_test_base.h index cb2c6e8d..d2ad9f1 100644 --- a/content/public/test/browser_test_base.h +++ b/content/public/test/browser_test_base.h
@@ -31,6 +31,7 @@ namespace content { class BrowserMainParts; +class ServiceManagerEnvironment; class WebContents; class BrowserTestBase : public testing::Test { @@ -168,9 +169,10 @@ #if defined(OS_ANDROID) // On Android we don't use ContentMainRunner for browser tests, so we bring - // our own DiscardableSharedMemoryManager instance. + // our own DiscardableSharedMemoryManager and ServiceManagerEnvironment. std::unique_ptr<discardable_memory::DiscardableSharedMemoryManager> discardable_shared_memory_manager_; + std::unique_ptr<ServiceManagerEnvironment> service_manager_environment_; #endif // Testing server, started on demand.
diff --git a/content/public/test/test_service_manager_context.cc b/content/public/test/test_service_manager_context.cc index fba365b9..011e1b2 100644 --- a/content/public/test/test_service_manager_context.cc +++ b/content/public/test/test_service_manager_context.cc
@@ -13,17 +13,15 @@ namespace content { TestServiceManagerContext::TestServiceManagerContext() { - // Isolate from previous tests that may have already initialized - // ServiceManagerConnection (e.g. in - // RenderProcessHostImpl::InitializeChannelProxy()). - ServiceManagerConnection::DestroyForProcess(); context_.reset(new ServiceManagerContext( base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}))); - ServiceManagerContext::StartBrowserConnection(); + auto* system_connection = ServiceManagerConnection::GetForProcess(); + system_connection->Start(); } TestServiceManagerContext::~TestServiceManagerContext() { ChildProcessLauncher::ResetRegisteredFilesForTesting(); + ServiceManagerConnection::DestroyForProcess(); } } // namespace content
diff --git a/content/renderer/categorized_worker_pool.cc b/content/renderer/categorized_worker_pool.cc index c5bf882..c5e02ef 100644 --- a/content/renderer/categorized_worker_pool.cc +++ b/content/renderer/categorized_worker_pool.cc
@@ -169,6 +169,9 @@ foreground_categories.push_back(cc::TASK_CATEGORY_FOREGROUND); for (int i = 0; i < num_threads; i++) { + base::SimpleThread::Options thread_options; + // Use same priority for foreground workers as compositor thread. + thread_options.priority = base::PlatformThread::GetCurrentThreadPriority(); std::unique_ptr<base::SimpleThread> thread(new CategorizedWorkerPoolThread( base::StringPrintf("CompositorTileWorker%d", i + 1).c_str(), base::SimpleThread::Options(), this, foreground_categories,
diff --git a/content/renderer/media/stream/media_stream_audio_processor_unittest.cc b/content/renderer/media/stream/media_stream_audio_processor_unittest.cc index 4540641..5d878dc1 100644 --- a/content/renderer/media/stream/media_stream_audio_processor_unittest.cc +++ b/content/renderer/media/stream/media_stream_audio_processor_unittest.cc
@@ -21,7 +21,6 @@ #include "base/time/time.h" #include "build/build_config.h" #include "content/renderer/media/stream/media_stream_audio_processor.h" -#include "content/renderer/media/stream/mock_constraint_factory.h" #include "media/base/audio_bus.h" #include "media/base/audio_parameters.h" #include "testing/gmock/include/gmock/gmock.h" @@ -30,6 +29,7 @@ #include "third_party/blink/public/platform/modules/mediastream/media_stream_audio_processor_options.h" #include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h" #include "third_party/blink/public/platform/web_media_constraints.h" +#include "third_party/blink/public/web/modules/mediastream/mock_constraint_factory.h" #include "third_party/webrtc/api/media_stream_interface.h" #include "third_party/webrtc/rtc_base/ref_counted_object.h"
diff --git a/content/renderer/media/stream/media_stream_constraints_util_audio_unittest.cc b/content/renderer/media/stream/media_stream_constraints_util_audio_unittest.cc index 16c7d62..235d2a3f 100644 --- a/content/renderer/media/stream/media_stream_constraints_util_audio_unittest.cc +++ b/content/renderer/media/stream/media_stream_constraints_util_audio_unittest.cc
@@ -15,7 +15,6 @@ #include "base/test/scoped_task_environment.h" #include "build/build_config.h" #include "content/renderer/media/stream/local_media_stream_audio_source.h" -#include "content/renderer/media/stream/mock_constraint_factory.h" #include "content/renderer/media/stream/processed_local_audio_source.h" #include "content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h" #include "media/base/audio_parameters.h" @@ -26,6 +25,7 @@ #include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h" #include "third_party/blink/public/platform/web_media_constraints.h" #include "third_party/blink/public/platform/web_string.h" +#include "third_party/blink/public/web/modules/mediastream/mock_constraint_factory.h" namespace content { @@ -39,14 +39,15 @@ using StringSetFunction = void (blink::StringConstraint::*)(const blink::WebString&); using MockFactoryAccessor = - blink::WebMediaTrackConstraintSet& (MockConstraintFactory::*)(); + blink::WebMediaTrackConstraintSet& (blink::MockConstraintFactory::*)(); const BoolSetFunction kBoolSetFunctions[] = { &blink::BooleanConstraint::SetExact, &blink::BooleanConstraint::SetIdeal, }; const MockFactoryAccessor kFactoryAccessors[] = { - &MockConstraintFactory::basic, &MockConstraintFactory::AddAdvanced}; + &blink::MockConstraintFactory::basic, + &blink::MockConstraintFactory::AddAdvanced}; const bool kBoolValues[] = {true, false}; @@ -401,7 +402,7 @@ expected_buffer_size); } - MockConstraintFactory constraint_factory_; + blink::MockConstraintFactory constraint_factory_; AudioDeviceCaptureCapabilities capabilities_; const AudioDeviceCaptureCapability* default_device_ = nullptr; const AudioDeviceCaptureCapability* system_echo_canceller_device_ = nullptr;
diff --git a/content/renderer/media/stream/media_stream_constraints_util_video_content_unittest.cc b/content/renderer/media/stream/media_stream_constraints_util_video_content_unittest.cc index d311c92f..56fc540c 100644 --- a/content/renderer/media/stream/media_stream_constraints_util_video_content_unittest.cc +++ b/content/renderer/media/stream/media_stream_constraints_util_video_content_unittest.cc
@@ -8,22 +8,21 @@ #include <string> #include "base/stl_util.h" -#include "content/renderer/media/stream/mock_constraint_factory.h" #include "media/base/limits.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/modules/mediastream/web_platform_media_stream_source.h" #include "third_party/blink/public/platform/web_media_constraints.h" +#include "third_party/blink/public/web/modules/mediastream/mock_constraint_factory.h" -namespace content { +namespace blink { namespace { const double kDefaultScreenCastAspectRatio = - static_cast<double>(blink::kDefaultScreenCastWidth) / - blink::kDefaultScreenCastHeight; + static_cast<double>(kDefaultScreenCastWidth) / kDefaultScreenCastHeight; -void CheckNonResolutionDefaults(const blink::VideoCaptureSettings& result) { - EXPECT_EQ(blink::kDefaultScreenCastFrameRate, result.FrameRate()); +void CheckNonResolutionDefaults(const VideoCaptureSettings& result) { + EXPECT_EQ(kDefaultScreenCastFrameRate, result.FrameRate()); EXPECT_EQ(base::Optional<double>(), result.min_frame_rate()); EXPECT_EQ(base::Optional<double>(), result.max_frame_rate()); EXPECT_EQ(base::Optional<bool>(), result.noise_reduction()); @@ -31,15 +30,14 @@ EXPECT_FALSE(result.min_frame_rate().has_value()); } -void CheckNonFrameRateDefaults(const blink::VideoCaptureSettings& result) { - EXPECT_EQ(blink::kDefaultScreenCastHeight, result.Height()); - EXPECT_EQ(blink::kDefaultScreenCastWidth, result.Width()); +void CheckNonFrameRateDefaults(const VideoCaptureSettings& result) { + EXPECT_EQ(kDefaultScreenCastHeight, result.Height()); + EXPECT_EQ(kDefaultScreenCastWidth, result.Width()); EXPECT_EQ(base::Optional<bool>(), result.noise_reduction()); EXPECT_EQ(std::string(), result.device_id()); } -void CheckTrackAdapterSettingsEqualsFormat( - const blink::VideoCaptureSettings& result) { +void CheckTrackAdapterSettingsEqualsFormat(const VideoCaptureSettings& result) { // For content capture, resolution and frame rate should always be the same // for source and track. EXPECT_TRUE(result.track_adapter_settings().target_size().has_value()); @@ -49,13 +47,13 @@ } void CheckTrackAdapterSettingsEqualsFormatDefaultAspectRatio( - const blink::VideoCaptureSettings& result) { - EXPECT_EQ(static_cast<double>(blink::kMinScreenCastDimension) / - blink::kMaxScreenCastDimension, - result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(blink::kMaxScreenCastDimension) / - blink::kMinScreenCastDimension, - result.track_adapter_settings().max_aspect_ratio()); + const VideoCaptureSettings& result) { + EXPECT_EQ( + static_cast<double>(kMinScreenCastDimension) / kMaxScreenCastDimension, + result.track_adapter_settings().min_aspect_ratio()); + EXPECT_EQ( + static_cast<double>(kMaxScreenCastDimension) / kMinScreenCastDimension, + result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -63,14 +61,14 @@ class MediaStreamConstraintsUtilVideoContentTest : public testing::Test { protected: - blink::VideoCaptureSettings SelectSettings( - blink::mojom::MediaStreamType stream_type = - blink::mojom::MediaStreamType::GUM_DESKTOP_VIDEO_CAPTURE) { - blink::WebMediaConstraints constraints = + VideoCaptureSettings SelectSettings( + mojom::MediaStreamType stream_type = + mojom::MediaStreamType::GUM_DESKTOP_VIDEO_CAPTURE) { + WebMediaConstraints constraints = constraint_factory_.CreateWebMediaConstraints(); - return blink::SelectSettingsVideoContentCapture( - constraints, stream_type, blink::kDefaultScreenCastWidth, - blink::kDefaultScreenCastHeight); + return SelectSettingsVideoContentCapture(constraints, stream_type, + kDefaultScreenCastWidth, + kDefaultScreenCastHeight); } MockConstraintFactory constraint_factory_; @@ -83,8 +81,8 @@ // All settings should have default values. EXPECT_TRUE(result.HasValue()); - EXPECT_EQ(blink::kDefaultScreenCastHeight, result.Height()); - EXPECT_EQ(blink::kDefaultScreenCastWidth, result.Width()); + EXPECT_EQ(kDefaultScreenCastHeight, result.Height()); + EXPECT_EQ(kDefaultScreenCastWidth, result.Width()); CheckNonResolutionDefaults(result); CheckTrackAdapterSettingsEqualsFormatDefaultAspectRatio(result); } @@ -93,22 +91,21 @@ // constraint results in failure to select a candidate. TEST_F(MediaStreamConstraintsUtilVideoContentTest, OverconstrainedOnHeight) { constraint_factory_.Reset(); - constraint_factory_.basic().height.SetExact(blink::kMaxScreenCastDimension + - 1); + constraint_factory_.basic().height.SetExact(kMaxScreenCastDimension + 1); auto result = SelectSettings(); EXPECT_FALSE(result.HasValue()); EXPECT_EQ(constraint_factory_.basic().height.GetName(), result.failed_constraint_name()); constraint_factory_.Reset(); - constraint_factory_.basic().height.SetMin(blink::kMaxScreenCastDimension + 1); + constraint_factory_.basic().height.SetMin(kMaxScreenCastDimension + 1); result = SelectSettings(); EXPECT_FALSE(result.HasValue()); EXPECT_EQ(constraint_factory_.basic().height.GetName(), result.failed_constraint_name()); constraint_factory_.Reset(); - constraint_factory_.basic().height.SetMax(blink::kMinScreenCastDimension - 1); + constraint_factory_.basic().height.SetMax(kMinScreenCastDimension - 1); result = SelectSettings(); EXPECT_FALSE(result.HasValue()); EXPECT_EQ(constraint_factory_.basic().height.GetName(), @@ -117,22 +114,21 @@ TEST_F(MediaStreamConstraintsUtilVideoContentTest, OverconstrainedOnWidth) { constraint_factory_.Reset(); - constraint_factory_.basic().width.SetExact(blink::kMaxScreenCastDimension + - 1); + constraint_factory_.basic().width.SetExact(kMaxScreenCastDimension + 1); auto result = SelectSettings(); EXPECT_FALSE(result.HasValue()); EXPECT_EQ(constraint_factory_.basic().width.GetName(), result.failed_constraint_name()); constraint_factory_.Reset(); - constraint_factory_.basic().width.SetMin(blink::kMaxScreenCastDimension + 1); + constraint_factory_.basic().width.SetMin(kMaxScreenCastDimension + 1); result = SelectSettings(); EXPECT_FALSE(result.HasValue()); EXPECT_EQ(constraint_factory_.basic().width.GetName(), result.failed_constraint_name()); constraint_factory_.Reset(); - constraint_factory_.basic().width.SetMax(blink::kMinScreenCastDimension - 1); + constraint_factory_.basic().width.SetMax(kMinScreenCastDimension - 1); result = SelectSettings(); EXPECT_FALSE(result.HasValue()); EXPECT_EQ(constraint_factory_.basic().width.GetName(), @@ -165,16 +161,15 @@ TEST_F(MediaStreamConstraintsUtilVideoContentTest, OverconstrainedOnFrameRate) { constraint_factory_.Reset(); - constraint_factory_.basic().frame_rate.SetExact( - blink::kMaxScreenCastFrameRate + 0.1); + constraint_factory_.basic().frame_rate.SetExact(kMaxScreenCastFrameRate + + 0.1); auto result = SelectSettings(); EXPECT_FALSE(result.HasValue()); EXPECT_EQ(constraint_factory_.basic().frame_rate.GetName(), result.failed_constraint_name()); constraint_factory_.Reset(); - constraint_factory_.basic().frame_rate.SetMin(blink::kMaxScreenCastFrameRate + - 0.1); + constraint_factory_.basic().frame_rate.SetMin(kMaxScreenCastFrameRate + 0.1); result = SelectSettings(); EXPECT_FALSE(result.HasValue()); EXPECT_EQ(constraint_factory_.basic().frame_rate.GetName(), @@ -192,7 +187,7 @@ OverconstrainedOnInvalidResizeMode) { constraint_factory_.Reset(); constraint_factory_.basic().resize_mode.SetExact( - blink::WebString::FromASCII("invalid")); + WebString::FromASCII("invalid")); auto result = SelectSettings(); EXPECT_FALSE(result.HasValue()); EXPECT_EQ(constraint_factory_.basic().resize_mode.GetName(), @@ -202,8 +197,7 @@ TEST_F(MediaStreamConstraintsUtilVideoContentTest, OverconstrainedOnEmptyResizeMode) { constraint_factory_.Reset(); - constraint_factory_.basic().resize_mode.SetExact( - blink::WebString::FromASCII("")); + constraint_factory_.basic().resize_mode.SetExact(WebString::FromASCII("")); auto result = SelectSettings(); EXPECT_FALSE(result.HasValue()); EXPECT_EQ(constraint_factory_.basic().resize_mode.GetName(), @@ -216,14 +210,14 @@ const std::string kDeviceID = "Some ID"; constraint_factory_.Reset(); constraint_factory_.basic().device_id.SetExact( - blink::WebString::FromASCII(kDeviceID)); + WebString::FromASCII(kDeviceID)); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); EXPECT_EQ(kDeviceID, result.device_id()); // Other settings should have default values. - EXPECT_EQ(blink::kDefaultScreenCastHeight, result.Height()); - EXPECT_EQ(blink::kDefaultScreenCastWidth, result.Width()); - EXPECT_EQ(blink::kDefaultScreenCastFrameRate, result.FrameRate()); + EXPECT_EQ(kDefaultScreenCastHeight, result.Height()); + EXPECT_EQ(kDefaultScreenCastWidth, result.Width()); + EXPECT_EQ(kDefaultScreenCastFrameRate, result.FrameRate()); EXPECT_EQ(base::Optional<bool>(), result.noise_reduction()); CheckTrackAdapterSettingsEqualsFormatDefaultAspectRatio(result); } @@ -231,23 +225,23 @@ TEST_F(MediaStreamConstraintsUtilVideoContentTest, IdealDeviceID) { const std::string kDeviceID = "Some ID"; const std::string kIdealID = "Ideal ID"; - blink::WebVector<blink::WebString> device_ids(static_cast<size_t>(2)); - device_ids[0] = blink::WebString::FromASCII(kDeviceID); - device_ids[1] = blink::WebString::FromASCII(kIdealID); + WebVector<WebString> device_ids(static_cast<size_t>(2)); + device_ids[0] = WebString::FromASCII(kDeviceID); + device_ids[1] = WebString::FromASCII(kIdealID); constraint_factory_.Reset(); constraint_factory_.basic().device_id.SetExact(device_ids); - blink::WebVector<blink::WebString> ideal_id(static_cast<size_t>(1)); - ideal_id[0] = blink::WebString::FromASCII(kIdealID); + WebVector<WebString> ideal_id(static_cast<size_t>(1)); + ideal_id[0] = WebString::FromASCII(kIdealID); constraint_factory_.basic().device_id.SetIdeal(ideal_id); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); EXPECT_EQ(kIdealID, result.device_id()); // Other settings should have default values. - EXPECT_EQ(blink::kDefaultScreenCastHeight, result.Height()); - EXPECT_EQ(blink::kDefaultScreenCastWidth, result.Width()); - EXPECT_EQ(blink::kDefaultScreenCastFrameRate, result.FrameRate()); + EXPECT_EQ(kDefaultScreenCastHeight, result.Height()); + EXPECT_EQ(kDefaultScreenCastWidth, result.Width()); + EXPECT_EQ(kDefaultScreenCastFrameRate, result.FrameRate()); EXPECT_EQ(base::Optional<bool>(), result.noise_reduction()); CheckTrackAdapterSettingsEqualsFormatDefaultAspectRatio(result); } @@ -261,9 +255,9 @@ EXPECT_TRUE(result.HasValue()); EXPECT_EQ(noise_reduction, result.noise_reduction()); // Other settings should have default values. - EXPECT_EQ(blink::kDefaultScreenCastHeight, result.Height()); - EXPECT_EQ(blink::kDefaultScreenCastWidth, result.Width()); - EXPECT_EQ(blink::kDefaultScreenCastFrameRate, result.FrameRate()); + EXPECT_EQ(kDefaultScreenCastHeight, result.Height()); + EXPECT_EQ(kDefaultScreenCastWidth, result.Width()); + EXPECT_EQ(kDefaultScreenCastFrameRate, result.FrameRate()); EXPECT_EQ(std::string(), result.device_id()); CheckTrackAdapterSettingsEqualsFormatDefaultAspectRatio(result); } @@ -278,9 +272,9 @@ EXPECT_TRUE(result.HasValue()); EXPECT_EQ(noise_reduction, result.noise_reduction()); // Other settings should have default values. - EXPECT_EQ(blink::kDefaultScreenCastHeight, result.Height()); - EXPECT_EQ(blink::kDefaultScreenCastWidth, result.Width()); - EXPECT_EQ(blink::kDefaultScreenCastFrameRate, result.FrameRate()); + EXPECT_EQ(kDefaultScreenCastHeight, result.Height()); + EXPECT_EQ(kDefaultScreenCastWidth, result.Width()); + EXPECT_EQ(kDefaultScreenCastFrameRate, result.FrameRate()); EXPECT_EQ(std::string(), result.device_id()); CheckTrackAdapterSettingsEqualsFormatDefaultAspectRatio(result); } @@ -298,7 +292,7 @@ result.Width()); CheckNonResolutionDefaults(result); EXPECT_EQ(1.0 / kHeight, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(blink::kMaxScreenCastDimension) / kHeight, + EXPECT_EQ(static_cast<double>(kMaxScreenCastDimension) / kHeight, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -314,9 +308,9 @@ EXPECT_EQ(std::round(kHeight * kDefaultScreenCastAspectRatio), result.Width()); CheckNonResolutionDefaults(result); - EXPECT_EQ(1.0 / blink::kMaxScreenCastDimension, + EXPECT_EQ(1.0 / kMaxScreenCastDimension, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(blink::kMaxScreenCastDimension) / kHeight, + EXPECT_EQ(static_cast<double>(kMaxScreenCastDimension) / kHeight, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); @@ -325,12 +319,12 @@ result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // kSmallHeight is less that the default, so expect the default. - EXPECT_EQ(blink::kDefaultScreenCastHeight, result.Height()); - EXPECT_EQ(blink::kDefaultScreenCastWidth, result.Width()); + EXPECT_EQ(kDefaultScreenCastHeight, result.Height()); + EXPECT_EQ(kDefaultScreenCastWidth, result.Width()); CheckNonResolutionDefaults(result); - EXPECT_EQ(1.0 / blink::kMaxScreenCastDimension, + EXPECT_EQ(1.0 / kMaxScreenCastDimension, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(blink::kMaxScreenCastDimension) / kSmallHeight, + EXPECT_EQ(static_cast<double>(kMaxScreenCastDimension) / kSmallHeight, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -339,7 +333,7 @@ // kMaxHeight smaller than the default. { constraint_factory_.Reset(); - const int kMaxHeight = blink::kDefaultScreenCastHeight - 100; + const int kMaxHeight = kDefaultScreenCastHeight - 100; constraint_factory_.basic().height.SetMax(kMaxHeight); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); @@ -349,7 +343,7 @@ CheckNonResolutionDefaults(result); EXPECT_EQ(1.0 / kMaxHeight, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(blink::kMaxScreenCastDimension, + EXPECT_EQ(kMaxScreenCastDimension, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -357,7 +351,7 @@ // kMaxHeight greater than the default. { constraint_factory_.Reset(); - const int kMaxHeight = blink::kDefaultScreenCastHeight + 100; + const int kMaxHeight = kDefaultScreenCastHeight + 100; constraint_factory_.basic().height.SetMax(kMaxHeight); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); @@ -367,7 +361,7 @@ CheckNonResolutionDefaults(result); EXPECT_EQ(1.0 / kMaxHeight, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(blink::kMaxScreenCastDimension, + EXPECT_EQ(kMaxScreenCastDimension, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -375,18 +369,17 @@ // kMaxHeight greater than the maximum allowed. { constraint_factory_.Reset(); - constraint_factory_.basic().height.SetMax(blink::kMaxScreenCastDimension + - 1); + constraint_factory_.basic().height.SetMax(kMaxScreenCastDimension + 1); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); - EXPECT_EQ(blink::kDefaultScreenCastHeight, result.Height()); - EXPECT_EQ(std::round(blink::kDefaultScreenCastHeight * - kDefaultScreenCastAspectRatio), - result.Width()); + EXPECT_EQ(kDefaultScreenCastHeight, result.Height()); + EXPECT_EQ( + std::round(kDefaultScreenCastHeight * kDefaultScreenCastAspectRatio), + result.Width()); CheckNonResolutionDefaults(result); - EXPECT_EQ(1.0 / blink::kMaxScreenCastDimension, + EXPECT_EQ(1.0 / kMaxScreenCastDimension, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(blink::kMaxScreenCastDimension, + EXPECT_EQ(kMaxScreenCastDimension, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -394,18 +387,18 @@ // kMaxHeight equal to the maximum allowed. { constraint_factory_.Reset(); - const int kMaxHeight = blink::kMaxScreenCastDimension; + const int kMaxHeight = kMaxScreenCastDimension; constraint_factory_.basic().height.SetMax(kMaxHeight); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); EXPECT_EQ(kMaxHeight, result.Height()); // Since the given max is too large, the default aspect ratio cannot be // used and the width is clamped to the maximum. - EXPECT_EQ(blink::kMaxScreenCastDimension, result.Width()); + EXPECT_EQ(kMaxScreenCastDimension, result.Width()); CheckNonResolutionDefaults(result); EXPECT_EQ(1.0 / kMaxHeight, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(blink::kMaxScreenCastDimension, + EXPECT_EQ(kMaxScreenCastDimension, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -415,8 +408,8 @@ // Range includes the default. { constraint_factory_.Reset(); - const int kMinHeight = blink::kDefaultScreenCastHeight - 100; - const int kMaxHeight = blink::kDefaultScreenCastHeight + 100; + const int kMinHeight = kDefaultScreenCastHeight - 100; + const int kMaxHeight = kDefaultScreenCastHeight + 100; constraint_factory_.basic().height.SetMin(kMinHeight); constraint_factory_.basic().height.SetMax(kMaxHeight); auto result = SelectSettings(); @@ -427,7 +420,7 @@ CheckNonResolutionDefaults(result); EXPECT_EQ(1.0 / kMaxHeight, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(blink::kMaxScreenCastDimension) / kMinHeight, + EXPECT_EQ(static_cast<double>(kMaxScreenCastDimension) / kMinHeight, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -435,8 +428,8 @@ // The whole range is greater than the default. { constraint_factory_.Reset(); - const int kMinHeight = blink::kDefaultScreenCastHeight + 100; - const int kMaxHeight = blink::kDefaultScreenCastHeight + 200; + const int kMinHeight = kDefaultScreenCastHeight + 100; + const int kMaxHeight = kDefaultScreenCastHeight + 200; constraint_factory_.basic().height.SetMin(kMinHeight); constraint_factory_.basic().height.SetMax(kMaxHeight); auto result = SelectSettings(); @@ -447,7 +440,7 @@ CheckNonResolutionDefaults(result); EXPECT_EQ(1.0 / kMaxHeight, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(blink::kMaxScreenCastDimension) / kMinHeight, + EXPECT_EQ(static_cast<double>(kMaxScreenCastDimension) / kMinHeight, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -455,8 +448,8 @@ // The whole range is less than the default. { constraint_factory_.Reset(); - const int kMinHeight = blink::kDefaultScreenCastHeight - 200; - const int kMaxHeight = blink::kDefaultScreenCastHeight - 100; + const int kMinHeight = kDefaultScreenCastHeight - 200; + const int kMaxHeight = kDefaultScreenCastHeight - 100; constraint_factory_.basic().height.SetMin(kMinHeight); constraint_factory_.basic().height.SetMax(kMaxHeight); auto result = SelectSettings(); @@ -467,7 +460,7 @@ CheckNonResolutionDefaults(result); EXPECT_EQ(1.0 / kMaxHeight, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(blink::kMaxScreenCastDimension) / kMinHeight, + EXPECT_EQ(static_cast<double>(kMaxScreenCastDimension) / kMinHeight, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -507,7 +500,7 @@ CheckNonResolutionDefaults(result); EXPECT_EQ(1.0 / kMaxHeight, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(blink::kMaxScreenCastDimension, + EXPECT_EQ(kMaxScreenCastDimension, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -527,9 +520,9 @@ EXPECT_EQ(std::round(kMinHeight * kDefaultScreenCastAspectRatio), result.Width()); CheckNonResolutionDefaults(result); - EXPECT_EQ(1.0 / blink::kMaxScreenCastDimension, + EXPECT_EQ(1.0 / kMaxScreenCastDimension, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(blink::kMaxScreenCastDimension) / kMinHeight, + EXPECT_EQ(static_cast<double>(kMaxScreenCastDimension) / kMinHeight, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -615,9 +608,9 @@ EXPECT_EQ(std::round(kWidth / kDefaultScreenCastAspectRatio), result.Height()); CheckNonResolutionDefaults(result); - EXPECT_EQ(static_cast<double>(kWidth) / blink::kMaxScreenCastDimension, + EXPECT_EQ(static_cast<double>(kWidth) / kMaxScreenCastDimension, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(kWidth) / blink::kMinScreenCastDimension, + EXPECT_EQ(static_cast<double>(kWidth) / kMinScreenCastDimension, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -633,11 +626,11 @@ EXPECT_EQ(std::round(kWidth / kDefaultScreenCastAspectRatio), result.Height()); CheckNonResolutionDefaults(result); - EXPECT_EQ(static_cast<double>(kWidth) / blink::kMaxScreenCastDimension, + EXPECT_EQ(static_cast<double>(kWidth) / kMaxScreenCastDimension, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(blink::kMaxScreenCastDimension) / - blink::kMinScreenCastDimension, - result.track_adapter_settings().max_aspect_ratio()); + EXPECT_EQ( + static_cast<double>(kMaxScreenCastDimension) / kMinScreenCastDimension, + result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); const int kSmallWidth = 100; @@ -645,14 +638,14 @@ result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // kSmallWidth is less that the default, so expect the default. - EXPECT_EQ(blink::kDefaultScreenCastWidth, result.Width()); - EXPECT_EQ(blink::kDefaultScreenCastHeight, result.Height()); + EXPECT_EQ(kDefaultScreenCastWidth, result.Width()); + EXPECT_EQ(kDefaultScreenCastHeight, result.Height()); CheckNonResolutionDefaults(result); - EXPECT_EQ(static_cast<double>(kSmallWidth) / blink::kMaxScreenCastDimension, + EXPECT_EQ(static_cast<double>(kSmallWidth) / kMaxScreenCastDimension, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(blink::kMaxScreenCastDimension) / - blink::kMinScreenCastDimension, - result.track_adapter_settings().max_aspect_ratio()); + EXPECT_EQ( + static_cast<double>(kMaxScreenCastDimension) / kMinScreenCastDimension, + result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -660,7 +653,7 @@ // kMaxWidth less than the default. { constraint_factory_.Reset(); - const int kMaxWidth = blink::kDefaultScreenCastWidth - 100; + const int kMaxWidth = kDefaultScreenCastWidth - 100; constraint_factory_.basic().width.SetMax(kMaxWidth); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); @@ -669,9 +662,9 @@ EXPECT_EQ(std::round(kMaxWidth / kDefaultScreenCastAspectRatio), result.Height()); CheckNonResolutionDefaults(result); - EXPECT_EQ(1.0 / blink::kMaxScreenCastDimension, + EXPECT_EQ(1.0 / kMaxScreenCastDimension, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(kMaxWidth) / blink::kMinScreenCastDimension, + EXPECT_EQ(static_cast<double>(kMaxWidth) / kMinScreenCastDimension, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -679,7 +672,7 @@ // kMaxWidth greater than the default. { constraint_factory_.Reset(); - const int kMaxWidth = blink::kDefaultScreenCastWidth + 100; + const int kMaxWidth = kDefaultScreenCastWidth + 100; constraint_factory_.basic().width.SetMax(kMaxWidth); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); @@ -688,9 +681,9 @@ EXPECT_EQ(std::round(kMaxWidth / kDefaultScreenCastAspectRatio), result.Height()); CheckNonResolutionDefaults(result); - EXPECT_EQ(1.0 / blink::kMaxScreenCastDimension, + EXPECT_EQ(1.0 / kMaxScreenCastDimension, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(kMaxWidth) / blink::kMinScreenCastDimension, + EXPECT_EQ(static_cast<double>(kMaxWidth) / kMinScreenCastDimension, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -698,28 +691,27 @@ // kMaxWidth greater than the maximum allowed (gets ignored). { constraint_factory_.Reset(); - constraint_factory_.basic().width.SetMax(blink::kMaxScreenCastDimension + - 1); + constraint_factory_.basic().width.SetMax(kMaxScreenCastDimension + 1); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // Expect the default, since the given max value cannot be used as default. - EXPECT_EQ(blink::kDefaultScreenCastWidth, result.Width()); - EXPECT_EQ(std::round(blink::kDefaultScreenCastWidth / - kDefaultScreenCastAspectRatio), - result.Height()); + EXPECT_EQ(kDefaultScreenCastWidth, result.Width()); + EXPECT_EQ( + std::round(kDefaultScreenCastWidth / kDefaultScreenCastAspectRatio), + result.Height()); CheckNonResolutionDefaults(result); - EXPECT_EQ(1.0 / blink::kMaxScreenCastDimension, + EXPECT_EQ(1.0 / kMaxScreenCastDimension, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(blink::kMaxScreenCastDimension) / - blink::kMinScreenCastDimension, - result.track_adapter_settings().max_aspect_ratio()); + EXPECT_EQ( + static_cast<double>(kMaxScreenCastDimension) / kMinScreenCastDimension, + result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } // kMaxWidth equal to the maximum allowed. { constraint_factory_.Reset(); - const int kMaxWidth = blink::kMaxScreenCastDimension; + const int kMaxWidth = kMaxScreenCastDimension; constraint_factory_.basic().width.SetMax(kMaxWidth); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); @@ -727,9 +719,9 @@ EXPECT_EQ(std::round(kMaxWidth / kDefaultScreenCastAspectRatio), result.Height()); CheckNonResolutionDefaults(result); - EXPECT_EQ(1.0 / blink::kMaxScreenCastDimension, + EXPECT_EQ(1.0 / kMaxScreenCastDimension, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(kMaxWidth) / blink::kMinScreenCastDimension, + EXPECT_EQ(static_cast<double>(kMaxWidth) / kMinScreenCastDimension, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -739,8 +731,8 @@ // The whole range is less than the default. { constraint_factory_.Reset(); - const int kMinWidth = blink::kDefaultScreenCastWidth - 200; - const int kMaxWidth = blink::kDefaultScreenCastWidth - 100; + const int kMinWidth = kDefaultScreenCastWidth - 200; + const int kMaxWidth = kDefaultScreenCastWidth - 100; constraint_factory_.basic().width.SetMin(kMinWidth); constraint_factory_.basic().width.SetMax(kMaxWidth); auto result = SelectSettings(); @@ -749,9 +741,9 @@ EXPECT_EQ(std::round(kMaxWidth / kDefaultScreenCastAspectRatio), result.Height()); CheckNonResolutionDefaults(result); - EXPECT_EQ(static_cast<double>(kMinWidth) / blink::kMaxScreenCastDimension, + EXPECT_EQ(static_cast<double>(kMinWidth) / kMaxScreenCastDimension, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(kMaxWidth) / blink::kMinScreenCastDimension, + EXPECT_EQ(static_cast<double>(kMaxWidth) / kMinScreenCastDimension, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -759,8 +751,8 @@ // The range includes the default. { constraint_factory_.Reset(); - const int kMinWidth = blink::kDefaultScreenCastWidth - 100; - const int kMaxWidth = blink::kDefaultScreenCastWidth + 100; + const int kMinWidth = kDefaultScreenCastWidth - 100; + const int kMaxWidth = kDefaultScreenCastWidth + 100; constraint_factory_.basic().width.SetMin(kMinWidth); constraint_factory_.basic().width.SetMax(kMaxWidth); auto result = SelectSettings(); @@ -769,9 +761,9 @@ EXPECT_EQ(std::round(kMaxWidth / kDefaultScreenCastAspectRatio), result.Height()); CheckNonResolutionDefaults(result); - EXPECT_EQ(static_cast<double>(kMinWidth) / blink::kMaxScreenCastDimension, + EXPECT_EQ(static_cast<double>(kMinWidth) / kMaxScreenCastDimension, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(kMaxWidth) / blink::kMinScreenCastDimension, + EXPECT_EQ(static_cast<double>(kMaxWidth) / kMinScreenCastDimension, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -779,8 +771,8 @@ // The whole range is greater than the default. { constraint_factory_.Reset(); - const int kMinWidth = blink::kDefaultScreenCastWidth + 100; - const int kMaxWidth = blink::kDefaultScreenCastWidth + 200; + const int kMinWidth = kDefaultScreenCastWidth + 100; + const int kMaxWidth = kDefaultScreenCastWidth + 200; constraint_factory_.basic().width.SetMin(kMinWidth); constraint_factory_.basic().width.SetMax(kMaxWidth); auto result = SelectSettings(); @@ -789,9 +781,9 @@ EXPECT_EQ(std::round(kMaxWidth / kDefaultScreenCastAspectRatio), result.Height()); CheckNonResolutionDefaults(result); - EXPECT_EQ(static_cast<double>(kMinWidth) / blink::kMaxScreenCastDimension, + EXPECT_EQ(static_cast<double>(kMinWidth) / kMaxScreenCastDimension, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(kMaxWidth) / blink::kMinScreenCastDimension, + EXPECT_EQ(static_cast<double>(kMaxWidth) / kMinScreenCastDimension, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -828,9 +820,9 @@ EXPECT_EQ(std::round(kMaxWidth / kDefaultScreenCastAspectRatio), result.Height()); CheckNonResolutionDefaults(result); - EXPECT_EQ(1.0 / blink::kMaxScreenCastDimension, + EXPECT_EQ(1.0 / kMaxScreenCastDimension, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(kMaxWidth) / blink::kMinScreenCastDimension, + EXPECT_EQ(static_cast<double>(kMaxWidth) / kMinScreenCastDimension, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -849,11 +841,11 @@ EXPECT_EQ(std::round(kMinWidth / kDefaultScreenCastAspectRatio), result.Height()); CheckNonResolutionDefaults(result); - EXPECT_EQ(static_cast<double>(kMinWidth) / blink::kMaxScreenCastDimension, + EXPECT_EQ(static_cast<double>(kMinWidth) / kMaxScreenCastDimension, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(blink::kMaxScreenCastDimension) / - blink::kMinScreenCastDimension, - result.track_adapter_settings().max_aspect_ratio()); + EXPECT_EQ( + static_cast<double>(kMaxScreenCastDimension) / kMinScreenCastDimension, + result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -937,8 +929,8 @@ // Given that the default aspect ratio cannot be preserved, the algorithm // tries to preserve, among the default height or width, the one that leads // to highest area. In this case, height is preserved. - EXPECT_EQ(blink::kDefaultScreenCastHeight, result.Height()); - EXPECT_EQ(std::round(blink::kDefaultScreenCastHeight * kAspectRatio), + EXPECT_EQ(kDefaultScreenCastHeight, result.Height()); + EXPECT_EQ(std::round(kDefaultScreenCastHeight * kAspectRatio), result.Width()); CheckNonResolutionDefaults(result); EXPECT_EQ(kAspectRatio, result.track_adapter_settings().min_aspect_ratio()); @@ -953,13 +945,13 @@ auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // kAspectRatio is greater that the default, so expect kAspectRatio. - EXPECT_EQ(blink::kDefaultScreenCastHeight, result.Height()); - EXPECT_EQ(std::round(blink::kDefaultScreenCastHeight * kAspectRatio), + EXPECT_EQ(kDefaultScreenCastHeight, result.Height()); + EXPECT_EQ(std::round(kDefaultScreenCastHeight * kAspectRatio), result.Width()); CheckNonResolutionDefaults(result); EXPECT_EQ(kAspectRatio, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(blink::kMaxScreenCastDimension) / - static_cast<double>(blink::kMinScreenCastDimension), + EXPECT_EQ(static_cast<double>(kMaxScreenCastDimension) / + static_cast<double>(kMinScreenCastDimension), result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); @@ -968,13 +960,13 @@ result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // kSmallAspectRatio is less that the default, so expect the default. - EXPECT_EQ(blink::kDefaultScreenCastHeight, result.Height()); - EXPECT_EQ(blink::kDefaultScreenCastWidth, result.Width()); + EXPECT_EQ(kDefaultScreenCastHeight, result.Height()); + EXPECT_EQ(kDefaultScreenCastWidth, result.Width()); CheckNonResolutionDefaults(result); EXPECT_EQ(kSmallAspectRatio, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(blink::kMaxScreenCastDimension) / - static_cast<double>(blink::kMinScreenCastDimension), + EXPECT_EQ(static_cast<double>(kMaxScreenCastDimension) / + static_cast<double>(kMinScreenCastDimension), result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -986,11 +978,11 @@ auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // kAspectRatio is greater that the default, so expect the default. - EXPECT_EQ(blink::kDefaultScreenCastHeight, result.Height()); - EXPECT_EQ(blink::kDefaultScreenCastWidth, result.Width()); + EXPECT_EQ(kDefaultScreenCastHeight, result.Height()); + EXPECT_EQ(kDefaultScreenCastWidth, result.Width()); CheckNonResolutionDefaults(result); - EXPECT_EQ(static_cast<double>(blink::kMinScreenCastDimension) / - static_cast<double>(blink::kMaxScreenCastDimension), + EXPECT_EQ(static_cast<double>(kMinScreenCastDimension) / + static_cast<double>(kMaxScreenCastDimension), result.track_adapter_settings().min_aspect_ratio()); EXPECT_EQ(kAspectRatio, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); @@ -1002,12 +994,12 @@ // kSmallAspectRatio is less that the default, so expect kSmallAspectRatio. // Prefer to preserve default width since that leads to larger area than // preserving default height. - EXPECT_EQ(std::round(blink::kDefaultScreenCastWidth / kSmallAspectRatio), + EXPECT_EQ(std::round(kDefaultScreenCastWidth / kSmallAspectRatio), result.Height()); - EXPECT_EQ(blink::kDefaultScreenCastWidth, result.Width()); + EXPECT_EQ(kDefaultScreenCastWidth, result.Width()); CheckNonResolutionDefaults(result); - EXPECT_EQ(static_cast<double>(blink::kMinScreenCastDimension) / - static_cast<double>(blink::kMaxScreenCastDimension), + EXPECT_EQ(static_cast<double>(kMinScreenCastDimension) / + static_cast<double>(kMaxScreenCastDimension), result.track_adapter_settings().min_aspect_ratio()); EXPECT_EQ(kSmallAspectRatio, result.track_adapter_settings().max_aspect_ratio()); @@ -1024,8 +1016,8 @@ auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // Range includes default, so expect the default. - EXPECT_EQ(blink::kDefaultScreenCastHeight, result.Height()); - EXPECT_EQ(blink::kDefaultScreenCastWidth, result.Width()); + EXPECT_EQ(kDefaultScreenCastHeight, result.Height()); + EXPECT_EQ(kDefaultScreenCastWidth, result.Width()); CheckNonResolutionDefaults(result); EXPECT_EQ(kMinAspectRatio, result.track_adapter_settings().min_aspect_ratio()); @@ -1042,8 +1034,8 @@ auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // The whole range is greater than the default. Expect the minimum. - EXPECT_EQ(blink::kDefaultScreenCastHeight, result.Height()); - EXPECT_EQ(std::round(blink::kDefaultScreenCastHeight * kMinAspectRatio), + EXPECT_EQ(kDefaultScreenCastHeight, result.Height()); + EXPECT_EQ(std::round(kDefaultScreenCastHeight * kMinAspectRatio), result.Width()); CheckNonResolutionDefaults(result); EXPECT_EQ(kMinAspectRatio, @@ -1061,9 +1053,9 @@ auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // The whole range is less than the default. Expect the maximum. - EXPECT_EQ(std::round(blink::kDefaultScreenCastWidth / kMaxAspectRatio), + EXPECT_EQ(std::round(kDefaultScreenCastWidth / kMaxAspectRatio), result.Height()); - EXPECT_EQ(blink::kDefaultScreenCastWidth, result.Width()); + EXPECT_EQ(kDefaultScreenCastWidth, result.Width()); CheckNonResolutionDefaults(result); EXPECT_EQ(kMinAspectRatio, result.track_adapter_settings().min_aspect_ratio()); @@ -1081,8 +1073,8 @@ constraint_factory_.basic().aspect_ratio.SetIdeal(kIdealAspectRatio); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); - EXPECT_EQ(blink::kDefaultScreenCastHeight, result.Height()); - EXPECT_EQ(std::round(blink::kDefaultScreenCastHeight * kIdealAspectRatio), + EXPECT_EQ(kDefaultScreenCastHeight, result.Height()); + EXPECT_EQ(std::round(kDefaultScreenCastHeight * kIdealAspectRatio), result.Width()); CheckNonResolutionDefaults(result); CheckTrackAdapterSettingsEqualsFormatDefaultAspectRatio(result); @@ -1098,13 +1090,13 @@ auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // Ideal aspect ratio is greater than the maximum, expect maximum. - EXPECT_EQ(std::round(blink::kDefaultScreenCastWidth / kMaxAspectRatio), + EXPECT_EQ(std::round(kDefaultScreenCastWidth / kMaxAspectRatio), result.Height()); - EXPECT_EQ(blink::kDefaultScreenCastWidth, result.Width()); + EXPECT_EQ(kDefaultScreenCastWidth, result.Width()); CheckNonResolutionDefaults(result); - EXPECT_EQ(static_cast<double>(blink::kMinScreenCastDimension) / - blink::kMaxScreenCastDimension, - result.track_adapter_settings().min_aspect_ratio()); + EXPECT_EQ( + static_cast<double>(kMinScreenCastDimension) / kMaxScreenCastDimension, + result.track_adapter_settings().min_aspect_ratio()); EXPECT_EQ(kMaxAspectRatio, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); @@ -1120,15 +1112,15 @@ auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // Ideal aspect ratio is less than the maximum, expect minimum. - EXPECT_EQ(std::round(blink::kDefaultScreenCastWidth / kMinAspectRatio), + EXPECT_EQ(std::round(kDefaultScreenCastWidth / kMinAspectRatio), result.Height()); - EXPECT_EQ(blink::kDefaultScreenCastWidth, result.Width()); + EXPECT_EQ(kDefaultScreenCastWidth, result.Width()); CheckNonResolutionDefaults(result); EXPECT_EQ(kMinAspectRatio, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(blink::kMaxScreenCastDimension) / - blink::kMinScreenCastDimension, - result.track_adapter_settings().max_aspect_ratio()); + EXPECT_EQ( + static_cast<double>(kMaxScreenCastDimension) / kMinScreenCastDimension, + result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -1183,13 +1175,12 @@ EXPECT_TRUE(result.HasValue()); // Ideal aspect-ratio is included in the bounding box. Preserving default // height leads to larger area than preserving default width. - EXPECT_EQ(blink::kDefaultScreenCastHeight, result.Height()); - EXPECT_EQ(blink::kDefaultScreenCastHeight * kIdealAspectRatio, - result.Width()); + EXPECT_EQ(kDefaultScreenCastHeight, result.Height()); + EXPECT_EQ(kDefaultScreenCastHeight * kIdealAspectRatio, result.Width()); CheckNonResolutionDefaults(result); - EXPECT_EQ(250.0 / blink::kMaxScreenCastDimension, + EXPECT_EQ(250.0 / kMaxScreenCastDimension, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(blink::kMaxScreenCastDimension / 250.0, + EXPECT_EQ(kMaxScreenCastDimension / 250.0, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -1332,7 +1323,7 @@ auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // No ideal or maximum frame rate given, expect default. - EXPECT_EQ(blink::kDefaultScreenCastFrameRate, result.FrameRate()); + EXPECT_EQ(kDefaultScreenCastFrameRate, result.FrameRate()); EXPECT_TRUE(result.min_frame_rate().has_value()); EXPECT_EQ(kMinFrameRate, result.min_frame_rate()); EXPECT_FALSE(result.max_frame_rate().has_value()); @@ -1347,7 +1338,7 @@ auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // No ideal or maximum frame rate given, expect default. - EXPECT_EQ(blink::kDefaultScreenCastFrameRate, result.FrameRate()); + EXPECT_EQ(kDefaultScreenCastFrameRate, result.FrameRate()); // kMinFrameRate should be ignored. EXPECT_FALSE(result.min_frame_rate().has_value()); EXPECT_FALSE(result.max_frame_rate().has_value()); @@ -1362,7 +1353,7 @@ auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // No ideal or maximum frame rate given, expect default. - EXPECT_EQ(blink::kDefaultScreenCastFrameRate, result.FrameRate()); + EXPECT_EQ(kDefaultScreenCastFrameRate, result.FrameRate()); EXPECT_TRUE(result.min_frame_rate().has_value()); EXPECT_EQ(kMinFrameRate, result.min_frame_rate()); EXPECT_FALSE(result.max_frame_rate().has_value()); @@ -1403,12 +1394,12 @@ // kMaxFrameRate greater than the maximum allowed { - const double kMaxFrameRate = blink::kMaxScreenCastFrameRate + 0.1; + const double kMaxFrameRate = kMaxScreenCastFrameRate + 0.1; constraint_factory_.basic().frame_rate.SetMax(kMaxFrameRate); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // Expect the default, since the given maximum is invalid. - EXPECT_EQ(blink::kDefaultScreenCastFrameRate, result.FrameRate()); + EXPECT_EQ(kDefaultScreenCastFrameRate, result.FrameRate()); EXPECT_EQ(base::Optional<double>(), result.min_frame_rate()); EXPECT_EQ(base::Optional<double>(), result.max_frame_rate()); CheckNonFrameRateDefaults(result); @@ -1417,7 +1408,7 @@ // kMaxFrameRate equal to the maximum allowed { - const double kMaxFrameRate = blink::kMaxScreenCastFrameRate; + const double kMaxFrameRate = kMaxScreenCastFrameRate; constraint_factory_.basic().frame_rate.SetMax(kMaxFrameRate); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); @@ -1550,7 +1541,7 @@ constraint_factory_.basic().width.SetIdeal(kIdealWidth); constraint_factory_.basic().height.SetIdeal(kIdealHeight); constraint_factory_.basic().resize_mode.SetExact( - blink::WebString::FromASCII("none")); + WebString::FromASCII("none")); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // Screen capture will proceed at 641x480, which will be considered "native". @@ -1560,7 +1551,7 @@ EXPECT_FALSE(result.track_adapter_settings().target_size().has_value()); constraint_factory_.basic().resize_mode.SetExact( - blink::WebString::FromASCII("crop-and-scale")); + WebString::FromASCII("crop-and-scale")); result = SelectSettings(); EXPECT_TRUE(result.HasValue()); EXPECT_EQ(result.Width(), kIdealWidth); @@ -1574,8 +1565,7 @@ TEST_F(MediaStreamConstraintsUtilVideoContentTest, AdvancedMinMaxResolutionFrameRate) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.width.SetMin(2000000000); advanced1.height.SetMin(2000000000); // The first advanced set cannot be satisfied and is therefore ignored in all @@ -1583,13 +1573,12 @@ // In this case, default settings must be selected. auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); - EXPECT_EQ(blink::kDefaultScreenCastHeight, result.Height()); - EXPECT_EQ(blink::kDefaultScreenCastWidth, result.Width()); + EXPECT_EQ(kDefaultScreenCastHeight, result.Height()); + EXPECT_EQ(kDefaultScreenCastWidth, result.Width()); CheckNonResolutionDefaults(result); CheckTrackAdapterSettingsEqualsFormatDefaultAspectRatio(result); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.height.SetMax(400); advanced2.width.SetMax(500); advanced2.aspect_ratio.SetExact(5.0 / 4.0); @@ -1602,8 +1591,7 @@ EXPECT_EQ(5.0 / 4.0, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); - blink::WebMediaTrackConstraintSet& advanced3 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced3 = constraint_factory_.AddAdvanced(); advanced3.frame_rate.SetMax(10.0); result = SelectSettings(); EXPECT_TRUE(result.HasValue()); @@ -1617,8 +1605,7 @@ EXPECT_EQ(5.0 / 4.0, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); - blink::WebMediaTrackConstraintSet& advanced4 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced4 = constraint_factory_.AddAdvanced(); advanced4.width.SetExact(1000); advanced4.height.SetExact(1000); result = SelectSettings(); @@ -1671,25 +1658,22 @@ TEST_F(MediaStreamConstraintsUtilVideoContentTest, AdvancedExactResolution) { { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.width.SetExact(40000000); advanced1.height.SetExact(40000000); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.width.SetExact(300000000); advanced2.height.SetExact(300000000); auto result = SelectSettings(); // None of the constraint sets can be satisfied. Default resolution should // be selected. EXPECT_TRUE(result.HasValue()); - EXPECT_EQ(blink::kDefaultScreenCastHeight, result.Height()); - EXPECT_EQ(blink::kDefaultScreenCastWidth, result.Width()); + EXPECT_EQ(kDefaultScreenCastHeight, result.Height()); + EXPECT_EQ(kDefaultScreenCastWidth, result.Width()); CheckNonResolutionDefaults(result); CheckTrackAdapterSettingsEqualsFormatDefaultAspectRatio(result); - blink::WebMediaTrackConstraintSet& advanced3 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced3 = constraint_factory_.AddAdvanced(); advanced3.width.SetExact(1920); advanced3.height.SetExact(1080); result = SelectSettings(); @@ -1703,8 +1687,7 @@ result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); - blink::WebMediaTrackConstraintSet& advanced4 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced4 = constraint_factory_.AddAdvanced(); advanced4.width.SetExact(640); advanced4.height.SetExact(480); result = SelectSettings(); @@ -1739,12 +1722,10 @@ TEST_F(MediaStreamConstraintsUtilVideoContentTest, AdvancedResolutionAndFrameRate) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.width.SetExact(1920); advanced1.height.SetExact(1080); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.frame_rate.SetExact(60.0); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); @@ -1760,12 +1741,10 @@ TEST_F(MediaStreamConstraintsUtilVideoContentTest, AdvancedNoiseReduction) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.width.SetMin(640); advanced1.height.SetMin(480); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); const int kMinWidth = 4000; const int kMinHeight = 2000; advanced2.width.SetMin(kMinWidth); @@ -1779,9 +1758,9 @@ std::round(result.Width() / kDefaultScreenCastAspectRatio)), result.Height()); EXPECT_TRUE(result.noise_reduction() && !*result.noise_reduction()); - EXPECT_EQ(kMinWidth / static_cast<double>(blink::kMaxScreenCastDimension), + EXPECT_EQ(kMinWidth / static_cast<double>(kMaxScreenCastDimension), result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(blink::kMaxScreenCastDimension) / kMinHeight, + EXPECT_EQ(static_cast<double>(kMaxScreenCastDimension) / kMinHeight, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -1791,13 +1770,11 @@ TEST_F(MediaStreamConstraintsUtilVideoContentTest, AdvancedContradictoryNoiseReduction) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.width.SetExact(640); advanced1.height.SetExact(480); advanced1.goog_noise_reduction.SetExact(true); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.width.SetExact(1920); advanced2.height.SetExact(1080); advanced2.goog_noise_reduction.SetExact(false); @@ -1814,12 +1791,10 @@ TEST_F(MediaStreamConstraintsUtilVideoContentTest, AdvancedContradictoryExactResolution) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.width.SetExact(640); advanced1.height.SetExact(480); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.width.SetExact(1920); advanced2.height.SetExact(1080); auto result = SelectSettings(); @@ -1835,12 +1810,10 @@ TEST_F(MediaStreamConstraintsUtilVideoContentTest, AdvancedContradictoryMaxMinResolutionFrameRate) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.width.SetMax(640); advanced1.height.SetMax(480); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.width.SetMin(1920); advanced2.height.SetMin(1080); advanced2.frame_rate.SetExact(60.0); @@ -1849,10 +1822,10 @@ EXPECT_EQ(640, result.Width()); EXPECT_EQ(480, result.Height()); // Resolution cannot exceed the requested resolution. - EXPECT_EQ(blink::kDefaultScreenCastFrameRate, result.FrameRate()); - EXPECT_EQ(blink::kMinScreenCastDimension / 480.0, + EXPECT_EQ(kDefaultScreenCastFrameRate, result.FrameRate()); + EXPECT_EQ(kMinScreenCastDimension / 480.0, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(640.0 / blink::kMinScreenCastDimension, + EXPECT_EQ(640.0 / kMinScreenCastDimension, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -1862,12 +1835,10 @@ const int kMinHeight = 2600; const int kMinWidth = 2800; constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.width.SetMin(kMinWidth); advanced1.height.SetMin(kMinHeight); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.width.SetMax(640); advanced2.height.SetMax(480); advanced2.frame_rate.SetExact(60.0); @@ -1876,10 +1847,10 @@ EXPECT_EQ(std::round(kMinHeight * kDefaultScreenCastAspectRatio), result.Width()); EXPECT_EQ(kMinHeight, result.Height()); - EXPECT_EQ(blink::kDefaultScreenCastFrameRate, result.FrameRate()); - EXPECT_EQ(static_cast<double>(kMinWidth) / blink::kMaxScreenCastDimension, + EXPECT_EQ(kDefaultScreenCastFrameRate, result.FrameRate()); + EXPECT_EQ(static_cast<double>(kMinWidth) / kMaxScreenCastDimension, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(blink::kMaxScreenCastDimension) / kMinHeight, + EXPECT_EQ(static_cast<double>(kMaxScreenCastDimension) / kMinHeight, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -1887,18 +1858,16 @@ TEST_F(MediaStreamConstraintsUtilVideoContentTest, AdvancedContradictoryExactAspectRatio) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); const double kMinAspectRatio = 5.0; advanced1.aspect_ratio.SetExact(kMinAspectRatio); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.aspect_ratio.SetExact(3.0); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); - EXPECT_EQ(std::round(blink::kDefaultScreenCastHeight * kMinAspectRatio), + EXPECT_EQ(std::round(kDefaultScreenCastHeight * kMinAspectRatio), result.Width()); - EXPECT_EQ(blink::kDefaultScreenCastHeight, result.Height()); + EXPECT_EQ(kDefaultScreenCastHeight, result.Height()); CheckNonResolutionDefaults(result); EXPECT_EQ(kMinAspectRatio, result.track_adapter_settings().min_aspect_ratio()); @@ -1910,35 +1879,31 @@ TEST_F(MediaStreamConstraintsUtilVideoContentTest, AdvancedContradictoryAspectRatioRange) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); const double kMinAspectRatio = 5.0; advanced1.aspect_ratio.SetMin(kMinAspectRatio); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.aspect_ratio.SetMax(3.0); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); - EXPECT_EQ(std::round(blink::kDefaultScreenCastHeight * kMinAspectRatio), + EXPECT_EQ(std::round(kDefaultScreenCastHeight * kMinAspectRatio), result.Width()); - EXPECT_EQ(blink::kDefaultScreenCastHeight, result.Height()); + EXPECT_EQ(kDefaultScreenCastHeight, result.Height()); CheckNonResolutionDefaults(result); EXPECT_EQ(kMinAspectRatio, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(blink::kMaxScreenCastDimension / - static_cast<double>(blink::kMinScreenCastDimension), - result.track_adapter_settings().max_aspect_ratio()); + EXPECT_EQ( + kMaxScreenCastDimension / static_cast<double>(kMinScreenCastDimension), + result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } TEST_F(MediaStreamConstraintsUtilVideoContentTest, AdvancedContradictoryExactFrameRate) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.frame_rate.SetExact(40.0); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.frame_rate.SetExact(45.0); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); @@ -1950,11 +1915,9 @@ TEST_F(MediaStreamConstraintsUtilVideoContentTest, AdvancedContradictoryFrameRateRange) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.frame_rate.SetMin(40.0); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.frame_rate.SetMax(35.0); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); @@ -1967,15 +1930,12 @@ AdvancedContradictoryWidthFrameRate) { const int kMaxWidth = 1920; constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.width.SetMax(kMaxWidth); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.width.SetMin(2000); advanced2.frame_rate.SetExact(10.0); - blink::WebMediaTrackConstraintSet& advanced3 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced3 = constraint_factory_.AddAdvanced(); advanced3.frame_rate.SetExact(90.0); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); @@ -1983,10 +1943,10 @@ EXPECT_EQ(std::round(kMaxWidth / kDefaultScreenCastAspectRatio), result.Height()); EXPECT_EQ(90.0, result.FrameRate()); - EXPECT_EQ(static_cast<double>(blink::kMinScreenCastDimension) / - blink::kMaxScreenCastDimension, - result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(kMaxWidth) / blink::kMinScreenCastDimension, + EXPECT_EQ( + static_cast<double>(kMinScreenCastDimension) / kMaxScreenCastDimension, + result.track_adapter_settings().min_aspect_ratio()); + EXPECT_EQ(static_cast<double>(kMaxWidth) / kMinScreenCastDimension, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -1995,15 +1955,12 @@ AdvancedContradictoryHeightFrameRate) { const int kMaxHeight = 2000; constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.height.SetMax(kMaxHeight); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.height.SetMin(4500); advanced2.frame_rate.SetExact(10.0); - blink::WebMediaTrackConstraintSet& advanced3 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced3 = constraint_factory_.AddAdvanced(); advanced3.frame_rate.SetExact(60.0); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); @@ -2011,11 +1968,11 @@ // Height defaults to explicitly given max constraint. EXPECT_EQ(kMaxHeight, result.Height()); EXPECT_EQ(60.0, result.FrameRate()); - EXPECT_EQ(static_cast<double>(blink::kMinScreenCastDimension) / kMaxHeight, + EXPECT_EQ(static_cast<double>(kMinScreenCastDimension) / kMaxHeight, result.track_adapter_settings().min_aspect_ratio()); - EXPECT_EQ(static_cast<double>(blink::kMaxScreenCastDimension) / - blink::kMinScreenCastDimension, - result.track_adapter_settings().max_aspect_ratio()); + EXPECT_EQ( + static_cast<double>(kMaxScreenCastDimension) / kMinScreenCastDimension, + result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFormat(result); } @@ -2025,18 +1982,16 @@ const std::string kDeviceID3 = "fake_device_3"; const std::string kDeviceID4 = "fake_device_4"; constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); - blink::WebString id_vector1[] = {blink::WebString::FromASCII(kDeviceID1), - blink::WebString::FromASCII(kDeviceID2)}; + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); + WebString id_vector1[] = {WebString::FromASCII(kDeviceID1), + WebString::FromASCII(kDeviceID2)}; advanced1.device_id.SetExact( - blink::WebVector<blink::WebString>(id_vector1, base::size(id_vector1))); - blink::WebString id_vector2[] = {blink::WebString::FromASCII(kDeviceID2), - blink::WebString::FromASCII(kDeviceID3)}; - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebVector<WebString>(id_vector1, base::size(id_vector1))); + WebString id_vector2[] = {WebString::FromASCII(kDeviceID2), + WebString::FromASCII(kDeviceID3)}; + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.device_id.SetExact( - blink::WebVector<blink::WebString>(id_vector2, base::size(id_vector2))); + WebVector<WebString>(id_vector2, base::size(id_vector2))); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // kDeviceID2 must be selected because it is the only one that satisfies both @@ -2052,18 +2007,16 @@ const std::string kDeviceID3 = "fake_device_3"; const std::string kDeviceID4 = "fake_device_4"; constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); - blink::WebString id_vector1[] = {blink::WebString::FromASCII(kDeviceID1), - blink::WebString::FromASCII(kDeviceID2)}; + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); + WebString id_vector1[] = {WebString::FromASCII(kDeviceID1), + WebString::FromASCII(kDeviceID2)}; advanced1.device_id.SetExact( - blink::WebVector<blink::WebString>(id_vector1, base::size(id_vector1))); - blink::WebString id_vector2[] = {blink::WebString::FromASCII(kDeviceID3), - blink::WebString::FromASCII(kDeviceID4)}; - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebVector<WebString>(id_vector1, base::size(id_vector1))); + WebString id_vector2[] = {WebString::FromASCII(kDeviceID3), + WebString::FromASCII(kDeviceID4)}; + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.device_id.SetExact( - blink::WebVector<blink::WebString>(id_vector2, base::size(id_vector2))); + WebVector<WebString>(id_vector2, base::size(id_vector2))); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // The second advanced set must be ignored because it contradicts the first @@ -2077,17 +2030,16 @@ const std::string kDeviceID2 = "fake_device_2"; const std::string kDeviceID3 = "fake_device_3"; constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced = - constraint_factory_.AddAdvanced(); - blink::WebString id_vector1[] = {blink::WebString::FromASCII(kDeviceID1), - blink::WebString::FromASCII(kDeviceID2)}; + WebMediaTrackConstraintSet& advanced = constraint_factory_.AddAdvanced(); + WebString id_vector1[] = {WebString::FromASCII(kDeviceID1), + WebString::FromASCII(kDeviceID2)}; advanced.device_id.SetExact( - blink::WebVector<blink::WebString>(id_vector1, base::size(id_vector1))); + WebVector<WebString>(id_vector1, base::size(id_vector1))); - blink::WebString id_vector2[] = {blink::WebString::FromASCII(kDeviceID2), - blink::WebString::FromASCII(kDeviceID3)}; + WebString id_vector2[] = {WebString::FromASCII(kDeviceID2), + WebString::FromASCII(kDeviceID3)}; constraint_factory_.basic().device_id.SetIdeal( - blink::WebVector<blink::WebString>(id_vector2, base::size(id_vector2))); + WebVector<WebString>(id_vector2, base::size(id_vector2))); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // Should select kDeviceID2, which appears in ideal and satisfies the advanced @@ -2102,9 +2054,8 @@ constraint_factory_.Reset(); constraint_factory_.basic().width.SetIdeal(kIdealWidth); constraint_factory_.basic().height.SetIdeal(kIdealHeight); - blink::WebMediaTrackConstraintSet& advanced = - constraint_factory_.AddAdvanced(); - advanced.resize_mode.SetExact(blink::WebString::FromASCII("none")); + WebMediaTrackConstraintSet& advanced = constraint_factory_.AddAdvanced(); + advanced.resize_mode.SetExact(WebString::FromASCII("none")); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // Screen capture will proceed at 641x480, which will be considered "native". @@ -2114,7 +2065,7 @@ EXPECT_EQ(result.Height(), kIdealHeight); EXPECT_FALSE(result.track_adapter_settings().target_size().has_value()); - advanced.resize_mode.SetExact(blink::WebString::FromASCII("crop-and-scale")); + advanced.resize_mode.SetExact(WebString::FromASCII("crop-and-scale")); result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // Screen capture will proceed at 641x480, which will be considered "native". @@ -2131,8 +2082,8 @@ { constraint_factory_.Reset(); auto result = SelectSettings(); - EXPECT_EQ(blink::kDefaultScreenCastWidth, result.Width()); - EXPECT_EQ(blink::kDefaultScreenCastHeight, result.Height()); + EXPECT_EQ(kDefaultScreenCastWidth, result.Width()); + EXPECT_EQ(kDefaultScreenCastHeight, result.Height()); // Resolution can be adjusted. EXPECT_EQ(media::ResolutionChangePolicy::ANY_WITHIN_LIMIT, result.ResolutionChangePolicy()); @@ -2140,10 +2091,9 @@ } { constraint_factory_.Reset(); - auto result = - SelectSettings(blink::mojom::MediaStreamType::GUM_TAB_VIDEO_CAPTURE); - EXPECT_EQ(blink::kDefaultScreenCastWidth, result.Width()); - EXPECT_EQ(blink::kDefaultScreenCastHeight, result.Height()); + auto result = SelectSettings(mojom::MediaStreamType::GUM_TAB_VIDEO_CAPTURE); + EXPECT_EQ(kDefaultScreenCastWidth, result.Width()); + EXPECT_EQ(kDefaultScreenCastHeight, result.Height()); // Default policy for tab capture is fixed resolution. EXPECT_EQ(media::ResolutionChangePolicy::FIXED_RESOLUTION, result.ResolutionChangePolicy()); @@ -2253,4 +2203,4 @@ } } -} // namespace content +} // namespace blink
diff --git a/content/renderer/media/stream/media_stream_video_source_unittest.cc b/content/renderer/media/stream/media_stream_video_source_unittest.cc index 2f7b6c2..b96d2dc9 100644 --- a/content/renderer/media/stream/media_stream_video_source_unittest.cc +++ b/content/renderer/media/stream/media_stream_video_source_unittest.cc
@@ -13,7 +13,6 @@ #include "base/test/scoped_task_environment.h" #include "build/build_config.h" #include "content/child/child_process.h" -#include "content/renderer/media/stream/mock_constraint_factory.h" #include "content/renderer/media/stream/mock_media_stream_video_sink.h" #include "media/base/limits.h" #include "media/base/video_frame.h" @@ -21,6 +20,7 @@ #include "third_party/blink/public/mojom/mediastream/media_stream.mojom-shared.h" #include "third_party/blink/public/web/modules/mediastream/media_stream_video_source.h" #include "third_party/blink/public/web/modules/mediastream/media_stream_video_track.h" +#include "third_party/blink/public/web/modules/mediastream/mock_constraint_factory.h" #include "third_party/blink/public/web/modules/mediastream/mock_media_stream_video_source.h" #include "third_party/blink/public/web/modules/mediastream/video_track_adapter_settings.h" #include "third_party/blink/public/web/web_heap.h"
diff --git a/content/renderer/media/stream/mock_constraint_factory.h b/content/renderer/media/stream/mock_constraint_factory.h deleted file mode 100644 index d721c6c..0000000 --- a/content/renderer/media/stream/mock_constraint_factory.h +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_RENDERER_MEDIA_STREAM_MOCK_CONSTRAINT_FACTORY_H_ -#define CONTENT_RENDERER_MEDIA_STREAM_MOCK_CONSTRAINT_FACTORY_H_ - -#include <string> -#include <vector> - -#include "base/macros.h" -#include "third_party/blink/public/platform/web_media_constraints.h" - -namespace content { - -class MockConstraintFactory { - public: - MockConstraintFactory(); - ~MockConstraintFactory(); - - blink::WebMediaConstraints CreateWebMediaConstraints() const; - blink::WebMediaTrackConstraintSet& basic() { return basic_; } - blink::WebMediaTrackConstraintSet& AddAdvanced(); - - void DisableDefaultAudioConstraints(); - void DisableAecAudioConstraints(); - void Reset(); - - private: - blink::WebMediaTrackConstraintSet basic_; - std::vector<blink::WebMediaTrackConstraintSet> advanced_; - - DISALLOW_COPY_AND_ASSIGN(MockConstraintFactory); -}; - -} // namespace content - -#endif // CONTENT_RENDERER_MEDIA_STREAM_MOCK_CONSTRAINT_FACTORY_H_
diff --git a/content/renderer/media/stream/user_media_client_impl_unittest.cc b/content/renderer/media/stream/user_media_client_impl_unittest.cc index 530b634..ec3e79f 100644 --- a/content/renderer/media/stream/user_media_client_impl_unittest.cc +++ b/content/renderer/media/stream/user_media_client_impl_unittest.cc
@@ -17,7 +17,6 @@ #include "base/test/scoped_task_environment.h" #include "content/child/child_process.h" #include "content/renderer/media/stream/media_stream_device_observer.h" -#include "content/renderer/media/stream/mock_constraint_factory.h" #include "content/renderer/media/stream/mock_mojo_media_stream_dispatcher_host.h" #include "content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h" #include "media/audio/audio_device_description.h" @@ -38,6 +37,7 @@ #include "third_party/blink/public/web/modules/mediastream/media_stream_constraints_util.h" #include "third_party/blink/public/web/modules/mediastream/media_stream_constraints_util_video_content.h" #include "third_party/blink/public/web/modules/mediastream/media_stream_video_track.h" +#include "third_party/blink/public/web/modules/mediastream/mock_constraint_factory.h" #include "third_party/blink/public/web/modules/mediastream/mock_media_stream_video_source.h" #include "third_party/blink/public/web/web_heap.h" @@ -52,7 +52,7 @@ namespace { blink::WebMediaConstraints CreateDefaultConstraints() { - MockConstraintFactory factory; + blink::MockConstraintFactory factory; factory.AddAdvanced(); return factory.CreateWebMediaConstraints(); } @@ -61,7 +61,7 @@ const char* basic_exact_value, const char* basic_ideal_value = nullptr, const char* advanced_exact_value = nullptr) { - MockConstraintFactory factory; + blink::MockConstraintFactory factory; if (basic_exact_value) { factory.basic().device_id.SetExact( blink::WebString::FromUTF8(basic_exact_value)); @@ -85,7 +85,7 @@ const char* basic_exact_value, const char* basic_ideal_value = nullptr, const char* advanced_exact_value = nullptr) { - MockConstraintFactory factory; + blink::MockConstraintFactory factory; if (basic_exact_value) { factory.basic().facing_mode.SetExact( blink::WebString::FromUTF8(basic_exact_value)); @@ -548,7 +548,7 @@ blink::WebMediaStreamTrack RequestLocalAudioTrackWithAssociatedSink( bool render_to_associated_sink) { - MockConstraintFactory constraint_factory; + blink::MockConstraintFactory constraint_factory; constraint_factory.basic().render_to_associated_sink.SetExact( render_to_associated_sink); blink::WebUserMediaRequest user_media_request = @@ -615,7 +615,7 @@ int width, int height, const base::Optional<double>& frame_rate = base::Optional<double>()) { - MockConstraintFactory factory; + blink::MockConstraintFactory factory; factory.basic().width.SetExact(width); factory.basic().height.SetExact(height); if (frame_rate) @@ -951,7 +951,7 @@ } TEST_F(UserMediaClientImplTest, DefaultTabCapturePropagate) { - MockConstraintFactory factory; + blink::MockConstraintFactory factory; factory.basic().media_stream_source.SetExact( blink::WebString::FromASCII(blink::kMediaStreamSourceTab)); blink::WebMediaConstraints audio_constraints = @@ -1009,7 +1009,7 @@ } TEST_F(UserMediaClientImplTest, DefaultDesktopCapturePropagate) { - MockConstraintFactory factory; + blink::MockConstraintFactory factory; factory.basic().media_stream_source.SetExact( blink::WebString::FromASCII(blink::kMediaStreamSourceDesktop)); blink::WebMediaConstraints audio_constraints = @@ -1070,7 +1070,7 @@ TEST_F(UserMediaClientImplTest, NonDefaultAudioConstraintsPropagate) { mock_dispatcher_host_.DoNotRunCallback(); - MockConstraintFactory factory; + blink::MockConstraintFactory factory; factory.basic().device_id.SetExact( blink::WebString::FromASCII(kFakeAudioInputDeviceId1)); factory.basic().disable_local_echo.SetExact(true); @@ -1397,7 +1397,7 @@ } TEST_F(UserMediaClientImplTest, DesktopCaptureChangeSource) { - MockConstraintFactory factory; + blink::MockConstraintFactory factory; factory.basic().media_stream_source.SetExact( blink::WebString::FromASCII(blink::kMediaStreamSourceDesktop)); blink::WebMediaConstraints audio_constraints = @@ -1435,7 +1435,7 @@ } TEST_F(UserMediaClientImplTest, DesktopCaptureChangeSourceWithoutAudio) { - MockConstraintFactory factory; + blink::MockConstraintFactory factory; factory.basic().media_stream_source.SetExact( blink::WebString::FromASCII(blink::kMediaStreamSourceDesktop)); blink::WebMediaConstraints audio_constraints =
diff --git a/content/renderer/media/webrtc/media_stream_video_webrtc_sink_unittest.cc b/content/renderer/media/webrtc/media_stream_video_webrtc_sink_unittest.cc index 5d320439..c692a21 100644 --- a/content/renderer/media/webrtc/media_stream_video_webrtc_sink_unittest.cc +++ b/content/renderer/media/webrtc/media_stream_video_webrtc_sink_unittest.cc
@@ -6,10 +6,10 @@ #include "base/test/scoped_task_environment.h" #include "content/child/child_process.h" -#include "content/renderer/media/stream/mock_constraint_factory.h" #include "content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h" +#include "third_party/blink/public/web/modules/mediastream/mock_constraint_factory.h" #include "third_party/blink/public/web/modules/mediastream/mock_media_stream_registry.h" #include "third_party/blink/public/web/modules/mediastream/video_track_adapter_settings.h"
diff --git a/content/renderer/media/webrtc/rtc_peer_connection_handler_unittest.cc b/content/renderer/media/webrtc/rtc_peer_connection_handler_unittest.cc index 5165cd3..50196b7 100644 --- a/content/renderer/media/webrtc/rtc_peer_connection_handler_unittest.cc +++ b/content/renderer/media/webrtc/rtc_peer_connection_handler_unittest.cc
@@ -25,7 +25,6 @@ #include "base/values.h" #include "content/child/child_process.h" #include "content/renderer/media/audio/mock_audio_device_factory.h" -#include "content/renderer/media/stream/mock_constraint_factory.h" #include "content/renderer/media/stream/processed_local_audio_source.h" #include "content/renderer/media/webrtc/mock_data_channel_impl.h" #include "content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h" @@ -55,6 +54,7 @@ #include "third_party/blink/public/platform/web_rtc_void_request.h" #include "third_party/blink/public/platform/web_url.h" #include "third_party/blink/public/web/modules/mediastream/media_stream_video_track.h" +#include "third_party/blink/public/web/modules/mediastream/mock_constraint_factory.h" #include "third_party/blink/public/web/modules/mediastream/mock_media_stream_video_source.h" #include "third_party/blink/public/web/web_heap.h" #include "third_party/webrtc/api/peer_connection_interface.h"
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index 859e25b..22a0959 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -1849,15 +1849,10 @@ "../renderer/media/stream/media_stream_audio_processor_unittest.cc", "../renderer/media/stream/media_stream_audio_unittest.cc", "../renderer/media/stream/media_stream_constraints_util_audio_unittest.cc", - "../renderer/media/stream/media_stream_constraints_util_sets_unittest.cc", - "../renderer/media/stream/media_stream_constraints_util_unittest.cc", "../renderer/media/stream/media_stream_constraints_util_video_content_unittest.cc", - "../renderer/media/stream/media_stream_constraints_util_video_device_unittest.cc", "../renderer/media/stream/media_stream_device_observer_unittest.cc", "../renderer/media/stream/media_stream_video_source_unittest.cc", "../renderer/media/stream/media_stream_video_track_unittest.cc", - "../renderer/media/stream/mock_constraint_factory.cc", - "../renderer/media/stream/mock_constraint_factory.h", "../renderer/media/stream/mock_media_stream_video_sink.cc", "../renderer/media/stream/mock_media_stream_video_sink.h", "../renderer/media/stream/processed_local_audio_source_unittest.cc",
diff --git a/device/bluetooth/bluetooth_device.h b/device/bluetooth/bluetooth_device.h index fb48054..13b5b3b 100644 --- a/device/bluetooth/bluetooth_device.h +++ b/device/bluetooth/bluetooth_device.h
@@ -581,6 +581,29 @@ const AbortWriteErrorCallback& error_callback) = 0; #endif + // Set the remaining battery of the device to show in the UI. This value must + // be between 0 and 100, inclusive. + // TODO(https://crbug.com/973237): Battery percentage is populated by + // ash::GattBatteryPoller and used only by Chrome OS. In the future, when + // there is a unified Mojo service, this logic will be moved to + // BluetoothDeviceInfo. + void set_battery_percentage(base::Optional<uint8_t> battery_percentage) { + if (battery_percentage) { + DCHECK(battery_percentage.value() >= 0 && + battery_percentage.value() <= 100); + } + battery_percentage_ = battery_percentage; + } + + // Returns the remaining battery for the device. + // TODO(https://crbug.com/973237): Battery percentage is populated by + // ash::GattBatteryPoller and used only by Chrome OS. In the future, when + // there is a unified Mojo service, this logic will be moved to + // BluetoothDeviceInfo. + const base::Optional<uint8_t>& battery_percentage() const { + return battery_percentage_; + } + protected: // BluetoothGattConnection is a friend to call Add/RemoveGattConnection. friend BluetoothGattConnection; @@ -714,6 +737,14 @@ // a device type for display when |name_| is empty. base::string16 GetAddressWithLocalizedDeviceTypeName() const; + // Remaining battery level of the device. + // TODO(https://crbug.com/973237): This field is populated by + // ash::GattBatteryPoller and used only by Chrome OS. This field is different + // from others because it is not filled by the platform. In the future, when + // there is a unified Mojo service, this field will be moved to + // BluetoothDeviceInfo. + base::Optional<uint8_t> battery_percentage_; + DISALLOW_COPY_AND_ASSIGN(BluetoothDevice); };
diff --git a/device/fido/bio/enrollment.cc b/device/fido/bio/enrollment.cc index 44b1407..c33b14b 100644 --- a/device/fido/bio/enrollment.cc +++ b/device/fido/bio/enrollment.cc
@@ -82,6 +82,30 @@ return request; } +// static +BioEnrollmentRequest BioEnrollmentRequest::ForRename( + const pin::TokenResponse& response, + std::vector<uint8_t> id, + std::string name) { + BioEnrollmentRequest request; + request.pin_protocol = 1; + request.modality = BioEnrollmentModality::kFingerprint; + request.subcommand = BioEnrollmentSubCommand::kSetFriendlyName; + request.params = cbor::Value::MapValue(); + request.params->emplace( + static_cast<int>(BioEnrollmentSubCommandParam::kTemplateId), + cbor::Value(std::move(id))); + + std::vector<uint8_t> pin_auth = + *cbor::Writer::Write(cbor::Value(*request.params)); + pin_auth.insert(pin_auth.begin(), static_cast<int>(*request.subcommand)); + pin_auth.insert(pin_auth.begin(), static_cast<int>(*request.modality)); + + request.pin_auth = response.PinAuth(std::move(pin_auth)); + + return request; +} + BioEnrollmentRequest::BioEnrollmentRequest(BioEnrollmentRequest&&) = default; BioEnrollmentRequest& BioEnrollmentRequest::operator=(BioEnrollmentRequest&&) = default;
diff --git a/device/fido/bio/enrollment.h b/device/fido/bio/enrollment.h index 58e6242..19804c0e 100644 --- a/device/fido/bio/enrollment.h +++ b/device/fido/bio/enrollment.h
@@ -108,7 +108,10 @@ const pin::TokenResponse& pin_token, std::vector<uint8_t> template_id); static BioEnrollmentRequest ForCancel(); - static BioEnrollmentRequest ForEnumerate(const pin::TokenResponse&); + static BioEnrollmentRequest ForEnumerate(const pin::TokenResponse& token); + static BioEnrollmentRequest ForRename(const pin::TokenResponse& token, + std::vector<uint8_t> id, + std::string name); base::Optional<BioEnrollmentModality> modality; base::Optional<BioEnrollmentSubCommand> subcommand;
diff --git a/device/fido/bio/enrollment_handler.cc b/device/fido/bio/enrollment_handler.cc index 265f928..b7c77fdb 100644 --- a/device/fido/bio/enrollment_handler.cc +++ b/device/fido/bio/enrollment_handler.cc
@@ -68,7 +68,7 @@ weak_factory_.GetWeakPtr())); } -void BioEnrollmentHandler::Cancel(base::OnceClosure callback) { +void BioEnrollmentHandler::Cancel(StatusCallback callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker); status_callback_ = std::move(callback); @@ -86,6 +86,18 @@ weak_factory_.GetWeakPtr())); } +void BioEnrollmentHandler::RenameTemplate(std::vector<uint8_t> id, + std::string name, + StatusCallback callback) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker); + + status_callback_ = std::move(callback); + authenticator_->BioEnrollRename( + *pin_token_response_, std::move(id), std::move(name), + base::BindOnce(&BioEnrollmentHandler::OnRenameTemplate, + weak_factory_.GetWeakPtr())); +} + void BioEnrollmentHandler::DispatchRequest(FidoAuthenticator* authenticator) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker); authenticator->GetTouch(base::BindOnce(&BioEnrollmentHandler::OnTouch, @@ -220,9 +232,9 @@ std::move(response_callback_).Run(code, std::move(response)); } -void BioEnrollmentHandler::OnCancel(CtapDeviceResponseCode, +void BioEnrollmentHandler::OnCancel(CtapDeviceResponseCode code, base::Optional<BioEnrollmentResponse>) { - std::move(status_callback_).Run(); + std::move(status_callback_).Run(code); } void BioEnrollmentHandler::OnEnumerateTemplates( @@ -243,4 +255,10 @@ std::move(response_callback_).Run(code, std::move(response)); } +void BioEnrollmentHandler::OnRenameTemplate( + CtapDeviceResponseCode code, + base::Optional<BioEnrollmentResponse> response) { + std::move(status_callback_).Run(code); +} + } // namespace device
diff --git a/device/fido/bio/enrollment_handler.h b/device/fido/bio/enrollment_handler.h index 68cddaa..c7b838b8 100644 --- a/device/fido/bio/enrollment_handler.h +++ b/device/fido/bio/enrollment_handler.h
@@ -29,6 +29,7 @@ using ResponseCallback = base::OnceCallback<void(CtapDeviceResponseCode, base::Optional<BioEnrollmentResponse>)>; + using StatusCallback = base::OnceCallback<void(CtapDeviceResponseCode)>; BioEnrollmentHandler( service_manager::Connector* connector, @@ -43,8 +44,11 @@ void GetModality(ResponseCallback); void GetSensorInfo(ResponseCallback); void EnrollTemplate(ResponseCallback); - void Cancel(base::OnceClosure); + void Cancel(StatusCallback); void EnumerateTemplates(ResponseCallback); + void RenameTemplate(std::vector<uint8_t> id, + std::string name, + StatusCallback); private: // FidoRequestHandlerBase: @@ -65,6 +69,8 @@ void OnCancel(CtapDeviceResponseCode, base::Optional<BioEnrollmentResponse>); void OnEnumerateTemplates(CtapDeviceResponseCode, base::Optional<BioEnrollmentResponse>); + void OnRenameTemplate(CtapDeviceResponseCode, + base::Optional<BioEnrollmentResponse>); SEQUENCE_CHECKER(sequence_checker); @@ -73,7 +79,7 @@ ErrorCallback error_callback_; GetPINCallback get_pin_callback_; ResponseCallback response_callback_; - base::OnceClosure status_callback_; + StatusCallback status_callback_; base::Optional<pin::TokenResponse> pin_token_response_; base::WeakPtrFactory<BioEnrollmentHandler> weak_factory_;
diff --git a/device/fido/bio/enrollment_handler_unittest.cc b/device/fido/bio/enrollment_handler_unittest.cc index 67d522f4..4884e33e 100644 --- a/device/fido/bio/enrollment_handler_unittest.cc +++ b/device/fido/bio/enrollment_handler_unittest.cc
@@ -4,6 +4,7 @@ #include <vector> +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "base/bind.h" @@ -182,11 +183,14 @@ auto handler = MakeHandler(); ready_callback_.WaitForCallback(); - test::TestCallbackReceiver<> cb; + test::ValueCallbackReceiver<CtapDeviceResponseCode> cb; handler->Cancel(cb.callback()); cb.WaitForCallback(); + + EXPECT_EQ(cb.value(), CtapDeviceResponseCode::kSuccess); } +// Tests enumerating enrollments expecting a list of size 1. TEST_F(BioEnrollmentHandlerTest, Enumerate) { VirtualCtap2Device::Config config; config.pin_support = true; @@ -215,5 +219,31 @@ EXPECT_EQ(v, expected); } +// Tests renaming an enrollment (success and failure). +TEST_F(BioEnrollmentHandlerTest, Rename) { + VirtualCtap2Device::Config config; + config.pin_support = true; + config.bio_enrollment_support = true; + + virtual_device_factory_.SetCtap2Config(config); + + auto handler = MakeHandler(); + ready_callback_.WaitForCallback(); + + // Rename existing enrollment. + test::ValueCallbackReceiver<CtapDeviceResponseCode> cb0; + handler->RenameTemplate({0, 0, 0, 1}, "OtherFingerprint1", cb0.callback()); + + cb0.WaitForCallback(); + EXPECT_EQ(cb0.value(), CtapDeviceResponseCode::kSuccess); + + // Rename non-existent enrollment. + test::ValueCallbackReceiver<CtapDeviceResponseCode> cb1; + handler->RenameTemplate({0, 0, 0, 2}, "OtherFingerprint2", cb1.callback()); + + cb1.WaitForCallback(); + EXPECT_EQ(cb1.value(), CtapDeviceResponseCode::kCtap2ErrInvalidOption); +} + } // namespace } // namespace device
diff --git a/device/fido/fido_authenticator.cc b/device/fido/fido_authenticator.cc index 4f5fc96..1e2929a 100644 --- a/device/fido/fido_authenticator.cc +++ b/device/fido/fido_authenticator.cc
@@ -105,6 +105,13 @@ NOTREACHED(); } +void FidoAuthenticator::BioEnrollRename(pin::TokenResponse, + std::vector<uint8_t>, + std::string, + BioEnrollmentCallback) { + NOTREACHED(); +} + void FidoAuthenticator::Reset(ResetCallback callback) { std::move(callback).Run(CtapDeviceResponseCode::kCtap1ErrInvalidCommand, base::nullopt);
diff --git a/device/fido/fido_authenticator.h b/device/fido/fido_authenticator.h index afe0093..ca04ead 100644 --- a/device/fido/fido_authenticator.h +++ b/device/fido/fido_authenticator.h
@@ -174,6 +174,10 @@ virtual void BioEnrollFingerprint(pin::TokenResponse, BioEnrollmentCallback); virtual void BioEnrollCancel(BioEnrollmentCallback); virtual void BioEnrollEnumerate(pin::TokenResponse, BioEnrollmentCallback); + virtual void BioEnrollRename(pin::TokenResponse, + std::vector<uint8_t>, + std::string, + BioEnrollmentCallback); // Reset triggers a reset operation on the authenticator. This erases all // stored resident keys and any configured PIN.
diff --git a/device/fido/fido_device_authenticator.cc b/device/fido/fido_device_authenticator.cc index 6291da93..6c3e677 100644 --- a/device/fido/fido_device_authenticator.cc +++ b/device/fido/fido_device_authenticator.cc
@@ -527,6 +527,23 @@ base::BindOnce(&BioEnrollmentResponse::Parse)); } +void FidoDeviceAuthenticator::BioEnrollRename(pin::TokenResponse token, + std::vector<uint8_t> id, + std::string name, + BioEnrollmentCallback callback) { + DCHECK( + Options()->bio_enrollment_availability_preview != + AuthenticatorSupportedOptions::BioEnrollmentAvailability::kNotSupported); + + operation_ = std::make_unique< + Ctap2DeviceOperation<BioEnrollmentRequest, BioEnrollmentResponse>>( + device_.get(), + BioEnrollmentRequest::ForRename(token, std::move(id), std::move(name)), + std::move(callback), base::BindOnce(&BioEnrollmentResponse::Parse), + /*string_fixup_predicate=*/nullptr); + operation_->Start(); +} + void FidoDeviceAuthenticator::OnBioEnroll( pin::TokenResponse token, BioEnrollmentCallback callback,
diff --git a/device/fido/fido_device_authenticator.h b/device/fido/fido_device_authenticator.h index 6e8cdde4..2b99479 100644 --- a/device/fido/fido_device_authenticator.h +++ b/device/fido/fido_device_authenticator.h
@@ -84,6 +84,10 @@ void BioEnrollFingerprint(pin::TokenResponse, BioEnrollmentCallback) override; void BioEnrollCancel(BioEnrollmentCallback) override; void BioEnrollEnumerate(pin::TokenResponse, BioEnrollmentCallback) override; + void BioEnrollRename(pin::TokenResponse, + std::vector<uint8_t>, + std::string, + BioEnrollmentCallback) override; void Reset(ResetCallback callback) override; void Cancel() override;
diff --git a/device/fido/virtual_ctap2_device.cc b/device/fido/virtual_ctap2_device.cc index b7097cb..77eef9e 100644 --- a/device/fido/virtual_ctap2_device.cc +++ b/device/fido/virtual_ctap2_device.cc
@@ -1364,6 +1364,7 @@ return CtapDeviceResponseCode::kCtap2ErrCBORUnexpectedType; } + // List of enrollments currently on test key. cbor::Value::MapValue id0; id0.emplace(cbor::Value(static_cast<int>( BioEnrollmentTemplateInfoParam::kTemplateId)), @@ -1375,6 +1376,20 @@ cbor::Value::ArrayValue enumerated_ids; enumerated_ids.emplace_back(id0); + // Template id from subcommand parameters, if it exists. + base::Optional<std::vector<uint8_t>> template_id; + + auto params_it = request_map.find(cbor::Value( + static_cast<int>(BioEnrollmentRequestKey::kSubCommandParams))); + if (params_it != request_map.end()) { + const auto& params = params_it->second.GetMap(); + auto template_it = params.find(cbor::Value( + static_cast<int>(BioEnrollmentSubCommandParam::kTemplateId))); + if (template_it != params.end() && template_it->second.is_bytestring()) { + template_id = template_it->second.GetBytestring(); + } + } + switch (it->second.GetUnsigned()) { case static_cast<int>(SubCmd::kGetFingerprintSensorInfo): response_map.emplace( @@ -1405,13 +1420,18 @@ response_map.emplace( static_cast<int>(BioEnrollmentResponseKey::kRemainingSamples), 0); break; - case static_cast<int>(SubCmd::kCancelCurrentEnrollment): - return CtapDeviceResponseCode::kSuccess; case static_cast<int>(SubCmd::kEnumerateEnrollments): response_map.emplace( static_cast<int>(BioEnrollmentResponseKey::kTemplateInfos), enumerated_ids); break; + case static_cast<int>(SubCmd::kSetFriendlyName): + if (template_id && *template_id == std::vector<uint8_t>{0, 0, 0, 2}) { + return CtapDeviceResponseCode::kCtap2ErrInvalidOption; + } + [[fallthrough]]; + case static_cast<int>(SubCmd::kCancelCurrentEnrollment): + return CtapDeviceResponseCode::kSuccess; default: // Handle all other commands as if they were unsupported (will change // when support is added).
diff --git a/docs/gpu/gpu_pixel_testing_with_gold.md b/docs/gpu/gpu_pixel_testing_with_gold.md new file mode 100644 index 0000000..e9eab79a --- /dev/null +++ b/docs/gpu/gpu_pixel_testing_with_gold.md
@@ -0,0 +1,214 @@ +# GPU Pixel Testing With Gold + +This page describes in detail the GPU pixel tests that utilize Skia Gold for +storing and comparing images (the `pixel_skia_gold_test` type). This includes +information such as how Skia Gold works, how to triage images produced by these +tests, and working on Gold itself. + +[TOC] + +## Skia Gold + +[Gold][gold documentation] is an image diff service developed by the Skia team. +It was originally developed solely for Skia's usage and only supported +post-submit tests, but has been picked up by other projects such as Chromium and +PDFium and now supports trybots. Unlike other image diff solutions in Chromium, +comparisons are done in an external service instead of locally on the testing +machine. + +[gold documentation]: https://skia.org/dev/testing/skiagold + +### Why Gold + +Gold has three main advantages over the traditional local image comparison +historically used by Chromium: + +1. Triage time can be much lower. Because triaging is handled by an external +service, new golden images don't need to go through the CQ and wait for +waterfall bots to pick up the CL. Once an image is triaged in Gold, it +becomes immediately available for future test runs. +2. Gold supports multiple approved images per test. It is not uncommon for +tests to produce images that are visually indistinguishable, but differ in +a handful of pixels by a small RGB value. Fuzzy image diffing can solve this +problem, but introduces its own set of issues such as possibly causing a test +to erroneously pass. Since most tests that exhibit this behavior only actually +produce 2 or 3 possible valid images, being able to say that any of those +images are acceptable is simpler and less error-prone. +3. Better image storage. Traditionally, images had to either be included +directly in the repository or uploaded to a Google Storage bucket and pulled in +using the image's hash. The former allowed users to easily see which images were +currently approved, but storing large sized or numerous binary files in git is +generally discouraged due to the way git's history works. The latter worked +around the git issues, but made it much more difficult to actually see what was +being used since the only thing the user had to go on was a hash. Gold moves the +images out of the repository, but provides a GUI interface for easily seeing +which images are currently approved for a particular test. + +### How It Works + +Gold consists of two main parts: the Gold instance/service and the `goldctl` +binary. A Gold instance in turn consists of two parts: a Google Storage bucket +that data is uploaded to and a server running on GCE that ingests the data and +provides a way to triage diffs. `goldctl` simply provides a standardized way +of interacting with Gold - uploading data to the correct place, retrieving +baselines/golden information, etc. + +In general, the following order of events occurs when running a Gold-enabled +test: + +1. The test produces an image and passes it to `goldctl`, along with some +information about the hardware and software configuration that the image was +produced on, the test name, etc. +2. `goldctl` checks whether the hash of the produced image is in the list of +approved hashes. + 1. If it is, `goldctl` exits with a non-failing return code and nothing else + happens. At this point, the test is finished. + 2. If it is not, `goldctl` uploads the image and metadata to the storage + bucket and exits with a failing return code. +3. The server sees the new data in the bucket and ingests it, showing a new +untriaged image in the GUI. +4. A user approves the new image in the GUI, and the server adds the image's +hash to the baselines. See the [Waterfall Bots](#Waterfall-Bots) and +[Trybots](#Trybots) sections for specifics on this. +5. The next time the test is run, the new image is in the baselines, and +assuming the test produces the same image again, the test passes. + +While this is the general order of events, there are several differences between +waterfall/CI bots and trybots. + +#### Waterfall Bots + +Waterfall bots are the simpler of the two bot types. There is only a single +set of baselines to worry about, which is whatever baselines were approved for +a git revision. Additionally, any new images that are produced on waterfalls are +all lumped into the same group of "untriaged images on master", and any images +that are approved from here will immediately be added to the set of baselines +for master. + +Since not all waterfall bots have a trybot counterpart that can be relied upon +to catch newly produced images before a CL is committed, it is likely that a +change that produces new goldens on the CQ will end up making some of the +waterfall bots red for a bit, particularly those on chromium.gpu.fyi. They will +remain red until the new images are triaged as positive or the tests stop +producing the untriaged images. So, it is best to keep an eye out for a few +hours after your CL is committed for any new images from the waterfall bots that +need triaging. + +#### Trybots + +Trybots are a little more complicated when it comes to retrieving and approving +images. First, the set of baselines that are provided when requested by a test +is the union of the master baselines for the current revision and any baselines +that are unique to the CL. For example, if an image with the hash `abcd` is in +the master baselines for `FooTest` and the CL being tested has also approved +an image with the hash `abef` for `FooTest`, then the provided baselines will +contain both `abcd` and `abef` for `FooTest`. + +When an image associated with a CL is approved, the approval only applies to +that CL until the CL is merged. Once this happens, any baselines produced by the +CL are automatically merged into the master baselines for whatever git revision +the CL was merged as. In the above example, if the CL was merged as commit +`ffff`, then both `abcd` and `abef` would be approved images on master from +`ffff` onward. + +## Triaging Failures + +### Standard Workflow + +The current approach to getting the triage links for new images is: + +1. Navigate to the failed build. +2. Search for the failed step for the `pixel_skia_gold_test` test. +3. Click on the `shard #0 (failed)` link +4. Search for `untriaged` on the page and follow any links to +https://chrome-gpu-gold.skia.org/ that the search finds. +5. Triage images at those links (typically by approving them, but you can also +mark them as a negative if it is an image that should not be produced). In the +case of a negative image, a bug should be filed on [crbug] to investigate and +fix the cause of the that particular image being produced, as future +occurrences of it will cause the test to fail. Such bugs should include the +`Internals>GPU>Testing` component and whatever component is suitable for the +type of failing test (likely `Blink>WebGL`). + +[crbug]: https://crbug.com + +This is a known pain point about using Gold in Chromium, but should be +alleviated in the future with several coming improvements: + +1. Links will be reported in a build's Milo output for a step, so you can skip +digging through the task output. +2. A comment will be automatically posted to CLs that produce new images with a +link to triage them. + +In addition, you can see all currently untriaged images on master on the +[GPU Gold instance's main page][gpu gold instance] and currently untriaged +images for a CL by substituting the Gerrit CL number into +`https://chrome-gpu-gold.skia.org/search?issue=[CL Number]&unt=true&master=true`. + +[gpu gold instance]: https://chrome-gpu-gold.skia.org + +### Triaging A Specific Image + +If for some reason an image is not showing up in Gold but you know the hash, you +can manually navigate to the page for it by filling in the correct information +to `https://chrome-gpu-gold.skia.org/detail?test=[test_name]&digest=[hash]`. +From there, you should be able to triage it as normal. + +If this happens, please also file a bug in [Skia's bug tracker][skia crbug] so +that the root cause can be investigated and fixed. It's likely that you will +be unable to directly edit the owner, CC list, etc. directly, in which case +ping kjlubick@ with a link to the filed bug to help speed up triaging. Include +as much detail as possible, such as a links to the failed swarming task and +the triage link for the problematic image. + +[skia crbug]: https://bugs.chromium.org/p/skia + +## Working On Gold + +### Modifying Gold And goldctl + +Although uncommon, changes to the Gold service and `goldctl` binary may be +needed. To do so, simply get a checkout of the +[Skia infrastructure repo][skia infra repo] and go through the same steps as +a Chromium CL (`git cl upload`, etc.). + +[skia infra repo]: https://skia.googlesource.com/buildbot/ + +The Gold service code is located in the `//golden/` directory, while `goldctl` +is located in `//gold-client/`. Once your change is merged, you will have to +either contact kjlubick@google.com to roll the service version or follow the +steps in [Rolling goldctl](#Rolling-goldctl) to roll the `goldctl` version used +by Chromium. + +### Rolling goldctl + +`goldctl` is available as a CIPD package and is DEPSed in as part of `gclient +sync` To update the binary used in Chromium, perform the following steps: + +1. (One-time only) get an [infra checkout][infra repo] +2. Run `infra $ ./go/env.py` and run each of the commands it outputs to change +your GOPATH and other environment variables for your terminal +3. Update the Skia revision in [`deps.yaml`][deps yaml] to match the revision +of your `goldctl` CL (or some revision after it) +4. Run `infra $ ./go/deps.py update` and copy the list of repos it updated +(include this in your CL description) +5. Upload the changelist ([sample CL][sample roll cl]) +6. Once the CL is merged, wait until the git revision of your merged CL shows +up in the tags of one of the instances for the [CIPD package][goldctl package] +7. Update the [revision in DEPS][goldctl deps entry] to be the merged CL's +revision + +[infra repo]: https://chromium.googlesource.com/infra/infra/ +[deps yaml]: https://chromium.googlesource.com/infra/infra/+/91333d832a4d871b4219580dfb874b49a97e6da4/go/deps.yaml#432 +[sample roll cl]: https://chromium-review.googlesource.com/c/infra/infra/+/1493426 +[goldctl package]: https://chrome-infra-packages.appspot.com/p/skia/tools/goldctl/linux-amd64/+/ +[goldctl deps entry]: https://chromium.googlesource.com/chromium/src/+/6b7213a45382f01ac0a2efec1015545bd051da89/DEPS#1304 + +If you want to make sure that `goldctl` builds after the update before +committing (e.g. to ensure that no extra third party dependencies were added), +run the following after the `./go/deps.py update` step: + +1. `infra $ ./go/deps.py install` +2. `infra $ go install go.skia.org/infra/gold-client/cmd/goldctl` +3. `infra $ which goldctl` which should point to a binary in `infra/go/bin/` +4. `infra $ goldctl` to make sure it actually runs
diff --git a/extensions/browser/BUILD.gn b/extensions/browser/BUILD.gn index 3bd8e01..dd1eb2c0 100644 --- a/extensions/browser/BUILD.gn +++ b/extensions/browser/BUILD.gn
@@ -546,11 +546,13 @@ "//base", "//base/test:test_support", "//content/public/browser", + "//content/test:test_support", "//extensions/browser", "//extensions/common", "//extensions/common:test_support", "//services/data_decoder:lib", "//services/data_decoder/public/cpp:test_support", + "//services/network:test_support", "//testing/gmock", "//testing/gtest", ]
diff --git a/extensions/browser/DEPS b/extensions/browser/DEPS index 5d48ea7c..26f3cc44 100644 --- a/extensions/browser/DEPS +++ b/extensions/browser/DEPS
@@ -20,6 +20,7 @@ "+gpu/config", "+grit/extensions_strings.h", "+net", + "-net/url_request", # This directory contains build flags and does not pull all of PPAPI in. "+ppapi/buildflags", "+services/data_decoder/public",
diff --git a/extensions/browser/api/bluetooth/bluetooth_api_utils.cc b/extensions/browser/api/bluetooth/bluetooth_api_utils.cc index 965ccc7..8f352df82 100644 --- a/extensions/browser/api/bluetooth/bluetooth_api_utils.cc +++ b/extensions/browser/api/bluetooth/bluetooth_api_utils.cc
@@ -159,6 +159,11 @@ else out->inquiry_tx_power.reset(); + if (device.battery_percentage()) + out->battery_percentage.reset(new int(device.battery_percentage().value())); + else + out->battery_percentage.reset(); + #if defined(OS_LINUX) ConvertTransportToApi(device.GetType(), &(out->transport)); #endif
diff --git a/extensions/browser/api/declarative_webrequest/webrequest_condition_attribute.cc b/extensions/browser/api/declarative_webrequest/webrequest_condition_attribute.cc index 77b6059..07d7365 100644 --- a/extensions/browser/api/declarative_webrequest/webrequest_condition_attribute.cc +++ b/extensions/browser/api/declarative_webrequest/webrequest_condition_attribute.cc
@@ -32,7 +32,6 @@ #include "net/base/static_cookie_policy.h" #include "net/http/http_request_headers.h" #include "net/http/http_util.h" -#include "net/url_request/url_request.h" using base::CaseInsensitiveCompareASCII; using base::DictionaryValue;
diff --git a/extensions/browser/api/declarative_webrequest/webrequest_condition_attribute_unittest.cc b/extensions/browser/api/declarative_webrequest/webrequest_condition_attribute_unittest.cc index 4f65e65..f69e81d 100644 --- a/extensions/browser/api/declarative_webrequest/webrequest_condition_attribute_unittest.cc +++ b/extensions/browser/api/declarative_webrequest/webrequest_condition_attribute_unittest.cc
@@ -9,22 +9,13 @@ #include <memory> #include <utility> -#include "base/files/file_path.h" -#include "base/message_loop/message_loop.h" -#include "base/run_loop.h" #include "base/stl_util.h" #include "base/values.h" -#include "content/public/browser/resource_request_info.h" -#include "content/public/common/previews_state.h" #include "extensions/browser/api/declarative_webrequest/webrequest_condition.h" #include "extensions/browser/api/declarative_webrequest/webrequest_constants.h" #include "extensions/browser/api/extensions_api_client.h" #include "extensions/browser/api/web_request/web_request_info.h" -#include "net/base/request_priority.h" -#include "net/test/embedded_test_server/embedded_test_server.h" -#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" -#include "net/url_request/url_request.h" -#include "net/url_request/url_request_test_util.h" +#include "net/http/http_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" @@ -39,16 +30,7 @@ namespace { const char kUnknownConditionName[] = "unknownType"; -base::FilePath TestDataPath(base::StringPiece relative_to_src) { - base::FilePath src_dir; - CHECK(base::PathService::Get(base::DIR_SOURCE_ROOT, &src_dir)); - return src_dir.AppendASCII(relative_to_src); -} - TEST(WebRequestConditionAttributeTest, CreateConditionAttribute) { - // Necessary for TestURLRequest. - base::MessageLoopForIO message_loop; - std::string error; scoped_refptr<const WebRequestConditionAttribute> result; base::Value string_value("main_frame"); @@ -87,9 +69,6 @@ } TEST(WebRequestConditionAttributeTest, ResourceType) { - // Necessary for TestURLRequest. - base::MessageLoopForIO message_loop; - std::string error; base::ListValue resource_types; // The 'sub_frame' value is chosen arbitrarily, so as the corresponding @@ -103,64 +82,29 @@ ASSERT_TRUE(attribute.get()); EXPECT_EQ(std::string(keys::kResourceTypeKey), attribute->GetName()); - net::TestURLRequestContext context; - std::unique_ptr<net::URLRequest> url_request_ok(context.CreateRequest( - GURL("http://www.example.com"), net::DEFAULT_PRIORITY, nullptr, - TRAFFIC_ANNOTATION_FOR_TESTS)); - content::ResourceRequestInfo::AllocateForTesting( - url_request_ok.get(), content::ResourceType::kSubFrame, - NULL, // context - -1, // render_process_id - -1, // render_view_id - -1, // render_frame_id - false, // is_main_frame - content::ResourceInterceptPolicy::kAllowAll, - false, // is_async - content::PREVIEWS_OFF, - nullptr); // navigation_ui_data - WebRequestInfo request_ok_info(url_request_ok.get()); + WebRequestInfoInitParams ok_params; + ok_params.type = content::ResourceType::kSubFrame; + ok_params.web_request_type = WebRequestResourceType::SUB_FRAME; + WebRequestInfo request_ok_info(std::move(ok_params)); EXPECT_TRUE(attribute->IsFulfilled( WebRequestData(&request_ok_info, ON_BEFORE_REQUEST))); - std::unique_ptr<net::URLRequest> url_request_fail(context.CreateRequest( - GURL("http://www.example.com"), net::DEFAULT_PRIORITY, nullptr, - TRAFFIC_ANNOTATION_FOR_TESTS)); - content::ResourceRequestInfo::AllocateForTesting( - url_request_fail.get(), content::ResourceType::kMainFrame, - NULL, // context - -1, // render_process_id - -1, // render_view_id - -1, // render_frame_id - true, // is_main_frame - content::ResourceInterceptPolicy::kAllowAll, - false, // is_async - content::PREVIEWS_OFF, - nullptr); // navigation_ui_data - WebRequestInfo request_fail_info(url_request_fail.get()); + WebRequestInfoInitParams fail_params; + ok_params.type = content::ResourceType::kMainFrame; + ok_params.web_request_type = WebRequestResourceType::MAIN_FRAME; + WebRequestInfo request_fail_info(std::move(fail_params)); EXPECT_FALSE(attribute->IsFulfilled( WebRequestData(&request_fail_info, ON_BEFORE_REQUEST))); } TEST(WebRequestConditionAttributeTest, ContentType) { - // Necessary for TestURLRequest. - base::MessageLoopForIO message_loop; - std::string error; scoped_refptr<const WebRequestConditionAttribute> result; - net::EmbeddedTestServer test_server; - test_server.ServeFilesFromDirectory(TestDataPath( - "chrome/test/data/extensions/api_test/webrequest/declarative")); - ASSERT_TRUE(test_server.Start()); - - net::TestURLRequestContext context; - net::TestDelegate delegate; - std::unique_ptr<net::URLRequest> url_request(context.CreateRequest( - test_server.GetURL("/headers.html"), net::DEFAULT_PRIORITY, &delegate, - TRAFFIC_ANNOTATION_FOR_TESTS)); - url_request->Start(); - WebRequestInfo request_info(url_request.get()); - base::RunLoop().Run(); + WebRequestInfo request_info(WebRequestInfoInitParams{}); + auto response_headers = base::MakeRefCounted<net::HttpResponseHeaders>( + net::HttpUtil::AssembleRawHeaders("HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain; UTF-8\r\n")); base::ListValue content_types; content_types.AppendString("text/plain"); @@ -170,9 +114,9 @@ EXPECT_EQ("", error); ASSERT_TRUE(attribute_include.get()); EXPECT_FALSE(attribute_include->IsFulfilled(WebRequestData( - &request_info, ON_BEFORE_REQUEST, url_request->response_headers()))); + &request_info, ON_BEFORE_REQUEST, response_headers.get()))); EXPECT_TRUE(attribute_include->IsFulfilled(WebRequestData( - &request_info, ON_HEADERS_RECEIVED, url_request->response_headers()))); + &request_info, ON_HEADERS_RECEIVED, response_headers.get()))); EXPECT_EQ(std::string(keys::kContentTypeKey), attribute_include->GetName()); scoped_refptr<const WebRequestConditionAttribute> attribute_exclude = @@ -181,7 +125,7 @@ EXPECT_EQ("", error); ASSERT_TRUE(attribute_exclude.get()); EXPECT_FALSE(attribute_exclude->IsFulfilled(WebRequestData( - &request_info, ON_HEADERS_RECEIVED, url_request->response_headers()))); + &request_info, ON_HEADERS_RECEIVED, response_headers.get()))); content_types.Clear(); content_types.AppendString("something/invalid"); @@ -191,7 +135,7 @@ EXPECT_EQ("", error); ASSERT_TRUE(attribute_unincluded.get()); EXPECT_FALSE(attribute_unincluded->IsFulfilled(WebRequestData( - &request_info, ON_HEADERS_RECEIVED, url_request->response_headers()))); + &request_info, ON_HEADERS_RECEIVED, response_headers.get()))); scoped_refptr<const WebRequestConditionAttribute> attribute_unexcluded = WebRequestConditionAttribute::Create( @@ -199,16 +143,13 @@ EXPECT_EQ("", error); ASSERT_TRUE(attribute_unexcluded.get()); EXPECT_TRUE(attribute_unexcluded->IsFulfilled(WebRequestData( - &request_info, ON_HEADERS_RECEIVED, url_request->response_headers()))); + &request_info, ON_HEADERS_RECEIVED, response_headers.get()))); EXPECT_EQ(std::string(keys::kExcludeContentTypeKey), attribute_unexcluded->GetName()); } // Testing WebRequestConditionAttributeThirdParty. TEST(WebRequestConditionAttributeTest, ThirdParty) { - // Necessary for TestURLRequest. - base::MessageLoopForIO message_loop; - std::string error; const Value value_true(true); // This attribute matches only third party requests. @@ -234,31 +175,33 @@ const GURL url_empty; const GURL url_a("http://a.com"); const GURL url_b("http://b.com"); - net::TestURLRequestContext context; - net::TestDelegate delegate; - std::unique_ptr<net::URLRequest> url_request(context.CreateRequest( - url_a, net::DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS)); for (unsigned int i = 1; i <= kLastActiveStage; i <<= 1) { if (!(kActiveStages & i)) continue; const RequestStage stage = static_cast<RequestStage>(i); - url_request->set_site_for_cookies(url_empty); - WebRequestInfo request_info1(url_request.get()); + WebRequestInfoInitParams empty_params; + empty_params.url = url_a; + empty_params.site_for_cookies = url_empty; + WebRequestInfo request_info1(std::move(empty_params)); EXPECT_TRUE(third_party_attribute->IsFulfilled( WebRequestData(&request_info1, stage))); EXPECT_FALSE(first_party_attribute->IsFulfilled( WebRequestData(&request_info1, stage))); - url_request->set_site_for_cookies(url_b); - WebRequestInfo request_info2(url_request.get()); + WebRequestInfoInitParams b_params; + b_params.url = url_a; + b_params.site_for_cookies = url_b; + WebRequestInfo request_info2(std::move(b_params)); EXPECT_TRUE(third_party_attribute->IsFulfilled( WebRequestData(&request_info2, stage))); EXPECT_FALSE(first_party_attribute->IsFulfilled( WebRequestData(&request_info2, stage))); - url_request->set_site_for_cookies(url_a); - WebRequestInfo request_info3(url_request.get()); + WebRequestInfoInitParams a_params; + a_params.url = url_a; + a_params.site_for_cookies = url_a; + WebRequestInfo request_info3(std::move(a_params)); EXPECT_FALSE(third_party_attribute->IsFulfilled( WebRequestData(&request_info3, stage))); EXPECT_TRUE(first_party_attribute->IsFulfilled( @@ -271,9 +214,6 @@ // applicable stages, one for each stage applicable for that stage, and one // applicable in all stages. TEST(WebRequestConditionAttributeTest, Stages) { - // Necessary for TestURLRequest. - base::MessageLoopForIO message_loop; - typedef std::pair<RequestStage, const char*> StageNamePair; static const StageNamePair active_stages[] = { StageNamePair(ON_BEFORE_REQUEST, keys::kOnBeforeRequestEnum), @@ -327,13 +267,7 @@ ASSERT_TRUE(one_stage_attributes.back().get() != NULL); } - const GURL url_empty; - net::TestURLRequestContext context; - net::TestDelegate delegate; - std::unique_ptr<net::URLRequest> url_request( - context.CreateRequest(url_empty, net::DEFAULT_PRIORITY, &delegate, - TRAFFIC_ANNOTATION_FOR_TESTS)); - WebRequestInfo request_info(url_request.get()); + WebRequestInfo request_info(WebRequestInfoInitParams{}); for (size_t i = 0; i < base::size(active_stages); ++i) { EXPECT_FALSE(empty_attribute->IsFulfilled( @@ -415,15 +349,13 @@ return dictionary; } -// Returns whether the response headers from |url_request| satisfy the match +// Returns whether the response headers from |request_info| satisfy the match // criteria given in |tests|. For at least one |i| all tests from |tests[i]| -// must pass. If |positive_test| is true, the dictionary is interpreted as the -// containsHeaders property of a RequestMatcher, otherwise as -// doesNotContainHeaders. -void MatchAndCheck(const std::vector< std::vector<const std::string*> >& tests, +// must pass. +void MatchAndCheck(const std::vector<std::vector<const std::string*>>& tests, const std::string& key, RequestStage stage, - net::URLRequest* url_request, + const WebRequestInfo& request_info, bool* result) { base::ListValue contains_headers; for (size_t i = 0; i < tests.size(); ++i) { @@ -440,9 +372,8 @@ ASSERT_TRUE(attribute.get()); EXPECT_EQ(key, attribute->GetName()); - WebRequestInfo request_info(url_request); - *result = attribute->IsFulfilled( - WebRequestData(&request_info, stage, url_request->response_headers())); + *result = attribute->IsFulfilled(WebRequestData( + &request_info, stage, request_info.response_headers.get())); } } // namespace @@ -452,18 +383,9 @@ // "ResponseHeaders" (below), because the header-matching code is shared // by both types of condition attributes, so it is enough to test it once. TEST(WebRequestConditionAttributeTest, RequestHeaders) { - // Necessary for TestURLRequest. - base::MessageLoopForIO message_loop; - - net::TestURLRequestContext context; - net::TestDelegate delegate; - std::unique_ptr<net::URLRequest> url_request(context.CreateRequest( - GURL("http://example.com"), // Dummy URL. - net::DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS)); - url_request->SetExtraRequestHeaderByName( - "Custom-header", "custom/value", true /* overwrite */); - url_request->Start(); - base::RunLoop().Run(); + WebRequestInfoInitParams params; + params.extra_request_headers.SetHeader("Custom-header", "custom/value"); + WebRequestInfo request_info(std::move(params)); std::vector<std::vector<const std::string*> > tests; bool result = false; @@ -480,12 +402,11 @@ const size_t kPassingConditionSizes[] = {base::size(kPassingCondition)}; GetArrayAsVector(kPassingCondition, kPassingConditionSizes, 1u, &tests); // Positive filter, passing (conjunction of tests). - MatchAndCheck( - tests, keys::kRequestHeadersKey, stage, url_request.get(), &result); + MatchAndCheck(tests, keys::kRequestHeadersKey, stage, request_info, &result); EXPECT_TRUE(result); // Negative filter, failing (conjunction of tests). - MatchAndCheck(tests, keys::kExcludeRequestHeadersKey, stage, - url_request.get(), &result); + MatchAndCheck(tests, keys::kExcludeRequestHeadersKey, stage, request_info, + &result); EXPECT_FALSE(result); // Second set of test data -- failing disjunction. @@ -498,35 +419,32 @@ const size_t kFailConditionSizes[] = { 2u, 2u, 2u, 2u }; GetArrayAsVector(kFailCondition, kFailConditionSizes, 4u, &tests); // Positive filter, failing (disjunction of tests). - MatchAndCheck(tests, keys::kRequestHeadersKey, stage, url_request.get(), - &result); + MatchAndCheck(tests, keys::kRequestHeadersKey, stage, request_info, &result); EXPECT_FALSE(result); // Negative filter, passing (disjunction of tests). - MatchAndCheck(tests, keys::kExcludeRequestHeadersKey, stage, - url_request.get(), &result); + MatchAndCheck(tests, keys::kExcludeRequestHeadersKey, stage, request_info, + &result); EXPECT_TRUE(result); // Third set of test data, corner case -- empty disjunction. GetArrayAsVector(NULL, NULL, 0u, &tests); // Positive filter, failing (no test to pass). - MatchAndCheck(tests, keys::kRequestHeadersKey, stage, url_request.get(), - &result); + MatchAndCheck(tests, keys::kRequestHeadersKey, stage, request_info, &result); EXPECT_FALSE(result); // Negative filter, passing (no test to fail). - MatchAndCheck(tests, keys::kExcludeRequestHeadersKey, stage, - url_request.get(), &result); + MatchAndCheck(tests, keys::kExcludeRequestHeadersKey, stage, request_info, + &result); EXPECT_TRUE(result); // Fourth set of test data, corner case -- empty conjunction. const size_t kEmptyConjunctionSizes[] = { 0u }; GetArrayAsVector(NULL, kEmptyConjunctionSizes, 1u, &tests); // Positive filter, passing (trivial test). - MatchAndCheck(tests, keys::kRequestHeadersKey, stage, url_request.get(), - &result); + MatchAndCheck(tests, keys::kRequestHeadersKey, stage, request_info, &result); EXPECT_TRUE(result); // Negative filter, failing. - MatchAndCheck(tests, keys::kExcludeRequestHeadersKey, stage, - url_request.get(), &result); + MatchAndCheck(tests, keys::kExcludeRequestHeadersKey, stage, request_info, + &result); EXPECT_FALSE(result); } @@ -536,21 +454,17 @@ // 3. Negating the match in case of 'doesNotContainHeaders'. TEST(WebRequestConditionAttributeTest, ResponseHeaders) { ExtensionsAPIClient api_client; - // Necessary for TestURLRequest. - base::MessageLoopForIO message_loop; - - net::EmbeddedTestServer test_server; - test_server.ServeFilesFromDirectory(TestDataPath( - "chrome/test/data/extensions/api_test/webrequest/declarative")); - ASSERT_TRUE(test_server.Start()); - - net::TestURLRequestContext context; - net::TestDelegate delegate; - std::unique_ptr<net::URLRequest> url_request(context.CreateRequest( - test_server.GetURL("/headers.html"), net::DEFAULT_PRIORITY, &delegate, - TRAFFIC_ANNOTATION_FOR_TESTS)); - url_request->Start(); - base::RunLoop().Run(); + WebRequestInfo request_info(WebRequestInfoInitParams{}); + request_info.response_headers = + base::MakeRefCounted<net::HttpResponseHeaders>( + net::HttpUtil::AssembleRawHeaders( + "HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain; UTF-8\r\n" + "Custom-Header: custom/value\r\n" + "Custom-Header-B: valueA\r\n" + "Custom-Header-B: valueB\r\n" + "Custom-Header-C: valueC, valueD\r\n" + "Custom-Header-D:\r\n")); // In all the tests below we assume that the server includes the headers // Custom-Header: custom/value @@ -574,8 +488,7 @@ }; const size_t kPassingConditionSizes[] = {base::size(kPassingCondition)}; GetArrayAsVector(kPassingCondition, kPassingConditionSizes, 1u, &tests); - MatchAndCheck(tests, keys::kResponseHeadersKey, stage, url_request.get(), - &result); + MatchAndCheck(tests, keys::kResponseHeadersKey, stage, request_info, &result); EXPECT_TRUE(result); // 1.b. -- None of the following tests in the discjunction should pass. @@ -587,8 +500,7 @@ }; const size_t kFailConditionSizes[] = { 2u, 2u, 2u, 2u }; GetArrayAsVector(kFailCondition, kFailConditionSizes, 4u, &tests); - MatchAndCheck(tests, keys::kResponseHeadersKey, stage, url_request.get(), - &result); + MatchAndCheck(tests, keys::kResponseHeadersKey, stage, request_info, &result); EXPECT_FALSE(result); // 1.c. -- This should fail (mixing name and value from different headers) @@ -598,8 +510,7 @@ }; const size_t kMixingConditionSizes[] = {base::size(kMixingCondition)}; GetArrayAsVector(kMixingCondition, kMixingConditionSizes, 1u, &tests); - MatchAndCheck(tests, keys::kResponseHeadersKey, stage, url_request.get(), - &result); + MatchAndCheck(tests, keys::kResponseHeadersKey, stage, request_info, &result); EXPECT_FALSE(result); // 1.d. -- Test handling multiple values for one header (both should pass). @@ -609,8 +520,7 @@ }; const size_t kMoreValues1Sizes[] = {base::size(kMoreValues1)}; GetArrayAsVector(kMoreValues1, kMoreValues1Sizes, 1u, &tests); - MatchAndCheck(tests, keys::kResponseHeadersKey, stage, url_request.get(), - &result); + MatchAndCheck(tests, keys::kResponseHeadersKey, stage, request_info, &result); EXPECT_TRUE(result); const std::string kMoreValues2[] = { keys::kNameEqualsKey, "Custom-header-b", @@ -618,8 +528,7 @@ }; const size_t kMoreValues2Sizes[] = {base::size(kMoreValues2)}; GetArrayAsVector(kMoreValues2, kMoreValues2Sizes, 1u, &tests); - MatchAndCheck(tests, keys::kResponseHeadersKey, stage, url_request.get(), - &result); + MatchAndCheck(tests, keys::kResponseHeadersKey, stage, request_info, &result); EXPECT_TRUE(result); // 1.e. -- This should fail as conjunction but pass as disjunction. @@ -630,14 +539,12 @@ // First disjunction, no conflict. const size_t kNoConflictSizes[] = { 2u, 2u }; GetArrayAsVector(kConflict, kNoConflictSizes, 2u, &tests); - MatchAndCheck(tests, keys::kResponseHeadersKey, stage, url_request.get(), - &result); + MatchAndCheck(tests, keys::kResponseHeadersKey, stage, request_info, &result); EXPECT_TRUE(result); // Then conjunction, conflict. const size_t kConflictSizes[] = {base::size(kConflict)}; GetArrayAsVector(kConflict, kConflictSizes, 1u, &tests); - MatchAndCheck(tests, keys::kResponseHeadersKey, stage, url_request.get(), - &result); + MatchAndCheck(tests, keys::kResponseHeadersKey, stage, request_info, &result); EXPECT_FALSE(result); // 1.f. -- This should pass, checking for correct treatment of ',' in values. @@ -647,8 +554,7 @@ }; const size_t kCommaSizes[] = {base::size(kComma)}; GetArrayAsVector(kComma, kCommaSizes, 1u, &tests); - MatchAndCheck(tests, keys::kResponseHeadersKey, stage, url_request.get(), - &result); + MatchAndCheck(tests, keys::kResponseHeadersKey, stage, request_info, &result); EXPECT_TRUE(result); // 1.g. -- This should pass, empty values are values as well. @@ -658,8 +564,7 @@ }; const size_t kEmptySizes[] = {base::size(kEmpty)}; GetArrayAsVector(kEmpty, kEmptySizes, 1u, &tests); - MatchAndCheck(tests, keys::kResponseHeadersKey, stage, url_request.get(), - &result); + MatchAndCheck(tests, keys::kResponseHeadersKey, stage, request_info, &result); EXPECT_TRUE(result); // 1.h. -- Values are case-sensitive, this should fail. @@ -675,8 +580,7 @@ }; const size_t kLowercaseSizes[] = { 4u, 4u, 4u, 4u }; // As disjunction. GetArrayAsVector(kLowercase, kLowercaseSizes, 4u, &tests); - MatchAndCheck(tests, keys::kResponseHeadersKey, stage, url_request.get(), - &result); + MatchAndCheck(tests, keys::kResponseHeadersKey, stage, request_info, &result); EXPECT_FALSE(result); // 1.i. -- Names are case-insensitive, this should pass. @@ -688,8 +592,7 @@ }; const size_t kUppercaseSizes[] = {base::size(kUppercase)}; // Conjunction. GetArrayAsVector(kUppercase, kUppercaseSizes, 1u, &tests); - MatchAndCheck(tests, keys::kResponseHeadersKey, stage, url_request.get(), - &result); + MatchAndCheck(tests, keys::kResponseHeadersKey, stage, request_info, &result); EXPECT_TRUE(result); // 2.a. -- This should pass as disjunction, because one of the tests passes. @@ -701,8 +604,7 @@ }; const size_t kDisjunctionSizes[] = { 2u, 2u, 2u, 2u }; GetArrayAsVector(kDisjunction, kDisjunctionSizes, 4u, &tests); - MatchAndCheck(tests, keys::kResponseHeadersKey, stage, url_request.get(), - &result); + MatchAndCheck(tests, keys::kResponseHeadersKey, stage, request_info, &result); EXPECT_TRUE(result); // 3.a. -- This should pass. @@ -712,8 +614,8 @@ }; const size_t kNonExistentSizes[] = {base::size(kNonExistent)}; GetArrayAsVector(kNonExistent, kNonExistentSizes, 1u, &tests); - MatchAndCheck(tests, keys::kExcludeResponseHeadersKey, stage, - url_request.get(), &result); + MatchAndCheck(tests, keys::kExcludeResponseHeadersKey, stage, request_info, + &result); EXPECT_TRUE(result); // 3.b. -- This should fail. @@ -723,34 +625,25 @@ }; const size_t kExistingSize[] = {base::size(kExisting)}; GetArrayAsVector(kExisting, kExistingSize, 1u, &tests); - MatchAndCheck(tests, keys::kExcludeResponseHeadersKey, stage, - url_request.get(), &result); + MatchAndCheck(tests, keys::kExcludeResponseHeadersKey, stage, request_info, + &result); EXPECT_FALSE(result); } TEST(WebRequestConditionAttributeTest, HideResponseHeaders) { - // Necessary for TestURLRequest. - base::MessageLoopForIO message_loop; - - net::EmbeddedTestServer test_server; - test_server.ServeFilesFromDirectory(TestDataPath( - "chrome/test/data/extensions/api_test/webrequest/declarative")); - ASSERT_TRUE(test_server.Start()); - - net::TestURLRequestContext context; - net::TestDelegate delegate; - GURL url = test_server.GetURL("/headers.html"); - std::unique_ptr<net::URLRequest> url_request(context.CreateRequest( - url, net::DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS)); - url_request->Start(); - base::RunLoop().Run(); + const GURL url("http://a.com"); + WebRequestInfoInitParams params; + params.url = url; + WebRequestInfo request_info(std::move(params)); + request_info.response_headers = + base::MakeRefCounted<net::HttpResponseHeaders>( + net::HttpUtil::AssembleRawHeaders( + "HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain; UTF-8\r\n" + "Custom-Header: custom/value\r\n")); // In all the test below we assume that the server includes the headers // Custom-Header: custom/value - // Custom-Header-B: valueA - // Custom-Header-B: valueB - // Custom-Header-C: valueC, valueD - // Custom-Header-D: std::vector<std::vector<const std::string*>> tests; bool result; @@ -762,7 +655,7 @@ { // Default client does not hide the response header. ExtensionsAPIClient api_client; - MatchAndCheck(tests, keys::kResponseHeadersKey, stage, url_request.get(), + MatchAndCheck(tests, keys::kResponseHeadersKey, stage, request_info, &result); EXPECT_TRUE(result); } @@ -787,7 +680,7 @@ }; TestExtensionsAPIClient api_client(url); - MatchAndCheck(tests, keys::kResponseHeadersKey, stage, url_request.get(), + MatchAndCheck(tests, keys::kResponseHeadersKey, stage, request_info, &result); EXPECT_FALSE(result); }
diff --git a/extensions/browser/api/declarative_webrequest/webrequest_condition_unittest.cc b/extensions/browser/api/declarative_webrequest/webrequest_condition_unittest.cc index 31fb92b..2534877 100644 --- a/extensions/browser/api/declarative_webrequest/webrequest_condition_unittest.cc +++ b/extensions/browser/api/declarative_webrequest/webrequest_condition_unittest.cc
@@ -7,18 +7,11 @@ #include <memory> #include <set> -#include "base/message_loop/message_loop.h" #include "base/test/values_test_util.h" #include "base/values.h" #include "components/url_matcher/url_matcher_constants.h" -#include "content/public/browser/resource_request_info.h" -#include "content/public/common/previews_state.h" #include "extensions/browser/api/declarative_webrequest/webrequest_constants.h" #include "extensions/browser/api/web_request/web_request_info.h" -#include "net/base/request_priority.h" -#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" -#include "net/url_request/url_request.h" -#include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" using url_matcher::URLMatcher; @@ -27,8 +20,6 @@ namespace extensions { TEST(WebRequestConditionTest, CreateCondition) { - // Necessary for TestURLRequest. - base::MessageLoopForIO message_loop; URLMatcher matcher; std::string error; @@ -77,22 +68,12 @@ result->GetURLMatcherConditionSets(&url_matcher_condition_set); matcher.AddConditionSets(url_matcher_condition_set); - net::TestURLRequestContext context; const GURL http_url("http://www.example.com"); - std::unique_ptr<net::URLRequest> match_request(context.CreateRequest( - http_url, net::DEFAULT_PRIORITY, nullptr, TRAFFIC_ANNOTATION_FOR_TESTS)); - content::ResourceRequestInfo::AllocateForTesting( - match_request.get(), content::ResourceType::kMainFrame, - NULL, // context - -1, // render_process_id - -1, // render_view_id - -1, // render_frame_id - true, // is_main_frame - content::ResourceInterceptPolicy::kAllowAll, - false, // is_async - content::PREVIEWS_OFF, - nullptr); // navigation_ui_data - WebRequestInfo match_request_info(match_request.get()); + WebRequestInfoInitParams match_params; + match_params.url = http_url; + match_params.type = content::ResourceType::kMainFrame; + match_params.web_request_type = WebRequestResourceType::MAIN_FRAME; + WebRequestInfo match_request_info(std::move(match_params)); WebRequestData data(&match_request_info, ON_BEFORE_REQUEST); WebRequestDataWithMatchIds request_data(&data); request_data.url_match_ids = matcher.MatchURL(http_url); @@ -100,20 +81,13 @@ EXPECT_TRUE(result->IsFulfilled(request_data)); const GURL https_url("https://www.example.com"); - std::unique_ptr<net::URLRequest> wrong_resource_type(context.CreateRequest( - https_url, net::DEFAULT_PRIORITY, nullptr, TRAFFIC_ANNOTATION_FOR_TESTS)); - content::ResourceRequestInfo::AllocateForTesting( - wrong_resource_type.get(), content::ResourceType::kSubFrame, - NULL, // context - -1, // render_process_id - -1, // render_view_id - -1, // render_frame_id - false, // is_main_frame - content::ResourceInterceptPolicy::kAllowAll, - false, // is_async - content::PREVIEWS_OFF, - nullptr); // navigation_ui_data - WebRequestInfo wrong_resource_type_request_info(wrong_resource_type.get()); + WebRequestInfoInitParams wrong_resource_type_params; + wrong_resource_type_params.url = https_url; + wrong_resource_type_params.type = content::ResourceType::kSubFrame; + wrong_resource_type_params.web_request_type = + WebRequestResourceType::SUB_FRAME; + WebRequestInfo wrong_resource_type_request_info( + std::move(wrong_resource_type_params)); data.request = &wrong_resource_type_request_info; request_data.url_match_ids = matcher.MatchURL(http_url); // Make sure IsFulfilled does not fail because of URL matching. @@ -122,8 +96,6 @@ } TEST(WebRequestConditionTest, CreateConditionFirstPartyForCookies) { - // Necessary for TestURLRequest. - base::MessageLoopForIO message_loop; URLMatcher matcher; std::string error; @@ -144,29 +116,19 @@ result->GetURLMatcherConditionSets(&url_matcher_condition_set); matcher.AddConditionSets(url_matcher_condition_set); - net::TestURLRequestContext context; const GURL http_url("http://www.example.com"); const GURL first_party_url("http://fpfc.example.com"); - std::unique_ptr<net::URLRequest> match_request(context.CreateRequest( - http_url, net::DEFAULT_PRIORITY, nullptr, TRAFFIC_ANNOTATION_FOR_TESTS)); - WebRequestInfo match_request_info(match_request.get()); + WebRequestInfoInitParams match_params; + match_params.url = http_url; + match_params.type = content::ResourceType::kMainFrame; + match_params.web_request_type = WebRequestResourceType::MAIN_FRAME; + WebRequestInfo match_request_info(std::move(match_params)); WebRequestData data(&match_request_info, ON_BEFORE_REQUEST); WebRequestDataWithMatchIds request_data(&data); request_data.url_match_ids = matcher.MatchURL(http_url); EXPECT_EQ(0u, request_data.url_match_ids.size()); request_data.first_party_url_match_ids = matcher.MatchURL(first_party_url); EXPECT_EQ(1u, request_data.first_party_url_match_ids.size()); - content::ResourceRequestInfo::AllocateForTesting( - match_request.get(), content::ResourceType::kMainFrame, - NULL, // context - -1, // render_process_id - -1, // render_view_id - -1, // render_frame_id - true, // is_main_frame - content::ResourceInterceptPolicy::kAllowAll, - false, // is_async - content::PREVIEWS_OFF, - nullptr); // navigation_ui_data EXPECT_TRUE(result->IsFulfilled(request_data)); } @@ -177,8 +139,6 @@ // 2. An empty condition (in particular, without UrlFilter attributes) is // always fulfilled. TEST(WebRequestConditionTest, NoUrlAttributes) { - // Necessary for TestURLRequest. - base::MessageLoopForIO message_loop; URLMatcher matcher; std::string error; @@ -227,12 +187,10 @@ EXPECT_EQ("", error); ASSERT_TRUE(condition_no_url_false.get()); - net::TestURLRequestContext context; - std::unique_ptr<net::URLRequest> https_request(context.CreateRequest( - GURL("https://www.example.com"), net::DEFAULT_PRIORITY, nullptr, - TRAFFIC_ANNOTATION_FOR_TESTS)); - https_request->set_site_for_cookies(GURL("https://www.example.com")); - WebRequestInfo https_request_info(https_request.get()); + WebRequestInfoInitParams params; + params.url = GURL("https://www.example.com"); + params.site_for_cookies = GURL("https://www.example.com"); + WebRequestInfo https_request_info(std::move(params)); // 1. A non-empty condition without UrlFilter attributes is fulfilled iff its // attributes are fulfilled. @@ -251,8 +209,6 @@ } TEST(WebRequestConditionTest, CreateConditionSet) { - // Necessary for TestURLRequest. - base::MessageLoopForIO message_loop; URLMatcher matcher; WebRequestConditionSet::Values conditions; @@ -291,10 +247,9 @@ // Test that the result is correct and matches http://www.example.com and // https://www.example.com GURL http_url("http://www.example.com"); - net::TestURLRequestContext context; - std::unique_ptr<net::URLRequest> http_request(context.CreateRequest( - http_url, net::DEFAULT_PRIORITY, nullptr, TRAFFIC_ANNOTATION_FOR_TESTS)); - WebRequestInfo http_request_info(http_request.get()); + WebRequestInfoInitParams http_params; + http_params.url = http_url; + WebRequestInfo http_request_info(std::move(http_params)); WebRequestData data(&http_request_info, ON_BEFORE_REQUEST); WebRequestDataWithMatchIds request_data(&data); request_data.url_match_ids = matcher.MatchURL(http_url); @@ -305,9 +260,9 @@ GURL https_url("https://www.example.com"); request_data.url_match_ids = matcher.MatchURL(https_url); EXPECT_EQ(1u, request_data.url_match_ids.size()); - std::unique_ptr<net::URLRequest> https_request(context.CreateRequest( - https_url, net::DEFAULT_PRIORITY, nullptr, TRAFFIC_ANNOTATION_FOR_TESTS)); - WebRequestInfo https_request_info(https_request.get()); + WebRequestInfoInitParams https_params; + https_params.url = https_url; + WebRequestInfo https_request_info(std::move(https_params)); data.request = &https_request_info; EXPECT_TRUE(result->IsFulfilled(*(request_data.url_match_ids.begin()), request_data)); @@ -316,17 +271,14 @@ GURL https_foo_url("https://foo.example.com"); request_data.url_match_ids = matcher.MatchURL(https_foo_url); EXPECT_EQ(0u, request_data.url_match_ids.size()); - std::unique_ptr<net::URLRequest> https_foo_request( - context.CreateRequest(https_foo_url, net::DEFAULT_PRIORITY, nullptr, - TRAFFIC_ANNOTATION_FOR_TESTS)); - WebRequestInfo https_foo_request_info(https_foo_request.get()); + WebRequestInfoInitParams https_foo_params; + https_foo_params.url = https_foo_url; + WebRequestInfo https_foo_request_info(std::move(https_foo_params)); data.request = &https_foo_request_info; EXPECT_FALSE(result->IsFulfilled(-1, request_data)); } TEST(WebRequestConditionTest, TestPortFilter) { - // Necessary for TestURLRequest. - base::MessageLoopForIO message_loop; URLMatcher matcher; WebRequestConditionSet::Values conditions; @@ -357,30 +309,18 @@ // Test various URLs. GURL http_url("http://www.example.com"); - net::TestURLRequestContext context; - std::unique_ptr<net::URLRequest> http_request(context.CreateRequest( - http_url, net::DEFAULT_PRIORITY, nullptr, TRAFFIC_ANNOTATION_FOR_TESTS)); url_match_ids = matcher.MatchURL(http_url); ASSERT_EQ(1u, url_match_ids.size()); GURL http_url_80("http://www.example.com:80"); - std::unique_ptr<net::URLRequest> http_request_80( - context.CreateRequest(http_url_80, net::DEFAULT_PRIORITY, nullptr, - TRAFFIC_ANNOTATION_FOR_TESTS)); url_match_ids = matcher.MatchURL(http_url_80); ASSERT_EQ(1u, url_match_ids.size()); GURL http_url_1000("http://www.example.com:1000"); - std::unique_ptr<net::URLRequest> http_request_1000( - context.CreateRequest(http_url_1000, net::DEFAULT_PRIORITY, nullptr, - TRAFFIC_ANNOTATION_FOR_TESTS)); url_match_ids = matcher.MatchURL(http_url_1000); ASSERT_EQ(1u, url_match_ids.size()); GURL http_url_2000("http://www.example.com:2000"); - std::unique_ptr<net::URLRequest> http_request_2000( - context.CreateRequest(http_url_2000, net::DEFAULT_PRIORITY, nullptr, - TRAFFIC_ANNOTATION_FOR_TESTS)); url_match_ids = matcher.MatchURL(http_url_2000); ASSERT_EQ(0u, url_match_ids.size()); } @@ -389,8 +329,6 @@ // the response header. The Create() method should fail and complain that it is // impossible that both conditions are fulfilled at the same time. TEST(WebRequestConditionTest, ConditionsWithConflictingStages) { - // Necessary for TestURLRequest. - base::MessageLoopForIO message_loop; URLMatcher matcher; std::string error;
diff --git a/extensions/browser/api/declarative_webrequest/webrequest_rules_registry.cc b/extensions/browser/api/declarative_webrequest/webrequest_rules_registry.cc index bb551be..5164d53 100644 --- a/extensions/browser/api/declarative_webrequest/webrequest_rules_registry.cc +++ b/extensions/browser/api/declarative_webrequest/webrequest_rules_registry.cc
@@ -21,7 +21,6 @@ #include "extensions/common/error_utils.h" #include "extensions/common/extension.h" #include "extensions/common/permissions/permissions_data.h" -#include "net/url_request/url_request.h" using url_matcher::URLMatcherConditionSet;
diff --git a/extensions/browser/api/sockets_tcp/sockets_tcp_api.cc b/extensions/browser/api/sockets_tcp/sockets_tcp_api.cc index 47044972..01fb97c 100644 --- a/extensions/browser/api/sockets_tcp/sockets_tcp_api.cc +++ b/extensions/browser/api/sockets_tcp/sockets_tcp_api.cc
@@ -19,8 +19,6 @@ #include "extensions/browser/api/sockets_tcp/tcp_socket_event_dispatcher.h" #include "extensions/common/api/sockets/sockets_manifest_data.h" #include "net/base/net_errors.h" -#include "net/url_request/url_request_context.h" -#include "net/url_request/url_request_context_getter.h" using extensions::ResumableTCPSocket; using extensions::api::sockets_tcp::SocketInfo;
diff --git a/extensions/browser/api/web_request/web_request_api.h b/extensions/browser/api/web_request/web_request_api.h index 64075598..eacca307 100644 --- a/extensions/browser/api/web_request/web_request_api.h +++ b/extensions/browser/api/web_request/web_request_api.h
@@ -79,10 +79,9 @@ public ExtensionRegistryObserver { public: // A callback used to asynchronously respond to an intercepted authentication - // request when the Network Service is enabled. If |should_cancel| is true - // the request will be cancelled. Otherwise any supplied |credentials| will be - // used. If no credentials are supplied, default browser behavior will follow - // (e.g. UI prompt for login). + // request. If |should_cancel| is true the request will be cancelled. + // Otherwise any supplied |credentials| will be used. If no credentials are + // supplied, default browser behavior will follow (e.g. UI prompt for login). using AuthRequestCallback = base::OnceCallback<void( const base::Optional<net::AuthCredentials>& credentials, bool should_cancel)>; @@ -193,7 +192,6 @@ // factories proxied for service worker. // // Returns |true| if the URLLoaderFactory will be proxied; |false| otherwise. - // Only used when the Network Service is enabled. bool MaybeProxyURLLoaderFactory( content::BrowserContext* browser_context, content::RenderFrameHost* frame, @@ -204,7 +202,7 @@ network::mojom::TrustedURLLoaderHeaderClientPtrInfo* header_client); // Any request which requires authentication to complete will be bounced - // through this method iff Network Service is enabled. + // through this method. // // If this returns |true|, |callback| will eventually be invoked on the UI // thread. @@ -220,8 +218,6 @@ // BrowserContext, |*request| is swapped out for a new request which proxies // through an internal WebSocket implementation. This supports lifetime // observation and control on behalf of the WebRequest API. - // - // Only used when the Network Service is enabled. void MaybeProxyWebSocket( content::RenderFrameHost* frame, network::mojom::WebSocketRequest* request, @@ -239,7 +235,7 @@ static const bool kServiceIsNULLWhileTesting = true; // Indicates whether or not the WebRequestAPI may have one or more proxies - // installed to support the API with Network Service enabled. + // installed to support the API. bool MayHaveProxies() const; // Checks if |MayHaveProxies()| has changed from false to true, and resets
diff --git a/extensions/browser/api/web_request/web_request_info.cc b/extensions/browser/api/web_request/web_request_info.cc index 20111693..da2862e 100644 --- a/extensions/browser/api/web_request/web_request_info.cc +++ b/extensions/browser/api/web_request/web_request_info.cc
@@ -24,7 +24,6 @@ #include "net/base/upload_data_stream.h" #include "net/base/upload_file_element_reader.h" #include "net/log/net_log_with_source.h" -#include "net/url_request/url_request.h" #include "services/network/public/cpp/resource_response.h" #include "services/network/public/mojom/network_context.mojom.h" #include "services/network/url_loader.h" @@ -36,9 +35,7 @@ namespace { // UploadDataSource abstracts an interface for feeding an arbitrary data element -// to an UploadDataPresenter. This is helpful because in the Network Service vs -// non-Network Service case, upload data comes from different types of source -// objects, but we'd like to share parsing code. +// to an UploadDataPresenter. class UploadDataSource { public: virtual ~UploadDataSource() {} @@ -78,43 +75,6 @@ DISALLOW_COPY_AND_ASSIGN(FileUploadDataSource); }; -base::Value NetLogExtensionIdCallback(const std::string& extension_id, - net::NetLogCaptureMode capture_mode) { - base::DictionaryValue params; - params.SetString("extension_id", extension_id); - return std::move(params); -} - -// Implements Logger using NetLog, mirroring the logging facilities used prior -// to the introduction of WebRequestInfo. -// TODO(crbug.com/721414): Transition away from using NetLog. -class NetLogLogger : public WebRequestInfoLogger { - public: - explicit NetLogLogger(net::URLRequest* request) : request_(request) {} - ~NetLogLogger() override = default; - - // WebRequestInfo::Logger: - void LogEvent(net::NetLogEventType event_type, - const std::string& extension_id) override { - request_->net_log().AddEvent( - event_type, - base::BindRepeating(&NetLogExtensionIdCallback, extension_id)); - } - - void LogBlockedBy(const std::string& blocker_info) override { - // LogAndReport allows extensions that block requests to be displayed in the - // load status bar. - request_->LogAndReportBlockedBy(blocker_info.c_str()); - } - - void LogUnblocked() override { request_->LogUnblocked(); } - - private: - net::URLRequest* const request_; - - DISALLOW_COPY_AND_ASSIGN(NetLogLogger); -}; - // TODO(https://crbug.com/721414): Need a real implementation here to support // the Network Service case. For now this is only to prevent crashing. class NetworkServiceLogger : public WebRequestInfoLogger { @@ -132,33 +92,6 @@ DISALLOW_COPY_AND_ASSIGN(NetworkServiceLogger); }; -bool CreateUploadDataSourcesFromURLRequest( - net::URLRequest* url_request, - std::vector<std::unique_ptr<UploadDataSource>>* data_sources) { - const net::UploadDataStream* upload_data = url_request->get_upload(); - if (!upload_data) - return false; - - const std::vector<std::unique_ptr<net::UploadElementReader>>* readers = - upload_data->GetElementReaders(); - if (!readers) - return true; - - for (const auto& reader : *readers) { - if (const auto* bytes_reader = reader->AsBytesReader()) { - data_sources->push_back(std::make_unique<BytesUploadDataSource>( - base::StringPiece(bytes_reader->bytes(), bytes_reader->length()))); - } else if (const auto* file_reader = reader->AsFileReader()) { - data_sources->push_back( - std::make_unique<FileUploadDataSource>(file_reader->path())); - } else { - DVLOG(1) << "Ignoring upsupported upload data type for WebRequest API."; - } - } - - return true; -} - bool CreateUploadDataSourcesFromResourceRequest( const network::ResourceRequest& request, std::vector<std::unique_ptr<UploadDataSource>>* data_sources) { @@ -238,70 +171,6 @@ WebRequestInfoInitParams& WebRequestInfoInitParams::operator=( WebRequestInfoInitParams&& other) = default; -WebRequestInfoInitParams::WebRequestInfoInitParams(net::URLRequest* url_request) - : id(url_request->identifier()), - url(url_request->url()), - site_for_cookies(url_request->site_for_cookies()), - method(url_request->method()), - initiator(url_request->initiator()), - extra_request_headers(url_request->extra_request_headers()), - is_pac_request(url_request->is_pac_request()), - logger(std::make_unique<NetLogLogger>(url_request)) { - if (url.SchemeIsWSOrWSS()) { - web_request_type = WebRequestResourceType::WEB_SOCKET; - - // TODO(pkalinnikov): Consider embedding WebSocketHandshakeRequestInfo into - // UrlRequestUserData. - content::WebSocketHandshakeRequestInfo* ws_info = - content::WebSocketHandshakeRequestInfo::ForRequest(url_request); - if (ws_info) { - render_process_id = ws_info->GetChildId(); - frame_id = ws_info->GetRenderFrameId(); - } - } else if (auto* info = - content::ResourceRequestInfo::ForRequest(url_request)) { - render_process_id = info->GetChildID(); - routing_id = info->GetRouteID(); - frame_id = info->GetRenderFrameID(); - type = info->GetResourceType(); - web_request_type = ToWebRequestResourceType(type.value()); - is_async = info->IsAsync(); - resource_context = info->GetContext(); - } else if (auto* url_loader = network::URLLoader::ForRequest(*url_request)) { - // This is reached only in the SimpleURLLoader case (since network service - // is disabled if we're in this constructor). Only set the IDs if they're - // non-zero, since almost all requests come from the browser and aren't - // associated with a frame. In the case that the browser wants this - // SimpleURLLoader associated with a frame, the process ID will be non-zero. - if (url_loader->GetProcessId() != network::mojom::kBrowserProcessId) { - render_process_id = url_loader->GetProcessId(); - frame_id = url_loader->GetRenderFrameId(); - } - type = static_cast<content::ResourceType>(url_loader->GetResourceType()); - } else { - // There may be basic process and frame info associated with the request - // even when |info| is null. Attempt to grab it as a last ditch effort. If - // this fails, we have no frame info. - content::ResourceRequestInfo::GetRenderFrameForRequest( - url_request, &render_process_id, &frame_id); - } - - ExtensionsBrowserClient* browser_client = ExtensionsBrowserClient::Get(); - ExtensionNavigationUIData* navigation_ui_data = - browser_client ? browser_client->GetExtensionNavigationUIData(url_request) - : nullptr; - if (navigation_ui_data) - is_browser_side_navigation = true; - - InitializeWebViewAndFrameData(navigation_ui_data); - - std::vector<std::unique_ptr<UploadDataSource>> data_sources; - if (CreateUploadDataSourcesFromURLRequest(url_request, &data_sources)) { - request_body_data = - CreateRequestBodyData(method, extra_request_headers, data_sources); - } -} - WebRequestInfoInitParams::WebRequestInfoInitParams( uint64_t request_id, int render_process_id, @@ -340,10 +209,6 @@ request_body_data = CreateRequestBodyData(method, extra_request_headers, data_sources); } - - // TODO(https://crbug.com/721414): For this constructor (i.e. the Network - // Service case), we are still missing information for |is_async| and - // |is_pac_request|. } WebRequestInfoInitParams::~WebRequestInfoInitParams() = default; @@ -382,9 +247,6 @@ } } -WebRequestInfo::WebRequestInfo(net::URLRequest* url_request) - : WebRequestInfo(WebRequestInfoInitParams(url_request)) {} - WebRequestInfo::WebRequestInfo(WebRequestInfoInitParams params) : id(params.id), url(std::move(params.url)), @@ -400,7 +262,6 @@ web_request_type(params.web_request_type), is_async(params.is_async), extra_request_headers(std::move(params.extra_request_headers)), - is_pac_request(params.is_pac_request), request_body_data(std::move(params.request_body_data)), is_web_view(params.is_web_view), web_view_instance_id(params.web_view_instance_id), @@ -411,14 +272,6 @@ WebRequestInfo::~WebRequestInfo() = default; -void WebRequestInfo::AddResponseInfoFromURLRequest( - net::URLRequest* url_request) { - response_code = url_request->GetResponseCode(); - response_headers = url_request->response_headers(); - response_ip = url_request->GetResponseRemoteEndpoint().ToStringWithoutPort(); - response_from_cache = url_request->was_cached(); -} - void WebRequestInfo::AddResponseInfoFromResourceResponse( const network::ResourceResponseHead& response) { response_headers = response.headers;
diff --git a/extensions/browser/api/web_request/web_request_info.h b/extensions/browser/api/web_request/web_request_info.h index c572234..27520d2 100644 --- a/extensions/browser/api/web_request/web_request_info.h +++ b/extensions/browser/api/web_request/web_request_info.h
@@ -30,11 +30,6 @@ class ResourceContext; } // namespace content -namespace net { -class HttpResponseHeaders; -class URLRequest; -} // namespace net - namespace network { struct ResourceResponseHead; } @@ -63,10 +58,8 @@ WebRequestInfoInitParams(WebRequestInfoInitParams&& other); WebRequestInfoInitParams& operator=(WebRequestInfoInitParams&& other); - explicit WebRequestInfoInitParams(net::URLRequest* url_request); - // Initializes a WebRequestInfoInitParams from information provided over a - // URLLoaderFactory interface, for use with the Network Service. + // URLLoaderFactory interface. WebRequestInfoInitParams( uint64_t request_id, int render_process_id, @@ -93,7 +86,6 @@ WebRequestResourceType web_request_type = WebRequestResourceType::OTHER; bool is_async = false; net::HttpRequestHeaders extra_request_headers; - bool is_pac_request = false; std::unique_ptr<base::DictionaryValue> request_body_data; bool is_web_view = false; int web_view_instance_id = -1; @@ -113,23 +105,11 @@ // A URL request representation used by WebRequest API internals. This structure // carries information about an in-progress request. struct WebRequestInfo { - // Initializes a WebRequestInfoInitParams from a net::URLRequest. Should be - // used sparingly, as we are moving away from direct URLRequest usage and - // toward using Network Service. Prefer passing and referencing - // WebRequestInfoInitParams in lieu of exposing any new direct references to - // net::URLRequest throughout extensions WebRequest-related code. - explicit WebRequestInfo(net::URLRequest* url_request); - explicit WebRequestInfo(WebRequestInfoInitParams params); ~WebRequestInfo(); - // Fill in response data for this request. Only used when the Network Service - // is disabled. - void AddResponseInfoFromURLRequest(net::URLRequest* url_request); - - // Fill in response data for this request. Only used when the Network Service - // is enabled. + // Fill in response data for this request. void AddResponseInfoFromResourceResponse( const network::ResourceResponseHead& response); @@ -180,9 +160,6 @@ const net::HttpRequestHeaders extra_request_headers; - // Indicates if this request is for a PAC script. - const bool is_pac_request; - // HTTP response code for this request if applicable. -1 if not. int response_code = -1;
diff --git a/extensions/browser/api/web_request/web_request_permissions.cc b/extensions/browser/api/web_request/web_request_permissions.cc index bf321bd..c7a6f32 100644 --- a/extensions/browser/api/web_request/web_request_permissions.cc +++ b/extensions/browser/api/web_request/web_request_permissions.cc
@@ -245,11 +245,6 @@ if (request.is_web_view) return false; - // Requests from PAC scripts are always hidden. - // See https://crbug.com/794674 - if (request.is_pac_request) - return true; - bool is_request_from_browser = request.render_process_id == -1; if (is_request_from_browser) {
diff --git a/extensions/browser/api/web_request/web_request_permissions_unittest.cc b/extensions/browser/api/web_request/web_request_permissions_unittest.cc index 129a291b..b42112ba 100644 --- a/extensions/browser/api/web_request/web_request_permissions_unittest.cc +++ b/extensions/browser/api/web_request/web_request_permissions_unittest.cc
@@ -189,18 +189,6 @@ EXPECT_TRUE(WebRequestPermissions::HideRequest(info_map.get(), sensitive_request_info)); } - - { - // Check that a request for a non-sensitive URL is rejected if it's a PAC - // script fetch. - WebRequestInfoInitParams non_sensitive_request_params = - create_request_params(non_sensitive_url, content::ResourceType::kScript, - kRendererProcessId); - non_sensitive_request_params.is_pac_request = true; - EXPECT_TRUE(WebRequestPermissions::HideRequest( - info_map.get(), - WebRequestInfo(std::move(non_sensitive_request_params)))); - } } TEST(ExtensionWebRequestPermissions,
diff --git a/extensions/browser/api/web_request/web_request_proxying_url_loader_factory.cc b/extensions/browser/api/web_request/web_request_proxying_url_loader_factory.cc index 046fa2a..d46e66c8 100644 --- a/extensions/browser/api/web_request/web_request_proxying_url_loader_factory.cc +++ b/extensions/browser/api/web_request/web_request_proxying_url_loader_factory.cc
@@ -888,10 +888,10 @@ // Make sure we are not proxying a browser initiated non-navigation request. DCHECK(render_process_id_ != -1 || navigation_ui_data_); - // The request ID doesn't really matter in the Network Service path. It just - // needs to be unique per-BrowserContext so extensions can make sense of it. - // Note that |network_service_request_id_| by contrast is not necessarily - // unique, so we don't use it for identity here. + // The request ID doesn't really matter. It just needs to be unique + // per-BrowserContext so extensions can make sense of it. Note that + // |network_service_request_id_| by contrast is not necessarily unique, so we + // don't use it for identity here. const uint64_t web_request_id = request_id_generator_->Generate(); if (request_id) {
diff --git a/extensions/browser/api/web_request/web_request_proxying_url_loader_factory.h b/extensions/browser/api/web_request/web_request_proxying_url_loader_factory.h index 945acff..663abae3 100644 --- a/extensions/browser/api/web_request/web_request_proxying_url_loader_factory.h +++ b/extensions/browser/api/web_request/web_request_proxying_url_loader_factory.h
@@ -39,9 +39,8 @@ // Service enabled. This is loosely controlled by the WebRequestAPI on the UI // thread, but does all its real work on the IO thread. This is only because // it is tightly coupled to ExtensionsWebRequestEventRouter, and that object -// must stay on the IO thread until we can deprecate the non-Network Service -// path. Once Network Service is the only path, we can move all this stuff to -// the UI thread. +// must stay on the IO thread. +// TODO(http://crbug.com/824840): Move this to the UI thread. class WebRequestProxyingURLLoaderFactory : public WebRequestAPI::Proxy, public network::mojom::URLLoaderFactory, @@ -150,8 +149,6 @@ // |OnHeadersReceived()| and request completion or restart. Pointers to // these fields are stored in a |BlockedRequest| (created and owned by // ExtensionWebRequestEventRouter) through much of the request's lifetime. - // That code supports both Network Service and non-Network Service behavior, - // which is why this weirdness exists here. network::ResourceResponseHead current_response_; scoped_refptr<net::HttpResponseHeaders> override_headers_; GURL redirect_url_;
diff --git a/extensions/browser/api/web_request/web_request_proxying_websocket.cc b/extensions/browser/api/web_request/web_request_proxying_websocket.cc index b7d181a..8edc34b 100644 --- a/extensions/browser/api/web_request/web_request_proxying_websocket.cc +++ b/extensions/browser/api/web_request/web_request_proxying_websocket.cc
@@ -181,10 +181,10 @@ response_.remote_endpoint = response->remote_endpoint; - // TODO(yhirano): with both network service enabled or disabled, - // OnFinishOpeningHandshake is called with the original response headers. - // That means if OnHeadersReceived modified them the renderer won't see that - // modification. This is the opposite of http(s) requests. + // TODO(yhirano): OnFinishOpeningHandshake is called with the original + // response headers. That means if OnHeadersReceived modified them the + // renderer won't see that modification. This is the opposite of http(s) + // requests. forwarding_handshake_client_->OnFinishOpeningHandshake(std::move(response)); if (!binding_as_header_client_ || response_.headers) {
diff --git a/extensions/browser/api/web_request/web_request_proxying_websocket.h b/extensions/browser/api/web_request/web_request_proxying_websocket.h index 04f782b..067780d 100644 --- a/extensions/browser/api/web_request/web_request_proxying_websocket.h +++ b/extensions/browser/api/web_request/web_request_proxying_websocket.h
@@ -32,7 +32,7 @@ namespace extensions { // A WebRequestProxyingWebSocket proxies a WebSocket connection and dispatches -// WebRequest API events. This is used only when the network service is enabled. +// WebRequest API events. class WebRequestProxyingWebSocket : public WebRequestAPI::Proxy, public network::mojom::WebSocket,
diff --git a/extensions/browser/content_verify_job_unittest.cc b/extensions/browser/content_verify_job_unittest.cc index 8b10d8f..66ff8b3a 100644 --- a/extensions/browser/content_verify_job_unittest.cc +++ b/extensions/browser/content_verify_job_unittest.cc
@@ -21,8 +21,6 @@ #include "extensions/common/constants.h" #include "extensions/common/extension_paths.h" #include "extensions/common/file_util.h" -#include "net/url_request/url_request_job_factory_impl.h" -#include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/zlib/google/zip.h" @@ -64,14 +62,12 @@ ExtensionsTest::SetUp(); extension_info_map_ = new InfoMap(); - old_factory_ = test_url_request_context_.job_factory(); content_verifier_ = new ContentVerifier( &testing_context_, std::make_unique<MockContentVerifierDelegate>()); extension_info_map_->SetContentVerifier(content_verifier_.get()); } void TearDown() override { - test_url_request_context_.set_job_factory(old_factory_); content_verifier_->Shutdown(); ExtensionsTest::TearDown(); @@ -159,9 +155,6 @@ } scoped_refptr<InfoMap> extension_info_map_; - net::URLRequestJobFactoryImpl job_factory_; - const net::URLRequestJobFactory* old_factory_; - net::TestURLRequestContext test_url_request_context_; scoped_refptr<ContentVerifier> content_verifier_; content::TestBrowserContext testing_context_;
diff --git a/extensions/browser/extension_protocols.cc b/extensions/browser/extension_protocols.cc index e0761e1..a51e6b4a 100644 --- a/extensions/browser/extension_protocols.cc +++ b/extensions/browser/extension_protocols.cc
@@ -76,9 +76,6 @@ #include "net/http/http_request_headers.h" #include "net/http/http_response_headers.h" #include "net/http/http_response_info.h" -#include "net/url_request/url_request_error_job.h" -#include "net/url_request/url_request_file_job.h" -#include "net/url_request/url_request_simple_job.h" #include "services/network/public/cpp/url_loader_completion_status.h" #include "url/url_util.h" @@ -106,41 +103,6 @@ } } -class GeneratedBackgroundPageJob : public net::URLRequestSimpleJob { - public: - GeneratedBackgroundPageJob(net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const scoped_refptr<const Extension> extension, - const std::string& content_security_policy) - : net::URLRequestSimpleJob(request, network_delegate), - extension_(extension) { - const bool send_cors_headers = false; - // Leave cache headers out of generated background page jobs. - response_info_.headers = BuildHttpHeaders(content_security_policy, - send_cors_headers, - base::Time()); - } - - // Overridden from URLRequestSimpleJob: - int GetData(std::string* mime_type, - std::string* charset, - std::string* data, - net::CompletionOnceCallback callback) const override { - GenerateBackgroundPageContents(extension_.get(), mime_type, charset, data); - return net::OK; - } - - void GetResponseInfo(net::HttpResponseInfo* info) override { - *info = response_info_; - } - - private: - ~GeneratedBackgroundPageJob() override {} - - scoped_refptr<const Extension> extension_; - net::HttpResponseInfo response_info_; -}; - base::Time GetFileLastModifiedTime(const base::FilePath& filename) { if (base::PathExists(filename)) { base::File::Info info; @@ -188,187 +150,6 @@ } } -class URLRequestExtensionJob : public net::URLRequestFileJob { - public: - URLRequestExtensionJob(net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const std::string& extension_id, - const base::FilePath& directory_path, - const base::FilePath& relative_path, - const std::string& content_security_policy, - bool send_cors_header, - bool follow_symlinks_anywhere, - scoped_refptr<ContentVerifyJob> verify_job) - : net::URLRequestFileJob( - request, - network_delegate, - base::FilePath(), - base::CreateTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})), - verify_job_(std::move(verify_job)), - seek_position_(0), - bytes_read_(0), - directory_path_(directory_path), - // TODO(tc): Move all of these files into resources.pak so we don't - // break when updating on Linux. - resource_(extension_id, directory_path, relative_path), - content_security_policy_(content_security_policy), - send_cors_header_(send_cors_header), - weak_factory_(this) { - if (follow_symlinks_anywhere) { - resource_.set_follow_symlinks_anywhere(); - } - } - - void GetResponseInfo(net::HttpResponseInfo* info) override { - *info = response_info_; - } - - void Start() override { - request_timer_.reset(new base::ElapsedTimer()); - base::FilePath* read_file_path = new base::FilePath; - base::Time* last_modified_time = new base::Time(); - - // Inherit task priority from the calling context. - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock()}, - base::Bind(&ReadResourceFilePathAndLastModifiedTime, resource_, - directory_path_, base::Unretained(read_file_path), - base::Unretained(last_modified_time)), - base::Bind(&URLRequestExtensionJob::OnFilePathAndLastModifiedTimeRead, - weak_factory_.GetWeakPtr(), base::Owned(read_file_path), - base::Owned(last_modified_time))); - } - - bool IsRedirectResponse(GURL* location, - int* http_status_code, - bool* insecure_scheme_was_upgraded) override { - return false; - } - - void SetExtraRequestHeaders(const net::HttpRequestHeaders& headers) override { - // TODO(asargent) - we'll need to add proper support for range headers. - // crbug.com/369895. - std::string range_header; - if (headers.GetHeader(net::HttpRequestHeaders::kRange, &range_header)) { - if (verify_job_.get()) - verify_job_ = NULL; - } - URLRequestFileJob::SetExtraRequestHeaders(headers); - } - - void OnOpenComplete(int result) override { - if (result < 0) { - // This can happen when the file is unreadable (which can happen during - // corruption or third-party interaction). We need to be sure to inform - // the verification job that we've finished reading so that it can - // proceed; see crbug.com/703888. - if (verify_job_.get()) { - std::string tmp; - verify_job_->BytesRead(0, base::data(tmp)); - verify_job_->DoneReading(); - } - } - } - - void OnSeekComplete(int64_t result) override { - DCHECK_EQ(seek_position_, 0); - seek_position_ = result; - // TODO(asargent) - we'll need to add proper support for range headers. - // crbug.com/369895. - const bool is_seek_contiguous = result == bytes_read_; - if (result > 0 && verify_job_.get() && !is_seek_contiguous) - verify_job_ = nullptr; - } - - void OnReadComplete(net::IOBuffer* buffer, int result) override { - if (result >= 0) - UMA_HISTOGRAM_COUNTS_1M("ExtensionUrlRequest.OnReadCompleteResult", - result); - else - base::UmaHistogramSparse("ExtensionUrlRequest.OnReadCompleteError", - -result); - if (result > 0) { - bytes_read_ += result; - if (verify_job_.get()) - verify_job_->BytesRead(result, buffer->data()); - } - } - - void DoneReading() override { - URLRequestFileJob::DoneReading(); - if (verify_job_.get()) - verify_job_->DoneReading(); - } - - private: - ~URLRequestExtensionJob() override { - UMA_HISTOGRAM_COUNTS_1M("ExtensionUrlRequest.TotalKbRead", - bytes_read_ / 1024); - UMA_HISTOGRAM_COUNTS_1M("ExtensionUrlRequest.SeekPosition", seek_position_); - if (request_timer_.get()) - UMA_HISTOGRAM_TIMES("ExtensionUrlRequest.Latency", - request_timer_->Elapsed()); - } - - bool CanAccessFile(const base::FilePath& original_path, - const base::FilePath& absolute_path) override { - // The access checks for the file are performed before the job is - // created, so we should know that this is safe. - return true; - } - - void OnFilePathAndLastModifiedTimeRead(base::FilePath* read_file_path, - base::Time* last_modified_time) { - file_path_ = *read_file_path; - response_info_.headers = BuildHttpHeaders( - content_security_policy_, - send_cors_header_, - *last_modified_time); - // Set the mime type for the request. - std::string mime_type; - bool found_mime_type = GetMimeType(&mime_type); - if (found_mime_type) - response_info_.headers->AddHeader("Content-Type: " + mime_type); - - URLRequestFileJob::Start(); - } - - bool GetMimeType(std::string* mime_type) const override { - base::FilePath::StringType file_extension = file_path_.Extension(); - if (file_extension.empty()) - return false; - - // We use GetWellKnownMimeTypeFromExtension() to ensure that configurations - // that may have been set by other programs on a user's machine don't affect - // the mime type returned (in particular, JS should always be - // application/javascript). See https://crbug.com/797712. Using an accurate - // mime type is necessary at least for modules, which enforce strict mime - // type requirements. - return net::GetWellKnownMimeTypeFromExtension( - file_extension.substr(1), // Trim leading '.' - mime_type); - } - - scoped_refptr<ContentVerifyJob> verify_job_; - - std::unique_ptr<base::ElapsedTimer> request_timer_; - - // The position we seeked to in the file. - int64_t seek_position_; - - // The number of bytes of content we read from the file. - int bytes_read_; - - net::HttpResponseInfo response_info_; - base::FilePath directory_path_; - extensions::ExtensionResource resource_; - std::string content_security_policy_; - bool send_cors_header_; - base::WeakPtrFactory<URLRequestExtensionJob> weak_factory_; -}; - bool ExtensionCanLoadInIncognito(bool is_main_frame, const Extension* extension, bool extension_enabled_in_incognito) { @@ -387,8 +168,7 @@ // Pass true for |is_incognito| only for incognito profiles and not Chrome OS // guest mode profiles. // -// May be called on the IO thread (non-Network Service path) or the UI thread -// (Network Service path). +// Called on the UI thread. bool AllowExtensionResourceLoad(const GURL& url, content::ResourceType resource_type, ui::PageTransition page_transition, @@ -480,22 +260,6 @@ return false; } -bool IsWebViewRequest(net::URLRequest* request) { - content::ResourceRequestInfo* info = - content::ResourceRequestInfo::ForRequest(request); - // |info| can be null sometimes: http://crbug.com/370070. - if (!info) - return false; - if (WebViewRendererState::GetInstance()->IsGuest(info->GetChildID())) - return true; - - // GetChildId() is -1 with PlzNavigate for navigation requests, so also try - // the ExtensionNavigationUIData data. - const ExtensionNavigationUIData* data = - ExtensionsBrowserClient::Get()->GetExtensionNavigationUIData(request); - return data && data->is_web_view(); -} - void GetSecurityPolicyForURL(const GURL& url, const Extension* extension, bool is_web_view_request, @@ -526,159 +290,6 @@ path_piece.substr(1) == kGeneratedBackgroundPageFilename; } -class ExtensionProtocolHandler - : public net::URLRequestJobFactory::ProtocolHandler { - public: - ExtensionProtocolHandler(bool is_incognito, - extensions::InfoMap* extension_info_map) - : is_incognito_(is_incognito), extension_info_map_(extension_info_map) {} - - ~ExtensionProtocolHandler() override {} - - net::URLRequestJob* MaybeCreateJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate) const override; - - bool IsSafeRedirectTarget(const GURL& location) const override; - - private: - const bool is_incognito_; - extensions::InfoMap* const extension_info_map_; - DISALLOW_COPY_AND_ASSIGN(ExtensionProtocolHandler); -}; - -// Creates URLRequestJobs for extension:// URLs. -net::URLRequestJob* -ExtensionProtocolHandler::MaybeCreateJob( - net::URLRequest* request, net::NetworkDelegate* network_delegate) const { - // chrome-extension://extension-id/resource/path.js - std::string extension_id = request->url().host(); - const Extension* extension = - extension_info_map_->extensions().GetByID(extension_id); - ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request); - const bool enabled_in_incognito = - extension_info_map_->IsIncognitoEnabled(extension_id); - - // We have seen crashes where info is NULL: crbug.com/52374. - if (!info) { - // SeviceWorker net requests created through ServiceWorkerWriteToCacheJob - // do not have ResourceRequestInfo associated with them. So skip logging - // spurious errors below. - // TODO(falken): Either consider attaching ResourceRequestInfo to these or - // finish refactoring ServiceWorkerWriteToCacheJob so that it doesn't spawn - // a new URLRequest. - if (!ResourceRequestInfo::OriginatedFromServiceWorker(request)) { - LOG(ERROR) << "Allowing load of " << request->url().spec() - << "from unknown origin. Could not find user data for " - << "request."; - } - } else if (!AllowExtensionResourceLoad( - request->url(), info->GetResourceType(), - info->GetPageTransition(), info->GetChildID(), is_incognito_, - extension, enabled_in_incognito, - extension_info_map_->extensions(), - extension_info_map_->process_map())) { - return new net::URLRequestErrorJob(request, network_delegate, - net::ERR_BLOCKED_BY_CLIENT); - } - - base::FilePath directory_path; - if (!GetDirectoryForExtensionURL(request->url(), extension_id, extension, - extension_info_map_->disabled_extensions(), - &directory_path)) { - return nullptr; - } - - // Set up content security policy. - std::string content_security_policy; - bool send_cors_header = false; - bool follow_symlinks_anywhere = false; - if (extension) { - GetSecurityPolicyForURL(request->url(), extension, - IsWebViewRequest(request), &content_security_policy, - &send_cors_header, &follow_symlinks_anywhere); - } - - // Create a job for a generated background page. - if (IsBackgroundPageURL(request->url())) { - return new GeneratedBackgroundPageJob( - request, network_delegate, extension, content_security_policy); - } - - // Component extension resources may be part of the embedder's resource files, - // for example component_extension_resources.pak in Chrome. - net::URLRequestJob* resource_bundle_job = - extensions::ExtensionsBrowserClient::Get() - ->MaybeCreateResourceBundleRequestJob(request, - network_delegate, - directory_path, - content_security_policy, - send_cors_header); - if (resource_bundle_job) - return resource_bundle_job; - - base::FilePath relative_path = - extensions::file_util::ExtensionURLToRelativeFilePath(request->url()); - - // Do not allow requests for resources in the _metadata folder, since any - // files there are internal implementation details that should not be - // considered part of the extension. - if (base::FilePath(kMetadataFolder).IsParent(relative_path)) - return nullptr; - - // Handle shared resources (extension A loading resources out of extension B). - std::string path = request->url().path(); - if (SharedModuleInfo::IsImportedPath(path)) { - std::string new_extension_id; - std::string new_relative_path; - SharedModuleInfo::ParseImportedPath(path, &new_extension_id, - &new_relative_path); - const Extension* new_extension = - extension_info_map_->extensions().GetByID(new_extension_id); - - if (SharedModuleInfo::ImportsExtensionById(extension, new_extension_id) && - new_extension) { - directory_path = new_extension->path(); - extension_id = new_extension_id; - relative_path = base::FilePath::FromUTF8Unsafe(new_relative_path); - } else { - return NULL; - } - } - - if (g_test_handler) - g_test_handler->Run(&directory_path, &relative_path); - - scoped_refptr<ContentVerifyJob> verify_job; - ContentVerifier* verifier = extension_info_map_->content_verifier(); - if (verifier) { - verify_job = - verifier->CreateJobFor(extension_id, directory_path, relative_path); - if (verify_job) - verify_job->Start(verifier); - } - - return new URLRequestExtensionJob( - request, network_delegate, extension_id, directory_path, relative_path, - content_security_policy, send_cors_header, follow_symlinks_anywhere, - std::move(verify_job)); -} - -bool ExtensionProtocolHandler::IsSafeRedirectTarget( - const GURL& location) const { - // Redirects originate from http/https origins, which are subject to - // webaccessible resources restrictions. Redirects can also be triggered via - // the extensions webrequest API, which is also limited to webaccessible - // resources. - std::string extension_id = location.host(); - const Extension* extension = - extension_info_map_->extensions().GetByID(extension_id); - if (!extension) - return false; - return WebAccessibleResourcesInfo::IsResourceWebAccessible(extension, - location.path()); -} - class FileLoaderObserver : public content::FileURLLoaderObserver { public: explicit FileLoaderObserver(scoped_refptr<ContentVerifyJob> verify_job) @@ -1032,13 +643,6 @@ return new net::HttpResponseHeaders(raw_headers); } -std::unique_ptr<net::URLRequestJobFactory::ProtocolHandler> -CreateExtensionProtocolHandler(bool is_incognito, - extensions::InfoMap* extension_info_map) { - return std::make_unique<ExtensionProtocolHandler>(is_incognito, - extension_info_map); -} - void SetExtensionProtocolTestHandler(ExtensionProtocolTestHandler* handler) { g_test_handler = handler; }
diff --git a/extensions/browser/extension_protocols.h b/extensions/browser/extension_protocols.h index 1ddcd71d..05149e4 100644 --- a/extensions/browser/extension_protocols.h +++ b/extensions/browser/extension_protocols.h
@@ -10,7 +10,6 @@ #include "base/callback.h" #include "base/memory/ref_counted.h" -#include "net/url_request/url_request_job_factory.h" #include "services/network/public/mojom/url_loader_factory.mojom.h" namespace base { @@ -27,7 +26,6 @@ } namespace extensions { -class InfoMap; using ExtensionProtocolTestHandler = base::Callback<void(base::FilePath* directory_path, @@ -40,12 +38,6 @@ bool send_cors_header, const base::Time& last_modified_time); -// Creates the handlers for the chrome-extension:// scheme. Pass true for -// |is_incognito| only for incognito profiles and not for Chrome OS guest mode -// profiles. -std::unique_ptr<net::URLRequestJobFactory::ProtocolHandler> -CreateExtensionProtocolHandler(bool is_incognito, InfoMap* extension_info_map); - // Allows tests to set a special handler for chrome-extension:// urls. Note // that this goes through all the normal security checks; it's essentially a // way to map extra resources to be included in extensions.
diff --git a/extensions/browser/extensions_browser_client.cc b/extensions/browser/extensions_browser_client.cc index 1edccf4..1dcae52 100644 --- a/extensions/browser/extensions_browser_client.cc +++ b/extensions/browser/extensions_browser_client.cc
@@ -68,12 +68,6 @@ return false; } -ExtensionNavigationUIData* -ExtensionsBrowserClient::GetExtensionNavigationUIData( - net::URLRequest* request) { - return nullptr; -} - void ExtensionsBrowserClient::GetTabAndWindowIdForWebContents( content::WebContents* web_contents, int* tab_id,
diff --git a/extensions/browser/extensions_browser_client.h b/extensions/browser/extensions_browser_client.h index 3ed3892..2f4890b5 100644 --- a/extensions/browser/extensions_browser_client.h +++ b/extensions/browser/extensions_browser_client.h
@@ -38,12 +38,6 @@ class WebContents; } -namespace net { -class NetworkDelegate; -class URLRequest; -class URLRequestJob; -} - namespace network { namespace mojom { class NetworkContext; @@ -63,7 +57,6 @@ class ExtensionHostDelegate; class ExtensionApiFrameIdMap; class ExtensionApiFrameIdMapHelper; -class ExtensionNavigationUIData; class ExtensionSet; class ExtensionSystem; class ExtensionSystemProvider; @@ -152,17 +145,6 @@ const extensions::Extension* extension, content::BrowserContext* context) const = 0; - // Returns an URLRequestJob to load an extension resource from the embedder's - // resource bundle (.pak) files. Returns NULL if the request is not for a - // resource bundle resource or if the embedder does not support this feature. - // Used for component extensions. Called on the IO thread. - virtual net::URLRequestJob* MaybeCreateResourceBundleRequestJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const base::FilePath& directory_path, - const std::string& content_security_policy, - bool send_cors_header) = 0; - // Return the resource relative path and id for the given request. virtual base::FilePath GetBundleResourcePath( const network::ResourceRequest& request, @@ -315,9 +297,6 @@ // Returns true if activity logging is enabled for the given |context|. virtual bool IsActivityLoggingEnabled(content::BrowserContext* context); - virtual ExtensionNavigationUIData* GetExtensionNavigationUIData( - net::URLRequest* request); - // Retrives the embedder's notion of tab and window ID for a given // WebContents. May return -1 for either or both values if the embedder does // not implement any such concepts. This is used to support the WebRequest API
diff --git a/extensions/browser/test_extensions_browser_client.cc b/extensions/browser/test_extensions_browser_client.cc index f4202b3e..8e5048c 100644 --- a/extensions/browser/test_extensions_browser_client.cc +++ b/extensions/browser/test_extensions_browser_client.cc
@@ -122,16 +122,6 @@ return false; } -net::URLRequestJob* -TestExtensionsBrowserClient::MaybeCreateResourceBundleRequestJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const base::FilePath& directory_path, - const std::string& content_security_policy, - bool send_cors_header) { - return nullptr; -} - base::FilePath TestExtensionsBrowserClient::GetBundleResourcePath( const network::ResourceRequest& request, const base::FilePath& extension_resources_path,
diff --git a/extensions/browser/test_extensions_browser_client.h b/extensions/browser/test_extensions_browser_client.h index 9c05e45..6ae3ab8 100644 --- a/extensions/browser/test_extensions_browser_client.h +++ b/extensions/browser/test_extensions_browser_client.h
@@ -81,12 +81,6 @@ bool CanExtensionCrossIncognito( const extensions::Extension* extension, content::BrowserContext* context) const override; - net::URLRequestJob* MaybeCreateResourceBundleRequestJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const base::FilePath& directory_path, - const std::string& content_security_policy, - bool send_cors_header) override; base::FilePath GetBundleResourcePath( const network::ResourceRequest& request, const base::FilePath& extension_resources_path,
diff --git a/extensions/browser/updater/extension_downloader.cc b/extensions/browser/updater/extension_downloader.cc index f6d4cbb..ebb3617 100644 --- a/extensions/browser/updater/extension_downloader.cc +++ b/extensions/browser/updater/extension_downloader.cc
@@ -44,7 +44,6 @@ #include "net/base/net_errors.h" #include "net/http/http_status_code.h" #include "net/traffic_annotation/network_traffic_annotation.h" -#include "net/url_request/url_request_status.h" #include "services/identity/public/cpp/access_token_info.h" #include "services/identity/public/cpp/identity_manager.h" #include "services/identity/public/cpp/primary_account_access_token_fetcher.h"
diff --git a/extensions/browser/url_request_util.cc b/extensions/browser/url_request_util.cc index e181cfe7..566e708e 100644 --- a/extensions/browser/url_request_util.cc +++ b/extensions/browser/url_request_util.cc
@@ -16,7 +16,6 @@ #include "extensions/common/manifest_handlers/icons_handler.h" #include "extensions/common/manifest_handlers/web_accessible_resources_info.h" #include "extensions/common/manifest_handlers/webview_info.h" -#include "net/url_request/url_request.h" namespace extensions { namespace url_request_util {
diff --git a/extensions/browser/url_request_util.h b/extensions/browser/url_request_util.h index 73a6d71..15b07184 100644 --- a/extensions/browser/url_request_util.h +++ b/extensions/browser/url_request_util.h
@@ -14,10 +14,6 @@ class GURL; -namespace net { -class URLRequest; -} - namespace extensions { class Extension; class ExtensionSet;
diff --git a/extensions/common/api/automation.idl b/extensions/common/api/automation.idl index 1a4a24a75..35f3068 100644 --- a/extensions/common/api/automation.idl +++ b/extensions/common/api/automation.idl
@@ -589,6 +589,16 @@ long[]? wordStarts; long[]? wordEnds; + // The start index of each word within the node's name. This is different + // from wordStarts because it is not restricted to inline text boxes and can + // be used for any type of element. + long[]? wordStartOffsets; + + // The end index of each word within the node's name. This is different + // from wordEnds because it is not restricted to inline text boxes and can + // be used for any type of element. + long[]? wordEndOffsets; + // The nodes, if any, which this node is specified to control via // <a href="http://www.w3.org/TR/wai-aria/states_and_properties#aria-controls"> // <code>aria-controls</code></a>.
diff --git a/extensions/common/api/bluetooth.idl b/extensions/common/api/bluetooth.idl index dfb3316f..6b0c953 100644 --- a/extensions/common/api/bluetooth.idl +++ b/extensions/common/api/bluetooth.idl
@@ -96,6 +96,13 @@ // The transport type of the bluetooth device. Transport? transport; + + // The remaining battery of the device. + // TODO(https://crbug.com/973237): This field is only used by Chrome OS and + // it is different from others because it is not filled by the platform. In + // the future, when there is a unified Mojo service, this field will be + // moved to BluetoothDeviceInfo. + long? batteryPercentage; }; dictionary BluetoothFilter {
diff --git a/extensions/renderer/api/automation/automation_internal_custom_bindings.cc b/extensions/renderer/api/automation/automation_internal_custom_bindings.cc index 992cfd7..f4103e5a 100644 --- a/extensions/renderer/api/automation/automation_internal_custom_bindings.cc +++ b/extensions/renderer/api/automation/automation_internal_custom_bindings.cc
@@ -41,6 +41,7 @@ #include "ui/accessibility/ax_language_info.h" #include "ui/accessibility/ax_node.h" #include "ui/accessibility/ax_role_properties.h" +#include "ui/accessibility/ax_text_utils.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/geometry/rect_conversions.h" @@ -780,6 +781,22 @@ response.Set("nodeIds", child_ids); result.Set(response.Build()); }); + RouteNodeIDFunction( + "GetWordStartOffsets", + [](v8::Isolate* isolate, v8::ReturnValue<v8::Value> result, + AutomationAXTreeWrapper* tree_wrapper, ui::AXNode* node) { + std::vector<int> word_starts = ui::GetWordStartOffsets( + node->GetString16Attribute(ax::mojom::StringAttribute::kName)); + result.Set(gin::ConvertToV8(isolate, word_starts)); + }); + RouteNodeIDFunction( + "GetWordEndOffsets", + [](v8::Isolate* isolate, v8::ReturnValue<v8::Value> result, + AutomationAXTreeWrapper* tree_wrapper, ui::AXNode* node) { + std::vector<int> word_ends = ui::GetWordEndOffsets( + node->GetString16Attribute(ax::mojom::StringAttribute::kName)); + result.Set(gin::ConvertToV8(isolate, word_ends)); + }); // Bindings that take a Tree ID and Node ID and string attribute name // and return a property of the node.
diff --git a/extensions/renderer/resources/automation/automation_node.js b/extensions/renderer/resources/automation/automation_node.js index e2d6107..c22a4d3b 100644 --- a/extensions/renderer/resources/automation/automation_node.js +++ b/extensions/renderer/resources/automation/automation_node.js
@@ -466,6 +466,20 @@ var GetLanguageAnnotationForStringAttribute = natives.GetLanguageAnnotationForStringAttribute; +/** + * @param {string} axTreeID The id of the accessibility tree. + * @param {number} nodeID The id of a node. + * @return {!Array<number>} + */ +var GetWordStartOffsets = natives.GetWordStartOffsets; + +/** + * @param {string} axTreeID The id of the accessibility tree. + * @param {number} nodeID The id of a node. + * @return {!Array<number>} + */ +var GetWordEndOffsets = natives.GetWordEndOffsets; + var logging = requireNative('logging'); var utils = require('utils'); @@ -858,6 +872,14 @@ return impl.get(info.nodeId); }, + wordStartOffsets: function() { + return GetWordStartOffsets(this.treeID, this.id); + }, + + wordEndOffsets: function() { + return GetWordEndOffsets(this.treeID, this.id); + }, + addEventListener: function(eventType, callback, capture) { this.removeEventListener(eventType, callback); if (!this.listeners[eventType]) @@ -1679,6 +1701,8 @@ 'toString', 'boundsForRange', 'languageAnnotationForStringAttribute', + 'wordStartOffsets', + 'wordEndOffsets', ], readonly: $Array.concat( publicAttributes,
diff --git a/extensions/shell/BUILD.gn b/extensions/shell/BUILD.gn index 5c668f63..50dafde 100644 --- a/extensions/shell/BUILD.gn +++ b/extensions/shell/BUILD.gn
@@ -146,8 +146,6 @@ "browser/shell_navigation_ui_data.h", "browser/shell_network_controller_chromeos.cc", "browser/shell_network_controller_chromeos.h", - "browser/shell_network_delegate.cc", - "browser/shell_network_delegate.h", "browser/shell_prefs.cc", "browser/shell_prefs.h", "browser/shell_special_storage_policy.cc", @@ -156,8 +154,6 @@ "browser/shell_speech_recognition_manager_delegate.h", "browser/shell_update_query_params_delegate.cc", "browser/shell_update_query_params_delegate.h", - "browser/shell_url_request_context_getter.cc", - "browser/shell_url_request_context_getter.h", "browser/shell_virtual_keyboard_delegate.cc", "browser/shell_virtual_keyboard_delegate.h", "browser/shell_web_view_guest_delegate.cc",
diff --git a/extensions/shell/browser/shell_browser_context.cc b/extensions/shell/browser/shell_browser_context.cc index eb7dad28..abd8742 100644 --- a/extensions/shell/browser/shell_browser_context.cc +++ b/extensions/shell/browser/shell_browser_context.cc
@@ -7,41 +7,19 @@ #include <utility> #include "base/bind.h" -#include "base/command_line.h" #include "base/task/post_task.h" #include "components/guest_view/browser/guest_view_manager.h" -#include "components/network_session_configurator/common/network_switches.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/common/content_switches.h" -#include "extensions/browser/extension_protocols.h" -#include "extensions/common/constants.h" -#include "extensions/shell/browser/shell_browser_main_parts.h" -#include "extensions/shell/browser/shell_extension_system.h" -#include "extensions/shell/browser/shell_network_delegate.h" #include "extensions/shell/browser/shell_special_storage_policy.h" -#include "extensions/shell/browser/shell_url_request_context_getter.h" namespace extensions { -namespace { - -bool IgnoreCertificateErrors() { - return base::CommandLine::ForCurrentProcess()->HasSwitch( - ::switches::kIgnoreCertificateErrors); -} - -} // namespace - // Create a normal recording browser context. If we used an incognito context // then app_shell would also have to create a normal context and manage both. -ShellBrowserContext::ShellBrowserContext( - ShellBrowserMainParts* browser_main_parts) +ShellBrowserContext::ShellBrowserContext() : content::ShellBrowserContext(false /* off_the_record */, nullptr /* net_log */, true /* delay_services_creation */), - storage_policy_(new ShellSpecialStoragePolicy), - browser_main_parts_(browser_main_parts) {} + storage_policy_(new ShellSpecialStoragePolicy) {} ShellBrowserContext::~ShellBrowserContext() { content::BrowserContext::NotifyWillBeDestroyed(this); @@ -55,29 +33,6 @@ return storage_policy_.get(); } -net::URLRequestContextGetter* ShellBrowserContext::CreateRequestContext( - content::ProtocolHandlerMap* protocol_handlers, - content::URLRequestInterceptorScopedVector request_interceptors) { - DCHECK(!url_request_context_getter()); - // Handle only chrome-extension:// requests. - InfoMap* extension_info_map = - browser_main_parts_->extension_system()->info_map(); - (*protocol_handlers)[kExtensionScheme] = CreateExtensionProtocolHandler( - false /* is_incognito */, extension_info_map); - - set_url_request_context_getter(new ShellURLRequestContextGetter( - this, IgnoreCertificateErrors(), GetPath(), - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO}), - protocol_handlers, std::move(request_interceptors), nullptr /* net_log */, - extension_info_map)); - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&ShellBrowserContext::InitURLRequestContextOnIOThread, - base::Unretained(this))); - return url_request_context_getter(); -} - void ShellBrowserContext::SetCorsOriginAccessListForOrigin( const url::Origin& source_origin, std::vector<network::mojom::CorsOriginPatternPtr> allow_patterns, @@ -88,12 +43,4 @@ base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(closure)); } -void ShellBrowserContext::InitURLRequestContextOnIOThread() { - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - - // GetURLRequestContext() will create a URLRequestContext if it isn't - // initialized. - url_request_context_getter()->GetURLRequestContext(); -} - } // namespace extensions
diff --git a/extensions/shell/browser/shell_browser_context.h b/extensions/shell/browser/shell_browser_context.h index 93ad6ec..fa686ed 100644 --- a/extensions/shell/browser/shell_browser_context.h +++ b/extensions/shell/browser/shell_browser_context.h
@@ -12,21 +12,16 @@ namespace extensions { -class ShellBrowserMainParts; - // The BrowserContext used by the content, apps and extensions systems in // app_shell. class ShellBrowserContext final : public content::ShellBrowserContext { public: - explicit ShellBrowserContext(ShellBrowserMainParts* browser_main_parts); + explicit ShellBrowserContext(); ~ShellBrowserContext() override; // content::BrowserContext implementation. content::BrowserPluginGuestManager* GetGuestManager() override; storage::SpecialStoragePolicy* GetSpecialStoragePolicy() override; - net::URLRequestContextGetter* CreateRequestContext( - content::ProtocolHandlerMap* protocol_handlers, - content::URLRequestInterceptorScopedVector request_interceptors) override; void SetCorsOriginAccessListForOrigin( const url::Origin& source_origin, std::vector<network::mojom::CorsOriginPatternPtr> allow_patterns, @@ -34,10 +29,7 @@ base::OnceClosure closure) override; private: - void InitURLRequestContextOnIOThread(); - scoped_refptr<storage::SpecialStoragePolicy> storage_policy_; - ShellBrowserMainParts* browser_main_parts_; DISALLOW_COPY_AND_ASSIGN(ShellBrowserContext); };
diff --git a/extensions/shell/browser/shell_browser_main_parts.cc b/extensions/shell/browser/shell_browser_main_parts.cc index 3b06e3b5..f6ef1c7 100644 --- a/extensions/shell/browser/shell_browser_main_parts.cc +++ b/extensions/shell/browser/shell_browser_main_parts.cc
@@ -184,7 +184,7 @@ shell::EnsureBrowserContextKeyedServiceFactoriesBuilt(); // Initialize our "profile" equivalent. - browser_context_ = std::make_unique<ShellBrowserContext>(this); + browser_context_ = std::make_unique<ShellBrowserContext>(); // app_shell only supports a single user, so all preferences live in the user // data directory, including the device-wide local state.
diff --git a/extensions/shell/browser/shell_extensions_browser_client.cc b/extensions/shell/browser/shell_extensions_browser_client.cc index 716e6f0..a69dc94 100644 --- a/extensions/shell/browser/shell_extensions_browser_client.cc +++ b/extensions/shell/browser/shell_extensions_browser_client.cc
@@ -120,16 +120,6 @@ return false; } -net::URLRequestJob* -ShellExtensionsBrowserClient::MaybeCreateResourceBundleRequestJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const base::FilePath& directory_path, - const std::string& content_security_policy, - bool send_cors_header) { - return NULL; -} - base::FilePath ShellExtensionsBrowserClient::GetBundleResourcePath( const network::ResourceRequest& request, const base::FilePath& extension_resources_path, @@ -285,20 +275,6 @@ return ShellExtensionWebContentsObserver::FromWebContents(web_contents); } -ExtensionNavigationUIData* -ShellExtensionsBrowserClient::GetExtensionNavigationUIData( - net::URLRequest* request) { - content::ResourceRequestInfo* info = - content::ResourceRequestInfo::ForRequest(request); - if (!info) - return nullptr; - ShellNavigationUIData* navigation_data = - static_cast<ShellNavigationUIData*>(info->GetNavigationUIData()); - if (!navigation_data) - return nullptr; - return navigation_data->GetExtensionNavigationUIData(); -} - KioskDelegate* ShellExtensionsBrowserClient::GetKioskDelegate() { if (!kiosk_delegate_) kiosk_delegate_.reset(new ShellKioskDelegate());
diff --git a/extensions/shell/browser/shell_extensions_browser_client.h b/extensions/shell/browser/shell_extensions_browser_client.h index bb1a6c50..3a05d10 100644 --- a/extensions/shell/browser/shell_extensions_browser_client.h +++ b/extensions/shell/browser/shell_extensions_browser_client.h
@@ -53,12 +53,6 @@ bool CanExtensionCrossIncognito( const Extension* extension, content::BrowserContext* context) const override; - net::URLRequestJob* MaybeCreateResourceBundleRequestJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const base::FilePath& directory_path, - const std::string& content_security_policy, - bool send_cors_header) override; base::FilePath GetBundleResourcePath( const network::ResourceRequest& request, const base::FilePath& extension_resources_path, @@ -111,8 +105,6 @@ bool IsMinBrowserVersionSupported(const std::string& min_version) override; ExtensionWebContentsObserver* GetExtensionWebContentsObserver( content::WebContents* web_contents) override; - ExtensionNavigationUIData* GetExtensionNavigationUIData( - net::URLRequest* request) override; KioskDelegate* GetKioskDelegate() override; bool IsLockScreenContext(content::BrowserContext* context) override; std::string GetApplicationLocale() override;
diff --git a/extensions/shell/browser/shell_network_delegate.cc b/extensions/shell/browser/shell_network_delegate.cc deleted file mode 100644 index 9d6ca65f..0000000 --- a/extensions/shell/browser/shell_network_delegate.cc +++ /dev/null
@@ -1,175 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "extensions/shell/browser/shell_network_delegate.h" - -#include <map> - -#include "base/lazy_instance.h" -#include "content/public/browser/render_frame_host.h" -#include "content/public/browser/resource_request_info.h" -#include "extensions/browser/api/web_request/web_request_api.h" -#include "extensions/browser/api/web_request/web_request_info.h" -#include "extensions/browser/extension_system.h" -#include "extensions/browser/extensions_browser_client.h" -#include "extensions/browser/process_manager.h" -#include "net/url_request/url_request.h" - -namespace extensions { - -namespace { - -bool g_accept_all_cookies = true; - -using RequestMap = std::map<net::URLRequest*, std::unique_ptr<WebRequestInfo>>; -base::LazyInstance<RequestMap>::Leaky g_requests = LAZY_INSTANCE_INITIALIZER; - -// Returns the corresponding WebRequestInfo object for the request, creating it -// if necessary. -WebRequestInfo* GetWebRequestInfo(net::URLRequest* request) { - auto it = g_requests.Get().find(request); - if (it == g_requests.Get().end()) { - it = g_requests.Get() - .emplace(request, std::make_unique<WebRequestInfo>(request)) - .first; - } - return it->second.get(); -} - -} // namespace - -ShellNetworkDelegate::ShellNetworkDelegate( - void* browser_context, InfoMap* extension_info_map) { - browser_context_ = browser_context; - extension_info_map_ = extension_info_map; -} - -ShellNetworkDelegate::~ShellNetworkDelegate() {} - -void ShellNetworkDelegate::SetAcceptAllCookies(bool accept) { - g_accept_all_cookies = accept; -} - -int ShellNetworkDelegate::OnBeforeURLRequest( - net::URLRequest* request, - net::CompletionOnceCallback callback, - GURL* new_url) { - WebRequestInfo* web_request_info = GetWebRequestInfo(request); - bool should_collapse_initiator = false; - int result = ExtensionWebRequestEventRouter::GetInstance()->OnBeforeRequest( - browser_context_, extension_info_map_.get(), web_request_info, - std::move(callback), new_url, &should_collapse_initiator); - if (should_collapse_initiator) { - auto* info = content::ResourceRequestInfo::ForRequest(request); - DCHECK(info); - info->SetResourceRequestBlockedReason( - blink::ResourceRequestBlockedReason::kCollapsedByClient); - } - - return result; -} - -namespace { -void OnHeadersReceivedAdapter(net::CompletionOnceCallback callback, - const std::set<std::string>& removed_headers, - const std::set<std::string>& set_headers, - int error_code) { - std::move(callback).Run(error_code); -} -} // namespace - -int ShellNetworkDelegate::OnBeforeStartTransaction( - net::URLRequest* request, - net::CompletionOnceCallback callback, - net::HttpRequestHeaders* headers) { - return ExtensionWebRequestEventRouter::GetInstance()->OnBeforeSendHeaders( - browser_context_, extension_info_map_.get(), GetWebRequestInfo(request), - base::BindOnce(OnHeadersReceivedAdapter, std::move(callback)), headers); -} - -void ShellNetworkDelegate::OnStartTransaction( - net::URLRequest* request, - const net::HttpRequestHeaders& headers) { - ExtensionWebRequestEventRouter::GetInstance()->OnSendHeaders( - browser_context_, extension_info_map_.get(), GetWebRequestInfo(request), - headers); -} - -int ShellNetworkDelegate::OnHeadersReceived( - net::URLRequest* request, - net::CompletionOnceCallback callback, - const net::HttpResponseHeaders* original_response_headers, - scoped_refptr<net::HttpResponseHeaders>* override_response_headers, - GURL* allowed_unsafe_redirect_url) { - return ExtensionWebRequestEventRouter::GetInstance()->OnHeadersReceived( - browser_context_, extension_info_map_.get(), GetWebRequestInfo(request), - std::move(callback), original_response_headers, override_response_headers, - allowed_unsafe_redirect_url); -} - -void ShellNetworkDelegate::OnBeforeRedirect( - net::URLRequest* request, - const GURL& new_location) { - auto* info = GetWebRequestInfo(request); - info->AddResponseInfoFromURLRequest(request); - ExtensionWebRequestEventRouter::GetInstance()->OnBeforeRedirect( - browser_context_, extension_info_map_.get(), info, new_location); -} - -void ShellNetworkDelegate::OnResponseStarted(net::URLRequest* request, - int net_error) { - auto* info = GetWebRequestInfo(request); - info->AddResponseInfoFromURLRequest(request); - ExtensionWebRequestEventRouter::GetInstance()->OnResponseStarted( - browser_context_, extension_info_map_.get(), info, net_error); -} - -void ShellNetworkDelegate::OnCompleted(net::URLRequest* request, - bool started, - int net_error) { - DCHECK_NE(net::ERR_IO_PENDING, net_error); - - if (net_error == net::OK) { - bool is_redirect = request->response_headers() && - net::HttpResponseHeaders::IsRedirectResponseCode( - request->response_headers()->response_code()); - if (!is_redirect) { - ExtensionWebRequestEventRouter::GetInstance()->OnCompleted( - browser_context_, extension_info_map_.get(), - GetWebRequestInfo(request), net_error); - } - } else { - ExtensionWebRequestEventRouter::GetInstance()->OnErrorOccurred( - browser_context_, extension_info_map_.get(), GetWebRequestInfo(request), - started, net_error); - } -} - -void ShellNetworkDelegate::OnURLRequestDestroyed( - net::URLRequest* request) { - auto it = g_requests.Get().find(request); - DCHECK(it != g_requests.Get().end()); - ExtensionWebRequestEventRouter::GetInstance()->OnRequestWillBeDestroyed( - browser_context_, it->second.get()); - g_requests.Get().erase(it); -} - -void ShellNetworkDelegate::OnPACScriptError( - int line_number, - const base::string16& error) { -} - -net::NetworkDelegate::AuthRequiredResponse ShellNetworkDelegate::OnAuthRequired( - net::URLRequest* request, - const net::AuthChallengeInfo& auth_info, - AuthCallback callback, - net::AuthCredentials* credentials) { - auto* info = GetWebRequestInfo(request); - info->AddResponseInfoFromURLRequest(request); - return ExtensionWebRequestEventRouter::GetInstance()->OnAuthRequired( - browser_context_, extension_info_map_.get(), info, auth_info, - std::move(callback), credentials); -} - -} // namespace extensions
diff --git a/extensions/shell/browser/shell_network_delegate.h b/extensions/shell/browser/shell_network_delegate.h deleted file mode 100644 index 3a7dda2..0000000 --- a/extensions/shell/browser/shell_network_delegate.h +++ /dev/null
@@ -1,61 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef EXTENSIONS_SHELL_BROWSER_SHELL_NETWORK_DELEGATE_H_ -#define EXTENSIONS_SHELL_BROWSER_SHELL_NETWORK_DELEGATE_H_ - -#include "base/macros.h" -#include "extensions/browser/info_map.h" -#include "net/base/network_delegate_impl.h" - -namespace extensions { - -class InfoMap; - -class ShellNetworkDelegate : public net::NetworkDelegateImpl { - public: - ShellNetworkDelegate(void* browser_context, InfoMap* extension_info_map); - ~ShellNetworkDelegate() override; - - static void SetAcceptAllCookies(bool accept); - - private: - // NetworkDelegate implementation. - int OnBeforeURLRequest(net::URLRequest* request, - net::CompletionOnceCallback callback, - GURL* new_url) override; - int OnBeforeStartTransaction(net::URLRequest* request, - net::CompletionOnceCallback callback, - net::HttpRequestHeaders* headers) override; - void OnStartTransaction(net::URLRequest* request, - const net::HttpRequestHeaders& headers) override; - int OnHeadersReceived( - net::URLRequest* request, - net::CompletionOnceCallback callback, - const net::HttpResponseHeaders* original_response_headers, - scoped_refptr<net::HttpResponseHeaders>* override_response_headers, - GURL* allowed_unsafe_redirect_url) override; - void OnBeforeRedirect(net::URLRequest* request, - const GURL& new_location) override; - void OnResponseStarted(net::URLRequest* request, int net_error) override; - void OnCompleted(net::URLRequest* request, - bool started, - int net_error) override; - void OnURLRequestDestroyed(net::URLRequest* request) override; - void OnPACScriptError(int line_number, const base::string16& error) override; - net::NetworkDelegate::AuthRequiredResponse OnAuthRequired( - net::URLRequest* request, - const net::AuthChallengeInfo& auth_info, - AuthCallback callback, - net::AuthCredentials* credentials) override; - - void* browser_context_; - scoped_refptr<extensions::InfoMap> extension_info_map_; - - DISALLOW_COPY_AND_ASSIGN(ShellNetworkDelegate); -}; - -} // namespace extensions - -#endif // EXTENSIONS_SHELL_BROWSER_SHELL_NETWORK_DELEGATE_H_
diff --git a/extensions/shell/browser/shell_url_request_context_getter.cc b/extensions/shell/browser/shell_url_request_context_getter.cc deleted file mode 100644 index 9cb25d8..0000000 --- a/extensions/shell/browser/shell_url_request_context_getter.cc +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "extensions/shell/browser/shell_url_request_context_getter.h" - -#include <utility> - -#include "content/public/browser/resource_request_info.h" -#include "extensions/browser/info_map.h" -#include "extensions/shell/browser/shell_network_delegate.h" - -namespace extensions { - -ShellURLRequestContextGetter::ShellURLRequestContextGetter( - content::BrowserContext* browser_context, - bool ignore_certificate_errors, - const base::FilePath& base_path, - scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, - content::ProtocolHandlerMap* protocol_handlers, - content::URLRequestInterceptorScopedVector request_interceptors, - net::NetLog* net_log, - InfoMap* extension_info_map) - : content::ShellURLRequestContextGetter(ignore_certificate_errors, - false /* not incognito */, - base_path, - std::move(io_task_runner), - protocol_handlers, - std::move(request_interceptors), - net_log), - browser_context_(browser_context), - extension_info_map_(extension_info_map) {} - -ShellURLRequestContextGetter::~ShellURLRequestContextGetter() { -} - -std::unique_ptr<net::NetworkDelegate> -ShellURLRequestContextGetter::CreateNetworkDelegate() { - return std::make_unique<ShellNetworkDelegate>(browser_context_, - extension_info_map_); -} - -} // namespace extensions
diff --git a/extensions/shell/browser/shell_url_request_context_getter.h b/extensions/shell/browser/shell_url_request_context_getter.h deleted file mode 100644 index 3fe6fd04..0000000 --- a/extensions/shell/browser/shell_url_request_context_getter.h +++ /dev/null
@@ -1,55 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef EXTENSIONS_SHELL_BROWSER_SHELL_URL_REQUEST_CONTEXT_GETTER_H_ -#define EXTENSIONS_SHELL_BROWSER_SHELL_URL_REQUEST_CONTEXT_GETTER_H_ - -#include "base/files/file_path.h" -#include "base/macros.h" -#include "base/single_thread_task_runner.h" -#include "content/shell/browser/shell_url_request_context_getter.h" - -namespace content { -class BrowserContext; -} - -namespace net { -class NetworkDelegate; -class NetLog; -} - -namespace extensions { - -class InfoMap; - -class ShellURLRequestContextGetter - : public content::ShellURLRequestContextGetter { - public: - ShellURLRequestContextGetter( - content::BrowserContext* browser_context, - bool ignore_certificate_errors, - const base::FilePath& base_path, - scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, - content::ProtocolHandlerMap* protocol_handlers, - content::URLRequestInterceptorScopedVector request_interceptors, - net::NetLog* net_log, - InfoMap* extension_info_map); - - // content::ShellURLRequestContextGetter implementation. - std::unique_ptr<net::NetworkDelegate> CreateNetworkDelegate() override; - - protected: - ~ShellURLRequestContextGetter() override; - - private: - content::BrowserContext* browser_context_; - InfoMap* extension_info_map_; - - private: - DISALLOW_COPY_AND_ASSIGN(ShellURLRequestContextGetter); -}; - -} // namespace extensions - -#endif // EXTENSIONS_SHELL_BROWSER_SHELL_URL_REQUEST_CONTEXT_GETTER_H_
diff --git a/fuchsia/base/mem_buffer_util.cc b/fuchsia/base/mem_buffer_util.cc index 575fa589..c71f2180 100644 --- a/fuchsia/base/mem_buffer_util.cc +++ b/fuchsia/base/mem_buffer_util.cc
@@ -29,8 +29,7 @@ fuchsia::mem::Buffer MemBufferFromString(const base::StringPiece& data) { fuchsia::mem::Buffer buffer; - zx_status_t status = - zx::vmo::create(data.size(), ZX_VMO_NON_RESIZABLE, &buffer.vmo); + zx_status_t status = zx::vmo::create(data.size(), 0, &buffer.vmo); ZX_CHECK(status == ZX_OK, status) << "zx_vmo_create"; status = buffer.vmo.write(data.data(), 0, data.size()); @@ -78,10 +77,9 @@ fuchsia::mem::Buffer CloneBuffer(const fuchsia::mem::Buffer& buffer) { fuchsia::mem::Buffer output; output.size = buffer.size; - zx_status_t status = - buffer.vmo.clone(ZX_VMO_CLONE_COPY_ON_WRITE | ZX_VMO_CLONE_NON_RESIZEABLE, - 0, buffer.size, &output.vmo); - ZX_CHECK(status == ZX_OK, status) << "zx_vmo_clone"; + zx_status_t status = buffer.vmo.create_child(ZX_VMO_CHILD_COPY_ON_WRITE, 0, + buffer.size, &output.vmo); + ZX_CHECK(status == ZX_OK, status) << "zx_vmo_create_child"; return output; }
diff --git a/fuchsia/engine/context_provider_impl.cc b/fuchsia/engine/context_provider_impl.cc index f5086687..b55dd2e 100644 --- a/fuchsia/engine/context_provider_impl.cc +++ b/fuchsia/engine/context_provider_impl.cc
@@ -6,9 +6,14 @@ #include <fuchsia/sys/cpp/fidl.h> #include <lib/async/default.h> +#include <lib/fdio/directory.h> +#include <lib/fdio/fd.h> #include <lib/fdio/io.h> #include <lib/zx/job.h> #include <stdio.h> +#include <sys/stat.h> +#include <sys/types.h> +#include <unistd.h> #include <zircon/processargs.h> #include <utility> @@ -17,6 +22,7 @@ #include "base/base_paths_fuchsia.h" #include "base/bind.h" #include "base/command_line.h" +#include "base/files/scoped_file.h" #include "base/fuchsia/default_job.h" #include "base/fuchsia/fuchsia_logging.h" #include "base/logging.h" @@ -47,6 +53,31 @@ return zx::channel(); } +// Verifies that Vulkan loader service is provided by the specified service +// directory. +bool CheckVulkanSupport( + const fidl::InterfaceHandle<::fuchsia::io::Directory>& directory_handle, + bool* enable_vulkan) { + zx::channel dir_channel(fdio_service_clone(directory_handle.channel().get())); + if (!dir_channel) + return false; + + base::ScopedFD dir_fd; + zx_status_t status = fdio_fd_create(dir_channel.release(), + base::ScopedFD::Receiver(dir_fd).get()); + if (status != ZX_OK) { + ZX_DLOG(ERROR, status) << "fdio_fd_create()"; + return false; + } + + struct stat statbuf; + int result = + fstatat(dir_fd.get(), "fuchsia.vulkan.loader.Loader", &statbuf, 0); + *enable_vulkan = result == 0; + + return true; +} + } // namespace ContextProviderImpl::ContextProviderImpl() = default; @@ -67,11 +98,22 @@ return; } + fidl::InterfaceHandle<::fuchsia::io::Directory> service_directory = + std::move(*params.mutable_service_directory()); + + // Enable Vulkan if the Vulkan loader service is present in the service + // directory. + bool enable_vulkan = false; + if (!CheckVulkanSupport(service_directory, &enable_vulkan)) { + // TODO(crbug.com/934539): Add type epitaph. + DLOG(WARNING) << "Invalid |service_directory| in CreateContextParams."; + return; + } + base::LaunchOptions launch_options; service_manager::SandboxPolicyFuchsia sandbox_policy; sandbox_policy.Initialize(service_manager::SANDBOX_TYPE_WEB_CONTEXT); - sandbox_policy.SetServiceDirectory( - std::move(*params.mutable_service_directory())); + sandbox_policy.SetServiceDirectory(std::move(service_directory)); sandbox_policy.UpdateLaunchOptionsForSandbox(&launch_options); // Transfer the ContextRequest handle to a well-known location in the child @@ -109,8 +151,9 @@ } launch_options.job_handle = job.get(); + base::CommandLine launch_command = *base::CommandLine::ForCurrentProcess(); + // Connect DevTools listeners to the new Context process. - base::CommandLine launch_command(*base::CommandLine::ForCurrentProcess()); std::vector<zx::channel> devtools_listener_channels; if (devtools_listeners_.size() != 0) { std::vector<std::string> handles_ids; @@ -129,6 +172,17 @@ base::JoinString(handles_ids, ",")); } + // Enable Vulkan when the Vulkan loader service is included in the service + // directory. + // TODO(https://crbug.com/962617): Enable Vulkan by default and remove this + // hack. + if (enable_vulkan) { + launch_command.AppendSwitchASCII( + "--enable-features", "DefaultEnableOopRasterization,UseSkiaRenderer"); + launch_command.AppendSwitch("--use-vulkan"); + launch_command.AppendSwitchASCII("--use-gl", "stub"); + } + if (launch_for_test_) launch_for_test_.Run(launch_command, launch_options); else
diff --git a/fuchsia/http/url_loader_impl.cc b/fuchsia/http/url_loader_impl.cc index a01491a..f745b9c2 100644 --- a/fuchsia/http/url_loader_impl.cc +++ b/fuchsia/http/url_loader_impl.cc
@@ -32,8 +32,7 @@ ::fuchsia::mem::Buffer mem_buffer; mem_buffer.size = total_size; - zx_status_t result = - zx::vmo::create(total_size, ZX_VMO_NON_RESIZABLE, &mem_buffer.vmo); + zx_status_t result = zx::vmo::create(total_size, 0, &mem_buffer.vmo); if (result != ZX_OK) { ZX_DLOG(WARNING, result) << "zx_vmo_create"; return nullptr;
diff --git a/fuchsia/runners/cast/sandbox_policy b/fuchsia/runners/cast/sandbox_policy index 0883374..61e5eed 100644 --- a/fuchsia/runners/cast/sandbox_policy +++ b/fuchsia/runners/cast/sandbox_policy
@@ -14,7 +14,6 @@ "fuchsia.ui.input.ImeService", "fuchsia.ui.input.ImeVisibilityService", "fuchsia.ui.scenic.Scenic", - "fuchsia.vulkan.loader.Loader", "fuchsia.web.ContextProvider" ] }
diff --git a/gpu/command_buffer/service/wrapped_sk_image.cc b/gpu/command_buffer/service/wrapped_sk_image.cc index a35f288..3f5c1de 100644 --- a/gpu/command_buffer/service/wrapped_sk_image.cc +++ b/gpu/command_buffer/service/wrapped_sk_image.cc
@@ -125,40 +125,32 @@ context_state_->set_need_context_state_reset(true); + // Initializing to bright green makes it obvious if the pixels are not + // properly set before they are displayed (e.g. https://crbug.com/956555). + // We don't do this on release builds because there is a slight overhead. +#if DCHECK_IS_ON() + backend_texture_ = context_state_->gr_context()->createBackendTexture( + size().width(), size().height(), GetSkColorType(), SkColors::kGreen, + GrMipMapped::kNo, GrRenderable::kYes); +#else backend_texture_ = context_state_->gr_context()->createBackendTexture( size().width(), size().height(), GetSkColorType(), GrMipMapped::kNo, GrRenderable::kYes); +#endif if (!backend_texture_.isValid()) return false; -#if DCHECK_IS_ON() - bool need_temporary_surface = true; -#else - bool need_temporary_surface = !data.empty(); -#endif - - sk_sp<SkSurface> surface = - need_temporary_surface - ? SkSurface::MakeFromBackendTexture( - context_state_->gr_context(), backend_texture_, - kTopLeft_GrSurfaceOrigin, /*sampleCnt=*/0, GetSkColorType(), - color_space().ToSkColorSpace(), /*surfaceProps=*/nullptr) - : nullptr; - -#if DCHECK_IS_ON() - { - auto* canvas = surface->getCanvas(); - canvas->clear(SK_ColorGREEN); - } -#endif - if (!data.empty()) { SkBitmap bitmap; if (!bitmap.installPixels(info, const_cast<uint8_t*>(data.data()), info.minRowBytes())) { return false; } + sk_sp<SkSurface> surface = SkSurface::MakeFromBackendTexture( + context_state_->gr_context(), backend_texture_, + kTopLeft_GrSurfaceOrigin, /*sampleCnt=*/0, GetSkColorType(), + color_space().ToSkColorSpace(), /*surfaceProps=*/nullptr); surface->writePixels(bitmap, /*dstX=*/0, /*dstY=*/0); }
diff --git a/gpu/config/gpu_finch_features.cc b/gpu/config/gpu_finch_features.cc index 99603711..c5a7732b 100644 --- a/gpu/config/gpu_finch_features.cc +++ b/gpu/config/gpu_finch_features.cc
@@ -74,12 +74,25 @@ const base::Feature kDirectCompositionUnderlays{ "DirectCompositionUnderlays", base::FEATURE_ENABLED_BY_DEFAULT}; +// Use ThreadPriority::DISPLAY for GPU main, viz compositor and IO threads. +#if defined(OS_ANDROID) || defined(OS_CHROMEOS) || defined(USE_OZONE) +const base::Feature kGpuUseDisplayThreadPriority{ + "GpuUseDisplayThreadPriority", base::FEATURE_ENABLED_BY_DEFAULT}; +#else +const base::Feature kGpuUseDisplayThreadPriority{ + "GpuUseDisplayThreadPriority", base::FEATURE_DISABLED_BY_DEFAULT}; +#endif + // Allow GPU watchdog to keep waiting for ackowledgement if one is already // issued from the monitored thread. const base::Feature kGpuWatchdogNoTerminationAwaitingAcknowledge{ "GpuWatchdogNoTerminationAwaitingAcknowledge", base::FEATURE_DISABLED_BY_DEFAULT}; +// Gpu watchdog V2 to simplify the logic and reduce GPU hangs +const base::Feature kGpuWatchdogV2{"GpuWatchdogV2", + base::FEATURE_DISABLED_BY_DEFAULT}; + #if defined(OS_MACOSX) // Enable use of Metal for OOP rasterization. const base::Feature kMetal{"Metal", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/gpu/config/gpu_finch_features.h b/gpu/config/gpu_finch_features.h index 3d22294..c222413 100644 --- a/gpu/config/gpu_finch_features.h +++ b/gpu/config/gpu_finch_features.h
@@ -29,9 +29,13 @@ GPU_EXPORT extern const base::Feature kDirectCompositionUnderlays; +GPU_EXPORT extern const base::Feature kGpuUseDisplayThreadPriority; + GPU_EXPORT extern const base::Feature kGpuWatchdogNoTerminationAwaitingAcknowledge; +GPU_EXPORT extern const base::Feature kGpuWatchdogV2; + #if defined(OS_MACOSX) GPU_EXPORT extern const base::Feature kMetal; #endif
diff --git a/gpu/ipc/service/BUILD.gn b/gpu/ipc/service/BUILD.gn index 075753d..fe5b1be3 100644 --- a/gpu/ipc/service/BUILD.gn +++ b/gpu/ipc/service/BUILD.gn
@@ -31,6 +31,8 @@ "gpu_memory_buffer_factory.h", "gpu_watchdog_thread.cc", "gpu_watchdog_thread.h", + "gpu_watchdog_thread_v2.cc", + "gpu_watchdog_thread_v2.h", "image_decode_accelerator_stub.cc", "image_decode_accelerator_stub.h", "image_decode_accelerator_worker.h",
diff --git a/gpu/ipc/service/gpu_init.cc b/gpu/ipc/service/gpu_init.cc index 46fafa1..f604ee7 100644 --- a/gpu/ipc/service/gpu_init.cc +++ b/gpu/ipc/service/gpu_init.cc
@@ -17,11 +17,13 @@ #include "gpu/command_buffer/service/service_utils.h" #include "gpu/config/gpu_driver_bug_list.h" #include "gpu/config/gpu_driver_bug_workaround_type.h" +#include "gpu/config/gpu_finch_features.h" #include "gpu/config/gpu_info_collector.h" #include "gpu/config/gpu_switches.h" #include "gpu/config/gpu_switching.h" #include "gpu/config/gpu_util.h" #include "gpu/ipc/service/gpu_watchdog_thread.h" +#include "gpu/ipc/service/gpu_watchdog_thread_v2.h" #include "ui/base/ui_base_features.h" #include "ui/gfx/switches.h" #include "ui/gl/buildflags.h" @@ -200,8 +202,14 @@ // Start the GPU watchdog only after anything that is expected to be time // consuming has completed, otherwise the process is liable to be aborted. if (enable_watchdog && !delayed_watchdog_enable) { - watchdog_thread_ = gpu::GpuWatchdogThread::Create( - gpu_preferences_.watchdog_starts_backgrounded); + if (base::FeatureList::IsEnabled(features::kGpuWatchdogV2)) { + watchdog_thread_ = gpu::GpuWatchdogThreadImplV2::Create( + gpu_preferences_.watchdog_starts_backgrounded); + } else { + watchdog_thread_ = gpu::GpuWatchdogThreadImplV1::Create( + gpu_preferences_.watchdog_starts_backgrounded); + } + #if defined(OS_WIN) // This is a workaround for an occasional deadlock between watchdog and // current thread. Watchdog hangs at thread initialization in @@ -387,8 +395,13 @@ watchdog_thread_->Stop(); watchdog_thread_ = nullptr; } else if (enable_watchdog && delayed_watchdog_enable) { - watchdog_thread_ = gpu::GpuWatchdogThread::Create( - gpu_preferences_.watchdog_starts_backgrounded); + if (base::FeatureList::IsEnabled(features::kGpuWatchdogV2)) { + watchdog_thread_ = gpu::GpuWatchdogThreadImplV2::Create( + gpu_preferences_.watchdog_starts_backgrounded); + } else { + watchdog_thread_ = gpu::GpuWatchdogThreadImplV1::Create( + gpu_preferences_.watchdog_starts_backgrounded); + } } UMA_HISTOGRAM_ENUMERATION("GPU.GLImplementation", gl::GetGLImplementation());
diff --git a/gpu/ipc/service/gpu_watchdog_thread.cc b/gpu/ipc/service/gpu_watchdog_thread.cc index b51f7ac2..78125a3 100644 --- a/gpu/ipc/service/gpu_watchdog_thread.cc +++ b/gpu/ipc/service/gpu_watchdog_thread.cc
@@ -52,9 +52,8 @@ } // namespace -GpuWatchdogThread::GpuWatchdogThread() - : base::Thread("Watchdog"), - watched_task_runner_(base::ThreadTaskRunnerHandle::Get()), +GpuWatchdogThreadImplV1::GpuWatchdogThreadImplV1() + : watched_task_runner_(base::ThreadTaskRunnerHandle::Get()), timeout_(base::TimeDelta::FromMilliseconds(kGpuTimeout)), armed_(false), task_observer_(this), @@ -92,9 +91,9 @@ } // static -std::unique_ptr<GpuWatchdogThread> GpuWatchdogThread::Create( +std::unique_ptr<GpuWatchdogThreadImplV1> GpuWatchdogThreadImplV1::Create( bool start_backgrounded) { - auto watchdog_thread = base::WrapUnique(new GpuWatchdogThread); + auto watchdog_thread = base::WrapUnique(new GpuWatchdogThreadImplV1); base::Thread::Options options; options.timer_slack = base::TIMER_SLACK_MAXIMUM; watchdog_thread->StartWithOptions(options); @@ -103,87 +102,88 @@ return watchdog_thread; } -void GpuWatchdogThread::CheckArmed() { +void GpuWatchdogThreadImplV1::CheckArmed() { base::subtle::NoBarrier_Store(&awaiting_acknowledge_, false); } -void GpuWatchdogThread::ReportProgress() { +void GpuWatchdogThreadImplV1::ReportProgress() { CheckArmed(); } -void GpuWatchdogThread::OnBackgrounded() { +void GpuWatchdogThreadImplV1::OnBackgrounded() { // As we stop the task runner before destroying this class, the unretained // reference will always outlive the task. task_runner()->PostTask( FROM_HERE, - base::BindOnce(&GpuWatchdogThread::OnBackgroundedOnWatchdogThread, + base::BindOnce(&GpuWatchdogThreadImplV1::OnBackgroundedOnWatchdogThread, base::Unretained(this))); } -void GpuWatchdogThread::OnForegrounded() { +void GpuWatchdogThreadImplV1::OnForegrounded() { // As we stop the task runner before destroying this class, the unretained // reference will always outlive the task. task_runner()->PostTask( FROM_HERE, - base::BindOnce(&GpuWatchdogThread::OnForegroundedOnWatchdogThread, + base::BindOnce(&GpuWatchdogThreadImplV1::OnForegroundedOnWatchdogThread, base::Unretained(this))); } -void GpuWatchdogThread::Init() { +void GpuWatchdogThreadImplV1::Init() { // Schedule the first check. OnCheck(false); } -void GpuWatchdogThread::CleanUp() { +void GpuWatchdogThreadImplV1::CleanUp() { weak_factory_.InvalidateWeakPtrs(); } -GpuWatchdogThread::GpuWatchdogTaskObserver::GpuWatchdogTaskObserver( - GpuWatchdogThread* watchdog) +GpuWatchdogThreadImplV1::GpuWatchdogTaskObserver::GpuWatchdogTaskObserver( + GpuWatchdogThreadImplV1* watchdog) : watchdog_(watchdog) {} -GpuWatchdogThread::GpuWatchdogTaskObserver::~GpuWatchdogTaskObserver() = +GpuWatchdogThreadImplV1::GpuWatchdogTaskObserver::~GpuWatchdogTaskObserver() = default; -void GpuWatchdogThread::GpuWatchdogTaskObserver::WillProcessTask( +void GpuWatchdogThreadImplV1::GpuWatchdogTaskObserver::WillProcessTask( const base::PendingTask& pending_task) { watchdog_->CheckArmed(); } -void GpuWatchdogThread::GpuWatchdogTaskObserver::DidProcessTask( +void GpuWatchdogThreadImplV1::GpuWatchdogTaskObserver::DidProcessTask( const base::PendingTask& pending_task) {} -GpuWatchdogThread::SuspensionCounter::SuspensionCounterRef:: +GpuWatchdogThreadImplV1::SuspensionCounter::SuspensionCounterRef:: SuspensionCounterRef(SuspensionCounter* counter) : counter_(counter) { counter_->OnAddRef(); } -GpuWatchdogThread::SuspensionCounter::SuspensionCounterRef:: +GpuWatchdogThreadImplV1::SuspensionCounter::SuspensionCounterRef:: ~SuspensionCounterRef() { counter_->OnReleaseRef(); } -GpuWatchdogThread::SuspensionCounter::SuspensionCounter( - GpuWatchdogThread* watchdog_thread) +GpuWatchdogThreadImplV1::SuspensionCounter::SuspensionCounter( + GpuWatchdogThreadImplV1* watchdog_thread) : watchdog_thread_(watchdog_thread) { // This class will only be used on the watchdog thread, but is constructed on // the main thread. Detach. DETACH_FROM_SEQUENCE(watchdog_thread_sequence_checker_); } -std::unique_ptr<GpuWatchdogThread::SuspensionCounter::SuspensionCounterRef> -GpuWatchdogThread::SuspensionCounter::Take() { +std::unique_ptr< + GpuWatchdogThreadImplV1::SuspensionCounter::SuspensionCounterRef> +GpuWatchdogThreadImplV1::SuspensionCounter::Take() { DCHECK_CALLED_ON_VALID_SEQUENCE(watchdog_thread_sequence_checker_); return std::make_unique<SuspensionCounterRef>(this); } -bool GpuWatchdogThread::SuspensionCounter::HasRefs() const { +bool GpuWatchdogThreadImplV1::SuspensionCounter::HasRefs() const { DCHECK_CALLED_ON_VALID_SEQUENCE(watchdog_thread_sequence_checker_); return suspend_count_ > 0; } -void GpuWatchdogThread::SuspensionCounter::OnWatchdogThreadStopped() { +void GpuWatchdogThreadImplV1::SuspensionCounter::OnWatchdogThreadStopped() { DETACH_FROM_SEQUENCE(watchdog_thread_sequence_checker_); // Null the |watchdog_thread_| ptr at shutdown to avoid trying to suspend or @@ -191,14 +191,14 @@ watchdog_thread_ = nullptr; } -void GpuWatchdogThread::SuspensionCounter::OnAddRef() { +void GpuWatchdogThreadImplV1::SuspensionCounter::OnAddRef() { DCHECK_CALLED_ON_VALID_SEQUENCE(watchdog_thread_sequence_checker_); suspend_count_++; if (watchdog_thread_ && suspend_count_ == 1) watchdog_thread_->SuspendStateChanged(); } -void GpuWatchdogThread::SuspensionCounter::OnReleaseRef() { +void GpuWatchdogThreadImplV1::SuspensionCounter::OnReleaseRef() { DCHECK_CALLED_ON_VALID_SEQUENCE(watchdog_thread_sequence_checker_); DCHECK_GT(suspend_count_, 0u); suspend_count_--; @@ -206,7 +206,7 @@ watchdog_thread_->SuspendStateChanged(); } -GpuWatchdogThread::~GpuWatchdogThread() { +GpuWatchdogThreadImplV1::~GpuWatchdogThreadImplV1() { DCHECK(watched_task_runner_->BelongsToCurrentThread()); Stop(); @@ -233,7 +233,7 @@ base::MessageLoopCurrent::Get()->RemoveTaskObserver(&task_observer_); } -void GpuWatchdogThread::OnAcknowledge() { +void GpuWatchdogThreadImplV1::OnAcknowledge() { CHECK(base::PlatformThread::CurrentId() == GetThreadId()); // The check has already been acknowledged and another has already been @@ -275,12 +275,12 @@ // The monitored thread has responded. Post a task to check it again. task_runner()->PostDelayedTask( FROM_HERE, - base::BindOnce(&GpuWatchdogThread::OnCheck, weak_factory_.GetWeakPtr(), - was_suspended), + base::BindOnce(&GpuWatchdogThreadImplV1::OnCheck, + weak_factory_.GetWeakPtr(), was_suspended), 0.5 * timeout_); } -void GpuWatchdogThread::OnCheck(bool after_suspend) { +void GpuWatchdogThreadImplV1::OnCheck(bool after_suspend) { CHECK(base::PlatformThread::CurrentId() == GetThreadId()); // Do not create any new termination tasks if one has already been created @@ -318,17 +318,17 @@ // not respond in time. task_runner()->PostDelayedTask( FROM_HERE, - base::BindOnce(&GpuWatchdogThread::OnCheckTimeout, + base::BindOnce(&GpuWatchdogThreadImplV1::OnCheckTimeout, weak_factory_.GetWeakPtr()), timeout); } -void GpuWatchdogThread::OnCheckTimeout() { +void GpuWatchdogThreadImplV1::OnCheckTimeout() { DeliberatelyTerminateToRecoverFromHang(); } // Use the --disable-gpu-watchdog command line switch to disable this. -void GpuWatchdogThread::DeliberatelyTerminateToRecoverFromHang() { +void GpuWatchdogThreadImplV1::DeliberatelyTerminateToRecoverFromHang() { // Should not get here while the system is suspended. DCHECK(!suspension_counter_.HasRefs()); @@ -359,7 +359,7 @@ if (use_thread_cpu_time_ && (time_since_arm < timeout_)) { task_runner()->PostDelayedTask( FROM_HERE, - base::BindOnce(&GpuWatchdogThread::OnCheckTimeout, + base::BindOnce(&GpuWatchdogThreadImplV1::OnCheckTimeout, weak_factory_.GetWeakPtr()), timeout_ - time_since_arm); return; @@ -500,7 +500,7 @@ } #if defined(USE_X11) -void GpuWatchdogThread::SetupXServer() { +void GpuWatchdogThreadImplV1::SetupXServer() { display_ = XOpenDisplay(nullptr); if (display_) { window_ = @@ -511,13 +511,13 @@ host_tty_ = GetActiveTTY(); } -void GpuWatchdogThread::SetupXChangeProp() { +void GpuWatchdogThreadImplV1::SetupXChangeProp() { DCHECK(display_); XChangeProperty(display_, window_, atom_, XA_STRING, 8, PropModeReplace, text, (base::size(text) - 1)); } -bool GpuWatchdogThread::MatchXEventAtom(XEvent* event) { +bool GpuWatchdogThreadImplV1::MatchXEventAtom(XEvent* event) { if (event->xproperty.window == window_ && event->type == PropertyNotify && event->xproperty.atom == atom_) return true; @@ -526,37 +526,37 @@ } #endif -void GpuWatchdogThread::AddPowerObserver() { +void GpuWatchdogThreadImplV1::AddPowerObserver() { // As we stop the task runner before destroying this class, the unretained // reference will always outlive the task. - task_runner()->PostTask(FROM_HERE, - base::BindOnce(&GpuWatchdogThread::OnAddPowerObserver, - base::Unretained(this))); + task_runner()->PostTask( + FROM_HERE, base::BindOnce(&GpuWatchdogThreadImplV1::OnAddPowerObserver, + base::Unretained(this))); } -void GpuWatchdogThread::OnAddPowerObserver() { +void GpuWatchdogThreadImplV1::OnAddPowerObserver() { base::PowerMonitor* power_monitor = base::PowerMonitor::Get(); DCHECK(power_monitor); power_monitor->AddObserver(this); } -void GpuWatchdogThread::OnSuspend() { +void GpuWatchdogThreadImplV1::OnSuspend() { power_suspend_ref_ = suspension_counter_.Take(); } -void GpuWatchdogThread::OnResume() { +void GpuWatchdogThreadImplV1::OnResume() { power_suspend_ref_.reset(); } -void GpuWatchdogThread::OnBackgroundedOnWatchdogThread() { +void GpuWatchdogThreadImplV1::OnBackgroundedOnWatchdogThread() { background_suspend_ref_ = suspension_counter_.Take(); } -void GpuWatchdogThread::OnForegroundedOnWatchdogThread() { +void GpuWatchdogThreadImplV1::OnForegroundedOnWatchdogThread() { background_suspend_ref_.reset(); } -void GpuWatchdogThread::SuspendStateChanged() { +void GpuWatchdogThreadImplV1::SuspendStateChanged() { if (suspension_counter_.HasRefs()) { suspend_time_ = base::Time::Now(); // When suspending force an acknowledgement to cancel any pending @@ -572,7 +572,7 @@ } #if defined(OS_WIN) -base::ThreadTicks GpuWatchdogThread::GetWatchedThreadTime() { +base::ThreadTicks GpuWatchdogThreadImplV1::GetWatchedThreadTime() { if (base::ThreadTicks::IsSupported()) { // Convert ThreadTicks::Now() to TimeDelta. return base::ThreadTicks::GetForThread( @@ -610,7 +610,7 @@ #endif #if defined(USE_X11) -int GpuWatchdogThread::GetActiveTTY() const { +int GpuWatchdogThreadImplV1::GetActiveTTY() const { char tty_string[8] = {0}; if (tty_file_ && !fseek(tty_file_, 0, SEEK_SET) && fread(tty_string, 1, 7, tty_file_)) { @@ -623,13 +623,16 @@ } #endif -void GpuWatchdogThread::SetAlternativeTerminateFunctionForTesting( +void GpuWatchdogThreadImplV1::SetAlternativeTerminateFunctionForTesting( base::RepeatingClosure on_terminate) { alternative_terminate_for_testing_ = std::move(on_terminate); } -void GpuWatchdogThread::SetTimeoutForTesting(base::TimeDelta timeout) { +void GpuWatchdogThreadImplV1::SetTimeoutForTesting(base::TimeDelta timeout) { timeout_ = timeout; } +GpuWatchdogThread::GpuWatchdogThread() : base::Thread("GpuWatchdog") {} +GpuWatchdogThread::~GpuWatchdogThread() {} + } // namespace gpu
diff --git a/gpu/ipc/service/gpu_watchdog_thread.h b/gpu/ipc/service/gpu_watchdog_thread.h index 0b0155ce..9b14468 100644 --- a/gpu/ipc/service/gpu_watchdog_thread.h +++ b/gpu/ipc/service/gpu_watchdog_thread.h
@@ -34,20 +34,41 @@ public: ~GpuWatchdogThread() override; - static std::unique_ptr<GpuWatchdogThread> Create(bool start_backgrounded); - // Must be called after a PowerMonitor has been created. Can be called from // any thread. - void AddPowerObserver(); - - // gl::ProgressReporter implementation: - void ReportProgress() override; + virtual void AddPowerObserver() = 0; // Notifies the watchdog when Chrome is backgrounded / foregrounded. Should // only be used if Chrome is completely backgrounded and not expected to // render (all windows backgrounded and not producing frames). - void OnBackgrounded(); - void OnForegrounded(); + virtual void OnBackgrounded() = 0; + virtual void OnForegrounded() = 0; + + protected: + GpuWatchdogThread(); + + // Do not change this name. This is used for [GPU HANG] carsh reports + virtual void DeliberatelyTerminateToRecoverFromHang() = 0; + + private: + DISALLOW_COPY_AND_ASSIGN(GpuWatchdogThread); +}; + +class GPU_IPC_SERVICE_EXPORT GpuWatchdogThreadImplV1 + : public GpuWatchdogThread { + public: + ~GpuWatchdogThreadImplV1() override; + + static std::unique_ptr<GpuWatchdogThreadImplV1> Create( + bool start_backgrounded); + + void AddPowerObserver() override; + + // gl::ProgressReporter implementation: + void ReportProgress() override; + + void OnBackgrounded() override; + void OnForegrounded() override; // Test only functions. Not thread safe - set before arming. void SetAlternativeTerminateFunctionForTesting( @@ -64,7 +85,7 @@ class GpuWatchdogTaskObserver : public base::MessageLoopCurrent::TaskObserver { public: - explicit GpuWatchdogTaskObserver(GpuWatchdogThread* watchdog); + explicit GpuWatchdogTaskObserver(GpuWatchdogThreadImplV1* watchdog); ~GpuWatchdogTaskObserver() override; // Implements MessageLoopCurrent::TaskObserver. @@ -72,7 +93,7 @@ void DidProcessTask(const base::PendingTask& pending_task) override; private: - GpuWatchdogThread* watchdog_; + GpuWatchdogThreadImplV1* watchdog_; }; // A helper class which allows multiple clients to suspend/resume the @@ -81,7 +102,7 @@ // of suspend requests. class SuspensionCounter { public: - SuspensionCounter(GpuWatchdogThread* watchdog_thread); + SuspensionCounter(GpuWatchdogThreadImplV1* watchdog_thread); class SuspensionCounterRef { public: @@ -103,20 +124,19 @@ private: void OnAddRef(); void OnReleaseRef(); - GpuWatchdogThread* watchdog_thread_; + GpuWatchdogThreadImplV1* watchdog_thread_; uint32_t suspend_count_ = 0; SEQUENCE_CHECKER(watchdog_thread_sequence_checker_); }; - - GpuWatchdogThread(); + GpuWatchdogThreadImplV1(); void CheckArmed(); void OnAcknowledge(); void OnCheck(bool after_suspend); void OnCheckTimeout(); - void DeliberatelyTerminateToRecoverFromHang(); + void DeliberatelyTerminateToRecoverFromHang() override; #if defined(USE_X11) void SetupXServer(); void SetupXChangeProp(); @@ -197,9 +217,9 @@ base::RepeatingClosure alternative_terminate_for_testing_; - base::WeakPtrFactory<GpuWatchdogThread> weak_factory_; + base::WeakPtrFactory<GpuWatchdogThreadImplV1> weak_factory_; - DISALLOW_COPY_AND_ASSIGN(GpuWatchdogThread); + DISALLOW_COPY_AND_ASSIGN(GpuWatchdogThreadImplV1); }; } // namespace gpu
diff --git a/gpu/ipc/service/gpu_watchdog_thread_v2.cc b/gpu/ipc/service/gpu_watchdog_thread_v2.cc new file mode 100644 index 0000000..ca85214 --- /dev/null +++ b/gpu/ipc/service/gpu_watchdog_thread_v2.cc
@@ -0,0 +1,94 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "gpu/ipc/service/gpu_watchdog_thread_v2.h" + +#include "base/bind.h" +#include "base/bind_helpers.h" +#include "base/threading/thread_task_runner_handle.h" +#include "build/build_config.h" + +namespace gpu { + +namespace { +#if defined(CYGPROFILE_INSTRUMENTATION) +const int kGpuTimeoutInMs = 30000; +#elif defined(OS_WIN) || defined(OS_MACOSX) +const int kGpuTimeoutInMs = 15000; +#else +const int kGpuTimeoutInMs = 10000; +#endif +} // namespace + +GpuWatchdogThreadImplV2::GpuWatchdogThreadImplV2() + : timeout_(base::TimeDelta::FromMilliseconds(kGpuTimeoutInMs)), + task_observer_(this), + watched_task_runner_(base::ThreadTaskRunnerHandle::Get()), + weak_factory_(this) {} + +GpuWatchdogThreadImplV2::~GpuWatchdogThreadImplV2() { + DCHECK(watched_task_runner_->BelongsToCurrentThread()); + Stop(); +} + +// static +std::unique_ptr<GpuWatchdogThreadImplV2> GpuWatchdogThreadImplV2::Create( + bool start_backgrounded) { + NOTREACHED(); // Not ready yet + + auto watchdog_thread = base::WrapUnique(new GpuWatchdogThreadImplV2); + base::Thread::Options options; + options.timer_slack = base::TIMER_SLACK_MAXIMUM; + watchdog_thread->StartWithOptions(options); + if (start_backgrounded) + watchdog_thread->OnBackgrounded(); + return watchdog_thread; +} + +void GpuWatchdogThreadImplV2::AddPowerObserver() {} + +void GpuWatchdogThreadImplV2::OnBackgrounded() {} + +void GpuWatchdogThreadImplV2::OnForegrounded() {} + +void GpuWatchdogThreadImplV2::ReportProgress() {} + +void GpuWatchdogThreadImplV2::Init() {} + +void GpuWatchdogThreadImplV2::CleanUp() { + weak_factory_.InvalidateWeakPtrs(); +} + +GpuWatchdogThreadImplV2::GpuWatchdogTaskObserver::GpuWatchdogTaskObserver( + GpuWatchdogThreadImplV2* watchdog) + : watchdog_(watchdog) {} + +GpuWatchdogThreadImplV2::GpuWatchdogTaskObserver::~GpuWatchdogTaskObserver() = + default; + +void GpuWatchdogThreadImplV2::GpuWatchdogTaskObserver::WillProcessTask( + const base::PendingTask& pending_task) {} + +void GpuWatchdogThreadImplV2::GpuWatchdogTaskObserver::DidProcessTask( + const base::PendingTask& pending_task) { + watchdog_->Disarm(); +} + +void GpuWatchdogThreadImplV2::Arm() {} + +void GpuWatchdogThreadImplV2::Disarm() {} + +void GpuWatchdogThreadImplV2::OnSuspend() {} + +void GpuWatchdogThreadImplV2::OnResume() {} + +void GpuWatchdogThreadImplV2::DeliberatelyTerminateToRecoverFromHang() { + // Store variables so they're available in crash dumps to help determine the + // cause of any hang. + + // Deliberately crash the process to create a crash dump. + *((volatile int*)0) = 0xdeadface; +} + +} // namespace gpu
diff --git a/gpu/ipc/service/gpu_watchdog_thread_v2.h b/gpu/ipc/service/gpu_watchdog_thread_v2.h new file mode 100644 index 0000000..64075f9 --- /dev/null +++ b/gpu/ipc/service/gpu_watchdog_thread_v2.h
@@ -0,0 +1,71 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef GPU_IPC_SERVICE_GPU_WATCHDOG_THREAD_V2_H_ +#define GPU_IPC_SERVICE_GPU_WATCHDOG_THREAD_V2_H_ + +#include "gpu/ipc/service/gpu_watchdog_thread.h" + +namespace gpu { + +class GPU_IPC_SERVICE_EXPORT GpuWatchdogThreadImplV2 + : public GpuWatchdogThread { + public: + static std::unique_ptr<GpuWatchdogThreadImplV2> Create( + bool start_backgrounded); + ~GpuWatchdogThreadImplV2() override; + + // Implements GpuWatchdogThread + void AddPowerObserver() override; + void OnBackgrounded() override; + void OnForegrounded() override; + + // Implements gl::ProgressReporter + void ReportProgress() override; + + protected: + // Implements base::Thread + void Init() override; + void CleanUp() override; + + private: + // An object of this type intercepts the reception and completion of all tasks + // on the watched thread and checks whether the watchdog is armed. + class GpuWatchdogTaskObserver + : public base::MessageLoopCurrent::TaskObserver { + public: + explicit GpuWatchdogTaskObserver(GpuWatchdogThreadImplV2* watchdog); + ~GpuWatchdogTaskObserver() override; + + // Implements MessageLoopCurrent::TaskObserver. + void WillProcessTask(const base::PendingTask& pending_task) override; + void DidProcessTask(const base::PendingTask& pending_task) override; + + private: + GpuWatchdogThreadImplV2* watchdog_; + }; + + GpuWatchdogThreadImplV2(); + void Arm(); + void Disarm(); + + // Implements base::PowerObserver + void OnSuspend() override; + void OnResume() override; + + // Implements GpuWatchdogThread + void DeliberatelyTerminateToRecoverFromHang() override; + + base::TimeDelta timeout_; + GpuWatchdogTaskObserver task_observer_; + scoped_refptr<base::SingleThreadTaskRunner> watched_task_runner_; + + base::WeakPtrFactory<GpuWatchdogThreadImplV2> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(GpuWatchdogThreadImplV2); +}; + +} // namespace gpu + +#endif // GPU_IPC_SERVICE_GPU_WATCHDOG_THREAD_V2_H_
diff --git a/infra/config/cr-buildbucket.cfg b/infra/config/cr-buildbucket.cfg index 130c4a14..25216a81 100644 --- a/infra/config/cr-buildbucket.cfg +++ b/infra/config/cr-buildbucket.cfg
@@ -337,6 +337,7 @@ builder_mixins { name: "android-gpu-ci" dimensions: "os:Ubuntu-14.04" + mixins: "builderless" recipe { properties: "mastername:chromium.gpu" } @@ -345,6 +346,7 @@ builder_mixins { name: "android-gpu-fyi-ci" dimensions: "os:Ubuntu-14.04" + mixins: "builderless" mixins: "gpu-fyi-ci" mixins: "gpu-slow-bot" } @@ -961,7 +963,6 @@ builders { name: "Android FYI 32 dEQP Vk Release (Pixel 2)" mixins: "android-gpu-fyi-ci" - mixins: "builderless" mixins: "goma-rbe-prod" } @@ -974,7 +975,6 @@ builders { name: "Android FYI 32 Vk Release (Pixel 2)" mixins: "android-gpu-fyi-ci" - mixins: "builderless" mixins: "goma-rbe-prod" } @@ -987,7 +987,6 @@ builders { name: "Android FYI 64 dEQP Vk Release (Pixel 2)" mixins: "android-gpu-fyi-ci" - mixins: "builderless" mixins: "goma-rbe-prod" } @@ -1000,7 +999,6 @@ builders { name: "Android FYI 64 Vk Release (Pixel 2)" mixins: "android-gpu-fyi-ci" - mixins: "builderless" mixins: "goma-rbe-prod" } @@ -1055,7 +1053,6 @@ builders { name: "Android FYI Release (Pixel 2)" mixins: "android-gpu-fyi-ci" - mixins: "builderless" mixins: "goma-rbe-prod" } @@ -1596,6 +1593,7 @@ builders { name: "linux-fieldtrial-rel" mixins: "builderless" + mixins: "fyi-ci" mixins: "linux-xenial" }
diff --git a/infra/config/luci-scheduler.cfg b/infra/config/luci-scheduler.cfg index 09fe2090..52883b23 100644 --- a/infra/config/luci-scheduler.cfg +++ b/infra/config/luci-scheduler.cfg
@@ -324,7 +324,6 @@ triggers: "chromeos-arm-generic-rel" triggers: "chromeos-kevin-rel" triggers: "chromeos-kevin-rel-hw-tests" - triggers: "chromeos-vm-code-coverage" triggers: "fuchsia-fyi-arm64-rel" triggers: "fuchsia-fyi-arm64-rel (Goma RBE FYI)" triggers: "fuchsia-fyi-x64-dbg" @@ -349,7 +348,6 @@ triggers: "linux-blink-animation-use-time-delta" triggers: "linux-blink-heap-concurrent-marking-tsan-rel" triggers: "linux-blink-heap-verification" - triggers: "linux-chromeos-code-coverage" triggers: "linux-chromeos-dbg" triggers: "linux-chromeos-oobe-code-coverage" triggers: "linux-chromeos-rel"
diff --git a/ios/chrome/browser/send_tab_to_self/BUILD.gn b/ios/chrome/browser/send_tab_to_self/BUILD.gn index 81cf622..25d9dd0 100644 --- a/ios/chrome/browser/send_tab_to_self/BUILD.gn +++ b/ios/chrome/browser/send_tab_to_self/BUILD.gn
@@ -52,8 +52,11 @@ "//base", "//base/test:test_support", "//components/send_tab_to_self", + "//components/send_tab_to_self:test_support", "//components/sync", "//ios/chrome/browser/browser_state:test_support", + "//ios/chrome/browser/sync", + "//ios/chrome/browser/sync:test_support", "//testing/gtest", "//third_party/ocmock", "//url",
diff --git a/ios/chrome/browser/send_tab_to_self/send_tab_to_self_util.h b/ios/chrome/browser/send_tab_to_self/send_tab_to_self_util.h index c029019..63c5637 100644 --- a/ios/chrome/browser/send_tab_to_self/send_tab_to_self_util.h +++ b/ios/chrome/browser/send_tab_to_self/send_tab_to_self_util.h
@@ -25,8 +25,8 @@ // Returns true if the SendTabToSelf sync datatype is active. bool IsUserSyncTypeActive(ios::ChromeBrowserState* browser_state); -// Returns true if the user syncing on two or more devices. -bool IsSyncingOnMultipleDevices(ios::ChromeBrowserState* browser_state); +// Returns true if there is valid device. +bool HasValidTargetDevice(ios::ChromeBrowserState* browser_state); // Returns true if the tab and web content requirements are met: // User is viewing an HTTP or HTTPS page.
diff --git a/ios/chrome/browser/send_tab_to_self/send_tab_to_self_util.mm b/ios/chrome/browser/send_tab_to_self/send_tab_to_self_util.mm index 311788e..96f3d9f54 100644 --- a/ios/chrome/browser/send_tab_to_self/send_tab_to_self_util.mm +++ b/ios/chrome/browser/send_tab_to_self/send_tab_to_self_util.mm
@@ -54,11 +54,11 @@ service->GetSendTabToSelfModel()->IsReady(); } -bool IsSyncingOnMultipleDevices(ios::ChromeBrowserState* browser_state) { - syncer::DeviceInfoSyncService* device_sync_service = - DeviceInfoSyncServiceFactory::GetForBrowserState(browser_state); - return device_sync_service && device_sync_service->GetDeviceInfoTracker() && - device_sync_service->GetDeviceInfoTracker()->CountActiveDevices() > 1; +bool HasValidTargetDevice(ios::ChromeBrowserState* browser_state) { + SendTabToSelfSyncService* service = + SendTabToSelfSyncServiceFactory::GetForBrowserState(browser_state); + return service && service->GetSendTabToSelfModel() && + service->GetSendTabToSelfModel()->HasValidTargetDevice(); } bool IsContentRequirementsMet(const GURL& url, @@ -73,7 +73,7 @@ const GURL& url) { // If sending is enabled, then so is receiving. return IsSendingEnabled() && IsUserSyncTypeActive(browser_state) && - IsSyncingOnMultipleDevices(browser_state) && + HasValidTargetDevice(browser_state) && IsContentRequirementsMet(url, browser_state); }
diff --git a/ios/chrome/browser/send_tab_to_self/send_tab_to_self_util_unittest.mm b/ios/chrome/browser/send_tab_to_self/send_tab_to_self_util_unittest.mm index f1ce137..54182dc9 100644 --- a/ios/chrome/browser/send_tab_to_self/send_tab_to_self_util_unittest.mm +++ b/ios/chrome/browser/send_tab_to_self/send_tab_to_self_util_unittest.mm
@@ -7,8 +7,11 @@ #include "base/test/scoped_feature_list.h" #include "base/test/scoped_task_environment.h" #include "components/send_tab_to_self/features.h" +#include "components/send_tab_to_self/send_tab_to_self_sync_service.h" +#include "components/send_tab_to_self/test_send_tab_to_self_model.h" #include "components/sync/driver/sync_driver_switches.h" #include "ios/chrome/browser/browser_state/test_chrome_browser_state.h" +#include "ios/chrome/browser/sync/send_tab_to_self_sync_service_factory.h" #import "testing/gtest_mac.h" #include "testing/platform_test.h" @@ -18,6 +21,36 @@ namespace send_tab_to_self { +// TODO (crbug/974040): update TestSendTabToSelfModel and delete this class +class SendTabToSelfModelMock : public TestSendTabToSelfModel { + public: + SendTabToSelfModelMock() = default; + ~SendTabToSelfModelMock() override = default; + + bool IsReady() override { return true; } + bool HasValidTargetDevice() override { return true; } +}; + +// TODO (crbug/974040): Move TestSendTabToSelfSyncService to components and +// reuse in both ios/chrome and chrome tests +class TestSendTabToSelfSyncService : public SendTabToSelfSyncService { + public: + TestSendTabToSelfSyncService() = default; + ~TestSendTabToSelfSyncService() override = default; + + SendTabToSelfModel* GetSendTabToSelfModel() override { + return &send_tab_to_self_model_mock_; + } + + protected: + SendTabToSelfModelMock send_tab_to_self_model_mock_; +}; + +std::unique_ptr<KeyedService> BuildTestSendTabToSelfSyncService( + web::BrowserState* context) { + return std::make_unique<TestSendTabToSelfSyncService>(); +} + class SendTabToSelfUtilTest : public PlatformTest { public: SendTabToSelfUtilTest() { @@ -39,6 +72,15 @@ std::unique_ptr<ios::ChromeBrowserState> browser_state_; }; +TEST_F(SendTabToSelfUtilTest, HasValidTargetDevice) { + EXPECT_FALSE(HasValidTargetDevice(browser_state())); + + SendTabToSelfSyncServiceFactory::GetInstance()->SetTestingFactory( + browser_state(), base::BindRepeating(&BuildTestSendTabToSelfSyncService)); + + EXPECT_TRUE(HasValidTargetDevice(browser_state())); +} + TEST_F(SendTabToSelfUtilTest, AreFlagsEnabled) { scoped_task_environment_.RunUntilIdle(); scoped_feature_list_.InitWithFeatures(
diff --git a/ios/chrome/browser/ui/location_bar/location_bar_steady_view.h b/ios/chrome/browser/ui/location_bar/location_bar_steady_view.h index 472236f..d433ced 100644 --- a/ios/chrome/browser/ui/location_bar/location_bar_steady_view.h +++ b/ios/chrome/browser/ui/location_bar/location_bar_steady_view.h
@@ -39,11 +39,17 @@ // Sets the location label's text. - (void)setLocationLabelText:(NSString*)string; +// Displays the location InfobarBadgeButton if |display| is YES, hides it if +// |display| is NO. Will animate change if |animated| is YES. +- (void)displayBadge:(BOOL)display animated:(BOOL)animated; + // The tappable button representing the location bar. @property(nonatomic, strong) UIButton* locationButton; // The label displaying the current location URL. @property(nonatomic, strong) UILabel* locationLabel; // The InfobarBadgeButton displayed in the leading corner of the view. +// Call displayBadge:animated: in this class instead of InfobarBadgeButton's +// directly. // TODO(crbug.com/935804): This button is currently only being used in the // Infobar redesign. @property(nonatomic, strong) InfobarBadgeButton* leadingButton;
diff --git a/ios/chrome/browser/ui/location_bar/location_bar_steady_view.mm b/ios/chrome/browser/ui/location_bar/location_bar_steady_view.mm index 28bde429..12958963 100644 --- a/ios/chrome/browser/ui/location_bar/location_bar_steady_view.mm +++ b/ios/chrome/browser/ui/location_bar/location_bar_steady_view.mm
@@ -261,9 +261,6 @@ l10n_util::GetNSString(IDS_ACCNAME_LOCATION); _accessibleElements = [[NSMutableArray alloc] init]; - if (IsInfobarUIRebootEnabled()) { - [_accessibleElements addObject:_leadingButton]; - } [_accessibleElements addObject:_locationButton]; [_accessibleElements addObject:_trailingButton]; @@ -321,6 +318,19 @@ [self updateAccessibility]; } +- (void)displayBadge:(BOOL)display animated:(BOOL)animated { + if (display) { + // Adding InfobarBadge button as an accessibility element behind location + // label. Thus, there should be at least one object alreading in + // |accessibleElements|. + DCHECK([self.accessibleElements count] > 0); + [self.accessibleElements insertObject:self.leadingButton atIndex:1]; + } else { + [self.accessibleElements removeObject:self.leadingButton]; + } + [self.leadingButton displayBadge:display animated:animated]; +} + #pragma mark - UIResponder // This is needed for UIMenu
diff --git a/ios/chrome/browser/ui/location_bar/location_bar_view_controller.mm b/ios/chrome/browser/ui/location_bar/location_bar_view_controller.mm index 11570d0..3428cc38 100644 --- a/ios/chrome/browser/ui/location_bar/location_bar_view_controller.mm +++ b/ios/chrome/browser/ui/location_bar/location_bar_view_controller.mm
@@ -266,7 +266,7 @@ metricsRecorder:(InfobarMetricsRecorder*)metricsRecorder { self.infobarMetricsRecorder = metricsRecorder; self.shouldShowLeadingButton = display; - [self.locationBarSteadyView.leadingButton displayBadge:display animated:YES]; + [self.locationBarSteadyView displayBadge:display animated:YES]; } #pragma mark - LocationBarAnimatee @@ -300,13 +300,12 @@ } - (void)hideSteadyViewLeadingButton { - [self.locationBarSteadyView.leadingButton displayBadge:NO animated:NO]; + [self.locationBarSteadyView displayBadge:NO animated:NO]; } - (void)showSteadyViewLeadingButtonIfNeeded { - [self.locationBarSteadyView.leadingButton - displayBadge:self.shouldShowLeadingButton - animated:NO]; + [self.locationBarSteadyView displayBadge:self.shouldShowLeadingButton + animated:NO]; } - (void)setEditViewFaded:(BOOL)hidden {
diff --git a/ios/web/shell/test/BUILD.gn b/ios/web/shell/test/BUILD.gn index 64f2a70..18567be 100644 --- a/ios/web/shell/test/BUILD.gn +++ b/ios/web/shell/test/BUILD.gn
@@ -173,6 +173,7 @@ deps = [ "//base", "//base/test:test_support", + "//ios/testing:http_server_bundle_data", "//ios/testing:nserror_support", "//ios/testing/earl_grey:eg_test_support+eg2", "//ios/third_party/earl_grey2:test_lib", @@ -231,6 +232,4 @@ # Test support libraries. ":eg_tests+eg2", ] - - bundle_deps = [ "//ios/testing:http_server_bundle_data" ] }
diff --git a/ios/web/shell/test/context_menu_egtest.mm b/ios/web/shell/test/context_menu_egtest.mm index 3f69c568..8d4811d 100644 --- a/ios/web/shell/test/context_menu_egtest.mm +++ b/ios/web/shell/test/context_menu_egtest.mm
@@ -7,6 +7,7 @@ #import <XCTest/XCTest.h> #import "base/ios/block_types.h" +#include "base/strings/sys_string_conversions.h" #import "ios/testing/earl_grey/earl_grey_test.h" #import "ios/testing/earl_grey/matchers.h" #include "ios/web/public/test/element_selector.h" @@ -40,7 +41,9 @@ - (void)setUp { [super setUp]; - _server.ServeFilesFromSourceDirectory(base::FilePath(FILE_PATH_LITERAL("."))); + NSString* bundlePath = [NSBundle bundleForClass:[self class]].resourcePath; + _server.ServeFilesFromDirectory( + base::FilePath(base::SysNSStringToUTF8(bundlePath))); GREYAssert(_server.Start(), @"EmbeddedTestServer failed to start."); }
diff --git a/ios/web/shell/test/page_state_egtest.mm b/ios/web/shell/test/page_state_egtest.mm index ac860c9..001725a 100644 --- a/ios/web/shell/test/page_state_egtest.mm +++ b/ios/web/shell/test/page_state_egtest.mm
@@ -7,6 +7,7 @@ #import <XCTest/XCTest.h> #include "base/strings/string_number_conversions.h" +#include "base/strings/sys_string_conversions.h" #import "ios/testing/earl_grey/earl_grey_test.h" #import "ios/web/shell/test/earl_grey/shell_earl_grey.h" #import "ios/web/shell/test/earl_grey/shell_matchers.h" @@ -74,7 +75,9 @@ - (void)setUp { [super setUp]; - _server.ServeFilesFromSourceDirectory(base::FilePath(FILE_PATH_LITERAL("."))); + NSString* bundlePath = [NSBundle bundleForClass:[self class]].resourcePath; + _server.ServeFilesFromDirectory( + base::FilePath(base::SysNSStringToUTF8(bundlePath))); GREYAssert(_server.Start(), @"EmbeddedTestServer failed to start."); }
diff --git a/media/audio/fuchsia/audio_output_stream_fuchsia.cc b/media/audio/fuchsia/audio_output_stream_fuchsia.cc index a497b7b..88c64942 100644 --- a/media/audio/fuchsia/audio_output_stream_fuchsia.cc +++ b/media/audio/fuchsia/audio_output_stream_fuchsia.cc
@@ -76,9 +76,11 @@ void AudioOutputStreamFuchsia::Stop() { callback_ = nullptr; - reference_time_ = base::TimeTicks(); - audio_renderer_->PauseNoReply(); - audio_renderer_->DiscardAllPacketsNoReply(); + if (!reference_time_.is_null()) { + reference_time_ = base::TimeTicks(); + audio_renderer_->PauseNoReply(); + audio_renderer_->DiscardAllPacketsNoReply(); + } timer_.Stop(); }
diff --git a/media/filters/fuchsia/fuchsia_video_decoder.cc b/media/filters/fuchsia/fuchsia_video_decoder.cc index 17416179a..f8a44f6c 100644 --- a/media/filters/fuchsia/fuchsia_video_decoder.cc +++ b/media/filters/fuchsia/fuchsia_video_decoder.cc
@@ -56,7 +56,7 @@ zx::vmo CreateVmo(size_t size) { zx::vmo vmo; - zx_status_t status = zx::vmo::create(size, ZX_VMO_NON_RESIZABLE, &vmo); + zx_status_t status = zx::vmo::create(size, 0, &vmo); if (status != ZX_OK) { ZX_DLOG(ERROR, status) << "zx_vmo_create"; return zx::vmo();
diff --git a/media/gpu/windows/dxva_video_decode_accelerator_win.cc b/media/gpu/windows/dxva_video_decode_accelerator_win.cc index 0be64d5..93d7452 100644 --- a/media/gpu/windows/dxva_video_decode_accelerator_win.cc +++ b/media/gpu/windows/dxva_video_decode_accelerator_win.cc
@@ -1446,13 +1446,17 @@ {gfx::Size(4096, 2160), gfx::Size(4096, 2304), gfx::Size(7680, 4320), gfx::Size(8192, 4320), gfx::Size(8192, 8192)}); - max_vp9_profile2_resolutions = GetMaxResolutionsForGUIDs( - max_vp9_profile2_resolutions.first, video_device.Get(), - {D3D11_DECODER_PROFILE_VP9_VLD_10BIT_PROFILE2}, - {gfx::Size(4096, 2160), gfx::Size(4096, 2304), - gfx::Size(7680, 4320), gfx::Size(8192, 4320), - gfx::Size(8192, 8192)}, - DXGI_FORMAT_P010); + + // RS3 has issues with VP9.2 decoding. See https://crbug.com/937108. + if (base::win::GetVersion() != base::win::Version::WIN10_RS3) { + max_vp9_profile2_resolutions = GetMaxResolutionsForGUIDs( + max_vp9_profile2_resolutions.first, video_device.Get(), + {D3D11_DECODER_PROFILE_VP9_VLD_10BIT_PROFILE2}, + {gfx::Size(4096, 2160), gfx::Size(4096, 2304), + gfx::Size(7680, 4320), gfx::Size(8192, 4320), + gfx::Size(8192, 8192)}, + DXGI_FORMAT_P010); + } } } }
diff --git a/media/mojo/interfaces/cdm_storage.mojom b/media/mojo/interfaces/cdm_storage.mojom index f07ebb7..6277c560 100644 --- a/media/mojo/interfaces/cdm_storage.mojom +++ b/media/mojo/interfaces/cdm_storage.mojom
@@ -15,42 +15,38 @@ kFailure // Unable to open file. }; - // Opens the file specified by |file_name| for read only. Writing to the file - // is done using a temporary file created with the CdmFile interface returned. - // Can be called multiple times for different files, or for the same file if - // the first one has been closed. If successful, kSuccess will be returned, - // |file_for_reading| can be used to read the contents, and |cdm_file| should - // be closed when access to the file is no longer needed (i.e. file closed). - // On failure, |status| <> kSuccess and |file_for_reading| and |cdm_file| - // are null. + // Opens the file specified by |file_name|. Can be called multiple times for + // different files, or for the same file if the first one has been closed. + // If successful, kSuccess will be returned, and |cdm_file| should be used to + // access the file. |cdm_file| should be closed when access to the file is no + // longer needed. On failure, |status| <> kSuccess and |cdm_file| is null. // - If the file is already opened, kInUse will be returned in |status|. // - |file_name| must not contain forward slash ('/') or backslash ('\'), // and must not start with an underscore ('_'). If this happens, // |status| == kFailure is returned. Open(string file_name) - => (Status status, - mojo_base.mojom.File? file_for_reading, - associated CdmFile? cdm_file); + => (Status status, associated CdmFile? cdm_file); }; -// Provides a way to keep track of the file opened. When the connection to this -// object is broken, it is assumed that the file has been closed and that no -// more operations will be performed on it. -// -// This interface is also used to be able to write to the file. Due to sandbox -// restrictions on some platforms (crbug.com/774762), setting the length of the -// file explicitly is not allowed in sandboxed processes. To get around this -// (and avoid file corruption issues), writing is done by opening a new file, -// letting the client write to it, and then replace the original file after -// writing. +// Provides a way to access the contents of the file opened. When the connection +// to this object is broken, it is assumed that the file has been closed and +// that no more operations will be performed on it. interface CdmFile { - // Open a new file that can be written to. This file will be in the same - // directory as the original file. If successful, returns |file_for_writing| - // which can be written to. - OpenFileForWriting() => (mojo_base.mojom.File? file_for_writing); + enum Status { + kSuccess, // Operation succeeded. + kFailure // Operation failed. + }; - // Closes the file opened for writing and replaces the original file. - // Returns a new file descriptor that should be used to read the original - // file from now on. - CommitWrite() => (mojo_base.mojom.File? updated_file_for_reading); -}; + // Reads the contents of the file and return them in |data|. Returns + // kSuccess and the file contents if successful. Errors reading the file will + // return kFailure. If the opened file does not exist, Read() will return + // kSuccess and |data| will be the empty array. + Read() => (Status status, array<uint8> data); + + // Updates the contents of the existing file with |data|. If the + // write operation is successful, then kSuccess is returned, otherwise + // kFailure is returned. If |data| is empty, then the file is deleted to + // save space. The contents of the file are unknown if Write() + // fails. + Write(array<uint8> data) => (Status status); +}; \ No newline at end of file
diff --git a/media/mojo/services/mojo_cdm_file_io.cc b/media/mojo/services/mojo_cdm_file_io.cc index d5df660..1112525 100644 --- a/media/mojo/services/mojo_cdm_file_io.cc +++ b/media/mojo/services/mojo_cdm_file_io.cc
@@ -5,13 +5,10 @@ #include "media/mojo/services/mojo_cdm_file_io.h" #include <utility> -#include <vector> #include "base/bind.h" #include "base/callback.h" -#include "base/metrics/histogram_macros.h" #include "base/task/post_task.h" -#include "base/time/time.h" #include "base/trace_event/trace_event.h" #include "mojo/public/cpp/bindings/callback_helpers.h" @@ -20,30 +17,28 @@ namespace { using ClientStatus = cdm::FileIOClient::Status; +using FileStatus = media::mojom::CdmFile::Status; using StorageStatus = media::mojom::CdmStorage::Status; -// File size limit is 32MB. Licenses saved by the CDM are typically several -// hundreds of bytes. -const int64_t kMaxFileSizeBytes = 32 * 1024 * 1024; +// File size limit is 512KB. Licenses saved by the CDM are typically several +// hundreds of bytes. This value should match what is in CdmFileImpl. +const int64_t kMaxFileSizeBytes = 512 * 1024; -// Maximum length of a file name. -const size_t kFileNameMaxLength = 256; - -// File names must only contain letters (A-Za-z), digits(0-9), or "._-", -// and not start with "_". It must contain at least 1 character, and not -// more then |kFileNameMaxLength| characters. -bool IsValidFileName(const std::string& name) { - if (name.empty() || name.length() > kFileNameMaxLength || name[0] == '_') - return false; - - for (auto ch : name) { - if (!base::IsAsciiAlpha(ch) && !base::IsAsciiDigit(ch) && ch != '.' && - ch != '_' && ch != '-') { - return false; - } +const char* ConvertStorageStatus(StorageStatus status) { + switch (status) { + case StorageStatus::kSuccess: + return "kSuccess"; + case StorageStatus::kInUse: + return "kInUse"; + case StorageStatus::kFailure: + return "kFailure"; } - return true; + return "unknown"; +} + +const char* ConvertFileStatus(FileStatus status) { + return status == FileStatus::kSuccess ? "kSuccess" : "kFailure"; } } // namespace @@ -69,8 +64,6 @@ std::string file_name_string(file_name, file_name_size); DVLOG(3) << __func__ << " file: " << file_name_string; - TRACE_EVENT1("media", "MojoCdmFileIO::Open", "file_name", file_name_string); - // Open is only allowed if the current state is kUnopened and the file name // is valid. if (state_ != State::kUnopened) { @@ -78,42 +71,39 @@ return; } - if (!IsValidFileName(file_name_string)) { - OnError(ErrorType::kOpenError); - return; - } - state_ = State::kOpening; file_name_ = file_name_string; + TRACE_EVENT_ASYNC_BEGIN1("media", "MojoCdmFileIO::Open", this, "file_name", + file_name_); + + // Wrap the callback to detect the case when the mojo connection is + // terminated prior to receiving the response. This avoids problems if the + // service is destroyed before the CDM. If that happens let the CDM know that + // Open() failed. auto callback = mojo::WrapCallbackWithDefaultInvokeIfNotRun( base::BindOnce(&MojoCdmFileIO::OnFileOpened, weak_factory_.GetWeakPtr()), - StorageStatus::kFailure, base::File(), nullptr); + StorageStatus::kFailure, nullptr); cdm_storage_->Open(file_name_string, std::move(callback)); } void MojoCdmFileIO::OnFileOpened(StorageStatus status, - base::File file, mojom::CdmFileAssociatedPtrInfo cdm_file) { DVLOG(3) << __func__ << " file: " << file_name_ << ", status: " << status; - TRACE_EVENT2("media", "MojoCdmFileIO::FileOpened", "file_name", file_name_, - "status", static_cast<int32_t>(status)); - + // This logs the end of the async Open() request, and separately logs + // how long the client takes in OnOpenComplete(). + TRACE_EVENT_ASYNC_END1("media", "MojoCdmFileIO::Open", this, "status", + ConvertStorageStatus(status)); switch (status) { case StorageStatus::kSuccess: - if (!file.IsValid()) { - NOTREACHED() << "File received is invalid."; - state_ = State::kError; - OnError(ErrorType::kOpenError); - return; - } - // File was successfully opened. state_ = State::kOpened; - file_for_reading_ = std::move(file); cdm_file_.Bind(std::move(cdm_file)); - client_->OnOpenComplete(ClientStatus::kSuccess); + { + TRACE_EVENT0("media", "FileIOClient::OnOpenComplete"); + client_->OnOpenComplete(ClientStatus::kSuccess); + } return; case StorageStatus::kInUse: // File already open by somebody else. @@ -133,8 +123,6 @@ void MojoCdmFileIO::Read() { DVLOG(3) << __func__ << " file: " << file_name_; - TRACE_EVENT1("media", "MojoCdmFileIO::Read", "file_name", file_name_); - // If another operation is in progress, fail. if (state_ == State::kReading || state_ == State::kWriting) { OnError(ErrorType::kReadInUse); @@ -147,83 +135,50 @@ return; } - // Determine the size of the file (so we know how many bytes to read). - int64_t num_bytes = file_for_reading_.GetLength(); - if (num_bytes < 0) { - // Negative bytes mean failure, so fail. This error is not recoverable, - // so don't allow any more operations other than close on the file. - state_ = State::kError; - OnError(ErrorType::kReadError); - return; - } + TRACE_EVENT_ASYNC_BEGIN1("media", "MojoCdmFileIO::Read", this, "file_name", + file_name_); - // Files are limited to 32MB, so fail if file too big. Setting |state_| - // back to Opened so that the CDM could write something valid to this file. - if (num_bytes > kMaxFileSizeBytes) { - DLOG(WARNING) << __func__ - << " Too much data to read. #bytes = " << num_bytes; - OnError(ErrorType::kReadError); - return; - } - - // Do the actual read asynchronously so that we don't need to copy the - // data when calling |client_|. state_ = State::kReading; - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(&MojoCdmFileIO::DoRead, - weak_factory_.GetWeakPtr(), num_bytes)); + + // Wrap the callback to detect the case when the mojo connection is + // terminated prior to receiving the response. This avoids problems if the + // service is destroyed before the CDM. If that happens let the CDM know that + // Read() failed. + auto callback = mojo::WrapCallbackWithDefaultInvokeIfNotRun( + base::BindOnce(&MojoCdmFileIO::OnFileRead, weak_factory_.GetWeakPtr()), + FileStatus::kFailure, std::vector<uint8_t>()); + cdm_file_->Read(std::move(callback)); } -void MojoCdmFileIO::DoRead(int64_t num_bytes) { +void MojoCdmFileIO::OnFileRead(FileStatus status, + const std::vector<uint8_t>& data) { DVLOG(3) << __func__ << " file: " << file_name_; DCHECK_EQ(State::kReading, state_); - TRACE_EVENT2("media", "MojoCdmFileIO::DoRead", "file_name", file_name_, - "bytes_to_read", num_bytes); + // This logs the end of the async Read() request, and separately logs + // how long the client takes in OnReadComplete(). + TRACE_EVENT_ASYNC_END2("media", "MojoCdmFileIO::Read", this, "bytes_read", + data.size(), "status", ConvertFileStatus(status)); - // We know how much data is available, so read the complete contents of the - // file into a buffer and passing it back to |client_|. As these should be - // small files, we don't worry about breaking it up into chunks to read it. - - // Read the contents of the file. Read() sizes (provided and returned) are - // type int, so cast appropriately. - int bytes_to_read = base::checked_cast<int>(num_bytes); - std::vector<uint8_t> buffer(bytes_to_read); - - // If the file has 0 bytes, no need to read anything. - if (bytes_to_read != 0) { - TRACE_EVENT0("media", "MojoCdmFileIO::ActualRead"); - base::TimeTicks start = base::TimeTicks::Now(); - int bytes_read = file_for_reading_.Read( - 0, reinterpret_cast<char*>(buffer.data()), bytes_to_read); - base::TimeDelta read_time = base::TimeTicks::Now() - start; - if (bytes_to_read != bytes_read) { - // Unable to read the contents of the file. Setting |state_| to kOpened - // so that the CDM can write something valid to this file. - DVLOG(1) << "Failed to read file " << file_name_ << ". Requested " - << bytes_to_read << " bytes, got " << bytes_read; - state_ = State::kOpened; - OnError(ErrorType::kReadError); - return; - } - - // Only report reading time for successful reads. - UMA_HISTOGRAM_TIMES("Media.EME.CdmFileIO.ReadTime", read_time); + if (status != FileStatus::kSuccess) { + DVLOG(1) << "Failed to read file " << file_name_; + state_ = State::kOpened; + OnError(ErrorType::kReadError); + return; } // Call this before OnReadComplete() so that we always have the latest file // size before CDM fires errors. - delegate_->ReportFileReadSize(bytes_to_read); + delegate_->ReportFileReadSize(data.size()); state_ = State::kOpened; - client_->OnReadComplete(ClientStatus::kSuccess, buffer.data(), buffer.size()); + TRACE_EVENT0("media", "FileIOClient::OnReadComplete"); + client_->OnReadComplete(ClientStatus::kSuccess, data.data(), data.size()); } void MojoCdmFileIO::Write(const uint8_t* data, uint32_t data_size) { DVLOG(3) << __func__ << " file: " << file_name_ << ", bytes: " << data_size; - TRACE_EVENT1("media", "MojoCdmFileIO::Write", "file_name", file_name_); - // If another operation is in progress, fail. if (state_ == State::kReading || state_ == State::kWriting) { OnError(ErrorType::kWriteInUse); @@ -236,7 +191,7 @@ return; } - // Files are limited to 32MB, so fail if file too big. + // Files are limited in size, so fail if file too big. if (data_size > kMaxFileSizeBytes) { DLOG(WARNING) << __func__ << " Too much data to write. #bytes = " << data_size; @@ -244,76 +199,40 @@ return; } - // Now open a temporary file for writing. Close |file_for_reading_| as it - // won't be used again. + TRACE_EVENT_ASYNC_BEGIN2("media", "MojoCdmFileIO::Write", this, "file_name", + file_name_, "bytes_to_write", data_size); + state_ = State::kWriting; - file_for_reading_.Close(); - cdm_file_->OpenFileForWriting( - base::BindOnce(&MojoCdmFileIO::DoWrite, weak_factory_.GetWeakPtr(), - std::vector<uint8_t>(data, data + data_size))); + + // Wrap the callback to detect the case when the mojo connection is + // terminated prior to receiving the response. This avoids problems if the + // service is destroyed before the CDM. If that happens let the CDM know that + // Write() failed. + auto callback = mojo::WrapCallbackWithDefaultInvokeIfNotRun( + base::BindOnce(&MojoCdmFileIO::OnFileWritten, weak_factory_.GetWeakPtr()), + FileStatus::kFailure); + cdm_file_->Write(std::vector<uint8_t>(data, data + data_size), + std::move(callback)); } -void MojoCdmFileIO::DoWrite(const std::vector<uint8_t>& data, - base::File temporary_file) { - DVLOG(3) << __func__ << " file: " << file_name_ << ", result: " - << base::File::ErrorToString(temporary_file.error_details()); - DCHECK_EQ(State::kWriting, state_); - - TRACE_EVENT2("media", "MojoCdmFileIO::DoWrite", "file_name", file_name_, - "bytes_to_write", data.size()); - - if (!temporary_file.IsValid()) { - // Failed to open temporary file. - state_ = State::kError; - OnError(ErrorType::kWriteError); - return; - } - - // As the temporary file should have been newly created, it should be empty. - // No need to call write() if there is no data. - CHECK_EQ(0u, temporary_file.GetLength()) << "Temporary file is not empty."; - int bytes_to_write = base::checked_cast<int>(data.size()); - if (bytes_to_write > 0) { - TRACE_EVENT0("media", "MojoCdmFileIO::ActualWrite"); - base::TimeTicks start = base::TimeTicks::Now(); - int bytes_written = temporary_file.Write( - 0, reinterpret_cast<const char*>(data.data()), bytes_to_write); - base::TimeDelta write_time = base::TimeTicks::Now() - start; - if (bytes_written != bytes_to_write) { - // Failed to write to the temporary file. - state_ = State::kError; - OnError(ErrorType::kWriteError); - return; - } - - // Only report writing time for successful writes. - UMA_HISTOGRAM_TIMES("Media.EME.CdmFileIO.WriteTime", write_time); - } - - // Close the temporary file returned before renaming. Original file was - // closed previously. - temporary_file.Close(); - DCHECK(!file_for_reading_.IsValid()) << "Original file was not closed."; - cdm_file_->CommitWrite(base::BindOnce(&MojoCdmFileIO::OnWriteCommitted, - weak_factory_.GetWeakPtr())); -} - -void MojoCdmFileIO::OnWriteCommitted(base::File reopened_file) { +void MojoCdmFileIO::OnFileWritten(FileStatus status) { DVLOG(3) << __func__ << " file: " << file_name_; DCHECK_EQ(State::kWriting, state_); - DCHECK(!file_for_reading_.IsValid()) << "Original file was not closed."; - TRACE_EVENT1("media", "MojoCdmFileIO::WriteDone", "file_name", file_name_); + // This logs the end of the async Write() request, and separately logs + // how long the client takes in OnWriteComplete(). + TRACE_EVENT_ASYNC_END1("media", "MojoCdmFileIO::Write", this, "status", + ConvertFileStatus(status)); - if (!reopened_file.IsValid()) { - // Rename failed, and no file to use. + if (status != FileStatus::kSuccess) { + DVLOG(1) << "Failed to write file " << file_name_; state_ = State::kError; OnError(ErrorType::kWriteError); return; } state_ = State::kOpened; - file_for_reading_ = std::move(reopened_file); + TRACE_EVENT0("media", "FileIOClient::OnWriteComplete"); client_->OnWriteComplete(ClientStatus::kSuccess); } @@ -333,6 +252,7 @@ } void MojoCdmFileIO::NotifyClientOfError(ErrorType error) { + // Note that no event tracing is done for error conditions. switch (error) { case ErrorType::kOpenError: client_->OnOpenComplete(ClientStatus::kError);
diff --git a/media/mojo/services/mojo_cdm_file_io.h b/media/mojo/services/mojo_cdm_file_io.h index cbebd32..d9972338 100644 --- a/media/mojo/services/mojo_cdm_file_io.h +++ b/media/mojo/services/mojo_cdm_file_io.h
@@ -11,10 +11,7 @@ #include <vector> #include "base/callback_forward.h" -#include "base/files/file.h" -#include "base/files/file_path.h" #include "base/macros.h" -#include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "media/cdm/api/content_decryption_module.h" #include "media/mojo/interfaces/cdm_storage.mojom.h" @@ -22,10 +19,6 @@ namespace media { -// TODO(crbug.com/774160): This class should do the Read/Write operations on a -// separate thread so as to not impact decoding happening on the same thread. -// The new thread may need to block shutdown so that the file is not corrupted. - // Implements a cdm::FileIO that communicates with mojom::CdmStorage. class MEDIA_MOJO_EXPORT MojoCdmFileIO : public cdm::FileIO { public: @@ -75,17 +68,14 @@ // Called when the file is opened (or not). void OnFileOpened(mojom::CdmStorage::Status status, - base::File file, mojom::CdmFileAssociatedPtrInfo cdm_file); - // Reading the file is done asynchronously. - void DoRead(int64_t num_bytes); + // Called when the read operation is done. + void OnFileRead(mojom::CdmFile::Status status, + const std::vector<uint8_t>& data); - // Called when a temporary file has been opened for writing. - void DoWrite(const std::vector<uint8_t>& data, base::File temporary_file); - - // Called after the write has been committed and replaces the original file. - void OnWriteCommitted(base::File reopened_file); + // Called when the write operation is done. + void OnFileWritten(mojom::CdmFile::Status status); // Called when an error occurs. Calls client_->OnXxxxComplete with kError // or kInUse asynchronously. In some cases we could actually call them @@ -108,11 +98,9 @@ // |file_name_| is only saved for logging purposes. std::string file_name_; - // Current file open for reading. - base::File file_for_reading_; - - // |cdm_file_| is used to write to the file and is released when the file is - // closed so that CdmStorage can tell that the file is no longer being used. + // |cdm_file_| is used to read and write the file and is released when the + // file is closed so that CdmStorage can tell that the file is no longer being + // used. mojom::CdmFileAssociatedPtr cdm_file_; // Keep track of operations in progress.
diff --git a/media/mojo/services/mojo_cdm_file_io_unittest.cc b/media/mojo/services/mojo_cdm_file_io_unittest.cc index 82dbbe1..b1145a3b 100644 --- a/media/mojo/services/mojo_cdm_file_io_unittest.cc +++ b/media/mojo/services/mojo_cdm_file_io_unittest.cc
@@ -4,16 +4,16 @@ #include "media/mojo/services/mojo_cdm_file_io.h" -#include "base/files/file.h" -#include "base/files/file_util.h" -#include "base/files/scoped_temp_dir.h" #include "base/run_loop.h" #include "base/test/scoped_task_environment.h" #include "media/cdm/api/content_decryption_module.h" +#include "mojo/public/cpp/bindings/associated_binding.h" +#include "mojo/public/cpp/bindings/binding.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::_; +using ::testing::Unused; using Status = cdm::FileIOClient::Status; namespace media { @@ -30,41 +30,41 @@ MOCK_METHOD1(OnWriteComplete, void(Status)); }; +class MockCdmFile : public mojom::CdmFile { + public: + MockCdmFile() = default; + ~MockCdmFile() override = default; + + MOCK_METHOD1(Read, void(ReadCallback)); + MOCK_METHOD2(Write, void(const std::vector<uint8_t>&, WriteCallback)); +}; + class MockCdmStorage : public mojom::CdmStorage { public: - MockCdmStorage() = default; + MockCdmStorage(mojom::CdmStorageRequest request, MockCdmFile* cdm_file) + : binding_(this, std::move(request)), client_binding_(cdm_file) {} ~MockCdmStorage() override = default; - bool SetUp() { return temp_directory_.CreateUniqueTempDir(); } - - // MojoCdmFileIO calls CdmStorage::Open() to actually open the file. - // Simulate this by creating a file in the temp directory and returning it. + // MojoCdmFileIO calls CdmStorage::Open() to open the file. Requests always + // succeed. void Open(const std::string& file_name, OpenCallback callback) override { - base::FilePath temp_file = temp_directory_.GetPath().AppendASCII(file_name); - DVLOG(1) << __func__ << " " << temp_file; - base::File file(temp_file, base::File::FLAG_CREATE_ALWAYS | - base::File::FLAG_READ | - base::File::FLAG_WRITE); + mojom::CdmFileAssociatedPtrInfo client_ptr_info; + client_binding_.Bind(mojo::MakeRequest(&client_ptr_info)); std::move(callback).Run(mojom::CdmStorage::Status::kSuccess, - std::move(file), nullptr); + std::move(client_ptr_info)); + + base::RunLoop().RunUntilIdle(); } private: - base::ScopedTempDir temp_directory_; + mojo::Binding<mojom::CdmStorage> binding_; + mojo::AssociatedBinding<mojom::CdmFile> client_binding_; }; } // namespace -// Currently MockCdmStorage::Open() returns NULL for the -// CdmFileAssociatedPtrInfo, so it is not possible to connect to a CdmFile -// object when writing data. This will require setting up a mojo connection -// between MojoCdmFileIOTest and CdmStorage, rather than using the object -// directly. -// // Note that the current browser_test ECKEncryptedMediaTest.FileIOTest -// does test writing (and reading) files using mojo. However, additional -// unittests would be good. -// TODO(crbug.com/777550): Implement tests that write to files. +// does test reading and writing files with real data. class MojoCdmFileIOTest : public testing::Test, public MojoCdmFileIO::Delegate { protected: @@ -74,10 +74,13 @@ // testing::Test implementation. void SetUp() override { client_ = std::make_unique<MockFileIOClient>(); - cdm_storage_ = std::make_unique<MockCdmStorage>(); - ASSERT_TRUE(cdm_storage_->SetUp()); + + auto request = mojo::MakeRequest(&cdm_storage_ptr_); + cdm_storage_ = + std::make_unique<MockCdmStorage>(std::move(request), &cdm_file_); + file_io_ = std::make_unique<MojoCdmFileIO>(this, client_.get(), - cdm_storage_.get()); + cdm_storage_ptr_.get()); } // MojoCdmFileIO::Delegate implementation. @@ -90,8 +93,10 @@ base::test::ScopedTaskEnvironment scoped_task_environment_; std::unique_ptr<MojoCdmFileIO> file_io_; - std::unique_ptr<MockCdmStorage> cdm_storage_; std::unique_ptr<MockFileIOClient> client_; + mojom::CdmStoragePtr cdm_storage_ptr_; + std::unique_ptr<MockCdmStorage> cdm_storage_; + MockCdmFile cdm_file_; }; TEST_F(MojoCdmFileIOTest, OpenFile) { @@ -140,31 +145,18 @@ base::RunLoop().RunUntilIdle(); } -TEST_F(MojoCdmFileIOTest, OpenBadFileName) { - // Anything other than ASCII letter, digits, and -._ will fail. Add a - // Unicode character to the name. - const std::string kFileName = "openfile\u1234"; - EXPECT_CALL(*client_.get(), OnOpenComplete(Status::kError)); - file_io_->Open(kFileName.data(), kFileName.length()); - base::RunLoop().RunUntilIdle(); -} - -TEST_F(MojoCdmFileIOTest, OpenTooLongFileName) { - // Limit is 256 characters, so try a file name with 257. - const std::string kFileName(257, 'a'); - EXPECT_CALL(*client_.get(), OnOpenComplete(Status::kError)); - file_io_->Open(kFileName.data(), kFileName.length()); - base::RunLoop().RunUntilIdle(); -} - TEST_F(MojoCdmFileIOTest, Read) { const std::string kFileName = "readfile"; EXPECT_CALL(*client_.get(), OnOpenComplete(Status::kSuccess)); file_io_->Open(kFileName.data(), kFileName.length()); base::RunLoop().RunUntilIdle(); - // File doesn't exist, so reading it should return 0 length buffer. - EXPECT_CALL(*client_.get(), OnReadComplete(Status::kSuccess, _, 0)); + // Successful reads always return a 3-byte buffer. + EXPECT_CALL(cdm_file_, Read(_)) + .WillOnce([](mojom::CdmFile::ReadCallback callback) { + std::move(callback).Run(mojom::CdmFile::Status::kSuccess, {1, 2, 3}); + }); + EXPECT_CALL(*client_.get(), OnReadComplete(Status::kSuccess, _, 3)); file_io_->Read(); base::RunLoop().RunUntilIdle(); } @@ -182,11 +174,61 @@ file_io_->Open(kFileName.data(), kFileName.length()); base::RunLoop().RunUntilIdle(); - EXPECT_CALL(*client_.get(), OnReadComplete(Status::kSuccess, _, 0)); + EXPECT_CALL(cdm_file_, Read(_)) + .WillOnce([](mojom::CdmFile::ReadCallback callback) { + std::move(callback).Run(mojom::CdmFile::Status::kSuccess, {1, 2, 3, 4}); + }); + EXPECT_CALL(*client_.get(), OnReadComplete(Status::kSuccess, _, 4)); EXPECT_CALL(*client_.get(), OnReadComplete(Status::kInUse, _, 0)); file_io_->Read(); file_io_->Read(); base::RunLoop().RunUntilIdle(); } +TEST_F(MojoCdmFileIOTest, Write) { + const std::string kFileName = "writefile"; + std::vector<uint8_t> data{1, 2, 3, 4, 5}; + + EXPECT_CALL(*client_.get(), OnOpenComplete(Status::kSuccess)); + file_io_->Open(kFileName.data(), kFileName.length()); + base::RunLoop().RunUntilIdle(); + + // Writing always succeeds. + EXPECT_CALL(cdm_file_, Write(_, _)) + .WillOnce([](Unused, mojom::CdmFile::WriteCallback callback) { + std::move(callback).Run(mojom::CdmFile::Status::kSuccess); + }); + EXPECT_CALL(*client_.get(), OnWriteComplete(Status::kSuccess)); + file_io_->Write(data.data(), data.size()); + base::RunLoop().RunUntilIdle(); +} + +TEST_F(MojoCdmFileIOTest, WriteBeforeOpen) { + std::vector<uint8_t> data{1, 2, 3, 4, 5}; + + // File not open, so writing should fail. + EXPECT_CALL(*client_.get(), OnWriteComplete(Status::kError)); + file_io_->Write(data.data(), data.size()); + base::RunLoop().RunUntilIdle(); +} + +TEST_F(MojoCdmFileIOTest, TwoWrites) { + const std::string kFileName = "writefile"; + std::vector<uint8_t> data{1, 2, 3, 4, 5}; + + EXPECT_CALL(*client_.get(), OnOpenComplete(Status::kSuccess)); + file_io_->Open(kFileName.data(), kFileName.length()); + base::RunLoop().RunUntilIdle(); + + EXPECT_CALL(cdm_file_, Write(_, _)) + .WillOnce([](Unused, mojom::CdmFile::WriteCallback callback) { + std::move(callback).Run(mojom::CdmFile::Status::kSuccess); + }); + EXPECT_CALL(*client_.get(), OnWriteComplete(Status::kSuccess)); + EXPECT_CALL(*client_.get(), OnWriteComplete(Status::kInUse)); + file_io_->Write(data.data(), data.size()); + file_io_->Write(data.data(), data.size()); + base::RunLoop().RunUntilIdle(); +} + } // namespace media
diff --git a/media/mojo/services/mojo_cdm_helper_unittest.cc b/media/mojo/services/mojo_cdm_helper_unittest.cc index 6a9a6b54..ed99b12 100644 --- a/media/mojo/services/mojo_cdm_helper_unittest.cc +++ b/media/mojo/services/mojo_cdm_helper_unittest.cc
@@ -5,9 +5,6 @@ #include "media/mojo/services/mojo_cdm_helper.h" #include "base/bind.h" -#include "base/files/file.h" -#include "base/files/file_util.h" -#include "base/files/scoped_temp_dir.h" #include "base/macros.h" #include "base/run_loop.h" #include "base/test/scoped_task_environment.h" @@ -35,25 +32,38 @@ MOCK_METHOD1(OnWriteComplete, void(Status)); }; +class TestCdmFile : public mojom::CdmFile { + public: + TestCdmFile() = default; + ~TestCdmFile() override = default; + + // Reading always succeeds with a 3-byte buffer. + void Read(ReadCallback callback) override { + std::move(callback).Run(Status::kSuccess, {1, 2, 3}); + } + + // Writing always succeeds. + void Write(const std::vector<uint8_t>& data, + WriteCallback callback) override { + std::move(callback).Run(Status::kSuccess); + } +}; + class MockCdmStorage : public mojom::CdmStorage { public: - MockCdmStorage() { CHECK(temp_directory_.CreateUniqueTempDir()); } + MockCdmStorage() : client_binding_(&cdm_file_) {} ~MockCdmStorage() override = default; - // MojoCdmFileIO calls CdmStorage::Open() to actually open the file. - // Simulate this by creating a file in the temp directory and returning it. void Open(const std::string& file_name, OpenCallback callback) override { - base::FilePath temp_file = temp_directory_.GetPath().AppendASCII(file_name); - DVLOG(1) << __func__ << " " << temp_file; - base::File file(temp_file, base::File::FLAG_CREATE_ALWAYS | - base::File::FLAG_READ | - base::File::FLAG_WRITE); + mojom::CdmFileAssociatedPtrInfo client_ptr_info; + client_binding_.Bind(mojo::MakeRequest(&client_ptr_info)); std::move(callback).Run(mojom::CdmStorage::Status::kSuccess, - std::move(file), nullptr); + std::move(client_ptr_info)); } private: - base::ScopedTempDir temp_directory_; + TestCdmFile cdm_file_; + mojo::AssociatedBinding<mojom::CdmFile> client_binding_; }; void CreateCdmStorage(mojom::CdmStorageRequest request) {
diff --git a/net/BUILD.gn b/net/BUILD.gn index 34964a03..9b05898 100644 --- a/net/BUILD.gn +++ b/net/BUILD.gn
@@ -985,6 +985,7 @@ "quic/network_connection.h", "quic/platform/impl/quic_aligned_impl.h", "quic/platform/impl/quic_arraysize_impl.h", + "quic/platform/impl/quic_bbr2_sender_impl.h", "quic/platform/impl/quic_bug_tracker_impl.h", "quic/platform/impl/quic_cert_utils_impl.h", "quic/platform/impl/quic_chromium_clock.cc", @@ -1647,6 +1648,7 @@ "third_party/quiche/src/quic/core/uber_received_packet_manager.h", "third_party/quiche/src/quic/platform/api/quic_aligned.h", "third_party/quiche/src/quic/platform/api/quic_arraysize.h", + "third_party/quiche/src/quic/platform/api/quic_bbr2_sender.h", "third_party/quiche/src/quic/platform/api/quic_bug_tracker.h", "third_party/quiche/src/quic/platform/api/quic_cert_utils.h", "third_party/quiche/src/quic/platform/api/quic_client_stats.h",
diff --git a/net/quic/platform/impl/quic_bbr2_sender_impl.h b/net/quic/platform/impl/quic_bbr2_sender_impl.h new file mode 100644 index 0000000..df919dc --- /dev/null +++ b/net/quic/platform/impl/quic_bbr2_sender_impl.h
@@ -0,0 +1,16 @@ +// Copyright (c) 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 NET_QUIC_PLATFORM_IMPL_QUIC_BBR2_SENDER_IMPL_H_ +#define NET_QUIC_PLATFORM_IMPL_QUIC_BBR2_SENDER_IMPL_H_ + +#include "net/third_party/quiche/src/quic/core/congestion_control/bbr_sender.h" + +namespace quic { + +using QuicBbr2SenderImpl = BbrSender; + +} // namespace quic + +#endif // NET_QUIC_PLATFORM_IMPL_QUIC_BBR2_SENDER_IMPL_H_
diff --git a/net/quic/quic_flags_list.h b/net/quic/quic_flags_list.h index 5f447074..4e71d697 100644 --- a/net/quic/quic_flags_list.h +++ b/net/quic/quic_flags_list.h
@@ -114,9 +114,6 @@ // Mechanism to override version label and ALPN for IETF interop. QUIC_FLAG(int32_t, FLAGS_quic_ietf_draft_version, 0) -// If true, enable QUIC v44. -QUIC_FLAG(bool, FLAGS_quic_reloadable_flag_quic_enable_version_44, true) - // Stop checking QuicUnackedPacketMap::HasUnackedRetransmittableFrames and // instead rely on the existing check that bytes_in_flight > 0 QUIC_FLAG(bool, FLAGS_quic_reloadable_flag_quic_optimize_inflight_check, false) @@ -187,9 +184,6 @@ FLAGS_quic_restart_flag_quic_no_server_conn_ver_negotiation2, true) -// If true, enable QUIC version 46. -QUIC_FLAG(bool, FLAGS_quic_reloadable_flag_quic_enable_version_46, true) - // When in STARTUP and recovery, do not add bytes_acked to QUIC BBR's CWND in // CalculateCongestionWindow() QUIC_FLAG(
diff --git a/sandbox/win/src/nt_internals.h b/sandbox/win/src/nt_internals.h index 2b2dc0f..341e291 100644 --- a/sandbox/win/src/nt_internals.h +++ b/sandbox/win/src/nt_internals.h
@@ -695,6 +695,11 @@ IN BOOLEAN Alertable, IN PLARGE_INTEGER Timeout OPTIONAL); +typedef NTSTATUS(WINAPI* NtWaitForSingleObjectFunction)( + IN HANDLE ObjectHandle, + IN BOOLEAN Alertable, + IN PLARGE_INTEGER TimeOut OPTIONAL); + typedef NTSTATUS(WINAPI* NtQuerySystemInformation)( IN SYSTEM_INFORMATION_CLASS SystemInformationClass, OUT PVOID SystemInformation,
diff --git a/sandbox/win/src/policy_broker.cc b/sandbox/win/src/policy_broker.cc index 679eb7db..406057ac 100644 --- a/sandbox/win/src/policy_broker.cc +++ b/sandbox/win/src/policy_broker.cc
@@ -55,6 +55,8 @@ INIT_GLOBAL_NT(QuerySection); INIT_GLOBAL_NT(QueryVirtualMemory); INIT_GLOBAL_NT(UnmapViewOfSection); + INIT_GLOBAL_NT(SignalAndWaitForSingleObject); + INIT_GLOBAL_NT(WaitForSingleObject); INIT_GLOBAL_RTL(RtlAllocateHeap); INIT_GLOBAL_RTL(RtlAnsiStringToUnicodeString);
diff --git a/sandbox/win/src/sandbox_nt_types.h b/sandbox/win/src/sandbox_nt_types.h index a5a40ce..eff0f01 100644 --- a/sandbox/win/src/sandbox_nt_types.h +++ b/sandbox/win/src/sandbox_nt_types.h
@@ -10,28 +10,30 @@ namespace sandbox { struct NtExports { - NtAllocateVirtualMemoryFunction AllocateVirtualMemory; - NtCloseFunction Close; - NtDuplicateObjectFunction DuplicateObject; - NtFreeVirtualMemoryFunction FreeVirtualMemory; - NtMapViewOfSectionFunction MapViewOfSection; - NtProtectVirtualMemoryFunction ProtectVirtualMemory; - NtQueryInformationProcessFunction QueryInformationProcess; - NtQueryObjectFunction QueryObject; - NtQuerySectionFunction QuerySection; - NtQueryVirtualMemoryFunction QueryVirtualMemory; - NtUnmapViewOfSectionFunction UnmapViewOfSection; - RtlAllocateHeapFunction RtlAllocateHeap; - RtlAnsiStringToUnicodeStringFunction RtlAnsiStringToUnicodeString; - RtlCompareUnicodeStringFunction RtlCompareUnicodeString; - RtlCreateHeapFunction RtlCreateHeap; - RtlCreateUserThreadFunction RtlCreateUserThread; - RtlDestroyHeapFunction RtlDestroyHeap; - RtlFreeHeapFunction RtlFreeHeap; - _strnicmpFunction _strnicmp; - strlenFunction strlen; - wcslenFunction wcslen; - memcpyFunction memcpy; + NtAllocateVirtualMemoryFunction AllocateVirtualMemory; + NtCloseFunction Close; + NtDuplicateObjectFunction DuplicateObject; + NtFreeVirtualMemoryFunction FreeVirtualMemory; + NtMapViewOfSectionFunction MapViewOfSection; + NtProtectVirtualMemoryFunction ProtectVirtualMemory; + NtQueryInformationProcessFunction QueryInformationProcess; + NtQueryObjectFunction QueryObject; + NtQuerySectionFunction QuerySection; + NtQueryVirtualMemoryFunction QueryVirtualMemory; + NtUnmapViewOfSectionFunction UnmapViewOfSection; + NtSignalAndWaitForSingleObjectFunction SignalAndWaitForSingleObject; + NtWaitForSingleObjectFunction WaitForSingleObject; + RtlAllocateHeapFunction RtlAllocateHeap; + RtlAnsiStringToUnicodeStringFunction RtlAnsiStringToUnicodeString; + RtlCompareUnicodeStringFunction RtlCompareUnicodeString; + RtlCreateHeapFunction RtlCreateHeap; + RtlCreateUserThreadFunction RtlCreateUserThread; + RtlDestroyHeapFunction RtlDestroyHeap; + RtlFreeHeapFunction RtlFreeHeap; + _strnicmpFunction _strnicmp; + strlenFunction strlen; + wcslenFunction wcslen; + memcpyFunction memcpy; }; // This is the value used for the ntdll level allocator.
diff --git a/sandbox/win/src/sharedmem_ipc_client.cc b/sandbox/win/src/sharedmem_ipc_client.cc index 3163c679..2f849be 100644 --- a/sandbox/win/src/sharedmem_ipc_client.cc +++ b/sandbox/win/src/sharedmem_ipc_client.cc
@@ -11,9 +11,50 @@ #include "sandbox/win/src/crosscall_client.h" #include "sandbox/win/src/crosscall_params.h" #include "sandbox/win/src/sandbox.h" +#include "sandbox/win/src/sandbox_nt_types.h" +#include "sandbox/win/src/sandbox_nt_util.h" namespace sandbox { +SANDBOX_INTERCEPT NtExports g_nt; + +namespace { + +DWORD SignalObjectAndWaitWrapper(HANDLE object_to_signal, + HANDLE object_to_wait_on, + DWORD millis, + BOOL alertable) { + // Not running in a sandboxed process so can call directly. + if (!g_nt.SignalAndWaitForSingleObject) + return SignalObjectAndWait(object_to_signal, object_to_wait_on, millis, + alertable); + // Don't support alertable. + CHECK_NT(!alertable); + LARGE_INTEGER timeout; + timeout.QuadPart = millis * -10000LL; + NTSTATUS status = g_nt.SignalAndWaitForSingleObject( + object_to_signal, object_to_wait_on, alertable, + millis == INFINITE ? nullptr : &timeout); + if (!NT_SUCCESS(status)) + return WAIT_FAILED; + return status; +} + +DWORD WaitForSingleObjectWrapper(HANDLE handle, DWORD millis) { + // Not running in a sandboxed process so can call directly. + if (!g_nt.WaitForSingleObject) + return WaitForSingleObject(handle, millis); + LARGE_INTEGER timeout; + timeout.QuadPart = millis * -10000LL; + NTSTATUS status = g_nt.WaitForSingleObject( + handle, FALSE, millis == INFINITE ? nullptr : &timeout); + if (!NT_SUCCESS(status)) + return WAIT_FAILED; + return status; +} + +} // namespace + // Get the base of the data buffer of the channel; this is where the input // parameters get serialized. Since they get serialized directly into the // channel we avoid one copy. @@ -68,18 +109,19 @@ // While the atomic signaling and waiting is not a requirement, it // is nice because we save a trip to kernel. - DWORD wait = - ::SignalObjectAndWait(channel[num].ping_event, channel[num].pong_event, - kIPCWaitTimeOut1, false); + DWORD wait = SignalObjectAndWaitWrapper(channel[num].ping_event, + channel[num].pong_event, + kIPCWaitTimeOut1, false); if (WAIT_TIMEOUT == wait) { // The server is taking too long. Enter a loop were we check if the // server_alive mutex has been abandoned which would signal a server crash // or else we keep waiting for a response. while (true) { - wait = ::WaitForSingleObject(control_->server_alive, 0); + wait = WaitForSingleObjectWrapper(control_->server_alive, 0); if (WAIT_TIMEOUT == wait) { // Server seems still alive. We already signaled so here we just wait. - wait = ::WaitForSingleObject(channel[num].pong_event, kIPCWaitTimeOut1); + wait = WaitForSingleObjectWrapper(channel[num].pong_event, + kIPCWaitTimeOut1); if (WAIT_OBJECT_0 == wait) { // The server took a long time but responded. break; @@ -131,7 +173,7 @@ } // We did not find any available channel, maybe the server is dead. DWORD wait = - ::WaitForSingleObject(control_->server_alive, kIPCWaitTimeOut2); + WaitForSingleObjectWrapper(control_->server_alive, kIPCWaitTimeOut2); if (WAIT_TIMEOUT != wait) { // The server is dead and we outlive it enough to get in trouble. *severe_failure = true;
diff --git a/services/audio/service.cc b/services/audio/service.cc index 37ebf55..aa1551c5 100644 --- a/services/audio/service.cc +++ b/services/audio/service.cc
@@ -7,8 +7,10 @@ #include <utility> #include "base/bind.h" +#include "base/deferred_sequenced_task_runner.h" #include "base/logging.h" #include "base/macros.h" +#include "base/no_destructor.h" #include "base/single_thread_task_runner.h" #include "base/system/system_monitor.h" #include "base/time/default_tick_clock.h" @@ -83,6 +85,13 @@ magic_bytes_ = 0xDEADBEEFu; } +// static +base::DeferredSequencedTaskRunner* Service::GetInProcessTaskRunner() { + static base::NoDestructor<scoped_refptr<base::DeferredSequencedTaskRunner>> + instance(base::MakeRefCounted<base::DeferredSequencedTaskRunner>()); + return instance->get(); +} + void Service::OnStart() { CHECK_EQ(magic_bytes_, 0x600DC0DEu); DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
diff --git a/services/audio/service.h b/services/audio/service.h index 66ec0d7..b37b539 100644 --- a/services/audio/service.h +++ b/services/audio/service.h
@@ -27,6 +27,7 @@ #include "services/service_manager/public/mojom/service.mojom.h" namespace base { +class DeferredSequencedTaskRunner; class SystemMonitor; } @@ -77,6 +78,10 @@ mojo::PendingReceiver<service_manager::mojom::Service> receiver); ~Service() final; + // Returns a DeferredSequencedTaskRunner to be used to run the audio service + // when launched in the browser process. + static base::DeferredSequencedTaskRunner* GetInProcessTaskRunner(); + // service_manager::Service implementation. void OnStart() final; void OnBindInterface(const service_manager::BindSourceInfo& source_info,
diff --git a/services/device/public/mojom/bluetooth_system.mojom b/services/device/public/mojom/bluetooth_system.mojom index 84fae98b..5c8f5dd2 100644 --- a/services/device/public/mojom/bluetooth_system.mojom +++ b/services/device/public/mojom/bluetooth_system.mojom
@@ -11,6 +11,12 @@ array<uint8, 6> address; }; +// These fields are placed in a struct to be nullable. +struct BluetoothDeviceBatteryInfo { + // The remaining battery of the device. + uint8 battery_percentage; +}; + // Holds information about a Bluetooth Device. struct BluetoothDeviceInfo { enum ConnectionState { @@ -60,6 +66,8 @@ // [1] https://www.bluetooth.com/specifications/assigned-numbers/baseband // [2] https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.gap.appearance.xml DeviceType device_type; + + BluetoothDeviceBatteryInfo? battery_info; }; // Factory to get an instance of the BluetoothSystem interface.
diff --git a/services/viz/privileged/interfaces/compositing/renderer_settings.mojom b/services/viz/privileged/interfaces/compositing/renderer_settings.mojom index 9b7ffd00..2296f9a 100644 --- a/services/viz/privileged/interfaces/compositing/renderer_settings.mojom +++ b/services/viz/privileged/interfaces/compositing/renderer_settings.mojom
@@ -10,7 +10,6 @@ struct RendererSettings { bool allow_antialiasing; - bool finish_rendering_on_resize; bool force_antialiasing; bool force_blending_with_shaders; bool tint_gl_composited_content;
diff --git a/services/viz/privileged/interfaces/compositing/renderer_settings_struct_traits.cc b/services/viz/privileged/interfaces/compositing/renderer_settings_struct_traits.cc index c9d4de3..d835807 100644 --- a/services/viz/privileged/interfaces/compositing/renderer_settings_struct_traits.cc +++ b/services/viz/privileged/interfaces/compositing/renderer_settings_struct_traits.cc
@@ -20,7 +20,6 @@ out->force_antialiasing = data.force_antialiasing(); out->force_blending_with_shaders = data.force_blending_with_shaders(); out->partial_swap_enabled = data.partial_swap_enabled(); - out->finish_rendering_on_resize = data.finish_rendering_on_resize(); out->should_clear_root_render_pass = data.should_clear_root_render_pass(); out->release_overlay_resources_after_gpu_query = data.release_overlay_resources_after_gpu_query();
diff --git a/services/viz/privileged/interfaces/compositing/renderer_settings_struct_traits.h b/services/viz/privileged/interfaces/compositing/renderer_settings_struct_traits.h index 4811bdf..50cfa55 100644 --- a/services/viz/privileged/interfaces/compositing/renderer_settings_struct_traits.h +++ b/services/viz/privileged/interfaces/compositing/renderer_settings_struct_traits.h
@@ -36,10 +36,6 @@ return input.partial_swap_enabled; } - static bool finish_rendering_on_resize(const viz::RendererSettings& input) { - return input.finish_rendering_on_resize; - } - static bool should_clear_root_render_pass( const viz::RendererSettings& input) { return input.should_clear_root_render_pass;
diff --git a/services/viz/privileged/interfaces/struct_traits_unittest.cc b/services/viz/privileged/interfaces/struct_traits_unittest.cc index be0299a..cdd68da 100644 --- a/services/viz/privileged/interfaces/struct_traits_unittest.cc +++ b/services/viz/privileged/interfaces/struct_traits_unittest.cc
@@ -24,7 +24,6 @@ input.force_antialiasing = true; input.force_blending_with_shaders = true; input.partial_swap_enabled = true; - input.finish_rendering_on_resize = true; input.should_clear_root_render_pass = false; input.release_overlay_resources_after_gpu_query = true; input.show_overdraw_feedback = true; @@ -40,8 +39,6 @@ EXPECT_EQ(input.force_blending_with_shaders, output.force_blending_with_shaders); EXPECT_EQ(input.partial_swap_enabled, output.partial_swap_enabled); - EXPECT_EQ(input.finish_rendering_on_resize, - output.finish_rendering_on_resize); EXPECT_EQ(input.should_clear_root_render_pass, output.should_clear_root_render_pass); EXPECT_EQ(input.release_overlay_resources_after_gpu_query,
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index e338a3b3..9bc3356 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -11016,6 +11016,25 @@ "linux-blink-rel-dummy": { "isolated_scripts": [ { + "isolate_name": "webdriver_wpt_tests", + "merge": { + "args": [ + "--verbose" + ], + "script": "//third_party/blink/tools/merge_web_test_results.py" + }, + "name": "webdriver_tests_suite", + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "os": "Ubuntu-14.04" + } + ], + "shards": 4 + } + }, + { "args": [ "--num-retries=3" ], @@ -11035,7 +11054,7 @@ "os": "Ubuntu-14.04" } ], - "shards": 20 + "shards": 12 } } ]
diff --git a/testing/buildbot/chromium.gpu.fyi.json b/testing/buildbot/chromium.gpu.fyi.json index de43befc..4bea5e0 100644 --- a/testing/buildbot/chromium.gpu.fyi.json +++ b/testing/buildbot/chromium.gpu.fyi.json
@@ -24168,6 +24168,58 @@ "--build-revision", "${got_revision}", "--test-machine-name", + "${buildername}", + "--use-skia-gold" + ], + "experiment_percentage": 100, + "isolate_name": "telemetry_gpu_integration_test", + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_isolated_script_merge.py" + }, + "name": "pixel_skia_gold_test", + "non_precommit_args": [ + "--upload-refimg-to-cloud-storage" + ], + "precommit_args": [ + "--download-refimg-from-cloud-storage", + "--review-patch-issue", + "${patch_issue}", + "--review-patch-set", + "${patch_set}", + "--buildbucket-build-id", + "${buildbucket_build_id}" + ], + "should_retry_with_patch": false, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "gpu": "nvidia-quadro-p400-win10-stable", + "os": "Windows-10", + "pool": "Chrome-GPU" + } + ], + "idempotent": false, + "service_account": "chrome-gpu-gold@chops-service-accounts.iam.gserviceaccount.com" + } + }, + { + "args": [ + "pixel", + "--show-stdout", + "--browser=release", + "--passthrough", + "-v", + "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc", + "--dont-restore-color-profile-after-test", + "--refimg-cloud-storage-bucket", + "chromium-gpu-archive/reference-images", + "--os-type", + "win", + "--build-revision", + "${got_revision}", + "--test-machine-name", "${buildername}" ], "isolate_name": "telemetry_gpu_integration_test", @@ -24196,6 +24248,26 @@ } }, { + "args": [], + "experiment_percentage": 100, + "isolate_name": "rendering_representative_perf_tests", + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_isolated_script_merge.py" + }, + "name": "rendering_representative_perf_tests", + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "gpu": "nvidia-quadro-p400-win10-stable", + "os": "Windows-10", + "pool": "Chrome-GPU" + } + ] + } + }, + { "args": [ "screenshot_sync", "--show-stdout",
diff --git a/testing/buildbot/test_suites.pyl b/testing/buildbot/test_suites.pyl index 50c479be..ac3c205 100644 --- a/testing/buildbot/test_suites.pyl +++ b/testing/buildbot/test_suites.pyl
@@ -2439,6 +2439,40 @@ }, }, + 'chromium_web_tests_and_wpt_webdriver_isolated_scripts': { + 'webkit_layout_tests': { + # layout test failures are retried 3 times when '--test-list' is not + # passed, but 0 times when '--test-list' is passed. We want to always + # retry 3 times, so we explicitly specify it. + 'args': [ + '--num-retries=3', + ], + 'isolate_name': 'blink_web_tests_exparchive', + 'merge': { + 'args': [ + '--verbose', + ], + 'script': '//third_party/blink/tools/merge_web_test_results.py', + }, + 'results_handler': 'layout tests', + 'swarming': { + 'shards': 12, + } + }, + 'webdriver_tests_suite': { + 'isolate_name': 'webdriver_wpt_tests', + 'merge': { + 'args': [ + '--verbose', + ], + 'script': '//third_party/blink/tools/merge_web_test_results.py', + }, + 'swarming': { + 'shards': 4, + }, + }, + }, + 'chromium_webkit_isolated_scripts': { 'webkit_layout_tests': { # layout test failures are retried 3 times when '--test-list' is not
diff --git a/testing/buildbot/waterfalls.pyl b/testing/buildbot/waterfalls.pyl index c746636..df9c90f 100644 --- a/testing/buildbot/waterfalls.pyl +++ b/testing/buildbot/waterfalls.pyl
@@ -1759,7 +1759,7 @@ }, 'linux-blink-rel-dummy': { 'test_suites': { - 'isolated_scripts': 'chromium_webkit_isolated_scripts', + 'isolated_scripts': 'chromium_web_tests_and_wpt_webdriver_isolated_scripts', }, 'swarming': { 'dimension_sets': [ @@ -1767,7 +1767,6 @@ 'os': 'Ubuntu-14.04', }, ], - 'shards': 20, }, }, 'linux-chromeos-code-coverage': { @@ -3072,8 +3071,8 @@ ], 'test_suites': { 'gtest_tests': 'gpu_fyi_win_gtests', - 'isolated_scripts': 'gpu_angle_fyi_win_optional_isolated_scripts', - 'gpu_telemetry_tests': 'gpu_fyi_win_release_telemetry_tests', + 'isolated_scripts': 'gpu_angle_fyi_win_optional_and_representative_perf_isolated_scripts', + 'gpu_telemetry_tests': 'gpu_fyi_win_release_gold_telemetry_tests', }, }, 'Win10 FYI Exp Release (Intel HD 630)': {
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 7573611..65f3def 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -594,6 +594,24 @@ ] } ], + "AutofillDoNotMigrateUnsupportedLocalCards": [ + { + "platforms": [ + "chromeos", + "linux", + "mac", + "windows" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "AutofillDoNotMigrateUnsupportedLocalCards" + ] + } + ] + } + ], "AutofillDoNotUploadSaveUnsupportedCards": [ { "platforms": [
diff --git a/third_party/apache-portable-runtime/OWNERS b/third_party/apache-portable-runtime/OWNERS index 96b9292..fb59c70 100644 --- a/third_party/apache-portable-runtime/OWNERS +++ b/third_party/apache-portable-runtime/OWNERS
@@ -1,2 +1 @@ -kapishnikov@chromium.org -mef@chromium.org +file://net/OWNERS
diff --git a/third_party/blink/public/BUILD.gn b/third_party/blink/public/BUILD.gn index e866409..2b4e5ac 100644 --- a/third_party/blink/public/BUILD.gn +++ b/third_party/blink/public/BUILD.gn
@@ -107,6 +107,7 @@ # TODO(crbug.com/704136): Remove the group of mock_media_*.h # files below when content/renderer/media/stream Onion souping # is done. + "web/modules/mediastream/mock_constraint_factory.h", "web/modules/mediastream/mock_media_stream_registry.h", "web/modules/mediastream/mock_media_stream_video_source.h", ]
diff --git a/third_party/blink/public/platform/web_runtime_features.h b/third_party/blink/public/platform/web_runtime_features.h index d5e06a2e..d06553df 100644 --- a/third_party/blink/public/platform/web_runtime_features.h +++ b/third_party/blink/public/platform/web_runtime_features.h
@@ -245,6 +245,7 @@ BLINK_PLATFORM_EXPORT static void EnableDisplayLocking(bool); BLINK_PLATFORM_EXPORT static void EnablePauseExecutionContextOnBackgroundFreeze(bool); + BLINK_PLATFORM_EXPORT static void EnableConsolidatedMovementXY(bool); private: WebRuntimeFeatures();
diff --git a/third_party/blink/public/web/modules/mediastream/mock_constraint_factory.h b/third_party/blink/public/web/modules/mediastream/mock_constraint_factory.h new file mode 100644 index 0000000..244624d0 --- /dev/null +++ b/third_party/blink/public/web/modules/mediastream/mock_constraint_factory.h
@@ -0,0 +1,40 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_PUBLIC_WEB_MODULES_MEDIASTREAM_MOCK_CONSTRAINT_FACTORY_H_ +#define THIRD_PARTY_BLINK_PUBLIC_WEB_MODULES_MEDIASTREAM_MOCK_CONSTRAINT_FACTORY_H_ + +#include <string> +#include <vector> + +#include "base/macros.h" +#include "third_party/blink/public/platform/web_media_constraints.h" + +namespace blink { + +// TODO(crbug.com/704136): Move this class out of the Blink exposed API +// when all users of it have been Onion souped. +class MockConstraintFactory { + public: + MockConstraintFactory(); + ~MockConstraintFactory(); + + WebMediaConstraints CreateWebMediaConstraints() const; + WebMediaTrackConstraintSet& basic() { return basic_; } + WebMediaTrackConstraintSet& AddAdvanced(); + + void DisableDefaultAudioConstraints(); + void DisableAecAudioConstraints(); + void Reset(); + + private: + WebMediaTrackConstraintSet basic_; + std::vector<WebMediaTrackConstraintSet> advanced_; + + DISALLOW_COPY_AND_ASSIGN(MockConstraintFactory); +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_PUBLIC_WEB_MODULES_MEDIASTREAM_MOCK_CONSTRAINT_FACTORY_H_
diff --git a/third_party/blink/renderer/core/dom/OWNERS b/third_party/blink/renderer/core/dom/OWNERS index 1828548..0c86b53 100644 --- a/third_party/blink/renderer/core/dom/OWNERS +++ b/third_party/blink/renderer/core/dom/OWNERS
@@ -1,4 +1,4 @@ -hayato@chromium.org +masonfreed@chromium.org per-file *_struct_traits*.*=set noparent per-file *_struct_traits*.*=file://ipc/SECURITY_OWNERS
diff --git a/third_party/blink/renderer/core/dom/README.md b/third_party/blink/renderer/core/dom/README.md index 55fba416f..c6e4107 100644 --- a/third_party/blink/renderer/core/dom/README.md +++ b/third_party/blink/renderer/core/dom/README.md
@@ -730,7 +730,7 @@ Since `Node::UpdateDistributionForFlatTreeTraversal` can take O(N) in the worst case (_even if the distribution flag is clean!_), you should be careful not to call it in hot code paths. If you are not sure, please contact -dom-dev@chromium.org, or add hayato@chromium.org to reviewers. +dom-dev@chromium.org, or add masonfreed@chromium.org to reviewers. Once Blink removes Shadow DOM v0 in the future, you don't need to call `Node::UpdateDistributionForFlatTreeTraversal` before using `FlatTreeTraversal`
diff --git a/third_party/blink/renderer/core/dom/node.cc b/third_party/blink/renderer/core/dom/node.cc index d0a43cd4..e091a023 100644 --- a/third_party/blink/renderer/core/dom/node.cc +++ b/third_party/blink/renderer/core/dom/node.cc
@@ -2816,7 +2816,7 @@ // in executing RecalcAssignment(), however, unfortunately, // that could happen as follows: // - // 1. RecalsAssignment() can detach a node + // 1. RecalcAssignment() can detach a node // 2. Then, DetachLayoutTree() may use FlatTreeTraversal via the hook of // AXObjectCacheImpl::ChildrenChanged(). //
diff --git a/third_party/blink/renderer/core/events/mouse_event.cc b/third_party/blink/renderer/core/events/mouse_event.cc index 0a489618..79c75c3 100644 --- a/third_party/blink/renderer/core/events/mouse_event.cc +++ b/third_party/blink/renderer/core/events/mouse_event.cc
@@ -245,10 +245,10 @@ initializer->setClientX(client_point.X()); initializer->setClientY(client_point.Y()); - // TODO(nzolghadr): We need to scale movement attrinutes as well. But if we - // do that here and round it to the int again it causes inconsistencies - // between screenX/Y and cumulative movementX/Y. - if (!RuntimeEnabledFeatures::MovementXYInBlinkEnabled()) { + if (!RuntimeEnabledFeatures::ConsolidatedMovementXYEnabled()) { + // TODO(nzolghadr): We need to scale movement attrinutes as well. But if we + // do that here and round it to the int again it causes inconsistencies + // between screenX/Y and cumulative movementX/Y. initializer->setMovementX(web_pointer_properties.movement_x); initializer->setMovementY(web_pointer_properties.movement_y); }
diff --git a/third_party/blink/renderer/core/events/pointer_event_factory.cc b/third_party/blink/renderer/core/events/pointer_event_factory.cc index 8b8dba7..5f2791ff 100644 --- a/third_party/blink/renderer/core/events/pointer_event_factory.cc +++ b/third_party/blink/renderer/core/events/pointer_event_factory.cc
@@ -94,7 +94,7 @@ MouseEvent::SetCoordinatesFromWebPointerProperties( web_pointer_event_in_root_frame, dom_window, pointer_event_init); - if (RuntimeEnabledFeatures::MovementXYInBlinkEnabled() && + if (RuntimeEnabledFeatures::ConsolidatedMovementXYEnabled() && web_pointer_event.GetType() == WebInputEvent::kPointerMove) { // TODO(eirage): pointerrawupdate event's movements are not calculated. pointer_event_init->setMovementX(web_pointer_event.PositionInScreen().x -
diff --git a/third_party/blink/renderer/core/input/mouse_event_manager.cc b/third_party/blink/renderer/core/input/mouse_event_manager.cc index a52c3aae..bccaac6 100644 --- a/third_party/blink/renderer/core/input/mouse_event_manager.cc +++ b/third_party/blink/renderer/core/input/mouse_event_manager.cc
@@ -64,7 +64,7 @@ void UpdateMouseMovementXY(const WebMouseEvent& mouse_event, const FloatPoint* last_position, MouseEventInit* initializer) { - if (RuntimeEnabledFeatures::MovementXYInBlinkEnabled() && + if (RuntimeEnabledFeatures::ConsolidatedMovementXYEnabled() && mouse_event.GetType() == WebInputEvent::kMouseMove && last_position) { if (RuntimeEnabledFeatures::FractionalMouseEventEnabled()) { initializer->setMovementX(mouse_event.PositionInScreen().x -
diff --git a/third_party/blink/renderer/core/input/pointer_event_manager_test.cc b/third_party/blink/renderer/core/input/pointer_event_manager_test.cc index 3c3d95c..0281503 100644 --- a/third_party/blink/renderer/core/input/pointer_event_manager_test.cc +++ b/third_party/blink/renderer/core/input/pointer_event_manager_test.cc
@@ -248,7 +248,7 @@ { // Turn on the flag for test. - ScopedMovementXYInBlinkForTest scoped_feature(true); + ScopedConsolidatedMovementXYForTest scoped_feature(true); WebView().MainFrameWidget()->HandleInputEvent(WebCoalescedInputEvent( CreateTestPointerEvent(WebInputEvent::kPointerMove, @@ -290,7 +290,7 @@ { // When flag is off, movementX/Y follows the value in WebPointerProperties. - ScopedMovementXYInBlinkForTest scoped_feature(false); + ScopedConsolidatedMovementXYForTest scoped_feature(false); WebView().MainFrameWidget()->HandleInputEvent(WebCoalescedInputEvent( CreateTestPointerEvent(WebInputEvent::kPointerMove,
diff --git a/third_party/blink/renderer/core/layout/geometry/logical_rect.h b/third_party/blink/renderer/core/layout/geometry/logical_rect.h index 457a9fe..b6196671 100644 --- a/third_party/blink/renderer/core/layout/geometry/logical_rect.h +++ b/third_party/blink/renderer/core/layout/geometry/logical_rect.h
@@ -46,9 +46,16 @@ LogicalOffset offset; LogicalSize size; - LogicalOffset EndOffset() const { return offset + size; } constexpr bool IsEmpty() const { return size.IsEmpty(); } + LayoutUnit InlineEndOffset() const { + return offset.inline_offset + size.inline_size; + } + LayoutUnit BlockEndOffset() const { + return offset.block_offset + size.block_size; + } + LogicalOffset EndOffset() const { return offset + size; } + constexpr bool operator==(const LogicalRect& other) const { return other.offset == offset && other.size == size; }
diff --git a/third_party/blink/renderer/core/layout/layout_text_test.cc b/third_party/blink/renderer/core/layout/layout_text_test.cc index f8b7005..671bb18 100644 --- a/third_party/blink/renderer/core/layout/layout_text_test.cc +++ b/third_party/blink/renderer/core/layout/layout_text_test.cc
@@ -773,6 +773,23 @@ "foo bar b^a|</div>")); } +TEST_P(ParameterizedLayoutTextTest, LocalSelectionRectNegativeLeading) { + LoadAhem(); + SetSelectionAndUpdateLayoutSelection(R"HTML( + <div id="container" style="font: 10px/10px Ahem"> + ^ + <span id="span" style="display: inline-block; line-height: 1px"> + Text + </span> + | + </div> + )HTML"); + LayoutObject* span = GetLayoutObjectByElementId("span"); + LayoutObject* text = span->SlowFirstChild(); + EXPECT_EQ(PhysicalRect(0, -5, LayoutNGEnabled() ? 40 : 50, 10), + text->LocalSelectionVisualRect()); +} + TEST_P(ParameterizedLayoutTextTest, LocalSelectionRectLineHeightVertical) { LoadAhem(); EXPECT_EQ(LayoutNGEnabled() ? PhysicalRect(0, 10, 50, 10)
diff --git a/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.cc b/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.cc index cea020a..5fd401f8 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.cc
@@ -210,17 +210,26 @@ if (!layout_object->IsAnonymous()) { outline_rects->emplace_back(additional_offset, Size().ToLayoutSize()); } - if (outline_type == NGOutlineType::kIncludeBlockVisualOverflow && !HasOverflowClip() && !HasControlClip(*this)) { - AddOutlineRectsForNormalChildren(outline_rects, additional_offset, + // Tricky code ahead: we pass a 0,0 additional_offset to + // AddOutlineRectsForNormalChildren, and add it in after the call. + // This is necessary because AddOutlineRectsForNormalChildren expects + // additional_offset to be an offset from containing_block. + // Since containing_block is our layout object, offset must be 0,0. + // https://crbug.com/968019 + Vector<PhysicalRect> children_rects; + AddOutlineRectsForNormalChildren(&children_rects, PhysicalOffset(), outline_type, ToLayoutBoxModelObject(GetLayoutObject())); - - // TODO(kojii): LayoutBlock::AddOutlineRects handles positioned objects - // here. Do we need it? + if (!additional_offset.IsZero()) { + for (auto& rect : children_rects) + rect.offset += additional_offset; + } + outline_rects->AppendVector(children_rects); + // LayoutBlock::AddOutlineRects also adds out of flow objects here. + // In LayoutNG out of flow objects are not part of the outline. } - // TODO(kojii): Needs inline_element_continuation logic from // LayoutBlockFlow::AddOutlineRects? }
diff --git a/third_party/blink/renderer/core/layout/ng/ng_physical_container_fragment.cc b/third_party/blink/renderer/core/layout/ng/ng_physical_container_fragment.cc index 7e60ee5..910c39d 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_physical_container_fragment.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_physical_container_fragment.cc
@@ -67,6 +67,7 @@ NGPhysicalContainerFragment::~NGPhysicalContainerFragment() = default; +// additional_offset must be offset from the containing_block. void NGPhysicalContainerFragment::AddOutlineRectsForNormalChildren( Vector<PhysicalRect>* outline_rects, const PhysicalOffset& additional_offset, @@ -95,6 +96,8 @@ } } +// additional_offset must be offset from the containing_block because +// LocalToAncestorRect returns rects wrt containing_block. void NGPhysicalContainerFragment::AddOutlineRectsForDescendant( const NGLink& descendant, Vector<PhysicalRect>* outline_rects,
diff --git a/third_party/blink/renderer/core/loader/document_loader.cc b/third_party/blink/renderer/core/loader/document_loader.cc index f221589..39f511bb 100644 --- a/third_party/blink/renderer/core/loader/document_loader.cc +++ b/third_party/blink/renderer/core/loader/document_loader.cc
@@ -1603,10 +1603,14 @@ document->Fetcher()->SetStaleWhileRevalidateEnabled( stale_while_revalidate_enabled); - if (EqualIgnoringASCIICase(response_.HttpHeaderField("mixed-content"), - "noupgrade")) { + bool opted_out_mixed_autoupgrade = EqualIgnoringASCIICase( + response_.HttpHeaderField("mixed-content"), "noupgrade"); + + if (opted_out_mixed_autoupgrade) { document->SetMixedAutoupgradeOptOut(true); } + UMA_HISTOGRAM_BOOLEAN("MixedAutoupgrade.Navigation.OptedOut", + opted_out_mixed_autoupgrade); // If stale while revalidate is enabled via Origin Trials count it as such. if (stale_while_revalidate_enabled &&
diff --git a/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.cc b/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.cc index 17f1b01ed7..6ace85bc2 100644 --- a/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.cc +++ b/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.cc
@@ -94,6 +94,7 @@ LogicalRect ExpandSelectionRectToLineHeight( const LogicalRect& rect, const NGPaintFragment& paint_fragment) { + // Compute the rect of the containing line box relative to |paint_fragment|. const NGPaintFragment* current_line = paint_fragment.ContainerLineBox(); DCHECK(current_line); const PhysicalRect line_physical_rect( @@ -102,8 +103,14 @@ current_line->Size()); const LogicalRect line_logical_rect = ComputeLogicalRectFor(line_physical_rect, paint_fragment); - return {{rect.offset.inline_offset, line_logical_rect.offset.block_offset}, - {rect.size.inline_size, line_logical_rect.size.block_size}}; + + // Unite the rect only in the block direction. + LayoutUnit selection_top = + std::min(rect.offset.block_offset, line_logical_rect.offset.block_offset); + LayoutUnit selection_bottom = + std::max(rect.BlockEndOffset(), line_logical_rect.BlockEndOffset()); + return {{rect.offset.inline_offset, selection_top}, + {rect.size.inline_size, selection_bottom - selection_top}}; } LogicalOffset ChildLogicalOffsetInParent(const NGPaintFragment& child) {
diff --git a/third_party/blink/renderer/core/paint/paint_layer.cc b/third_party/blink/renderer/core/paint/paint_layer.cc index e9dd61a..3508bf48 100644 --- a/third_party/blink/renderer/core/paint/paint_layer.cc +++ b/third_party/blink/renderer/core/paint/paint_layer.cc
@@ -3338,11 +3338,22 @@ } float zoom = style.EffectiveZoom(); FloatRect reference_box = BackdropFilterReferenceBox(); + // Tack on regular filter values here - they need to be applied to the + // backdrop image as well, in addition to being applied to the painted content + // and children of the element. This is a bit of a hack - according to the + // spec, filters should apply to the entire render pass as a whole, including + // the backdrop-filtered content. However, because in the case that we have + // both filters and backdrop-filters on a single element, we create two effect + // nodes, and two render surfaces, and the backdrop-filter node comes first. + // To get around that, we add the "regular" filters to the backdrop filters to + // approximate. + FilterOperations filter_operations = style.BackdropFilter(); + filter_operations.Operations().AppendVector(style.Filter().Operations()); // Use kClamp tile mode to avoid pixel moving filters bringing in black // transparent pixels from the viewport edge. return_value = FilterEffectBuilder(reference_box, zoom, nullptr, nullptr, SkBlurImageFilter::kClamp_TileMode) - .BuildFilterOperations(style.BackdropFilter()); + .BuildFilterOperations(filter_operations); DCHECK(!return_value.IsEmpty()); return return_value; }
diff --git a/third_party/blink/renderer/devtools/front_end/Runtime.js b/third_party/blink/renderer/devtools/front_end/Runtime.js index 3aa8650..2b8ac78 100644 --- a/third_party/blink/renderer/devtools/front_end/Runtime.js +++ b/third_party/blink/renderer/devtools/front_end/Runtime.js
@@ -928,6 +928,8 @@ this._experiments = []; this._experimentNames = {}; this._enabledTransiently = {}; + /** @type {!Set<string>} */ + this._serverEnabled = new Set(); } /** @@ -982,6 +984,8 @@ return false; if (this._enabledTransiently[experimentName]) return true; + if (this._serverEnabled.has(experimentName)) + return true; if (!this.supportEnabled()) return false; @@ -1010,6 +1014,16 @@ } /** + * @param {!Array.<string>} experimentNames + */ + setServerEnabledExperiments(experimentNames) { + for (const experiment of experimentNames) { + this._checkExperiment(experiment); + this._serverEnabled.add(experiment); + } + } + + /** * @param {string} experimentName */ enableForTest(experimentName) { @@ -1021,6 +1035,7 @@ this._experiments = []; this._experimentNames = {}; this._enabledTransiently = {}; + this._serverEnabled.clear(); } cleanUpStaleExperiments() {
diff --git a/third_party/blink/renderer/devtools/front_end/components/TargetDetachedDialog.js b/third_party/blink/renderer/devtools/front_end/components/TargetDetachedDialog.js index fd9cc8c9..15e5c5f 100644 --- a/third_party/blink/renderer/devtools/front_end/components/TargetDetachedDialog.js +++ b/third_party/blink/renderer/devtools/front_end/components/TargetDetachedDialog.js
@@ -29,7 +29,7 @@ } static webSocketConnectionLost() { - UI.RemoteDebuggingTerminatedScreen.show('WebSocket disconnected'); + UI.RemoteDebuggingTerminatedScreen.show(ls`WebSocket disconnected`); } /**
diff --git a/third_party/blink/renderer/devtools/front_end/components/components_strings.grdp b/third_party/blink/renderer/devtools/front_end/components/components_strings.grdp index b4506088..599e065 100644 --- a/third_party/blink/renderer/devtools/front_end/components/components_strings.grdp +++ b/third_party/blink/renderer/devtools/front_end/components/components_strings.grdp
@@ -39,6 +39,9 @@ <message name="IDS_DEVTOOLS_d3d2e617335f08df83599665eef8a418" desc=""> Close </message> + <message name="IDS_DEVTOOLS_e3de40c656e1189770049db9846b69df" desc="Text on the remote debugging window to indicate the connection is lost"> + WebSocket disconnected + </message> <message name="IDS_DEVTOOLS_e48081c5f0698efee665fbf8e9d123f9" desc=""> Open using <ph name="TITLE">$1s</ph> </message>
diff --git a/third_party/blink/renderer/devtools/front_end/devices/DevicesView.js b/third_party/blink/renderer/devtools/front_end/devices/DevicesView.js index 002876b..d8f444e9 100644 --- a/third_party/blink/renderer/devtools/front_end/devices/DevicesView.js +++ b/third_party/blink/renderer/devtools/front_end/devices/DevicesView.js
@@ -35,11 +35,11 @@ const discoveryFooter = this.contentElement.createChild('div', 'devices-footer'); this._deviceCountSpan = discoveryFooter.createChild('span'); - discoveryFooter.createChild('span').textContent = Common.UIString(' Read '); - discoveryFooter.appendChild(UI.XLink.create( + const documentationLink = UI.XLink.create( 'https://developers.google.com/chrome-developer-tools/docs/remote-debugging', - Common.UIString('remote debugging documentation'))); - discoveryFooter.createChild('span').textContent = Common.UIString(' for more information.'); + ls`remote debugging documentation`); + discoveryFooter.appendChild( + UI.formatLocalized('%s Read %s for more information.', [this._deviceCountSpan, documentationLink])); this._updateFooter(); this._selectSidebarListItem(this._discoveryListItem, this._discoveryView); @@ -217,10 +217,10 @@ }, false); const help = this.element.createChild('div', 'discovery-help'); - help.createChild('span').textContent = Common.UIString('Need help? Read Chrome '); - help.appendChild(UI.XLink.create( + const documentationLink = UI.XLink.create( 'https://developers.google.com/chrome-developer-tools/docs/remote-debugging', - Common.UIString('remote debugging documentation.'))); + ls`remote debugging documentation`); + help.appendChild(UI.formatLocalized('Need help? Read Chrome %s.', [documentationLink])); /** @type {!Adb.Config} */ this._config; @@ -265,10 +265,12 @@ this._portForwardingEnabledCheckbox.addEventListener('click', this._update.bind(this), false); const portForwardingFooter = this.element.createChild('div', 'port-forwarding-footer'); - portForwardingFooter.createChild('span').textContent = Common.UIString( - 'Define the listening port on your device that maps to a port accessible from your development machine. '); - portForwardingFooter.appendChild(UI.XLink.create( - 'https://developer.chrome.com/devtools/docs/remote-debugging#port-forwarding', Common.UIString('Learn more'))); + const documentationLink = UI.XLink.create( + 'https://developer.chrome.com/devtools/docs/remote-debugging#port-forwarding', + ls`remote debugging documentation`); + portForwardingFooter.appendChild(UI.formatLocalized( + 'Define the listening port on your device that maps to a port accessible from your development machine. Read %s for more.', + [documentationLink])); /** @type {!UI.ListWidget<!Adb.PortForwardingRule>} */ this._list = new UI.ListWidget(this);
diff --git a/third_party/blink/renderer/devtools/front_end/devices/devices_strings.grdp b/third_party/blink/renderer/devtools/front_end/devices/devices_strings.grdp index 87165540..5e60893 100644 --- a/third_party/blink/renderer/devtools/front_end/devices/devices_strings.grdp +++ b/third_party/blink/renderer/devtools/front_end/devices/devices_strings.grdp
@@ -3,6 +3,9 @@ <message name="IDS_DEVTOOLS_00fcbe531dd989e566cab0a9e250f14c" desc=""> Port Forwarding: </message> + <message name="IDS_DEVTOOLS_034fd013261994214d1e8cb42571d191" desc=""> + Need help? Read Chrome <ph name="DOCUMENTATIONLINK">$1s</ph>. + </message> <message name="IDS_DEVTOOLS_03fc5c0bd59679c442b86074c7a7cc3a" desc=""> Port forwarding </message> @@ -21,9 +24,6 @@ <message name="IDS_DEVTOOLS_2157ba7738ed20565fd089f2a6287cdd" desc=""> View less tabs… </message> - <message name="IDS_DEVTOOLS_258771f02f7548d3282560829e7c9b69" desc=""> - Define the listening port on your device that maps to a port accessible from your development machine. ''' - </message> <message name="IDS_DEVTOOLS_2ec0d16e4ca169baedb9b2d50ec5c6d7" desc=""> Connected </message> @@ -51,9 +51,6 @@ <message name="IDS_DEVTOOLS_88183b946cc5f0e8c96b2e66e1c74a7e" desc=""> Unknown </message> - <message name="IDS_DEVTOOLS_8c7074069d61ba9d2f76b078fb1dd154" desc=""> - Need help? Read Chrome ''' - </message> <message name="IDS_DEVTOOLS_926f97ab5b90b053d6a3a31082316f15" desc=""> No browsers detected. </message> @@ -63,12 +60,12 @@ <message name="IDS_DEVTOOLS_9ba01fbecae523e4160afa26f75f1757" desc=""> View more tabs… </message> - <message name="IDS_DEVTOOLS_a105a2ea6a8f53afe9640d8684ffe5d5" desc=""> - ''' Read ''' - </message> <message name="IDS_DEVTOOLS_a2040c5569ac3718b10af77aaa3fbb03" desc=""> Pending authentication: please accept debugging session on the device. </message> + <message name="IDS_DEVTOOLS_bb65fcb8595fb531c5be41fa427d39a0" desc=""> + <ph name="THIS__DEVICECOUNTSPAN">$1s</ph> Read <ph name="DOCUMENTATIONLINK">$2s</ph> for more information. + </message> <message name="IDS_DEVTOOLS_bcca96534b404f08faf65d76be6aa782" desc=""> 1 device detected. </message> @@ -78,15 +75,9 @@ <message name="IDS_DEVTOOLS_c3bf447eabe632720a3aa1a7ce401274" desc=""> Open </message> - <message name="IDS_DEVTOOLS_c9d2bd107ad7a2c20f80efcaaf365d23" desc=""> - ''' for more information. - </message> <message name="IDS_DEVTOOLS_cc63a5ac37dd9d1c607a59aad3292392" desc=""> No rules </message> - <message name="IDS_DEVTOOLS_ceb747e16b7e536d03047492e4491314" desc=""> - remote debugging documentation. - </message> <message name="IDS_DEVTOOLS_d38dcac8af912356e255cbace8984e9a" desc=""> New tab: </message> @@ -99,6 +90,9 @@ <message name="IDS_DEVTOOLS_e24ee2487879116dcab772c0ac4fe341" desc=""> Focus </message> + <message name="IDS_DEVTOOLS_ed725244eec042fa550990c608639b38" desc=""> + Define the listening port on your device that maps to a port accessible from your development machine. Read <ph name="DOCUMENTATIONLINK">$1s</ph> for more. + </message> <message name="IDS_DEVTOOLS_f114563447e4786042d7e7ce05f1157c" desc=""> Device port (3333) </message>
diff --git a/third_party/blink/renderer/devtools/front_end/main/Main.js b/third_party/blink/renderer/devtools/front_end/main/Main.js index 6b0399f..51b662e 100644 --- a/third_party/blink/renderer/devtools/front_end/main/Main.js +++ b/third_party/blink/renderer/devtools/front_end/main/Main.js
@@ -132,6 +132,9 @@ Runtime.experiments.register('timelineWebGL', 'Timeline: WebGL-based flamechart'); Runtime.experiments.cleanUpStaleExperiments(); + const enabledExperiments = Runtime.queryParam('enabledExperiments'); + if (enabledExperiments) + Runtime.experiments.setServerEnabledExperiments(enabledExperiments.split(';')); Runtime.experiments.setDefaultExperiments(['backgroundServices']); if (Host.isUnderTest() && Runtime.queryParam('test').includes('live-line-level-heap-profile.js'))
diff --git a/third_party/blink/renderer/devtools/front_end/perf_ui/FlameChart.js b/third_party/blink/renderer/devtools/front_end/perf_ui/FlameChart.js index 575aa14..5db2780 100644 --- a/third_party/blink/renderer/devtools/front_end/perf_ui/FlameChart.js +++ b/third_party/blink/renderer/devtools/front_end/perf_ui/FlameChart.js
@@ -87,7 +87,10 @@ this._canvas = /** @type {!HTMLCanvasElement} */ (this._viewportElement.createChild('canvas', 'fill')); this._canvas.tabIndex = 0; + UI.ARIAUtils.setAccessibleName(this._canvas, ls`Flame Chart`); + UI.ARIAUtils.markAsTree(this._canvas); this.setDefaultFocusedElement(this._canvas); + this._canvas.classList.add('flame-chart-canvas'); this._canvas.addEventListener('mousemove', this._onMouseMove.bind(this), false); this._canvas.addEventListener('mouseout', this._onMouseOut.bind(this), false); this._canvas.addEventListener('click', this._onClick.bind(this), false); @@ -134,6 +137,10 @@ this._lastMouseOffsetX = 0; this._selectedGroup = -1; + + // Keyboard focused group is used to navigate groups irrespective of whether they are selectable or not + this._keyboardFocusedGroup = -1; + this._selectedGroupBackroundColor = UI.themeSupport.patchColorText( PerfUI.FlameChart.Colors.SelectedGroupBackground, UI.ThemeSupport.ColorUsage.Background); this._selectedGroupBorderColor = UI.themeSupport.patchColorText( @@ -421,7 +428,7 @@ return; this._selectGroup(this._coordinatesToGroupIndex(event.offsetX, event.offsetY, false /* headerOnly */)); - this._toggleGroupVisibility(this._coordinatesToGroupIndex(event.offsetX, event.offsetY, true /* headerOnly */)); + this._toggleGroupExpand(this._coordinatesToGroupIndex(event.offsetX, event.offsetY, true /* headerOnly */)); const timelineData = this._timelineData(); if (event.shiftKey && this._highlightedEntryIndex !== -1 && timelineData) { const start = timelineData.entryStartTimes[this._highlightedEntryIndex]; @@ -437,26 +444,62 @@ * @param {number} groupIndex */ _selectGroup(groupIndex) { - const groups = this._rawTimelineData.groups; - if (groupIndex < 0 || !groups[groupIndex].selectable || this._selectedGroup === groupIndex) + if (groupIndex < 0 || this._selectedGroup === groupIndex) return; + const groups = this._rawTimelineData.groups; + this._keyboardFocusedGroup = groupIndex; + if (!groups[groupIndex].selectable) { + this._deselectAllGroups(); + } else { + this._selectedGroup = groupIndex; + this._flameChartDelegate.updateSelectedGroup(this, groups[groupIndex]); + this._resetCanvas(); + this._draw(); + } + } - this._selectedGroup = groupIndex; - this._flameChartDelegate.updateSelectedGroup(this, groups[groupIndex]); + _deselectAllGroups() { + this._selectedGroup = -1; + this._flameChartDelegate.updateSelectedGroup(this, null); + this._resetCanvas(); + this._draw(); + } + + _deselectAllEntries() { + this._selectedEntryIndex = -1; this._resetCanvas(); this._draw(); } /** + * @param {number} index + */ + _isGroupFocused(index) { + return index === this._selectedGroup || index === this._keyboardFocusedGroup; + } + + /** * @param {number} groupIndex */ - _toggleGroupVisibility(groupIndex) { + _toggleGroupExpand(groupIndex) { + if (groupIndex < 0 || !this._isGroupCollapsible(groupIndex)) + return; + + this._expandGroup(groupIndex, !this._rawTimelineData.groups[groupIndex].expanded /* setExpanded */); + } + + /** + * @param {number} groupIndex + * @param {boolean=} setExpanded + */ + _expandGroup(groupIndex, setExpanded = true) { if (groupIndex < 0 || !this._isGroupCollapsible(groupIndex)) return; const groups = this._rawTimelineData.groups; const group = groups[groupIndex]; - group.expanded = !group.expanded; + group.expanded = setExpanded; + this._groupExpansionState[group.name] = group.expanded; if (this._groupExpansionSetting) this._groupExpansionSetting.set(this._groupExpansionState); @@ -480,20 +523,149 @@ * @param {!Event} e */ _onKeyDown(e) { - this._handleSelectionNavigation(e); + if (!UI.KeyboardShortcut.hasNoModifiers(e) || !this._timelineData()) + return; + + const eventHandled = this._handleSelectionNavigation(e); + + // Handle keyboard navigation in groups + if (!eventHandled && this._rawTimelineData && this._rawTimelineData.groups) + this._handleKeyboardGroupNavigation(e); } /** * @param {!Event} e */ + _handleKeyboardGroupNavigation(e) { + let handled = false; + let entrySelected = false; + + if (e.code === 'ArrowUp') { + handled = this._selectPreviousGroup(); + } else if (e.code === 'ArrowDown') { + handled = this._selectNextGroup(); + } else if (e.code === 'ArrowLeft') { + if (this._keyboardFocusedGroup >= 0) { + this._expandGroup(this._keyboardFocusedGroup, false /* setExpanded */); + handled = true; + } + } else if (e.code === 'ArrowRight') { + if (this._keyboardFocusedGroup >= 0) { + this._expandGroup(this._keyboardFocusedGroup, true /* setExpanded */); + this._selectFirstChild(); + handled = true; + } + } else if (isEnterKey(e)) { + entrySelected = this._selectFirstEntryInCurrentGroup(); + handled = entrySelected; + } + + if (handled && !entrySelected) + this._deselectAllEntries(); + + if (handled) + e.consume(true); + } + + /** + * @return {boolean} + */ + _selectFirstEntryInCurrentGroup() { + const allGroups = this._rawTimelineData.groups; + + if (this._keyboardFocusedGroup < 0) + return false; + + const group = allGroups[this._keyboardFocusedGroup]; + const startLevelInGroup = group.startLevel; + + // Return if no levels in this group + if (startLevelInGroup < 0) + return false; + + // Make sure this is the innermost nested group with this startLevel + // This is because a parent group also contains levels of all its child groups + // So check if the next group has the same level, if it does, user should + // go to that child group to select this entry + if (this._keyboardFocusedGroup < allGroups.length - 1 && + allGroups[this._keyboardFocusedGroup + 1].startLevel === startLevelInGroup) + return false; + + + // Get first (default) entry in startLevel of selected group + const firstEntryIndex = this._timelineLevels[startLevelInGroup][0]; + + this._expandGroup(this._keyboardFocusedGroup, true /* setExpanded */); + this.setSelectedEntry(firstEntryIndex); + return true; + } + + /** + * @return {boolean} + */ + _selectPreviousGroup() { + if (this._keyboardFocusedGroup <= 0) + return false; + + const groupIndexToSelect = this._getGroupIndexToSelect(-1 /* offset */); + this._selectGroup(groupIndexToSelect); + return true; + } + + /** + * @return {boolean} + */ + _selectNextGroup() { + if (this._keyboardFocusedGroup >= this._rawTimelineData.groups.length - 1) + return false; + + const groupIndexToSelect = this._getGroupIndexToSelect(1 /* offset */); + this._selectGroup(groupIndexToSelect); + return true; + } + + /** + * @param {number} offset + * @return {number} + */ + _getGroupIndexToSelect(offset) { + const allGroups = this._rawTimelineData.groups; + let groupIndexToSelect = this._keyboardFocusedGroup; + let groupName, groupWithSubNestingLevel; + + do { + groupIndexToSelect += offset; + groupName = this._rawTimelineData.groups[groupIndexToSelect].name; + groupWithSubNestingLevel = this._keyboardFocusedGroup !== -1 && + allGroups[groupIndexToSelect].style.nestingLevel > allGroups[this._keyboardFocusedGroup].style.nestingLevel; + } while (groupIndexToSelect > 0 && groupIndexToSelect < allGroups.length - 1 && + (!groupName || groupWithSubNestingLevel)); + + return groupIndexToSelect; + } + + _selectFirstChild() { + const allGroups = this._rawTimelineData.groups; + if (this._keyboardFocusedGroup < 0 || this._keyboardFocusedGroup >= allGroups.length - 1) + return; + + const groupIndexToSelect = this._keyboardFocusedGroup + 1; + if (allGroups[groupIndexToSelect].style.nestingLevel > allGroups[this._keyboardFocusedGroup].style.nestingLevel) { + this._selectGroup(groupIndexToSelect); + this._expandGroup(groupIndexToSelect, true /* setExpanded */); + } + } + + /** + * @param {!Event} e + * @return {boolean} + */ _handleSelectionNavigation(e) { - if (!UI.KeyboardShortcut.hasNoModifiers(e)) - return; if (this._selectedEntryIndex === -1) - return; + return false; const timelineData = this._timelineData(); if (!timelineData) - return; + return false; /** * @param {number} time @@ -526,14 +698,16 @@ e.consume(true); if (indexOnLevel >= 0 && indexOnLevel < levelIndexes.length) this.dispatchEventToListeners(PerfUI.FlameChart.Events.EntrySelected, levelIndexes[indexOnLevel]); - return; + return true; } if (e.keyCode === keys.Up.code || e.keyCode === keys.Down.code) { - e.consume(true); let level = timelineData.entryLevels[this._selectedEntryIndex]; level += e.keyCode === keys.Up.code ? -1 : 1; - if (level < 0 || level >= this._timelineLevels.length) - return; + if (level < 0 || level >= this._timelineLevels.length) { + this._deselectAllEntries(); + e.consume(true); + return true; + } const entryTime = timelineData.entryStartTimes[this._selectedEntryIndex] + timelineData.entryTotalTimes[this._selectedEntryIndex] / 2; const levelIndexes = this._timelineLevels[level]; @@ -541,11 +715,21 @@ if (!entriesIntersect(this._selectedEntryIndex, levelIndexes[indexOnLevel])) { ++indexOnLevel; if (indexOnLevel >= levelIndexes.length || - !entriesIntersect(this._selectedEntryIndex, levelIndexes[indexOnLevel])) - return; + !entriesIntersect(this._selectedEntryIndex, levelIndexes[indexOnLevel])) { + if (e.code === 'ArrowDown') + return false; + + // Stay in the current group and give focus to the parent group instead of entries + this._deselectAllEntries(); + e.consume(true); + return true; + } } + e.consume(true); this.dispatchEventToListeners(PerfUI.FlameChart.Events.EntrySelected, levelIndexes[indexOnLevel]); + return true; } + return false; } /** @@ -759,7 +943,7 @@ } else { context.save(); this._forEachGroupInViewport((offset, index, group, isFirst, groupHeight) => { - if (index === this._selectedGroup) { + if (this._isGroupFocused(index)) { context.fillStyle = this._selectedGroupBackroundColor; context.fillRect(0, offset, width, groupHeight - group.style.padding); } @@ -1117,7 +1301,7 @@ if (group.style.useFirstLineForOverview) return; if (!this._isGroupCollapsible(index) || group.expanded) { - if (!group.style.shareHeaderLine && index !== this._selectedGroup) { + if (!group.style.shareHeaderLine && this._isGroupFocused(index)) { context.fillStyle = group.style.backgroundColor; context.fillRect(0, offset, width, group.style.height); } @@ -1137,7 +1321,7 @@ context.font = group.style.font; if (this._isGroupCollapsible(index) && !group.expanded || group.style.shareHeaderLine) { const width = this._labelWidthForGroup(context, group) + 2; - if (index === this._selectedGroup) + if (this._isGroupFocused(index)) context.fillStyle = this._selectedGroupBackroundColor; else context.fillStyle = Common.Color.parse(group.style.backgroundColor).setAlpha(0.8).asString(null); @@ -1169,7 +1353,7 @@ context.stroke(); this._forEachGroupInViewport((offset, index, group, isFirst, groupHeight) => { - if (index === this._selectedGroup) { + if (this._isGroupFocused(index)) { const lineWidth = 2; const bracketLength = 10; context.fillStyle = this._selectedGroupBorderColor; @@ -1451,6 +1635,7 @@ this._entryColorsCache = null; this._rawTimelineDataLength = 0; this._selectedGroup = -1; + this._keyboardFocusedGroup = -1; this._flameChartDelegate.updateSelectedGroup(this, null); return; } @@ -1472,6 +1657,7 @@ levelIndexes[i] = new Uint32Array(entryCounters[i]); entryCounters[i] = 0; } + for (let i = 0; i < timelineData.entryLevels.length; ++i) { const level = timelineData.entryLevels[i]; levelIndexes[level][entryCounters[level]++] = i; @@ -1487,6 +1673,7 @@ this._updateHeight(); this._selectedGroup = timelineData.selectedGroup ? groups.indexOf(timelineData.selectedGroup) : -1; + this._keyboardFocusedGroup = this._selectedGroup; this._flameChartDelegate.updateSelectedGroup(this, timelineData.selectedGroup); }
diff --git a/third_party/blink/renderer/devtools/front_end/perf_ui/flameChart.css b/third_party/blink/renderer/devtools/front_end/perf_ui/flameChart.css index 7c085e5..d4dfb43f 100644 --- a/third_party/blink/renderer/devtools/front_end/perf_ui/flameChart.css +++ b/third_party/blink/renderer/devtools/front_end/perf_ui/flameChart.css
@@ -18,6 +18,11 @@ display: block; } +.flame-chart-canvas[data-keyboard-focus="true"]:focus { + border-top: 1px solid var(--accent-color); + border-bottom: 1px solid var(--accent-color); +} + .flame-chart-highlight-element { position: absolute; pointer-events: none;
diff --git a/third_party/blink/renderer/devtools/front_end/perf_ui/perf_ui_strings.grdp b/third_party/blink/renderer/devtools/front_end/perf_ui/perf_ui_strings.grdp index d38f94e0..ad4a52c6 100644 --- a/third_party/blink/renderer/devtools/front_end/perf_ui/perf_ui_strings.grdp +++ b/third_party/blink/renderer/devtools/front_end/perf_ui/perf_ui_strings.grdp
@@ -33,6 +33,9 @@ <message name="IDS_DEVTOOLS_77c168e60d966216cd1261c200f87e27" desc=""> Show live memory allocation annotations </message> + <message name="IDS_DEVTOOLS_85386891ddce057fa25f92fe4ad28190" desc=""> + Flame Chart + </message> <message name="IDS_DEVTOOLS_87f8a6ab85c9ced3702b4ea641ad4bb5" desc=""> Medium </message>
diff --git a/third_party/blink/renderer/devtools/front_end/sources/DebuggerPausedMessage.js b/third_party/blink/renderer/devtools/front_end/sources/DebuggerPausedMessage.js index f70671d..282cdb98 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/DebuggerPausedMessage.js +++ b/third_party/blink/renderer/devtools/front_end/sources/DebuggerPausedMessage.js
@@ -42,8 +42,8 @@ const mainElement = messageWrapper.createChild('div', 'status-main'); mainElement.appendChild(UI.Icon.create('smallicon-info', 'status-icon')); - mainElement.appendChild(createTextNode( - String.sprintf('Paused on %s', Sources.DebuggerPausedMessage.BreakpointTypeNouns.get(data.type)))); + const breakpointType = Sources.DebuggerPausedMessage.BreakpointTypeNouns.get(data.type); + mainElement.appendChild(createTextNode(ls`Paused on ${breakpointType}`)); const subElement = messageWrapper.createChild('div', 'status-sub monospace'); const linkifiedNode = await Common.Linkifier.linkify(data.node); @@ -51,13 +51,17 @@ if (data.targetNode) { const targetNodeLink = await Common.Linkifier.linkify(data.targetNode); - let message; - if (data.insertion) - message = data.targetNode === data.node ? 'Child %s added' : 'Descendant %s added'; - else - message = 'Descendant %s removed'; + let messageElement; + if (data.insertion) { + if (data.targetNode === data.node) + messageElement = UI.formatLocalized('Child %s added', [targetNodeLink]); + else + messageElement = UI.formatLocalized('Descendant %s added', [targetNodeLink]); + } else { + messageElement = UI.formatLocalized('Descendant %s removed', [targetNodeLink]); + } subElement.appendChild(createElement('br')); - subElement.appendChild(UI.formatLocalized(message, [targetNodeLink])); + subElement.appendChild(messageElement); } return messageWrapper; }
diff --git a/third_party/blink/renderer/devtools/front_end/sources/sources_strings.grdp b/third_party/blink/renderer/devtools/front_end/sources/sources_strings.grdp index 122cbf6..ca62f1c0 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/sources_strings.grdp +++ b/third_party/blink/renderer/devtools/front_end/sources/sources_strings.grdp
@@ -84,6 +84,9 @@ <message name="IDS_DEVTOOLS_30e71ab6fb45b9773731a0af4d7fb3b4" desc=""> Do not show whitespace characters </message> + <message name="IDS_DEVTOOLS_31e8c8e899cef6cd6751e92daf6ff6d5" desc="Text in the JavaScript Debugging pane of the Sources pane when a DOM breakpoint is hit because a child is added to the subtree"> + Child <ph name="TARGETNODELINK">$1s</ph> added + </message> <message name="IDS_DEVTOOLS_327cbc7239d92013006f601d8b9aff8f" desc=""> Remove folder from workspace </message> @@ -453,6 +456,9 @@ <message name="IDS_DEVTOOLS_ed5eceb0fe85ceeeabf4b4b93eeca711" desc=""> Continue to here </message> + <message name="IDS_DEVTOOLS_f0044321a791b3a9942860e8df9d8bea" desc="Text in the JavaScript Debugging pane of the Sources pane when a DOM breakpoint is hit because a descendant is added"> + Descendant <ph name="TARGETNODELINK">$1s</ph> added + </message> <message name="IDS_DEVTOOLS_f0a47f037ca7a988466a647277ef1134" desc=""> Paused on assertion </message> @@ -468,9 +474,15 @@ <message name="IDS_DEVTOOLS_f515d5945239e7a61fa267bd058134f1" desc=""> Add folder to workspace </message> + <message name="IDS_DEVTOOLS_f6acaaac4875e10151fa08b8d01e0b98" desc="Text in the JavaScript Debugging pane of the Sources pane when a DOM breakpoint is hit"> + Paused on <ph name="BREAKPOINTTYPE">$1s</ph> + </message> <message name="IDS_DEVTOOLS_f96985d765ed09d4930d76a3ca869508" desc=""> Terminate current JavaScript call </message> + <message name="IDS_DEVTOOLS_fada802796e35f867c2b3f605982b21d" desc="Text in the JavaScript Debugging pane of the Sources pane when a DOM breakpoint is hit because a descendant is removed"> + Descendant <ph name="TARGETNODELINK">$1s</ph> removed + </message> <message name="IDS_DEVTOOLS_fd1be3efcf102a4183d9445d789574f4" desc=""> Are you sure you want to delete this file? </message>
diff --git a/third_party/blink/renderer/devtools/front_end/ui/RemoteDebuggingTerminatedScreen.js b/third_party/blink/renderer/devtools/front_end/ui/RemoteDebuggingTerminatedScreen.js index 043370d2..7205897 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/RemoteDebuggingTerminatedScreen.js +++ b/third_party/blink/renderer/devtools/front_end/ui/RemoteDebuggingTerminatedScreen.js
@@ -10,8 +10,9 @@ super(true); this.registerRequiredCSS('ui/remoteDebuggingTerminatedScreen.css'); const message = this.contentElement.createChild('div', 'message'); - message.createChild('span').textContent = Common.UIString('Debugging connection was closed. Reason: '); - message.createChild('span', 'reason').textContent = reason; + const reasonElement = message.createChild('span', 'reason'); + reasonElement.textContent = reason; + message.appendChild(UI.formatLocalized('Debugging connection was closed. Reason: %s', [reasonElement])); this.contentElement.createChild('div', 'message').textContent = Common.UIString('Reconnect when ready by reopening DevTools.'); const button = UI.createTextButton(Common.UIString('Reconnect DevTools'), () => window.location.reload());
diff --git a/third_party/blink/renderer/devtools/front_end/ui/ui_strings.grdp b/third_party/blink/renderer/devtools/front_end/ui/ui_strings.grdp index 3b5ef3b..97adc072ec 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/ui_strings.grdp +++ b/third_party/blink/renderer/devtools/front_end/ui/ui_strings.grdp
@@ -81,6 +81,9 @@ <message name="IDS_DEVTOOLS_44ac014b674d7d86a04702e6fd1fa858" desc=""> Reconnect when ready by reopening DevTools. </message> + <message name="IDS_DEVTOOLS_471566447bf928c469d32014791036cc" desc=""> + Debugging connection was closed. Reason: <ph name="REASONELEMENT">$1s</ph> + </message> <message name="IDS_DEVTOOLS_47df0ee8f6dc4f553c907c49e686216c" desc=""> Memory Panel </message> @@ -108,9 +111,6 @@ <message name="IDS_DEVTOOLS_52ebc26c2921d5b84fc670dff9891821" desc=""> Zoom out </message> - <message name="IDS_DEVTOOLS_534d1b2eaff704d4888de7c4a5e282c0" desc=""> - Debugging connection was closed. Reason: ''' - </message> <message name="IDS_DEVTOOLS_5372591390f99dcf8e0467c671abbc23" desc=""> Switch to rotate mode </message>
diff --git a/third_party/blink/renderer/modules/BUILD.gn b/third_party/blink/renderer/modules/BUILD.gn index 4ea796ad..0e3eeb4 100644 --- a/third_party/blink/renderer/modules/BUILD.gn +++ b/third_party/blink/renderer/modules/BUILD.gn
@@ -329,6 +329,9 @@ "mediarecorder/audio_track_recorder_unittest.cc", "mediastream/media_constraints_test.cc", "mediastream/media_devices_test.cc", + "mediastream/media_stream_constraints_util_sets_test.cc", + "mediastream/media_stream_constraints_util_test.cc", + "mediastream/media_stream_constraints_util_video_device_test.cc", "mediastream/media_stream_video_capturer_source_test.cc", "mediastream/media_stream_video_renderer_sink_test.cc", "mediastream/mock_mojo_media_stream_dispatcher_host.cc", @@ -429,6 +432,7 @@ "//skia", "//testing/gmock", "//testing/gtest", + "//third_party/blink/public:blink_headers", "//third_party/blink/renderer/core", "//third_party/blink/renderer/modules/gamepad:unit_tests", "//third_party/blink/renderer/modules/storage:unit_tests",
diff --git a/third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.cc b/third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.cc index 59505bb..54f052a 100644 --- a/third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.cc +++ b/third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.cc
@@ -1108,40 +1108,13 @@ image_flags.setImageFilter(nullptr); } - if (!image_source->IsVideoElement()) { - image_flags.setAntiAlias(ShouldDrawImageAntialiased(dst_rect)); - image->Draw(c, image_flags, dst_rect, src_rect, - kDoNotRespectImageOrientation, - Image::kDoNotClampImageToSourceRect, Image::kSyncDecode); - } else { - c->save(); - c->clipRect(dst_rect); - c->translate(dst_rect.X(), dst_rect.Y()); - c->scale(dst_rect.Width() / src_rect.Width(), - dst_rect.Height() / src_rect.Height()); - c->translate(-src_rect.X(), -src_rect.Y()); - HTMLVideoElement* video = static_cast<HTMLVideoElement*>(image_source); - video->PaintCurrentFrame( - c, - IntRect(IntPoint(), IntSize(video->videoWidth(), video->videoHeight())), - &image_flags); - } + image_flags.setAntiAlias(ShouldDrawImageAntialiased(dst_rect)); + image->Draw(c, image_flags, dst_rect, src_rect, kDoNotRespectImageOrientation, + Image::kDoNotClampImageToSourceRect, Image::kSyncDecode); c->restoreToCount(initial_save_count); } -bool ShouldDisableDeferral(CanvasImageSource* image_source, - DisableDeferralReason* reason) { - DCHECK(reason); - DCHECK_EQ(*reason, kDisableDeferralReasonUnknown); - - if (image_source->IsVideoElement()) { - *reason = kDisableDeferralReasonDrawImageOfVideo; - return true; - } - return false; -} - void BaseRenderingContext2D::SetOriginTaintedByContent() { SetOriginTainted(); origin_tainted_by_content_ = true; @@ -1168,22 +1141,17 @@ scoped_refptr<Image> image; FloatSize default_object_size(Width(), Height()); SourceImageStatus source_image_status = kInvalidSourceImageStatus; - if (!image_source->IsVideoElement()) { - AccelerationHint hint = - IsAccelerated() ? kPreferAcceleration : kPreferNoAcceleration; - image = image_source->GetSourceImageForCanvas(&source_image_status, hint, - default_object_size); - if (source_image_status == kUndecodableSourceImageStatus) { - exception_state.ThrowDOMException( - DOMExceptionCode::kInvalidStateError, - "The HTMLImageElement provided is in the 'broken' state."); - } - if (!image || !image->width() || !image->height()) - return; - } else { - if (!static_cast<HTMLVideoElement*>(image_source)->HasAvailableVideoFrame()) - return; + AccelerationHint hint = + IsAccelerated() ? kPreferAcceleration : kPreferNoAcceleration; + image = image_source->GetSourceImageForCanvas(&source_image_status, hint, + default_object_size); + if (source_image_status == kUndecodableSourceImageStatus) { + exception_state.ThrowDOMException( + DOMExceptionCode::kInvalidStateError, + "The HTMLImageElement provided is in the 'broken' state."); } + if (!image || !image->width() || !image->height()) + return; if (!std::isfinite(dx) || !std::isfinite(dy) || !std::isfinite(dw) || !std::isfinite(dh) || !std::isfinite(sx) || !std::isfinite(sy) || @@ -1212,10 +1180,6 @@ if (src_rect.IsEmpty()) return; - DisableDeferralReason reason = kDisableDeferralReasonUnknown; - if (ShouldDisableDeferral(image_source, &reason)) - DisableDeferral(reason); - ValidateStateStack(); WillDrawImage(image_source);
diff --git a/third_party/blink/renderer/modules/mediasession/media_session.cc b/third_party/blink/renderer/modules/mediasession/media_session.cc index 9e2b5a2..eb91016a 100644 --- a/third_party/blink/renderer/modules/mediasession/media_session.cc +++ b/third_party/blink/renderer/modules/mediasession/media_session.cc
@@ -37,6 +37,7 @@ DEFINE_STATIC_LOCAL(const AtomicString, seek_forward_action_name, ("seekforward")); DEFINE_STATIC_LOCAL(const AtomicString, skip_ad_action_name, ("skipad")); + DEFINE_STATIC_LOCAL(const AtomicString, stop_action_name, ("stop")); switch (action) { case MediaSessionAction::kPlay: @@ -53,6 +54,8 @@ return seek_forward_action_name; case MediaSessionAction::kSkipAd: return skip_ad_action_name; + case MediaSessionAction::kStop: + return stop_action_name; default: NOTREACHED(); } @@ -75,6 +78,8 @@ return MediaSessionAction::kSeekForward; if ("skipad" == action_name) return MediaSessionAction::kSkipAd; + if ("stop" == action_name) + return MediaSessionAction::kStop; NOTREACHED(); return base::nullopt;
diff --git a/third_party/blink/renderer/modules/mediasession/media_session.idl b/third_party/blink/renderer/modules/mediasession/media_session.idl index ac749c036f..9ba8c54 100644 --- a/third_party/blink/renderer/modules/mediasession/media_session.idl +++ b/third_party/blink/renderer/modules/mediasession/media_session.idl
@@ -20,6 +20,7 @@ "seekbackward", "seekforward", "skipad", + "stop", }; callback MediaSessionActionHandler = void ();
diff --git a/third_party/blink/renderer/modules/mediastream/BUILD.gn b/third_party/blink/renderer/modules/mediastream/BUILD.gn index 4796be7..0b0f64f 100644 --- a/third_party/blink/renderer/modules/mediastream/BUILD.gn +++ b/third_party/blink/renderer/modules/mediastream/BUILD.gn
@@ -61,6 +61,7 @@ testonly = true sources = [ + "mock_constraint_factory.cc", "mock_media_stream_registry.cc", "mock_media_stream_video_source.cc", ]
diff --git a/content/renderer/media/stream/media_stream_constraints_util_sets_unittest.cc b/third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_sets_test.cc similarity index 93% rename from content/renderer/media/stream/media_stream_constraints_util_sets_unittest.cc rename to third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_sets_test.cc index 6541e7f2..947270b 100644 --- a/content/renderer/media/stream/media_stream_constraints_util_sets_unittest.cc +++ b/third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_sets_test.cc
@@ -8,16 +8,16 @@ #include <string> #include <vector> -#include "content/renderer/media/stream/mock_constraint_factory.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/web_media_stream_track.h" +#include "third_party/blink/public/web/modules/mediastream/mock_constraint_factory.h" -namespace content { +namespace blink { namespace media_constraints { -using blink::media_constraints::ResolutionSet; +using media_constraints::ResolutionSet; using Point = ResolutionSet::Point; -using BoolSet = blink::media_constraints::DiscreteSet<bool>; +using BoolSet = media_constraints::DiscreteSet<bool>; namespace { @@ -1153,7 +1153,7 @@ } TEST_F(MediaStreamConstraintsUtilSetsTest, NumericRangeSetDouble) { - using DoubleRangeSet = blink::media_constraints::NumericRangeSet<double>; + using DoubleRangeSet = media_constraints::NumericRangeSet<double>; // Open set. DoubleRangeSet set; EXPECT_FALSE(set.Min().has_value()); @@ -1220,11 +1220,10 @@ TEST_F(MediaStreamConstraintsUtilSetsTest, NumericRangeSetFromConstraint) { // Exact value translates in a range with a single value. - blink::LongConstraint constraint = blink::LongConstraint("aConstraint"); + LongConstraint constraint = LongConstraint("aConstraint"); constraint.SetExact(10); - blink::media_constraints::NumericRangeSet<int> range = - blink::media_constraints::NumericRangeSet<int>::FromConstraint( - constraint); + media_constraints::NumericRangeSet<int> range = + media_constraints::NumericRangeSet<int>::FromConstraint(constraint); EXPECT_FALSE(range.IsEmpty()); EXPECT_TRUE(range.Min()); EXPECT_EQ(*range.Min(), 10); @@ -1233,11 +1232,10 @@ // A constraint with min and max translates to range with same min and same // max. - constraint = blink::LongConstraint("aConstraint"); + constraint = LongConstraint("aConstraint"); constraint.SetMin(0); constraint.SetMax(100); - range = blink::media_constraints::NumericRangeSet<int>::FromConstraint( - constraint); + range = media_constraints::NumericRangeSet<int>::FromConstraint(constraint); EXPECT_FALSE(range.IsEmpty()); EXPECT_TRUE(range.Min()); EXPECT_EQ(*range.Min(), 0); @@ -1246,28 +1244,25 @@ // A constraint with only a min or a max value translates to a half-bounded // set in both cases. - constraint = blink::LongConstraint("aConstraint"); + constraint = LongConstraint("aConstraint"); constraint.SetMin(0); - range = blink::media_constraints::NumericRangeSet<int>::FromConstraint( - constraint); + range = media_constraints::NumericRangeSet<int>::FromConstraint(constraint); EXPECT_FALSE(range.IsEmpty()); EXPECT_TRUE(range.Min()); EXPECT_EQ(*range.Min(), 0); EXPECT_FALSE(range.Max()); - constraint = blink::LongConstraint("aConstraint"); + constraint = LongConstraint("aConstraint"); constraint.SetMax(100); - range = blink::media_constraints::NumericRangeSet<int>::FromConstraint( - constraint); + range = media_constraints::NumericRangeSet<int>::FromConstraint(constraint); EXPECT_FALSE(range.IsEmpty()); EXPECT_TRUE(range.Max()); EXPECT_EQ(*range.Max(), 100); EXPECT_FALSE(range.Min()); // A constraint with no values specified maps to an unbounded range. - constraint = blink::LongConstraint("aConstraint"); - range = blink::media_constraints::NumericRangeSet<int>::FromConstraint( - constraint); + constraint = LongConstraint("aConstraint"); + range = media_constraints::NumericRangeSet<int>::FromConstraint(constraint); EXPECT_FALSE(range.IsEmpty()); EXPECT_FALSE(range.Min()); EXPECT_FALSE(range.Max()); @@ -1278,10 +1273,10 @@ int upper_bound = 25; int lower_bound = 5; // Exact value translates in a range with a single value. - blink::LongConstraint constraint = blink::LongConstraint("aConstraint"); + LongConstraint constraint = LongConstraint("aConstraint"); constraint.SetExact(10); - blink::media_constraints::NumericRangeSet<int> range = - blink::media_constraints::NumericRangeSet<int>::FromConstraint( + media_constraints::NumericRangeSet<int> range = + media_constraints::NumericRangeSet<int>::FromConstraint( constraint, lower_bound, upper_bound); EXPECT_FALSE(range.IsEmpty()); EXPECT_TRUE(range.Min()); @@ -1292,17 +1287,17 @@ // A constraint with min and max translates to range with same min and same // max. If lower and upper bound do not permit that, will have unspecified // min and max respectively. - constraint = blink::LongConstraint("aConstraint"); + constraint = LongConstraint("aConstraint"); constraint.SetMin(0); constraint.SetMax(100); - range = blink::media_constraints::NumericRangeSet<int>::FromConstraint( - constraint, 0, 100); + range = media_constraints::NumericRangeSet<int>::FromConstraint(constraint, 0, + 100); EXPECT_FALSE(range.IsEmpty()); EXPECT_TRUE(range.Min()); EXPECT_EQ(*range.Min(), 0); EXPECT_TRUE(range.Max()); EXPECT_EQ(*range.Max(), 100); - range = blink::media_constraints::NumericRangeSet<int>::FromConstraint( + range = media_constraints::NumericRangeSet<int>::FromConstraint( constraint, lower_bound, upper_bound); EXPECT_FALSE(range.IsEmpty()); EXPECT_FALSE(range.Min()); @@ -1311,17 +1306,17 @@ // A constraint with only a min or a max value translates to a half-bounded // or unbounded range depending on the whether the lower and the upper bounds // allow for it. - constraint = blink::LongConstraint("aConstraint"); + constraint = LongConstraint("aConstraint"); constraint.SetMin(0); - range = blink::media_constraints::NumericRangeSet<int>::FromConstraint( + range = media_constraints::NumericRangeSet<int>::FromConstraint( constraint, lower_bound, upper_bound); EXPECT_FALSE(range.IsEmpty()); EXPECT_FALSE(range.Min()); EXPECT_FALSE(range.Max()); - constraint = blink::LongConstraint("aConstraint"); + constraint = LongConstraint("aConstraint"); constraint.SetMax(100); - range = blink::media_constraints::NumericRangeSet<int>::FromConstraint( + range = media_constraints::NumericRangeSet<int>::FromConstraint( constraint, lower_bound, upper_bound); EXPECT_FALSE(range.IsEmpty()); EXPECT_FALSE(range.Min()); @@ -1329,8 +1324,8 @@ // A constraint with no values specified maps to an unbounded range // independently of upper and lower bounds. - constraint = blink::LongConstraint("aConstraint"); - range = blink::media_constraints::NumericRangeSet<int>::FromConstraint( + constraint = LongConstraint("aConstraint"); + range = media_constraints::NumericRangeSet<int>::FromConstraint( constraint, lower_bound, upper_bound); EXPECT_FALSE(range.IsEmpty()); EXPECT_FALSE(range.Min()); @@ -1338,17 +1333,17 @@ // If the constraint specifies a range that does not overlap with lower and // upper bounds, the resulting range will be empty. - constraint = blink::LongConstraint("aConstraint"); + constraint = LongConstraint("aConstraint"); constraint.SetMin(-5); constraint.SetMax(0); - range = blink::media_constraints::NumericRangeSet<int>::FromConstraint( + range = media_constraints::NumericRangeSet<int>::FromConstraint( constraint, lower_bound, upper_bound); EXPECT_TRUE(range.IsEmpty()); - constraint = blink::LongConstraint("aConstraint"); + constraint = LongConstraint("aConstraint"); constraint.SetMin(105); constraint.SetMax(110); - range = blink::media_constraints::NumericRangeSet<int>::FromConstraint( + range = media_constraints::NumericRangeSet<int>::FromConstraint( constraint, lower_bound, upper_bound); EXPECT_TRUE(range.IsEmpty()); } @@ -1356,7 +1351,7 @@ TEST_F(MediaStreamConstraintsUtilSetsTest, NumericRangeSetFromValue) { // Getting a range from a single value, will return a range with a single // value set as both max and min. - auto range = blink::media_constraints::NumericRangeSet<int>::FromValue(0); + auto range = media_constraints::NumericRangeSet<int>::FromValue(0); EXPECT_FALSE(range.IsEmpty()); EXPECT_TRUE(range.Min()); EXPECT_EQ(*range.Min(), 0); @@ -1366,7 +1361,7 @@ TEST_F(MediaStreamConstraintsUtilSetsTest, DiscreteSetString) { // Universal set. - using StringSet = blink::media_constraints::DiscreteSet<std::string>; + using StringSet = media_constraints::DiscreteSet<std::string>; StringSet set = StringSet::UniversalSet(); EXPECT_TRUE(set.Contains("arbitrary")); EXPECT_TRUE(set.Contains("strings")); @@ -1515,55 +1510,53 @@ TEST_F(MediaStreamConstraintsUtilSetsTest, RescaleSetFromConstraints) { factory_.Reset(); factory_.CreateWebMediaConstraints(); - BoolSet set = blink::media_constraints::RescaleSetFromConstraint( - factory_.basic().resize_mode); + BoolSet set = + media_constraints::RescaleSetFromConstraint(factory_.basic().resize_mode); EXPECT_TRUE(set.is_universal()); EXPECT_FALSE(set.HasExplicitElements()); // Invalid exact value. - factory_.basic().resize_mode.SetExact( - {blink::WebString::FromASCII("invalid")}); - set = blink::media_constraints::RescaleSetFromConstraint( - factory_.basic().resize_mode); + factory_.basic().resize_mode.SetExact({WebString::FromASCII("invalid")}); + set = + media_constraints::RescaleSetFromConstraint(factory_.basic().resize_mode); EXPECT_TRUE(set.IsEmpty()); // No rescaling factory_.basic().resize_mode.SetExact( - blink::WebString::FromASCII(blink::WebMediaStreamTrack::kResizeModeNone)); - set = blink::media_constraints::RescaleSetFromConstraint( - factory_.basic().resize_mode); + WebString::FromASCII(WebMediaStreamTrack::kResizeModeNone)); + set = + media_constraints::RescaleSetFromConstraint(factory_.basic().resize_mode); EXPECT_TRUE(set.Contains(false)); EXPECT_FALSE(set.Contains(true)); // Rescaling - factory_.basic().resize_mode.SetExact(blink::WebString::FromASCII( - blink::WebMediaStreamTrack::kResizeModeRescale)); - set = blink::media_constraints::RescaleSetFromConstraint( - factory_.basic().resize_mode); + factory_.basic().resize_mode.SetExact( + WebString::FromASCII(WebMediaStreamTrack::kResizeModeRescale)); + set = + media_constraints::RescaleSetFromConstraint(factory_.basic().resize_mode); EXPECT_TRUE(set.Contains(true)); EXPECT_FALSE(set.Contains(false)); // Both explicit - blink::WebString rescale_modes[] = { - blink::WebString::FromASCII( - blink::WebMediaStreamTrack::kResizeModeRescale), - blink::WebString::FromASCII(blink::WebMediaStreamTrack::kResizeModeNone)}; - factory_.basic().resize_mode.SetExact(blink::WebVector<blink::WebString>( - rescale_modes, base::size(rescale_modes))); - set = blink::media_constraints::RescaleSetFromConstraint( - factory_.basic().resize_mode); + WebString rescale_modes[] = { + WebString::FromASCII(WebMediaStreamTrack::kResizeModeRescale), + WebString::FromASCII(WebMediaStreamTrack::kResizeModeNone)}; + factory_.basic().resize_mode.SetExact( + WebVector<WebString>(rescale_modes, base::size(rescale_modes))); + set = + media_constraints::RescaleSetFromConstraint(factory_.basic().resize_mode); EXPECT_TRUE(set.Contains(true)); EXPECT_TRUE(set.Contains(false)); // Invalid and no rescaling. rescale_modes[0] = "invalid"; - factory_.basic().resize_mode.SetExact(blink::WebVector<blink::WebString>( - rescale_modes, base::size(rescale_modes))); - set = blink::media_constraints::RescaleSetFromConstraint( - factory_.basic().resize_mode); + factory_.basic().resize_mode.SetExact( + WebVector<WebString>(rescale_modes, base::size(rescale_modes))); + set = + media_constraints::RescaleSetFromConstraint(factory_.basic().resize_mode); EXPECT_FALSE(set.Contains(true)); EXPECT_TRUE(set.Contains(false)); } } // namespace media_constraints -} // namespace content +} // namespace blink
diff --git a/content/renderer/media/stream/media_stream_constraints_util_unittest.cc b/third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_test.cc similarity index 94% rename from content/renderer/media/stream/media_stream_constraints_util_unittest.cc rename to third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_test.cc index d5c42b71..18188fff1 100644 --- a/content/renderer/media/stream/media_stream_constraints_util_unittest.cc +++ b/third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_test.cc
@@ -4,13 +4,13 @@ #include <string> -#include "content/renderer/media/stream/mock_constraint_factory.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/modules/mediastream/media_stream_audio_processor_options.h" #include "third_party/blink/public/web/modules/mediastream/media_stream_constraints_util.h" #include "third_party/blink/public/web/modules/mediastream/media_stream_constraints_util_sets.h" +#include "third_party/blink/public/web/modules/mediastream/mock_constraint_factory.h" -namespace content { +namespace blink { namespace { @@ -20,10 +20,10 @@ static_cast<double>(kSourceWidth) / static_cast<double>(kSourceHeight); constexpr double kSourceFrameRate = 100.0; -blink::VideoTrackAdapterSettings SelectTrackSettings( - const blink::WebMediaTrackConstraintSet& basic_constraint_set, - const blink::media_constraints::ResolutionSet& resolution_set, - const blink::media_constraints::NumericRangeSet<double>& frame_rate_set, +VideoTrackAdapterSettings SelectTrackSettings( + const WebMediaTrackConstraintSet& basic_constraint_set, + const media_constraints::ResolutionSet& resolution_set, + const media_constraints::NumericRangeSet<double>& frame_rate_set, bool enable_rescale = true) { media::VideoCaptureFormat source_format( gfx::Size(kSourceWidth, kSourceHeight), kSourceFrameRate, @@ -37,8 +37,8 @@ class MediaStreamConstraintsUtilTest : public testing::Test { protected: - using DoubleRangeSet = blink::media_constraints::NumericRangeSet<double>; - using ResolutionSet = blink::media_constraints::ResolutionSet; + using DoubleRangeSet = media_constraints::NumericRangeSet<double>; + using ResolutionSet = media_constraints::ResolutionSet; }; TEST_F(MediaStreamConstraintsUtilTest, BooleanConstraints) { @@ -49,15 +49,15 @@ // Mandatory constraints. constraint_factory.basic().echo_cancellation.SetExact(true); constraint_factory.basic().goog_echo_cancellation.SetExact(false); - blink::WebMediaConstraints constraints = + WebMediaConstraints constraints = constraint_factory.CreateWebMediaConstraints(); bool value_true = false; bool value_false = false; EXPECT_TRUE(GetConstraintValueAsBoolean( - constraints, &blink::WebMediaTrackConstraintSet::echo_cancellation, + constraints, &WebMediaTrackConstraintSet::echo_cancellation, &value_true)); EXPECT_TRUE(GetConstraintValueAsBoolean( - constraints, &blink::WebMediaTrackConstraintSet::goog_echo_cancellation, + constraints, &WebMediaTrackConstraintSet::goog_echo_cancellation, &value_false)); EXPECT_TRUE(value_true); EXPECT_FALSE(value_false); @@ -68,10 +68,10 @@ constraint_factory.AddAdvanced().goog_echo_cancellation.SetExact(true); constraints = constraint_factory.CreateWebMediaConstraints(); EXPECT_TRUE(GetConstraintValueAsBoolean( - constraints, &blink::WebMediaTrackConstraintSet::echo_cancellation, + constraints, &WebMediaTrackConstraintSet::echo_cancellation, &value_false)); EXPECT_TRUE(GetConstraintValueAsBoolean( - constraints, &blink::WebMediaTrackConstraintSet::goog_echo_cancellation, + constraints, &WebMediaTrackConstraintSet::goog_echo_cancellation, &value_true)); EXPECT_TRUE(value_true); EXPECT_FALSE(value_false); @@ -82,7 +82,7 @@ constraint_factory.basic().echo_cancellation.SetExact(true); constraints = constraint_factory.CreateWebMediaConstraints(); EXPECT_TRUE(GetConstraintValueAsBoolean( - constraints, &blink::WebMediaTrackConstraintSet::echo_cancellation, + constraints, &WebMediaTrackConstraintSet::echo_cancellation, &value_true)); EXPECT_TRUE(value_true); } @@ -92,14 +92,14 @@ const double test_value = 0.01f; constraint_factory.basic().aspect_ratio.SetExact(test_value); - blink::WebMediaConstraints constraints = + WebMediaConstraints constraints = constraint_factory.CreateWebMediaConstraints(); double value; EXPECT_FALSE(GetConstraintValueAsDouble( - constraints, &blink::WebMediaTrackConstraintSet::frame_rate, &value)); + constraints, &WebMediaTrackConstraintSet::frame_rate, &value)); EXPECT_TRUE(GetConstraintValueAsDouble( - constraints, &blink::WebMediaTrackConstraintSet::aspect_ratio, &value)); + constraints, &WebMediaTrackConstraintSet::aspect_ratio, &value)); EXPECT_EQ(test_value, value); } @@ -108,20 +108,20 @@ const int test_value = 327; constraint_factory.basic().width.SetExact(test_value); - blink::WebMediaConstraints constraints = + WebMediaConstraints constraints = constraint_factory.CreateWebMediaConstraints(); int value; EXPECT_TRUE(GetConstraintValueAsInteger( - constraints, &blink::WebMediaTrackConstraintSet::width, &value)); + constraints, &WebMediaTrackConstraintSet::width, &value)); EXPECT_EQ(test_value, value); // An exact value should also be reflected as min and max. EXPECT_TRUE(GetConstraintMaxAsInteger( - constraints, &blink::WebMediaTrackConstraintSet::width, &value)); + constraints, &WebMediaTrackConstraintSet::width, &value)); EXPECT_EQ(test_value, value); EXPECT_TRUE(GetConstraintMinAsInteger( - constraints, &blink::WebMediaTrackConstraintSet::width, &value)); + constraints, &WebMediaTrackConstraintSet::width, &value)); EXPECT_EQ(test_value, value); } @@ -723,4 +723,4 @@ } } -} // namespace content +} // namespace blink
diff --git a/content/renderer/media/stream/media_stream_constraints_util_video_device_unittest.cc b/third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_video_device_test.cc similarity index 90% rename from content/renderer/media/stream/media_stream_constraints_util_video_device_unittest.cc rename to third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_video_device_test.cc index f91d916f..b37e9a5 100644 --- a/content/renderer/media/stream/media_stream_constraints_util_video_device_unittest.cc +++ b/third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_video_device_test.cc
@@ -9,15 +9,13 @@ #include "base/optional.h" #include "base/stl_util.h" -#include "content/renderer/media/stream/mock_constraint_factory.h" #include "media/base/limits.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/web_media_constraints.h" #include "third_party/blink/public/web/modules/mediastream/media_stream_video_source.h" +#include "third_party/blink/public/web/modules/mediastream/mock_constraint_factory.h" -namespace content { - -using blink::MediaStreamVideoSource; +namespace blink { namespace { @@ -34,7 +32,7 @@ const char kGroupID5[] = "fake_group_5"; void CheckTrackAdapterSettingsEqualsResolution( - const blink::VideoCaptureSettings& settings) { + const VideoCaptureSettings& settings) { EXPECT_FALSE(settings.track_adapter_settings().target_size()); EXPECT_EQ(1.0 / settings.Format().frame_size.height(), settings.track_adapter_settings().min_aspect_ratio()); @@ -43,7 +41,7 @@ } void CheckTrackAdapterSettingsEqualsFrameRate( - const blink::VideoCaptureSettings& settings, + const VideoCaptureSettings& settings, double value = 0.0) { if (value >= settings.FrameRate()) value = 0.0; @@ -51,7 +49,7 @@ } void CheckTrackAdapterSettingsEqualsFormat( - const blink::VideoCaptureSettings& settings) { + const VideoCaptureSettings& settings) { CheckTrackAdapterSettingsEqualsResolution(settings); CheckTrackAdapterSettingsEqualsFrameRate(settings); } @@ -61,9 +59,9 @@ static_cast<double>(format.frame_size.height()); } -blink::VideoCaptureSettings SelectSettingsVideoDeviceCapture( - const blink::VideoDeviceCaptureCapabilities& capabilities, - const blink::WebMediaConstraints& constraints) { +VideoCaptureSettings SelectSettingsVideoDeviceCapture( + const VideoDeviceCaptureCapabilities& capabilities, + const WebMediaConstraints& constraints) { return SelectSettingsVideoDeviceCapture( capabilities, constraints, MediaStreamVideoSource::kDefaultWidth, MediaStreamVideoSource::kDefaultHeight, @@ -76,7 +74,7 @@ public: void SetUp() override { // Default device. It is default because it is the first in the enumeration. - blink::VideoInputDeviceCapabilities device; + VideoInputDeviceCapabilities device; device.device_id = kDeviceID1; device.group_id = kGroupID1; device.facing_mode = media::MEDIA_VIDEO_FACING_NONE; @@ -166,7 +164,8 @@ capabilities_.device_capabilities.push_back(std::move(device)); capabilities_.noise_reduction_capabilities = { - base::Optional<bool>(), base::Optional<bool>(true), + base::Optional<bool>(), + base::Optional<bool>(true), base::Optional<bool>(false), }; @@ -181,17 +180,17 @@ } protected: - blink::VideoCaptureSettings SelectSettings() { - blink::WebMediaConstraints constraints = + VideoCaptureSettings SelectSettings() { + WebMediaConstraints constraints = constraint_factory_.CreateWebMediaConstraints(); return SelectSettingsVideoDeviceCapture(capabilities_, constraints); } - blink::VideoDeviceCaptureCapabilities capabilities_; - const blink::VideoInputDeviceCapabilities* default_device_; - const blink::VideoInputDeviceCapabilities* low_res_device_; - const blink::VideoInputDeviceCapabilities* high_res_device_; - const blink::VideoInputDeviceCapabilities* invalid_frame_rate_device_; + VideoDeviceCaptureCapabilities capabilities_; + const VideoInputDeviceCapabilities* default_device_; + const VideoInputDeviceCapabilities* low_res_device_; + const VideoInputDeviceCapabilities* high_res_device_; + const VideoInputDeviceCapabilities* invalid_frame_rate_device_; // Closest formats to the default settings. const media::VideoCaptureFormat* default_closest_format_; const media::VideoCaptureFormat* low_res_closest_format_; @@ -218,7 +217,7 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, OverconstrainedOnDeviceID) { constraint_factory_.Reset(); constraint_factory_.basic().device_id.SetExact( - blink::WebString::FromASCII("NONEXISTING")); + WebString::FromASCII("NONEXISTING")); auto result = SelectSettings(); EXPECT_FALSE(result.HasValue()); EXPECT_EQ(constraint_factory_.basic().device_id.GetName(), @@ -228,7 +227,7 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, OverconstrainedOnGroupID) { constraint_factory_.Reset(); constraint_factory_.basic().group_id.SetExact( - blink::WebString::FromASCII("NONEXISTING")); + WebString::FromASCII("NONEXISTING")); auto result = SelectSettings(); EXPECT_FALSE(result.HasValue()); EXPECT_EQ(constraint_factory_.basic().group_id.GetName(), @@ -239,7 +238,7 @@ constraint_factory_.Reset(); // No device in |capabilities_| has facing mode equal to LEFT. constraint_factory_.basic().facing_mode.SetExact( - blink::WebString::FromASCII("left")); + WebString::FromASCII("left")); auto result = SelectSettings(); EXPECT_FALSE(result.HasValue()); EXPECT_EQ(constraint_factory_.basic().facing_mode.GetName(), @@ -250,8 +249,7 @@ OverconstrainedOnEmptyFacingMode) { constraint_factory_.Reset(); // Empty is not a valid facingMode value. - constraint_factory_.basic().facing_mode.SetExact( - blink::WebString::FromASCII("")); + constraint_factory_.basic().facing_mode.SetExact(WebString::FromASCII("")); auto result = SelectSettings(); EXPECT_FALSE(result.HasValue()); EXPECT_EQ(constraint_factory_.basic().facing_mode.GetName(), @@ -262,7 +260,7 @@ OverconstrainedOnInvalidResizeMode) { constraint_factory_.Reset(); constraint_factory_.basic().resize_mode.SetExact( - blink::WebString::FromASCII("invalid")); + WebString::FromASCII("invalid")); auto result = SelectSettings(); EXPECT_FALSE(result.HasValue()); EXPECT_EQ(constraint_factory_.basic().resize_mode.GetName(), @@ -272,8 +270,7 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, OverconstrainedOnEmptyResizeMode) { constraint_factory_.Reset(); - constraint_factory_.basic().resize_mode.SetExact( - blink::WebString::FromASCII("")); + constraint_factory_.basic().resize_mode.SetExact(WebString::FromASCII("")); auto result = SelectSettings(); EXPECT_FALSE(result.HasValue()); EXPECT_EQ(constraint_factory_.basic().resize_mode.GetName(), @@ -284,7 +281,7 @@ constraint_factory_.Reset(); // No device in |capabilities_| has video kind infrared. constraint_factory_.basic().video_kind.SetExact( - blink::WebString::FromASCII("infrared")); + WebString::FromASCII("infrared")); auto result = SelectSettings(); EXPECT_FALSE(result.HasValue()); EXPECT_EQ(constraint_factory_.basic().video_kind.GetName(), @@ -391,8 +388,8 @@ // Simulate a system that does not support noise reduction. // Manually adding device capabilities because VideoDeviceCaptureCapabilities // is move only. - blink::VideoDeviceCaptureCapabilities capabilities; - blink::VideoInputDeviceCapabilities device; + VideoDeviceCaptureCapabilities capabilities; + VideoInputDeviceCapabilities device; device.device_id = kDeviceID1; device.facing_mode = media::MEDIA_VIDEO_FACING_NONE; device.formats = { @@ -416,7 +413,7 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, MandatoryDeviceID) { constraint_factory_.Reset(); constraint_factory_.basic().device_id.SetExact( - blink::WebString::FromASCII(default_device_->device_id)); + WebString::FromASCII(default_device_->device_id)); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); EXPECT_EQ(default_device_->device_id, result.device_id()); @@ -424,14 +421,14 @@ CheckTrackAdapterSettingsEqualsFormat(result); constraint_factory_.basic().device_id.SetExact( - blink::WebString::FromASCII(low_res_device_->device_id)); + WebString::FromASCII(low_res_device_->device_id)); result = SelectSettings(); EXPECT_EQ(low_res_device_->device_id, result.device_id()); EXPECT_EQ(*low_res_closest_format_, result.Format()); CheckTrackAdapterSettingsEqualsFormat(result); constraint_factory_.basic().device_id.SetExact( - blink::WebString::FromASCII(high_res_device_->device_id)); + WebString::FromASCII(high_res_device_->device_id)); result = SelectSettings(); EXPECT_EQ(high_res_device_->device_id, result.device_id()); EXPECT_EQ(*high_res_closest_format_, result.Format()); @@ -441,7 +438,7 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, MandatoryGroupID) { constraint_factory_.Reset(); constraint_factory_.basic().group_id.SetExact( - blink::WebString::FromASCII(default_device_->group_id)); + WebString::FromASCII(default_device_->group_id)); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); EXPECT_EQ(default_device_->device_id, result.device_id()); @@ -449,14 +446,14 @@ CheckTrackAdapterSettingsEqualsFormat(result); constraint_factory_.basic().group_id.SetExact( - blink::WebString::FromASCII(low_res_device_->group_id)); + WebString::FromASCII(low_res_device_->group_id)); result = SelectSettings(); EXPECT_EQ(low_res_device_->device_id, result.device_id()); EXPECT_EQ(*low_res_closest_format_, result.Format()); CheckTrackAdapterSettingsEqualsFormat(result); constraint_factory_.basic().group_id.SetExact( - blink::WebString::FromASCII(high_res_device_->group_id)); + WebString::FromASCII(high_res_device_->group_id)); result = SelectSettings(); EXPECT_EQ(high_res_device_->device_id, result.device_id()); EXPECT_EQ(*high_res_closest_format_, result.Format()); @@ -466,7 +463,7 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, MandatoryFacingMode) { constraint_factory_.Reset(); constraint_factory_.basic().facing_mode.SetExact( - blink::WebString::FromASCII("environment")); + WebString::FromASCII("environment")); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // Only the low-res device supports environment facing mode. Should select @@ -478,7 +475,7 @@ CheckTrackAdapterSettingsEqualsFormat(result); constraint_factory_.basic().facing_mode.SetExact( - blink::WebString::FromASCII("user")); + WebString::FromASCII("user")); result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // Only the high-res device supports user facing mode. Should select default @@ -492,7 +489,7 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, MandatoryVideoKind) { constraint_factory_.Reset(); constraint_factory_.basic().video_kind.SetExact( - blink::WebString::FromASCII("depth")); + WebString::FromASCII("depth")); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); EXPECT_EQ(kDeviceID4, result.device_id()); @@ -500,7 +497,7 @@ CheckTrackAdapterSettingsEqualsFormat(result); constraint_factory_.basic().video_kind.SetExact( - blink::WebString::FromASCII("color")); + WebString::FromASCII("color")); result = SelectSettings(); EXPECT_TRUE(result.HasValue()); EXPECT_EQ(default_device_->device_id, result.device_id()); @@ -1693,7 +1690,7 @@ constraint_factory_.basic().width.SetIdeal(kIdealWidth); constraint_factory_.basic().height.SetIdeal(kIdealHeight); constraint_factory_.basic().resize_mode.SetExact( - blink::WebString::FromASCII("none")); + WebString::FromASCII("none")); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // A native mode of 640x480 should be selected since it is closest native mode @@ -1703,7 +1700,7 @@ EXPECT_FALSE(result.track_adapter_settings().target_size().has_value()); constraint_factory_.basic().resize_mode.SetExact( - blink::WebString::FromASCII("crop-and-scale")); + WebString::FromASCII("crop-and-scale")); result = SelectSettings(); EXPECT_TRUE(result.HasValue()); EXPECT_GE(result.Width(), kIdealWidth); @@ -1715,7 +1712,7 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, IdealResizeMode) { constraint_factory_.Reset(); constraint_factory_.basic().resize_mode.SetIdeal( - blink::WebString::FromASCII("crop-and-scale")); + WebString::FromASCII("crop-and-scale")); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // Since no constraints are given, the default device with resolution closest @@ -1738,7 +1735,7 @@ constraint_factory_.basic().width.SetIdeal(kIdealWidth); constraint_factory_.basic().height.SetIdeal(kIdealHeight); constraint_factory_.basic().resize_mode.SetIdeal( - blink::WebString::FromASCII("none")); + WebString::FromASCII("none")); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // A native mode of 640x480 should be selected since it is the closest native @@ -1748,7 +1745,7 @@ EXPECT_FALSE(result.track_adapter_settings().target_size().has_value()); constraint_factory_.basic().resize_mode.SetIdeal( - blink::WebString::FromASCII("crop-and-scale")); + WebString::FromASCII("crop-and-scale")); result = SelectSettings(); EXPECT_TRUE(result.HasValue()); EXPECT_GE(result.Width(), kIdealWidth); @@ -1766,7 +1763,7 @@ constraint_factory_.basic().width.SetIdeal(kIdealWidth); constraint_factory_.basic().height.SetIdeal(kIdealHeight); constraint_factory_.basic().resize_mode.SetIdeal( - blink::WebString::FromASCII("none")); + WebString::FromASCII("none")); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // A native mode of 640x480 should be selected since it is the closest native @@ -1776,7 +1773,7 @@ EXPECT_FALSE(result.track_adapter_settings().target_size().has_value()); constraint_factory_.basic().resize_mode.SetIdeal( - blink::WebString::FromASCII("crop-and-scale")); + WebString::FromASCII("crop-and-scale")); result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // Rescaling is preferred, therefore a native mode greater than the ideal @@ -1792,7 +1789,7 @@ constraint_factory_.basic().width.SetIdeal(1); constraint_factory_.basic().height.SetIdeal(1); constraint_factory_.basic().resize_mode.SetIdeal( - blink::WebString::FromASCII("none")); + WebString::FromASCII("none")); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // The native mode closest to 1x1 is 40x30 with the low-res device. @@ -1810,7 +1807,7 @@ constraint_factory_.Reset(); constraint_factory_.basic().width.SetIdeal(1); constraint_factory_.basic().resize_mode.SetIdeal( - blink::WebString::FromASCII("none")); + WebString::FromASCII("none")); result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // The native mode closest to 1x1 is 40x30 with the low-res device. @@ -1827,10 +1824,8 @@ constraint_factory_.Reset(); constraint_factory_.basic().width.SetIdeal(641); constraint_factory_.basic().height.SetIdeal(481); - constraint_factory_.basic().resize_mode.SetIdeal( - blink::WebVector<blink::WebString>( - {blink::WebString::FromASCII("none"), - blink::WebString::FromASCII("crop-and-scale")})); + constraint_factory_.basic().resize_mode.SetIdeal(WebVector<WebString>( + {WebString::FromASCII("none"), WebString::FromASCII("crop-and-scale")})); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // 800x600 rescaled to 641x481 is closest to the specified ideal values. @@ -1844,10 +1839,8 @@ EXPECT_EQ(result.track_adapter_settings().target_height(), 481); constraint_factory_.Reset(); - constraint_factory_.basic().resize_mode.SetIdeal( - blink::WebVector<blink::WebString>( - {blink::WebString::FromASCII("none"), - blink::WebString::FromASCII("crop-and-scale")})); + constraint_factory_.basic().resize_mode.SetIdeal(WebVector<WebString>( + {WebString::FromASCII("none"), WebString::FromASCII("crop-and-scale")})); result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // Given that both resize modes are ideal, the default device with the @@ -1863,8 +1856,7 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, AdvancedMinMaxResolutionFrameRate) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.width.SetMin(4000); advanced1.height.SetMin(4000); // No device supports the first advanced set. This first advanced constraint @@ -1875,8 +1867,7 @@ EXPECT_EQ(*default_closest_format_, result.Format()); CheckTrackAdapterSettingsEqualsFormat(result); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.width.SetMin(320); advanced2.height.SetMin(240); advanced2.width.SetMax(640); @@ -1892,8 +1883,7 @@ EXPECT_EQ(640.0 / 240.0, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFrameRate(result); - blink::WebMediaTrackConstraintSet& advanced3 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced3 = constraint_factory_.AddAdvanced(); advanced3.frame_rate.SetMax(10.0); result = SelectSettings(); EXPECT_TRUE(result.HasValue()); @@ -1907,8 +1897,7 @@ EXPECT_EQ(640.0 / 240.0, result.track_adapter_settings().max_aspect_ratio()); CheckTrackAdapterSettingsEqualsFrameRate(result, 10.0); - blink::WebMediaTrackConstraintSet& advanced4 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced4 = constraint_factory_.AddAdvanced(); advanced4.width.SetMax(1000); advanced4.height.SetMax(1000); result = SelectSettings(); @@ -1963,15 +1952,12 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, AdvancedResolutionAndFrameRate) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.width.SetExact(1920); advanced1.height.SetExact(1080); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.frame_rate.SetExact(60.0); - blink::WebMediaTrackConstraintSet& advanced3 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced3 = constraint_factory_.AddAdvanced(); advanced3.width.SetExact(2304); advanced3.height.SetExact(1536); auto result = SelectSettings(); @@ -1994,12 +1980,10 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, AdvancedNoiseReduction) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.width.SetMin(640); advanced1.height.SetMin(480); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.width.SetMin(1920); advanced2.height.SetMin(1080); advanced2.goog_noise_reduction.SetExact(false); @@ -2021,13 +2005,11 @@ AdvancedContradictoryNoiseReduction) { { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.width.SetMin(640); advanced1.height.SetMin(480); advanced1.goog_noise_reduction.SetExact(true); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.width.SetMin(1920); advanced2.height.SetMin(1080); advanced2.goog_noise_reduction.SetExact(false); @@ -2051,12 +2033,10 @@ // Same test without noise reduction { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.width.SetMin(640); advanced1.height.SetMin(480); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.width.SetMin(1920); advanced2.height.SetMin(1080); auto result = SelectSettings(); @@ -2079,12 +2059,10 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, AdvancedContradictoryExactResolution) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.width.SetExact(640); advanced1.height.SetExact(480); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.width.SetExact(1920); advanced2.height.SetExact(1080); auto result = SelectSettings(); @@ -2104,12 +2082,10 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, AdvancedContradictoryMaxMinResolutionFrameRate) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.width.SetMax(640); advanced1.height.SetMax(480); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.width.SetMin(1920); advanced2.height.SetMin(1080); advanced2.frame_rate.SetExact(60.0); @@ -2133,12 +2109,10 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, AdvancedContradictoryMinMaxResolutionFrameRate) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.width.SetMin(800); advanced1.height.SetMin(600); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.width.SetMax(640); advanced2.height.SetMax(480); advanced2.frame_rate.SetExact(60.0); @@ -2163,11 +2137,9 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, AdvancedContradictoryExactAspectRatio) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.aspect_ratio.SetExact(2300.0); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.aspect_ratio.SetExact(3.0); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); @@ -2188,11 +2160,9 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, AdvancedContradictoryAspectRatioRange) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.aspect_ratio.SetMin(2300.0); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.aspect_ratio.SetMax(3.0); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); @@ -2213,11 +2183,9 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, AdvancedContradictoryExactFrameRate) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.frame_rate.SetExact(40.0); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.frame_rate.SetExact(45.0); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); @@ -2231,11 +2199,9 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, AdvancedContradictoryFrameRateRange) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.frame_rate.SetMin(40.0); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.frame_rate.SetMax(35.0); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); @@ -2249,15 +2215,12 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, AdvancedContradictoryWidthFrameRate) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.width.SetMax(1920); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.width.SetMin(2000); advanced2.frame_rate.SetExact(10.0); - blink::WebMediaTrackConstraintSet& advanced3 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced3 = constraint_factory_.AddAdvanced(); advanced3.frame_rate.SetExact(30.0); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); @@ -2273,15 +2236,12 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, AdvancedContradictoryHeightFrameRate) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.height.SetMax(1080); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.height.SetMin(1500); advanced2.frame_rate.SetExact(10.0); - blink::WebMediaTrackConstraintSet& advanced3 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced3 = constraint_factory_.AddAdvanced(); advanced3.frame_rate.SetExact(60.0); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); @@ -2297,18 +2257,16 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, AdvancedDeviceID) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); - blink::WebString id_vector1[] = {blink::WebString::FromASCII(kDeviceID1), - blink::WebString::FromASCII(kDeviceID2)}; + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); + WebString id_vector1[] = {WebString::FromASCII(kDeviceID1), + WebString::FromASCII(kDeviceID2)}; advanced1.device_id.SetExact( - blink::WebVector<blink::WebString>(id_vector1, base::size(id_vector1))); - blink::WebString id_vector2[] = {blink::WebString::FromASCII(kDeviceID2), - blink::WebString::FromASCII(kDeviceID3)}; - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebVector<WebString>(id_vector1, base::size(id_vector1))); + WebString id_vector2[] = {WebString::FromASCII(kDeviceID2), + WebString::FromASCII(kDeviceID3)}; + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.device_id.SetExact( - blink::WebVector<blink::WebString>(id_vector2, base::size(id_vector2))); + WebVector<WebString>(id_vector2, base::size(id_vector2))); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // kDeviceID2 must be selected because it is the only one that satisfies both @@ -2319,18 +2277,16 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, AdvancedGroupID) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); - blink::WebString id_vector1[] = {blink::WebString::FromASCII(kGroupID1), - blink::WebString::FromASCII(kGroupID2)}; + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); + WebString id_vector1[] = {WebString::FromASCII(kGroupID1), + WebString::FromASCII(kGroupID2)}; advanced1.group_id.SetExact( - blink::WebVector<blink::WebString>(id_vector1, base::size(id_vector1))); - blink::WebString id_vector2[] = {blink::WebString::FromASCII(kGroupID2), - blink::WebString::FromASCII(kGroupID3)}; - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebVector<WebString>(id_vector1, base::size(id_vector1))); + WebString id_vector2[] = {WebString::FromASCII(kGroupID2), + WebString::FromASCII(kGroupID3)}; + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.group_id.SetExact( - blink::WebVector<blink::WebString>(id_vector2, base::size(id_vector2))); + WebVector<WebString>(id_vector2, base::size(id_vector2))); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // The device with group_id kGroupID2 must be selected because it is the only @@ -2342,18 +2298,16 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, AdvancedContradictoryDeviceID) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); - blink::WebString id_vector1[] = {blink::WebString::FromASCII(kDeviceID1), - blink::WebString::FromASCII(kDeviceID2)}; + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); + WebString id_vector1[] = {WebString::FromASCII(kDeviceID1), + WebString::FromASCII(kDeviceID2)}; advanced1.device_id.SetExact( - blink::WebVector<blink::WebString>(id_vector1, base::size(id_vector1))); - blink::WebString id_vector2[] = {blink::WebString::FromASCII(kDeviceID3), - blink::WebString::FromASCII(kDeviceID4)}; - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebVector<WebString>(id_vector1, base::size(id_vector1))); + WebString id_vector2[] = {WebString::FromASCII(kDeviceID3), + WebString::FromASCII(kDeviceID4)}; + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.device_id.SetExact( - blink::WebVector<blink::WebString>(id_vector2, base::size(id_vector2))); + WebVector<WebString>(id_vector2, base::size(id_vector2))); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // The second advanced set must be ignored because it contradicts the first @@ -2365,20 +2319,17 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, AdvancedContradictoryDeviceIDAndResolution) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.device_id.SetExact( - {blink::WebString::FromASCII(low_res_device_->device_id)}); + {WebString::FromASCII(low_res_device_->device_id)}); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.device_id.SetExact( - {blink::WebString::FromASCII(high_res_device_->device_id)}); + {WebString::FromASCII(high_res_device_->device_id)}); advanced2.width.SetMax(50); advanced2.height.SetMax(50); - blink::WebMediaTrackConstraintSet& advanced3 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced3 = constraint_factory_.AddAdvanced(); advanced3.width.SetExact(800); advanced3.height.SetExact(600); @@ -2395,18 +2346,16 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, AdvancedContradictoryGroupID) { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); - blink::WebString id_vector1[] = {blink::WebString::FromASCII(kGroupID1), - blink::WebString::FromASCII(kGroupID2)}; + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); + WebString id_vector1[] = {WebString::FromASCII(kGroupID1), + WebString::FromASCII(kGroupID2)}; advanced1.group_id.SetExact( - blink::WebVector<blink::WebString>(id_vector1, base::size(id_vector1))); - blink::WebString id_vector2[] = {blink::WebString::FromASCII(kGroupID3), - blink::WebString::FromASCII(kGroupID4)}; - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebVector<WebString>(id_vector1, base::size(id_vector1))); + WebString id_vector2[] = {WebString::FromASCII(kGroupID3), + WebString::FromASCII(kGroupID4)}; + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.group_id.SetExact( - blink::WebVector<blink::WebString>(id_vector2, base::size(id_vector2))); + WebVector<WebString>(id_vector2, base::size(id_vector2))); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // The second advanced set must be ignored because it contradicts the first @@ -2419,11 +2368,9 @@ AdvancedContradictoryAspectRatioWidth) { { constraint_factory_.Reset(); - blink::WebMediaTrackConstraintSet& advanced1 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced1 = constraint_factory_.AddAdvanced(); advanced1.aspect_ratio.SetMin(17); - blink::WebMediaTrackConstraintSet& advanced2 = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced2 = constraint_factory_.AddAdvanced(); advanced2.width.SetMax(1); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); @@ -2446,10 +2393,9 @@ constraint_factory_.Reset(); constraint_factory_.basic().width.SetIdeal(1); constraint_factory_.basic().height.SetIdeal(1); - blink::WebMediaTrackConstraintSet& advanced = - constraint_factory_.AddAdvanced(); + WebMediaTrackConstraintSet& advanced = constraint_factory_.AddAdvanced(); - advanced.resize_mode.SetExact(blink::WebString::FromASCII("none")); + advanced.resize_mode.SetExact(WebString::FromASCII("none")); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); // The native mode closest to 1x1 is 40x30 with the low-res device. @@ -2468,9 +2414,8 @@ // This advanced set must be ignored because there are no native resolutions // with width equal to 639. - blink::WebMediaTrackConstraintSet& advanced = - constraint_factory_.AddAdvanced(); - advanced.resize_mode.SetExact(blink::WebString::FromASCII("none")); + WebMediaTrackConstraintSet& advanced = constraint_factory_.AddAdvanced(); + advanced.resize_mode.SetExact(WebString::FromASCII("none")); advanced.frame_rate.SetExact(19.0); auto result = SelectSettings(); @@ -2515,7 +2460,7 @@ // when there are no candidates to choose from. TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, NoDevicesNoConstraints) { constraint_factory_.Reset(); - blink::VideoDeviceCaptureCapabilities capabilities; + VideoDeviceCaptureCapabilities capabilities; auto result = SelectSettingsVideoDeviceCapture( capabilities, constraint_factory_.CreateWebMediaConstraints()); EXPECT_FALSE(result.HasValue()); @@ -2525,7 +2470,7 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, NoDevicesWithConstraints) { constraint_factory_.Reset(); constraint_factory_.basic().height.SetExact(100); - blink::VideoDeviceCaptureCapabilities capabilities; + VideoDeviceCaptureCapabilities capabilities; auto result = SelectSettingsVideoDeviceCapture( capabilities, constraint_factory_.CreateWebMediaConstraints()); EXPECT_FALSE(result.HasValue()); @@ -2537,7 +2482,7 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, InvalidFrameRateDevice) { constraint_factory_.Reset(); constraint_factory_.basic().device_id.SetExact( - blink::WebString::FromASCII(invalid_frame_rate_device_->device_id)); + WebString::FromASCII(invalid_frame_rate_device_->device_id)); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); EXPECT_EQ(invalid_frame_rate_device_->device_id, result.device_id()); @@ -2564,7 +2509,7 @@ TEST_F(MediaStreamConstraintsUtilVideoDeviceTest, InvertedDefaultResolution) { constraint_factory_.Reset(); constraint_factory_.basic().device_id.SetExact( - blink::WebString::FromASCII(high_res_device_->device_id)); + WebString::FromASCII(high_res_device_->device_id)); auto result = SelectSettings(); EXPECT_TRUE(result.HasValue()); EXPECT_EQ(high_res_device_->device_id, result.device_id()); @@ -2572,4 +2517,4 @@ EXPECT_EQ(result.Height(), MediaStreamVideoSource::kDefaultHeight); } -} // namespace content +} // namespace blink
diff --git a/content/renderer/media/stream/mock_constraint_factory.cc b/third_party/blink/renderer/modules/mediastream/mock_constraint_factory.cc similarity index 78% rename from content/renderer/media/stream/mock_constraint_factory.cc rename to third_party/blink/renderer/modules/mediastream/mock_constraint_factory.cc index 8260245..f63f546 100644 --- a/content/renderer/media/stream/mock_constraint_factory.cc +++ b/third_party/blink/renderer/modules/mediastream/mock_constraint_factory.cc
@@ -2,28 +2,28 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "third_party/blink/public/web/modules/mediastream/mock_constraint_factory.h" + #include <stddef.h> #include "base/macros.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" -#include "content/renderer/media/stream/mock_constraint_factory.h" #include "third_party/blink/public/platform/modules/mediastream/media_stream_audio_processor_options.h" -namespace content { +namespace blink { MockConstraintFactory::MockConstraintFactory() {} MockConstraintFactory::~MockConstraintFactory() {} -blink::WebMediaTrackConstraintSet& MockConstraintFactory::AddAdvanced() { +WebMediaTrackConstraintSet& MockConstraintFactory::AddAdvanced() { advanced_.emplace_back(); return advanced_.back(); } -blink::WebMediaConstraints MockConstraintFactory::CreateWebMediaConstraints() - const { - blink::WebMediaConstraints constraints; +WebMediaConstraints MockConstraintFactory::CreateWebMediaConstraints() const { + WebMediaConstraints constraints; constraints.Initialize(basic_, advanced_); return constraints; } @@ -44,8 +44,8 @@ } void MockConstraintFactory::Reset() { - basic_ = blink::WebMediaTrackConstraintSet(); + basic_ = WebMediaTrackConstraintSet(); advanced_.clear(); } -} // namespace content +} // namespace blink
diff --git a/third_party/blink/renderer/modules/webaudio/audio_basic_processor_handler.cc b/third_party/blink/renderer/modules/webaudio/audio_basic_processor_handler.cc index 7be1d80b..32da640 100644 --- a/third_party/blink/renderer/modules/webaudio/audio_basic_processor_handler.cc +++ b/third_party/blink/renderer/modules/webaudio/audio_basic_processor_handler.cc
@@ -154,4 +154,17 @@ return processor_->LatencyTime(); } +bool AudioBasicProcessorHandler::HasNonFiniteOutput() const { + AudioBus* output_bus = Output(0).Bus(); + + for (wtf_size_t k = 0; k < output_bus->NumberOfChannels(); ++k) { + AudioChannel* channel = output_bus->Channel(k); + if (channel->length() > 0 && !std::isfinite(channel->Data()[0])) { + return true; + } + } + + return false; +} + } // namespace blink
diff --git a/third_party/blink/renderer/modules/webaudio/audio_basic_processor_handler.h b/third_party/blink/renderer/modules/webaudio/audio_basic_processor_handler.h index e4951b68..6f4d60f 100644 --- a/third_party/blink/renderer/modules/webaudio/audio_basic_processor_handler.h +++ b/third_party/blink/renderer/modules/webaudio/audio_basic_processor_handler.h
@@ -43,7 +43,7 @@ ~AudioBasicProcessorHandler() override; // AudioHandler - void Process(uint32_t frames_to_process) final; + void Process(uint32_t frames_to_process) override; void ProcessOnlyAudioParams(uint32_t frames_to_process) final; void PullInputs(uint32_t frames_to_process) final; void Initialize() final; @@ -62,6 +62,14 @@ AudioNode&, float sample_rate, std::unique_ptr<AudioProcessor>); + + // Returns true if the first output sample of any channel is non-finite. This + // is a proxy for determining if the filter state is bad. For + // BiquadFilterNodes and IIRFilterNodes, if the internal state has non-finite + // values, the non-finite value propagates pretty much forever in the output. + // This is because infinities and NaNs are sticky. + bool HasNonFiniteOutput() const; + private: bool RequiresTailProcessing() const final; double TailTime() const final;
diff --git a/third_party/blink/renderer/modules/webaudio/audio_node.cc b/third_party/blink/renderer/modules/webaudio/audio_node.cc index 4977ccfb..709d1f81 100644 --- a/third_party/blink/renderer/modules/webaudio/audio_node.cc +++ b/third_party/blink/renderer/modules/webaudio/audio_node.cc
@@ -209,6 +209,10 @@ return *outputs_[i]; } +const AudioNodeOutput& AudioHandler::Output(unsigned i) const { + return *outputs_[i]; +} + unsigned AudioHandler::ChannelCount() { return channel_count_; }
diff --git a/third_party/blink/renderer/modules/webaudio/audio_node.h b/third_party/blink/renderer/modules/webaudio/audio_node.h index ec29ada..686a026 100644 --- a/third_party/blink/renderer/modules/webaudio/audio_node.h +++ b/third_party/blink/renderer/modules/webaudio/audio_node.h
@@ -171,6 +171,7 @@ AudioNodeInput& Input(unsigned); // The argument must be less than numberOfOutputs(). AudioNodeOutput& Output(unsigned); + const AudioNodeOutput& Output(unsigned) const; // processIfNecessary() is called by our output(s) when the rendering graph // needs this AudioNode to process. This method ensures that the AudioNode
diff --git a/third_party/blink/renderer/modules/webaudio/biquad_filter_node.cc b/third_party/blink/renderer/modules/webaudio/biquad_filter_node.cc index 8add896..8a7e9d0b 100644 --- a/third_party/blink/renderer/modules/webaudio/biquad_filter_node.cc +++ b/third_party/blink/renderer/modules/webaudio/biquad_filter_node.cc
@@ -27,11 +27,15 @@ #include <memory> +#include "third_party/blink/renderer/core/inspector/console_message.h" #include "third_party/blink/renderer/modules/webaudio/audio_basic_processor_handler.h" +#include "third_party/blink/renderer/modules/webaudio/audio_node_output.h" #include "third_party/blink/renderer/modules/webaudio/biquad_filter_options.h" #include "third_party/blink/renderer/platform/bindings/exception_messages.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/histogram.h" +#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h" +#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h" namespace blink { @@ -50,6 +54,12 @@ q, gain, detune)) { + DCHECK(Context()); + DCHECK(Context()->GetExecutionContext()); + + task_runner_ = Context()->GetExecutionContext()->GetTaskRunner( + TaskType::kMediaElementEvent); + // Initialize the handler so that AudioParams can be processed. Initialize(); } @@ -65,6 +75,36 @@ new BiquadFilterHandler(node, sample_rate, frequency, q, gain, detune)); } +void BiquadFilterHandler::Process(uint32_t frames_to_process) { + AudioBasicProcessorHandler::Process(frames_to_process); + + if (!did_warn_bad_filter_state_) { + // Inform the user once if the output has a non-finite value. This is a + // proxy for the filter state containing non-finite values since the output + // is also saved as part of the state of the filter. + if (HasNonFiniteOutput()) { + did_warn_bad_filter_state_ = true; + + PostCrossThreadTask( + *task_runner_, FROM_HERE, + CrossThreadBindOnce(&BiquadFilterHandler::NotifyBadState, + WrapRefCounted(this))); + } + } +} + +void BiquadFilterHandler::NotifyBadState() const { + DCHECK(IsMainThread()); + if (!Context() || !Context()->GetExecutionContext()) + return; + + Context()->GetExecutionContext()->AddConsoleMessage(ConsoleMessage::Create( + mojom::ConsoleMessageSource::kJavaScript, + mojom::ConsoleMessageLevel::kWarning, + NodeTypeName() + ": state is bad, probably due to unstable filter caused " + "by fast parameter automation.")); +} + BiquadFilterNode::BiquadFilterNode(BaseAudioContext& context) : AudioNode(context), frequency_(
diff --git a/third_party/blink/renderer/modules/webaudio/biquad_filter_node.h b/third_party/blink/renderer/modules/webaudio/biquad_filter_node.h index fb59ba2..7ed45955 100644 --- a/third_party/blink/renderer/modules/webaudio/biquad_filter_node.h +++ b/third_party/blink/renderer/modules/webaudio/biquad_filter_node.h
@@ -47,6 +47,8 @@ AudioParamHandler& gain, AudioParamHandler& detune); + void Process(uint32_t frames_to_process) override; + private: BiquadFilterHandler(AudioNode&, float sample_rate, @@ -54,6 +56,15 @@ AudioParamHandler& q, AudioParamHandler& gain, AudioParamHandler& detune); + + void NotifyBadState() const; + + // Only notify the user of the once. No need to spam the console with + // messages, because once we're in a bad state, it usually stays that way + // forever. Only accessed from audio thread. + bool did_warn_bad_filter_state_ = false; + + scoped_refptr<base::SingleThreadTaskRunner> task_runner_; }; class BiquadFilterNode final : public AudioNode {
diff --git a/third_party/blink/renderer/modules/webaudio/iir_filter_node.cc b/third_party/blink/renderer/modules/webaudio/iir_filter_node.cc index bb50d3a..edb6630 100644 --- a/third_party/blink/renderer/modules/webaudio/iir_filter_node.cc +++ b/third_party/blink/renderer/modules/webaudio/iir_filter_node.cc
@@ -7,11 +7,14 @@ #include <memory> #include "third_party/blink/renderer/core/inspector/console_message.h" +#include "third_party/blink/renderer/modules/webaudio/audio_node_output.h" #include "third_party/blink/renderer/modules/webaudio/base_audio_context.h" #include "third_party/blink/renderer/modules/webaudio/iir_filter_options.h" #include "third_party/blink/renderer/platform/bindings/exception_messages.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/histogram.h" +#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h" +#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h" namespace blink { @@ -28,7 +31,13 @@ 1, feedforward_coef, feedback_coef, - is_filter_stable)) {} + is_filter_stable)) { + DCHECK(Context()); + DCHECK(Context()->GetExecutionContext()); + + task_runner_ = Context()->GetExecutionContext()->GetTaskRunner( + TaskType::kMediaElementEvent); +} scoped_refptr<IIRFilterHandler> IIRFilterHandler::Create( AudioNode& node, @@ -85,6 +94,34 @@ return true; } +void IIRFilterHandler::Process(uint32_t frames_to_process) { + AudioBasicProcessorHandler::Process(frames_to_process); + + if (!did_warn_bad_filter_state_) { + // Inform the user once if the output has a non-finite value. This is a + // proxy for the filter state containing non-finite values since the output + // is also saved as part of the state of the filter. + if (HasNonFiniteOutput()) { + did_warn_bad_filter_state_ = true; + + PostCrossThreadTask(*task_runner_, FROM_HERE, + CrossThreadBind(&IIRFilterHandler::NotifyBadState, + WrapRefCounted(this))); + } + } +} + +void IIRFilterHandler::NotifyBadState() const { + DCHECK(IsMainThread()); + if (!Context() || !Context()->GetExecutionContext()) + return; + + Context()->GetExecutionContext()->AddConsoleMessage(ConsoleMessage::Create( + mojom::ConsoleMessageSource::kJavaScript, + mojom::ConsoleMessageLevel::kWarning, + NodeTypeName() + ": state is bad, probably due to unstable filter.")); +} + IIRFilterNode::IIRFilterNode(BaseAudioContext& context, const Vector<double>& feedforward_coef, const Vector<double>& feedback_coef,
diff --git a/third_party/blink/renderer/modules/webaudio/iir_filter_node.h b/third_party/blink/renderer/modules/webaudio/iir_filter_node.h index a33d99c2..dc049ae 100644 --- a/third_party/blink/renderer/modules/webaudio/iir_filter_node.h +++ b/third_party/blink/renderer/modules/webaudio/iir_filter_node.h
@@ -5,6 +5,7 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_WEBAUDIO_IIR_FILTER_NODE_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_WEBAUDIO_IIR_FILTER_NODE_H_ +#include "base/single_thread_task_runner.h" #include "third_party/blink/renderer/core/typed_arrays/array_buffer_view_helpers.h" #include "third_party/blink/renderer/core/typed_arrays/dom_typed_array.h" #include "third_party/blink/renderer/modules/webaudio/audio_basic_processor_handler.h" @@ -26,12 +27,23 @@ const Vector<double>& feedback_coef, bool is_filter_stable); + void Process(uint32_t frames_to_process) override; + private: IIRFilterHandler(AudioNode&, float sample_rate, const Vector<double>& feedforward_coef, const Vector<double>& feedback_coef, bool is_filter_stable); + + void NotifyBadState() const; + + // Only notify the user of the once. No need to spam the console with + // messages, because once we're in a bad state, it usually stays that way + // forever. Only accessed from audio thread. + bool did_warn_bad_filter_state_ = false; + + scoped_refptr<base::SingleThreadTaskRunner> task_runner_; }; class IIRFilterNode : public AudioNode {
diff --git a/third_party/blink/renderer/platform/exported/web_runtime_features.cc b/third_party/blink/renderer/platform/exported/web_runtime_features.cc index de44df93..e261a81 100644 --- a/third_party/blink/renderer/platform/exported/web_runtime_features.cc +++ b/third_party/blink/renderer/platform/exported/web_runtime_features.cc
@@ -695,4 +695,8 @@ enable); } +void WebRuntimeFeatures::EnableConsolidatedMovementXY(bool enable) { + RuntimeEnabledFeatures::SetConsolidatedMovementXYEnabled(enable); +} + } // namespace blink
diff --git a/third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.cc b/third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.cc index d7fb1cd..35fe760 100644 --- a/third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.cc +++ b/third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.cc
@@ -98,10 +98,11 @@ PlatformThreadId context_thread_id, bool is_origin_top_left, std::unique_ptr<viz::SingleReleaseCallback> release_callback) - : paint_image_content_id_(cc::PaintImage::GetNextContentId()), - release_callback_(std::move(release_callback)) { + : mailbox_ref_(base::MakeRefCounted<TextureHolder::MailboxRef>( + std::move(release_callback))), + paint_image_content_id_(cc::PaintImage::GetNextContentId()) { mailbox_texture_holder_ = std::make_unique<MailboxTextureHolder>( - mailbox, sync_token, std::move(context_provider_wrapper), + mailbox, sync_token, std::move(context_provider_wrapper), mailbox_ref_, context_thread_id, sk_image_info, texture_target, is_origin_top_left); } @@ -132,11 +133,6 @@ AcceleratedStaticBitmapImage::~AcceleratedStaticBitmapImage() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - if (release_callback_) { - DCHECK(mailbox_texture_holder_); - release_callback_->Run(GetSyncToken(), false /* is_lost */); - } - // If the original SkImage was retained, it must be destroyed on the thread // where it came from. In the same thread case, there is nothing to do because // the regular destruction flow is fine.
diff --git a/third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.h b/third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.h index dd1b902..51b4bf6b 100644 --- a/third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.h +++ b/third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.h
@@ -146,6 +146,8 @@ return mailbox_texture_holder_.get(); } + scoped_refptr<TextureHolder::MailboxRef> mailbox_ref_; + // The image is created with one of the texture holders below while the other // one is created lazily if needed and then persisted for the lifetime of the // image on a particular thread. @@ -165,8 +167,6 @@ scoped_refptr<base::SingleThreadTaskRunner> original_skia_image_task_runner_; base::WeakPtr<WebGraphicsContext3DProviderWrapper> original_skia_image_context_provider_wrapper_; - - std::unique_ptr<viz::SingleReleaseCallback> release_callback_; }; } // namespace blink
diff --git a/third_party/blink/renderer/platform/graphics/canvas_resource.cc b/third_party/blink/renderer/platform/graphics/canvas_resource.cc index e459e7a..3248c5f5 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_resource.cc +++ b/third_party/blink/renderer/platform/graphics/canvas_resource.cc
@@ -770,6 +770,10 @@ void CanvasResourceSharedImage::WillDraw() { DCHECK(!is_cross_thread()) << "Write access is only allowed on the owning thread"; + // If skia is accessing the resource, it can modify the texture's filter + // params. Make sure to set them to the desired value before sending the + // resource to the display compositor. + needs_gl_filter_reset_ = true; mailbox_needs_new_sync_token_ = true; } @@ -854,16 +858,16 @@ void CanvasResourceSharedImage::SetGLFilterIfNeeded() { DCHECK(!is_cross_thread()); - if (!needs_gl_filter_reset_ || !ContextGL()) + if (!needs_gl_filter_reset_ || !ContextGL() || !WeakProvider()) return; ContextGL()->BindTexture(TextureTarget(), GetTextureIdForBackendTexture()); ContextGL()->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GLFilter()); ContextGL()->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GLFilter()); ContextGL()->BindTexture(TextureTarget(), 0u); - // TODO(khushalsagar): Inform skia about the param modification. mailbox_needs_new_sync_token_ = true; needs_gl_filter_reset_ = false; + Provider()->NotifyTexParamsModified(this); } bool CanvasResourceSharedImage::HasGpuMailbox() const {
diff --git a/third_party/blink/renderer/platform/graphics/canvas_resource_provider.cc b/third_party/blink/renderer/platform/graphics/canvas_resource_provider.cc index 6217bf0..3f1b399 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_resource_provider.cc +++ b/third_party/blink/renderer/platform/graphics/canvas_resource_provider.cc
@@ -503,6 +503,17 @@ ColorParams(), is_overlay_candidate_, is_origin_top_left_); } + void NotifyTexParamsModified(const CanvasResource* resource) override { + if (resource_.get() == resource) { + DCHECK(!current_resource_has_write_access_); + // Note that the call below is guarenteed to not issue any GPU work for + // the backend texture since we ensure that all skia work on the resource + // is issued before releasing write access. + surface_->getBackendTexture(SkSurface::kFlushRead_BackendHandleAccess) + .glTextureParametersModified(); + } + } + protected: scoped_refptr<CanvasResource> ProduceCanvasResource() override { TRACE_EVENT0("blink", @@ -902,8 +913,6 @@ size, color_params, context_provider_wrapper, resource_dispatcher); break; case CanvasResourceType::kSharedImage: { - // TODO(khushalsagar): Enable this once the shared image work is done. -#if 0 // TODO(khushalsagar): Also kAcceleratedDirect2DResourceUsage when we // switch it to use shared images. const bool is_overlay_candidate = @@ -915,8 +924,6 @@ provider = std::make_unique<CanvasResourceProviderSharedImage>( size, msaa_sample_count, color_params, context_provider_wrapper, resource_dispatcher, is_origin_top_left, is_overlay_candidate); -#endif - continue; } break; } if (!provider->IsValid())
diff --git a/third_party/blink/renderer/platform/graphics/canvas_resource_provider.h b/third_party/blink/renderer/platform/graphics/canvas_resource_provider.h index 1c06473..a4ee49b0 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_resource_provider.h +++ b/third_party/blink/renderer/platform/graphics/canvas_resource_provider.h
@@ -167,6 +167,10 @@ return weak_ptr_factory_.GetWeakPtr(); } + // Notifies the provider when the texture params associated with |resource| + // are modified externally from the provider's SkSurface. + virtual void NotifyTexParamsModified(const CanvasResource* resource) {} + protected: gpu::gles2::GLES2Interface* ContextGL() const; GrContext* GetGrContext() const;
diff --git a/third_party/blink/renderer/platform/graphics/gpu/graphics_context_3d_utils.cc b/third_party/blink/renderer/platform/graphics/gpu/graphics_context_3d_utils.cc index 6544ed6..e4a3331 100644 --- a/third_party/blink/renderer/platform/graphics/gpu/graphics_context_3d_utils.cc +++ b/third_party/blink/renderer/platform/graphics/gpu/graphics_context_3d_utils.cc
@@ -86,6 +86,12 @@ gr_texture->textureParamsModified(); } +void GraphicsContext3DUtils::RegisterMailbox(GrTexture* gr_texture, + const gpu::Mailbox& mailbox) { + DCHECK(cached_mailboxes_.find(gr_texture) == cached_mailboxes_.end()); + cached_mailboxes_.insert(gr_texture, mailbox); +} + void GraphicsContext3DUtils::RemoveCachedMailbox(GrTexture* gr_texture) { cached_mailboxes_.erase(gr_texture); }
diff --git a/third_party/blink/renderer/platform/graphics/gpu/graphics_context_3d_utils.h b/third_party/blink/renderer/platform/graphics/gpu/graphics_context_3d_utils.h index cea20e4..911dac0 100644 --- a/third_party/blink/renderer/platform/graphics/gpu/graphics_context_3d_utils.h +++ b/third_party/blink/renderer/platform/graphics/gpu/graphics_context_3d_utils.h
@@ -38,6 +38,7 @@ GLenum&, const sk_sp<SkImage>&, GLenum filter); + void RegisterMailbox(GrTexture*, const gpu::Mailbox&); void RemoveCachedMailbox(GrTexture*); bool Accelerated2DCanvasFeatureEnabled();
diff --git a/third_party/blink/renderer/platform/graphics/graphics_types.h b/third_party/blink/renderer/platform/graphics/graphics_types.h index c938ca49..ebce9b7 100644 --- a/third_party/blink/renderer/platform/graphics/graphics_types.h +++ b/third_party/blink/renderer/platform/graphics/graphics_types.h
@@ -129,7 +129,6 @@ kDisableDeferralReasonUnknown = 0, // Should not appear in production histograms kDisableDeferralReasonUsingTextureBackedPattern = 2, - kDisableDeferralReasonDrawImageOfVideo = 3, kDisableDeferralReasonLowEndDevice = 7, kDisableDeferralReasonCount, };
diff --git a/third_party/blink/renderer/platform/graphics/mailbox_texture_holder.cc b/third_party/blink/renderer/platform/graphics/mailbox_texture_holder.cc index 7dc7769..1693f32 100644 --- a/third_party/blink/renderer/platform/graphics/mailbox_texture_holder.cc +++ b/third_party/blink/renderer/platform/graphics/mailbox_texture_holder.cc
@@ -40,15 +40,17 @@ context_provider_wrapper, IntSize mailbox_size, bool is_origin_top_left) - : TextureHolder(std::move(context_provider_wrapper), is_origin_top_left), + : TextureHolder(std::move(context_provider_wrapper), + base::MakeRefCounted<MailboxRef>(nullptr), + is_origin_top_left), mailbox_(mailbox), - sync_token_(sync_token), texture_id_(texture_id_to_delete_after_mailbox_consumed), is_converted_from_skia_texture_(false), thread_id_(0), sk_image_info_(SkImageInfo::MakeN32Premul(mailbox_size.Width(), mailbox_size.Height())), texture_target_(GL_TEXTURE_2D) { + mailbox_ref()->set_sync_token(sync_token); InitCommon(); } @@ -57,26 +59,30 @@ const gpu::SyncToken& sync_token, base::WeakPtr<WebGraphicsContext3DProviderWrapper>&& context_provider_wrapper, + scoped_refptr<MailboxRef> mailbox_ref, PlatformThreadId context_thread_id, const SkImageInfo& sk_image_info, GLenum texture_target, bool is_origin_top_left) - : TextureHolder(std::move(context_provider_wrapper), is_origin_top_left), + : TextureHolder(std::move(context_provider_wrapper), + std::move(mailbox_ref), + is_origin_top_left), mailbox_(mailbox), - sync_token_(sync_token), texture_id_(0), is_converted_from_skia_texture_(false), thread_id_(context_thread_id), sk_image_info_(sk_image_info), texture_target_(texture_target) { DCHECK(thread_id_); - DCHECK(!IsCrossThread() || sync_token_.verified_flush()); + DCHECK(!IsCrossThread() || sync_token.verified_flush()); + this->mailbox_ref()->set_sync_token(sync_token); } MailboxTextureHolder::MailboxTextureHolder( const SkiaTextureHolder* texture_holder, GLenum filter) : TextureHolder(texture_holder->ContextProviderWrapper(), + texture_holder->mailbox_ref(), texture_holder->IsOriginTopLeft()), texture_id_(0), is_converted_from_skia_texture_(true), @@ -95,11 +101,13 @@ } void MailboxTextureHolder::Sync(MailboxSyncMode mode) { + gpu::SyncToken sync_token = mailbox_ref()->sync_token(); + if (IsCrossThread()) { // Was originally created on another thread. Should already have a sync // token from the original source context, already verified if needed. - DCHECK(sync_token_.HasData()); - DCHECK(mode != kVerifiedSyncToken || sync_token_.verified_flush()); + DCHECK(sync_token.HasData()); + DCHECK(mode != kVerifiedSyncToken || sync_token.verified_flush()); return; } @@ -119,25 +127,27 @@ return; } - if (!sync_token_.HasData()) { + if (!sync_token.HasData()) { if (mode == kVerifiedSyncToken) { - gl->GenSyncTokenCHROMIUM(sync_token_.GetData()); + gl->GenSyncTokenCHROMIUM(sync_token.GetData()); } else { - gl->GenUnverifiedSyncTokenCHROMIUM(sync_token_.GetData()); + gl->GenUnverifiedSyncTokenCHROMIUM(sync_token.GetData()); } + mailbox_ref()->set_sync_token(sync_token); return; } // At this point we have a pre-existing sync token. We just need to verify // it if needed. Providing a verified sync token when unverified is requested // is fine. - if (mode == kVerifiedSyncToken && !sync_token_.verified_flush()) { - int8_t* token_data = sync_token_.GetData(); + if (mode == kVerifiedSyncToken && !sync_token.verified_flush()) { + int8_t* token_data = sync_token.GetData(); // TODO(junov): Batch this verification in the case where there are multiple // offscreen canvases being committed. gl->ShallowFlushCHROMIUM(); gl->VerifySyncTokensCHROMIUM(&token_data, 1); - sync_token_.SetVerifyFlush(); + sync_token.SetVerifyFlush(); + mailbox_ref()->set_sync_token(sync_token); } } @@ -163,7 +173,7 @@ MailboxTextureHolder::~MailboxTextureHolder() { std::unique_ptr<gpu::SyncToken> passed_sync_token( - new gpu::SyncToken(sync_token_)); + new gpu::SyncToken(mailbox_ref()->sync_token())); std::unique_ptr<gpu::Mailbox> passed_mailbox(new gpu::Mailbox(mailbox_)); if (texture_thread_task_runner_ &&
diff --git a/third_party/blink/renderer/platform/graphics/mailbox_texture_holder.h b/third_party/blink/renderer/platform/graphics/mailbox_texture_holder.h index 63eb042..930f022d 100644 --- a/third_party/blink/renderer/platform/graphics/mailbox_texture_holder.h +++ b/third_party/blink/renderer/platform/graphics/mailbox_texture_holder.h
@@ -31,8 +31,12 @@ bool IsCrossThread() const; const gpu::Mailbox& GetMailbox() const { return mailbox_; } - const gpu::SyncToken& GetSyncToken() const { return sync_token_; } - void UpdateSyncToken(gpu::SyncToken sync_token) { sync_token_ = sync_token; } + const gpu::SyncToken& GetSyncToken() const { + return mailbox_ref()->sync_token(); + } + void UpdateSyncToken(gpu::SyncToken sync_token) { + mailbox_ref()->set_sync_token(sync_token); + } const SkImageInfo& sk_image_info() const { return sk_image_info_; } GLenum texture_target() const { return texture_target_; } @@ -55,6 +59,7 @@ MailboxTextureHolder(const gpu::Mailbox&, const gpu::SyncToken&, base::WeakPtr<WebGraphicsContext3DProviderWrapper>&&, + scoped_refptr<MailboxRef> mailbox_ref, PlatformThreadId context_thread_id, const SkImageInfo& sk_image_info, GLenum texture_target, @@ -64,7 +69,6 @@ void InitCommon(); gpu::Mailbox mailbox_; - gpu::SyncToken sync_token_; unsigned texture_id_; bool is_converted_from_skia_texture_; scoped_refptr<base::SingleThreadTaskRunner> texture_thread_task_runner_;
diff --git a/third_party/blink/renderer/platform/graphics/skia_texture_holder.cc b/third_party/blink/renderer/platform/graphics/skia_texture_holder.cc index a486fe3..a361d77 100644 --- a/third_party/blink/renderer/platform/graphics/skia_texture_holder.cc +++ b/third_party/blink/renderer/platform/graphics/skia_texture_holder.cc
@@ -14,27 +14,54 @@ #include "third_party/skia/include/gpu/GrBackendSurface.h" #include "third_party/skia/include/gpu/GrContext.h" +namespace blink { + namespace { bool IsSkImageOriginTopLeft(sk_sp<SkImage> image) { GrSurfaceOrigin origin; image->getBackendTexture(false, &origin); return origin == kTopLeft_GrSurfaceOrigin; } -} // namespace -namespace blink { +struct ReleaseContext { + scoped_refptr<TextureHolder::MailboxRef> mailbox_ref; + GLuint texture_id = 0u; + bool is_shared_image = false; + GrTexture* gr_texture = nullptr; + base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper; +}; + +void ReleaseTexture(void* ctx) { + auto* release_ctx = static_cast<ReleaseContext*>(ctx); + if (release_ctx->context_provider_wrapper) { + release_ctx->context_provider_wrapper->Utils()->RemoveCachedMailbox( + release_ctx->gr_texture); + + auto* gl = + release_ctx->context_provider_wrapper->ContextProvider()->ContextGL(); + if (release_ctx->is_shared_image) + gl->EndSharedImageAccessDirectCHROMIUM(release_ctx->texture_id); + gl->DeleteTextures(1u, &release_ctx->texture_id); + } + + delete release_ctx; +} + +} // namespace SkiaTextureHolder::SkiaTextureHolder( sk_sp<SkImage> image, base::WeakPtr<WebGraphicsContext3DProviderWrapper>&& context_provider_wrapper) : TextureHolder(std::move(context_provider_wrapper), + base::MakeRefCounted<MailboxRef>(nullptr), IsSkImageOriginTopLeft(image)), image_(std::move(image)) {} SkiaTextureHolder::SkiaTextureHolder( const MailboxTextureHolder* mailbox_texture_holder) : TextureHolder(SharedGpuContext::ContextProviderWrapper(), + mailbox_texture_holder->mailbox_ref(), mailbox_texture_holder->IsOriginTopLeft()) { const gpu::Mailbox mailbox = mailbox_texture_holder->GetMailbox(); const gpu::SyncToken sync_token = mailbox_texture_holder->GetSyncToken(); @@ -56,11 +83,9 @@ shared_gl->CreateAndTexStorage2DSharedImageCHROMIUM(mailbox.name); shared_gl->BeginSharedImageAccessDirectCHROMIUM( shared_context_texture_id, GL_SHARED_IMAGE_ACCESS_MODE_READ_CHROMIUM); - shared_image_texture_id_ = shared_context_texture_id; } else { shared_context_texture_id = shared_gl->CreateAndConsumeTextureCHROMIUM(mailbox.name); - shared_image_texture_id_ = 0u; } GrGLTextureInfo texture_info; @@ -75,18 +100,28 @@ GrSurfaceOrigin origin = IsOriginTopLeft() ? kTopLeft_GrSurfaceOrigin : kBottomLeft_GrSurfaceOrigin; - image_ = SkImage::MakeFromAdoptedTexture( + auto* release_ctx = new ReleaseContext; + release_ctx->mailbox_ref = mailbox_ref(); + release_ctx->texture_id = shared_context_texture_id; + release_ctx->is_shared_image = mailbox.IsSharedImage(); + release_ctx->context_provider_wrapper = ContextProviderWrapper(); + + image_ = SkImage::MakeFromTexture( shared_gr_context, backend_texture, origin, sk_image_info.colorType(), - sk_image_info.alphaType(), sk_image_info.refColorSpace()); + sk_image_info.alphaType(), sk_image_info.refColorSpace(), &ReleaseTexture, + release_ctx); + if (image_) { + release_ctx->gr_texture = image_->getTexture(); + ContextProviderWrapper()->Utils()->RegisterMailbox(image_->getTexture(), + mailbox); + } else { + delete release_ctx; + } } SkiaTextureHolder::~SkiaTextureHolder() { // Object must be destroyed on the same thread where it was created. DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - if (shared_image_texture_id_ && ContextProvider()) { - ContextProvider()->ContextGL()->EndSharedImageAccessDirectCHROMIUM( - shared_image_texture_id_); - } } bool SkiaTextureHolder::IsValid() const {
diff --git a/third_party/blink/renderer/platform/graphics/skia_texture_holder.h b/third_party/blink/renderer/platform/graphics/skia_texture_holder.h index 0cfc9a3..5053f795 100644 --- a/third_party/blink/renderer/platform/graphics/skia_texture_holder.h +++ b/third_party/blink/renderer/platform/graphics/skia_texture_holder.h
@@ -40,7 +40,6 @@ // The image_ should always be texture-backed. sk_sp<SkImage> image_; - GLuint shared_image_texture_id_ = 0u; THREAD_CHECKER(thread_checker_); };
diff --git a/third_party/blink/renderer/platform/graphics/texture_holder.h b/third_party/blink/renderer/platform/graphics/texture_holder.h index e14fc6e7..a1ba07e2 100644 --- a/third_party/blink/renderer/platform/graphics/texture_holder.h +++ b/third_party/blink/renderer/platform/graphics/texture_holder.h
@@ -6,6 +6,7 @@ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_TEXTURE_HOLDER_H_ #include "base/memory/weak_ptr.h" +#include "components/viz/common/resources/single_release_callback.h" #include "gpu/command_buffer/common/mailbox.h" #include "gpu/command_buffer/common/sync_token.h" #include "third_party/blink/renderer/platform/geometry/int_size.h" @@ -13,6 +14,7 @@ #include "third_party/blink/renderer/platform/graphics/image.h" #include "third_party/blink/renderer/platform/graphics/web_graphics_context_3d_provider_wrapper.h" #include "third_party/blink/renderer/platform/platform_export.h" +#include "third_party/blink/renderer/platform/wtf/thread_safe_ref_counted.h" #include "third_party/skia/include/core/SkImage.h" #include "third_party/skia/include/core/SkRefCnt.h" @@ -20,6 +22,24 @@ class PLATFORM_EXPORT TextureHolder { public: + class MailboxRef : public ThreadSafeRefCounted<MailboxRef> { + public: + explicit MailboxRef( + std::unique_ptr<viz::SingleReleaseCallback> release_callback) + : release_callback_(std::move(release_callback)) {} + ~MailboxRef() { + if (release_callback_) + release_callback_->Run(sync_token_, false /* resource_lost */); + } + + void set_sync_token(gpu::SyncToken token) { sync_token_ = token; } + const gpu::SyncToken& sync_token() const { return sync_token_; } + + private: + gpu::SyncToken sync_token_; + std::unique_ptr<viz::SingleReleaseCallback> release_callback_; + }; + virtual ~TextureHolder() = default; // Methods overridden by all sub-classes @@ -41,15 +61,22 @@ bool IsOriginTopLeft() const { return is_origin_top_left_; } + const scoped_refptr<MailboxRef>& mailbox_ref() const { return mailbox_ref_; } + protected: TextureHolder(base::WeakPtr<WebGraphicsContext3DProviderWrapper>&& context_provider_wrapper, + scoped_refptr<MailboxRef> mailbox_ref, bool is_origin_top_left) : context_provider_wrapper_(std::move(context_provider_wrapper)), - is_origin_top_left_(is_origin_top_left) {} + mailbox_ref_(std::move(mailbox_ref)), + is_origin_top_left_(is_origin_top_left) { + DCHECK(mailbox_ref_); + } private: base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper_; + scoped_refptr<MailboxRef> mailbox_ref_; bool is_origin_top_left_; };
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index bc0bf2a..6f5b6c4 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -291,6 +291,9 @@ status: "experimental", }, { + name: "ConsolidatedMovementXY", + }, + { name: "ContactsManager", origin_trial_feature_name: "ContactsManager", status: "experimental", @@ -944,9 +947,6 @@ status: "test", }, { - name: "MovementXYInBlink", - }, - { name: "MuteButton", depends_on: ["PictureInPictureAPI"], origin_trial_feature_name: "MuteButton",
diff --git a/third_party/blink/renderer/platform/scheduler/common/thread.cc b/third_party/blink/renderer/platform/scheduler/common/thread.cc index c95408a..aa970db 100644 --- a/third_party/blink/renderer/platform/scheduler/common/thread.cc +++ b/third_party/blink/renderer/platform/scheduler/common/thread.cc
@@ -29,6 +29,16 @@ namespace { +// Controls whether we use ThreadPriority::DISPLAY for compositor thread. +const base::Feature kBlinkCompositorUseDisplayThreadPriority { + "BlinkCompositorUseDisplayThreadPriority", +#if defined(OS_ANDROID) || defined(OS_CHROMEOS) || defined(USE_OZONE) + base::FEATURE_ENABLED_BY_DEFAULT +#else + base::FEATURE_DISABLED_BY_DEFAULT +#endif +}; + // Thread-local storage for "blink::Thread"s. Thread*& ThreadTLSSlot() { DEFINE_THREAD_SAFE_STATIC_LOCAL(WTF::ThreadSpecific<Thread*>, thread_tls_slot, @@ -112,9 +122,9 @@ DCHECK(!GetCompositorThread()); ThreadCreationParams params(WebThreadType::kCompositorThread); -#if defined(OS_ANDROID) || defined(OS_CHROMEOS) || defined(USE_OZONE) - params.thread_priority = base::ThreadPriority::DISPLAY; -#endif + if (base::FeatureList::IsEnabled(kBlinkCompositorUseDisplayThreadPriority)) + params.thread_priority = base::ThreadPriority::DISPLAY; + auto compositor_thread = std::make_unique<scheduler::CompositorThread>(params); compositor_thread->Init();
diff --git a/third_party/blink/tools/blinkpy/common/config/builders.json b/third_party/blink/tools/blinkpy/common/config/builders.json index b10bfc42..9598ebe 100644 --- a/third_party/blink/tools/blinkpy/common/config/builders.json +++ b/third_party/blink/tools/blinkpy/common/config/builders.json
@@ -72,6 +72,8 @@ "linux-blink-rel": { "port_name": "linux-trusty", "specifiers": ["Trusty", "Release"], + "master": "tryserver.blink", + "has_webdriver_tests": true, "is_try_builder": true }, "mac10.10-blink-rel": { @@ -108,12 +110,5 @@ "port_name": "win-win10", "specifiers": ["Win10", "Release"], "is_try_builder": true - }, - "linux-rel": { - "bucket": "luci.chromium.try", - "port_name": "linux-trusty", - "specifiers": ["Trusty", "Release"], - "master": "tryserver.chromium.linux", - "is_try_builder": false } }
diff --git a/third_party/blink/tools/blinkpy/common/net/buildbot.py b/third_party/blink/tools/blinkpy/common/net/buildbot.py index 874bc64..b9fa6cec 100644 --- a/third_party/blink/tools/blinkpy/common/net/buildbot.py +++ b/third_party/blink/tools/blinkpy/common/net/buildbot.py
@@ -110,11 +110,6 @@ def accumulated_results_url_base(self, builder_name): return self.builder_results_url_base(builder_name) + '/results/layout-test-results' - def fetch_full_results(self, build, full=False, master=''): - if master: - return self.fetch_webdriver_test_results(build, master) - return self.fetch_results(build, full) - @memoized def fetch_results(self, build, full=False): """Returns a WebTestResults object for results from a given Build.
diff --git a/third_party/blink/tools/blinkpy/common/net/buildbot_mock.py b/third_party/blink/tools/blinkpy/common/net/buildbot_mock.py index 076c8506..2ca7f49 100644 --- a/third_party/blink/tools/blinkpy/common/net/buildbot_mock.py +++ b/third_party/blink/tools/blinkpy/common/net/buildbot_mock.py
@@ -36,7 +36,9 @@ super(MockBuildBot, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} + self._webdriver_results = {} self.fetched_builds = [] + self.fetched_webdriver_builds = [] self._layout_test_step_name = 'webkit_layout_tests (with patch)' def set_results(self, build, results): @@ -46,6 +48,13 @@ self.fetched_builds.append(build) return self._canned_results.get(build) + def set_webdriver_test_results(self, build, master, results): + self._webdriver_results[(build, master)] = results + + def fetch_webdriver_test_results(self, build, master): + self.fetched_webdriver_builds.append((build, master)) + return self._webdriver_results.get((build, master)) + def set_retry_sumary_json(self, build, content): self._canned_retry_summary_json[build] = content
diff --git a/third_party/blink/tools/blinkpy/common/net/buildbot_unittest.py b/third_party/blink/tools/blinkpy/common/net/buildbot_unittest.py index b90a2a59..deb460a 100644 --- a/third_party/blink/tools/blinkpy/common/net/buildbot_unittest.py +++ b/third_party/blink/tools/blinkpy/common/net/buildbot_unittest.py
@@ -128,24 +128,26 @@ buildbot = BuildBot() self.assertIsNone(buildbot.fetch_webdriver_test_results( Build('builder', None), 'bar')) - self.assertLog(['DEBUG: Builder name or build number or master is None\n']) + self.assertLog( + ['DEBUG: Builder name or build number or master is None\n']) def test_fetch_webdriver_results_without_master(self): buildbot = BuildBot() self.assertIsNone(buildbot.fetch_webdriver_test_results( Build('builder', 1), '')) - self.assertLog(['DEBUG: Builder name or build number or master is None\n']) + self.assertLog( + ['DEBUG: Builder name or build number or master is None\n']) def test_fetch_webdriver_test_results_with_no_results(self): buildbot = BuildBot() buildbot.web = MockWeb() results = buildbot.fetch_webdriver_test_results( - Build('linux-rel', 123), 'tryserver.chromium.linux') + Build('bar-rel', 123), 'foo.chrome') self.assertIsNone(results) self.assertLog([ 'DEBUG: Got 404 response from:\n' 'https://test-results.appspot.com/testfile?buildnumber=123&' - 'master=tryserver.chromium.linux&builder=linux-rel&' + 'master=foo.chrome&builder=bar-rel&' 'testtype=webdriver_tests_suite+%28with+patch%29&name=full_results.json\n' ]) @@ -153,48 +155,13 @@ buildbot = BuildBot() buildbot.web = MockWeb(urls={ 'https://test-results.appspot.com/testfile?buildnumber=123&' - 'master=tryserver.chromium.linux&builder=linux-rel&' + 'master=foo.chrome&builder=bar-rel&' 'testtype=webdriver_tests_suite+%28with+patch%29&' 'name=full_results.json': json.dumps({'passed': True}), }) results = buildbot.fetch_webdriver_test_results( - Build('linux-rel', 123), 'tryserver.chromium.linux') - self.assertEqual(results._results, { # pylint: disable=protected-access - 'passed': True - }) - self.assertLog([]) - - def test_fetch_full_results_webdriver(self): - buildbot = BuildBot() - buildbot.web = MockWeb(urls={ - 'https://test-results.appspot.com/testfile?buildnumber=321&' - 'master=tryserver.chromium.linux&builder=foo&' - 'testtype=webdriver_tests_suite+%28with+patch%29&' - 'name=full_results.json': - json.dumps({'passed': True}), - }) - results = buildbot.fetch_full_results( - Build('foo', 321), master='tryserver.chromium.linux') - self.assertEqual(results._results, { # pylint: disable=protected-access - 'passed': True - }) - self.assertLog([]) - - def test_fetch_full_results_web_tests(self): - buildbot = BuildBot() - buildbot.web = MockWeb(urls={ - 'https://test-results.appspot.com/testfile?buildnumber=123&' - 'callback=ADD_RESULTS&builder=builder&name=full_results.json': - 'ADD_RESULTS(%s);' % (json.dumps( - [{"TestType": "webkit_layout_tests on Intel GPU (with patch)"}, - {"TestType": "base_unittests (with patch)"}])), - 'https://test-results.appspot.com/data/layout_results/builder/123/' - 'webkit_layout_tests%20on%20Intel%20GPU%20%28with%20patch%29/' - 'layout-test-results/failing_results.json': - json.dumps({'passed': True}), - }) - results = buildbot.fetch_full_results(Build('builder', 123), master='') + Build('bar-rel', 123), 'foo.chrome') self.assertEqual(results._results, { # pylint: disable=protected-access 'passed': True })
diff --git a/third_party/blink/tools/blinkpy/w3c/wpt_expectations_updater.py b/third_party/blink/tools/blinkpy/w3c/wpt_expectations_updater.py index 70acacfa..58897842 100644 --- a/third_party/blink/tools/blinkpy/w3c/wpt_expectations_updater.py +++ b/third_party/blink/tools/blinkpy/w3c/wpt_expectations_updater.py
@@ -131,13 +131,26 @@ # All tests passed, so there should be no failing results. return {} - master = self.host.builders.master_for_builder(build.builder_name) - web_test_results = self.host.buildbot.fetch_full_results(build, master=master) - if web_test_results is None: + test_result_list = [self.host.buildbot.fetch_results(build)] + has_webdriver_tests = self.host.builders.has_webdriver_tests_for_builder( + build.builder_name) + if has_webdriver_tests: + master = self.host.builders.master_for_builder( + build.builder_name) + test_result_list.append( + self.host.buildbot.fetch_webdriver_test_results(build, master)) + + test_result_list = filter(None, test_result_list) + if not test_result_list: _log.warning('No results for build %s', build) self.ports_with_no_results.add(self.port_name(build)) return {} - failing_test_results = [result for result in web_test_results.didnt_run_as_expected_results() if not result.did_pass()] + + failing_test_results = [] + for test_result in test_result_list: + failing_test_results += [ + result for result in test_result.didnt_run_as_expected_results() if not result.did_pass()] + return self.generate_results_dict(self.port_name(build), failing_test_results) @memoized
diff --git a/third_party/blink/tools/blinkpy/w3c/wpt_expectations_updater_unittest.py b/third_party/blink/tools/blinkpy/w3c/wpt_expectations_updater_unittest.py index 8c35226f..3bf488c 100644 --- a/third_party/blink/tools/blinkpy/w3c/wpt_expectations_updater_unittest.py +++ b/third_party/blink/tools/blinkpy/w3c/wpt_expectations_updater_unittest.py
@@ -41,6 +41,8 @@ 'MOCK Try Trusty': { 'port_name': 'test-linux-trusty', 'specifiers': ['Trusty', 'Release'], + 'master': 'tryserver.blink', + 'has_webdriver_tests': True, 'is_try_builder': True, }, 'MOCK Try Precise': { @@ -229,6 +231,63 @@ results_dict = updater.get_failing_results_dict(Build('MOCK Try Mac10.10', 123)) self.assertEqual(results_dict, {}) + def test_get_failing_results_dict_webdriver_failing_results_(self): + host = self.mock_host() + host.buildbot.set_results(Build('MOCK Try Trusty', 123), WebTestResults({ + 'tests': { + 'external': { + 'wpt': { + 'x': { + 'failing-test.html': { + 'expected': 'PASS', + 'actual': 'IMAGE', + 'is_unexpected': True, + }, + }, + }, + }, + }, + })) + + host.buildbot.set_webdriver_test_results(Build('MOCK Try Trusty', 123), "tryserver.blink", WebTestResults({ + 'tests': { + 'external': { + 'wpt': { + 'y': { + 'webdriver-fail.html': { + 'expected': 'PASS', + 'actual': 'FAIL', + 'is_unexpected': True, + }, + }, + }, + }, + }, + })) + updater = WPTExpectationsUpdater(host) + results_dict = updater.get_failing_results_dict( + Build('MOCK Try Trusty', 123)) + + self.assertEqual(len(results_dict.keys()), 2) + self.assertEqual( + results_dict, + { + 'external/wpt/x/failing-test.html': { + 'test-linux-trusty': SimpleTestResult( + actual='IMAGE', + expected='PASS', + bug='crbug.com/626703', + ), + }, + 'external/wpt/y/webdriver-fail.html': { + 'test-linux-trusty': SimpleTestResult( + actual='FAIL', + expected='PASS', + bug='crbug.com/626703', + ), + }, + }) + def test_merge_same_valued_keys_all_match(self): updater = WPTExpectationsUpdater(self.mock_host()) self.assertEqual(
diff --git a/third_party/blink/tools/blinkpy/web_tests/builder_list.py b/third_party/blink/tools/blinkpy/web_tests/builder_list.py index 26ea0121..b4aa967 100644 --- a/third_party/blink/tools/blinkpy/web_tests/builder_list.py +++ b/third_party/blink/tools/blinkpy/web_tests/builder_list.py
@@ -51,6 +51,7 @@ "is_try_builder": Whether the builder is a try bot. "master": The master name of the builder. It is deprecated, but still required by test-results.appspot.com API." + "has_webdriver_tests": Whether webdriver_tests_suite runs on this builder. Possible refactoring note: Potentially, it might make sense to use blinkpy.common.buildbot.Builder and add port_name and specifiers @@ -87,6 +88,9 @@ def master_for_builder(self, builder_name): return self._builders[builder_name].get('master', '') + def has_webdriver_tests_for_builder(self, builder_name): + return self._builders[builder_name].get('has_webdriver_tests') + def port_name_for_builder_name(self, builder_name): return self._builders[builder_name]['port_name']
diff --git a/third_party/blink/tools/blinkpy/web_tests/builder_list_unittest.py b/third_party/blink/tools/blinkpy/web_tests/builder_list_unittest.py index 7e8924c..9ec9843 100644 --- a/third_party/blink/tools/blinkpy/web_tests/builder_list_unittest.py +++ b/third_party/blink/tools/blinkpy/web_tests/builder_list_unittest.py
@@ -44,7 +44,7 @@ 'Try B': {'port_name': 'port-b', 'specifiers': ['B', 'Release'], 'is_try_builder': True}, 'CQ Try A': {'bucket': 'bucket.a', 'port_name': 'port-a', 'specifiers': ['A', 'Release'], 'is_try_builder': True}, 'CQ Try B': {'bucket': 'bucket.b', 'port_name': 'port-b', 'specifiers': ['B', 'Release'], 'is_try_builder': True}, - 'CQ Try C': {'bucket': 'bucket.c', 'port_name': 'port-c', 'specifiers': ['c', 'Release'], 'is_try_builder': True, 'master': "luci"}, + 'CQ Try C': {'bucket': 'bucket.c', 'port_name': 'port-c', 'specifiers': ['c', 'Release'], 'is_try_builder': True, 'master': "luci", 'has_webdriver_tests': True}, }) def test_constructor_validates_list(self): @@ -86,6 +86,16 @@ builders = self.sample_builder_list() self.assertEqual('luci', builders.master_for_builder('CQ Try C')) + def test_has_webdriver_tests_for_builder_default_value(self): + builders = self.sample_builder_list() + self.assertEqual( + None, builders.has_webdriver_tests_for_builder('Try A')) + + def test_has_webdriver_tests_for_builder_configured_value(self): + builders = self.sample_builder_list() + self.assertEqual( + True, builders.has_webdriver_tests_for_builder('CQ Try C')) + def test_port_name_for_builder_name(self): builders = self.sample_builder_list() self.assertEqual('port-b', builders.port_name_for_builder_name('Blink B'))
diff --git a/third_party/blink/web_tests/FlagExpectations/enable-blink-features=CompositeAfterPaint b/third_party/blink/web_tests/FlagExpectations/enable-blink-features=CompositeAfterPaint index 11c069d..9ce2a75 100644 --- a/third_party/blink/web_tests/FlagExpectations/enable-blink-features=CompositeAfterPaint +++ b/third_party/blink/web_tests/FlagExpectations/enable-blink-features=CompositeAfterPaint
@@ -393,7 +393,6 @@ crbug.com/923429 css3/filters/backdrop-filter-browser-zoom.html [ Failure ] crbug.com/923429 css3/filters/backdrop-filter-border-radius.html [ Failure ] crbug.com/923429 css3/filters/backdrop-filter-clip-rect-zoom.html [ Failure ] -crbug.com/923429 css3/filters/backdrop-filter-plus-filter.html [ Failure ] crbug.com/923429 css3/filters/backdrop-filter-rendering.html [ Failure ] crbug.com/923429 css3/filters/backdrop-filter-rendering-no-background.html [ Failure ] crbug.com/923429 css3/filters/backdrop-filter-transform.html [ Failure ] @@ -408,13 +407,13 @@ crbug.com/923429 external/wpt/css/filter-effects/backdrop-filter-isolation-isolate.html [ Failure ] crbug.com/923429 external/wpt/css/filter-effects/backdrop-filter-update.html [ Failure ] crbug.com/923429 external/wpt/css/filter-effects/backdrop-filter-clipped.html [ Failure ] +crbug.com/923429 external/wpt/css/filter-effects/backdrop-filter-plus-filter.html [ Failure ] crbug.com/923429 virtual/scalefactor200/css3/filters/backdrop-filter-basic-blur.html [ Failure ] crbug.com/923429 virtual/scalefactor200/css3/filters/backdrop-filter-border-radius.html [ Failure ] crbug.com/923429 virtual/scalefactor200/css3/filters/backdrop-filter-boundary.html [ Failure ] crbug.com/923429 virtual/scalefactor200/css3/filters/backdrop-filter-browser-zoom.html [ Failure ] crbug.com/923429 virtual/scalefactor200/css3/filters/backdrop-filter-clip-rect-zoom.html [ Failure ] crbug.com/923429 virtual/scalefactor200/css3/filters/backdrop-filter-edge-pixels.html [ Failure ] -crbug.com/923429 virtual/scalefactor200/css3/filters/backdrop-filter-plus-filter.html [ Failure ] crbug.com/923429 virtual/scalefactor200/css3/filters/backdrop-filter-rendering-no-background.html [ Failure ] crbug.com/923429 virtual/scalefactor200/css3/filters/backdrop-filter-rendering.html [ Failure ] crbug.com/923429 virtual/scalefactor200/css3/filters/backdrop-filter-transform.html [ Failure ] @@ -427,6 +426,7 @@ crbug.com/923429 virtual/scalefactor200/external/wpt/css/filter-effects/backdrop-filter-isolation-isolate.html [ Failure ] crbug.com/923429 virtual/scalefactor200/external/wpt/css/filter-effects/backdrop-filter-isolation.html [ Failure ] crbug.com/923429 virtual/scalefactor200/external/wpt/css/filter-effects/backdrop-filter-update.html [ Failure ] +crbug.com/923429 virtual/scalefactor200/external/wpt/css/filter-effects/backdrop-filter-plus-filter.html [ Failure ] crbug.com/940033 virtual/fractional_scrolling_threaded/fast/scrolling/wheel-scrolling-over-custom-scrollbar.html [ Failure ] crbug.com/940033 virtual/threaded/fast/scrolling/wheel-scrolling-over-custom-scrollbar.html [ Failure ]
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index cc8077e..bdef700c 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -5843,7 +5843,6 @@ crbug.com/970142 virtual/blink-cors/http/tests/security/mixedContent/insecure-css-resources.html [ Failure ] # Sheriff 2019-06-05 -crbug.com/971252 [ Mac ] external/wpt/media-source/mediasource-play.html [ Pass Timeout ] crbug.com/971259 media/controls/volumechange-stopimmediatepropagation.html [ Pass Failure ] crbug.com/971262 http/tests/devtools/profiler/live-line-level-heap-profile.js [ Pass Timeout ] crbug.com/971319 [ Mac ] media/audio-garbage-collect.html [ Pass Timeout ]
diff --git a/third_party/blink/web_tests/css3/filters/backdrop-filter-plus-filter-expected.png b/third_party/blink/web_tests/css3/filters/backdrop-filter-plus-filter-expected.png deleted file mode 100644 index 89c49dc..0000000 --- a/third_party/blink/web_tests/css3/filters/backdrop-filter-plus-filter-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/css3/filters/backdrop-filter-plus-filter.html b/third_party/blink/web_tests/css3/filters/backdrop-filter-plus-filter.html deleted file mode 100644 index 602a4a3..0000000 --- a/third_party/blink/web_tests/css3/filters/backdrop-filter-plus-filter.html +++ /dev/null
@@ -1,36 +0,0 @@ -<!DOCTYPE html> -<div class="container"> - <div class="orangebox"></div> - <div class="bluebox blur blur-bd"></div> -</div> - - -<style> -div { - width: 100px; - height: 100px; - position :absolute; -} -.container { - width:200px; - height:200px; - position:absolute; -} -.blur { - -webkit-filter: blur(3px); - filter: blur(3px); -} -.blur-bd { - backdrop-filter: blur(15px); -} -.orangebox { - left: 10px; - top: 50px; - background: orange; -} -.bluebox { - left: 60px; - top: 110px; - background: #0000ff33; -} -</style>
diff --git a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json index 0f9141b9..6006a772 100644 --- a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json +++ b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json
@@ -97673,6 +97673,18 @@ {} ] ], + "css/filter-effects/backdrop-filter-edge-clipping.html": [ + [ + "css/filter-effects/backdrop-filter-edge-clipping.html", + [ + [ + "/css/filter-effects/backdrop-filter-paint-order-ref.html", + "==" + ] + ], + {} + ] + ], "css/filter-effects/backdrop-filter-edge-pixels.html": [ [ "css/filter-effects/backdrop-filter-edge-pixels.html", @@ -395105,6 +395117,10 @@ "bc25b25944f47d6f053580939752803f0b929c99", "reftest" ], + "css/filter-effects/backdrop-filter-edge-clipping.html": [ + "5d09c414497de3d1d34bf2a6032c94c87a9bdb82", + "reftest" + ], "css/filter-effects/backdrop-filter-edge-pixels-ref.html": [ "bbd562856f7a0ee305874575935c66e8b4830c1d", "support"
diff --git a/third_party/blink/web_tests/external/wpt/css/filter-effects/backdrop-filter-plus-filter-ref.html b/third_party/blink/web_tests/external/wpt/css/filter-effects/backdrop-filter-plus-filter-ref.html new file mode 100644 index 0000000..bf476ea --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/filter-effects/backdrop-filter-plus-filter-ref.html
@@ -0,0 +1,49 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>backdrop-filter: Only filter objects painted before</title> +<link rel="author" title="Mason Freed" href="mailto:masonfreed@chromium.org"> + + + +<p>Expected: A green box with an overlapping purple box.<br> +The overlapping portion of the boxes should be bright magenta.<br> + +<div class="container"> + <div class="orangebox"></div> + <div class="bluebox blur-bd"></div> + <div class="invert"></div> +</div> + + +<style> +div { + position: absolute; + width: 100px; + height: 100px; +} +.container { + width:200px; + height:200px; + top: 50px; + position:absolute; +} +.blur-bd { + backdrop-filter: blur(10px); +} +.orangebox { + left: 10px; + top: 50px; + background: green; +} +.bluebox { + left: 60px; + top: 110px; + background: #00ff0055; +} +.invert { + left: 60px; + top: 110px; + background: transparent; + backdrop-filter: invert(1); +} +</style>
diff --git a/third_party/blink/web_tests/external/wpt/css/filter-effects/backdrop-filter-plus-filter.html b/third_party/blink/web_tests/external/wpt/css/filter-effects/backdrop-filter-plus-filter.html new file mode 100644 index 0000000..3a2d8fe --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/filter-effects/backdrop-filter-plus-filter.html
@@ -0,0 +1,45 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>backdrop-filter: Correctly apply filters to backdrop-filter content</title> +<link rel="author" title="Mason Freed" href="mailto:masonfreed@chromium.org"> +<link rel="help" href="https://drafts.fxtf.org/filter-effects-2/#BackdropFilterProperty"> +<link rel="match" href="backdrop-filter-plus-filter-ref.html"> + +<p>Expected: A green box with an overlapping purple box.<br> +The overlapping portion of the boxes should be bright magenta.<br> + +<div class="container"> + <div class="orangebox"></div> + <div class="bluebox blur blur-bd"></div> +</div> + + +<style> +div { + position: absolute; + width: 100px; + height: 100px; +} +.container { + width:200px; + height:200px; + top: 50px; + position:absolute; +} +.blur { + filter: invert(1); +} +.blur-bd { + backdrop-filter: blur(10px); +} +.orangebox { + left: 10px; + top: 50px; + background: green; +} +.bluebox { + left: 60px; + top: 110px; + background: #00ff0055; +} +</style>
diff --git a/third_party/blink/web_tests/external/wpt/media-source/mediasource-play.html b/third_party/blink/web_tests/external/wpt/media-source/mediasource-play.html index 62fb046..2129b8f 100644 --- a/third_party/blink/web_tests/external/wpt/media-source/mediasource-play.html +++ b/third_party/blink/web_tests/external/wpt/media-source/mediasource-play.html
@@ -3,6 +3,7 @@ <html> <head> <title>Simple MediaSource playback test case.</title> + <meta name="timeout" content="long"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="mediasource-util.js"></script>
diff --git a/third_party/blink/web_tests/external/wpt/mediasession/setactionhandler.html b/third_party/blink/web_tests/external/wpt/mediasession/setactionhandler.html index dc7c3359..06d145b 100644 --- a/third_party/blink/web_tests/external/wpt/mediasession/setactionhandler.html +++ b/third_party/blink/web_tests/external/wpt/mediasession/setactionhandler.html
@@ -11,6 +11,7 @@ window.navigator.mediaSession.setActionHandler("nexttrack", null); window.navigator.mediaSession.setActionHandler("seekbackward", null); window.navigator.mediaSession.setActionHandler("seekforward", null); + window.navigator.mediaSession.setActionHandler("stop", null); }, "Test that setActionHandler() can be executed for supported actions"); test(function(t) {
diff --git a/third_party/blink/web_tests/external/wpt/service-workers/service-worker/fetch-event-async-respond-with.https.html b/third_party/blink/web_tests/external/wpt/service-workers/service-worker/fetch-event-async-respond-with.https.html index ae64fcb9..d9147f8 100644 --- a/third_party/blink/web_tests/external/wpt/service-workers/service-worker/fetch-event-async-respond-with.https.html +++ b/third_party/blink/web_tests/external/wpt/service-workers/service-worker/fetch-event-async-respond-with.https.html
@@ -44,10 +44,12 @@ assert_equals(response, 'messageHandlerInitialized'); // Start a fetch. - frame.contentWindow.fetch(url); + const fetchPromise = frame.contentWindow.fetch(url); // Receive the test result from the service worker. - return wait_for_message(); + const result = wait_for_message(); + await fetchPromise.then(()=> {}, () => {}); + return result; }; promise_test(async (t) => {
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=LayoutNG/fast/text/selection/selection-rect-line-height-too-small-expected.png b/third_party/blink/web_tests/flag-specific/enable-blink-features=LayoutNG/fast/text/selection/selection-rect-line-height-too-small-expected.png index 04f9505..302922b 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=LayoutNG/fast/text/selection/selection-rect-line-height-too-small-expected.png +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=LayoutNG/fast/text/selection/selection-rect-line-height-too-small-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/repaint-across-writing-mode-boundary-expected.png b/third_party/blink/web_tests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/repaint-across-writing-mode-boundary-expected.png index dc4db36..b9105ca49 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/repaint-across-writing-mode-boundary-expected.png +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/repaint-across-writing-mode-boundary-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/repaint-across-writing-mode-boundary-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/repaint-across-writing-mode-boundary-expected.txt index 6cf00f0..5f51a1b5 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/repaint-across-writing-mode-boundary-expected.txt +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=LayoutNG/paint/invalidation/repaint-across-writing-mode-boundary-expected.txt
@@ -19,7 +19,7 @@ "paintInvalidations": [ { "object": "NGPhysicalTextFragment '\u7B2C\u4E00\u6BB5\u843D paragraph 1'", - "rect": [549, 191, 21, 36], + "rect": [548, 191, 23, 36], "reason": "selection" } ]
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=LayoutNG/paint/text/selection-no-clip-text-expected.png b/third_party/blink/web_tests/flag-specific/enable-blink-features=LayoutNG/paint/text/selection-no-clip-text-expected.png index 975d596..e95ce48 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=LayoutNG/paint/text/selection-no-clip-text-expected.png +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=LayoutNG/paint/text/selection-no-clip-text-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/fast/canvas/canvas-composite-video-expected.png b/third_party/blink/web_tests/platform/linux/fast/canvas/canvas-composite-video-expected.png index 9707867..b684f94 100644 --- a/third_party/blink/web_tests/platform/linux/fast/canvas/canvas-composite-video-expected.png +++ b/third_party/blink/web_tests/platform/linux/fast/canvas/canvas-composite-video-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/fast/canvas/canvas-composite-video-shadow-expected.png b/third_party/blink/web_tests/platform/linux/fast/canvas/canvas-composite-video-shadow-expected.png index fc7db0b..9d0294c1 100644 --- a/third_party/blink/web_tests/platform/linux/fast/canvas/canvas-composite-video-shadow-expected.png +++ b/third_party/blink/web_tests/platform/linux/fast/canvas/canvas-composite-video-shadow-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/fast/canvas/canvas-drawImage-video-expected.png b/third_party/blink/web_tests/platform/linux/fast/canvas/canvas-drawImage-video-expected.png index a58254b..697e8fb 100644 --- a/third_party/blink/web_tests/platform/linux/fast/canvas/canvas-drawImage-video-expected.png +++ b/third_party/blink/web_tests/platform/linux/fast/canvas/canvas-drawImage-video-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/media/alpha-video-playback-expected.png b/third_party/blink/web_tests/platform/linux/media/alpha-video-playback-expected.png index e2872f31..0e018ea 100644 --- a/third_party/blink/web_tests/platform/linux/media/alpha-video-playback-expected.png +++ b/third_party/blink/web_tests/platform/linux/media/alpha-video-playback-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/media/video-canvas-alpha-expected.png b/third_party/blink/web_tests/platform/linux/media/video-canvas-alpha-expected.png index d67be5e..528f3a79 100644 --- a/third_party/blink/web_tests/platform/linux/media/video-canvas-alpha-expected.png +++ b/third_party/blink/web_tests/platform/linux/media/video-canvas-alpha-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/gpu/fast/canvas/canvas-composite-video-expected.png b/third_party/blink/web_tests/platform/linux/virtual/gpu/fast/canvas/canvas-composite-video-expected.png index 05c18ef4..0e0de36f 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/gpu/fast/canvas/canvas-composite-video-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/gpu/fast/canvas/canvas-composite-video-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/gpu/fast/canvas/canvas-composite-video-shadow-expected.png b/third_party/blink/web_tests/platform/linux/virtual/gpu/fast/canvas/canvas-composite-video-shadow-expected.png index a3d1c3c6..70eb9b6 100644 --- a/third_party/blink/web_tests/platform/linux/virtual/gpu/fast/canvas/canvas-composite-video-shadow-expected.png +++ b/third_party/blink/web_tests/platform/linux/virtual/gpu/fast/canvas/canvas-composite-video-shadow-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/fast/canvas/canvas-composite-video-expected.png b/third_party/blink/web_tests/platform/win/fast/canvas/canvas-composite-video-expected.png index 5754aae..3961117 100644 --- a/third_party/blink/web_tests/platform/win/fast/canvas/canvas-composite-video-expected.png +++ b/third_party/blink/web_tests/platform/win/fast/canvas/canvas-composite-video-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/fast/canvas/canvas-composite-video-shadow-expected.png b/third_party/blink/web_tests/platform/win/fast/canvas/canvas-composite-video-shadow-expected.png index cbbdf17..9e2708d 100644 --- a/third_party/blink/web_tests/platform/win/fast/canvas/canvas-composite-video-shadow-expected.png +++ b/third_party/blink/web_tests/platform/win/fast/canvas/canvas-composite-video-shadow-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/media/alpha-video-playback-expected.png b/third_party/blink/web_tests/platform/win/media/alpha-video-playback-expected.png index 806797b..23777c3 100644 --- a/third_party/blink/web_tests/platform/win/media/alpha-video-playback-expected.png +++ b/third_party/blink/web_tests/platform/win/media/alpha-video-playback-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/gpu/fast/canvas/canvas-composite-video-expected.png b/third_party/blink/web_tests/platform/win/virtual/gpu/fast/canvas/canvas-composite-video-expected.png index ad55ce264..0ee084f 100644 --- a/third_party/blink/web_tests/platform/win/virtual/gpu/fast/canvas/canvas-composite-video-expected.png +++ b/third_party/blink/web_tests/platform/win/virtual/gpu/fast/canvas/canvas-composite-video-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/gpu/fast/canvas/canvas-composite-video-shadow-expected.png b/third_party/blink/web_tests/platform/win/virtual/gpu/fast/canvas/canvas-composite-video-shadow-expected.png index 949f909c..d5b9d5c 100644 --- a/third_party/blink/web_tests/platform/win/virtual/gpu/fast/canvas/canvas-composite-video-shadow-expected.png +++ b/third_party/blink/web_tests/platform/win/virtual/gpu/fast/canvas/canvas-composite-video-shadow-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/backdrop-filter-plus-filter-expected.png b/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/backdrop-filter-plus-filter-expected.png deleted file mode 100644 index 398cdce..0000000 --- a/third_party/blink/web_tests/virtual/scalefactor200/css3/filters/backdrop-filter-plus-filter-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/webaudio/BiquadFilter/unstable-filter-warning-expected.txt b/third_party/blink/web_tests/webaudio/BiquadFilter/unstable-filter-warning-expected.txt new file mode 100644 index 0000000..33892c1 --- /dev/null +++ b/third_party/blink/web_tests/webaudio/BiquadFilter/unstable-filter-warning-expected.txt
@@ -0,0 +1,11 @@ +CONSOLE ERROR: line 39: [audit.js] this test requires the explicit comparison with the expected result when it runs with run_web_tests.py. +CONSOLE WARNING: BiquadFilterNode: state is bad, probably due to unstable filter caused by fast parameter automation. +This is a testharness.js-based test. +PASS # AUDIT TASK RUNNER STARTED. +PASS > [test] Console warning for unstable filter +PASS BiquadFilterNode.detune.automationRate is equal to a-rate. +PASS At least one non-Finite output value is true. +PASS < [test] All assertions passed. (total 2 assertions) +PASS # AUDIT TASK RUNNER FINISHED: 1 tasks ran successfully. +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/webaudio/BiquadFilter/unstable-filter-warning.html b/third_party/blink/web_tests/webaudio/BiquadFilter/unstable-filter-warning.html new file mode 100644 index 0000000..99735a6 --- /dev/null +++ b/third_party/blink/web_tests/webaudio/BiquadFilter/unstable-filter-warning.html
@@ -0,0 +1,75 @@ +<!doctype html> +<html> + <head> + <title> + Console Warning for Unstable BiquadFilterNode + </title> + <script src="../../resources/testharness.js"></script> + <script src="../../resources/testharnessreport.js"></script> + <script src="../resources/audit.js"></script> + </head> + + <body> + <script> + let audit = Audit.createTaskRunner({requireResultFile: true}); + + // Fairly arbitrary sample rate. If you change it, be sure to verify that + // the filter does produce non-finite values before 1 sec is up. + let sampleRate = 48000; + + audit.define( + {label: 'test', description: 'Console warning for unstable filter'}, + (task, should) => { + // The length depends on how fast the filter blows up. This seems + // to work. + let context = new OfflineAudioContext( + {length: sampleRate, sampleRate: sampleRate}); + + // Test consists of an oscillator feeding a biquad filter whose + // detune parameter is modulated by another oscillator. + let src = + new OscillatorNode(context, {type: 'sine', frequency: 80}); + let detuneMod = + new OscillatorNode(context, {type: 'sine', frequency: 1000}); + let modGain = new GainNode(context, {gain: 3000}); + let filter = new BiquadFilterNode(context, {frequency: 200}); + // Make sure filter detune automation is a-rate! + filter.detune.automationRate = 'a-rate'; + + detuneMod.connect(modGain).connect(filter.detune); + src.connect(filter).connect(context.destination); + + src.start(); + detuneMod.start(); + + context.startRendering() + .then(buffer => { + let output = buffer.getChannelData(0); + + // This test really requires an a-rate BiquadFilter. Print a + // simple message so we know. + should( + filter.detune.automationRate, + 'BiquadFilterNode.detune.automationRate') + .beEqualTo('a-rate'); + + // The output should have at least one non-finite value. + // (Don't care where or how many.) + let nonFiniteFound = false; + for (let k = 0; k < output.length; ++k) { + if (!isFinite(output[k])) { + nonFiniteFound = true; + break; + } + } + + should(nonFiniteFound, 'At least one non-Finite output value') + .beTrue(); + }) + .then(() => task.done()); + }); + + audit.run(); + </script> + </body> +</html>
diff --git a/third_party/blink/web_tests/webaudio/IIRFilter/unstable-filter-warning-expected.txt b/third_party/blink/web_tests/webaudio/IIRFilter/unstable-filter-warning-expected.txt new file mode 100644 index 0000000..d2871cc --- /dev/null +++ b/third_party/blink/web_tests/webaudio/IIRFilter/unstable-filter-warning-expected.txt
@@ -0,0 +1,11 @@ +CONSOLE ERROR: line 39: [audit.js] this test requires the explicit comparison with the expected result when it runs with run_web_tests.py. +CONSOLE WARNING: line 31: Unstable IIRFilter with feedback coefficients: [1, -10] +CONSOLE WARNING: IIRFilterNode: state is bad, probably due to unstable filter. +This is a testharness.js-based test. +PASS # AUDIT TASK RUNNER STARTED. +PASS > [test] Console warning for unstable filter +PASS At least one non-Finite output value is true. +PASS < [test] All assertions passed. (total 1 assertions) +PASS # AUDIT TASK RUNNER FINISHED: 1 tasks ran successfully. +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/webaudio/IIRFilter/unstable-filter-warning.html b/third_party/blink/web_tests/webaudio/IIRFilter/unstable-filter-warning.html new file mode 100644 index 0000000..a81a428 --- /dev/null +++ b/third_party/blink/web_tests/webaudio/IIRFilter/unstable-filter-warning.html
@@ -0,0 +1,61 @@ +<!doctype html> +<html> + <head> + <title> + Console Warning for Unstable IIRFilterNode + </title> + <script src="../../resources/testharness.js"></script> + <script src="../../resources/testharnessreport.js"></script> + <script src="../resources/audit.js"></script> + </head> + + <body> + <script> + let audit = Audit.createTaskRunner({requireResultFile: true}); + + // Fairly arbitrary sample rate. If you change it, be sure to verify that + // the filter does produce non-finite values before 1 sec is up. + let sampleRate = 48000; + + audit.define( + {label: 'test', description: 'Console warning for unstable filter'}, + (task, should) => { + // The length depends on how fast the filter blows up. This seems + // to work. + let context = new OfflineAudioContext( + {length: sampleRate, sampleRate: sampleRate}); + + // Test consists of an oscillator feeding an unstable IIR filter + let src = + new OscillatorNode(context, {type: 'sine', frequency: 80}); + let filter = new IIRFilterNode( + context, {feedforward: [1], feedback: [1, -10]}); + + src.connect(filter).connect(context.destination); + + src.start(); + + context.startRendering() + .then(buffer => { + let output = buffer.getChannelData(0); + + // The output should have at least one non-finite value. + // (Don't care where or how many.) + let nonFiniteFound = false; + for (let k = 0; k < output.length; ++k) { + if (!isFinite(output[k])) { + nonFiniteFound = true; + break; + } + } + + should(nonFiniteFound, 'At least one non-Finite output value') + .beTrue(); + }) + .then(() => task.done()); + }); + + audit.run(); + </script> + </body> +</html>
diff --git a/third_party/blink/web_tests/wpt_internal/css/css-ui/outline-focus-layer-ref.html b/third_party/blink/web_tests/wpt_internal/css/css-ui/outline-focus-layer-ref.html new file mode 100644 index 0000000..0cbe6bc6 --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/css/css-ui/outline-focus-layer-ref.html
@@ -0,0 +1,32 @@ +<!DOCTYPE html> +<link rel="author" href="mailto:atotic@google.com"> +<style> +body { + margin: 50px; + font-size: 0; +} +.outline { + outline-style: auto; +} +#container { + width: 200px; + height: 200px; +} +#target { + display: inline-block; + width: 100px; + height: 100px; + background: #EEE; + transform: translate(120px, 120px); +} +.spacer { + display: inline-block; + height: 50px; + width: 200px; +} +</style> +<!-- --> +<div id="container" class="outline"> + <div class="spacer"></div> + <div id="target"></div> +</div>
diff --git a/third_party/blink/web_tests/wpt_internal/css/css-ui/outline-focus-layer.html b/third_party/blink/web_tests/wpt_internal/css/css-ui/outline-focus-layer.html new file mode 100644 index 0000000..df7714d --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/css/css-ui/outline-focus-layer.html
@@ -0,0 +1,37 @@ +<!DOCTYPE html> +<link rel="author" href="mailto:atotic@google.com"> +<link rel="help" href="https://drafts.csswg.org/css-ui-3/#outline-props"> +<link rel="help" href="https://crbug.com/968019"> +<link rel="match" href="outline-focus-layer-ref.html"> +<meta name="assert" content="Outline is displayed correctly on children with paint layers"> +<style> +body { + margin: 50px; + font-size: 0; +} +.outline { + outline-style: auto; +} +#container { + position: relative; + width: 200px; + height: 200px; +} +#target { + display: inline-block; + width: 100px; + height: 100px; + background: #EEE; + transform: translate(120px, 120px); +} +.spacer { + display: inline-block; + height: 50px; + width: 200px; +} +</style> +<!-- target outline should be painted as part of container outline --> +<div id="container" class="outline"> + <span class="spacer"></span> + <span id="target"></span> +</div>
diff --git a/third_party/closure_compiler/externs/automation.js b/third_party/closure_compiler/externs/automation.js index 7d0199b..a7b9f8f 100644 --- a/third_party/closure_compiler/externs/automation.js +++ b/third_party/closure_compiler/externs/automation.js
@@ -652,6 +652,19 @@ chrome.automation.AutomationNode.prototype.wordEnds; /** + * The start and end index of each word within the node's name. Different from wordStarts and wordEnds because they're not restricted to inline text boxes and can be used for any type of element. + * @type {(!Array<number>|undefined)} + * @see https://developer.chrome.com/extensions/automation#type-wordStartOffsets + */ +chrome.automation.AutomationNode.prototype.wordStartOffsets; + +/** + * @type {(!Array<number>|undefined)} + * @see https://developer.chrome.com/extensions/automation#type-wordEndOffsets + */ +chrome.automation.AutomationNode.prototype.wordEndOffsets; + +/** * The nodes, if any, which this node is specified to control via <a href="http://www.w3.org/TR/wai-aria/states_and_properties#aria-controls"> <code>aria-controls</code></a>. * @type {(!Array<!chrome.automation.AutomationNode>|undefined)} * @see https://developer.chrome.com/extensions/automation#type-controls
diff --git a/third_party/closure_compiler/externs/bluetooth.js b/third_party/closure_compiler/externs/bluetooth.js index d6a884a..ad06a28 100644 --- a/third_party/closure_compiler/externs/bluetooth.js +++ b/third_party/closure_compiler/externs/bluetooth.js
@@ -94,7 +94,8 @@ * uuids: (!Array<string>|undefined), * inquiryRssi: (number|undefined), * inquiryTxPower: (number|undefined), - * transport: (!chrome.bluetooth.Transport|undefined) + * transport: (!chrome.bluetooth.Transport|undefined), + * batteryPercentage: (number|undefined) * }} * @see https://developer.chrome.com/extensions/bluetooth#type-Device */
diff --git a/third_party/netty-tcnative/OWNERS b/third_party/netty-tcnative/OWNERS index 96b9292..fb59c70 100644 --- a/third_party/netty-tcnative/OWNERS +++ b/third_party/netty-tcnative/OWNERS
@@ -1,2 +1 @@ -kapishnikov@chromium.org -mef@chromium.org +file://net/OWNERS
diff --git a/third_party/netty4/OWNERS b/third_party/netty4/OWNERS index 96b9292..fb59c70 100644 --- a/third_party/netty4/OWNERS +++ b/third_party/netty4/OWNERS
@@ -1,2 +1 @@ -kapishnikov@chromium.org -mef@chromium.org +file://net/OWNERS
diff --git a/third_party/webxr_test_pages/webxr-samples/gamepad.html b/third_party/webxr_test_pages/webxr-samples/gamepad.html new file mode 100644 index 0000000..ac01bc5 --- /dev/null +++ b/third_party/webxr_test_pages/webxr-samples/gamepad.html
@@ -0,0 +1,320 @@ +<!doctype html> +<!-- +Copyright 2018 The Immersive Web Community Group + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +--> +<html> + <head> + <meta charset='utf-8'> + <meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=no'> + <meta name='mobile-web-app-capable' content='yes'> + <meta name='apple-mobile-web-app-capable' content='yes'> + + <!-- Origin Trial Token, feature = WebXR Device API, origin = https://immersive-web.github.io, expires = 2018-08-28 --> +<meta http-equiv="origin-trial" data-feature="WebXR Device API" data-expires="2018-08-28" content="AnNpu7ceXvLew05ccD8Zr1OZsdZiB2hLQKK82kTTMDwF7oRKtP3QEJ4RzkeHrmB8Sq0vSV6ZNmszpBCZ0I8p9gAAAABceyJvcmlnaW4iOiJodHRwczovL2ltbWVyc2l2ZS13ZWIuZ2l0aHViLmlvOjQ0MyIsImZlYXR1cmUiOiJXZWJYUkRldmljZSIsImV4cGlyeSI6MTUzNTQxNDQwMH0="> + + <title>Gamepad</title> + + <link href='css/common.css' rel='stylesheet'></link> + + <!--The polyfill is not needed for browser that have native API support, + but is linked by these samples for wider compatibility.--> + <!--script src='https://cdn.jsdelivr.net/npm/webxr-polyfill@latest/build/webxr-polyfill.js'></script--> + <script src='js/xrray-polyfill.js' type='module'></script> + <script src='js/webxr-polyfill.js'></script> + + <script src='js/webxr-button.js'></script> + </head> + <body> + <header> + <details open> + <summary>Gamepad</summary> + <p> + This sample demonstrates using XRInputSource Gamepad button presses + to change box color and joystick/touchpad input to move boxes in 2 + dimensions. + <a class="back" href="./index.html">Back</a> + </p> + </details> + </header> + <div id="gamepad-details"> + <!-- Tables updated in real-time data from WebXR gamepads will be + displayed here if requested. --> + </div> + <script type="module"> + import {Scene} from './js/cottontail/src/scenes/scene.js'; + import {Renderer, createWebGLContext} from './js/cottontail/src/core/renderer.js'; + import {Gltf2Node} from './js/cottontail/src/nodes/gltf2.js'; + import {QueryArgs} from './js/cottontail/src/util/query-args.js'; + import {FallbackHelper} from './js/cottontail/src/util/fallback-helper.js'; + import {Node} from './js/cottontail/src/core/node.js'; + import {PbrMaterial} from './js/cottontail/src/materials/pbr.js'; + import {BoxBuilder} from './js/cottontail/src/geometry/box-builder.js'; + import {mat4, vec3, quat} from './js/cottontail/src/math/gl-matrix.js'; + import {GamepadTableManager} from './js/gamepad-data-tables.js'; + + // If requested, initialize the WebXR polyfill + if (QueryArgs.getBool('allowPolyfill', false)) { + var polyfill = new WebXRPolyfill(); + } + + // If requested, don't display the frame rate info. + let hideStats = QueryArgs.getBool('hideStats', false); + + // Display HTML tables updated in real-time with gamepad data. Useful for + // testing + debugging. + let displayTables = QueryArgs.getBool('displayTables', false); + let tableManager = null; + if (displayTables) { + tableManager = new GamepadTableManager(); + } + + // XR globals. + let xrButton = null; + let xrRefSpace = null; + + // WebGL scene globals. + let gl = null; + let renderer = null; + let scene = new Scene(); + if (hideStats) { + scene.enableStats(false); + } + scene.addNode(new Gltf2Node({url: '../media/gltf/cube-room/cube-room.gltf'})); + scene.standingStats(true); + + let floorSize = 10; + let floorPosition = [0, -floorSize / 2 + 0.01, 0]; + let floorNode = null; + + let boxTable = {}; + + class GamepadBox { + constructor(position) { + this.position = position; + let boxBuilder = new BoxBuilder(); + boxBuilder.pushCube([0, 0, 0], 0.4); + let boxPrimitive = boxBuilder.finishPrimitive(renderer); + let boxMaterial = new PbrMaterial(); + boxMaterial.baseColorFactor.value = [1, 0, 0, 1]; // red + this.renderPrimitive = renderer.createRenderPrimitive(boxPrimitive, boxMaterial); + + this.node = new Node(); + this.node.addRenderPrimitive(this.renderPrimitive); + scene.addNode(this.node); + + this.color_state = true; + this.is_button_pressed = false; + } + + toggle_color() { + this.renderPrimitive.uniforms.baseColorFactor.value = this.color_state ? + [0, 1, 0, 1] : // green + [1, 0, 0, 1]; // red + this.color_state = !this.color_state; + } + + move(dx, dy) { + const inv_speed = 100; + let translation = [dx / inv_speed, dy / inv_speed, 0]; + vec3.add(this.position, this.position, translation); + } + + // Returns true iff button which was previously pressed is not pressed + // anymore. The WebXR + Gamepad APIs don't support button press events + // which is why keeping track of the state this way is necessary. + update_button_state(is_button_pressed) { + let did_button_fire = this.is_button_pressed && !is_button_pressed; + this.is_button_pressed = is_button_pressed; + return did_button_fire; + } + } + + class GamepadBoxSet { + constructor(button_count, y) { + // Place the boxes in a horizontal line. + this.boxes = []; + let x_shift = button_count / 2; + for (let x = 1; x <= button_count; ++x) { + this.boxes.push(new GamepadBox([x - x_shift, y, 1])); + } + } + + update_state(gamepad) { + // A button press (pressing and then releasing a button) will change + // the associated box's color from red to green (or from green to red + // if it's currently green). + for (let i = 0; i < gamepad.buttons.length; ++i) { + if (this.boxes[i].update_button_state(gamepad.buttons[i].pressed)) { + this.boxes[i].toggle_color(); + } + } + + if (gamepad.mapping == "xr-standard") { + // Invert the y axis because gamepads follow the convention that -1 + // is up/forwards, but we want to have a forward joystick/touchpad + // input result in forward motion for the box. + + // xr-standard Gamepads always have at least one touchpad/joystick. + // Its button will always be in the second slot. + let dx = gamepad.axes[0]; + let dy = -gamepad.axes[1]; + this.boxes[1].move(dx, dy); + + if (gamepad.axes.length >= 4 && gamepad.buttons.length >= 4) { + // If an xr-standard Gamepad has a secondary touchpad/joystick, its + // button will be in the 4th slot and it will use the second pair + // of input axes. + dx = gamepad.axes[2]; + dy = -gamepad.axes[3]; + this.boxes[3].move(dx, dy); + } + } + } + + update() { + // Update the matrix for each box so that they are rendered in the + // correct positions. + for (let box of this.boxes) { + mat4.identity(box.node.matrix); + mat4.translate(box.node.matrix, box.node.matrix, box.position); + } + } + } + + function ProcessGamepad(gamepad, hand) { + if (displayTables) { + tableManager.update(gamepad, hand); + } + + if (!(hand in boxTable)) { + const y_positions = { + "left" : 1, + "right" : 2, + "none" : 3, + }; + boxTable[hand] = new GamepadBoxSet(gamepad.buttons.length, y_positions[hand]); + } + + boxTable[hand].update_state(gamepad); + } + + function initXR() { + xrButton = new XRDeviceButton({ + onRequestSession: onRequestSession, + onEndSession: (session) => session.end(), + supportedSessionTypes: ['immersive-vr'] + }); + document.querySelector('header').appendChild(xrButton.domElement); + } + + function initGL() { + if (gl) + return; + + gl = createWebGLContext({ + xrCompatible: true + }); + document.body.appendChild(gl.canvas); + + function onResize() { + gl.canvas.width = (gl.canvas.offsetWidth * window.devicePixelRatio); + gl.canvas.height = (gl.canvas.offsetHeight * window.devicePixelRatio); + } + window.addEventListener('resize', onResize); + onResize(); + + renderer = new Renderer(gl); + + scene.setRenderer(renderer); + scene.inputRenderer.setControllerMesh(new Gltf2Node({url: '../media/gltf/controller/controller.gltf'})); + + addFloorBox(); + } + + function addFloorBox() { + let boxBuilder = new BoxBuilder(); + boxBuilder.pushCube([0, 0, 0], floorSize); + let boxPrimitive = boxBuilder.finishPrimitive(renderer); + + let boxMaterial = new PbrMaterial(); + boxMaterial.baseColorFactor.value = [0.3, 0.3, 0.3, 1.0]; + let boxRenderPrimitive = renderer.createRenderPrimitive(boxPrimitive, boxMaterial); + + floorNode = new Node(); + floorNode.addRenderPrimitive(boxRenderPrimitive); + floorNode.selectable = true; + scene.addNode(floorNode); + mat4.identity(floorNode.matrix); + mat4.translate(floorNode.matrix, floorNode.matrix, floorPosition); + } + + function onRequestSession() { + navigator.xr.requestSession('immersive-vr').then((session) => { + xrButton.setSession(session); + onSessionStarted(session); + }); + } + + function onSessionStarted(session) { + session.addEventListener('end', () => xrButton.setSession(null)); + + initGL(); + + session.updateRenderState({ + baseLayer : new XRWebGLLayer(session, gl) + }); + + session.requestReferenceSpace('local-floor').then((refSpace) => { + // Save the session-specific reference space. + xrRefSpace = refSpace; + session.requestAnimationFrame(onXRFrame); + }); + } + + function onXRFrame(time, frame) { + let session = frame.session; + let pose = frame.getViewerPose(xrRefSpace); + scene.startFrame(); + session.requestAnimationFrame(onXRFrame); + + for (let source of session.inputSources) { + if (source.gamepad) { + ProcessGamepad(source.gamepad, source.handedness); + } + } + + if (displayTables) { + tableManager.nextFrame(); + } + + for (let hand in boxTable) { + boxTable[hand].update(); + } + + scene.updateInputSources(frame, xrRefSpace); + scene.drawXRFrame(frame, pose); + scene.endFrame(); + } + + // Start the XR application. + initXR(); + </script> + </body> +</html>
diff --git a/third_party/webxr_test_pages/webxr-samples/index.html b/third_party/webxr_test_pages/webxr-samples/index.html index 12bcb47..db4d01e 100644 --- a/third_party/webxr_test_pages/webxr-samples/index.html +++ b/third_party/webxr_test_pages/webxr-samples/index.html
@@ -127,9 +127,13 @@ path: 'input-tracking.html', description: 'Demonstrates basic tracking and rendering of XRInputSources.'}, - { title: 'Input Selection', category: 'Input', - path: 'input-selection.html', - description: 'Demonstrates handling \'select\' events generated by XRInputSources.'}, + { title: 'Teleportation', category: 'Input', + path: 'teleportation.html', + description: 'Demonstrates teleporting the viewer by updating the XRSession reference space.' }, + + { title: 'Gamepad', category: 'Input', + path: 'gamepad.html', + description: 'Demonstrates handling input from Gamepads attached to XRInputSources.' }, { title: 'Framebuffer Scaling', category: 'Performance', path: 'framebuffer-scaling.html',
diff --git a/third_party/webxr_test_pages/webxr-samples/input-selection.html b/third_party/webxr_test_pages/webxr-samples/input-selection.html deleted file mode 100644 index 5f70d7f..0000000 --- a/third_party/webxr_test_pages/webxr-samples/input-selection.html +++ /dev/null
@@ -1,728 +0,0 @@ -<!doctype html> -<!-- -Copyright 2018 The Immersive Web Community Group - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ---> -<html> - <head> - <meta charset='utf-8'> - <meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=no'> - <meta name='mobile-web-app-capable' content='yes'> - <meta name='apple-mobile-web-app-capable' content='yes'> - - <!-- Origin Trial Token, feature = WebXR Device API, origin = https://immersive-web.github.io, expires = 2018-08-28 --> -<meta http-equiv="origin-trial" data-feature="WebXR Device API" data-expires="2018-08-28" content="AnNpu7ceXvLew05ccD8Zr1OZsdZiB2hLQKK82kTTMDwF7oRKtP3QEJ4RzkeHrmB8Sq0vSV6ZNmszpBCZ0I8p9gAAAABceyJvcmlnaW4iOiJodHRwczovL2ltbWVyc2l2ZS13ZWIuZ2l0aHViLmlvOjQ0MyIsImZlYXR1cmUiOiJXZWJYUkRldmljZSIsImV4cGlyeSI6MTUzNTQxNDQwMH0="> - - <title>Input Selection</title> - - <link href='css/common.css' rel='stylesheet'></link> - - - <!--The polyfill is not needed for browser that have native API support, - but is linked by these samples for wider compatibility.--> - <!--script src='https://cdn.jsdelivr.net/npm/webxr-polyfill@latest/build/webxr-polyfill.js'></script--> - <script src='js/xrray-polyfill.js' type='module'></script> - <script src='js/webxr-polyfill.js'></script> - - <script src='js/webxr-button.js'></script> - </head> - <body> - <header> - <details open> - <summary>Input Selection</summary> - <p> - This sample demonstrates handling 'select' events generated by - XRInputSources to create clickable objects in the scene. - <a class="back" href="./index.html">Back</a> - </p> - </details> - </header> - <header> - <details id="gamepad-details-hand-none"> - <summary>None-hand Gamepad</summary> - <p>Real-time info for gamepad not associated with a particular hand.</p> - </details> - </header> - <header> - <details id="gamepad-details-hand-left"> - <summary>Left-hand Gamepad</summary> - <p>Real-time info for gamepad associated with left hand.</p> - </details> - </header> - <header> - <details id="gamepad-details-hand-right"> - <summary>Right-hand Gamepad</summary> - <p>Real-time info for gamepad associated with right hand.</p> - </details> - </header> - <script type="module"> - import {Scene} from './js/cottontail/src/scenes/scene.js'; - import {Renderer, createWebGLContext} from './js/cottontail/src/core/renderer.js'; - import {Gltf2Node} from './js/cottontail/src/nodes/gltf2.js'; - import {QueryArgs} from './js/cottontail/src/util/query-args.js'; - import {FallbackHelper} from './js/cottontail/src/util/fallback-helper.js'; - import {Node} from './js/cottontail/src/core/node.js'; - import {PbrMaterial} from './js/cottontail/src/materials/pbr.js'; - import {BoxBuilder} from './js/cottontail/src/geometry/box-builder.js'; - import {mat4, vec3, quat} from './js/cottontail/src/math/gl-matrix.js'; - import {BoundsRenderer} from './js/cottontail/src/nodes/bounds-renderer.js'; - - // If requested, initialize the WebXR polyfill - if (QueryArgs.getBool('allowPolyfill', false)) { - var polyfill = new WebXRPolyfill(); - } - - // Temporary - let hideStats = QueryArgs.getBool('hideStats', false); - - // XR globals. - let xrButton = null; - let xrImmersiveRefSpaceBase = null; - let xrImmersiveRefSpaceOffset = null; - let xrNonImmersiveRefSpaceBase = null; - let xrNonImmersiveRefSpaceOffset = null; - let xrViewerSpace = null; - - // WebGL scene globals. - let gl = null; - let renderer = null; - let scene = new Scene(); - let boundsRenderer = null; - if (hideStats) { - scene.enableStats(false); - } - scene.addNode(new Gltf2Node({url: '../media/gltf/cube-room/cube-room.gltf'})); - scene.standingStats(true); - - let boxes = []; - - let trackingSpaceOriginInWorldSpace = vec3.create(); - let trackingSpaceHeadingDegrees = 0; // around +Y axis, positive angles rotate left - let floorSize = 10; - let floorPosition = [0, -floorSize / 2 + 0.01, 0]; - let floorNode = null; - - let controllerTable = {}; - let boxTable = {}; - let movableBoxes = {}; - let loggedGamepadInfo = {}; - - let frame_number = 0; - let axes_tables = {}; - let info_tables = {}; - let button_tables = {}; - - class XRControllerState { - constructor(button_count) { - this.buttons = []; - for (let i = 0; i < button_count; ++i) { - this.buttons.push(false); - } - } - - // returns array of buttons to fire events for - update(gamepad) { - let result = []; - for (let i = 0; i < this.buttons.length; ++i) { - let old_state = this.buttons[i]; - let new_state = gamepad.buttons[i].pressed; - if (old_state && !new_state) { - // Button which was previously pressed is not pressed anymore. - result.push(i); - } - this.buttons[i] = new_state; - } - return result; - } - } - - class GamepadBoxSet { - constructor(button_count, x, z) { - this.box_list = []; - this.box_state = []; - for (let y = 1; y <= button_count; ++y) { - addBox(x, y, z, 1, 0, 0, this.box_list); - this.box_state.push(true); - } - } - - toggle(box_index) { - let box = this.box_list[box_index]; - let uniforms = box.renderPrimitive.uniforms; - if (this.box_state[box_index]) { - uniforms.baseColorFactor.value = [0, 1, 0, 1]; - } else { - uniforms.baseColorFactor.value = [1, 0, 0, 1]; - } - this.box_state[box_index] = !this.box_state[box_index]; - } - } - - class MovableBox { - constructor(x, y, z, inv_speed) { - this.box_list = []; - addBox(x, y, z, 0, 0, 1, this.box_list); - this.inv_speed = inv_speed; - } - - update(dx, dz) { - vec3.add(this.box_list[0].position, this.box_list[0].position, [dx / this.inv_speed, 0, dz / this.inv_speed]); - } - } - - class GamepadTable { - constructor(title, cols, hand) { - this.table = document.createElement("table"); - this.table.setAttribute("border", 1); - this.body = document.createElement("tbody"); - this.AddHeader(title, cols); - this.table.appendChild(this.body); - document.getElementById("gamepad-details-hand-" + hand).appendChild(this.table); - } - - AddHeader(title, cols) { - let row = document.createElement("tr"); - let th = document.createElement("th"); - th.setAttribute("colspan", cols); - th.appendChild(document.createTextNode(title)); - row.appendChild(th); - this.body.appendChild(row); - } - - AddCell(row, text) { - let cell = document.createElement("td"); - cell.appendChild(document.createTextNode(text)); - row.appendChild(cell); - return cell; - } - - AddRow(values) { - let cells = []; - let row = document.createElement("tr"); - for (let i = 0; i < values.length; ++i) { - cells.push(this.AddCell(row, values[i])); - } - this.body.appendChild(row); - return cells; - } - } - - class ButtonTable extends GamepadTable { - constructor(buttons, hand) { - super("button data", 3, hand); - - this.AddRow(["pressed", "touched", "value"]); - - this.pressed_cells = []; - this.touched_cells = []; - this.value_cells = []; - - this.pressed = []; - this.touched = []; - this.values = []; - - for (let i = 0; i < buttons.length; ++i) { - this.pressed.push(buttons[i].pressed); - this.touched.push(buttons[i].touched); - this.values.push(buttons[i].value); - let cells = this.AddRow([buttons[i].pressed, buttons[i].touched, buttons[i].value.toFixed(3)]); - this.pressed_cells.push(cells[0]); - this.touched_cells.push(cells[1]); - this.value_cells.push(cells[2]); - } - } - - update(buttons) { - for (let i = 0; i < buttons.length; ++i) { - const is_pressed = buttons[i].pressed; - if (this.pressed[i] != is_pressed) { - this.pressed_cells[i].innerHTML = is_pressed; - this.pressed[i] = is_pressed; - } - const is_touched = buttons[i].touched; - if (this.touched[i] != is_touched) { - this.touched_cells[i].innerHTML = is_touched; - this.touched[i] = is_touched; - } - const value = buttons[i].value; - if (this.values[i] != value) { - this.value_cells[i].innerHTML = value.toFixed(3); - this.values[i] = value; - } - } - } - } - - class AxesTable extends GamepadTable { - constructor(axes, hand) { - super("axis values", 1, hand); - - this.values = []; - for (let i = 0; i < axes.length; ++i) { - this.values.push(axes[i]); - } - - this.cells = []; - for (let i = 0; i < axes.length; ++i) { - let temp_cells = this.AddRow([axes[i].toFixed(3)]); - this.cells.push(temp_cells[0]); - } - } - - update(axes) { - // assumes length is still the same - for (let i = 0; i < axes.length; ++i) { - if (this.values[i] != axes[i]) { - this.cells[i].innerHTML = axes[i].toFixed(3); - this.values[i] = axes[i]; - } - } - } - } - - class InfoTable extends GamepadTable { - constructor(gamepad, hand) { - super("Gamepad", 2, hand); - - this.hand = hand; - this.id = gamepad.id; - this.mapping = gamepad.mapping; - - this.hand_cell = this.AddRow(["hand", hand])[1]; - this.id_cell = this.AddRow(["id", gamepad.id])[1]; - this.mapping_cell = this.AddRow(["mapping", gamepad.mapping])[1]; - } - - update(gamepad, hand) { - if (this.hand != hand) { - this.hand_cell.innerHTML = hand; - this.hand = hand; - } - if (this.id != gamepad.id) { - this.id_cell.innerHTML = gamepad.id; - this.id = gamepad.id; - } - if (this.mapping != gamepad.mapping) { - this.mapping_cell.innerHTML = gamepad.mapping; - this.mapping = gamepad.mapping; - } - } - } - - function ProcessGamepad(gamepad, input_source) { - let hand = input_source.handedness; - if (!(hand in loggedGamepadInfo)) { - loggedGamepadInfo[hand] = true; - console.log(gamepad); - } - if (!(hand in movableBoxes)) { - let x = 2; - let z = 2; - if (hand == "right") { - x = -2; - z = -2; - } - movableBoxes[hand] = new MovableBox(x, 2, z, 100); - } - if (!(hand in boxTable)) { - let x = 1; - let z = 1; - if (hand == "right") { - x = -1; - z = -1; - } - boxTable[hand] = new GamepadBoxSet(gamepad.buttons.length, x, z); - } - if (!(hand in controllerTable)) { - controllerTable[hand] = new XRControllerState(gamepad.buttons.length); - } - let buttons_fired = controllerTable[hand].update(gamepad); - for (let button_index of buttons_fired) { - let message = "controller for " + hand + " hand fired button " + button_index.toString(); - console.log(message); - boxTable[hand].toggle(button_index); - } - for (let i = 0; i < gamepad.axes.length; i += 2) { - let dx = gamepad.axes[i]; - let dy = gamepad.axes[i + 1]; - if (dx != 0 || dy != 0) { - // Invert the y axis because gamepads follow the convention that -1 - // is up/forwards, but we want to have a forward joystick/touchpad - // input result in forward motion for the box. - // TODO(https://crbug.com/966060): Revisit this if the convention changes. - movableBoxes[hand].update(dx, -dy); - } - } - - // Only update the gamepad tables once every 10 frames for perf reasons. - // Only update the tables if the relevant section is expanded on the page. - let details_elem = document.getElementById("gamepad-details-hand-" + hand); - if (details_elem.hasAttribute("open")) { - // Construct the tables if necessary. Must check this every frame - // because otherwise, the table doesn't get created until the gamepad - // has an input change on a frame that's a multiple of 10. - if (!(hand in info_tables)) { - info_tables[hand] = new InfoTable(gamepad, hand); - } - - if (!(hand in axes_tables)) { - axes_tables[hand] = new AxesTable(gamepad.axes, hand); - } - - if (!(hand in button_tables)) { - button_tables[hand] = new ButtonTable(gamepad.buttons, hand); - } - - if ((frame_number % 10) == 0) { - info_tables[hand].update(gamepad, hand); - axes_tables[hand].update(gamepad.axes); - button_tables[hand].update(gamepad.buttons); - } - } - frame_number++; - } - - function initXR() { - xrButton = new XRDeviceButton({ - onRequestSession: onRequestSession, - onEndSession: onEndSession, - supportedSessionTypes: ['immersive-vr'] - }); - document.querySelector('header').appendChild(xrButton.domElement); - - if (navigator.xr) { - const mode = 'inline'; - navigator.xr.requestSession(mode).then((session) => { - session.mode = mode; - onSessionStarted(session); - }); - } else { - initFallback(); - } - } - - function initFallback() { - initGL(); - let fallbackHelper = new FallbackHelper(scene, gl); - fallbackHelper.emulateStage = true; - } - - function addBox(x, y, z, r, g, b, box_list) { - let boxBuilder = new BoxBuilder(); - boxBuilder.pushCube([0, 0, 0], 0.4); - let boxPrimitive = boxBuilder.finishPrimitive(renderer); - let boxMaterial = new PbrMaterial(); - boxMaterial.baseColorFactor.value = [r, g, b, 1.0]; - let boxRenderPrimitive = renderer.createRenderPrimitive(boxPrimitive, boxMaterial); - let boxNode = new Node(); - boxNode.addRenderPrimitive(boxRenderPrimitive); - // Marks the node as one that needs to be checked when hit testing. - boxNode.selectable = true; - box_list.push({ - node: boxNode, - renderPrimitive: boxRenderPrimitive, - position: [x, y, z] - }); - scene.addNode(boxNode); - } - - function initGL() { - if (gl) - return; - - gl = createWebGLContext({ - xrCompatible: true - }); - document.body.appendChild(gl.canvas); - - function onResize () { - gl.canvas.width = (gl.canvas.offsetWidth * window.devicePixelRatio); - gl.canvas.height = (gl.canvas.offsetHeight * window.devicePixelRatio); - } - window.addEventListener('resize', onResize); - onResize(); - - renderer = new Renderer(gl); - - scene.setRenderer(renderer); - scene.inputRenderer.setControllerMesh(new Gltf2Node({url: '../media/gltf/controller/controller.gltf'})); - - // Create several boxes to use for hit testing. - addBox(-1.0, 1.6, -1.3, 1.0, 0.0, 0.0, boxes); - addBox(0.0, 1.7, -1.5, 0.0, 1.0, 0.0, boxes); - addBox(1.0, 1.6, -1.3, 0.0, 0.0, 1.0, boxes); - - addFloorBox(); - } - - function addFloorBox() { - let boxBuilder = new BoxBuilder(); - boxBuilder.pushCube([0, 0, 0], floorSize); - let boxPrimitive = boxBuilder.finishPrimitive(renderer); - - let boxMaterial = new PbrMaterial(); - boxMaterial.baseColorFactor.value = [0.3, 0.3, 0.3, 1.0]; - let boxRenderPrimitive = renderer.createRenderPrimitive(boxPrimitive, boxMaterial); - - floorNode = new Node(); - floorNode.addRenderPrimitive(boxRenderPrimitive); - floorNode.selectable = true; - scene.addNode(floorNode); - mat4.identity(floorNode.matrix); - mat4.translate(floorNode.matrix, floorNode.matrix, floorPosition); - } - - function onRequestSession() { - const mode = 'immersive-vr'; - navigator.xr.requestSession(mode).then((session) => { - session.mode = mode; - xrButton.setSession(session); - onSessionStarted(session); - }); - } - - function onSessionStarted(session) { - if (!session.mode) { - session.mode = 'inline'; - } - - session.addEventListener('end', onSessionEnded); - - // By listening for the 'select' event we can find out when the user has - // performed some sort of primary input action and respond to it. - session.addEventListener('select', onSelect); - - initGL(); - - session.updateRenderState({ - baseLayer: new XRWebGLLayer(session, gl, { - compositionDisabled: session.mode == 'inline' - }) - }); - - // Same logic for establishing a reference space as in room-scale.html - session.requestReferenceSpace('local-floor').then((refSpace) => { - return refSpace; - }, (e) => { - if (!session.mode.startsWith('immersive')) { - // If we're in inline mode, our underlying platform may not support - // the stationary reference space, but an identity space is guaranteed. - console.log("falling back to identity reference space"); - return session.requestReferenceSpace('viewer'); - } else { - throw e; - } - }).then((refSpace) => { - // Save the session-specific reference space, and apply the - // current player orientation/position as originOffset. - setRefSpace(session, refSpace, false); - updateOriginOffset(session); - session.requestReferenceSpace('viewer').then(function(viewerSpace){ - xrViewerSpace = viewerSpace; - session.requestAnimationFrame(onXRFrame); - }); - }); - } - - let playerInWorldSpaceOld = vec3.create(); - let playerInWorldSpaceNew = vec3.create(); - let playerOffsetInWorldSpaceOld = vec3.create(); - let playerOffsetInWorldSpaceNew = vec3.create(); - let rotationDeltaQuat = quat.create(); - - function onSelect(ev) { - let session = ev.frame.session; - let refSpace = getRefSpace(session, true); - - let headPose = ev.frame.getPose(xrViewerSpace, refSpace); - if (!headPose) return; - - // Get the position offset in world space from the tracking space origin - // to the player's feet. The headPose position is the head position in world space. - // Subtract the tracking space origin position in world space to get a relative world space vector. - vec3.set(playerInWorldSpaceOld, headPose.transform.position.x, 0, headPose.transform.position.z); - vec3.sub(playerOffsetInWorldSpaceOld, playerInWorldSpaceOld, trackingSpaceOriginInWorldSpace); - - // based on https://github.com/immersive-web/webxr/blob/master/input-explainer.md#targeting-ray-pose - let inputSourcePose = ev.frame.getPose(ev.inputSource.targetRaySpace, refSpace); - if (!inputSourcePose) { - return; - } - - vec3.copy(playerInWorldSpaceNew, playerInWorldSpaceOld); - let rotationDelta = 0; - - // Hit test results can change teleport position and orientation. - let targetRay = new XRRay(inputSourcePose.transform); - let hitResult = scene.hitTest(targetRay) - if (hitResult) { - // Check to see if the hit result was one of our boxes. - for (let i = 0; i < boxes.length; ++i) { - let box = boxes[i]; - if (hitResult.node == box.node) { - // Change the box color to something random. - let uniforms = box.renderPrimitive.uniforms; - uniforms.baseColorFactor.value = [Math.random(), Math.random(), Math.random(), 1.0]; - if (i == 0) { - // turn left - rotationDelta = 30; - } else if (i == 1) { - // reset heading by undoing the current rotation - rotationDelta = -trackingSpaceHeadingDegrees; - } else if (i == 2) { - // turn right - rotationDelta = -30; - } - console.log('rotate by', rotationDelta); - } - } - if (hitResult.node == floorNode) { - // New position uses x/z values of the hit test result, keeping y at 0 (floor level) - playerInWorldSpaceNew[0] = hitResult.intersection[0]; - playerInWorldSpaceNew[1] = 0; - playerInWorldSpaceNew[2] = hitResult.intersection[2]; - console.log('teleport to', playerInWorldSpaceNew); - } - } - - // Get the new world space offset vector from tracking space origin - // to the player's feet, for the updated tracking space rotation. - // Formally, this is the old world-space player offset transformed - // into tracking space using the old originOffset's rotation component, - // then transformed back into world space using the inverse of the - // new originOffset. This simplifies to a rotation of the old player - // offset by (new angle - old angle): - // worldOffsetNew = inv(rot_of(originoffsetNew)) * rot_of(originoffsetOld) * worldOffsetOld - // = inv(rotY(-angleNew)) * rotY(-angleOld) * worldOffsetOld - // = rotY(angleNew) * rotY(-angleOld) * worldOffsetOld - // = rotY(angleNew - angleOld) * worldOffsetOld - quat.identity(rotationDeltaQuat); - quat.rotateY(rotationDeltaQuat, rotationDeltaQuat, rotationDelta * Math.PI / 180); - vec3.transformQuat(playerOffsetInWorldSpaceNew, playerOffsetInWorldSpaceOld, rotationDeltaQuat); - trackingSpaceHeadingDegrees += rotationDelta; - - // Update tracking space origin so that origin + playerOffset == player location in world space - vec3.sub(trackingSpaceOriginInWorldSpace, playerInWorldSpaceNew, playerOffsetInWorldSpaceNew); - - updateOriginOffset(session); - } - - function updateOriginOffset(session) { - // Compute the origin offset based on player position/orientation. - quat.identity(invOrientation); - quat.rotateY(invOrientation, invOrientation, -trackingSpaceHeadingDegrees * Math.PI / 180); - vec3.negate(invPosition, trackingSpaceOriginInWorldSpace); - vec3.transformQuat(invPosition, invPosition, invOrientation); - let xform = new XRRigidTransform( - {x: invPosition[0], y: invPosition[1], z: invPosition[2]}, - {x: invOrientation[0], y: invOrientation[1], z: invOrientation[2], w: invOrientation[3]}); - - // Update offset reference to use a new originOffset with the teleported player position and orientation. - // This new offset needs to be applied to the base ref space. - let refSpace = getRefSpace(session, false).getOffsetReferenceSpace(xform); - setRefSpace(session, refSpace, true); - - console.log('teleport to', trackingSpaceOriginInWorldSpace); - } - - function onEndSession(session) { - session.end(); - } - - function onSessionEnded(event) { - if (event.session.mode.startsWith('immersive')) { - xrButton.setSession(null); - } - } - - let invPosition = vec3.create(); - let invOrientation = quat.create(); - - function getRefSpace(session, isOffset) { - return session.mode.startsWith('immersive') ? - (isOffset ? xrImmersiveRefSpaceOffset : xrImmersiveRefSpaceBase) : - (isOffset ? xrNonImmersiveRefSpaceOffset : xrNonImmersiveRefSpaceBase); - } - - function setRefSpace(session, refSpace, isOffset) { - if (session.mode.startsWith('immersive')) { - if (isOffset) { - xrImmersiveRefSpaceOffset = refSpace; - } else { - xrImmersiveRefSpaceBase = refSpace; - } - } else { - if (isOffset) { - xrNonImmersiveRefSpaceOffset = refSpace; - } else { - xrNonImmersiveRefSpaceBase = refSpace; - } - } - } - - function onXRFrame(time, frame) { - let session = frame.session; - let refSpace = getRefSpace(session, true); - - let pose = frame.getViewerPose(refSpace); - scene.startFrame(); - session.requestAnimationFrame(onXRFrame); - - function updateBoxes(box_list, rotate) { - // Update the matrix for each box - for (let box of box_list) { - let node = box.node; - mat4.identity(node.matrix); - mat4.translate(node.matrix, node.matrix, box.position); - if (rotate) { - mat4.rotateX(node.matrix, node.matrix, time/1000); - mat4.rotateY(node.matrix, node.matrix, time/1500); - } - } - } - - for (let source of session.inputSources) { - let gamepad = source.gamepad; - if (gamepad) { - ProcessGamepad(gamepad, source); - } - } - - updateBoxes(boxes, true); - for (let hand in boxTable) { - updateBoxes(boxTable[hand].box_list, false); - } - for (let hand in movableBoxes) { - updateBoxes(movableBoxes[hand].box_list, false); - } - - // In this sample and most samples after it we'll use a helper function - // to automatically add the right meshes for the session's input sources - // each frame. This also does simple hit detection to position the - // cursors correctly on the surface of selectable nodes. - scene.updateInputSources(frame, refSpace); - scene.drawXRFrame(frame, pose); - scene.endFrame(); - } - - // Start the XR application. - initXR(); - </script> - </body> -</html>
diff --git a/third_party/webxr_test_pages/webxr-samples/js/gamepad-data-tables.js b/third_party/webxr_test_pages/webxr-samples/js/gamepad-data-tables.js new file mode 100644 index 0000000..55f1376 --- /dev/null +++ b/third_party/webxr_test_pages/webxr-samples/js/gamepad-data-tables.js
@@ -0,0 +1,197 @@ +// Copyright 2018 The Immersive Web Community Group +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +class GamepadTable { + constructor(title, cols, parent) { + this.table = document.createElement("table"); + this.table.setAttribute("border", 1); + this.body = document.createElement("tbody"); + this.AddHeader(title, cols); + this.table.appendChild(this.body); + parent.appendChild(this.table); + } + + AddHeader(title, cols) { + let row = document.createElement("tr"); + let th = document.createElement("th"); + th.setAttribute("colspan", cols); + th.appendChild(document.createTextNode(title)); + row.appendChild(th); + this.body.appendChild(row); + } + + AddCell(row, text) { + let cell = document.createElement("td"); + cell.appendChild(document.createTextNode(text)); + row.appendChild(cell); + return cell; + } + + AddRow(values) { + let cells = []; + let row = document.createElement("tr"); + for (let i = 0; i < values.length; ++i) { + cells.push(this.AddCell(row, values[i])); + } + this.body.appendChild(row); + return cells; + } +} + +class ButtonTable extends GamepadTable { + constructor(buttons, parent) { + super("button data", 3, parent); + + this.AddRow(["pressed", "touched", "value"]); + + this.pressed_cells = []; + this.touched_cells = []; + this.value_cells = []; + + this.pressed = []; + this.touched = []; + this.values = []; + + for (let i = 0; i < buttons.length; ++i) { + this.pressed.push(buttons[i].pressed); + this.touched.push(buttons[i].touched); + this.values.push(buttons[i].value); + let cells = this.AddRow([buttons[i].pressed, buttons[i].touched, buttons[i].value.toFixed(3)]); + this.pressed_cells.push(cells[0]); + this.touched_cells.push(cells[1]); + this.value_cells.push(cells[2]); + } + } + + update(buttons) { + for (let i = 0; i < buttons.length; ++i) { + const is_pressed = buttons[i].pressed; + if (this.pressed[i] != is_pressed) { + this.pressed_cells[i].innerHTML = is_pressed; + this.pressed[i] = is_pressed; + } + const is_touched = buttons[i].touched; + if (this.touched[i] != is_touched) { + this.touched_cells[i].innerHTML = is_touched; + this.touched[i] = is_touched; + } + const value = buttons[i].value; + if (this.values[i] != value) { + this.value_cells[i].innerHTML = value.toFixed(3); + this.values[i] = value; + } + } + } +} + +class AxesTable extends GamepadTable { + constructor(axes, parent) { + super("axis values", 1, parent); + + this.values = []; + for (let i = 0; i < axes.length; ++i) { + this.values.push(axes[i]); + } + + this.cells = []; + for (let i = 0; i < axes.length; ++i) { + let temp_cells = this.AddRow([axes[i].toFixed(3)]); + this.cells.push(temp_cells[0]); + } + } + + update(axes) { + // assumes length is still the same + for (let i = 0; i < axes.length; ++i) { + if (this.values[i] != axes[i]) { + this.cells[i].innerHTML = axes[i].toFixed(3); + this.values[i] = axes[i]; + } + } + } +} + +class InfoTable extends GamepadTable { + constructor(gamepad, parent) { + super("Gamepad", 2, parent); + + this.id = gamepad.id; + this.mapping = gamepad.mapping; + + this.id_cell = this.AddRow(["id", gamepad.id])[1]; + this.mapping_cell = this.AddRow(["mapping", gamepad.mapping])[1]; + } + + update(gamepad) { + if (this.id != gamepad.id) { + this.id_cell.innerHTML = gamepad.id; + this.id = gamepad.id; + } + if (this.mapping != gamepad.mapping) { + this.mapping_cell.innerHTML = gamepad.mapping; + this.mapping = gamepad.mapping; + } + } +} + +export class GamepadTableManager { + constructor() { + this.frame_number = 0; + this.tables = {}; + } + + nextFrame() { + this.frame_number++; + } + + update(gamepad, hand) { + // Construct the tables if necessary. Must check this every frame + // because otherwise, the table doesn't get created until the gamepad + // has an input change on a frame that's a multiple of 10. + if (!(hand in this.tables)) { + let div = document.getElementById("gamepad-details"); + let header = document.createElement("header"); + let details = document.createElement("details"); + details.setAttribute("id", "gamepad-details-hand-" + hand); + details.setAttribute("open", ""); + let summary = document.createElement("summary"); + summary.innerHTML = hand + "-hand Gamepad"; + let p = document.createElement("p"); + p.innerHTML = "Real-time info for gamepad associated with " + hand + " hand."; + details.appendChild(summary); + details.appendChild(p); + header.appendChild(details); + div.appendChild(header); + + this.tables[hand] = { + info : new InfoTable(gamepad, details), + axes : new AxesTable(gamepad.axes, details), + buttons : new ButtonTable(gamepad.buttons, details) + }; + } + + // Only update the gamepad tables once every 10 frames for perf reasons. + if ((this.frame_number % 10) == 0) { + this.tables[hand].info.update(gamepad); + this.tables[hand].axes.update(gamepad.axes); + this.tables[hand].buttons.update(gamepad.buttons); + } + } +}
diff --git a/third_party/webxr_test_pages/webxr-samples/magic-window.html b/third_party/webxr_test_pages/webxr-samples/magic-window.html index d011dd5..9413131b 100644 --- a/third_party/webxr_test_pages/webxr-samples/magic-window.html +++ b/third_party/webxr_test_pages/webxr-samples/magic-window.html
@@ -57,7 +57,8 @@ <p> This sample demonstrates use of a non-immersive XRSession to present 'Magic Window' content prior to entering XR presentation with an - immersive session. + immersive session. Click and drag with the mouse on this page to + adjust the viewer pose. </p> <p> <a class="back" href="./index.html">Back</a> @@ -80,6 +81,7 @@ import {Gltf2Node} from './js/cottontail/src/nodes/gltf2.js'; import {QueryArgs} from './js/cottontail/src/util/query-args.js'; import {SkyboxNode} from './js/cottontail/src/nodes/skybox.js'; + import {mat4, vec3, quat} from './js/cottontail/src/math/gl-matrix.js'; // If requested, initialize the WebXR polyfill if (QueryArgs.getBool('allowPolyfill', false)) { @@ -201,6 +203,21 @@ } } + let lookYaw = 0; + let lookPitch = 0; + const lookSpeed = 0.0025; + window.addEventListener('mousemove', (ev) => { + // Only rotate when the left button is pressed + if (ev.buttons && 1) { + lookYaw += ev.movementX * lookSpeed; + lookPitch += ev.movementY * lookSpeed; + if (lookPitch < -Math.PI*0.5) + lookPitch = -Math.PI*0.5; + if (lookPitch > Math.PI*0.5) + lookPitch = Math.PI*0.5; + } + }); + // Called every time a XRSession requests that a new frame be drawn. function onXRFrame(t, frame) { let session = frame.session; @@ -208,10 +225,19 @@ let refSpace = session.mode.startsWith('immersive') ? xrImmersiveRefSpace : xrNonImmersiveRefSpace; + + // Account for the click-and-drag mouse movement when calculating the + // viewer pose. + let invOrientation = quat.create(); + quat.rotateX(invOrientation, invOrientation, -lookPitch); + quat.rotateY(invOrientation, invOrientation, -lookYaw); + let xform = new XRRigidTransform( + {x: 0, y: 0, z: 0}, + {x: invOrientation[0], y: invOrientation[1], z: invOrientation[2], w: invOrientation[3]}); + refSpace = refSpace.getOffsetReferenceSpace(xform); let pose = frame.getViewerPose(refSpace); scene.startFrame(); - session.requestAnimationFrame(onXRFrame); if (pose) {
diff --git a/third_party/webxr_test_pages/webxr-samples/positional-audio.html b/third_party/webxr_test_pages/webxr-samples/positional-audio.html index 5fec78d2..6892dfe 100644 --- a/third_party/webxr_test_pages/webxr-samples/positional-audio.html +++ b/third_party/webxr_test_pages/webxr-samples/positional-audio.html
@@ -70,7 +70,7 @@ var polyfill = new WebXRPolyfill(); } - // Temporary + // If requested, don't display the frame rate info. let hideStats = QueryArgs.getBool('hideStats', false); const DEFAULT_HEIGHT = 1.5;
diff --git a/third_party/webxr_test_pages/webxr-samples/teleportation.html b/third_party/webxr_test_pages/webxr-samples/teleportation.html new file mode 100644 index 0000000..20f6558 --- /dev/null +++ b/third_party/webxr_test_pages/webxr-samples/teleportation.html
@@ -0,0 +1,410 @@ +<!doctype html> +<!-- +Copyright 2018 The Immersive Web Community Group + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +--> +<html> + <head> + <meta charset='utf-8'> + <meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=no'> + <meta name='mobile-web-app-capable' content='yes'> + <meta name='apple-mobile-web-app-capable' content='yes'> + + <!-- Origin Trial Token, feature = WebXR Device API, origin = https://immersive-web.github.io, expires = 2018-08-28 --> +<meta http-equiv="origin-trial" data-feature="WebXR Device API" data-expires="2018-08-28" content="AnNpu7ceXvLew05ccD8Zr1OZsdZiB2hLQKK82kTTMDwF7oRKtP3QEJ4RzkeHrmB8Sq0vSV6ZNmszpBCZ0I8p9gAAAABceyJvcmlnaW4iOiJodHRwczovL2ltbWVyc2l2ZS13ZWIuZ2l0aHViLmlvOjQ0MyIsImZlYXR1cmUiOiJXZWJYUkRldmljZSIsImV4cGlyeSI6MTUzNTQxNDQwMH0="> + + <title>Teleportation</title> + + <link href='css/common.css' rel='stylesheet'></link> + + <!--The polyfill is not needed for browser that have native API support, + but is linked by these samples for wider compatibility.--> + <!--script src='https://cdn.jsdelivr.net/npm/webxr-polyfill@latest/build/webxr-polyfill.js'></script--> + <script src='js/xrray-polyfill.js' type='module'></script> + <script src='js/webxr-polyfill.js'></script> + + <script src='js/webxr-button.js'></script> + </head> + <body> + <header> + <details open> + <summary>Teleportation</summary> + <p> + This sample demonstrates teleporting the viewer by updating the + XRSession reference space. Select a point on the floor with a + controller to teleport to it. Select the leftmost box to rotate to the + left by 30 degrees. Selecting the rightmost box rotates the viewer by + 30 degress to the right. Select the middle box to reset the + viewer orientation. + <a class="back" href="./index.html">Back</a> + </p> + </details> + </header> + <script type="module"> + import {Scene} from './js/cottontail/src/scenes/scene.js'; + import {Renderer, createWebGLContext} from './js/cottontail/src/core/renderer.js'; + import {Gltf2Node} from './js/cottontail/src/nodes/gltf2.js'; + import {QueryArgs} from './js/cottontail/src/util/query-args.js'; + import {FallbackHelper} from './js/cottontail/src/util/fallback-helper.js'; + import {Node} from './js/cottontail/src/core/node.js'; + import {PbrMaterial} from './js/cottontail/src/materials/pbr.js'; + import {BoxBuilder} from './js/cottontail/src/geometry/box-builder.js'; + import {mat4, vec3, quat} from './js/cottontail/src/math/gl-matrix.js'; + import {BoundsRenderer} from './js/cottontail/src/nodes/bounds-renderer.js'; + + // If requested, initialize the WebXR polyfill + if (QueryArgs.getBool('allowPolyfill', false)) { + var polyfill = new WebXRPolyfill(); + } + + // If requested, don't display the frame rate info. + let hideStats = QueryArgs.getBool('hideStats', false); + + // XR globals. + let xrButton = null; + let xrImmersiveRefSpaceBase = null; + let xrImmersiveRefSpaceOffset = null; + let xrNonImmersiveRefSpaceBase = null; + let xrNonImmersiveRefSpaceOffset = null; + let xrViewerSpace = null; + + // WebGL scene globals. + let gl = null; + let renderer = null; + let scene = new Scene(); + let boundsRenderer = null; + if (hideStats) { + scene.enableStats(false); + } + scene.addNode(new Gltf2Node({url: '../media/gltf/cube-room/cube-room.gltf'})); + scene.standingStats(true); + + let boxes = []; + + let trackingSpaceOriginInWorldSpace = vec3.create(); + let trackingSpaceHeadingDegrees = 0; // around +Y axis, positive angles rotate left + let floorSize = 10; + let floorPosition = [0, -floorSize / 2 + 0.01, 0]; + let floorNode = null; + + function initXR() { + xrButton = new XRDeviceButton({ + onRequestSession: onRequestSession, + onEndSession: onEndSession, + supportedSessionTypes: ['immersive-vr'] + }); + document.querySelector('header').appendChild(xrButton.domElement); + + if (navigator.xr) { + const mode = 'inline'; + navigator.xr.requestSession(mode).then((session) => { + session.mode = mode; + onSessionStarted(session); + }); + } else { + initFallback(); + } + } + + function initFallback() { + initGL(); + let fallbackHelper = new FallbackHelper(scene, gl); + fallbackHelper.emulateStage = true; + } + + function addBox(x, y, z, r, g, b, box_list) { + let boxBuilder = new BoxBuilder(); + boxBuilder.pushCube([0, 0, 0], 0.4); + let boxPrimitive = boxBuilder.finishPrimitive(renderer); + let boxMaterial = new PbrMaterial(); + boxMaterial.baseColorFactor.value = [r, g, b, 1.0]; + let boxRenderPrimitive = renderer.createRenderPrimitive(boxPrimitive, boxMaterial); + let boxNode = new Node(); + boxNode.addRenderPrimitive(boxRenderPrimitive); + // Marks the node as one that needs to be checked when hit testing. + boxNode.selectable = true; + box_list.push({ + node: boxNode, + renderPrimitive: boxRenderPrimitive, + position: [x, y, z] + }); + scene.addNode(boxNode); + } + + function initGL() { + if (gl) + return; + + gl = createWebGLContext({ + xrCompatible: true + }); + document.body.appendChild(gl.canvas); + + function onResize () { + gl.canvas.width = (gl.canvas.offsetWidth * window.devicePixelRatio); + gl.canvas.height = (gl.canvas.offsetHeight * window.devicePixelRatio); + } + window.addEventListener('resize', onResize); + onResize(); + + renderer = new Renderer(gl); + + scene.setRenderer(renderer); + scene.inputRenderer.setControllerMesh(new Gltf2Node({url: '../media/gltf/controller/controller.gltf'})); + + // Create several boxes to use for hit testing. + addBox(-1.0, 1.6, -1.3, 1.0, 0.0, 0.0, boxes); + addBox(0.0, 1.7, -1.5, 0.0, 1.0, 0.0, boxes); + addBox(1.0, 1.6, -1.3, 0.0, 0.0, 1.0, boxes); + + addFloorBox(); + } + + function addFloorBox() { + let boxBuilder = new BoxBuilder(); + boxBuilder.pushCube([0, 0, 0], floorSize); + let boxPrimitive = boxBuilder.finishPrimitive(renderer); + + let boxMaterial = new PbrMaterial(); + boxMaterial.baseColorFactor.value = [0.3, 0.3, 0.3, 1.0]; + let boxRenderPrimitive = renderer.createRenderPrimitive(boxPrimitive, boxMaterial); + + floorNode = new Node(); + floorNode.addRenderPrimitive(boxRenderPrimitive); + floorNode.selectable = true; + scene.addNode(floorNode); + mat4.identity(floorNode.matrix); + mat4.translate(floorNode.matrix, floorNode.matrix, floorPosition); + } + + function onRequestSession() { + const mode = 'immersive-vr'; + navigator.xr.requestSession(mode).then((session) => { + session.mode = mode; + xrButton.setSession(session); + onSessionStarted(session); + }); + } + + function onSessionStarted(session) { + if (!session.mode) { + session.mode = 'inline'; + } + + session.addEventListener('end', onSessionEnded); + + // By listening for the 'select' event we can find out when the user has + // performed some sort of primary input action and respond to it. + session.addEventListener('select', onSelect); + + initGL(); + + session.updateRenderState({ + baseLayer: new XRWebGLLayer(session, gl, { + compositionDisabled: session.mode == 'inline' + }) + }); + + // Same logic for establishing a reference space as in room-scale.html + session.requestReferenceSpace('local-floor').then((refSpace) => { + return refSpace; + }, (e) => { + if (!session.mode.startsWith('immersive')) { + // If we're in inline mode, our underlying platform may not support + // the stationary reference space, but an identity space is guaranteed. + console.log("falling back to identity reference space"); + return session.requestReferenceSpace('viewer'); + } else { + throw e; + } + }).then((refSpace) => { + // Save the session-specific reference space, and apply the + // current player orientation/position as originOffset. + setRefSpace(session, refSpace, false); + updateOriginOffset(session); + session.requestReferenceSpace('viewer').then(function(viewerSpace){ + xrViewerSpace = viewerSpace; + session.requestAnimationFrame(onXRFrame); + }); + }); + } + + let playerInWorldSpaceOld = vec3.create(); + let playerInWorldSpaceNew = vec3.create(); + let playerOffsetInWorldSpaceOld = vec3.create(); + let playerOffsetInWorldSpaceNew = vec3.create(); + let rotationDeltaQuat = quat.create(); + + function onSelect(ev) { + let session = ev.frame.session; + let refSpace = getRefSpace(session, true); + + let headPose = ev.frame.getPose(xrViewerSpace, refSpace); + if (!headPose) return; + + // Get the position offset in world space from the tracking space origin + // to the player's feet. The headPose position is the head position in world space. + // Subtract the tracking space origin position in world space to get a relative world space vector. + vec3.set(playerInWorldSpaceOld, headPose.transform.position.x, 0, headPose.transform.position.z); + vec3.sub(playerOffsetInWorldSpaceOld, playerInWorldSpaceOld, trackingSpaceOriginInWorldSpace); + + // based on https://github.com/immersive-web/webxr/blob/master/input-explainer.md#targeting-ray-pose + let inputSourcePose = ev.frame.getPose(ev.inputSource.targetRaySpace, refSpace); + if (!inputSourcePose) { + return; + } + + vec3.copy(playerInWorldSpaceNew, playerInWorldSpaceOld); + let rotationDelta = 0; + + // Hit test results can change teleport position and orientation. + let targetRay = new XRRay(inputSourcePose.transform); + let hitResult = scene.hitTest(targetRay) + if (hitResult) { + // Check to see if the hit result was one of our boxes. + for (let i = 0; i < boxes.length; ++i) { + let box = boxes[i]; + if (hitResult.node == box.node) { + // Change the box color to something random. + let uniforms = box.renderPrimitive.uniforms; + uniforms.baseColorFactor.value = [Math.random(), Math.random(), Math.random(), 1.0]; + if (i == 0) { + // turn left + rotationDelta = 30; + } else if (i == 1) { + // reset heading by undoing the current rotation + rotationDelta = -trackingSpaceHeadingDegrees; + } else if (i == 2) { + // turn right + rotationDelta = -30; + } + console.log('rotate by', rotationDelta); + } + } + if (hitResult.node == floorNode) { + // New position uses x/z values of the hit test result, keeping y at 0 (floor level) + playerInWorldSpaceNew[0] = hitResult.intersection[0]; + playerInWorldSpaceNew[1] = 0; + playerInWorldSpaceNew[2] = hitResult.intersection[2]; + console.log('teleport to', playerInWorldSpaceNew); + } + } + + // Get the new world space offset vector from tracking space origin + // to the player's feet, for the updated tracking space rotation. + // Formally, this is the old world-space player offset transformed + // into tracking space using the old originOffset's rotation component, + // then transformed back into world space using the inverse of the + // new originOffset. This simplifies to a rotation of the old player + // offset by (new angle - old angle): + // worldOffsetNew = inv(rot_of(originoffsetNew)) * rot_of(originoffsetOld) * worldOffsetOld + // = inv(rotY(-angleNew)) * rotY(-angleOld) * worldOffsetOld + // = rotY(angleNew) * rotY(-angleOld) * worldOffsetOld + // = rotY(angleNew - angleOld) * worldOffsetOld + quat.identity(rotationDeltaQuat); + quat.rotateY(rotationDeltaQuat, rotationDeltaQuat, rotationDelta * Math.PI / 180); + vec3.transformQuat(playerOffsetInWorldSpaceNew, playerOffsetInWorldSpaceOld, rotationDeltaQuat); + trackingSpaceHeadingDegrees += rotationDelta; + + // Update tracking space origin so that origin + playerOffset == player location in world space + vec3.sub(trackingSpaceOriginInWorldSpace, playerInWorldSpaceNew, playerOffsetInWorldSpaceNew); + + updateOriginOffset(session); + } + + function updateOriginOffset(session) { + // Compute the origin offset based on player position/orientation. + quat.identity(invOrientation); + quat.rotateY(invOrientation, invOrientation, -trackingSpaceHeadingDegrees * Math.PI / 180); + vec3.negate(invPosition, trackingSpaceOriginInWorldSpace); + vec3.transformQuat(invPosition, invPosition, invOrientation); + let xform = new XRRigidTransform( + {x: invPosition[0], y: invPosition[1], z: invPosition[2]}, + {x: invOrientation[0], y: invOrientation[1], z: invOrientation[2], w: invOrientation[3]}); + + // Update offset reference to use a new originOffset with the teleported player position and orientation. + // This new offset needs to be applied to the base ref space. + let refSpace = getRefSpace(session, false).getOffsetReferenceSpace(xform); + setRefSpace(session, refSpace, true); + + console.log('teleport to', trackingSpaceOriginInWorldSpace); + } + + function onEndSession(session) { + session.end(); + } + + function onSessionEnded(event) { + if (event.session.mode.startsWith('immersive')) { + xrButton.setSession(null); + } + } + + let invPosition = vec3.create(); + let invOrientation = quat.create(); + + function getRefSpace(session, isOffset) { + return session.mode.startsWith('immersive') ? + (isOffset ? xrImmersiveRefSpaceOffset : xrImmersiveRefSpaceBase) : + (isOffset ? xrNonImmersiveRefSpaceOffset : xrNonImmersiveRefSpaceBase); + } + + function setRefSpace(session, refSpace, isOffset) { + if (session.mode.startsWith('immersive')) { + if (isOffset) { + xrImmersiveRefSpaceOffset = refSpace; + } else { + xrImmersiveRefSpaceBase = refSpace; + } + } else { + if (isOffset) { + xrNonImmersiveRefSpaceOffset = refSpace; + } else { + xrNonImmersiveRefSpaceBase = refSpace; + } + } + } + + function onXRFrame(time, frame) { + let session = frame.session; + let refSpace = getRefSpace(session, true); + + let pose = frame.getViewerPose(refSpace); + scene.startFrame(); + session.requestAnimationFrame(onXRFrame); + + // Update the matrix for each box + for (let box of boxes) { + let node = box.node; + mat4.identity(node.matrix); + mat4.translate(node.matrix, node.matrix, box.position); + mat4.rotateX(node.matrix, node.matrix, time/1000); + mat4.rotateY(node.matrix, node.matrix, time/1500); + } + + scene.updateInputSources(frame, refSpace); + scene.drawXRFrame(frame, pose); + scene.endFrame(); + } + + // Start the XR application. + initXR(); + </script> + </body> +</html>
diff --git a/third_party/webxr_test_pages/webxr-samples/tests/sponza.html b/third_party/webxr_test_pages/webxr-samples/tests/sponza.html index 8ac4dd9..372ed85b 100644 --- a/third_party/webxr_test_pages/webxr-samples/tests/sponza.html +++ b/third_party/webxr_test_pages/webxr-samples/tests/sponza.html
@@ -65,7 +65,7 @@ var polyfill = new WebXRPolyfill(); } - // Temporary + // If requested, don't display the frame rate info. let hideStats = QueryArgs.getBool('hideStats', false); // XR globals.
diff --git a/third_party/webxr_test_pages/webxr-samples/xr-barebones.html b/third_party/webxr_test_pages/webxr-samples/xr-barebones.html index bb9e5e1..0120898 100644 --- a/third_party/webxr_test_pages/webxr-samples/xr-barebones.html +++ b/third_party/webxr_test_pages/webxr-samples/xr-barebones.html
@@ -26,8 +26,8 @@ <meta name='mobile-web-app-capable' content='yes'> <meta name='apple-mobile-web-app-capable' content='yes'> - <!-- Origin Trial Token, feature = WebXR Device API, origin = https://immersive-web.github.io, expires = 2018-08-28 --> -<meta http-equiv="origin-trial" data-feature="WebXR Device API" data-expires="2018-08-28" content="AnNpu7ceXvLew05ccD8Zr1OZsdZiB2hLQKK82kTTMDwF7oRKtP3QEJ4RzkeHrmB8Sq0vSV6ZNmszpBCZ0I8p9gAAAABceyJvcmlnaW4iOiJodHRwczovL2ltbWVyc2l2ZS13ZWIuZ2l0aHViLmlvOjQ0MyIsImZlYXR1cmUiOiJXZWJYUkRldmljZSIsImV4cGlyeSI6MTUzNTQxNDQwMH0="> + <!-- Origin Trial Token, feature = WebXR Device API (For Chrome M76+), origin = storage.googleapis.com, expires = 2019-07-24 --> + <meta http-equiv="origin-trial" data-feature="WebXR Device API (For Chrome M76+)" data-expires="2019-07-24" content="Ap6io/uhkGK7vXCD+golNnQfj8wJ4so790EzZoqb8YOljMXIBTvBEQFPTHYIz5d/BgtuwZTKOLrmHAOt30f38g8AAABxeyJvcmlnaW4iOiJodHRwczovL3N0b3JhZ2UuZ29vZ2xlYXBpcy5jb206NDQzIiwiZmVhdHVyZSI6IldlYlhSRGV2aWNlTTc2IiwiZXhwaXJ5IjoxNTY0MDA5MzU2LCJpc1N1YmRvbWFpbiI6dHJ1ZX0="> <title>Barebones WebXR</title>
diff --git a/tools/chrome_proxy/webdriver/subresource_redirect.py b/tools/chrome_proxy/webdriver/subresource_redirect.py new file mode 100644 index 0000000..9051184 --- /dev/null +++ b/tools/chrome_proxy/webdriver/subresource_redirect.py
@@ -0,0 +1,75 @@ +# 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. + +import re + +from common import TestDriver +from common import IntegrationTest +from decorators import ChromeVersionEqualOrAfterM + +LITEPAGES_REGEXP = r'https://\w+\.litepages\.googlezip\.net/.*' + +class SubresourceRedirect(IntegrationTest): + + @ChromeVersionEqualOrAfterM(77) + def testCompressImage(self): + with TestDriver() as test_driver: + test_driver.AddChromeArg('--enable-subresource-redirect') + test_driver.LoadURL('https://check.googlezip.net/static/index.html') + + image_responses = 0 + + for response in test_driver.GetHTTPResponses(): + content_type = '' + if 'content-type' in response.response_headers: + content_type = response.response_headers['content-type'] + if ('image/' in content_type + and re.match(LITEPAGES_REGEXP, response.url) + and 200 == response.status): + image_responses += 1 + + self.assertEqual(5, image_responses) + + # TODO(harrisonsean): Add compression server bypass test + + @ChromeVersionEqualOrAfterM(77) + def testNoCompressNonImage(self): + with TestDriver() as test_driver: + test_driver.AddChromeArg('--enable-subresource-redirect') + test_driver.LoadURL('https://check.googlezip.net/testvideo.html') + + image_responses = 0 + + for response in test_driver.GetHTTPResponses(): + content_type = '' + if 'content-type' in response.response_headers: + content_type = response.response_headers['content-type'] + if ('image/' in content_type + and re.match(LITEPAGES_REGEXP, response.url) + and 200 == response.status): + image_responses += 1 + + self.assertEqual(0, image_responses) + + @ChromeVersionEqualOrAfterM(77) + def testNoCompressNonHTTPS(self): + with TestDriver() as test_driver: + test_driver.AddChromeArg('--enable-subresource-redirect') + test_driver.LoadURL('http://check.googlezip.net/static/index.html') + + image_responses = 0 + + for response in test_driver.GetHTTPResponses(): + content_type = '' + if 'content-type' in response.response_headers: + content_type = response.response_headers['content-type'] + if ('image/' in content_type + and re.match(LITEPAGES_REGEXP, response.url) + and 200 == response.status): + image_responses += 1 + + self.assertEqual(0, image_responses) + +if __name__ == '__main__': + IntegrationTest.RunAllTests()
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index b4c7094..daabd86c 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -6135,6 +6135,11 @@ <int value="1" label="Opted-in"/> </enum> +<enum name="BooleanOptedOut"> + <int value="0" label="Not opted-out"/> + <int value="1" label="Opted-out"/> +</enum> + <enum name="BooleanOptionConditionsChanged"> <int value="0" label="Conditions unchanged"/> <int value="1" label="Conditions changed"/> @@ -35662,6 +35667,7 @@ <int value="1367529437" label="NTPAssetDownloadSuggestions:enabled"/> <int value="1367671275" label="enable-proximity-auth-proximity-detection"/> <int value="1369449914" label="SysInternals:disabled"/> + <int value="1370797930" label="ShowBluetoothDeviceBattery:enabled"/> <int value="1371092708" label="disable-desktop-capture-picker-old-ui"/> <int value="1371907429" label="enable-wallet-card-import"/> <int value="1372680885" label="enable-mtp-write-support"/> @@ -36118,6 +36124,7 @@ <int value="2043321329" label="OfflinePagesPrefetchingUI:disabled"/> <int value="2047695652" label="DelegateOverscrollSwipes:enabled"/> <int value="2047981703" label="IntentPicker:enabled"/> + <int value="2051403297" label="ShowBluetoothDeviceBattery:disabled"/> <int value="2056572020" label="EnableUsernameCorrection:disabled"/> <int value="2058148069" label="UseMessagesStagingUrl:enabled"/> <int value="2058283872" label="CCTModuleCache:disabled"/> @@ -38202,6 +38209,7 @@ <int value="7" label="Seek backward"/> <int value="8" label="Seek forward"/> <int value="9" label="Skip ad"/> + <int value="10" label="Stop"/> </enum> <enum name="MediaSinkType">
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 2c51a34..a6e2f90 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -61471,6 +61471,16 @@ </summary> </histogram> +<histogram name="MixedAutoupgrade.Navigation.OptedOut" enum="BooleanOptedOut" + expires_after="M79"> + <owner>carlosil@chromium.org</owner> + <owner>estark@chromium.org</owner> + <summary> + Whether a navigation opted out or not of Mixed Content autoupgrades. + Recorded every navigation. + </summary> +</histogram> + <histogram name="MixedAutoupgrade.ResourceRequest.ErrorOrResponseCode" enum="CombinedHttpResponseAndNetErrorCode"> <owner>carlosil@chromium.org</owner>
diff --git a/tools/perf/benchmarks/blink_perf_unittest.py b/tools/perf/benchmarks/blink_perf_unittest.py index 7456eeda..9184e9d 100644 --- a/tools/perf/benchmarks/blink_perf_unittest.py +++ b/tools/perf/benchmarks/blink_perf_unittest.py
@@ -113,7 +113,7 @@ ps=self._CreateStorySetForTestFile( 'simple-blob-measure-async.html'), options=self._options) - self.assertFalse(results.failures) + self.assertFalse(results.had_failures) self.assertEquals(len(results.FindAllTraceValues()), 1) blob_requests = results.FindAllPageSpecificValuesNamed( @@ -151,7 +151,7 @@ ps=self._CreateStorySetForTestFile( 'lifecycle-methods.html'), options=self._options) - self.assertFalse(results.failures) + self.assertFalse(results.had_failures) # pylint: disable=protected-access
diff --git a/ui/accessibility/ax_tree_manager_map.cc b/ui/accessibility/ax_tree_manager_map.cc index ad30a3a..19673fd 100644 --- a/ui/accessibility/ax_tree_manager_map.cc +++ b/ui/accessibility/ax_tree_manager_map.cc
@@ -4,6 +4,8 @@ #include "ui/accessibility/ax_tree_manager_map.h" +#include "base/stl_util.h" + namespace ui { AXTreeManagerMap::AXTreeManagerMap() {} @@ -27,10 +29,10 @@ } AXTreeManager* AXTreeManagerMap::GetManager(AXTreeID tree_id) { - if (tree_id == AXTreeIDUnknown()) + if (tree_id == AXTreeIDUnknown() || !base::Contains(map_, tree_id)) return nullptr; - return map_[tree_id]; + return map_.at(tree_id); } AXTreeManager* AXTreeManagerMap::GetManagerForChildTree(
diff --git a/ui/aura/window_tree_host.cc b/ui/aura/window_tree_host.cc index 825328c54..490d9e8 100644 --- a/ui/aura/window_tree_host.cc +++ b/ui/aura/window_tree_host.cc
@@ -442,6 +442,11 @@ void WindowTreeHost::OnHostResizedInPixels( const gfx::Size& new_size_in_pixels) { + // The compositor is deleted from WM_DESTROY, but we don't delete things until + // WM_NCDESTROY, and it must be possible to still get some messages between + // these two. + if (!compositor_) + return; display::Display display = display::Screen::GetScreen()->GetDisplayNearestWindow(window()); device_scale_factor_ = display.device_scale_factor();
diff --git a/ui/base/ime/win/input_method_win_tsf.cc b/ui/base/ime/win/input_method_win_tsf.cc index 5eff607..972945e 100644 --- a/ui/base/ime/win/input_method_win_tsf.cc +++ b/ui/base/ime/win/input_method_win_tsf.cc
@@ -129,6 +129,14 @@ ui::TSFBridge::GetInstance()->RemoveFocusedClient(client); } +bool InputMethodWinTSF::IsInputLocaleCJK() const { + if (!ui::TSFBridge::GetInstance()) { + return false; + } + + return ui::TSFBridge::GetInstance()->IsInputLanguageCJK(); +} + bool InputMethodWinTSF::IsCandidatePopupOpen() const { return tsf_event_observer_->IsCandidatePopupOpen(); }
diff --git a/ui/base/ime/win/input_method_win_tsf.h b/ui/base/ime/win/input_method_win_tsf.h index b04867d6..9fcf1701 100644 --- a/ui/base/ime/win/input_method_win_tsf.h +++ b/ui/base/ime/win/input_method_win_tsf.h
@@ -33,6 +33,7 @@ void OnCaretBoundsChanged(const TextInputClient* client) override; void CancelComposition(const TextInputClient* client) override; void DetachTextInputClient(TextInputClient* client) override; + bool IsInputLocaleCJK() const override; bool IsCandidatePopupOpen() const override; // Overridden from InputMethodBase:
diff --git a/ui/base/ime/win/tsf_bridge.cc b/ui/base/ime/win/tsf_bridge.cc index 6025a79..e70f1b9 100644 --- a/ui/base/ime/win/tsf_bridge.cc +++ b/ui/base/ime/win/tsf_bridge.cc
@@ -42,6 +42,7 @@ void RemoveFocusedClient(TextInputClient* client) override; void SetInputMethodDelegate(internal::InputMethodDelegate* delegate) override; void RemoveInputMethodDelegate() override; + bool IsInputLanguageCJK() override; Microsoft::WRL::ComPtr<ITfThreadMgr> GetThreadManager() override; TextInputClient* GetFocusedTextInputClient() const override; @@ -109,6 +110,10 @@ // An ITfThreadMgr object to be used in focus and document management. Microsoft::WRL::ComPtr<ITfThreadMgr> thread_manager_; + // An ITfInputProcessorProfiles object to be used to get current language + // locale profile. + Microsoft::WRL::ComPtr<ITfInputProcessorProfiles> input_processor_profiles_; + // A map from TextInputType to an editable document for TSF. We use multiple // TSF documents that have different InputScopes and TSF attributes based on // the TextInputType associated with the target document. For a TextInputType @@ -172,6 +177,13 @@ return false; } + if (FAILED(::CoCreateInstance(CLSID_TF_InputProcessorProfiles, nullptr, + CLSCTX_ALL, + IID_PPV_ARGS(&input_processor_profiles_)))) { + DVLOG(1) << "Failed to create InputProcessorProfiles instance."; + return false; + } + if (FAILED(::CoCreateInstance(CLSID_TF_ThreadMgr, nullptr, CLSCTX_ALL, IID_PPV_ARGS(&thread_manager_)))) { DVLOG(1) << "Failed to create ThreadManager instance."; @@ -332,6 +344,17 @@ } } +bool TSFBridgeImpl::IsInputLanguageCJK() { + LANGID lang_locale; + if (SUCCEEDED(input_processor_profiles_->GetCurrentLanguage(&lang_locale))) { + lang_locale = PRIMARYLANGID(lang_locale); + return lang_locale == LANG_CHINESE || lang_locale == LANG_JAPANESE || + lang_locale == LANG_KOREAN; + } else { + return false; + } +} + TextInputClient* TSFBridgeImpl::GetFocusedTextInputClient() const { return client_; }
diff --git a/ui/base/ime/win/tsf_bridge.h b/ui/base/ime/win/tsf_bridge.h index 2fbc7bf..0082f52 100644 --- a/ui/base/ime/win/tsf_bridge.h +++ b/ui/base/ime/win/tsf_bridge.h
@@ -82,6 +82,9 @@ // Remove InputMethodDelegate instance from TSFTextStore when not in focus. virtual void RemoveInputMethodDelegate() = 0; + // Returns whether the system's input language is CJK. + virtual bool IsInputLanguageCJK() = 0; + // Obtains current thread manager. virtual Microsoft::WRL::ComPtr<ITfThreadMgr> GetThreadManager() = 0;
diff --git a/ui/compositor/test/fake_context_factory.cc b/ui/compositor/test/fake_context_factory.cc index 945c13c1..ef4ecf4 100644 --- a/ui/compositor/test/fake_context_factory.cc +++ b/ui/compositor/test/fake_context_factory.cc
@@ -24,9 +24,7 @@ namespace ui { FakeContextFactory::FakeContextFactory() { -#if defined(OS_WIN) - renderer_settings_.finish_rendering_on_resize = true; -#elif defined(OS_MACOSX) +#if defined(OS_MACOSX) renderer_settings_.release_overlay_resources_after_gpu_query = true; // Ensure that tests don't wait for frames that will never come. ui::CATransactionCoordinator::Get().DisableForTesting();
diff --git a/ui/compositor/test/in_process_context_factory.cc b/ui/compositor/test/in_process_context_factory.cc index 1ed00d3..659b21d 100644 --- a/ui/compositor/test/in_process_context_factory.cc +++ b/ui/compositor/test/in_process_context_factory.cc
@@ -170,9 +170,7 @@ DCHECK_NE(gl::GetGLImplementation(), gl::kGLImplementationNone) << "If running tests, ensure that main() is calling " << "gl::GLSurfaceTestSupport::InitializeOneOff()"; -#if defined(OS_WIN) - renderer_settings_.finish_rendering_on_resize = true; -#elif defined(OS_MACOSX) +#if defined(OS_MACOSX) renderer_settings_.release_overlay_resources_after_gpu_query = true; // Ensure that tests don't wait for frames that will never come. ui::CATransactionCoordinator::Get().DisableForTesting();
diff --git a/ui/events/blink/blink_event_util.cc b/ui/events/blink/blink_event_util.cc index ebb47db..2498868 100644 --- a/ui/events/blink/blink_event_util.cc +++ b/ui/events/blink/blink_event_util.cc
@@ -268,6 +268,7 @@ return (event.GetType() == WebInputEvent::kPointerMove || event.GetType() == WebInputEvent::kPointerRawUpdate) && event.GetType() == event_to_coalesce.GetType() && + event.GetModifiers() == event_to_coalesce.GetModifiers() && event.id == event_to_coalesce.id && event.pointer_type == event_to_coalesce.pointer_type; } @@ -290,6 +291,7 @@ // coalescing mouse events. return event.GetType() == WebInputEvent::kMouseMove && event.GetType() == event_to_coalesce.GetType() && + event.GetModifiers() == event_to_coalesce.GetModifiers() && event.id == event_to_coalesce.id && event.pointer_type == event_to_coalesce.pointer_type; }
diff --git a/ui/events/blink/blink_event_util_unittest.cc b/ui/events/blink/blink_event_util_unittest.cc index f190ed4..dbaa3698 100644 --- a/ui/events/blink/blink_event_util_unittest.cc +++ b/ui/events/blink/blink_event_util_unittest.cc
@@ -10,10 +10,43 @@ #include "third_party/blink/public/platform/web_gesture_event.h" #include "third_party/blink/public/platform/web_input_event.h" #include "third_party/blink/public/platform/web_mouse_wheel_event.h" +#include "third_party/blink/public/platform/web_pointer_event.h" #include "ui/events/gesture_event_details.h" namespace ui { +namespace { + +blink::WebMouseEvent CreateWebMouseMoveEvent() { + blink::WebMouseEvent mouse_event; + mouse_event.SetType(blink::WebInputEvent::kMouseMove); + mouse_event.id = 1; + mouse_event.pointer_type = blink::WebPointerProperties::PointerType::kMouse; + return mouse_event; +} + +blink::WebPointerEvent CreateWebPointerMoveEvent() { + blink::WebPointerEvent pointer_event; + pointer_event.SetType(blink::WebInputEvent::kPointerMove); + pointer_event.id = 1; + pointer_event.pointer_type = blink::WebPointerProperties::PointerType::kMouse; + return pointer_event; +} + +blink::WebTouchEvent CreateWebTouchMoveEvent() { + blink::WebTouchPoint touch_point; + touch_point.id = 1; + touch_point.state = blink::WebTouchPoint::kStateMoved; + touch_point.pointer_type = blink::WebPointerProperties::PointerType::kTouch; + + blink::WebTouchEvent touch_event; + touch_event.SetType(blink::WebInputEvent::kTouchMove); + touch_event.touches[touch_event.touches_length++] = touch_point; + return touch_event; +} + +} // namespace + using BlinkEventUtilTest = testing::Test; TEST(BlinkEventUtilTest, NoScalingWith1DSF) { @@ -173,23 +206,14 @@ } TEST(BlinkEventUtilTest, TouchEventCoalescing) { - blink::WebTouchPoint touch_point; - touch_point.id = 1; - touch_point.state = blink::WebTouchPoint::kStateMoved; - touch_point.pointer_type = blink::WebPointerProperties::PointerType::kTouch; - - blink::WebTouchEvent coalesced_event; + blink::WebTouchEvent coalesced_event = CreateWebTouchMoveEvent(); coalesced_event.SetType(blink::WebInputEvent::kTouchMove); - touch_point.movement_x = 5; - touch_point.movement_y = 10; - coalesced_event.touches[coalesced_event.touches_length++] = touch_point; + coalesced_event.touches[0].movement_x = 5; + coalesced_event.touches[0].movement_y = 10; - blink::WebTouchEvent event_to_be_coalesced; - event_to_be_coalesced.SetType(blink::WebInputEvent::kTouchMove); - touch_point.movement_x = 3; - touch_point.movement_y = -4; - event_to_be_coalesced.touches[event_to_be_coalesced.touches_length++] = - touch_point; + blink::WebTouchEvent event_to_be_coalesced = CreateWebTouchMoveEvent(); + event_to_be_coalesced.touches[0].movement_x = 3; + event_to_be_coalesced.touches[0].movement_y = -4; EXPECT_TRUE(CanCoalesce(event_to_be_coalesced, coalesced_event)); Coalesce(event_to_be_coalesced, &coalesced_event); @@ -199,6 +223,11 @@ coalesced_event.touches[0].pointer_type = blink::WebPointerProperties::PointerType::kPen; EXPECT_FALSE(CanCoalesce(event_to_be_coalesced, coalesced_event)); + + coalesced_event = CreateWebTouchMoveEvent(); + event_to_be_coalesced = CreateWebTouchMoveEvent(); + event_to_be_coalesced.SetModifiers(blink::WebInputEvent::kControlKey); + EXPECT_FALSE(CanCoalesce(event_to_be_coalesced, coalesced_event)); } TEST(BlinkEventUtilTest, WebMouseWheelEventCoalescing) { @@ -321,33 +350,75 @@ } TEST(BlinkEventUtilTest, MouseEventCoalescing) { - blink::WebMouseEvent coalesced_event; - coalesced_event.SetType(blink::WebInputEvent::kMouseMove); + blink::WebMouseEvent coalesced_event = CreateWebMouseMoveEvent(); + blink::WebMouseEvent event_to_be_coalesced = CreateWebMouseMoveEvent(); + EXPECT_TRUE(CanCoalesce(event_to_be_coalesced, coalesced_event)); + + // Test coalescing movements. coalesced_event.movement_x = 5; coalesced_event.movement_y = 10; - coalesced_event.id = 1; - coalesced_event.pointer_type = - blink::WebPointerProperties::PointerType::kMouse; - blink::WebMouseEvent event_to_be_coalesced; - event_to_be_coalesced.SetType(blink::WebInputEvent::kMouseMove); event_to_be_coalesced.movement_x = 3; event_to_be_coalesced.movement_y = -4; - event_to_be_coalesced.id = 1; - event_to_be_coalesced.pointer_type = - blink::WebPointerProperties::PointerType::kMouse; - EXPECT_TRUE(CanCoalesce(event_to_be_coalesced, coalesced_event)); Coalesce(event_to_be_coalesced, &coalesced_event); EXPECT_EQ(8, coalesced_event.movement_x); EXPECT_EQ(6, coalesced_event.movement_y); + // Test id. + coalesced_event = CreateWebMouseMoveEvent(); + event_to_be_coalesced = CreateWebMouseMoveEvent(); event_to_be_coalesced.id = 3; EXPECT_FALSE(CanCoalesce(event_to_be_coalesced, coalesced_event)); + // Test pointer_type. + coalesced_event = CreateWebMouseMoveEvent(); + event_to_be_coalesced = CreateWebMouseMoveEvent(); event_to_be_coalesced.pointer_type = blink::WebPointerProperties::PointerType::kPen; EXPECT_FALSE(CanCoalesce(event_to_be_coalesced, coalesced_event)); + + // Test modifiers + coalesced_event = CreateWebMouseMoveEvent(); + event_to_be_coalesced = CreateWebMouseMoveEvent(); + event_to_be_coalesced.SetModifiers(blink::WebInputEvent::kControlKey); + EXPECT_FALSE(CanCoalesce(event_to_be_coalesced, coalesced_event)); +} + +TEST(BlinkEventUtilTest, PointerEventCoalescing) { + blink::WebPointerEvent coalesced_event = CreateWebPointerMoveEvent(); + blink::WebPointerEvent event_to_be_coalesced = CreateWebPointerMoveEvent(); + EXPECT_TRUE(CanCoalesce(event_to_be_coalesced, coalesced_event)); + + // Test coalescing movements. + coalesced_event.movement_x = 5; + coalesced_event.movement_y = 10; + + event_to_be_coalesced.movement_x = 3; + event_to_be_coalesced.movement_y = -4; + EXPECT_TRUE(CanCoalesce(event_to_be_coalesced, coalesced_event)); + Coalesce(event_to_be_coalesced, &coalesced_event); + EXPECT_EQ(8, coalesced_event.movement_x); + EXPECT_EQ(6, coalesced_event.movement_y); + + // Test id. + coalesced_event = CreateWebPointerMoveEvent(); + event_to_be_coalesced = CreateWebPointerMoveEvent(); + event_to_be_coalesced.id = 3; + EXPECT_FALSE(CanCoalesce(event_to_be_coalesced, coalesced_event)); + + // Test pointer_type. + coalesced_event = CreateWebPointerMoveEvent(); + event_to_be_coalesced = CreateWebPointerMoveEvent(); + event_to_be_coalesced.pointer_type = + blink::WebPointerProperties::PointerType::kPen; + EXPECT_FALSE(CanCoalesce(event_to_be_coalesced, coalesced_event)); + + // Test modifiers + coalesced_event = CreateWebPointerMoveEvent(); + event_to_be_coalesced = CreateWebPointerMoveEvent(); + event_to_be_coalesced.SetModifiers(blink::WebInputEvent::kControlKey); + EXPECT_FALSE(CanCoalesce(event_to_be_coalesced, coalesced_event)); } TEST(BlinkEventUtilTest, WebEventModifersAndEventFlags) {
diff --git a/ui/gfx/linux/native_pixmap_dmabuf.cc b/ui/gfx/linux/native_pixmap_dmabuf.cc index e0417c0..97fa6de 100644 --- a/ui/gfx/linux/native_pixmap_dmabuf.cc +++ b/ui/gfx/linux/native_pixmap_dmabuf.cc
@@ -33,14 +33,14 @@ return handle_.planes[plane].fd.get(); } -int NativePixmapDmaBuf::GetDmaBufPitch(size_t plane) const { +uint32_t NativePixmapDmaBuf::GetDmaBufPitch(size_t plane) const { DCHECK_LT(plane, handle_.planes.size()); return handle_.planes[plane].stride; } -int NativePixmapDmaBuf::GetDmaBufOffset(size_t plane) const { +size_t NativePixmapDmaBuf::GetDmaBufOffset(size_t plane) const { DCHECK_LT(plane, handle_.planes.size()); - return handle_.planes[plane].offset; + return static_cast<size_t>(handle_.planes[plane].offset); } size_t NativePixmapDmaBuf::GetDmaBufPlaneSize(size_t plane) const {
diff --git a/ui/gfx/linux/native_pixmap_dmabuf.h b/ui/gfx/linux/native_pixmap_dmabuf.h index cd0c665..dbfb919 100644 --- a/ui/gfx/linux/native_pixmap_dmabuf.h +++ b/ui/gfx/linux/native_pixmap_dmabuf.h
@@ -30,8 +30,8 @@ // NativePixmap: bool AreDmaBufFdsValid() const override; int GetDmaBufFd(size_t plane) const override; - int GetDmaBufPitch(size_t plane) const override; - int GetDmaBufOffset(size_t plane) const override; + uint32_t GetDmaBufPitch(size_t plane) const override; + size_t GetDmaBufOffset(size_t plane) const override; size_t GetDmaBufPlaneSize(size_t plane) const override; uint64_t GetBufferFormatModifier() const override; gfx::BufferFormat GetBufferFormat() const override;
diff --git a/ui/gfx/mojo/buffer_types.mojom b/ui/gfx/mojo/buffer_types.mojom index ecd50be..8d86e063 100644 --- a/ui/gfx/mojo/buffer_types.mojom +++ b/ui/gfx/mojo/buffer_types.mojom
@@ -52,7 +52,7 @@ [EnableIf=supports_native_pixmap] struct NativePixmapPlane { uint32 stride; - int32 offset; + uint64 offset; uint64 size; // A platform-specific handle the underlying memory object.
diff --git a/ui/gfx/native_pixmap.h b/ui/gfx/native_pixmap.h index 9c7d52f75..7cb6717 100644 --- a/ui/gfx/native_pixmap.h +++ b/ui/gfx/native_pixmap.h
@@ -27,8 +27,8 @@ virtual bool AreDmaBufFdsValid() const = 0; virtual int GetDmaBufFd(size_t plane) const = 0; - virtual int GetDmaBufPitch(size_t plane) const = 0; - virtual int GetDmaBufOffset(size_t plane) const = 0; + virtual uint32_t GetDmaBufPitch(size_t plane) const = 0; + virtual size_t GetDmaBufOffset(size_t plane) const = 0; virtual size_t GetDmaBufPlaneSize(size_t plane) const = 0; // The following methods return format, modifier and size of the buffer,
diff --git a/ui/gfx/native_pixmap_handle.h b/ui/gfx/native_pixmap_handle.h index 562433f..da15ba5 100644 --- a/ui/gfx/native_pixmap_handle.h +++ b/ui/gfx/native_pixmap_handle.h
@@ -47,8 +47,8 @@ // The strides and offsets in bytes to be used when accessing the buffers via // a memory mapping. One per plane per entry. - int stride; - int offset; + uint32_t stride; + uint64_t offset; // Size in bytes of the plane. // This is necessary to map the buffers. uint64_t size;
diff --git a/ui/gl/gl_surface_egl.cc b/ui/gl/gl_surface_egl.cc index f8e5dae..249cd6b7 100644 --- a/ui/gl/gl_surface_egl.cc +++ b/ui/gl/gl_surface_egl.cc
@@ -1562,6 +1562,8 @@ int width, int height, PresentationCallback callback) { + TRACE_EVENT2("gpu", "NativeViewGLSurfaceEGL:PostSubBuffer", "width", width, + "height", height); DCHECK(supports_post_sub_buffer_); if (!CommitAndClearPendingOverlays()) { DVLOG(1) << "Failed to commit pending overlay planes.";
diff --git a/ui/ozone/common/linux/gbm_buffer.h b/ui/ozone/common/linux/gbm_buffer.h index cad6f6b..2c7d803 100644 --- a/ui/ozone/common/linux/gbm_buffer.h +++ b/ui/ozone/common/linux/gbm_buffer.h
@@ -31,8 +31,8 @@ virtual size_t GetNumPlanes() const = 0; virtual int GetPlaneFd(size_t plane) const = 0; virtual uint32_t GetPlaneHandle(size_t plane) const = 0; - virtual int GetPlaneStride(size_t plane) const = 0; - virtual int GetPlaneOffset(size_t plane) const = 0; + virtual uint32_t GetPlaneStride(size_t plane) const = 0; + virtual size_t GetPlaneOffset(size_t plane) const = 0; virtual size_t GetPlaneSize(size_t plane) const = 0; virtual uint32_t GetHandle() const = 0; virtual gfx::NativePixmapHandle ExportHandle() const = 0;
diff --git a/ui/ozone/common/linux/gbm_wrapper.cc b/ui/ozone/common/linux/gbm_wrapper.cc index ccc5b32..6d11f2c 100644 --- a/ui/ozone/common/linux/gbm_wrapper.cc +++ b/ui/ozone/common/linux/gbm_wrapper.cc
@@ -126,11 +126,11 @@ DCHECK_LT(plane, handle_.planes.size()); return handle_.planes[plane].fd.get(); } - int GetPlaneStride(size_t plane) const override { + uint32_t GetPlaneStride(size_t plane) const override { DCHECK_LT(plane, handle_.planes.size()); return handle_.planes[plane].stride; } - int GetPlaneOffset(size_t plane) const override { + size_t GetPlaneOffset(size_t plane) const override { DCHECK_LT(plane, handle_.planes.size()); return handle_.planes[plane].offset; } @@ -261,7 +261,7 @@ uint32_t format, const gfx::Size& size, gfx::NativePixmapHandle handle) override { - DCHECK_EQ(handle.planes[0].offset, 0); + DCHECK_EQ(handle.planes[0].offset, 0u); // Try to use scanout if supported. int gbm_flags = GBM_BO_USE_SCANOUT;
diff --git a/ui/ozone/platform/cast/surface_factory_cast.cc b/ui/ozone/platform/cast/surface_factory_cast.cc index 4643843..0d229b3 100644 --- a/ui/ozone/platform/cast/surface_factory_cast.cc +++ b/ui/ozone/platform/cast/surface_factory_cast.cc
@@ -51,8 +51,8 @@ bool AreDmaBufFdsValid() const override { return false; } int GetDmaBufFd(size_t plane) const override { return -1; } - int GetDmaBufPitch(size_t plane) const override { return 0; } - int GetDmaBufOffset(size_t plane) const override { return 0; } + uint32_t GetDmaBufPitch(size_t plane) const override { return 0; } + size_t GetDmaBufOffset(size_t plane) const override { return 0; } size_t GetDmaBufPlaneSize(size_t plane) const override { return 0; } uint64_t GetBufferFormatModifier() const override { return 0; } gfx::BufferFormat GetBufferFormat() const override {
diff --git a/ui/ozone/platform/drm/gpu/gbm_pixmap.cc b/ui/ozone/platform/drm/gpu/gbm_pixmap.cc index 2055555..c63eb9f 100644 --- a/ui/ozone/platform/drm/gpu/gbm_pixmap.cc +++ b/ui/ozone/platform/drm/gpu/gbm_pixmap.cc
@@ -36,11 +36,11 @@ return buffer_->GetPlaneFd(plane); } -int GbmPixmap::GetDmaBufPitch(size_t plane) const { +uint32_t GbmPixmap::GetDmaBufPitch(size_t plane) const { return buffer_->GetPlaneStride(plane); } -int GbmPixmap::GetDmaBufOffset(size_t plane) const { +size_t GbmPixmap::GetDmaBufOffset(size_t plane) const { return buffer_->GetPlaneOffset(plane); }
diff --git a/ui/ozone/platform/drm/gpu/gbm_pixmap.h b/ui/ozone/platform/drm/gpu/gbm_pixmap.h index db22bbf9..5e00f78 100644 --- a/ui/ozone/platform/drm/gpu/gbm_pixmap.h +++ b/ui/ozone/platform/drm/gpu/gbm_pixmap.h
@@ -27,8 +27,8 @@ // NativePixmap: bool AreDmaBufFdsValid() const override; int GetDmaBufFd(size_t plane) const override; - int GetDmaBufPitch(size_t plane) const override; - int GetDmaBufOffset(size_t plane) const override; + uint32_t GetDmaBufPitch(size_t plane) const override; + size_t GetDmaBufOffset(size_t plane) const override; size_t GetDmaBufPlaneSize(size_t plane) const override; uint64_t GetBufferFormatModifier() const override; gfx::BufferFormat GetBufferFormat() const override;
diff --git a/ui/ozone/platform/drm/gpu/mock_gbm_device.cc b/ui/ozone/platform/drm/gpu/mock_gbm_device.cc index d2fb2a5..9680a22 100644 --- a/ui/ozone/platform/drm/gpu/mock_gbm_device.cc +++ b/ui/ozone/platform/drm/gpu/mock_gbm_device.cc
@@ -49,11 +49,11 @@ NOTREACHED(); return -1; } - int GetPlaneStride(size_t plane) const override { + uint32_t GetPlaneStride(size_t plane) const override { DCHECK_LT(plane, planes_.size()); return planes_[plane].stride; } - int GetPlaneOffset(size_t plane) const override { + size_t GetPlaneOffset(size_t plane) const override { DCHECK_LT(plane, planes_.size()); return planes_[plane].offset; }
diff --git a/ui/ozone/platform/headless/headless_surface_factory.cc b/ui/ozone/platform/headless/headless_surface_factory.cc index 73ab3cd..b982cf5 100644 --- a/ui/ozone/platform/headless/headless_surface_factory.cc +++ b/ui/ozone/platform/headless/headless_surface_factory.cc
@@ -83,8 +83,8 @@ bool AreDmaBufFdsValid() const override { return false; } int GetDmaBufFd(size_t plane) const override { return -1; } - int GetDmaBufPitch(size_t plane) const override { return 0; } - int GetDmaBufOffset(size_t plane) const override { return 0; } + uint32_t GetDmaBufPitch(size_t plane) const override { return 0; } + size_t GetDmaBufOffset(size_t plane) const override { return 0; } size_t GetDmaBufPlaneSize(size_t plane) const override { return 0; } uint64_t GetBufferFormatModifier() const override { return 0; } gfx::BufferFormat GetBufferFormat() const override { return format_; }
diff --git a/ui/ozone/platform/scenic/sysmem_buffer_collection.cc b/ui/ozone/platform/scenic/sysmem_buffer_collection.cc index aef7b7d..72fc3f25 100644 --- a/ui/ozone/platform/scenic/sysmem_buffer_collection.cc +++ b/ui/ozone/platform/scenic/sysmem_buffer_collection.cc
@@ -25,13 +25,13 @@ NOTREACHED(); return -1; } - int GetDmaBufPitch(size_t plane) const override { + uint32_t GetDmaBufPitch(size_t plane) const override { NOTREACHED(); - return 0; + return 0u; } - int GetDmaBufOffset(size_t plane) const override { + size_t GetDmaBufOffset(size_t plane) const override { NOTREACHED(); - return 0; + return 0u; } size_t GetDmaBufPlaneSize(size_t plane) const override { NOTREACHED();
diff --git a/ui/ozone/platform/wayland/gpu/gbm_pixmap_wayland.cc b/ui/ozone/platform/wayland/gpu/gbm_pixmap_wayland.cc index c4f97786..7fea3d603 100644 --- a/ui/ozone/platform/wayland/gpu/gbm_pixmap_wayland.cc +++ b/ui/ozone/platform/wayland/gpu/gbm_pixmap_wayland.cc
@@ -94,11 +94,11 @@ return gbm_bo_->GetPlaneFd(plane); } -int GbmPixmapWayland::GetDmaBufPitch(size_t plane) const { +uint32_t GbmPixmapWayland::GetDmaBufPitch(size_t plane) const { return gbm_bo_->GetPlaneStride(plane); } -int GbmPixmapWayland::GetDmaBufOffset(size_t plane) const { +size_t GbmPixmapWayland::GetDmaBufOffset(size_t plane) const { return gbm_bo_->GetPlaneOffset(plane); }
diff --git a/ui/ozone/platform/wayland/gpu/gbm_pixmap_wayland.h b/ui/ozone/platform/wayland/gpu/gbm_pixmap_wayland.h index baee537..54829c3 100644 --- a/ui/ozone/platform/wayland/gpu/gbm_pixmap_wayland.h +++ b/ui/ozone/platform/wayland/gpu/gbm_pixmap_wayland.h
@@ -32,8 +32,8 @@ // gfx::NativePixmap overrides: bool AreDmaBufFdsValid() const override; int GetDmaBufFd(size_t plane) const override; - int GetDmaBufPitch(size_t plane) const override; - int GetDmaBufOffset(size_t plane) const override; + uint32_t GetDmaBufPitch(size_t plane) const override; + size_t GetDmaBufOffset(size_t plane) const override; size_t GetDmaBufPlaneSize(size_t plane) const override; uint64_t GetBufferFormatModifier() const override; gfx::BufferFormat GetBufferFormat() const override;
diff --git a/ui/ozone/platform/wayland/gpu/wayland_surface_factory_unittest.cc b/ui/ozone/platform/wayland/gpu/wayland_surface_factory_unittest.cc index 267aae96..821b673 100644 --- a/ui/ozone/platform/wayland/gpu/wayland_surface_factory_unittest.cc +++ b/ui/ozone/platform/wayland/gpu/wayland_surface_factory_unittest.cc
@@ -44,8 +44,8 @@ size_t GetNumPlanes() const override { return 0; } int GetPlaneFd(size_t plane) const override { return -1; } uint32_t GetPlaneHandle(size_t plane) const override { return 0; } - int GetPlaneStride(size_t plane) const override { return -1; } - int GetPlaneOffset(size_t plane) const override { return -1; } + uint32_t GetPlaneStride(size_t plane) const override { return 0u; } + size_t GetPlaneOffset(size_t plane) const override { return 0u; } size_t GetPlaneSize(size_t plane) const override { return 0; } uint32_t GetHandle() const override { return 0; } gfx::NativePixmapHandle ExportHandle() const override {
diff --git a/ui/webui/resources/cr_elements/chromeos/cr_picture/cr_camera.html b/ui/webui/resources/cr_elements/chromeos/cr_picture/cr_camera.html index 3238057..7d115878 100644 --- a/ui/webui/resources/cr_elements/chromeos/cr_picture/cr_camera.html +++ b/ui/webui/resources/cr_elements/chromeos/cr_picture/cr_camera.html
@@ -85,6 +85,7 @@ height: var(--cr-camera-image-size, 228px); object-fit: cover; object-position: center; + position: absolute; width: var(--cr-camera-image-size, 228px); }