1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "ash/test/ash_test_helper.h"
6 
7 #include <algorithm>
8 
9 #include "ash/accelerometer/accelerometer_reader.h"
10 #include "ash/ambient/test/ambient_ash_test_helper.h"
11 #include "ash/app_list/test/app_list_test_helper.h"
12 #include "ash/assistant/assistant_controller_impl.h"
13 #include "ash/assistant/test/test_assistant_service.h"
14 #include "ash/display/display_configuration_controller_test_api.h"
15 #include "ash/display/screen_ash.h"
16 #include "ash/host/ash_window_tree_host.h"
17 #include "ash/keyboard/keyboard_controller_impl.h"
18 #include "ash/keyboard/test_keyboard_ui.h"
19 #include "ash/public/cpp/ash_switches.h"
20 #include "ash/public/cpp/test/test_keyboard_controller_observer.h"
21 #include "ash/public/cpp/test/test_new_window_delegate.h"
22 #include "ash/session/test_session_controller_client.h"
23 #include "ash/shell.h"
24 #include "ash/shell_init_params.h"
25 #include "ash/system/model/system_tray_model.h"
26 #include "ash/system/screen_layout_observer.h"
27 #include "ash/test/ash_test_views_delegate.h"
28 #include "ash/test/toplevel_window.h"
29 #include "ash/test_shell_delegate.h"
30 #include "ash/wallpaper/wallpaper_controller_impl.h"
31 #include "ash/wm/overview/overview_controller.h"
32 #include "ash/wm/tablet_mode/tablet_mode_controller.h"
33 #include "base/run_loop.h"
34 #include "base/system/sys_info.h"
35 #include "chromeos/audio/cras_audio_handler.h"
36 #include "chromeos/dbus/audio/cras_audio_client.h"
37 #include "chromeos/dbus/power/power_policy_controller.h"
38 #include "device/bluetooth/bluetooth_adapter_factory.h"
39 #include "device/bluetooth/dbus/bluez_dbus_manager.h"
40 #include "ui/aura/test/test_windows.h"
41 #include "ui/aura/window.h"
42 #include "ui/aura/window_tree_host.h"
43 #include "ui/display/display.h"
44 #include "ui/display/display_switches.h"
45 #include "ui/display/manager/display_manager.h"
46 #include "ui/display/test/display_manager_test_api.h"
47 #include "ui/events/gesture_detection/gesture_configuration.h"
48 #include "ui/gfx/geometry/point.h"
49 #include "ui/platform_window/common/platform_window_defaults.h"
50 #include "ui/views/test/views_test_helper_aura.h"
51 #include "ui/wm/core/capture_controller.h"
52 #include "ui/wm/core/cursor_manager.h"
53 #include "ui/wm/core/focus_controller.h"
54 
55 namespace ash {
56 
57 namespace {
MakeTestViewsDelegate()58 std::unique_ptr<views::TestViewsDelegate> MakeTestViewsDelegate() {
59   return std::make_unique<AshTestViewsDelegate>();
60 }
61 }  // namespace
62 
63 AshTestHelper::InitParams::InitParams() = default;
64 AshTestHelper::InitParams::InitParams(InitParams&&) = default;
65 AshTestHelper::InitParams::~InitParams() = default;
66 
67 class AshTestHelper::BluezDBusManagerInitializer {
68  public:
BluezDBusManagerInitializer()69   BluezDBusManagerInitializer() { bluez::BluezDBusManager::InitializeFake(); }
~BluezDBusManagerInitializer()70   ~BluezDBusManagerInitializer() {
71     device::BluetoothAdapterFactory::Shutdown();
72     bluez::BluezDBusManager::Shutdown();
73   }
74 };
75 
76 class AshTestHelper::PowerPolicyControllerInitializer {
77  public:
PowerPolicyControllerInitializer()78   PowerPolicyControllerInitializer() {
79     chromeos::PowerPolicyController::Initialize(
80         chromeos::PowerManagerClient::Get());
81   }
~PowerPolicyControllerInitializer()82   ~PowerPolicyControllerInitializer() {
83     chromeos::PowerPolicyController::Shutdown();
84   }
85 };
86 
AshTestHelper(ConfigType config_type,ui::ContextFactory * context_factory)87 AshTestHelper::AshTestHelper(ConfigType config_type,
88                              ui::ContextFactory* context_factory)
89     : AuraTestHelper(context_factory, config_type == kUnitTest),
90       config_type_(config_type) {
91   views::ViewsTestHelperAura::SetFallbackTestViewsDelegateFactory(
92       &MakeTestViewsDelegate);
93 
94   // TODO(jamescook): Can we do this without changing command line?
95   // Use the origin (1,1) so that it doesn't overlap with the native mouse
96   // cursor.
97   if (!base::SysInfo::IsRunningOnChromeOS() &&
98       !command_line_->GetProcessCommandLine()->HasSwitch(
99           ::switches::kHostWindowBounds)) {
100     // TODO(oshima): Disable native events instead of adding offset.
101     command_line_->GetProcessCommandLine()->AppendSwitchASCII(
102         ::switches::kHostWindowBounds, "10+10-800x600");
103   }
104 
105   if (config_type_ == kUnitTest)
106     TabletModeController::SetUseScreenshotForTest(false);
107 
108   if (config_type_ != kShell)
109     display::ResetDisplayIdForTest();
110 
111   chromeos::CrasAudioClient::InitializeFake();
112   // Create CrasAudioHandler for testing since g_browser_process is not
113   // created in AshTestBase tests.
114   chromeos::CrasAudioHandler::InitializeForTesting();
115 
116   // Reset the global state for the cursor manager. This includes the
117   // last cursor visibility state, etc.
118   wm::CursorManager::ResetCursorVisibilityStateForTest();
119 
120   // Clears the saved state so that test doesn't use on the wrong
121   // default state.
122   shell::ToplevelWindow::ClearSavedStateForTest();
123 }
124 
~AshTestHelper()125 AshTestHelper::~AshTestHelper() {
126   if (app_list_test_helper_)
127     TearDown();
128 
129   // Ensure the next test starts with a null display::Screen.  This must be done
130   // here instead of in TearDown() since some tests test access to the Screen
131   // after the shell shuts down (which they use TearDown() to trigger).
132   ScreenAsh::DeleteScreenForShutdown();
133 
134   // This should never have a meaningful effect, since either there is no
135   // ViewsTestHelperAura instance or the instance is currently in its
136   // destructor.
137   views::ViewsTestHelperAura::SetFallbackTestViewsDelegateFactory(nullptr);
138 }
139 
SetUp()140 void AshTestHelper::SetUp() {
141   SetUp(InitParams());
142 }
143 
TearDown()144 void AshTestHelper::TearDown() {
145   ambient_ash_test_helper_.reset();
146 
147   // The AppListTestHelper holds a pointer to the AppListController the Shell
148   // owns, so shut the test helper down first.
149   app_list_test_helper_.reset();
150 
151   Shell::DeleteInstance();
152   // Suspend the tear down until all resources are returned via
153   // CompositorFrameSinkClient::ReclaimResources()
154   base::RunLoop().RunUntilIdle();
155 
156   chromeos::CrasAudioHandler::Shutdown();
157   chromeos::CrasAudioClient::Shutdown();
158 
159   // The PowerPolicyController holds a pointer to the PowerManagementClient, so
160   // shut the controller down first.
161   power_policy_controller_initializer_.reset();
162   chromeos::PowerManagerClient::Shutdown();
163 
164   TabletModeController::SetUseScreenshotForTest(true);
165 
166   // Destroy all owned objects to prevent tests from depending on their state
167   // after this returns.
168   test_keyboard_controller_observer_.reset();
169   session_controller_client_.reset();
170   test_views_delegate_.reset();
171   new_window_delegate_.reset();
172   bluez_dbus_manager_initializer_.reset();
173   system_tray_client_.reset();
174   assistant_service_.reset();
175   notifier_settings_controller_.reset();
176   prefs_provider_.reset();
177   statistics_provider_.reset();
178   command_line_.reset();
179 
180   AuraTestHelper::TearDown();
181 }
182 
GetContext()183 aura::Window* AshTestHelper::GetContext() {
184   aura::Window* root_window = Shell::GetRootWindowForNewWindows();
185   if (!root_window)
186     root_window = Shell::GetPrimaryRootWindow();
187   DCHECK(root_window);
188   return root_window;
189 }
190 
GetHost()191 aura::WindowTreeHost* AshTestHelper::GetHost() {
192   auto* manager = Shell::Get()->window_tree_host_manager();
193   const int64_t id = manager->GetPrimaryDisplayId();
194   return manager->GetAshWindowTreeHostForDisplayId(id)->AsWindowTreeHost();
195 }
196 
GetTestScreen()197 aura::TestScreen* AshTestHelper::GetTestScreen() {
198   // If a test needs this, we may need to refactor TestScreen such that its
199   // methods can operate atop some sort of real screen/host/display, and hook
200   // them to the ones provided by the shell.  For now, not bothering.
201   NOTIMPLEMENTED();
202   return nullptr;
203 }
204 
GetFocusClient()205 aura::client::FocusClient* AshTestHelper::GetFocusClient() {
206   return Shell::Get()->focus_controller();
207 }
208 
GetCaptureClient()209 aura::client::CaptureClient* AshTestHelper::GetCaptureClient() {
210   return wm::CaptureController::Get();
211 }
212 
SetUp(InitParams init_params)213 void AshTestHelper::SetUp(InitParams init_params) {
214   // This block of objects are conditionally initialized here rather than in the
215   // constructor to make it easier for test classes to override them.
216   if (!bluez::BluezDBusManager::IsInitialized()) {
217     bluez_dbus_manager_initializer_ =
218         std::make_unique<BluezDBusManagerInitializer>();
219   }
220   if (!chromeos::PowerManagerClient::Get())
221     chromeos::PowerManagerClient::InitializeFake();
222   if (!chromeos::PowerPolicyController::IsInitialized()) {
223     power_policy_controller_initializer_ =
224         std::make_unique<PowerPolicyControllerInitializer>();
225   }
226   if (!NewWindowDelegate::GetInstance())
227     new_window_delegate_ = std::make_unique<TestNewWindowDelegate>();
228   if (!views::ViewsDelegate::GetInstance())
229     test_views_delegate_ = MakeTestViewsDelegate();
230 
231   ambient_ash_test_helper_ = std::make_unique<AmbientAshTestHelper>();
232 
233   ShellInitParams shell_init_params;
234   shell_init_params.delegate = std::move(init_params.delegate);
235   if (!shell_init_params.delegate)
236     shell_init_params.delegate = std::make_unique<TestShellDelegate>();
237   shell_init_params.context_factory = GetContextFactory();
238   shell_init_params.local_state = init_params.local_state;
239   shell_init_params.keyboard_ui_factory =
240       std::make_unique<TestKeyboardUIFactory>();
241   Shell::CreateInstance(std::move(shell_init_params));
242   Shell* shell = Shell::Get();
243 
244   // Cursor is visible by default in tests.
245   shell->cursor_manager()->ShowCursor();
246 
247   shell->assistant_controller()->SetAssistant(assistant_service_.get());
248 
249   shell->system_tray_model()->SetClient(system_tray_client_.get());
250 
251   session_controller_client_ = std::make_unique<TestSessionControllerClient>(
252       shell->session_controller(), prefs_provider_.get());
253   session_controller_client_->InitializeAndSetClient();
254   if (init_params.start_session)
255     session_controller_client_->CreatePredefinedUserSessions(1);
256 
257   // Requires the AppListController the Shell creates.
258   app_list_test_helper_ = std::make_unique<AppListTestHelper>();
259 
260   Shell::GetPrimaryRootWindow()->Show();
261   Shell::GetPrimaryRootWindow()->GetHost()->Show();
262 
263   if (config_type_ == kShell) {
264     shell->wallpaper_controller()->ShowDefaultWallpaperForTesting();
265     return;
266   }
267 
268   // Don't change the display size due to host size resize.
269   display::test::DisplayManagerTestApi(shell->display_manager())
270       .DisableChangeDisplayUponHostResize();
271 
272   // Create the test keyboard controller observer to respond to
273   // OnLoadKeyboardContentsRequested().
274   test_keyboard_controller_observer_ =
275       std::make_unique<TestKeyboardControllerObserver>(
276           shell->keyboard_controller());
277 
278   if (config_type_ != kUnitTest)
279     return;
280 
281   // Tests that change the display configuration generally don't care about the
282   // notifications and the popup UI can interfere with things like cursors.
283   shell->screen_layout_observer()->set_show_notifications_for_testing(false);
284 
285   // Disable display change animations in unit tests.
286   DisplayConfigurationControllerTestApi(
287       shell->display_configuration_controller())
288       .SetDisplayAnimator(false);
289 
290   // Remove the app dragging animations delay for testing purposes.
291   shell->overview_controller()->set_delayed_animation_task_delay_for_test(
292       base::TimeDelta());
293 
294   // Tests expect empty wallpaper.
295   shell->wallpaper_controller()->CreateEmptyWallpaperForTesting();
296 
297   // Move the mouse cursor to far away so that native events don't interfere
298   // with test expectations.
299   Shell::GetPrimaryRootWindow()->MoveCursorTo(gfx::Point(-1000, -1000));
300   Shell::Get()->cursor_manager()->EnableMouseEvents();
301 
302   // Changing GestureConfiguration shouldn't make tests fail. These values
303   // prevent unexpected events from being generated during tests. Such as
304   // delayed events which create race conditions on slower tests.
305   ui::GestureConfiguration* gesture_config =
306       ui::GestureConfiguration::GetInstance();
307   gesture_config->set_max_touch_down_duration_for_click_in_ms(800);
308   gesture_config->set_long_press_time_in_ms(1000);
309   gesture_config->set_max_touch_move_in_pixels_for_click(5);
310 
311   // Fake the |ec_lid_angle_driver_status_| in the unittests.
312   AccelerometerReader::GetInstance()->SetECLidAngleDriverStatusForTesting(
313       ECLidAngleDriverStatus::NOT_SUPPORTED);
314 }
315 
GetSecondaryDisplay() const316 display::Display AshTestHelper::GetSecondaryDisplay() const {
317   return display::test::DisplayManagerTestApi(Shell::Get()->display_manager())
318       .GetSecondaryDisplay();
319 }
320 
321 }  // namespace ash
322