Debian Codegraph @

core/java/android/app/search/SearchSession.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2020 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.app.search;
17
18 import android.annotation.CallbackExecutor;
19 import android.annotation.NonNull;
20 import android.annotation.Nullable;
21 import android.annotation.SystemApi;
22 import android.app.search.ISearchCallback.Stub;
23 import android.content.Context;
24 import android.content.pm.ParceledListSlice;
25 import android.os.Binder;
26 import android.os.Bundle;
27 import android.os.IBinder;
28 import android.os.RemoteException;
29 import android.os.ServiceManager;
30 import android.os.SystemClock;
31 import android.util.Log;
32
33 import dalvik.system.CloseGuard;
34
35 import java.util.List;
36 import java.util.UUID;
37 import java.util.concurrent.Executor;
38 import java.util.concurrent.atomic.AtomicBoolean;
39 import java.util.function.Consumer;
40
41 /**
42 * Client needs to create {@link SearchSession} object from in order to execute
43 * {@link #query(Query, Executor, Consumer)} method and share client side signals
44 * back to the service using {@link #notifyEvent(Query, SearchTargetEvent)}.
45 *
46 * <p>
47 * Usage: <pre> {@code
48 *
49 * class MyActivity {
50 *
51 * void onCreate() {
52 * mSearchSession.createSearchSession(searchContext)
53 * }
54 *
55 * void afterTextChanged(...) {
56 * mSearchSession.query(...);
57 * }
58 *
59 * void onTouch(...) OR
60 * void onStateTransitionStarted(...) OR
61 * void onResume(...) OR
62 * void onStop(...) {
63 * mSearchSession.notifyEvent(event);
64 * }
65 *
66 * void onDestroy() {
67 * mSearchSession.close();
68 * }
69 *
70 * }</pre>
71 *
72 * @hide
73 */
74 @SystemApi
75 public final class SearchSession implements AutoCloseable {
76
77 private static final String TAG = SearchSession.class.getSimpleName();
78 private static final boolean DEBUG = false;
79
80 private final android.app.search.ISearchUiManager mInterface;
81 private final CloseGuard mCloseGuard = CloseGuard.get();
82 private final AtomicBoolean mIsClosed = new AtomicBoolean(false);
83
84 private final SearchSessionId mSessionId;
85 private final IBinder mToken = new Binder();
86
87 /**
88 * Creates a new search ui client.
89 * <p>
90 * The caller should call {@link SearchSession#destroy()} to dispose the client once it
91 * no longer used.
92 *
93 * @param context the {@link Context} of the user of this {@link SearchSession}.
94 * @param searchContext the search context.
95 */
96 // b/175668315 Create weak reference child objects to not leak context.
97 SearchSession(@NonNull Context context, @NonNull SearchContext searchContext) {
98 IBinder b = ServiceManager.getService(Context.SEARCH_UI_SERVICE);
99 mInterface = android.app.search.ISearchUiManager.Stub.asInterface(b);
100 mSessionId = new SearchSessionId(
101 context.getPackageName() + ":" + UUID.randomUUID().toString(), context.getUserId());
102 // b/175527717 whitelist possible clients of this API
103 searchContext.setPackageName(context.getPackageName());
104 try {
105 mInterface.createSearchSession(searchContext, mSessionId, mToken);
106 } catch (RemoteException e) {
107 Log.e(TAG, "Failed to search session", e);
108 e.rethrowFromSystemServer();
109 }
110
111 mCloseGuard.open("SearchSession.close");
112 }
113
114 /**
115 * Notifies the search service of an search target event (e.g., user interaction
116 * and lifecycle event of the search surface).
117 *
118 * {@see SearchTargetEvent}
119 *
120 * @param query input object associated with the event.
121 * @param event The {@link SearchTargetEvent} that represents the search target event.
122 */
123 public void notifyEvent(@NonNull Query query, @NonNull SearchTargetEvent event) {
124 if (mIsClosed.get()) {
125 throw new IllegalStateException("This client has already been destroyed.");
126 }
127
128 try {
129 mInterface.notifyEvent(mSessionId, query, event);
130 } catch (RemoteException e) {
131 Log.e(TAG, "Failed to notify event", e);
132 e.rethrowFromSystemServer();
133 }
134 }
135
136 /**
137 * Calls consumer with list of {@link SearchTarget}s based on the input query.
138 *
139 * @param input query object to be used for the request.
140 * @param callbackExecutor The callback executor to use when calling the callback.
141 * @param callback The callback to return the list of search targets.
142 */
143 @Nullable
144 public void query(@NonNull Query input,
145 @NonNull @CallbackExecutor Executor callbackExecutor,
146 @NonNull Consumer<List<SearchTarget>> callback) {
147 if (mIsClosed.get()) {
148 throw new IllegalStateException("This client has already been destroyed.");
149 }
150
151 try {
152
153 mInterface.query(mSessionId, input, new CallbackWrapper(callbackExecutor, callback));
154 } catch (RemoteException e) {
155 Log.e(TAG, "Failed to sort targets", e);
156 e.rethrowFromSystemServer();
157 }
158 }
159
160 /**
161 * Destroys the client and unregisters the callback. Any method on this class after this call
162 * will throw {@link IllegalStateException}.
163 *
164 * @deprecated
165 * @removed
166 */
167 @Deprecated
168 public void destroy() {
169 if (!mIsClosed.getAndSet(true)) {
170 mCloseGuard.close();
171
172 // Do destroy;
173 try {
174 mInterface.destroySearchSession(mSessionId);
175 } catch (RemoteException e) {
176 Log.e(TAG, "Failed to notify search target event", e);
177 e.rethrowFromSystemServer();
178 }
179 } else {
180 throw new IllegalStateException("This client has already been destroyed.");
181 }
182 }
183
184 @Override
185 protected void finalize() {
186 try {
187 if (mCloseGuard != null) {
188 mCloseGuard.warnIfOpen();
189 }
190 if (!mIsClosed.get()) {
191 destroy();
192 }
193 } finally {
194 try {
195 super.finalize();
196 } catch (Throwable throwable) {
197 throwable.printStackTrace();
198 }
199 }
200 }
201
202 /**
203 * Destroys the client and unregisters the callback. Any method on this class after this call
204 * will throw {@link IllegalStateException}.
205 *
206 */
207 @Override
208 public void close() {
209 try {
210 finalize();
211 } catch (Throwable throwable) {
212 throwable.printStackTrace();
213 }
214 }
215
216 static class CallbackWrapper extends Stub {
217
218 private final Consumer<List<SearchTarget>> mCallback;
219 private final Executor mExecutor;
220
221 CallbackWrapper(@NonNull Executor callbackExecutor,
222 @NonNull Consumer<List<SearchTarget>> callback) {
223 mCallback = callback;
224 mExecutor = callbackExecutor;
225 }
226
227 @Override
228 public void onResult(ParceledListSlice result) {
229 final long identity = Binder.clearCallingIdentity();
230 try {
231 if (DEBUG) {
232 Log.d(TAG, "CallbackWrapper.onResult result=" + result.getList());
233 }
234 List<SearchTarget> list = result.getList();
235 if (list.size() > 0) {
236 Bundle bundle = list.get(0).getExtras();
237 if (bundle != null) {
238 bundle.putLong("key_ipc_start", SystemClock.elapsedRealtime());
239 }
240 }
241 mExecutor.execute(() -> mCallback.accept(list));
242 } finally {
243 Binder.restoreCallingIdentity(identity);
244 }
245 }
246 }
247 }