1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.hardware.display;
18 
19 import android.annotation.Nullable;
20 import android.graphics.Point;
21 import android.hardware.SensorManager;
22 import android.os.Handler;
23 import android.os.PowerManager;
24 import android.util.IntArray;
25 import android.util.SparseArray;
26 import android.view.Display;
27 import android.view.DisplayInfo;
28 import android.view.SurfaceControl;
29 import android.view.SurfaceControl.Transaction;
30 
31 /**
32  * Display manager local system service interface.
33  *
34  * @hide Only for use within the system server.
35  */
36 public abstract class DisplayManagerInternal {
37     /**
38      * Called by the power manager to initialize power management facilities.
39      */
initPowerManagement(DisplayPowerCallbacks callbacks, Handler handler, SensorManager sensorManager)40     public abstract void initPowerManagement(DisplayPowerCallbacks callbacks,
41             Handler handler, SensorManager sensorManager);
42 
43     /**
44      * Called by the power manager to request a new power state.
45      * <p>
46      * The display power controller makes a copy of the provided object and then
47      * begins adjusting the power state to match what was requested.
48      * </p>
49      *
50      * @param request The requested power state.
51      * @param waitForNegativeProximity If true, issues a request to wait for
52      * negative proximity before turning the screen back on, assuming the screen
53      * was turned off by the proximity sensor.
54      * @return True if display is ready, false if there are important changes that must
55      * be made asynchronously (such as turning the screen on), in which case the caller
56      * should grab a wake lock, watch for {@link DisplayPowerCallbacks#onStateChanged()}
57      * then try the request again later until the state converges.
58      */
requestPowerState(DisplayPowerRequest request, boolean waitForNegativeProximity)59     public abstract boolean requestPowerState(DisplayPowerRequest request,
60             boolean waitForNegativeProximity);
61 
62     /**
63      * Returns true if the proximity sensor screen-off function is available.
64      */
isProximitySensorAvailable()65     public abstract boolean isProximitySensorAvailable();
66 
67     /**
68      * Screenshot for internal system-only use such as rotation, etc.  This method includes
69      * secure layers and the result should never be exposed to non-system applications.
70      * This method does not apply any rotation and provides the output in natural orientation.
71      *
72      * @param displayId The display id to take the screenshot of.
73      * @return The buffer or null if we have failed.
74      */
systemScreenshot(int displayId)75     public abstract SurfaceControl.ScreenshotGraphicBuffer systemScreenshot(int displayId);
76 
77     /**
78      * General screenshot functionality that excludes secure layers and applies appropriate
79      * rotation that the device is currently in.
80      *
81      * @param displayId The display id to take the screenshot of.
82      * @return The buffer or null if we have failed.
83      */
userScreenshot(int displayId)84     public abstract SurfaceControl.ScreenshotGraphicBuffer userScreenshot(int displayId);
85 
86     /**
87      * Returns information about the specified logical display.
88      *
89      * @param displayId The logical display id.
90      * @return The logical display info, or null if the display does not exist.  The
91      * returned object must be treated as immutable.
92      */
getDisplayInfo(int displayId)93     public abstract DisplayInfo getDisplayInfo(int displayId);
94 
95     /**
96      * Returns the position of the display's projection.
97      *
98      * @param displayId The logical display id.
99      * @return The x, y coordinates of the display, or null if the display does not exist. The
100      * return object must be treated as immutable.
101      */
102     @Nullable
getDisplayPosition(int displayId)103     public abstract Point getDisplayPosition(int displayId);
104 
105     /**
106      * Registers a display transaction listener to provide the client a chance to
107      * update its surfaces within the same transaction as any display layout updates.
108      *
109      * @param listener The listener to register.
110      */
registerDisplayTransactionListener(DisplayTransactionListener listener)111     public abstract void registerDisplayTransactionListener(DisplayTransactionListener listener);
112 
113     /**
114      * Unregisters a display transaction listener to provide the client a chance to
115      * update its surfaces within the same transaction as any display layout updates.
116      *
117      * @param listener The listener to unregister.
118      */
unregisterDisplayTransactionListener(DisplayTransactionListener listener)119     public abstract void unregisterDisplayTransactionListener(DisplayTransactionListener listener);
120 
121     /**
122      * Overrides the display information of a particular logical display.
123      * This is used by the window manager to control the size and characteristics
124      * of the default display.  It is expected to apply the requested change
125      * to the display information synchronously so that applications will immediately
126      * observe the new state.
127      *
128      * NOTE: This method must be the only entry point by which the window manager
129      * influences the logical configuration of displays.
130      *
131      * @param displayId The logical display id.
132      * @param info The new data to be stored.
133      */
setDisplayInfoOverrideFromWindowManager( int displayId, DisplayInfo info)134     public abstract void setDisplayInfoOverrideFromWindowManager(
135             int displayId, DisplayInfo info);
136 
137     /**
138      * Get current display info without override from WindowManager.
139      * Current implementation of LogicalDisplay#getDisplayInfoLocked() always returns display info
140      * with overrides from WM if set. This method can be used for getting real display size without
141      * overrides to determine if real changes to display metrics happened.
142      * @param displayId Id of the target display.
143      * @param outInfo {@link DisplayInfo} to fill.
144      */
getNonOverrideDisplayInfo(int displayId, DisplayInfo outInfo)145     public abstract void getNonOverrideDisplayInfo(int displayId, DisplayInfo outInfo);
146 
147     /**
148      * Called by the window manager to perform traversals while holding a
149      * surface flinger transaction.
150      */
performTraversal(Transaction t)151     public abstract void performTraversal(Transaction t);
152 
153     /**
154      * Tells the display manager about properties of the display that depend on the windows on it.
155      * This includes whether there is interesting unique content on the specified logical display,
156      * and whether the one of the windows has a preferred refresh rate.
157      * <p>
158      * If the display has unique content, then the display manager arranges for it
159      * to be presented on a physical display if appropriate.  Otherwise, the display manager
160      * may choose to make the physical display mirror some other logical display.
161      * </p>
162      *
163      * <p>
164      * If one of the windows on the display has a preferred refresh rate that's supported by the
165      * display, then the display manager will request its use.
166      * </p>
167      *
168      * @param displayId The logical display id to update.
169      * @param hasContent True if the logical display has content. This is used to control automatic
170      * mirroring.
171      * @param requestedRefreshRate The preferred refresh rate for the top-most visible window that
172      * has a preference.
173      * @param requestedModeId The preferred mode id for the top-most visible window that has a
174      * preference.
175      * @param requestedMinimalPostProcessing The preferred minimal post processing setting for the
176      * display. This is true when there is at least one visible window that wants minimal post
177      * processng on.
178      * @param inTraversal True if called from WindowManagerService during a window traversal
179      * prior to call to performTraversalInTransactionFromWindowManager.
180      */
setDisplayProperties(int displayId, boolean hasContent, float requestedRefreshRate, int requestedModeId, boolean requestedMinimalPostProcessing, boolean inTraversal)181     public abstract void setDisplayProperties(int displayId, boolean hasContent,
182             float requestedRefreshRate, int requestedModeId, boolean requestedMinimalPostProcessing,
183             boolean inTraversal);
184 
185     /**
186      * Applies an offset to the contents of a display, for example to avoid burn-in.
187      * <p>
188      * TODO: Technically this should be associated with a physical rather than logical
189      * display but this is good enough for now.
190      * </p>
191      *
192      * @param displayId The logical display id to update.
193      * @param x The X offset by which to shift the contents of the display.
194      * @param y The Y offset by which to shift the contents of the display.
195      */
setDisplayOffsets(int displayId, int x, int y)196     public abstract void setDisplayOffsets(int displayId, int x, int y);
197 
198     /**
199      * Disables scaling for a display.
200      *
201      * @param displayId The logical display id to disable scaling for.
202      * @param disableScaling {@code true} to disable scaling,
203      * {@code false} to use the default scaling behavior of the logical display.
204      */
setDisplayScalingDisabled(int displayId, boolean disableScaling)205     public abstract void setDisplayScalingDisabled(int displayId, boolean disableScaling);
206 
207     /**
208      * Provide a list of UIDs that are present on the display and are allowed to access it.
209      *
210      * @param displayAccessUIDs Mapping displayId -> int array of UIDs.
211      */
setDisplayAccessUIDs(SparseArray<IntArray> displayAccessUIDs)212     public abstract void setDisplayAccessUIDs(SparseArray<IntArray> displayAccessUIDs);
213 
214     /**
215      * Persist brightness slider events and ambient brightness stats.
216      */
persistBrightnessTrackerState()217     public abstract void persistBrightnessTrackerState();
218 
219     /**
220      * Notifies the display manager that resource overlays have changed.
221      */
onOverlayChanged()222     public abstract void onOverlayChanged();
223 
224     /**
225      * Get the attributes available for display color sampling.
226      * @param displayId id of the display to collect the sample from.
227      *
228      * @return The attributes the display supports, or null if sampling is not supported.
229      */
230     @Nullable
getDisplayedContentSamplingAttributes( int displayId)231     public abstract DisplayedContentSamplingAttributes getDisplayedContentSamplingAttributes(
232             int displayId);
233 
234     /**
235      * Enable or disable the collection of color samples.
236      *
237      * @param displayId id of the display to collect the sample from.
238      * @param componentMask a bitmask of the color channels to collect samples for, or zero for all
239      *                      available.
240      * @param maxFrames maintain a ringbuffer of the last maxFrames.
241      * @param enable True to enable, False to disable.
242      *
243      * @return True if sampling was enabled, false if failure.
244      */
setDisplayedContentSamplingEnabled( int displayId, boolean enable, int componentMask, int maxFrames)245     public abstract boolean setDisplayedContentSamplingEnabled(
246             int displayId, boolean enable, int componentMask, int maxFrames);
247 
248     /**
249      * Accesses the color histogram statistics of displayed frames on devices that support sampling.
250      *
251      * @param displayId id of the display to collect the sample from
252      * @param maxFrames limit the statistics to the last maxFrames number of frames.
253      * @param timestamp discard statistics that were collected prior to timestamp, where timestamp
254      *                  is given as CLOCK_MONOTONIC.
255      * @return The statistics representing a histogram of the color distribution of the frames
256      *         displayed on-screen, or null if sampling is not supported.
257     */
258     @Nullable
getDisplayedContentSample( int displayId, long maxFrames, long timestamp)259     public abstract DisplayedContentSample getDisplayedContentSample(
260             int displayId, long maxFrames, long timestamp);
261 
262     /**
263      * Describes the requested power state of the display.
264      *
265      * This object is intended to describe the general characteristics of the
266      * power state, such as whether the screen should be on or off and the current
267      * brightness controls leaving the DisplayPowerController to manage the
268      * details of how the transitions between states should occur.  The goal is for
269      * the PowerManagerService to focus on the global power state and not
270      * have to micro-manage screen off animations, auto-brightness and other effects.
271      */
272     public static final class DisplayPowerRequest {
273         // Policy: Turn screen off as if the user pressed the power button
274         // including playing a screen off animation if applicable.
275         public static final int POLICY_OFF = 0;
276         // Policy: Enable dozing and always-on display functionality.
277         public static final int POLICY_DOZE = 1;
278         // Policy: Make the screen dim when the user activity timeout is
279         // about to expire.
280         public static final int POLICY_DIM = 2;
281         // Policy: Make the screen bright as usual.
282         public static final int POLICY_BRIGHT = 3;
283         // Policy: Keep the screen and display optimized for VR mode.
284         public static final int POLICY_VR = 4;
285 
286         // The basic overall policy to apply: off, doze, dim or bright.
287         public int policy;
288 
289         // If true, the proximity sensor overrides the screen state when an object is
290         // nearby, turning it off temporarily until the object is moved away.
291         public boolean useProximitySensor;
292 
293         // An override of the screen brightness.
294         // Set to PowerManager.BRIGHTNESS_INVALID if there's no override.
295         public float screenBrightnessOverride;
296 
297         // An override of the screen auto-brightness adjustment factor in the range -1 (dimmer) to
298         // 1 (brighter). Set to Float.NaN if there's no override.
299         public float screenAutoBrightnessAdjustmentOverride;
300 
301         // If true, enables automatic brightness control.
302         public boolean useAutoBrightness;
303 
304         // If true, scales the brightness to a fraction of desired (as defined by
305         // screenLowPowerBrightnessFactor).
306         public boolean lowPowerMode;
307 
308         // The factor to adjust the screen brightness in low power mode in the range
309         // 0 (screen off) to 1 (no change)
310         public float screenLowPowerBrightnessFactor;
311 
312         // If true, applies a brightness boost.
313         public boolean boostScreenBrightness;
314 
315         // If true, prevents the screen from completely turning on if it is currently off.
316         // The display does not enter a "ready" state if this flag is true and screen on is
317         // blocked.  The window manager policy blocks screen on while it prepares the keyguard to
318         // prevent the user from seeing intermediate updates.
319         //
320         // Technically, we may not block the screen itself from turning on (because that introduces
321         // extra unnecessary latency) but we do prevent content on screen from becoming
322         // visible to the user.
323         public boolean blockScreenOn;
324 
325         // Overrides the policy for adjusting screen brightness and state while dozing.
326         public int dozeScreenState;
327         public float dozeScreenBrightness;
328 
DisplayPowerRequest()329         public DisplayPowerRequest() {
330             policy = POLICY_BRIGHT;
331             useProximitySensor = false;
332             screenBrightnessOverride = PowerManager.BRIGHTNESS_INVALID_FLOAT;
333             useAutoBrightness = false;
334             screenAutoBrightnessAdjustmentOverride = Float.NaN;
335             screenLowPowerBrightnessFactor = 0.5f;
336             blockScreenOn = false;
337             dozeScreenBrightness = PowerManager.BRIGHTNESS_INVALID_FLOAT;
338             dozeScreenState = Display.STATE_UNKNOWN;
339         }
340 
DisplayPowerRequest(DisplayPowerRequest other)341         public DisplayPowerRequest(DisplayPowerRequest other) {
342             copyFrom(other);
343         }
344 
isBrightOrDim()345         public boolean isBrightOrDim() {
346             return policy == POLICY_BRIGHT || policy == POLICY_DIM;
347         }
348 
isVr()349         public boolean isVr() {
350             return policy == POLICY_VR;
351         }
352 
copyFrom(DisplayPowerRequest other)353         public void copyFrom(DisplayPowerRequest other) {
354             policy = other.policy;
355             useProximitySensor = other.useProximitySensor;
356             screenBrightnessOverride = other.screenBrightnessOverride;
357             useAutoBrightness = other.useAutoBrightness;
358             screenAutoBrightnessAdjustmentOverride = other.screenAutoBrightnessAdjustmentOverride;
359             screenLowPowerBrightnessFactor = other.screenLowPowerBrightnessFactor;
360             blockScreenOn = other.blockScreenOn;
361             lowPowerMode = other.lowPowerMode;
362             boostScreenBrightness = other.boostScreenBrightness;
363             dozeScreenBrightness = other.dozeScreenBrightness;
364             dozeScreenState = other.dozeScreenState;
365         }
366 
367         @Override
equals(Object o)368         public boolean equals(Object o) {
369             return o instanceof DisplayPowerRequest
370                     && equals((DisplayPowerRequest)o);
371         }
372 
equals(DisplayPowerRequest other)373         public boolean equals(DisplayPowerRequest other) {
374             return other != null
375                     && policy == other.policy
376                     && useProximitySensor == other.useProximitySensor
377                     && floatEquals(screenBrightnessOverride,
378                             other.screenBrightnessOverride)
379                     && useAutoBrightness == other.useAutoBrightness
380                     && floatEquals(screenAutoBrightnessAdjustmentOverride,
381                             other.screenAutoBrightnessAdjustmentOverride)
382                     && screenLowPowerBrightnessFactor
383                     == other.screenLowPowerBrightnessFactor
384                     && blockScreenOn == other.blockScreenOn
385                     && lowPowerMode == other.lowPowerMode
386                     && boostScreenBrightness == other.boostScreenBrightness
387                     && floatEquals(dozeScreenBrightness, other.dozeScreenBrightness)
388                     && dozeScreenState == other.dozeScreenState;
389         }
390 
floatEquals(float f1, float f2)391         private boolean floatEquals(float f1, float f2) {
392             return f1 == f2 || Float.isNaN(f1) && Float.isNaN(f2);
393         }
394 
395         @Override
hashCode()396         public int hashCode() {
397             return 0; // don't care
398         }
399 
400         @Override
toString()401         public String toString() {
402             return "policy=" + policyToString(policy)
403                     + ", useProximitySensor=" + useProximitySensor
404                     + ", screenBrightnessOverride=" + screenBrightnessOverride
405                     + ", useAutoBrightness=" + useAutoBrightness
406                     + ", screenAutoBrightnessAdjustmentOverride="
407                     + screenAutoBrightnessAdjustmentOverride
408                     + ", screenLowPowerBrightnessFactor=" + screenLowPowerBrightnessFactor
409                     + ", blockScreenOn=" + blockScreenOn
410                     + ", lowPowerMode=" + lowPowerMode
411                     + ", boostScreenBrightness=" + boostScreenBrightness
412                     + ", dozeScreenBrightness=" + dozeScreenBrightness
413                     + ", dozeScreenState=" + Display.stateToString(dozeScreenState);
414         }
415 
policyToString(int policy)416         public static String policyToString(int policy) {
417             switch (policy) {
418                 case POLICY_OFF:
419                     return "OFF";
420                 case POLICY_DOZE:
421                     return "DOZE";
422                 case POLICY_DIM:
423                     return "DIM";
424                 case POLICY_BRIGHT:
425                     return "BRIGHT";
426                 case POLICY_VR:
427                     return "VR";
428                 default:
429                     return Integer.toString(policy);
430             }
431         }
432     }
433 
434     /**
435      * Asynchronous callbacks from the power controller to the power manager service.
436      */
437     public interface DisplayPowerCallbacks {
onStateChanged()438         void onStateChanged();
onProximityPositive()439         void onProximityPositive();
onProximityNegative()440         void onProximityNegative();
onDisplayStateChange(int state)441         void onDisplayStateChange(int state); // one of the Display state constants
442 
acquireSuspendBlocker()443         void acquireSuspendBlocker();
releaseSuspendBlocker()444         void releaseSuspendBlocker();
445     }
446 
447     /**
448      * Called within a Surface transaction whenever the size or orientation of a
449      * display may have changed.  Provides an opportunity for the client to
450      * update the position of its surfaces as part of the same transaction.
451      */
452     public interface DisplayTransactionListener {
onDisplayTransaction(Transaction t)453         void onDisplayTransaction(Transaction t);
454     }
455 }
456