Debian Codegraph @

core/java/android/view/contentcapture/ContentCaptureSession.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2018 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 package android.view.contentcapture;
17
18 import static android.view.contentcapture.ContentCaptureHelper.sDebug;
19 import static android.view.contentcapture.ContentCaptureHelper.sVerbose;
20 import static android.view.contentcapture.ContentCaptureManager.NO_SESSION_ID;
21
22 import android.annotation.CallSuper;
23 import android.annotation.IntDef;
24 import android.annotation.NonNull;
25 import android.annotation.Nullable;
26 import android.graphics.Insets;
27 import android.util.DebugUtils;
28 import android.util.Log;
29 import android.view.View;
30 import android.view.ViewStructure;
31 import android.view.autofill.AutofillId;
32 import android.view.contentcapture.ViewNode.ViewStructureImpl;
33
34 import com.android.internal.annotations.GuardedBy;
35 import com.android.internal.annotations.VisibleForTesting;
36 import com.android.internal.util.ArrayUtils;
37 import com.android.internal.util.Preconditions;
38
39 import java.io.PrintWriter;
40 import java.lang.annotation.Retention;
41 import java.lang.annotation.RetentionPolicy;
42 import java.security.SecureRandom;
43 import java.util.ArrayList;
44 import java.util.Objects;
45
46 /**
47 * Session used when notifying the Android system about events associated with views.
48 */
49 public abstract class ContentCaptureSession implements AutoCloseable {
50
51 private static final String TAG = ContentCaptureSession.class.getSimpleName();
52
53 // TODO(b/158778794): to make the session ids truly globally unique across
54 // processes, we may need to explore other options.
55 private static final SecureRandom ID_GENERATOR = new SecureRandom();
56
57 /**
58 * Initial state, when there is no session.
59 *
60 * @hide
61 */
62 // NOTE: not prefixed by STATE_ so it's not printed on getStateAsString()
63 public static final int UNKNOWN_STATE = 0x0;
64
65 /**
66 * Service's startSession() was called, but server didn't confirm it was created yet.
67 *
68 * @hide
69 */
70 public static final int STATE_WAITING_FOR_SERVER = 0x1;
71
72 /**
73 * Session is active.
74 *
75 * @hide
76 */
77 public static final int STATE_ACTIVE = 0x2;
78
79 /**
80 * Session is disabled because there is no service for this user.
81 *
82 * @hide
83 */
84 public static final int STATE_DISABLED = 0x4;
85
86 /**
87 * Session is disabled because its id already existed on server.
88 *
89 * @hide
90 */
91 public static final int STATE_DUPLICATED_ID = 0x8;
92
93 /**
94 * Session is disabled because service is not set for user.
95 *
96 * @hide
97 */
98 public static final int STATE_NO_SERVICE = 0x10;
99
100 /**
101 * Session is disabled by FLAG_SECURE
102 *
103 * @hide
104 */
105 public static final int STATE_FLAG_SECURE = 0x20;
106
107 /**
108 * Session is disabled manually by the specific app
109 * (through {@link ContentCaptureManager#setContentCaptureEnabled(boolean)}).
110 *
111 * @hide
112 */
113 public static final int STATE_BY_APP = 0x40;
114
115 /**
116 * Session is disabled because session start was never replied.
117 *
118 * @hide
119 */
120 public static final int STATE_NO_RESPONSE = 0x80;
121
122 /**
123 * Session is disabled because an internal error.
124 *
125 * @hide
126 */
127 public static final int STATE_INTERNAL_ERROR = 0x100;
128
129 /**
130 * Session is disabled because service didn't allowlist package or activity.
131 *
132 * @hide
133 */
134 public static final int STATE_NOT_WHITELISTED = 0x200;
135
136 /**
137 * Session is disabled because the service died.
138 *
139 * @hide
140 */
141 public static final int STATE_SERVICE_DIED = 0x400;
142
143 /**
144 * Session is disabled because the service package is being udpated.
145 *
146 * @hide
147 */
148 public static final int STATE_SERVICE_UPDATING = 0x800;
149
150 /**
151 * Session is enabled, after the service died and came back to live.
152 *
153 * @hide
154 */
155 public static final int STATE_SERVICE_RESURRECTED = 0x1000;
156
157 private static final int INITIAL_CHILDREN_CAPACITY = 5;
158
159 /** @hide */
160 public static final int FLUSH_REASON_FULL = 1;
161 /** @hide */
162 public static final int FLUSH_REASON_VIEW_ROOT_ENTERED = 2;
163 /** @hide */
164 public static final int FLUSH_REASON_SESSION_STARTED = 3;
165 /** @hide */
166 public static final int FLUSH_REASON_SESSION_FINISHED = 4;
167 /** @hide */
168 public static final int FLUSH_REASON_IDLE_TIMEOUT = 5;
169 /** @hide */
170 public static final int FLUSH_REASON_TEXT_CHANGE_TIMEOUT = 6;
171 /** @hide */
172 public static final int FLUSH_REASON_SESSION_CONNECTED = 7;
173
174 /** @hide */
175 @IntDef(prefix = { "FLUSH_REASON_" }, value = {
176 FLUSH_REASON_FULL,
177 FLUSH_REASON_VIEW_ROOT_ENTERED,
178 FLUSH_REASON_SESSION_STARTED,
179 FLUSH_REASON_SESSION_FINISHED,
180 FLUSH_REASON_IDLE_TIMEOUT,
181 FLUSH_REASON_TEXT_CHANGE_TIMEOUT,
182 FLUSH_REASON_SESSION_CONNECTED
183 })
184 @Retention(RetentionPolicy.SOURCE)
185 public @interface FlushReason{}
186
187 private final Object mLock = new Object();
188
189 /**
190 * Guard use to ignore events after it's destroyed.
191 */
192 @NonNull
193 @GuardedBy("mLock")
194 private boolean mDestroyed;
195
196 /** @hide */
197 @Nullable
198 protected final int mId;
199
200 private int mState = UNKNOWN_STATE;
201
202 // Lazily created on demand.
203 private ContentCaptureSessionId mContentCaptureSessionId;
204
205 /**
206 * {@link ContentCaptureContext} set by client, or {@code null} when it's the
207 * {@link ContentCaptureManager#getMainContentCaptureSession() default session} for the
208 * context.
209 */
210 @Nullable
211 private ContentCaptureContext mClientContext;
212
213 /**
214 * List of children session.
215 */
216 @Nullable
217 @GuardedBy("mLock")
218 private ArrayList<ContentCaptureSession> mChildren;
219
220 /** @hide */
221 protected ContentCaptureSession() {
222 this(getRandomSessionId());
223 }
224
225 /** @hide */
226 @VisibleForTesting
227 public ContentCaptureSession(int id) {
228 Preconditions.checkArgument(id != NO_SESSION_ID);
229 mId = id;
230 }
231
232 // Used by ChildCOntentCaptureSession
233 ContentCaptureSession(@NonNull ContentCaptureContext initialContext) {
234 this();
235 mClientContext = Objects.requireNonNull(initialContext);
236 }
237
238 /** @hide */
239 @NonNull
240 abstract MainContentCaptureSession getMainCaptureSession();
241
242 /**
243 * Gets the id used to identify this session.
244 */
245 @NonNull
246 public final ContentCaptureSessionId getContentCaptureSessionId() {
247 if (mContentCaptureSessionId == null) {
248 mContentCaptureSessionId = new ContentCaptureSessionId(mId);
249 }
250 return mContentCaptureSessionId;
251 }
252
253 /** @hide */
254 @NonNull
255 public int getId() {
256 return mId;
257 }
258
259 /**
260 * Creates a new {@link ContentCaptureSession}.
261 *
262 * <p>See {@link View#setContentCaptureSession(ContentCaptureSession)} for more info.
263 */
264 @NonNull
265 public final ContentCaptureSession createContentCaptureSession(
266 @NonNull ContentCaptureContext context) {
267 final ContentCaptureSession child = newChild(context);
268 if (sDebug) {
269 Log.d(TAG, "createContentCaptureSession(" + context + ": parent=" + mId + ", child="
270 + child.mId);
271 }
272 synchronized (mLock) {
273 if (mChildren == null) {
274 mChildren = new ArrayList<>(INITIAL_CHILDREN_CAPACITY);
275 }
276 mChildren.add(child);
277 }
278 return child;
279 }
280
281 abstract ContentCaptureSession newChild(@NonNull ContentCaptureContext context);
282
283 /**
284 * Flushes the buffered events to the service.
285 */
286 abstract void flush(@FlushReason int reason);
287
288 /**
289 * Sets the {@link ContentCaptureContext} associated with the session.
290 *
291 * <p>Typically used to change the context associated with the default session from an activity.
292 */
293 public final void setContentCaptureContext(@Nullable ContentCaptureContext context) {
294 if (!isContentCaptureEnabled()) return;
295
296 mClientContext = context;
297 updateContentCaptureContext(context);
298 }
299
300 abstract void updateContentCaptureContext(@Nullable ContentCaptureContext context);
301
302 /**
303 * Gets the {@link ContentCaptureContext} associated with the session.
304 *
305 * @return context set on constructor or by
306 * {@link #setContentCaptureContext(ContentCaptureContext)}, or {@code null} if never
307 * explicitly set.
308 */
309 @Nullable
310 public final ContentCaptureContext getContentCaptureContext() {
311 return mClientContext;
312 }
313
314 /**
315 * Destroys this session, flushing out all pending notifications to the service.
316 *
317 * <p>Once destroyed, any new notification will be dropped.
318 */
319 public final void destroy() {
320 synchronized (mLock) {
321 if (mDestroyed) {
322 if (sDebug) Log.d(TAG, "destroy(" + mId + "): already destroyed");
323 return;
324 }
325 mDestroyed = true;
326
327 // TODO(b/111276913): check state (for example, how to handle if it's waiting for remote
328 // id) and send it to the cache of batched commands
329 if (sVerbose) {
330 Log.v(TAG, "destroy(): state=" + getStateAsString(mState) + ", mId=" + mId);
331 }
332 // Finish children first
333 if (mChildren != null) {
334 final int numberChildren = mChildren.size();
335 if (sVerbose) Log.v(TAG, "Destroying " + numberChildren + " children first");
336 for (int i = 0; i < numberChildren; i++) {
337 final ContentCaptureSession child = mChildren.get(i);
338 try {
339 child.destroy();
340 } catch (Exception e) {
341 Log.w(TAG, "exception destroying child session #" + i + ": " + e);
342 }
343 }
344 }
345 }
346
347 onDestroy();
348 }
349
350 abstract void onDestroy();
351
352 /** @hide */
353 @Override
354 public void close() {
355 destroy();
356 }
357
358 /**
359 * Notifies the Content Capture Service that a node has been added to the view structure.
360 *
361 * <p>Typically called "manually" by views that handle their own virtual view hierarchy, or
362 * automatically by the Android System for views that return {@code true} on
363 * {@link View#onProvideContentCaptureStructure(ViewStructure, int)}.
364 *
365 * @param node node that has been added.
366 */
367 public final void notifyViewAppeared(@NonNull ViewStructure node) {
368 Objects.requireNonNull(node);
369 if (!isContentCaptureEnabled()) return;
370
371 if (!(node instanceof ViewNode.ViewStructureImpl)) {
372 throw new IllegalArgumentException("Invalid node class: " + node.getClass());
373 }
374
375 internalNotifyViewAppeared((ViewStructureImpl) node);
376 }
377
378 abstract void internalNotifyViewAppeared(@NonNull ViewNode.ViewStructureImpl node);
379
380 /**
381 * Notifies the Content Capture Service that a node has been removed from the view structure.
382 *
383 * <p>Typically called "manually" by views that handle their own virtual view hierarchy, or
384 * automatically by the Android System for standard views.
385 *
386 * @param id id of the node that has been removed.
387 */
388 public final void notifyViewDisappeared(@NonNull AutofillId id) {
389 Objects.requireNonNull(id);
390 if (!isContentCaptureEnabled()) return;
391
392 internalNotifyViewDisappeared(id);
393 }
394
395 abstract void internalNotifyViewDisappeared(@NonNull AutofillId id);
396
397 /**
398 * Notifies the Content Capture Service that many nodes has been removed from a virtual view
399 * structure.
400 *
401 * <p>Should only be called by views that handle their own virtual view hierarchy.
402 *
403 * @param hostId id of the non-virtual view hosting the virtual view hierarchy (it can be
404 * obtained by calling {@link ViewStructure#getAutofillId()}).
405 * @param virtualIds ids of the virtual children.
406 *
407 * @throws IllegalArgumentException if the {@code hostId} is an autofill id for a virtual view.
408 * @throws IllegalArgumentException if {@code virtualIds} is empty
409 */
410 public final void notifyViewsDisappeared(@NonNull AutofillId hostId,
411 @NonNull long[] virtualIds) {
412 Preconditions.checkArgument(hostId.isNonVirtual(), "hostId cannot be virtual: %s", hostId);
413 Preconditions.checkArgument(!ArrayUtils.isEmpty(virtualIds), "virtual ids cannot be empty");
414 if (!isContentCaptureEnabled()) return;
415
416 // TODO(b/123036895): use a internalNotifyViewsDisappeared that optimizes how the event is
417 // parcelized
418 for (long id : virtualIds) {
419 internalNotifyViewDisappeared(new AutofillId(hostId, id, mId));
420 }
421 }
422
423 /**
424 * Notifies the Intelligence Service that the value of a text node has been changed.
425 *
426 * @param id of the node.
427 * @param text new text.
428 */
429 public final void notifyViewTextChanged(@NonNull AutofillId id, @Nullable CharSequence text) {
430 Objects.requireNonNull(id);
431
432 if (!isContentCaptureEnabled()) return;
433
434 internalNotifyViewTextChanged(id, text);
435 }
436
437 abstract void internalNotifyViewTextChanged(@NonNull AutofillId id,
438 @Nullable CharSequence text);
439
440 /**
441 * Notifies the Intelligence Service that the insets of a view have changed.
442 */
443 public final void notifyViewInsetsChanged(@NonNull Insets viewInsets) {
444 Objects.requireNonNull(viewInsets);
445
446 if (!isContentCaptureEnabled()) return;
447
448 internalNotifyViewInsetsChanged(viewInsets);
449 }
450
451 abstract void internalNotifyViewInsetsChanged(@NonNull Insets viewInsets);
452
453 /** @hide */
454 public abstract void internalNotifyViewTreeEvent(boolean started);
455
456 /**
457 * Notifies the Content Capture Service that a session has resumed.
458 */
459 public final void notifySessionResumed() {
460 if (!isContentCaptureEnabled()) return;
461
462 internalNotifySessionResumed();
463 }
464
465 abstract void internalNotifySessionResumed();
466
467 /**
468 * Notifies the Content Capture Service that a session has paused.
469 */
470 public final void notifySessionPaused() {
471 if (!isContentCaptureEnabled()) return;
472
473 internalNotifySessionPaused();
474 }
475
476 abstract void internalNotifySessionPaused();
477
478 /**
479 * Creates a {@link ViewStructure} for a "standard" view.
480 *
481 * <p>This method should be called after a visible view is laid out; the view then must populate
482 * the structure and pass it to {@link #notifyViewAppeared(ViewStructure)}.
483 *
484 * <b>Note: </b>views that manage a virtual structure under this view must populate just the
485 * node representing this view and return right away, then asynchronously report (not
486 * necessarily in the UI thread) when the children nodes appear, disappear or have their text
487 * changed by calling {@link ContentCaptureSession#notifyViewAppeared(ViewStructure)},
488 * {@link ContentCaptureSession#notifyViewDisappeared(AutofillId)}, and
489 * {@link ContentCaptureSession#notifyViewTextChanged(AutofillId, CharSequence)} respectively.
490 * The structure for the a child must be created using
491 * {@link ContentCaptureSession#newVirtualViewStructure(AutofillId, long)}, and the
492 * {@code autofillId} for a child can be obtained either through
493 * {@code childStructure.getAutofillId()} or
494 * {@link ContentCaptureSession#newAutofillId(AutofillId, long)}.
495 *
496 * <p>When the virtual view hierarchy represents a web page, you should also:
497 *
498 * <ul>
499 * <li>Call {@link ContentCaptureManager#getContentCaptureConditions()} to infer content capture
500 * events should be generate for that URL.
501 * <li>Create a new {@link ContentCaptureSession} child for every HTML element that renders a
502 * new URL (like an {@code IFRAME}) and use that session to notify events from that subtree.
503 * </ul>
504 *
505 * <p><b>Note: </b>the following methods of the {@code structure} will be ignored:
506 * <ul>
507 * <li>{@link ViewStructure#setChildCount(int)}
508 * <li>{@link ViewStructure#addChildCount(int)}
509 * <li>{@link ViewStructure#getChildCount()}
510 * <li>{@link ViewStructure#newChild(int)}
511 * <li>{@link ViewStructure#asyncNewChild(int)}
512 * <li>{@link ViewStructure#asyncCommit()}
513 * <li>{@link ViewStructure#setWebDomain(String)}
514 * <li>{@link ViewStructure#newHtmlInfoBuilder(String)}
515 * <li>{@link ViewStructure#setHtmlInfo(android.view.ViewStructure.HtmlInfo)}
516 * <li>{@link ViewStructure#setDataIsSensitive(boolean)}
517 * <li>{@link ViewStructure#setAlpha(float)}
518 * <li>{@link ViewStructure#setElevation(float)}
519 * <li>{@link ViewStructure#setTransformation(android.graphics.Matrix)}
520 * </ul>
521 */
522 @NonNull
523 public final ViewStructure newViewStructure(@NonNull View view) {
524 return new ViewNode.ViewStructureImpl(view);
525 }
526
527 /**
528 * Creates a new {@link AutofillId} for a virtual child, so it can be used to uniquely identify
529 * the children in the session.
530 *
531 * @param hostId id of the non-virtual view hosting the virtual view hierarchy (it can be
532 * obtained by calling {@link ViewStructure#getAutofillId()}).
533 * @param virtualChildId id of the virtual child, relative to the parent.
534 *
535 * @return if for the virtual child
536 *
537 * @throws IllegalArgumentException if the {@code parentId} is a virtual child id.
538 */
539 public @NonNull AutofillId newAutofillId(@NonNull AutofillId hostId, long virtualChildId) {
540 Objects.requireNonNull(hostId);
541 Preconditions.checkArgument(hostId.isNonVirtual(), "hostId cannot be virtual: %s", hostId);
542 return new AutofillId(hostId, virtualChildId, mId);
543 }
544
545 /**
546 * Creates a {@link ViewStructure} for a "virtual" view, so it can be passed to
547 * {@link #notifyViewAppeared(ViewStructure)} by the view managing the virtual view hierarchy.
548 *
549 * @param parentId id of the virtual view parent (it can be obtained by calling
550 * {@link ViewStructure#getAutofillId()} on the parent).
551 * @param virtualId id of the virtual child, relative to the parent.
552 *
553 * @return a new {@link ViewStructure} that can be used for Content Capture purposes.
554 */
555 @NonNull
556 public final ViewStructure newVirtualViewStructure(@NonNull AutofillId parentId,
557 long virtualId) {
558 return new ViewNode.ViewStructureImpl(parentId, virtualId, mId);
559 }
560
561 boolean isContentCaptureEnabled() {
562 synchronized (mLock) {
563 return !mDestroyed;
564 }
565 }
566
567 @CallSuper
568 void dump(@NonNull String prefix, @NonNull PrintWriter pw) {
569 pw.print(prefix); pw.print("id: "); pw.println(mId);
570 if (mClientContext != null) {
571 pw.print(prefix); mClientContext.dump(pw); pw.println();
572 }
573 synchronized (mLock) {
574 pw.print(prefix); pw.print("destroyed: "); pw.println(mDestroyed);
575 if (mChildren != null && !mChildren.isEmpty()) {
576 final String prefix2 = prefix + " ";
577 final int numberChildren = mChildren.size();
578 pw.print(prefix); pw.print("number children: "); pw.println(numberChildren);
579 for (int i = 0; i < numberChildren; i++) {
580 final ContentCaptureSession child = mChildren.get(i);
581 pw.print(prefix); pw.print(i); pw.println(": "); child.dump(prefix2, pw);
582 }
583 }
584 }
585 }
586
587 @Override
588 public String toString() {
589 return Integer.toString(mId);
590 }
591
592 /** @hide */
593 @NonNull
594 protected static String getStateAsString(int state) {
595 return state + " (" + (state == UNKNOWN_STATE ? "UNKNOWN"
596 : DebugUtils.flagsToString(ContentCaptureSession.class, "STATE_", state)) + ")";
597 }
598
599 /** @hide */
600 @NonNull
601 public static String getFlushReasonAsString(@FlushReason int reason) {
602 switch (reason) {
603 case FLUSH_REASON_FULL:
604 return "FULL";
605 case FLUSH_REASON_VIEW_ROOT_ENTERED:
606 return "VIEW_ROOT";
607 case FLUSH_REASON_SESSION_STARTED:
608 return "STARTED";
609 case FLUSH_REASON_SESSION_FINISHED:
610 return "FINISHED";
611 case FLUSH_REASON_IDLE_TIMEOUT:
612 return "IDLE";
613 case FLUSH_REASON_TEXT_CHANGE_TIMEOUT:
614 return "TEXT_CHANGE";
615 case FLUSH_REASON_SESSION_CONNECTED:
616 return "CONNECTED";
617 default:
618 return "UNKOWN-" + reason;
619 }
620 }
621
622 private static int getRandomSessionId() {
623 int id;
624 do {
625 id = ID_GENERATOR.nextInt();
626 } while (id == NO_SESSION_ID);
627 return id;
628 }
629 }