1 /*
2  * Copyright (C) 2015 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 com.android.systemui.statusbar;
18 
19 import android.annotation.Nullable;
20 import android.net.Uri;
21 import android.service.notification.StatusBarNotification;
22 import android.util.ArrayMap;
23 import android.util.IndentingPrintWriter;
24 import android.util.Pair;
25 
26 import androidx.annotation.NonNull;
27 
28 import com.android.systemui.statusbar.notification.RemoteInputControllerLogger;
29 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
30 import com.android.systemui.statusbar.policy.RemoteInputUriController;
31 import com.android.systemui.statusbar.policy.RemoteInputView;
32 import com.android.systemui.util.DumpUtilsKt;
33 
34 import com.google.errorprone.annotations.CompileTimeConstant;
35 
36 import java.lang.ref.WeakReference;
37 import java.util.ArrayList;
38 import java.util.Objects;
39 
40 /**
41  * Keeps track of the currently active {@link RemoteInputView}s.
42  */
43 public class RemoteInputController {
44     private final ArrayList<Pair<WeakReference<NotificationEntry>, Object>> mOpen
45             = new ArrayList<>();
46     private final ArrayMap<String, Object> mSpinning = new ArrayMap<>();
47     private final ArrayList<Callback> mCallbacks = new ArrayList<>(3);
48     private final Delegate mDelegate;
49     private final RemoteInputUriController mRemoteInputUriController;
50 
51     private final RemoteInputControllerLogger mLogger;
52 
53     /**
54      * RemoteInput Active's last emitted value. It's added for debugging purpose to directly see
55      * its last emitted value. As RemoteInputController holds weak reference, isRemoteInputActive
56      * in dump may not reflect the last emitted value of  Active.
57      */
58     @Nullable private Boolean mLastAppliedRemoteInputActive = null;
59 
RemoteInputController(Delegate delegate, RemoteInputUriController remoteInputUriController, RemoteInputControllerLogger logger)60     public RemoteInputController(Delegate delegate,
61             RemoteInputUriController remoteInputUriController,
62             RemoteInputControllerLogger logger) {
63         mDelegate = delegate;
64         mRemoteInputUriController = remoteInputUriController;
65         mLogger = logger;
66     }
67 
68     /**
69      * Adds a currently active remote input.
70      *
71      * @param entry the entry for which a remote input is now active.
72      * @param token a token identifying the view that is managing the remote input
73      */
addRemoteInput(NotificationEntry entry, Object token, @CompileTimeConstant String reason)74     public void addRemoteInput(NotificationEntry entry, Object token,
75             @CompileTimeConstant String reason) {
76         Objects.requireNonNull(entry);
77         Objects.requireNonNull(token);
78         boolean isActive = isRemoteInputActive(entry);
79         boolean found = pruneWeakThenRemoveAndContains(
80                 entry /* contains */, null /* remove */, token /* removeToken */);
81         mLogger.logAddRemoteInput(entry.getKey()/* entryKey */,
82                 isActive /* isRemoteInputAlreadyActive */,
83                 found /* isRemoteInputFound */,
84                 reason /* reason */,
85                 entry.getNotificationStyle()/* notificationStyle */);
86         if (!found) {
87             mOpen.add(new Pair<>(new WeakReference<>(entry), token));
88         }
89         // If the remote input focus is being transferred between different notification layouts
90         // (ex: Expanded->Contracted), then we don't want to re-apply.
91         if (!isActive) {
92             apply(entry);
93         }
94     }
95 
96     /**
97      * Removes a currently active remote input.
98      *
99      * @param entry the entry for which a remote input should be removed.
100      * @param token a token identifying the view that is requesting the removal. If non-null,
101      *              the entry is only removed if the token matches the last added token for this
102      *              entry. If null, the entry is removed regardless.
103      */
removeRemoteInput(NotificationEntry entry, Object token, @CompileTimeConstant String reason)104     public void removeRemoteInput(NotificationEntry entry, Object token,
105             @CompileTimeConstant String reason) {
106         Objects.requireNonNull(entry);
107         if (entry.mRemoteEditImeVisible && entry.mRemoteEditImeAnimatingAway) {
108             mLogger.logRemoveRemoteInput(
109                     entry.getKey() /* entryKey*/,
110                     true /* remoteEditImeVisible */,
111                     true /* remoteEditImeAnimatingAway */,
112                     isRemoteInputActive(entry) /* isRemoteInputActiveForEntry */,
113                     isRemoteInputActive() /* isRemoteInputActive */,
114                     reason /* reason */,
115                     entry.getNotificationStyle()/* notificationStyle */);
116             return;
117         }
118 
119         // If the view is being removed, this may be called even though we're not active
120         boolean remoteInputActiveForEntry = isRemoteInputActive(entry);
121         boolean remoteInputActive = isRemoteInputActive();
122         mLogger.logRemoveRemoteInput(
123                 entry.getKey() /* entryKey */,
124                 entry.mRemoteEditImeVisible /* remoteEditImeVisible */,
125                 entry.mRemoteEditImeAnimatingAway /* remoteEditImeAnimatingAway */,
126                 remoteInputActiveForEntry /* isRemoteInputActiveForEntry */,
127                 remoteInputActive/* isRemoteInputActive */,
128                 reason/* reason */,
129                 entry.getNotificationStyle()/* notificationStyle */);
130 
131         if (!remoteInputActiveForEntry) {
132             if (mLastAppliedRemoteInputActive != null
133                     && mLastAppliedRemoteInputActive
134                     && !remoteInputActive) {
135                 mLogger.logRemoteInputApplySkipped(
136                         entry.getKey() /* entryKey */,
137                         reason/* reason */,
138                         entry.getNotificationStyle()/* notificationStyle */);
139             }
140             return;
141         }
142 
143         pruneWeakThenRemoveAndContains(null /* contains */, entry /* remove */, token);
144 
145         apply(entry);
146     }
147 
148     /**
149      * Adds a currently spinning (i.e. sending) remote input.
150      *
151      * @param key the key of the entry that's spinning.
152      * @param token the token of the view managing the remote input.
153      */
addSpinning(String key, Object token)154     public void addSpinning(String key, Object token) {
155         Objects.requireNonNull(key);
156         Objects.requireNonNull(token);
157 
158         mSpinning.put(key, token);
159     }
160 
161     /**
162      * Removes a currently spinning remote input.
163      *
164      * @param key the key of the entry for which a remote input should be removed.
165      * @param token a token identifying the view that is requesting the removal. If non-null,
166      *              the entry is only removed if the token matches the last added token for this
167      *              entry. If null, the entry is removed regardless.
168      */
removeSpinning(String key, Object token)169     public void removeSpinning(String key, Object token) {
170         Objects.requireNonNull(key);
171 
172         if (token == null || mSpinning.get(key) == token) {
173             mSpinning.remove(key);
174         }
175     }
176 
isSpinning(String key)177     public boolean isSpinning(String key) {
178         return mSpinning.containsKey(key);
179     }
180 
181     /**
182      * Same as {@link #isSpinning}, but also verifies that the token is the same
183      * @param key the key that is spinning
184      * @param token the token that needs to be the same
185      * @return if this key with a given token is spinning
186      */
isSpinning(String key, Object token)187     public boolean isSpinning(String key, Object token) {
188         return mSpinning.get(key) == token;
189     }
190 
apply(NotificationEntry entry)191     private void apply(NotificationEntry entry) {
192         mDelegate.setRemoteInputActive(entry, isRemoteInputActive(entry));
193         boolean remoteInputActive = isRemoteInputActive();
194         int N = mCallbacks.size();
195         for (int i = 0; i < N; i++) {
196             mCallbacks.get(i).onRemoteInputActive(remoteInputActive);
197         }
198         mLastAppliedRemoteInputActive = remoteInputActive;
199     }
200 
201     /**
202      * @return true if {@param entry} has an active RemoteInput
203      */
isRemoteInputActive(NotificationEntry entry)204     public boolean isRemoteInputActive(NotificationEntry entry) {
205         return pruneWeakThenRemoveAndContains(entry /* contains */, null /* remove */,
206                 null /* removeToken */);
207     }
208 
209     /**
210      * @return true if any entry has an active RemoteInput
211      */
isRemoteInputActive()212     public boolean isRemoteInputActive() {
213         pruneWeakThenRemoveAndContains(null /* contains */, null /* remove */,
214                 null /* removeToken */);
215         return !mOpen.isEmpty();
216     }
217 
218     /**
219      * Prunes dangling weak references, removes entries referring to {@param remove} and returns
220      * whether {@param contains} is part of the array in a single loop.
221      * @param remove if non-null, removes this entry from the active remote inputs
222      * @param removeToken if non-null, only removes an entry if this matches the token when the
223      *                    entry was added.
224      * @return true if {@param contains} is in the set of active remote inputs
225      */
pruneWeakThenRemoveAndContains( NotificationEntry contains, NotificationEntry remove, Object removeToken)226     private boolean pruneWeakThenRemoveAndContains(
227             NotificationEntry contains, NotificationEntry remove, Object removeToken) {
228         boolean found = false;
229         for (int i = mOpen.size() - 1; i >= 0; i--) {
230             NotificationEntry item = mOpen.get(i).first.get();
231             Object itemToken = mOpen.get(i).second;
232             boolean removeTokenMatches = (removeToken == null || itemToken == removeToken);
233 
234             if (item == null || (item == remove && removeTokenMatches)) {
235                 mOpen.remove(i);
236             } else if (item == contains) {
237                 if (removeToken != null && removeToken != itemToken) {
238                     // We need to update the token. Remove here and let caller reinsert it.
239                     mOpen.remove(i);
240                 } else {
241                     found = true;
242                 }
243             }
244         }
245         return found;
246     }
247 
248 
addCallback(Callback callback)249     public void addCallback(Callback callback) {
250         Objects.requireNonNull(callback);
251         mCallbacks.add(callback);
252     }
253 
removeCallback(Callback callback)254     public void removeCallback(Callback callback) {
255         mCallbacks.remove(callback);
256     }
257 
remoteInputSent(NotificationEntry entry)258     public void remoteInputSent(NotificationEntry entry) {
259         int N = mCallbacks.size();
260         for (int i = 0; i < N; i++) {
261             mCallbacks.get(i).onRemoteInputSent(entry);
262         }
263     }
264 
closeRemoteInputs()265     public void closeRemoteInputs() {
266         if (mOpen.size() == 0) {
267             return;
268         }
269 
270         // Make a copy because closing the remote inputs will modify mOpen.
271         ArrayList<NotificationEntry> list = new ArrayList<>(mOpen.size());
272         for (int i = mOpen.size() - 1; i >= 0; i--) {
273             NotificationEntry entry = mOpen.get(i).first.get();
274             if (entry != null && entry.rowExists()) {
275                 list.add(entry);
276             }
277         }
278 
279         for (int i = list.size() - 1; i >= 0; i--) {
280             NotificationEntry entry = list.get(i);
281             if (entry.rowExists()) {
282                 entry.closeRemoteInput();
283             }
284         }
285     }
286 
requestDisallowLongPressAndDismiss()287     public void requestDisallowLongPressAndDismiss() {
288         mDelegate.requestDisallowLongPressAndDismiss();
289     }
290 
lockScrollTo(NotificationEntry entry)291     public void lockScrollTo(NotificationEntry entry) {
292         mDelegate.lockScrollTo(entry);
293     }
294 
295     /**
296      * Create a temporary grant which allows the app that submitted the notification access to the
297      * specified URI.
298      */
grantInlineReplyUriPermission(StatusBarNotification sbn, Uri data)299     public void grantInlineReplyUriPermission(StatusBarNotification sbn, Uri data) {
300         mRemoteInputUriController.grantInlineReplyUriPermission(sbn, data);
301     }
302 
303     /** dump debug info; called by {@link NotificationRemoteInputManager} */
dump(@onNull IndentingPrintWriter pw)304     public void dump(@NonNull IndentingPrintWriter pw) {
305         pw.print("mLastAppliedRemoteInputActive: ");
306         pw.println((Object) mLastAppliedRemoteInputActive);
307         pw.print("isRemoteInputActive: ");
308         pw.println(isRemoteInputActive()); // Note that this prunes the mOpen list, printed later.
309         pw.println("mOpen: " + mOpen.size());
310         DumpUtilsKt.withIncreasedIndent(pw, () -> {
311             for (Pair<WeakReference<NotificationEntry>, Object> open : mOpen) {
312                 NotificationEntry entry = open.first.get();
313                 pw.println(entry == null ? "???" : entry.getKey());
314             }
315         });
316         pw.println("mSpinning: " + mSpinning.size());
317         DumpUtilsKt.withIncreasedIndent(pw, () -> {
318             for (String key : mSpinning.keySet()) {
319                 pw.println(key);
320             }
321         });
322         pw.println(mSpinning);
323         pw.print("mDelegate: ");
324         pw.println(mDelegate);
325     }
326 
327     public interface Callback {
onRemoteInputActive(boolean active)328         default void onRemoteInputActive(boolean active) {}
329 
onRemoteInputSent(NotificationEntry entry)330         default void onRemoteInputSent(NotificationEntry entry) {}
331     }
332 
333     /**
334      * This is a delegate which implements some view controller pieces of the remote input process
335      */
336     public interface Delegate {
337         /**
338          * Activate remote input if necessary.
339          */
setRemoteInputActive(NotificationEntry entry, boolean remoteInputActive)340         void setRemoteInputActive(NotificationEntry entry, boolean remoteInputActive);
341 
342         /**
343          * Request that the view does not dismiss nor perform long press for the current touch.
344          */
requestDisallowLongPressAndDismiss()345         void requestDisallowLongPressAndDismiss();
346 
347         /**
348          * Request that the view is made visible by scrolling to it, and keep the scroll locked until
349          * the user scrolls, or {@param entry} loses focus or is detached.
350          */
lockScrollTo(NotificationEntry entry)351         void lockScrollTo(NotificationEntry entry);
352     }
353 }
354