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.h" 6 #include "chrome/browser/profiles/profile.h" 7 #include "ui/base/accelerators/accelerator.h" 8 9 namespace extensions { 10 11 GlobalShortcutListener::GlobalShortcutListener() { 12 } 13 14 GlobalShortcutListener::~GlobalShortcutListener() { 15 DCHECK(accelerator_map_.empty()); // Make sure we've cleaned up. 16 } 17 18 void GlobalShortcutListener::RegisterAccelerator( 19 const ui::Accelerator& accelerator, Observer* observer) { 20 AcceleratorMap::const_iterator it = accelerator_map_.find(accelerator); 21 if (it == accelerator_map_.end()) { 22 if (accelerator_map_.empty()) 23 GlobalShortcutListener::GetInstance()->StartListening(); 24 Observers* observers = new Observers; 25 observers->AddObserver(observer); 26 accelerator_map_[accelerator] = observers; 27 } else { 28 // Make sure we don't register the same accelerator twice. 29 DCHECK(!accelerator_map_[accelerator]->HasObserver(observer)); 30 accelerator_map_[accelerator]->AddObserver(observer); 31 } 32 } 33 34 void GlobalShortcutListener::UnregisterAccelerator( 35 const ui::Accelerator& accelerator, Observer* observer) { 36 AcceleratorMap::iterator it = accelerator_map_.find(accelerator); 37 DCHECK(it != accelerator_map_.end()); 38 DCHECK(it->second->HasObserver(observer)); 39 it->second->RemoveObserver(observer); 40 if (!it->second->might_have_observers()) { 41 accelerator_map_.erase(it); 42 if (accelerator_map_.empty()) 43 GlobalShortcutListener::GetInstance()->StopListening(); 44 } 45 } 46 47 void GlobalShortcutListener::NotifyKeyPressed( 48 const ui::Accelerator& accelerator) { 49 AcceleratorMap::iterator iter = accelerator_map_.find(accelerator); 50 if (iter == accelerator_map_.end()) { 51 // This should never occur, because if it does, we have failed to unregister 52 // or failed to clean up the map after unregistering the shortcut. 53 NOTREACHED(); 54 return; // No-one is listening to this key. 55 } 56 // The observer list should not be empty. 57 DCHECK(iter->second->might_have_observers()); 58 59 FOR_EACH_OBSERVER(Observer, *(iter->second), OnKeyPressed(accelerator)); 60 } 61 62 } // namespace extensions 63