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 "components/power/origin_power_map.h" 6 7#include "base/logging.h" 8#include "content/public/common/url_constants.h" 9#include "url/gurl.h" 10 11namespace power { 12 13OriginPowerMap::OriginPowerMap() : total_consumed_(0.0) { 14} 15 16OriginPowerMap::~OriginPowerMap() { 17} 18 19int OriginPowerMap::GetPowerForOrigin(const GURL& url) { 20 if (!total_consumed_) 21 return 0; 22 23 OriginMap::const_iterator it = origin_map_.find(url.GetOrigin()); 24 return it == origin_map_.end() ? 0 : 25 static_cast<int>(it->second * 100 / total_consumed_ + 0.5); 26} 27 28void OriginPowerMap::AddPowerForOrigin(const GURL& url, double power) { 29 DCHECK_GE(power, 0); 30 GURL origin = url.GetOrigin(); 31 if (!origin.is_valid() || origin.SchemeIs(content::kChromeUIScheme)) 32 return; 33 34 origin_map_[origin] += power; 35 total_consumed_ += power; 36} 37 38OriginPowerMap::PercentOriginMap OriginPowerMap::GetPercentOriginMap() { 39 OriginPowerMap::PercentOriginMap percent_map; 40 41 if (!total_consumed_) 42 return percent_map; 43 44 for (OriginMap::iterator it = origin_map_.begin(); it != origin_map_.end(); 45 ++it) { 46 percent_map[it->first] = 47 static_cast<int>(it->second * 100 / total_consumed_ + 0.5); 48 } 49 return percent_map; 50} 51 52scoped_ptr<OriginPowerMap::Subscription> 53OriginPowerMap::AddPowerConsumptionUpdatedCallback( 54 const base::Closure& callback) { 55 return callback_list_.Add(callback); 56} 57 58void OriginPowerMap::OnAllOriginsUpdated() { 59 callback_list_.Notify(); 60} 61 62void OriginPowerMap::ClearOriginMap() { 63 origin_map_.clear(); 64 total_consumed_ = 0; 65} 66 67} // namespace power 68