a32812ab46688111e7ac0db0724142e5431a6dc9
[platform/framework/web/crosswalk.git] / src / ash / wm / maximize_mode / maximize_mode_controller.cc
1 // Copyright 2014 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/wm/maximize_mode/maximize_mode_controller.h"
6
7 #include "ash/accelerators/accelerator_controller.h"
8 #include "ash/accelerators/accelerator_table.h"
9 #include "ash/accelerometer/accelerometer_controller.h"
10 #include "ash/ash_switches.h"
11 #include "ash/display/display_manager.h"
12 #include "ash/shell.h"
13 #include "ash/wm/maximize_mode/maximize_mode_event_blocker.h"
14 #include "ash/wm/maximize_mode/maximize_mode_window_manager.h"
15 #include "base/auto_reset.h"
16 #include "base/command_line.h"
17 #include "base/metrics/histogram.h"
18 #include "ui/base/accelerators/accelerator.h"
19 #include "ui/events/event.h"
20 #include "ui/events/event_handler.h"
21 #include "ui/events/keycodes/keyboard_codes.h"
22 #include "ui/gfx/vector3d_f.h"
23
24 namespace ash {
25
26 namespace {
27
28 // The hinge angle at which to enter maximize mode.
29 const float kEnterMaximizeModeAngle = 200.0f;
30
31 // The angle at which to exit maximize mode, this is specifically less than the
32 // angle to enter maximize mode to prevent rapid toggling when near the angle.
33 const float kExitMaximizeModeAngle = 160.0f;
34
35 // When the lid is fully open 360 degrees, the accelerometer readings can
36 // occasionally appear as though the lid is almost closed. If the lid appears
37 // near closed but the device is on we assume it is an erroneous reading from
38 // it being open 360 degrees.
39 const float kFullyOpenAngleErrorTolerance = 20.0f;
40
41 // When the device approaches vertical orientation (i.e. portrait orientation)
42 // the accelerometers for the base and lid approach the same values (i.e.
43 // gravity pointing in the direction of the hinge). When this happens we cannot
44 // compute the hinge angle reliably and must turn ignore accelerometer readings.
45 // This is the minimum acceleration perpendicular to the hinge under which to
46 // detect hinge angle.
47 const float kHingeAngleDetectionThreshold = 0.25f;
48
49 // The maximum deviation from the acceleration expected due to gravity under
50 // which to detect hinge angle and screen rotation.
51 const float kDeviationFromGravityThreshold = 0.1f;
52
53 // The maximum deviation between the magnitude of the two accelerometers under
54 // which to detect hinge angle and screen rotation. These accelerometers are
55 // attached to the same physical device and so should be under the same
56 // acceleration.
57 const float kNoisyMagnitudeDeviation = 0.1f;
58
59 // The angle which the screen has to be rotated past before the display will
60 // rotate to match it (i.e. 45.0f is no stickiness).
61 const float kDisplayRotationStickyAngleDegrees = 60.0f;
62
63 // The minimum acceleration in a direction required to trigger screen rotation.
64 // This prevents rapid toggling of rotation when the device is near flat and
65 // there is very little screen aligned force on it. The value is effectively the
66 // sine of the rise angle required, with the current value requiring at least a
67 // 25 degree rise.
68 const float kMinimumAccelerationScreenRotation = 0.42f;
69
70 const float kRadiansToDegrees = 180.0f / 3.14159265f;
71
72 // Returns the angle between |base| and |other| in degrees.
73 float AngleBetweenVectorsInDegrees(const gfx::Vector3dF& base,
74                                  const gfx::Vector3dF& other) {
75   return acos(gfx::DotProduct(base, other) /
76               base.Length() / other.Length()) * kRadiansToDegrees;
77 }
78
79 // Returns the clockwise angle between |base| and |other| where |normal| is the
80 // normal of the virtual surface to measure clockwise according to.
81 float ClockwiseAngleBetweenVectorsInDegrees(const gfx::Vector3dF& base,
82                                             const gfx::Vector3dF& other,
83                                             const gfx::Vector3dF& normal) {
84   float angle = AngleBetweenVectorsInDegrees(base, other);
85   gfx::Vector3dF cross(base);
86   cross.Cross(other);
87   // If the dot product of this cross product is normal, it means that the
88   // shortest angle between |base| and |other| was counterclockwise with respect
89   // to the surface represented by |normal| and this angle must be reversed.
90   if (gfx::DotProduct(cross, normal) > 0.0f)
91     angle = 360.0f - angle;
92   return angle;
93 }
94
95 #if defined(OS_CHROMEOS)
96
97 // An event handler which listens for a volume down + power keypress and
98 // triggers a screenshot when this is seen.
99 class ScreenshotActionHandler : public ui::EventHandler {
100  public:
101   ScreenshotActionHandler();
102   virtual ~ScreenshotActionHandler();
103
104   // ui::EventHandler:
105   virtual void OnKeyEvent(ui::KeyEvent* event) OVERRIDE;
106
107  private:
108   bool volume_down_pressed_;
109
110   DISALLOW_COPY_AND_ASSIGN(ScreenshotActionHandler);
111 };
112
113 ScreenshotActionHandler::ScreenshotActionHandler()
114     : volume_down_pressed_(false) {
115   Shell::GetInstance()->PrependPreTargetHandler(this);
116 }
117
118 ScreenshotActionHandler::~ScreenshotActionHandler() {
119   Shell::GetInstance()->RemovePreTargetHandler(this);
120 }
121
122 void ScreenshotActionHandler::OnKeyEvent(ui::KeyEvent* event) {
123   if (event->key_code() == ui::VKEY_VOLUME_DOWN) {
124     volume_down_pressed_ = event->type() == ui::ET_KEY_PRESSED ||
125                            event->type() == ui::ET_TRANSLATED_KEY_PRESS;
126   } else if (volume_down_pressed_ &&
127              event->key_code() == ui::VKEY_POWER &&
128              event->type() == ui::ET_KEY_PRESSED) {
129     Shell::GetInstance()->accelerator_controller()->PerformAction(
130         ash::TAKE_SCREENSHOT, ui::Accelerator());
131   }
132 }
133
134 #endif  // OS_CHROMEOS
135
136 }  // namespace
137
138 MaximizeModeController::MaximizeModeController()
139     : rotation_locked_(false),
140       have_seen_accelerometer_data_(false),
141       in_set_screen_rotation_(false),
142       user_rotation_(gfx::Display::ROTATE_0),
143       last_touchview_transition_time_(base::Time::Now()) {
144   Shell::GetInstance()->accelerometer_controller()->AddObserver(this);
145   Shell::GetInstance()->AddShellObserver(this);
146 }
147
148 MaximizeModeController::~MaximizeModeController() {
149   Shell::GetInstance()->RemoveShellObserver(this);
150   Shell::GetInstance()->accelerometer_controller()->RemoveObserver(this);
151 }
152
153 void MaximizeModeController::SetRotationLocked(bool rotation_locked) {
154   if (rotation_locked_ == rotation_locked)
155     return;
156   rotation_locked_ = rotation_locked;
157   FOR_EACH_OBSERVER(Observer, observers_,
158                     OnRotationLockChanged(rotation_locked_));
159 }
160
161 void MaximizeModeController::AddObserver(Observer* observer) {
162   observers_.AddObserver(observer);
163 }
164
165 void MaximizeModeController::RemoveObserver(Observer* observer) {
166   observers_.RemoveObserver(observer);
167 }
168
169 bool MaximizeModeController::CanEnterMaximizeMode() {
170   // If we have ever seen accelerometer data, then HandleHingeRotation may
171   // trigger maximize mode at some point in the future.
172   // The --enable-touch-view-testing switch can also mean that we may enter
173   // maximize mode.
174   return have_seen_accelerometer_data_ ||
175          CommandLine::ForCurrentProcess()->HasSwitch(
176              switches::kAshEnableTouchViewTesting);
177 }
178
179 void MaximizeModeController::EnableMaximizeModeWindowManager(bool enable) {
180   if (enable && !maximize_mode_window_manager_.get()) {
181     maximize_mode_window_manager_.reset(new MaximizeModeWindowManager());
182     // TODO(jonross): Move the maximize mode notifications from ShellObserver
183     // to MaximizeModeController::Observer
184     Shell::GetInstance()->OnMaximizeModeStarted();
185   } else if (!enable && maximize_mode_window_manager_.get()) {
186     maximize_mode_window_manager_.reset();
187     Shell::GetInstance()->OnMaximizeModeEnded();
188   }
189 }
190
191 bool MaximizeModeController::IsMaximizeModeWindowManagerEnabled() const {
192   return maximize_mode_window_manager_.get() != NULL;
193 }
194
195 void MaximizeModeController::Shutdown() {
196   maximize_mode_window_manager_.reset();
197   Shell::GetInstance()->OnMaximizeModeEnded();
198 }
199
200 void MaximizeModeController::OnAccelerometerUpdated(
201     const gfx::Vector3dF& base,
202     const gfx::Vector3dF& lid) {
203   have_seen_accelerometer_data_ = true;
204
205   // Ignore the reading if it appears unstable. The reading is considered
206   // unstable if it deviates too much from gravity and/or the magnitude of the
207   // reading from the lid differs too much from the reading from the base.
208   float base_magnitude = base.Length();
209   float lid_magnitude = lid.Length();
210   if (std::abs(base_magnitude - lid_magnitude) > kNoisyMagnitudeDeviation ||
211       std::abs(base_magnitude - 1.0f) > kDeviationFromGravityThreshold ||
212       std::abs(lid_magnitude - 1.0f) > kDeviationFromGravityThreshold) {
213       return;
214   }
215
216   // Responding to the hinge rotation can change the maximize mode state which
217   // affects screen rotation, so we handle hinge rotation first.
218   HandleHingeRotation(base, lid);
219   HandleScreenRotation(lid);
220 }
221
222 void MaximizeModeController::OnDisplayConfigurationChanged() {
223   if (in_set_screen_rotation_)
224     return;
225   DisplayManager* display_manager = Shell::GetInstance()->display_manager();
226   gfx::Display::Rotation user_rotation = display_manager->
227       GetDisplayInfo(gfx::Display::InternalDisplayId()).rotation();
228   if (user_rotation != current_rotation_) {
229     // A user may change other display configuration settings. When the user
230     // does change the rotation setting, then lock rotation to prevent the
231     // accelerometer from erasing their change.
232     SetRotationLocked(true);
233     user_rotation_ = user_rotation;
234     current_rotation_ = user_rotation;
235   }
236 }
237
238 void MaximizeModeController::HandleHingeRotation(const gfx::Vector3dF& base,
239                                                  const gfx::Vector3dF& lid) {
240   static const gfx::Vector3dF hinge_vector(0.0f, 1.0f, 0.0f);
241   bool maximize_mode_engaged = IsMaximizeModeWindowManagerEnabled();
242   // Ignore the component of acceleration parallel to the hinge for the purposes
243   // of hinge angle calculation.
244   gfx::Vector3dF base_flattened(base);
245   gfx::Vector3dF lid_flattened(lid);
246   base_flattened.set_y(0.0f);
247   lid_flattened.set_y(0.0f);
248
249   // As the hinge approaches a vertical angle, the base and lid accelerometers
250   // approach the same values making any angle calculations highly inaccurate.
251   // Bail out early when it is too close.
252   if (base_flattened.Length() < kHingeAngleDetectionThreshold ||
253       lid_flattened.Length() < kHingeAngleDetectionThreshold) {
254     return;
255   }
256
257   // Compute the angle between the base and the lid.
258   float angle = ClockwiseAngleBetweenVectorsInDegrees(base_flattened,
259       lid_flattened, hinge_vector);
260
261   // Toggle maximize mode on or off when corresponding thresholds are passed.
262   // TODO(flackr): Make MaximizeModeController own the MaximizeModeWindowManager
263   // such that observations of state changes occur after the change and shell
264   // has fewer states to track.
265   if (maximize_mode_engaged &&
266       angle > kFullyOpenAngleErrorTolerance &&
267       angle < kExitMaximizeModeAngle) {
268     LeaveMaximizeMode();
269   } else if (!maximize_mode_engaged &&
270       angle > kEnterMaximizeModeAngle) {
271     EnterMaximizeMode();
272   }
273 }
274
275 void MaximizeModeController::HandleScreenRotation(const gfx::Vector3dF& lid) {
276   bool maximize_mode_engaged = IsMaximizeModeWindowManagerEnabled();
277
278   // TODO(jonross): track the updated rotation angle even when locked. So that
279   // when rotation lock is removed the accelerometer rotation can be applied
280   // without waiting for the next update.
281   if (!maximize_mode_engaged || rotation_locked_)
282     return;
283
284   DisplayManager* display_manager =
285       Shell::GetInstance()->display_manager();
286   gfx::Display::Rotation current_rotation = display_manager->GetDisplayInfo(
287       gfx::Display::InternalDisplayId()).rotation();
288
289   // After determining maximize mode state, determine if the screen should
290   // be rotated.
291   gfx::Vector3dF lid_flattened(lid.x(), lid.y(), 0.0f);
292   float lid_flattened_length = lid_flattened.Length();
293   // When the lid is close to being flat, don't change rotation as it is too
294   // sensitive to slight movements.
295   if (lid_flattened_length < kMinimumAccelerationScreenRotation)
296     return;
297
298   // The reference vector is the angle of gravity when the device is rotated
299   // clockwise by 45 degrees. Computing the angle between this vector and
300   // gravity we can easily determine the expected display rotation.
301   static gfx::Vector3dF rotation_reference(-1.0f, 1.0f, 0.0f);
302
303   // Set the down vector to match the expected direction of gravity given the
304   // last configured rotation. This is used to enforce a stickiness that the
305   // user must overcome to rotate the display and prevents frequent rotations
306   // when holding the device near 45 degrees.
307   gfx::Vector3dF down(0.0f, 0.0f, 0.0f);
308   if (current_rotation == gfx::Display::ROTATE_0)
309     down.set_x(-1.0f);
310   else if (current_rotation == gfx::Display::ROTATE_90)
311     down.set_y(1.0f);
312   else if (current_rotation == gfx::Display::ROTATE_180)
313     down.set_x(1.0f);
314   else
315     down.set_y(-1.0f);
316
317   // Don't rotate if the screen has not passed the threshold.
318   if (AngleBetweenVectorsInDegrees(down, lid_flattened) <
319       kDisplayRotationStickyAngleDegrees) {
320     return;
321   }
322
323   float angle = ClockwiseAngleBetweenVectorsInDegrees(rotation_reference,
324       lid_flattened, gfx::Vector3dF(0.0f, 0.0f, -1.0f));
325
326   gfx::Display::Rotation new_rotation = gfx::Display::ROTATE_90;
327   if (angle < 90.0f)
328     new_rotation = gfx::Display::ROTATE_0;
329   else if (angle < 180.0f)
330     new_rotation = gfx::Display::ROTATE_270;
331   else if (angle < 270.0f)
332     new_rotation = gfx::Display::ROTATE_180;
333
334   if (new_rotation != current_rotation)
335     SetDisplayRotation(display_manager, new_rotation);
336 }
337
338 void MaximizeModeController::SetDisplayRotation(
339     DisplayManager* display_manager,
340     gfx::Display::Rotation rotation) {
341   base::AutoReset<bool> auto_in_set_screen_rotation(
342       &in_set_screen_rotation_, true);
343   current_rotation_ = rotation;
344   display_manager->SetDisplayRotation(gfx::Display::InternalDisplayId(),
345                                       rotation);
346 }
347
348 void MaximizeModeController::EnterMaximizeMode() {
349   DisplayManager* display_manager = Shell::GetInstance()->display_manager();
350   current_rotation_ = user_rotation_ = display_manager->
351       GetDisplayInfo(gfx::Display::InternalDisplayId()).rotation();
352   EnableMaximizeModeWindowManager(true);
353   event_blocker_.reset(new MaximizeModeEventBlocker);
354 #if defined(OS_CHROMEOS)
355   event_handler_.reset(new ScreenshotActionHandler);
356 #endif
357   Shell::GetInstance()->display_controller()->AddObserver(this);
358 }
359
360 void MaximizeModeController::LeaveMaximizeMode() {
361   DisplayManager* display_manager = Shell::GetInstance()->display_manager();
362   gfx::Display::Rotation current_rotation = display_manager->
363       GetDisplayInfo(gfx::Display::InternalDisplayId()).rotation();
364   if (current_rotation != user_rotation_)
365     SetDisplayRotation(display_manager, user_rotation_);
366   rotation_locked_ = false;
367   EnableMaximizeModeWindowManager(false);
368   event_blocker_.reset();
369   event_handler_.reset();
370 }
371
372 void MaximizeModeController::OnSuspend() {
373   RecordTouchViewStateTransition();
374 }
375
376 void MaximizeModeController::OnResume() {
377   last_touchview_transition_time_ = base::Time::Now();
378 }
379
380 // Called after maximize mode has started, windows might still animate though.
381 void MaximizeModeController::OnMaximizeModeStarted() {
382   RecordTouchViewStateTransition();
383 }
384
385 // Called after maximize mode has ended, windows might still be returning to
386 // their original position.
387 void MaximizeModeController::OnMaximizeModeEnded() {
388   RecordTouchViewStateTransition();
389 }
390
391 void MaximizeModeController::RecordTouchViewStateTransition() {
392   if (CanEnterMaximizeMode()) {
393     base::Time current_time = base::Time::Now();
394     base::TimeDelta delta = current_time - last_touchview_transition_time_;
395     if (IsMaximizeModeWindowManagerEnabled()) {
396       UMA_HISTOGRAM_LONG_TIMES("Ash.TouchView.TouchViewInactive", delta);
397       total_non_touchview_time_ += delta;
398     } else {
399       UMA_HISTOGRAM_LONG_TIMES("Ash.TouchView.TouchViewActive", delta);
400       total_touchview_time_ += delta;
401     }
402     last_touchview_transition_time_ = current_time;
403   }
404 }
405
406 void MaximizeModeController::OnAppTerminating() {
407   if (CanEnterMaximizeMode()) {
408     RecordTouchViewStateTransition();
409     UMA_HISTOGRAM_CUSTOM_COUNTS("Ash.TouchView.TouchViewActiveTotal",
410         total_touchview_time_.InMinutes(),
411         1, base::TimeDelta::FromDays(7).InMinutes(), 50);
412     UMA_HISTOGRAM_CUSTOM_COUNTS("Ash.TouchView.TouchViewInactiveTotal",
413         total_non_touchview_time_.InMinutes(),
414         1, base::TimeDelta::FromDays(7).InMinutes(), 50);
415     base::TimeDelta total_runtime = total_touchview_time_ +
416         total_non_touchview_time_;
417     if (total_runtime.InSeconds() > 0) {
418       UMA_HISTOGRAM_PERCENTAGE("Ash.TouchView.TouchViewActivePercentage",
419           100 * total_touchview_time_.InSeconds() / total_runtime.InSeconds());
420     }
421   }
422   Shell::GetInstance()->display_controller()->RemoveObserver(this);
423 }
424
425 }  // namespace ash