Debian Codegraph @

core/java/android/view/contentcapture/ContentCaptureManager.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package android.view.contentcapture;
17
18 import static android.view.contentcapture.ContentCaptureHelper.sDebug;
19 import static android.view.contentcapture.ContentCaptureHelper.sVerbose;
20 import static android.view.contentcapture.ContentCaptureHelper.toSet;
21
22 import android.annotation.CallbackExecutor;
23 import android.annotation.IntDef;
24 import android.annotation.NonNull;
25 import android.annotation.Nullable;
26 import android.annotation.RequiresPermission;
27 import android.annotation.SystemApi;
28 import android.annotation.SystemService;
29 import android.annotation.TestApi;
30 import android.annotation.UiThread;
31 import android.annotation.UserIdInt;
32 import android.app.Activity;
33 import android.app.Service;
34 import android.content.ComponentName;
35 import android.content.ContentCaptureOptions;
36 import android.content.Context;
37 import android.graphics.Canvas;
38 import android.os.Binder;
39 import android.os.Handler;
40 import android.os.IBinder;
41 import android.os.Looper;
42 import android.os.ParcelFileDescriptor;
43 import android.os.RemoteException;
44 import android.os.ServiceManager;
45 import android.util.Dumpable;
46 import android.util.Log;
47 import android.util.Slog;
48 import android.view.View;
49 import android.view.ViewStructure;
50 import android.view.WindowManager;
51 import android.view.contentcapture.ContentCaptureSession.FlushReason;
52
53 import com.android.internal.annotations.GuardedBy;
54 import com.android.internal.util.SyncResultReceiver;
55
56 import java.io.PrintWriter;
57 import java.lang.annotation.Retention;
58 import java.lang.annotation.RetentionPolicy;
59 import java.lang.ref.WeakReference;
60 import java.util.ArrayList;
61 import java.util.HashMap;
62 import java.util.Map;
63 import java.util.Objects;
64 import java.util.Set;
65 import java.util.concurrent.Executor;
66 import java.util.function.Consumer;
67
68 /**
69 * <p>The {@link ContentCaptureManager} provides additional ways for for apps to
70 * integrate with the content capture subsystem.
71 *
72 * <p>Content capture provides real-time, continuous capture of application activity, display and
73 * events to an intelligence service that is provided by the Android system. The intelligence
74 * service then uses that info to mediate and speed user journey through different apps. For
75 * example, when the user receives a restaurant address in a chat app and switches to a map app
76 * to search for that restaurant, the intelligence service could offer an autofill dialog to
77 * let the user automatically select its address.
78 *
79 * <p>Content capture was designed with two major concerns in mind: privacy and performance.
80 *
81 * <ul>
82 * <li><b>Privacy:</b> the intelligence service is a trusted component provided that is provided
83 * by the device manufacturer and that cannot be changed by the user (although the user can
84 * globaly disable content capture using the Android Settings app). This service can only use the
85 * data for in-device machine learning, which is enforced both by process isolation and
86 * <a href="https://source.android.com/compatibility/cdd">CDD requirements</a>.
87 * <li><b>Performance:</b> content capture is highly optimized to minimize its impact in the app
88 * jankiness and overall device system health. For example, its only enabled on apps (or even
89 * specific activities from an app) that were explicitly allowlisted by the intelligence service,
90 * and it buffers the events so they are sent in a batch to the service (see
91 * {@link #isContentCaptureEnabled()} for other cases when its disabled).
92 * </ul>
93 *
94 * <p>In fact, before using this manager, the app developer should check if it's available. Example:
95 * <pre><code>
96 * ContentCaptureManager mgr = context.getSystemService(ContentCaptureManager.class);
97 * if (mgr != null && mgr.isContentCaptureEnabled()) {
98 * // ...
99 * }
100 * </code></pre>
101 *
102 * <p>App developers usually don't need to explicitly interact with content capture, except when the
103 * app:
104 *
105 * <ul>
106 * <li>Can define a contextual {@link android.content.LocusId} to identify unique state (such as a
107 * conversation between 2 chat users).
108 * <li>Can have multiple view hierarchies with different contextual meaning (for example, a
109 * browser app with multiple tabs, each representing a different URL).
110 * <li>Contains custom views (that extend View directly and are not provided by the standard
111 * Android SDK.
112 * <li>Contains views that provide their own virtual hierarchy (like a web browser that render the
113 * HTML elements using a Canvas).
114 * </ul>
115 *
116 * <p>The main integration point with content capture is the {@link ContentCaptureSession}. A "main"
117 * session is automatically created by the Android System when content capture is enabled for the
118 * activity and its used by the standard Android views to notify the content capture service of
119 * events such as views being added, views been removed, and text changed by user input. The session
120 * could have a {@link ContentCaptureContext} to provide more contextual info about it, such as
121 * the locus associated with the view hierarchy (see {@link android.content.LocusId} for more info
122 * about locus). By default, the main session doesn't have a {@code ContentCaptureContext}, but you
123 * can change it after its created. Example:
124 *
125 * <pre><code>
126 * protected void onCreate(Bundle savedInstanceState) {
127 * // Initialize view structure
128 * ContentCaptureSession session = rootView.getContentCaptureSession();
129 * if (session != null) {
130 * session.setContentCaptureContext(ContentCaptureContext.forLocusId("chat_UserA_UserB"));
131 * }
132 * }
133 * </code></pre>
134 *
135 * <p>If your activity contains view hierarchies with a different contextual meaning, you should
136 * created child sessions for each view hierarchy root. For example, if your activity is a browser,
137 * you could use the main session for the main URL being rendered, then child sessions for each
138 * {@code IFRAME}:
139 *
140 * <pre><code>
141 * ContentCaptureSession mMainSession;
142 *
143 * protected void onCreate(Bundle savedInstanceState) {
144 * // Initialize view structure...
145 * mMainSession = rootView.getContentCaptureSession();
146 * if (mMainSession != null) {
147 * mMainSession.setContentCaptureContext(
148 * ContentCaptureContext.forLocusId("https://example.com"));
149 * }
150 * }
151 *
152 * private void loadIFrame(View iframeRootView, String url) {
153 * if (mMainSession != null) {
154 * ContentCaptureSession iFrameSession = mMainSession.newChild(
155 * ContentCaptureContext.forLocusId(url));
156 * }
157 * iframeRootView.setContentCaptureSession(iFrameSession);
158 * }
159 * // Load iframe...
160 * }
161 * </code></pre>
162 *
163 * <p>If your activity has custom views (i.e., views that extend {@link View} directly and provide
164 * just one logical view, not a virtual tree hiearchy) and it provides content that's relevant for
165 * content capture (as of {@link android.os.Build.VERSION_CODES#Q Android Q}, the only relevant
166 * content is text), then your view implementation should:
167 *
168 * <ul>
169 * <li>Set it as important for content capture.
170 * <li>Fill {@link ViewStructure} used for content capture.
171 * <li>Notify the {@link ContentCaptureSession} when the text is changed by user input.
172 * </ul>
173 *
174 * <p>Here's an example of the relevant methods for an {@code EditText}-like view:
175 *
176 * <pre><code>
177 * public class MyEditText extends View {
178 *
179 * public MyEditText(...) {
180 * if (getImportantForContentCapture() == IMPORTANT_FOR_CONTENT_CAPTURE_AUTO) {
181 * setImportantForContentCapture(IMPORTANT_FOR_CONTENT_CAPTURE_YES);
182 * }
183 * }
184 *
185 * public void onProvideContentCaptureStructure(@NonNull ViewStructure structure, int flags) {
186 * super.onProvideContentCaptureStructure(structure, flags);
187 *
188 * structure.setText(getText(), getSelectionStart(), getSelectionEnd());
189 * structure.setHint(getHint());
190 * structure.setInputType(getInputType());
191 * // set other properties like setTextIdEntry(), setTextLines(), setTextStyle(),
192 * // setMinTextEms(), setMaxTextEms(), setMaxTextLength()
193 * }
194 *
195 * private void onTextChanged() {
196 * if (isLaidOut() && isImportantForContentCapture() && isTextEditable()) {
197 * ContentCaptureManager mgr = mContext.getSystemService(ContentCaptureManager.class);
198 * if (cm != null && cm.isContentCaptureEnabled()) {
199 * ContentCaptureSession session = getContentCaptureSession();
200 * if (session != null) {
201 * session.notifyViewTextChanged(getAutofillId(), getText());
202 * }
203 * }
204 * }
205 * </code></pre>
206 *
207 * <p>If your view provides its own virtual hierarchy (for example, if it's a browser that draws
208 * the HTML using {@link Canvas} or native libraries in a different render process), then the view
209 * is also responsible to notify the session when the virtual elements appear and disappear - see
210 * {@link View#onProvideContentCaptureStructure(ViewStructure, int)} for more info.
211 */
212 @SystemService(Context.CONTENT_CAPTURE_MANAGER_SERVICE)
213 public final class ContentCaptureManager {
214
215 private static final String TAG = ContentCaptureManager.class.getSimpleName();
216
217 /** @hide */
218 public static final boolean DEBUG = false;
219
220 /** @hide */
221 @TestApi
222 public static final String DUMPABLE_NAME = "ContentCaptureManager";
223
224 /** Error happened during the data sharing session. */
225 public static final int DATA_SHARE_ERROR_UNKNOWN = 1;
226
227 /** Request has been rejected, because a concurrent data share sessions is in progress. */
228 public static final int DATA_SHARE_ERROR_CONCURRENT_REQUEST = 2;
229
230 /** Request has been interrupted because of data share session timeout. */
231 public static final int DATA_SHARE_ERROR_TIMEOUT_INTERRUPTED = 3;
232
233 /** @hide */
234 @IntDef(flag = false, value = {
235 DATA_SHARE_ERROR_UNKNOWN,
236 DATA_SHARE_ERROR_CONCURRENT_REQUEST,
237 DATA_SHARE_ERROR_TIMEOUT_INTERRUPTED
238 })
239 @Retention(RetentionPolicy.SOURCE)
240 public @interface DataShareError {}
241
242 /** @hide */
243 public static final int RESULT_CODE_OK = 0;
244 /** @hide */
245 public static final int RESULT_CODE_TRUE = 1;
246 /** @hide */
247 public static final int RESULT_CODE_FALSE = 2;
248 /** @hide */
249 public static final int RESULT_CODE_SECURITY_EXCEPTION = -1;
250
251 /**
252 * ID used to indicate that a session does not exist
253 * @hide
254 */
255 @SystemApi
256 public static final int NO_SESSION_ID = 0;
257
258 /**
259 * Timeout for calls to system_server.
260 */
261 private static final int SYNC_CALLS_TIMEOUT_MS = 5000;
262
263 /**
264 * DeviceConfig property used by {@code com.android.server.SystemServer} on start to decide
265 * whether the content capture service should be created or not
266 *
267 * <p>By default it should *NOT* be set (or set to {@code "default"}, so the decision is based
268 * on whether the OEM provides an implementation for the service), but it can be overridden to:
269 *
270 * <ul>
271 * <li>Provide a "kill switch" so OEMs can disable it remotely in case of emergency (when
272 * it's set to {@code "false"}).
273 * <li>Enable the CTS tests to be run on AOSP builds (when it's set to {@code "true"}).
274 * </ul>
275 *
276 * @hide
277 */
278 @TestApi
279 public static final String DEVICE_CONFIG_PROPERTY_SERVICE_EXPLICITLY_ENABLED =
280 "service_explicitly_enabled";
281
282 /**
283 * Device config property used by {@code android.widget.AbsListView} to determine whether or
284 * not it should report the positions of its children to Content Capture.
285 *
286 * @hide
287 */
288 public static final String DEVICE_CONFIG_PROPERTY_REPORT_LIST_VIEW_CHILDREN =
289 "report_list_view_children";
290
291 /**
292 * Maximum number of events that are buffered before sent to the app.
293 *
294 * @hide
295 */
296 @TestApi
297 public static final String DEVICE_CONFIG_PROPERTY_MAX_BUFFER_SIZE = "max_buffer_size";
298
299 /**
300 * Frequency (in ms) of buffer flushes when no events are received.
301 *
302 * @hide
303 */
304 @TestApi
305 public static final String DEVICE_CONFIG_PROPERTY_IDLE_FLUSH_FREQUENCY = "idle_flush_frequency";
306
307 /**
308 * Frequency (in ms) of buffer flushes when no events are received and the last one was a
309 * text change event.
310 *
311 * @hide
312 */
313 @TestApi
314 public static final String DEVICE_CONFIG_PROPERTY_TEXT_CHANGE_FLUSH_FREQUENCY =
315 "text_change_flush_frequency";
316
317 /**
318 * Size of events that are logging on {@code dump}.
319 *
320 * <p>Set it to {@code 0} or less to disable history.
321 *
322 * @hide
323 */
324 @TestApi
325 public static final String DEVICE_CONFIG_PROPERTY_LOG_HISTORY_SIZE = "log_history_size";
326
327 /**
328 * Sets the logging level for {@code logcat} statements.
329 *
330 * <p>Valid values are: {@link #LOGGING_LEVEL_OFF}, {@value #LOGGING_LEVEL_DEBUG}, and
331 * {@link #LOGGING_LEVEL_VERBOSE}.
332 *
333 * @hide
334 */
335 @TestApi
336 public static final String DEVICE_CONFIG_PROPERTY_LOGGING_LEVEL = "logging_level";
337
338 /**
339 * Sets how long (in ms) the service is bound while idle.
340 *
341 * <p>Use {@code 0} to keep it permanently bound.
342 *
343 * @hide
344 */
345 public static final String DEVICE_CONFIG_PROPERTY_IDLE_UNBIND_TIMEOUT = "idle_unbind_timeout";
346
347 /** @hide */
348 @TestApi
349 public static final int LOGGING_LEVEL_OFF = 0;
350
351 /** @hide */
352 @TestApi
353 public static final int LOGGING_LEVEL_DEBUG = 1;
354
355 /** @hide */
356 @TestApi
357 public static final int LOGGING_LEVEL_VERBOSE = 2;
358
359 /** @hide */
360 @IntDef(flag = false, value = {
361 LOGGING_LEVEL_OFF,
362 LOGGING_LEVEL_DEBUG,
363 LOGGING_LEVEL_VERBOSE
364 })
365 @Retention(RetentionPolicy.SOURCE)
366 public @interface LoggingLevel {}
367
368
369 /** @hide */
370 public static final int DEFAULT_MAX_BUFFER_SIZE = 500; // Enough for typical busy screen.
371 /** @hide */
372 public static final int DEFAULT_IDLE_FLUSHING_FREQUENCY_MS = 5_000;
373 /** @hide */
374 public static final int DEFAULT_TEXT_CHANGE_FLUSHING_FREQUENCY_MS = 1_000;
375 /** @hide */
376 public static final int DEFAULT_LOG_HISTORY_SIZE = 10;
377
378 private final Object mLock = new Object();
379
380 @NonNull
381 private final StrippedContext mContext;
382
383 @NonNull
384 private final IContentCaptureManager mService;
385
386 @GuardedBy("mLock")
387 private final LocalDataShareAdapterResourceManager mDataShareAdapterResourceManager;
388
389 @NonNull
390 final ContentCaptureOptions mOptions;
391
392 // Flags used for starting session.
393 @GuardedBy("mLock")
394 private int mFlags;
395
396 // TODO(b/119220549): use UI Thread directly (as calls are one-way) or a shared thread / handler
397 // held at the Application level
398 @NonNull
399 private final Handler mHandler;
400
401 @GuardedBy("mLock")
402 private MainContentCaptureSession mMainSession;
403
404 @Nullable // set on-demand by addDumpable()
405 private Dumper mDumpable;
406
407 /** @hide */
408 public interface ContentCaptureClient {
409 /**
410 * Gets the component name of the client.
411 */
412 @NonNull
413 ComponentName contentCaptureClientGetComponentName();
414 }
415
416 /** @hide */
417 static class StrippedContext {
418 final String mPackageName;
419 final String mContext;
420 final @UserIdInt int mUserId;
421
422 private StrippedContext(Context context) {
423 mPackageName = context.getPackageName();
424 mContext = context.toString();
425 mUserId = context.getUserId();
426 }
427
428 @Override
429 public String toString() {
430 return mContext;
431 }
432
433 public String getPackageName() {
434 return mPackageName;
435 }
436
437 @UserIdInt
438 public int getUserId() {
439 return mUserId;
440 }
441 }
442
443 /** @hide */
444 public ContentCaptureManager(@NonNull Context context,
445 @NonNull IContentCaptureManager service, @NonNull ContentCaptureOptions options) {
446 Objects.requireNonNull(context, "context cannot be null");
447 mContext = new StrippedContext(context);
448 mService = Objects.requireNonNull(service, "service cannot be null");
449 mOptions = Objects.requireNonNull(options, "options cannot be null");
450
451 ContentCaptureHelper.setLoggingLevel(mOptions.loggingLevel);
452
453 if (sVerbose) Log.v(TAG, "Constructor for " + context.getPackageName());
454
455 // TODO(b/119220549): we might not even need a handler, as the IPCs are oneway. But if we
456 // do, then we should optimize it to run the tests after the Choreographer finishes the most
457 // important steps of the frame.
458 mHandler = Handler.createAsync(Looper.getMainLooper());
459
460 mDataShareAdapterResourceManager = new LocalDataShareAdapterResourceManager();
461 }
462
463 /**
464 * Gets the main session associated with the context.
465 *
466 * <p>By default there's just one (associated with the activity lifecycle), but apps could
467 * explicitly add more using
468 * {@link ContentCaptureSession#createContentCaptureSession(ContentCaptureContext)}.
469 *
470 * @hide
471 */
472 @NonNull
473 @UiThread
474 public MainContentCaptureSession getMainContentCaptureSession() {
475 synchronized (mLock) {
476 if (mMainSession == null) {
477 mMainSession = new MainContentCaptureSession(mContext, this, mHandler, mService);
478 if (sVerbose) Log.v(TAG, "getMainContentCaptureSession(): created " + mMainSession);
479 }
480 return mMainSession;
481 }
482 }
483
484 /** @hide */
485 @UiThread
486 public void onActivityCreated(@NonNull IBinder applicationToken,
487 @NonNull IBinder shareableActivityToken, @NonNull ComponentName activityComponent) {
488 if (mOptions.lite) return;
489 synchronized (mLock) {
490 getMainContentCaptureSession().start(applicationToken, shareableActivityToken,
491 activityComponent, mFlags);
492 }
493 }
494
495 /** @hide */
496 @UiThread
497 public void onActivityResumed() {
498 if (mOptions.lite) return;
499 getMainContentCaptureSession().notifySessionResumed();
500 }
501
502 /** @hide */
503 @UiThread
504 public void onActivityPaused() {
505 if (mOptions.lite) return;
506 getMainContentCaptureSession().notifySessionPaused();
507 }
508
509 /** @hide */
510 @UiThread
511 public void onActivityDestroyed() {
512 if (mOptions.lite) return;
513 getMainContentCaptureSession().destroy();
514 }
515
516 /**
517 * Flushes the content of all sessions.
518 *
519 * <p>Typically called by {@code Activity} when it's paused / resumed.
520 *
521 * @hide
522 */
523 @UiThread
524 public void flush(@FlushReason int reason) {
525 if (mOptions.lite) return;
526 getMainContentCaptureSession().flush(reason);
527 }
528
529 /**
530 * Returns the component name of the system service that is consuming the captured events for
531 * the current user.
532 *
533 * @throws RuntimeException if getting the component name is timed out.
534 */
535 @Nullable
536 public ComponentName getServiceComponentName() {
537 if (!isContentCaptureEnabled() && !mOptions.lite) return null;
538
539 final SyncResultReceiver resultReceiver = new SyncResultReceiver(SYNC_CALLS_TIMEOUT_MS);
540 try {
541 mService.getServiceComponentName(resultReceiver);
542 return resultReceiver.getParcelableResult();
543 } catch (RemoteException e) {
544 throw e.rethrowFromSystemServer();
545 } catch (SyncResultReceiver.TimeoutException e) {
546 throw new RuntimeException("Fail to get service componentName.");
547 }
548 }
549
550 /**
551 * Gets the (optional) intent used to launch the service-specific settings.
552 *
553 * <p>This method is static because it's called by Settings, which might not be allowlisted
554 * for content capture (in which case the ContentCaptureManager on its context would be null).
555 *
556 * @hide
557 */
558 // TODO: use "lite" options as it's done by activities from the content capture service
559 @Nullable
560 public static ComponentName getServiceSettingsComponentName() {
561 final IBinder binder = ServiceManager
562 .checkService(Context.CONTENT_CAPTURE_MANAGER_SERVICE);
563 if (binder == null) return null;
564
565 final IContentCaptureManager service = IContentCaptureManager.Stub.asInterface(binder);
566 final SyncResultReceiver resultReceiver = new SyncResultReceiver(SYNC_CALLS_TIMEOUT_MS);
567 try {
568 service.getServiceSettingsActivity(resultReceiver);
569 final int resultCode = resultReceiver.getIntResult();
570 if (resultCode == RESULT_CODE_SECURITY_EXCEPTION) {
571 throw new SecurityException(resultReceiver.getStringResult());
572 }
573 return resultReceiver.getParcelableResult();
574 } catch (RemoteException e) {
575 throw e.rethrowFromSystemServer();
576 } catch (SyncResultReceiver.TimeoutException e) {
577 Log.e(TAG, "Fail to get service settings componentName: " + e);
578 return null;
579 }
580 }
581
582 /**
583 * Checks whether content capture is enabled for this activity.
584 *
585 * <p>There are many reasons it could be disabled, such as:
586 * <ul>
587 * <li>App itself disabled content capture through {@link #setContentCaptureEnabled(boolean)}.
588 * <li>Intelligence service did not allowlist content capture for this activity's package.
589 * <li>Intelligence service did not allowlist content capture for this specific activity.
590 * <li>Intelligence service disabled content capture globally.
591 * <li>User disabled content capture globally through the Android Settings app.
592 * <li>Device manufacturer (OEM) disabled content capture globally.
593 * <li>Transient errors, such as intelligence service package being updated.
594 * </ul>
595 */
596 public boolean isContentCaptureEnabled() {
597 if (mOptions.lite) return false;
598
599 final MainContentCaptureSession mainSession;
600 synchronized (mLock) {
601 mainSession = mMainSession;
602 }
603 // The main session is only set when the activity starts, so we need to return true until
604 // then.
605 if (mainSession != null && mainSession.isDisabled()) return false;
606
607 return true;
608 }
609
610 /**
611 * Gets the list of conditions for when content capture should be allowed.
612 *
613 * <p>This method is typically used by web browsers so they don't generate unnecessary content
614 * capture events for websites the content capture service is not interested on.
615 *
616 * @return list of conditions, or {@code null} if the service didn't set any restriction
617 * (in which case content capture events should always be generated). If the list is empty,
618 * then it should not generate any event at all.
619 */
620 @Nullable
621 public Set<ContentCaptureCondition> getContentCaptureConditions() {
622 // NOTE: we could cache the conditions on ContentCaptureOptions, but then it would be stick
623 // to the lifetime of the app. OTOH, by dynamically calling the server every time, we allow
624 // the service to fine tune how long-lived apps (like browsers) are allowlisted.
625 if (!isContentCaptureEnabled() && !mOptions.lite) return null;
626
627 final SyncResultReceiver resultReceiver = syncRun(
628 (r) -> mService.getContentCaptureConditions(mContext.getPackageName(), r));
629
630 try {
631 final ArrayList<ContentCaptureCondition> result = resultReceiver
632 .getParcelableListResult();
633 return toSet(result);
634 } catch (SyncResultReceiver.TimeoutException e) {
635 throw new RuntimeException("Fail to get content capture conditions.");
636 }
637 }
638
639 /**
640 * Called by apps to explicitly enable or disable content capture.
641 *
642 * <p><b>Note: </b> this call is not persisted accross reboots, so apps should typically call
643 * it on {@link android.app.Activity#onCreate(android.os.Bundle, android.os.PersistableBundle)}.
644 */
645 public void setContentCaptureEnabled(boolean enabled) {
646 if (sDebug) {
647 Log.d(TAG, "setContentCaptureEnabled(): setting to " + enabled + " for " + mContext);
648 }
649
650 MainContentCaptureSession mainSession;
651 synchronized (mLock) {
652 if (enabled) {
653 mFlags &= ~ContentCaptureContext.FLAG_DISABLED_BY_APP;
654 } else {
655 mFlags |= ContentCaptureContext.FLAG_DISABLED_BY_APP;
656 }
657 mainSession = mMainSession;
658 }
659 if (mainSession != null) {
660 mainSession.setDisabled(!enabled);
661 }
662 }
663
664 /**
665 * Called by apps to update flag secure when window attributes change.
666 *
667 * @hide
668 */
669 public void updateWindowAttributes(@NonNull WindowManager.LayoutParams params) {
670 if (sDebug) {
671 Log.d(TAG, "updateWindowAttributes(): window flags=" + params.flags);
672 }
673 final boolean flagSecureEnabled =
674 (params.flags & WindowManager.LayoutParams.FLAG_SECURE) != 0;
675
676 MainContentCaptureSession mainSession;
677 synchronized (mLock) {
678 if (flagSecureEnabled) {
679 mFlags |= ContentCaptureContext.FLAG_DISABLED_BY_FLAG_SECURE;
680 } else {
681 mFlags &= ~ContentCaptureContext.FLAG_DISABLED_BY_FLAG_SECURE;
682 }
683 mainSession = mMainSession;
684 }
685 if (mainSession != null) {
686 mainSession.setDisabled(flagSecureEnabled);
687 }
688 }
689
690 /**
691 * Gets whether content capture is enabled for the given user.
692 *
693 * <p>This method is typically used by the content capture service settings page, so it can
694 * provide a toggle to enable / disable it.
695 *
696 * @throws SecurityException if caller is not the app that owns the content capture service
697 * associated with the user.
698 *
699 * @hide
700 */
701 @SystemApi
702 public boolean isContentCaptureFeatureEnabled() {
703 final SyncResultReceiver resultReceiver = syncRun(
704 (r) -> mService.isContentCaptureFeatureEnabled(r));
705
706 try {
707 final int resultCode = resultReceiver.getIntResult();
708 switch (resultCode) {
709 case RESULT_CODE_TRUE:
710 return true;
711 case RESULT_CODE_FALSE:
712 return false;
713 default:
714 Log.wtf(TAG, "received invalid result: " + resultCode);
715 return false;
716 }
717 } catch (SyncResultReceiver.TimeoutException e) {
718 Log.e(TAG, "Fail to get content capture feature enable status: " + e);
719 return false;
720 }
721 }
722
723 /**
724 * Called by the app to request the content capture service to remove content capture data
725 * associated with some context.
726 *
727 * @param request object specifying what user data should be removed.
728 */
729 public void removeData(@NonNull DataRemovalRequest request) {
730 Objects.requireNonNull(request);
731
732 try {
733 mService.removeData(request);
734 } catch (RemoteException e) {
735 throw e.rethrowFromSystemServer();
736 }
737 }
738
739 /**
740 * Called by the app to request data sharing via writing to a file.
741 *
742 * <p>The ContentCaptureService app will receive a read-only file descriptor pointing to the
743 * same file and will be able to read data being shared from it.
744 *
745 * <p>Note: using this API doesn't guarantee the app staying alive and is "best-effort".
746 * Starting a foreground service would minimize the chances of the app getting killed during the
747 * file sharing session.
748 *
749 * @param request object specifying details of the data being shared.
750 */
751 public void shareData(@NonNull DataShareRequest request,
752 @NonNull @CallbackExecutor Executor executor,
753 @NonNull DataShareWriteAdapter dataShareWriteAdapter) {
754 Objects.requireNonNull(request);
755 Objects.requireNonNull(dataShareWriteAdapter);
756 Objects.requireNonNull(executor);
757
758 try {
759 mService.shareData(request,
760 new DataShareAdapterDelegate(executor, dataShareWriteAdapter,
761 mDataShareAdapterResourceManager));
762 } catch (RemoteException e) {
763 throw e.rethrowFromSystemServer();
764 }
765 }
766
767 /**
768 * Runs a sync method in the service, properly handling exceptions.
769 *
770 * @throws SecurityException if caller is not allowed to execute the method.
771 */
772 @NonNull
773 private SyncResultReceiver syncRun(@NonNull MyRunnable r) {
774 final SyncResultReceiver resultReceiver = new SyncResultReceiver(SYNC_CALLS_TIMEOUT_MS);
775 try {
776 r.run(resultReceiver);
777 final int resultCode = resultReceiver.getIntResult();
778 if (resultCode == RESULT_CODE_SECURITY_EXCEPTION) {
779 throw new SecurityException(resultReceiver.getStringResult());
780 }
781 } catch (RemoteException e) {
782 throw e.rethrowFromSystemServer();
783 } catch (SyncResultReceiver.TimeoutException e) {
784 throw new RuntimeException("Fail to get syn run result from SyncResultReceiver.");
785 }
786 return resultReceiver;
787 }
788
789 /** @hide */
790 public void addDumpable(Activity activity) {
791 if (mDumpable == null) {
792 mDumpable = new Dumper();
793 }
794 activity.addDumpable(mDumpable);
795 }
796
797 // NOTE: ContentCaptureManager cannot implement it directly as it would be exposed as public API
798 private final class Dumper implements Dumpable {
799 @Override
800 public void dump(@NonNull PrintWriter pw, @Nullable String[] args) {
801 String prefix = "";
802 pw.print(prefix); pw.println("ContentCaptureManager");
803 final String prefix2 = prefix + " ";
804 synchronized (mLock) {
805 pw.print(prefix2); pw.print("isContentCaptureEnabled(): ");
806 pw.println(isContentCaptureEnabled());
807 pw.print(prefix2); pw.print("Debug: "); pw.print(sDebug);
808 pw.print(" Verbose: "); pw.println(sVerbose);
809 pw.print(prefix2); pw.print("Context: "); pw.println(mContext);
810 pw.print(prefix2); pw.print("User: "); pw.println(mContext.getUserId());
811 pw.print(prefix2); pw.print("Service: "); pw.println(mService);
812 pw.print(prefix2); pw.print("Flags: "); pw.println(mFlags);
813 pw.print(prefix2); pw.print("Options: "); mOptions.dumpShort(pw); pw.println();
814 if (mMainSession != null) {
815 final String prefix3 = prefix2 + " ";
816 pw.print(prefix2); pw.println("Main session:");
817 mMainSession.dump(prefix3, pw);
818 } else {
819 pw.print(prefix2); pw.println("No sessions");
820 }
821 }
822 }
823
824 @Override
825 public String getDumpableName() {
826 return DUMPABLE_NAME;
827 }
828 }
829
830 /**
831 * Resets the temporary content capture service implementation to the default component.
832 *
833 * @hide
834 */
835 @TestApi
836 @RequiresPermission(android.Manifest.permission.MANAGE_CONTENT_CAPTURE)
837 public static void resetTemporaryService(@UserIdInt int userId) {
838 final IContentCaptureManager service = getService();
839 if (service == null) {
840 Log.e(TAG, "IContentCaptureManager is null");
841 }
842 try {
843 service.resetTemporaryService(userId);
844 } catch (RemoteException e) {
845 throw e.rethrowFromSystemServer();
846 }
847 }
848
849 /**
850 * Temporarily sets the content capture service implementation.
851 *
852 * @param userId user Id to set the temporary service on.
853 * @param serviceName name of the new component
854 * @param duration how long the change will be valid (the service will be automatically reset
855 * to the default component after this timeout expires).
856 *
857 * @hide
858 */
859 @TestApi
860 @RequiresPermission(android.Manifest.permission.MANAGE_CONTENT_CAPTURE)
861 public static void setTemporaryService(
862 @UserIdInt int userId, @NonNull String serviceName, int duration) {
863 final IContentCaptureManager service = getService();
864 if (service == null) {
865 Log.e(TAG, "IContentCaptureManager is null");
866 }
867 try {
868 service.setTemporaryService(userId, serviceName, duration);
869 } catch (RemoteException e) {
870 throw e.rethrowFromSystemServer();
871 }
872 }
873
874 /**
875 * Sets whether the default content capture service should be used.
876 *
877 * @hide
878 */
879 @TestApi
880 @RequiresPermission(android.Manifest.permission.MANAGE_CONTENT_CAPTURE)
881 public static void setDefaultServiceEnabled(@UserIdInt int userId, boolean enabled) {
882 final IContentCaptureManager service = getService();
883 if (service == null) {
884 Log.e(TAG, "IContentCaptureManager is null");
885 }
886 try {
887 service.setDefaultServiceEnabled(userId, enabled);
888 } catch (RemoteException e) {
889 throw e.rethrowFromSystemServer();
890 }
891 }
892
893 private static IContentCaptureManager getService() {
894 return IContentCaptureManager.Stub.asInterface(ServiceManager.getService(
895 Service.CONTENT_CAPTURE_MANAGER_SERVICE));
896 }
897
898 private interface MyRunnable {
899 void run(@NonNull SyncResultReceiver receiver) throws RemoteException;
900 }
901
902 private static class DataShareAdapterDelegate extends IDataShareWriteAdapter.Stub {
903
904 private final WeakReference<LocalDataShareAdapterResourceManager> mResourceManagerReference;
905
906 private DataShareAdapterDelegate(Executor executor, DataShareWriteAdapter adapter,
907 LocalDataShareAdapterResourceManager resourceManager) {
908 Objects.requireNonNull(executor);
909 Objects.requireNonNull(adapter);
910 Objects.requireNonNull(resourceManager);
911
912 resourceManager.initializeForDelegate(this, adapter, executor);
913 mResourceManagerReference = new WeakReference<>(resourceManager);
914 }
915
916 @Override
917 public void write(ParcelFileDescriptor destination)
918 throws RemoteException {
919 executeAdapterMethodLocked(adapter -> adapter.onWrite(destination), "onWrite");
920 }
921
922 @Override
923 public void error(int errorCode) throws RemoteException {
924 executeAdapterMethodLocked(adapter -> adapter.onError(errorCode), "onError");
925 clearHardReferences();
926 }
927
928 @Override
929 public void rejected() throws RemoteException {
930 executeAdapterMethodLocked(DataShareWriteAdapter::onRejected, "onRejected");
931 clearHardReferences();
932 }
933
934 @Override
935 public void finish() throws RemoteException {
936 clearHardReferences();
937 }
938
939 private void executeAdapterMethodLocked(Consumer<DataShareWriteAdapter> adapterFn,
940 String methodName) {
941 LocalDataShareAdapterResourceManager resourceManager = mResourceManagerReference.get();
942 if (resourceManager == null) {
943 Slog.w(TAG, "Can't execute " + methodName + "(), resource manager has been GC'ed");
944 return;
945 }
946
947 DataShareWriteAdapter adapter = resourceManager.getAdapter(this);
948 Executor executor = resourceManager.getExecutor(this);
949
950 if (adapter == null || executor == null) {
951 Slog.w(TAG, "Can't execute " + methodName + "(), references are null");
952 return;
953 }
954
955 final long identity = Binder.clearCallingIdentity();
956 try {
957 executor.execute(() -> adapterFn.accept(adapter));
958 } finally {
959 Binder.restoreCallingIdentity(identity);
960 }
961 }
962
963 private void clearHardReferences() {
964 LocalDataShareAdapterResourceManager resourceManager = mResourceManagerReference.get();
965 if (resourceManager == null) {
966 Slog.w(TAG, "Can't clear references, resource manager has been GC'ed");
967 return;
968 }
969
970 resourceManager.clearHardReferences(this);
971 }
972 }
973
974 /**
975 * Wrapper class making sure dependencies on the current application stay in the application
976 * context.
977 */
978 private static class LocalDataShareAdapterResourceManager {
979
980 // Keeping hard references to the remote objects in the current process (static context)
981 // to prevent them to be gc'ed during the lifetime of the application. This is an
982 // artifact of only operating with weak references remotely: there has to be at least 1
983 // hard reference in order for this to not be killed.
984 private Map<DataShareAdapterDelegate, DataShareWriteAdapter> mWriteAdapterHardReferences =
985 new HashMap<>();
986 private Map<DataShareAdapterDelegate, Executor> mExecutorHardReferences =
987 new HashMap<>();
988
989 void initializeForDelegate(DataShareAdapterDelegate delegate, DataShareWriteAdapter adapter,
990 Executor executor) {
991 mWriteAdapterHardReferences.put(delegate, adapter);
992 mExecutorHardReferences.put(delegate, executor);
993 }
994
995 Executor getExecutor(DataShareAdapterDelegate delegate) {
996 return mExecutorHardReferences.get(delegate);
997 }
998
999 DataShareWriteAdapter getAdapter(DataShareAdapterDelegate delegate) {
1000 return mWriteAdapterHardReferences.get(delegate);
1001 }
1002
1003 void clearHardReferences(DataShareAdapterDelegate delegate) {
1004 mWriteAdapterHardReferences.remove(delegate);
1005 mExecutorHardReferences.remove(delegate);
1006 }
1007 }
1008 }