Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(28)

Side by Side Diff: content/browser/battery_status/battery_status_manager_mac.cc

Issue 398683006: Battery Status API: implementation for Mac OS. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: comments + rebase Created 6 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « no previous file | content/content_browser.gypi » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
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 "content/browser/battery_status/battery_status_manager.h"
6
7 #include <CoreFoundation/CoreFoundation.h>
8 #include <IOKit/ps/IOPowerSources.h>
9 #include <IOKit/ps/IOPSKeys.h>
10
11 #include "base/mac/foundation_util.h"
12 #include "base/mac/scoped_cftyperef.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/time/time.h"
15 #include "content/public/browser/browser_thread.h"
16 #include "third_party/WebKit/public/platform/WebBatteryStatus.h"
17
18 namespace content {
19
20 namespace {
21
22 typedef BatteryStatusService::BatteryUpdateCallback BatteryCallback;
23
24 // Returns the value corresponding to |key| in the dictionary |description|.
25 // Returns |default_value| if the dictionary does not contain |key|, the
26 // corresponding value is NULL or it could not be converted to SInt64.
27 SInt64 GetValueAsSInt64(CFDictionaryRef description,
28 CFStringRef key,
29 SInt64 default_value) {
30 CFNumberRef number =
31 base::mac::GetValueFromDictionary<CFNumberRef>(description, key);
32 SInt64 value;
33
34 if (number && CFNumberGetValue(number, kCFNumberSInt64Type, &value))
35 return value;
36
37 return default_value;
38 }
39
40 bool GetValueAsBoolean(CFDictionaryRef description,
41 CFStringRef key,
42 bool default_value) {
43 CFBooleanRef boolean =
44 base::mac::GetValueFromDictionary<CFBooleanRef>(description, key);
45
46 return boolean ? CFBooleanGetValue(boolean) : default_value;
47 }
48
49 bool CFStringsAreEqual(CFStringRef string1, CFStringRef string2) {
50 if (!string1 || !string2)
51 return false;
52 return CFStringCompare(string1, string2, 0) == kCFCompareEqualTo;
53 }
54
55 void FetchBatteryStatus(CFDictionaryRef description,
56 blink::WebBatteryStatus& status) {
57 CFStringRef current_state =
58 base::mac::GetValueFromDictionary<CFStringRef>(description,
59 CFSTR(kIOPSPowerSourceStateKey));
60
61 bool on_battery_power =
62 CFStringsAreEqual(current_state, CFSTR(kIOPSBatteryPowerValue));
63 bool is_charging =
64 GetValueAsBoolean(description, CFSTR(kIOPSIsChargingKey), true);
65 bool is_charged =
66 GetValueAsBoolean(description, CFSTR(kIOPSIsChargedKey), false);
67
68 status.charging = !on_battery_power || is_charging;
69
70 SInt64 current_capacity =
71 GetValueAsSInt64(description, CFSTR(kIOPSCurrentCapacityKey), -1);
72 SInt64 max_capacity =
73 GetValueAsSInt64(description, CFSTR(kIOPSMaxCapacityKey), -1);
74
75 // Set level if it is available and valid. Otherwise leave the default value,
76 // which is 1.
77 if (current_capacity != -1 && max_capacity != -1 &&
78 current_capacity <= max_capacity && max_capacity != 0) {
79 status.level = current_capacity / static_cast<double>(max_capacity);
80 }
81
82 if (is_charging) {
83 SInt64 charging_time =
84 GetValueAsSInt64(description, CFSTR(kIOPSTimeToFullChargeKey), -1);
85
86 // Battery is charging: set the charging time if it's available, otherwise
87 // set to +infinity.
88 status.chargingTime = charging_time != -1
89 ? base::TimeDelta::FromMinutes(charging_time).InSeconds()
90 : std::numeric_limits<double>::infinity();
91 } else {
92 // Battery is not charging.
93 // Set chargingTime to +infinity if the battery is not charged. Otherwise
94 // leave the default value, which is 0.
95 if (!is_charged)
96 status.chargingTime = std::numeric_limits<double>::infinity();
97
98 // Set dischargingTime if it's available and valid, i.e. when on battery
99 // power. Otherwise leave the default value, which is +infinity.
100 if (on_battery_power) {
101 SInt64 discharging_time =
102 GetValueAsSInt64(description, CFSTR(kIOPSTimeToEmptyKey), -1);
103 if (discharging_time != -1) {
104 status.dischargingTime =
105 base::TimeDelta::FromMinutes(discharging_time).InSeconds();
106 }
107 }
108 }
109 }
110
111 void OnBatteryStatusChanged(const BatteryCallback& callback) {
112 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
113 blink::WebBatteryStatus status;
114 base::ScopedCFTypeRef<CFTypeRef> info(IOPSCopyPowerSourcesInfo());
115 base::ScopedCFTypeRef<CFArrayRef> power_sources_list(
116 IOPSCopyPowerSourcesList(info));
117 CFIndex count = CFArrayGetCount(power_sources_list);
118
119 bool internal_source_found = false;
120
121 for (CFIndex i = 0; i < count; ++i) {
122 CFDictionaryRef description = IOPSGetPowerSourceDescription(info,
123 CFArrayGetValueAtIndex(power_sources_list, i));
124
125 if (!description)
126 continue;
127
128 CFStringRef transport_type =
129 base::mac::GetValueFromDictionary<CFStringRef>(description,
130 CFSTR(kIOPSTransportTypeKey));
131
132 bool internal_source =
133 CFStringsAreEqual(transport_type, CFSTR(kIOPSInternalType));
134 bool source_present =
135 GetValueAsBoolean(description, CFSTR(kIOPSIsPresentKey), false);
136
137 if (internal_source && source_present) {
138 // TODO(timvolodine): implement the case when there are multiple internal
139 // sources, e.g. when multiple batteries are present. Currently this will
140 // fail a DCHECK.
141 DCHECK(!internal_source_found);
142 FetchBatteryStatus(description, status);
143 internal_source_found = true;
144 }
145 }
146
147 callback.Run(status);
148 }
149
150 class BatteryStatusObserver
151 : public base::RefCountedThreadSafe<BatteryStatusObserver> {
152 public:
153 explicit BatteryStatusObserver(const BatteryCallback& callback)
154 : callback_(callback) {}
155
156 void Start() {
157 // Need to start on a thread with UI-type message loop for
158 // |notifier_run_loop_| to receive callbacks.
159 if (BrowserThread::CurrentlyOn(BrowserThread::UI)) {
160 StartOnUI();
161 } else {
162 BrowserThread::PostTask(
163 BrowserThread::UI,
164 FROM_HERE,
165 base::Bind(&BatteryStatusObserver::StartOnUI, this));
166 }
167 }
168
169 void Stop() {
170 if (BrowserThread::CurrentlyOn(BrowserThread::UI)) {
171 StopOnUI();
172 } else {
173 BrowserThread::PostTask(
174 BrowserThread::UI,
175 FROM_HERE,
176 base::Bind(&BatteryStatusObserver::StopOnUI, this));
177 }
178 }
179
180 private:
181 friend class base::RefCountedThreadSafe<BatteryStatusObserver>;
182 virtual ~BatteryStatusObserver() { DCHECK(!notifier_run_loop_source_); }
183
184 void StartOnUI() {
185 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
186
187 if (notifier_run_loop_source_)
188 return;
189
190 notifier_run_loop_source_.reset(
191 IOPSNotificationCreateRunLoopSource(OnBatteryStatusChangedUI,
192 static_cast<void*>(&callback_)));
193 if (!notifier_run_loop_source_) {
194 LOG(ERROR) << "Failed to create battery status notification run loop";
195 // Make sure to execute to callback with the default values.
196 callback_.Run(blink::WebBatteryStatus());
197 return;
198 }
199
200 OnBatteryStatusChangedUI(static_cast<void*>(&callback_));
201 CFRunLoopAddSource(CFRunLoopGetCurrent(), notifier_run_loop_source_,
202 kCFRunLoopDefaultMode);
203 }
204
205 void StopOnUI() {
206 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
207
208 if (!notifier_run_loop_source_)
209 return;
210
211 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), notifier_run_loop_source_,
212 kCFRunLoopDefaultMode);
213 notifier_run_loop_source_.reset();
214 }
215
216 static void OnBatteryStatusChangedUI(void* callback) {
217 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
218 // Offload fetching of values and callback execution to the IO thread.
219 BrowserThread::PostTask(
220 BrowserThread::IO,
221 FROM_HERE,
222 base::Bind(&OnBatteryStatusChanged,
223 *static_cast<BatteryCallback*>(callback)));
224 }
225
226 BatteryCallback callback_;
227 base::ScopedCFTypeRef<CFRunLoopSourceRef> notifier_run_loop_source_;
228
229 DISALLOW_COPY_AND_ASSIGN(BatteryStatusObserver);
230 };
231
232 class BatteryStatusManagerMac : public BatteryStatusManager {
233 public:
234 explicit BatteryStatusManagerMac(const BatteryCallback& callback)
235 : notifier_(new BatteryStatusObserver(callback)) {}
236
237 virtual ~BatteryStatusManagerMac() {
238 notifier_->Stop();
239 }
240
241 // BatteryStatusManager:
242 virtual bool StartListeningBatteryChange() OVERRIDE {
243 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
244 notifier_->Start();
245 return true;
246 }
247
248 virtual void StopListeningBatteryChange() OVERRIDE {
249 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
250 notifier_->Stop();
251 }
252
253 private:
254 scoped_refptr<BatteryStatusObserver> notifier_;
255
256 DISALLOW_COPY_AND_ASSIGN(BatteryStatusManagerMac);
257 };
258
259 } // end namespace
260
261 // static
262 scoped_ptr<BatteryStatusManager> BatteryStatusManager::Create(
263 const BatteryStatusService::BatteryUpdateCallback& callback) {
264 return scoped_ptr<BatteryStatusManager>(
265 new BatteryStatusManagerMac(callback));
266 }
267
268 } // namespace content
OLDNEW
« no previous file with comments | « no previous file | content/content_browser.gypi » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698