1// Copyright (c) 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 "chrome/browser/extensions/global_shortcut_listener_chromeos.h"
6
7#include "ash/accelerators/accelerator_controller.h"
8#include "ash/shell.h"
9#include "content/public/browser/browser_thread.h"
10
11using content::BrowserThread;
12
13namespace extensions {
14
15// static
16GlobalShortcutListener* GlobalShortcutListener::GetInstance() {
17  CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
18  static GlobalShortcutListenerChromeOS* instance =
19      new GlobalShortcutListenerChromeOS();
20  return instance;
21}
22
23GlobalShortcutListenerChromeOS::GlobalShortcutListenerChromeOS()
24    : is_listening_(false) {
25  CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
26}
27
28GlobalShortcutListenerChromeOS::~GlobalShortcutListenerChromeOS() {
29  if (is_listening_)
30    StopListening();
31}
32
33void GlobalShortcutListenerChromeOS::StartListening() {
34  DCHECK(!is_listening_);  // Don't start twice.
35  is_listening_ = true;
36}
37
38void GlobalShortcutListenerChromeOS::StopListening() {
39  DCHECK(is_listening_);  // No point if we are not already listening.
40  is_listening_ = false;
41}
42
43bool GlobalShortcutListenerChromeOS::RegisterAcceleratorImpl(
44    const ui::Accelerator& accelerator) {
45  ash::AcceleratorController* controller =
46      ash::Shell::GetInstance()->accelerator_controller();
47  if (controller->IsRegistered(accelerator))
48    return false;
49
50  // TODO(dtseng): Support search key mapping.
51  controller->Register(accelerator, this);
52  return controller->IsRegistered(accelerator);
53}
54
55void GlobalShortcutListenerChromeOS::UnregisterAcceleratorImpl(
56    const ui::Accelerator& accelerator) {
57  // This code path gets called during object destruction.
58  if (!ash::Shell::HasInstance())
59    return;
60  ash::Shell::GetInstance()->accelerator_controller()->Unregister(accelerator,
61                                                                  this);
62}
63
64bool GlobalShortcutListenerChromeOS::AcceleratorPressed(
65    const ui::Accelerator& accelerator) {
66  DCHECK(is_listening_);
67  ash::AcceleratorController* controller =
68      ash::Shell::GetInstance()->accelerator_controller();
69  ash::AcceleratorController::AcceleratorProcessingRestriction restriction =
70      controller->GetCurrentAcceleratorRestriction();
71  if (restriction == ash::AcceleratorController::RESTRICTION_NONE) {
72    NotifyKeyPressed(accelerator);
73    return true;
74  }
75  return restriction == ash::AcceleratorController::
76                            RESTRICTION_PREVENT_PROCESSING_AND_PROPAGATION;
77}
78
79bool GlobalShortcutListenerChromeOS::CanHandleAccelerators() const {
80  return is_listening_;
81}
82
83}  // namespace extensions
84