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 #ifndef CHROMEOS_DBUS_POWER_FAKE_POWER_MANAGER_CLIENT_H_
6 #define CHROMEOS_DBUS_POWER_FAKE_POWER_MANAGER_CLIENT_H_
7
8 #include <memory>
9 #include <queue>
10 #include <string>
11 #include <utility>
12 #include <vector>
13
14 #include "base/callback_forward.h"
15 #include "base/component_export.h"
16 #include "base/containers/circular_deque.h"
17 #include "base/containers/flat_map.h"
18 #include "base/macros.h"
19 #include "base/memory/weak_ptr.h"
20 #include "base/observer_list.h"
21 #include "base/optional.h"
22 #include "base/time/tick_clock.h"
23 #include "base/time/time.h"
24 #include "chromeos/dbus/power/power_manager_client.h"
25 #include "chromeos/dbus/power_manager/backlight.pb.h"
26 #include "chromeos/dbus/power_manager/policy.pb.h"
27 #include "chromeos/dbus/power_manager/power_supply_properties.pb.h"
28 #include "chromeos/dbus/power_manager/suspend.pb.h"
29
30 namespace base {
31 class OneShotTimer;
32 }
33
34 namespace chromeos {
35
36 // A fake implementation of PowerManagerClient. This remembers the policy passed
37 // to SetPolicy() and the user of this class can inspect the last set policy by
38 // get_policy().
COMPONENT_EXPORT(DBUS_POWER)39 class COMPONENT_EXPORT(DBUS_POWER) FakePowerManagerClient
40 : public PowerManagerClient {
41 public:
42 FakePowerManagerClient();
43 ~FakePowerManagerClient() override;
44
45 // Checks that FakePowerManagerClient was initialized and returns it.
46 static FakePowerManagerClient* Get();
47
48 const power_manager::PowerManagementPolicy& policy() { return policy_; }
49 int num_request_restart_calls() const { return num_request_restart_calls_; }
50 int num_request_shutdown_calls() const { return num_request_shutdown_calls_; }
51 int num_set_policy_calls() const { return num_set_policy_calls_; }
52 int num_set_is_projecting_calls() const {
53 return num_set_is_projecting_calls_;
54 }
55 int num_wake_notification_calls() const {
56 return num_wake_notification_calls_;
57 }
58 int num_pending_suspend_readiness_callbacks() const {
59 return num_pending_suspend_readiness_callbacks_;
60 }
61 double screen_brightness_percent() const {
62 return screen_brightness_percent_.value();
63 }
64 bool is_projecting() const { return is_projecting_; }
65 bool have_video_activity_report() const {
66 return !video_activity_reports_.empty();
67 }
68 bool backlights_forced_off() const { return backlights_forced_off_; }
69 int num_set_backlights_forced_off_calls() const {
70 return num_set_backlights_forced_off_calls_;
71 }
72 void set_enqueue_brightness_changes_on_backlights_forced_off(bool enqueue) {
73 enqueue_brightness_changes_on_backlights_forced_off_ = enqueue;
74 }
75 const std::queue<power_manager::BacklightBrightnessChange>&
76 pending_screen_brightness_changes() const {
77 return pending_screen_brightness_changes_;
78 }
79 void set_user_activity_callback(base::RepeatingClosure callback) {
80 user_activity_callback_ = std::move(callback);
81 }
82 void set_peripheral_battery_refresh_level(const std::string& address,
83 int level) {
84 peripheral_battery_refresh_levels_[address] = level;
85 }
86
87 // PowerManagerClient overrides:
88 void AddObserver(Observer* observer) override;
89 void RemoveObserver(Observer* observer) override;
90 bool HasObserver(const Observer* observer) const override;
91 void SetRenderProcessManagerDelegate(
92 base::WeakPtr<RenderProcessManagerDelegate> delegate) override;
93 void DecreaseScreenBrightness(bool allow_off) override;
94 void IncreaseScreenBrightness() override;
95 void SetScreenBrightness(
96 const power_manager::SetBacklightBrightnessRequest& request) override;
97 void GetScreenBrightnessPercent(DBusMethodCallback<double> callback) override;
98 void DecreaseKeyboardBrightness() override;
99 void IncreaseKeyboardBrightness() override;
100 void GetKeyboardBrightnessPercent(
101 DBusMethodCallback<double> callback) override;
102 const base::Optional<power_manager::PowerSupplyProperties>& GetLastStatus()
103 override;
104 void RequestStatusUpdate() override;
105 void RequestSuspend() override;
106 void RequestRestart(power_manager::RequestRestartReason reason,
107 const std::string& description) override;
108 void RequestShutdown(power_manager::RequestShutdownReason reason,
109 const std::string& description) override;
110 void NotifyUserActivity(power_manager::UserActivityType type) override;
111 void NotifyVideoActivity(bool is_fullscreen) override;
112 void NotifyWakeNotification() override;
113 void SetPolicy(const power_manager::PowerManagementPolicy& policy) override;
114 void SetIsProjecting(bool is_projecting) override;
115 void SetPowerSource(const std::string& id) override;
116 void SetBacklightsForcedOff(bool forced_off) override;
117 void GetBacklightsForcedOff(DBusMethodCallback<bool> callback) override;
118 void GetSwitchStates(DBusMethodCallback<SwitchStates> callback) override;
119 void GetInactivityDelays(
120 DBusMethodCallback<power_manager::PowerManagementPolicy::Delays> callback)
121 override;
122 void BlockSuspend(const base::UnguessableToken& token,
123 const std::string& debug_info) override;
124 void UnblockSuspend(const base::UnguessableToken& token) override;
125 bool SupportsAmbientColor() override;
126 void CreateArcTimers(
127 const std::string& tag,
128 std::vector<std::pair<clockid_t, base::ScopedFD>> arc_timer_requests,
129 DBusMethodCallback<std::vector<TimerId>> callback) override;
130 void StartArcTimer(TimerId timer_id,
131 base::TimeTicks absolute_expiration_time,
132 VoidDBusMethodCallback callback) override;
133 void DeleteArcTimers(const std::string& tag,
134 VoidDBusMethodCallback callback) override;
135 base::TimeDelta GetDarkSuspendDelayTimeout() override;
136 void RefreshBluetoothBattery(const std::string& address) override;
137
138 // Pops the first report from |video_activity_reports_|, returning whether the
139 // activity was fullscreen or not. There must be at least one report.
140 bool PopVideoActivityReport();
141
142 // Emulates the power manager announcing that the system is starting or
143 // completing a suspend attempt.
144 void SendSuspendImminent(power_manager::SuspendImminent::Reason reason);
145 void SendSuspendDone(base::TimeDelta sleep_duration = base::TimeDelta());
146 void SendDarkSuspendImminent();
147
148 // Emulates the power manager announcing that the system is changing the
149 // screen or keyboard brightness.
150 void SendScreenBrightnessChanged(
151 const power_manager::BacklightBrightnessChange& proto);
152 void SendKeyboardBrightnessChanged(
153 const power_manager::BacklightBrightnessChange& proto);
154
155 // Notifies observers about the screen idle state changing.
156 void SendScreenIdleStateChanged(const power_manager::ScreenIdleState& proto);
157
158 // Notifies observers that the power button has been pressed or released.
159 void SendPowerButtonEvent(bool down, const base::TimeTicks& timestamp);
160
161 // Sets |lid_state_| or |tablet_mode_| and notifies |observers_| about the
162 // change.
163 void SetLidState(LidState state, const base::TimeTicks& timestamp);
164 void SetTabletMode(TabletMode mode, const base::TimeTicks& timestamp);
165
166 // Sets |inactivity_delays_| and notifies |observers_| about the change.
167 void SetInactivityDelays(
168 const power_manager::PowerManagementPolicy::Delays& delays);
169
170 // Updates |props_| and notifies observers of its changes.
171 void UpdatePowerProperties(
172 const power_manager::PowerSupplyProperties& power_props);
173
174 // The PowerAPI requests system wake lock asynchronously. Test can run a
175 // RunLoop and set the quit closure by this function to make sure the wake
176 // lock has been created.
177 void SetPowerPolicyQuitClosure(base::OnceClosure quit_closure);
178
179 // Updates screen brightness to the first pending value in
180 // |pending_screen_brightness_changes_|.
181 // Returns whether the screen brightness change was applied - this will
182 // return false if there are no pending brightness changes.
183 bool ApplyPendingScreenBrightnessChange();
184
185 // Returns time ticks from boot including time ticks spent during sleeping.
186 base::TimeTicks GetCurrentBootTime();
187
188 // Sets the screen brightness percent to be returned.
189 // The nullopt |percent| means an error. In case of success,
190 // |percent| must be in the range of [0, 100].
191 void set_screen_brightness_percent(const base::Optional<double>& percent) {
192 screen_brightness_percent_ = percent;
193 }
194
195 void set_keyboard_brightness_percent(const base::Optional<double>& percent) {
196 keyboard_brightness_percent_ = percent;
197 }
198
199 void set_supports_ambient_color(bool supports_ambient_color) {
200 supports_ambient_color_ = supports_ambient_color;
201 }
202
203 // Sets |tick_clock| to |tick_clock_|.
204 void set_tick_clock(const base::TickClock* tick_clock) {
205 tick_clock_ = tick_clock;
206 }
207
208 void simulate_start_arc_timer_failure(bool simulate) {
209 simulate_start_arc_timer_failure_ = simulate;
210 }
211
212 private:
213 // Notifies |observers_| that |props_| has been updated.
214 void NotifyObservers();
215
216 // Deletes all timers, if any, associated with |tag|.
217 void DeleteArcTimersInternal(const std::string& tag);
218
219 base::ObserverList<Observer>::Unchecked observers_;
220
221 // Last policy passed to SetPolicy().
222 power_manager::PowerManagementPolicy policy_;
223
224 // Power status received from the power manager.
225 base::Optional<power_manager::PowerSupplyProperties> props_;
226
227 // Number of times that various methods have been called.
228 int num_request_restart_calls_ = 0;
229 int num_request_shutdown_calls_ = 0;
230 int num_set_policy_calls_ = 0;
231 int num_set_is_projecting_calls_ = 0;
232 int num_set_backlights_forced_off_calls_ = 0;
233 int num_wake_notification_calls_ = 0;
234
235 // Number of pending suspend readiness callbacks.
236 int num_pending_suspend_readiness_callbacks_ = 0;
237
238 // Current screen brightness in the range [0.0, 100.0].
239 base::Optional<double> screen_brightness_percent_;
240
241 // Current keyboard brightness in the range [0.0, 100.0].
242 base::Optional<double> keyboard_brightness_percent_;
243
244 // Last screen brightness requested via SetScreenBrightness().
245 // Unlike |screen_brightness_percent_|, this value will not be changed by
246 // SetBacklightsForcedOff() method - a method that implicitly changes screen
247 // brightness.
248 // Initially set to an arbitrary non-null value.
249 double requested_screen_brightness_percent_ = 80;
250
251 // Last projecting state set in SetIsProjecting().
252 bool is_projecting_ = false;
253
254 // Display and keyboard backlights (if present) forced off state set in
255 // SetBacklightsForcedOff().
256 bool backlights_forced_off_ = false;
257
258 // Whether screen brightness changes in SetBacklightsForcedOff() should be
259 // enqueued.
260 // If not set, SetBacklightsForcedOff() will update current screen
261 // brightness and send a brightness change event (provided undimmed
262 // brightness percent is set).
263 // If set, brightness changes will be enqueued to
264 // |pending_screen_brightness_changes_|, and will have to be applied
265 // explicitly by calling ApplyPendingScreenBrightnessChange().
266 bool enqueue_brightness_changes_on_backlights_forced_off_ = false;
267
268 // Whether the device has an ambient color sensor. Can be set via
269 // SetSupportsAmbientColor().
270 bool supports_ambient_color_ = false;
271
272 // Pending screen brightness changes caused by SetBacklightsForcedOff().
273 // ApplyPendingScreenBrightnessChange() applies the first pending change.
274 std::queue<power_manager::BacklightBrightnessChange>
275 pending_screen_brightness_changes_;
276
277 // Delays returned by GetInactivityDelays().
278 power_manager::PowerManagementPolicy::Delays inactivity_delays_;
279
280 // States returned by GetSwitchStates().
281 LidState lid_state_ = LidState::OPEN;
282 TabletMode tablet_mode_ = TabletMode::UNSUPPORTED;
283
284 // Monotonically increasing timer id assigned to created timers.
285 TimerId next_timer_id_ = 1;
286
287 // Represents the timer and the timer expiration fd associated with a timer id
288 // stored as the key. The fd is written to when the timer associated with the
289 // clock expires.
290 base::flat_map<TimerId,
291 std::pair<std::unique_ptr<base::OneShotTimer>, base::ScopedFD>>
292 arc_timers_;
293
294 // Maps a client's tag to its list of timer ids.
295 base::flat_map<std::string, std::vector<TimerId>> client_timer_ids_;
296
297 // Video activity reports that we were requested to send, in the order they
298 // were requested. True if fullscreen.
299 base::circular_deque<bool> video_activity_reports_;
300
301 // Delegate for managing power consumption of Chrome's renderer processes.
302 base::WeakPtr<RenderProcessManagerDelegate> render_process_manager_delegate_;
303
304 // If non-empty, called by SetPowerPolicy().
305 base::OnceClosure power_policy_quit_closure_;
306
307 // If non-empty, called by NotifyUserActivity().
308 base::RepeatingClosure user_activity_callback_;
309
310 // Clock to use to calculate time ticks. Used for ArcTimer related APIs.
311 const base::TickClock* tick_clock_;
312
313 // If set then |StartArcTimer| returns failure.
314 bool simulate_start_arc_timer_failure_ = false;
315
316 // Used in RefreshBluetoothBattery.
317 base::flat_map<std::string, int> peripheral_battery_refresh_levels_;
318
319 // Note: This should remain the last member so it'll be destroyed and
320 // invalidate its weak pointers before any other members are destroyed.
321 base::WeakPtrFactory<FakePowerManagerClient> weak_ptr_factory_{this};
322
323 DISALLOW_COPY_AND_ASSIGN(FakePowerManagerClient);
324 };
325
326 } // namespace chromeos
327
328 #endif // CHROMEOS_DBUS_POWER_FAKE_POWER_MANAGER_CLIENT_H_
329