blob: 810c967ce2c8da5cc6eabd4aad7e9b846bb13e72 [file] [log] [blame]
Felipe Lemeb63e0dd2018-12-18 11:56:42 -08001/*
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 */
16package android.view.contentcapture;
17
Felipe Leme01297692019-01-29 18:16:23 -080018import static android.view.contentcapture.ContentCaptureEvent.TYPE_INITIAL_VIEW_TREE_APPEARED;
19import static android.view.contentcapture.ContentCaptureEvent.TYPE_INITIAL_VIEW_TREE_APPEARING;
Felipe Leme87a9dc92018-12-18 14:28:07 -080020import static android.view.contentcapture.ContentCaptureEvent.TYPE_SESSION_FINISHED;
21import static android.view.contentcapture.ContentCaptureEvent.TYPE_SESSION_STARTED;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080022import static android.view.contentcapture.ContentCaptureEvent.TYPE_VIEW_APPEARED;
23import static android.view.contentcapture.ContentCaptureEvent.TYPE_VIEW_DISAPPEARED;
24import static android.view.contentcapture.ContentCaptureEvent.TYPE_VIEW_TEXT_CHANGED;
Felipe Lemebe002d82019-01-23 10:22:32 -080025import static android.view.contentcapture.ContentCaptureHelper.DEBUG;
26import static android.view.contentcapture.ContentCaptureHelper.VERBOSE;
27import static android.view.contentcapture.ContentCaptureHelper.getSanitizedString;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080028
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080029import android.annotation.NonNull;
30import android.annotation.Nullable;
Felipe Leme3fe6e922019-02-04 17:52:27 -080031import android.annotation.UiThread;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080032import android.content.ComponentName;
33import android.content.Context;
34import android.content.pm.ParceledListSlice;
35import android.os.Bundle;
36import android.os.Handler;
37import android.os.IBinder;
38import android.os.IBinder.DeathRecipient;
39import android.os.RemoteException;
Felipe Leme1af85ea2019-01-16 13:23:40 -080040import android.util.LocalLog;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080041import android.util.Log;
42import android.util.TimeUtils;
43import android.view.autofill.AutofillId;
44import android.view.contentcapture.ViewNode.ViewStructureImpl;
45
46import com.android.internal.os.IResultReceiver;
47
48import java.io.PrintWriter;
49import java.util.ArrayList;
50import java.util.Collections;
51import java.util.List;
52import java.util.concurrent.atomic.AtomicBoolean;
53
54/**
55 * Main session associated with a context.
56 *
57 * <p>This session is created when the activity starts and finished when it stops; clients can use
58 * it to create children activities.
59 *
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080060 * @hide
61 */
Felipe Leme87a9dc92018-12-18 14:28:07 -080062public final class MainContentCaptureSession extends ContentCaptureSession {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080063
Felipe Lemeaf1a0e72019-01-03 11:07:25 -080064 private static final String TAG = MainContentCaptureSession.class.getSimpleName();
65
Felipe Leme01297692019-01-29 18:16:23 -080066 private static final boolean FORCE_FLUSH = true;
67
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080068 /**
69 * Handler message used to flush the buffer.
70 */
71 private static final int MSG_FLUSH = 1;
72
73 /**
74 * Maximum number of events that are buffered before sent to the app.
75 */
76 // TODO(b/121044064): use settings
77 private static final int MAX_BUFFER_SIZE = 100;
78
79 /**
80 * Frequency the buffer is flushed if stale.
81 */
82 // TODO(b/121044064): use settings
83 private static final int FLUSHING_FREQUENCY_MS = 5_000;
84
85 /**
86 * Name of the {@link IResultReceiver} extra used to pass the binder interface to the service.
87 * @hide
88 */
89 public static final String EXTRA_BINDER = "binder";
90
91 @NonNull
Felipe Leme609991d2019-01-30 16:27:24 -080092 private final AtomicBoolean mDisabled = new AtomicBoolean(false);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080093
94 @NonNull
95 private final Context mContext;
96
97 @NonNull
Felipe Leme609991d2019-01-30 16:27:24 -080098 private final ContentCaptureManager mManager;
99
100 @NonNull
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800101 private final Handler mHandler;
102
103 /**
104 * Interface to the system_server binder object - it's only used to start the session (and
105 * notify when the session is finished).
106 */
Felipe Leme609991d2019-01-30 16:27:24 -0800107 @Nullable // TODO(b/122959591): shoul never be null, we should make main session null instead
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800108 private final IContentCaptureManager mSystemServerInterface;
109
110 /**
111 * Direct interface to the service binder object - it's used to send the events, including the
112 * last ones (when the session is finished)
113 */
114 @Nullable
115 private IContentCaptureDirectManager mDirectServiceInterface;
116 @Nullable
117 private DeathRecipient mDirectServiceVulture;
118
Felipe Leme35ea7632019-01-29 16:13:30 -0800119 private int mState = UNKNOWN_STATE;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800120
121 @Nullable
122 private IBinder mApplicationToken;
123
124 @Nullable
125 private ComponentName mComponentName;
126
127 /**
128 * List of events held to be sent as a batch.
129 */
130 @Nullable
131 private ArrayList<ContentCaptureEvent> mEvents;
132
133 // Used just for debugging purposes (on dump)
134 private long mNextFlush;
135
Felipe Leme1af85ea2019-01-16 13:23:40 -0800136 // TODO(b/121044064): use settings to set size
137 private final LocalLog mFlushHistory = new LocalLog(10);
138
Felipe Leme87a9dc92018-12-18 14:28:07 -0800139 /** @hide */
Felipe Leme609991d2019-01-30 16:27:24 -0800140 protected MainContentCaptureSession(@NonNull Context context,
141 @NonNull ContentCaptureManager manager, @NonNull Handler handler,
142 @Nullable IContentCaptureManager systemServerInterface) {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800143 mContext = context;
Felipe Leme609991d2019-01-30 16:27:24 -0800144 mManager = manager;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800145 mHandler = handler;
146 mSystemServerInterface = systemServerInterface;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800147 }
148
Felipe Leme87a9dc92018-12-18 14:28:07 -0800149 @Override
Felipe Leme4bc0f6b2019-01-03 19:01:07 -0800150 MainContentCaptureSession getMainCaptureSession() {
151 return this;
152 }
153
154 @Override
Felipe Leme87a9dc92018-12-18 14:28:07 -0800155 ContentCaptureSession newChild(@NonNull ContentCaptureContext clientContext) {
156 final ContentCaptureSession child = new ChildContentCaptureSession(this, clientContext);
157 notifyChildSessionStarted(mId, child.mId, clientContext);
158 return child;
159 }
160
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800161 /**
162 * Starts this session.
163 *
164 * @hide
165 */
Felipe Leme3fe6e922019-02-04 17:52:27 -0800166 @UiThread
167 void start(@NonNull IBinder token, @NonNull ComponentName component,
Adam He328c0e32019-01-03 15:19:22 -0800168 int flags) {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800169 if (!isContentCaptureEnabled()) return;
170
171 if (VERBOSE) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800172 Log.v(TAG, "start(): token=" + token + ", comp="
173 + ComponentName.flattenToShortString(component));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800174 }
175
Felipe Leme3fe6e922019-02-04 17:52:27 -0800176 if (hasStarted()) {
Felipe Lemed65692c2019-01-16 12:10:50 -0800177 // TODO(b/122959591): make sure this is expected (and when), or use Log.w
178 if (DEBUG) {
179 Log.d(TAG, "ignoring handleStartSession(" + token + "/"
Felipe Leme3fe6e922019-02-04 17:52:27 -0800180 + ComponentName.flattenToShortString(component) + " while on state "
Felipe Lemed65692c2019-01-16 12:10:50 -0800181 + getStateAsString(mState));
182 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800183 return;
184 }
185 mState = STATE_WAITING_FOR_SERVER;
186 mApplicationToken = token;
Felipe Leme3fe6e922019-02-04 17:52:27 -0800187 mComponentName = component;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800188
189 if (VERBOSE) {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800190 Log.v(TAG, "handleStartSession(): token=" + token + ", act="
Felipe Lemed65692c2019-01-16 12:10:50 -0800191 + getDebugState() + ", id=" + mId);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800192 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800193
194 try {
Adam He6884fed2019-01-07 13:18:32 -0800195 if (mSystemServerInterface == null) return;
196
Felipe Leme3fe6e922019-02-04 17:52:27 -0800197 mSystemServerInterface.startSession(mApplicationToken, component, mId, flags,
Felipe Lemef2aa0d22019-01-28 10:38:46 -0800198 new IResultReceiver.Stub() {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800199 @Override
200 public void send(int resultCode, Bundle resultData) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800201 final IBinder binder;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800202 if (resultData != null) {
203 binder = resultData.getBinder(EXTRA_BINDER);
204 if (binder == null) {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800205 Log.wtf(TAG, "No " + EXTRA_BINDER + " extra result");
Felipe Leme3fe6e922019-02-04 17:52:27 -0800206 mHandler.post(() -> resetSession(
207 STATE_DISABLED | STATE_INTERNAL_ERROR));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800208 return;
209 }
Felipe Leme3fe6e922019-02-04 17:52:27 -0800210 } else {
211 binder = null;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800212 }
Felipe Leme3fe6e922019-02-04 17:52:27 -0800213 mHandler.post(() -> onSessionStarted(resultCode, binder));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800214 }
215 });
216 } catch (RemoteException e) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800217 Log.w(TAG, "Error starting session for " + component.flattenToShortString() + ": " + e);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800218 }
219 }
220
Felipe Leme3fe6e922019-02-04 17:52:27 -0800221 @Override
222 void onDestroy() {
223 mHandler.removeMessages(MSG_FLUSH);
224 mHandler.post(() -> destroySession());
225 }
226
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800227 /**
228 * Callback from {@code system_server} after call to
Felipe Leme609991d2019-01-30 16:27:24 -0800229 * {@link IContentCaptureManager#startSession(IBinder, ComponentName, String, int,
230 * IResultReceiver)}
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800231 *
232 * @param resultCode session state
233 * @param binder handle to {@code IContentCaptureDirectManager}
234 */
Felipe Leme3fe6e922019-02-04 17:52:27 -0800235 @UiThread
236 private void onSessionStarted(int resultCode, @Nullable IBinder binder) {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800237 if (binder != null) {
238 mDirectServiceInterface = IContentCaptureDirectManager.Stub.asInterface(binder);
239 mDirectServiceVulture = () -> {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800240 Log.w(TAG, "Destroying session " + mId + " because service died");
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800241 destroy();
242 };
243 try {
244 binder.linkToDeath(mDirectServiceVulture, 0);
245 } catch (RemoteException e) {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800246 Log.w(TAG, "Failed to link to death on " + binder + ": " + e);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800247 }
248 }
Adam He328c0e32019-01-03 15:19:22 -0800249
Felipe Lemed65692c2019-01-16 12:10:50 -0800250 if ((resultCode & STATE_DISABLED) != 0) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800251 resetSession(resultCode);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800252 } else {
Felipe Lemed65692c2019-01-16 12:10:50 -0800253 mState = resultCode;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800254 mDisabled.set(false);
255 }
256 if (VERBOSE) {
Felipe Lemed65692c2019-01-16 12:10:50 -0800257 Log.v(TAG, "handleSessionStarted() result: id=" + mId + " resultCode=" + resultCode
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800258 + ", state=" + getStateAsString(mState) + ", disabled=" + mDisabled.get()
Felipe Lemee127c9a2019-01-04 14:56:38 -0800259 + ", binder=" + binder + ", events=" + (mEvents == null ? 0 : mEvents.size()));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800260 }
261 }
262
Felipe Leme3fe6e922019-02-04 17:52:27 -0800263 @UiThread
264 private void sendEvent(@NonNull ContentCaptureEvent event) {
265 sendEvent(event, /* forceFlush= */ false);
Felipe Leme01297692019-01-29 18:16:23 -0800266 }
267
Felipe Leme3fe6e922019-02-04 17:52:27 -0800268 @UiThread
269 private void sendEvent(@NonNull ContentCaptureEvent event, boolean forceFlush) {
Felipe Leme1af85ea2019-01-16 13:23:40 -0800270 final int eventType = event.getType();
Felipe Lemebe002d82019-01-23 10:22:32 -0800271 if (VERBOSE) Log.v(TAG, "handleSendEvent(" + getDebugState() + "): " + event);
Felipe Leme3fe6e922019-02-04 17:52:27 -0800272 if (!hasStarted() && eventType != ContentCaptureEvent.TYPE_SESSION_STARTED) {
Felipe Lemed65692c2019-01-16 12:10:50 -0800273 // TODO(b/120494182): comment when this could happen (dialogs?)
274 Log.v(TAG, "handleSendEvent(" + getDebugState() + ", "
Felipe Leme1af85ea2019-01-16 13:23:40 -0800275 + ContentCaptureEvent.getTypeAsString(eventType)
Felipe Lemed65692c2019-01-16 12:10:50 -0800276 + "): session not started yet");
277 return;
278 }
Felipe Lemebe002d82019-01-23 10:22:32 -0800279 if (mDisabled.get()) {
280 // This happens when the event was queued in the handler before the sesison was ready,
281 // then handleSessionStarted() returned and set it as disabled - we need to drop it,
282 // otherwise it will keep triggering handleScheduleFlush()
283 if (VERBOSE) Log.v(TAG, "handleSendEvent(): ignoring when disabled");
284 return;
285 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800286 if (mEvents == null) {
287 if (VERBOSE) {
Felipe Lemebe002d82019-01-23 10:22:32 -0800288 Log.v(TAG, "handleSendEvent(): creating buffer for " + MAX_BUFFER_SIZE + " events");
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800289 }
290 mEvents = new ArrayList<>(MAX_BUFFER_SIZE);
291 }
Adam Heac132652019-01-02 14:40:15 -0800292
Felipe Leme48f363c2019-01-17 10:53:46 -0800293 // Some type of events can be merged together
294 boolean addEvent = true;
295
Felipe Leme1af85ea2019-01-16 13:23:40 -0800296 if (!mEvents.isEmpty() && eventType == TYPE_VIEW_TEXT_CHANGED) {
Adam Heac132652019-01-02 14:40:15 -0800297 final ContentCaptureEvent lastEvent = mEvents.get(mEvents.size() - 1);
298
299 // TODO(b/121045053): check if flags match
300 if (lastEvent.getType() == TYPE_VIEW_TEXT_CHANGED
301 && lastEvent.getId().equals(event.getId())) {
302 if (VERBOSE) {
Felipe Lemebe002d82019-01-23 10:22:32 -0800303 Log.v(TAG, "Buffering VIEW_TEXT_CHANGED event, updated text="
304 + getSanitizedString(event.getText()));
Adam Heac132652019-01-02 14:40:15 -0800305 }
Felipe Lemec8875e72019-02-08 09:45:34 -0800306 // TODO(b/124107816): should call lastEvent.merge(event) instead
Adam Heac132652019-01-02 14:40:15 -0800307 lastEvent.setText(event.getText());
Felipe Leme48f363c2019-01-17 10:53:46 -0800308 addEvent = false;
Adam Heac132652019-01-02 14:40:15 -0800309 }
Felipe Leme48f363c2019-01-17 10:53:46 -0800310 }
311
312 if (!mEvents.isEmpty() && eventType == TYPE_VIEW_DISAPPEARED) {
313 final ContentCaptureEvent lastEvent = mEvents.get(mEvents.size() - 1);
314 if (lastEvent.getType() == TYPE_VIEW_DISAPPEARED
315 && event.getSessionId().equals(lastEvent.getSessionId())) {
316 if (VERBOSE) {
317 Log.v(TAG, "Buffering TYPE_VIEW_DISAPPEARED events for session "
318 + lastEvent.getSessionId());
319 }
Felipe Lemec8875e72019-02-08 09:45:34 -0800320 mergeViewsDisappearedEvent(lastEvent, event);
Felipe Leme48f363c2019-01-17 10:53:46 -0800321 addEvent = false;
322 }
323 }
324
325 if (addEvent) {
Adam Heac132652019-01-02 14:40:15 -0800326 mEvents.add(event);
327 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800328
329 final int numberEvents = mEvents.size();
330
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800331 final boolean bufferEvent = numberEvents < MAX_BUFFER_SIZE;
332
333 if (bufferEvent && !forceFlush) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800334 scheduleFlush(FLUSH_REASON_IDLE_TIMEOUT, /* checkExisting= */ true);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800335 return;
336 }
337
Felipe Lemee127c9a2019-01-04 14:56:38 -0800338 if (mState != STATE_ACTIVE && numberEvents >= MAX_BUFFER_SIZE) {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800339 // Callback from startSession hasn't been called yet - typically happens on system
340 // apps that are started before the system service
Felipe Lemed65692c2019-01-16 12:10:50 -0800341 // TODO(b/122959591): try to ignore session while system is not ready / boot
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800342 // not complete instead. Similarly, the manager service should return right away
343 // when the user does not have a service set
Felipe Lemee127c9a2019-01-04 14:56:38 -0800344 if (DEBUG) {
Felipe Lemed65692c2019-01-16 12:10:50 -0800345 Log.d(TAG, "Closing session for " + getDebugState()
346 + " after " + numberEvents + " delayed events");
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800347 }
Felipe Leme3fe6e922019-02-04 17:52:27 -0800348 resetSession(STATE_DISABLED | STATE_NO_RESPONSE);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800349 // TODO(b/111276913): blacklist activity / use special flag to indicate that
350 // when it's launched again
351 return;
352 }
Felipe Leme1af85ea2019-01-16 13:23:40 -0800353 final int flushReason;
354 switch (eventType) {
355 case ContentCaptureEvent.TYPE_SESSION_STARTED:
356 flushReason = FLUSH_REASON_SESSION_STARTED;
357 break;
358 case ContentCaptureEvent.TYPE_SESSION_FINISHED:
359 flushReason = FLUSH_REASON_SESSION_FINISHED;
360 break;
361 default:
362 flushReason = FLUSH_REASON_FULL;
363 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800364
Felipe Leme3fe6e922019-02-04 17:52:27 -0800365 flush(flushReason);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800366 }
367
Felipe Lemec8875e72019-02-08 09:45:34 -0800368 // TODO(b/124107816): should be ContentCaptureEvent Event.merge(event) instead (which would
369 // replace the addAutofillId() method - we would also need unit tests on ContentCaptureEventTest
370 // to check these scenarios)
371 private void mergeViewsDisappearedEvent(@NonNull ContentCaptureEvent lastEvent,
372 @NonNull ContentCaptureEvent event) {
373 final List<AutofillId> ids = event.getIds();
374 final AutofillId id = event.getId();
375 if (ids != null) {
376 if (id != null) {
377 Log.w(TAG, "got TYPE_VIEW_DISAPPEARED event with both id and ids: " + event);
378 }
379 for (int i = 0; i < ids.size(); i++) {
380 lastEvent.addAutofillId(ids.get(i));
381 }
382 return;
383 }
384 if (id != null) {
385 lastEvent.addAutofillId(id);
386 return;
387 }
388 throw new IllegalArgumentException(
389 "got TYPE_VIEW_DISAPPEARED event with neither id or ids: " + event);
390 }
391
Felipe Leme3fe6e922019-02-04 17:52:27 -0800392 @UiThread
393 private boolean hasStarted() {
Felipe Leme35ea7632019-01-29 16:13:30 -0800394 return mState != UNKNOWN_STATE;
Felipe Lemed65692c2019-01-16 12:10:50 -0800395 }
396
Felipe Leme3fe6e922019-02-04 17:52:27 -0800397 @UiThread
398 private void scheduleFlush(@FlushReason int reason, boolean checkExisting) {
Felipe Lemebe002d82019-01-23 10:22:32 -0800399 if (VERBOSE) {
400 Log.v(TAG, "handleScheduleFlush(" + getDebugState(reason)
401 + ", checkExisting=" + checkExisting);
402 }
Felipe Leme3fe6e922019-02-04 17:52:27 -0800403 if (!hasStarted()) {
Felipe Lemebe002d82019-01-23 10:22:32 -0800404 if (VERBOSE) Log.v(TAG, "handleScheduleFlush(): session not started yet");
405 return;
406 }
407
408 if (mDisabled.get()) {
409 // Should not be called on this state, as handleSendEvent checks.
410 // But we rather add one if check and log than re-schedule and keep the session alive...
411 Log.e(TAG, "handleScheduleFlush(" + getDebugState(reason) + "): should not be called "
412 + "when disabled. events=" + (mEvents == null ? null : mEvents.size()));
Felipe Lemed65692c2019-01-16 12:10:50 -0800413 return;
414 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800415 if (checkExisting && mHandler.hasMessages(MSG_FLUSH)) {
416 // "Renew" the flush message by removing the previous one
417 mHandler.removeMessages(MSG_FLUSH);
418 }
Felipe Leme1af85ea2019-01-16 13:23:40 -0800419 mNextFlush = System.currentTimeMillis() + FLUSHING_FREQUENCY_MS;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800420 if (VERBOSE) {
Felipe Lemebe002d82019-01-23 10:22:32 -0800421 Log.v(TAG, "handleScheduleFlush(): scheduled to flush in "
Felipe Leme1af85ea2019-01-16 13:23:40 -0800422 + FLUSHING_FREQUENCY_MS + "ms: " + TimeUtils.logTimeOfDay(mNextFlush));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800423 }
Felipe Leme3fe6e922019-02-04 17:52:27 -0800424 // Post using a Runnable directly to trim a few μs from PooledLambda.obtainMessage()
425 mHandler.postDelayed(() -> flushIfNeeded(reason), MSG_FLUSH, FLUSHING_FREQUENCY_MS);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800426 }
427
Felipe Leme3fe6e922019-02-04 17:52:27 -0800428 @UiThread
429 private void flushIfNeeded(@FlushReason int reason) {
Felipe Leme3d570a42019-01-28 13:04:34 -0800430 if (mEvents == null || mEvents.isEmpty()) {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800431 if (VERBOSE) Log.v(TAG, "Nothing to flush");
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800432 return;
433 }
Felipe Leme3fe6e922019-02-04 17:52:27 -0800434 flush(reason);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800435 }
436
Felipe Leme3fe6e922019-02-04 17:52:27 -0800437 @Override
438 @UiThread
439 void flush(@FlushReason int reason) {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800440 if (mEvents == null) return;
441
Felipe Lemebe002d82019-01-23 10:22:32 -0800442 if (mDisabled.get()) {
443 Log.e(TAG, "handleForceFlush(" + getDebugState(reason) + "): should not be when "
444 + "disabled");
445 return;
446 }
447
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800448 if (mDirectServiceInterface == null) {
Felipe Lemee127c9a2019-01-04 14:56:38 -0800449 if (VERBOSE) {
Felipe Lemebe002d82019-01-23 10:22:32 -0800450 Log.v(TAG, "handleForceFlush(" + getDebugState(reason) + "): hold your horses, "
451 + "client not ready: " + mEvents);
Felipe Lemee127c9a2019-01-04 14:56:38 -0800452 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800453 if (!mHandler.hasMessages(MSG_FLUSH)) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800454 scheduleFlush(reason, /* checkExisting= */ false);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800455 }
456 return;
457 }
458
459 final int numberEvents = mEvents.size();
Felipe Leme1af85ea2019-01-16 13:23:40 -0800460 final String reasonString = getflushReasonAsString(reason);
461 if (DEBUG) {
Felipe Lemebe002d82019-01-23 10:22:32 -0800462 Log.d(TAG, "Flushing " + numberEvents + " event(s) for " + getDebugState(reason));
Felipe Leme1af85ea2019-01-16 13:23:40 -0800463 }
464 // Logs reason, size, max size, idle timeout
465 final String logRecord = "r=" + reasonString + " s=" + numberEvents
466 + " m=" + MAX_BUFFER_SIZE + " i=" + FLUSHING_FREQUENCY_MS;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800467 try {
Felipe Leme1af85ea2019-01-16 13:23:40 -0800468 mFlushHistory.log(logRecord);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800469 mHandler.removeMessages(MSG_FLUSH);
470
Felipe Leme3fe6e922019-02-04 17:52:27 -0800471 final ParceledListSlice<ContentCaptureEvent> events = clearEvents();
Felipe Lemefc24bea2018-12-18 13:19:01 -0800472 mDirectServiceInterface.sendEvents(events);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800473 } catch (RemoteException e) {
Felipe Lemed65692c2019-01-16 12:10:50 -0800474 Log.w(TAG, "Error sending " + numberEvents + " for " + getDebugState()
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800475 + ": " + e);
476 }
477 }
478
479 /**
480 * Resets the buffer and return a {@link ParceledListSlice} with the previous events.
481 */
482 @NonNull
Felipe Leme3fe6e922019-02-04 17:52:27 -0800483 @UiThread
484 private ParceledListSlice<ContentCaptureEvent> clearEvents() {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800485 // NOTE: we must save a reference to the current mEvents and then set it to to null,
486 // otherwise clearing it would clear it in the receiving side if the service is also local.
487 final List<ContentCaptureEvent> events = mEvents == null
488 ? Collections.emptyList()
489 : mEvents;
490 mEvents = null;
491 return new ParceledListSlice<>(events);
492 }
493
Felipe Leme3fe6e922019-02-04 17:52:27 -0800494 @UiThread
495 private void destroySession() {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800496 if (DEBUG) {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800497 Log.d(TAG, "Destroying session (ctx=" + mContext + ", id=" + mId + ") with "
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800498 + (mEvents == null ? 0 : mEvents.size()) + " event(s) for "
Felipe Lemed65692c2019-01-16 12:10:50 -0800499 + getDebugState());
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800500 }
501
502 try {
Adam He6884fed2019-01-07 13:18:32 -0800503 if (mSystemServerInterface == null) return;
504
Felipe Lemef2aa0d22019-01-28 10:38:46 -0800505 mSystemServerInterface.finishSession(mId);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800506 } catch (RemoteException e) {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800507 Log.e(TAG, "Error destroying system-service session " + mId + " for "
Felipe Lemed65692c2019-01-16 12:10:50 -0800508 + getDebugState() + ": " + e);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800509 }
510 }
511
Felipe Leme4bc0f6b2019-01-03 19:01:07 -0800512 // TODO(b/122454205): once we support multiple sessions, we might need to move some of these
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800513 // clearings out.
Felipe Leme3fe6e922019-02-04 17:52:27 -0800514 @UiThread
515 private void resetSession(int newState) {
Felipe Lemed65692c2019-01-16 12:10:50 -0800516 if (VERBOSE) {
517 Log.v(TAG, "handleResetSession(" + getActivityName() + "): from "
518 + getStateAsString(mState) + " to " + getStateAsString(newState));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800519 }
Felipe Lemed65692c2019-01-16 12:10:50 -0800520 mState = newState;
521 mDisabled.set((newState & STATE_DISABLED) != 0);
Felipe Leme4bc0f6b2019-01-03 19:01:07 -0800522 // TODO(b/122454205): must reset children (which currently is owned by superclass)
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800523 mApplicationToken = null;
524 mComponentName = null;
525 mEvents = null;
526 if (mDirectServiceInterface != null) {
527 mDirectServiceInterface.asBinder().unlinkToDeath(mDirectServiceVulture, 0);
528 }
529 mDirectServiceInterface = null;
530 mHandler.removeMessages(MSG_FLUSH);
531 }
532
533 @Override
534 void internalNotifyViewAppeared(@NonNull ViewStructureImpl node) {
Felipe Leme87a9dc92018-12-18 14:28:07 -0800535 notifyViewAppeared(mId, node);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800536 }
537
538 @Override
539 void internalNotifyViewDisappeared(@NonNull AutofillId id) {
Felipe Leme87a9dc92018-12-18 14:28:07 -0800540 notifyViewDisappeared(mId, id);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800541 }
542
543 @Override
Felipe Leme21e8dcb2019-01-18 09:09:45 -0800544 void internalNotifyViewTextChanged(@NonNull AutofillId id, @Nullable CharSequence text) {
545 notifyViewTextChanged(mId, id, text);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800546 }
547
548 @Override
Felipe Leme01297692019-01-29 18:16:23 -0800549 public void internalNotifyViewHierarchyEvent(boolean started) {
550 notifyInitialViewHierarchyEvent(mId, started);
551 }
552
553 @Override
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800554 boolean isContentCaptureEnabled() {
Felipe Leme609991d2019-01-30 16:27:24 -0800555 return super.isContentCaptureEnabled() && mManager.isContentCaptureEnabled();
556 }
557
558 // Called by ContentCaptureManager.isContentCaptureEnabled
559 boolean isDisabled() {
560 return mDisabled.get();
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800561 }
562
Felipe Leme4bc0f6b2019-01-03 19:01:07 -0800563 // TODO(b/122454205): refactor "notifyXXXX" methods below to a common "Buffer" object that is
Felipe Leme87a9dc92018-12-18 14:28:07 -0800564 // shared between ActivityContentCaptureSession and ChildContentCaptureSession objects. Such
565 // change should also get get rid of the "internalNotifyXXXX" methods above
566 void notifyChildSessionStarted(@NonNull String parentSessionId,
567 @NonNull String childSessionId, @NonNull ContentCaptureContext clientContext) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800568 sendEvent(new ContentCaptureEvent(childSessionId, TYPE_SESSION_STARTED)
569 .setParentSessionId(parentSessionId).setClientContext(clientContext),
570 FORCE_FLUSH);
Felipe Leme87a9dc92018-12-18 14:28:07 -0800571 }
572
573 void notifyChildSessionFinished(@NonNull String parentSessionId,
574 @NonNull String childSessionId) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800575 sendEvent(new ContentCaptureEvent(childSessionId, TYPE_SESSION_FINISHED)
576 .setParentSessionId(parentSessionId), FORCE_FLUSH);
Felipe Leme87a9dc92018-12-18 14:28:07 -0800577 }
578
579 void notifyViewAppeared(@NonNull String sessionId, @NonNull ViewStructureImpl node) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800580 sendEvent(new ContentCaptureEvent(sessionId, TYPE_VIEW_APPEARED)
581 .setViewNode(node.mNode));
Felipe Leme87a9dc92018-12-18 14:28:07 -0800582 }
583
584 void notifyViewDisappeared(@NonNull String sessionId, @NonNull AutofillId id) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800585 sendEvent(
586 new ContentCaptureEvent(sessionId, TYPE_VIEW_DISAPPEARED).setAutofillId(id));
Felipe Leme01297692019-01-29 18:16:23 -0800587 }
588
589 /** @hide */
590 public void notifyViewsDisappeared(@NonNull String sessionId,
591 @NonNull ArrayList<AutofillId> ids) {
592 final ContentCaptureEvent event = new ContentCaptureEvent(sessionId, TYPE_VIEW_DISAPPEARED);
593 if (ids.size() == 1) {
594 event.setAutofillId(ids.get(0));
595 } else {
596 event.setAutofillIds(ids);
597 }
Felipe Leme3fe6e922019-02-04 17:52:27 -0800598 sendEvent(event);
Felipe Leme87a9dc92018-12-18 14:28:07 -0800599 }
600
601 void notifyViewTextChanged(@NonNull String sessionId, @NonNull AutofillId id,
Felipe Leme21e8dcb2019-01-18 09:09:45 -0800602 @Nullable CharSequence text) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800603 sendEvent(new ContentCaptureEvent(sessionId, TYPE_VIEW_TEXT_CHANGED).setAutofillId(id)
604 .setText(text));
Felipe Leme01297692019-01-29 18:16:23 -0800605 }
606
607 void notifyInitialViewHierarchyEvent(@NonNull String sessionId, boolean started) {
608 if (started) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800609 sendEvent(new ContentCaptureEvent(sessionId, TYPE_INITIAL_VIEW_TREE_APPEARING));
Felipe Leme01297692019-01-29 18:16:23 -0800610 } else {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800611 sendEvent(new ContentCaptureEvent(sessionId, TYPE_INITIAL_VIEW_TREE_APPEARED),
612 FORCE_FLUSH);
Felipe Leme01297692019-01-29 18:16:23 -0800613 }
Felipe Leme87a9dc92018-12-18 14:28:07 -0800614 }
615
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800616 @Override
617 void dump(@NonNull String prefix, @NonNull PrintWriter pw) {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800618 pw.print(prefix); pw.print("mContext: "); pw.println(mContext);
619 pw.print(prefix); pw.print("user: "); pw.println(mContext.getUserId());
620 if (mSystemServerInterface != null) {
621 pw.print(prefix); pw.print("mSystemServerInterface: ");
622 pw.println(mSystemServerInterface);
623 }
624 if (mDirectServiceInterface != null) {
625 pw.print(prefix); pw.print("mDirectServiceInterface: ");
626 pw.println(mDirectServiceInterface);
627 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800628 pw.print(prefix); pw.print("mDisabled: "); pw.println(mDisabled.get());
629 pw.print(prefix); pw.print("isEnabled(): "); pw.println(isContentCaptureEnabled());
Felipe Leme01b87492019-01-15 13:26:52 -0800630 pw.print(prefix); pw.print("state: "); pw.println(getStateAsString(mState));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800631 if (mApplicationToken != null) {
632 pw.print(prefix); pw.print("app token: "); pw.println(mApplicationToken);
633 }
634 if (mComponentName != null) {
635 pw.print(prefix); pw.print("component name: ");
636 pw.println(mComponentName.flattenToShortString());
637 }
638 if (mEvents != null && !mEvents.isEmpty()) {
639 final int numberEvents = mEvents.size();
640 pw.print(prefix); pw.print("buffered events: "); pw.print(numberEvents);
641 pw.print('/'); pw.println(MAX_BUFFER_SIZE);
642 if (VERBOSE && numberEvents > 0) {
643 final String prefix3 = prefix + " ";
644 for (int i = 0; i < numberEvents; i++) {
645 final ContentCaptureEvent event = mEvents.get(i);
646 pw.print(prefix3); pw.print(i); pw.print(": "); event.dump(pw);
647 pw.println();
648 }
649 }
650 pw.print(prefix); pw.print("flush frequency: "); pw.println(FLUSHING_FREQUENCY_MS);
651 pw.print(prefix); pw.print("next flush: ");
Felipe Leme1af85ea2019-01-16 13:23:40 -0800652 TimeUtils.formatDuration(mNextFlush - System.currentTimeMillis(), pw);
653 pw.print(" ("); pw.print(TimeUtils.logTimeOfDay(mNextFlush)); pw.println(")");
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800654 }
Felipe Leme1af85ea2019-01-16 13:23:40 -0800655 pw.print(prefix); pw.println("flush history:");
656 mFlushHistory.reverseDump(/* fd= */ null, pw, /* args= */ null); pw.println();
657
Felipe Leme87a9dc92018-12-18 14:28:07 -0800658 super.dump(prefix, pw);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800659 }
660
661 /**
662 * Gets a string that can be used to identify the activity on logging statements.
663 */
Felipe Lemed65692c2019-01-16 12:10:50 -0800664 private String getActivityName() {
665 return mComponentName == null
666 ? "pkg:" + mContext.getPackageName()
667 : "act:" + mComponentName.flattenToShortString();
668 }
669
Felipe Lemebe002d82019-01-23 10:22:32 -0800670 @NonNull
Felipe Lemed65692c2019-01-16 12:10:50 -0800671 private String getDebugState() {
Felipe Lemebe002d82019-01-23 10:22:32 -0800672 return getActivityName() + " [state=" + getStateAsString(mState) + ", disabled="
673 + mDisabled.get() + "]";
674 }
675
676 @NonNull
677 private String getDebugState(@FlushReason int reason) {
678 return getDebugState() + ", reason=" + getflushReasonAsString(reason);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800679 }
680}