blob: f0f2c49f31ee1d8222e97536db35c7085273ee5f [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.DEBUG;
27import static android.view.contentcapture.ContentCaptureHelper.VERBOSE;
28import static android.view.contentcapture.ContentCaptureHelper.getSanitizedString;
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 Leme01297692019-01-29 18:16:23 -080067 private static final boolean FORCE_FLUSH = true;
68
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080069 /**
70 * Handler message used to flush the buffer.
71 */
72 private static final int MSG_FLUSH = 1;
73
74 /**
75 * Maximum number of events that are buffered before sent to the app.
76 */
77 // TODO(b/121044064): use settings
78 private static final int MAX_BUFFER_SIZE = 100;
79
80 /**
81 * Frequency the buffer is flushed if stale.
82 */
83 // TODO(b/121044064): use settings
84 private static final int FLUSHING_FREQUENCY_MS = 5_000;
85
86 /**
87 * Name of the {@link IResultReceiver} extra used to pass the binder interface to the service.
88 * @hide
89 */
90 public static final String EXTRA_BINDER = "binder";
91
92 @NonNull
Felipe Leme609991d2019-01-30 16:27:24 -080093 private final AtomicBoolean mDisabled = new AtomicBoolean(false);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080094
95 @NonNull
96 private final Context mContext;
97
98 @NonNull
Felipe Leme609991d2019-01-30 16:27:24 -080099 private final ContentCaptureManager mManager;
100
101 @NonNull
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800102 private final Handler mHandler;
103
104 /**
105 * Interface to the system_server binder object - it's only used to start the session (and
106 * notify when the session is finished).
107 */
Felipe Lemed49d52c2019-02-15 09:48:20 -0800108 @NonNull
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800109 private final IContentCaptureManager mSystemServerInterface;
110
111 /**
112 * Direct interface to the service binder object - it's used to send the events, including the
113 * last ones (when the session is finished)
114 */
Felipe Lemed49d52c2019-02-15 09:48:20 -0800115 @NonNull
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800116 private IContentCaptureDirectManager mDirectServiceInterface;
117 @Nullable
118 private DeathRecipient mDirectServiceVulture;
119
Felipe Leme35ea7632019-01-29 16:13:30 -0800120 private int mState = UNKNOWN_STATE;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800121
122 @Nullable
123 private IBinder mApplicationToken;
124
125 @Nullable
126 private ComponentName mComponentName;
127
128 /**
129 * List of events held to be sent as a batch.
130 */
131 @Nullable
132 private ArrayList<ContentCaptureEvent> mEvents;
133
134 // Used just for debugging purposes (on dump)
135 private long mNextFlush;
136
Felipe Leme1af85ea2019-01-16 13:23:40 -0800137 // TODO(b/121044064): use settings to set size
138 private final LocalLog mFlushHistory = new LocalLog(10);
139
Felipe Leme87a9dc92018-12-18 14:28:07 -0800140 /** @hide */
Felipe Leme609991d2019-01-30 16:27:24 -0800141 protected MainContentCaptureSession(@NonNull Context context,
142 @NonNull ContentCaptureManager manager, @NonNull Handler handler,
Felipe Lemed49d52c2019-02-15 09:48:20 -0800143 @NonNull IContentCaptureManager systemServerInterface) {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800144 mContext = context;
Felipe Leme609991d2019-01-30 16:27:24 -0800145 mManager = manager;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800146 mHandler = handler;
147 mSystemServerInterface = systemServerInterface;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800148 }
149
Felipe Leme87a9dc92018-12-18 14:28:07 -0800150 @Override
Felipe Leme4bc0f6b2019-01-03 19:01:07 -0800151 MainContentCaptureSession getMainCaptureSession() {
152 return this;
153 }
154
155 @Override
Felipe Leme87a9dc92018-12-18 14:28:07 -0800156 ContentCaptureSession newChild(@NonNull ContentCaptureContext clientContext) {
157 final ContentCaptureSession child = new ChildContentCaptureSession(this, clientContext);
158 notifyChildSessionStarted(mId, child.mId, clientContext);
159 return child;
160 }
161
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800162 /**
163 * Starts this session.
164 *
165 * @hide
166 */
Felipe Leme3fe6e922019-02-04 17:52:27 -0800167 @UiThread
168 void start(@NonNull IBinder token, @NonNull ComponentName component,
Adam He328c0e32019-01-03 15:19:22 -0800169 int flags) {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800170 if (!isContentCaptureEnabled()) return;
171
172 if (VERBOSE) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800173 Log.v(TAG, "start(): token=" + token + ", comp="
174 + ComponentName.flattenToShortString(component));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800175 }
176
Felipe Leme3fe6e922019-02-04 17:52:27 -0800177 if (hasStarted()) {
Felipe Lemed65692c2019-01-16 12:10:50 -0800178 // TODO(b/122959591): make sure this is expected (and when), or use Log.w
179 if (DEBUG) {
180 Log.d(TAG, "ignoring handleStartSession(" + token + "/"
Felipe Leme3fe6e922019-02-04 17:52:27 -0800181 + ComponentName.flattenToShortString(component) + " while on state "
Felipe Lemed65692c2019-01-16 12:10:50 -0800182 + getStateAsString(mState));
183 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800184 return;
185 }
186 mState = STATE_WAITING_FOR_SERVER;
187 mApplicationToken = token;
Felipe Leme3fe6e922019-02-04 17:52:27 -0800188 mComponentName = component;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800189
190 if (VERBOSE) {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800191 Log.v(TAG, "handleStartSession(): token=" + token + ", act="
Felipe Lemed65692c2019-01-16 12:10:50 -0800192 + getDebugState() + ", id=" + mId);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800193 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800194
195 try {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800196 mSystemServerInterface.startSession(mApplicationToken, component, mId, flags,
Felipe Lemef2aa0d22019-01-28 10:38:46 -0800197 new IResultReceiver.Stub() {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800198 @Override
199 public void send(int resultCode, Bundle resultData) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800200 final IBinder binder;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800201 if (resultData != null) {
202 binder = resultData.getBinder(EXTRA_BINDER);
203 if (binder == null) {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800204 Log.wtf(TAG, "No " + EXTRA_BINDER + " extra result");
Felipe Leme3fe6e922019-02-04 17:52:27 -0800205 mHandler.post(() -> resetSession(
206 STATE_DISABLED | STATE_INTERNAL_ERROR));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800207 return;
208 }
Felipe Leme3fe6e922019-02-04 17:52:27 -0800209 } else {
210 binder = null;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800211 }
Felipe Leme3fe6e922019-02-04 17:52:27 -0800212 mHandler.post(() -> onSessionStarted(resultCode, binder));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800213 }
214 });
215 } catch (RemoteException e) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800216 Log.w(TAG, "Error starting session for " + component.flattenToShortString() + ": " + e);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800217 }
218 }
219
Felipe Leme3fe6e922019-02-04 17:52:27 -0800220 @Override
221 void onDestroy() {
222 mHandler.removeMessages(MSG_FLUSH);
223 mHandler.post(() -> destroySession());
224 }
225
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800226 /**
227 * Callback from {@code system_server} after call to
Felipe Leme609991d2019-01-30 16:27:24 -0800228 * {@link IContentCaptureManager#startSession(IBinder, ComponentName, String, int,
229 * IResultReceiver)}
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800230 *
231 * @param resultCode session state
232 * @param binder handle to {@code IContentCaptureDirectManager}
233 */
Felipe Leme3fe6e922019-02-04 17:52:27 -0800234 @UiThread
235 private void onSessionStarted(int resultCode, @Nullable IBinder binder) {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800236 if (binder != null) {
237 mDirectServiceInterface = IContentCaptureDirectManager.Stub.asInterface(binder);
238 mDirectServiceVulture = () -> {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800239 Log.w(TAG, "Destroying session " + mId + " because service died");
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800240 destroy();
241 };
242 try {
243 binder.linkToDeath(mDirectServiceVulture, 0);
244 } catch (RemoteException e) {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800245 Log.w(TAG, "Failed to link to death on " + binder + ": " + e);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800246 }
247 }
Adam He328c0e32019-01-03 15:19:22 -0800248
Felipe Lemed65692c2019-01-16 12:10:50 -0800249 if ((resultCode & STATE_DISABLED) != 0) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800250 resetSession(resultCode);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800251 } else {
Felipe Lemed65692c2019-01-16 12:10:50 -0800252 mState = resultCode;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800253 mDisabled.set(false);
254 }
255 if (VERBOSE) {
Felipe Lemed65692c2019-01-16 12:10:50 -0800256 Log.v(TAG, "handleSessionStarted() result: id=" + mId + " resultCode=" + resultCode
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800257 + ", state=" + getStateAsString(mState) + ", disabled=" + mDisabled.get()
Felipe Lemee127c9a2019-01-04 14:56:38 -0800258 + ", binder=" + binder + ", events=" + (mEvents == null ? 0 : mEvents.size()));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800259 }
260 }
261
Felipe Leme3fe6e922019-02-04 17:52:27 -0800262 @UiThread
263 private void sendEvent(@NonNull ContentCaptureEvent event) {
264 sendEvent(event, /* forceFlush= */ false);
Felipe Leme01297692019-01-29 18:16:23 -0800265 }
266
Felipe Leme3fe6e922019-02-04 17:52:27 -0800267 @UiThread
268 private void sendEvent(@NonNull ContentCaptureEvent event, boolean forceFlush) {
Felipe Leme1af85ea2019-01-16 13:23:40 -0800269 final int eventType = event.getType();
Felipe Lemebe002d82019-01-23 10:22:32 -0800270 if (VERBOSE) Log.v(TAG, "handleSendEvent(" + getDebugState() + "): " + event);
Felipe Leme4eecbe62019-02-11 17:50:17 -0800271 if (!hasStarted() && eventType != ContentCaptureEvent.TYPE_SESSION_STARTED
272 && eventType != ContentCaptureEvent.TYPE_CONTEXT_UPDATED) {
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 Leme4eecbe62019-02-11 17:50:17 -0800276 + "): dropping because session not started yet");
Felipe Lemed65692c2019-01-16 12:10:50 -0800277 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
Felipe Leme4eecbe62019-02-11 17:50:17 -0800479 @Override
480 public void updateContentCaptureContext(@Nullable ContentCaptureContext context) {
481 notifyContextUpdated(mId, context);
482 }
483
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800484 /**
485 * Resets the buffer and return a {@link ParceledListSlice} with the previous events.
486 */
487 @NonNull
Felipe Leme3fe6e922019-02-04 17:52:27 -0800488 @UiThread
489 private ParceledListSlice<ContentCaptureEvent> clearEvents() {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800490 // NOTE: we must save a reference to the current mEvents and then set it to to null,
491 // otherwise clearing it would clear it in the receiving side if the service is also local.
492 final List<ContentCaptureEvent> events = mEvents == null
493 ? Collections.emptyList()
494 : mEvents;
495 mEvents = null;
496 return new ParceledListSlice<>(events);
497 }
498
Felipe Leme3fe6e922019-02-04 17:52:27 -0800499 @UiThread
500 private void destroySession() {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800501 if (DEBUG) {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800502 Log.d(TAG, "Destroying session (ctx=" + mContext + ", id=" + mId + ") with "
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800503 + (mEvents == null ? 0 : mEvents.size()) + " event(s) for "
Felipe Lemed65692c2019-01-16 12:10:50 -0800504 + getDebugState());
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800505 }
506
507 try {
Felipe Lemef2aa0d22019-01-28 10:38:46 -0800508 mSystemServerInterface.finishSession(mId);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800509 } catch (RemoteException e) {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800510 Log.e(TAG, "Error destroying system-service session " + mId + " for "
Felipe Lemed65692c2019-01-16 12:10:50 -0800511 + getDebugState() + ": " + e);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800512 }
513 }
514
Felipe Leme4bc0f6b2019-01-03 19:01:07 -0800515 // TODO(b/122454205): once we support multiple sessions, we might need to move some of these
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800516 // clearings out.
Felipe Leme3fe6e922019-02-04 17:52:27 -0800517 @UiThread
518 private void resetSession(int newState) {
Felipe Lemed65692c2019-01-16 12:10:50 -0800519 if (VERBOSE) {
520 Log.v(TAG, "handleResetSession(" + getActivityName() + "): from "
521 + getStateAsString(mState) + " to " + getStateAsString(newState));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800522 }
Felipe Lemed65692c2019-01-16 12:10:50 -0800523 mState = newState;
524 mDisabled.set((newState & STATE_DISABLED) != 0);
Felipe Leme4bc0f6b2019-01-03 19:01:07 -0800525 // TODO(b/122454205): must reset children (which currently is owned by superclass)
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800526 mApplicationToken = null;
527 mComponentName = null;
528 mEvents = null;
529 if (mDirectServiceInterface != null) {
530 mDirectServiceInterface.asBinder().unlinkToDeath(mDirectServiceVulture, 0);
531 }
532 mDirectServiceInterface = null;
533 mHandler.removeMessages(MSG_FLUSH);
534 }
535
536 @Override
537 void internalNotifyViewAppeared(@NonNull ViewStructureImpl node) {
Felipe Leme87a9dc92018-12-18 14:28:07 -0800538 notifyViewAppeared(mId, node);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800539 }
540
541 @Override
542 void internalNotifyViewDisappeared(@NonNull AutofillId id) {
Felipe Leme87a9dc92018-12-18 14:28:07 -0800543 notifyViewDisappeared(mId, id);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800544 }
545
546 @Override
Felipe Leme21e8dcb2019-01-18 09:09:45 -0800547 void internalNotifyViewTextChanged(@NonNull AutofillId id, @Nullable CharSequence text) {
548 notifyViewTextChanged(mId, id, text);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800549 }
550
551 @Override
Felipe Leme01297692019-01-29 18:16:23 -0800552 public void internalNotifyViewHierarchyEvent(boolean started) {
553 notifyInitialViewHierarchyEvent(mId, started);
554 }
555
556 @Override
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800557 boolean isContentCaptureEnabled() {
Felipe Leme609991d2019-01-30 16:27:24 -0800558 return super.isContentCaptureEnabled() && mManager.isContentCaptureEnabled();
559 }
560
561 // Called by ContentCaptureManager.isContentCaptureEnabled
562 boolean isDisabled() {
563 return mDisabled.get();
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800564 }
565
Felipe Leme4bc0f6b2019-01-03 19:01:07 -0800566 // TODO(b/122454205): refactor "notifyXXXX" methods below to a common "Buffer" object that is
Felipe Leme87a9dc92018-12-18 14:28:07 -0800567 // shared between ActivityContentCaptureSession and ChildContentCaptureSession objects. Such
568 // change should also get get rid of the "internalNotifyXXXX" methods above
569 void notifyChildSessionStarted(@NonNull String parentSessionId,
570 @NonNull String childSessionId, @NonNull ContentCaptureContext clientContext) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800571 sendEvent(new ContentCaptureEvent(childSessionId, TYPE_SESSION_STARTED)
572 .setParentSessionId(parentSessionId).setClientContext(clientContext),
573 FORCE_FLUSH);
Felipe Leme87a9dc92018-12-18 14:28:07 -0800574 }
575
576 void notifyChildSessionFinished(@NonNull String parentSessionId,
577 @NonNull String childSessionId) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800578 sendEvent(new ContentCaptureEvent(childSessionId, TYPE_SESSION_FINISHED)
579 .setParentSessionId(parentSessionId), FORCE_FLUSH);
Felipe Leme87a9dc92018-12-18 14:28:07 -0800580 }
581
582 void notifyViewAppeared(@NonNull String sessionId, @NonNull ViewStructureImpl node) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800583 sendEvent(new ContentCaptureEvent(sessionId, TYPE_VIEW_APPEARED)
584 .setViewNode(node.mNode));
Felipe Leme87a9dc92018-12-18 14:28:07 -0800585 }
586
587 void notifyViewDisappeared(@NonNull String sessionId, @NonNull AutofillId id) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800588 sendEvent(
589 new ContentCaptureEvent(sessionId, TYPE_VIEW_DISAPPEARED).setAutofillId(id));
Felipe Leme01297692019-01-29 18:16:23 -0800590 }
591
592 /** @hide */
593 public void notifyViewsDisappeared(@NonNull String sessionId,
594 @NonNull ArrayList<AutofillId> ids) {
595 final ContentCaptureEvent event = new ContentCaptureEvent(sessionId, TYPE_VIEW_DISAPPEARED);
596 if (ids.size() == 1) {
597 event.setAutofillId(ids.get(0));
598 } else {
599 event.setAutofillIds(ids);
600 }
Felipe Leme3fe6e922019-02-04 17:52:27 -0800601 sendEvent(event);
Felipe Leme87a9dc92018-12-18 14:28:07 -0800602 }
603
604 void notifyViewTextChanged(@NonNull String sessionId, @NonNull AutofillId id,
Felipe Leme21e8dcb2019-01-18 09:09:45 -0800605 @Nullable CharSequence text) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800606 sendEvent(new ContentCaptureEvent(sessionId, TYPE_VIEW_TEXT_CHANGED).setAutofillId(id)
607 .setText(text));
Felipe Leme01297692019-01-29 18:16:23 -0800608 }
609
610 void notifyInitialViewHierarchyEvent(@NonNull String sessionId, boolean started) {
611 if (started) {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800612 sendEvent(new ContentCaptureEvent(sessionId, TYPE_INITIAL_VIEW_TREE_APPEARING));
Felipe Leme01297692019-01-29 18:16:23 -0800613 } else {
Felipe Leme3fe6e922019-02-04 17:52:27 -0800614 sendEvent(new ContentCaptureEvent(sessionId, TYPE_INITIAL_VIEW_TREE_APPEARED),
615 FORCE_FLUSH);
Felipe Leme01297692019-01-29 18:16:23 -0800616 }
Felipe Leme87a9dc92018-12-18 14:28:07 -0800617 }
618
Felipe Leme4eecbe62019-02-11 17:50:17 -0800619 void notifyContextUpdated(@NonNull String sessionId,
620 @Nullable ContentCaptureContext context) {
621 sendEvent(new ContentCaptureEvent(sessionId, TYPE_CONTEXT_UPDATED)
622 .setClientContext(context));
623 }
624
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800625 @Override
626 void dump(@NonNull String prefix, @NonNull PrintWriter pw) {
Felipe Lemed49d52c2019-02-15 09:48:20 -0800627 super.dump(prefix, pw);
628
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800629 pw.print(prefix); pw.print("mContext: "); pw.println(mContext);
630 pw.print(prefix); pw.print("user: "); pw.println(mContext.getUserId());
Felipe Lemed49d52c2019-02-15 09:48:20 -0800631 pw.print(prefix); pw.print("mSystemServerInterface: ");
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800632 if (mDirectServiceInterface != null) {
633 pw.print(prefix); pw.print("mDirectServiceInterface: ");
634 pw.println(mDirectServiceInterface);
635 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800636 pw.print(prefix); pw.print("mDisabled: "); pw.println(mDisabled.get());
637 pw.print(prefix); pw.print("isEnabled(): "); pw.println(isContentCaptureEnabled());
Felipe Leme01b87492019-01-15 13:26:52 -0800638 pw.print(prefix); pw.print("state: "); pw.println(getStateAsString(mState));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800639 if (mApplicationToken != null) {
640 pw.print(prefix); pw.print("app token: "); pw.println(mApplicationToken);
641 }
642 if (mComponentName != null) {
643 pw.print(prefix); pw.print("component name: ");
644 pw.println(mComponentName.flattenToShortString());
645 }
646 if (mEvents != null && !mEvents.isEmpty()) {
647 final int numberEvents = mEvents.size();
648 pw.print(prefix); pw.print("buffered events: "); pw.print(numberEvents);
649 pw.print('/'); pw.println(MAX_BUFFER_SIZE);
650 if (VERBOSE && numberEvents > 0) {
651 final String prefix3 = prefix + " ";
652 for (int i = 0; i < numberEvents; i++) {
653 final ContentCaptureEvent event = mEvents.get(i);
654 pw.print(prefix3); pw.print(i); pw.print(": "); event.dump(pw);
655 pw.println();
656 }
657 }
658 pw.print(prefix); pw.print("flush frequency: "); pw.println(FLUSHING_FREQUENCY_MS);
659 pw.print(prefix); pw.print("next flush: ");
Felipe Leme1af85ea2019-01-16 13:23:40 -0800660 TimeUtils.formatDuration(mNextFlush - System.currentTimeMillis(), pw);
661 pw.print(" ("); pw.print(TimeUtils.logTimeOfDay(mNextFlush)); pw.println(")");
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800662 }
Felipe Leme1af85ea2019-01-16 13:23:40 -0800663 pw.print(prefix); pw.println("flush history:");
664 mFlushHistory.reverseDump(/* fd= */ null, pw, /* args= */ null); pw.println();
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800665 }
666
667 /**
668 * Gets a string that can be used to identify the activity on logging statements.
669 */
Felipe Lemed65692c2019-01-16 12:10:50 -0800670 private String getActivityName() {
671 return mComponentName == null
672 ? "pkg:" + mContext.getPackageName()
673 : "act:" + mComponentName.flattenToShortString();
674 }
675
Felipe Lemebe002d82019-01-23 10:22:32 -0800676 @NonNull
Felipe Lemed65692c2019-01-16 12:10:50 -0800677 private String getDebugState() {
Felipe Lemebe002d82019-01-23 10:22:32 -0800678 return getActivityName() + " [state=" + getStateAsString(mState) + ", disabled="
679 + mDisabled.get() + "]";
680 }
681
682 @NonNull
683 private String getDebugState(@FlushReason int reason) {
684 return getDebugState() + ", reason=" + getflushReasonAsString(reason);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800685 }
686}