summaryrefslogtreecommitdiffstats
path: root/components/power/origin_power_map.cc
blob: 4ce32e28f0cbfa74abb4403e723ac7917eb5d4d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/power/origin_power_map.h"

#include "base/logging.h"
#include "content/public/common/url_constants.h"
#include "url/gurl.h"

namespace power {

OriginPowerMap::OriginPowerMap() : total_consumed_(0.0) {
}

OriginPowerMap::~OriginPowerMap() {
}

int OriginPowerMap::GetPowerForOrigin(const GURL& url) {
  if (!total_consumed_)
    return 0;

  OriginMap::const_iterator it = origin_map_.find(url.GetOrigin());
  return it == origin_map_.end() ? 0 :
      static_cast<int>(it->second * 100 / total_consumed_ + 0.5);
}

void OriginPowerMap::AddPowerForOrigin(const GURL& url, double power) {
  DCHECK_GE(power, 0);
  GURL origin = url.GetOrigin();
  if (!origin.is_valid() || origin.SchemeIs(content::kChromeUIScheme))
    return;

  origin_map_[origin] += power;
  total_consumed_ += power;
}

OriginPowerMap::PercentOriginMap OriginPowerMap::GetPercentOriginMap() {
  OriginPowerMap::PercentOriginMap percent_map;

  if (!total_consumed_)
    return percent_map;

  for (OriginMap::iterator it = origin_map_.begin(); it != origin_map_.end();
       ++it) {
    percent_map[it->first] =
        static_cast<int>(it->second * 100 / total_consumed_ + 0.5);
  }
  return percent_map;
}

scoped_ptr<OriginPowerMap::Subscription>
OriginPowerMap::AddPowerConsumptionUpdatedCallback(
    const base::Closure& callback) {
  return callback_list_.Add(callback);
}

void OriginPowerMap::OnAllOriginsUpdated() {
  callback_list_.Notify();
}

}  // namespace power