blob: f24d8cd0d3b57e2293b9ef77d5e807947f50dd0d [file] [log] [blame]
satok988323c2011-06-22 16:38:13 +09001/*
2 * Copyright (C) 2011 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
17package com.android.server;
18
Yohei Yukawa3f8c5682018-03-01 13:10:23 -080019import static android.view.textservice.TextServicesManager.DISABLE_PER_PROFILE_SPELL_CHECKER;
20
21import com.android.internal.annotations.GuardedBy;
satok988323c2011-06-22 16:38:13 +090022import com.android.internal.content.PackageMonitor;
Yohei Yukawa174843a2015-06-26 18:02:54 -070023import com.android.internal.inputmethod.InputMethodUtils;
satok988323c2011-06-22 16:38:13 +090024import com.android.internal.textservice.ISpellCheckerService;
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -080025import com.android.internal.textservice.ISpellCheckerServiceCallback;
satok988323c2011-06-22 16:38:13 +090026import com.android.internal.textservice.ISpellCheckerSession;
27import com.android.internal.textservice.ISpellCheckerSessionListener;
28import com.android.internal.textservice.ITextServicesManager;
29import com.android.internal.textservice.ITextServicesSessionListener;
Yohei Yukawa3f8c5682018-03-01 13:10:23 -080030import com.android.internal.textservice.LazyIntToIntMap;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060031import com.android.internal.util.DumpUtils;
satok988323c2011-06-22 16:38:13 +090032
satok03b2ea12011-08-03 17:36:14 +090033import org.xmlpull.v1.XmlPullParserException;
34
Yohei Yukawaf0f16802016-03-08 16:04:58 -080035import android.annotation.NonNull;
Yohei Yukawa08ce1872016-03-16 17:22:30 -070036import android.annotation.Nullable;
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -080037import android.annotation.UserIdInt;
satok988323c2011-06-22 16:38:13 +090038import android.content.ComponentName;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090039import android.content.ContentResolver;
satok988323c2011-06-22 16:38:13 +090040import android.content.Context;
41import android.content.Intent;
42import android.content.ServiceConnection;
Guliz Tuncay0f0a37b2017-08-16 12:02:31 -070043import android.content.pm.ApplicationInfo;
satok988323c2011-06-22 16:38:13 +090044import android.content.pm.PackageManager;
45import android.content.pm.ResolveInfo;
46import android.content.pm.ServiceInfo;
Guliz Tuncay06a26242017-06-30 18:32:04 -070047import android.content.pm.UserInfo;
satok6be6d752011-07-28 20:40:38 +090048import android.os.Binder;
satok53578062011-08-03 16:08:59 +090049import android.os.Bundle;
satok988323c2011-06-22 16:38:13 +090050import android.os.IBinder;
Guliz Tuncayf982e752017-06-14 09:33:16 -070051import android.os.RemoteCallbackList;
satok988323c2011-06-22 16:38:13 +090052import android.os.RemoteException;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090053import android.os.UserHandle;
Yohei Yukawa095fa372014-10-27 14:02:23 +090054import android.os.UserManager;
satok988323c2011-06-22 16:38:13 +090055import android.provider.Settings;
satok988323c2011-06-22 16:38:13 +090056import android.service.textservice.SpellCheckerService;
satok53578062011-08-03 16:08:59 +090057import android.text.TextUtils;
satok988323c2011-06-22 16:38:13 +090058import android.util.Slog;
Guliz Tuncay06a26242017-06-30 18:32:04 -070059import android.util.SparseArray;
satok05f24702011-11-02 19:29:35 +090060import android.view.inputmethod.InputMethodManager;
61import android.view.inputmethod.InputMethodSubtype;
satok988323c2011-06-22 16:38:13 +090062import android.view.textservice.SpellCheckerInfo;
satokada8c4e2011-08-23 14:56:56 +090063import android.view.textservice.SpellCheckerSubtype;
satok988323c2011-06-22 16:38:13 +090064
Dianne Hackborn71e14da2011-10-16 16:28:10 -070065import java.io.FileDescriptor;
satok03b2ea12011-08-03 17:36:14 +090066import java.io.IOException;
Dianne Hackborn71e14da2011-10-16 16:28:10 -070067import java.io.PrintWriter;
Yohei Yukawa174843a2015-06-26 18:02:54 -070068import java.util.Arrays;
satok988323c2011-06-22 16:38:13 +090069import java.util.ArrayList;
70import java.util.HashMap;
satok988323c2011-06-22 16:38:13 +090071import java.util.List;
Yohei Yukawa174843a2015-06-26 18:02:54 -070072import java.util.Locale;
Dianne Hackborn71e14da2011-10-16 16:28:10 -070073import java.util.Map;
Yohei Yukawa73ac9472018-05-01 11:40:29 -070074import java.util.function.Predicate;
satok988323c2011-06-22 16:38:13 +090075
76public class TextServicesManagerService extends ITextServicesManager.Stub {
77 private static final String TAG = TextServicesManagerService.class.getSimpleName();
78 private static final boolean DBG = false;
79
80 private final Context mContext;
satok988323c2011-06-22 16:38:13 +090081 private final TextServicesMonitor mMonitor;
Guliz Tuncay06a26242017-06-30 18:32:04 -070082 private final SparseArray<TextServicesData> mUserData = new SparseArray<>();
Yohei Yukawaf0f16802016-03-08 16:04:58 -080083 @NonNull
84 private final UserManager mUserManager;
Guliz Tuncay10ae3852017-07-07 10:35:59 -070085 private final Object mLock = new Object();
satok988323c2011-06-22 16:38:13 +090086
Yohei Yukawa3f8c5682018-03-01 13:10:23 -080087 @NonNull
88 @GuardedBy("mLock")
89 private final LazyIntToIntMap mSpellCheckerOwnerUserIdMap;
90
Guliz Tuncay06a26242017-06-30 18:32:04 -070091 private static class TextServicesData {
92 @UserIdInt
93 private final int mUserId;
94 private final HashMap<String, SpellCheckerInfo> mSpellCheckerMap;
95 private final ArrayList<SpellCheckerInfo> mSpellCheckerList;
96 private final HashMap<String, SpellCheckerBindGroup> mSpellCheckerBindGroups;
Guliz Tuncay8e6fa022017-08-14 16:50:15 -070097 private final Context mContext;
98 private final ContentResolver mResolver;
99 public int mUpdateCount = 0;
Guliz Tuncay06a26242017-06-30 18:32:04 -0700100
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700101 public TextServicesData(@UserIdInt int userId, @NonNull Context context) {
Guliz Tuncay06a26242017-06-30 18:32:04 -0700102 mUserId = userId;
103 mSpellCheckerMap = new HashMap<>();
104 mSpellCheckerList = new ArrayList<>();
105 mSpellCheckerBindGroups = new HashMap<>();
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700106 mContext = context;
107 mResolver = context.getContentResolver();
108 }
109
110 private void putString(final String key, final String str) {
111 Settings.Secure.putStringForUser(mResolver, key, str, mUserId);
112 }
113
114 @Nullable
115 private String getString(@NonNull final String key, @Nullable final String defaultValue) {
116 final String result;
117 result = Settings.Secure.getStringForUser(mResolver, key, mUserId);
118 return result != null ? result : defaultValue;
119 }
120
121 private void putInt(final String key, final int value) {
122 Settings.Secure.putIntForUser(mResolver, key, value, mUserId);
123 }
124
125 private int getInt(final String key, final int defaultValue) {
126 return Settings.Secure.getIntForUser(mResolver, key, defaultValue, mUserId);
127 }
128
129 private boolean getBoolean(final String key, final boolean defaultValue) {
130 return getInt(key, defaultValue ? 1 : 0) == 1;
131 }
132
133 private void putSelectedSpellChecker(@Nullable String sciId) {
Guliz Tuncay83a73302017-08-17 15:25:38 -0700134 putString(Settings.Secure.SELECTED_SPELL_CHECKER, sciId);
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700135 }
136
137 private void putSelectedSpellCheckerSubtype(int hashCode) {
138 putInt(Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, hashCode);
139 }
140
141 @NonNull
142 private String getSelectedSpellChecker() {
143 return getString(Settings.Secure.SELECTED_SPELL_CHECKER, "");
144 }
145
146 public int getSelectedSpellCheckerSubtype(final int defaultValue) {
147 return getInt(Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, defaultValue);
148 }
149
150 public boolean isSpellCheckerEnabled() {
151 return getBoolean(Settings.Secure.SPELL_CHECKER_ENABLED, true);
152 }
153
154 @Nullable
155 public SpellCheckerInfo getCurrentSpellChecker() {
156 final String curSpellCheckerId = getSelectedSpellChecker();
157 if (TextUtils.isEmpty(curSpellCheckerId)) {
158 return null;
159 }
160 return mSpellCheckerMap.get(curSpellCheckerId);
161 }
162
Guliz Tuncay83a73302017-08-17 15:25:38 -0700163 public void setCurrentSpellChecker(@Nullable SpellCheckerInfo sci) {
164 if (sci != null) {
165 putSelectedSpellChecker(sci.getId());
166 } else {
167 putSelectedSpellChecker("");
168 }
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700169 putSelectedSpellCheckerSubtype(SpellCheckerSubtype.SUBTYPE_ID_NONE);
170 }
171
172 private void initializeTextServicesData() {
173 if (DBG) {
174 Slog.d(TAG, "initializeTextServicesData for user: " + mUserId);
175 }
176 mSpellCheckerList.clear();
177 mSpellCheckerMap.clear();
178 mUpdateCount++;
179 final PackageManager pm = mContext.getPackageManager();
180 // Note: We do not specify PackageManager.MATCH_ENCRYPTION_* flags here because the
181 // default behavior of PackageManager is exactly what we want. It by default picks up
182 // appropriate services depending on the unlock state for the specified user.
183 final List<ResolveInfo> services = pm.queryIntentServicesAsUser(
184 new Intent(SpellCheckerService.SERVICE_INTERFACE), PackageManager.GET_META_DATA,
185 mUserId);
186 final int N = services.size();
187 for (int i = 0; i < N; ++i) {
188 final ResolveInfo ri = services.get(i);
189 final ServiceInfo si = ri.serviceInfo;
190 final ComponentName compName = new ComponentName(si.packageName, si.name);
191 if (!android.Manifest.permission.BIND_TEXT_SERVICE.equals(si.permission)) {
192 Slog.w(TAG, "Skipping text service " + compName
193 + ": it does not require the permission "
194 + android.Manifest.permission.BIND_TEXT_SERVICE);
195 continue;
196 }
197 if (DBG) Slog.d(TAG, "Add: " + compName + " for user: " + mUserId);
198 try {
199 final SpellCheckerInfo sci = new SpellCheckerInfo(mContext, ri);
200 if (sci.getSubtypeCount() <= 0) {
201 Slog.w(TAG, "Skipping text service " + compName
202 + ": it does not contain subtypes.");
203 continue;
204 }
205 mSpellCheckerList.add(sci);
206 mSpellCheckerMap.put(sci.getId(), sci);
207 } catch (XmlPullParserException e) {
208 Slog.w(TAG, "Unable to load the spell checker " + compName, e);
209 } catch (IOException e) {
210 Slog.w(TAG, "Unable to load the spell checker " + compName, e);
211 }
212 }
213 if (DBG) {
214 Slog.d(TAG, "initializeSpellCheckerMap: " + mSpellCheckerList.size() + ","
215 + mSpellCheckerMap.size());
216 }
217 }
218
219 private void dump(PrintWriter pw) {
220 int spellCheckerIndex = 0;
221 pw.println(" User #" + mUserId);
222 pw.println(" Spell Checkers:");
223 pw.println(" Spell Checkers: " + "mUpdateCount=" + mUpdateCount);
224 for (final SpellCheckerInfo info : mSpellCheckerMap.values()) {
225 pw.println(" Spell Checker #" + spellCheckerIndex);
226 info.dump(pw, " ");
227 ++spellCheckerIndex;
228 }
229
230 pw.println("");
231 pw.println(" Spell Checker Bind Groups:");
232 HashMap<String, SpellCheckerBindGroup> spellCheckerBindGroups = mSpellCheckerBindGroups;
233 for (final Map.Entry<String, SpellCheckerBindGroup> ent
234 : spellCheckerBindGroups.entrySet()) {
235 final SpellCheckerBindGroup grp = ent.getValue();
236 pw.println(" " + ent.getKey() + " " + grp + ":");
237 pw.println(" " + "mInternalConnection=" + grp.mInternalConnection);
238 pw.println(" " + "mSpellChecker=" + grp.mSpellChecker);
239 pw.println(" " + "mUnbindCalled=" + grp.mUnbindCalled);
240 pw.println(" " + "mConnected=" + grp.mConnected);
241 final int numPendingSessionRequests = grp.mPendingSessionRequests.size();
242 for (int j = 0; j < numPendingSessionRequests; j++) {
243 final SessionRequest req = grp.mPendingSessionRequests.get(j);
244 pw.println(" " + "Pending Request #" + j + ":");
245 pw.println(" " + "mTsListener=" + req.mTsListener);
246 pw.println(" " + "mScListener=" + req.mScListener);
247 pw.println(
Yohei Yukawae4622842018-02-26 11:31:47 +0900248 " " + "mScLocale=" + req.mLocale + " mUid=" + req.mUid);
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700249 }
250 final int numOnGoingSessionRequests = grp.mOnGoingSessionRequests.size();
251 for (int j = 0; j < numOnGoingSessionRequests; j++) {
252 final SessionRequest req = grp.mOnGoingSessionRequests.get(j);
253 pw.println(" " + "On going Request #" + j + ":");
254 ++j;
255 pw.println(" " + "mTsListener=" + req.mTsListener);
256 pw.println(" " + "mScListener=" + req.mScListener);
257 pw.println(
Yohei Yukawae4622842018-02-26 11:31:47 +0900258 " " + "mScLocale=" + req.mLocale + " mUid=" + req.mUid);
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700259 }
260 final int N = grp.mListeners.getRegisteredCallbackCount();
261 for (int j = 0; j < N; j++) {
262 final ISpellCheckerSessionListener mScListener =
263 grp.mListeners.getRegisteredCallbackItem(j);
264 pw.println(" " + "Listener #" + j + ":");
265 pw.println(" " + "mScListener=" + mScListener);
266 pw.println(" " + "mGroup=" + grp);
267 }
268 }
Guliz Tuncay06a26242017-06-30 18:32:04 -0700269 }
270 }
271
Yohei Yukawaa6a152e2016-03-07 13:41:15 -0800272 public static final class Lifecycle extends SystemService {
273 private TextServicesManagerService mService;
274
275 public Lifecycle(Context context) {
276 super(context);
277 mService = new TextServicesManagerService(context);
278 }
279
280 @Override
281 public void onStart() {
282 publishBinderService(Context.TEXT_SERVICES_MANAGER_SERVICE, mService);
283 }
284
285 @Override
Guliz Tuncay06a26242017-06-30 18:32:04 -0700286 public void onStopUser(@UserIdInt int userHandle) {
287 if (DBG) {
288 Slog.d(TAG, "onStopUser userId: " + userHandle);
289 }
290 mService.onStopUser(userHandle);
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -0800291 }
292
293 @Override
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800294 public void onUnlockUser(@UserIdInt int userHandle) {
Guliz Tuncay06a26242017-06-30 18:32:04 -0700295 if(DBG) {
296 Slog.d(TAG, "onUnlockUser userId: " + userHandle);
297 }
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800298 // Called on the system server's main looper thread.
299 // TODO: Dispatch this to a worker thread as needed.
300 mService.onUnlockUser(userHandle);
301 }
Yohei Yukawaa6a152e2016-03-07 13:41:15 -0800302 }
303
Guliz Tuncay06a26242017-06-30 18:32:04 -0700304 void onStopUser(@UserIdInt int userId) {
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700305 synchronized (mLock) {
Yohei Yukawa3f8c5682018-03-01 13:10:23 -0800306 // Clear user ID mapping table.
307 mSpellCheckerOwnerUserIdMap.delete(userId);
308
Guliz Tuncay06a26242017-06-30 18:32:04 -0700309 // Clean per-user data
310 TextServicesData tsd = mUserData.get(userId);
311 if (tsd == null) return;
312
313 unbindServiceLocked(tsd); // Remove bind groups first
314 mUserData.remove(userId); // This needs to be done after bind groups are all removed
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800315 }
316 }
317
318 void onUnlockUser(@UserIdInt int userId) {
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700319 synchronized (mLock) {
Guliz Tuncay06a26242017-06-30 18:32:04 -0700320 // Initialize internal state for the given user
321 initializeInternalStateLocked(userId);
satok988323c2011-06-22 16:38:13 +0900322 }
323 }
324
325 public TextServicesManagerService(Context context) {
satok988323c2011-06-22 16:38:13 +0900326 mContext = context;
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800327 mUserManager = mContext.getSystemService(UserManager.class);
Yohei Yukawa3f8c5682018-03-01 13:10:23 -0800328 mSpellCheckerOwnerUserIdMap = new LazyIntToIntMap(callingUserId -> {
329 if (DISABLE_PER_PROFILE_SPELL_CHECKER) {
330 final long token = Binder.clearCallingIdentity();
331 try {
332 final UserInfo parent = mUserManager.getProfileParent(callingUserId);
333 return (parent != null) ? parent.id : callingUserId;
334 } finally {
335 Binder.restoreCallingIdentity(token);
336 }
337 } else {
338 return callingUserId;
339 }
340 });
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800341
satok988323c2011-06-22 16:38:13 +0900342 mMonitor = new TextServicesMonitor();
Guliz Tuncay06a26242017-06-30 18:32:04 -0700343 mMonitor.register(context, null, UserHandle.ALL, true);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900344 }
345
Guliz Tuncay5e1d5d62017-07-26 11:19:08 -0700346 private void initializeInternalStateLocked(@UserIdInt int userId) {
Yohei Yukawa3f8c5682018-03-01 13:10:23 -0800347 // When DISABLE_PER_PROFILE_SPELL_CHECKER is true, we make sure here that work profile users
348 // will never have non-null TextServicesData for their user ID.
349 if (DISABLE_PER_PROFILE_SPELL_CHECKER
350 && userId != mSpellCheckerOwnerUserIdMap.get(userId)) {
351 return;
352 }
353
Guliz Tuncay06a26242017-06-30 18:32:04 -0700354 TextServicesData tsd = mUserData.get(userId);
355 if (tsd == null) {
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700356 tsd = new TextServicesData(userId, mContext);
Guliz Tuncay06a26242017-06-30 18:32:04 -0700357 mUserData.put(userId, tsd);
358 }
359
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700360 tsd.initializeTextServicesData();
361 SpellCheckerInfo sci = tsd.getCurrentSpellChecker();
satokdf5659d2011-07-29 18:38:21 +0900362 if (sci == null) {
Guliz Tuncay0f0a37b2017-08-16 12:02:31 -0700363 sci = findAvailSystemSpellCheckerLocked(null, tsd);
Guliz Tuncay83a73302017-08-17 15:25:38 -0700364 // Set the current spell checker if there is one or more system spell checkers
365 // available. In this case, "sci" is the first one in the available spell
366 // checkers.
367 setCurrentSpellCheckerLocked(sci, tsd);
satokdf5659d2011-07-29 18:38:21 +0900368 }
satok988323c2011-06-22 16:38:13 +0900369 }
370
Guliz Tuncay06a26242017-06-30 18:32:04 -0700371 private final class TextServicesMonitor extends PackageMonitor {
satok988323c2011-06-22 16:38:13 +0900372 @Override
373 public void onSomePackagesChanged() {
Guliz Tuncay06a26242017-06-30 18:32:04 -0700374 int userId = getChangingUserId();
375 if(DBG) {
376 Slog.d(TAG, "onSomePackagesChanged: " + userId);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900377 }
Guliz Tuncay06a26242017-06-30 18:32:04 -0700378
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700379 synchronized (mLock) {
Guliz Tuncay06a26242017-06-30 18:32:04 -0700380 TextServicesData tsd = mUserData.get(userId);
381 if (tsd == null) return;
382
satok988323c2011-06-22 16:38:13 +0900383 // TODO: Update for each locale
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700384 SpellCheckerInfo sci = tsd.getCurrentSpellChecker();
385 tsd.initializeTextServicesData();
Guliz Tuncay83a73302017-08-17 15:25:38 -0700386 // If spell checker is disabled, just return. The user should explicitly
Satoshi Kataoka02260e22013-08-02 16:22:04 +0900387 // enable the spell checker.
Guliz Tuncay83a73302017-08-17 15:25:38 -0700388 if (!tsd.isSpellCheckerEnabled()) return;
389
390 if (sci == null) {
391 sci = findAvailSystemSpellCheckerLocked(null, tsd);
392 // Set the current spell checker if there is one or more system spell checkers
393 // available. In this case, "sci" is the first one in the available spell
394 // checkers.
395 setCurrentSpellCheckerLocked(sci, tsd);
396 } else {
397 final String packageName = sci.getPackageName();
398 final int change = isPackageDisappearing(packageName);
399 if (DBG) Slog.d(TAG, "Changing package name: " + packageName);
Yohei Yukawa4993f4e2018-05-01 15:22:27 -0700400 if (change == PACKAGE_PERMANENT_CHANGE || change == PACKAGE_TEMPORARY_CHANGE) {
Guliz Tuncay83a73302017-08-17 15:25:38 -0700401 SpellCheckerInfo availSci =
402 findAvailSystemSpellCheckerLocked(packageName, tsd);
403 // Set the spell checker settings if different than before
404 if (availSci == null
405 || (availSci != null && !availSci.getId().equals(sci.getId()))) {
406 setCurrentSpellCheckerLocked(availSci, tsd);
407 }
satok5b9b5a92011-08-02 12:24:44 +0900408 }
satok988323c2011-06-22 16:38:13 +0900409 }
410 }
411 }
412 }
413
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900414 private boolean bindCurrentSpellCheckerService(
Guliz Tuncay06a26242017-06-30 18:32:04 -0700415 Intent service, ServiceConnection conn, int flags, @UserIdInt int userId) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900416 if (service == null || conn == null) {
Guliz Tuncay06a26242017-06-30 18:32:04 -0700417 Slog.e(TAG, "--- bind failed: service = " + service + ", conn = " + conn +
418 ", userId =" + userId);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900419 return false;
420 }
Guliz Tuncay06a26242017-06-30 18:32:04 -0700421 return mContext.bindServiceAsUser(service, conn, flags, UserHandle.of(userId));
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900422 }
423
Guliz Tuncay06a26242017-06-30 18:32:04 -0700424 private void unbindServiceLocked(TextServicesData tsd) {
425 HashMap<String, SpellCheckerBindGroup> spellCheckerBindGroups = tsd.mSpellCheckerBindGroups;
426 for (SpellCheckerBindGroup scbg : spellCheckerBindGroups.values()) {
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700427 scbg.removeAllLocked();
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900428 }
Guliz Tuncay06a26242017-06-30 18:32:04 -0700429 spellCheckerBindGroups.clear();
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900430 }
431
Guliz Tuncay0f0a37b2017-08-16 12:02:31 -0700432 private SpellCheckerInfo findAvailSystemSpellCheckerLocked(String prefPackage,
Guliz Tuncay06a26242017-06-30 18:32:04 -0700433 TextServicesData tsd) {
Guliz Tuncay0f0a37b2017-08-16 12:02:31 -0700434 // Filter the spell checker list to remove spell checker services that are not pre-installed
435 ArrayList<SpellCheckerInfo> spellCheckerList = new ArrayList<>();
436 for (SpellCheckerInfo sci : tsd.mSpellCheckerList) {
437 if ((sci.getServiceInfo().applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
438 spellCheckerList.add(sci);
439 }
440 }
441
Guliz Tuncay06a26242017-06-30 18:32:04 -0700442 final int spellCheckersCount = spellCheckerList.size();
satok988323c2011-06-22 16:38:13 +0900443 if (spellCheckersCount == 0) {
444 Slog.w(TAG, "no available spell checker services found");
445 return null;
446 }
447 if (prefPackage != null) {
448 for (int i = 0; i < spellCheckersCount; ++i) {
Guliz Tuncay06a26242017-06-30 18:32:04 -0700449 final SpellCheckerInfo sci = spellCheckerList.get(i);
satok988323c2011-06-22 16:38:13 +0900450 if (prefPackage.equals(sci.getPackageName())) {
satokda317ef2011-07-26 08:02:45 +0900451 if (DBG) {
Guliz Tuncay0f0a37b2017-08-16 12:02:31 -0700452 Slog.d(TAG, "findAvailSystemSpellCheckerLocked: " + sci.getPackageName());
satokda317ef2011-07-26 08:02:45 +0900453 }
satok988323c2011-06-22 16:38:13 +0900454 return sci;
455 }
456 }
457 }
Yohei Yukawa174843a2015-06-26 18:02:54 -0700458
459 // Look up a spell checker based on the system locale.
460 // TODO: Still there is a room to improve in the following logic: e.g., check if the package
461 // is pre-installed or not.
462 final Locale systemLocal = mContext.getResources().getConfiguration().locale;
463 final ArrayList<Locale> suitableLocales =
464 InputMethodUtils.getSuitableLocalesForSpellChecker(systemLocal);
465 if (DBG) {
Guliz Tuncay0f0a37b2017-08-16 12:02:31 -0700466 Slog.w(TAG, "findAvailSystemSpellCheckerLocked suitableLocales="
Yohei Yukawa174843a2015-06-26 18:02:54 -0700467 + Arrays.toString(suitableLocales.toArray(new Locale[suitableLocales.size()])));
468 }
469 final int localeCount = suitableLocales.size();
470 for (int localeIndex = 0; localeIndex < localeCount; ++localeIndex) {
471 final Locale locale = suitableLocales.get(localeIndex);
472 for (int spellCheckersIndex = 0; spellCheckersIndex < spellCheckersCount;
473 ++spellCheckersIndex) {
Guliz Tuncay06a26242017-06-30 18:32:04 -0700474 final SpellCheckerInfo info = spellCheckerList.get(spellCheckersIndex);
Yohei Yukawa174843a2015-06-26 18:02:54 -0700475 final int subtypeCount = info.getSubtypeCount();
476 for (int subtypeIndex = 0; subtypeIndex < subtypeCount; ++subtypeIndex) {
477 final SpellCheckerSubtype subtype = info.getSubtypeAt(subtypeIndex);
478 final Locale subtypeLocale = InputMethodUtils.constructLocaleFromString(
479 subtype.getLocale());
480 if (locale.equals(subtypeLocale)) {
481 // TODO: We may have more spell checkers that fall into this category.
482 // Ideally we should pick up the most suitable one instead of simply
483 // returning the first found one.
484 return info;
485 }
486 }
487 }
488 }
489
satok988323c2011-06-22 16:38:13 +0900490 if (spellCheckersCount > 1) {
491 Slog.w(TAG, "more than one spell checker service found, picking first");
492 }
Guliz Tuncay06a26242017-06-30 18:32:04 -0700493 return spellCheckerList.get(0);
satok988323c2011-06-22 16:38:13 +0900494 }
495
496 // TODO: Save SpellCheckerService by supported languages. Currently only one spell
497 // checker is saved.
498 @Override
499 public SpellCheckerInfo getCurrentSpellChecker(String locale) {
Guliz Tuncay06a26242017-06-30 18:32:04 -0700500 int userId = UserHandle.getCallingUserId();
501 synchronized (mLock) {
Yohei Yukawa3f8c5682018-03-01 13:10:23 -0800502 final TextServicesData tsd = getDataFromCallingUserIdLocked(userId);
Guliz Tuncay06a26242017-06-30 18:32:04 -0700503 if (tsd == null) return null;
504
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700505 return tsd.getCurrentSpellChecker();
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900506 }
Yohei Yukawa095fa372014-10-27 14:02:23 +0900507 }
508
satok3cb5b392011-08-26 11:55:21 +0900509 // TODO: Respect allowImplicitlySelectedSubtype
Satoshi Kataoka17150cf2012-05-30 20:05:44 +0900510 // TODO: Save SpellCheckerSubtype by supported languages by looking at "locale".
satokada8c4e2011-08-23 14:56:56 +0900511 @Override
satok3cb5b392011-08-26 11:55:21 +0900512 public SpellCheckerSubtype getCurrentSpellCheckerSubtype(
513 String locale, boolean allowImplicitlySelectedSubtype) {
Yohei Yukawae3e31a82016-09-20 06:43:03 -0700514 final int subtypeHashCode;
515 final SpellCheckerInfo sci;
516 final Locale systemLocale;
Guliz Tuncay06a26242017-06-30 18:32:04 -0700517 final int userId = UserHandle.getCallingUserId();
518
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700519 synchronized (mLock) {
Yohei Yukawa3f8c5682018-03-01 13:10:23 -0800520 final TextServicesData tsd = getDataFromCallingUserIdLocked(userId);
Guliz Tuncay06a26242017-06-30 18:32:04 -0700521 if (tsd == null) return null;
522
Yohei Yukawae3e31a82016-09-20 06:43:03 -0700523 subtypeHashCode =
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700524 tsd.getSelectedSpellCheckerSubtype(SpellCheckerSubtype.SUBTYPE_ID_NONE);
satokada8c4e2011-08-23 14:56:56 +0900525 if (DBG) {
Yohei Yukawaad150ee2016-03-16 17:22:27 -0700526 Slog.w(TAG, "getCurrentSpellCheckerSubtype: " + subtypeHashCode);
satokada8c4e2011-08-23 14:56:56 +0900527 }
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700528 sci = tsd.getCurrentSpellChecker();
Yohei Yukawae3e31a82016-09-20 06:43:03 -0700529 systemLocale = mContext.getResources().getConfiguration().locale;
satokada8c4e2011-08-23 14:56:56 +0900530 }
Yohei Yukawae3e31a82016-09-20 06:43:03 -0700531 if (sci == null || sci.getSubtypeCount() == 0) {
532 if (DBG) {
533 Slog.w(TAG, "Subtype not found.");
534 }
535 return null;
536 }
537 if (subtypeHashCode == SpellCheckerSubtype.SUBTYPE_ID_NONE
538 && !allowImplicitlySelectedSubtype) {
539 return null;
540 }
541 String candidateLocale = null;
542 if (subtypeHashCode == 0) {
543 // Spell checker language settings == "auto"
544 final InputMethodManager imm = mContext.getSystemService(InputMethodManager.class);
545 if (imm != null) {
546 final InputMethodSubtype currentInputMethodSubtype =
547 imm.getCurrentInputMethodSubtype();
548 if (currentInputMethodSubtype != null) {
549 final String localeString = currentInputMethodSubtype.getLocale();
550 if (!TextUtils.isEmpty(localeString)) {
551 // 1. Use keyboard locale if available in the spell checker
552 candidateLocale = localeString;
553 }
554 }
555 }
556 if (candidateLocale == null) {
557 // 2. Use System locale if available in the spell checker
558 candidateLocale = systemLocale.toString();
559 }
560 }
561 SpellCheckerSubtype candidate = null;
562 for (int i = 0; i < sci.getSubtypeCount(); ++i) {
563 final SpellCheckerSubtype scs = sci.getSubtypeAt(i);
564 if (subtypeHashCode == 0) {
565 final String scsLocale = scs.getLocale();
566 if (candidateLocale.equals(scsLocale)) {
567 return scs;
568 } else if (candidate == null) {
569 if (candidateLocale.length() >= 2 && scsLocale.length() >= 2
570 && candidateLocale.startsWith(scsLocale)) {
571 // Fall back to the applicable language
572 candidate = scs;
573 }
574 }
575 } else if (scs.hashCode() == subtypeHashCode) {
576 if (DBG) {
577 Slog.w(TAG, "Return subtype " + scs.hashCode() + ", input= " + locale
578 + ", " + scs.getLocale());
579 }
580 // 3. Use the user specified spell check language
581 return scs;
582 }
583 }
584 // 4. Fall back to the applicable language and return it if not null
585 // 5. Simply just return it even if it's null which means we could find no suitable
586 // spell check languages
587 return candidate;
satokada8c4e2011-08-23 14:56:56 +0900588 }
589
satok988323c2011-06-22 16:38:13 +0900590 @Override
satok5b9b5a92011-08-02 12:24:44 +0900591 public void getSpellCheckerService(String sciId, String locale,
satok53578062011-08-03 16:08:59 +0900592 ITextServicesSessionListener tsListener, ISpellCheckerSessionListener scListener,
593 Bundle bundle) {
satok5b9b5a92011-08-02 12:24:44 +0900594 if (TextUtils.isEmpty(sciId) || tsListener == null || scListener == null) {
satok988323c2011-06-22 16:38:13 +0900595 Slog.e(TAG, "getSpellCheckerService: Invalid input.");
596 return;
597 }
Guliz Tuncay06a26242017-06-30 18:32:04 -0700598 int callingUserId = UserHandle.getCallingUserId();
599
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700600 synchronized (mLock) {
Yohei Yukawa3f8c5682018-03-01 13:10:23 -0800601 final TextServicesData tsd = getDataFromCallingUserIdLocked(callingUserId);
Guliz Tuncay06a26242017-06-30 18:32:04 -0700602 if (tsd == null) return;
603
604 HashMap<String, SpellCheckerInfo> spellCheckerMap = tsd.mSpellCheckerMap;
605 if (!spellCheckerMap.containsKey(sciId)) {
satok988323c2011-06-22 16:38:13 +0900606 return;
607 }
Guliz Tuncay06a26242017-06-30 18:32:04 -0700608 final SpellCheckerInfo sci = spellCheckerMap.get(sciId);
609 HashMap<String, SpellCheckerBindGroup> spellCheckerBindGroups =
610 tsd.mSpellCheckerBindGroups;
611 SpellCheckerBindGroup bindGroup = spellCheckerBindGroups.get(sciId);
satokdf5659d2011-07-29 18:38:21 +0900612 final int uid = Binder.getCallingUid();
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800613 if (bindGroup == null) {
614 final long ident = Binder.clearCallingIdentity();
615 try {
Guliz Tuncay06a26242017-06-30 18:32:04 -0700616 bindGroup = startSpellCheckerServiceInnerLocked(sci, tsd);
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800617 } finally {
618 Binder.restoreCallingIdentity(ident);
619 }
620 if (bindGroup == null) {
621 // startSpellCheckerServiceInnerLocked failed.
622 return;
satok6be6d752011-07-28 20:40:38 +0900623 }
satok988323c2011-06-22 16:38:13 +0900624 }
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800625
626 // Start getISpellCheckerSession async IPC, or just queue the request until the spell
627 // checker service is bound.
628 bindGroup.getISpellCheckerSessionOrQueueLocked(
Guliz Tuncay5e1d5d62017-07-26 11:19:08 -0700629 new SessionRequest(uid, locale, tsListener, scListener, bundle));
satok988323c2011-06-22 16:38:13 +0900630 }
satok988323c2011-06-22 16:38:13 +0900631 }
632
satoka33c4fc2011-08-25 16:50:11 +0900633 @Override
634 public boolean isSpellCheckerEnabled() {
Guliz Tuncay06a26242017-06-30 18:32:04 -0700635 int userId = UserHandle.getCallingUserId();
636
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700637 synchronized (mLock) {
Yohei Yukawa3f8c5682018-03-01 13:10:23 -0800638 final TextServicesData tsd = getDataFromCallingUserIdLocked(userId);
Guliz Tuncay06a26242017-06-30 18:32:04 -0700639 if (tsd == null) return false;
640
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700641 return tsd.isSpellCheckerEnabled();
satoka33c4fc2011-08-25 16:50:11 +0900642 }
643 }
644
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800645 @Nullable
Guliz Tuncay06a26242017-06-30 18:32:04 -0700646 private SpellCheckerBindGroup startSpellCheckerServiceInnerLocked(SpellCheckerInfo info,
647 TextServicesData tsd) {
satokdf5659d2011-07-29 18:38:21 +0900648 if (DBG) {
649 Slog.w(TAG, "Start spell checker session inner locked.");
650 }
satok6be6d752011-07-28 20:40:38 +0900651 final String sciId = info.getId();
Guliz Tuncay06a26242017-06-30 18:32:04 -0700652 final InternalServiceConnection connection = new InternalServiceConnection(sciId,
653 tsd.mSpellCheckerBindGroups);
satok6be6d752011-07-28 20:40:38 +0900654 final Intent serviceIntent = new Intent(SpellCheckerService.SERVICE_INTERFACE);
655 serviceIntent.setComponent(info.getComponent());
656 if (DBG) {
657 Slog.w(TAG, "bind service: " + info.getId());
658 }
Dianne Hackbornd69e4c12015-04-24 09:54:54 -0700659 if (!bindCurrentSpellCheckerService(serviceIntent, connection,
Guliz Tuncay06a26242017-06-30 18:32:04 -0700660 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT_BACKGROUND, tsd.mUserId)) {
satok6be6d752011-07-28 20:40:38 +0900661 Slog.e(TAG, "Failed to get a spell checker service.");
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800662 return null;
satok6be6d752011-07-28 20:40:38 +0900663 }
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800664 final SpellCheckerBindGroup group = new SpellCheckerBindGroup(connection);
Guliz Tuncay06a26242017-06-30 18:32:04 -0700665
666 tsd.mSpellCheckerBindGroups.put(sciId, group);
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800667 return group;
satok6be6d752011-07-28 20:40:38 +0900668 }
669
satok988323c2011-06-22 16:38:13 +0900670 @Override
satok562ab582011-07-25 10:12:21 +0900671 public SpellCheckerInfo[] getEnabledSpellCheckers() {
Guliz Tuncay06a26242017-06-30 18:32:04 -0700672 int callingUserId = UserHandle.getCallingUserId();
673
674 synchronized (mLock) {
Yohei Yukawa3f8c5682018-03-01 13:10:23 -0800675 final TextServicesData tsd = getDataFromCallingUserIdLocked(callingUserId);
Guliz Tuncay06a26242017-06-30 18:32:04 -0700676 if (tsd == null) return null;
677
678 ArrayList<SpellCheckerInfo> spellCheckerList = tsd.mSpellCheckerList;
679 if (DBG) {
680 Slog.d(TAG, "getEnabledSpellCheckers: " + spellCheckerList.size());
681 for (int i = 0; i < spellCheckerList.size(); ++i) {
682 Slog.d(TAG,
683 "EnabledSpellCheckers: " + spellCheckerList.get(i).getPackageName());
684 }
satokda317ef2011-07-26 08:02:45 +0900685 }
Guliz Tuncay06a26242017-06-30 18:32:04 -0700686 return spellCheckerList.toArray(new SpellCheckerInfo[spellCheckerList.size()]);
satokda317ef2011-07-26 08:02:45 +0900687 }
satok562ab582011-07-25 10:12:21 +0900688 }
689
690 @Override
satok988323c2011-06-22 16:38:13 +0900691 public void finishSpellCheckerService(ISpellCheckerSessionListener listener) {
satokda317ef2011-07-26 08:02:45 +0900692 if (DBG) {
693 Slog.d(TAG, "FinishSpellCheckerService");
694 }
Guliz Tuncay06a26242017-06-30 18:32:04 -0700695 int userId = UserHandle.getCallingUserId();
696
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700697 synchronized (mLock) {
Yohei Yukawa3f8c5682018-03-01 13:10:23 -0800698 final TextServicesData tsd = getDataFromCallingUserIdLocked(userId);
Guliz Tuncay06a26242017-06-30 18:32:04 -0700699 if (tsd == null) return;
700
Yohei Yukawa074637f2016-03-06 14:34:55 -0800701 final ArrayList<SpellCheckerBindGroup> removeList = new ArrayList<>();
Guliz Tuncay06a26242017-06-30 18:32:04 -0700702 HashMap<String, SpellCheckerBindGroup> spellCheckerBindGroups =
703 tsd.mSpellCheckerBindGroups;
704 for (SpellCheckerBindGroup group : spellCheckerBindGroups.values()) {
satok988323c2011-06-22 16:38:13 +0900705 if (group == null) continue;
satok4c3fa642011-11-30 18:17:59 +0900706 // Use removeList to avoid modifying mSpellCheckerBindGroups in this loop.
707 removeList.add(group);
708 }
709 final int removeSize = removeList.size();
710 for (int i = 0; i < removeSize; ++i) {
711 removeList.get(i).removeListener(listener);
satok988323c2011-06-22 16:38:13 +0900712 }
713 }
714 }
715
Guliz Tuncay83a73302017-08-17 15:25:38 -0700716 private void setCurrentSpellCheckerLocked(@Nullable SpellCheckerInfo sci, TextServicesData tsd) {
717 final String sciId = (sci != null) ? sci.getId() : "";
satok562ab582011-07-25 10:12:21 +0900718 if (DBG) {
satok5b9b5a92011-08-02 12:24:44 +0900719 Slog.w(TAG, "setCurrentSpellChecker: " + sciId);
satok562ab582011-07-25 10:12:21 +0900720 }
satokdf5659d2011-07-29 18:38:21 +0900721 final long ident = Binder.clearCallingIdentity();
722 try {
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700723 tsd.setCurrentSpellChecker(sci);
satoka33c4fc2011-08-25 16:50:11 +0900724 } finally {
725 Binder.restoreCallingIdentity(ident);
726 }
727 }
728
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700729 @Override
730 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600731 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700732
Yohei Yukawa02f646e2018-01-24 17:50:32 -0800733 if (args.length == 0 || (args.length == 1 && args[0].equals("-a"))) {
734 // Dump all users' data
Guliz Tuncay06a26242017-06-30 18:32:04 -0700735 synchronized (mLock) {
736 pw.println("Current Text Services Manager state:");
Guliz Tuncay06a26242017-06-30 18:32:04 -0700737 pw.println(" Users:");
738 final int numOfUsers = mUserData.size();
739 for (int i = 0; i < numOfUsers; i++) {
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700740 TextServicesData tsd = mUserData.valueAt(i);
741 tsd.dump(pw);
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700742 }
743 }
Guliz Tuncay06a26242017-06-30 18:32:04 -0700744 } else { // Dump a given user's data
745 if (args.length != 2 || !args[0].equals("--user")) {
746 pw.println("Invalid arguments to text services." );
747 return;
748 } else {
749 int userId = Integer.parseInt(args[1]);
750 UserInfo userInfo = mUserManager.getUserInfo(userId);
751 if (userInfo == null) {
752 pw.println("Non-existent user.");
753 return;
754 }
755 TextServicesData tsd = mUserData.get(userId);
756 if (tsd == null) {
757 pw.println("User needs to unlock first." );
758 return;
759 }
760 synchronized (mLock) {
761 pw.println("Current Text Services Manager state:");
Guliz Tuncay06a26242017-06-30 18:32:04 -0700762 pw.println(" User " + userId + ":");
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700763 tsd.dump(pw);
Guliz Tuncay06a26242017-06-30 18:32:04 -0700764 }
765 }
766 }
767 }
768
Yohei Yukawa3f8c5682018-03-01 13:10:23 -0800769 /**
770 * @param callingUserId user ID of the calling process
771 * @return {@link TextServicesData} for the given user. {@code null} if spell checker is not
772 * temporarily / permanently available for the specified user
773 */
774 @Nullable
775 private TextServicesData getDataFromCallingUserIdLocked(@UserIdInt int callingUserId) {
776 final int spellCheckerOwnerUserId = mSpellCheckerOwnerUserIdMap.get(callingUserId);
777 final TextServicesData data = mUserData.get(spellCheckerOwnerUserId);
778 if (DISABLE_PER_PROFILE_SPELL_CHECKER) {
779 if (spellCheckerOwnerUserId != callingUserId) {
780 // Calling process is running under child profile.
781 if (data == null) {
782 return null;
783 }
784 final SpellCheckerInfo info = data.getCurrentSpellChecker();
785 if (info == null) {
786 return null;
787 }
788 final ServiceInfo serviceInfo = info.getServiceInfo();
789 if ((serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
790 // To be conservative, non pre-installed spell checker services are not allowed
791 // to be used for child profiles.
792 return null;
793 }
794 }
795 }
796 return data;
797 }
798
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800799 private static final class SessionRequest {
Yohei Yukawae4622842018-02-26 11:31:47 +0900800 public final int mUid;
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800801 @Nullable
802 public final String mLocale;
803 @NonNull
804 public final ITextServicesSessionListener mTsListener;
805 @NonNull
806 public final ISpellCheckerSessionListener mScListener;
807 @Nullable
808 public final Bundle mBundle;
809
Yohei Yukawae4622842018-02-26 11:31:47 +0900810 SessionRequest(int uid, @Nullable String locale,
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800811 @NonNull ITextServicesSessionListener tsListener,
812 @NonNull ISpellCheckerSessionListener scListener, @Nullable Bundle bundle) {
Yohei Yukawae4622842018-02-26 11:31:47 +0900813 mUid = uid;
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800814 mLocale = locale;
815 mTsListener = tsListener;
816 mScListener = scListener;
817 mBundle = bundle;
818 }
819 }
820
satok988323c2011-06-22 16:38:13 +0900821 // SpellCheckerBindGroup contains active text service session listeners.
822 // If there are no listeners anymore, the SpellCheckerBindGroup instance will be removed from
823 // mSpellCheckerBindGroups
Yohei Yukawa06b4be72017-01-29 14:08:17 -0800824 private final class SpellCheckerBindGroup {
satokdf5659d2011-07-29 18:38:21 +0900825 private final String TAG = SpellCheckerBindGroup.class.getSimpleName();
satok6be6d752011-07-28 20:40:38 +0900826 private final InternalServiceConnection mInternalConnection;
Guliz Tuncayf982e752017-06-14 09:33:16 -0700827 private final InternalDeathRecipients mListeners;
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800828 private boolean mUnbindCalled;
829 private ISpellCheckerService mSpellChecker;
830 private boolean mConnected;
831 private final ArrayList<SessionRequest> mPendingSessionRequests = new ArrayList<>();
832 private final ArrayList<SessionRequest> mOnGoingSessionRequests = new ArrayList<>();
Guliz Tuncay06a26242017-06-30 18:32:04 -0700833 @NonNull
834 HashMap<String, SpellCheckerBindGroup> mSpellCheckerBindGroups;
835
satok988323c2011-06-22 16:38:13 +0900836
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800837 public SpellCheckerBindGroup(InternalServiceConnection connection) {
satok988323c2011-06-22 16:38:13 +0900838 mInternalConnection = connection;
Guliz Tuncayf982e752017-06-14 09:33:16 -0700839 mListeners = new InternalDeathRecipients(this);
Guliz Tuncay06a26242017-06-30 18:32:04 -0700840 mSpellCheckerBindGroups = connection.mSpellCheckerBindGroups;
satok988323c2011-06-22 16:38:13 +0900841 }
842
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700843 public void onServiceConnectedLocked(ISpellCheckerService spellChecker) {
satokda317ef2011-07-26 08:02:45 +0900844 if (DBG) {
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700845 Slog.d(TAG, "onServiceConnectedLocked");
satokda317ef2011-07-26 08:02:45 +0900846 }
satok4e713f12012-02-28 16:51:15 +0900847
Yohei Yukawa4163a962017-08-07 10:17:59 -0700848 if (mUnbindCalled) {
849 return;
satok988323c2011-06-22 16:38:13 +0900850 }
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700851 mSpellChecker = spellChecker;
852 mConnected = true;
853 // Dispatch pending getISpellCheckerSession requests.
Yohei Yukawa4163a962017-08-07 10:17:59 -0700854 try {
855 final int size = mPendingSessionRequests.size();
856 for (int i = 0; i < size; ++i) {
857 final SessionRequest request = mPendingSessionRequests.get(i);
858 mSpellChecker.getISpellCheckerSession(
859 request.mLocale, request.mScListener, request.mBundle,
860 new ISpellCheckerServiceCallbackBinder(this, request));
861 mOnGoingSessionRequests.add(request);
862 }
863 mPendingSessionRequests.clear();
864 } catch(RemoteException e) {
865 // The target spell checker service is not available. Better to reset the state.
866 removeAllLocked();
867 }
868 cleanLocked();
satok988323c2011-06-22 16:38:13 +0900869 }
870
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700871 public void onServiceDisconnectedLocked() {
Guliz Tuncay787aa8c2017-06-19 17:15:40 -0700872 if (DBG) {
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700873 Slog.d(TAG, "onServiceDisconnectedLocked");
Guliz Tuncay787aa8c2017-06-19 17:15:40 -0700874 }
875
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700876 mSpellChecker = null;
877 mConnected = false;
Guliz Tuncay787aa8c2017-06-19 17:15:40 -0700878 }
879
satok988323c2011-06-22 16:38:13 +0900880 public void removeListener(ISpellCheckerSessionListener listener) {
satokda317ef2011-07-26 08:02:45 +0900881 if (DBG) {
satokdf5659d2011-07-29 18:38:21 +0900882 Slog.w(TAG, "remove listener: " + listener.hashCode());
satokda317ef2011-07-26 08:02:45 +0900883 }
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700884 synchronized (mLock) {
Guliz Tuncayf982e752017-06-14 09:33:16 -0700885 mListeners.unregister(listener);
Yohei Yukawa73ac9472018-05-01 11:40:29 -0700886 final IBinder scListenerBinder = listener.asBinder();
887 final Predicate<SessionRequest> removeCondition =
888 request -> request.mScListener.asBinder() == scListenerBinder;
889 mPendingSessionRequests.removeIf(removeCondition);
890 mOnGoingSessionRequests.removeIf(removeCondition);
satok988323c2011-06-22 16:38:13 +0900891 cleanLocked();
892 }
893 }
894
satok4c3fa642011-11-30 18:17:59 +0900895 // cleanLocked may remove elements from mSpellCheckerBindGroups
satok988323c2011-06-22 16:38:13 +0900896 private void cleanLocked() {
satokda317ef2011-07-26 08:02:45 +0900897 if (DBG) {
898 Slog.d(TAG, "cleanLocked");
899 }
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800900 if (mUnbindCalled) {
901 return;
satok988323c2011-06-22 16:38:13 +0900902 }
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800903 // If there are no more active listeners, clean up. Only do this once.
Guliz Tuncayf982e752017-06-14 09:33:16 -0700904 if (mListeners.getRegisteredCallbackCount() > 0) {
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800905 return;
906 }
907 if (!mPendingSessionRequests.isEmpty()) {
908 return;
909 }
910 if (!mOnGoingSessionRequests.isEmpty()) {
911 return;
912 }
913 final String sciId = mInternalConnection.mSciId;
914 final SpellCheckerBindGroup cur = mSpellCheckerBindGroups.get(sciId);
915 if (cur == this) {
916 if (DBG) {
917 Slog.d(TAG, "Remove bind group.");
918 }
919 mSpellCheckerBindGroups.remove(sciId);
920 }
921 mContext.unbindService(mInternalConnection);
922 mUnbindCalled = true;
satok988323c2011-06-22 16:38:13 +0900923 }
satok6be6d752011-07-28 20:40:38 +0900924
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700925 public void removeAllLocked() {
satok6be6d752011-07-28 20:40:38 +0900926 Slog.e(TAG, "Remove the spell checker bind unexpectedly.");
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700927 final int size = mListeners.getRegisteredCallbackCount();
928 for (int i = size - 1; i >= 0; --i) {
929 mListeners.unregister(mListeners.getRegisteredCallbackItem(i));
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800930 }
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700931 mPendingSessionRequests.clear();
932 mOnGoingSessionRequests.clear();
933 cleanLocked();
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800934 }
935
936 public void getISpellCheckerSessionOrQueueLocked(@NonNull SessionRequest request) {
937 if (mUnbindCalled) {
938 return;
939 }
Yohei Yukawa73ac9472018-05-01 11:40:29 -0700940 mListeners.register(request.mScListener);
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800941 if (!mConnected) {
942 mPendingSessionRequests.add(request);
943 return;
944 }
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800945 try {
946 mSpellChecker.getISpellCheckerSession(
947 request.mLocale, request.mScListener, request.mBundle,
948 new ISpellCheckerServiceCallbackBinder(this, request));
949 mOnGoingSessionRequests.add(request);
950 } catch(RemoteException e) {
951 // The target spell checker service is not available. Better to reset the state.
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700952 removeAllLocked();
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800953 }
954 cleanLocked();
955 }
956
957 void onSessionCreated(@Nullable final ISpellCheckerSession newSession,
958 @NonNull final SessionRequest request) {
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700959 synchronized (mLock) {
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800960 if (mUnbindCalled) {
961 return;
962 }
963 if (mOnGoingSessionRequests.remove(request)) {
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800964 try {
965 request.mTsListener.onServiceConnected(newSession);
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800966 } catch (RemoteException e) {
967 // Technically this can happen if the spell checker client app is already
968 // dead. We can just forget about this request; the request is already
969 // removed from mOnGoingSessionRequests and the death recipient listener is
970 // not yet added to mListeners. There is nothing to release further.
971 }
972 }
satokdf5659d2011-07-29 18:38:21 +0900973 cleanLocked();
974 }
satok6be6d752011-07-28 20:40:38 +0900975 }
satok988323c2011-06-22 16:38:13 +0900976 }
977
Yohei Yukawa06b4be72017-01-29 14:08:17 -0800978 private final class InternalServiceConnection implements ServiceConnection {
satok988323c2011-06-22 16:38:13 +0900979 private final String mSciId;
Guliz Tuncay06a26242017-06-30 18:32:04 -0700980 @NonNull
981 private final HashMap<String, SpellCheckerBindGroup> mSpellCheckerBindGroups;
982 public InternalServiceConnection(String id,
983 @NonNull HashMap<String, SpellCheckerBindGroup> spellCheckerBindGroups) {
satok988323c2011-06-22 16:38:13 +0900984 mSciId = id;
Guliz Tuncay06a26242017-06-30 18:32:04 -0700985 mSpellCheckerBindGroups = spellCheckerBindGroups;
satok988323c2011-06-22 16:38:13 +0900986 }
987
988 @Override
989 public void onServiceConnected(ComponentName name, IBinder service) {
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700990 synchronized (mLock) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900991 onServiceConnectedInnerLocked(name, service);
992 }
993 }
994
995 private void onServiceConnectedInnerLocked(ComponentName name, IBinder service) {
996 if (DBG) {
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700997 Slog.w(TAG, "onServiceConnectedInnerLocked: " + name);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900998 }
999 final ISpellCheckerService spellChecker =
1000 ISpellCheckerService.Stub.asInterface(service);
Guliz Tuncay06a26242017-06-30 18:32:04 -07001001
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001002 final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId);
1003 if (group != null && this == group.mInternalConnection) {
Yohei Yukawa1854cb52017-08-07 10:17:46 -07001004 group.onServiceConnectedLocked(spellChecker);
satok988323c2011-06-22 16:38:13 +09001005 }
1006 }
1007
1008 @Override
1009 public void onServiceDisconnected(ComponentName name) {
Guliz Tuncay10ae3852017-07-07 10:35:59 -07001010 synchronized (mLock) {
Guliz Tuncay787aa8c2017-06-19 17:15:40 -07001011 onServiceDisconnectedInnerLocked(name);
1012 }
1013 }
1014
1015 private void onServiceDisconnectedInnerLocked(ComponentName name) {
1016 if (DBG) {
Yohei Yukawa1854cb52017-08-07 10:17:46 -07001017 Slog.w(TAG, "onServiceDisconnectedInnerLocked: " + name);
Guliz Tuncay787aa8c2017-06-19 17:15:40 -07001018 }
1019 final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId);
1020 if (group != null && this == group.mInternalConnection) {
Yohei Yukawa1854cb52017-08-07 10:17:46 -07001021 group.onServiceDisconnectedLocked();
Dianne Hackborn71e14da2011-10-16 16:28:10 -07001022 }
satok988323c2011-06-22 16:38:13 +09001023 }
1024 }
1025
Yohei Yukawaf14fe142017-06-22 22:30:45 -07001026 private static final class InternalDeathRecipients extends
Guliz Tuncayf982e752017-06-14 09:33:16 -07001027 RemoteCallbackList<ISpellCheckerSessionListener> {
satok988323c2011-06-22 16:38:13 +09001028 private final SpellCheckerBindGroup mGroup;
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -08001029
Guliz Tuncayf982e752017-06-14 09:33:16 -07001030 public InternalDeathRecipients(SpellCheckerBindGroup group) {
satok988323c2011-06-22 16:38:13 +09001031 mGroup = group;
1032 }
1033
Guliz Tuncayf982e752017-06-14 09:33:16 -07001034 @Override
1035 public void onCallbackDied(ISpellCheckerSessionListener listener) {
Yohei Yukawaf14fe142017-06-22 22:30:45 -07001036 mGroup.removeListener(listener);
satok988323c2011-06-22 16:38:13 +09001037 }
satok988323c2011-06-22 16:38:13 +09001038 }
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001039
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -08001040 private static final class ISpellCheckerServiceCallbackBinder
1041 extends ISpellCheckerServiceCallback.Stub {
1042 @NonNull
1043 private final SpellCheckerBindGroup mBindGroup;
1044 @NonNull
1045 private final SessionRequest mRequest;
1046
1047 ISpellCheckerServiceCallbackBinder(@NonNull final SpellCheckerBindGroup bindGroup,
1048 @NonNull final SessionRequest request) {
1049 mBindGroup = bindGroup;
1050 mRequest = request;
1051 }
1052
1053 @Override
1054 public void onSessionCreated(@Nullable ISpellCheckerSession newSession) {
1055 mBindGroup.onSessionCreated(newSession, mRequest);
1056 }
1057 }
satok988323c2011-06-22 16:38:13 +09001058}