1 // Copyright (c) 2012 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.
5 #ifndef CHROMEOS_DISPLAY_OUTPUT_CONFIGURATOR_H_
6 #define CHROMEOS_DISPLAY_OUTPUT_CONFIGURATOR_H_
12 #include "base/basictypes.h"
13 #include "base/event_types.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/message_loop/message_pump_dispatcher.h"
17 #include "base/observer_list.h"
18 #include "base/timer/timer.h"
19 #include "chromeos/chromeos_export.h"
20 #include "third_party/cros_system_api/dbus/service_constants.h"
21 #include "ui/display/display_constants.h"
23 // Forward declarations for Xlib and Xrandr.
24 // This is so unused X definitions don't pollute the namespace.
25 typedef unsigned long XID;
32 // This class interacts directly with the underlying Xrandr API to manipulate
34 class CHROMEOS_EXPORT OutputConfigurator
35 : public base::MessagePumpDispatcher,
36 public base::MessagePumpObserver {
38 typedef uint64_t OutputProtectionClientId;
39 static const OutputProtectionClientId kInvalidClientId = 0;
43 ModeInfo(int width, int height, bool interlaced, float refresh_rate);
51 typedef std::map<RRMode, ModeInfo> ModeInfoMap;
53 struct CoordinateTransformation {
54 // Initialized to the identity transformation.
55 CoordinateTransformation();
63 // Information about an output's current state.
64 struct OutputSnapshot {
70 // CRTC that should be used for this output. Not necessarily the CRTC
71 // that XRandR reports is currently being used.
74 // Mode currently being used by the output.
77 // "Best" mode supported by the output.
80 // Mode used when displaying the same desktop on multiple outputs.
83 // User-selected mode for the output.
86 // Output's origin on the framebuffer.
90 // Output's physical dimensions.
94 bool is_aspect_preserving_scaling;
96 // The type of output.
99 // Map from mode IDs to details about the corresponding modes.
100 ModeInfoMap mode_infos;
102 // XInput device ID or 0 if this output isn't a touchscreen.
105 CoordinateTransformation transform;
107 // Display id for this output.
112 // This output's index in the array returned by XRandR. Stable even as
113 // outputs are connected or disconnected.
119 virtual ~Observer() {}
121 // Called after the display mode has been changed. |output| contains the
122 // just-applied configuration. Note that the X server is no longer grabbed
123 // when this method is called, so the actual configuration could've changed
125 virtual void OnDisplayModeChanged(
126 const std::vector<OutputSnapshot>& outputs) {}
128 // Called after a display mode change attempt failed. |failed_new_state| is
129 // the new state which the system failed to enter.
130 virtual void OnDisplayModeChangeFailed(ui::OutputState failed_new_state) {}
133 // Interface for classes that make decisions about which output state
135 class StateController {
137 virtual ~StateController() {}
139 // Called when displays are detected.
140 virtual ui::OutputState GetStateForDisplayIds(
141 const std::vector<int64>& display_ids) const = 0;
143 // Queries the resolution (|width|x|height|) in pixels
144 // to select output mode for the given display id.
145 virtual bool GetResolutionForDisplayId(int64 display_id,
147 int* height) const = 0;
150 // Interface for classes that implement software based mirroring.
151 class SoftwareMirroringController {
153 virtual ~SoftwareMirroringController() {}
155 // Called when the hardware mirroring failed.
156 virtual void SetSoftwareMirroring(bool enabled) = 0;
159 // Interface for classes that perform display configuration actions on behalf
160 // of OutputConfigurator.
161 class NativeDisplayDelegate {
163 virtual ~NativeDisplayDelegate() {}
165 // Initializes the XRandR extension, saving the base event ID to
167 virtual void InitXRandRExtension(int* event_base) = 0;
169 // Tells XRandR to update its configuration in response to |event|, an
170 // RRScreenChangeNotify event.
171 virtual void UpdateXRandRConfiguration(const base::NativeEvent& event) = 0;
173 // Grabs the X server and refreshes XRandR-related resources. While
174 // the server is grabbed, other clients are blocked. Must be balanced
175 // by a call to UngrabServer().
176 virtual void GrabServer() = 0;
178 // Ungrabs the server and frees XRandR-related resources.
179 virtual void UngrabServer() = 0;
181 // Flushes all pending requests and waits for replies.
182 virtual void SyncWithServer() = 0;
184 // Sets the window's background color to |color_argb|.
185 virtual void SetBackgroundColor(uint32 color_argb) = 0;
187 // Enables DPMS and forces it to the "on" state.
188 virtual void ForceDPMSOn() = 0;
190 // Returns information about the current outputs. This method may block for
191 // 60 milliseconds or more. The returned outputs are not fully initialized;
192 // the rest of the work happens in
193 // OutputConfigurator::UpdateCachedOutputs().
194 virtual std::vector<OutputSnapshot> GetOutputs() = 0;
196 // Adds |mode| to |output|.
197 virtual void AddOutputMode(RROutput output, RRMode mode) = 0;
199 // Calls XRRSetCrtcConfig() with the given options but some of our default
200 // output count and rotation arguments. Returns true on success.
201 virtual bool ConfigureCrtc(RRCrtc crtc,
207 // Called to set the frame buffer (underlying XRR "screen") size. Has
208 // a side-effect of disabling all CRTCs.
209 virtual void CreateFrameBuffer(
212 const std::vector<OutputConfigurator::OutputSnapshot>& outputs) = 0;
214 // Gets HDCP state of output.
215 virtual bool GetHDCPState(RROutput id, ui::HDCPState* state) = 0;
217 // Sets HDCP state of output.
218 virtual bool SetHDCPState(RROutput id, ui::HDCPState state) = 0;
221 class TouchscreenDelegate {
223 virtual ~TouchscreenDelegate() {}
225 // Searches for touchscreens among input devices,
226 // and tries to match them up to screens in |outputs|.
227 // |outputs| is an array of detected screens.
228 // If a touchscreen with same resolution as an output's native mode
229 // is detected, its id will be stored in this output.
230 virtual void AssociateTouchscreens(
231 std::vector<OutputSnapshot>* outputs) = 0;
233 // Configures XInput's Coordinate Transformation Matrix property.
234 // |touch_device_id| the ID of the touchscreen device to configure.
235 // |ctm| contains the desired transformation parameters. The offsets
236 // in it should be normalized so that 1 corresponds to the X or Y axis
237 // size for the corresponding offset.
238 virtual void ConfigureCTM(int touch_device_id,
239 const CoordinateTransformation& ctm) = 0;
242 // Helper class used by tests.
245 TestApi(OutputConfigurator* configurator, int xrandr_event_base)
246 : configurator_(configurator),
247 xrandr_event_base_(xrandr_event_base) {}
250 const std::vector<OutputSnapshot>& cached_outputs() const {
251 return configurator_->cached_outputs_;
254 // Dispatches an RRScreenChangeNotify event to |configurator_|.
255 void SendScreenChangeEvent();
257 // Dispatches an RRNotify_OutputChange event to |configurator_|.
258 void SendOutputChangeEvent(RROutput output,
263 // If |configure_timer_| is started, stops the timer, runs
264 // ConfigureOutputs(), and returns true; returns false otherwise.
265 bool TriggerConfigureTimeout();
268 OutputConfigurator* configurator_; // not owned
270 int xrandr_event_base_;
272 DISALLOW_COPY_AND_ASSIGN(TestApi);
275 // Flags that can be passed to SetDisplayPower().
276 static const int kSetDisplayPowerNoFlags = 0;
277 // Configure displays even if the passed-in state matches |power_state_|.
278 static const int kSetDisplayPowerForceProbe = 1 << 0;
279 // Do not change the state if multiple displays are connected or if the
280 // only connected display is external.
281 static const int kSetDisplayPowerOnlyIfSingleInternalDisplay = 1 << 1;
283 // Gap between screens so cursor at bottom of active display doesn't
284 // partially appear on top of inactive display. Higher numbers guard
285 // against larger cursors, but also waste more memory.
286 // For simplicity, this is hard-coded to avoid the complexity of always
287 // determining the DPI of the screen and rationalizing which screen we
288 // need to use for the DPI calculation.
289 // See crbug.com/130188 for initial discussion.
290 static const int kVerticalGap = 60;
292 // Returns a pointer to the ModeInfo struct in |output| corresponding to
293 // |mode|, or NULL if the struct isn't present.
294 static const ModeInfo* GetModeInfo(const OutputSnapshot& output,
297 // Returns the mode within |output| that matches the given size with highest
298 // refresh rate. Returns None if no matching output was found.
299 static RRMode FindOutputModeMatchingSize(const OutputSnapshot& output,
303 OutputConfigurator();
304 virtual ~OutputConfigurator();
306 ui::OutputState output_state() const { return output_state_; }
307 DisplayPowerState power_state() const { return power_state_; }
309 void set_state_controller(StateController* controller) {
310 state_controller_ = controller;
312 void set_mirroring_controller(SoftwareMirroringController* controller) {
313 mirroring_controller_ = controller;
316 // Replaces |native_display_delegate_| with |delegate| and sets
317 // |configure_display_| to true. Should be called before Init().
318 void SetNativeDisplayDelegateForTesting(
319 scoped_ptr<NativeDisplayDelegate> delegate);
321 void SetTouchscreenDelegateForTesting(
322 scoped_ptr<TouchscreenDelegate> delegate);
324 // Sets the initial value of |power_state_|. Must be called before Start().
325 void SetInitialDisplayPower(DisplayPowerState power_state);
327 // Initialization, must be called right after constructor.
328 // |is_panel_fitting_enabled| indicates hardware panel fitting support.
329 void Init(bool is_panel_fitting_enabled);
331 // Does initial configuration of displays during startup.
332 // If |background_color_argb| is non zero and there are multiple displays,
333 // OutputConfigurator sets the background color of X's RootWindow to this
335 void Start(uint32 background_color_argb);
337 // Stop handling display configuration events/requests.
340 // Called when powerd notifies us that some set of displays should be turned
341 // on or off. This requires enabling or disabling the CRTC associated with
342 // the display(s) in question so that the low power state is engaged.
343 // |flags| contains bitwise-or-ed kSetDisplayPower* values.
344 bool SetDisplayPower(DisplayPowerState power_state, int flags);
346 // Force switching the display mode to |new_state|. Returns false if
347 // switching failed (possibly because |new_state| is invalid for the
348 // current set of connected outputs).
349 bool SetDisplayMode(ui::OutputState new_state);
351 // Called when an RRNotify event is received. The implementation is
352 // interested in the cases of RRNotify events which correspond to output
353 // add/remove events. Note that Output add/remove events are sent in response
354 // to our own reconfiguration operations so spurious events are common.
355 // Spurious events will have no effect.
356 virtual uint32_t Dispatch(const base::NativeEvent& event) OVERRIDE;
358 // Overridden from base::MessagePumpObserver:
359 virtual base::EventStatus WillProcessEvent(
360 const base::NativeEvent& event) OVERRIDE;
361 virtual void DidProcessEvent(const base::NativeEvent& event) OVERRIDE;
363 void AddObserver(Observer* observer);
364 void RemoveObserver(Observer* observer);
366 // Sets all the displays into pre-suspend mode; usually this means
367 // configure them for their resume state. This allows faster resume on
368 // machines where display configuration is slow.
369 void SuspendDisplays();
371 // Reprobes displays to handle changes made while the system was
373 void ResumeDisplays();
375 const std::map<int, float>& GetMirroredDisplayAreaRatioMap() {
376 return mirrored_display_area_ratio_map_;
379 // Configure outputs with |kConfigureDelayMs| delay,
380 // so that time-consuming ConfigureOutputs() won't be called multiple times.
381 void ScheduleConfigureOutputs();
383 // Registers a client for output protection and requests a client id. Returns
384 // 0 if requesting failed.
385 OutputProtectionClientId RegisterOutputProtectionClient();
387 // Unregisters the client.
388 void UnregisterOutputProtectionClient(OutputProtectionClientId client_id);
390 // Queries link status and protection status.
391 // |link_mask| is the type of connected output links, which is a bitmask of
392 // OutputType values. |protection_mask| is the desired protection methods,
393 // which is a bitmask of the OutputProtectionMethod values.
394 // Returns true on success.
395 bool QueryOutputProtectionStatus(
396 OutputProtectionClientId client_id,
399 uint32_t* protection_mask);
401 // Requests the desired protection methods.
402 // |protection_mask| is the desired protection methods, which is a bitmask
403 // of the OutputProtectionMethod values.
404 // Returns true when the protection request has been made.
405 bool EnableOutputProtection(
406 OutputProtectionClientId client_id,
408 uint32_t desired_protection_mask);
411 // Mapping a display_id to a protection request bitmask.
412 typedef std::map<int64, uint32_t> DisplayProtections;
413 // Mapping a client to its protection request.
414 typedef std::map<OutputProtectionClientId,
415 DisplayProtections> ProtectionRequests;
417 // Updates |cached_outputs_| to contain currently-connected outputs. Calls
418 // |delegate_->GetOutputs()| and then does additional work, like finding the
419 // mirror mode and setting user-preferred modes. Note that the server must be
420 // grabbed via |delegate_->GrabServer()| first.
421 void UpdateCachedOutputs();
423 // Helper method for UpdateCachedOutputs() that initializes the passed-in
424 // outputs' |mirror_mode| fields by looking for a mode in |internal_output|
425 // and |external_output| having the same resolution. Returns false if a shared
426 // mode wasn't found or created.
428 // |try_panel_fitting| allows creating a panel-fitting mode for
429 // |internal_output| instead of only searching for a matching mode (note that
430 // it may lead to a crash if |internal_info| is not capable of panel fitting).
432 // |preserve_aspect| limits the search/creation only to the modes having the
433 // native aspect ratio of |external_output|.
434 bool FindMirrorMode(OutputSnapshot* internal_output,
435 OutputSnapshot* external_output,
436 bool try_panel_fitting,
437 bool preserve_aspect);
439 // Configures outputs.
440 void ConfigureOutputs();
442 // Notifies observers about an attempted state change.
443 void NotifyObservers(bool success, ui::OutputState attempted_state);
445 // Switches to the state specified in |output_state| and |power_state|.
446 // If the hardware mirroring failed and |mirroring_controller_| is set,
447 // it switches to |STATE_DUAL_EXTENDED| and calls |SetSoftwareMirroring()|
448 // to enable software based mirroring.
449 // On success, updates |output_state_|, |power_state_|, and |cached_outputs_|
451 bool EnterStateOrFallBackToSoftwareMirroring(ui::OutputState output_state,
452 DisplayPowerState power_state);
454 // Switches to the state specified in |output_state| and |power_state|.
455 // On success, updates |output_state_|, |power_state_|, and
456 // |cached_outputs_| and returns true.
457 bool EnterState(ui::OutputState output_state, DisplayPowerState power_state);
459 // Returns the output state that should be used with |cached_outputs_| while
461 ui::OutputState ChooseOutputState(DisplayPowerState power_state) const;
463 // Computes the relevant transformation for mirror mode.
464 // |output| is the output on which mirror mode is being applied.
465 // Returns the transformation or identity if computations fail.
466 CoordinateTransformation GetMirrorModeCTM(
467 const OutputConfigurator::OutputSnapshot& output);
469 // Computes the relevant transformation for extended mode.
470 // |output| is the output on which extended mode is being applied.
471 // |width| and |height| are the width and height of the combined framebuffer.
472 // Returns the transformation or identity if computations fail.
473 CoordinateTransformation GetExtendedModeCTM(
474 const OutputConfigurator::OutputSnapshot& output,
475 int framebuffer_width,
476 int frame_buffer_height);
478 // Returns the ratio between mirrored mode area and native mode area:
479 // (mirror_mode_width * mirrow_mode_height) / (native_width * native_height)
480 float GetMirroredDisplayAreaRatio(
481 const OutputConfigurator::OutputSnapshot& output);
483 // Applies output protections according to requests.
484 bool ApplyProtections(const DisplayProtections& requests);
486 StateController* state_controller_;
487 SoftwareMirroringController* mirroring_controller_;
488 scoped_ptr<NativeDisplayDelegate> native_display_delegate_;
489 scoped_ptr<TouchscreenDelegate> touchscreen_delegate_;
491 // Used to enable modes which rely on panel fitting.
492 bool is_panel_fitting_enabled_;
494 // Key of the map is the touch display's id, and the value of the map is the
495 // touch display's area ratio in mirror mode defined as :
496 // mirror_mode_area / native_mode_area.
497 // This is used for scaling touch event's radius when the touch display is in
499 // new_touch_radius = sqrt(area_ratio) * old_touch_radius
500 std::map<int, float> mirrored_display_area_ratio_map_;
502 // This is detected by the constructor to determine whether or not we should
503 // be enabled. If we aren't running on ChromeOS, we can't assume that the
504 // Xrandr X11 extension is supported.
505 // If this flag is set to false, any attempts to change the output
506 // configuration to immediately fail without changing the state.
507 bool configure_display_;
509 // The base of the event numbers used to represent XRandr events used in
510 // decoding events regarding output add/remove.
511 int xrandr_event_base_;
513 // The current display state.
514 ui::OutputState output_state_;
516 // The current power state.
517 DisplayPowerState power_state_;
519 // Most-recently-used output configuration. Note that the actual
520 // configuration changes asynchronously.
521 std::vector<OutputSnapshot> cached_outputs_;
523 ObserverList<Observer> observers_;
525 // The timer to delay configuring outputs. See also the comments in
527 scoped_ptr<base::OneShotTimer<OutputConfigurator> > configure_timer_;
529 // Id for next output protection client.
530 OutputProtectionClientId next_output_protection_client_id_;
532 // Output protection requests of each client.
533 ProtectionRequests client_protection_requests_;
535 DISALLOW_COPY_AND_ASSIGN(OutputConfigurator);
538 typedef std::vector<OutputConfigurator::OutputSnapshot> OutputSnapshotList;
540 } // namespace chromeos
542 #endif // CHROMEOS_DISPLAY_OUTPUT_CONFIGURATOR_H_