Debian Codegraph @

libs/WindowManager/Jetpack/src/androidx/window/extensions/layout/WindowLayoutComponentImpl.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2021 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 androidx.window.extensions.layout;
18
19 import static android.view.Display.DEFAULT_DISPLAY;
20
21 import static androidx.window.common.CommonFoldingFeature.COMMON_STATE_FLAT;
22 import static androidx.window.common.CommonFoldingFeature.COMMON_STATE_HALF_OPENED;
23 import static androidx.window.util.ExtensionHelper.isZero;
24 import static androidx.window.util.ExtensionHelper.rotateRectToDisplayRotation;
25 import static androidx.window.util.ExtensionHelper.transformToWindowSpaceRect;
26
27 import android.app.Activity;
28 import android.app.ActivityClient;
29 import android.app.Application;
30 import android.app.WindowConfiguration;
31 import android.content.ComponentCallbacks;
32 import android.content.Context;
33 import android.content.res.Configuration;
34 import android.graphics.Rect;
35 import android.os.Bundle;
36 import android.os.IBinder;
37 import android.util.ArrayMap;
38 import android.view.WindowManager;
39 import android.window.TaskFragmentOrganizer;
40
41 import androidx.annotation.GuardedBy;
42 import androidx.annotation.NonNull;
43 import androidx.annotation.Nullable;
44 import androidx.annotation.UiContext;
45 import androidx.window.common.CommonFoldingFeature;
46 import androidx.window.common.DeviceStateManagerFoldingFeatureProducer;
47 import androidx.window.common.EmptyLifecycleCallbacksAdapter;
48 import androidx.window.util.DataProducer;
49
50 import java.util.ArrayList;
51 import java.util.Collections;
52 import java.util.List;
53 import java.util.Map;
54 import java.util.Objects;
55 import java.util.Set;
56 import java.util.function.Consumer;
57
58 /**
59 * Reference implementation of androidx.window.extensions.layout OEM interface for use with
60 * WindowManager Jetpack.
61 *
62 * NOTE: This version is a work in progress and under active development. It MUST NOT be used in
63 * production builds since the interface can still change before reaching stable version.
64 * Please refer to {@link androidx.window.sidecar.SampleSidecarImpl} instead.
65 */
66 public class WindowLayoutComponentImpl implements WindowLayoutComponent {
67 private static final String TAG = "SampleExtension";
68
69 private final Object mLock = new Object();
70
71 @GuardedBy("mLock")
72 private final Map<Context, Consumer<WindowLayoutInfo>> mWindowLayoutChangeListeners =
73 new ArrayMap<>();
74
75 @GuardedBy("mLock")
76 private final DataProducer<List<CommonFoldingFeature>> mFoldingFeatureProducer;
77
78 @GuardedBy("mLock")
79 private final List<CommonFoldingFeature> mLastReportedFoldingFeatures = new ArrayList<>();
80
81 @GuardedBy("mLock")
82 private final Map<IBinder, ConfigurationChangeListener> mConfigurationChangeListeners =
83 new ArrayMap<>();
84
85 private final TaskFragmentOrganizer mTaskFragmentOrganizer;
86
87 public WindowLayoutComponentImpl(@NonNull Context context,
88 @NonNull TaskFragmentOrganizer taskFragmentOrganizer,
89 @NonNull DeviceStateManagerFoldingFeatureProducer foldingFeatureProducer) {
90 ((Application) context.getApplicationContext())
91 .registerActivityLifecycleCallbacks(new NotifyOnConfigurationChanged());
92 mFoldingFeatureProducer = foldingFeatureProducer;
93 mFoldingFeatureProducer.addDataChangedCallback(this::onDisplayFeaturesChanged);
94 mTaskFragmentOrganizer = taskFragmentOrganizer;
95 }
96
97 /** Registers to listen to {@link CommonFoldingFeature} changes */
98 public void addFoldingStateChangedCallback(Consumer<List<CommonFoldingFeature>> consumer) {
99 synchronized (mLock) {
100 mFoldingFeatureProducer.addDataChangedCallback(consumer);
101 }
102 }
103
104 /**
105 * Adds a listener interested in receiving updates to {@link WindowLayoutInfo}
106 *
107 * @param activity hosting a {@link android.view.Window}
108 * @param consumer interested in receiving updates to {@link WindowLayoutInfo}
109 */
110 @Override
111 public void addWindowLayoutInfoListener(@NonNull Activity activity,
112 @NonNull Consumer<WindowLayoutInfo> consumer) {
113 addWindowLayoutInfoListener((Context) activity, consumer);
114 }
115
116 /**
117 * Similar to {@link #addWindowLayoutInfoListener(Activity, Consumer)}, but takes a UI Context
118 * as a parameter.
119 *
120 * Jetpack {@link androidx.window.layout.ExtensionWindowLayoutInfoBackend} makes sure all
121 * consumers related to the same {@link Context} gets updated {@link WindowLayoutInfo}
122 * together. However only the first registered consumer of a {@link Context} will actually
123 * invoke {@link #addWindowLayoutInfoListener(Context, Consumer)}.
124 * Here we enforce that {@link #addWindowLayoutInfoListener(Context, Consumer)} can only be
125 * called once for each {@link Context}.
126 */
127 @Override
128 public void addWindowLayoutInfoListener(@NonNull @UiContext Context context,
129 @NonNull Consumer<WindowLayoutInfo> consumer) {
130 synchronized (mLock) {
131 if (mWindowLayoutChangeListeners.containsKey(context)
132 // In theory this method can be called on the same consumer with different
133 // context.
134 || mWindowLayoutChangeListeners.containsValue(consumer)) {
135 return;
136 }
137 if (!context.isUiContext()) {
138 throw new IllegalArgumentException("Context must be a UI Context, which should be"
139 + " an Activity, WindowContext or InputMethodService");
140 }
141 mFoldingFeatureProducer.getData((features) -> {
142 WindowLayoutInfo newWindowLayout = getWindowLayoutInfo(context, features);
143 consumer.accept(newWindowLayout);
144 });
145 mWindowLayoutChangeListeners.put(context, consumer);
146
147 final IBinder windowContextToken = context.getWindowContextToken();
148 if (windowContextToken != null) {
149 // We register component callbacks for window contexts. For activity contexts, they
150 // will receive callbacks from NotifyOnConfigurationChanged instead.
151 final ConfigurationChangeListener listener =
152 new ConfigurationChangeListener(windowContextToken);
153 context.registerComponentCallbacks(listener);
154 mConfigurationChangeListeners.put(windowContextToken, listener);
155 }
156 }
157 }
158
159 /**
160 * Removes a listener no longer interested in receiving updates.
161 *
162 * @param consumer no longer interested in receiving updates to {@link WindowLayoutInfo}
163 */
164 @Override
165 public void removeWindowLayoutInfoListener(@NonNull Consumer<WindowLayoutInfo> consumer) {
166 synchronized (mLock) {
167 for (Context context : mWindowLayoutChangeListeners.keySet()) {
168 if (!mWindowLayoutChangeListeners.get(context).equals(consumer)) {
169 continue;
170 }
171 final IBinder token = context.getWindowContextToken();
172 if (token != null) {
173 context.unregisterComponentCallbacks(mConfigurationChangeListeners.get(token));
174 mConfigurationChangeListeners.remove(token);
175 }
176 break;
177 }
178 mWindowLayoutChangeListeners.values().remove(consumer);
179 }
180 }
181
182 @GuardedBy("mLock")
183 @NonNull
184 private Set<Context> getContextsListeningForLayoutChanges() {
185 return mWindowLayoutChangeListeners.keySet();
186 }
187
188 @GuardedBy("mLock")
189 private boolean isListeningForLayoutChanges(IBinder token) {
190 for (Context context : getContextsListeningForLayoutChanges()) {
191 if (token.equals(Context.getToken(context))) {
192 return true;
193 }
194 }
195 return false;
196 }
197
198 /**
199 * A convenience method to translate from the common feature state to the extensions feature
200 * state. More specifically, translates from {@link CommonFoldingFeature.State} to
201 * {@link FoldingFeature#STATE_FLAT} or {@link FoldingFeature#STATE_HALF_OPENED}. If it is not
202 * possible to translate, then we will return a {@code null} value.
203 *
204 * @param state if it matches a value in {@link CommonFoldingFeature.State}, {@code null}
205 * otherwise. @return a {@link FoldingFeature#STATE_FLAT} or
206 * {@link FoldingFeature#STATE_HALF_OPENED} if the given state matches a value in
207 * {@link CommonFoldingFeature.State} and {@code null} otherwise.
208 */
209 @Nullable
210 private Integer convertToExtensionState(int state) {
211 if (state == COMMON_STATE_FLAT) {
212 return FoldingFeature.STATE_FLAT;
213 } else if (state == COMMON_STATE_HALF_OPENED) {
214 return FoldingFeature.STATE_HALF_OPENED;
215 } else {
216 return null;
217 }
218 }
219
220 private void onDisplayFeaturesChanged(List<CommonFoldingFeature> storedFeatures) {
221 synchronized (mLock) {
222 mLastReportedFoldingFeatures.clear();
223 mLastReportedFoldingFeatures.addAll(storedFeatures);
224 for (Context context : getContextsListeningForLayoutChanges()) {
225 // Get the WindowLayoutInfo from the activity and pass the value to the
226 // layoutConsumer.
227 Consumer<WindowLayoutInfo> layoutConsumer = mWindowLayoutChangeListeners.get(
228 context);
229 WindowLayoutInfo newWindowLayout = getWindowLayoutInfo(context, storedFeatures);
230 layoutConsumer.accept(newWindowLayout);
231 }
232 }
233 }
234
235 /**
236 * Translates the {@link DisplayFeature} into a {@link WindowLayoutInfo} when a
237 * valid state is found.
238 *
239 * @param context a proxy for the {@link android.view.Window} that contains the
240 * {@link DisplayFeature}.
241 */
242 private WindowLayoutInfo getWindowLayoutInfo(@NonNull @UiContext Context context,
243 List<CommonFoldingFeature> storedFeatures) {
244 List<DisplayFeature> displayFeatureList = getDisplayFeatures(context, storedFeatures);
245 return new WindowLayoutInfo(displayFeatureList);
246 }
247
248 /**
249 * Gets the current {@link WindowLayoutInfo} computed with passed {@link WindowConfiguration}.
250 *
251 * @return current {@link WindowLayoutInfo} on the default display. Returns
252 * empty {@link WindowLayoutInfo} on secondary displays.
253 */
254 @NonNull
255 public WindowLayoutInfo getCurrentWindowLayoutInfo(int displayId,
256 @NonNull WindowConfiguration windowConfiguration) {
257 synchronized (mLock) {
258 return getWindowLayoutInfo(displayId, windowConfiguration,
259 mLastReportedFoldingFeatures);
260 }
261 }
262
263 /** @see #getWindowLayoutInfo(Context, List) */
264 private WindowLayoutInfo getWindowLayoutInfo(int displayId,
265 @NonNull WindowConfiguration windowConfiguration,
266 List<CommonFoldingFeature> storedFeatures) {
267 List<DisplayFeature> displayFeatureList = getDisplayFeatures(displayId, windowConfiguration,
268 storedFeatures);
269 return new WindowLayoutInfo(displayFeatureList);
270 }
271
272 /**
273 * Translate from the {@link CommonFoldingFeature} to
274 * {@link DisplayFeature} for a given {@link Activity}. If a
275 * {@link CommonFoldingFeature} is not valid then it will be omitted.
276 *
277 * For a {@link FoldingFeature} the bounds are localized into the {@link Activity} window
278 * coordinate space and the state is calculated from {@link CommonFoldingFeature#getState()}.
279 * The state from {@link #mFoldingFeatureProducer} may not be valid since
280 * {@link #mFoldingFeatureProducer} is a general state controller. If the state is not valid,
281 * the {@link FoldingFeature} is omitted from the {@link List} of {@link DisplayFeature}. If the
282 * bounds are not valid, constructing a {@link FoldingFeature} will throw an
283 * {@link IllegalArgumentException} since this can cause negative UI effects down stream.
284 *
285 * @param context a proxy for the {@link android.view.Window} that contains the
286 * {@link DisplayFeature}.
287 * @return a {@link List} of {@link DisplayFeature}s that are within the
288 * {@link android.view.Window} of the {@link Activity}
289 */
290 private List<DisplayFeature> getDisplayFeatures(
291 @NonNull @UiContext Context context, List<CommonFoldingFeature> storedFeatures) {
292 if (!shouldReportDisplayFeatures(context)) {
293 return Collections.emptyList();
294 }
295 return getDisplayFeatures(context.getDisplayId(),
296 context.getResources().getConfiguration().windowConfiguration,
297 storedFeatures);
298 }
299
300 /** @see #getDisplayFeatures(Context, List) */
301 private List<DisplayFeature> getDisplayFeatures(int displayId,
302 @NonNull WindowConfiguration windowConfiguration,
303 List<CommonFoldingFeature> storedFeatures) {
304 List<DisplayFeature> features = new ArrayList<>();
305 if (displayId != DEFAULT_DISPLAY) {
306 return features;
307 }
308
309 for (CommonFoldingFeature baseFeature : storedFeatures) {
310 Integer state = convertToExtensionState(baseFeature.getState());
311 if (state == null) {
312 continue;
313 }
314 Rect featureRect = baseFeature.getRect();
315 rotateRectToDisplayRotation(displayId, featureRect);
316 transformToWindowSpaceRect(windowConfiguration, featureRect);
317
318 if (!isZero(featureRect)) {
319 // TODO(b/228641877): Remove guarding when fixed.
320 features.add(new FoldingFeature(featureRect, baseFeature.getType(), state));
321 }
322 }
323 return features;
324 }
325
326 /**
327 * Calculates if the display features should be reported for the UI Context. The calculation
328 * uses the task information because that is accurate for Activities in ActivityEmbedding mode.
329 * TODO(b/238948678): Support reporting display features in all windowing modes.
330 *
331 * @return true if the display features should be reported for the UI Context, false otherwise.
332 */
333 private boolean shouldReportDisplayFeatures(@NonNull @UiContext Context context) {
334 int displayId = context.getDisplay().getDisplayId();
335 if (displayId != DEFAULT_DISPLAY) {
336 // Display features are not supported on secondary displays.
337 return false;
338 }
339 final int windowingMode;
340 IBinder activityToken = context.getActivityToken();
341 if (activityToken != null) {
342 final Configuration taskConfig = ActivityClient.getInstance().getTaskConfiguration(
343 activityToken);
344 if (taskConfig == null) {
345 // If we cannot determine the task configuration for any reason, it is likely that
346 // we won't be able to determine its position correctly as well. DisplayFeatures'
347 // bounds in this case can't be computed correctly, so we should skip.
348 return false;
349 }
350 final Rect taskBounds = taskConfig.windowConfiguration.getBounds();
351 final WindowManager windowManager = Objects.requireNonNull(
352 context.getSystemService(WindowManager.class));
353 final Rect currentBounds = windowManager.getCurrentWindowMetrics().getBounds();
354 final Rect maxBounds = windowManager.getMaximumWindowMetrics().getBounds();
355 boolean isTaskExpanded = maxBounds.equals(taskBounds);
356 boolean isActivityExpanded = maxBounds.equals(currentBounds);
357 /*
358 * We need to proxy being in full screen because when a user enters PiP and exits PiP
359 * the task windowingMode will report multi-window/pinned until the transition is
360 * finished in WM Shell.
361 * maxBounds == taskWindowBounds is a proxy check to verify the window is full screen
362 * For tasks that are letterboxed, we use currentBounds == maxBounds to filter these
363 * out.
364 */
365 // TODO(b/262900133) remove currentBounds check when letterboxed apps report bounds.
366 // currently we don't want to report to letterboxed apps since they do not update the
367 // window bounds when the Activity is moved. An inaccurate fold will be reported so
368 // we skip.
369 return isTaskExpanded && (isActivityExpanded
370 || mTaskFragmentOrganizer.isActivityEmbedded(activityToken));
371 } else {
372 // TODO(b/242674941): use task windowing mode for window context that associates with
373 // activity.
374 windowingMode = context.getResources().getConfiguration().windowConfiguration
375 .getWindowingMode();
376 }
377 // It is recommended not to report any display features in multi-window mode, since it
378 // won't be possible to synchronize the display feature positions with window movement.
379 return !WindowConfiguration.inMultiWindowMode(windowingMode);
380 }
381
382 @GuardedBy("mLock")
383 private void onDisplayFeaturesChangedIfListening(@NonNull IBinder token) {
384 if (isListeningForLayoutChanges(token)) {
385 mFoldingFeatureProducer.getData(
386 WindowLayoutComponentImpl.this::onDisplayFeaturesChanged);
387 }
388 }
389
390 private final class NotifyOnConfigurationChanged extends EmptyLifecycleCallbacksAdapter {
391 @Override
392 public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
393 super.onActivityCreated(activity, savedInstanceState);
394 synchronized (mLock) {
395 onDisplayFeaturesChangedIfListening(activity.getActivityToken());
396 }
397 }
398
399 @Override
400 public void onActivityConfigurationChanged(Activity activity) {
401 super.onActivityConfigurationChanged(activity);
402 synchronized (mLock) {
403 onDisplayFeaturesChangedIfListening(activity.getActivityToken());
404 }
405 }
406 }
407
408 private final class ConfigurationChangeListener implements ComponentCallbacks {
409 final IBinder mToken;
410
411 ConfigurationChangeListener(IBinder token) {
412 mToken = token;
413 }
414
415 @Override
416 public void onConfigurationChanged(@NonNull Configuration newConfig) {
417 synchronized (mLock) {
418 onDisplayFeaturesChangedIfListening(mToken);
419 }
420 }
421
422 @Override
423 public void onLowMemory() {
424 }
425 }
426 }