blob: 83dbf2d5bb5858ba492841605ee981511fe13da7 [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 Leme87a9dc92018-12-18 14:28:07 -080018import static android.view.contentcapture.ContentCaptureEvent.TYPE_SESSION_FINISHED;
19import static android.view.contentcapture.ContentCaptureEvent.TYPE_SESSION_STARTED;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080020import static android.view.contentcapture.ContentCaptureEvent.TYPE_VIEW_APPEARED;
21import static android.view.contentcapture.ContentCaptureEvent.TYPE_VIEW_DISAPPEARED;
22import static android.view.contentcapture.ContentCaptureEvent.TYPE_VIEW_TEXT_CHANGED;
Felipe Lemebe002d82019-01-23 10:22:32 -080023import static android.view.contentcapture.ContentCaptureHelper.DEBUG;
24import static android.view.contentcapture.ContentCaptureHelper.VERBOSE;
25import static android.view.contentcapture.ContentCaptureHelper.getSanitizedString;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080026
27import static com.android.internal.util.function.pooled.PooledLambda.obtainMessage;
28
29import android.annotation.NonNull;
30import android.annotation.Nullable;
31import android.content.ComponentName;
32import android.content.Context;
33import android.content.pm.ParceledListSlice;
34import android.os.Bundle;
35import android.os.Handler;
36import android.os.IBinder;
37import android.os.IBinder.DeathRecipient;
38import android.os.RemoteException;
Felipe Leme1af85ea2019-01-16 13:23:40 -080039import android.util.LocalLog;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080040import android.util.Log;
41import android.util.TimeUtils;
42import android.view.autofill.AutofillId;
43import android.view.contentcapture.ViewNode.ViewStructureImpl;
44
45import com.android.internal.os.IResultReceiver;
46
47import java.io.PrintWriter;
48import java.util.ArrayList;
49import java.util.Collections;
50import java.util.List;
51import java.util.concurrent.atomic.AtomicBoolean;
52
53/**
54 * Main session associated with a context.
55 *
56 * <p>This session is created when the activity starts and finished when it stops; clients can use
57 * it to create children activities.
58 *
59 * <p><b>NOTE: all methods in this class should return right away, or do the real work in a handler
60 * thread. Hence, the only field that must be thread-safe is {@code mEnabled}, which is called at
61 * the beginning of every method.
62 *
63 * @hide
64 */
Felipe Leme87a9dc92018-12-18 14:28:07 -080065public final class MainContentCaptureSession extends ContentCaptureSession {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080066
Felipe Lemeaf1a0e72019-01-03 11:07:25 -080067 private static final String TAG = MainContentCaptureSession.class.getSimpleName();
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
Felipe Leme01b87492019-01-15 13:26:52 -080092 // TODO(b/111276913): make sure disabled state is in sync with manager's disabled
Felipe Lemeb63e0dd2018-12-18 11:56:42 -080093 @NonNull
94 private final AtomicBoolean mDisabled;
95
96 @NonNull
97 private final Context mContext;
98
99 @NonNull
100 private final Handler mHandler;
101
102 /**
103 * Interface to the system_server binder object - it's only used to start the session (and
104 * notify when the session is finished).
105 */
106 @Nullable
107 private final IContentCaptureManager mSystemServerInterface;
108
109 /**
110 * Direct interface to the service binder object - it's used to send the events, including the
111 * last ones (when the session is finished)
112 */
113 @Nullable
114 private IContentCaptureDirectManager mDirectServiceInterface;
115 @Nullable
116 private DeathRecipient mDirectServiceVulture;
117
Felipe Leme01b87492019-01-15 13:26:52 -0800118 private int mState = UNKNWON_STATE;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800119
120 @Nullable
121 private IBinder mApplicationToken;
122
123 @Nullable
124 private ComponentName mComponentName;
125
126 /**
127 * List of events held to be sent as a batch.
128 */
129 @Nullable
130 private ArrayList<ContentCaptureEvent> mEvents;
131
132 // Used just for debugging purposes (on dump)
133 private long mNextFlush;
134
Felipe Leme1af85ea2019-01-16 13:23:40 -0800135 // TODO(b/121044064): use settings to set size
136 private final LocalLog mFlushHistory = new LocalLog(10);
137
Felipe Leme87a9dc92018-12-18 14:28:07 -0800138 /** @hide */
139 protected MainContentCaptureSession(@NonNull Context context, @NonNull Handler handler,
140 @Nullable IContentCaptureManager systemServerInterface,
Felipe Leme01b87492019-01-15 13:26:52 -0800141 @NonNull boolean disabled) {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800142 mContext = context;
143 mHandler = handler;
144 mSystemServerInterface = systemServerInterface;
Felipe Leme01b87492019-01-15 13:26:52 -0800145 mDisabled = new AtomicBoolean(disabled);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800146 }
147
Felipe Leme87a9dc92018-12-18 14:28:07 -0800148 @Override
Felipe Leme4bc0f6b2019-01-03 19:01:07 -0800149 MainContentCaptureSession getMainCaptureSession() {
150 return this;
151 }
152
153 @Override
Felipe Leme87a9dc92018-12-18 14:28:07 -0800154 ContentCaptureSession newChild(@NonNull ContentCaptureContext clientContext) {
155 final ContentCaptureSession child = new ChildContentCaptureSession(this, clientContext);
156 notifyChildSessionStarted(mId, child.mId, clientContext);
157 return child;
158 }
159
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800160 /**
161 * Starts this session.
162 *
163 * @hide
164 */
Adam He328c0e32019-01-03 15:19:22 -0800165 void start(@NonNull IBinder applicationToken, @NonNull ComponentName activityComponent,
166 int flags) {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800167 if (!isContentCaptureEnabled()) return;
168
169 if (VERBOSE) {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800170 Log.v(TAG, "start(): token=" + applicationToken + ", comp="
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800171 + ComponentName.flattenToShortString(activityComponent));
172 }
173
Felipe Leme87a9dc92018-12-18 14:28:07 -0800174 mHandler.sendMessage(obtainMessage(MainContentCaptureSession::handleStartSession, this,
Adam He328c0e32019-01-03 15:19:22 -0800175 applicationToken, activityComponent, flags));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800176 }
177
178 @Override
Felipe Leme1af85ea2019-01-16 13:23:40 -0800179 void flush(@FlushReason int reason) {
180 mHandler.sendMessage(
181 obtainMessage(MainContentCaptureSession::handleForceFlush, this, reason));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800182 }
183
184 @Override
185 void onDestroy() {
Felipe Lemee127c9a2019-01-04 14:56:38 -0800186 mHandler.removeMessages(MSG_FLUSH);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800187 mHandler.sendMessage(
Felipe Leme87a9dc92018-12-18 14:28:07 -0800188 obtainMessage(MainContentCaptureSession::handleDestroySession, this));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800189 }
190
Adam He328c0e32019-01-03 15:19:22 -0800191 private void handleStartSession(@NonNull IBinder token, @NonNull ComponentName componentName,
192 int flags) {
Felipe Lemed65692c2019-01-16 12:10:50 -0800193 if (handleHasStarted()) {
194 // TODO(b/122959591): make sure this is expected (and when), or use Log.w
195 if (DEBUG) {
196 Log.d(TAG, "ignoring handleStartSession(" + token + "/"
197 + ComponentName.flattenToShortString(componentName) + " while on state "
198 + getStateAsString(mState));
199 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800200 return;
201 }
202 mState = STATE_WAITING_FOR_SERVER;
203 mApplicationToken = token;
204 mComponentName = componentName;
205
206 if (VERBOSE) {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800207 Log.v(TAG, "handleStartSession(): token=" + token + ", act="
Felipe Lemed65692c2019-01-16 12:10:50 -0800208 + getDebugState() + ", id=" + mId);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800209 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800210
211 try {
Adam He6884fed2019-01-07 13:18:32 -0800212 if (mSystemServerInterface == null) return;
213
Felipe Lemef2aa0d22019-01-28 10:38:46 -0800214 mSystemServerInterface.startSession(mApplicationToken, componentName, mId, flags,
215 new IResultReceiver.Stub() {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800216 @Override
217 public void send(int resultCode, Bundle resultData) {
218 IBinder binder = null;
219 if (resultData != null) {
220 binder = resultData.getBinder(EXTRA_BINDER);
221 if (binder == null) {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800222 Log.wtf(TAG, "No " + EXTRA_BINDER + " extra result");
Felipe Lemed65692c2019-01-16 12:10:50 -0800223 handleResetSession(STATE_DISABLED | STATE_INTERNAL_ERROR);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800224 return;
225 }
226 }
227 handleSessionStarted(resultCode, binder);
228 }
229 });
230 } catch (RemoteException e) {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800231 Log.w(TAG, "Error starting session for " + componentName.flattenToShortString() + ": "
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800232 + e);
233 }
234 }
235
236 /**
237 * Callback from {@code system_server} after call to
238 * {@link IContentCaptureManager#startSession(int, IBinder, ComponentName, String,
Felipe Lemebef744c2019-01-03 11:07:25 -0800239 * int, IResultReceiver)}.
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800240 *
241 * @param resultCode session state
242 * @param binder handle to {@code IContentCaptureDirectManager}
243 */
244 private void handleSessionStarted(int resultCode, @Nullable IBinder binder) {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800245 if (binder != null) {
246 mDirectServiceInterface = IContentCaptureDirectManager.Stub.asInterface(binder);
247 mDirectServiceVulture = () -> {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800248 Log.w(TAG, "Destroying session " + mId + " because service died");
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800249 destroy();
250 };
251 try {
252 binder.linkToDeath(mDirectServiceVulture, 0);
253 } catch (RemoteException e) {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800254 Log.w(TAG, "Failed to link to death on " + binder + ": " + e);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800255 }
256 }
Adam He328c0e32019-01-03 15:19:22 -0800257
Felipe Lemed65692c2019-01-16 12:10:50 -0800258 if ((resultCode & STATE_DISABLED) != 0) {
259 handleResetSession(resultCode);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800260 } else {
Felipe Lemed65692c2019-01-16 12:10:50 -0800261 mState = resultCode;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800262 mDisabled.set(false);
263 }
264 if (VERBOSE) {
Felipe Lemed65692c2019-01-16 12:10:50 -0800265 Log.v(TAG, "handleSessionStarted() result: id=" + mId + " resultCode=" + resultCode
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800266 + ", state=" + getStateAsString(mState) + ", disabled=" + mDisabled.get()
Felipe Lemee127c9a2019-01-04 14:56:38 -0800267 + ", binder=" + binder + ", events=" + (mEvents == null ? 0 : mEvents.size()));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800268 }
269 }
270
271 private void handleSendEvent(@NonNull ContentCaptureEvent event, boolean forceFlush) {
Felipe Leme1af85ea2019-01-16 13:23:40 -0800272 final int eventType = event.getType();
Felipe Lemebe002d82019-01-23 10:22:32 -0800273 if (VERBOSE) Log.v(TAG, "handleSendEvent(" + getDebugState() + "): " + event);
Felipe Leme1af85ea2019-01-16 13:23:40 -0800274 if (!handleHasStarted() && eventType != ContentCaptureEvent.TYPE_SESSION_STARTED) {
Felipe Lemed65692c2019-01-16 12:10:50 -0800275 // TODO(b/120494182): comment when this could happen (dialogs?)
276 Log.v(TAG, "handleSendEvent(" + getDebugState() + ", "
Felipe Leme1af85ea2019-01-16 13:23:40 -0800277 + ContentCaptureEvent.getTypeAsString(eventType)
Felipe Lemed65692c2019-01-16 12:10:50 -0800278 + "): session not started yet");
279 return;
280 }
Felipe Lemebe002d82019-01-23 10:22:32 -0800281 if (mDisabled.get()) {
282 // This happens when the event was queued in the handler before the sesison was ready,
283 // then handleSessionStarted() returned and set it as disabled - we need to drop it,
284 // otherwise it will keep triggering handleScheduleFlush()
285 if (VERBOSE) Log.v(TAG, "handleSendEvent(): ignoring when disabled");
286 return;
287 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800288 if (mEvents == null) {
289 if (VERBOSE) {
Felipe Lemebe002d82019-01-23 10:22:32 -0800290 Log.v(TAG, "handleSendEvent(): creating buffer for " + MAX_BUFFER_SIZE + " events");
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800291 }
292 mEvents = new ArrayList<>(MAX_BUFFER_SIZE);
293 }
Adam Heac132652019-01-02 14:40:15 -0800294
Felipe Leme48f363c2019-01-17 10:53:46 -0800295 // Some type of events can be merged together
296 boolean addEvent = true;
297
Felipe Leme1af85ea2019-01-16 13:23:40 -0800298 if (!mEvents.isEmpty() && eventType == TYPE_VIEW_TEXT_CHANGED) {
Adam Heac132652019-01-02 14:40:15 -0800299 final ContentCaptureEvent lastEvent = mEvents.get(mEvents.size() - 1);
300
301 // TODO(b/121045053): check if flags match
302 if (lastEvent.getType() == TYPE_VIEW_TEXT_CHANGED
303 && lastEvent.getId().equals(event.getId())) {
304 if (VERBOSE) {
Felipe Lemebe002d82019-01-23 10:22:32 -0800305 Log.v(TAG, "Buffering VIEW_TEXT_CHANGED event, updated text="
306 + getSanitizedString(event.getText()));
Adam Heac132652019-01-02 14:40:15 -0800307 }
308 lastEvent.setText(event.getText());
Felipe Leme48f363c2019-01-17 10:53:46 -0800309 addEvent = false;
Adam Heac132652019-01-02 14:40:15 -0800310 }
Felipe Leme48f363c2019-01-17 10:53:46 -0800311 }
312
313 if (!mEvents.isEmpty() && eventType == TYPE_VIEW_DISAPPEARED) {
314 final ContentCaptureEvent lastEvent = mEvents.get(mEvents.size() - 1);
315 if (lastEvent.getType() == TYPE_VIEW_DISAPPEARED
316 && event.getSessionId().equals(lastEvent.getSessionId())) {
317 if (VERBOSE) {
318 Log.v(TAG, "Buffering TYPE_VIEW_DISAPPEARED events for session "
319 + lastEvent.getSessionId());
320 }
321 lastEvent.addAutofillId(event.getId());
322 addEvent = false;
323 }
324 }
325
326 if (addEvent) {
Adam Heac132652019-01-02 14:40:15 -0800327 mEvents.add(event);
328 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800329
330 final int numberEvents = mEvents.size();
331
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800332 final boolean bufferEvent = numberEvents < MAX_BUFFER_SIZE;
333
334 if (bufferEvent && !forceFlush) {
Felipe Leme1af85ea2019-01-16 13:23:40 -0800335 handleScheduleFlush(FLUSH_REASON_IDLE_TIMEOUT, /* checkExisting= */ true);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800336 return;
337 }
338
Felipe Lemee127c9a2019-01-04 14:56:38 -0800339 if (mState != STATE_ACTIVE && numberEvents >= MAX_BUFFER_SIZE) {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800340 // Callback from startSession hasn't been called yet - typically happens on system
341 // apps that are started before the system service
Felipe Lemed65692c2019-01-16 12:10:50 -0800342 // TODO(b/122959591): try to ignore session while system is not ready / boot
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800343 // not complete instead. Similarly, the manager service should return right away
344 // when the user does not have a service set
Felipe Lemee127c9a2019-01-04 14:56:38 -0800345 if (DEBUG) {
Felipe Lemed65692c2019-01-16 12:10:50 -0800346 Log.d(TAG, "Closing session for " + getDebugState()
347 + " after " + numberEvents + " delayed events");
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800348 }
Felipe Lemed65692c2019-01-16 12:10:50 -0800349 handleResetSession(STATE_DISABLED | STATE_NO_RESPONSE);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800350 // TODO(b/111276913): blacklist activity / use special flag to indicate that
351 // when it's launched again
352 return;
353 }
Felipe Leme1af85ea2019-01-16 13:23:40 -0800354 final int flushReason;
355 switch (eventType) {
356 case ContentCaptureEvent.TYPE_SESSION_STARTED:
357 flushReason = FLUSH_REASON_SESSION_STARTED;
358 break;
359 case ContentCaptureEvent.TYPE_SESSION_FINISHED:
360 flushReason = FLUSH_REASON_SESSION_FINISHED;
361 break;
362 default:
363 flushReason = FLUSH_REASON_FULL;
364 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800365
Felipe Leme1af85ea2019-01-16 13:23:40 -0800366 handleForceFlush(flushReason);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800367 }
368
Felipe Lemed65692c2019-01-16 12:10:50 -0800369 private boolean handleHasStarted() {
370 return mState != UNKNWON_STATE;
371 }
372
Felipe Leme1af85ea2019-01-16 13:23:40 -0800373 private void handleScheduleFlush(@FlushReason int reason, boolean checkExisting) {
Felipe Lemebe002d82019-01-23 10:22:32 -0800374 if (VERBOSE) {
375 Log.v(TAG, "handleScheduleFlush(" + getDebugState(reason)
376 + ", checkExisting=" + checkExisting);
377 }
Felipe Lemed65692c2019-01-16 12:10:50 -0800378 if (!handleHasStarted()) {
Felipe Lemebe002d82019-01-23 10:22:32 -0800379 if (VERBOSE) Log.v(TAG, "handleScheduleFlush(): session not started yet");
380 return;
381 }
382
383 if (mDisabled.get()) {
384 // Should not be called on this state, as handleSendEvent checks.
385 // But we rather add one if check and log than re-schedule and keep the session alive...
386 Log.e(TAG, "handleScheduleFlush(" + getDebugState(reason) + "): should not be called "
387 + "when disabled. events=" + (mEvents == null ? null : mEvents.size()));
Felipe Lemed65692c2019-01-16 12:10:50 -0800388 return;
389 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800390 if (checkExisting && mHandler.hasMessages(MSG_FLUSH)) {
391 // "Renew" the flush message by removing the previous one
392 mHandler.removeMessages(MSG_FLUSH);
393 }
Felipe Leme1af85ea2019-01-16 13:23:40 -0800394 mNextFlush = System.currentTimeMillis() + FLUSHING_FREQUENCY_MS;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800395 if (VERBOSE) {
Felipe Lemebe002d82019-01-23 10:22:32 -0800396 Log.v(TAG, "handleScheduleFlush(): scheduled to flush in "
Felipe Leme1af85ea2019-01-16 13:23:40 -0800397 + FLUSHING_FREQUENCY_MS + "ms: " + TimeUtils.logTimeOfDay(mNextFlush));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800398 }
399 mHandler.sendMessageDelayed(
Felipe Leme1af85ea2019-01-16 13:23:40 -0800400 obtainMessage(MainContentCaptureSession::handleFlushIfNeeded, this, reason)
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800401 .setWhat(MSG_FLUSH), FLUSHING_FREQUENCY_MS);
402 }
403
Felipe Leme1af85ea2019-01-16 13:23:40 -0800404 private void handleFlushIfNeeded(@FlushReason int reason) {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800405 if (mEvents.isEmpty()) {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800406 if (VERBOSE) Log.v(TAG, "Nothing to flush");
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800407 return;
408 }
Felipe Leme1af85ea2019-01-16 13:23:40 -0800409 handleForceFlush(reason);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800410 }
411
Felipe Leme1af85ea2019-01-16 13:23:40 -0800412 private void handleForceFlush(@FlushReason int reason) {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800413 if (mEvents == null) return;
414
Felipe Lemebe002d82019-01-23 10:22:32 -0800415 if (mDisabled.get()) {
416 Log.e(TAG, "handleForceFlush(" + getDebugState(reason) + "): should not be when "
417 + "disabled");
418 return;
419 }
420
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800421 if (mDirectServiceInterface == null) {
Felipe Lemee127c9a2019-01-04 14:56:38 -0800422 if (VERBOSE) {
Felipe Lemebe002d82019-01-23 10:22:32 -0800423 Log.v(TAG, "handleForceFlush(" + getDebugState(reason) + "): hold your horses, "
424 + "client not ready: " + mEvents);
Felipe Lemee127c9a2019-01-04 14:56:38 -0800425 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800426 if (!mHandler.hasMessages(MSG_FLUSH)) {
Felipe Leme1af85ea2019-01-16 13:23:40 -0800427 handleScheduleFlush(reason, /* checkExisting= */ false);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800428 }
429 return;
430 }
431
432 final int numberEvents = mEvents.size();
Felipe Leme1af85ea2019-01-16 13:23:40 -0800433 final String reasonString = getflushReasonAsString(reason);
434 if (DEBUG) {
Felipe Lemebe002d82019-01-23 10:22:32 -0800435 Log.d(TAG, "Flushing " + numberEvents + " event(s) for " + getDebugState(reason));
Felipe Leme1af85ea2019-01-16 13:23:40 -0800436 }
437 // Logs reason, size, max size, idle timeout
438 final String logRecord = "r=" + reasonString + " s=" + numberEvents
439 + " m=" + MAX_BUFFER_SIZE + " i=" + FLUSHING_FREQUENCY_MS;
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800440 try {
Felipe Leme1af85ea2019-01-16 13:23:40 -0800441 mFlushHistory.log(logRecord);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800442 mHandler.removeMessages(MSG_FLUSH);
443
444 final ParceledListSlice<ContentCaptureEvent> events = handleClearEvents();
Felipe Lemefc24bea2018-12-18 13:19:01 -0800445 mDirectServiceInterface.sendEvents(events);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800446 } catch (RemoteException e) {
Felipe Lemed65692c2019-01-16 12:10:50 -0800447 Log.w(TAG, "Error sending " + numberEvents + " for " + getDebugState()
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800448 + ": " + e);
449 }
450 }
451
452 /**
453 * Resets the buffer and return a {@link ParceledListSlice} with the previous events.
454 */
455 @NonNull
456 private ParceledListSlice<ContentCaptureEvent> handleClearEvents() {
457 // NOTE: we must save a reference to the current mEvents and then set it to to null,
458 // otherwise clearing it would clear it in the receiving side if the service is also local.
459 final List<ContentCaptureEvent> events = mEvents == null
460 ? Collections.emptyList()
461 : mEvents;
462 mEvents = null;
463 return new ParceledListSlice<>(events);
464 }
465
466 private void handleDestroySession() {
467 if (DEBUG) {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800468 Log.d(TAG, "Destroying session (ctx=" + mContext + ", id=" + mId + ") with "
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800469 + (mEvents == null ? 0 : mEvents.size()) + " event(s) for "
Felipe Lemed65692c2019-01-16 12:10:50 -0800470 + getDebugState());
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800471 }
472
473 try {
Adam He6884fed2019-01-07 13:18:32 -0800474 if (mSystemServerInterface == null) return;
475
Felipe Lemef2aa0d22019-01-28 10:38:46 -0800476 mSystemServerInterface.finishSession(mId);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800477 } catch (RemoteException e) {
Felipe Lemeaf1a0e72019-01-03 11:07:25 -0800478 Log.e(TAG, "Error destroying system-service session " + mId + " for "
Felipe Lemed65692c2019-01-16 12:10:50 -0800479 + getDebugState() + ": " + e);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800480 }
481 }
482
Felipe Leme4bc0f6b2019-01-03 19:01:07 -0800483 // TODO(b/122454205): once we support multiple sessions, we might need to move some of these
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800484 // clearings out.
Felipe Lemed65692c2019-01-16 12:10:50 -0800485 private void handleResetSession(int newState) {
486 if (VERBOSE) {
487 Log.v(TAG, "handleResetSession(" + getActivityName() + "): from "
488 + getStateAsString(mState) + " to " + getStateAsString(newState));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800489 }
Felipe Lemed65692c2019-01-16 12:10:50 -0800490 mState = newState;
491 mDisabled.set((newState & STATE_DISABLED) != 0);
Felipe Leme4bc0f6b2019-01-03 19:01:07 -0800492 // TODO(b/122454205): must reset children (which currently is owned by superclass)
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800493 mApplicationToken = null;
494 mComponentName = null;
495 mEvents = null;
496 if (mDirectServiceInterface != null) {
497 mDirectServiceInterface.asBinder().unlinkToDeath(mDirectServiceVulture, 0);
498 }
499 mDirectServiceInterface = null;
500 mHandler.removeMessages(MSG_FLUSH);
501 }
502
503 @Override
504 void internalNotifyViewAppeared(@NonNull ViewStructureImpl node) {
Felipe Leme87a9dc92018-12-18 14:28:07 -0800505 notifyViewAppeared(mId, node);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800506 }
507
508 @Override
509 void internalNotifyViewDisappeared(@NonNull AutofillId id) {
Felipe Leme87a9dc92018-12-18 14:28:07 -0800510 notifyViewDisappeared(mId, id);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800511 }
512
513 @Override
Felipe Leme21e8dcb2019-01-18 09:09:45 -0800514 void internalNotifyViewTextChanged(@NonNull AutofillId id, @Nullable CharSequence text) {
515 notifyViewTextChanged(mId, id, text);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800516 }
517
518 @Override
519 boolean isContentCaptureEnabled() {
Felipe Lemebef744c2019-01-03 11:07:25 -0800520 return super.isContentCaptureEnabled() && mSystemServerInterface != null
521 && !mDisabled.get();
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800522 }
523
Felipe Leme4bc0f6b2019-01-03 19:01:07 -0800524 // TODO(b/122454205): refactor "notifyXXXX" methods below to a common "Buffer" object that is
Felipe Leme87a9dc92018-12-18 14:28:07 -0800525 // shared between ActivityContentCaptureSession and ChildContentCaptureSession objects. Such
526 // change should also get get rid of the "internalNotifyXXXX" methods above
527 void notifyChildSessionStarted(@NonNull String parentSessionId,
528 @NonNull String childSessionId, @NonNull ContentCaptureContext clientContext) {
529 mHandler.sendMessage(obtainMessage(MainContentCaptureSession::handleSendEvent, this,
530 new ContentCaptureEvent(childSessionId, TYPE_SESSION_STARTED)
531 .setParentSessionId(parentSessionId)
532 .setClientContext(clientContext),
Felipe Lemee127c9a2019-01-04 14:56:38 -0800533 /* forceFlush= */ true));
Felipe Leme87a9dc92018-12-18 14:28:07 -0800534 }
535
536 void notifyChildSessionFinished(@NonNull String parentSessionId,
537 @NonNull String childSessionId) {
538 mHandler.sendMessage(obtainMessage(MainContentCaptureSession::handleSendEvent, this,
539 new ContentCaptureEvent(childSessionId, TYPE_SESSION_FINISHED)
Felipe Lemee127c9a2019-01-04 14:56:38 -0800540 .setParentSessionId(parentSessionId), /* forceFlush= */ true));
Felipe Leme87a9dc92018-12-18 14:28:07 -0800541 }
542
543 void notifyViewAppeared(@NonNull String sessionId, @NonNull ViewStructureImpl node) {
544 mHandler.sendMessage(obtainMessage(MainContentCaptureSession::handleSendEvent, this,
545 new ContentCaptureEvent(sessionId, TYPE_VIEW_APPEARED)
546 .setViewNode(node.mNode), /* forceFlush= */ false));
547 }
548
549 void notifyViewDisappeared(@NonNull String sessionId, @NonNull AutofillId id) {
550 mHandler.sendMessage(obtainMessage(MainContentCaptureSession::handleSendEvent, this,
551 new ContentCaptureEvent(sessionId, TYPE_VIEW_DISAPPEARED).setAutofillId(id),
552 /* forceFlush= */ false));
553 }
554
555 void notifyViewTextChanged(@NonNull String sessionId, @NonNull AutofillId id,
Felipe Leme21e8dcb2019-01-18 09:09:45 -0800556 @Nullable CharSequence text) {
Felipe Leme87a9dc92018-12-18 14:28:07 -0800557 mHandler.sendMessage(obtainMessage(MainContentCaptureSession::handleSendEvent, this,
Felipe Leme21e8dcb2019-01-18 09:09:45 -0800558 new ContentCaptureEvent(sessionId, TYPE_VIEW_TEXT_CHANGED).setAutofillId(id)
Felipe Leme87a9dc92018-12-18 14:28:07 -0800559 .setText(text), /* forceFlush= */ false));
560 }
561
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800562 @Override
563 void dump(@NonNull String prefix, @NonNull PrintWriter pw) {
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800564 pw.print(prefix); pw.print("mContext: "); pw.println(mContext);
565 pw.print(prefix); pw.print("user: "); pw.println(mContext.getUserId());
566 if (mSystemServerInterface != null) {
567 pw.print(prefix); pw.print("mSystemServerInterface: ");
568 pw.println(mSystemServerInterface);
569 }
570 if (mDirectServiceInterface != null) {
571 pw.print(prefix); pw.print("mDirectServiceInterface: ");
572 pw.println(mDirectServiceInterface);
573 }
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800574 pw.print(prefix); pw.print("mDisabled: "); pw.println(mDisabled.get());
575 pw.print(prefix); pw.print("isEnabled(): "); pw.println(isContentCaptureEnabled());
Felipe Leme01b87492019-01-15 13:26:52 -0800576 pw.print(prefix); pw.print("state: "); pw.println(getStateAsString(mState));
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800577 if (mApplicationToken != null) {
578 pw.print(prefix); pw.print("app token: "); pw.println(mApplicationToken);
579 }
580 if (mComponentName != null) {
581 pw.print(prefix); pw.print("component name: ");
582 pw.println(mComponentName.flattenToShortString());
583 }
584 if (mEvents != null && !mEvents.isEmpty()) {
585 final int numberEvents = mEvents.size();
586 pw.print(prefix); pw.print("buffered events: "); pw.print(numberEvents);
587 pw.print('/'); pw.println(MAX_BUFFER_SIZE);
588 if (VERBOSE && numberEvents > 0) {
589 final String prefix3 = prefix + " ";
590 for (int i = 0; i < numberEvents; i++) {
591 final ContentCaptureEvent event = mEvents.get(i);
592 pw.print(prefix3); pw.print(i); pw.print(": "); event.dump(pw);
593 pw.println();
594 }
595 }
596 pw.print(prefix); pw.print("flush frequency: "); pw.println(FLUSHING_FREQUENCY_MS);
597 pw.print(prefix); pw.print("next flush: ");
Felipe Leme1af85ea2019-01-16 13:23:40 -0800598 TimeUtils.formatDuration(mNextFlush - System.currentTimeMillis(), pw);
599 pw.print(" ("); pw.print(TimeUtils.logTimeOfDay(mNextFlush)); pw.println(")");
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800600 }
Felipe Leme1af85ea2019-01-16 13:23:40 -0800601 pw.print(prefix); pw.println("flush history:");
602 mFlushHistory.reverseDump(/* fd= */ null, pw, /* args= */ null); pw.println();
603
Felipe Leme87a9dc92018-12-18 14:28:07 -0800604 super.dump(prefix, pw);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800605 }
606
607 /**
608 * Gets a string that can be used to identify the activity on logging statements.
609 */
Felipe Lemed65692c2019-01-16 12:10:50 -0800610 private String getActivityName() {
611 return mComponentName == null
612 ? "pkg:" + mContext.getPackageName()
613 : "act:" + mComponentName.flattenToShortString();
614 }
615
Felipe Lemebe002d82019-01-23 10:22:32 -0800616 @NonNull
Felipe Lemed65692c2019-01-16 12:10:50 -0800617 private String getDebugState() {
Felipe Lemebe002d82019-01-23 10:22:32 -0800618 return getActivityName() + " [state=" + getStateAsString(mState) + ", disabled="
619 + mDisabled.get() + "]";
620 }
621
622 @NonNull
623 private String getDebugState(@FlushReason int reason) {
624 return getDebugState() + ", reason=" + getflushReasonAsString(reason);
Felipe Lemeb63e0dd2018-12-18 11:56:42 -0800625 }
626}