blob: d4aa59d3ce8544ce0da8cc940a15d9ab88b0aa1c [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
Yohei Yukawaeb1e8042018-09-12 14:02:00 -070017package com.android.server.textservices;
satok988323c2011-06-22 16:38:13 +090018
Yohei Yukawa9f141ee2019-01-18 09:17:16 -080019import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
20
Yohei Yukawaf0f16802016-03-08 16:04:58 -080021import android.annotation.NonNull;
Yohei Yukawa08ce1872016-03-16 17:22:30 -070022import android.annotation.Nullable;
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -080023import android.annotation.UserIdInt;
satok988323c2011-06-22 16:38:13 +090024import android.content.ComponentName;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090025import android.content.ContentResolver;
satok988323c2011-06-22 16:38:13 +090026import android.content.Context;
27import android.content.Intent;
28import android.content.ServiceConnection;
Guliz Tuncay0f0a37b2017-08-16 12:02:31 -070029import android.content.pm.ApplicationInfo;
satok988323c2011-06-22 16:38:13 +090030import android.content.pm.PackageManager;
31import android.content.pm.ResolveInfo;
32import android.content.pm.ServiceInfo;
Guliz Tuncay06a26242017-06-30 18:32:04 -070033import android.content.pm.UserInfo;
satok6be6d752011-07-28 20:40:38 +090034import android.os.Binder;
satok53578062011-08-03 16:08:59 +090035import android.os.Bundle;
satok988323c2011-06-22 16:38:13 +090036import android.os.IBinder;
Guliz Tuncayf982e752017-06-14 09:33:16 -070037import android.os.RemoteCallbackList;
satok988323c2011-06-22 16:38:13 +090038import android.os.RemoteException;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090039import android.os.UserHandle;
Yohei Yukawa095fa372014-10-27 14:02:23 +090040import android.os.UserManager;
satok988323c2011-06-22 16:38:13 +090041import android.provider.Settings;
satok988323c2011-06-22 16:38:13 +090042import android.service.textservice.SpellCheckerService;
satok53578062011-08-03 16:08:59 +090043import android.text.TextUtils;
satok988323c2011-06-22 16:38:13 +090044import android.util.Slog;
Guliz Tuncay06a26242017-06-30 18:32:04 -070045import android.util.SparseArray;
Yohei Yukawaa878b952019-01-10 19:36:24 -080046import android.view.inputmethod.InputMethodSystemProperty;
satok988323c2011-06-22 16:38:13 +090047import android.view.textservice.SpellCheckerInfo;
satokada8c4e2011-08-23 14:56:56 +090048import android.view.textservice.SpellCheckerSubtype;
satok988323c2011-06-22 16:38:13 +090049
Yohei Yukawa75504b12018-12-20 20:52:53 -080050import com.android.internal.annotations.GuardedBy;
51import com.android.internal.content.PackageMonitor;
52import com.android.internal.inputmethod.SubtypeLocaleUtils;
53import com.android.internal.textservice.ISpellCheckerService;
54import com.android.internal.textservice.ISpellCheckerServiceCallback;
55import com.android.internal.textservice.ISpellCheckerSession;
56import com.android.internal.textservice.ISpellCheckerSessionListener;
57import com.android.internal.textservice.ITextServicesManager;
58import com.android.internal.textservice.ITextServicesSessionListener;
59import com.android.internal.util.DumpUtils;
Yohei Yukawaafec9a242018-12-20 20:53:12 -080060import com.android.server.LocalServices;
Yohei Yukawa75504b12018-12-20 20:52:53 -080061import com.android.server.SystemService;
62
63import org.xmlpull.v1.XmlPullParserException;
64
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 Yukawab7dfb9b2018-06-19 12:55:07 -070068import java.lang.ref.WeakReference;
satok988323c2011-06-22 16:38:13 +090069import java.util.ArrayList;
Yohei Yukawa75504b12018-12-20 20:52:53 -080070import java.util.Arrays;
satok988323c2011-06-22 16:38:13 +090071import java.util.HashMap;
satok988323c2011-06-22 16:38:13 +090072import java.util.List;
Yohei Yukawa174843a2015-06-26 18:02:54 -070073import java.util.Locale;
Dianne Hackborn71e14da2011-10-16 16:28:10 -070074import java.util.Map;
Yohei Yukawabc601162018-06-17 21:08:20 -070075import java.util.Objects;
Yohei Yukawa73ac9472018-05-01 11:40:29 -070076import java.util.function.Predicate;
satok988323c2011-06-22 16:38:13 +090077
78public class TextServicesManagerService extends ITextServicesManager.Stub {
79 private static final String TAG = TextServicesManagerService.class.getSimpleName();
80 private static final boolean DBG = false;
81
82 private final Context mContext;
satok988323c2011-06-22 16:38:13 +090083 private final TextServicesMonitor mMonitor;
Guliz Tuncay06a26242017-06-30 18:32:04 -070084 private final SparseArray<TextServicesData> mUserData = new SparseArray<>();
Yohei Yukawaf0f16802016-03-08 16:04:58 -080085 @NonNull
86 private final UserManager mUserManager;
Guliz Tuncay10ae3852017-07-07 10:35:59 -070087 private final Object mLock = new Object();
satok988323c2011-06-22 16:38:13 +090088
Yohei Yukawa3f8c5682018-03-01 13:10:23 -080089 @NonNull
90 @GuardedBy("mLock")
91 private final LazyIntToIntMap mSpellCheckerOwnerUserIdMap;
92
Guliz Tuncay06a26242017-06-30 18:32:04 -070093 private static class TextServicesData {
94 @UserIdInt
95 private final int mUserId;
96 private final HashMap<String, SpellCheckerInfo> mSpellCheckerMap;
97 private final ArrayList<SpellCheckerInfo> mSpellCheckerList;
98 private final HashMap<String, SpellCheckerBindGroup> mSpellCheckerBindGroups;
Guliz Tuncay8e6fa022017-08-14 16:50:15 -070099 private final Context mContext;
100 private final ContentResolver mResolver;
101 public int mUpdateCount = 0;
Guliz Tuncay06a26242017-06-30 18:32:04 -0700102
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700103 public TextServicesData(@UserIdInt int userId, @NonNull Context context) {
Guliz Tuncay06a26242017-06-30 18:32:04 -0700104 mUserId = userId;
105 mSpellCheckerMap = new HashMap<>();
106 mSpellCheckerList = new ArrayList<>();
107 mSpellCheckerBindGroups = new HashMap<>();
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700108 mContext = context;
109 mResolver = context.getContentResolver();
110 }
111
112 private void putString(final String key, final String str) {
113 Settings.Secure.putStringForUser(mResolver, key, str, mUserId);
114 }
115
116 @Nullable
117 private String getString(@NonNull final String key, @Nullable final String defaultValue) {
118 final String result;
119 result = Settings.Secure.getStringForUser(mResolver, key, mUserId);
120 return result != null ? result : defaultValue;
121 }
122
123 private void putInt(final String key, final int value) {
124 Settings.Secure.putIntForUser(mResolver, key, value, mUserId);
125 }
126
127 private int getInt(final String key, final int defaultValue) {
128 return Settings.Secure.getIntForUser(mResolver, key, defaultValue, mUserId);
129 }
130
131 private boolean getBoolean(final String key, final boolean defaultValue) {
132 return getInt(key, defaultValue ? 1 : 0) == 1;
133 }
134
135 private void putSelectedSpellChecker(@Nullable String sciId) {
Guliz Tuncay83a73302017-08-17 15:25:38 -0700136 putString(Settings.Secure.SELECTED_SPELL_CHECKER, sciId);
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700137 }
138
139 private void putSelectedSpellCheckerSubtype(int hashCode) {
140 putInt(Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, hashCode);
141 }
142
143 @NonNull
144 private String getSelectedSpellChecker() {
145 return getString(Settings.Secure.SELECTED_SPELL_CHECKER, "");
146 }
147
148 public int getSelectedSpellCheckerSubtype(final int defaultValue) {
149 return getInt(Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, defaultValue);
150 }
151
152 public boolean isSpellCheckerEnabled() {
153 return getBoolean(Settings.Secure.SPELL_CHECKER_ENABLED, true);
154 }
155
156 @Nullable
157 public SpellCheckerInfo getCurrentSpellChecker() {
158 final String curSpellCheckerId = getSelectedSpellChecker();
159 if (TextUtils.isEmpty(curSpellCheckerId)) {
160 return null;
161 }
162 return mSpellCheckerMap.get(curSpellCheckerId);
163 }
164
Guliz Tuncay83a73302017-08-17 15:25:38 -0700165 public void setCurrentSpellChecker(@Nullable SpellCheckerInfo sci) {
166 if (sci != null) {
167 putSelectedSpellChecker(sci.getId());
168 } else {
169 putSelectedSpellChecker("");
170 }
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700171 putSelectedSpellCheckerSubtype(SpellCheckerSubtype.SUBTYPE_ID_NONE);
172 }
173
174 private void initializeTextServicesData() {
175 if (DBG) {
176 Slog.d(TAG, "initializeTextServicesData for user: " + mUserId);
177 }
178 mSpellCheckerList.clear();
179 mSpellCheckerMap.clear();
180 mUpdateCount++;
181 final PackageManager pm = mContext.getPackageManager();
182 // Note: We do not specify PackageManager.MATCH_ENCRYPTION_* flags here because the
183 // default behavior of PackageManager is exactly what we want. It by default picks up
184 // appropriate services depending on the unlock state for the specified user.
185 final List<ResolveInfo> services = pm.queryIntentServicesAsUser(
186 new Intent(SpellCheckerService.SERVICE_INTERFACE), PackageManager.GET_META_DATA,
187 mUserId);
188 final int N = services.size();
189 for (int i = 0; i < N; ++i) {
190 final ResolveInfo ri = services.get(i);
191 final ServiceInfo si = ri.serviceInfo;
192 final ComponentName compName = new ComponentName(si.packageName, si.name);
193 if (!android.Manifest.permission.BIND_TEXT_SERVICE.equals(si.permission)) {
194 Slog.w(TAG, "Skipping text service " + compName
195 + ": it does not require the permission "
196 + android.Manifest.permission.BIND_TEXT_SERVICE);
197 continue;
198 }
199 if (DBG) Slog.d(TAG, "Add: " + compName + " for user: " + mUserId);
200 try {
201 final SpellCheckerInfo sci = new SpellCheckerInfo(mContext, ri);
202 if (sci.getSubtypeCount() <= 0) {
203 Slog.w(TAG, "Skipping text service " + compName
204 + ": it does not contain subtypes.");
205 continue;
206 }
207 mSpellCheckerList.add(sci);
208 mSpellCheckerMap.put(sci.getId(), sci);
209 } catch (XmlPullParserException e) {
210 Slog.w(TAG, "Unable to load the spell checker " + compName, e);
211 } catch (IOException e) {
212 Slog.w(TAG, "Unable to load the spell checker " + compName, e);
213 }
214 }
215 if (DBG) {
216 Slog.d(TAG, "initializeSpellCheckerMap: " + mSpellCheckerList.size() + ","
217 + mSpellCheckerMap.size());
218 }
219 }
220
221 private void dump(PrintWriter pw) {
222 int spellCheckerIndex = 0;
223 pw.println(" User #" + mUserId);
224 pw.println(" Spell Checkers:");
225 pw.println(" Spell Checkers: " + "mUpdateCount=" + mUpdateCount);
226 for (final SpellCheckerInfo info : mSpellCheckerMap.values()) {
227 pw.println(" Spell Checker #" + spellCheckerIndex);
228 info.dump(pw, " ");
229 ++spellCheckerIndex;
230 }
231
232 pw.println("");
233 pw.println(" Spell Checker Bind Groups:");
234 HashMap<String, SpellCheckerBindGroup> spellCheckerBindGroups = mSpellCheckerBindGroups;
235 for (final Map.Entry<String, SpellCheckerBindGroup> ent
236 : spellCheckerBindGroups.entrySet()) {
237 final SpellCheckerBindGroup grp = ent.getValue();
238 pw.println(" " + ent.getKey() + " " + grp + ":");
239 pw.println(" " + "mInternalConnection=" + grp.mInternalConnection);
240 pw.println(" " + "mSpellChecker=" + grp.mSpellChecker);
241 pw.println(" " + "mUnbindCalled=" + grp.mUnbindCalled);
242 pw.println(" " + "mConnected=" + grp.mConnected);
243 final int numPendingSessionRequests = grp.mPendingSessionRequests.size();
244 for (int j = 0; j < numPendingSessionRequests; j++) {
245 final SessionRequest req = grp.mPendingSessionRequests.get(j);
246 pw.println(" " + "Pending Request #" + j + ":");
247 pw.println(" " + "mTsListener=" + req.mTsListener);
248 pw.println(" " + "mScListener=" + req.mScListener);
249 pw.println(
Yohei Yukawae4622842018-02-26 11:31:47 +0900250 " " + "mScLocale=" + req.mLocale + " mUid=" + req.mUid);
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700251 }
252 final int numOnGoingSessionRequests = grp.mOnGoingSessionRequests.size();
253 for (int j = 0; j < numOnGoingSessionRequests; j++) {
254 final SessionRequest req = grp.mOnGoingSessionRequests.get(j);
255 pw.println(" " + "On going Request #" + j + ":");
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700256 pw.println(" " + "mTsListener=" + req.mTsListener);
257 pw.println(" " + "mScListener=" + req.mScListener);
258 pw.println(
Yohei Yukawae4622842018-02-26 11:31:47 +0900259 " " + "mScLocale=" + req.mLocale + " mUid=" + req.mUid);
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700260 }
261 final int N = grp.mListeners.getRegisteredCallbackCount();
262 for (int j = 0; j < N; j++) {
263 final ISpellCheckerSessionListener mScListener =
264 grp.mListeners.getRegisteredCallbackItem(j);
265 pw.println(" " + "Listener #" + j + ":");
266 pw.println(" " + "mScListener=" + mScListener);
267 pw.println(" " + "mGroup=" + grp);
268 }
269 }
Guliz Tuncay06a26242017-06-30 18:32:04 -0700270 }
271 }
272
Yohei Yukawaa6a152e2016-03-07 13:41:15 -0800273 public static final class Lifecycle extends SystemService {
274 private TextServicesManagerService mService;
275
276 public Lifecycle(Context context) {
277 super(context);
278 mService = new TextServicesManagerService(context);
279 }
280
281 @Override
282 public void onStart() {
Yohei Yukawaafec9a242018-12-20 20:53:12 -0800283 LocalServices.addService(TextServicesManagerInternal.class,
284 new TextServicesManagerInternal() {
285 @Override
286 public SpellCheckerInfo getCurrentSpellCheckerForUser(
287 @UserIdInt int userId) {
288 return mService.getCurrentSpellCheckerForUser(userId);
289 }
290 });
Yohei Yukawaa6a152e2016-03-07 13:41:15 -0800291 publishBinderService(Context.TEXT_SERVICES_MANAGER_SERVICE, mService);
292 }
293
294 @Override
Guliz Tuncay06a26242017-06-30 18:32:04 -0700295 public void onStopUser(@UserIdInt int userHandle) {
296 if (DBG) {
297 Slog.d(TAG, "onStopUser userId: " + userHandle);
298 }
299 mService.onStopUser(userHandle);
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -0800300 }
301
302 @Override
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800303 public void onUnlockUser(@UserIdInt int userHandle) {
Guliz Tuncay06a26242017-06-30 18:32:04 -0700304 if(DBG) {
305 Slog.d(TAG, "onUnlockUser userId: " + userHandle);
306 }
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800307 // Called on the system server's main looper thread.
308 // TODO: Dispatch this to a worker thread as needed.
309 mService.onUnlockUser(userHandle);
310 }
Yohei Yukawaa6a152e2016-03-07 13:41:15 -0800311 }
312
Guliz Tuncay06a26242017-06-30 18:32:04 -0700313 void onStopUser(@UserIdInt int userId) {
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700314 synchronized (mLock) {
Yohei Yukawa3f8c5682018-03-01 13:10:23 -0800315 // Clear user ID mapping table.
316 mSpellCheckerOwnerUserIdMap.delete(userId);
317
Guliz Tuncay06a26242017-06-30 18:32:04 -0700318 // Clean per-user data
319 TextServicesData tsd = mUserData.get(userId);
320 if (tsd == null) return;
321
322 unbindServiceLocked(tsd); // Remove bind groups first
323 mUserData.remove(userId); // This needs to be done after bind groups are all removed
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800324 }
325 }
326
327 void onUnlockUser(@UserIdInt int userId) {
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700328 synchronized (mLock) {
Guliz Tuncay06a26242017-06-30 18:32:04 -0700329 // Initialize internal state for the given user
330 initializeInternalStateLocked(userId);
satok988323c2011-06-22 16:38:13 +0900331 }
332 }
333
334 public TextServicesManagerService(Context context) {
satok988323c2011-06-22 16:38:13 +0900335 mContext = context;
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800336 mUserManager = mContext.getSystemService(UserManager.class);
Yohei Yukawa3f8c5682018-03-01 13:10:23 -0800337 mSpellCheckerOwnerUserIdMap = new LazyIntToIntMap(callingUserId -> {
Yohei Yukawaa878b952019-01-10 19:36:24 -0800338 if (!InputMethodSystemProperty.PER_PROFILE_IME_ENABLED) {
Yohei Yukawa3f8c5682018-03-01 13:10:23 -0800339 final long token = Binder.clearCallingIdentity();
340 try {
341 final UserInfo parent = mUserManager.getProfileParent(callingUserId);
342 return (parent != null) ? parent.id : callingUserId;
343 } finally {
344 Binder.restoreCallingIdentity(token);
345 }
346 } else {
347 return callingUserId;
348 }
349 });
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800350
satok988323c2011-06-22 16:38:13 +0900351 mMonitor = new TextServicesMonitor();
Guliz Tuncay06a26242017-06-30 18:32:04 -0700352 mMonitor.register(context, null, UserHandle.ALL, true);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900353 }
354
Andreas Gamped6d42062018-07-20 13:08:21 -0700355 @GuardedBy("mLock")
Guliz Tuncay5e1d5d62017-07-26 11:19:08 -0700356 private void initializeInternalStateLocked(@UserIdInt int userId) {
Yohei Yukawa3f8c5682018-03-01 13:10:23 -0800357 // When DISABLE_PER_PROFILE_SPELL_CHECKER is true, we make sure here that work profile users
358 // will never have non-null TextServicesData for their user ID.
Yohei Yukawaa878b952019-01-10 19:36:24 -0800359 if (!InputMethodSystemProperty.PER_PROFILE_IME_ENABLED
Yohei Yukawa3f8c5682018-03-01 13:10:23 -0800360 && userId != mSpellCheckerOwnerUserIdMap.get(userId)) {
361 return;
362 }
363
Guliz Tuncay06a26242017-06-30 18:32:04 -0700364 TextServicesData tsd = mUserData.get(userId);
365 if (tsd == null) {
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700366 tsd = new TextServicesData(userId, mContext);
Guliz Tuncay06a26242017-06-30 18:32:04 -0700367 mUserData.put(userId, tsd);
368 }
369
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700370 tsd.initializeTextServicesData();
371 SpellCheckerInfo sci = tsd.getCurrentSpellChecker();
satokdf5659d2011-07-29 18:38:21 +0900372 if (sci == null) {
Guliz Tuncay0f0a37b2017-08-16 12:02:31 -0700373 sci = findAvailSystemSpellCheckerLocked(null, tsd);
Guliz Tuncay83a73302017-08-17 15:25:38 -0700374 // Set the current spell checker if there is one or more system spell checkers
375 // available. In this case, "sci" is the first one in the available spell
376 // checkers.
377 setCurrentSpellCheckerLocked(sci, tsd);
satokdf5659d2011-07-29 18:38:21 +0900378 }
satok988323c2011-06-22 16:38:13 +0900379 }
380
Guliz Tuncay06a26242017-06-30 18:32:04 -0700381 private final class TextServicesMonitor extends PackageMonitor {
satok988323c2011-06-22 16:38:13 +0900382 @Override
383 public void onSomePackagesChanged() {
Guliz Tuncay06a26242017-06-30 18:32:04 -0700384 int userId = getChangingUserId();
385 if(DBG) {
386 Slog.d(TAG, "onSomePackagesChanged: " + userId);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900387 }
Guliz Tuncay06a26242017-06-30 18:32:04 -0700388
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700389 synchronized (mLock) {
Guliz Tuncay06a26242017-06-30 18:32:04 -0700390 TextServicesData tsd = mUserData.get(userId);
391 if (tsd == null) return;
392
satok988323c2011-06-22 16:38:13 +0900393 // TODO: Update for each locale
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700394 SpellCheckerInfo sci = tsd.getCurrentSpellChecker();
395 tsd.initializeTextServicesData();
Guliz Tuncay83a73302017-08-17 15:25:38 -0700396 // If spell checker is disabled, just return. The user should explicitly
Satoshi Kataoka02260e22013-08-02 16:22:04 +0900397 // enable the spell checker.
Guliz Tuncay83a73302017-08-17 15:25:38 -0700398 if (!tsd.isSpellCheckerEnabled()) return;
399
400 if (sci == null) {
401 sci = findAvailSystemSpellCheckerLocked(null, tsd);
402 // Set the current spell checker if there is one or more system spell checkers
403 // available. In this case, "sci" is the first one in the available spell
404 // checkers.
405 setCurrentSpellCheckerLocked(sci, tsd);
406 } else {
407 final String packageName = sci.getPackageName();
408 final int change = isPackageDisappearing(packageName);
409 if (DBG) Slog.d(TAG, "Changing package name: " + packageName);
Yohei Yukawa4993f4e2018-05-01 15:22:27 -0700410 if (change == PACKAGE_PERMANENT_CHANGE || change == PACKAGE_TEMPORARY_CHANGE) {
Guliz Tuncay83a73302017-08-17 15:25:38 -0700411 SpellCheckerInfo availSci =
412 findAvailSystemSpellCheckerLocked(packageName, tsd);
413 // Set the spell checker settings if different than before
414 if (availSci == null
415 || (availSci != null && !availSci.getId().equals(sci.getId()))) {
416 setCurrentSpellCheckerLocked(availSci, tsd);
417 }
satok5b9b5a92011-08-02 12:24:44 +0900418 }
satok988323c2011-06-22 16:38:13 +0900419 }
420 }
421 }
422 }
423
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900424 private boolean bindCurrentSpellCheckerService(
Guliz Tuncay06a26242017-06-30 18:32:04 -0700425 Intent service, ServiceConnection conn, int flags, @UserIdInt int userId) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900426 if (service == null || conn == null) {
Guliz Tuncay06a26242017-06-30 18:32:04 -0700427 Slog.e(TAG, "--- bind failed: service = " + service + ", conn = " + conn +
428 ", userId =" + userId);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900429 return false;
430 }
Guliz Tuncay06a26242017-06-30 18:32:04 -0700431 return mContext.bindServiceAsUser(service, conn, flags, UserHandle.of(userId));
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900432 }
433
Guliz Tuncay06a26242017-06-30 18:32:04 -0700434 private void unbindServiceLocked(TextServicesData tsd) {
435 HashMap<String, SpellCheckerBindGroup> spellCheckerBindGroups = tsd.mSpellCheckerBindGroups;
436 for (SpellCheckerBindGroup scbg : spellCheckerBindGroups.values()) {
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700437 scbg.removeAllLocked();
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900438 }
Guliz Tuncay06a26242017-06-30 18:32:04 -0700439 spellCheckerBindGroups.clear();
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900440 }
441
Guliz Tuncay0f0a37b2017-08-16 12:02:31 -0700442 private SpellCheckerInfo findAvailSystemSpellCheckerLocked(String prefPackage,
Guliz Tuncay06a26242017-06-30 18:32:04 -0700443 TextServicesData tsd) {
Guliz Tuncay0f0a37b2017-08-16 12:02:31 -0700444 // Filter the spell checker list to remove spell checker services that are not pre-installed
445 ArrayList<SpellCheckerInfo> spellCheckerList = new ArrayList<>();
446 for (SpellCheckerInfo sci : tsd.mSpellCheckerList) {
447 if ((sci.getServiceInfo().applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
448 spellCheckerList.add(sci);
449 }
450 }
451
Guliz Tuncay06a26242017-06-30 18:32:04 -0700452 final int spellCheckersCount = spellCheckerList.size();
satok988323c2011-06-22 16:38:13 +0900453 if (spellCheckersCount == 0) {
454 Slog.w(TAG, "no available spell checker services found");
455 return null;
456 }
457 if (prefPackage != null) {
458 for (int i = 0; i < spellCheckersCount; ++i) {
Guliz Tuncay06a26242017-06-30 18:32:04 -0700459 final SpellCheckerInfo sci = spellCheckerList.get(i);
satok988323c2011-06-22 16:38:13 +0900460 if (prefPackage.equals(sci.getPackageName())) {
satokda317ef2011-07-26 08:02:45 +0900461 if (DBG) {
Guliz Tuncay0f0a37b2017-08-16 12:02:31 -0700462 Slog.d(TAG, "findAvailSystemSpellCheckerLocked: " + sci.getPackageName());
satokda317ef2011-07-26 08:02:45 +0900463 }
satok988323c2011-06-22 16:38:13 +0900464 return sci;
465 }
466 }
467 }
Yohei Yukawa174843a2015-06-26 18:02:54 -0700468
469 // Look up a spell checker based on the system locale.
470 // TODO: Still there is a room to improve in the following logic: e.g., check if the package
471 // is pre-installed or not.
472 final Locale systemLocal = mContext.getResources().getConfiguration().locale;
473 final ArrayList<Locale> suitableLocales =
Yohei Yukawa3781ca82018-09-12 15:36:03 -0700474 LocaleUtils.getSuitableLocalesForSpellChecker(systemLocal);
Yohei Yukawa174843a2015-06-26 18:02:54 -0700475 if (DBG) {
Guliz Tuncay0f0a37b2017-08-16 12:02:31 -0700476 Slog.w(TAG, "findAvailSystemSpellCheckerLocked suitableLocales="
Yohei Yukawa174843a2015-06-26 18:02:54 -0700477 + Arrays.toString(suitableLocales.toArray(new Locale[suitableLocales.size()])));
478 }
479 final int localeCount = suitableLocales.size();
480 for (int localeIndex = 0; localeIndex < localeCount; ++localeIndex) {
481 final Locale locale = suitableLocales.get(localeIndex);
482 for (int spellCheckersIndex = 0; spellCheckersIndex < spellCheckersCount;
483 ++spellCheckersIndex) {
Guliz Tuncay06a26242017-06-30 18:32:04 -0700484 final SpellCheckerInfo info = spellCheckerList.get(spellCheckersIndex);
Yohei Yukawa174843a2015-06-26 18:02:54 -0700485 final int subtypeCount = info.getSubtypeCount();
486 for (int subtypeIndex = 0; subtypeIndex < subtypeCount; ++subtypeIndex) {
487 final SpellCheckerSubtype subtype = info.getSubtypeAt(subtypeIndex);
Yohei Yukawa835ab942018-09-12 16:23:26 -0700488 final Locale subtypeLocale = SubtypeLocaleUtils.constructLocaleFromString(
Yohei Yukawa174843a2015-06-26 18:02:54 -0700489 subtype.getLocale());
490 if (locale.equals(subtypeLocale)) {
491 // TODO: We may have more spell checkers that fall into this category.
492 // Ideally we should pick up the most suitable one instead of simply
493 // returning the first found one.
494 return info;
495 }
496 }
497 }
498 }
499
satok988323c2011-06-22 16:38:13 +0900500 if (spellCheckersCount > 1) {
501 Slog.w(TAG, "more than one spell checker service found, picking first");
502 }
Guliz Tuncay06a26242017-06-30 18:32:04 -0700503 return spellCheckerList.get(0);
satok988323c2011-06-22 16:38:13 +0900504 }
505
Yohei Yukawaafec9a242018-12-20 20:53:12 -0800506 @Nullable
507 private SpellCheckerInfo getCurrentSpellCheckerForUser(@UserIdInt int userId) {
508 synchronized (mLock) {
509 final int spellCheckerOwnerUserId = mSpellCheckerOwnerUserIdMap.get(userId);
510 final TextServicesData data = mUserData.get(spellCheckerOwnerUserId);
511 return data != null ? data.getCurrentSpellChecker() : null;
512 }
513 }
514
satok988323c2011-06-22 16:38:13 +0900515 // TODO: Save SpellCheckerService by supported languages. Currently only one spell
516 // checker is saved.
517 @Override
Yohei Yukawa9f141ee2019-01-18 09:17:16 -0800518 public SpellCheckerInfo getCurrentSpellChecker(@UserIdInt int userId, String locale) {
519 verifyUser(userId);
Guliz Tuncay06a26242017-06-30 18:32:04 -0700520 synchronized (mLock) {
Yohei Yukawa3f8c5682018-03-01 13:10:23 -0800521 final TextServicesData tsd = getDataFromCallingUserIdLocked(userId);
Guliz Tuncay06a26242017-06-30 18:32:04 -0700522 if (tsd == null) return null;
523
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700524 return tsd.getCurrentSpellChecker();
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900525 }
Yohei Yukawa095fa372014-10-27 14:02:23 +0900526 }
527
satok3cb5b392011-08-26 11:55:21 +0900528 // TODO: Respect allowImplicitlySelectedSubtype
Satoshi Kataoka17150cf2012-05-30 20:05:44 +0900529 // TODO: Save SpellCheckerSubtype by supported languages by looking at "locale".
satokada8c4e2011-08-23 14:56:56 +0900530 @Override
satok3cb5b392011-08-26 11:55:21 +0900531 public SpellCheckerSubtype getCurrentSpellCheckerSubtype(
Yohei Yukawa9f141ee2019-01-18 09:17:16 -0800532 @UserIdInt int userId, boolean allowImplicitlySelectedSubtype) {
533 verifyUser(userId);
534
Yohei Yukawae3e31a82016-09-20 06:43:03 -0700535 final int subtypeHashCode;
536 final SpellCheckerInfo sci;
537 final Locale systemLocale;
Guliz Tuncay06a26242017-06-30 18:32:04 -0700538
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700539 synchronized (mLock) {
Yohei Yukawa3f8c5682018-03-01 13:10:23 -0800540 final TextServicesData tsd = getDataFromCallingUserIdLocked(userId);
Guliz Tuncay06a26242017-06-30 18:32:04 -0700541 if (tsd == null) return null;
542
Yohei Yukawae3e31a82016-09-20 06:43:03 -0700543 subtypeHashCode =
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700544 tsd.getSelectedSpellCheckerSubtype(SpellCheckerSubtype.SUBTYPE_ID_NONE);
satokada8c4e2011-08-23 14:56:56 +0900545 if (DBG) {
Yohei Yukawaad150ee2016-03-16 17:22:27 -0700546 Slog.w(TAG, "getCurrentSpellCheckerSubtype: " + subtypeHashCode);
satokada8c4e2011-08-23 14:56:56 +0900547 }
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700548 sci = tsd.getCurrentSpellChecker();
Yohei Yukawae3e31a82016-09-20 06:43:03 -0700549 systemLocale = mContext.getResources().getConfiguration().locale;
satokada8c4e2011-08-23 14:56:56 +0900550 }
Yohei Yukawae3e31a82016-09-20 06:43:03 -0700551 if (sci == null || sci.getSubtypeCount() == 0) {
552 if (DBG) {
553 Slog.w(TAG, "Subtype not found.");
554 }
555 return null;
556 }
557 if (subtypeHashCode == SpellCheckerSubtype.SUBTYPE_ID_NONE
558 && !allowImplicitlySelectedSubtype) {
559 return null;
560 }
Yohei Yukawa6def6cd2018-06-15 16:36:51 -0700561
562 final int numSubtypes = sci.getSubtypeCount();
563 if (subtypeHashCode != 0) {
564 // Use the user specified spell checker subtype
565 for (int i = 0; i < numSubtypes; ++i) {
566 final SpellCheckerSubtype scs = sci.getSubtypeAt(i);
567 if (scs.hashCode() == subtypeHashCode) {
568 return scs;
569 }
570 }
571 return null;
572 }
573
574 // subtypeHashCode == 0 means spell checker language settings is "auto"
575
576 if (systemLocale == null) {
577 return null;
578 }
579 SpellCheckerSubtype firstLanguageMatchingSubtype = null;
Yohei Yukawae3e31a82016-09-20 06:43:03 -0700580 for (int i = 0; i < sci.getSubtypeCount(); ++i) {
581 final SpellCheckerSubtype scs = sci.getSubtypeAt(i);
Yohei Yukawa6def6cd2018-06-15 16:36:51 -0700582 final Locale scsLocale = scs.getLocaleObject();
583 if (Objects.equals(scsLocale, systemLocale)) {
584 // Exact match wins.
Yohei Yukawae3e31a82016-09-20 06:43:03 -0700585 return scs;
586 }
Yohei Yukawa6def6cd2018-06-15 16:36:51 -0700587 if (firstLanguageMatchingSubtype == null && scsLocale != null
588 && TextUtils.equals(systemLocale.getLanguage(), scsLocale.getLanguage())) {
589 // Remember as a fall back candidate
590 firstLanguageMatchingSubtype = scs;
591 }
Yohei Yukawae3e31a82016-09-20 06:43:03 -0700592 }
Yohei Yukawa6def6cd2018-06-15 16:36:51 -0700593 return firstLanguageMatchingSubtype;
satokada8c4e2011-08-23 14:56:56 +0900594 }
595
satok988323c2011-06-22 16:38:13 +0900596 @Override
Yohei Yukawa9f141ee2019-01-18 09:17:16 -0800597 public void getSpellCheckerService(@UserIdInt int userId, String sciId, String locale,
satok53578062011-08-03 16:08:59 +0900598 ITextServicesSessionListener tsListener, ISpellCheckerSessionListener scListener,
599 Bundle bundle) {
Yohei Yukawa9f141ee2019-01-18 09:17:16 -0800600 verifyUser(userId);
satok5b9b5a92011-08-02 12:24:44 +0900601 if (TextUtils.isEmpty(sciId) || tsListener == null || scListener == null) {
satok988323c2011-06-22 16:38:13 +0900602 Slog.e(TAG, "getSpellCheckerService: Invalid input.");
603 return;
604 }
Guliz Tuncay06a26242017-06-30 18:32:04 -0700605
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700606 synchronized (mLock) {
Yohei Yukawa9f141ee2019-01-18 09:17:16 -0800607 final TextServicesData tsd = getDataFromCallingUserIdLocked(userId);
Guliz Tuncay06a26242017-06-30 18:32:04 -0700608 if (tsd == null) return;
609
610 HashMap<String, SpellCheckerInfo> spellCheckerMap = tsd.mSpellCheckerMap;
611 if (!spellCheckerMap.containsKey(sciId)) {
satok988323c2011-06-22 16:38:13 +0900612 return;
613 }
Guliz Tuncay06a26242017-06-30 18:32:04 -0700614 final SpellCheckerInfo sci = spellCheckerMap.get(sciId);
615 HashMap<String, SpellCheckerBindGroup> spellCheckerBindGroups =
616 tsd.mSpellCheckerBindGroups;
617 SpellCheckerBindGroup bindGroup = spellCheckerBindGroups.get(sciId);
satokdf5659d2011-07-29 18:38:21 +0900618 final int uid = Binder.getCallingUid();
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800619 if (bindGroup == null) {
620 final long ident = Binder.clearCallingIdentity();
621 try {
Guliz Tuncay06a26242017-06-30 18:32:04 -0700622 bindGroup = startSpellCheckerServiceInnerLocked(sci, tsd);
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800623 } finally {
624 Binder.restoreCallingIdentity(ident);
625 }
626 if (bindGroup == null) {
627 // startSpellCheckerServiceInnerLocked failed.
628 return;
satok6be6d752011-07-28 20:40:38 +0900629 }
satok988323c2011-06-22 16:38:13 +0900630 }
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800631
632 // Start getISpellCheckerSession async IPC, or just queue the request until the spell
633 // checker service is bound.
634 bindGroup.getISpellCheckerSessionOrQueueLocked(
Guliz Tuncay5e1d5d62017-07-26 11:19:08 -0700635 new SessionRequest(uid, locale, tsListener, scListener, bundle));
satok988323c2011-06-22 16:38:13 +0900636 }
satok988323c2011-06-22 16:38:13 +0900637 }
638
satoka33c4fc2011-08-25 16:50:11 +0900639 @Override
Yohei Yukawa9f141ee2019-01-18 09:17:16 -0800640 public boolean isSpellCheckerEnabled(@UserIdInt int userId) {
641 verifyUser(userId);
Guliz Tuncay06a26242017-06-30 18:32:04 -0700642
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700643 synchronized (mLock) {
Yohei Yukawa3f8c5682018-03-01 13:10:23 -0800644 final TextServicesData tsd = getDataFromCallingUserIdLocked(userId);
Guliz Tuncay06a26242017-06-30 18:32:04 -0700645 if (tsd == null) return false;
646
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700647 return tsd.isSpellCheckerEnabled();
satoka33c4fc2011-08-25 16:50:11 +0900648 }
649 }
650
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800651 @Nullable
Guliz Tuncay06a26242017-06-30 18:32:04 -0700652 private SpellCheckerBindGroup startSpellCheckerServiceInnerLocked(SpellCheckerInfo info,
653 TextServicesData tsd) {
satokdf5659d2011-07-29 18:38:21 +0900654 if (DBG) {
655 Slog.w(TAG, "Start spell checker session inner locked.");
656 }
satok6be6d752011-07-28 20:40:38 +0900657 final String sciId = info.getId();
Guliz Tuncay06a26242017-06-30 18:32:04 -0700658 final InternalServiceConnection connection = new InternalServiceConnection(sciId,
659 tsd.mSpellCheckerBindGroups);
satok6be6d752011-07-28 20:40:38 +0900660 final Intent serviceIntent = new Intent(SpellCheckerService.SERVICE_INTERFACE);
661 serviceIntent.setComponent(info.getComponent());
662 if (DBG) {
663 Slog.w(TAG, "bind service: " + info.getId());
664 }
Dianne Hackbornd69e4c12015-04-24 09:54:54 -0700665 if (!bindCurrentSpellCheckerService(serviceIntent, connection,
Guliz Tuncay06a26242017-06-30 18:32:04 -0700666 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT_BACKGROUND, tsd.mUserId)) {
satok6be6d752011-07-28 20:40:38 +0900667 Slog.e(TAG, "Failed to get a spell checker service.");
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800668 return null;
satok6be6d752011-07-28 20:40:38 +0900669 }
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800670 final SpellCheckerBindGroup group = new SpellCheckerBindGroup(connection);
Guliz Tuncay06a26242017-06-30 18:32:04 -0700671
672 tsd.mSpellCheckerBindGroups.put(sciId, group);
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800673 return group;
satok6be6d752011-07-28 20:40:38 +0900674 }
675
satok988323c2011-06-22 16:38:13 +0900676 @Override
Yohei Yukawa9f141ee2019-01-18 09:17:16 -0800677 public SpellCheckerInfo[] getEnabledSpellCheckers(@UserIdInt int userId) {
678 verifyUser(userId);
Guliz Tuncay06a26242017-06-30 18:32:04 -0700679
680 synchronized (mLock) {
Yohei Yukawa9f141ee2019-01-18 09:17:16 -0800681 final TextServicesData tsd = getDataFromCallingUserIdLocked(userId);
Guliz Tuncay06a26242017-06-30 18:32:04 -0700682 if (tsd == null) return null;
683
684 ArrayList<SpellCheckerInfo> spellCheckerList = tsd.mSpellCheckerList;
685 if (DBG) {
686 Slog.d(TAG, "getEnabledSpellCheckers: " + spellCheckerList.size());
687 for (int i = 0; i < spellCheckerList.size(); ++i) {
688 Slog.d(TAG,
689 "EnabledSpellCheckers: " + spellCheckerList.get(i).getPackageName());
690 }
satokda317ef2011-07-26 08:02:45 +0900691 }
Guliz Tuncay06a26242017-06-30 18:32:04 -0700692 return spellCheckerList.toArray(new SpellCheckerInfo[spellCheckerList.size()]);
satokda317ef2011-07-26 08:02:45 +0900693 }
satok562ab582011-07-25 10:12:21 +0900694 }
695
696 @Override
Yohei Yukawa9f141ee2019-01-18 09:17:16 -0800697 public void finishSpellCheckerService(@UserIdInt int userId,
698 ISpellCheckerSessionListener listener) {
satokda317ef2011-07-26 08:02:45 +0900699 if (DBG) {
700 Slog.d(TAG, "FinishSpellCheckerService");
701 }
Yohei Yukawa9f141ee2019-01-18 09:17:16 -0800702 verifyUser(userId);
Guliz Tuncay06a26242017-06-30 18:32:04 -0700703
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700704 synchronized (mLock) {
Yohei Yukawa3f8c5682018-03-01 13:10:23 -0800705 final TextServicesData tsd = getDataFromCallingUserIdLocked(userId);
Guliz Tuncay06a26242017-06-30 18:32:04 -0700706 if (tsd == null) return;
707
Yohei Yukawa074637f2016-03-06 14:34:55 -0800708 final ArrayList<SpellCheckerBindGroup> removeList = new ArrayList<>();
Guliz Tuncay06a26242017-06-30 18:32:04 -0700709 HashMap<String, SpellCheckerBindGroup> spellCheckerBindGroups =
710 tsd.mSpellCheckerBindGroups;
711 for (SpellCheckerBindGroup group : spellCheckerBindGroups.values()) {
satok988323c2011-06-22 16:38:13 +0900712 if (group == null) continue;
satok4c3fa642011-11-30 18:17:59 +0900713 // Use removeList to avoid modifying mSpellCheckerBindGroups in this loop.
714 removeList.add(group);
715 }
716 final int removeSize = removeList.size();
717 for (int i = 0; i < removeSize; ++i) {
718 removeList.get(i).removeListener(listener);
satok988323c2011-06-22 16:38:13 +0900719 }
720 }
721 }
722
Yohei Yukawa9f141ee2019-01-18 09:17:16 -0800723 private void verifyUser(@UserIdInt int userId) {
724 final int callingUserId = UserHandle.getCallingUserId();
725 if (userId != callingUserId) {
726 mContext.enforceCallingPermission(INTERACT_ACROSS_USERS_FULL,
727 "Cross-user interaction requires INTERACT_ACROSS_USERS_FULL. userId=" + userId
728 + " callingUserId=" + callingUserId);
729 }
730 }
731
Guliz Tuncay83a73302017-08-17 15:25:38 -0700732 private void setCurrentSpellCheckerLocked(@Nullable SpellCheckerInfo sci, TextServicesData tsd) {
733 final String sciId = (sci != null) ? sci.getId() : "";
satok562ab582011-07-25 10:12:21 +0900734 if (DBG) {
satok5b9b5a92011-08-02 12:24:44 +0900735 Slog.w(TAG, "setCurrentSpellChecker: " + sciId);
satok562ab582011-07-25 10:12:21 +0900736 }
satokdf5659d2011-07-29 18:38:21 +0900737 final long ident = Binder.clearCallingIdentity();
738 try {
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700739 tsd.setCurrentSpellChecker(sci);
satoka33c4fc2011-08-25 16:50:11 +0900740 } finally {
741 Binder.restoreCallingIdentity(ident);
742 }
743 }
744
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700745 @Override
746 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600747 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700748
Yohei Yukawa02f646e2018-01-24 17:50:32 -0800749 if (args.length == 0 || (args.length == 1 && args[0].equals("-a"))) {
750 // Dump all users' data
Guliz Tuncay06a26242017-06-30 18:32:04 -0700751 synchronized (mLock) {
752 pw.println("Current Text Services Manager state:");
Guliz Tuncay06a26242017-06-30 18:32:04 -0700753 pw.println(" Users:");
754 final int numOfUsers = mUserData.size();
755 for (int i = 0; i < numOfUsers; i++) {
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700756 TextServicesData tsd = mUserData.valueAt(i);
757 tsd.dump(pw);
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700758 }
759 }
Guliz Tuncay06a26242017-06-30 18:32:04 -0700760 } else { // Dump a given user's data
761 if (args.length != 2 || !args[0].equals("--user")) {
762 pw.println("Invalid arguments to text services." );
763 return;
764 } else {
765 int userId = Integer.parseInt(args[1]);
766 UserInfo userInfo = mUserManager.getUserInfo(userId);
767 if (userInfo == null) {
768 pw.println("Non-existent user.");
769 return;
770 }
771 TextServicesData tsd = mUserData.get(userId);
772 if (tsd == null) {
773 pw.println("User needs to unlock first." );
774 return;
775 }
776 synchronized (mLock) {
777 pw.println("Current Text Services Manager state:");
Guliz Tuncay06a26242017-06-30 18:32:04 -0700778 pw.println(" User " + userId + ":");
Guliz Tuncay8e6fa022017-08-14 16:50:15 -0700779 tsd.dump(pw);
Guliz Tuncay06a26242017-06-30 18:32:04 -0700780 }
781 }
782 }
783 }
784
Yohei Yukawa3f8c5682018-03-01 13:10:23 -0800785 /**
786 * @param callingUserId user ID of the calling process
787 * @return {@link TextServicesData} for the given user. {@code null} if spell checker is not
788 * temporarily / permanently available for the specified user
789 */
Andreas Gamped6d42062018-07-20 13:08:21 -0700790 @GuardedBy("mLock")
Yohei Yukawa3f8c5682018-03-01 13:10:23 -0800791 @Nullable
792 private TextServicesData getDataFromCallingUserIdLocked(@UserIdInt int callingUserId) {
793 final int spellCheckerOwnerUserId = mSpellCheckerOwnerUserIdMap.get(callingUserId);
794 final TextServicesData data = mUserData.get(spellCheckerOwnerUserId);
Yohei Yukawaa878b952019-01-10 19:36:24 -0800795 if (!InputMethodSystemProperty.PER_PROFILE_IME_ENABLED) {
Yohei Yukawa3f8c5682018-03-01 13:10:23 -0800796 if (spellCheckerOwnerUserId != callingUserId) {
797 // Calling process is running under child profile.
798 if (data == null) {
799 return null;
800 }
801 final SpellCheckerInfo info = data.getCurrentSpellChecker();
802 if (info == null) {
803 return null;
804 }
805 final ServiceInfo serviceInfo = info.getServiceInfo();
806 if ((serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
807 // To be conservative, non pre-installed spell checker services are not allowed
808 // to be used for child profiles.
809 return null;
810 }
811 }
812 }
813 return data;
814 }
815
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800816 private static final class SessionRequest {
Yohei Yukawae4622842018-02-26 11:31:47 +0900817 public final int mUid;
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800818 @Nullable
819 public final String mLocale;
820 @NonNull
821 public final ITextServicesSessionListener mTsListener;
822 @NonNull
823 public final ISpellCheckerSessionListener mScListener;
824 @Nullable
825 public final Bundle mBundle;
826
Yohei Yukawae4622842018-02-26 11:31:47 +0900827 SessionRequest(int uid, @Nullable String locale,
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800828 @NonNull ITextServicesSessionListener tsListener,
829 @NonNull ISpellCheckerSessionListener scListener, @Nullable Bundle bundle) {
Yohei Yukawae4622842018-02-26 11:31:47 +0900830 mUid = uid;
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800831 mLocale = locale;
832 mTsListener = tsListener;
833 mScListener = scListener;
834 mBundle = bundle;
835 }
836 }
837
satok988323c2011-06-22 16:38:13 +0900838 // SpellCheckerBindGroup contains active text service session listeners.
839 // If there are no listeners anymore, the SpellCheckerBindGroup instance will be removed from
840 // mSpellCheckerBindGroups
Yohei Yukawa06b4be72017-01-29 14:08:17 -0800841 private final class SpellCheckerBindGroup {
satokdf5659d2011-07-29 18:38:21 +0900842 private final String TAG = SpellCheckerBindGroup.class.getSimpleName();
satok6be6d752011-07-28 20:40:38 +0900843 private final InternalServiceConnection mInternalConnection;
Guliz Tuncayf982e752017-06-14 09:33:16 -0700844 private final InternalDeathRecipients mListeners;
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800845 private boolean mUnbindCalled;
846 private ISpellCheckerService mSpellChecker;
847 private boolean mConnected;
848 private final ArrayList<SessionRequest> mPendingSessionRequests = new ArrayList<>();
849 private final ArrayList<SessionRequest> mOnGoingSessionRequests = new ArrayList<>();
Guliz Tuncay06a26242017-06-30 18:32:04 -0700850 @NonNull
851 HashMap<String, SpellCheckerBindGroup> mSpellCheckerBindGroups;
852
satok988323c2011-06-22 16:38:13 +0900853
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800854 public SpellCheckerBindGroup(InternalServiceConnection connection) {
satok988323c2011-06-22 16:38:13 +0900855 mInternalConnection = connection;
Guliz Tuncayf982e752017-06-14 09:33:16 -0700856 mListeners = new InternalDeathRecipients(this);
Guliz Tuncay06a26242017-06-30 18:32:04 -0700857 mSpellCheckerBindGroups = connection.mSpellCheckerBindGroups;
satok988323c2011-06-22 16:38:13 +0900858 }
859
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700860 public void onServiceConnectedLocked(ISpellCheckerService spellChecker) {
satokda317ef2011-07-26 08:02:45 +0900861 if (DBG) {
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700862 Slog.d(TAG, "onServiceConnectedLocked");
satokda317ef2011-07-26 08:02:45 +0900863 }
satok4e713f12012-02-28 16:51:15 +0900864
Yohei Yukawa4163a962017-08-07 10:17:59 -0700865 if (mUnbindCalled) {
866 return;
satok988323c2011-06-22 16:38:13 +0900867 }
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700868 mSpellChecker = spellChecker;
869 mConnected = true;
870 // Dispatch pending getISpellCheckerSession requests.
Yohei Yukawa4163a962017-08-07 10:17:59 -0700871 try {
872 final int size = mPendingSessionRequests.size();
873 for (int i = 0; i < size; ++i) {
874 final SessionRequest request = mPendingSessionRequests.get(i);
875 mSpellChecker.getISpellCheckerSession(
876 request.mLocale, request.mScListener, request.mBundle,
877 new ISpellCheckerServiceCallbackBinder(this, request));
878 mOnGoingSessionRequests.add(request);
879 }
880 mPendingSessionRequests.clear();
881 } catch(RemoteException e) {
882 // The target spell checker service is not available. Better to reset the state.
883 removeAllLocked();
884 }
885 cleanLocked();
satok988323c2011-06-22 16:38:13 +0900886 }
887
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700888 public void onServiceDisconnectedLocked() {
Guliz Tuncay787aa8c2017-06-19 17:15:40 -0700889 if (DBG) {
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700890 Slog.d(TAG, "onServiceDisconnectedLocked");
Guliz Tuncay787aa8c2017-06-19 17:15:40 -0700891 }
892
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700893 mSpellChecker = null;
894 mConnected = false;
Guliz Tuncay787aa8c2017-06-19 17:15:40 -0700895 }
896
satok988323c2011-06-22 16:38:13 +0900897 public void removeListener(ISpellCheckerSessionListener listener) {
satokda317ef2011-07-26 08:02:45 +0900898 if (DBG) {
satokdf5659d2011-07-29 18:38:21 +0900899 Slog.w(TAG, "remove listener: " + listener.hashCode());
satokda317ef2011-07-26 08:02:45 +0900900 }
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700901 synchronized (mLock) {
Guliz Tuncayf982e752017-06-14 09:33:16 -0700902 mListeners.unregister(listener);
Yohei Yukawa73ac9472018-05-01 11:40:29 -0700903 final IBinder scListenerBinder = listener.asBinder();
904 final Predicate<SessionRequest> removeCondition =
905 request -> request.mScListener.asBinder() == scListenerBinder;
906 mPendingSessionRequests.removeIf(removeCondition);
907 mOnGoingSessionRequests.removeIf(removeCondition);
satok988323c2011-06-22 16:38:13 +0900908 cleanLocked();
909 }
910 }
911
satok4c3fa642011-11-30 18:17:59 +0900912 // cleanLocked may remove elements from mSpellCheckerBindGroups
satok988323c2011-06-22 16:38:13 +0900913 private void cleanLocked() {
satokda317ef2011-07-26 08:02:45 +0900914 if (DBG) {
915 Slog.d(TAG, "cleanLocked");
916 }
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800917 if (mUnbindCalled) {
918 return;
satok988323c2011-06-22 16:38:13 +0900919 }
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800920 // If there are no more active listeners, clean up. Only do this once.
Guliz Tuncayf982e752017-06-14 09:33:16 -0700921 if (mListeners.getRegisteredCallbackCount() > 0) {
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800922 return;
923 }
924 if (!mPendingSessionRequests.isEmpty()) {
925 return;
926 }
927 if (!mOnGoingSessionRequests.isEmpty()) {
928 return;
929 }
930 final String sciId = mInternalConnection.mSciId;
931 final SpellCheckerBindGroup cur = mSpellCheckerBindGroups.get(sciId);
932 if (cur == this) {
933 if (DBG) {
934 Slog.d(TAG, "Remove bind group.");
935 }
936 mSpellCheckerBindGroups.remove(sciId);
937 }
938 mContext.unbindService(mInternalConnection);
939 mUnbindCalled = true;
satok988323c2011-06-22 16:38:13 +0900940 }
satok6be6d752011-07-28 20:40:38 +0900941
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700942 public void removeAllLocked() {
satok6be6d752011-07-28 20:40:38 +0900943 Slog.e(TAG, "Remove the spell checker bind unexpectedly.");
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700944 final int size = mListeners.getRegisteredCallbackCount();
945 for (int i = size - 1; i >= 0; --i) {
946 mListeners.unregister(mListeners.getRegisteredCallbackItem(i));
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800947 }
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700948 mPendingSessionRequests.clear();
949 mOnGoingSessionRequests.clear();
950 cleanLocked();
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800951 }
952
953 public void getISpellCheckerSessionOrQueueLocked(@NonNull SessionRequest request) {
954 if (mUnbindCalled) {
955 return;
956 }
Yohei Yukawa73ac9472018-05-01 11:40:29 -0700957 mListeners.register(request.mScListener);
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800958 if (!mConnected) {
959 mPendingSessionRequests.add(request);
960 return;
961 }
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800962 try {
963 mSpellChecker.getISpellCheckerSession(
964 request.mLocale, request.mScListener, request.mBundle,
965 new ISpellCheckerServiceCallbackBinder(this, request));
966 mOnGoingSessionRequests.add(request);
967 } catch(RemoteException e) {
968 // The target spell checker service is not available. Better to reset the state.
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700969 removeAllLocked();
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800970 }
971 cleanLocked();
972 }
973
974 void onSessionCreated(@Nullable final ISpellCheckerSession newSession,
975 @NonNull final SessionRequest request) {
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700976 synchronized (mLock) {
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800977 if (mUnbindCalled) {
978 return;
979 }
980 if (mOnGoingSessionRequests.remove(request)) {
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800981 try {
982 request.mTsListener.onServiceConnected(newSession);
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800983 } catch (RemoteException e) {
984 // Technically this can happen if the spell checker client app is already
985 // dead. We can just forget about this request; the request is already
986 // removed from mOnGoingSessionRequests and the death recipient listener is
987 // not yet added to mListeners. There is nothing to release further.
988 }
989 }
satokdf5659d2011-07-29 18:38:21 +0900990 cleanLocked();
991 }
satok6be6d752011-07-28 20:40:38 +0900992 }
satok988323c2011-06-22 16:38:13 +0900993 }
994
Yohei Yukawa06b4be72017-01-29 14:08:17 -0800995 private final class InternalServiceConnection implements ServiceConnection {
satok988323c2011-06-22 16:38:13 +0900996 private final String mSciId;
Guliz Tuncay06a26242017-06-30 18:32:04 -0700997 @NonNull
998 private final HashMap<String, SpellCheckerBindGroup> mSpellCheckerBindGroups;
999 public InternalServiceConnection(String id,
1000 @NonNull HashMap<String, SpellCheckerBindGroup> spellCheckerBindGroups) {
satok988323c2011-06-22 16:38:13 +09001001 mSciId = id;
Guliz Tuncay06a26242017-06-30 18:32:04 -07001002 mSpellCheckerBindGroups = spellCheckerBindGroups;
satok988323c2011-06-22 16:38:13 +09001003 }
1004
1005 @Override
1006 public void onServiceConnected(ComponentName name, IBinder service) {
Guliz Tuncay10ae3852017-07-07 10:35:59 -07001007 synchronized (mLock) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001008 onServiceConnectedInnerLocked(name, service);
1009 }
1010 }
1011
1012 private void onServiceConnectedInnerLocked(ComponentName name, IBinder service) {
1013 if (DBG) {
Yohei Yukawa1854cb52017-08-07 10:17:46 -07001014 Slog.w(TAG, "onServiceConnectedInnerLocked: " + name);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001015 }
1016 final ISpellCheckerService spellChecker =
1017 ISpellCheckerService.Stub.asInterface(service);
Guliz Tuncay06a26242017-06-30 18:32:04 -07001018
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001019 final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId);
1020 if (group != null && this == group.mInternalConnection) {
Yohei Yukawa1854cb52017-08-07 10:17:46 -07001021 group.onServiceConnectedLocked(spellChecker);
satok988323c2011-06-22 16:38:13 +09001022 }
1023 }
1024
1025 @Override
1026 public void onServiceDisconnected(ComponentName name) {
Guliz Tuncay10ae3852017-07-07 10:35:59 -07001027 synchronized (mLock) {
Guliz Tuncay787aa8c2017-06-19 17:15:40 -07001028 onServiceDisconnectedInnerLocked(name);
1029 }
1030 }
1031
1032 private void onServiceDisconnectedInnerLocked(ComponentName name) {
1033 if (DBG) {
Yohei Yukawa1854cb52017-08-07 10:17:46 -07001034 Slog.w(TAG, "onServiceDisconnectedInnerLocked: " + name);
Guliz Tuncay787aa8c2017-06-19 17:15:40 -07001035 }
1036 final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId);
1037 if (group != null && this == group.mInternalConnection) {
Yohei Yukawa1854cb52017-08-07 10:17:46 -07001038 group.onServiceDisconnectedLocked();
Dianne Hackborn71e14da2011-10-16 16:28:10 -07001039 }
satok988323c2011-06-22 16:38:13 +09001040 }
1041 }
1042
Yohei Yukawaf14fe142017-06-22 22:30:45 -07001043 private static final class InternalDeathRecipients extends
Guliz Tuncayf982e752017-06-14 09:33:16 -07001044 RemoteCallbackList<ISpellCheckerSessionListener> {
satok988323c2011-06-22 16:38:13 +09001045 private final SpellCheckerBindGroup mGroup;
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -08001046
Guliz Tuncayf982e752017-06-14 09:33:16 -07001047 public InternalDeathRecipients(SpellCheckerBindGroup group) {
satok988323c2011-06-22 16:38:13 +09001048 mGroup = group;
1049 }
1050
Guliz Tuncayf982e752017-06-14 09:33:16 -07001051 @Override
1052 public void onCallbackDied(ISpellCheckerSessionListener listener) {
Yohei Yukawaf14fe142017-06-22 22:30:45 -07001053 mGroup.removeListener(listener);
satok988323c2011-06-22 16:38:13 +09001054 }
satok988323c2011-06-22 16:38:13 +09001055 }
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001056
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -08001057 private static final class ISpellCheckerServiceCallbackBinder
1058 extends ISpellCheckerServiceCallback.Stub {
1059 @NonNull
Yohei Yukawab7dfb9b2018-06-19 12:55:07 -07001060 private final Object mCallbackLock = new Object();
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -08001061
Yohei Yukawab7dfb9b2018-06-19 12:55:07 -07001062 @GuardedBy("mCallbackLock")
1063 @Nullable
1064 private WeakReference<SpellCheckerBindGroup> mBindGroup;
1065
1066 /**
1067 * Original {@link SessionRequest} that is associated with this callback.
1068 *
1069 * <p>Note that {@link SpellCheckerBindGroup#mOnGoingSessionRequests} guarantees that this
1070 * {@link SessionRequest} object is kept alive until the request is canceled.</p>
1071 */
1072 @GuardedBy("mCallbackLock")
1073 @Nullable
1074 private WeakReference<SessionRequest> mRequest;
1075
1076 ISpellCheckerServiceCallbackBinder(@NonNull SpellCheckerBindGroup bindGroup,
1077 @NonNull SessionRequest request) {
1078 synchronized (mCallbackLock) {
1079 mBindGroup = new WeakReference<>(bindGroup);
1080 mRequest = new WeakReference<>(request);
1081 }
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -08001082 }
1083
1084 @Override
1085 public void onSessionCreated(@Nullable ISpellCheckerSession newSession) {
Yohei Yukawab7dfb9b2018-06-19 12:55:07 -07001086 final SpellCheckerBindGroup group;
1087 final SessionRequest request;
1088 synchronized (mCallbackLock) {
1089 if (mBindGroup == null || mRequest == null) {
1090 return;
1091 }
1092 group = mBindGroup.get();
1093 request = mRequest.get();
1094 mBindGroup = null;
1095 mRequest = null;
1096 }
1097 if (group != null && request != null) {
1098 group.onSessionCreated(newSession, request);
1099 }
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -08001100 }
1101 }
satok988323c2011-06-22 16:38:13 +09001102}