1// Copyright (c) 2006-2008 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/command_updater.h" 6 7#include <algorithm> 8 9#include "base/logging.h" 10#include "base/observer_list.h" 11#include "base/stl_util-inl.h" 12 13CommandUpdater::CommandUpdaterDelegate::~CommandUpdaterDelegate() { 14} 15 16class CommandUpdater::Command { 17 public: 18 bool enabled; 19 ObserverList<CommandObserver> observers; 20 21 Command() : enabled(true) {} 22}; 23 24CommandUpdater::CommandUpdater(CommandUpdaterDelegate* handler) 25 : delegate_(handler) { 26} 27 28CommandUpdater::~CommandUpdater() { 29 STLDeleteContainerPairSecondPointers(commands_.begin(), commands_.end()); 30} 31 32bool CommandUpdater::IsCommandEnabled(int id) const { 33 const CommandMap::const_iterator command(commands_.find(id)); 34 if (command == commands_.end()) 35 return false; 36 return command->second->enabled; 37} 38 39bool CommandUpdater::SupportsCommand(int id) const { 40 return commands_.find(id) != commands_.end(); 41} 42 43void CommandUpdater::ExecuteCommand(int id) { 44 if (IsCommandEnabled(id)) 45 delegate_->ExecuteCommand(id); 46} 47 48CommandUpdater::CommandObserver::~CommandObserver() { 49} 50 51void CommandUpdater::UpdateCommandEnabled(int id, bool enabled) { 52 Command* command = GetCommand(id, true); 53 if (command->enabled == enabled) 54 return; // Nothing to do. 55 command->enabled = enabled; 56 FOR_EACH_OBSERVER(CommandObserver, command->observers, 57 EnabledStateChangedForCommand(id, enabled)); 58} 59 60CommandUpdater::Command* CommandUpdater::GetCommand(int id, bool create) { 61 bool supported = SupportsCommand(id); 62 if (supported) 63 return commands_[id]; 64 DCHECK(create); 65 Command* command = new Command; 66 commands_[id] = command; 67 return command; 68} 69 70void CommandUpdater::AddCommandObserver(int id, CommandObserver* observer) { 71 GetCommand(id, true)->observers.AddObserver(observer); 72} 73 74void CommandUpdater::RemoveCommandObserver(int id, CommandObserver* observer) { 75 GetCommand(id, false)->observers.RemoveObserver(observer); 76} 77 78void CommandUpdater::RemoveCommandObserver(CommandObserver* observer) { 79 for (CommandMap::const_iterator it = commands_.begin(); 80 it != commands_.end(); 81 ++it) { 82 Command* command = it->second; 83 if (command) 84 command->observers.RemoveObserver(observer); 85 } 86} 87