Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / chromeos / display / output_configurator.h
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.
4
5 #ifndef CHROMEOS_DISPLAY_OUTPUT_CONFIGURATOR_H_
6 #define CHROMEOS_DISPLAY_OUTPUT_CONFIGURATOR_H_
7
8 #include <map>
9 #include <string>
10 #include <vector>
11
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"
22
23 // Forward declarations for Xlib and Xrandr.
24 // This is so unused X definitions don't pollute the namespace.
25 typedef unsigned long XID;
26 typedef XID RROutput;
27 typedef XID RRCrtc;
28 typedef XID RRMode;
29
30 namespace chromeos {
31
32 // This class interacts directly with the underlying Xrandr API to manipulate
33 // CTRCs and Outputs.
34 class CHROMEOS_EXPORT OutputConfigurator
35     : public base::MessagePumpDispatcher,
36       public base::MessagePumpObserver {
37  public:
38   typedef uint64_t OutputProtectionClientId;
39   static const OutputProtectionClientId kInvalidClientId = 0;
40
41   struct ModeInfo {
42     ModeInfo();
43     ModeInfo(int width, int height, bool interlaced, float refresh_rate);
44
45     int width;
46     int height;
47     bool interlaced;
48     float refresh_rate;
49   };
50
51   typedef std::map<RRMode, ModeInfo> ModeInfoMap;
52
53   struct CoordinateTransformation {
54     // Initialized to the identity transformation.
55     CoordinateTransformation();
56
57     float x_scale;
58     float x_offset;
59     float y_scale;
60     float y_offset;
61   };
62
63   // Information about an output's current state.
64   struct OutputSnapshot {
65     OutputSnapshot();
66     ~OutputSnapshot();
67
68     RROutput output;
69
70     // CRTC that should be used for this output. Not necessarily the CRTC
71     // that XRandR reports is currently being used.
72     RRCrtc crtc;
73
74     // Mode currently being used by the output.
75     RRMode current_mode;
76
77     // "Best" mode supported by the output.
78     RRMode native_mode;
79
80     // Mode used when displaying the same desktop on multiple outputs.
81     RRMode mirror_mode;
82
83     // User-selected mode for the output.
84     RRMode selected_mode;
85
86     // Output's origin on the framebuffer.
87     int x;
88     int y;
89
90     // Output's physical dimensions.
91     uint64 width_mm;
92     uint64 height_mm;
93
94     bool is_aspect_preserving_scaling;
95
96     // The type of output.
97     ui::OutputType type;
98
99     // Map from mode IDs to details about the corresponding modes.
100     ModeInfoMap mode_infos;
101
102     // XInput device ID or 0 if this output isn't a touchscreen.
103     int touch_device_id;
104
105     CoordinateTransformation transform;
106
107     // Display id for this output.
108     int64 display_id;
109
110     bool has_display_id;
111
112     // This output's index in the array returned by XRandR. Stable even as
113     // outputs are connected or disconnected.
114     int index;
115   };
116
117   class Observer {
118    public:
119     virtual ~Observer() {}
120
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
124     // already.
125     virtual void OnDisplayModeChanged(
126         const std::vector<OutputSnapshot>& outputs) {}
127
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) {}
131   };
132
133   // Interface for classes that make decisions about which output state
134   // should be used.
135   class StateController {
136    public:
137     virtual ~StateController() {}
138
139     // Called when displays are detected.
140     virtual ui::OutputState GetStateForDisplayIds(
141         const std::vector<int64>& display_ids) const = 0;
142
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,
146                                            int* width,
147                                            int* height) const = 0;
148   };
149
150   // Interface for classes that implement software based mirroring.
151   class SoftwareMirroringController {
152    public:
153     virtual ~SoftwareMirroringController() {}
154
155     // Called when the hardware mirroring failed.
156     virtual void SetSoftwareMirroring(bool enabled) = 0;
157   };
158
159   // Interface for classes that perform display configuration actions on behalf
160   // of OutputConfigurator.
161   class NativeDisplayDelegate {
162    public:
163     virtual ~NativeDisplayDelegate() {}
164
165     // Initializes the XRandR extension, saving the base event ID to
166     // |event_base|.
167     virtual void InitXRandRExtension(int* event_base) = 0;
168
169     // Tells XRandR to update its configuration in response to |event|, an
170     // RRScreenChangeNotify event.
171     virtual void UpdateXRandRConfiguration(const base::NativeEvent& event) = 0;
172
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;
177
178     // Ungrabs the server and frees XRandR-related resources.
179     virtual void UngrabServer() = 0;
180
181     // Flushes all pending requests and waits for replies.
182     virtual void SyncWithServer() = 0;
183
184     // Sets the window's background color to |color_argb|.
185     virtual void SetBackgroundColor(uint32 color_argb) = 0;
186
187     // Enables DPMS and forces it to the "on" state.
188     virtual void ForceDPMSOn() = 0;
189
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;
195
196     // Adds |mode| to |output|.
197     virtual void AddOutputMode(RROutput output, RRMode mode) = 0;
198
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,
202                                RRMode mode,
203                                RROutput output,
204                                int x,
205                                int y) = 0;
206
207     // Called to set the frame buffer (underlying XRR "screen") size.  Has
208     // a side-effect of disabling all CRTCs.
209     virtual void CreateFrameBuffer(
210         int width,
211         int height,
212         const std::vector<OutputConfigurator::OutputSnapshot>& outputs) = 0;
213
214     // Gets HDCP state of output.
215     virtual bool GetHDCPState(RROutput id, ui::HDCPState* state) = 0;
216
217     // Sets HDCP state of output.
218     virtual bool SetHDCPState(RROutput id, ui::HDCPState state) = 0;
219   };
220
221   class TouchscreenDelegate {
222    public:
223     virtual ~TouchscreenDelegate() {}
224
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;
232
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;
240   };
241
242   // Helper class used by tests.
243   class TestApi {
244    public:
245     TestApi(OutputConfigurator* configurator, int xrandr_event_base)
246         : configurator_(configurator),
247           xrandr_event_base_(xrandr_event_base) {}
248     ~TestApi() {}
249
250     const std::vector<OutputSnapshot>& cached_outputs() const {
251       return configurator_->cached_outputs_;
252     }
253
254     // Dispatches an RRScreenChangeNotify event to |configurator_|.
255     void SendScreenChangeEvent();
256
257     // Dispatches an RRNotify_OutputChange event to |configurator_|.
258     void SendOutputChangeEvent(RROutput output,
259                                RRCrtc crtc,
260                                RRMode mode,
261                                bool connected);
262
263     // If |configure_timer_| is started, stops the timer, runs
264     // ConfigureOutputs(), and returns true; returns false otherwise.
265     bool TriggerConfigureTimeout();
266
267    private:
268     OutputConfigurator* configurator_;  // not owned
269
270     int xrandr_event_base_;
271
272     DISALLOW_COPY_AND_ASSIGN(TestApi);
273   };
274
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;
282
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;
291
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,
295                                      RRMode mode);
296
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,
300                                            int width,
301                                            int height);
302
303   OutputConfigurator();
304   virtual ~OutputConfigurator();
305
306   ui::OutputState output_state() const { return output_state_; }
307   DisplayPowerState power_state() const { return power_state_; }
308
309   void set_state_controller(StateController* controller) {
310     state_controller_ = controller;
311   }
312   void set_mirroring_controller(SoftwareMirroringController* controller) {
313     mirroring_controller_ = controller;
314   }
315
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);
320
321   void SetTouchscreenDelegateForTesting(
322       scoped_ptr<TouchscreenDelegate> delegate);
323
324   // Sets the initial value of |power_state_|.  Must be called before Start().
325   void SetInitialDisplayPower(DisplayPowerState power_state);
326
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);
330
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
334   // color.
335   void Start(uint32 background_color_argb);
336
337   // Stop handling display configuration events/requests.
338   void Stop();
339
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);
345
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);
350
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;
357
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;
362
363   void AddObserver(Observer* observer);
364   void RemoveObserver(Observer* observer);
365
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();
370
371   // Reprobes displays to handle changes made while the system was
372   // suspended.
373   void ResumeDisplays();
374
375   const std::map<int, float>& GetMirroredDisplayAreaRatioMap() {
376     return mirrored_display_area_ratio_map_;
377   }
378
379   // Configure outputs with |kConfigureDelayMs| delay,
380   // so that time-consuming ConfigureOutputs() won't be called multiple times.
381   void ScheduleConfigureOutputs();
382
383   // Registers a client for output protection and requests a client id. Returns
384   // 0 if requesting failed.
385   OutputProtectionClientId RegisterOutputProtectionClient();
386
387   // Unregisters the client.
388   void UnregisterOutputProtectionClient(OutputProtectionClientId client_id);
389
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,
397       int64 display_id,
398       uint32_t* link_mask,
399       uint32_t* protection_mask);
400
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,
407       int64 display_id,
408       uint32_t desired_protection_mask);
409
410  private:
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;
416
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();
422
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.
427   //
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).
431   //
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);
438
439   // Configures outputs.
440   void ConfigureOutputs();
441
442   // Notifies observers about an attempted state change.
443   void NotifyObservers(bool success, ui::OutputState attempted_state);
444
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_|
450   // and returns true.
451   bool EnterStateOrFallBackToSoftwareMirroring(ui::OutputState output_state,
452                                                DisplayPowerState power_state);
453
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);
458
459   // Returns the output state that should be used with |cached_outputs_| while
460   // in |power_state|.
461   ui::OutputState ChooseOutputState(DisplayPowerState power_state) const;
462
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);
468
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);
477
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);
482
483   // Applies output protections according to requests.
484   bool ApplyProtections(const DisplayProtections& requests);
485
486   StateController* state_controller_;
487   SoftwareMirroringController* mirroring_controller_;
488   scoped_ptr<NativeDisplayDelegate> native_display_delegate_;
489   scoped_ptr<TouchscreenDelegate> touchscreen_delegate_;
490
491   // Used to enable modes which rely on panel fitting.
492   bool is_panel_fitting_enabled_;
493
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
498   // mirror mode :
499   // new_touch_radius = sqrt(area_ratio) * old_touch_radius
500   std::map<int, float> mirrored_display_area_ratio_map_;
501
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_;
508
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_;
512
513   // The current display state.
514   ui::OutputState output_state_;
515
516   // The current power state.
517   DisplayPowerState power_state_;
518
519   // Most-recently-used output configuration. Note that the actual
520   // configuration changes asynchronously.
521   std::vector<OutputSnapshot> cached_outputs_;
522
523   ObserverList<Observer> observers_;
524
525   // The timer to delay configuring outputs. See also the comments in
526   // Dispatch().
527   scoped_ptr<base::OneShotTimer<OutputConfigurator> > configure_timer_;
528
529   // Id for next output protection client.
530   OutputProtectionClientId next_output_protection_client_id_;
531
532   // Output protection requests of each client.
533   ProtectionRequests client_protection_requests_;
534
535   DISALLOW_COPY_AND_ASSIGN(OutputConfigurator);
536 };
537
538 typedef std::vector<OutputConfigurator::OutputSnapshot> OutputSnapshotList;
539
540 }  // namespace chromeos
541
542 #endif  // CHROMEOS_DISPLAY_OUTPUT_CONFIGURATOR_H_