accelerator_controller.cc revision 7d4cd473f85ac64c3747c96c277f9e506a0d2246
1// Copyright (c) 2012 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/accelerators/accelerator_controller.h"
6
7#include <algorithm>
8#include <cmath>
9#include <iostream>
10#include <string>
11
12#include "ash/accelerators/accelerator_table.h"
13#include "ash/ash_switches.h"
14#include "ash/caps_lock_delegate.h"
15#include "ash/debug.h"
16#include "ash/desktop_background/desktop_background_controller.h"
17#include "ash/desktop_background/user_wallpaper_delegate.h"
18#include "ash/display/display_controller.h"
19#include "ash/display/display_manager.h"
20#include "ash/focus_cycler.h"
21#include "ash/ime_control_delegate.h"
22#include "ash/launcher/launcher.h"
23#include "ash/launcher/launcher_delegate.h"
24#include "ash/launcher/launcher_model.h"
25#include "ash/magnifier/magnification_controller.h"
26#include "ash/magnifier/partial_magnification_controller.h"
27#include "ash/root_window_controller.h"
28#include "ash/rotator/screen_rotation.h"
29#include "ash/screenshot_delegate.h"
30#include "ash/session_state_delegate.h"
31#include "ash/shelf/shelf_widget.h"
32#include "ash/shell.h"
33#include "ash/shell_delegate.h"
34#include "ash/shell_window_ids.h"
35#include "ash/system/brightness/brightness_control_delegate.h"
36#include "ash/system/keyboard_brightness/keyboard_brightness_control_delegate.h"
37#include "ash/system/status_area_widget.h"
38#include "ash/system/tray/system_tray.h"
39#include "ash/system/tray/system_tray_delegate.h"
40#include "ash/system/tray/system_tray_notifier.h"
41#include "ash/system/web_notification/web_notification_tray.h"
42#include "ash/touch/touch_observer_hud.h"
43#include "ash/volume_control_delegate.h"
44#include "ash/wm/partial_screenshot_view.h"
45#include "ash/wm/power_button_controller.h"
46#include "ash/wm/property_util.h"
47#include "ash/wm/window_cycle_controller.h"
48#include "ash/wm/window_util.h"
49#include "ash/wm/workspace/snap_sizer.h"
50#include "base/bind.h"
51#include "base/command_line.h"
52#include "content/public/browser/gpu_data_manager.h"
53#include "ui/aura/env.h"
54#include "ui/aura/root_window.h"
55#include "ui/base/accelerators/accelerator.h"
56#include "ui/base/accelerators/accelerator_manager.h"
57#include "ui/base/events/event.h"
58#include "ui/base/keycodes/keyboard_codes.h"
59#include "ui/compositor/debug_utils.h"
60#include "ui/compositor/layer.h"
61#include "ui/compositor/layer_animation_sequence.h"
62#include "ui/compositor/layer_animator.h"
63#include "ui/gfx/screen.h"
64#include "ui/oak/oak.h"
65#include "ui/views/controls/webview/webview.h"
66#include "ui/views/debug_utils.h"
67#include "ui/views/widget/widget.h"
68
69#if defined(OS_CHROMEOS)
70#include "ash/system/chromeos/keyboard_brightness_controller.h"
71#include "base/chromeos/chromeos_version.h"
72#endif  // defined(OS_CHROMEOS)
73
74namespace ash {
75namespace {
76
77using internal::DisplayInfo;
78
79bool DebugShortcutsEnabled() {
80#if defined(NDEBUG)
81  return CommandLine::ForCurrentProcess()->HasSwitch(
82          switches::kAshDebugShortcuts);
83#else
84  return true;
85#endif
86}
87
88bool HandleCycleWindowMRU(WindowCycleController::Direction direction,
89                          bool is_alt_down) {
90  Shell::GetInstance()->
91      window_cycle_controller()->HandleCycleWindow(direction, is_alt_down);
92  // Always report we handled the key, even if the window didn't change.
93  return true;
94}
95
96void HandleCycleWindowLinear(CycleDirection direction) {
97  Shell::GetInstance()->
98        window_cycle_controller()->HandleLinearCycleWindow();
99}
100
101bool HandleAccessibleFocusCycle(bool reverse) {
102  if (!Shell::GetInstance()->delegate()->IsSpokenFeedbackEnabled())
103    return false;
104  aura::Window* active_window = ash::wm::GetActiveWindow();
105  if (!active_window)
106    return false;
107  views::Widget* widget =
108      views::Widget::GetWidgetForNativeWindow(active_window);
109  if (!widget)
110    return false;
111  views::FocusManager* focus_manager = widget->GetFocusManager();
112  if (!focus_manager)
113    return false;
114  views::View* view = focus_manager->GetFocusedView();
115  if (!view)
116    return false;
117  if (!strcmp(view->GetClassName(), views::WebView::kViewClassName))
118    return false;
119
120  focus_manager->AdvanceFocus(reverse);
121  return true;
122}
123
124void HandleSilenceSpokenFeedback() {
125  if (!Shell::GetInstance()->delegate()->IsSpokenFeedbackEnabled())
126    return;
127
128  Shell::GetInstance()->delegate()->SilenceSpokenFeedback();
129}
130
131#if defined(OS_CHROMEOS)
132bool HandleLock() {
133  Shell::GetInstance()->session_state_delegate()->LockScreen();
134  return true;
135}
136
137bool HandleFileManager(bool as_dialog) {
138  Shell::GetInstance()->delegate()->OpenFileManager(as_dialog);
139  return true;
140}
141
142bool HandleCrosh() {
143  Shell::GetInstance()->delegate()->OpenCrosh();
144  return true;
145}
146
147bool HandleToggleSpokenFeedback() {
148  Shell::GetInstance()->delegate()->
149      ToggleSpokenFeedback(A11Y_NOTIFICATION_SHOW);
150  return true;
151}
152
153#endif  // defined(OS_CHROMEOS)
154
155bool HandleRotatePaneFocus(Shell::Direction direction) {
156  Shell* shell = Shell::GetInstance();
157  switch (direction) {
158    case Shell::FORWARD:
159      shell->focus_cycler()->RotateFocus(internal::FocusCycler::FORWARD);
160      break;
161    case Shell::BACKWARD:
162      shell->focus_cycler()->RotateFocus(internal::FocusCycler::BACKWARD);
163      break;
164  }
165  return true;
166}
167
168// Rotate the active window.
169bool HandleRotateActiveWindow() {
170  aura::Window* active_window = wm::GetActiveWindow();
171  if (active_window) {
172    // The rotation animation bases its target transform on the current
173    // rotation and position. Since there could be an animation in progress
174    // right now, queue this animation so when it starts it picks up a neutral
175    // rotation and position. Use replace so we only enqueue one at a time.
176    active_window->layer()->GetAnimator()->
177        set_preemption_strategy(ui::LayerAnimator::REPLACE_QUEUED_ANIMATIONS);
178    active_window->layer()->GetAnimator()->StartAnimation(
179        new ui::LayerAnimationSequence(
180            new ash::ScreenRotation(360, active_window->layer())));
181  }
182  return true;
183}
184
185gfx::Display::Rotation GetNextRotation(gfx::Display::Rotation current) {
186  switch (current) {
187    case gfx::Display::ROTATE_0:
188      return gfx::Display::ROTATE_90;
189    case gfx::Display::ROTATE_90:
190      return gfx::Display::ROTATE_180;
191    case gfx::Display::ROTATE_180:
192      return gfx::Display::ROTATE_270;
193    case gfx::Display::ROTATE_270:
194      return gfx::Display::ROTATE_0;
195  }
196  NOTREACHED() << "Unknown rotation:" << current;
197  return gfx::Display::ROTATE_0;
198}
199
200bool HandleScaleUI(bool up) {
201  internal::DisplayManager* display_manager =
202      Shell::GetInstance()->display_manager();
203  int64 display_id = display_manager->GetDisplayIdForUIScaling();
204  if (display_id == gfx::Display::kInvalidDisplayID)
205    return false;
206  const DisplayInfo& display_info = display_manager->GetDisplayInfo(display_id);
207  float next_scale =
208      internal::DisplayManager::GetNextUIScale(display_info, up);
209  display_manager->SetDisplayUIScale(display_id, next_scale);
210  return true;
211}
212
213bool HandleScaleReset() {
214  internal::DisplayManager* display_manager =
215      Shell::GetInstance()->display_manager();
216  int64 display_id = display_manager->GetDisplayIdForUIScaling();
217  if (display_id == gfx::Display::kInvalidDisplayID)
218    return false;
219  display_manager->SetDisplayUIScale(display_id, 1.0f);
220  return true;
221}
222
223// Rotates the screen.
224bool HandleRotateScreen() {
225  gfx::Point point = Shell::GetScreen()->GetCursorScreenPoint();
226  gfx::Display display = Shell::GetScreen()->GetDisplayNearestPoint(point);
227  const DisplayInfo& display_info =
228      Shell::GetInstance()->display_manager()->GetDisplayInfo(display.id());
229  Shell::GetInstance()->display_manager()->SetDisplayRotation(
230      display.id(), GetNextRotation(display_info.rotation()));
231  return true;
232}
233
234bool HandleToggleDesktopBackgroundMode() {
235  DesktopBackgroundController* desktop_background_controller =
236      Shell::GetInstance()->desktop_background_controller();
237  if (desktop_background_controller->desktop_background_mode() ==
238      DesktopBackgroundController::BACKGROUND_IMAGE) {
239    desktop_background_controller->SetDesktopBackgroundSolidColorMode(
240        SK_ColorBLACK);
241  } else {
242    ash::Shell::GetInstance()->user_wallpaper_delegate()->
243        InitializeWallpaper();
244  }
245  return true;
246}
247
248bool HandleToggleRootWindowFullScreen() {
249  Shell::GetPrimaryRootWindow()->ToggleFullScreen();
250  return true;
251}
252
253// Magnify the screen
254bool HandleMagnifyScreen(int delta_index) {
255  if (ash::Shell::GetInstance()->magnification_controller()->IsEnabled()) {
256    // TODO(yoshiki): Move the following logic to MagnificationController.
257    float scale =
258        ash::Shell::GetInstance()->magnification_controller()->GetScale();
259    // Calculate rounded logarithm (base kMagnificationScaleFactor) of scale.
260    int scale_index =
261        std::floor(std::log(scale) / std::log(kMagnificationScaleFactor) + 0.5);
262
263    int new_scale_index = std::max(0, std::min(8, scale_index + delta_index));
264
265    ash::Shell::GetInstance()->magnification_controller()->
266        SetScale(std::pow(kMagnificationScaleFactor, new_scale_index), true);
267  } else if (ash::Shell::GetInstance()->
268             partial_magnification_controller()->is_enabled()) {
269    float scale = delta_index > 0 ? kDefaultPartialMagnifiedScale : 1;
270    ash::Shell::GetInstance()->partial_magnification_controller()->
271        SetScale(scale);
272  }
273
274  return true;
275}
276
277bool HandleMediaNextTrack() {
278  Shell::GetInstance()->delegate()->HandleMediaNextTrack();
279  return true;
280}
281
282bool HandleMediaPlayPause() {
283  Shell::GetInstance()->delegate()->HandleMediaPlayPause();
284  return true;
285}
286
287bool HandleMediaPrevTrack() {
288  Shell::GetInstance()->delegate()->HandleMediaPrevTrack();
289  return true;
290}
291
292bool HandlePrintLayerHierarchy() {
293  Shell::RootWindowList root_windows = Shell::GetAllRootWindows();
294  for (size_t i = 0; i < root_windows.size(); ++i) {
295    ui::PrintLayerHierarchy(root_windows[i]->layer(),
296                            root_windows[i]->GetLastMouseLocationInRoot());
297  }
298  return true;
299}
300
301bool HandlePrintViewHierarchy() {
302  aura::Window* active_window = ash::wm::GetActiveWindow();
303  if (!active_window)
304    return true;
305  views::Widget* browser_widget =
306      views::Widget::GetWidgetForNativeWindow(active_window);
307  if (!browser_widget)
308    return true;
309  views::PrintViewHierarchy(browser_widget->GetRootView());
310  return true;
311}
312
313void PrintWindowHierarchy(aura::Window* window,
314                          int indent,
315                          std::ostringstream* out) {
316  std::string indent_str(indent, ' ');
317  std::string name(window->name());
318  if (name.empty())
319    name = "\"\"";
320  *out << indent_str << name << " (" << window << ")"
321       << " type=" << window->type()
322       << (wm::IsActiveWindow(window) ? " [active] " : " ")
323       << (window->IsVisible() ? " visible " : " ")
324       << window->bounds().ToString()
325       << '\n';
326
327  for (size_t i = 0; i < window->children().size(); ++i)
328    PrintWindowHierarchy(window->children()[i], indent + 3, out);
329}
330
331bool HandlePrintWindowHierarchy() {
332  Shell::RootWindowControllerList controllers =
333      Shell::GetAllRootWindowControllers();
334  for (size_t i = 0; i < controllers.size(); ++i) {
335    std::ostringstream out;
336    out << "RootWindow " << i << ":\n";
337    PrintWindowHierarchy(controllers[i]->root_window(), 0, &out);
338    // Error so logs can be collected from end-users.
339    LOG(ERROR) << out.str();
340  }
341  return true;
342}
343
344bool HandlePrintUIHierarchies() {
345  // This is a separate command so the user only has to hit one key to generate
346  // all the logs. Developers use the individual dumps repeatedly, so keep
347  // those as separate commands to avoid spamming their logs.
348  HandlePrintLayerHierarchy();
349  HandlePrintWindowHierarchy();
350  HandlePrintViewHierarchy();
351  return true;
352}
353
354}  // namespace
355
356////////////////////////////////////////////////////////////////////////////////
357// AcceleratorControllerContext, public:
358
359AcceleratorControllerContext::AcceleratorControllerContext() {
360  current_accelerator_.set_type(ui::ET_UNKNOWN);
361  previous_accelerator_.set_type(ui::ET_UNKNOWN);
362}
363
364void AcceleratorControllerContext::UpdateContext(
365    const ui::Accelerator& accelerator) {
366  previous_accelerator_ = current_accelerator_;
367  current_accelerator_ = accelerator;
368}
369
370////////////////////////////////////////////////////////////////////////////////
371// AcceleratorController, public:
372
373AcceleratorController::AcceleratorController()
374    : accelerator_manager_(new ui::AcceleratorManager) {
375  Init();
376}
377
378AcceleratorController::~AcceleratorController() {
379}
380
381void AcceleratorController::Init() {
382  for (size_t i = 0; i < kActionsAllowedAtLoginOrLockScreenLength; ++i) {
383    actions_allowed_at_login_screen_.insert(
384        kActionsAllowedAtLoginOrLockScreen[i]);
385    actions_allowed_at_lock_screen_.insert(
386        kActionsAllowedAtLoginOrLockScreen[i]);
387  }
388  for (size_t i = 0; i < kActionsAllowedAtLockScreenLength; ++i)
389    actions_allowed_at_lock_screen_.insert(kActionsAllowedAtLockScreen[i]);
390  for (size_t i = 0; i < kActionsAllowedAtModalWindowLength; ++i)
391    actions_allowed_at_modal_window_.insert(kActionsAllowedAtModalWindow[i]);
392  for (size_t i = 0; i < kReservedActionsLength; ++i)
393    reserved_actions_.insert(kReservedActions[i]);
394  for (size_t i = 0; i < kNonrepeatableActionsLength; ++i)
395    nonrepeatable_actions_.insert(kNonrepeatableActions[i]);
396  for (size_t i = 0; i < kActionsAllowedInAppModeLength; ++i)
397    actions_allowed_in_app_mode_.insert(kActionsAllowedInAppMode[i]);
398
399  RegisterAccelerators(kAcceleratorData, kAcceleratorDataLength);
400
401#if !defined(NDEBUG)
402  RegisterAccelerators(kDesktopAcceleratorData, kDesktopAcceleratorDataLength);
403#endif
404
405  if (DebugShortcutsEnabled()) {
406    RegisterAccelerators(kDebugAcceleratorData, kDebugAcceleratorDataLength);
407    for (size_t i = 0; i < kReservedDebugActionsLength; ++i)
408      reserved_actions_.insert(kReservedDebugActions[i]);
409  }
410
411#if defined(OS_CHROMEOS)
412  keyboard_brightness_control_delegate_.reset(
413      new KeyboardBrightnessController());
414#endif
415}
416
417void AcceleratorController::Register(const ui::Accelerator& accelerator,
418                                     ui::AcceleratorTarget* target) {
419  accelerator_manager_->Register(accelerator,
420                                 ui::AcceleratorManager::kNormalPriority,
421                                 target);
422}
423
424void AcceleratorController::Unregister(const ui::Accelerator& accelerator,
425                                       ui::AcceleratorTarget* target) {
426  accelerator_manager_->Unregister(accelerator, target);
427}
428
429void AcceleratorController::UnregisterAll(ui::AcceleratorTarget* target) {
430  accelerator_manager_->UnregisterAll(target);
431}
432
433bool AcceleratorController::Process(const ui::Accelerator& accelerator) {
434  if (ime_control_delegate_) {
435    return accelerator_manager_->Process(
436        ime_control_delegate_->RemapAccelerator(accelerator));
437  }
438  return accelerator_manager_->Process(accelerator);
439}
440
441bool AcceleratorController::IsRegistered(
442    const ui::Accelerator& accelerator) const {
443  return accelerator_manager_->GetCurrentTarget(accelerator) != NULL;
444}
445
446bool AcceleratorController::IsReservedAccelerator(
447    const ui::Accelerator& accelerator) const {
448  const ui::Accelerator remapped_accelerator = ime_control_delegate_.get() ?
449      ime_control_delegate_->RemapAccelerator(accelerator) : accelerator;
450
451  std::map<ui::Accelerator, int>::const_iterator iter =
452      accelerators_.find(remapped_accelerator);
453  if (iter == accelerators_.end())
454    return false;  // not an accelerator.
455
456  return reserved_actions_.find(iter->second) != reserved_actions_.end();
457}
458
459bool AcceleratorController::PerformAction(int action,
460                                          const ui::Accelerator& accelerator) {
461  ash::Shell* shell = ash::Shell::GetInstance();
462  if (!shell->session_state_delegate()->IsActiveUserSessionStarted() &&
463      actions_allowed_at_login_screen_.find(action) ==
464      actions_allowed_at_login_screen_.end()) {
465    return false;
466  }
467  if (shell->session_state_delegate()->IsScreenLocked() &&
468      actions_allowed_at_lock_screen_.find(action) ==
469      actions_allowed_at_lock_screen_.end()) {
470    return false;
471  }
472  if (shell->IsSystemModalWindowOpen() &&
473      actions_allowed_at_modal_window_.find(action) ==
474      actions_allowed_at_modal_window_.end()) {
475    // Note: we return true. This indicates the shortcut is handled
476    // and will not be passed to the modal window. This is important
477    // for things like Alt+Tab that would cause an undesired effect
478    // in the modal window by cycling through its window elements.
479    return true;
480  }
481  if (shell->delegate()->IsRunningInForcedAppMode() &&
482      actions_allowed_in_app_mode_.find(action) ==
483      actions_allowed_in_app_mode_.end()) {
484    return false;
485  }
486
487  const ui::KeyboardCode key_code = accelerator.key_code();
488  // PerformAction() is performed from gesture controllers and passes
489  // empty Accelerator() instance as the second argument. Such events
490  // should never be suspended.
491  const bool gesture_event = key_code == ui::VKEY_UNKNOWN;
492
493  // Ignore accelerators invoked as repeated (while holding a key for a long
494  // time, if their handling is nonrepeatable.
495  if (nonrepeatable_actions_.find(action) != nonrepeatable_actions_.end() &&
496      context_.repeated() && !gesture_event) {
497    return true;
498  }
499  // Type of the previous accelerator. Used by NEXT_IME and DISABLE_CAPS_LOCK.
500  const ui::EventType previous_event_type =
501    context_.previous_accelerator().type();
502  const ui::KeyboardCode previous_key_code =
503    context_.previous_accelerator().key_code();
504
505  // You *MUST* return true when some action is performed. Otherwise, this
506  // function might be called *twice*, via BrowserView::PreHandleKeyboardEvent
507  // and BrowserView::HandleKeyboardEvent, for a single accelerator press.
508  switch (action) {
509    case ACCESSIBLE_FOCUS_NEXT:
510      return HandleAccessibleFocusCycle(false);
511    case ACCESSIBLE_FOCUS_PREVIOUS:
512      return HandleAccessibleFocusCycle(true);
513    case CYCLE_BACKWARD_MRU:
514      if (key_code == ui::VKEY_TAB)
515        shell->delegate()->RecordUserMetricsAction(UMA_ACCEL_PREVWINDOW_TAB);
516      return HandleCycleWindowMRU(WindowCycleController::BACKWARD,
517                                  accelerator.IsAltDown());
518    case CYCLE_FORWARD_MRU:
519      if (key_code == ui::VKEY_TAB)
520        shell->delegate()->RecordUserMetricsAction(UMA_ACCEL_NEXTWINDOW_TAB);
521      return HandleCycleWindowMRU(WindowCycleController::FORWARD,
522                                  accelerator.IsAltDown());
523    case CYCLE_BACKWARD_LINEAR:
524      if (key_code == ui::VKEY_MEDIA_LAUNCH_APP1)
525        shell->delegate()->RecordUserMetricsAction(UMA_ACCEL_PREVWINDOW_F5);
526      HandleCycleWindowLinear(CYCLE_BACKWARD);
527      return true;
528    case CYCLE_FORWARD_LINEAR:
529      if (key_code == ui::VKEY_MEDIA_LAUNCH_APP1)
530        shell->delegate()->RecordUserMetricsAction(UMA_ACCEL_NEXTWINDOW_F5);
531      HandleCycleWindowLinear(CYCLE_FORWARD);
532      return true;
533#if defined(OS_CHROMEOS)
534    case ADD_REMOVE_DISPLAY:
535      Shell::GetInstance()->display_manager()->AddRemoveDisplay();
536      return true;
537    case TOGGLE_MIRROR_MODE:
538      Shell::GetInstance()->display_controller()->ToggleMirrorMode();
539      return true;
540    case LOCK_SCREEN:
541      if (key_code == ui::VKEY_L)
542        shell->delegate()->RecordUserMetricsAction(UMA_ACCEL_LOCK_SCREEN_L);
543      return HandleLock();
544    case OPEN_FILE_DIALOG:
545      return HandleFileManager(true /* as_dialog */);
546    case OPEN_FILE_MANAGER:
547      return HandleFileManager(false /* as_dialog */);
548    case OPEN_CROSH:
549      return HandleCrosh();
550    case SILENCE_SPOKEN_FEEDBACK:
551      HandleSilenceSpokenFeedback();
552      break;
553    case SWAP_PRIMARY_DISPLAY:
554      Shell::GetInstance()->display_controller()->SwapPrimaryDisplay();
555      return true;
556    case TOGGLE_SPOKEN_FEEDBACK:
557      return HandleToggleSpokenFeedback();
558    case TOGGLE_WIFI:
559      Shell::GetInstance()->system_tray_notifier()->NotifyRequestToggleWifi();
560      return true;
561    case TOUCH_HUD_CLEAR: {
562      internal::RootWindowController* controller =
563          internal::RootWindowController::ForActiveRootWindow();
564      if (controller->touch_observer_hud()) {
565        controller->touch_observer_hud()->Clear();
566        return true;
567      }
568      return false;
569    }
570    case TOUCH_HUD_MODE_CHANGE: {
571      internal::RootWindowController* controller =
572          internal::RootWindowController::ForActiveRootWindow();
573      if (controller->touch_observer_hud()) {
574        controller->touch_observer_hud()->ChangeToNextMode();
575        return true;
576      }
577      return false;
578    }
579    case DISABLE_GPU_WATCHDOG:
580      content::GpuDataManager::GetInstance()->DisableGpuWatchdog();
581      return true;
582#endif
583    case OPEN_FEEDBACK_PAGE:
584      ash::Shell::GetInstance()->delegate()->OpenFeedbackPage();
585      return true;
586    case EXIT:
587      // UMA metrics are recorded in the handler.
588      exit_warning_handler_.HandleAccelerator();
589      return true;
590    case NEW_INCOGNITO_WINDOW:
591      Shell::GetInstance()->delegate()->NewWindow(true /* is_incognito */);
592      return true;
593    case NEW_TAB:
594      if (key_code == ui::VKEY_T)
595        shell->delegate()->RecordUserMetricsAction(UMA_ACCEL_NEWTAB_T);
596      Shell::GetInstance()->delegate()->NewTab();
597      return true;
598    case NEW_WINDOW:
599      Shell::GetInstance()->delegate()->NewWindow(false /* is_incognito */);
600      return true;
601    case RESTORE_TAB:
602      Shell::GetInstance()->delegate()->RestoreTab();
603      return true;
604    case TAKE_SCREENSHOT:
605      if (screenshot_delegate_.get() &&
606          screenshot_delegate_->CanTakeScreenshot()) {
607        screenshot_delegate_->HandleTakeScreenshotForAllRootWindows();
608      }
609      // Return true to prevent propagation of the key event.
610      return true;
611    case TAKE_PARTIAL_SCREENSHOT:
612      if (screenshot_delegate_) {
613        ash::PartialScreenshotView::StartPartialScreenshot(
614            screenshot_delegate_.get());
615      }
616      // Return true to prevent propagation of the key event because
617      // this key combination is reserved for partial screenshot.
618      return true;
619    case TOGGLE_APP_LIST:
620      // If something else was pressed between the Search key (LWIN)
621      // being pressed and released, then ignore the release of the
622      // Search key.
623      if (key_code == ui::VKEY_LWIN &&
624          (previous_event_type == ui::ET_KEY_RELEASED ||
625           previous_key_code != ui::VKEY_LWIN))
626        return false;
627      if (key_code == ui::VKEY_LWIN)
628        shell->delegate()->RecordUserMetricsAction(UMA_ACCEL_SEARCH_LWIN);
629      // When spoken feedback is enabled, we should neither toggle the list nor
630      // consume the key since Search+Shift is one of the shortcuts the a11y
631      // feature uses. crbug.com/132296
632      DCHECK_EQ(ui::VKEY_LWIN, accelerator.key_code());
633      if (Shell::GetInstance()->delegate()->IsSpokenFeedbackEnabled())
634        return false;
635      ash::Shell::GetInstance()->ToggleAppList(NULL);
636      return true;
637    case DISABLE_CAPS_LOCK:
638      if (previous_event_type == ui::ET_KEY_RELEASED ||
639          (previous_key_code != ui::VKEY_LSHIFT &&
640           previous_key_code != ui::VKEY_SHIFT &&
641           previous_key_code != ui::VKEY_RSHIFT)) {
642        // If something else was pressed between the Shift key being pressed
643        // and released, then ignore the release of the Shift key.
644        return false;
645      }
646      if (shell->caps_lock_delegate()->IsCapsLockEnabled()) {
647        shell->caps_lock_delegate()->SetCapsLockEnabled(false);
648        return true;
649      }
650      return false;
651    case TOGGLE_CAPS_LOCK:
652      if (key_code == ui::VKEY_LWIN) {
653        // If something else was pressed between the Search key (LWIN)
654        // being pressed and released, then ignore the release of the
655        // Search key.
656        // TODO(danakj): Releasing Alt first breaks this: crbug.com/166495
657        if (previous_event_type == ui::ET_KEY_RELEASED ||
658            previous_key_code != ui::VKEY_LWIN)
659          return false;
660      }
661      shell->caps_lock_delegate()->ToggleCapsLock();
662      return true;
663    case BRIGHTNESS_DOWN:
664      if (brightness_control_delegate_)
665        return brightness_control_delegate_->HandleBrightnessDown(accelerator);
666      break;
667    case BRIGHTNESS_UP:
668      if (brightness_control_delegate_)
669        return brightness_control_delegate_->HandleBrightnessUp(accelerator);
670      break;
671    case KEYBOARD_BRIGHTNESS_DOWN:
672      if (keyboard_brightness_control_delegate_)
673        return keyboard_brightness_control_delegate_->
674            HandleKeyboardBrightnessDown(accelerator);
675      break;
676    case KEYBOARD_BRIGHTNESS_UP:
677      if (keyboard_brightness_control_delegate_)
678        return keyboard_brightness_control_delegate_->
679            HandleKeyboardBrightnessUp(accelerator);
680      break;
681    case VOLUME_MUTE:
682      return shell->system_tray_delegate()->GetVolumeControlDelegate()->
683          HandleVolumeMute(accelerator);
684      break;
685    case VOLUME_DOWN:
686      return shell->system_tray_delegate()->GetVolumeControlDelegate()->
687          HandleVolumeDown(accelerator);
688      break;
689    case VOLUME_UP:
690      return shell->system_tray_delegate()->GetVolumeControlDelegate()->
691          HandleVolumeUp(accelerator);
692      break;
693    case FOCUS_LAUNCHER:
694      return shell->focus_cycler()->FocusWidget(
695          Launcher::ForPrimaryDisplay()->shelf_widget());
696      break;
697    case FOCUS_NEXT_PANE:
698      return HandleRotatePaneFocus(Shell::FORWARD);
699    case FOCUS_PREVIOUS_PANE:
700      return HandleRotatePaneFocus(Shell::BACKWARD);
701    case SHOW_KEYBOARD_OVERLAY:
702      ash::Shell::GetInstance()->delegate()->ShowKeyboardOverlay();
703      return true;
704    case SHOW_OAK:
705      if (CommandLine::ForCurrentProcess()->HasSwitch(
706              switches::kAshEnableOak)) {
707        oak::ShowOakWindowWithContext(Shell::GetPrimaryRootWindow());
708        return true;
709      }
710      break;
711    case SHOW_SYSTEM_TRAY_BUBBLE: {
712      internal::RootWindowController* controller =
713          internal::RootWindowController::ForActiveRootWindow();
714      if (!controller->GetSystemTray()->HasSystemBubble())
715        controller->GetSystemTray()->ShowDefaultView(BUBBLE_CREATE_NEW);
716      break;
717    }
718    case SHOW_MESSAGE_CENTER_BUBBLE: {
719      internal::RootWindowController* controller =
720          internal::RootWindowController::ForActiveRootWindow();
721      internal::StatusAreaWidget* status_area_widget =
722          controller->shelf()->status_area_widget();
723      if (status_area_widget) {
724        WebNotificationTray* notification_tray =
725            status_area_widget->web_notification_tray();
726        if (notification_tray->visible())
727          notification_tray->ShowMessageCenterBubble();
728      }
729      break;
730    }
731    case SHOW_TASK_MANAGER:
732      Shell::GetInstance()->delegate()->ShowTaskManager();
733      return true;
734    case NEXT_IME:
735      // This check is necessary e.g. not to process the Shift+Alt+
736      // ET_KEY_RELEASED accelerator for Chrome OS (see ash/accelerators/
737      // accelerator_controller.cc) when Shift+Alt+Tab is pressed and then Tab
738      // is released.
739      if (previous_event_type == ui::ET_KEY_RELEASED &&
740          // Workaround for crbug.com/139556. CJK IME users tend to press
741          // Enter (or Space) and Shift+Alt almost at the same time to commit
742          // an IME string and then switch from the IME to the English layout.
743          // This workaround allows the user to trigger NEXT_IME even if the
744          // user presses Shift+Alt before releasing Enter.
745          // TODO(nona|mazda): Fix crbug.com/139556 in a cleaner way.
746          previous_key_code != ui::VKEY_RETURN &&
747          previous_key_code != ui::VKEY_SPACE) {
748        // We totally ignore this accelerator.
749        // TODO(mazda): Fix crbug.com/158217
750        return false;
751      }
752      if (ime_control_delegate_)
753        return ime_control_delegate_->HandleNextIme();
754      break;
755    case PREVIOUS_IME:
756      if (ime_control_delegate_)
757        return ime_control_delegate_->HandlePreviousIme();
758      break;
759    case PRINT_UI_HIERARCHIES:
760      return HandlePrintUIHierarchies();
761    case SWITCH_IME:
762      if (ime_control_delegate_)
763        return ime_control_delegate_->HandleSwitchIme(accelerator);
764      break;
765    case SELECT_WIN_0:
766      Launcher::ForPrimaryDisplay()->SwitchToWindow(0);
767      return true;
768    case SELECT_WIN_1:
769      Launcher::ForPrimaryDisplay()->SwitchToWindow(1);
770      return true;
771    case SELECT_WIN_2:
772      Launcher::ForPrimaryDisplay()->SwitchToWindow(2);
773      return true;
774    case SELECT_WIN_3:
775      Launcher::ForPrimaryDisplay()->SwitchToWindow(3);
776      return true;
777    case SELECT_WIN_4:
778      Launcher::ForPrimaryDisplay()->SwitchToWindow(4);
779      return true;
780    case SELECT_WIN_5:
781      Launcher::ForPrimaryDisplay()->SwitchToWindow(5);
782      return true;
783    case SELECT_WIN_6:
784      Launcher::ForPrimaryDisplay()->SwitchToWindow(6);
785      return true;
786    case SELECT_WIN_7:
787      Launcher::ForPrimaryDisplay()->SwitchToWindow(7);
788      return true;
789    case SELECT_LAST_WIN:
790      Launcher::ForPrimaryDisplay()->SwitchToWindow(-1);
791      return true;
792    case WINDOW_SNAP_LEFT:
793    case WINDOW_SNAP_RIGHT: {
794      aura::Window* window = wm::GetActiveWindow();
795      // Disable window docking shortcut key for full screen window due to
796      // http://crbug.com/135487.
797      if (!window ||
798          window->type() != aura::client::WINDOW_TYPE_NORMAL ||
799          wm::IsWindowFullscreen(window)) {
800        break;
801      }
802
803      internal::SnapSizer::SnapWindow(window,
804          action == WINDOW_SNAP_LEFT ? internal::SnapSizer::LEFT_EDGE :
805                                       internal::SnapSizer::RIGHT_EDGE);
806      return true;
807    }
808    case WINDOW_MINIMIZE: {
809      aura::Window* window = wm::GetActiveWindow();
810      // Attempt to restore the window that would be cycled through next from
811      // the launcher when there is no active window.
812      if (!window)
813        return HandleCycleWindowMRU(WindowCycleController::FORWARD, false);
814      // Disable the shortcut for minimizing full screen window due to
815      // crbug.com/131709, which is a crashing issue related to minimizing
816      // full screen pepper window.
817      if (!wm::IsWindowFullscreen(window) && wm::CanMinimizeWindow(window)) {
818        ash::Shell::GetInstance()->delegate()->RecordUserMetricsAction(
819            ash::UMA_MINIMIZE_PER_KEY);
820        wm::MinimizeWindow(window);
821        return true;
822      }
823      break;
824    }
825    case TOGGLE_FULLSCREEN: {
826      if (key_code == ui::VKEY_MEDIA_LAUNCH_APP2) {
827        shell->delegate()->RecordUserMetricsAction(
828            UMA_ACCEL_FULLSCREEN_F4);
829      }
830      shell->delegate()->ToggleFullscreen();
831      return true;
832    }
833    case TOGGLE_MAXIMIZED: {
834      if (key_code == ui::VKEY_MEDIA_LAUNCH_APP2) {
835        shell->delegate()->RecordUserMetricsAction(
836            UMA_ACCEL_MAXIMIZE_RESTORE_F4);
837      }
838      shell->delegate()->ToggleMaximized();
839      return true;
840    }
841    case WINDOW_POSITION_CENTER: {
842      aura::Window* window = wm::GetActiveWindow();
843      if (window) {
844        wm::CenterWindow(window);
845        return true;
846      }
847      break;
848    }
849    case SCALE_UI_UP:
850      return HandleScaleUI(true /* up */);
851    case SCALE_UI_DOWN:
852      return HandleScaleUI(false /* down */);
853    case SCALE_UI_RESET:
854      return HandleScaleReset();
855    case ROTATE_WINDOW:
856      return HandleRotateActiveWindow();
857    case ROTATE_SCREEN:
858      return HandleRotateScreen();
859    case TOGGLE_DESKTOP_BACKGROUND_MODE:
860      return HandleToggleDesktopBackgroundMode();
861    case TOGGLE_ROOT_WINDOW_FULL_SCREEN:
862      return HandleToggleRootWindowFullScreen();
863    case DEBUG_TOGGLE_DEVICE_SCALE_FACTOR:
864      Shell::GetInstance()->display_manager()->ToggleDisplayScaleFactor();
865      return true;
866    case DEBUG_TOGGLE_SHOW_DEBUG_BORDERS:
867      ash::debug::ToggleShowDebugBorders();
868      return true;
869    case DEBUG_TOGGLE_SHOW_FPS_COUNTER:
870      ash::debug::ToggleShowFpsCounter();
871      return true;
872    case DEBUG_TOGGLE_SHOW_PAINT_RECTS:
873      ash::debug::ToggleShowPaintRects();
874      return true;
875    case MAGNIFY_SCREEN_ZOOM_IN:
876      return HandleMagnifyScreen(1);
877    case MAGNIFY_SCREEN_ZOOM_OUT:
878      return HandleMagnifyScreen(-1);
879    case MEDIA_NEXT_TRACK:
880      return HandleMediaNextTrack();
881    case MEDIA_PLAY_PAUSE:
882       return HandleMediaPlayPause();
883    case MEDIA_PREV_TRACK:
884       return HandleMediaPrevTrack();
885    case POWER_PRESSED:  // fallthrough
886    case POWER_RELEASED:
887#if defined(OS_CHROMEOS)
888      if (!base::chromeos::IsRunningOnChromeOS()) {
889        // There is no powerd in linux desktop, so call the
890        // PowerButtonController here.
891        Shell::GetInstance()->power_button_controller()->
892            OnPowerButtonEvent(action == POWER_PRESSED, base::TimeTicks());
893      }
894#endif
895      // We don't do anything with these at present on the device,
896      // (power button events are reported to us from powerm via
897      // D-BUS), but we consume them to prevent them from getting
898      // passed to apps -- see http://crbug.com/146609.
899      return true;
900    case LOCK_PRESSED:
901    case LOCK_RELEASED:
902      Shell::GetInstance()->power_button_controller()->
903          OnLockButtonEvent(action == LOCK_PRESSED, base::TimeTicks());
904      return true;
905#if !defined(NDEBUG)
906    case PRINT_LAYER_HIERARCHY:
907      return HandlePrintLayerHierarchy();
908    case PRINT_VIEW_HIERARCHY:
909      return HandlePrintViewHierarchy();
910    case PRINT_WINDOW_HIERARCHY:
911      return HandlePrintWindowHierarchy();
912#endif
913    default:
914      NOTREACHED() << "Unhandled action " << action;
915  }
916  return false;
917}
918
919void AcceleratorController::SetBrightnessControlDelegate(
920    scoped_ptr<BrightnessControlDelegate> brightness_control_delegate) {
921  // Install brightness control delegate only when internal
922  // display exists.
923  if (Shell::GetInstance()->display_manager()->HasInternalDisplay() ||
924      CommandLine::ForCurrentProcess()->HasSwitch(
925          switches::kAshEnableBrightnessControl)) {
926    brightness_control_delegate_ = brightness_control_delegate.Pass();
927  }
928}
929
930void AcceleratorController::SetImeControlDelegate(
931    scoped_ptr<ImeControlDelegate> ime_control_delegate) {
932  ime_control_delegate_ = ime_control_delegate.Pass();
933}
934
935void AcceleratorController::SetScreenshotDelegate(
936    scoped_ptr<ScreenshotDelegate> screenshot_delegate) {
937  screenshot_delegate_ = screenshot_delegate.Pass();
938}
939
940////////////////////////////////////////////////////////////////////////////////
941// AcceleratorController, ui::AcceleratorTarget implementation:
942
943bool AcceleratorController::AcceleratorPressed(
944    const ui::Accelerator& accelerator) {
945  std::map<ui::Accelerator, int>::const_iterator it =
946      accelerators_.find(accelerator);
947  DCHECK(it != accelerators_.end());
948  return PerformAction(static_cast<AcceleratorAction>(it->second), accelerator);
949}
950
951void AcceleratorController::RegisterAccelerators(
952    const AcceleratorData accelerators[],
953    size_t accelerators_length) {
954  for (size_t i = 0; i < accelerators_length; ++i) {
955    ui::Accelerator accelerator(accelerators[i].keycode,
956                                accelerators[i].modifiers);
957    accelerator.set_type(accelerators[i].trigger_on_press ?
958                         ui::ET_KEY_PRESSED : ui::ET_KEY_RELEASED);
959    Register(accelerator, this);
960    accelerators_.insert(
961        std::make_pair(accelerator, accelerators[i].action));
962  }
963}
964
965void AcceleratorController::SetKeyboardBrightnessControlDelegate(
966    scoped_ptr<KeyboardBrightnessControlDelegate>
967    keyboard_brightness_control_delegate) {
968  keyboard_brightness_control_delegate_ =
969      keyboard_brightness_control_delegate.Pass();
970}
971
972bool AcceleratorController::CanHandleAccelerators() const {
973  return true;
974}
975
976}  // namespace ash
977