Debian Codegraph @

core/java/android/window/WindowOnBackInvokedDispatcher.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 android.window;
18
19 import android.annotation.NonNull;
20 import android.annotation.Nullable;
21 import android.content.Context;
22 import android.os.Handler;
23 import android.os.RemoteException;
24 import android.os.SystemProperties;
25 import android.text.TextUtils;
26 import android.util.Log;
27 import android.view.IWindow;
28 import android.view.IWindowSession;
29
30 import java.lang.ref.WeakReference;
31 import java.util.ArrayList;
32 import java.util.HashMap;
33 import java.util.Objects;
34 import java.util.TreeMap;
35
36 /**
37 * Provides window based implementation of {@link OnBackInvokedDispatcher}.
38 * <p>
39 * Callbacks with higher priorities receive back dispatching first.
40 * Within the same priority, callbacks receive back dispatching in the reverse order
41 * in which they are added.
42 * <p>
43 * When the top priority callback is updated, the new callback is propagated to the Window Manager
44 * if the window the instance is associated with has been attached. It is allowed to register /
45 * unregister {@link OnBackInvokedCallback}s before the window is attached, although
46 * callbacks will not receive dispatches until window attachment.
47 *
48 * @hide
49 */
50 public class WindowOnBackInvokedDispatcher implements OnBackInvokedDispatcher {
51 private IWindowSession mWindowSession;
52 private IWindow mWindow;
53 private static final String TAG = "WindowOnBackDispatcher";
54 private static final boolean ENABLE_PREDICTIVE_BACK = SystemProperties
55 .getInt("persist.wm.debug.predictive_back", 1) != 0;
56 private static final boolean ALWAYS_ENFORCE_PREDICTIVE_BACK = SystemProperties
57 .getInt("persist.wm.debug.predictive_back_always_enforce", 0) != 0;
58 @Nullable
59 private ImeOnBackInvokedDispatcher mImeDispatcher;
60
61 /** Convenience hashmap to quickly decide if a callback has been added. */
62 private final HashMap<OnBackInvokedCallback, Integer> mAllCallbacks = new HashMap<>();
63 /** Holds all callbacks by priorities. */
64 private final TreeMap<Integer, ArrayList<OnBackInvokedCallback>>
65 mOnBackInvokedCallbacks = new TreeMap<>();
66 private final Checker mChecker;
67
68 public WindowOnBackInvokedDispatcher(boolean applicationCallBackEnabled) {
69 mChecker = new Checker(applicationCallBackEnabled);
70 }
71
72 /**
73 * Sends the pending top callback (if one exists) to WM when the view root
74 * is attached a window.
75 */
76 public void attachToWindow(@NonNull IWindowSession windowSession, @NonNull IWindow window) {
77 mWindowSession = windowSession;
78 mWindow = window;
79 if (!mAllCallbacks.isEmpty()) {
80 setTopOnBackInvokedCallback(getTopCallback());
81 }
82 }
83
84 /** Detaches the dispatcher instance from its window. */
85 public void detachFromWindow() {
86 clear();
87 mWindow = null;
88 mWindowSession = null;
89 }
90
91 // TODO: Take an Executor for the callback to run on.
92 @Override
93 public void registerOnBackInvokedCallback(
94 @Priority int priority, @NonNull OnBackInvokedCallback callback) {
95 if (mChecker.checkApplicationCallbackRegistration(priority, callback)) {
96 registerOnBackInvokedCallbackUnchecked(callback, priority);
97 }
98 }
99
100 /**
101 * Register a callback bypassing platform checks. This is used to register compatibility
102 * callbacks.
103 */
104 public void registerOnBackInvokedCallbackUnchecked(
105 @NonNull OnBackInvokedCallback callback, @Priority int priority) {
106 if (mImeDispatcher != null) {
107 mImeDispatcher.registerOnBackInvokedCallback(priority, callback);
108 return;
109 }
110 if (!mOnBackInvokedCallbacks.containsKey(priority)) {
111 mOnBackInvokedCallbacks.put(priority, new ArrayList<>());
112 }
113 ArrayList<OnBackInvokedCallback> callbacks = mOnBackInvokedCallbacks.get(priority);
114
115 // If callback has already been added, remove it and re-add it.
116 if (mAllCallbacks.containsKey(callback)) {
117 if (DEBUG) {
118 Log.i(TAG, "Callback already added. Removing and re-adding it.");
119 }
120 Integer prevPriority = mAllCallbacks.get(callback);
121 mOnBackInvokedCallbacks.get(prevPriority).remove(callback);
122 }
123
124 OnBackInvokedCallback previousTopCallback = getTopCallback();
125 callbacks.add(callback);
126 mAllCallbacks.put(callback, priority);
127 if (previousTopCallback == null
128 || (previousTopCallback != callback
129 && mAllCallbacks.get(previousTopCallback) <= priority)) {
130 setTopOnBackInvokedCallback(callback);
131 }
132 }
133
134 @Override
135 public void unregisterOnBackInvokedCallback(@NonNull OnBackInvokedCallback callback) {
136 if (mImeDispatcher != null) {
137 mImeDispatcher.unregisterOnBackInvokedCallback(callback);
138 return;
139 }
140 if (!mAllCallbacks.containsKey(callback)) {
141 if (DEBUG) {
142 Log.i(TAG, "Callback not found. returning...");
143 }
144 return;
145 }
146 OnBackInvokedCallback previousTopCallback = getTopCallback();
147 Integer priority = mAllCallbacks.get(callback);
148 ArrayList<OnBackInvokedCallback> callbacks = mOnBackInvokedCallbacks.get(priority);
149 callbacks.remove(callback);
150 if (callbacks.isEmpty()) {
151 mOnBackInvokedCallbacks.remove(priority);
152 }
153 mAllCallbacks.remove(callback);
154 // Re-populate the top callback to WM if the removed callback was previously the top one.
155 if (previousTopCallback == callback) {
156 setTopOnBackInvokedCallback(getTopCallback());
157 }
158 }
159
160 @Override
161 public void registerSystemOnBackInvokedCallback(@NonNull OnBackInvokedCallback callback) {
162 registerOnBackInvokedCallbackUnchecked(callback, OnBackInvokedDispatcher.PRIORITY_SYSTEM);
163 }
164
165 /** Clears all registered callbacks on the instance. */
166 public void clear() {
167 if (mImeDispatcher != null) {
168 mImeDispatcher.clear();
169 mImeDispatcher = null;
170 }
171 if (!mAllCallbacks.isEmpty()) {
172 // Clear binder references in WM.
173 setTopOnBackInvokedCallback(null);
174 }
175 mAllCallbacks.clear();
176 mOnBackInvokedCallbacks.clear();
177 }
178
179 private void setTopOnBackInvokedCallback(@Nullable OnBackInvokedCallback callback) {
180 if (mWindowSession == null || mWindow == null) {
181 return;
182 }
183 try {
184 OnBackInvokedCallbackInfo callbackInfo = null;
185 if (callback != null) {
186 int priority = mAllCallbacks.get(callback);
187 final IOnBackInvokedCallback iCallback =
188 callback instanceof ImeOnBackInvokedDispatcher
189 .ImeOnBackInvokedCallback
190 ? ((ImeOnBackInvokedDispatcher.ImeOnBackInvokedCallback)
191 callback).getIOnBackInvokedCallback()
192 : new OnBackInvokedCallbackWrapper(callback);
193 callbackInfo = new OnBackInvokedCallbackInfo(iCallback, priority);
194 }
195 mWindowSession.setOnBackInvokedCallbackInfo(mWindow, callbackInfo);
196 } catch (RemoteException e) {
197 Log.e(TAG, "Failed to set OnBackInvokedCallback to WM. Error: " + e);
198 }
199 }
200
201 public OnBackInvokedCallback getTopCallback() {
202 if (mAllCallbacks.isEmpty()) {
203 return null;
204 }
205 for (Integer priority : mOnBackInvokedCallbacks.descendingKeySet()) {
206 ArrayList<OnBackInvokedCallback> callbacks = mOnBackInvokedCallbacks.get(priority);
207 if (!callbacks.isEmpty()) {
208 return callbacks.get(callbacks.size() - 1);
209 }
210 }
211 return null;
212 }
213
214 /**
215 * Returns the checker used to check whether a callback can be registered
216 */
217 @NonNull
218 public Checker getChecker() {
219 return mChecker;
220 }
221 @NonNull
222 private static final BackProgressAnimator mProgressAnimator = new BackProgressAnimator();
223
224 static class OnBackInvokedCallbackWrapper extends IOnBackInvokedCallback.Stub {
225 private final WeakReference<OnBackInvokedCallback> mCallback;
226
227 OnBackInvokedCallbackWrapper(@NonNull OnBackInvokedCallback callback) {
228 mCallback = new WeakReference<>(callback);
229 }
230
231 @Override
232 public void onBackStarted(BackEvent backEvent) {
233 Handler.getMain().post(() -> {
234 final OnBackAnimationCallback callback = getBackAnimationCallback();
235 if (callback != null) {
236 mProgressAnimator.onBackStarted(backEvent, event ->
237 callback.onBackProgressed(event));
238 callback.onBackStarted(backEvent);
239 }
240 });
241 }
242
243 @Override
244 public void onBackProgressed(BackEvent backEvent) {
245 Handler.getMain().post(() -> {
246 final OnBackAnimationCallback callback = getBackAnimationCallback();
247 if (callback != null) {
248 mProgressAnimator.onBackProgressed(backEvent);
249 }
250 });
251 }
252
253 @Override
254 public void onBackCancelled() {
255 Handler.getMain().post(() -> {
256 mProgressAnimator.reset();
257 final OnBackAnimationCallback callback = getBackAnimationCallback();
258 if (callback != null) {
259 callback.onBackCancelled();
260 }
261 });
262 }
263
264 @Override
265 public void onBackInvoked() throws RemoteException {
266 Handler.getMain().post(() -> {
267 mProgressAnimator.reset();
268 final OnBackInvokedCallback callback = mCallback.get();
269 if (callback == null) {
270 return;
271 }
272 callback.onBackInvoked();
273 });
274 }
275
276 @Nullable
277 private OnBackAnimationCallback getBackAnimationCallback() {
278 OnBackInvokedCallback callback = mCallback.get();
279 return callback instanceof OnBackAnimationCallback ? (OnBackAnimationCallback) callback
280 : null;
281 }
282 }
283
284 /**
285 * Returns if the legacy back behavior should be used.
286 * <p>
287 * Legacy back behavior dispatches KEYCODE_BACK instead of invoking the application registered
288 * {@link OnBackInvokedCallback}.
289 */
290 public static boolean isOnBackInvokedCallbackEnabled(@Nullable Context context) {
291 // new back is enabled if the feature flag is enabled AND the app does not explicitly
292 // request legacy back.
293 boolean featureFlagEnabled = ENABLE_PREDICTIVE_BACK;
294 // If the context is null, we assume true and fallback on the two other conditions.
295 boolean appRequestsPredictiveBack =
296 context != null && context.getApplicationInfo().isOnBackInvokedCallbackEnabled();
297
298 if (DEBUG) {
299 Log.d(TAG, TextUtils.formatSimple("App: %s featureFlagEnabled=%s "
300 + "appRequestsPredictiveBack=%s alwaysEnforce=%s",
301 context != null ? context.getApplicationInfo().packageName : "null context",
302 featureFlagEnabled, appRequestsPredictiveBack, ALWAYS_ENFORCE_PREDICTIVE_BACK));
303 }
304
305 return featureFlagEnabled && (appRequestsPredictiveBack || ALWAYS_ENFORCE_PREDICTIVE_BACK);
306 }
307
308 @Override
309 public void setImeOnBackInvokedDispatcher(
310 @NonNull ImeOnBackInvokedDispatcher imeDispatcher) {
311 mImeDispatcher = imeDispatcher;
312 }
313
314
315 /**
316 * Class used to check whether a callback can be registered or not. This is meant to be
317 * shared with {@link ProxyOnBackInvokedDispatcher} which needs to do the same checks.
318 */
319 public static class Checker {
320
321 private final boolean mApplicationCallBackEnabled;
322
323 public Checker(boolean applicationCallBackEnabled) {
324 mApplicationCallBackEnabled = applicationCallBackEnabled;
325 }
326
327 /**
328 * Checks whether the given callback can be registered with the given priority.
329 * @return true if the callback can be added.
330 * @throws IllegalArgumentException if the priority is negative.
331 */
332 public boolean checkApplicationCallbackRegistration(int priority,
333 OnBackInvokedCallback callback) {
334 if (!mApplicationCallBackEnabled
335 && !(callback instanceof CompatOnBackInvokedCallback)
336 && !ALWAYS_ENFORCE_PREDICTIVE_BACK) {
337 Log.w("OnBackInvokedCallback",
338 "OnBackInvokedCallback is not enabled for the application."
339 + "\nSet 'android:enableOnBackInvokedCallback=\"true\"' in the"
340 + " application manifest.");
341 return false;
342 }
343 if (priority < 0) {
344 throw new IllegalArgumentException("Application registered OnBackInvokedCallback "
345 + "cannot have negative priority. Priority: " + priority);
346 }
347 Objects.requireNonNull(callback);
348 return true;
349 }
350 }
351 }