blob: c297010e4389475367669d0c1c5aa0749f600ed7 [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 Yukawa095fa372014-10-27 14:02:23 +090019import com.android.internal.annotations.GuardedBy;
satok988323c2011-06-22 16:38:13 +090020import com.android.internal.content.PackageMonitor;
Yohei Yukawa174843a2015-06-26 18:02:54 -070021import com.android.internal.inputmethod.InputMethodUtils;
satok988323c2011-06-22 16:38:13 +090022import com.android.internal.textservice.ISpellCheckerService;
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -080023import com.android.internal.textservice.ISpellCheckerServiceCallback;
satok988323c2011-06-22 16:38:13 +090024import com.android.internal.textservice.ISpellCheckerSession;
25import com.android.internal.textservice.ISpellCheckerSessionListener;
26import com.android.internal.textservice.ITextServicesManager;
27import com.android.internal.textservice.ITextServicesSessionListener;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060028import com.android.internal.util.DumpUtils;
satok988323c2011-06-22 16:38:13 +090029
satok03b2ea12011-08-03 17:36:14 +090030import org.xmlpull.v1.XmlPullParserException;
31
Yohei Yukawaf0f16802016-03-08 16:04:58 -080032import android.annotation.NonNull;
Yohei Yukawa08ce1872016-03-16 17:22:30 -070033import android.annotation.Nullable;
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -080034import android.annotation.UserIdInt;
Sudheer Shankadc589ac2016-11-10 15:30:17 -080035import android.app.ActivityManager;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090036import android.app.AppGlobals;
Yohei Yukawa095fa372014-10-27 14:02:23 +090037import android.content.BroadcastReceiver;
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;
Yohei Yukawa095fa372014-10-27 14:02:23 +090042import android.content.IntentFilter;
satok988323c2011-06-22 16:38:13 +090043import android.content.ServiceConnection;
Yohei Yukawa095fa372014-10-27 14:02:23 +090044import android.content.pm.ApplicationInfo;
satok988323c2011-06-22 16:38:13 +090045import android.content.pm.PackageManager;
46import android.content.pm.ResolveInfo;
47import android.content.pm.ServiceInfo;
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;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090051import android.os.Process;
Guliz Tuncayf982e752017-06-14 09:33:16 -070052import android.os.RemoteCallbackList;
satok988323c2011-06-22 16:38:13 +090053import android.os.RemoteException;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090054import android.os.UserHandle;
Yohei Yukawa095fa372014-10-27 14:02:23 +090055import android.os.UserManager;
satok988323c2011-06-22 16:38:13 +090056import android.provider.Settings;
satok988323c2011-06-22 16:38:13 +090057import android.service.textservice.SpellCheckerService;
satok53578062011-08-03 16:08:59 +090058import android.text.TextUtils;
satok988323c2011-06-22 16:38:13 +090059import android.util.Slog;
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;
satok988323c2011-06-22 16:38:13 +090074
75public class TextServicesManagerService extends ITextServicesManager.Stub {
76 private static final String TAG = TextServicesManagerService.class.getSimpleName();
77 private static final boolean DBG = false;
78
79 private final Context mContext;
80 private boolean mSystemReady;
81 private final TextServicesMonitor mMonitor;
Yohei Yukawa074637f2016-03-06 14:34:55 -080082 private final HashMap<String, SpellCheckerInfo> mSpellCheckerMap = new HashMap<>();
83 private final ArrayList<SpellCheckerInfo> mSpellCheckerList = new ArrayList<>();
84 private final HashMap<String, SpellCheckerBindGroup> mSpellCheckerBindGroups = new HashMap<>();
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090085 private final TextServicesSettings mSettings;
Yohei Yukawaf0f16802016-03-08 16:04:58 -080086 @NonNull
87 private final UserManager mUserManager;
Guliz Tuncay10ae3852017-07-07 10:35:59 -070088 private final Object mLock = new Object();
satok988323c2011-06-22 16:38:13 +090089
Yohei Yukawaa6a152e2016-03-07 13:41:15 -080090 public static final class Lifecycle extends SystemService {
91 private TextServicesManagerService mService;
92
93 public Lifecycle(Context context) {
94 super(context);
95 mService = new TextServicesManagerService(context);
96 }
97
98 @Override
99 public void onStart() {
100 publishBinderService(Context.TEXT_SERVICES_MANAGER_SERVICE, mService);
101 }
102
103 @Override
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -0800104 public void onSwitchUser(@UserIdInt int userHandle) {
105 // Called on the system server's main looper thread.
106 // TODO: Dispatch this to a worker thread as needed.
107 mService.onSwitchUser(userHandle);
108 }
109
110 @Override
Yohei Yukawaa6a152e2016-03-07 13:41:15 -0800111 public void onBootPhase(int phase) {
112 // Called on the system server's main looper thread.
113 // TODO: Dispatch this to a worker thread as needed.
114 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
115 mService.systemRunning();
116 }
117 }
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800118
119 @Override
120 public void onUnlockUser(@UserIdInt int userHandle) {
121 // Called on the system server's main looper thread.
122 // TODO: Dispatch this to a worker thread as needed.
123 mService.onUnlockUser(userHandle);
124 }
Yohei Yukawaa6a152e2016-03-07 13:41:15 -0800125 }
126
127 void systemRunning() {
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700128 synchronized (mLock) {
Yohei Yukawaa6a152e2016-03-07 13:41:15 -0800129 if (!mSystemReady) {
130 mSystemReady = true;
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800131 resetInternalState(mSettings.getCurrentUserId());
Yohei Yukawaa6a152e2016-03-07 13:41:15 -0800132 }
satok988323c2011-06-22 16:38:13 +0900133 }
134 }
135
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -0800136 void onSwitchUser(@UserIdInt int userId) {
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700137 synchronized (mLock) {
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800138 resetInternalState(userId);
139 }
140 }
141
142 void onUnlockUser(@UserIdInt int userId) {
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700143 synchronized (mLock) {
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800144 final int currentUserId = mSettings.getCurrentUserId();
145 if (userId != currentUserId) {
146 return;
147 }
148 resetInternalState(currentUserId);
satok988323c2011-06-22 16:38:13 +0900149 }
150 }
151
152 public TextServicesManagerService(Context context) {
153 mSystemReady = false;
154 mContext = context;
Yohei Yukawa095fa372014-10-27 14:02:23 +0900155
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800156 mUserManager = mContext.getSystemService(UserManager.class);
157
Yohei Yukawa095fa372014-10-27 14:02:23 +0900158 final IntentFilter broadcastFilter = new IntentFilter();
159 broadcastFilter.addAction(Intent.ACTION_USER_ADDED);
160 broadcastFilter.addAction(Intent.ACTION_USER_REMOVED);
161 mContext.registerReceiver(new TextServicesBroadcastReceiver(), broadcastFilter);
162
Xiaohui Chen7c696362015-09-16 09:56:14 -0700163 int userId = UserHandle.USER_SYSTEM;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900164 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800165 userId = ActivityManager.getService().getCurrentUser().id;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900166 } catch (RemoteException e) {
167 Slog.w(TAG, "Couldn't get current user ID; guessing it's 0", e);
168 }
satok988323c2011-06-22 16:38:13 +0900169 mMonitor = new TextServicesMonitor();
Dianne Hackbornd0d75032012-04-19 23:12:09 -0700170 mMonitor.register(context, null, true);
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800171 final boolean useCopyOnWriteSettings =
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600172 !mSystemReady || !mUserManager.isUserUnlockingOrUnlocked(userId);
Yohei Yukawa49ed1402016-03-07 19:12:54 -0800173 mSettings = new TextServicesSettings(context.getContentResolver(), userId,
174 useCopyOnWriteSettings);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900175
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800176 // "resetInternalState" initializes the states for the foreground user
177 resetInternalState(userId);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900178 }
179
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800180 private void resetInternalState(@UserIdInt int userId) {
181 final boolean useCopyOnWriteSettings =
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600182 !mSystemReady || !mUserManager.isUserUnlockingOrUnlocked(userId);
Yohei Yukawa49ed1402016-03-07 19:12:54 -0800183 mSettings.switchCurrentUser(userId, useCopyOnWriteSettings);
Yohei Yukawa095fa372014-10-27 14:02:23 +0900184 updateCurrentProfileIds();
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900185 unbindServiceLocked();
186 buildSpellCheckerMapLocked(mContext, mSpellCheckerList, mSpellCheckerMap, mSettings);
satokdf5659d2011-07-29 18:38:21 +0900187 SpellCheckerInfo sci = getCurrentSpellChecker(null);
188 if (sci == null) {
Yohei Yukawa174843a2015-06-26 18:02:54 -0700189 sci = findAvailSpellCheckerLocked(null);
satokdf5659d2011-07-29 18:38:21 +0900190 if (sci != null) {
191 // Set the current spell checker if there is one or more spell checkers
192 // available. In this case, "sci" is the first one in the available spell
193 // checkers.
Guliz Tuncay1c94b8c2017-07-10 10:33:32 -0700194 setCurrentSpellCheckerLocked(sci);
satokdf5659d2011-07-29 18:38:21 +0900195 }
196 }
satok988323c2011-06-22 16:38:13 +0900197 }
198
Yohei Yukawa095fa372014-10-27 14:02:23 +0900199 void updateCurrentProfileIds() {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700200 mSettings.setCurrentProfileIds(
201 mUserManager.getProfileIdsWithDisabled(mSettings.getCurrentUserId()));
Yohei Yukawa095fa372014-10-27 14:02:23 +0900202 }
203
Yohei Yukawa06b4be72017-01-29 14:08:17 -0800204 private final class TextServicesMonitor extends PackageMonitor {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900205 private boolean isChangingPackagesOfCurrentUser() {
206 final int userId = getChangingUserId();
207 final boolean retval = userId == mSettings.getCurrentUserId();
208 if (DBG) {
209 Slog.d(TAG, "--- ignore this call back from a background user: " + userId);
210 }
211 return retval;
212 }
213
satok988323c2011-06-22 16:38:13 +0900214 @Override
215 public void onSomePackagesChanged() {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900216 if (!isChangingPackagesOfCurrentUser()) {
217 return;
218 }
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700219 synchronized (mLock) {
satok988323c2011-06-22 16:38:13 +0900220 // TODO: Update for each locale
221 SpellCheckerInfo sci = getCurrentSpellChecker(null);
Guliz Tuncayaaa0e432017-07-11 14:16:19 -0700222 buildSpellCheckerMapLocked(
223 mContext, mSpellCheckerList, mSpellCheckerMap, mSettings);
Satoshi Kataoka02260e22013-08-02 16:22:04 +0900224 // If no spell checker is enabled, just return. The user should explicitly
225 // enable the spell checker.
satokda317ef2011-07-26 08:02:45 +0900226 if (sci == null) return;
satok988323c2011-06-22 16:38:13 +0900227 final String packageName = sci.getPackageName();
228 final int change = isPackageDisappearing(packageName);
satok5b9b5a92011-08-02 12:24:44 +0900229 if (// Package disappearing
230 change == PACKAGE_PERMANENT_CHANGE || change == PACKAGE_TEMPORARY_CHANGE
231 // Package modified
232 || isPackageModified(packageName)) {
Guliz Tuncay1c94b8c2017-07-10 10:33:32 -0700233 SpellCheckerInfo availSci = findAvailSpellCheckerLocked(packageName);
234 // Set the spell checker settings if different than before
235 if (availSci != null && !availSci.getId().equals(sci.getId())) {
236 setCurrentSpellCheckerLocked(availSci);
satok5b9b5a92011-08-02 12:24:44 +0900237 }
satok988323c2011-06-22 16:38:13 +0900238 }
239 }
240 }
241 }
242
Yohei Yukawa06b4be72017-01-29 14:08:17 -0800243 private final class TextServicesBroadcastReceiver extends BroadcastReceiver {
Yohei Yukawa095fa372014-10-27 14:02:23 +0900244 @Override
245 public void onReceive(Context context, Intent intent) {
246 final String action = intent.getAction();
247 if (Intent.ACTION_USER_ADDED.equals(action)
248 || Intent.ACTION_USER_REMOVED.equals(action)) {
249 updateCurrentProfileIds();
250 return;
251 }
252 Slog.w(TAG, "Unexpected intent " + intent);
253 }
254 }
255
satok988323c2011-06-22 16:38:13 +0900256 private static void buildSpellCheckerMapLocked(Context context,
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900257 ArrayList<SpellCheckerInfo> list, HashMap<String, SpellCheckerInfo> map,
258 TextServicesSettings settings) {
satok988323c2011-06-22 16:38:13 +0900259 list.clear();
260 map.clear();
261 final PackageManager pm = context.getPackageManager();
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800262 // Note: We do not specify PackageManager.MATCH_ENCRYPTION_* flags here because the default
263 // behavior of PackageManager is exactly what we want. It by default picks up appropriate
264 // services depending on the unlock state for the specified user.
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900265 final List<ResolveInfo> services = pm.queryIntentServicesAsUser(
266 new Intent(SpellCheckerService.SERVICE_INTERFACE), PackageManager.GET_META_DATA,
267 settings.getCurrentUserId());
satok988323c2011-06-22 16:38:13 +0900268 final int N = services.size();
269 for (int i = 0; i < N; ++i) {
270 final ResolveInfo ri = services.get(i);
271 final ServiceInfo si = ri.serviceInfo;
272 final ComponentName compName = new ComponentName(si.packageName, si.name);
273 if (!android.Manifest.permission.BIND_TEXT_SERVICE.equals(si.permission)) {
274 Slog.w(TAG, "Skipping text service " + compName
275 + ": it does not require the permission "
276 + android.Manifest.permission.BIND_TEXT_SERVICE);
277 continue;
278 }
279 if (DBG) Slog.d(TAG, "Add: " + compName);
satok03b2ea12011-08-03 17:36:14 +0900280 try {
281 final SpellCheckerInfo sci = new SpellCheckerInfo(context, ri);
satok3cb5b392011-08-26 11:55:21 +0900282 if (sci.getSubtypeCount() <= 0) {
283 Slog.w(TAG, "Skipping text service " + compName
284 + ": it does not contain subtypes.");
285 continue;
286 }
satok03b2ea12011-08-03 17:36:14 +0900287 list.add(sci);
288 map.put(sci.getId(), sci);
289 } catch (XmlPullParserException e) {
290 Slog.w(TAG, "Unable to load the spell checker " + compName, e);
291 } catch (IOException e) {
292 Slog.w(TAG, "Unable to load the spell checker " + compName, e);
293 }
satok988323c2011-06-22 16:38:13 +0900294 }
satokda317ef2011-07-26 08:02:45 +0900295 if (DBG) {
296 Slog.d(TAG, "buildSpellCheckerMapLocked: " + list.size() + "," + map.size());
297 }
satok988323c2011-06-22 16:38:13 +0900298 }
299
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900300 // ---------------------------------------------------------------------------------------
301 // Check whether or not this is a valid IPC. Assumes an IPC is valid when either
302 // 1) it comes from the system process
303 // 2) the calling process' user id is identical to the current user id TSMS thinks.
304 private boolean calledFromValidUser() {
305 final int uid = Binder.getCallingUid();
306 final int userId = UserHandle.getUserId(uid);
307 if (DBG) {
308 Slog.d(TAG, "--- calledFromForegroundUserOrSystemProcess ? "
309 + "calling uid = " + uid + " system uid = " + Process.SYSTEM_UID
310 + " calling userId = " + userId + ", foreground user id = "
Yohei Yukawa095fa372014-10-27 14:02:23 +0900311 + mSettings.getCurrentUserId() + ", calling pid = " + Binder.getCallingPid());
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900312 try {
313 final String[] packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
314 for (int i = 0; i < packageNames.length; ++i) {
315 if (DBG) {
316 Slog.d(TAG, "--- process name for "+ uid + " = " + packageNames[i]);
317 }
318 }
319 } catch (RemoteException e) {
320 }
321 }
322
323 if (uid == Process.SYSTEM_UID || userId == mSettings.getCurrentUserId()) {
324 return true;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900325 }
Yohei Yukawa095fa372014-10-27 14:02:23 +0900326
327 // Permits current profile to use TSFM as long as the current text service is the system's
328 // one. This is a tentative solution and should be replaced with fully functional multiuser
329 // support.
330 // TODO: Implement multiuser support in TSMS.
331 final boolean isCurrentProfile = mSettings.isCurrentProfile(userId);
332 if (DBG) {
333 Slog.d(TAG, "--- userId = "+ userId + " isCurrentProfile = " + isCurrentProfile);
334 }
335 if (mSettings.isCurrentProfile(userId)) {
336 final SpellCheckerInfo spellCheckerInfo = getCurrentSpellCheckerWithoutVerification();
337 if (spellCheckerInfo != null) {
338 final ServiceInfo serviceInfo = spellCheckerInfo.getServiceInfo();
339 final boolean isSystemSpellChecker =
340 (serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
341 if (DBG) {
342 Slog.d(TAG, "--- current spell checker = "+ spellCheckerInfo.getPackageName()
343 + " isSystem = " + isSystemSpellChecker);
344 }
345 if (isSystemSpellChecker) {
346 return true;
347 }
348 }
349 }
350
351 // Unlike InputMethodManagerService#calledFromValidUser, INTERACT_ACROSS_USERS_FULL isn't
352 // taken into account here. Anyway this method is supposed to be removed once multiuser
353 // support is implemented.
354 if (DBG) {
355 Slog.d(TAG, "--- IPC from userId:" + userId + " is being ignored. \n"
356 + getStackTrace());
357 }
358 return false;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900359 }
360
361 private boolean bindCurrentSpellCheckerService(
362 Intent service, ServiceConnection conn, int flags) {
363 if (service == null || conn == null) {
364 Slog.e(TAG, "--- bind failed: service = " + service + ", conn = " + conn);
365 return false;
366 }
Amith Yamasani27b89e62013-01-16 12:30:11 -0800367 return mContext.bindServiceAsUser(service, conn, flags,
368 new UserHandle(mSettings.getCurrentUserId()));
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900369 }
370
371 private void unbindServiceLocked() {
372 for (SpellCheckerBindGroup scbg : mSpellCheckerBindGroups.values()) {
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700373 scbg.removeAllLocked();
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900374 }
375 mSpellCheckerBindGroups.clear();
376 }
377
Yohei Yukawa174843a2015-06-26 18:02:54 -0700378 private SpellCheckerInfo findAvailSpellCheckerLocked(String prefPackage) {
satok988323c2011-06-22 16:38:13 +0900379 final int spellCheckersCount = mSpellCheckerList.size();
380 if (spellCheckersCount == 0) {
381 Slog.w(TAG, "no available spell checker services found");
382 return null;
383 }
384 if (prefPackage != null) {
385 for (int i = 0; i < spellCheckersCount; ++i) {
386 final SpellCheckerInfo sci = mSpellCheckerList.get(i);
387 if (prefPackage.equals(sci.getPackageName())) {
satokda317ef2011-07-26 08:02:45 +0900388 if (DBG) {
389 Slog.d(TAG, "findAvailSpellCheckerLocked: " + sci.getPackageName());
390 }
satok988323c2011-06-22 16:38:13 +0900391 return sci;
392 }
393 }
394 }
Yohei Yukawa174843a2015-06-26 18:02:54 -0700395
396 // Look up a spell checker based on the system locale.
397 // TODO: Still there is a room to improve in the following logic: e.g., check if the package
398 // is pre-installed or not.
399 final Locale systemLocal = mContext.getResources().getConfiguration().locale;
400 final ArrayList<Locale> suitableLocales =
401 InputMethodUtils.getSuitableLocalesForSpellChecker(systemLocal);
402 if (DBG) {
403 Slog.w(TAG, "findAvailSpellCheckerLocked suitableLocales="
404 + Arrays.toString(suitableLocales.toArray(new Locale[suitableLocales.size()])));
405 }
406 final int localeCount = suitableLocales.size();
407 for (int localeIndex = 0; localeIndex < localeCount; ++localeIndex) {
408 final Locale locale = suitableLocales.get(localeIndex);
409 for (int spellCheckersIndex = 0; spellCheckersIndex < spellCheckersCount;
410 ++spellCheckersIndex) {
411 final SpellCheckerInfo info = mSpellCheckerList.get(spellCheckersIndex);
412 final int subtypeCount = info.getSubtypeCount();
413 for (int subtypeIndex = 0; subtypeIndex < subtypeCount; ++subtypeIndex) {
414 final SpellCheckerSubtype subtype = info.getSubtypeAt(subtypeIndex);
415 final Locale subtypeLocale = InputMethodUtils.constructLocaleFromString(
416 subtype.getLocale());
417 if (locale.equals(subtypeLocale)) {
418 // TODO: We may have more spell checkers that fall into this category.
419 // Ideally we should pick up the most suitable one instead of simply
420 // returning the first found one.
421 return info;
422 }
423 }
424 }
425 }
426
satok988323c2011-06-22 16:38:13 +0900427 if (spellCheckersCount > 1) {
428 Slog.w(TAG, "more than one spell checker service found, picking first");
429 }
430 return mSpellCheckerList.get(0);
431 }
432
433 // TODO: Save SpellCheckerService by supported languages. Currently only one spell
434 // checker is saved.
435 @Override
436 public SpellCheckerInfo getCurrentSpellChecker(String locale) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900437 // TODO: Make this work even for non-current users?
438 if (!calledFromValidUser()) {
439 return null;
440 }
Yohei Yukawa095fa372014-10-27 14:02:23 +0900441 return getCurrentSpellCheckerWithoutVerification();
442 }
443
444 private SpellCheckerInfo getCurrentSpellCheckerWithoutVerification() {
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700445 synchronized (mLock) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900446 final String curSpellCheckerId = mSettings.getSelectedSpellChecker();
satok562ab582011-07-25 10:12:21 +0900447 if (DBG) {
448 Slog.w(TAG, "getCurrentSpellChecker: " + curSpellCheckerId);
449 }
satok988323c2011-06-22 16:38:13 +0900450 if (TextUtils.isEmpty(curSpellCheckerId)) {
satokdf5659d2011-07-29 18:38:21 +0900451 return null;
satok988323c2011-06-22 16:38:13 +0900452 }
453 return mSpellCheckerMap.get(curSpellCheckerId);
454 }
455 }
456
satok3cb5b392011-08-26 11:55:21 +0900457 // TODO: Respect allowImplicitlySelectedSubtype
Satoshi Kataoka17150cf2012-05-30 20:05:44 +0900458 // TODO: Save SpellCheckerSubtype by supported languages by looking at "locale".
satokada8c4e2011-08-23 14:56:56 +0900459 @Override
satok3cb5b392011-08-26 11:55:21 +0900460 public SpellCheckerSubtype getCurrentSpellCheckerSubtype(
461 String locale, boolean allowImplicitlySelectedSubtype) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900462 // TODO: Make this work even for non-current users?
463 if (!calledFromValidUser()) {
464 return null;
465 }
Yohei Yukawae3e31a82016-09-20 06:43:03 -0700466 final int subtypeHashCode;
467 final SpellCheckerInfo sci;
468 final Locale systemLocale;
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700469 synchronized (mLock) {
Yohei Yukawae3e31a82016-09-20 06:43:03 -0700470 subtypeHashCode =
Yohei Yukawaad150ee2016-03-16 17:22:27 -0700471 mSettings.getSelectedSpellCheckerSubtype(SpellCheckerSubtype.SUBTYPE_ID_NONE);
satokada8c4e2011-08-23 14:56:56 +0900472 if (DBG) {
Yohei Yukawaad150ee2016-03-16 17:22:27 -0700473 Slog.w(TAG, "getCurrentSpellCheckerSubtype: " + subtypeHashCode);
satokada8c4e2011-08-23 14:56:56 +0900474 }
Yohei Yukawae3e31a82016-09-20 06:43:03 -0700475 sci = getCurrentSpellChecker(null);
476 systemLocale = mContext.getResources().getConfiguration().locale;
satokada8c4e2011-08-23 14:56:56 +0900477 }
Yohei Yukawae3e31a82016-09-20 06:43:03 -0700478 if (sci == null || sci.getSubtypeCount() == 0) {
479 if (DBG) {
480 Slog.w(TAG, "Subtype not found.");
481 }
482 return null;
483 }
484 if (subtypeHashCode == SpellCheckerSubtype.SUBTYPE_ID_NONE
485 && !allowImplicitlySelectedSubtype) {
486 return null;
487 }
488 String candidateLocale = null;
489 if (subtypeHashCode == 0) {
490 // Spell checker language settings == "auto"
491 final InputMethodManager imm = mContext.getSystemService(InputMethodManager.class);
492 if (imm != null) {
493 final InputMethodSubtype currentInputMethodSubtype =
494 imm.getCurrentInputMethodSubtype();
495 if (currentInputMethodSubtype != null) {
496 final String localeString = currentInputMethodSubtype.getLocale();
497 if (!TextUtils.isEmpty(localeString)) {
498 // 1. Use keyboard locale if available in the spell checker
499 candidateLocale = localeString;
500 }
501 }
502 }
503 if (candidateLocale == null) {
504 // 2. Use System locale if available in the spell checker
505 candidateLocale = systemLocale.toString();
506 }
507 }
508 SpellCheckerSubtype candidate = null;
509 for (int i = 0; i < sci.getSubtypeCount(); ++i) {
510 final SpellCheckerSubtype scs = sci.getSubtypeAt(i);
511 if (subtypeHashCode == 0) {
512 final String scsLocale = scs.getLocale();
513 if (candidateLocale.equals(scsLocale)) {
514 return scs;
515 } else if (candidate == null) {
516 if (candidateLocale.length() >= 2 && scsLocale.length() >= 2
517 && candidateLocale.startsWith(scsLocale)) {
518 // Fall back to the applicable language
519 candidate = scs;
520 }
521 }
522 } else if (scs.hashCode() == subtypeHashCode) {
523 if (DBG) {
524 Slog.w(TAG, "Return subtype " + scs.hashCode() + ", input= " + locale
525 + ", " + scs.getLocale());
526 }
527 // 3. Use the user specified spell check language
528 return scs;
529 }
530 }
531 // 4. Fall back to the applicable language and return it if not null
532 // 5. Simply just return it even if it's null which means we could find no suitable
533 // spell check languages
534 return candidate;
satokada8c4e2011-08-23 14:56:56 +0900535 }
536
satok988323c2011-06-22 16:38:13 +0900537 @Override
satok5b9b5a92011-08-02 12:24:44 +0900538 public void getSpellCheckerService(String sciId, String locale,
satok53578062011-08-03 16:08:59 +0900539 ITextServicesSessionListener tsListener, ISpellCheckerSessionListener scListener,
540 Bundle bundle) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900541 if (!calledFromValidUser()) {
542 return;
543 }
satok988323c2011-06-22 16:38:13 +0900544 if (!mSystemReady) {
545 return;
546 }
satok5b9b5a92011-08-02 12:24:44 +0900547 if (TextUtils.isEmpty(sciId) || tsListener == null || scListener == null) {
satok988323c2011-06-22 16:38:13 +0900548 Slog.e(TAG, "getSpellCheckerService: Invalid input.");
549 return;
550 }
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700551 synchronized (mLock) {
satok988323c2011-06-22 16:38:13 +0900552 if (!mSpellCheckerMap.containsKey(sciId)) {
553 return;
554 }
satok5b9b5a92011-08-02 12:24:44 +0900555 final SpellCheckerInfo sci = mSpellCheckerMap.get(sciId);
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800556 SpellCheckerBindGroup bindGroup = mSpellCheckerBindGroups.get(sciId);
satokdf5659d2011-07-29 18:38:21 +0900557 final int uid = Binder.getCallingUid();
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800558 if (bindGroup == null) {
559 final long ident = Binder.clearCallingIdentity();
560 try {
561 bindGroup = startSpellCheckerServiceInnerLocked(sci);
562 } finally {
563 Binder.restoreCallingIdentity(ident);
564 }
565 if (bindGroup == null) {
566 // startSpellCheckerServiceInnerLocked failed.
567 return;
satok6be6d752011-07-28 20:40:38 +0900568 }
satok988323c2011-06-22 16:38:13 +0900569 }
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800570
571 // Start getISpellCheckerSession async IPC, or just queue the request until the spell
572 // checker service is bound.
573 bindGroup.getISpellCheckerSessionOrQueueLocked(
574 new SessionRequest(uid, locale, tsListener, scListener, bundle));
satok988323c2011-06-22 16:38:13 +0900575 }
satok988323c2011-06-22 16:38:13 +0900576 }
577
satoka33c4fc2011-08-25 16:50:11 +0900578 @Override
579 public boolean isSpellCheckerEnabled() {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900580 if (!calledFromValidUser()) {
581 return false;
582 }
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700583 synchronized (mLock) {
satoka33c4fc2011-08-25 16:50:11 +0900584 return isSpellCheckerEnabledLocked();
585 }
586 }
587
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800588 @Nullable
589 private SpellCheckerBindGroup startSpellCheckerServiceInnerLocked(SpellCheckerInfo info) {
satokdf5659d2011-07-29 18:38:21 +0900590 if (DBG) {
591 Slog.w(TAG, "Start spell checker session inner locked.");
592 }
satok6be6d752011-07-28 20:40:38 +0900593 final String sciId = info.getId();
Yohei Yukawa06b4be72017-01-29 14:08:17 -0800594 final InternalServiceConnection connection = new InternalServiceConnection(sciId);
satok6be6d752011-07-28 20:40:38 +0900595 final Intent serviceIntent = new Intent(SpellCheckerService.SERVICE_INTERFACE);
596 serviceIntent.setComponent(info.getComponent());
597 if (DBG) {
598 Slog.w(TAG, "bind service: " + info.getId());
599 }
Dianne Hackbornd69e4c12015-04-24 09:54:54 -0700600 if (!bindCurrentSpellCheckerService(serviceIntent, connection,
Yohei Yukawaad78a612017-08-04 01:57:27 -0700601 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT_BACKGROUND)) {
satok6be6d752011-07-28 20:40:38 +0900602 Slog.e(TAG, "Failed to get a spell checker service.");
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800603 return null;
satok6be6d752011-07-28 20:40:38 +0900604 }
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800605 final SpellCheckerBindGroup group = new SpellCheckerBindGroup(connection);
satok6be6d752011-07-28 20:40:38 +0900606 mSpellCheckerBindGroups.put(sciId, group);
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800607 return group;
satok6be6d752011-07-28 20:40:38 +0900608 }
609
satok988323c2011-06-22 16:38:13 +0900610 @Override
satok562ab582011-07-25 10:12:21 +0900611 public SpellCheckerInfo[] getEnabledSpellCheckers() {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900612 // TODO: Make this work even for non-current users?
613 if (!calledFromValidUser()) {
614 return null;
615 }
satokda317ef2011-07-26 08:02:45 +0900616 if (DBG) {
617 Slog.d(TAG, "getEnabledSpellCheckers: " + mSpellCheckerList.size());
618 for (int i = 0; i < mSpellCheckerList.size(); ++i) {
619 Slog.d(TAG, "EnabledSpellCheckers: " + mSpellCheckerList.get(i).getPackageName());
620 }
621 }
satok562ab582011-07-25 10:12:21 +0900622 return mSpellCheckerList.toArray(new SpellCheckerInfo[mSpellCheckerList.size()]);
623 }
624
625 @Override
satok988323c2011-06-22 16:38:13 +0900626 public void finishSpellCheckerService(ISpellCheckerSessionListener listener) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900627 if (!calledFromValidUser()) {
628 return;
629 }
satokda317ef2011-07-26 08:02:45 +0900630 if (DBG) {
631 Slog.d(TAG, "FinishSpellCheckerService");
632 }
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700633 synchronized (mLock) {
Yohei Yukawa074637f2016-03-06 14:34:55 -0800634 final ArrayList<SpellCheckerBindGroup> removeList = new ArrayList<>();
satok988323c2011-06-22 16:38:13 +0900635 for (SpellCheckerBindGroup group : mSpellCheckerBindGroups.values()) {
636 if (group == null) continue;
satok4c3fa642011-11-30 18:17:59 +0900637 // Use removeList to avoid modifying mSpellCheckerBindGroups in this loop.
638 removeList.add(group);
639 }
640 final int removeSize = removeList.size();
641 for (int i = 0; i < removeSize; ++i) {
642 removeList.get(i).removeListener(listener);
satok988323c2011-06-22 16:38:13 +0900643 }
644 }
645 }
646
Guliz Tuncay1c94b8c2017-07-10 10:33:32 -0700647 private void setCurrentSpellCheckerLocked(SpellCheckerInfo sci) {
648 final String sciId = sci.getId();
satok562ab582011-07-25 10:12:21 +0900649 if (DBG) {
satok5b9b5a92011-08-02 12:24:44 +0900650 Slog.w(TAG, "setCurrentSpellChecker: " + sciId);
satok562ab582011-07-25 10:12:21 +0900651 }
satokdf5659d2011-07-29 18:38:21 +0900652 final long ident = Binder.clearCallingIdentity();
653 try {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900654 mSettings.putSelectedSpellChecker(sciId);
satokf39daef2011-08-26 19:54:27 +0900655 setCurrentSpellCheckerSubtypeLocked(0);
satokada8c4e2011-08-23 14:56:56 +0900656 } finally {
657 Binder.restoreCallingIdentity(ident);
658 }
659 }
660
satoka33c4fc2011-08-25 16:50:11 +0900661 private void setCurrentSpellCheckerSubtypeLocked(int hashCode) {
satokada8c4e2011-08-23 14:56:56 +0900662 if (DBG) {
663 Slog.w(TAG, "setCurrentSpellCheckerSubtype: " + hashCode);
664 }
665 final SpellCheckerInfo sci = getCurrentSpellChecker(null);
satokfbedf1a2011-08-26 15:48:50 +0900666 int tempHashCode = 0;
667 for (int i = 0; sci != null && i < sci.getSubtypeCount(); ++i) {
satokada8c4e2011-08-23 14:56:56 +0900668 if(sci.getSubtypeAt(i).hashCode() == hashCode) {
satokfbedf1a2011-08-26 15:48:50 +0900669 tempHashCode = hashCode;
satokada8c4e2011-08-23 14:56:56 +0900670 break;
671 }
672 }
satokada8c4e2011-08-23 14:56:56 +0900673 final long ident = Binder.clearCallingIdentity();
674 try {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900675 mSettings.putSelectedSpellCheckerSubtype(tempHashCode);
satokdf5659d2011-07-29 18:38:21 +0900676 } finally {
677 Binder.restoreCallingIdentity(ident);
678 }
satok988323c2011-06-22 16:38:13 +0900679 }
680
satoka33c4fc2011-08-25 16:50:11 +0900681 private boolean isSpellCheckerEnabledLocked() {
682 final long ident = Binder.clearCallingIdentity();
683 try {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900684 final boolean retval = mSettings.isSpellCheckerEnabled();
satoka33c4fc2011-08-25 16:50:11 +0900685 if (DBG) {
686 Slog.w(TAG, "getSpellCheckerEnabled: " + retval);
687 }
688 return retval;
689 } finally {
690 Binder.restoreCallingIdentity(ident);
691 }
692 }
693
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700694 @Override
695 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600696 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700697
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700698 synchronized (mLock) {
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700699 pw.println("Current Text Services Manager state:");
Yohei Yukawa85df6982016-03-08 15:16:07 -0800700 pw.println(" Spell Checkers:");
701 int spellCheckerIndex = 0;
702 for (final SpellCheckerInfo info : mSpellCheckerMap.values()) {
703 pw.println(" Spell Checker #" + spellCheckerIndex);
704 info.dump(pw, " ");
705 ++spellCheckerIndex;
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700706 }
707 pw.println("");
708 pw.println(" Spell Checker Bind Groups:");
Yohei Yukawa85df6982016-03-08 15:16:07 -0800709 for (final Map.Entry<String, SpellCheckerBindGroup> ent
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700710 : mSpellCheckerBindGroups.entrySet()) {
Yohei Yukawa85df6982016-03-08 15:16:07 -0800711 final SpellCheckerBindGroup grp = ent.getValue();
712 pw.println(" " + ent.getKey() + " " + grp + ":");
713 pw.println(" " + "mInternalConnection=" + grp.mInternalConnection);
714 pw.println(" " + "mSpellChecker=" + grp.mSpellChecker);
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800715 pw.println(" " + "mUnbindCalled=" + grp.mUnbindCalled);
716 pw.println(" " + "mConnected=" + grp.mConnected);
717 final int numPendingSessionRequests = grp.mPendingSessionRequests.size();
718 for (int i = 0; i < numPendingSessionRequests; i++) {
719 final SessionRequest req = grp.mPendingSessionRequests.get(i);
720 pw.println(" " + "Pending Request #" + i + ":");
721 pw.println(" " + "mTsListener=" + req.mTsListener);
722 pw.println(" " + "mScListener=" + req.mScListener);
723 pw.println(" " + "mScLocale=" + req.mLocale + " mUid=" + req.mUserId);
724 }
725 final int numOnGoingSessionRequests = grp.mOnGoingSessionRequests.size();
726 for (int i = 0; i < numOnGoingSessionRequests; i++) {
727 final SessionRequest req = grp.mOnGoingSessionRequests.get(i);
728 pw.println(" " + "On going Request #" + i + ":");
729 ++i;
730 pw.println(" " + "mTsListener=" + req.mTsListener);
731 pw.println(" " + "mScListener=" + req.mScListener);
732 pw.println(
733 " " + "mScLocale=" + req.mLocale + " mUid=" + req.mUserId);
734 }
Guliz Tuncayf982e752017-06-14 09:33:16 -0700735 final int N = grp.mListeners.getRegisteredCallbackCount();
Yohei Yukawa85df6982016-03-08 15:16:07 -0800736 for (int i = 0; i < N; i++) {
Guliz Tuncayf982e752017-06-14 09:33:16 -0700737 final ISpellCheckerSessionListener mScListener =
738 grp.mListeners.getRegisteredCallbackItem(i);
Yohei Yukawa85df6982016-03-08 15:16:07 -0800739 pw.println(" " + "Listener #" + i + ":");
Guliz Tuncayf982e752017-06-14 09:33:16 -0700740 pw.println(" " + "mScListener=" + mScListener);
741 pw.println(" " + "mGroup=" + grp);
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700742 }
743 }
Yohei Yukawa85df6982016-03-08 15:16:07 -0800744 pw.println("");
745 pw.println(" mSettings:");
746 mSettings.dumpLocked(pw, " ");
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700747 }
748 }
749
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800750 private static final class SessionRequest {
751 @UserIdInt
752 public final int mUserId;
753 @Nullable
754 public final String mLocale;
755 @NonNull
756 public final ITextServicesSessionListener mTsListener;
757 @NonNull
758 public final ISpellCheckerSessionListener mScListener;
759 @Nullable
760 public final Bundle mBundle;
761
762 SessionRequest(@UserIdInt final int userId, @Nullable String locale,
763 @NonNull ITextServicesSessionListener tsListener,
764 @NonNull ISpellCheckerSessionListener scListener, @Nullable Bundle bundle) {
765 mUserId = userId;
766 mLocale = locale;
767 mTsListener = tsListener;
768 mScListener = scListener;
769 mBundle = bundle;
770 }
771 }
772
satok988323c2011-06-22 16:38:13 +0900773 // SpellCheckerBindGroup contains active text service session listeners.
774 // If there are no listeners anymore, the SpellCheckerBindGroup instance will be removed from
775 // mSpellCheckerBindGroups
Yohei Yukawa06b4be72017-01-29 14:08:17 -0800776 private final class SpellCheckerBindGroup {
satokdf5659d2011-07-29 18:38:21 +0900777 private final String TAG = SpellCheckerBindGroup.class.getSimpleName();
satok6be6d752011-07-28 20:40:38 +0900778 private final InternalServiceConnection mInternalConnection;
Guliz Tuncayf982e752017-06-14 09:33:16 -0700779 private final InternalDeathRecipients mListeners;
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800780 private boolean mUnbindCalled;
781 private ISpellCheckerService mSpellChecker;
782 private boolean mConnected;
783 private final ArrayList<SessionRequest> mPendingSessionRequests = new ArrayList<>();
784 private final ArrayList<SessionRequest> mOnGoingSessionRequests = new ArrayList<>();
satok988323c2011-06-22 16:38:13 +0900785
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800786 public SpellCheckerBindGroup(InternalServiceConnection connection) {
satok988323c2011-06-22 16:38:13 +0900787 mInternalConnection = connection;
Guliz Tuncayf982e752017-06-14 09:33:16 -0700788 mListeners = new InternalDeathRecipients(this);
satok988323c2011-06-22 16:38:13 +0900789 }
790
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700791 public void onServiceConnectedLocked(ISpellCheckerService spellChecker) {
satokda317ef2011-07-26 08:02:45 +0900792 if (DBG) {
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700793 Slog.d(TAG, "onServiceConnectedLocked");
satokda317ef2011-07-26 08:02:45 +0900794 }
satok4e713f12012-02-28 16:51:15 +0900795
Yohei Yukawa4163a962017-08-07 10:17:59 -0700796 if (mUnbindCalled) {
797 return;
satok988323c2011-06-22 16:38:13 +0900798 }
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700799 mSpellChecker = spellChecker;
800 mConnected = true;
801 // Dispatch pending getISpellCheckerSession requests.
Yohei Yukawa4163a962017-08-07 10:17:59 -0700802 try {
803 final int size = mPendingSessionRequests.size();
804 for (int i = 0; i < size; ++i) {
805 final SessionRequest request = mPendingSessionRequests.get(i);
806 mSpellChecker.getISpellCheckerSession(
807 request.mLocale, request.mScListener, request.mBundle,
808 new ISpellCheckerServiceCallbackBinder(this, request));
809 mOnGoingSessionRequests.add(request);
810 }
811 mPendingSessionRequests.clear();
812 } catch(RemoteException e) {
813 // The target spell checker service is not available. Better to reset the state.
814 removeAllLocked();
815 }
816 cleanLocked();
satok988323c2011-06-22 16:38:13 +0900817 }
818
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700819 public void onServiceDisconnectedLocked() {
Guliz Tuncay787aa8c2017-06-19 17:15:40 -0700820 if (DBG) {
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700821 Slog.d(TAG, "onServiceDisconnectedLocked");
Guliz Tuncay787aa8c2017-06-19 17:15:40 -0700822 }
823
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700824 mSpellChecker = null;
825 mConnected = false;
Guliz Tuncay787aa8c2017-06-19 17:15:40 -0700826 }
827
satok988323c2011-06-22 16:38:13 +0900828 public void removeListener(ISpellCheckerSessionListener listener) {
satokda317ef2011-07-26 08:02:45 +0900829 if (DBG) {
satokdf5659d2011-07-29 18:38:21 +0900830 Slog.w(TAG, "remove listener: " + listener.hashCode());
satokda317ef2011-07-26 08:02:45 +0900831 }
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700832 synchronized (mLock) {
Guliz Tuncayf982e752017-06-14 09:33:16 -0700833 mListeners.unregister(listener);
satok988323c2011-06-22 16:38:13 +0900834 cleanLocked();
835 }
836 }
837
satok4c3fa642011-11-30 18:17:59 +0900838 // cleanLocked may remove elements from mSpellCheckerBindGroups
satok988323c2011-06-22 16:38:13 +0900839 private void cleanLocked() {
satokda317ef2011-07-26 08:02:45 +0900840 if (DBG) {
841 Slog.d(TAG, "cleanLocked");
842 }
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800843 if (mUnbindCalled) {
844 return;
satok988323c2011-06-22 16:38:13 +0900845 }
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800846 // If there are no more active listeners, clean up. Only do this once.
Guliz Tuncayf982e752017-06-14 09:33:16 -0700847 if (mListeners.getRegisteredCallbackCount() > 0) {
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800848 return;
849 }
850 if (!mPendingSessionRequests.isEmpty()) {
851 return;
852 }
853 if (!mOnGoingSessionRequests.isEmpty()) {
854 return;
855 }
856 final String sciId = mInternalConnection.mSciId;
857 final SpellCheckerBindGroup cur = mSpellCheckerBindGroups.get(sciId);
858 if (cur == this) {
859 if (DBG) {
860 Slog.d(TAG, "Remove bind group.");
861 }
862 mSpellCheckerBindGroups.remove(sciId);
863 }
864 mContext.unbindService(mInternalConnection);
865 mUnbindCalled = true;
satok988323c2011-06-22 16:38:13 +0900866 }
satok6be6d752011-07-28 20:40:38 +0900867
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700868 public void removeAllLocked() {
satok6be6d752011-07-28 20:40:38 +0900869 Slog.e(TAG, "Remove the spell checker bind unexpectedly.");
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700870 final int size = mListeners.getRegisteredCallbackCount();
871 for (int i = size - 1; i >= 0; --i) {
872 mListeners.unregister(mListeners.getRegisteredCallbackItem(i));
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800873 }
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700874 mPendingSessionRequests.clear();
875 mOnGoingSessionRequests.clear();
876 cleanLocked();
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800877 }
878
879 public void getISpellCheckerSessionOrQueueLocked(@NonNull SessionRequest request) {
880 if (mUnbindCalled) {
881 return;
882 }
883 if (!mConnected) {
884 mPendingSessionRequests.add(request);
885 return;
886 }
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800887 try {
888 mSpellChecker.getISpellCheckerSession(
889 request.mLocale, request.mScListener, request.mBundle,
890 new ISpellCheckerServiceCallbackBinder(this, request));
891 mOnGoingSessionRequests.add(request);
892 } catch(RemoteException e) {
893 // The target spell checker service is not available. Better to reset the state.
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700894 removeAllLocked();
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800895 }
896 cleanLocked();
897 }
898
899 void onSessionCreated(@Nullable final ISpellCheckerSession newSession,
900 @NonNull final SessionRequest request) {
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700901 synchronized (mLock) {
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800902 if (mUnbindCalled) {
903 return;
904 }
905 if (mOnGoingSessionRequests.remove(request)) {
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800906 try {
907 request.mTsListener.onServiceConnected(newSession);
Guliz Tuncayf982e752017-06-14 09:33:16 -0700908 mListeners.register(request.mScListener);
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800909 } catch (RemoteException e) {
910 // Technically this can happen if the spell checker client app is already
911 // dead. We can just forget about this request; the request is already
912 // removed from mOnGoingSessionRequests and the death recipient listener is
913 // not yet added to mListeners. There is nothing to release further.
914 }
915 }
satokdf5659d2011-07-29 18:38:21 +0900916 cleanLocked();
917 }
satok6be6d752011-07-28 20:40:38 +0900918 }
satok988323c2011-06-22 16:38:13 +0900919 }
920
Yohei Yukawa06b4be72017-01-29 14:08:17 -0800921 private final class InternalServiceConnection implements ServiceConnection {
satok988323c2011-06-22 16:38:13 +0900922 private final String mSciId;
Yohei Yukawa06b4be72017-01-29 14:08:17 -0800923 public InternalServiceConnection(String id) {
satok988323c2011-06-22 16:38:13 +0900924 mSciId = id;
satok988323c2011-06-22 16:38:13 +0900925 }
926
927 @Override
928 public void onServiceConnected(ComponentName name, IBinder service) {
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700929 synchronized (mLock) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900930 onServiceConnectedInnerLocked(name, service);
931 }
932 }
933
934 private void onServiceConnectedInnerLocked(ComponentName name, IBinder service) {
935 if (DBG) {
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700936 Slog.w(TAG, "onServiceConnectedInnerLocked: " + name);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900937 }
938 final ISpellCheckerService spellChecker =
939 ISpellCheckerService.Stub.asInterface(service);
940 final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId);
941 if (group != null && this == group.mInternalConnection) {
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700942 group.onServiceConnectedLocked(spellChecker);
satok988323c2011-06-22 16:38:13 +0900943 }
944 }
945
946 @Override
947 public void onServiceDisconnected(ComponentName name) {
Guliz Tuncay10ae3852017-07-07 10:35:59 -0700948 synchronized (mLock) {
Guliz Tuncay787aa8c2017-06-19 17:15:40 -0700949 onServiceDisconnectedInnerLocked(name);
950 }
951 }
952
953 private void onServiceDisconnectedInnerLocked(ComponentName name) {
954 if (DBG) {
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700955 Slog.w(TAG, "onServiceDisconnectedInnerLocked: " + name);
Guliz Tuncay787aa8c2017-06-19 17:15:40 -0700956 }
957 final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId);
958 if (group != null && this == group.mInternalConnection) {
Yohei Yukawa1854cb52017-08-07 10:17:46 -0700959 group.onServiceDisconnectedLocked();
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700960 }
satok988323c2011-06-22 16:38:13 +0900961 }
962 }
963
Yohei Yukawaf14fe142017-06-22 22:30:45 -0700964 private static final class InternalDeathRecipients extends
Guliz Tuncayf982e752017-06-14 09:33:16 -0700965 RemoteCallbackList<ISpellCheckerSessionListener> {
satok988323c2011-06-22 16:38:13 +0900966 private final SpellCheckerBindGroup mGroup;
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800967
Guliz Tuncayf982e752017-06-14 09:33:16 -0700968 public InternalDeathRecipients(SpellCheckerBindGroup group) {
satok988323c2011-06-22 16:38:13 +0900969 mGroup = group;
970 }
971
Guliz Tuncayf982e752017-06-14 09:33:16 -0700972 @Override
973 public void onCallbackDied(ISpellCheckerSessionListener listener) {
Yohei Yukawaf14fe142017-06-22 22:30:45 -0700974 mGroup.removeListener(listener);
satok988323c2011-06-22 16:38:13 +0900975 }
satok988323c2011-06-22 16:38:13 +0900976 }
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900977
Yohei Yukawa7fa65ee2017-02-08 11:54:05 -0800978 private static final class ISpellCheckerServiceCallbackBinder
979 extends ISpellCheckerServiceCallback.Stub {
980 @NonNull
981 private final SpellCheckerBindGroup mBindGroup;
982 @NonNull
983 private final SessionRequest mRequest;
984
985 ISpellCheckerServiceCallbackBinder(@NonNull final SpellCheckerBindGroup bindGroup,
986 @NonNull final SessionRequest request) {
987 mBindGroup = bindGroup;
988 mRequest = request;
989 }
990
991 @Override
992 public void onSessionCreated(@Nullable ISpellCheckerSession newSession) {
993 mBindGroup.onSessionCreated(newSession, mRequest);
994 }
995 }
996
Yohei Yukawa06b4be72017-01-29 14:08:17 -0800997 private static final class TextServicesSettings {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900998 private final ContentResolver mResolver;
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -0800999 @UserIdInt
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001000 private int mCurrentUserId;
Yohei Yukawa095fa372014-10-27 14:02:23 +09001001 @GuardedBy("mLock")
1002 private int[] mCurrentProfileIds = new int[0];
1003 private Object mLock = new Object();
1004
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001005 /**
1006 * On-memory data store to emulate when {@link #mCopyOnWrite} is {@code true}.
1007 */
1008 private final HashMap<String, String> mCopyOnWriteDataStore = new HashMap<>();
1009 private boolean mCopyOnWrite = false;
1010
1011 public TextServicesSettings(ContentResolver resolver, @UserIdInt int userId,
1012 boolean copyOnWrite) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001013 mResolver = resolver;
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001014 switchCurrentUser(userId, copyOnWrite);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001015 }
1016
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001017 /**
1018 * Must be called when the current user is changed.
1019 *
1020 * @param userId The user ID.
1021 * @param copyOnWrite If {@code true}, for each settings key
1022 * (e.g. {@link Settings.Secure#SELECTED_SPELL_CHECKER}) we use the actual settings on the
1023 * {@link Settings.Secure} until we do the first write operation.
1024 */
1025 public void switchCurrentUser(@UserIdInt int userId, boolean copyOnWrite) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001026 if (DBG) {
1027 Slog.d(TAG, "--- Swtich the current user from " + mCurrentUserId + " to "
1028 + userId + ", new ime = " + getSelectedSpellChecker());
1029 }
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001030 if (mCurrentUserId != userId || mCopyOnWrite != copyOnWrite) {
1031 mCopyOnWriteDataStore.clear();
1032 // TODO: mCurrentProfileIds should be cleared here.
1033 }
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001034 // TSMS settings are kept per user, so keep track of current user
1035 mCurrentUserId = userId;
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001036 mCopyOnWrite = copyOnWrite;
1037 // TODO: mCurrentProfileIds should be updated here.
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001038 }
1039
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001040 private void putString(final String key, final String str) {
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001041 if (mCopyOnWrite) {
1042 mCopyOnWriteDataStore.put(key, str);
1043 } else {
1044 Settings.Secure.putStringForUser(mResolver, key, str, mCurrentUserId);
1045 }
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001046 }
1047
Yohei Yukawa08ce1872016-03-16 17:22:30 -07001048 @Nullable
1049 private String getString(@NonNull final String key, @Nullable final String defaultValue) {
1050 final String result;
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001051 if (mCopyOnWrite && mCopyOnWriteDataStore.containsKey(key)) {
Yohei Yukawa08ce1872016-03-16 17:22:30 -07001052 result = mCopyOnWriteDataStore.get(key);
1053 } else {
1054 result = Settings.Secure.getStringForUser(mResolver, key, mCurrentUserId);
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001055 }
Yohei Yukawa08ce1872016-03-16 17:22:30 -07001056 return result != null ? result : defaultValue;
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001057 }
1058
1059 private void putInt(final String key, final int value) {
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001060 if (mCopyOnWrite) {
1061 mCopyOnWriteDataStore.put(key, String.valueOf(value));
1062 } else {
1063 Settings.Secure.putIntForUser(mResolver, key, value, mCurrentUserId);
1064 }
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001065 }
1066
1067 private int getInt(final String key, final int defaultValue) {
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001068 if (mCopyOnWrite && mCopyOnWriteDataStore.containsKey(key)) {
1069 final String result = mCopyOnWriteDataStore.get(key);
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001070 return result != null ? Integer.parseInt(result) : 0;
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001071 }
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001072 return Settings.Secure.getIntForUser(mResolver, key, defaultValue, mCurrentUserId);
1073 }
1074
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001075 private boolean getBoolean(final String key, final boolean defaultValue) {
1076 return getInt(key, defaultValue ? 1 : 0) == 1;
1077 }
1078
Yohei Yukawa095fa372014-10-27 14:02:23 +09001079 public void setCurrentProfileIds(int[] currentProfileIds) {
1080 synchronized (mLock) {
1081 mCurrentProfileIds = currentProfileIds;
1082 }
1083 }
1084
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -08001085 public boolean isCurrentProfile(@UserIdInt int userId) {
Yohei Yukawa095fa372014-10-27 14:02:23 +09001086 synchronized (mLock) {
1087 if (userId == mCurrentUserId) return true;
1088 for (int i = 0; i < mCurrentProfileIds.length; i++) {
1089 if (userId == mCurrentProfileIds[i]) return true;
1090 }
1091 return false;
1092 }
1093 }
1094
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -08001095 @UserIdInt
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001096 public int getCurrentUserId() {
1097 return mCurrentUserId;
1098 }
1099
Yohei Yukawa08ce1872016-03-16 17:22:30 -07001100 public void putSelectedSpellChecker(@Nullable String sciId) {
1101 if (TextUtils.isEmpty(sciId)) {
1102 // OK to coalesce to null, since getSelectedSpellChecker() can take care of the
1103 // empty data scenario.
1104 putString(Settings.Secure.SELECTED_SPELL_CHECKER, null);
1105 } else {
1106 putString(Settings.Secure.SELECTED_SPELL_CHECKER, sciId);
1107 }
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001108 }
1109
1110 public void putSelectedSpellCheckerSubtype(int hashCode) {
Yohei Yukawaad150ee2016-03-16 17:22:27 -07001111 putInt(Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, hashCode);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001112 }
1113
Yohei Yukawa08ce1872016-03-16 17:22:30 -07001114 @NonNull
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001115 public String getSelectedSpellChecker() {
Yohei Yukawa08ce1872016-03-16 17:22:30 -07001116 return getString(Settings.Secure.SELECTED_SPELL_CHECKER, "");
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001117 }
1118
Yohei Yukawaad150ee2016-03-16 17:22:27 -07001119 public int getSelectedSpellCheckerSubtype(final int defaultValue) {
1120 return getInt(Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, defaultValue);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001121 }
1122
1123 public boolean isSpellCheckerEnabled() {
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001124 return getBoolean(Settings.Secure.SPELL_CHECKER_ENABLED, true);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001125 }
Yohei Yukawa85df6982016-03-08 15:16:07 -08001126
1127 public void dumpLocked(final PrintWriter pw, final String prefix) {
1128 pw.println(prefix + "mCurrentUserId=" + mCurrentUserId);
1129 pw.println(prefix + "mCurrentProfileIds=" + Arrays.toString(mCurrentProfileIds));
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001130 pw.println(prefix + "mCopyOnWrite=" + mCopyOnWrite);
Yohei Yukawa85df6982016-03-08 15:16:07 -08001131 }
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001132 }
1133
1134 // ----------------------------------------------------------------------
1135 // Utilities for debug
1136 private static String getStackTrace() {
1137 final StringBuilder sb = new StringBuilder();
1138 try {
1139 throw new RuntimeException();
1140 } catch (RuntimeException e) {
1141 final StackTraceElement[] frames = e.getStackTrace();
1142 // Start at 1 because the first frame is here and we don't care about it
1143 for (int j = 1; j < frames.length; ++j) {
1144 sb.append(frames[j].toString() + "\n");
1145 }
1146 }
1147 return sb.toString();
1148 }
satok988323c2011-06-22 16:38:13 +09001149}