Debian Codegraph @

core/java/android/hardware/display/DisplayManagerGlobal.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2012 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
20 import static android.hardware.display.DisplayManager.EventsMask;
21 import static android.view.Display.HdrCapabilities.HdrType;
22
23 import android.annotation.IntDef;
24 import android.annotation.NonNull;
25 import android.annotation.Nullable;
26 import android.app.PropertyInvalidatedCache;
27 import android.compat.annotation.UnsupportedAppUsage;
28 import android.content.Context;
29 import android.content.pm.ParceledListSlice;
30 import android.content.res.Resources;
31 import android.graphics.ColorSpace;
32 import android.graphics.Point;
33 import android.hardware.display.DisplayManager.DisplayListener;
34 import android.hardware.graphics.common.DisplayDecorationSupport;
35 import android.media.projection.IMediaProjection;
36 import android.media.projection.MediaProjection;
37 import android.os.Handler;
38 import android.os.IBinder;
39 import android.os.Looper;
40 import android.os.Message;
41 import android.os.RemoteException;
42 import android.os.ServiceManager;
43 import android.util.Log;
44 import android.util.Pair;
45 import android.util.SparseArray;
46 import android.view.Display;
47 import android.view.DisplayAdjustments;
48 import android.view.DisplayInfo;
49 import android.view.Surface;
50
51 import com.android.internal.annotations.VisibleForTesting;
52
53 import java.lang.annotation.Retention;
54 import java.lang.annotation.RetentionPolicy;
55 import java.util.ArrayList;
56 import java.util.Collections;
57 import java.util.List;
58 import java.util.Objects;
59 import java.util.concurrent.Executor;
60
61 /**
62 * Manager communication with the display manager service on behalf of
63 * an application process. You're probably looking for {@link DisplayManager}.
64 *
65 * @hide
66 */
67 public final class DisplayManagerGlobal {
68 private static final String TAG = "DisplayManager";
69 private static final boolean DEBUG = false;
70
71 // True if display info and display ids should be cached.
72 //
73 // FIXME: The cache is currently disabled because it's unclear whether we have the
74 // necessary guarantees that the caches will always be flushed before clients
75 // attempt to observe their new state. For example, depending on the order
76 // in which the binder transactions take place, we might have a problem where
77 // an application could start processing a configuration change due to a display
78 // orientation change before the display info cache has actually been invalidated.
79 private static final boolean USE_CACHE = false;
80
81 @IntDef(prefix = {"SWITCHING_TYPE_"}, value = {
82 EVENT_DISPLAY_ADDED,
83 EVENT_DISPLAY_CHANGED,
84 EVENT_DISPLAY_REMOVED,
85 EVENT_DISPLAY_BRIGHTNESS_CHANGED
86 })
87 @Retention(RetentionPolicy.SOURCE)
88 public @interface DisplayEvent {}
89
90 public static final int EVENT_DISPLAY_ADDED = 1;
91 public static final int EVENT_DISPLAY_CHANGED = 2;
92 public static final int EVENT_DISPLAY_REMOVED = 3;
93 public static final int EVENT_DISPLAY_BRIGHTNESS_CHANGED = 4;
94
95 @UnsupportedAppUsage
96 private static DisplayManagerGlobal sInstance;
97
98 // Guarded by mLock
99 private boolean mDispatchNativeCallbacks = false;
100 private float mNativeCallbackReportedRefreshRate;
101 private final Object mLock = new Object();
102
103 @UnsupportedAppUsage
104 private final IDisplayManager mDm;
105
106 private DisplayManagerCallback mCallback;
107 private @EventsMask long mRegisteredEventsMask = 0;
108 private final ArrayList<DisplayListenerDelegate> mDisplayListeners = new ArrayList<>();
109
110 private final SparseArray<DisplayInfo> mDisplayInfoCache = new SparseArray<>();
111 private final ColorSpace mWideColorSpace;
112 private int[] mDisplayIdCache;
113
114 private int mWifiDisplayScanNestCount;
115
116 @VisibleForTesting
117 public DisplayManagerGlobal(IDisplayManager dm) {
118 mDm = dm;
119 try {
120 mWideColorSpace =
121 ColorSpace.get(
122 ColorSpace.Named.values()[mDm.getPreferredWideGamutColorSpaceId()]);
123 } catch (RemoteException ex) {
124 throw ex.rethrowFromSystemServer();
125 }
126 }
127
128 private PropertyInvalidatedCache<Integer, DisplayInfo> mDisplayCache =
129 new PropertyInvalidatedCache<Integer, DisplayInfo>(
130 8, // size of display cache
131 CACHE_KEY_DISPLAY_INFO_PROPERTY) {
132 @Override
133 public DisplayInfo recompute(Integer id) {
134 try {
135 return mDm.getDisplayInfo(id);
136 } catch (RemoteException ex) {
137 throw ex.rethrowFromSystemServer();
138 }
139 }
140 };
141
142 /**
143 * Gets an instance of the display manager global singleton.
144 *
145 * @return The display manager instance, may be null early in system startup
146 * before the display manager has been fully initialized.
147 */
148 @UnsupportedAppUsage
149 public static DisplayManagerGlobal getInstance() {
150 synchronized (DisplayManagerGlobal.class) {
151 if (sInstance == null) {
152 IBinder b = ServiceManager.getService(Context.DISPLAY_SERVICE);
153 if (b != null) {
154 sInstance = new DisplayManagerGlobal(IDisplayManager.Stub.asInterface(b));
155 }
156 }
157 return sInstance;
158 }
159 }
160
161 /**
162 * Get information about a particular logical display.
163 *
164 * @param displayId The logical display id.
165 * @return Information about the specified display, or null if it does not exist.
166 * This object belongs to an internal cache and should be treated as if it were immutable.
167 */
168 @UnsupportedAppUsage
169 public DisplayInfo getDisplayInfo(int displayId) {
170 synchronized (mLock) {
171 return getDisplayInfoLocked(displayId);
172 }
173 }
174
175 /**
176 * Gets information about a particular logical display
177 * See {@link getDisplayInfo}, but assumes that {@link mLock} is held
178 */
179 private @Nullable DisplayInfo getDisplayInfoLocked(int displayId) {
180 DisplayInfo info = null;
181 if (mDisplayCache != null) {
182 info = mDisplayCache.query(displayId);
183 } else {
184 try {
185 info = mDm.getDisplayInfo(displayId);
186 } catch (RemoteException ex) {
187 ex.rethrowFromSystemServer();
188 }
189 }
190 if (info == null) {
191 return null;
192 }
193
194 registerCallbackIfNeededLocked();
195
196 if (DEBUG) {
197 Log.d(TAG, "getDisplayInfo: displayId=" + displayId + ", info=" + info);
198 }
199 return info;
200 }
201
202 /**
203 * Gets all currently valid logical display ids.
204 *
205 * @return An array containing all display ids.
206 */
207 @UnsupportedAppUsage
208 public int[] getDisplayIds() {
209 return getDisplayIds(/* includeDisabled= */ false);
210 }
211
212 /**
213 * Gets all currently valid logical display ids.
214 *
215 * @param includeDisabled True if the returned list of displays includes disabled displays.
216 * @return An array containing all display ids.
217 */
218 public int[] getDisplayIds(boolean includeDisabled) {
219 try {
220 synchronized (mLock) {
221 if (USE_CACHE) {
222 if (mDisplayIdCache != null) {
223 return mDisplayIdCache;
224 }
225 }
226
227 int[] displayIds = mDm.getDisplayIds(includeDisabled);
228 if (USE_CACHE) {
229 mDisplayIdCache = displayIds;
230 }
231 registerCallbackIfNeededLocked();
232 return displayIds;
233 }
234 } catch (RemoteException ex) {
235 throw ex.rethrowFromSystemServer();
236 }
237 }
238
239 /**
240 * Check if specified UID's content is present on display and should be granted access to it.
241 *
242 * @param uid UID to be checked.
243 * @param displayId id of the display where presence of the content is checked.
244 * @return {@code true} if UID is present on display, {@code false} otherwise.
245 */
246 public boolean isUidPresentOnDisplay(int uid, int displayId) {
247 try {
248 return mDm.isUidPresentOnDisplay(uid, displayId);
249 } catch (RemoteException ex) {
250 throw ex.rethrowFromSystemServer();
251 }
252 }
253
254 /**
255 * Gets information about a logical display.
256 *
257 * The display metrics may be adjusted to provide compatibility
258 * for legacy applications or limited screen areas.
259 *
260 * @param displayId The logical display id.
261 * @param daj The compatibility info and activityToken.
262 * @return The display object, or null if there is no display with the given id.
263 */
264 public Display getCompatibleDisplay(int displayId, DisplayAdjustments daj) {
265 DisplayInfo displayInfo = getDisplayInfo(displayId);
266 if (displayInfo == null) {
267 return null;
268 }
269 return new Display(this, displayId, displayInfo, daj);
270 }
271
272 /**
273 * Gets information about a logical display.
274 *
275 * The display metrics may be adjusted to provide compatibility
276 * for legacy applications or limited screen areas.
277 *
278 * @param displayId The logical display id.
279 * @param resources Resources providing compatibility info.
280 * @return The display object, or null if there is no display with the given id.
281 */
282 public Display getCompatibleDisplay(int displayId, Resources resources) {
283 DisplayInfo displayInfo = getDisplayInfo(displayId);
284 if (displayInfo == null) {
285 return null;
286 }
287 return new Display(this, displayId, displayInfo, resources);
288 }
289
290 /**
291 * Gets information about a logical display without applying any compatibility metrics.
292 *
293 * @param displayId The logical display id.
294 * @return The display object, or null if there is no display with the given id.
295 */
296 @UnsupportedAppUsage
297 public Display getRealDisplay(int displayId) {
298 return getCompatibleDisplay(displayId, DisplayAdjustments.DEFAULT_DISPLAY_ADJUSTMENTS);
299 }
300
301 /**
302 * Register a listener for display-related changes.
303 *
304 * @param listener The listener that will be called when display changes occur.
305 * @param handler Handler for the thread that will be receiving the callbacks. May be null.
306 * If null, listener will use the handler for the current thread, and if still null,
307 * the handler for the main thread.
308 * If that is still null, a runtime exception will be thrown.
309 */
310 public void registerDisplayListener(@NonNull DisplayListener listener,
311 @Nullable Handler handler, @EventsMask long eventsMask) {
312 if (listener == null) {
313 throw new IllegalArgumentException("listener must not be null");
314 }
315
316 if (eventsMask == 0) {
317 throw new IllegalArgumentException("The set of events to listen to must not be empty.");
318 }
319
320 synchronized (mLock) {
321 int index = findDisplayListenerLocked(listener);
322 if (index < 0) {
323 Looper looper = getLooperForHandler(handler);
324 mDisplayListeners.add(new DisplayListenerDelegate(listener, looper, eventsMask));
325 registerCallbackIfNeededLocked();
326 } else {
327 mDisplayListeners.get(index).setEventsMask(eventsMask);
328 }
329 updateCallbackIfNeededLocked();
330 }
331 }
332
333 public void unregisterDisplayListener(DisplayListener listener) {
334 if (listener == null) {
335 throw new IllegalArgumentException("listener must not be null");
336 }
337
338 synchronized (mLock) {
339 int index = findDisplayListenerLocked(listener);
340 if (index >= 0) {
341 DisplayListenerDelegate d = mDisplayListeners.get(index);
342 d.clearEvents();
343 mDisplayListeners.remove(index);
344 updateCallbackIfNeededLocked();
345 }
346 }
347 }
348
349 private static Looper getLooperForHandler(@Nullable Handler handler) {
350 Looper looper = handler != null ? handler.getLooper() : Looper.myLooper();
351 if (looper == null) {
352 looper = Looper.getMainLooper();
353 }
354 if (looper == null) {
355 throw new RuntimeException("Could not get Looper for the UI thread.");
356 }
357 return looper;
358 }
359
360 private int findDisplayListenerLocked(DisplayListener listener) {
361 final int numListeners = mDisplayListeners.size();
362 for (int i = 0; i < numListeners; i++) {
363 if (mDisplayListeners.get(i).mListener == listener) {
364 return i;
365 }
366 }
367 return -1;
368 }
369
370 @EventsMask
371 private int calculateEventsMaskLocked() {
372 int mask = 0;
373 final int numListeners = mDisplayListeners.size();
374 for (int i = 0; i < numListeners; i++) {
375 mask |= mDisplayListeners.get(i).mEventsMask;
376 }
377 if (mDispatchNativeCallbacks) {
378 mask |= DisplayManager.EVENT_FLAG_DISPLAY_ADDED
379 | DisplayManager.EVENT_FLAG_DISPLAY_CHANGED
380 | DisplayManager.EVENT_FLAG_DISPLAY_REMOVED;
381 }
382 return mask;
383 }
384
385 private void registerCallbackIfNeededLocked() {
386 if (mCallback == null) {
387 mCallback = new DisplayManagerCallback();
388 updateCallbackIfNeededLocked();
389 }
390 }
391
392 private void updateCallbackIfNeededLocked() {
393 int mask = calculateEventsMaskLocked();
394 if (mask != mRegisteredEventsMask) {
395 try {
396 mDm.registerCallbackWithEventMask(mCallback, mask);
397 mRegisteredEventsMask = mask;
398 } catch (RemoteException ex) {
399 throw ex.rethrowFromSystemServer();
400 }
401 }
402 }
403
404 private void handleDisplayEvent(int displayId, @DisplayEvent int event) {
405 synchronized (mLock) {
406 if (USE_CACHE) {
407 mDisplayInfoCache.remove(displayId);
408
409 if (event == EVENT_DISPLAY_ADDED || event == EVENT_DISPLAY_REMOVED) {
410 mDisplayIdCache = null;
411 }
412 }
413
414 final int numListeners = mDisplayListeners.size();
415 DisplayInfo info = getDisplayInfo(displayId);
416 for (int i = 0; i < numListeners; i++) {
417 mDisplayListeners.get(i).sendDisplayEvent(displayId, event, info);
418 }
419 if (event == EVENT_DISPLAY_CHANGED && mDispatchNativeCallbacks) {
420 // Choreographer only supports a single display, so only dispatch refresh rate
421 // changes for the default display.
422 if (displayId == Display.DEFAULT_DISPLAY) {
423 // We can likely save a binder hop if we attach the refresh rate onto the
424 // listener.
425 DisplayInfo display = getDisplayInfoLocked(displayId);
426 if (display != null
427 && mNativeCallbackReportedRefreshRate != display.getRefreshRate()) {
428 mNativeCallbackReportedRefreshRate = display.getRefreshRate();
429 // Signal native callbacks if we ever set a refresh rate.
430 nSignalNativeCallbacks(mNativeCallbackReportedRefreshRate);
431 }
432 }
433 }
434 }
435 }
436
437 public void startWifiDisplayScan() {
438 synchronized (mLock) {
439 if (mWifiDisplayScanNestCount++ == 0) {
440 registerCallbackIfNeededLocked();
441 try {
442 mDm.startWifiDisplayScan();
443 } catch (RemoteException ex) {
444 throw ex.rethrowFromSystemServer();
445 }
446 }
447 }
448 }
449
450 public void stopWifiDisplayScan() {
451 synchronized (mLock) {
452 if (--mWifiDisplayScanNestCount == 0) {
453 try {
454 mDm.stopWifiDisplayScan();
455 } catch (RemoteException ex) {
456 throw ex.rethrowFromSystemServer();
457 }
458 } else if (mWifiDisplayScanNestCount < 0) {
459 Log.wtf(TAG, "Wifi display scan nest count became negative: "
460 + mWifiDisplayScanNestCount);
461 mWifiDisplayScanNestCount = 0;
462 }
463 }
464 }
465
466 public void connectWifiDisplay(String deviceAddress) {
467 if (deviceAddress == null) {
468 throw new IllegalArgumentException("deviceAddress must not be null");
469 }
470
471 try {
472 mDm.connectWifiDisplay(deviceAddress);
473 } catch (RemoteException ex) {
474 throw ex.rethrowFromSystemServer();
475 }
476 }
477
478 public void pauseWifiDisplay() {
479 try {
480 mDm.pauseWifiDisplay();
481 } catch (RemoteException ex) {
482 throw ex.rethrowFromSystemServer();
483 }
484 }
485
486 public void resumeWifiDisplay() {
487 try {
488 mDm.resumeWifiDisplay();
489 } catch (RemoteException ex) {
490 throw ex.rethrowFromSystemServer();
491 }
492 }
493
494 @UnsupportedAppUsage
495 public void disconnectWifiDisplay() {
496 try {
497 mDm.disconnectWifiDisplay();
498 } catch (RemoteException ex) {
499 throw ex.rethrowFromSystemServer();
500 }
501 }
502
503 public void renameWifiDisplay(String deviceAddress, String alias) {
504 if (deviceAddress == null) {
505 throw new IllegalArgumentException("deviceAddress must not be null");
506 }
507
508 try {
509 mDm.renameWifiDisplay(deviceAddress, alias);
510 } catch (RemoteException ex) {
511 throw ex.rethrowFromSystemServer();
512 }
513 }
514
515 public void forgetWifiDisplay(String deviceAddress) {
516 if (deviceAddress == null) {
517 throw new IllegalArgumentException("deviceAddress must not be null");
518 }
519
520 try {
521 mDm.forgetWifiDisplay(deviceAddress);
522 } catch (RemoteException ex) {
523 throw ex.rethrowFromSystemServer();
524 }
525 }
526
527 @UnsupportedAppUsage
528 public WifiDisplayStatus getWifiDisplayStatus() {
529 try {
530 return mDm.getWifiDisplayStatus();
531 } catch (RemoteException ex) {
532 throw ex.rethrowFromSystemServer();
533 }
534 }
535
536 /**
537 * Sets the HDR types that have been disabled by user.
538 * @param userDisabledHdrTypes the HDR types to disable. The HDR types are any of
539 */
540 public void setUserDisabledHdrTypes(@HdrType int[] userDisabledHdrTypes) {
541 try {
542 mDm.setUserDisabledHdrTypes(userDisabledHdrTypes);
543 } catch (RemoteException ex) {
544 throw ex.rethrowFromSystemServer();
545 }
546 }
547
548 /**
549 * Sets whether or not the user disabled HDR types are returned from
550 * {@link Display#getHdrCapabilities}.
551 *
552 * @param areUserDisabledHdrTypesAllowed If true, the user-disabled
553 * types are ignored and returned, if the display supports them. If
554 * false, the user-disabled types are taken into consideration and
555 * are never returned, even if the display supports them.
556 */
557 public void setAreUserDisabledHdrTypesAllowed(boolean areUserDisabledHdrTypesAllowed) {
558 try {
559 mDm.setAreUserDisabledHdrTypesAllowed(areUserDisabledHdrTypesAllowed);
560 } catch (RemoteException ex) {
561 throw ex.rethrowFromSystemServer();
562 }
563 }
564
565 /**
566 * Returns whether or not the user-disabled HDR types are returned from
567 * {@link Display#getHdrCapabilities}.
568 */
569 public boolean areUserDisabledHdrTypesAllowed() {
570 try {
571 return mDm.areUserDisabledHdrTypesAllowed();
572 } catch (RemoteException ex) {
573 throw ex.rethrowFromSystemServer();
574 }
575 }
576
577 /**
578 * Returns the HDR formats disabled by the user.
579 *
580 */
581 public int[] getUserDisabledHdrTypes() {
582 try {
583 return mDm.getUserDisabledHdrTypes();
584 } catch (RemoteException ex) {
585 throw ex.rethrowFromSystemServer();
586 }
587 }
588
589 public void requestColorMode(int displayId, int colorMode) {
590 try {
591 mDm.requestColorMode(displayId, colorMode);
592 } catch (RemoteException ex) {
593 throw ex.rethrowFromSystemServer();
594 }
595 }
596
597 public VirtualDisplay createVirtualDisplay(@NonNull Context context, MediaProjection projection,
598 @NonNull VirtualDisplayConfig virtualDisplayConfig, VirtualDisplay.Callback callback,
599 @Nullable Executor executor, @Nullable Context windowContext) {
600 VirtualDisplayCallback callbackWrapper = new VirtualDisplayCallback(callback, executor);
601 IMediaProjection projectionToken = projection != null ? projection.getProjection() : null;
602 int displayId;
603 try {
604 displayId = mDm.createVirtualDisplay(virtualDisplayConfig, callbackWrapper,
605 projectionToken, context.getPackageName());
606 } catch (RemoteException ex) {
607 throw ex.rethrowFromSystemServer();
608 }
609 return createVirtualDisplayWrapper(virtualDisplayConfig, windowContext, callbackWrapper,
610 displayId);
611 }
612
613 /**
614 * Create a VirtualDisplay wrapper object for a newly created virtual display ; to be called
615 * once the display has been created in system_server.
616 */
617 @Nullable
618 public VirtualDisplay createVirtualDisplayWrapper(VirtualDisplayConfig virtualDisplayConfig,
619 Context windowContext, IVirtualDisplayCallback callbackWrapper, int displayId) {
620 if (displayId < 0) {
621 Log.e(TAG, "Could not create virtual display: " + virtualDisplayConfig.getName());
622 return null;
623 }
624 Display display = getRealDisplay(displayId);
625 if (display == null) {
626 Log.wtf(TAG, "Could not obtain display info for newly created "
627 + "virtual display: " + virtualDisplayConfig.getName());
628 try {
629 mDm.releaseVirtualDisplay(callbackWrapper);
630 } catch (RemoteException ex) {
631 throw ex.rethrowFromSystemServer();
632 }
633 return null;
634 }
635 return new VirtualDisplay(this, display, callbackWrapper,
636 virtualDisplayConfig.getSurface(), windowContext);
637 }
638
639 public void setVirtualDisplaySurface(IVirtualDisplayCallback token, Surface surface) {
640 try {
641 mDm.setVirtualDisplaySurface(token, surface);
642 setVirtualDisplayState(token, surface != null);
643 } catch (RemoteException ex) {
644 throw ex.rethrowFromSystemServer();
645 }
646 }
647
648 public void resizeVirtualDisplay(IVirtualDisplayCallback token,
649 int width, int height, int densityDpi) {
650 try {
651 mDm.resizeVirtualDisplay(token, width, height, densityDpi);
652 } catch (RemoteException ex) {
653 throw ex.rethrowFromSystemServer();
654 }
655 }
656
657 public void releaseVirtualDisplay(IVirtualDisplayCallback token) {
658 try {
659 mDm.releaseVirtualDisplay(token);
660 } catch (RemoteException ex) {
661 throw ex.rethrowFromSystemServer();
662 }
663 }
664
665 void setVirtualDisplayState(IVirtualDisplayCallback token, boolean isOn) {
666 try {
667 mDm.setVirtualDisplayState(token, isOn);
668 } catch (RemoteException ex) {
669 throw ex.rethrowFromSystemServer();
670 }
671 }
672
673 /**
674 * Gets the stable device display size, in pixels.
675 */
676 public Point getStableDisplaySize() {
677 try {
678 return mDm.getStableDisplaySize();
679 } catch (RemoteException ex) {
680 throw ex.rethrowFromSystemServer();
681 }
682 }
683
684 /**
685 * Retrieves brightness change events.
686 */
687 public List<BrightnessChangeEvent> getBrightnessEvents(String callingPackage) {
688 try {
689 ParceledListSlice<BrightnessChangeEvent> events =
690 mDm.getBrightnessEvents(callingPackage);
691 if (events == null) {
692 return Collections.emptyList();
693 }
694 return events.getList();
695 } catch (RemoteException ex) {
696 throw ex.rethrowFromSystemServer();
697 }
698 }
699
700 /**
701 * Retrieves Brightness Info for the specified display.
702 */
703 public BrightnessInfo getBrightnessInfo(int displayId) {
704 try {
705 return mDm.getBrightnessInfo(displayId);
706 } catch (RemoteException ex) {
707 throw ex.rethrowFromSystemServer();
708 }
709 }
710
711 /**
712 * Gets the preferred wide gamut color space for all displays.
713 * The wide gamut color space is returned from composition pipeline
714 * based on hardware capability.
715 *
716 * @hide
717 */
718 public ColorSpace getPreferredWideGamutColorSpace() {
719 return mWideColorSpace;
720 }
721
722 /**
723 * Sets the global brightness configuration for a given user.
724 *
725 * @hide
726 */
727 public void setBrightnessConfigurationForUser(BrightnessConfiguration c, int userId,
728 String packageName) {
729 try {
730 mDm.setBrightnessConfigurationForUser(c, userId, packageName);
731 } catch (RemoteException ex) {
732 throw ex.rethrowFromSystemServer();
733 }
734 }
735
736 /**
737 * Sets the brightness configuration for a given display.
738 *
739 * @hide
740 */
741 public void setBrightnessConfigurationForDisplay(BrightnessConfiguration c,
742 String uniqueDisplayId, int userId, String packageName) {
743 try {
744 mDm.setBrightnessConfigurationForDisplay(c, uniqueDisplayId, userId, packageName);
745 } catch (RemoteException ex) {
746 throw ex.rethrowFromSystemServer();
747 }
748 }
749
750 /**
751 * Gets the brightness configuration for a given display or null if one hasn't been set.
752 *
753 * @hide
754 */
755 public BrightnessConfiguration getBrightnessConfigurationForDisplay(String uniqueDisplayId,
756 int userId) {
757 try {
758 return mDm.getBrightnessConfigurationForDisplay(uniqueDisplayId, userId);
759 } catch (RemoteException ex) {
760 throw ex.rethrowFromSystemServer();
761 }
762 }
763
764 /**
765 * Gets the global brightness configuration for a given user or null if one hasn't been set.
766 *
767 * @hide
768 */
769 public BrightnessConfiguration getBrightnessConfigurationForUser(int userId) {
770 try {
771 return mDm.getBrightnessConfigurationForUser(userId);
772 } catch (RemoteException ex) {
773 throw ex.rethrowFromSystemServer();
774 }
775 }
776
777 /**
778 * Gets the default brightness configuration or null if one hasn't been configured.
779 *
780 * @hide
781 */
782 public BrightnessConfiguration getDefaultBrightnessConfiguration() {
783 try {
784 return mDm.getDefaultBrightnessConfiguration();
785 } catch (RemoteException ex) {
786 throw ex.rethrowFromSystemServer();
787 }
788 }
789
790 /**
791 * Gets the last requested minimal post processing setting for the display with displayId.
792 *
793 * @hide
794 */
795 public boolean isMinimalPostProcessingRequested(int displayId) {
796 try {
797 return mDm.isMinimalPostProcessingRequested(displayId);
798 } catch (RemoteException ex) {
799 throw ex.rethrowFromSystemServer();
800 }
801 }
802
803 /**
804 * Temporarily sets the brightness of the display.
805 * <p>
806 * Requires the {@link android.Manifest.permission#CONTROL_DISPLAY_BRIGHTNESS} permission.
807 * </p>
808 *
809 * @param brightness The brightness value from 0.0f to 1.0f.
810 *
811 * @hide Requires signature permission.
812 */
813 public void setTemporaryBrightness(int displayId, float brightness) {
814 try {
815 mDm.setTemporaryBrightness(displayId, brightness);
816 } catch (RemoteException ex) {
817 throw ex.rethrowFromSystemServer();
818 }
819 }
820
821
822 /**
823 * Sets the brightness of the display.
824 *
825 * @param brightness The brightness value from 0.0f to 1.0f.
826 *
827 * @hide
828 */
829 public void setBrightness(int displayId, float brightness) {
830 try {
831 mDm.setBrightness(displayId, brightness);
832 } catch (RemoteException ex) {
833 throw ex.rethrowFromSystemServer();
834 }
835 }
836
837 /**
838 * Report whether/how the display supports DISPLAY_DECORATION.
839 *
840 * @param displayId The display whose support is being queried.
841 *
842 * @hide
843 */
844 public DisplayDecorationSupport getDisplayDecorationSupport(int displayId) {
845 try {
846 return mDm.getDisplayDecorationSupport(displayId);
847 } catch (RemoteException ex) {
848 throw ex.rethrowFromSystemServer();
849 }
850 }
851
852 /**
853 * Gets the brightness of the display.
854 *
855 * @param displayId The display from which to get the brightness
856 *
857 * @hide
858 */
859 public float getBrightness(int displayId) {
860 try {
861 return mDm.getBrightness(displayId);
862 } catch (RemoteException ex) {
863 throw ex.rethrowFromSystemServer();
864 }
865 }
866
867 /**
868 * Temporarily sets the auto brightness adjustment factor.
869 * <p>
870 * Requires the {@link android.Manifest.permission#CONTROL_DISPLAY_BRIGHTNESS} permission.
871 * </p>
872 *
873 * @param adjustment The adjustment factor from -1.0 to 1.0.
874 *
875 * @hide Requires signature permission.
876 */
877 public void setTemporaryAutoBrightnessAdjustment(float adjustment) {
878 try {
879 mDm.setTemporaryAutoBrightnessAdjustment(adjustment);
880 } catch (RemoteException ex) {
881 throw ex.rethrowFromSystemServer();
882 }
883 }
884
885 /**
886 * Returns the minimum brightness curve, which guarantess that any brightness curve that dips
887 * below it is rejected by the system.
888 * This prevent auto-brightness from setting the screen so dark as to prevent the user from
889 * resetting or disabling it, and maps lux to the absolute minimum nits that are still readable
890 * in that ambient brightness.
891 *
892 * @return The minimum brightness curve (as lux values and their corresponding nits values).
893 */
894 public Pair<float[], float[]> getMinimumBrightnessCurve() {
895 try {
896 Curve curve = mDm.getMinimumBrightnessCurve();
897 return Pair.create(curve.getX(), curve.getY());
898 } catch (RemoteException ex) {
899 throw ex.rethrowFromSystemServer();
900 }
901 }
902
903 /**
904 * Retrieves ambient brightness stats.
905 */
906 public List<AmbientBrightnessDayStats> getAmbientBrightnessStats() {
907 try {
908 ParceledListSlice<AmbientBrightnessDayStats> stats = mDm.getAmbientBrightnessStats();
909 if (stats == null) {
910 return Collections.emptyList();
911 }
912 return stats.getList();
913 } catch (RemoteException ex) {
914 throw ex.rethrowFromSystemServer();
915 }
916 }
917
918 /**
919 * Sets the default display mode, according to the refresh rate and the resolution chosen by the
920 * user.
921 */
922 public void setUserPreferredDisplayMode(int displayId, Display.Mode mode) {
923 try {
924 mDm.setUserPreferredDisplayMode(displayId, mode);
925 } catch (RemoteException ex) {
926 throw ex.rethrowFromSystemServer();
927 }
928 }
929
930 /**
931 * Returns the user preferred display mode.
932 */
933 public Display.Mode getUserPreferredDisplayMode(int displayId) {
934 try {
935 return mDm.getUserPreferredDisplayMode(displayId);
936 } catch (RemoteException ex) {
937 throw ex.rethrowFromSystemServer();
938 }
939 }
940
941 /**
942 * Returns the system preferred display mode.
943 */
944 public Display.Mode getSystemPreferredDisplayMode(int displayId) {
945 try {
946 return mDm.getSystemPreferredDisplayMode(displayId);
947 } catch (RemoteException ex) {
948 throw ex.rethrowFromSystemServer();
949 }
950 }
951
952 /**
953 * When enabled the app requested display resolution and refresh rate is always selected
954 * in DisplayModeDirector regardless of user settings and policies for low brightness, low
955 * battery etc.
956 */
957 public void setShouldAlwaysRespectAppRequestedMode(boolean enabled) {
958 try {
959 mDm.setShouldAlwaysRespectAppRequestedMode(enabled);
960 } catch (RemoteException ex) {
961 throw ex.rethrowFromSystemServer();
962 }
963 }
964
965 /**
966 * Returns whether DisplayModeDirector is running in a mode which always selects the app
967 * requested display mode and ignores user settings and policies for low brightness, low
968 * battery etc.
969 */
970 public boolean shouldAlwaysRespectAppRequestedMode() {
971 try {
972 return mDm.shouldAlwaysRespectAppRequestedMode();
973 } catch (RemoteException ex) {
974 throw ex.rethrowFromSystemServer();
975 }
976 }
977
978 /**
979 * Sets the refresh rate switching type.
980 *
981 * @hide
982 */
983 public void setRefreshRateSwitchingType(@DisplayManager.SwitchingType int newValue) {
984 try {
985 mDm.setRefreshRateSwitchingType(newValue);
986 } catch (RemoteException ex) {
987 throw ex.rethrowFromSystemServer();
988 }
989 }
990
991 /**
992 * Returns the refresh rate switching type.
993 *
994 * @hide
995 */
996 @DisplayManager.SwitchingType
997 public int getRefreshRateSwitchingType() {
998 try {
999 return mDm.getRefreshRateSwitchingType();
1000 } catch (RemoteException ex) {
1001 throw ex.rethrowFromSystemServer();
1002 }
1003 }
1004
1005 private final class DisplayManagerCallback extends IDisplayManagerCallback.Stub {
1006 @Override
1007 public void onDisplayEvent(int displayId, @DisplayEvent int event) {
1008 if (DEBUG) {
1009 Log.d(TAG, "onDisplayEvent: displayId=" + displayId + ", event=" + event);
1010 }
1011 handleDisplayEvent(displayId, event);
1012 }
1013 }
1014
1015 private static final class DisplayListenerDelegate extends Handler {
1016 public final DisplayListener mListener;
1017 public volatile long mEventsMask;
1018
1019 private final DisplayInfo mDisplayInfo = new DisplayInfo();
1020
1021 DisplayListenerDelegate(DisplayListener listener, @NonNull Looper looper,
1022 @EventsMask long eventsMask) {
1023 super(looper, null, true /*async*/);
1024 mListener = listener;
1025 mEventsMask = eventsMask;
1026 }
1027
1028 public void sendDisplayEvent(int displayId, @DisplayEvent int event, DisplayInfo info) {
1029 Message msg = obtainMessage(event, displayId, 0, info);
1030 sendMessage(msg);
1031 }
1032
1033 public void clearEvents() {
1034 removeCallbacksAndMessages(null);
1035 }
1036
1037 public void setEventsMask(@EventsMask long newEventsMask) {
1038 mEventsMask = newEventsMask;
1039 }
1040
1041 @Override
1042 public void handleMessage(Message msg) {
1043 switch (msg.what) {
1044 case EVENT_DISPLAY_ADDED:
1045 if ((mEventsMask & DisplayManager.EVENT_FLAG_DISPLAY_ADDED) != 0) {
1046 mListener.onDisplayAdded(msg.arg1);
1047 }
1048 break;
1049 case EVENT_DISPLAY_CHANGED:
1050 if ((mEventsMask & DisplayManager.EVENT_FLAG_DISPLAY_CHANGED) != 0) {
1051 DisplayInfo newInfo = (DisplayInfo) msg.obj;
1052 if (newInfo != null && !newInfo.equals(mDisplayInfo)) {
1053 mDisplayInfo.copyFrom(newInfo);
1054 mListener.onDisplayChanged(msg.arg1);
1055 }
1056 }
1057 break;
1058 case EVENT_DISPLAY_BRIGHTNESS_CHANGED:
1059 if ((mEventsMask & DisplayManager.EVENT_FLAG_DISPLAY_BRIGHTNESS) != 0) {
1060 mListener.onDisplayChanged(msg.arg1);
1061 }
1062 break;
1063 case EVENT_DISPLAY_REMOVED:
1064 if ((mEventsMask & DisplayManager.EVENT_FLAG_DISPLAY_REMOVED) != 0) {
1065 mListener.onDisplayRemoved(msg.arg1);
1066 }
1067 break;
1068 }
1069 }
1070 }
1071
1072 /**
1073 * Assists in dispatching VirtualDisplay lifecycle event callbacks on a given Executor.
1074 */
1075 public static final class VirtualDisplayCallback extends IVirtualDisplayCallback.Stub {
1076 @Nullable private final VirtualDisplay.Callback mCallback;
1077 @Nullable private final Executor mExecutor;
1078
1079 /**
1080 * Creates a virtual display callback.
1081 *
1082 * @param callback The callback to call for virtual display events, or {@code null} if the
1083 * caller does not wish to receive callback events.
1084 * @param executor The executor to call the {@code callback} on. Must not be {@code null} if
1085 * the callback is not {@code null}.
1086 */
1087 public VirtualDisplayCallback(VirtualDisplay.Callback callback, Executor executor) {
1088 mCallback = callback;
1089 mExecutor = mCallback != null ? Objects.requireNonNull(executor) : null;
1090 }
1091
1092 // These methods are called from the binder thread, but the AIDL is oneway, so it should be
1093 // safe to call the callback on arbitrary executors directly without risking blocking
1094 // the system.
1095
1096 @Override // Binder call
1097 public void onPaused() {
1098 if (mCallback != null) {
1099 mExecutor.execute(mCallback::onPaused);
1100 }
1101 }
1102
1103 @Override // Binder call
1104 public void onResumed() {
1105 if (mCallback != null) {
1106 mExecutor.execute(mCallback::onResumed);
1107 }
1108 }
1109
1110 @Override // Binder call
1111 public void onStopped() {
1112 if (mCallback != null) {
1113 mExecutor.execute(mCallback::onStopped);
1114 }
1115 }
1116 }
1117
1118 /**
1119 * Name of the property containing a unique token which changes every time we update the
1120 * system's display configuration.
1121 */
1122 public static final String CACHE_KEY_DISPLAY_INFO_PROPERTY =
1123 "cache_key.display_info";
1124
1125 /**
1126 * Invalidates the contents of the display info cache for all applications. Can only
1127 * be called by system_server.
1128 */
1129 public static void invalidateLocalDisplayInfoCaches() {
1130 PropertyInvalidatedCache.invalidateCache(CACHE_KEY_DISPLAY_INFO_PROPERTY);
1131 }
1132
1133 /**
1134 * Disables the binder call cache.
1135 */
1136 public void disableLocalDisplayInfoCaches() {
1137 mDisplayCache = null;
1138 }
1139
1140 private static native void nSignalNativeCallbacks(float refreshRate);
1141
1142 /**
1143 * Called from AChoreographer via JNI.
1144 * Registers AChoreographer so that refresh rate callbacks can be dispatched from DMS.
1145 * Public for unit testing to be able to call this method.
1146 */
1147 @VisibleForTesting
1148 public void registerNativeChoreographerForRefreshRateCallbacks() {
1149 synchronized (mLock) {
1150 mDispatchNativeCallbacks = true;
1151 registerCallbackIfNeededLocked();
1152 updateCallbackIfNeededLocked();
1153 DisplayInfo display = getDisplayInfoLocked(Display.DEFAULT_DISPLAY);
1154 if (display != null) {
1155 // We need to tell AChoreographer instances the current refresh rate so that apps
1156 // can get it for free once a callback first registers.
1157 mNativeCallbackReportedRefreshRate = display.getRefreshRate();
1158 nSignalNativeCallbacks(mNativeCallbackReportedRefreshRate);
1159 }
1160 }
1161 }
1162
1163 /**
1164 * Called from AChoreographer via JNI.
1165 * Unregisters AChoreographer from receiving refresh rate callbacks.
1166 * Public for unit testing to be able to call this method.
1167 */
1168 @VisibleForTesting
1169 public void unregisterNativeChoreographerForRefreshRateCallbacks() {
1170 synchronized (mLock) {
1171 mDispatchNativeCallbacks = false;
1172 updateCallbackIfNeededLocked();
1173 }
1174 }
1175 }