blob: 0c0a555fd16a7a1459f1ff6720f99e0eb04f8ae1 [file] [log] [blame]
Felipe Leme3461d3c2017-01-19 08:54:55 -08001/*
2 * Copyright (C) 2017 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
17package android.view.autofill;
18
Felipe Lemea7de4022019-02-19 17:16:45 -080019import static android.service.autofill.FillRequest.FLAG_AUGMENTED_AUTOFILL_REQUEST;
felipealfd3f8f62018-02-07 11:49:07 +010020import static android.service.autofill.FillRequest.FLAG_MANUAL_REQUEST;
21import static android.view.autofill.Helper.sDebug;
22import static android.view.autofill.Helper.sVerbose;
23
Svetoslav Ganov24c90452017-12-27 15:17:14 -080024import android.accessibilityservice.AccessibilityServiceInfo;
Felipe Lemee6010f22017-03-03 11:19:51 -080025import android.annotation.IntDef;
Philip P. Moltmann44611812017-02-23 12:52:46 -080026import android.annotation.NonNull;
Felipe Lemee6010f22017-03-03 11:19:51 -080027import android.annotation.Nullable;
Jeff Sharkey98af2e42018-02-16 10:14:57 -070028import android.annotation.RequiresFeature;
Felipe Leme559e21d2019-01-18 17:57:21 -080029import android.annotation.SystemApi;
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060030import android.annotation.SystemService;
Felipe Leme2cab38c2019-01-11 10:39:14 -080031import android.annotation.TestApi;
Felipe Lemea4f39cd2019-02-19 15:08:59 -080032import android.content.AutofillOptions;
Felipe Leme17292d12017-10-24 14:03:10 -070033import android.content.ComponentName;
Felipe Leme3461d3c2017-01-19 08:54:55 -080034import android.content.Context;
Svet Ganov782043c2017-02-11 00:52:02 +000035import android.content.Intent;
36import android.content.IntentSender;
Svetoslav Ganov24c90452017-12-27 15:17:14 -080037import android.content.pm.PackageManager;
38import android.content.pm.ResolveInfo;
Felipe Leme3461d3c2017-01-19 08:54:55 -080039import android.graphics.Rect;
Felipe Leme4753bb02017-03-22 20:24:00 -070040import android.metrics.LogMaker;
Felipe Leme68b22222018-07-24 14:57:01 -070041import android.os.Build;
Svet Ganov782043c2017-02-11 00:52:02 +000042import android.os.Bundle;
Felipe Lemec24a56a2017-08-03 14:27:57 -070043import android.os.IBinder;
Svet Ganov782043c2017-02-11 00:52:02 +000044import android.os.Parcelable;
Felipe Leme3461d3c2017-01-19 08:54:55 -080045import android.os.RemoteException;
Philip P. Moltmanncc684ed2017-04-17 14:18:33 -070046import android.service.autofill.AutofillService;
47import android.service.autofill.FillEventHistory;
Felipe Leme452886a2017-11-27 13:09:13 -080048import android.service.autofill.UserData;
Felipe Leme4753bb02017-03-22 20:24:00 -070049import android.util.ArrayMap;
Philip P. Moltmann494c3f52017-04-11 10:13:33 -070050import android.util.ArraySet;
Felipe Leme3461d3c2017-01-19 08:54:55 -080051import android.util.Log;
Felipe Lemece404982018-09-17 09:46:13 -070052import android.util.Slog;
Felipe Leme4753bb02017-03-22 20:24:00 -070053import android.util.SparseArray;
Svetoslav Ganov24c90452017-12-27 15:17:14 -080054import android.view.Choreographer;
Dake Gu6a20a192018-02-08 12:09:30 -080055import android.view.KeyEvent;
Felipe Leme3461d3c2017-01-19 08:54:55 -080056import android.view.View;
Svetoslav Ganov24c90452017-12-27 15:17:14 -080057import android.view.accessibility.AccessibilityEvent;
58import android.view.accessibility.AccessibilityManager;
59import android.view.accessibility.AccessibilityNodeInfo;
60import android.view.accessibility.AccessibilityNodeProvider;
61import android.view.accessibility.AccessibilityWindowInfo;
felipealfd3f8f62018-02-07 11:49:07 +010062
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -070063import com.android.internal.annotations.GuardedBy;
Felipe Leme4753bb02017-03-22 20:24:00 -070064import com.android.internal.logging.MetricsLogger;
Felipe Lemeb22d6352017-09-08 20:03:53 -070065import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Felipe Lemed4e52282018-06-18 13:56:38 -070066import com.android.internal.os.IResultReceiver;
Svetoslav Ganov24c90452017-12-27 15:17:14 -080067import com.android.internal.util.ArrayUtils;
Felipe Leme637e05e2017-12-06 12:09:37 -080068import com.android.internal.util.Preconditions;
Felipe Lemec0c15a32019-01-08 10:53:33 -080069import com.android.internal.util.SyncResultReceiver;
felipealfd3f8f62018-02-07 11:49:07 +010070
Svetoslav Ganov24c90452017-12-27 15:17:14 -080071import org.xmlpull.v1.XmlPullParserException;
Felipe Leme4753bb02017-03-22 20:24:00 -070072
Svetoslav Ganov24c90452017-12-27 15:17:14 -080073import java.io.IOException;
Felipe Lemec24a56a2017-08-03 14:27:57 -070074import java.io.PrintWriter;
Felipe Lemee6010f22017-03-03 11:19:51 -080075import java.lang.annotation.Retention;
76import java.lang.annotation.RetentionPolicy;
Svet Ganov782043c2017-02-11 00:52:02 +000077import java.lang.ref.WeakReference;
Philip P. Moltmann134cee22017-05-06 11:28:38 -070078import java.util.ArrayList;
Felipe Lemebc055b02018-01-05 17:04:10 -080079import java.util.Arrays;
Felipe Leme27f45732017-12-22 09:05:22 -080080import java.util.Collections;
Svet Ganov782043c2017-02-11 00:52:02 +000081import java.util.List;
Philip P. Moltmannb42d1332017-03-27 09:55:30 -070082import java.util.Objects;
Felipe Leme7a3c9f52019-02-13 16:32:49 -080083import java.util.Set;
Felipe Lemec0c15a32019-01-08 10:53:33 -080084
Felipe Leme67e62092018-02-15 14:47:31 -080085//TODO: use java.lang.ref.Cleaner once Android supports Java 9
felipealfd3f8f62018-02-07 11:49:07 +010086import sun.misc.Cleaner;
Svetoslav Ganov24c90452017-12-27 15:17:14 -080087
Felipe Leme3461d3c2017-01-19 08:54:55 -080088/**
Laura Davis43e75d92018-08-10 15:46:06 -070089 * <p>The {@link AutofillManager} class provides ways for apps and custom views to
90 * integrate with the Autofill Framework lifecycle.
91 *
92 * <p>To learn about using Autofill in your app, read
93 * the <a href="/guide/topics/text/autofill">Autofill Framework</a> guides.
94 *
95 * <h3 id="autofill-lifecycle">Autofill lifecycle</h3>
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -070096 *
Felipe Leme744976e2017-07-31 11:34:14 -070097 * <p>The autofill lifecycle starts with the creation of an autofill context associated with an
Laura Davis43e75d92018-08-10 15:46:06 -070098 * activity context. The autofill context is created when one of the following methods is called for
Felipe Leme744976e2017-07-31 11:34:14 -070099 * the first time in an activity context, and the current user has an enabled autofill service:
100 *
101 * <ul>
102 * <li>{@link #notifyViewEntered(View)}
103 * <li>{@link #notifyViewEntered(View, int, Rect)}
104 * <li>{@link #requestAutofill(View)}
105 * </ul>
106 *
Laura Davis43e75d92018-08-10 15:46:06 -0700107 * <p>Typically, the context is automatically created when the first view of the activity is
Felipe Leme744976e2017-07-31 11:34:14 -0700108 * focused because {@code View.onFocusChanged()} indirectly calls
109 * {@link #notifyViewEntered(View)}. App developers can call {@link #requestAutofill(View)} to
110 * explicitly create it (for example, a custom view developer could offer a contextual menu action
111 * in a text-field view to let users manually request autofill).
112 *
113 * <p>After the context is created, the Android System creates a {@link android.view.ViewStructure}
114 * that represents the view hierarchy by calling
115 * {@link View#dispatchProvideAutofillStructure(android.view.ViewStructure, int)} in the root views
116 * of all application windows. By default, {@code dispatchProvideAutofillStructure()} results in
117 * subsequent calls to {@link View#onProvideAutofillStructure(android.view.ViewStructure, int)} and
118 * {@link View#onProvideAutofillVirtualStructure(android.view.ViewStructure, int)} for each view in
119 * the hierarchy.
120 *
121 * <p>The resulting {@link android.view.ViewStructure} is then passed to the autofill service, which
122 * parses it looking for views that can be autofilled. If the service finds such views, it returns
123 * a data structure to the Android System containing the following optional info:
124 *
125 * <ul>
126 * <li>Datasets used to autofill subsets of views in the activity.
127 * <li>Id of views that the service can save their values for future autofilling.
128 * </ul>
129 *
130 * <p>When the service returns datasets, the Android System displays an autofill dataset picker
Felipe Leme2fe3ade2017-09-28 15:03:36 -0700131 * UI associated with the view, when the view is focused on and is part of a dataset.
132 * The application can be notified when the UI is shown by registering an
Felipe Leme744976e2017-07-31 11:34:14 -0700133 * {@link AutofillCallback} through {@link #registerCallback(AutofillCallback)}. When the user
Felipe Leme2fe3ade2017-09-28 15:03:36 -0700134 * selects a dataset from the UI, all views present in the dataset are autofilled, through
Felipe Leme744976e2017-07-31 11:34:14 -0700135 * calls to {@link View#autofill(AutofillValue)} or {@link View#autofill(SparseArray)}.
136 *
137 * <p>When the service returns ids of savable views, the Android System keeps track of changes
138 * made to these views, so they can be used to determine if the autofill save UI is shown later.
139 *
140 * <p>The context is then finished when one of the following occurs:
141 *
142 * <ul>
143 * <li>{@link #commit()} is called or all savable views are gone.
144 * <li>{@link #cancel()} is called.
145 * </ul>
146 *
147 * <p>Finally, after the autofill context is commited (i.e., not cancelled), the Android System
Felipe Leme2fe3ade2017-09-28 15:03:36 -0700148 * shows an autofill save UI if the value of savable views have changed. If the user selects the
Felipe Leme744976e2017-07-31 11:34:14 -0700149 * option to Save, the current value of the views is then sent to the autofill service.
150 *
Laura Davis43e75d92018-08-10 15:46:06 -0700151 * <h3 id="additional-notes">Additional notes</h3>
152 *
153 * <p>It is safe to call <code>AutofillManager</code> methods from any thread.
Felipe Leme3461d3c2017-01-19 08:54:55 -0800154 */
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -0600155@SystemService(Context.AUTOFILL_MANAGER_SERVICE)
Jeff Sharkey98af2e42018-02-16 10:14:57 -0700156@RequiresFeature(PackageManager.FEATURE_AUTOFILL)
Felipe Leme640f30a2017-03-06 15:44:06 -0800157public final class AutofillManager {
Felipe Leme3461d3c2017-01-19 08:54:55 -0800158
Felipe Leme640f30a2017-03-06 15:44:06 -0800159 private static final String TAG = "AutofillManager";
Felipe Leme3461d3c2017-01-19 08:54:55 -0800160
Svet Ganov782043c2017-02-11 00:52:02 +0000161 /**
162 * Intent extra: The assist structure which captures the filled screen.
Felipe Leme7320ca92017-03-29 15:09:54 -0700163 *
Svet Ganov782043c2017-02-11 00:52:02 +0000164 * <p>
165 * Type: {@link android.app.assist.AssistStructure}
Svet Ganov782043c2017-02-11 00:52:02 +0000166 */
167 public static final String EXTRA_ASSIST_STRUCTURE =
168 "android.view.autofill.extra.ASSIST_STRUCTURE";
169
170 /**
171 * Intent extra: The result of an authentication operation. It is
172 * either a fully populated {@link android.service.autofill.FillResponse}
173 * or a fully populated {@link android.service.autofill.Dataset} if
174 * a response or a dataset is being authenticated respectively.
175 *
176 * <p>
177 * Type: {@link android.service.autofill.FillResponse} or a
178 * {@link android.service.autofill.Dataset}
Svet Ganov782043c2017-02-11 00:52:02 +0000179 */
180 public static final String EXTRA_AUTHENTICATION_RESULT =
181 "android.view.autofill.extra.AUTHENTICATION_RESULT";
182
Felipe Leme7320ca92017-03-29 15:09:54 -0700183 /**
184 * Intent extra: The optional extras provided by the
185 * {@link android.service.autofill.AutofillService}.
186 *
187 * <p>For example, when the service responds to a {@link
188 * android.service.autofill.FillCallback#onSuccess(android.service.autofill.FillResponse)} with
189 * a {@code FillResponse} that requires authentication, the Intent that launches the
190 * service authentication will contain the Bundle set by
Felipe Leme49e96962017-04-20 15:46:18 -0700191 * {@link android.service.autofill.FillResponse.Builder#setClientState(Bundle)} on this extra.
Felipe Leme7320ca92017-03-29 15:09:54 -0700192 *
Felipe Lemea9372382017-10-09 14:42:36 -0700193 * <p>On Android {@link android.os.Build.VERSION_CODES#P} and higher, the autofill service
194 * can also add this bundle to the {@link Intent} set as the
195 * {@link android.app.Activity#setResult(int, Intent) result} for an authentication request,
196 * so the bundle can be recovered later on
197 * {@link android.service.autofill.SaveRequest#getClientState()}.
198 *
Felipe Leme7320ca92017-03-29 15:09:54 -0700199 * <p>
200 * Type: {@link android.os.Bundle}
201 */
Felipe Leme37a440fd2017-04-28 10:50:20 -0700202 public static final String EXTRA_CLIENT_STATE =
Jeff Sharkey000ce802017-04-29 13:13:27 -0600203 "android.view.autofill.extra.CLIENT_STATE";
Felipe Leme7320ca92017-03-29 15:09:54 -0700204
Felipe Lemec24a56a2017-08-03 14:27:57 -0700205 /** @hide */
206 public static final String EXTRA_RESTORE_SESSION_TOKEN =
207 "android.view.autofill.extra.RESTORE_SESSION_TOKEN";
208
Felipe Leme284ad1c2018-11-15 18:16:12 -0800209 /**
210 * Internal extra used to pass a binder to the {@link IAugmentedAutofillManagerClient}.
211 *
212 * @hide
213 */
214 public static final String EXTRA_AUGMENTED_AUTOFILL_CLIENT =
215 "android.view.autofill.extra.AUGMENTED_AUTOFILL_CLIENT";
216
Felipe Lemec24a56a2017-08-03 14:27:57 -0700217 private static final String SESSION_ID_TAG = "android:sessionId";
218 private static final String STATE_TAG = "android:state";
219 private static final String LAST_AUTOFILLED_DATA_TAG = "android:lastAutoFilledData";
220
Felipe Leme0aa4c502017-04-26 12:36:01 -0700221 /** @hide */ public static final int ACTION_START_SESSION = 1;
222 /** @hide */ public static final int ACTION_VIEW_ENTERED = 2;
223 /** @hide */ public static final int ACTION_VIEW_EXITED = 3;
224 /** @hide */ public static final int ACTION_VALUE_CHANGED = 4;
Felipe Leme3461d3c2017-01-19 08:54:55 -0800225
Felipe Leme68b22222018-07-24 14:57:01 -0700226 /** @hide */ public static final int NO_LOGGING = 0;
Felipe Leme9f9ee252017-04-27 13:56:22 -0700227 /** @hide */ public static final int FLAG_ADD_CLIENT_ENABLED = 0x1;
228 /** @hide */ public static final int FLAG_ADD_CLIENT_DEBUG = 0x2;
229 /** @hide */ public static final int FLAG_ADD_CLIENT_VERBOSE = 0x4;
Felipe Leme68b22222018-07-24 14:57:01 -0700230 /** @hide */
231 public static final int DEFAULT_LOGGING_LEVEL = Build.IS_DEBUGGABLE
232 ? AutofillManager.FLAG_ADD_CLIENT_DEBUG
233 : AutofillManager.NO_LOGGING;
234
235 /** @hide */
236 public static final int DEFAULT_MAX_PARTITIONS_SIZE = 10;
Felipe Leme9f9ee252017-04-27 13:56:22 -0700237
Svetoslav Ganova9379d02017-05-09 17:40:24 -0700238 /** Which bits in an authentication id are used for the dataset id */
239 private static final int AUTHENTICATION_ID_DATASET_ID_MASK = 0xFFFF;
240 /** How many bits in an authentication id are used for the dataset id */
241 private static final int AUTHENTICATION_ID_DATASET_ID_SHIFT = 16;
242 /** @hide The index for an undefined data set */
243 public static final int AUTHENTICATION_ID_DATASET_ID_UNDEFINED = 0xFFFF;
244
245 /**
Felipe Lemec24a56a2017-08-03 14:27:57 -0700246 * Used on {@link #onPendingSaveUi(int, IBinder)} to cancel the pending UI.
247 *
248 * @hide
249 */
250 public static final int PENDING_UI_OPERATION_CANCEL = 1;
251
252 /**
253 * Used on {@link #onPendingSaveUi(int, IBinder)} to restore the pending UI.
254 *
255 * @hide
256 */
257 public static final int PENDING_UI_OPERATION_RESTORE = 2;
258
259 /**
260 * Initial state of the autofill context, set when there is no session (i.e., when
261 * {@link #mSessionId} is {@link #NO_SESSION}).
262 *
Felipe Lemec7b45292017-09-19 09:06:20 -0700263 * <p>In this state, app callbacks (such as {@link #notifyViewEntered(View)}) are notified to
264 * the server.
265 *
Felipe Lemec24a56a2017-08-03 14:27:57 -0700266 * @hide
267 */
Felipe Lemec7b45292017-09-19 09:06:20 -0700268 public static final int STATE_UNKNOWN = 0;
Felipe Lemec24a56a2017-08-03 14:27:57 -0700269
270 /**
271 * State where the autofill context hasn't been {@link #commit() finished} nor
272 * {@link #cancel() canceled} yet.
273 *
274 * @hide
275 */
Felipe Lemec7b45292017-09-19 09:06:20 -0700276 public static final int STATE_ACTIVE = 1;
277
278 /**
279 * State where the autofill context was finished by the server because the autofill
Felipe Leme17292d12017-10-24 14:03:10 -0700280 * service could not autofill the activity.
Felipe Lemec7b45292017-09-19 09:06:20 -0700281 *
282 * <p>In this state, most apps callback (such as {@link #notifyViewEntered(View)}) are ignored,
283 * exception {@link #requestAutofill(View)} (and {@link #requestAutofill(View, int, Rect)}).
284 *
285 * @hide
286 */
287 public static final int STATE_FINISHED = 2;
Felipe Lemec24a56a2017-08-03 14:27:57 -0700288
289 /**
290 * State where the autofill context has been {@link #commit() finished} but the server still has
291 * a session because the Save UI hasn't been dismissed yet.
292 *
293 * @hide
294 */
Felipe Lemec7b45292017-09-19 09:06:20 -0700295 public static final int STATE_SHOWING_SAVE_UI = 3;
Felipe Lemec24a56a2017-08-03 14:27:57 -0700296
297 /**
Felipe Leme17292d12017-10-24 14:03:10 -0700298 * State where the autofill is disabled because the service cannot autofill the activity at all.
299 *
300 * <p>In this state, every call is ignored, even {@link #requestAutofill(View)}
301 * (and {@link #requestAutofill(View, int, Rect)}).
302 *
303 * @hide
304 */
305 public static final int STATE_DISABLED_BY_SERVICE = 4;
306
307 /**
Felipe Leme0c8ce322018-03-23 13:54:22 -0700308 * Same as {@link #STATE_UNKNOWN}, but used on
309 * {@link AutofillManagerClient#setSessionFinished(int)} when the session was finished because
310 * the URL bar changed on client mode
311 *
312 * @hide
313 */
314 public static final int STATE_UNKNOWN_COMPAT_MODE = 5;
315
Felipe Lemed9dc9542018-09-19 11:54:28 -0700316 /**
317 * Same as {@link #STATE_UNKNOWN}, but used on
318 * {@link AutofillManagerClient#setSessionFinished(int)} when the session was finished because
319 * the service failed to fullfil a request.
320 *
321 * @hide
322 */
323 public static final int STATE_UNKNOWN_FAILED = 6;
Felipe Leme0c8ce322018-03-23 13:54:22 -0700324
325 /**
Felipe Lemebc055b02018-01-05 17:04:10 -0800326 * Timeout in ms for calls to the field classification service.
327 * @hide
328 */
329 public static final int FC_SERVICE_TIMEOUT = 5000;
330
331 /**
Felipe Lemec0c15a32019-01-08 10:53:33 -0800332 * Timeout for calls to system_server.
333 */
334 private static final int SYNC_CALLS_TIMEOUT_MS = 5000;
335
336 /**
Felipe Leme2cab38c2019-01-11 10:39:14 -0800337 * @hide
338 */
339 @TestApi
340 public static final int MAX_TEMP_AUGMENTED_SERVICE_DURATION_MS = 1_000 * 60 * 2; // 2 minutes
341
342 /**
Felipe Lemecc510272019-02-07 14:56:27 -0800343 * Disables Augmented Autofill.
344 *
345 * @hide
346 */
347 @TestApi
348 public static final int FLAG_SMART_SUGGESTION_OFF = 0x0;
349
350 /**
Felipe Leme559e21d2019-01-18 17:57:21 -0800351 * Displays the Augment Autofill window using the same mechanism (such as a popup-window
352 * attached to the focused view) as the standard autofill.
353 *
354 * @hide
355 */
356 @TestApi
357 public static final int FLAG_SMART_SUGGESTION_SYSTEM = 0x1;
358
Felipe Leme559e21d2019-01-18 17:57:21 -0800359 /** @hide */
Felipe Lemecc510272019-02-07 14:56:27 -0800360 @IntDef(flag = false, value = { FLAG_SMART_SUGGESTION_OFF, FLAG_SMART_SUGGESTION_SYSTEM })
Felipe Leme559e21d2019-01-18 17:57:21 -0800361 @Retention(RetentionPolicy.SOURCE)
362 public @interface SmartSuggestionMode {}
363
364 /**
Felipe Lemecc510272019-02-07 14:56:27 -0800365 * {@code DeviceConfig} property used to set which Smart Suggestion modes for Augmented Autofill
366 * are available.
Felipe Leme7841d022019-02-07 13:02:18 -0800367 *
368 * @hide
369 */
370 @TestApi
371 public static final String DEVICE_CONFIG_AUTOFILL_SMART_SUGGESTION_SUPPORTED_MODES =
372 "smart_suggestion_supported_modes";
373
Felipe Lemea8209102019-02-21 18:01:47 -0800374 /**
375 * Sets how long (in ms) the augmented autofill service is bound while idle.
376 *
377 * <p>Use {@code 0} to keep it permanently bound.
378 *
379 * @hide
380 */
381 public static final String DEVICE_CONFIG_AUGMENTED_SERVICE_IDLE_UNBIND_TIMEOUT =
382 "augmented_service_idle_unbind_timeout";
383
384 /**
385 * Sets how long (in ms) the augmented autofill service request is killed if not replied.
386 *
387 * @hide
388 */
389 public static final String DEVICE_CONFIG_AUGMENTED_SERVICE_REQUEST_TIMEOUT =
390 "augmented_service_request_timeout";
391
Felipe Leme80e7bf12019-02-14 10:56:52 -0800392 /** @hide */
393 public static final int RESULT_OK = 0;
394 /** @hide */
395 public static final int RESULT_CODE_NOT_SERVICE = -1;
396
Felipe Leme7841d022019-02-07 13:02:18 -0800397 /**
Svetoslav Ganova9379d02017-05-09 17:40:24 -0700398 * Makes an authentication id from a request id and a dataset id.
399 *
400 * @param requestId The request id.
401 * @param datasetId The dataset id.
402 * @return The authentication id.
403 * @hide
404 */
405 public static int makeAuthenticationId(int requestId, int datasetId) {
406 return (requestId << AUTHENTICATION_ID_DATASET_ID_SHIFT)
407 | (datasetId & AUTHENTICATION_ID_DATASET_ID_MASK);
408 }
409
410 /**
411 * Gets the request id from an authentication id.
412 *
413 * @param authRequestId The authentication id.
414 * @return The request id.
415 * @hide
416 */
417 public static int getRequestIdFromAuthenticationId(int authRequestId) {
418 return (authRequestId >> AUTHENTICATION_ID_DATASET_ID_SHIFT);
419 }
420
421 /**
422 * Gets the dataset id from an authentication id.
423 *
424 * @param authRequestId The authentication id.
425 * @return The dataset id.
426 * @hide
427 */
428 public static int getDatasetIdFromAuthenticationId(int authRequestId) {
429 return (authRequestId & AUTHENTICATION_ID_DATASET_ID_MASK);
430 }
431
Felipe Leme4753bb02017-03-22 20:24:00 -0700432 private final MetricsLogger mMetricsLogger = new MetricsLogger();
Svet Ganov782043c2017-02-11 00:52:02 +0000433
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700434 /**
435 * There is currently no session running.
436 * {@hide}
437 */
438 public static final int NO_SESSION = Integer.MIN_VALUE;
439
Svet Ganov782043c2017-02-11 00:52:02 +0000440 private final IAutoFillManager mService;
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700441
442 private final Object mLock = new Object();
443
444 @GuardedBy("mLock")
Svet Ganov782043c2017-02-11 00:52:02 +0000445 private IAutoFillManagerClient mServiceClient;
446
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700447 @GuardedBy("mLock")
Koji Fukuiccec6a62017-10-18 17:48:40 +0900448 private Cleaner mServiceClientCleaner;
449
450 @GuardedBy("mLock")
Felipe Leme284ad1c2018-11-15 18:16:12 -0800451 private IAugmentedAutofillManagerClient mAugmentedAutofillServiceClient;
452
453 @GuardedBy("mLock")
Felipe Lemee6010f22017-03-03 11:19:51 -0800454 private AutofillCallback mCallback;
455
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700456 private final Context mContext;
Svet Ganov782043c2017-02-11 00:52:02 +0000457
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700458 @GuardedBy("mLock")
459 private int mSessionId = NO_SESSION;
460
461 @GuardedBy("mLock")
Felipe Lemec24a56a2017-08-03 14:27:57 -0700462 private int mState = STATE_UNKNOWN;
463
464 @GuardedBy("mLock")
Svet Ganov782043c2017-02-11 00:52:02 +0000465 private boolean mEnabled;
466
Philip P. Moltmannb42d1332017-03-27 09:55:30 -0700467 /** If a view changes to this mapping the autofill operation was successful */
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700468 @GuardedBy("mLock")
Philip P. Moltmannb42d1332017-03-27 09:55:30 -0700469 @Nullable private ParcelableMap mLastAutofilledData;
470
Philip P. Moltmann494c3f52017-04-11 10:13:33 -0700471 /** If view tracking is enabled, contains the tracking state */
472 @GuardedBy("mLock")
473 @Nullable private TrackedViews mTrackedViews;
474
Felipe Leme27e20222017-05-18 15:24:11 -0700475 /** Views that are only tracked because they are fillable and could be anchoring the UI. */
476 @GuardedBy("mLock")
477 @Nullable private ArraySet<AutofillId> mFillableIds;
478
Dake Gub0fa3782018-02-26 12:25:14 -0800479 /** id of last requested autofill ui */
480 @Nullable private AutofillId mIdShownFillUi;
481
Felipe Leme9a15c0f2018-02-14 17:26:46 -0800482 /**
483 * Views that were already "entered" - if they're entered again when the session is not active,
484 * they're ignored
485 * */
486 @GuardedBy("mLock")
487 @Nullable private ArraySet<AutofillId> mEnteredIds;
488
Felipe Lemea7de4022019-02-19 17:16:45 -0800489 /**
490 * Views that were otherwised not important for autofill but triggered a session because the
491 * context is whitelisted for augmented autofill.
492 */
493 @GuardedBy("mLock")
494 @Nullable private Set<AutofillId> mEnteredForAugmentedAutofillIds;
495
Felipe Leme2fe3ade2017-09-28 15:03:36 -0700496 /** If set, session is commited when the field is clicked. */
497 @GuardedBy("mLock")
498 @Nullable private AutofillId mSaveTriggerId;
499
Dake Gu67decfa2017-12-27 11:48:08 -0800500 /** set to true when onInvisibleForAutofill is called, used by onAuthenticationResult */
501 @GuardedBy("mLock")
502 private boolean mOnInvisibleCalled;
503
Felipe Leme2fe3ade2017-09-28 15:03:36 -0700504 /** If set, session is commited when the activity is finished; otherwise session is canceled. */
505 @GuardedBy("mLock")
506 private boolean mSaveOnFinish;
507
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800508 /** If compatibility mode is enabled - this is a bridge to interact with a11y */
509 @GuardedBy("mLock")
510 private CompatibilityBridge mCompatibilityBridge;
511
Felipe Lemea4f39cd2019-02-19 15:08:59 -0800512 @Nullable
513 private final AutofillOptions mOptions;
514
Svet Ganov782043c2017-02-11 00:52:02 +0000515 /** @hide */
Felipe Leme640f30a2017-03-06 15:44:06 -0800516 public interface AutofillClient {
Svet Ganov782043c2017-02-11 00:52:02 +0000517 /**
Svet Ganov782043c2017-02-11 00:52:02 +0000518 * Asks the client to start an authentication flow.
519 *
Svetoslav Ganova9379d02017-05-09 17:40:24 -0700520 * @param authenticationId A unique id of the authentication operation.
Svet Ganov782043c2017-02-11 00:52:02 +0000521 * @param intent The authentication intent.
522 * @param fillInIntent The authentication fill-in intent.
523 */
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800524 void autofillClientAuthenticate(int authenticationId, IntentSender intent,
Svetoslav Ganova9379d02017-05-09 17:40:24 -0700525 Intent fillInIntent);
Svet Ganov17db9dc2017-02-21 19:54:31 -0800526
527 /**
528 * Tells the client this manager has state to be reset.
529 */
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800530 void autofillClientResetableStateAvailable();
Felipe Leme4753bb02017-03-22 20:24:00 -0700531
532 /**
533 * Request showing the autofill UI.
534 *
535 * @param anchor The real view the UI needs to anchor to.
536 * @param width The width of the fill UI content.
537 * @param height The height of the fill UI content.
538 * @param virtualBounds The bounds of the virtual decendant of the anchor.
539 * @param presenter The presenter that controls the fill UI window.
540 * @return Whether the UI was shown.
541 */
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800542 boolean autofillClientRequestShowFillUi(@NonNull View anchor, int width, int height,
Felipe Leme4753bb02017-03-22 20:24:00 -0700543 @Nullable Rect virtualBounds, IAutofillWindowPresenter presenter);
544
545 /**
Dake Gu6a20a192018-02-08 12:09:30 -0800546 * Dispatch unhandled keyevent from Autofill window
547 * @param anchor The real view the UI needs to anchor to.
548 * @param keyEvent Unhandled KeyEvent from autofill window.
549 */
550 void autofillClientDispatchUnhandledKey(@NonNull View anchor, @NonNull KeyEvent keyEvent);
551
552 /**
Felipe Leme4753bb02017-03-22 20:24:00 -0700553 * Request hiding the autofill UI.
554 *
555 * @return Whether the UI was hidden.
556 */
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800557 boolean autofillClientRequestHideFillUi();
558
559 /**
560 * Gets whether the fill UI is currenlty being shown.
561 *
562 * @return Whether the fill UI is currently being shown
563 */
564 boolean autofillClientIsFillUiShowing();
Philip P. Moltmann494c3f52017-04-11 10:13:33 -0700565
566 /**
Philip P. Moltmann134cee22017-05-06 11:28:38 -0700567 * Checks if views are currently attached and visible.
Philip P. Moltmann494c3f52017-04-11 10:13:33 -0700568 *
Philip P. Moltmann134cee22017-05-06 11:28:38 -0700569 * @return And array with {@code true} iff the view is attached or visible
Philip P. Moltmann494c3f52017-04-11 10:13:33 -0700570 */
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800571 @NonNull boolean[] autofillClientGetViewVisibility(@NonNull AutofillId[] autofillIds);
Philip P. Moltmann494c3f52017-04-11 10:13:33 -0700572
573 /**
574 * Checks is the client is currently visible as understood by autofill.
575 *
576 * @return {@code true} if the client is currently visible
577 */
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800578 boolean autofillClientIsVisibleForAutofill();
Philip P. Moltmann134cee22017-05-06 11:28:38 -0700579
580 /**
Dake Gu67decfa2017-12-27 11:48:08 -0800581 * Client might disable enter/exit event e.g. when activity is paused.
582 */
583 boolean isDisablingEnterExitEventForAutofill();
584
585 /**
Felipe Leme27e20222017-05-18 15:24:11 -0700586 * Finds views by traversing the hierarchies of the client.
Philip P. Moltmann134cee22017-05-06 11:28:38 -0700587 *
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800588 * @param autofillIds The autofill ids of the views to find
Philip P. Moltmann134cee22017-05-06 11:28:38 -0700589 *
Felipe Leme27e20222017-05-18 15:24:11 -0700590 * @return And array containing the views (empty if no views found).
Philip P. Moltmann134cee22017-05-06 11:28:38 -0700591 */
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800592 @NonNull View[] autofillClientFindViewsByAutofillIdTraversal(
593 @NonNull AutofillId[] autofillIds);
Felipe Leme27e20222017-05-18 15:24:11 -0700594
595 /**
596 * Finds a view by traversing the hierarchies of the client.
597 *
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800598 * @param autofillId The autofill id of the views to find
Felipe Leme27e20222017-05-18 15:24:11 -0700599 *
600 * @return The view, or {@code null} if not found
601 */
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800602 @Nullable View autofillClientFindViewByAutofillIdTraversal(@NonNull AutofillId autofillId);
603
604 /**
605 * Finds a view by a11y id in a given client window.
606 *
607 * @param viewId The accessibility id of the views to find
608 * @param windowId The accessibility window id where to search
609 *
610 * @return The view, or {@code null} if not found
611 */
612 @Nullable View autofillClientFindViewByAccessibilityIdTraversal(int viewId, int windowId);
Felipe Leme9876a6f2017-05-30 15:47:28 -0700613
614 /**
615 * Runs the specified action on the UI thread.
616 */
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800617 void autofillClientRunOnUiThread(Runnable action);
Felipe Leme17292d12017-10-24 14:03:10 -0700618
619 /**
620 * Gets the complete component name of this client.
621 */
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800622 ComponentName autofillClientGetComponentName();
623
624 /**
625 * Gets the activity token
626 */
627 @Nullable IBinder autofillClientGetActivityToken();
628
629 /**
630 * @return Whether compatibility mode is enabled.
631 */
Felipe Leme42b97932018-02-20 13:04:31 -0800632 boolean autofillClientIsCompatibilityModeEnabled();
633
634 /**
635 * Gets the next unique autofill ID.
636 *
637 * <p>Typically used to manage views whose content is recycled - see
638 * {@link View#setAutofillId(AutofillId)} for more info.
639 *
640 * @return An ID that is unique in the activity.
641 */
642 @Nullable AutofillId autofillClientGetNextAutofillId();
Svet Ganov782043c2017-02-11 00:52:02 +0000643 }
Felipe Leme3461d3c2017-01-19 08:54:55 -0800644
645 /**
646 * @hide
647 */
Felipe Leme640f30a2017-03-06 15:44:06 -0800648 public AutofillManager(Context context, IAutoFillManager service) {
Felipe Leme637e05e2017-12-06 12:09:37 -0800649 mContext = Preconditions.checkNotNull(context, "context cannot be null");
Felipe Leme3461d3c2017-01-19 08:54:55 -0800650 mService = service;
Felipe Lemea4f39cd2019-02-19 15:08:59 -0800651 mOptions = context.getAutofillOptions();
652
653 if (mOptions != null) {
654 sDebug = (mOptions.loggingLevel & FLAG_ADD_CLIENT_DEBUG) != 0;
655 sVerbose = (mOptions.loggingLevel & FLAG_ADD_CLIENT_VERBOSE) != 0;
656 }
Felipe Leme3461d3c2017-01-19 08:54:55 -0800657 }
658
659 /**
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800660 * @hide
661 */
662 public void enableCompatibilityMode() {
663 synchronized (mLock) {
664 // The accessibility manager is a singleton so we may need to plug
665 // different bridge based on which activity is currently focused
666 // in the current process. Since compat would be rarely used, just
667 // create and register a new instance every time.
Felipe Lemece404982018-09-17 09:46:13 -0700668 if (sDebug) {
669 Slog.d(TAG, "creating CompatibilityBridge for " + mContext);
670 }
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800671 mCompatibilityBridge = new CompatibilityBridge();
672 }
673 }
674
675 /**
Philip P. Moltmannb42d1332017-03-27 09:55:30 -0700676 * Restore state after activity lifecycle
677 *
678 * @param savedInstanceState The state to be restored
679 *
680 * {@hide}
681 */
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700682 public void onCreate(Bundle savedInstanceState) {
Svet Ganov43574b02017-04-12 09:25:20 -0700683 if (!hasAutofillFeature()) {
684 return;
685 }
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700686 synchronized (mLock) {
687 mLastAutofilledData = savedInstanceState.getParcelable(LAST_AUTOFILLED_DATA_TAG);
688
Felipe Lemec24a56a2017-08-03 14:27:57 -0700689 if (isActiveLocked()) {
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700690 Log.w(TAG, "New session was started before onCreate()");
691 return;
692 }
693
694 mSessionId = savedInstanceState.getInt(SESSION_ID_TAG, NO_SESSION);
Felipe Lemec24a56a2017-08-03 14:27:57 -0700695 mState = savedInstanceState.getInt(STATE_TAG, STATE_UNKNOWN);
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700696
697 if (mSessionId != NO_SESSION) {
698 ensureServiceClientAddedIfNeededLocked();
699
Felipe Leme637e05e2017-12-06 12:09:37 -0800700 final AutofillClient client = getClient();
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700701 if (client != null) {
Felipe Lemec0c15a32019-01-08 10:53:33 -0800702 final SyncResultReceiver receiver = new SyncResultReceiver(
703 SYNC_CALLS_TIMEOUT_MS);
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700704 try {
Felipe Lemed4e52282018-06-18 13:56:38 -0700705 mService.restoreSession(mSessionId, client.autofillClientGetActivityToken(),
706 mServiceClient.asBinder(), receiver);
707 final boolean sessionWasRestored = receiver.getIntResult() == 1;
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700708
709 if (!sessionWasRestored) {
710 Log.w(TAG, "Session " + mSessionId + " could not be restored");
711 mSessionId = NO_SESSION;
Felipe Lemec24a56a2017-08-03 14:27:57 -0700712 mState = STATE_UNKNOWN;
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700713 } else {
Felipe Leme9f9ee252017-04-27 13:56:22 -0700714 if (sDebug) {
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700715 Log.d(TAG, "session " + mSessionId + " was restored");
716 }
717
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800718 client.autofillClientResetableStateAvailable();
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700719 }
720 } catch (RemoteException e) {
721 Log.e(TAG, "Could not figure out if there was an autofill session", e);
722 }
723 }
724 }
725 }
726 }
727
728 /**
Philip P. Moltmann494c3f52017-04-11 10:13:33 -0700729 * Called once the client becomes visible.
730 *
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800731 * @see AutofillClient#autofillClientIsVisibleForAutofill()
Philip P. Moltmann494c3f52017-04-11 10:13:33 -0700732 *
733 * {@hide}
734 */
735 public void onVisibleForAutofill() {
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800736 // This gets called when the client just got visible at which point the visibility
737 // of the tracked views may not have been computed (due to a pending layout, etc).
738 // While generally we have no way to know when the UI has settled. We will evaluate
739 // the tracked views state at the end of next frame to guarantee that everything
740 // that may need to be laid out is laid out.
741 Choreographer.getInstance().postCallback(Choreographer.CALLBACK_COMMIT, () -> {
742 synchronized (mLock) {
743 if (mEnabled && isActiveLocked() && mTrackedViews != null) {
744 mTrackedViews.onVisibleForAutofillChangedLocked();
745 }
Philip P. Moltmann494c3f52017-04-11 10:13:33 -0700746 }
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800747 }, null);
Philip P. Moltmann494c3f52017-04-11 10:13:33 -0700748 }
749
750 /**
Dake Gu67decfa2017-12-27 11:48:08 -0800751 * Called once the client becomes invisible.
752 *
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800753 * @see AutofillClient#autofillClientIsVisibleForAutofill()
Dake Gu67decfa2017-12-27 11:48:08 -0800754 *
755 * {@hide}
756 */
757 public void onInvisibleForAutofill() {
758 synchronized (mLock) {
759 mOnInvisibleCalled = true;
760 }
761 }
762
763 /**
Philip P. Moltmannb42d1332017-03-27 09:55:30 -0700764 * Save state before activity lifecycle
765 *
766 * @param outState Place to store the state
767 *
768 * {@hide}
769 */
770 public void onSaveInstanceState(Bundle outState) {
Svet Ganov43574b02017-04-12 09:25:20 -0700771 if (!hasAutofillFeature()) {
772 return;
773 }
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700774 synchronized (mLock) {
775 if (mSessionId != NO_SESSION) {
776 outState.putInt(SESSION_ID_TAG, mSessionId);
777 }
Felipe Lemec24a56a2017-08-03 14:27:57 -0700778 if (mState != STATE_UNKNOWN) {
779 outState.putInt(STATE_TAG, mState);
780 }
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700781 if (mLastAutofilledData != null) {
782 outState.putParcelable(LAST_AUTOFILLED_DATA_TAG, mLastAutofilledData);
783 }
Philip P. Moltmannb42d1332017-03-27 09:55:30 -0700784 }
785 }
786
787 /**
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800788 * @hide
789 */
Andreas Gampe3f24e692018-02-05 13:24:28 -0800790 @GuardedBy("mLock")
felipealfd3f8f62018-02-07 11:49:07 +0100791 public boolean isCompatibilityModeEnabledLocked() {
792 return mCompatibilityBridge != null;
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800793 }
794
795 /**
Philip P. Moltmannb42d1332017-03-27 09:55:30 -0700796 * Checks whether autofill is enabled for the current user.
Felipe Leme2ac463e2017-03-13 14:06:25 -0700797 *
798 * <p>Typically used to determine whether the option to explicitly request autofill should
799 * be offered - see {@link #requestAutofill(View)}.
800 *
801 * @return whether autofill is enabled for the current user.
802 */
803 public boolean isEnabled() {
Felipe Leme3103c632017-12-18 15:05:14 -0800804 if (!hasAutofillFeature()) {
Svet Ganov43574b02017-04-12 09:25:20 -0700805 return false;
806 }
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700807 synchronized (mLock) {
Felipe Leme3103c632017-12-18 15:05:14 -0800808 if (isDisabledByServiceLocked()) {
809 return false;
810 }
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700811 ensureServiceClientAddedIfNeededLocked();
812 return mEnabled;
813 }
Felipe Leme2ac463e2017-03-13 14:06:25 -0700814 }
815
816 /**
Philip P. Moltmanncc684ed2017-04-17 14:18:33 -0700817 * Should always be called from {@link AutofillService#getFillEventHistory()}.
818 *
819 * @hide
820 */
821 @Nullable public FillEventHistory getFillEventHistory() {
822 try {
Felipe Lemec0c15a32019-01-08 10:53:33 -0800823 final SyncResultReceiver receiver = new SyncResultReceiver(SYNC_CALLS_TIMEOUT_MS);
Felipe Lemed4e52282018-06-18 13:56:38 -0700824 mService.getFillEventHistory(receiver);
Felipe Lemec0c15a32019-01-08 10:53:33 -0800825 return receiver.getParcelableResult();
Philip P. Moltmanncc684ed2017-04-17 14:18:33 -0700826 } catch (RemoteException e) {
827 e.rethrowFromSystemServer();
828 return null;
829 }
830 }
831
832 /**
Felipe Leme2ac463e2017-03-13 14:06:25 -0700833 * Explicitly requests a new autofill context.
834 *
Felipe Leme6dcec872017-05-25 11:24:23 -0700835 * <p>Normally, the autofill context is automatically started if necessary when
836 * {@link #notifyViewEntered(View)} is called, but this method should be used in the
837 * cases where it must be explicitly started. For example, when the view offers an AUTOFILL
838 * option on its contextual overflow menu, and the user selects it.
Felipe Leme2ac463e2017-03-13 14:06:25 -0700839 *
840 * @param view view requesting the new autofill context.
841 */
842 public void requestAutofill(@NonNull View view) {
Felipe Lemed1146422017-04-26 10:17:05 -0700843 notifyViewEntered(view, FLAG_MANUAL_REQUEST);
Felipe Leme2ac463e2017-03-13 14:06:25 -0700844 }
845
846 /**
847 * Explicitly requests a new autofill context for virtual views.
848 *
Felipe Leme6dcec872017-05-25 11:24:23 -0700849 * <p>Normally, the autofill context is automatically started if necessary when
850 * {@link #notifyViewEntered(View, int, Rect)} is called, but this method should be used in the
851 * cases where it must be explicitly started. For example, when the virtual view offers an
852 * AUTOFILL option on its contextual overflow menu, and the user selects it.
Felipe Leme2ac463e2017-03-13 14:06:25 -0700853 *
Felipe Leme6dcec872017-05-25 11:24:23 -0700854 * <p>The virtual view boundaries must be absolute screen coordinates. For example, if the
855 * parent view uses {@code bounds} to draw the virtual view inside its Canvas,
856 * the absolute bounds could be calculated by:
857 *
858 * <pre class="prettyprint">
859 * int offset[] = new int[2];
860 * getLocationOnScreen(offset);
861 * Rect absBounds = new Rect(bounds.left + offset[0],
862 * bounds.top + offset[1],
863 * bounds.right + offset[0], bounds.bottom + offset[1]);
864 * </pre>
865 *
866 * @param view the virtual view parent.
867 * @param virtualId id identifying the virtual child inside the parent view.
868 * @param absBounds absolute boundaries of the virtual view in the screen.
Felipe Leme2ac463e2017-03-13 14:06:25 -0700869 */
Felipe Leme6dcec872017-05-25 11:24:23 -0700870 public void requestAutofill(@NonNull View view, int virtualId, @NonNull Rect absBounds) {
871 notifyViewEntered(view, virtualId, absBounds, FLAG_MANUAL_REQUEST);
Felipe Leme2ac463e2017-03-13 14:06:25 -0700872 }
873
Felipe Leme2ac463e2017-03-13 14:06:25 -0700874 /**
Svet Ganov2f8fb1f2017-03-13 00:21:04 -0700875 * Called when a {@link View} that supports autofill is entered.
Felipe Leme3461d3c2017-01-19 08:54:55 -0800876 *
Svet Ganov2f8fb1f2017-03-13 00:21:04 -0700877 * @param view {@link View} that was entered.
Felipe Leme3461d3c2017-01-19 08:54:55 -0800878 */
Svet Ganov2f8fb1f2017-03-13 00:21:04 -0700879 public void notifyViewEntered(@NonNull View view) {
Felipe Lemed1146422017-04-26 10:17:05 -0700880 notifyViewEntered(view, 0);
881 }
882
Andreas Gampe3f24e692018-02-05 13:24:28 -0800883 @GuardedBy("mLock")
Felipe Leme9a15c0f2018-02-14 17:26:46 -0800884 private boolean shouldIgnoreViewEnteredLocked(@NonNull AutofillId id, int flags) {
Felipe Leme3103c632017-12-18 15:05:14 -0800885 if (isDisabledByServiceLocked()) {
Felipe Leme17292d12017-10-24 14:03:10 -0700886 if (sVerbose) {
Felipe Leme9a15c0f2018-02-14 17:26:46 -0800887 Log.v(TAG, "ignoring notifyViewEntered(flags=" + flags + ", view=" + id
888 + ") on state " + getStateAsStringLocked() + " because disabled by svc");
Felipe Leme17292d12017-10-24 14:03:10 -0700889 }
890 return true;
891 }
Felipe Leme9a15c0f2018-02-14 17:26:46 -0800892 if (isFinishedLocked()) {
893 // Session already finished: ignore if automatic request and view already entered
894 if ((flags & FLAG_MANUAL_REQUEST) == 0 && mEnteredIds != null
895 && mEnteredIds.contains(id)) {
896 if (sVerbose) {
897 Log.v(TAG, "ignoring notifyViewEntered(flags=" + flags + ", view=" + id
898 + ") on state " + getStateAsStringLocked()
899 + " because view was already entered: " + mEnteredIds);
900 }
901 return true;
902 }
903 }
Felipe Leme17292d12017-10-24 14:03:10 -0700904 return false;
905 }
906
Dake Gu67decfa2017-12-27 11:48:08 -0800907 private boolean isClientVisibleForAutofillLocked() {
908 final AutofillClient client = getClient();
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800909 return client != null && client.autofillClientIsVisibleForAutofill();
Dake Gu67decfa2017-12-27 11:48:08 -0800910 }
911
912 private boolean isClientDisablingEnterExitEvent() {
913 final AutofillClient client = getClient();
914 return client != null && client.isDisablingEnterExitEventForAutofill();
915 }
916
Felipe Lemed1146422017-04-26 10:17:05 -0700917 private void notifyViewEntered(@NonNull View view, int flags) {
Svet Ganov43574b02017-04-12 09:25:20 -0700918 if (!hasAutofillFeature()) {
919 return;
920 }
Dake Gu67decfa2017-12-27 11:48:08 -0800921 AutofillCallback callback;
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700922 synchronized (mLock) {
Dake Gu67decfa2017-12-27 11:48:08 -0800923 callback = notifyViewEnteredLocked(view, flags);
924 }
Felipe Lemec7b45292017-09-19 09:06:20 -0700925
Dake Gu67decfa2017-12-27 11:48:08 -0800926 if (callback != null) {
927 mCallback.onAutofillEvent(view, AutofillCallback.EVENT_INPUT_UNAVAILABLE);
928 }
929 }
Svet Ganov782043c2017-02-11 00:52:02 +0000930
Dake Gu67decfa2017-12-27 11:48:08 -0800931 /** Returns AutofillCallback if need fire EVENT_INPUT_UNAVAILABLE */
Andreas Gampe3f24e692018-02-05 13:24:28 -0800932 @GuardedBy("mLock")
Dake Gu67decfa2017-12-27 11:48:08 -0800933 private AutofillCallback notifyViewEnteredLocked(@NonNull View view, int flags) {
Felipe Leme42b97932018-02-20 13:04:31 -0800934 final AutofillId id = view.getAutofillId();
Felipe Leme9a15c0f2018-02-14 17:26:46 -0800935 if (shouldIgnoreViewEnteredLocked(id, flags)) return null;
Dake Gu67decfa2017-12-27 11:48:08 -0800936
937 AutofillCallback callback = null;
938
939 ensureServiceClientAddedIfNeededLocked();
940
941 if (!mEnabled) {
Felipe Lemef3b844b2018-10-02 13:50:50 -0700942 if (sVerbose) {
943 Log.v(TAG, "ignoring notifyViewEntered(" + id + "): disabled");
944 }
Dake Gu67decfa2017-12-27 11:48:08 -0800945 if (mCallback != null) {
946 callback = mCallback;
947 }
948 } else {
949 // don't notify entered when Activity is already in background
950 if (!isClientDisablingEnterExitEvent()) {
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700951 final AutofillValue value = view.getAutofillValue();
952
Felipe Lemec24a56a2017-08-03 14:27:57 -0700953 if (!isActiveLocked()) {
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700954 // Starts new session.
Philip P. Moltmann134cee22017-05-06 11:28:38 -0700955 startSessionLocked(id, null, value, flags);
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700956 } else {
957 // Update focus on existing session.
Felipe Leme0aa4c502017-04-26 12:36:01 -0700958 updateSessionLocked(id, null, value, ACTION_VIEW_ENTERED, flags);
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700959 }
Felipe Leme9a15c0f2018-02-14 17:26:46 -0800960 addEnteredIdLocked(id);
Felipe Leme24aae152017-03-15 12:33:01 -0700961 }
Felipe Lemebab851c2017-02-03 18:45:08 -0800962 }
Dake Gu67decfa2017-12-27 11:48:08 -0800963 return callback;
Felipe Lemebab851c2017-02-03 18:45:08 -0800964 }
965
966 /**
Svet Ganov2f8fb1f2017-03-13 00:21:04 -0700967 * Called when a {@link View} that supports autofill is exited.
Felipe Lemebab851c2017-02-03 18:45:08 -0800968 *
Svet Ganov2f8fb1f2017-03-13 00:21:04 -0700969 * @param view {@link View} that was exited.
Philip P. Moltmann44611812017-02-23 12:52:46 -0800970 */
Svet Ganov2f8fb1f2017-03-13 00:21:04 -0700971 public void notifyViewExited(@NonNull View view) {
Svet Ganov43574b02017-04-12 09:25:20 -0700972 if (!hasAutofillFeature()) {
973 return;
974 }
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700975 synchronized (mLock) {
Dake Gu67decfa2017-12-27 11:48:08 -0800976 notifyViewExitedLocked(view);
977 }
978 }
Philip P. Moltmann44611812017-02-23 12:52:46 -0800979
Andreas Gampe3f24e692018-02-05 13:24:28 -0800980 @GuardedBy("mLock")
Dake Gu67decfa2017-12-27 11:48:08 -0800981 void notifyViewExitedLocked(@NonNull View view) {
982 ensureServiceClientAddedIfNeededLocked();
983
984 if (mEnabled && isActiveLocked()) {
985 // dont notify exited when Activity is already in background
986 if (!isClientDisablingEnterExitEvent()) {
Felipe Leme42b97932018-02-20 13:04:31 -0800987 final AutofillId id = view.getAutofillId();
Philip P. Moltmann44611812017-02-23 12:52:46 -0800988
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700989 // Update focus on existing session.
Felipe Leme0aa4c502017-04-26 12:36:01 -0700990 updateSessionLocked(id, null, null, ACTION_VIEW_EXITED, 0);
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700991 }
Philip P. Moltmann44611812017-02-23 12:52:46 -0800992 }
993 }
994
995 /**
Svetoslav Ganov4db89ba2017-06-28 16:50:37 -0700996 * Called when a {@link View view's} visibility changed.
Philip P. Moltmann494c3f52017-04-11 10:13:33 -0700997 *
998 * @param view {@link View} that was exited.
999 * @param isVisible visible if the view is visible in the view hierarchy.
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07001000 */
Svetoslav Ganov4db89ba2017-06-28 16:50:37 -07001001 public void notifyViewVisibilityChanged(@NonNull View view, boolean isVisible) {
1002 notifyViewVisibilityChangedInternal(view, 0, isVisible, false);
1003 }
1004
1005 /**
1006 * Called when a virtual view's visibility changed.
1007 *
1008 * @param view {@link View} that was exited.
1009 * @param virtualId id identifying the virtual child inside the parent view.
1010 * @param isVisible visible if the view is visible in the view hierarchy.
1011 */
1012 public void notifyViewVisibilityChanged(@NonNull View view, int virtualId, boolean isVisible) {
1013 notifyViewVisibilityChangedInternal(view, virtualId, isVisible, true);
1014 }
1015
1016 /**
1017 * Called when a view/virtual view's visibility changed.
1018 *
1019 * @param view {@link View} that was exited.
1020 * @param virtualId id identifying the virtual child inside the parent view.
1021 * @param isVisible visible if the view is visible in the view hierarchy.
1022 * @param virtual Whether the view is virtual.
1023 */
1024 private void notifyViewVisibilityChangedInternal(@NonNull View view, int virtualId,
1025 boolean isVisible, boolean virtual) {
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07001026 synchronized (mLock) {
Felipe Lemec24a56a2017-08-03 14:27:57 -07001027 if (mEnabled && isActiveLocked()) {
Felipe Leme305fd402018-09-11 18:20:42 +00001028 final AutofillId id = virtual ? getAutofillId(view, virtualId)
Svetoslav Ganov4db89ba2017-06-28 16:50:37 -07001029 : view.getAutofillId();
Felipe Leme42b97932018-02-20 13:04:31 -08001030 if (sVerbose) Log.v(TAG, "visibility changed for " + id + ": " + isVisible);
Felipe Leme27e20222017-05-18 15:24:11 -07001031 if (!isVisible && mFillableIds != null) {
Felipe Leme27e20222017-05-18 15:24:11 -07001032 if (mFillableIds.contains(id)) {
1033 if (sDebug) Log.d(TAG, "Hidding UI when view " + id + " became invisible");
1034 requestHideFillUi(id, view);
1035 }
1036 }
1037 if (mTrackedViews != null) {
Dake Gu67decfa2017-12-27 11:48:08 -08001038 mTrackedViews.notifyViewVisibilityChangedLocked(id, isVisible);
Felipe Leme42b97932018-02-20 13:04:31 -08001039 } else if (sVerbose) {
1040 Log.v(TAG, "Ignoring visibility change on " + id + ": no tracked views");
Felipe Leme27e20222017-05-18 15:24:11 -07001041 }
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07001042 }
1043 }
1044 }
1045
1046 /**
Svet Ganov2f8fb1f2017-03-13 00:21:04 -07001047 * Called when a virtual view that supports autofill is entered.
Philip P. Moltmann44611812017-02-23 12:52:46 -08001048 *
Felipe Leme6dcec872017-05-25 11:24:23 -07001049 * <p>The virtual view boundaries must be absolute screen coordinates. For example, if the
1050 * parent, non-virtual view uses {@code bounds} to draw the virtual view inside its Canvas,
1051 * the absolute bounds could be calculated by:
1052 *
1053 * <pre class="prettyprint">
1054 * int offset[] = new int[2];
1055 * getLocationOnScreen(offset);
1056 * Rect absBounds = new Rect(bounds.left + offset[0],
1057 * bounds.top + offset[1],
1058 * bounds.right + offset[0], bounds.bottom + offset[1]);
1059 * </pre>
1060 *
1061 * @param view the virtual view parent.
1062 * @param virtualId id identifying the virtual child inside the parent view.
1063 * @param absBounds absolute boundaries of the virtual view in the screen.
Felipe Lemebab851c2017-02-03 18:45:08 -08001064 */
Felipe Leme6dcec872017-05-25 11:24:23 -07001065 public void notifyViewEntered(@NonNull View view, int virtualId, @NonNull Rect absBounds) {
1066 notifyViewEntered(view, virtualId, absBounds, 0);
Felipe Lemed1146422017-04-26 10:17:05 -07001067 }
1068
Felipe Leme6dcec872017-05-25 11:24:23 -07001069 private void notifyViewEntered(View view, int virtualId, Rect bounds, int flags) {
Svet Ganov43574b02017-04-12 09:25:20 -07001070 if (!hasAutofillFeature()) {
1071 return;
1072 }
Dake Gu67decfa2017-12-27 11:48:08 -08001073 AutofillCallback callback;
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001074 synchronized (mLock) {
Dake Gu67decfa2017-12-27 11:48:08 -08001075 callback = notifyViewEnteredLocked(view, virtualId, bounds, flags);
1076 }
Felipe Leme17292d12017-10-24 14:03:10 -07001077
Dake Gu67decfa2017-12-27 11:48:08 -08001078 if (callback != null) {
1079 callback.onAutofillEvent(view, virtualId,
1080 AutofillCallback.EVENT_INPUT_UNAVAILABLE);
1081 }
1082 }
Svet Ganov782043c2017-02-11 00:52:02 +00001083
Dake Gu67decfa2017-12-27 11:48:08 -08001084 /** Returns AutofillCallback if need fire EVENT_INPUT_UNAVAILABLE */
Andreas Gampe3f24e692018-02-05 13:24:28 -08001085 @GuardedBy("mLock")
Dake Gu67decfa2017-12-27 11:48:08 -08001086 private AutofillCallback notifyViewEnteredLocked(View view, int virtualId, Rect bounds,
1087 int flags) {
Felipe Leme305fd402018-09-11 18:20:42 +00001088 final AutofillId id = getAutofillId(view, virtualId);
Dake Gu67decfa2017-12-27 11:48:08 -08001089 AutofillCallback callback = null;
Felipe Leme9a15c0f2018-02-14 17:26:46 -08001090 if (shouldIgnoreViewEnteredLocked(id, flags)) return callback;
Dake Gu67decfa2017-12-27 11:48:08 -08001091
1092 ensureServiceClientAddedIfNeededLocked();
1093
1094 if (!mEnabled) {
Felipe Lemef3b844b2018-10-02 13:50:50 -07001095 if (sVerbose) {
1096 Log.v(TAG, "ignoring notifyViewEntered(" + id + "): disabled");
1097 }
Dake Gu67decfa2017-12-27 11:48:08 -08001098 if (mCallback != null) {
1099 callback = mCallback;
1100 }
1101 } else {
1102 // don't notify entered when Activity is already in background
1103 if (!isClientDisablingEnterExitEvent()) {
Felipe Lemec24a56a2017-08-03 14:27:57 -07001104 if (!isActiveLocked()) {
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001105 // Starts new session.
Philip P. Moltmann134cee22017-05-06 11:28:38 -07001106 startSessionLocked(id, bounds, null, flags);
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001107 } else {
1108 // Update focus on existing session.
Felipe Leme0aa4c502017-04-26 12:36:01 -07001109 updateSessionLocked(id, bounds, null, ACTION_VIEW_ENTERED, flags);
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001110 }
Felipe Leme9a15c0f2018-02-14 17:26:46 -08001111 addEnteredIdLocked(id);
Felipe Leme24aae152017-03-15 12:33:01 -07001112 }
Felipe Lemebab851c2017-02-03 18:45:08 -08001113 }
Dake Gu67decfa2017-12-27 11:48:08 -08001114 return callback;
Philip P. Moltmann44611812017-02-23 12:52:46 -08001115 }
1116
Felipe Leme9a15c0f2018-02-14 17:26:46 -08001117 @GuardedBy("mLock")
1118 private void addEnteredIdLocked(@NonNull AutofillId id) {
1119 if (mEnteredIds == null) {
1120 mEnteredIds = new ArraySet<>(1);
1121 }
1122 mEnteredIds.add(id);
1123 }
1124
Philip P. Moltmann44611812017-02-23 12:52:46 -08001125 /**
Svet Ganov2f8fb1f2017-03-13 00:21:04 -07001126 * Called when a virtual view that supports autofill is exited.
Philip P. Moltmann44611812017-02-23 12:52:46 -08001127 *
Felipe Leme6dcec872017-05-25 11:24:23 -07001128 * @param view the virtual view parent.
1129 * @param virtualId id identifying the virtual child inside the parent view.
Philip P. Moltmann44611812017-02-23 12:52:46 -08001130 */
Felipe Leme6dcec872017-05-25 11:24:23 -07001131 public void notifyViewExited(@NonNull View view, int virtualId) {
Felipe Leme54cc6832018-03-06 12:54:31 -08001132 if (sVerbose) Log.v(TAG, "notifyViewExited(" + view.getAutofillId() + ", " + virtualId);
Svet Ganov43574b02017-04-12 09:25:20 -07001133 if (!hasAutofillFeature()) {
1134 return;
1135 }
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001136 synchronized (mLock) {
Dake Gu67decfa2017-12-27 11:48:08 -08001137 notifyViewExitedLocked(view, virtualId);
1138 }
1139 }
Philip P. Moltmann44611812017-02-23 12:52:46 -08001140
Andreas Gampe3f24e692018-02-05 13:24:28 -08001141 @GuardedBy("mLock")
Dake Gu67decfa2017-12-27 11:48:08 -08001142 private void notifyViewExitedLocked(@NonNull View view, int virtualId) {
1143 ensureServiceClientAddedIfNeededLocked();
1144
1145 if (mEnabled && isActiveLocked()) {
1146 // don't notify exited when Activity is already in background
1147 if (!isClientDisablingEnterExitEvent()) {
Felipe Leme305fd402018-09-11 18:20:42 +00001148 final AutofillId id = getAutofillId(view, virtualId);
Philip P. Moltmann44611812017-02-23 12:52:46 -08001149
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001150 // Update focus on existing session.
Felipe Leme0aa4c502017-04-26 12:36:01 -07001151 updateSessionLocked(id, null, null, ACTION_VIEW_EXITED, 0);
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001152 }
Svet Ganov782043c2017-02-11 00:52:02 +00001153 }
Felipe Lemebab851c2017-02-03 18:45:08 -08001154 }
1155
1156 /**
Felipe Leme640f30a2017-03-06 15:44:06 -08001157 * Called to indicate the value of an autofillable {@link View} changed.
Felipe Lemebab851c2017-02-03 18:45:08 -08001158 *
Philip P. Moltmann44611812017-02-23 12:52:46 -08001159 * @param view view whose value changed.
Felipe Lemebab851c2017-02-03 18:45:08 -08001160 */
Svet Ganov2f8fb1f2017-03-13 00:21:04 -07001161 public void notifyValueChanged(View view) {
Svet Ganov43574b02017-04-12 09:25:20 -07001162 if (!hasAutofillFeature()) {
1163 return;
1164 }
Philip P. Moltmannb42d1332017-03-27 09:55:30 -07001165 AutofillId id = null;
1166 boolean valueWasRead = false;
1167 AutofillValue value = null;
1168
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001169 synchronized (mLock) {
1170 // If the session is gone some fields might still be highlighted, hence we have to
1171 // remove the isAutofilled property even if no sessions are active.
1172 if (mLastAutofilledData == null) {
1173 view.setAutofilled(false);
1174 } else {
Felipe Leme42b97932018-02-20 13:04:31 -08001175 id = view.getAutofillId();
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001176 if (mLastAutofilledData.containsKey(id)) {
1177 value = view.getAutofillValue();
1178 valueWasRead = true;
Philip P. Moltmannb42d1332017-03-27 09:55:30 -07001179
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001180 if (Objects.equals(mLastAutofilledData.get(id), value)) {
1181 view.setAutofilled(true);
1182 } else {
1183 view.setAutofilled(false);
1184 mLastAutofilledData.remove(id);
1185 }
Philip P. Moltmannb42d1332017-03-27 09:55:30 -07001186 } else {
1187 view.setAutofilled(false);
Philip P. Moltmannb42d1332017-03-27 09:55:30 -07001188 }
Philip P. Moltmannb42d1332017-03-27 09:55:30 -07001189 }
Philip P. Moltmannb42d1332017-03-27 09:55:30 -07001190
Felipe Lemec24a56a2017-08-03 14:27:57 -07001191 if (!mEnabled || !isActiveLocked()) {
Felipe Leme9a15c0f2018-02-14 17:26:46 -08001192 if (sVerbose) {
1193 Log.v(TAG, "notifyValueChanged(" + view.getAutofillId()
1194 + "): ignoring on state " + getStateAsStringLocked());
Felipe Lemec7b45292017-09-19 09:06:20 -07001195 }
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001196 return;
1197 }
Felipe Lemebab851c2017-02-03 18:45:08 -08001198
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001199 if (id == null) {
Felipe Leme42b97932018-02-20 13:04:31 -08001200 id = view.getAutofillId();
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001201 }
Philip P. Moltmannb42d1332017-03-27 09:55:30 -07001202
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001203 if (!valueWasRead) {
1204 value = view.getAutofillValue();
1205 }
Philip P. Moltmannb42d1332017-03-27 09:55:30 -07001206
Felipe Leme0aa4c502017-04-26 12:36:01 -07001207 updateSessionLocked(id, null, value, ACTION_VALUE_CHANGED, 0);
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001208 }
Felipe Lemebab851c2017-02-03 18:45:08 -08001209 }
1210
Felipe Lemebab851c2017-02-03 18:45:08 -08001211 /**
Felipe Leme6dcec872017-05-25 11:24:23 -07001212 * Called to indicate the value of an autofillable virtual view has changed.
Felipe Lemebab851c2017-02-03 18:45:08 -08001213 *
Felipe Leme6dcec872017-05-25 11:24:23 -07001214 * @param view the virtual view parent.
1215 * @param virtualId id identifying the virtual child inside the parent view.
Felipe Lemebab851c2017-02-03 18:45:08 -08001216 * @param value new value of the child.
1217 */
Felipe Leme6dcec872017-05-25 11:24:23 -07001218 public void notifyValueChanged(View view, int virtualId, AutofillValue value) {
Svet Ganov43574b02017-04-12 09:25:20 -07001219 if (!hasAutofillFeature()) {
1220 return;
1221 }
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001222 synchronized (mLock) {
Felipe Lemec24a56a2017-08-03 14:27:57 -07001223 if (!mEnabled || !isActiveLocked()) {
Felipe Leme9a15c0f2018-02-14 17:26:46 -08001224 if (sVerbose) {
1225 Log.v(TAG, "notifyValueChanged(" + view.getAutofillId() + ":" + virtualId
1226 + "): ignoring on state " + getStateAsStringLocked());
1227 }
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001228 return;
1229 }
Felipe Lemebab851c2017-02-03 18:45:08 -08001230
Felipe Leme305fd402018-09-11 18:20:42 +00001231 final AutofillId id = getAutofillId(view, virtualId);
Felipe Leme0aa4c502017-04-26 12:36:01 -07001232 updateSessionLocked(id, null, value, ACTION_VALUE_CHANGED, 0);
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001233 }
Felipe Lemebab851c2017-02-03 18:45:08 -08001234 }
1235
Felipe Leme2fe3ade2017-09-28 15:03:36 -07001236 /**
Felipe Leme67e62092018-02-15 14:47:31 -08001237 * Called to indicate a {@link View} is clicked.
Felipe Leme2fe3ade2017-09-28 15:03:36 -07001238 *
Felipe Leme67e62092018-02-15 14:47:31 -08001239 * @param view view that has been clicked.
Felipe Leme2fe3ade2017-09-28 15:03:36 -07001240 */
Felipe Leme67e62092018-02-15 14:47:31 -08001241 public void notifyViewClicked(@NonNull View view) {
1242 notifyViewClicked(view.getAutofillId());
1243 }
Felipe Leme2fe3ade2017-09-28 15:03:36 -07001244
Felipe Leme67e62092018-02-15 14:47:31 -08001245 /**
1246 * Called to indicate a virtual view has been clicked.
1247 *
1248 * @param view the virtual view parent.
1249 * @param virtualId id identifying the virtual child inside the parent view.
1250 */
1251 public void notifyViewClicked(@NonNull View view, int virtualId) {
Felipe Leme305fd402018-09-11 18:20:42 +00001252 notifyViewClicked(getAutofillId(view, virtualId));
Felipe Leme67e62092018-02-15 14:47:31 -08001253 }
1254
1255 private void notifyViewClicked(AutofillId id) {
1256 if (!hasAutofillFeature()) {
1257 return;
1258 }
Felipe Leme2fe3ade2017-09-28 15:03:36 -07001259 if (sVerbose) Log.v(TAG, "notifyViewClicked(): id=" + id + ", trigger=" + mSaveTriggerId);
1260
1261 synchronized (mLock) {
Felipe Leme67e62092018-02-15 14:47:31 -08001262 if (!mEnabled || !isActiveLocked()) {
1263 return;
1264 }
Felipe Leme2fe3ade2017-09-28 15:03:36 -07001265 if (mSaveTriggerId != null && mSaveTriggerId.equals(id)) {
1266 if (sDebug) Log.d(TAG, "triggering commit by click of " + id);
1267 commitLocked();
Felipe Leme11166522018-05-07 10:18:47 -07001268 mMetricsLogger.write(newLog(MetricsEvent.AUTOFILL_SAVE_EXPLICITLY_TRIGGERED));
Felipe Leme2fe3ade2017-09-28 15:03:36 -07001269 }
1270 }
1271 }
1272
1273 /**
1274 * Called by {@link android.app.Activity} to commit or cancel the session on finish.
1275 *
1276 * @hide
1277 */
Felipe Leme5b32ebe2018-02-15 12:52:19 -08001278 public void onActivityFinishing() {
Felipe Leme2fe3ade2017-09-28 15:03:36 -07001279 if (!hasAutofillFeature()) {
1280 return;
1281 }
1282 synchronized (mLock) {
1283 if (mSaveOnFinish) {
Felipe Leme5b32ebe2018-02-15 12:52:19 -08001284 if (sDebug) Log.d(TAG, "onActivityFinishing(): calling commitLocked()");
Felipe Leme2fe3ade2017-09-28 15:03:36 -07001285 commitLocked();
1286 } else {
Felipe Leme5b32ebe2018-02-15 12:52:19 -08001287 if (sDebug) Log.d(TAG, "onActivityFinishing(): calling cancelLocked()");
Felipe Leme2fe3ade2017-09-28 15:03:36 -07001288 cancelLocked();
1289 }
1290 }
1291 }
1292
Felipe Lemebab851c2017-02-03 18:45:08 -08001293 /**
Svet Ganov2f8fb1f2017-03-13 00:21:04 -07001294 * Called to indicate the current autofill context should be commited.
Felipe Lemebab851c2017-02-03 18:45:08 -08001295 *
Felipe Lemeafdfe762017-07-24 11:25:56 -07001296 * <p>This method is typically called by {@link View Views} that manage virtual views; for
1297 * example, when the view is rendering an {@code HTML} page with a form and virtual views
1298 * that represent the HTML elements, it should call this method after the form is submitted and
1299 * another page is rendered.
1300 *
1301 * <p><b>Note:</b> This method does not need to be called on regular application lifecycle
1302 * methods such as {@link android.app.Activity#finish()}.
Felipe Lemebab851c2017-02-03 18:45:08 -08001303 */
Svet Ganov2f8fb1f2017-03-13 00:21:04 -07001304 public void commit() {
Svet Ganov43574b02017-04-12 09:25:20 -07001305 if (!hasAutofillFeature()) {
1306 return;
1307 }
Felipe Leme5b32ebe2018-02-15 12:52:19 -08001308 if (sVerbose) Log.v(TAG, "commit() called by app");
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001309 synchronized (mLock) {
Felipe Leme2fe3ade2017-09-28 15:03:36 -07001310 commitLocked();
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001311 }
Felipe Leme0200d9e2017-01-24 15:10:26 -08001312 }
1313
Andreas Gampe3f24e692018-02-05 13:24:28 -08001314 @GuardedBy("mLock")
Felipe Leme2fe3ade2017-09-28 15:03:36 -07001315 private void commitLocked() {
1316 if (!mEnabled && !isActiveLocked()) {
1317 return;
1318 }
1319 finishSessionLocked();
1320 }
1321
Svet Ganov2f8fb1f2017-03-13 00:21:04 -07001322 /**
1323 * Called to indicate the current autofill context should be cancelled.
1324 *
Felipe Lemeafdfe762017-07-24 11:25:56 -07001325 * <p>This method is typically called by {@link View Views} that manage virtual views; for
1326 * example, when the view is rendering an {@code HTML} page with a form and virtual views
1327 * that represent the HTML elements, it should call this method if the user does not post the
1328 * form but moves to another form in this page.
1329 *
1330 * <p><b>Note:</b> This method does not need to be called on regular application lifecycle
1331 * methods such as {@link android.app.Activity#finish()}.
Svet Ganov2f8fb1f2017-03-13 00:21:04 -07001332 */
1333 public void cancel() {
Felipe Leme601d2202017-11-17 08:21:23 -08001334 if (sVerbose) Log.v(TAG, "cancel() called by app");
Svet Ganov43574b02017-04-12 09:25:20 -07001335 if (!hasAutofillFeature()) {
1336 return;
1337 }
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001338 synchronized (mLock) {
Felipe Leme2fe3ade2017-09-28 15:03:36 -07001339 cancelLocked();
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001340 }
Svet Ganov2f8fb1f2017-03-13 00:21:04 -07001341 }
1342
Andreas Gampe3f24e692018-02-05 13:24:28 -08001343 @GuardedBy("mLock")
Felipe Leme2fe3ade2017-09-28 15:03:36 -07001344 private void cancelLocked() {
1345 if (!mEnabled && !isActiveLocked()) {
1346 return;
1347 }
1348 cancelSessionLocked();
1349 }
1350
Svet Ganovf965b872017-04-28 16:34:02 -07001351 /** @hide */
1352 public void disableOwnedAutofillServices() {
1353 disableAutofillServices();
1354 }
1355
Svet Ganovf20a0372017-04-10 17:08:05 -07001356 /**
1357 * If the app calling this API has enabled autofill services they
1358 * will be disabled.
1359 */
Svet Ganovf965b872017-04-28 16:34:02 -07001360 public void disableAutofillServices() {
Svet Ganov43574b02017-04-12 09:25:20 -07001361 if (!hasAutofillFeature()) {
1362 return;
1363 }
Svet Ganovf20a0372017-04-10 17:08:05 -07001364 try {
1365 mService.disableOwnedAutofillServices(mContext.getUserId());
1366 } catch (RemoteException e) {
1367 throw e.rethrowFromSystemServer();
1368 }
1369 }
1370
Felipe Lemedb041182017-04-21 17:33:38 -07001371 /**
1372 * Returns {@code true} if the calling application provides a {@link AutofillService} that is
1373 * enabled for the current user, or {@code false} otherwise.
1374 */
1375 public boolean hasEnabledAutofillServices() {
1376 if (mService == null) return false;
1377
Felipe Lemec0c15a32019-01-08 10:53:33 -08001378 final SyncResultReceiver receiver = new SyncResultReceiver(SYNC_CALLS_TIMEOUT_MS);
Felipe Lemedb041182017-04-21 17:33:38 -07001379 try {
Felipe Lemed4e52282018-06-18 13:56:38 -07001380 mService.isServiceEnabled(mContext.getUserId(), mContext.getPackageName(), receiver);
1381 return receiver.getIntResult() == 1;
Felipe Lemedb041182017-04-21 17:33:38 -07001382 } catch (RemoteException e) {
1383 throw e.rethrowFromSystemServer();
1384 }
1385 }
1386
1387 /**
Felipe Leme23c75ff2017-12-14 13:27:44 -08001388 * Returns the component name of the {@link AutofillService} that is enabled for the current
1389 * user.
1390 */
1391 @Nullable
1392 public ComponentName getAutofillServiceComponentName() {
1393 if (mService == null) return null;
1394
Felipe Lemec0c15a32019-01-08 10:53:33 -08001395 final SyncResultReceiver receiver = new SyncResultReceiver(SYNC_CALLS_TIMEOUT_MS);
Felipe Leme23c75ff2017-12-14 13:27:44 -08001396 try {
Felipe Lemed4e52282018-06-18 13:56:38 -07001397 mService.getAutofillServiceComponentName(receiver);
Felipe Lemec0c15a32019-01-08 10:53:33 -08001398 return receiver.getParcelableResult();
Felipe Leme23c75ff2017-12-14 13:27:44 -08001399 } catch (RemoteException e) {
1400 throw e.rethrowFromSystemServer();
1401 }
1402 }
1403
1404 /**
Felipe Lemef0baef742018-01-26 14:39:39 -08001405 * Gets the id of the {@link UserData} used for
1406 * <a href="AutofillService.html#FieldClassification">field classification</a>.
1407 *
1408 * <p>This method is useful when the service must check the status of the {@link UserData} in
1409 * the device without fetching the whole object.
1410 *
1411 * <p><b>Note:</b> This method should only be called by an app providing an autofill service,
1412 * and it's ignored if the caller currently doesn't have an enabled autofill service for
1413 * the user.
1414 *
1415 * @return id of the {@link UserData} previously set by {@link #setUserData(UserData)}
1416 * or {@code null} if it was reset or if the caller currently does not have an enabled autofill
1417 * service for the user.
1418 */
1419 @Nullable public String getUserDataId() {
1420 try {
Felipe Lemec0c15a32019-01-08 10:53:33 -08001421 final SyncResultReceiver receiver = new SyncResultReceiver(SYNC_CALLS_TIMEOUT_MS);
Felipe Lemed4e52282018-06-18 13:56:38 -07001422 mService.getUserDataId(receiver);
Felipe Lemec0c15a32019-01-08 10:53:33 -08001423 return receiver.getStringResult();
Felipe Lemef0baef742018-01-26 14:39:39 -08001424 } catch (RemoteException e) {
1425 e.rethrowFromSystemServer();
1426 return null;
1427 }
1428 }
1429
1430 /**
Felipe Leme78172e72017-12-08 17:01:15 -08001431 * Gets the user data used for
1432 * <a href="AutofillService.html#FieldClassification">field classification</a>.
Felipe Leme452886a2017-11-27 13:09:13 -08001433 *
Felipe Leme27f45732017-12-22 09:05:22 -08001434 * <p><b>Note:</b> This method should only be called by an app providing an autofill service,
1435 * and it's ignored if the caller currently doesn't have an enabled autofill service for
1436 * the user.
Felipe Leme452886a2017-11-27 13:09:13 -08001437 *
Felipe Leme452886a2017-11-27 13:09:13 -08001438 * @return value previously set by {@link #setUserData(UserData)} or {@code null} if it was
1439 * reset or if the caller currently does not have an enabled autofill service for the user.
Felipe Leme452886a2017-11-27 13:09:13 -08001440 */
Felipe Leme452886a2017-11-27 13:09:13 -08001441 @Nullable public UserData getUserData() {
1442 try {
Felipe Lemec0c15a32019-01-08 10:53:33 -08001443 final SyncResultReceiver receiver = new SyncResultReceiver(SYNC_CALLS_TIMEOUT_MS);
Felipe Lemed4e52282018-06-18 13:56:38 -07001444 mService.getUserData(receiver);
Felipe Lemec0c15a32019-01-08 10:53:33 -08001445 return receiver.getParcelableResult();
Felipe Leme452886a2017-11-27 13:09:13 -08001446 } catch (RemoteException e) {
1447 e.rethrowFromSystemServer();
1448 return null;
1449 }
1450 }
1451
1452 /**
Felipe Lemef0baef742018-01-26 14:39:39 -08001453 * Sets the {@link UserData} used for
Felipe Leme78172e72017-12-08 17:01:15 -08001454 * <a href="AutofillService.html#FieldClassification">field classification</a>
Felipe Leme452886a2017-11-27 13:09:13 -08001455 *
1456 * <p><b>Note:</b> This method should only be called by an app providing an autofill service,
1457 * and it's ignored if the caller currently doesn't have an enabled autofill service for
1458 * the user.
Felipe Leme452886a2017-11-27 13:09:13 -08001459 */
Felipe Leme452886a2017-11-27 13:09:13 -08001460 public void setUserData(@Nullable UserData userData) {
1461 try {
1462 mService.setUserData(userData);
1463 } catch (RemoteException e) {
1464 e.rethrowFromSystemServer();
1465 }
1466 }
1467
1468 /**
Felipe Leme78172e72017-12-08 17:01:15 -08001469 * Checks if <a href="AutofillService.html#FieldClassification">field classification</a> is
1470 * enabled.
1471 *
1472 * <p>As field classification is an expensive operation, it could be disabled, either
1473 * temporarily (for example, because the service exceeded a rate-limit threshold) or
1474 * permanently (for example, because the device is a low-level device).
1475 *
1476 * <p><b>Note:</b> This method should only be called by an app providing an autofill service,
1477 * and it's ignored if the caller currently doesn't have an enabled autofill service for
1478 * the user.
Felipe Leme329d0402017-12-06 09:22:43 -08001479 */
Felipe Leme329d0402017-12-06 09:22:43 -08001480 public boolean isFieldClassificationEnabled() {
Felipe Lemec0c15a32019-01-08 10:53:33 -08001481 final SyncResultReceiver receiver = new SyncResultReceiver(SYNC_CALLS_TIMEOUT_MS);
Felipe Leme329d0402017-12-06 09:22:43 -08001482 try {
Felipe Lemed4e52282018-06-18 13:56:38 -07001483 mService.isFieldClassificationEnabled(receiver);
1484 return receiver.getIntResult() == 1;
Felipe Leme329d0402017-12-06 09:22:43 -08001485 } catch (RemoteException e) {
1486 e.rethrowFromSystemServer();
1487 return false;
1488 }
1489 }
1490
1491 /**
Felipe Leme27f45732017-12-22 09:05:22 -08001492 * Gets the name of the default algorithm used for
1493 * <a href="AutofillService.html#FieldClassification">field classification</a>.
1494 *
1495 * <p>The default algorithm is used when the algorithm on {@link UserData} is invalid or not
1496 * set.
1497 *
1498 * <p><b>Note:</b> This method should only be called by an app providing an autofill service,
1499 * and it's ignored if the caller currently doesn't have an enabled autofill service for
1500 * the user.
1501 */
1502 @Nullable
1503 public String getDefaultFieldClassificationAlgorithm() {
Felipe Lemec0c15a32019-01-08 10:53:33 -08001504 final SyncResultReceiver receiver = new SyncResultReceiver(SYNC_CALLS_TIMEOUT_MS);
Felipe Leme27f45732017-12-22 09:05:22 -08001505 try {
Felipe Lemed4e52282018-06-18 13:56:38 -07001506 mService.getDefaultFieldClassificationAlgorithm(receiver);
Felipe Lemec0c15a32019-01-08 10:53:33 -08001507 return receiver.getStringResult();
Felipe Leme27f45732017-12-22 09:05:22 -08001508 } catch (RemoteException e) {
1509 e.rethrowFromSystemServer();
1510 return null;
1511 }
1512 }
1513
1514 /**
1515 * Gets the name of all algorithms currently available for
1516 * <a href="AutofillService.html#FieldClassification">field classification</a>.
1517 *
1518 * <p><b>Note:</b> This method should only be called by an app providing an autofill service,
Felipe Lemebc055b02018-01-05 17:04:10 -08001519 * and it returns an empty list if the caller currently doesn't have an enabled autofill service
1520 * for the user.
Felipe Leme27f45732017-12-22 09:05:22 -08001521 */
1522 @NonNull
1523 public List<String> getAvailableFieldClassificationAlgorithms() {
Felipe Lemec0c15a32019-01-08 10:53:33 -08001524 final SyncResultReceiver receiver = new SyncResultReceiver(SYNC_CALLS_TIMEOUT_MS);
Felipe Leme27f45732017-12-22 09:05:22 -08001525 try {
Felipe Lemed4e52282018-06-18 13:56:38 -07001526 mService.getAvailableFieldClassificationAlgorithms(receiver);
Felipe Lemec0c15a32019-01-08 10:53:33 -08001527 final String[] algorithms = receiver.getStringArrayResult();
Felipe Lemee4ac7402018-01-16 19:37:00 -08001528 return algorithms != null ? Arrays.asList(algorithms) : Collections.emptyList();
Felipe Leme27f45732017-12-22 09:05:22 -08001529 } catch (RemoteException e) {
1530 e.rethrowFromSystemServer();
1531 return null;
1532 }
1533 }
1534
1535 /**
Ricardo Loo33d226c2017-06-27 14:17:33 -07001536 * Returns {@code true} if autofill is supported by the current device and
1537 * is supported for this user.
Felipe Lemedb041182017-04-21 17:33:38 -07001538 *
1539 * <p>Autofill is typically supported, but it could be unsupported in cases like:
1540 * <ol>
1541 * <li>Low-end devices.
1542 * <li>Device policy rules that forbid its usage.
1543 * </ol>
1544 */
1545 public boolean isAutofillSupported() {
1546 if (mService == null) return false;
1547
Felipe Lemec0c15a32019-01-08 10:53:33 -08001548 final SyncResultReceiver receiver = new SyncResultReceiver(SYNC_CALLS_TIMEOUT_MS);
Felipe Lemedb041182017-04-21 17:33:38 -07001549 try {
Felipe Lemed4e52282018-06-18 13:56:38 -07001550 mService.isServiceSupported(mContext.getUserId(), receiver);
1551 return receiver.getIntResult() == 1;
Felipe Lemedb041182017-04-21 17:33:38 -07001552 } catch (RemoteException e) {
1553 throw e.rethrowFromSystemServer();
1554 }
1555 }
1556
Felipe Leme637e05e2017-12-06 12:09:37 -08001557 // Note: don't need to use locked suffix because mContext is final.
1558 private AutofillClient getClient() {
Felipe Leme686128e2017-10-17 14:02:20 -07001559 final AutofillClient client = mContext.getAutofillClient();
Felipe Leme261e75f2018-12-17 10:15:08 -08001560 if (client == null && sVerbose) {
1561 Log.v(TAG, "No AutofillClient for " + mContext.getPackageName() + " on context "
Felipe Leme686128e2017-10-17 14:02:20 -07001562 + mContext);
1563 }
1564 return client;
Svet Ganov782043c2017-02-11 00:52:02 +00001565 }
1566
Dake Gud9dbd272018-03-13 11:38:42 -07001567 /**
1568 * Check if autofill ui is showing, must be called on UI thread.
1569 * @hide
1570 */
1571 public boolean isAutofillUiShowing() {
1572 final AutofillClient client = mContext.getAutofillClient();
Felipe Lemecb2e83d2018-03-19 11:15:00 -07001573 return client != null && client.autofillClientIsFillUiShowing();
Dake Gud9dbd272018-03-13 11:38:42 -07001574 }
1575
Svet Ganov782043c2017-02-11 00:52:02 +00001576 /** @hide */
Dake Gu67decfa2017-12-27 11:48:08 -08001577 public void onAuthenticationResult(int authenticationId, Intent data, View focusView) {
Svet Ganov43574b02017-04-12 09:25:20 -07001578 if (!hasAutofillFeature()) {
1579 return;
1580 }
Felipe Leme85d1c2d2017-04-21 08:56:04 -07001581 // TODO: the result code is being ignored, so this method is not reliably
Felipe Lemed633f072017-02-14 10:17:17 -08001582 // handling the cases where it's not RESULT_OK: it works fine if the service does not
1583 // set the EXTRA_AUTHENTICATION_RESULT extra, but it could cause weird results if the
1584 // service set the extra and returned RESULT_CANCELED...
1585
Felipe Leme1ad95f02018-06-15 13:07:34 -07001586 if (sDebug) {
1587 Log.d(TAG, "onAuthenticationResult(): id= " + authenticationId + ", data=" + data);
1588 }
Felipe Lemed633f072017-02-14 10:17:17 -08001589
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001590 synchronized (mLock) {
Dake Gu67decfa2017-12-27 11:48:08 -08001591 if (!isActiveLocked()) {
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001592 return;
1593 }
Dake Gu67decfa2017-12-27 11:48:08 -08001594 // If authenticate activity closes itself during onCreate(), there is no onStop/onStart
1595 // of app activity. We enforce enter event to re-show fill ui in such case.
1596 // CTS example:
1597 // LoginActivityTest#testDatasetAuthTwoFieldsUserCancelsFirstAttempt
1598 // LoginActivityTest#testFillResponseAuthBothFieldsUserCancelsFirstAttempt
1599 if (!mOnInvisibleCalled && focusView != null
1600 && focusView.canNotifyAutofillEnterExitEvent()) {
1601 notifyViewExitedLocked(focusView);
1602 notifyViewEnteredLocked(focusView, 0);
1603 }
1604 if (data == null) {
1605 // data is set to null when result is not RESULT_OK
1606 return;
1607 }
1608
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001609 final Parcelable result = data.getParcelableExtra(EXTRA_AUTHENTICATION_RESULT);
1610 final Bundle responseData = new Bundle();
1611 responseData.putParcelable(EXTRA_AUTHENTICATION_RESULT, result);
Felipe Lemea9372382017-10-09 14:42:36 -07001612 final Bundle newClientState = data.getBundleExtra(EXTRA_CLIENT_STATE);
1613 if (newClientState != null) {
1614 responseData.putBundle(EXTRA_CLIENT_STATE, newClientState);
1615 }
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001616 try {
Svetoslav Ganova9379d02017-05-09 17:40:24 -07001617 mService.setAuthenticationResult(responseData, mSessionId, authenticationId,
1618 mContext.getUserId());
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001619 } catch (RemoteException e) {
1620 Log.e(TAG, "Error delivering authentication result", e);
1621 }
Svet Ganov782043c2017-02-11 00:52:02 +00001622 }
Felipe Lemebab851c2017-02-03 18:45:08 -08001623 }
1624
Felipe Leme42b97932018-02-20 13:04:31 -08001625 /**
1626 * Gets the next unique autofill ID for the activity context.
1627 *
1628 * <p>Typically used to manage views whose content is recycled - see
1629 * {@link View#setAutofillId(AutofillId)} for more info.
1630 *
1631 * @return An ID that is unique in the activity, or {@code null} if autofill is not supported in
1632 * the {@link Context} associated with this {@link AutofillManager}.
1633 */
1634 @Nullable
1635 public AutofillId getNextAutofillId() {
1636 final AutofillClient client = getClient();
1637 if (client == null) return null;
1638
1639 final AutofillId id = client.autofillClientGetNextAutofillId();
1640
1641 if (id == null && sDebug) {
1642 Log.d(TAG, "getNextAutofillId(): client " + client + " returned null");
1643 }
1644
1645 return id;
Felipe Leme0200d9e2017-01-24 15:10:26 -08001646 }
1647
Felipe Leme305fd402018-09-11 18:20:42 +00001648 private static AutofillId getAutofillId(View parent, int virtualId) {
1649 return new AutofillId(parent.getAutofillViewId(), virtualId);
Felipe Lemebab851c2017-02-03 18:45:08 -08001650 }
1651
Andreas Gampe3f24e692018-02-05 13:24:28 -08001652 @GuardedBy("mLock")
Philip P. Moltmann134cee22017-05-06 11:28:38 -07001653 private void startSessionLocked(@NonNull AutofillId id, @NonNull Rect bounds,
1654 @NonNull AutofillValue value, int flags) {
Felipe Lemea7de4022019-02-19 17:16:45 -08001655 if (mEnteredForAugmentedAutofillIds != null
1656 && mEnteredForAugmentedAutofillIds.contains(id)) {
1657 if (sVerbose) Log.v(TAG, "Starting session for augmented autofill on " + id);
1658 flags |= FLAG_AUGMENTED_AUTOFILL_REQUEST;
1659 }
Felipe Leme9f9ee252017-04-27 13:56:22 -07001660 if (sVerbose) {
1661 Log.v(TAG, "startSessionLocked(): id=" + id + ", bounds=" + bounds + ", value=" + value
felipealfd3f8f62018-02-07 11:49:07 +01001662 + ", flags=" + flags + ", state=" + getStateAsStringLocked()
Felipe Leme9a15c0f2018-02-14 17:26:46 -08001663 + ", compatMode=" + isCompatibilityModeEnabledLocked()
1664 + ", enteredIds=" + mEnteredIds);
Felipe Lemebab851c2017-02-03 18:45:08 -08001665 }
Felipe Leme3103c632017-12-18 15:05:14 -08001666 if (mState != STATE_UNKNOWN && !isFinishedLocked() && (flags & FLAG_MANUAL_REQUEST) == 0) {
Felipe Lemec7b45292017-09-19 09:06:20 -07001667 if (sVerbose) {
1668 Log.v(TAG, "not automatically starting session for " + id
Felipe Leme3103c632017-12-18 15:05:14 -08001669 + " on state " + getStateAsStringLocked() + " and flags " + flags);
Felipe Lemec7b45292017-09-19 09:06:20 -07001670 }
Felipe Lemec24a56a2017-08-03 14:27:57 -07001671 return;
1672 }
Felipe Lemebab851c2017-02-03 18:45:08 -08001673 try {
Felipe Leme637e05e2017-12-06 12:09:37 -08001674 final AutofillClient client = getClient();
felipealfd3f8f62018-02-07 11:49:07 +01001675 if (client == null) return; // NOTE: getClient() already logged it..
Felipe Leme637e05e2017-12-06 12:09:37 -08001676
Felipe Lemec0c15a32019-01-08 10:53:33 -08001677 final SyncResultReceiver receiver = new SyncResultReceiver(SYNC_CALLS_TIMEOUT_MS);
Felipe Lemed4e52282018-06-18 13:56:38 -07001678 mService.startSession(client.autofillClientGetActivityToken(),
Felipe Lemee6010f22017-03-03 11:19:51 -08001679 mServiceClient.asBinder(), id, bounds, value, mContext.getUserId(),
Felipe Leme185de722018-02-13 17:25:44 -08001680 mCallback != null, flags, client.autofillClientGetComponentName(),
Felipe Lemed4e52282018-06-18 13:56:38 -07001681 isCompatibilityModeEnabledLocked(), receiver);
1682 mSessionId = receiver.getIntResult();
Felipe Lemec24a56a2017-08-03 14:27:57 -07001683 if (mSessionId != NO_SESSION) {
1684 mState = STATE_ACTIVE;
1685 }
Svetoslav Ganov24c90452017-12-27 15:17:14 -08001686 client.autofillClientResetableStateAvailable();
Svet Ganov782043c2017-02-11 00:52:02 +00001687 } catch (RemoteException e) {
1688 throw e.rethrowFromSystemServer();
1689 }
1690 }
1691
Andreas Gampe3f24e692018-02-05 13:24:28 -08001692 @GuardedBy("mLock")
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001693 private void finishSessionLocked() {
Felipe Lemec7b45292017-09-19 09:06:20 -07001694 if (sVerbose) Log.v(TAG, "finishSessionLocked(): " + getStateAsStringLocked());
Felipe Lemec24a56a2017-08-03 14:27:57 -07001695
1696 if (!isActiveLocked()) return;
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001697
Svet Ganov782043c2017-02-11 00:52:02 +00001698 try {
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001699 mService.finishSession(mSessionId, mContext.getUserId());
Felipe Lemebab851c2017-02-03 18:45:08 -08001700 } catch (RemoteException e) {
1701 throw e.rethrowFromSystemServer();
1702 }
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001703
Felipe Leme9a15c0f2018-02-14 17:26:46 -08001704 resetSessionLocked(/* resetEnteredIds= */ true);
Felipe Lemebab851c2017-02-03 18:45:08 -08001705 }
1706
Andreas Gampe3f24e692018-02-05 13:24:28 -08001707 @GuardedBy("mLock")
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001708 private void cancelSessionLocked() {
Felipe Lemec7b45292017-09-19 09:06:20 -07001709 if (sVerbose) Log.v(TAG, "cancelSessionLocked(): " + getStateAsStringLocked());
Felipe Lemec24a56a2017-08-03 14:27:57 -07001710
1711 if (!isActiveLocked()) return;
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001712
Svet Ganov2f8fb1f2017-03-13 00:21:04 -07001713 try {
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001714 mService.cancelSession(mSessionId, mContext.getUserId());
Svet Ganov2f8fb1f2017-03-13 00:21:04 -07001715 } catch (RemoteException e) {
1716 throw e.rethrowFromSystemServer();
1717 }
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001718
Felipe Leme9a15c0f2018-02-14 17:26:46 -08001719 resetSessionLocked(/* resetEnteredIds= */ true);
Svet Ganov48f10a22017-04-26 18:49:30 -07001720 }
1721
Andreas Gampe3f24e692018-02-05 13:24:28 -08001722 @GuardedBy("mLock")
Felipe Leme9a15c0f2018-02-14 17:26:46 -08001723 private void resetSessionLocked(boolean resetEnteredIds) {
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001724 mSessionId = NO_SESSION;
Felipe Lemec24a56a2017-08-03 14:27:57 -07001725 mState = STATE_UNKNOWN;
Svet Ganov48f10a22017-04-26 18:49:30 -07001726 mTrackedViews = null;
Felipe Lemec24a56a2017-08-03 14:27:57 -07001727 mFillableIds = null;
Felipe Leme2fe3ade2017-09-28 15:03:36 -07001728 mSaveTriggerId = null;
Dake Gub0fa3782018-02-26 12:25:14 -08001729 mIdShownFillUi = null;
Felipe Leme9a15c0f2018-02-14 17:26:46 -08001730 if (resetEnteredIds) {
1731 mEnteredIds = null;
1732 }
Svet Ganov2f8fb1f2017-03-13 00:21:04 -07001733 }
1734
Andreas Gampe3f24e692018-02-05 13:24:28 -08001735 @GuardedBy("mLock")
Felipe Leme0aa4c502017-04-26 12:36:01 -07001736 private void updateSessionLocked(AutofillId id, Rect bounds, AutofillValue value, int action,
1737 int flags) {
Felipe Leme9a15c0f2018-02-14 17:26:46 -08001738 if (sVerbose) {
Felipe Leme9f9ee252017-04-27 13:56:22 -07001739 Log.v(TAG, "updateSessionLocked(): id=" + id + ", bounds=" + bounds
1740 + ", value=" + value + ", action=" + action + ", flags=" + flags);
Felipe Lemebab851c2017-02-03 18:45:08 -08001741 }
Felipe Leme3461d3c2017-01-19 08:54:55 -08001742 try {
Felipe Lemed62b5162018-06-06 15:08:25 -07001743 mService.updateSession(mSessionId, id, bounds, value, action, flags,
1744 mContext.getUserId());
Felipe Leme3461d3c2017-01-19 08:54:55 -08001745 } catch (RemoteException e) {
1746 throw e.rethrowFromSystemServer();
1747 }
1748 }
Svet Ganov782043c2017-02-11 00:52:02 +00001749
Andreas Gampe3f24e692018-02-05 13:24:28 -08001750 @GuardedBy("mLock")
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001751 private void ensureServiceClientAddedIfNeededLocked() {
Felipe Leme637e05e2017-12-06 12:09:37 -08001752 if (getClient() == null) {
Svet Ganov782043c2017-02-11 00:52:02 +00001753 return;
1754 }
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001755
Svet Ganov782043c2017-02-11 00:52:02 +00001756 if (mServiceClient == null) {
Felipe Leme640f30a2017-03-06 15:44:06 -08001757 mServiceClient = new AutofillManagerClient(this);
Svet Ganov782043c2017-02-11 00:52:02 +00001758 try {
Koji Fukuiccec6a62017-10-18 17:48:40 +09001759 final int userId = mContext.getUserId();
Felipe Lemec0c15a32019-01-08 10:53:33 -08001760 final SyncResultReceiver receiver = new SyncResultReceiver(SYNC_CALLS_TIMEOUT_MS);
Felipe Lemed4e52282018-06-18 13:56:38 -07001761 mService.addClient(mServiceClient, userId, receiver);
1762 final int flags = receiver.getIntResult();
Felipe Leme9f9ee252017-04-27 13:56:22 -07001763 mEnabled = (flags & FLAG_ADD_CLIENT_ENABLED) != 0;
1764 sDebug = (flags & FLAG_ADD_CLIENT_DEBUG) != 0;
1765 sVerbose = (flags & FLAG_ADD_CLIENT_VERBOSE) != 0;
Koji Fukuiccec6a62017-10-18 17:48:40 +09001766 final IAutoFillManager service = mService;
1767 final IAutoFillManagerClient serviceClient = mServiceClient;
1768 mServiceClientCleaner = Cleaner.create(this, () -> {
Felipe Leme559e21d2019-01-18 17:57:21 -08001769 // TODO(b/123100811): call service to also remove reference to
Felipe Leme284ad1c2018-11-15 18:16:12 -08001770 // mAugmentedAutofillServiceClient
Koji Fukuiccec6a62017-10-18 17:48:40 +09001771 try {
1772 service.removeClient(serviceClient, userId);
1773 } catch (RemoteException e) {
1774 }
1775 });
Svet Ganov782043c2017-02-11 00:52:02 +00001776 } catch (RemoteException e) {
1777 throw e.rethrowFromSystemServer();
1778 }
1779 }
1780 }
1781
Felipe Lemee6010f22017-03-03 11:19:51 -08001782 /**
1783 * Registers a {@link AutofillCallback} to receive autofill events.
1784 *
1785 * @param callback callback to receive events.
1786 */
1787 public void registerCallback(@Nullable AutofillCallback callback) {
Svet Ganov43574b02017-04-12 09:25:20 -07001788 if (!hasAutofillFeature()) {
1789 return;
1790 }
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001791 synchronized (mLock) {
1792 if (callback == null) return;
Felipe Lemee6010f22017-03-03 11:19:51 -08001793
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001794 final boolean hadCallback = mCallback != null;
1795 mCallback = callback;
Felipe Lemee6010f22017-03-03 11:19:51 -08001796
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001797 if (!hadCallback) {
1798 try {
1799 mService.setHasCallback(mSessionId, mContext.getUserId(), true);
1800 } catch (RemoteException e) {
1801 throw e.rethrowFromSystemServer();
1802 }
Felipe Lemee6010f22017-03-03 11:19:51 -08001803 }
1804 }
1805 }
1806
1807 /**
1808 * Unregisters a {@link AutofillCallback} to receive autofill events.
1809 *
1810 * @param callback callback to stop receiving events.
1811 */
1812 public void unregisterCallback(@Nullable AutofillCallback callback) {
Svet Ganov43574b02017-04-12 09:25:20 -07001813 if (!hasAutofillFeature()) {
1814 return;
1815 }
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001816 synchronized (mLock) {
1817 if (callback == null || mCallback == null || callback != mCallback) return;
Felipe Lemee6010f22017-03-03 11:19:51 -08001818
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001819 mCallback = null;
Felipe Lemee6010f22017-03-03 11:19:51 -08001820
Felipe Lemee6010f22017-03-03 11:19:51 -08001821 try {
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001822 mService.setHasCallback(mSessionId, mContext.getUserId(), false);
Felipe Lemee6010f22017-03-03 11:19:51 -08001823 } catch (RemoteException e) {
1824 throw e.rethrowFromSystemServer();
1825 }
1826 }
1827 }
1828
Felipe Leme559e21d2019-01-18 17:57:21 -08001829 /**
Felipe Leme559e21d2019-01-18 17:57:21 -08001830 * Explicitly limits augmented autofill to the given packages and activities.
1831 *
Felipe Leme559e21d2019-01-18 17:57:21 -08001832 * <p>To reset the whitelist, call it passing {@code null} to both arguments.
1833 *
1834 * <p>Useful when the service wants to restrict augmented autofill to a category of apps, like
1835 * apps that uses addresses. For example, if the service wants to support augmented autofill on
1836 * all activities of app {@code AddressApp1} and just activities {@code act1} and {@code act2}
1837 * of {@code AddressApp2}, it would call:
1838 * {@code setAugmentedAutofillWhitelist(Arrays.asList("AddressApp1"),
1839 * Arrays.asList(new ComponentName("AddressApp2", "act1"),
1840 * new ComponentName("AddressApp2", "act2")));}
1841 *
1842 * <p><b>Note:</b> This method should only be called by the app providing the augmented autofill
1843 * service, and it's ignored if the caller isn't it.
1844 *
1845 * @hide
1846 */
1847 @SystemApi
1848 @TestApi
Felipe Leme7a3c9f52019-02-13 16:32:49 -08001849 public void setAugmentedAutofillWhitelist(@Nullable Set<String> packages,
1850 @Nullable Set<ComponentName> activities) {
Felipe Leme80e7bf12019-02-14 10:56:52 -08001851 if (!hasAutofillFeature()) {
1852 return;
1853 }
1854
1855 final SyncResultReceiver resultReceiver = new SyncResultReceiver(SYNC_CALLS_TIMEOUT_MS);
1856 final int resultCode;
1857 try {
1858 mService.setAugmentedAutofillWhitelist(toList(packages), toList(activities),
1859 resultReceiver);
1860 resultCode = resultReceiver.getIntResult();
1861 } catch (RemoteException e) {
1862 throw e.rethrowFromSystemServer();
1863 }
1864 switch (resultCode) {
1865 case RESULT_OK:
1866 return;
1867 case RESULT_CODE_NOT_SERVICE:
1868 throw new SecurityException("caller is not user's Augmented Autofill Service");
1869 default:
1870 Log.wtf(TAG, "setAugmentedAutofillWhitelist(): received invalid result: "
1871 + resultCode);
1872 }
1873 }
1874
1875 private <T> ArrayList<T> toList(@Nullable Set<T> set) {
1876 return set == null ? null : new ArrayList<T>(set);
Felipe Leme559e21d2019-01-18 17:57:21 -08001877 }
1878
Felipe Lemea7de4022019-02-19 17:16:45 -08001879 /**
1880 * Notifies that a non-autofillable view was entered because the activity is whitelisted for
1881 * augmented autofill.
1882 *
1883 * <p>This method is necessary to set the right flag on start, so the server-side session
1884 * doesn't trigger the standard autofill workflow, but the augmented's instead.
1885 *
1886 * @hide
1887 */
1888 public void notifyViewEnteredForAugmentedAutofill(@NonNull View view) {
1889 final AutofillId id = view.getAutofillId();
1890 synchronized (mLock) {
1891 if (mEnteredForAugmentedAutofillIds == null) {
1892 mEnteredForAugmentedAutofillIds = new ArraySet<>(1);
1893 }
1894 mEnteredForAugmentedAutofillIds.add(id);
1895 }
1896 }
1897
Philip P. Moltmann134cee22017-05-06 11:28:38 -07001898 private void requestShowFillUi(int sessionId, AutofillId id, int width, int height,
1899 Rect anchorBounds, IAutofillWindowPresenter presenter) {
1900 final View anchor = findView(id);
Felipe Leme4753bb02017-03-22 20:24:00 -07001901 if (anchor == null) {
1902 return;
1903 }
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001904
1905 AutofillCallback callback = null;
1906 synchronized (mLock) {
Philip P. Moltmanne048a652017-04-11 10:13:33 -07001907 if (mSessionId == sessionId) {
Felipe Leme637e05e2017-12-06 12:09:37 -08001908 AutofillClient client = getClient();
Philip P. Moltmanne048a652017-04-11 10:13:33 -07001909
1910 if (client != null) {
Svetoslav Ganov24c90452017-12-27 15:17:14 -08001911 if (client.autofillClientRequestShowFillUi(anchor, width, height,
Dake Gub0fa3782018-02-26 12:25:14 -08001912 anchorBounds, presenter)) {
Philip P. Moltmanne048a652017-04-11 10:13:33 -07001913 callback = mCallback;
Dake Gub0fa3782018-02-26 12:25:14 -08001914 mIdShownFillUi = id;
Philip P. Moltmanne048a652017-04-11 10:13:33 -07001915 }
1916 }
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001917 }
1918 }
1919
1920 if (callback != null) {
Felipe Lemea75333c2019-01-22 15:45:32 -08001921 if (id.isVirtualInt()) {
1922 callback.onAutofillEvent(anchor, id.getVirtualChildIntId(),
Felipe Leme4753bb02017-03-22 20:24:00 -07001923 AutofillCallback.EVENT_INPUT_SHOWN);
1924 } else {
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001925 callback.onAutofillEvent(anchor, AutofillCallback.EVENT_INPUT_SHOWN);
Felipe Leme4753bb02017-03-22 20:24:00 -07001926 }
1927 }
1928 }
1929
Svetoslav Ganova9379d02017-05-09 17:40:24 -07001930 private void authenticate(int sessionId, int authenticationId, IntentSender intent,
1931 Intent fillInIntent) {
Philip P. Moltmanne048a652017-04-11 10:13:33 -07001932 synchronized (mLock) {
1933 if (sessionId == mSessionId) {
Felipe Leme637e05e2017-12-06 12:09:37 -08001934 final AutofillClient client = getClient();
Philip P. Moltmanne048a652017-04-11 10:13:33 -07001935 if (client != null) {
Dake Gu67decfa2017-12-27 11:48:08 -08001936 // clear mOnInvisibleCalled and we will see if receive onInvisibleForAutofill()
1937 // before onAuthenticationResult()
1938 mOnInvisibleCalled = false;
Svetoslav Ganov24c90452017-12-27 15:17:14 -08001939 client.autofillClientAuthenticate(authenticationId, intent, fillInIntent);
Philip P. Moltmanne048a652017-04-11 10:13:33 -07001940 }
1941 }
1942 }
1943 }
1944
Dake Gu6a20a192018-02-08 12:09:30 -08001945 private void dispatchUnhandledKey(int sessionId, AutofillId id, KeyEvent keyEvent) {
1946 final View anchor = findView(id);
1947 if (anchor == null) {
1948 return;
1949 }
1950
Dake Gu6a20a192018-02-08 12:09:30 -08001951 synchronized (mLock) {
1952 if (mSessionId == sessionId) {
1953 AutofillClient client = getClient();
1954
1955 if (client != null) {
1956 client.autofillClientDispatchUnhandledKey(anchor, keyEvent);
1957 }
1958 }
1959 }
1960 }
1961
Felipe Leme51e29da2017-10-24 14:03:10 -07001962 /** @hide */
1963 public static final int SET_STATE_FLAG_ENABLED = 0x01;
1964 /** @hide */
1965 public static final int SET_STATE_FLAG_RESET_SESSION = 0x02;
1966 /** @hide */
1967 public static final int SET_STATE_FLAG_RESET_CLIENT = 0x04;
1968 /** @hide */
1969 public static final int SET_STATE_FLAG_DEBUG = 0x08;
1970 /** @hide */
1971 public static final int SET_STATE_FLAG_VERBOSE = 0x10;
1972
1973 private void setState(int flags) {
1974 if (sVerbose) Log.v(TAG, "setState(" + flags + ")");
Philip P. Moltmanne048a652017-04-11 10:13:33 -07001975 synchronized (mLock) {
Felipe Leme51e29da2017-10-24 14:03:10 -07001976 mEnabled = (flags & SET_STATE_FLAG_ENABLED) != 0;
1977 if (!mEnabled || (flags & SET_STATE_FLAG_RESET_SESSION) != 0) {
Svet Ganov48f10a22017-04-26 18:49:30 -07001978 // Reset the session state
Felipe Leme9a15c0f2018-02-14 17:26:46 -08001979 resetSessionLocked(/* resetEnteredIds= */ true);
Svet Ganov48f10a22017-04-26 18:49:30 -07001980 }
Felipe Leme51e29da2017-10-24 14:03:10 -07001981 if ((flags & SET_STATE_FLAG_RESET_CLIENT) != 0) {
Svet Ganov48f10a22017-04-26 18:49:30 -07001982 // Reset connection to system
1983 mServiceClient = null;
Felipe Leme284ad1c2018-11-15 18:16:12 -08001984 mAugmentedAutofillServiceClient = null;
Koji Fukuiccec6a62017-10-18 17:48:40 +09001985 if (mServiceClientCleaner != null) {
1986 mServiceClientCleaner.clean();
1987 mServiceClientCleaner = null;
1988 }
Svet Ganov48f10a22017-04-26 18:49:30 -07001989 }
Philip P. Moltmanne048a652017-04-11 10:13:33 -07001990 }
Felipe Leme51e29da2017-10-24 14:03:10 -07001991 sDebug = (flags & SET_STATE_FLAG_DEBUG) != 0;
1992 sVerbose = (flags & SET_STATE_FLAG_VERBOSE) != 0;
Philip P. Moltmanne048a652017-04-11 10:13:33 -07001993 }
1994
Philip P. Moltmannb42d1332017-03-27 09:55:30 -07001995 /**
1996 * Sets a view as autofilled if the current value is the {code targetValue}.
1997 *
1998 * @param view The view that is to be autofilled
1999 * @param targetValue The value we want to fill into view
2000 */
2001 private void setAutofilledIfValuesIs(@NonNull View view, @Nullable AutofillValue targetValue) {
2002 AutofillValue currentValue = view.getAutofillValue();
2003 if (Objects.equals(currentValue, targetValue)) {
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07002004 synchronized (mLock) {
2005 if (mLastAutofilledData == null) {
2006 mLastAutofilledData = new ParcelableMap(1);
2007 }
Felipe Leme42b97932018-02-20 13:04:31 -08002008 mLastAutofilledData.put(view.getAutofillId(), targetValue);
Philip P. Moltmannb42d1332017-03-27 09:55:30 -07002009 }
Philip P. Moltmannb42d1332017-03-27 09:55:30 -07002010 view.setAutofilled(true);
2011 }
2012 }
2013
Philip P. Moltmann134cee22017-05-06 11:28:38 -07002014 private void autofill(int sessionId, List<AutofillId> ids, List<AutofillValue> values) {
Philip P. Moltmanne048a652017-04-11 10:13:33 -07002015 synchronized (mLock) {
2016 if (sessionId != mSessionId) {
2017 return;
Felipe Leme4753bb02017-03-22 20:24:00 -07002018 }
Philip P. Moltmanne048a652017-04-11 10:13:33 -07002019
Felipe Leme637e05e2017-12-06 12:09:37 -08002020 final AutofillClient client = getClient();
Philip P. Moltmann134cee22017-05-06 11:28:38 -07002021 if (client == null) {
Philip P. Moltmanne048a652017-04-11 10:13:33 -07002022 return;
2023 }
2024
2025 final int itemCount = ids.size();
2026 int numApplied = 0;
2027 ArrayMap<View, SparseArray<AutofillValue>> virtualValues = null;
Svetoslav Ganov24c90452017-12-27 15:17:14 -08002028 final View[] views = client.autofillClientFindViewsByAutofillIdTraversal(
2029 Helper.toArray(ids));
Philip P. Moltmanne048a652017-04-11 10:13:33 -07002030
Felipe Leme49f08ed2018-03-26 16:18:45 -07002031 ArrayList<AutofillId> failedIds = null;
2032
Philip P. Moltmanne048a652017-04-11 10:13:33 -07002033 for (int i = 0; i < itemCount; i++) {
2034 final AutofillId id = ids.get(i);
2035 final AutofillValue value = values.get(i);
Philip P. Moltmann134cee22017-05-06 11:28:38 -07002036 final View view = views[i];
Philip P. Moltmanne048a652017-04-11 10:13:33 -07002037 if (view == null) {
Felipe Leme49f08ed2018-03-26 16:18:45 -07002038 // Most likely view has been removed after the initial request was sent to the
2039 // the service; this is fine, but we need to update the view status in the
2040 // server side so it can be triggered again.
2041 Log.d(TAG, "autofill(): no View with id " + id);
2042 if (failedIds == null) {
2043 failedIds = new ArrayList<>();
2044 }
2045 failedIds.add(id);
Philip P. Moltmanne048a652017-04-11 10:13:33 -07002046 continue;
Felipe Leme4753bb02017-03-22 20:24:00 -07002047 }
Felipe Lemea75333c2019-01-22 15:45:32 -08002048 if (id.isVirtualInt()) {
Philip P. Moltmanne048a652017-04-11 10:13:33 -07002049 if (virtualValues == null) {
2050 // Most likely there will be just one view with virtual children.
2051 virtualValues = new ArrayMap<>(1);
2052 }
2053 SparseArray<AutofillValue> valuesByParent = virtualValues.get(view);
2054 if (valuesByParent == null) {
2055 // We don't know the size yet, but usually it will be just a few fields...
2056 valuesByParent = new SparseArray<>(5);
2057 virtualValues.put(view, valuesByParent);
2058 }
Felipe Lemea75333c2019-01-22 15:45:32 -08002059 valuesByParent.put(id.getVirtualChildIntId(), value);
Philip P. Moltmanne048a652017-04-11 10:13:33 -07002060 } else {
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07002061 // Mark the view as to be autofilled with 'value'
2062 if (mLastAutofilledData == null) {
2063 mLastAutofilledData = new ParcelableMap(itemCount - i);
2064 }
2065 mLastAutofilledData.put(id, value);
Philip P. Moltmanne048a652017-04-11 10:13:33 -07002066
2067 view.autofill(value);
2068
2069 // Set as autofilled if the values match now, e.g. when the value was updated
2070 // synchronously.
2071 // If autofill happens async, the view is set to autofilled in
2072 // notifyValueChanged.
2073 setAutofilledIfValuesIs(view, value);
2074
2075 numApplied++;
Philip P. Moltmannb42d1332017-03-27 09:55:30 -07002076 }
Felipe Leme4753bb02017-03-22 20:24:00 -07002077 }
Felipe Leme4753bb02017-03-22 20:24:00 -07002078
Felipe Leme49f08ed2018-03-26 16:18:45 -07002079 if (failedIds != null) {
2080 if (sVerbose) {
2081 Log.v(TAG, "autofill(): total failed views: " + failedIds);
2082 }
2083 try {
2084 mService.setAutofillFailure(mSessionId, failedIds, mContext.getUserId());
2085 } catch (RemoteException e) {
2086 // In theory, we could ignore this error since it's not a big deal, but
2087 // in reality, we rather crash the app anyways, as the failure could be
2088 // a consequence of something going wrong on the server side...
2089 e.rethrowFromSystemServer();
2090 }
2091 }
2092
Philip P. Moltmanne048a652017-04-11 10:13:33 -07002093 if (virtualValues != null) {
2094 for (int i = 0; i < virtualValues.size(); i++) {
2095 final View parent = virtualValues.keyAt(i);
2096 final SparseArray<AutofillValue> childrenValues = virtualValues.valueAt(i);
2097 parent.autofill(childrenValues);
2098 numApplied += childrenValues.size();
Felipe Leme49f08ed2018-03-26 16:18:45 -07002099 // TODO: we should provide a callback so the parent can call failures; something
2100 // like notifyAutofillFailed(View view, int[] childrenIds);
Philip P. Moltmanne048a652017-04-11 10:13:33 -07002101 }
Felipe Leme4753bb02017-03-22 20:24:00 -07002102 }
Felipe Leme4753bb02017-03-22 20:24:00 -07002103
Felipe Leme11166522018-05-07 10:18:47 -07002104 mMetricsLogger.write(newLog(MetricsEvent.AUTOFILL_DATASET_APPLIED)
Felipe Lemeb22d6352017-09-08 20:03:53 -07002105 .addTaggedData(MetricsEvent.FIELD_AUTOFILL_NUM_VALUES, itemCount)
Felipe Leme11166522018-05-07 10:18:47 -07002106 .addTaggedData(MetricsEvent.FIELD_AUTOFILL_NUM_VIEWS_FILLED, numApplied));
Philip P. Moltmanne048a652017-04-11 10:13:33 -07002107 }
Felipe Leme4753bb02017-03-22 20:24:00 -07002108 }
2109
Felipe Leme11166522018-05-07 10:18:47 -07002110 private LogMaker newLog(int category) {
Felipe Lemeb838a092018-05-22 14:56:15 -07002111 final LogMaker log = new LogMaker(category)
Felipe Leme833c99b2018-05-24 10:41:48 -07002112 .addTaggedData(MetricsEvent.FIELD_AUTOFILL_SESSION_ID, mSessionId);
2113
2114 if (isCompatibilityModeEnabledLocked()) {
2115 log.addTaggedData(MetricsEvent.FIELD_AUTOFILL_COMPAT_MODE, 1);
2116 }
Felipe Lemeb838a092018-05-22 14:56:15 -07002117 final AutofillClient client = getClient();
2118 if (client == null) {
2119 // Client should never be null here, but it doesn't hurt to check...
2120 log.setPackageName(mContext.getPackageName());
2121 } else {
2122 log.setComponentName(client.autofillClientGetComponentName());
2123 }
2124 return log;
Felipe Leme11166522018-05-07 10:18:47 -07002125 }
2126
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002127 /**
2128 * Set the tracked views.
2129 *
Felipe Leme2fe3ade2017-09-28 15:03:36 -07002130 * @param trackedIds The views to be tracked.
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002131 * @param saveOnAllViewsInvisible Finish the session once all tracked views are invisible.
Felipe Leme2fe3ade2017-09-28 15:03:36 -07002132 * @param saveOnFinish Finish the session once the activity is finished.
Felipe Leme27e20222017-05-18 15:24:11 -07002133 * @param fillableIds Views that might anchor FillUI.
Felipe Leme2fe3ade2017-09-28 15:03:36 -07002134 * @param saveTriggerId View that when clicked triggers commit().
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002135 */
Felipe Leme27e20222017-05-18 15:24:11 -07002136 private void setTrackedViews(int sessionId, @Nullable AutofillId[] trackedIds,
Felipe Leme2fe3ade2017-09-28 15:03:36 -07002137 boolean saveOnAllViewsInvisible, boolean saveOnFinish,
2138 @Nullable AutofillId[] fillableIds, @Nullable AutofillId saveTriggerId) {
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002139 synchronized (mLock) {
2140 if (mEnabled && mSessionId == sessionId) {
2141 if (saveOnAllViewsInvisible) {
2142 mTrackedViews = new TrackedViews(trackedIds);
2143 } else {
2144 mTrackedViews = null;
2145 }
Felipe Leme2fe3ade2017-09-28 15:03:36 -07002146 mSaveOnFinish = saveOnFinish;
Felipe Leme27e20222017-05-18 15:24:11 -07002147 if (fillableIds != null) {
2148 if (mFillableIds == null) {
2149 mFillableIds = new ArraySet<>(fillableIds.length);
2150 }
2151 for (AutofillId id : fillableIds) {
2152 mFillableIds.add(id);
2153 }
2154 if (sVerbose) {
Felipe Leme27e1bf32018-07-10 15:45:43 -07002155 Log.v(TAG, "setTrackedViews(): fillableIds=" + Arrays.toString(fillableIds)
Felipe Leme27e20222017-05-18 15:24:11 -07002156 + ", mFillableIds" + mFillableIds);
2157 }
2158 }
Felipe Leme2fe3ade2017-09-28 15:03:36 -07002159
2160 if (mSaveTriggerId != null && !mSaveTriggerId.equals(saveTriggerId)) {
2161 // Turn off trigger on previous view id.
2162 setNotifyOnClickLocked(mSaveTriggerId, false);
2163 }
2164
2165 if (saveTriggerId != null && !saveTriggerId.equals(mSaveTriggerId)) {
2166 // Turn on trigger on new view id.
2167 mSaveTriggerId = saveTriggerId;
2168 setNotifyOnClickLocked(mSaveTriggerId, true);
2169 }
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002170 }
2171 }
2172 }
2173
Felipe Leme2fe3ade2017-09-28 15:03:36 -07002174 private void setNotifyOnClickLocked(@NonNull AutofillId id, boolean notify) {
2175 final View view = findView(id);
2176 if (view == null) {
2177 Log.w(TAG, "setNotifyOnClick(): invalid id: " + id);
2178 return;
2179 }
2180 view.setNotifyAutofillManagerOnClick(notify);
2181 }
2182
Felipe Lemec24a56a2017-08-03 14:27:57 -07002183 private void setSaveUiState(int sessionId, boolean shown) {
2184 if (sDebug) Log.d(TAG, "setSaveUiState(" + sessionId + "): " + shown);
2185 synchronized (mLock) {
2186 if (mSessionId != NO_SESSION) {
2187 // Race condition: app triggered a new session after the previous session was
2188 // finished but before server called setSaveUiState() - need to cancel the new
2189 // session to avoid further inconsistent behavior.
2190 Log.w(TAG, "setSaveUiState(" + sessionId + ", " + shown
2191 + ") called on existing session " + mSessionId + "; cancelling it");
2192 cancelSessionLocked();
2193 }
2194 if (shown) {
2195 mSessionId = sessionId;
2196 mState = STATE_SHOWING_SAVE_UI;
2197 } else {
2198 mSessionId = NO_SESSION;
2199 mState = STATE_UNKNOWN;
2200 }
2201 }
2202 }
2203
Felipe Leme650f7ab2017-09-19 13:08:24 -07002204 /**
2205 * Marks the state of the session as finished.
2206 *
2207 * @param newState {@link #STATE_FINISHED} (because the autofill service returned a {@code null}
Felipe Leme0c8ce322018-03-23 13:54:22 -07002208 * FillResponse), {@link #STATE_UNKNOWN} (because the session was removed),
2209 * {@link #STATE_UNKNOWN_COMPAT_MODE} (beucase the session was finished when the URL bar
Felipe Lemed9dc9542018-09-19 11:54:28 -07002210 * changed on compat mode), {@link #STATE_UNKNOWN_FAILED} (because the session was finished
2211 * when the service failed to fullfil the request, or {@link #STATE_DISABLED_BY_SERVICE}
2212 * (because the autofill service or {@link #STATE_DISABLED_BY_SERVICE} (because the autofill
2213 * service disabled further autofill requests for the activity).
Felipe Leme650f7ab2017-09-19 13:08:24 -07002214 */
2215 private void setSessionFinished(int newState) {
Felipe Lemec7b45292017-09-19 09:06:20 -07002216 synchronized (mLock) {
Felipe Leme0c8ce322018-03-23 13:54:22 -07002217 if (sVerbose) {
2218 Log.v(TAG, "setSessionFinished(): from " + getStateAsStringLocked() + " to "
2219 + getStateAsString(newState));
2220 }
Felipe Lemed9dc9542018-09-19 11:54:28 -07002221 if (newState == STATE_UNKNOWN_COMPAT_MODE || newState == STATE_UNKNOWN_FAILED) {
Felipe Leme0c8ce322018-03-23 13:54:22 -07002222 resetSessionLocked(/* resetEnteredIds= */ true);
2223 mState = STATE_UNKNOWN;
2224 } else {
2225 resetSessionLocked(/* resetEnteredIds= */ false);
2226 mState = newState;
2227 }
Felipe Lemec7b45292017-09-19 09:06:20 -07002228 }
2229 }
2230
Felipe Leme284ad1c2018-11-15 18:16:12 -08002231 /**
2232 * Gets a {@link AugmentedAutofillManagerClient} for this {@link AutofillManagerClient}.
2233 *
2234 * <p>These are 2 distinct objects because we need to restrict what the Augmented Autofill
2235 * service can do (which is defined by {@code IAugmentedAutofillManagerClient.aidl}).
2236 */
2237 private void getAugmentedAutofillClient(@NonNull IResultReceiver result) {
2238 synchronized (mLock) {
2239 if (mAugmentedAutofillServiceClient == null) {
2240 mAugmentedAutofillServiceClient = new AugmentedAutofillManagerClient(this);
2241 }
2242 final Bundle resultData = new Bundle();
2243 resultData.putBinder(EXTRA_AUGMENTED_AUTOFILL_CLIENT,
2244 mAugmentedAutofillServiceClient.asBinder());
2245
2246 try {
2247 result.send(0, resultData);
2248 } catch (RemoteException e) {
2249 Log.w(TAG, "Could not send AugmentedAutofillClient back: " + e);
2250 }
2251 }
2252 }
2253
Dake Gub0fa3782018-02-26 12:25:14 -08002254 /** @hide */
2255 public void requestHideFillUi() {
2256 requestHideFillUi(mIdShownFillUi, true);
2257 }
2258
2259 private void requestHideFillUi(AutofillId id, boolean force) {
2260 final View anchor = id == null ? null : findView(id);
Felipe Leme27e20222017-05-18 15:24:11 -07002261 if (sVerbose) Log.v(TAG, "requestHideFillUi(" + id + "): anchor = " + anchor);
Philip P. Moltmann134cee22017-05-06 11:28:38 -07002262 if (anchor == null) {
Dake Gub0fa3782018-02-26 12:25:14 -08002263 if (force) {
2264 // When user taps outside autofill window, force to close fill ui even id does
2265 // not match.
2266 AutofillClient client = getClient();
2267 if (client != null) {
2268 client.autofillClientRequestHideFillUi();
2269 }
2270 }
Philip P. Moltmann134cee22017-05-06 11:28:38 -07002271 return;
2272 }
Felipe Leme27e20222017-05-18 15:24:11 -07002273 requestHideFillUi(id, anchor);
2274 }
2275
2276 private void requestHideFillUi(AutofillId id, View anchor) {
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07002277
2278 AutofillCallback callback = null;
2279 synchronized (mLock) {
Svet Ganov48f10a22017-04-26 18:49:30 -07002280 // We do not check the session id for two reasons:
2281 // 1. If local and remote session id are off sync the UI would be stuck shown
2282 // 2. There is a race between the user state being destroyed due the fill
2283 // service being uninstalled and the UI being dismissed.
Felipe Leme637e05e2017-12-06 12:09:37 -08002284 AutofillClient client = getClient();
Svet Ganov48f10a22017-04-26 18:49:30 -07002285 if (client != null) {
Dake Gub0fa3782018-02-26 12:25:14 -08002286 if (client.autofillClientRequestHideFillUi()) {
2287 mIdShownFillUi = null;
Svet Ganov48f10a22017-04-26 18:49:30 -07002288 callback = mCallback;
Philip P. Moltmanne048a652017-04-11 10:13:33 -07002289 }
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07002290 }
2291 }
2292
2293 if (callback != null) {
Felipe Lemea75333c2019-01-22 15:45:32 -08002294 if (id.isVirtualInt()) {
2295 callback.onAutofillEvent(anchor, id.getVirtualChildIntId(),
Felipe Leme4753bb02017-03-22 20:24:00 -07002296 AutofillCallback.EVENT_INPUT_HIDDEN);
2297 } else {
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07002298 callback.onAutofillEvent(anchor, AutofillCallback.EVENT_INPUT_HIDDEN);
Felipe Leme4753bb02017-03-22 20:24:00 -07002299 }
2300 }
2301 }
2302
Felipe Leme17292d12017-10-24 14:03:10 -07002303 private void notifyNoFillUi(int sessionId, AutofillId id, int sessionFinishedState) {
Felipe Lemec7b45292017-09-19 09:06:20 -07002304 if (sVerbose) {
2305 Log.v(TAG, "notifyNoFillUi(): sessionId=" + sessionId + ", autofillId=" + id
Felipe Leme17292d12017-10-24 14:03:10 -07002306 + ", sessionFinishedState=" + sessionFinishedState);
Felipe Lemec7b45292017-09-19 09:06:20 -07002307 }
Philip P. Moltmann134cee22017-05-06 11:28:38 -07002308 final View anchor = findView(id);
2309 if (anchor == null) {
2310 return;
2311 }
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07002312
Philip P. Moltmanne048a652017-04-11 10:13:33 -07002313 AutofillCallback callback = null;
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07002314 synchronized (mLock) {
Felipe Leme637e05e2017-12-06 12:09:37 -08002315 if (mSessionId == sessionId && getClient() != null) {
Philip P. Moltmanne048a652017-04-11 10:13:33 -07002316 callback = mCallback;
2317 }
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07002318 }
2319
2320 if (callback != null) {
Felipe Lemea75333c2019-01-22 15:45:32 -08002321 if (id.isVirtualInt()) {
2322 callback.onAutofillEvent(anchor, id.getVirtualChildIntId(),
Felipe Leme4753bb02017-03-22 20:24:00 -07002323 AutofillCallback.EVENT_INPUT_UNAVAILABLE);
2324 } else {
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07002325 callback.onAutofillEvent(anchor, AutofillCallback.EVENT_INPUT_UNAVAILABLE);
Felipe Leme4753bb02017-03-22 20:24:00 -07002326 }
Felipe Lemec7b45292017-09-19 09:06:20 -07002327 }
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07002328
Felipe Leme17292d12017-10-24 14:03:10 -07002329 if (sessionFinishedState != 0) {
Felipe Lemec7b45292017-09-19 09:06:20 -07002330 // Callback call was "hijacked" to also update the session state.
Felipe Leme17292d12017-10-24 14:03:10 -07002331 setSessionFinished(sessionFinishedState);
Felipe Leme4753bb02017-03-22 20:24:00 -07002332 }
2333 }
2334
Philip P. Moltmann134cee22017-05-06 11:28:38 -07002335 /**
Philip P. Moltmann134cee22017-05-06 11:28:38 -07002336 * Find a single view by its id.
2337 *
2338 * @param autofillId The autofill id of the view
2339 *
2340 * @return The view or {@code null} if view was not found
2341 */
2342 private View findView(@NonNull AutofillId autofillId) {
Felipe Leme637e05e2017-12-06 12:09:37 -08002343 final AutofillClient client = getClient();
Svetoslav Ganov24c90452017-12-27 15:17:14 -08002344 if (client != null) {
2345 return client.autofillClientFindViewByAutofillIdTraversal(autofillId);
Felipe Lemee6010f22017-03-03 11:19:51 -08002346 }
Svetoslav Ganov24c90452017-12-27 15:17:14 -08002347 return null;
Felipe Lemee6010f22017-03-03 11:19:51 -08002348 }
2349
Felipe Lemebb810922017-04-25 15:54:06 -07002350 /** @hide */
2351 public boolean hasAutofillFeature() {
Svet Ganov43574b02017-04-12 09:25:20 -07002352 return mService != null;
2353 }
2354
Felipe Lemec24a56a2017-08-03 14:27:57 -07002355 /** @hide */
2356 public void onPendingSaveUi(int operation, IBinder token) {
2357 if (sVerbose) Log.v(TAG, "onPendingSaveUi(" + operation + "): " + token);
2358
2359 synchronized (mLock) {
2360 try {
2361 mService.onPendingSaveUi(operation, token);
2362 } catch (RemoteException e) {
2363 e.rethrowFromSystemServer();
2364 }
2365 }
2366 }
2367
2368 /** @hide */
2369 public void dump(String outerPrefix, PrintWriter pw) {
2370 pw.print(outerPrefix); pw.println("AutofillManager:");
2371 final String pfx = outerPrefix + " ";
2372 pw.print(pfx); pw.print("sessionId: "); pw.println(mSessionId);
Felipe Lemec7b45292017-09-19 09:06:20 -07002373 pw.print(pfx); pw.print("state: "); pw.println(getStateAsStringLocked());
Felipe Leme686128e2017-10-17 14:02:20 -07002374 pw.print(pfx); pw.print("context: "); pw.println(mContext);
Felipe Lemeb546ca72018-08-15 08:44:12 -07002375 final AutofillClient client = getClient();
2376 if (client != null) {
2377 pw.print(pfx); pw.print("client: "); pw.print(client);
2378 pw.print(" ("); pw.print(client.autofillClientGetActivityToken()); pw.println(')');
2379 }
Felipe Lemec24a56a2017-08-03 14:27:57 -07002380 pw.print(pfx); pw.print("enabled: "); pw.println(mEnabled);
2381 pw.print(pfx); pw.print("hasService: "); pw.println(mService != null);
2382 pw.print(pfx); pw.print("hasCallback: "); pw.println(mCallback != null);
Dake Gu67decfa2017-12-27 11:48:08 -08002383 pw.print(pfx); pw.print("onInvisibleCalled "); pw.println(mOnInvisibleCalled);
Felipe Lemec24a56a2017-08-03 14:27:57 -07002384 pw.print(pfx); pw.print("last autofilled data: "); pw.println(mLastAutofilledData);
Felipe Lemef5e26302018-06-08 16:26:39 -07002385 pw.print(pfx); pw.print("id of last fill UI shown: "); pw.println(mIdShownFillUi);
Felipe Lemec24a56a2017-08-03 14:27:57 -07002386 pw.print(pfx); pw.print("tracked views: ");
2387 if (mTrackedViews == null) {
2388 pw.println("null");
2389 } else {
2390 final String pfx2 = pfx + " ";
2391 pw.println();
2392 pw.print(pfx2); pw.print("visible:"); pw.println(mTrackedViews.mVisibleTrackedIds);
2393 pw.print(pfx2); pw.print("invisible:"); pw.println(mTrackedViews.mInvisibleTrackedIds);
2394 }
2395 pw.print(pfx); pw.print("fillable ids: "); pw.println(mFillableIds);
Felipe Leme9a15c0f2018-02-14 17:26:46 -08002396 pw.print(pfx); pw.print("entered ids: "); pw.println(mEnteredIds);
Felipe Lemea7de4022019-02-19 17:16:45 -08002397 if (mEnteredForAugmentedAutofillIds != null) {
2398 pw.print(pfx); pw.print("entered ids for augmented autofill: ");
2399 pw.println(mEnteredForAugmentedAutofillIds);
2400 }
Felipe Leme2fe3ade2017-09-28 15:03:36 -07002401 pw.print(pfx); pw.print("save trigger id: "); pw.println(mSaveTriggerId);
2402 pw.print(pfx); pw.print("save on finish(): "); pw.println(mSaveOnFinish);
Felipe Lemea4f39cd2019-02-19 15:08:59 -08002403 if (mOptions != null) {
2404 pw.print(pfx); pw.print("options: "); mOptions.dumpShort(pw); pw.println();
2405 }
Felipe Lemeb546ca72018-08-15 08:44:12 -07002406 pw.print(pfx); pw.print("compat mode enabled: ");
2407 synchronized (mLock) {
2408 if (mCompatibilityBridge != null) {
2409 final String pfx2 = pfx + " ";
2410 pw.println("true");
2411 pw.print(pfx2); pw.print("windowId: ");
2412 pw.println(mCompatibilityBridge.mFocusedWindowId);
2413 pw.print(pfx2); pw.print("nodeId: ");
2414 pw.println(mCompatibilityBridge.mFocusedNodeId);
2415 pw.print(pfx2); pw.print("virtualId: ");
2416 pw.println(AccessibilityNodeInfo
2417 .getVirtualDescendantId(mCompatibilityBridge.mFocusedNodeId));
2418 pw.print(pfx2); pw.print("focusedBounds: ");
2419 pw.println(mCompatibilityBridge.mFocusedBounds);
2420 } else {
2421 pw.println("false");
2422 }
2423 }
Felipe Leme51e29da2017-10-24 14:03:10 -07002424 pw.print(pfx); pw.print("debug: "); pw.print(sDebug);
2425 pw.print(" verbose: "); pw.println(sVerbose);
Felipe Lemec24a56a2017-08-03 14:27:57 -07002426 }
2427
Andreas Gampe3f24e692018-02-05 13:24:28 -08002428 @GuardedBy("mLock")
Felipe Lemec7b45292017-09-19 09:06:20 -07002429 private String getStateAsStringLocked() {
Felipe Leme0c8ce322018-03-23 13:54:22 -07002430 return getStateAsString(mState);
2431 }
2432
2433 @NonNull
2434 private static String getStateAsString(int state) {
2435 switch (state) {
Felipe Lemec7b45292017-09-19 09:06:20 -07002436 case STATE_UNKNOWN:
Felipe Leme0c8ce322018-03-23 13:54:22 -07002437 return "UNKNOWN";
Felipe Lemec7b45292017-09-19 09:06:20 -07002438 case STATE_ACTIVE:
Felipe Leme0c8ce322018-03-23 13:54:22 -07002439 return "ACTIVE";
Felipe Lemec7b45292017-09-19 09:06:20 -07002440 case STATE_FINISHED:
Felipe Leme0c8ce322018-03-23 13:54:22 -07002441 return "FINISHED";
Felipe Lemec7b45292017-09-19 09:06:20 -07002442 case STATE_SHOWING_SAVE_UI:
Felipe Leme0c8ce322018-03-23 13:54:22 -07002443 return "SHOWING_SAVE_UI";
Felipe Leme17292d12017-10-24 14:03:10 -07002444 case STATE_DISABLED_BY_SERVICE:
Felipe Leme0c8ce322018-03-23 13:54:22 -07002445 return "DISABLED_BY_SERVICE";
2446 case STATE_UNKNOWN_COMPAT_MODE:
2447 return "UNKNOWN_COMPAT_MODE";
Felipe Lemed9dc9542018-09-19 11:54:28 -07002448 case STATE_UNKNOWN_FAILED:
2449 return "UNKNOWN_FAILED";
Felipe Lemec7b45292017-09-19 09:06:20 -07002450 default:
Felipe Leme0c8ce322018-03-23 13:54:22 -07002451 return "INVALID:" + state;
Felipe Lemec7b45292017-09-19 09:06:20 -07002452 }
2453 }
2454
Felipe Leme559e21d2019-01-18 17:57:21 -08002455 /** @hide */
2456 public static String getSmartSuggestionModeToString(@SmartSuggestionMode int flags) {
Felipe Lemecc510272019-02-07 14:56:27 -08002457 switch (flags) {
2458 case FLAG_SMART_SUGGESTION_OFF:
2459 return "OFF";
2460 case FLAG_SMART_SUGGESTION_SYSTEM:
2461 return "SYSTEM";
2462 default:
2463 return "INVALID:" + flags;
2464 }
Felipe Leme559e21d2019-01-18 17:57:21 -08002465 }
2466
Andreas Gampe3f24e692018-02-05 13:24:28 -08002467 @GuardedBy("mLock")
Felipe Lemec24a56a2017-08-03 14:27:57 -07002468 private boolean isActiveLocked() {
2469 return mState == STATE_ACTIVE;
2470 }
2471
Andreas Gampe3f24e692018-02-05 13:24:28 -08002472 @GuardedBy("mLock")
Felipe Leme3103c632017-12-18 15:05:14 -08002473 private boolean isDisabledByServiceLocked() {
Felipe Leme17292d12017-10-24 14:03:10 -07002474 return mState == STATE_DISABLED_BY_SERVICE;
Felipe Lemec7b45292017-09-19 09:06:20 -07002475 }
2476
Andreas Gampe3f24e692018-02-05 13:24:28 -08002477 @GuardedBy("mLock")
Felipe Leme3103c632017-12-18 15:05:14 -08002478 private boolean isFinishedLocked() {
2479 return mState == STATE_FINISHED;
2480 }
2481
Felipe Leme9876a6f2017-05-30 15:47:28 -07002482 private void post(Runnable runnable) {
Felipe Leme637e05e2017-12-06 12:09:37 -08002483 final AutofillClient client = getClient();
Felipe Leme9876a6f2017-05-30 15:47:28 -07002484 if (client == null) {
2485 if (sVerbose) Log.v(TAG, "ignoring post() because client is null");
2486 return;
2487 }
Svetoslav Ganov24c90452017-12-27 15:17:14 -08002488 client.autofillClientRunOnUiThread(runnable);
2489 }
2490
2491 /**
2492 * Implementation of the accessibility based compatibility.
2493 */
2494 private final class CompatibilityBridge implements AccessibilityManager.AccessibilityPolicy {
2495 @GuardedBy("mLock")
2496 private final Rect mFocusedBounds = new Rect();
2497 @GuardedBy("mLock")
2498 private final Rect mTempBounds = new Rect();
2499
2500 @GuardedBy("mLock")
2501 private int mFocusedWindowId = AccessibilityWindowInfo.UNDEFINED_WINDOW_ID;
2502 @GuardedBy("mLock")
2503 private long mFocusedNodeId = AccessibilityNodeInfo.UNDEFINED_NODE_ID;
2504
2505 // Need to report a fake service in case a11y clients check the service list
2506 @NonNull
2507 @GuardedBy("mLock")
2508 AccessibilityServiceInfo mCompatServiceInfo;
2509
2510 CompatibilityBridge() {
2511 final AccessibilityManager am = AccessibilityManager.getInstance(mContext);
2512 am.setAccessibilityPolicy(this);
2513 }
2514
2515 private AccessibilityServiceInfo getCompatServiceInfo() {
2516 synchronized (mLock) {
2517 if (mCompatServiceInfo != null) {
2518 return mCompatServiceInfo;
2519 }
2520 final Intent intent = new Intent();
2521 intent.setComponent(new ComponentName("android",
2522 "com.android.server.autofill.AutofillCompatAccessibilityService"));
2523 final ResolveInfo resolveInfo = mContext.getPackageManager().resolveService(
2524 intent, PackageManager.MATCH_SYSTEM_ONLY | PackageManager.GET_META_DATA);
2525 try {
2526 mCompatServiceInfo = new AccessibilityServiceInfo(resolveInfo, mContext);
2527 } catch (XmlPullParserException | IOException e) {
2528 Log.e(TAG, "Cannot find compat autofill service:" + intent);
2529 throw new IllegalStateException("Cannot find compat autofill service");
2530 }
2531 return mCompatServiceInfo;
2532 }
2533 }
2534
2535 @Override
2536 public boolean isEnabled(boolean accessibilityEnabled) {
2537 return true;
2538 }
2539
2540 @Override
2541 public int getRelevantEventTypes(int relevantEventTypes) {
2542 return relevantEventTypes | AccessibilityEvent.TYPE_VIEW_FOCUSED
2543 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
Felipe Leme54cc6832018-03-06 12:54:31 -08002544 | AccessibilityEvent.TYPE_VIEW_CLICKED
Svetoslav Ganov24c90452017-12-27 15:17:14 -08002545 | AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED;
2546 }
2547
2548 @Override
2549 public List<AccessibilityServiceInfo> getInstalledAccessibilityServiceList(
2550 List<AccessibilityServiceInfo> installedServices) {
2551 if (installedServices == null) {
2552 installedServices = new ArrayList<>();
2553 }
2554 installedServices.add(getCompatServiceInfo());
2555 return installedServices;
2556 }
2557
2558 @Override
2559 public List<AccessibilityServiceInfo> getEnabledAccessibilityServiceList(
2560 int feedbackTypeFlags, List<AccessibilityServiceInfo> enabledService) {
2561 if (enabledService == null) {
2562 enabledService = new ArrayList<>();
2563 }
2564 enabledService.add(getCompatServiceInfo());
2565 return enabledService;
2566 }
2567
2568 @Override
2569 public AccessibilityEvent onAccessibilityEvent(AccessibilityEvent event,
2570 boolean accessibilityEnabled, int relevantEventTypes) {
Felipe Leme5d35d3d2018-08-13 18:15:32 -07002571 final int type = event.getEventType();
2572 if (sVerbose) {
2573 // NOTE: this is waaay spammy, but that's life.
2574 Log.v(TAG, "onAccessibilityEvent(" + AccessibilityEvent.eventTypeToString(type)
Felipe Leme7d4461d2018-08-16 10:49:03 -07002575 + "): virtualId="
2576 + AccessibilityNodeInfo.getVirtualDescendantId(event.getSourceNodeId())
2577 + ", client=" + getClient());
Felipe Leme5d35d3d2018-08-13 18:15:32 -07002578 }
2579 switch (type) {
Svetoslav Ganov24c90452017-12-27 15:17:14 -08002580 case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
2581 synchronized (mLock) {
2582 if (mFocusedWindowId == event.getWindowId()
2583 && mFocusedNodeId == event.getSourceNodeId()) {
2584 return event;
2585 }
2586 if (mFocusedWindowId != AccessibilityWindowInfo.UNDEFINED_WINDOW_ID
2587 && mFocusedNodeId != AccessibilityNodeInfo.UNDEFINED_NODE_ID) {
2588 notifyViewExited(mFocusedWindowId, mFocusedNodeId);
2589 mFocusedWindowId = AccessibilityWindowInfo.UNDEFINED_WINDOW_ID;
2590 mFocusedNodeId = AccessibilityNodeInfo.UNDEFINED_NODE_ID;
2591 mFocusedBounds.set(0, 0, 0, 0);
2592 }
2593 final int windowId = event.getWindowId();
2594 final long nodeId = event.getSourceNodeId();
2595 if (notifyViewEntered(windowId, nodeId, mFocusedBounds)) {
2596 mFocusedWindowId = windowId;
2597 mFocusedNodeId = nodeId;
2598 }
2599 }
2600 } break;
2601
2602 case AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED: {
2603 synchronized (mLock) {
2604 if (mFocusedWindowId == event.getWindowId()
2605 && mFocusedNodeId == event.getSourceNodeId()) {
2606 notifyValueChanged(event.getWindowId(), event.getSourceNodeId());
2607 }
2608 }
2609 } break;
2610
Felipe Leme54cc6832018-03-06 12:54:31 -08002611 case AccessibilityEvent.TYPE_VIEW_CLICKED: {
2612 synchronized (mLock) {
2613 notifyViewClicked(event.getWindowId(), event.getSourceNodeId());
2614 }
2615 } break;
2616
Svetoslav Ganov24c90452017-12-27 15:17:14 -08002617 case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED: {
2618 final AutofillClient client = getClient();
2619 if (client != null) {
2620 synchronized (mLock) {
2621 if (client.autofillClientIsFillUiShowing()) {
2622 notifyViewEntered(mFocusedWindowId, mFocusedNodeId, mFocusedBounds);
2623 }
2624 updateTrackedViewsLocked();
2625 }
2626 }
2627 } break;
2628 }
2629
2630 return accessibilityEnabled ? event : null;
2631 }
2632
2633 private boolean notifyViewEntered(int windowId, long nodeId, Rect focusedBounds) {
2634 final int virtualId = AccessibilityNodeInfo.getVirtualDescendantId(nodeId);
2635 if (!isVirtualNode(virtualId)) {
2636 return false;
2637 }
2638 final View view = findViewByAccessibilityId(windowId, nodeId);
2639 if (view == null) {
2640 return false;
2641 }
2642 final AccessibilityNodeInfo node = findVirtualNodeByAccessibilityId(view, virtualId);
2643 if (node == null) {
2644 return false;
2645 }
2646 if (!node.isEditable()) {
2647 return false;
2648 }
2649 final Rect newBounds = mTempBounds;
2650 node.getBoundsInScreen(newBounds);
2651 if (newBounds.equals(focusedBounds)) {
2652 return false;
2653 }
2654 focusedBounds.set(newBounds);
2655 AutofillManager.this.notifyViewEntered(view, virtualId, newBounds);
2656 return true;
2657 }
2658
2659 private void notifyViewExited(int windowId, long nodeId) {
2660 final int virtualId = AccessibilityNodeInfo.getVirtualDescendantId(nodeId);
2661 if (!isVirtualNode(virtualId)) {
2662 return;
2663 }
2664 final View view = findViewByAccessibilityId(windowId, nodeId);
2665 if (view == null) {
2666 return;
2667 }
2668 AutofillManager.this.notifyViewExited(view, virtualId);
2669 }
2670
2671 private void notifyValueChanged(int windowId, long nodeId) {
2672 final int virtualId = AccessibilityNodeInfo.getVirtualDescendantId(nodeId);
2673 if (!isVirtualNode(virtualId)) {
2674 return;
2675 }
2676 final View view = findViewByAccessibilityId(windowId, nodeId);
2677 if (view == null) {
2678 return;
2679 }
2680 final AccessibilityNodeInfo node = findVirtualNodeByAccessibilityId(view, virtualId);
2681 if (node == null) {
2682 return;
2683 }
2684 AutofillManager.this.notifyValueChanged(view, virtualId,
2685 AutofillValue.forText(node.getText()));
2686 }
2687
Felipe Leme54cc6832018-03-06 12:54:31 -08002688 private void notifyViewClicked(int windowId, long nodeId) {
2689 final int virtualId = AccessibilityNodeInfo.getVirtualDescendantId(nodeId);
2690 if (!isVirtualNode(virtualId)) {
2691 return;
2692 }
2693 final View view = findViewByAccessibilityId(windowId, nodeId);
2694 if (view == null) {
2695 return;
2696 }
2697 final AccessibilityNodeInfo node = findVirtualNodeByAccessibilityId(view, virtualId);
2698 if (node == null) {
2699 return;
2700 }
2701 AutofillManager.this.notifyViewClicked(view, virtualId);
2702 }
2703
Andreas Gampe3f24e692018-02-05 13:24:28 -08002704 @GuardedBy("mLock")
Svetoslav Ganov24c90452017-12-27 15:17:14 -08002705 private void updateTrackedViewsLocked() {
2706 if (mTrackedViews != null) {
2707 mTrackedViews.onVisibleForAutofillChangedLocked();
2708 }
2709 }
2710
2711 private View findViewByAccessibilityId(int windowId, long nodeId) {
2712 final AutofillClient client = getClient();
2713 if (client == null) {
2714 return null;
2715 }
2716 final int viewId = AccessibilityNodeInfo.getAccessibilityViewId(nodeId);
2717 return client.autofillClientFindViewByAccessibilityIdTraversal(viewId, windowId);
2718 }
2719
2720 private AccessibilityNodeInfo findVirtualNodeByAccessibilityId(View view, int virtualId) {
2721 final AccessibilityNodeProvider provider = view.getAccessibilityNodeProvider();
2722 if (provider == null) {
2723 return null;
2724 }
2725 return provider.createAccessibilityNodeInfo(virtualId);
2726 }
2727
2728 private boolean isVirtualNode(int nodeId) {
2729 return nodeId != AccessibilityNodeProvider.HOST_VIEW_ID
2730 && nodeId != AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
2731 }
Felipe Leme9876a6f2017-05-30 15:47:28 -07002732 }
2733
Felipe Lemee6010f22017-03-03 11:19:51 -08002734 /**
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002735 * View tracking information. Once all tracked views become invisible the session is finished.
2736 */
2737 private class TrackedViews {
2738 /** Visible tracked views */
2739 @Nullable private ArraySet<AutofillId> mVisibleTrackedIds;
2740
2741 /** Invisible tracked views */
2742 @Nullable private ArraySet<AutofillId> mInvisibleTrackedIds;
2743
2744 /**
2745 * Check if set is null or value is in set.
2746 *
2747 * @param set The set or null (== empty set)
2748 * @param value The value that might be in the set
2749 *
2750 * @return {@code true} iff set is not empty and value is in set
2751 */
Felipe Leme27e20222017-05-18 15:24:11 -07002752 // TODO: move to Helper as static method
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002753 private <T> boolean isInSet(@Nullable ArraySet<T> set, T value) {
2754 return set != null && set.contains(value);
2755 }
2756
2757 /**
2758 * Add a value to a set. If set is null, create a new set.
2759 *
2760 * @param set The set or null (== empty set)
2761 * @param valueToAdd The value to add
2762 *
2763 * @return The set including the new value. If set was {@code null}, a set containing only
2764 * the new value.
2765 */
Felipe Leme27e20222017-05-18 15:24:11 -07002766 // TODO: move to Helper as static method
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002767 @NonNull
2768 private <T> ArraySet<T> addToSet(@Nullable ArraySet<T> set, T valueToAdd) {
2769 if (set == null) {
2770 set = new ArraySet<>(1);
2771 }
2772
2773 set.add(valueToAdd);
2774
2775 return set;
2776 }
2777
2778 /**
2779 * Remove a value from a set.
2780 *
2781 * @param set The set or null (== empty set)
2782 * @param valueToRemove The value to remove
2783 *
2784 * @return The set without the removed value. {@code null} if set was null, or is empty
2785 * after removal.
2786 */
Felipe Leme27e20222017-05-18 15:24:11 -07002787 // TODO: move to Helper as static method
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002788 @Nullable
2789 private <T> ArraySet<T> removeFromSet(@Nullable ArraySet<T> set, T valueToRemove) {
2790 if (set == null) {
2791 return null;
2792 }
2793
2794 set.remove(valueToRemove);
2795
2796 if (set.isEmpty()) {
2797 return null;
2798 }
2799
2800 return set;
2801 }
2802
2803 /**
2804 * Set the tracked views.
2805 *
2806 * @param trackedIds The views to be tracked
2807 */
Felipe Leme27e20222017-05-18 15:24:11 -07002808 TrackedViews(@Nullable AutofillId[] trackedIds) {
Felipe Leme637e05e2017-12-06 12:09:37 -08002809 final AutofillClient client = getClient();
Svetoslav Ganov24c90452017-12-27 15:17:14 -08002810 if (!ArrayUtils.isEmpty(trackedIds) && client != null) {
Philip P. Moltmann134cee22017-05-06 11:28:38 -07002811 final boolean[] isVisible;
2812
Svetoslav Ganov24c90452017-12-27 15:17:14 -08002813 if (client.autofillClientIsVisibleForAutofill()) {
Felipe Leme5b32ebe2018-02-15 12:52:19 -08002814 if (sVerbose) Log.v(TAG, "client is visible, check tracked ids");
Svetoslav Ganov24c90452017-12-27 15:17:14 -08002815 isVisible = client.autofillClientGetViewVisibility(trackedIds);
Philip P. Moltmann134cee22017-05-06 11:28:38 -07002816 } else {
2817 // All false
Felipe Leme27e20222017-05-18 15:24:11 -07002818 isVisible = new boolean[trackedIds.length];
Philip P. Moltmann134cee22017-05-06 11:28:38 -07002819 }
2820
Felipe Leme27e20222017-05-18 15:24:11 -07002821 final int numIds = trackedIds.length;
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002822 for (int i = 0; i < numIds; i++) {
Felipe Leme27e20222017-05-18 15:24:11 -07002823 final AutofillId id = trackedIds[i];
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002824
Philip P. Moltmann134cee22017-05-06 11:28:38 -07002825 if (isVisible[i]) {
Philip P. Moltmanne0e28712017-04-20 15:19:06 -07002826 mVisibleTrackedIds = addToSet(mVisibleTrackedIds, id);
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002827 } else {
2828 mInvisibleTrackedIds = addToSet(mInvisibleTrackedIds, id);
2829 }
2830 }
2831 }
2832
Felipe Leme9f9ee252017-04-27 13:56:22 -07002833 if (sVerbose) {
Felipe Leme5b32ebe2018-02-15 12:52:19 -08002834 Log.v(TAG, "TrackedViews(trackedIds=" + Arrays.toString(trackedIds) + "): "
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002835 + " mVisibleTrackedIds=" + mVisibleTrackedIds
2836 + " mInvisibleTrackedIds=" + mInvisibleTrackedIds);
2837 }
2838
2839 if (mVisibleTrackedIds == null) {
2840 finishSessionLocked();
2841 }
2842 }
2843
2844 /**
2845 * Called when a {@link View view's} visibility changes.
2846 *
Svetoslav Ganov4db89ba2017-06-28 16:50:37 -07002847 * @param id the id of the view/virtual view whose visibility changed.
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002848 * @param isVisible visible if the view is visible in the view hierarchy.
2849 */
Andreas Gampe3f24e692018-02-05 13:24:28 -08002850 @GuardedBy("mLock")
Dake Gu67decfa2017-12-27 11:48:08 -08002851 void notifyViewVisibilityChangedLocked(@NonNull AutofillId id, boolean isVisible) {
Felipe Leme9f9ee252017-04-27 13:56:22 -07002852 if (sDebug) {
Svetoslav Ganov24c90452017-12-27 15:17:14 -08002853 Log.d(TAG, "notifyViewVisibilityChangedLocked(): id=" + id + " isVisible="
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002854 + isVisible);
2855 }
2856
Dake Gu67decfa2017-12-27 11:48:08 -08002857 if (isClientVisibleForAutofillLocked()) {
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002858 if (isVisible) {
2859 if (isInSet(mInvisibleTrackedIds, id)) {
2860 mInvisibleTrackedIds = removeFromSet(mInvisibleTrackedIds, id);
2861 mVisibleTrackedIds = addToSet(mVisibleTrackedIds, id);
2862 }
2863 } else {
2864 if (isInSet(mVisibleTrackedIds, id)) {
2865 mVisibleTrackedIds = removeFromSet(mVisibleTrackedIds, id);
2866 mInvisibleTrackedIds = addToSet(mInvisibleTrackedIds, id);
2867 }
2868 }
2869 }
2870
2871 if (mVisibleTrackedIds == null) {
Felipe Leme27e20222017-05-18 15:24:11 -07002872 if (sVerbose) {
2873 Log.v(TAG, "No more visible ids. Invisibile = " + mInvisibleTrackedIds);
2874 }
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002875 finishSessionLocked();
2876 }
2877 }
2878
2879 /**
2880 * Called once the client becomes visible.
2881 *
Svetoslav Ganov24c90452017-12-27 15:17:14 -08002882 * @see AutofillClient#autofillClientIsVisibleForAutofill()
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002883 */
Andreas Gampe3f24e692018-02-05 13:24:28 -08002884 @GuardedBy("mLock")
Svetoslav Ganov24c90452017-12-27 15:17:14 -08002885 void onVisibleForAutofillChangedLocked() {
Philip P. Moltmann134cee22017-05-06 11:28:38 -07002886 // The visibility of the views might have changed while the client was not be visible,
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002887 // hence update the visibility state for all views.
Felipe Leme637e05e2017-12-06 12:09:37 -08002888 AutofillClient client = getClient();
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002889 ArraySet<AutofillId> updatedVisibleTrackedIds = null;
2890 ArraySet<AutofillId> updatedInvisibleTrackedIds = null;
2891 if (client != null) {
Felipe Leme7008e702018-03-16 18:02:16 -07002892 if (sVerbose) {
2893 Log.v(TAG, "onVisibleForAutofillChangedLocked(): inv= " + mInvisibleTrackedIds
2894 + " vis=" + mVisibleTrackedIds);
2895 }
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002896 if (mInvisibleTrackedIds != null) {
Philip P. Moltmann134cee22017-05-06 11:28:38 -07002897 final ArrayList<AutofillId> orderedInvisibleIds =
2898 new ArrayList<>(mInvisibleTrackedIds);
Svetoslav Ganov24c90452017-12-27 15:17:14 -08002899 final boolean[] isVisible = client.autofillClientGetViewVisibility(
2900 Helper.toArray(orderedInvisibleIds));
Philip P. Moltmann134cee22017-05-06 11:28:38 -07002901
2902 final int numInvisibleTrackedIds = orderedInvisibleIds.size();
2903 for (int i = 0; i < numInvisibleTrackedIds; i++) {
2904 final AutofillId id = orderedInvisibleIds.get(i);
2905 if (isVisible[i]) {
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002906 updatedVisibleTrackedIds = addToSet(updatedVisibleTrackedIds, id);
2907
Felipe Leme9f9ee252017-04-27 13:56:22 -07002908 if (sDebug) {
2909 Log.d(TAG, "onVisibleForAutofill() " + id + " became visible");
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002910 }
2911 } else {
2912 updatedInvisibleTrackedIds = addToSet(updatedInvisibleTrackedIds, id);
2913 }
2914 }
2915 }
2916
2917 if (mVisibleTrackedIds != null) {
Philip P. Moltmann134cee22017-05-06 11:28:38 -07002918 final ArrayList<AutofillId> orderedVisibleIds =
2919 new ArrayList<>(mVisibleTrackedIds);
Svetoslav Ganov24c90452017-12-27 15:17:14 -08002920 final boolean[] isVisible = client.autofillClientGetViewVisibility(
2921 Helper.toArray(orderedVisibleIds));
Philip P. Moltmann134cee22017-05-06 11:28:38 -07002922
2923 final int numVisibleTrackedIds = orderedVisibleIds.size();
2924 for (int i = 0; i < numVisibleTrackedIds; i++) {
2925 final AutofillId id = orderedVisibleIds.get(i);
2926
2927 if (isVisible[i]) {
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002928 updatedVisibleTrackedIds = addToSet(updatedVisibleTrackedIds, id);
2929 } else {
2930 updatedInvisibleTrackedIds = addToSet(updatedInvisibleTrackedIds, id);
2931
Felipe Leme9f9ee252017-04-27 13:56:22 -07002932 if (sDebug) {
2933 Log.d(TAG, "onVisibleForAutofill() " + id + " became invisible");
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002934 }
2935 }
2936 }
2937 }
2938
2939 mInvisibleTrackedIds = updatedInvisibleTrackedIds;
2940 mVisibleTrackedIds = updatedVisibleTrackedIds;
2941 }
2942
2943 if (mVisibleTrackedIds == null) {
Felipe Leme5b32ebe2018-02-15 12:52:19 -08002944 if (sVerbose) {
2945 Log.v(TAG, "onVisibleForAutofillChangedLocked(): no more visible ids");
2946 }
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07002947 finishSessionLocked();
2948 }
2949 }
2950 }
2951
2952 /**
Felipe Leme744976e2017-07-31 11:34:14 -07002953 * Callback for autofill related events.
Felipe Lemee6010f22017-03-03 11:19:51 -08002954 *
2955 * <p>Typically used for applications that display their own "auto-complete" views, so they can
Felipe Leme2fe3ade2017-09-28 15:03:36 -07002956 * enable / disable such views when the autofill UI is shown / hidden.
Felipe Lemee6010f22017-03-03 11:19:51 -08002957 */
2958 public abstract static class AutofillCallback {
2959
2960 /** @hide */
Jeff Sharkeyce8db992017-12-13 20:05:05 -07002961 @IntDef(prefix = { "EVENT_INPUT_" }, value = {
2962 EVENT_INPUT_SHOWN,
2963 EVENT_INPUT_HIDDEN,
2964 EVENT_INPUT_UNAVAILABLE
2965 })
Felipe Lemee6010f22017-03-03 11:19:51 -08002966 @Retention(RetentionPolicy.SOURCE)
2967 public @interface AutofillEventType {}
2968
2969 /**
Felipe Leme2fe3ade2017-09-28 15:03:36 -07002970 * The autofill input UI associated with the view was shown.
Felipe Lemee6010f22017-03-03 11:19:51 -08002971 *
Felipe Leme2fe3ade2017-09-28 15:03:36 -07002972 * <p>If the view provides its own auto-complete UI and its currently shown, it
Felipe Lemee6010f22017-03-03 11:19:51 -08002973 * should be hidden upon receiving this event.
2974 */
2975 public static final int EVENT_INPUT_SHOWN = 1;
2976
2977 /**
Felipe Leme2fe3ade2017-09-28 15:03:36 -07002978 * The autofill input UI associated with the view was hidden.
Felipe Lemee6010f22017-03-03 11:19:51 -08002979 *
Felipe Leme2fe3ade2017-09-28 15:03:36 -07002980 * <p>If the view provides its own auto-complete UI that was hidden upon a
Felipe Lemee6010f22017-03-03 11:19:51 -08002981 * {@link #EVENT_INPUT_SHOWN} event, it could be shown again now.
2982 */
2983 public static final int EVENT_INPUT_HIDDEN = 2;
2984
2985 /**
Felipe Leme2fe3ade2017-09-28 15:03:36 -07002986 * The autofill input UI associated with the view isn't shown because
Felipe Leme24aae152017-03-15 12:33:01 -07002987 * autofill is not available.
2988 *
Felipe Leme2fe3ade2017-09-28 15:03:36 -07002989 * <p>If the view provides its own auto-complete UI but was not displaying it
Felipe Leme24aae152017-03-15 12:33:01 -07002990 * to avoid flickering, it could shown it upon receiving this event.
2991 */
2992 public static final int EVENT_INPUT_UNAVAILABLE = 3;
2993
2994 /**
Felipe Lemee6010f22017-03-03 11:19:51 -08002995 * Called after a change in the autofill state associated with a view.
2996 *
2997 * @param view view associated with the change.
2998 *
2999 * @param event currently either {@link #EVENT_INPUT_SHOWN} or {@link #EVENT_INPUT_HIDDEN}.
3000 */
Felipe Leme81f01d92017-03-16 17:13:25 -07003001 public void onAutofillEvent(@NonNull View view, @AutofillEventType int event) {
3002 }
Felipe Lemee6010f22017-03-03 11:19:51 -08003003
3004 /**
3005 * Called after a change in the autofill state associated with a virtual view.
3006 *
3007 * @param view parent view associated with the change.
Felipe Leme6dcec872017-05-25 11:24:23 -07003008 * @param virtualId id identifying the virtual child inside the parent view.
Felipe Lemee6010f22017-03-03 11:19:51 -08003009 *
3010 * @param event currently either {@link #EVENT_INPUT_SHOWN} or {@link #EVENT_INPUT_HIDDEN}.
3011 */
Felipe Leme6dcec872017-05-25 11:24:23 -07003012 public void onAutofillEvent(@NonNull View view, int virtualId,
3013 @AutofillEventType int event) {
Felipe Leme81f01d92017-03-16 17:13:25 -07003014 }
Felipe Lemee6010f22017-03-03 11:19:51 -08003015 }
3016
Felipe Leme640f30a2017-03-06 15:44:06 -08003017 private static final class AutofillManagerClient extends IAutoFillManagerClient.Stub {
3018 private final WeakReference<AutofillManager> mAfm;
Svet Ganov782043c2017-02-11 00:52:02 +00003019
Felipe Leme284ad1c2018-11-15 18:16:12 -08003020 private AutofillManagerClient(AutofillManager autofillManager) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003021 mAfm = new WeakReference<>(autofillManager);
Svet Ganov782043c2017-02-11 00:52:02 +00003022 }
3023
3024 @Override
Felipe Leme51e29da2017-10-24 14:03:10 -07003025 public void setState(int flags) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003026 final AutofillManager afm = mAfm.get();
3027 if (afm != null) {
Felipe Leme51e29da2017-10-24 14:03:10 -07003028 afm.post(() -> afm.setState(flags));
Svet Ganov782043c2017-02-11 00:52:02 +00003029 }
3030 }
3031
3032 @Override
Philip P. Moltmann134cee22017-05-06 11:28:38 -07003033 public void autofill(int sessionId, List<AutofillId> ids, List<AutofillValue> values) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003034 final AutofillManager afm = mAfm.get();
3035 if (afm != null) {
Felipe Leme9876a6f2017-05-30 15:47:28 -07003036 afm.post(() -> afm.autofill(sessionId, ids, values));
Svet Ganov782043c2017-02-11 00:52:02 +00003037 }
3038 }
3039
3040 @Override
Svetoslav Ganova9379d02017-05-09 17:40:24 -07003041 public void authenticate(int sessionId, int authenticationId, IntentSender intent,
3042 Intent fillInIntent) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003043 final AutofillManager afm = mAfm.get();
3044 if (afm != null) {
Felipe Leme9876a6f2017-05-30 15:47:28 -07003045 afm.post(() -> afm.authenticate(sessionId, authenticationId, intent, fillInIntent));
Svet Ganov782043c2017-02-11 00:52:02 +00003046 }
3047 }
Felipe Lemee6010f22017-03-03 11:19:51 -08003048
3049 @Override
Philip P. Moltmann134cee22017-05-06 11:28:38 -07003050 public void requestShowFillUi(int sessionId, AutofillId id, int width, int height,
3051 Rect anchorBounds, IAutofillWindowPresenter presenter) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003052 final AutofillManager afm = mAfm.get();
3053 if (afm != null) {
Felipe Leme9876a6f2017-05-30 15:47:28 -07003054 afm.post(() -> afm.requestShowFillUi(sessionId, id, width, height, anchorBounds,
3055 presenter));
Felipe Leme4753bb02017-03-22 20:24:00 -07003056 }
3057 }
3058
3059 @Override
Philip P. Moltmann134cee22017-05-06 11:28:38 -07003060 public void requestHideFillUi(int sessionId, AutofillId id) {
Felipe Leme4753bb02017-03-22 20:24:00 -07003061 final AutofillManager afm = mAfm.get();
3062 if (afm != null) {
Dake Gub0fa3782018-02-26 12:25:14 -08003063 afm.post(() -> afm.requestHideFillUi(id, false));
Felipe Leme4753bb02017-03-22 20:24:00 -07003064 }
3065 }
3066
3067 @Override
Felipe Leme17292d12017-10-24 14:03:10 -07003068 public void notifyNoFillUi(int sessionId, AutofillId id, int sessionFinishedState) {
Felipe Leme4753bb02017-03-22 20:24:00 -07003069 final AutofillManager afm = mAfm.get();
3070 if (afm != null) {
Felipe Leme17292d12017-10-24 14:03:10 -07003071 afm.post(() -> afm.notifyNoFillUi(sessionId, id, sessionFinishedState));
Felipe Lemee6010f22017-03-03 11:19:51 -08003072 }
3073 }
Svet Ganovc3d1c852017-04-12 22:34:28 -07003074
3075 @Override
Dake Gu6a20a192018-02-08 12:09:30 -08003076 public void dispatchUnhandledKey(int sessionId, AutofillId id, KeyEvent fullScreen) {
3077 final AutofillManager afm = mAfm.get();
3078 if (afm != null) {
3079 afm.post(() -> afm.dispatchUnhandledKey(sessionId, id, fullScreen));
3080 }
3081 }
3082
3083 @Override
Felipe Lemec24a56a2017-08-03 14:27:57 -07003084 public void startIntentSender(IntentSender intentSender, Intent intent) {
Svet Ganovc3d1c852017-04-12 22:34:28 -07003085 final AutofillManager afm = mAfm.get();
3086 if (afm != null) {
Felipe Leme9876a6f2017-05-30 15:47:28 -07003087 afm.post(() -> {
Svet Ganovc3d1c852017-04-12 22:34:28 -07003088 try {
Felipe Lemec24a56a2017-08-03 14:27:57 -07003089 afm.mContext.startIntentSender(intentSender, intent, 0, 0, 0);
Svet Ganovc3d1c852017-04-12 22:34:28 -07003090 } catch (IntentSender.SendIntentException e) {
3091 Log.e(TAG, "startIntentSender() failed for intent:" + intentSender, e);
3092 }
3093 });
3094 }
3095 }
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07003096
3097 @Override
Felipe Leme27e20222017-05-18 15:24:11 -07003098 public void setTrackedViews(int sessionId, AutofillId[] ids,
Felipe Leme2fe3ade2017-09-28 15:03:36 -07003099 boolean saveOnAllViewsInvisible, boolean saveOnFinish, AutofillId[] fillableIds,
3100 AutofillId saveTriggerId) {
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07003101 final AutofillManager afm = mAfm.get();
3102 if (afm != null) {
Felipe Leme2fe3ade2017-09-28 15:03:36 -07003103 afm.post(() -> afm.setTrackedViews(sessionId, ids, saveOnAllViewsInvisible,
3104 saveOnFinish, fillableIds, saveTriggerId));
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07003105 }
3106 }
Felipe Lemec24a56a2017-08-03 14:27:57 -07003107
3108 @Override
3109 public void setSaveUiState(int sessionId, boolean shown) {
3110 final AutofillManager afm = mAfm.get();
3111 if (afm != null) {
Felipe Lemec7b45292017-09-19 09:06:20 -07003112 afm.post(() -> afm.setSaveUiState(sessionId, shown));
3113 }
3114 }
3115
3116 @Override
Felipe Leme650f7ab2017-09-19 13:08:24 -07003117 public void setSessionFinished(int newState) {
Felipe Lemec7b45292017-09-19 09:06:20 -07003118 final AutofillManager afm = mAfm.get();
3119 if (afm != null) {
Felipe Leme650f7ab2017-09-19 13:08:24 -07003120 afm.post(() -> afm.setSessionFinished(newState));
Felipe Lemec24a56a2017-08-03 14:27:57 -07003121 }
3122 }
Felipe Leme284ad1c2018-11-15 18:16:12 -08003123
3124 @Override
3125 public void getAugmentedAutofillClient(IResultReceiver result) {
3126 final AutofillManager afm = mAfm.get();
3127 if (afm != null) {
3128 afm.post(() -> afm.getAugmentedAutofillClient(result));
3129 }
3130 }
3131 }
3132
3133 private static final class AugmentedAutofillManagerClient
3134 extends IAugmentedAutofillManagerClient.Stub {
3135 private final WeakReference<AutofillManager> mAfm;
3136
3137 private AugmentedAutofillManagerClient(AutofillManager autofillManager) {
3138 mAfm = new WeakReference<>(autofillManager);
3139 }
3140
3141 @Override
3142 public Rect getViewCoordinates(@NonNull AutofillId id) {
Felipe Leme284ad1c2018-11-15 18:16:12 -08003143 final AutofillManager afm = mAfm.get();
3144 if (afm == null) return null;
3145
3146 final View view = afm.getClient().autofillClientFindViewByAutofillIdTraversal(id);
Feng Cao023b84c2018-12-14 15:51:17 -08003147 final Rect windowVisibleDisplayFrame = new Rect();
3148 view.getWindowVisibleDisplayFrame(windowVisibleDisplayFrame);
Felipe Leme284ad1c2018-11-15 18:16:12 -08003149 final int[] location = new int[2];
3150 view.getLocationOnScreen(location);
Feng Cao023b84c2018-12-14 15:51:17 -08003151 final Rect rect = new Rect(location[0], location[1] - windowVisibleDisplayFrame.top,
3152 location[0] + view.getWidth(),
3153 location[1] - windowVisibleDisplayFrame.top + view.getHeight());
Felipe Leme284ad1c2018-11-15 18:16:12 -08003154 if (sVerbose) {
3155 Log.v(TAG, "Coordinates for " + id + ": " + rect);
3156 }
3157 return rect;
3158 }
3159
3160 @Override
3161 public void autofill(int sessionId, List<AutofillId> ids, List<AutofillValue> values) {
3162 final AutofillManager afm = mAfm.get();
3163 if (afm != null) {
3164 afm.post(() -> afm.autofill(sessionId, ids, values));
3165 }
3166 }
Feng Cao158b6562019-01-07 15:42:52 -08003167
3168 @Override
3169 public void requestShowFillUi(int sessionId, AutofillId id, int width, int height,
3170 Rect anchorBounds, IAutofillWindowPresenter presenter) {
3171 final AutofillManager afm = mAfm.get();
3172 if (afm != null) {
3173 afm.post(() -> afm.requestShowFillUi(sessionId, id, width, height, anchorBounds,
3174 presenter));
3175 }
3176 }
3177
3178 @Override
3179 public void requestHideFillUi(int sessionId, AutofillId id) {
3180 final AutofillManager afm = mAfm.get();
3181 if (afm != null) {
3182 afm.post(() -> afm.requestHideFillUi(id, false));
3183 }
3184 }
Svet Ganov782043c2017-02-11 00:52:02 +00003185 }
Felipe Leme3461d3c2017-01-19 08:54:55 -08003186}