blob: 14b2b28deaeb1d036ed41eee38bf202f72a9956d [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 Leme4eecbe62019-02-11 17:50:17 -080018import static android.view.contentcapture.ContentCaptureEvent.TYPE_CONTEXT_UPDATED;
Felipe Leme01297692019-01-29 18:16:23 -080019import static android.view.contentcapture.ContentCaptureEvent.TYPE_INITIAL_VIEW_TREE_APPEARED;
20import static android.view.contentcapture.ContentCaptureEvent.TYPE_INITIAL_VIEW_TREE_APPEARING;
Felipe Leme87a9dc92018-12-18 14:28:07 -080021import static android.view.contentcapture.ContentCaptureEvent.TYPE_SESSION_FINISHED;
22import static android.view.contentcapture.ContentCaptureEvent.TYPE_SESSION_STARTED;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080023import static android.view.contentcapture.ContentCaptureEvent.TYPE_VIEW_APPEARED;
24import static android.view.contentcapture.ContentCaptureEvent.TYPE_VIEW_DISAPPEARED;
25import static android.view.contentcapture.ContentCaptureEvent.TYPE_VIEW_TEXT_CHANGED;
Felipe Lemebe002d82019-01-23 10:22:32 -080026import static android.view.contentcapture.ContentCaptureHelper.getSanitizedString;
Felipe Lemed32d8f6f2019-02-15 10:25:33 -080027import static android.view.contentcapture.ContentCaptureHelper.sDebug;
28import static android.view.contentcapture.ContentCaptureHelper.sVerbose;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080029
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080030import android.annotation.NonNull;
31import android.annotation.Nullable;
Felipe Leme3fe6e922019-02-04 17:52:27 -080032import android.annotation.UiThread;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080033import android.content.ComponentName;
34import android.content.Context;
35import android.content.pm.ParceledListSlice;
36import android.os.Bundle;
37import android.os.Handler;
38import android.os.IBinder;
39import android.os.IBinder.DeathRecipient;
40import android.os.RemoteException;
Felipe Leme1af85ea2019-01-16 13:23:40 -080041import android.util.LocalLog;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080042import android.util.Log;
43import android.util.TimeUtils;
44import android.view.autofill.AutofillId;
45import android.view.contentcapture.ViewNode.ViewStructureImpl;
46
47import com.android.internal.os.IResultReceiver;
48
49import java.io.PrintWriter;
50import java.util.ArrayList;
51import java.util.Collections;
52import java.util.List;
53import java.util.concurrent.atomic.AtomicBoolean;
54
55/**
56 * Main session associated with a context.
57 *
58 * <p>This session is created when the activity starts and finished when it stops; clients can use
59 * it to create children activities.
60 *
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080061 * @hide
62 */
Felipe Leme87a9dc92018-12-18 14:28:07 -080063public final class MainContentCaptureSession extends ContentCaptureSession {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080064
Felipe Lemeaf1a0e72019-01-03 11:07:25 -080065 private static final String TAG = MainContentCaptureSession.class.getSimpleName();
66
Felipe Lemed32d8f6f2019-02-15 10:25:33 -080067 // For readability purposes...
Felipe Leme01297692019-01-29 18:16:23 -080068 private static final boolean FORCE_FLUSH = true;
69
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080070 /**
71 * Handler message used to flush the buffer.
72 */
73 private static final int MSG_FLUSH = 1;
74
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080075 /**
76 * Name of the {@link IResultReceiver} extra used to pass the binder interface to the service.
77 * @hide
78 */
79 public static final String EXTRA_BINDER = "binder";
80
81 @NonNull
Felipe Leme609991d2019-01-30 16:27:24 -080082 private final AtomicBoolean mDisabled = new AtomicBoolean(false);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080083
84 @NonNull
85 private final Context mContext;
86
87 @NonNull
Felipe Leme609991d2019-01-30 16:27:24 -080088 private final ContentCaptureManager mManager;
89
90 @NonNull
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080091 private final Handler mHandler;
92
93 /**
94 * Interface to the system_server binder object - it's only used to start the session (and
95 * notify when the session is finished).
96 */
Felipe Lemed49d52c2019-02-15 09:48:20 -080097 @NonNull
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080098 private final IContentCaptureManager mSystemServerInterface;
99
100 /**
101 * Direct interface to the service binder object - it's used to send the events, including the
102 * last ones (when the session is finished)
103 */
Felipe Lemed49d52c2019-02-15 09:48:20 -0800104 @NonNull
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800105 private IContentCaptureDirectManager mDirectServiceInterface;
106 @Nullable
107 private DeathRecipient mDirectServiceVulture;
108
Felipe Leme35ea7632019-01-29 16:13:30 -0800109 private int mState = UNKNOWN_STATE;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800110
111 @Nullable
112 private IBinder mApplicationToken;
113
114 @Nullable
115 private ComponentName mComponentName;
116
117 /**
118 * List of events held to be sent as a batch.
119 */
120 @Nullable
121 private ArrayList<ContentCaptureEvent> mEvents;
122
123 // Used just for debugging purposes (on dump)
124 private long mNextFlush;
125
Felipe Lemed32d8f6f2019-02-15 10:25:33 -0800126 @Nullable
127 private final LocalLog mFlushHistory;
Felipe Leme1af85ea2019-01-16 13:23:40 -0800128
Felipe Leme609991d2019-01-30 16:27:24 -0800129 protected MainContentCaptureSession(@NonNull Context context,
130 @NonNull ContentCaptureManager manager, @NonNull Handler handler,
Felipe Lemed49d52c2019-02-15 09:48:20 -0800131 @NonNull IContentCaptureManager systemServerInterface) {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800132 mContext = context;
Felipe Leme609991d2019-01-30 16:27:24 -0800133 mManager = manager;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800134 mHandler = handler;
135 mSystemServerInterface = systemServerInterface;
Felipe Lemed32d8f6f2019-02-15 10:25:33 -0800136
Felipe Leme326f15a2019-02-19 09:42:24 -0800137 final int logHistorySize = mManager.mOptions.logHistorySize;
Felipe Lemed32d8f6f2019-02-15 10:25:33 -0800138 mFlushHistory = logHistorySize > 0 ? new LocalLog(logHistorySize) : null;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800139 }
140
Felipe Leme87a9dc92018-12-18 14:28:07 -0800141 @Override
Felipe Leme4bc0f6b2019-01-03 19:01:07 -0800142 MainContentCaptureSession getMainCaptureSession() {
143 return this;
144 }
145
146 @Override
Felipe Leme87a9dc92018-12-18 14:28:07 -0800147 ContentCaptureSession newChild(@NonNull ContentCaptureContext clientContext) {
148 final ContentCaptureSession child = new ChildContentCaptureSession(this, clientContext);
149 notifyChildSessionStarted(mId, child.mId, clientContext);
150 return child;
151 }
152
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800153 /**
154 * Starts this session.
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800155 */
Felipe Leme3fe6e922019-02-04 17:52:27 -0800156 @UiThread
157 void start(@NonNull IBinder token, @NonNull ComponentName component,
Adam He328c0e32019-01-03 15:19:22 -0800158 int flags) {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800159 if (!isContentCaptureEnabled()) return;
160
Felipe Lemed32d8f6f2019-02-15 10:25:33 -0800161 if (sVerbose) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800162 Log.v(TAG, "start(): token=" + token + ", comp="
163 + ComponentName.flattenToShortString(component));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800164 }
165
Felipe Leme3fe6e922019-02-04 17:52:27 -0800166 if (hasStarted()) {
Felipe Lemed65692c2019-01-16 12:10:50 -0800167 // TODO(b/122959591): make sure this is expected (and when), or use Log.w
Felipe Lemed32d8f6f2019-02-15 10:25:33 -0800168 if (sDebug) {
Felipe Lemed65692c2019-01-16 12:10:50 -0800169 Log.d(TAG, "ignoring handleStartSession(" + token + "/"
Felipe Leme3fe6e922019-02-04 17:52:27 -0800170 + ComponentName.flattenToShortString(component) + " while on state "
Felipe Lemed65692c2019-01-16 12:10:50 -0800171 + getStateAsString(mState));
172 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800173 return;
174 }
175 mState = STATE_WAITING_FOR_SERVER;
176 mApplicationToken = token;
Felipe Leme3fe6e922019-02-04 17:52:27 -0800177 mComponentName = component;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800178
Felipe Lemed32d8f6f2019-02-15 10:25:33 -0800179 if (sVerbose) {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800180 Log.v(TAG, "handleStartSession(): token=" + token + ", act="
Felipe Lemed65692c2019-01-16 12:10:50 -0800181 + getDebugState() + ", id=" + mId);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800182 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800183
184 try {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800185 mSystemServerInterface.startSession(mApplicationToken, component, mId, flags,
Felipe Lemef2aa0d22019-01-28 10:38:46 -0800186 new IResultReceiver.Stub() {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800187 @Override
188 public void send(int resultCode, Bundle resultData) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800189 final IBinder binder;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800190 if (resultData != null) {
191 binder = resultData.getBinder(EXTRA_BINDER);
192 if (binder == null) {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800193 Log.wtf(TAG, "No " + EXTRA_BINDER + " extra result");
Felipe Leme3fe6e922019-02-04 17:52:27 -0800194 mHandler.post(() -> resetSession(
195 STATE_DISABLED | STATE_INTERNAL_ERROR));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800196 return;
197 }
Felipe Leme3fe6e922019-02-04 17:52:27 -0800198 } else {
199 binder = null;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800200 }
Felipe Leme3fe6e922019-02-04 17:52:27 -0800201 mHandler.post(() -> onSessionStarted(resultCode, binder));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800202 }
203 });
204 } catch (RemoteException e) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800205 Log.w(TAG, "Error starting session for " + component.flattenToShortString() + ": " + e);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800206 }
207 }
208
Felipe Leme3fe6e922019-02-04 17:52:27 -0800209 @Override
210 void onDestroy() {
211 mHandler.removeMessages(MSG_FLUSH);
212 mHandler.post(() -> destroySession());
213 }
214
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800215 /**
216 * Callback from {@code system_server} after call to
Felipe Leme609991d2019-01-30 16:27:24 -0800217 * {@link IContentCaptureManager#startSession(IBinder, ComponentName, String, int,
218 * IResultReceiver)}
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800219 *
220 * @param resultCode session state
221 * @param binder handle to {@code IContentCaptureDirectManager}
222 */
Felipe Leme3fe6e922019-02-04 17:52:27 -0800223 @UiThread
224 private void onSessionStarted(int resultCode, @Nullable IBinder binder) {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800225 if (binder != null) {
226 mDirectServiceInterface = IContentCaptureDirectManager.Stub.asInterface(binder);
227 mDirectServiceVulture = () -> {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800228 Log.w(TAG, "Destroying session " + mId + " because service died");
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800229 destroy();
230 };
231 try {
232 binder.linkToDeath(mDirectServiceVulture, 0);
233 } catch (RemoteException e) {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800234 Log.w(TAG, "Failed to link to death on " + binder + ": " + e);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800235 }
236 }
Adam He328c0e32019-01-03 15:19:22 -0800237
Felipe Lemed65692c2019-01-16 12:10:50 -0800238 if ((resultCode & STATE_DISABLED) != 0) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800239 resetSession(resultCode);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800240 } else {
Felipe Lemed65692c2019-01-16 12:10:50 -0800241 mState = resultCode;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800242 mDisabled.set(false);
243 }
Felipe Lemed32d8f6f2019-02-15 10:25:33 -0800244 if (sVerbose) {
Felipe Lemed65692c2019-01-16 12:10:50 -0800245 Log.v(TAG, "handleSessionStarted() result: id=" + mId + " resultCode=" + resultCode
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800246 + ", state=" + getStateAsString(mState) + ", disabled=" + mDisabled.get()
Felipe Lemee127c9a2019-01-04 14:56:38 -0800247 + ", binder=" + binder + ", events=" + (mEvents == null ? 0 : mEvents.size()));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800248 }
249 }
250
Felipe Leme3fe6e922019-02-04 17:52:27 -0800251 @UiThread
252 private void sendEvent(@NonNull ContentCaptureEvent event) {
253 sendEvent(event, /* forceFlush= */ false);
Felipe Leme01297692019-01-29 18:16:23 -0800254 }
255
Felipe Leme3fe6e922019-02-04 17:52:27 -0800256 @UiThread
257 private void sendEvent(@NonNull ContentCaptureEvent event, boolean forceFlush) {
Felipe Leme1af85ea2019-01-16 13:23:40 -0800258 final int eventType = event.getType();
Felipe Lemed32d8f6f2019-02-15 10:25:33 -0800259 if (sVerbose) Log.v(TAG, "handleSendEvent(" + getDebugState() + "): " + event);
Felipe Leme4eecbe62019-02-11 17:50:17 -0800260 if (!hasStarted() && eventType != ContentCaptureEvent.TYPE_SESSION_STARTED
261 && eventType != ContentCaptureEvent.TYPE_CONTEXT_UPDATED) {
Felipe Lemed65692c2019-01-16 12:10:50 -0800262 // TODO(b/120494182): comment when this could happen (dialogs?)
263 Log.v(TAG, "handleSendEvent(" + getDebugState() + ", "
Felipe Leme1af85ea2019-01-16 13:23:40 -0800264 + ContentCaptureEvent.getTypeAsString(eventType)
Felipe Leme4eecbe62019-02-11 17:50:17 -0800265 + "): dropping because session not started yet");
Felipe Lemed65692c2019-01-16 12:10:50 -0800266 return;
267 }
Felipe Lemebe002d82019-01-23 10:22:32 -0800268 if (mDisabled.get()) {
269 // This happens when the event was queued in the handler before the sesison was ready,
270 // then handleSessionStarted() returned and set it as disabled - we need to drop it,
271 // otherwise it will keep triggering handleScheduleFlush()
Felipe Lemed32d8f6f2019-02-15 10:25:33 -0800272 if (sVerbose) Log.v(TAG, "handleSendEvent(): ignoring when disabled");
Felipe Lemebe002d82019-01-23 10:22:32 -0800273 return;
274 }
Felipe Leme326f15a2019-02-19 09:42:24 -0800275 final int maxBufferSize = mManager.mOptions.maxBufferSize;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800276 if (mEvents == null) {
Felipe Lemed32d8f6f2019-02-15 10:25:33 -0800277 if (sVerbose) {
Felipe Leme326f15a2019-02-19 09:42:24 -0800278 Log.v(TAG, "handleSendEvent(): creating buffer for " + maxBufferSize + " events");
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800279 }
Felipe Leme326f15a2019-02-19 09:42:24 -0800280 mEvents = new ArrayList<>(maxBufferSize);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800281 }
Adam Heac132652019-01-02 14:40:15 -0800282
Felipe Leme48f363c2019-01-17 10:53:46 -0800283 // Some type of events can be merged together
284 boolean addEvent = true;
285
Felipe Leme1af85ea2019-01-16 13:23:40 -0800286 if (!mEvents.isEmpty() && eventType == TYPE_VIEW_TEXT_CHANGED) {
Adam Heac132652019-01-02 14:40:15 -0800287 final ContentCaptureEvent lastEvent = mEvents.get(mEvents.size() - 1);
288
289 // TODO(b/121045053): check if flags match
290 if (lastEvent.getType() == TYPE_VIEW_TEXT_CHANGED
291 && lastEvent.getId().equals(event.getId())) {
Felipe Lemed32d8f6f2019-02-15 10:25:33 -0800292 if (sVerbose) {
Felipe Lemebe002d82019-01-23 10:22:32 -0800293 Log.v(TAG, "Buffering VIEW_TEXT_CHANGED event, updated text="
294 + getSanitizedString(event.getText()));
Adam Heac132652019-01-02 14:40:15 -0800295 }
Felipe Lemec8875e72019-02-08 09:45:34 -0800296 // TODO(b/124107816): should call lastEvent.merge(event) instead
Adam Heac132652019-01-02 14:40:15 -0800297 lastEvent.setText(event.getText());
Felipe Leme48f363c2019-01-17 10:53:46 -0800298 addEvent = false;
Adam Heac132652019-01-02 14:40:15 -0800299 }
Felipe Leme48f363c2019-01-17 10:53:46 -0800300 }
301
302 if (!mEvents.isEmpty() && eventType == TYPE_VIEW_DISAPPEARED) {
303 final ContentCaptureEvent lastEvent = mEvents.get(mEvents.size() - 1);
304 if (lastEvent.getType() == TYPE_VIEW_DISAPPEARED
305 && event.getSessionId().equals(lastEvent.getSessionId())) {
Felipe Lemed32d8f6f2019-02-15 10:25:33 -0800306 if (sVerbose) {
Felipe Leme48f363c2019-01-17 10:53:46 -0800307 Log.v(TAG, "Buffering TYPE_VIEW_DISAPPEARED events for session "
308 + lastEvent.getSessionId());
309 }
Felipe Lemec8875e72019-02-08 09:45:34 -0800310 mergeViewsDisappearedEvent(lastEvent, event);
Felipe Leme48f363c2019-01-17 10:53:46 -0800311 addEvent = false;
312 }
313 }
314
315 if (addEvent) {
Adam Heac132652019-01-02 14:40:15 -0800316 mEvents.add(event);
317 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800318
319 final int numberEvents = mEvents.size();
320
Felipe Leme326f15a2019-02-19 09:42:24 -0800321 final boolean bufferEvent = numberEvents < maxBufferSize;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800322
323 if (bufferEvent && !forceFlush) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800324 scheduleFlush(FLUSH_REASON_IDLE_TIMEOUT, /* checkExisting= */ true);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800325 return;
326 }
327
Felipe Leme326f15a2019-02-19 09:42:24 -0800328 if (mState != STATE_ACTIVE && numberEvents >= maxBufferSize) {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800329 // Callback from startSession hasn't been called yet - typically happens on system
330 // apps that are started before the system service
Felipe Lemed65692c2019-01-16 12:10:50 -0800331 // TODO(b/122959591): try to ignore session while system is not ready / boot
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800332 // not complete instead. Similarly, the manager service should return right away
333 // when the user does not have a service set
Felipe Lemed32d8f6f2019-02-15 10:25:33 -0800334 if (sDebug) {
Felipe Lemed65692c2019-01-16 12:10:50 -0800335 Log.d(TAG, "Closing session for " + getDebugState()
336 + " after " + numberEvents + " delayed events");
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800337 }
Felipe Leme3fe6e922019-02-04 17:52:27 -0800338 resetSession(STATE_DISABLED | STATE_NO_RESPONSE);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800339 // TODO(b/111276913): blacklist activity / use special flag to indicate that
340 // when it's launched again
341 return;
342 }
Felipe Leme1af85ea2019-01-16 13:23:40 -0800343 final int flushReason;
344 switch (eventType) {
345 case ContentCaptureEvent.TYPE_SESSION_STARTED:
346 flushReason = FLUSH_REASON_SESSION_STARTED;
347 break;
348 case ContentCaptureEvent.TYPE_SESSION_FINISHED:
349 flushReason = FLUSH_REASON_SESSION_FINISHED;
350 break;
351 default:
352 flushReason = FLUSH_REASON_FULL;
353 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800354
Felipe Leme3fe6e922019-02-04 17:52:27 -0800355 flush(flushReason);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800356 }
357
Felipe Lemec8875e72019-02-08 09:45:34 -0800358 // TODO(b/124107816): should be ContentCaptureEvent Event.merge(event) instead (which would
359 // replace the addAutofillId() method - we would also need unit tests on ContentCaptureEventTest
360 // to check these scenarios)
361 private void mergeViewsDisappearedEvent(@NonNull ContentCaptureEvent lastEvent,
362 @NonNull ContentCaptureEvent event) {
363 final List<AutofillId> ids = event.getIds();
364 final AutofillId id = event.getId();
365 if (ids != null) {
366 if (id != null) {
367 Log.w(TAG, "got TYPE_VIEW_DISAPPEARED event with both id and ids: " + event);
368 }
369 for (int i = 0; i < ids.size(); i++) {
370 lastEvent.addAutofillId(ids.get(i));
371 }
372 return;
373 }
374 if (id != null) {
375 lastEvent.addAutofillId(id);
376 return;
377 }
378 throw new IllegalArgumentException(
379 "got TYPE_VIEW_DISAPPEARED event with neither id or ids: " + event);
380 }
381
Felipe Leme3fe6e922019-02-04 17:52:27 -0800382 @UiThread
383 private boolean hasStarted() {
Felipe Leme35ea7632019-01-29 16:13:30 -0800384 return mState != UNKNOWN_STATE;
Felipe Lemed65692c2019-01-16 12:10:50 -0800385 }
386
Felipe Leme3fe6e922019-02-04 17:52:27 -0800387 @UiThread
388 private void scheduleFlush(@FlushReason int reason, boolean checkExisting) {
Felipe Lemed32d8f6f2019-02-15 10:25:33 -0800389 if (sVerbose) {
Felipe Lemebe002d82019-01-23 10:22:32 -0800390 Log.v(TAG, "handleScheduleFlush(" + getDebugState(reason)
391 + ", checkExisting=" + checkExisting);
392 }
Felipe Leme3fe6e922019-02-04 17:52:27 -0800393 if (!hasStarted()) {
Felipe Lemed32d8f6f2019-02-15 10:25:33 -0800394 if (sVerbose) Log.v(TAG, "handleScheduleFlush(): session not started yet");
Felipe Lemebe002d82019-01-23 10:22:32 -0800395 return;
396 }
397
398 if (mDisabled.get()) {
399 // Should not be called on this state, as handleSendEvent checks.
400 // But we rather add one if check and log than re-schedule and keep the session alive...
401 Log.e(TAG, "handleScheduleFlush(" + getDebugState(reason) + "): should not be called "
402 + "when disabled. events=" + (mEvents == null ? null : mEvents.size()));
Felipe Lemed65692c2019-01-16 12:10:50 -0800403 return;
404 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800405 if (checkExisting && mHandler.hasMessages(MSG_FLUSH)) {
406 // "Renew" the flush message by removing the previous one
407 mHandler.removeMessages(MSG_FLUSH);
408 }
Felipe Leme326f15a2019-02-19 09:42:24 -0800409 final int idleFlushingFrequencyMs = mManager.mOptions.idleFlushingFrequencyMs;
410 mNextFlush = System.currentTimeMillis() + idleFlushingFrequencyMs;
Felipe Lemed32d8f6f2019-02-15 10:25:33 -0800411 if (sVerbose) {
Felipe Lemebe002d82019-01-23 10:22:32 -0800412 Log.v(TAG, "handleScheduleFlush(): scheduled to flush in "
Felipe Leme326f15a2019-02-19 09:42:24 -0800413 + idleFlushingFrequencyMs + "ms: " + TimeUtils.logTimeOfDay(mNextFlush));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800414 }
Felipe Leme3fe6e922019-02-04 17:52:27 -0800415 // Post using a Runnable directly to trim a few μs from PooledLambda.obtainMessage()
Felipe Leme326f15a2019-02-19 09:42:24 -0800416 mHandler.postDelayed(() -> flushIfNeeded(reason), MSG_FLUSH, idleFlushingFrequencyMs);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800417 }
418
Felipe Leme3fe6e922019-02-04 17:52:27 -0800419 @UiThread
420 private void flushIfNeeded(@FlushReason int reason) {
Felipe Leme3d570a42019-01-28 13:04:34 -0800421 if (mEvents == null || mEvents.isEmpty()) {
Felipe Lemed32d8f6f2019-02-15 10:25:33 -0800422 if (sVerbose) Log.v(TAG, "Nothing to flush");
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800423 return;
424 }
Felipe Leme3fe6e922019-02-04 17:52:27 -0800425 flush(reason);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800426 }
427
Felipe Leme3fe6e922019-02-04 17:52:27 -0800428 @Override
429 @UiThread
430 void flush(@FlushReason int reason) {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800431 if (mEvents == null) return;
432
Felipe Lemebe002d82019-01-23 10:22:32 -0800433 if (mDisabled.get()) {
434 Log.e(TAG, "handleForceFlush(" + getDebugState(reason) + "): should not be when "
435 + "disabled");
436 return;
437 }
438
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800439 if (mDirectServiceInterface == null) {
Felipe Lemed32d8f6f2019-02-15 10:25:33 -0800440 if (sVerbose) {
Felipe Lemebe002d82019-01-23 10:22:32 -0800441 Log.v(TAG, "handleForceFlush(" + getDebugState(reason) + "): hold your horses, "
442 + "client not ready: " + mEvents);
Felipe Lemee127c9a2019-01-04 14:56:38 -0800443 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800444 if (!mHandler.hasMessages(MSG_FLUSH)) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800445 scheduleFlush(reason, /* checkExisting= */ false);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800446 }
447 return;
448 }
449
450 final int numberEvents = mEvents.size();
Felipe Lemed58c1ea2019-02-21 11:22:45 -0800451 final String reasonString = getFlushReasonAsString(reason);
Felipe Lemed32d8f6f2019-02-15 10:25:33 -0800452 if (sDebug) {
Felipe Lemebe002d82019-01-23 10:22:32 -0800453 Log.d(TAG, "Flushing " + numberEvents + " event(s) for " + getDebugState(reason));
Felipe Leme1af85ea2019-01-16 13:23:40 -0800454 }
Felipe Lemed32d8f6f2019-02-15 10:25:33 -0800455 if (mFlushHistory != null) {
456 // Logs reason, size, max size, idle timeout
457 final String logRecord = "r=" + reasonString + " s=" + numberEvents
Felipe Leme326f15a2019-02-19 09:42:24 -0800458 + " m=" + mManager.mOptions.maxBufferSize
459 + " i=" + mManager.mOptions.idleFlushingFrequencyMs;
Felipe Leme1af85ea2019-01-16 13:23:40 -0800460 mFlushHistory.log(logRecord);
Felipe Lemed32d8f6f2019-02-15 10:25:33 -0800461 }
462 try {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800463 mHandler.removeMessages(MSG_FLUSH);
464
Felipe Leme3fe6e922019-02-04 17:52:27 -0800465 final ParceledListSlice<ContentCaptureEvent> events = clearEvents();
Felipe Lemefc24bea2018-12-18 13:19:01 -0800466 mDirectServiceInterface.sendEvents(events);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800467 } catch (RemoteException e) {
Felipe Lemed65692c2019-01-16 12:10:50 -0800468 Log.w(TAG, "Error sending " + numberEvents + " for " + getDebugState()
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800469 + ": " + e);
470 }
471 }
472
Felipe Leme4eecbe62019-02-11 17:50:17 -0800473 @Override
474 public void updateContentCaptureContext(@Nullable ContentCaptureContext context) {
475 notifyContextUpdated(mId, context);
476 }
477
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800478 /**
479 * Resets the buffer and return a {@link ParceledListSlice} with the previous events.
480 */
481 @NonNull
Felipe Leme3fe6e922019-02-04 17:52:27 -0800482 @UiThread
483 private ParceledListSlice<ContentCaptureEvent> clearEvents() {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800484 // NOTE: we must save a reference to the current mEvents and then set it to to null,
485 // otherwise clearing it would clear it in the receiving side if the service is also local.
486 final List<ContentCaptureEvent> events = mEvents == null
487 ? Collections.emptyList()
488 : mEvents;
489 mEvents = null;
490 return new ParceledListSlice<>(events);
491 }
492
Felipe Leme3fe6e922019-02-04 17:52:27 -0800493 @UiThread
494 private void destroySession() {
Felipe Lemed32d8f6f2019-02-15 10:25:33 -0800495 if (sDebug) {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800496 Log.d(TAG, "Destroying session (ctx=" + mContext + ", id=" + mId + ") with "
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800497 + (mEvents == null ? 0 : mEvents.size()) + " event(s) for "
Felipe Lemed65692c2019-01-16 12:10:50 -0800498 + getDebugState());
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800499 }
500
501 try {
Felipe Lemef2aa0d22019-01-28 10:38:46 -0800502 mSystemServerInterface.finishSession(mId);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800503 } catch (RemoteException e) {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800504 Log.e(TAG, "Error destroying system-service session " + mId + " for "
Felipe Lemed65692c2019-01-16 12:10:50 -0800505 + getDebugState() + ": " + e);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800506 }
507 }
508
Felipe Leme4bc0f6b2019-01-03 19:01:07 -0800509 // TODO(b/122454205): once we support multiple sessions, we might need to move some of these
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800510 // clearings out.
Felipe Leme3fe6e922019-02-04 17:52:27 -0800511 @UiThread
512 private void resetSession(int newState) {
Felipe Lemed32d8f6f2019-02-15 10:25:33 -0800513 if (sVerbose) {
Felipe Lemed65692c2019-01-16 12:10:50 -0800514 Log.v(TAG, "handleResetSession(" + getActivityName() + "): from "
515 + getStateAsString(mState) + " to " + getStateAsString(newState));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800516 }
Felipe Lemed65692c2019-01-16 12:10:50 -0800517 mState = newState;
518 mDisabled.set((newState & STATE_DISABLED) != 0);
Felipe Leme4bc0f6b2019-01-03 19:01:07 -0800519 // TODO(b/122454205): must reset children (which currently is owned by superclass)
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800520 mApplicationToken = null;
521 mComponentName = null;
522 mEvents = null;
523 if (mDirectServiceInterface != null) {
524 mDirectServiceInterface.asBinder().unlinkToDeath(mDirectServiceVulture, 0);
525 }
526 mDirectServiceInterface = null;
527 mHandler.removeMessages(MSG_FLUSH);
528 }
529
530 @Override
531 void internalNotifyViewAppeared(@NonNull ViewStructureImpl node) {
Felipe Leme87a9dc92018-12-18 14:28:07 -0800532 notifyViewAppeared(mId, node);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800533 }
534
535 @Override
536 void internalNotifyViewDisappeared(@NonNull AutofillId id) {
Felipe Leme87a9dc92018-12-18 14:28:07 -0800537 notifyViewDisappeared(mId, id);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800538 }
539
540 @Override
Felipe Leme21e8dcb2019-01-18 09:09:45 -0800541 void internalNotifyViewTextChanged(@NonNull AutofillId id, @Nullable CharSequence text) {
542 notifyViewTextChanged(mId, id, text);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800543 }
544
545 @Override
Felipe Leme01297692019-01-29 18:16:23 -0800546 public void internalNotifyViewHierarchyEvent(boolean started) {
Felipe Leme544b39c2019-02-22 09:26:29 -0800547 notifyViewHierarchyEvent(mId, started);
Felipe Leme01297692019-01-29 18:16:23 -0800548 }
549
550 @Override
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800551 boolean isContentCaptureEnabled() {
Felipe Leme609991d2019-01-30 16:27:24 -0800552 return super.isContentCaptureEnabled() && mManager.isContentCaptureEnabled();
553 }
554
555 // Called by ContentCaptureManager.isContentCaptureEnabled
556 boolean isDisabled() {
557 return mDisabled.get();
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800558 }
559
Felipe Leme4bc0f6b2019-01-03 19:01:07 -0800560 // TODO(b/122454205): refactor "notifyXXXX" methods below to a common "Buffer" object that is
Felipe Leme87a9dc92018-12-18 14:28:07 -0800561 // shared between ActivityContentCaptureSession and ChildContentCaptureSession objects. Such
562 // change should also get get rid of the "internalNotifyXXXX" methods above
563 void notifyChildSessionStarted(@NonNull String parentSessionId,
564 @NonNull String childSessionId, @NonNull ContentCaptureContext clientContext) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800565 sendEvent(new ContentCaptureEvent(childSessionId, TYPE_SESSION_STARTED)
566 .setParentSessionId(parentSessionId).setClientContext(clientContext),
567 FORCE_FLUSH);
Felipe Leme87a9dc92018-12-18 14:28:07 -0800568 }
569
570 void notifyChildSessionFinished(@NonNull String parentSessionId,
571 @NonNull String childSessionId) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800572 sendEvent(new ContentCaptureEvent(childSessionId, TYPE_SESSION_FINISHED)
573 .setParentSessionId(parentSessionId), FORCE_FLUSH);
Felipe Leme87a9dc92018-12-18 14:28:07 -0800574 }
575
576 void notifyViewAppeared(@NonNull String sessionId, @NonNull ViewStructureImpl node) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800577 sendEvent(new ContentCaptureEvent(sessionId, TYPE_VIEW_APPEARED)
578 .setViewNode(node.mNode));
Felipe Leme87a9dc92018-12-18 14:28:07 -0800579 }
580
Felipe Leme544b39c2019-02-22 09:26:29 -0800581 /** Public because is also used by ViewRootImpl */
582 public void notifyViewDisappeared(@NonNull String sessionId, @NonNull AutofillId id) {
583 sendEvent(new ContentCaptureEvent(sessionId, TYPE_VIEW_DISAPPEARED).setAutofillId(id));
Felipe Leme87a9dc92018-12-18 14:28:07 -0800584 }
585
586 void notifyViewTextChanged(@NonNull String sessionId, @NonNull AutofillId id,
Felipe Leme21e8dcb2019-01-18 09:09:45 -0800587 @Nullable CharSequence text) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800588 sendEvent(new ContentCaptureEvent(sessionId, TYPE_VIEW_TEXT_CHANGED).setAutofillId(id)
589 .setText(text));
Felipe Leme01297692019-01-29 18:16:23 -0800590 }
591
Felipe Leme544b39c2019-02-22 09:26:29 -0800592 /** Public because is also used by ViewRootImpl */
593 public void notifyViewHierarchyEvent(@NonNull String sessionId, boolean started) {
594 final int type = started ? TYPE_INITIAL_VIEW_TREE_APPEARING
595 : TYPE_INITIAL_VIEW_TREE_APPEARED;
596 sendEvent(new ContentCaptureEvent(sessionId, type), FORCE_FLUSH);
Felipe Leme87a9dc92018-12-18 14:28:07 -0800597 }
598
Felipe Leme4eecbe62019-02-11 17:50:17 -0800599 void notifyContextUpdated(@NonNull String sessionId,
600 @Nullable ContentCaptureContext context) {
601 sendEvent(new ContentCaptureEvent(sessionId, TYPE_CONTEXT_UPDATED)
602 .setClientContext(context));
603 }
604
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800605 @Override
606 void dump(@NonNull String prefix, @NonNull PrintWriter pw) {
Felipe Lemed49d52c2019-02-15 09:48:20 -0800607 super.dump(prefix, pw);
608
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800609 pw.print(prefix); pw.print("mContext: "); pw.println(mContext);
610 pw.print(prefix); pw.print("user: "); pw.println(mContext.getUserId());
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800611 if (mDirectServiceInterface != null) {
612 pw.print(prefix); pw.print("mDirectServiceInterface: ");
613 pw.println(mDirectServiceInterface);
614 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800615 pw.print(prefix); pw.print("mDisabled: "); pw.println(mDisabled.get());
616 pw.print(prefix); pw.print("isEnabled(): "); pw.println(isContentCaptureEnabled());
Felipe Leme01b87492019-01-15 13:26:52 -0800617 pw.print(prefix); pw.print("state: "); pw.println(getStateAsString(mState));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800618 if (mApplicationToken != null) {
619 pw.print(prefix); pw.print("app token: "); pw.println(mApplicationToken);
620 }
621 if (mComponentName != null) {
622 pw.print(prefix); pw.print("component name: ");
623 pw.println(mComponentName.flattenToShortString());
624 }
625 if (mEvents != null && !mEvents.isEmpty()) {
626 final int numberEvents = mEvents.size();
627 pw.print(prefix); pw.print("buffered events: "); pw.print(numberEvents);
Felipe Leme326f15a2019-02-19 09:42:24 -0800628 pw.print('/'); pw.println(mManager.mOptions.maxBufferSize);
Felipe Lemed32d8f6f2019-02-15 10:25:33 -0800629 if (sVerbose && numberEvents > 0) {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800630 final String prefix3 = prefix + " ";
631 for (int i = 0; i < numberEvents; i++) {
632 final ContentCaptureEvent event = mEvents.get(i);
633 pw.print(prefix3); pw.print(i); pw.print(": "); event.dump(pw);
634 pw.println();
635 }
636 }
Felipe Leme326f15a2019-02-19 09:42:24 -0800637 pw.print(prefix); pw.print("flush frequency: ");
638 pw.println(mManager.mOptions.idleFlushingFrequencyMs);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800639 pw.print(prefix); pw.print("next flush: ");
Felipe Leme1af85ea2019-01-16 13:23:40 -0800640 TimeUtils.formatDuration(mNextFlush - System.currentTimeMillis(), pw);
641 pw.print(" ("); pw.print(TimeUtils.logTimeOfDay(mNextFlush)); pw.println(")");
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800642 }
Felipe Lemed32d8f6f2019-02-15 10:25:33 -0800643 if (mFlushHistory != null) {
644 pw.print(prefix); pw.println("flush history:");
645 mFlushHistory.reverseDump(/* fd= */ null, pw, /* args= */ null); pw.println();
646 } else {
647 pw.print(prefix); pw.println("not logging flush history");
648 }
649
650 super.dump(prefix, pw);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800651 }
652
653 /**
654 * Gets a string that can be used to identify the activity on logging statements.
655 */
Felipe Lemed65692c2019-01-16 12:10:50 -0800656 private String getActivityName() {
657 return mComponentName == null
658 ? "pkg:" + mContext.getPackageName()
659 : "act:" + mComponentName.flattenToShortString();
660 }
661
Felipe Lemebe002d82019-01-23 10:22:32 -0800662 @NonNull
Felipe Lemed65692c2019-01-16 12:10:50 -0800663 private String getDebugState() {
Felipe Lemebe002d82019-01-23 10:22:32 -0800664 return getActivityName() + " [state=" + getStateAsString(mState) + ", disabled="
665 + mDisabled.get() + "]";
666 }
667
668 @NonNull
669 private String getDebugState(@FlushReason int reason) {
Felipe Lemed58c1ea2019-02-21 11:22:45 -0800670 return getDebugState() + ", reason=" + getFlushReasonAsString(reason);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800671 }
672}