blob: 4b0d4be11b148e1cf03b9d065ca23b8b77ecd954 [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;
23import com.android.internal.textservice.ISpellCheckerSession;
24import com.android.internal.textservice.ISpellCheckerSessionListener;
25import com.android.internal.textservice.ITextServicesManager;
26import com.android.internal.textservice.ITextServicesSessionListener;
27
satok03b2ea12011-08-03 17:36:14 +090028import org.xmlpull.v1.XmlPullParserException;
29
Yohei Yukawaf0f16802016-03-08 16:04:58 -080030import android.annotation.NonNull;
Yohei Yukawa08ce1872016-03-16 17:22:30 -070031import android.annotation.Nullable;
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -080032import android.annotation.UserIdInt;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090033import android.app.ActivityManagerNative;
34import android.app.AppGlobals;
Yohei Yukawa095fa372014-10-27 14:02:23 +090035import android.content.BroadcastReceiver;
satok988323c2011-06-22 16:38:13 +090036import android.content.ComponentName;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090037import android.content.ContentResolver;
satok988323c2011-06-22 16:38:13 +090038import android.content.Context;
39import android.content.Intent;
Yohei Yukawa095fa372014-10-27 14:02:23 +090040import android.content.IntentFilter;
satok988323c2011-06-22 16:38:13 +090041import android.content.ServiceConnection;
Yohei Yukawa095fa372014-10-27 14:02:23 +090042import android.content.pm.ApplicationInfo;
satok988323c2011-06-22 16:38:13 +090043import android.content.pm.PackageManager;
44import android.content.pm.ResolveInfo;
45import android.content.pm.ServiceInfo;
satok6be6d752011-07-28 20:40:38 +090046import android.os.Binder;
satok53578062011-08-03 16:08:59 +090047import android.os.Bundle;
satok988323c2011-06-22 16:38:13 +090048import android.os.IBinder;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090049import android.os.Process;
satok988323c2011-06-22 16:38:13 +090050import android.os.RemoteException;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090051import android.os.UserHandle;
Yohei Yukawa095fa372014-10-27 14:02:23 +090052import android.os.UserManager;
satok988323c2011-06-22 16:38:13 +090053import android.provider.Settings;
satok988323c2011-06-22 16:38:13 +090054import android.service.textservice.SpellCheckerService;
satok53578062011-08-03 16:08:59 +090055import android.text.TextUtils;
satok988323c2011-06-22 16:38:13 +090056import android.util.Slog;
satok05f24702011-11-02 19:29:35 +090057import android.view.inputmethod.InputMethodManager;
58import android.view.inputmethod.InputMethodSubtype;
satok988323c2011-06-22 16:38:13 +090059import android.view.textservice.SpellCheckerInfo;
satokada8c4e2011-08-23 14:56:56 +090060import android.view.textservice.SpellCheckerSubtype;
satok988323c2011-06-22 16:38:13 +090061
Dianne Hackborn71e14da2011-10-16 16:28:10 -070062import java.io.FileDescriptor;
satok03b2ea12011-08-03 17:36:14 +090063import java.io.IOException;
Dianne Hackborn71e14da2011-10-16 16:28:10 -070064import java.io.PrintWriter;
Yohei Yukawa174843a2015-06-26 18:02:54 -070065import java.util.Arrays;
satok988323c2011-06-22 16:38:13 +090066import java.util.ArrayList;
67import java.util.HashMap;
satok988323c2011-06-22 16:38:13 +090068import java.util.List;
Yohei Yukawa174843a2015-06-26 18:02:54 -070069import java.util.Locale;
Dianne Hackborn71e14da2011-10-16 16:28:10 -070070import java.util.Map;
satok4e713f12012-02-28 16:51:15 +090071import java.util.concurrent.CopyOnWriteArrayList;
satok988323c2011-06-22 16:38:13 +090072
73public class TextServicesManagerService extends ITextServicesManager.Stub {
74 private static final String TAG = TextServicesManagerService.class.getSimpleName();
75 private static final boolean DBG = false;
76
77 private final Context mContext;
78 private boolean mSystemReady;
79 private final TextServicesMonitor mMonitor;
Yohei Yukawa074637f2016-03-06 14:34:55 -080080 private final HashMap<String, SpellCheckerInfo> mSpellCheckerMap = new HashMap<>();
81 private final ArrayList<SpellCheckerInfo> mSpellCheckerList = new ArrayList<>();
82 private final HashMap<String, SpellCheckerBindGroup> mSpellCheckerBindGroups = new HashMap<>();
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090083 private final TextServicesSettings mSettings;
Yohei Yukawaf0f16802016-03-08 16:04:58 -080084 @NonNull
85 private final UserManager mUserManager;
satok988323c2011-06-22 16:38:13 +090086
Yohei Yukawaa6a152e2016-03-07 13:41:15 -080087 public static final class Lifecycle extends SystemService {
88 private TextServicesManagerService mService;
89
90 public Lifecycle(Context context) {
91 super(context);
92 mService = new TextServicesManagerService(context);
93 }
94
95 @Override
96 public void onStart() {
97 publishBinderService(Context.TEXT_SERVICES_MANAGER_SERVICE, mService);
98 }
99
100 @Override
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -0800101 public void onSwitchUser(@UserIdInt int userHandle) {
102 // Called on the system server's main looper thread.
103 // TODO: Dispatch this to a worker thread as needed.
104 mService.onSwitchUser(userHandle);
105 }
106
107 @Override
Yohei Yukawaa6a152e2016-03-07 13:41:15 -0800108 public void onBootPhase(int phase) {
109 // Called on the system server's main looper thread.
110 // TODO: Dispatch this to a worker thread as needed.
111 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
112 mService.systemRunning();
113 }
114 }
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800115
116 @Override
117 public void onUnlockUser(@UserIdInt int userHandle) {
118 // Called on the system server's main looper thread.
119 // TODO: Dispatch this to a worker thread as needed.
120 mService.onUnlockUser(userHandle);
121 }
Yohei Yukawaa6a152e2016-03-07 13:41:15 -0800122 }
123
124 void systemRunning() {
125 synchronized (mSpellCheckerMap) {
126 if (!mSystemReady) {
127 mSystemReady = true;
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800128 resetInternalState(mSettings.getCurrentUserId());
Yohei Yukawaa6a152e2016-03-07 13:41:15 -0800129 }
satok988323c2011-06-22 16:38:13 +0900130 }
131 }
132
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -0800133 void onSwitchUser(@UserIdInt int userId) {
134 synchronized (mSpellCheckerMap) {
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800135 resetInternalState(userId);
136 }
137 }
138
139 void onUnlockUser(@UserIdInt int userId) {
140 synchronized(mSpellCheckerMap) {
141 final int currentUserId = mSettings.getCurrentUserId();
142 if (userId != currentUserId) {
143 return;
144 }
145 resetInternalState(currentUserId);
satok988323c2011-06-22 16:38:13 +0900146 }
147 }
148
149 public TextServicesManagerService(Context context) {
150 mSystemReady = false;
151 mContext = context;
Yohei Yukawa095fa372014-10-27 14:02:23 +0900152
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800153 mUserManager = mContext.getSystemService(UserManager.class);
154
Yohei Yukawa095fa372014-10-27 14:02:23 +0900155 final IntentFilter broadcastFilter = new IntentFilter();
156 broadcastFilter.addAction(Intent.ACTION_USER_ADDED);
157 broadcastFilter.addAction(Intent.ACTION_USER_REMOVED);
158 mContext.registerReceiver(new TextServicesBroadcastReceiver(), broadcastFilter);
159
Xiaohui Chen7c696362015-09-16 09:56:14 -0700160 int userId = UserHandle.USER_SYSTEM;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900161 try {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900162 userId = ActivityManagerNative.getDefault().getCurrentUser().id;
163 } catch (RemoteException e) {
164 Slog.w(TAG, "Couldn't get current user ID; guessing it's 0", e);
165 }
satok988323c2011-06-22 16:38:13 +0900166 mMonitor = new TextServicesMonitor();
Dianne Hackbornd0d75032012-04-19 23:12:09 -0700167 mMonitor.register(context, null, true);
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800168 final boolean useCopyOnWriteSettings =
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600169 !mSystemReady || !mUserManager.isUserUnlockingOrUnlocked(userId);
Yohei Yukawa49ed1402016-03-07 19:12:54 -0800170 mSettings = new TextServicesSettings(context.getContentResolver(), userId,
171 useCopyOnWriteSettings);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900172
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800173 // "resetInternalState" initializes the states for the foreground user
174 resetInternalState(userId);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900175 }
176
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800177 private void resetInternalState(@UserIdInt int userId) {
178 final boolean useCopyOnWriteSettings =
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600179 !mSystemReady || !mUserManager.isUserUnlockingOrUnlocked(userId);
Yohei Yukawa49ed1402016-03-07 19:12:54 -0800180 mSettings.switchCurrentUser(userId, useCopyOnWriteSettings);
Yohei Yukawa095fa372014-10-27 14:02:23 +0900181 updateCurrentProfileIds();
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900182 unbindServiceLocked();
183 buildSpellCheckerMapLocked(mContext, mSpellCheckerList, mSpellCheckerMap, mSettings);
satokdf5659d2011-07-29 18:38:21 +0900184 SpellCheckerInfo sci = getCurrentSpellChecker(null);
185 if (sci == null) {
Yohei Yukawa174843a2015-06-26 18:02:54 -0700186 sci = findAvailSpellCheckerLocked(null);
satokdf5659d2011-07-29 18:38:21 +0900187 if (sci != null) {
188 // Set the current spell checker if there is one or more spell checkers
189 // available. In this case, "sci" is the first one in the available spell
190 // checkers.
satok5b9b5a92011-08-02 12:24:44 +0900191 setCurrentSpellCheckerLocked(sci.getId());
satokdf5659d2011-07-29 18:38:21 +0900192 }
193 }
satok988323c2011-06-22 16:38:13 +0900194 }
195
Yohei Yukawa095fa372014-10-27 14:02:23 +0900196 void updateCurrentProfileIds() {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700197 mSettings.setCurrentProfileIds(
198 mUserManager.getProfileIdsWithDisabled(mSettings.getCurrentUserId()));
Yohei Yukawa095fa372014-10-27 14:02:23 +0900199 }
200
satok988323c2011-06-22 16:38:13 +0900201 private class TextServicesMonitor extends PackageMonitor {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900202 private boolean isChangingPackagesOfCurrentUser() {
203 final int userId = getChangingUserId();
204 final boolean retval = userId == mSettings.getCurrentUserId();
205 if (DBG) {
206 Slog.d(TAG, "--- ignore this call back from a background user: " + userId);
207 }
208 return retval;
209 }
210
satok988323c2011-06-22 16:38:13 +0900211 @Override
212 public void onSomePackagesChanged() {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900213 if (!isChangingPackagesOfCurrentUser()) {
214 return;
215 }
satok988323c2011-06-22 16:38:13 +0900216 synchronized (mSpellCheckerMap) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900217 buildSpellCheckerMapLocked(
218 mContext, mSpellCheckerList, mSpellCheckerMap, mSettings);
satok988323c2011-06-22 16:38:13 +0900219 // TODO: Update for each locale
220 SpellCheckerInfo sci = getCurrentSpellChecker(null);
Satoshi Kataoka02260e22013-08-02 16:22:04 +0900221 // If no spell checker is enabled, just return. The user should explicitly
222 // enable the spell checker.
satokda317ef2011-07-26 08:02:45 +0900223 if (sci == null) return;
satok988323c2011-06-22 16:38:13 +0900224 final String packageName = sci.getPackageName();
225 final int change = isPackageDisappearing(packageName);
satok5b9b5a92011-08-02 12:24:44 +0900226 if (// Package disappearing
227 change == PACKAGE_PERMANENT_CHANGE || change == PACKAGE_TEMPORARY_CHANGE
228 // Package modified
229 || isPackageModified(packageName)) {
Yohei Yukawa174843a2015-06-26 18:02:54 -0700230 sci = findAvailSpellCheckerLocked(packageName);
satok5b9b5a92011-08-02 12:24:44 +0900231 if (sci != null) {
232 setCurrentSpellCheckerLocked(sci.getId());
233 }
satok988323c2011-06-22 16:38:13 +0900234 }
235 }
236 }
237 }
238
Yohei Yukawa095fa372014-10-27 14:02:23 +0900239 class TextServicesBroadcastReceiver extends BroadcastReceiver {
240 @Override
241 public void onReceive(Context context, Intent intent) {
242 final String action = intent.getAction();
243 if (Intent.ACTION_USER_ADDED.equals(action)
244 || Intent.ACTION_USER_REMOVED.equals(action)) {
245 updateCurrentProfileIds();
246 return;
247 }
248 Slog.w(TAG, "Unexpected intent " + intent);
249 }
250 }
251
satok988323c2011-06-22 16:38:13 +0900252 private static void buildSpellCheckerMapLocked(Context context,
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900253 ArrayList<SpellCheckerInfo> list, HashMap<String, SpellCheckerInfo> map,
254 TextServicesSettings settings) {
satok988323c2011-06-22 16:38:13 +0900255 list.clear();
256 map.clear();
257 final PackageManager pm = context.getPackageManager();
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800258 // Note: We do not specify PackageManager.MATCH_ENCRYPTION_* flags here because the default
259 // behavior of PackageManager is exactly what we want. It by default picks up appropriate
260 // services depending on the unlock state for the specified user.
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900261 final List<ResolveInfo> services = pm.queryIntentServicesAsUser(
262 new Intent(SpellCheckerService.SERVICE_INTERFACE), PackageManager.GET_META_DATA,
263 settings.getCurrentUserId());
satok988323c2011-06-22 16:38:13 +0900264 final int N = services.size();
265 for (int i = 0; i < N; ++i) {
266 final ResolveInfo ri = services.get(i);
267 final ServiceInfo si = ri.serviceInfo;
268 final ComponentName compName = new ComponentName(si.packageName, si.name);
269 if (!android.Manifest.permission.BIND_TEXT_SERVICE.equals(si.permission)) {
270 Slog.w(TAG, "Skipping text service " + compName
271 + ": it does not require the permission "
272 + android.Manifest.permission.BIND_TEXT_SERVICE);
273 continue;
274 }
275 if (DBG) Slog.d(TAG, "Add: " + compName);
satok03b2ea12011-08-03 17:36:14 +0900276 try {
277 final SpellCheckerInfo sci = new SpellCheckerInfo(context, ri);
satok3cb5b392011-08-26 11:55:21 +0900278 if (sci.getSubtypeCount() <= 0) {
279 Slog.w(TAG, "Skipping text service " + compName
280 + ": it does not contain subtypes.");
281 continue;
282 }
satok03b2ea12011-08-03 17:36:14 +0900283 list.add(sci);
284 map.put(sci.getId(), sci);
285 } catch (XmlPullParserException e) {
286 Slog.w(TAG, "Unable to load the spell checker " + compName, e);
287 } catch (IOException e) {
288 Slog.w(TAG, "Unable to load the spell checker " + compName, e);
289 }
satok988323c2011-06-22 16:38:13 +0900290 }
satokda317ef2011-07-26 08:02:45 +0900291 if (DBG) {
292 Slog.d(TAG, "buildSpellCheckerMapLocked: " + list.size() + "," + map.size());
293 }
satok988323c2011-06-22 16:38:13 +0900294 }
295
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900296 // ---------------------------------------------------------------------------------------
297 // Check whether or not this is a valid IPC. Assumes an IPC is valid when either
298 // 1) it comes from the system process
299 // 2) the calling process' user id is identical to the current user id TSMS thinks.
300 private boolean calledFromValidUser() {
301 final int uid = Binder.getCallingUid();
302 final int userId = UserHandle.getUserId(uid);
303 if (DBG) {
304 Slog.d(TAG, "--- calledFromForegroundUserOrSystemProcess ? "
305 + "calling uid = " + uid + " system uid = " + Process.SYSTEM_UID
306 + " calling userId = " + userId + ", foreground user id = "
Yohei Yukawa095fa372014-10-27 14:02:23 +0900307 + mSettings.getCurrentUserId() + ", calling pid = " + Binder.getCallingPid());
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900308 try {
309 final String[] packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
310 for (int i = 0; i < packageNames.length; ++i) {
311 if (DBG) {
312 Slog.d(TAG, "--- process name for "+ uid + " = " + packageNames[i]);
313 }
314 }
315 } catch (RemoteException e) {
316 }
317 }
318
319 if (uid == Process.SYSTEM_UID || userId == mSettings.getCurrentUserId()) {
320 return true;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900321 }
Yohei Yukawa095fa372014-10-27 14:02:23 +0900322
323 // Permits current profile to use TSFM as long as the current text service is the system's
324 // one. This is a tentative solution and should be replaced with fully functional multiuser
325 // support.
326 // TODO: Implement multiuser support in TSMS.
327 final boolean isCurrentProfile = mSettings.isCurrentProfile(userId);
328 if (DBG) {
329 Slog.d(TAG, "--- userId = "+ userId + " isCurrentProfile = " + isCurrentProfile);
330 }
331 if (mSettings.isCurrentProfile(userId)) {
332 final SpellCheckerInfo spellCheckerInfo = getCurrentSpellCheckerWithoutVerification();
333 if (spellCheckerInfo != null) {
334 final ServiceInfo serviceInfo = spellCheckerInfo.getServiceInfo();
335 final boolean isSystemSpellChecker =
336 (serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
337 if (DBG) {
338 Slog.d(TAG, "--- current spell checker = "+ spellCheckerInfo.getPackageName()
339 + " isSystem = " + isSystemSpellChecker);
340 }
341 if (isSystemSpellChecker) {
342 return true;
343 }
344 }
345 }
346
347 // Unlike InputMethodManagerService#calledFromValidUser, INTERACT_ACROSS_USERS_FULL isn't
348 // taken into account here. Anyway this method is supposed to be removed once multiuser
349 // support is implemented.
350 if (DBG) {
351 Slog.d(TAG, "--- IPC from userId:" + userId + " is being ignored. \n"
352 + getStackTrace());
353 }
354 return false;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900355 }
356
357 private boolean bindCurrentSpellCheckerService(
358 Intent service, ServiceConnection conn, int flags) {
359 if (service == null || conn == null) {
360 Slog.e(TAG, "--- bind failed: service = " + service + ", conn = " + conn);
361 return false;
362 }
Amith Yamasani27b89e62013-01-16 12:30:11 -0800363 return mContext.bindServiceAsUser(service, conn, flags,
364 new UserHandle(mSettings.getCurrentUserId()));
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900365 }
366
367 private void unbindServiceLocked() {
368 for (SpellCheckerBindGroup scbg : mSpellCheckerBindGroups.values()) {
369 scbg.removeAll();
370 }
371 mSpellCheckerBindGroups.clear();
372 }
373
Yohei Yukawa174843a2015-06-26 18:02:54 -0700374 private SpellCheckerInfo findAvailSpellCheckerLocked(String prefPackage) {
satok988323c2011-06-22 16:38:13 +0900375 final int spellCheckersCount = mSpellCheckerList.size();
376 if (spellCheckersCount == 0) {
377 Slog.w(TAG, "no available spell checker services found");
378 return null;
379 }
380 if (prefPackage != null) {
381 for (int i = 0; i < spellCheckersCount; ++i) {
382 final SpellCheckerInfo sci = mSpellCheckerList.get(i);
383 if (prefPackage.equals(sci.getPackageName())) {
satokda317ef2011-07-26 08:02:45 +0900384 if (DBG) {
385 Slog.d(TAG, "findAvailSpellCheckerLocked: " + sci.getPackageName());
386 }
satok988323c2011-06-22 16:38:13 +0900387 return sci;
388 }
389 }
390 }
Yohei Yukawa174843a2015-06-26 18:02:54 -0700391
392 // Look up a spell checker based on the system locale.
393 // TODO: Still there is a room to improve in the following logic: e.g., check if the package
394 // is pre-installed or not.
395 final Locale systemLocal = mContext.getResources().getConfiguration().locale;
396 final ArrayList<Locale> suitableLocales =
397 InputMethodUtils.getSuitableLocalesForSpellChecker(systemLocal);
398 if (DBG) {
399 Slog.w(TAG, "findAvailSpellCheckerLocked suitableLocales="
400 + Arrays.toString(suitableLocales.toArray(new Locale[suitableLocales.size()])));
401 }
402 final int localeCount = suitableLocales.size();
403 for (int localeIndex = 0; localeIndex < localeCount; ++localeIndex) {
404 final Locale locale = suitableLocales.get(localeIndex);
405 for (int spellCheckersIndex = 0; spellCheckersIndex < spellCheckersCount;
406 ++spellCheckersIndex) {
407 final SpellCheckerInfo info = mSpellCheckerList.get(spellCheckersIndex);
408 final int subtypeCount = info.getSubtypeCount();
409 for (int subtypeIndex = 0; subtypeIndex < subtypeCount; ++subtypeIndex) {
410 final SpellCheckerSubtype subtype = info.getSubtypeAt(subtypeIndex);
411 final Locale subtypeLocale = InputMethodUtils.constructLocaleFromString(
412 subtype.getLocale());
413 if (locale.equals(subtypeLocale)) {
414 // TODO: We may have more spell checkers that fall into this category.
415 // Ideally we should pick up the most suitable one instead of simply
416 // returning the first found one.
417 return info;
418 }
419 }
420 }
421 }
422
satok988323c2011-06-22 16:38:13 +0900423 if (spellCheckersCount > 1) {
424 Slog.w(TAG, "more than one spell checker service found, picking first");
425 }
426 return mSpellCheckerList.get(0);
427 }
428
429 // TODO: Save SpellCheckerService by supported languages. Currently only one spell
430 // checker is saved.
431 @Override
432 public SpellCheckerInfo getCurrentSpellChecker(String locale) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900433 // TODO: Make this work even for non-current users?
434 if (!calledFromValidUser()) {
435 return null;
436 }
Yohei Yukawa095fa372014-10-27 14:02:23 +0900437 return getCurrentSpellCheckerWithoutVerification();
438 }
439
440 private SpellCheckerInfo getCurrentSpellCheckerWithoutVerification() {
satok988323c2011-06-22 16:38:13 +0900441 synchronized (mSpellCheckerMap) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900442 final String curSpellCheckerId = mSettings.getSelectedSpellChecker();
satok562ab582011-07-25 10:12:21 +0900443 if (DBG) {
444 Slog.w(TAG, "getCurrentSpellChecker: " + curSpellCheckerId);
445 }
satok988323c2011-06-22 16:38:13 +0900446 if (TextUtils.isEmpty(curSpellCheckerId)) {
satokdf5659d2011-07-29 18:38:21 +0900447 return null;
satok988323c2011-06-22 16:38:13 +0900448 }
449 return mSpellCheckerMap.get(curSpellCheckerId);
450 }
451 }
452
satok3cb5b392011-08-26 11:55:21 +0900453 // TODO: Respect allowImplicitlySelectedSubtype
Satoshi Kataoka17150cf2012-05-30 20:05:44 +0900454 // TODO: Save SpellCheckerSubtype by supported languages by looking at "locale".
satokada8c4e2011-08-23 14:56:56 +0900455 @Override
satok3cb5b392011-08-26 11:55:21 +0900456 public SpellCheckerSubtype getCurrentSpellCheckerSubtype(
457 String locale, boolean allowImplicitlySelectedSubtype) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900458 // TODO: Make this work even for non-current users?
459 if (!calledFromValidUser()) {
460 return null;
461 }
satokada8c4e2011-08-23 14:56:56 +0900462 synchronized (mSpellCheckerMap) {
Yohei Yukawaad150ee2016-03-16 17:22:27 -0700463 final int subtypeHashCode =
464 mSettings.getSelectedSpellCheckerSubtype(SpellCheckerSubtype.SUBTYPE_ID_NONE);
satokada8c4e2011-08-23 14:56:56 +0900465 if (DBG) {
Yohei Yukawaad150ee2016-03-16 17:22:27 -0700466 Slog.w(TAG, "getCurrentSpellCheckerSubtype: " + subtypeHashCode);
satokada8c4e2011-08-23 14:56:56 +0900467 }
468 final SpellCheckerInfo sci = getCurrentSpellChecker(null);
satoka33c4fc2011-08-25 16:50:11 +0900469 if (sci == null || sci.getSubtypeCount() == 0) {
470 if (DBG) {
471 Slog.w(TAG, "Subtype not found.");
472 }
satokada8c4e2011-08-23 14:56:56 +0900473 return null;
474 }
Yohei Yukawaad150ee2016-03-16 17:22:27 -0700475 if (subtypeHashCode == SpellCheckerSubtype.SUBTYPE_ID_NONE
476 && !allowImplicitlySelectedSubtype) {
satok3cb5b392011-08-26 11:55:21 +0900477 return null;
satokada8c4e2011-08-23 14:56:56 +0900478 }
satok05f24702011-11-02 19:29:35 +0900479 String candidateLocale = null;
Yohei Yukawaad150ee2016-03-16 17:22:27 -0700480 if (subtypeHashCode == 0) {
satok05f24702011-11-02 19:29:35 +0900481 // Spell checker language settings == "auto"
Yohei Yukawa777ef952015-11-25 20:32:24 -0800482 final InputMethodManager imm = mContext.getSystemService(InputMethodManager.class);
satok05f24702011-11-02 19:29:35 +0900483 if (imm != null) {
484 final InputMethodSubtype currentInputMethodSubtype =
485 imm.getCurrentInputMethodSubtype();
486 if (currentInputMethodSubtype != null) {
487 final String localeString = currentInputMethodSubtype.getLocale();
488 if (!TextUtils.isEmpty(localeString)) {
489 // 1. Use keyboard locale if available in the spell checker
490 candidateLocale = localeString;
491 }
492 }
493 }
494 if (candidateLocale == null) {
495 // 2. Use System locale if available in the spell checker
496 candidateLocale = mContext.getResources().getConfiguration().locale.toString();
497 }
498 }
satokb3879542011-08-26 17:35:27 +0900499 SpellCheckerSubtype candidate = null;
satokada8c4e2011-08-23 14:56:56 +0900500 for (int i = 0; i < sci.getSubtypeCount(); ++i) {
501 final SpellCheckerSubtype scs = sci.getSubtypeAt(i);
Yohei Yukawaad150ee2016-03-16 17:22:27 -0700502 if (subtypeHashCode == 0) {
Satoshi Kataoka17150cf2012-05-30 20:05:44 +0900503 final String scsLocale = scs.getLocale();
504 if (candidateLocale.equals(scsLocale)) {
satokb3879542011-08-26 17:35:27 +0900505 return scs;
506 } else if (candidate == null) {
satok7018a902012-05-24 18:10:37 +0900507 if (candidateLocale.length() >= 2 && scsLocale.length() >= 2
508 && candidateLocale.startsWith(scsLocale)) {
satok05f24702011-11-02 19:29:35 +0900509 // Fall back to the applicable language
satokb3879542011-08-26 17:35:27 +0900510 candidate = scs;
511 }
512 }
Yohei Yukawaad150ee2016-03-16 17:22:27 -0700513 } else if (scs.hashCode() == subtypeHashCode) {
satoka33c4fc2011-08-25 16:50:11 +0900514 if (DBG) {
satok70deff42011-09-30 15:14:21 +0900515 Slog.w(TAG, "Return subtype " + scs.hashCode() + ", input= " + locale
516 + ", " + scs.getLocale());
satoka33c4fc2011-08-25 16:50:11 +0900517 }
satok05f24702011-11-02 19:29:35 +0900518 // 3. Use the user specified spell check language
satokada8c4e2011-08-23 14:56:56 +0900519 return scs;
520 }
521 }
satok05f24702011-11-02 19:29:35 +0900522 // 4. Fall back to the applicable language and return it if not null
523 // 5. Simply just return it even if it's null which means we could find no suitable
524 // spell check languages
satokb3879542011-08-26 17:35:27 +0900525 return candidate;
satokada8c4e2011-08-23 14:56:56 +0900526 }
527 }
528
satok988323c2011-06-22 16:38:13 +0900529 @Override
satok5b9b5a92011-08-02 12:24:44 +0900530 public void getSpellCheckerService(String sciId, String locale,
satok53578062011-08-03 16:08:59 +0900531 ITextServicesSessionListener tsListener, ISpellCheckerSessionListener scListener,
532 Bundle bundle) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900533 if (!calledFromValidUser()) {
534 return;
535 }
satok988323c2011-06-22 16:38:13 +0900536 if (!mSystemReady) {
537 return;
538 }
satok5b9b5a92011-08-02 12:24:44 +0900539 if (TextUtils.isEmpty(sciId) || tsListener == null || scListener == null) {
satok988323c2011-06-22 16:38:13 +0900540 Slog.e(TAG, "getSpellCheckerService: Invalid input.");
541 return;
542 }
satok988323c2011-06-22 16:38:13 +0900543 synchronized(mSpellCheckerMap) {
544 if (!mSpellCheckerMap.containsKey(sciId)) {
545 return;
546 }
satok5b9b5a92011-08-02 12:24:44 +0900547 final SpellCheckerInfo sci = mSpellCheckerMap.get(sciId);
satokdf5659d2011-07-29 18:38:21 +0900548 final int uid = Binder.getCallingUid();
satok988323c2011-06-22 16:38:13 +0900549 if (mSpellCheckerBindGroups.containsKey(sciId)) {
satok6be6d752011-07-28 20:40:38 +0900550 final SpellCheckerBindGroup bindGroup = mSpellCheckerBindGroups.get(sciId);
551 if (bindGroup != null) {
552 final InternalDeathRecipient recipient =
553 mSpellCheckerBindGroups.get(sciId).addListener(
satok53578062011-08-03 16:08:59 +0900554 tsListener, locale, scListener, uid, bundle);
satok6be6d752011-07-28 20:40:38 +0900555 if (recipient == null) {
556 if (DBG) {
557 Slog.w(TAG, "Didn't create a death recipient.");
558 }
559 return;
560 }
561 if (bindGroup.mSpellChecker == null & bindGroup.mConnected) {
562 Slog.e(TAG, "The state of the spell checker bind group is illegal.");
563 bindGroup.removeAll();
564 } else if (bindGroup.mSpellChecker != null) {
565 if (DBG) {
satokdf5659d2011-07-29 18:38:21 +0900566 Slog.w(TAG, "Existing bind found. Return a spell checker session now. "
567 + "Listeners count = " + bindGroup.mListeners.size());
satok6be6d752011-07-28 20:40:38 +0900568 }
569 try {
570 final ISpellCheckerSession session =
571 bindGroup.mSpellChecker.getISpellCheckerSession(
satok53578062011-08-03 16:08:59 +0900572 recipient.mScLocale, recipient.mScListener, bundle);
satokdf5659d2011-07-29 18:38:21 +0900573 if (session != null) {
574 tsListener.onServiceConnected(session);
575 return;
576 } else {
577 if (DBG) {
578 Slog.w(TAG, "Existing bind already expired. ");
579 }
580 bindGroup.removeAll();
581 }
satok6be6d752011-07-28 20:40:38 +0900582 } catch (RemoteException e) {
583 Slog.e(TAG, "Exception in getting spell checker session: " + e);
584 bindGroup.removeAll();
585 }
586 }
587 }
satok988323c2011-06-22 16:38:13 +0900588 }
satok6be6d752011-07-28 20:40:38 +0900589 final long ident = Binder.clearCallingIdentity();
590 try {
satok53578062011-08-03 16:08:59 +0900591 startSpellCheckerServiceInnerLocked(
592 sci, locale, tsListener, scListener, uid, bundle);
satok6be6d752011-07-28 20:40:38 +0900593 } finally {
594 Binder.restoreCallingIdentity(ident);
satok988323c2011-06-22 16:38:13 +0900595 }
satok988323c2011-06-22 16:38:13 +0900596 }
597 return;
598 }
599
satoka33c4fc2011-08-25 16:50:11 +0900600 @Override
601 public boolean isSpellCheckerEnabled() {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900602 if (!calledFromValidUser()) {
603 return false;
604 }
satoka33c4fc2011-08-25 16:50:11 +0900605 synchronized(mSpellCheckerMap) {
606 return isSpellCheckerEnabledLocked();
607 }
608 }
609
satok6be6d752011-07-28 20:40:38 +0900610 private void startSpellCheckerServiceInnerLocked(SpellCheckerInfo info, String locale,
satokdf5659d2011-07-29 18:38:21 +0900611 ITextServicesSessionListener tsListener, ISpellCheckerSessionListener scListener,
satok53578062011-08-03 16:08:59 +0900612 int uid, Bundle bundle) {
satokdf5659d2011-07-29 18:38:21 +0900613 if (DBG) {
614 Slog.w(TAG, "Start spell checker session inner locked.");
615 }
satok6be6d752011-07-28 20:40:38 +0900616 final String sciId = info.getId();
617 final InternalServiceConnection connection = new InternalServiceConnection(
satok060677f2011-11-17 09:40:56 +0900618 sciId, locale, bundle);
satok6be6d752011-07-28 20:40:38 +0900619 final Intent serviceIntent = new Intent(SpellCheckerService.SERVICE_INTERFACE);
620 serviceIntent.setComponent(info.getComponent());
621 if (DBG) {
622 Slog.w(TAG, "bind service: " + info.getId());
623 }
Dianne Hackbornd69e4c12015-04-24 09:54:54 -0700624 if (!bindCurrentSpellCheckerService(serviceIntent, connection,
625 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE_WHILE_AWAKE)) {
satok6be6d752011-07-28 20:40:38 +0900626 Slog.e(TAG, "Failed to get a spell checker service.");
627 return;
628 }
629 final SpellCheckerBindGroup group = new SpellCheckerBindGroup(
satok53578062011-08-03 16:08:59 +0900630 connection, tsListener, locale, scListener, uid, bundle);
satok6be6d752011-07-28 20:40:38 +0900631 mSpellCheckerBindGroups.put(sciId, group);
632 }
633
satok988323c2011-06-22 16:38:13 +0900634 @Override
satok562ab582011-07-25 10:12:21 +0900635 public SpellCheckerInfo[] getEnabledSpellCheckers() {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900636 // TODO: Make this work even for non-current users?
637 if (!calledFromValidUser()) {
638 return null;
639 }
satokda317ef2011-07-26 08:02:45 +0900640 if (DBG) {
641 Slog.d(TAG, "getEnabledSpellCheckers: " + mSpellCheckerList.size());
642 for (int i = 0; i < mSpellCheckerList.size(); ++i) {
643 Slog.d(TAG, "EnabledSpellCheckers: " + mSpellCheckerList.get(i).getPackageName());
644 }
645 }
satok562ab582011-07-25 10:12:21 +0900646 return mSpellCheckerList.toArray(new SpellCheckerInfo[mSpellCheckerList.size()]);
647 }
648
649 @Override
satok988323c2011-06-22 16:38:13 +0900650 public void finishSpellCheckerService(ISpellCheckerSessionListener listener) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900651 if (!calledFromValidUser()) {
652 return;
653 }
satokda317ef2011-07-26 08:02:45 +0900654 if (DBG) {
655 Slog.d(TAG, "FinishSpellCheckerService");
656 }
satok988323c2011-06-22 16:38:13 +0900657 synchronized(mSpellCheckerMap) {
Yohei Yukawa074637f2016-03-06 14:34:55 -0800658 final ArrayList<SpellCheckerBindGroup> removeList = new ArrayList<>();
satok988323c2011-06-22 16:38:13 +0900659 for (SpellCheckerBindGroup group : mSpellCheckerBindGroups.values()) {
660 if (group == null) continue;
satok4c3fa642011-11-30 18:17:59 +0900661 // Use removeList to avoid modifying mSpellCheckerBindGroups in this loop.
662 removeList.add(group);
663 }
664 final int removeSize = removeList.size();
665 for (int i = 0; i < removeSize; ++i) {
666 removeList.get(i).removeListener(listener);
satok988323c2011-06-22 16:38:13 +0900667 }
668 }
669 }
670
satokdf5659d2011-07-29 18:38:21 +0900671 @Override
satokada8c4e2011-08-23 14:56:56 +0900672 public void setCurrentSpellChecker(String locale, String sciId) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900673 if (!calledFromValidUser()) {
674 return;
675 }
satokdf5659d2011-07-29 18:38:21 +0900676 synchronized(mSpellCheckerMap) {
677 if (mContext.checkCallingOrSelfPermission(
678 android.Manifest.permission.WRITE_SECURE_SETTINGS)
679 != PackageManager.PERMISSION_GRANTED) {
680 throw new SecurityException(
681 "Requires permission "
682 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
683 }
satok5b9b5a92011-08-02 12:24:44 +0900684 setCurrentSpellCheckerLocked(sciId);
satokdf5659d2011-07-29 18:38:21 +0900685 }
686 }
687
satokada8c4e2011-08-23 14:56:56 +0900688 @Override
689 public void setCurrentSpellCheckerSubtype(String locale, int hashCode) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900690 if (!calledFromValidUser()) {
691 return;
692 }
satokada8c4e2011-08-23 14:56:56 +0900693 synchronized(mSpellCheckerMap) {
694 if (mContext.checkCallingOrSelfPermission(
695 android.Manifest.permission.WRITE_SECURE_SETTINGS)
696 != PackageManager.PERMISSION_GRANTED) {
697 throw new SecurityException(
698 "Requires permission "
699 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
700 }
satoka33c4fc2011-08-25 16:50:11 +0900701 setCurrentSpellCheckerSubtypeLocked(hashCode);
702 }
703 }
704
705 @Override
706 public void setSpellCheckerEnabled(boolean enabled) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900707 if (!calledFromValidUser()) {
708 return;
709 }
satoka33c4fc2011-08-25 16:50:11 +0900710 synchronized(mSpellCheckerMap) {
711 if (mContext.checkCallingOrSelfPermission(
712 android.Manifest.permission.WRITE_SECURE_SETTINGS)
713 != PackageManager.PERMISSION_GRANTED) {
714 throw new SecurityException(
715 "Requires permission "
716 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
717 }
718 setSpellCheckerEnabledLocked(enabled);
satokada8c4e2011-08-23 14:56:56 +0900719 }
720 }
721
satok5b9b5a92011-08-02 12:24:44 +0900722 private void setCurrentSpellCheckerLocked(String sciId) {
satok562ab582011-07-25 10:12:21 +0900723 if (DBG) {
satok5b9b5a92011-08-02 12:24:44 +0900724 Slog.w(TAG, "setCurrentSpellChecker: " + sciId);
satok562ab582011-07-25 10:12:21 +0900725 }
satok5b9b5a92011-08-02 12:24:44 +0900726 if (TextUtils.isEmpty(sciId) || !mSpellCheckerMap.containsKey(sciId)) return;
satokf39daef2011-08-26 19:54:27 +0900727 final SpellCheckerInfo currentSci = getCurrentSpellChecker(null);
728 if (currentSci != null && currentSci.getId().equals(sciId)) {
729 // Do nothing if the current spell checker is same as new spell checker.
730 return;
731 }
satokdf5659d2011-07-29 18:38:21 +0900732 final long ident = Binder.clearCallingIdentity();
733 try {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900734 mSettings.putSelectedSpellChecker(sciId);
satokf39daef2011-08-26 19:54:27 +0900735 setCurrentSpellCheckerSubtypeLocked(0);
satokada8c4e2011-08-23 14:56:56 +0900736 } finally {
737 Binder.restoreCallingIdentity(ident);
738 }
739 }
740
satoka33c4fc2011-08-25 16:50:11 +0900741 private void setCurrentSpellCheckerSubtypeLocked(int hashCode) {
satokada8c4e2011-08-23 14:56:56 +0900742 if (DBG) {
743 Slog.w(TAG, "setCurrentSpellCheckerSubtype: " + hashCode);
744 }
745 final SpellCheckerInfo sci = getCurrentSpellChecker(null);
satokfbedf1a2011-08-26 15:48:50 +0900746 int tempHashCode = 0;
747 for (int i = 0; sci != null && i < sci.getSubtypeCount(); ++i) {
satokada8c4e2011-08-23 14:56:56 +0900748 if(sci.getSubtypeAt(i).hashCode() == hashCode) {
satokfbedf1a2011-08-26 15:48:50 +0900749 tempHashCode = hashCode;
satokada8c4e2011-08-23 14:56:56 +0900750 break;
751 }
752 }
satokada8c4e2011-08-23 14:56:56 +0900753 final long ident = Binder.clearCallingIdentity();
754 try {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900755 mSettings.putSelectedSpellCheckerSubtype(tempHashCode);
satokdf5659d2011-07-29 18:38:21 +0900756 } finally {
757 Binder.restoreCallingIdentity(ident);
758 }
satok988323c2011-06-22 16:38:13 +0900759 }
760
satoka33c4fc2011-08-25 16:50:11 +0900761 private void setSpellCheckerEnabledLocked(boolean enabled) {
762 if (DBG) {
763 Slog.w(TAG, "setSpellCheckerEnabled: " + enabled);
764 }
765 final long ident = Binder.clearCallingIdentity();
766 try {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900767 mSettings.setSpellCheckerEnabled(enabled);
satoka33c4fc2011-08-25 16:50:11 +0900768 } finally {
769 Binder.restoreCallingIdentity(ident);
770 }
771 }
772
773 private boolean isSpellCheckerEnabledLocked() {
774 final long ident = Binder.clearCallingIdentity();
775 try {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900776 final boolean retval = mSettings.isSpellCheckerEnabled();
satoka33c4fc2011-08-25 16:50:11 +0900777 if (DBG) {
778 Slog.w(TAG, "getSpellCheckerEnabled: " + retval);
779 }
780 return retval;
781 } finally {
782 Binder.restoreCallingIdentity(ident);
783 }
784 }
785
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700786 @Override
787 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
788 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
789 != PackageManager.PERMISSION_GRANTED) {
790
791 pw.println("Permission Denial: can't dump TextServicesManagerService from from pid="
792 + Binder.getCallingPid()
793 + ", uid=" + Binder.getCallingUid());
794 return;
795 }
796
797 synchronized(mSpellCheckerMap) {
798 pw.println("Current Text Services Manager state:");
Yohei Yukawa85df6982016-03-08 15:16:07 -0800799 pw.println(" Spell Checkers:");
800 int spellCheckerIndex = 0;
801 for (final SpellCheckerInfo info : mSpellCheckerMap.values()) {
802 pw.println(" Spell Checker #" + spellCheckerIndex);
803 info.dump(pw, " ");
804 ++spellCheckerIndex;
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700805 }
806 pw.println("");
807 pw.println(" Spell Checker Bind Groups:");
Yohei Yukawa85df6982016-03-08 15:16:07 -0800808 for (final Map.Entry<String, SpellCheckerBindGroup> ent
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700809 : mSpellCheckerBindGroups.entrySet()) {
Yohei Yukawa85df6982016-03-08 15:16:07 -0800810 final SpellCheckerBindGroup grp = ent.getValue();
811 pw.println(" " + ent.getKey() + " " + grp + ":");
812 pw.println(" " + "mInternalConnection=" + grp.mInternalConnection);
813 pw.println(" " + "mSpellChecker=" + grp.mSpellChecker);
814 pw.println(" " + "mBound=" + grp.mBound + " mConnected=" + grp.mConnected);
815 final int N = grp.mListeners.size();
816 for (int i = 0; i < N; i++) {
817 final InternalDeathRecipient listener = grp.mListeners.get(i);
818 pw.println(" " + "Listener #" + i + ":");
819 pw.println(" " + "mTsListener=" + listener.mTsListener);
820 pw.println(" " + "mScListener=" + listener.mScListener);
821 pw.println(" " + "mGroup=" + listener.mGroup);
822 pw.println(" " + "mScLocale=" + listener.mScLocale
823 + " mUid=" + listener.mUid);
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700824 }
825 }
Yohei Yukawa85df6982016-03-08 15:16:07 -0800826 pw.println("");
827 pw.println(" mSettings:");
828 mSettings.dumpLocked(pw, " ");
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700829 }
830 }
831
satok988323c2011-06-22 16:38:13 +0900832 // SpellCheckerBindGroup contains active text service session listeners.
833 // If there are no listeners anymore, the SpellCheckerBindGroup instance will be removed from
834 // mSpellCheckerBindGroups
835 private class SpellCheckerBindGroup {
satokdf5659d2011-07-29 18:38:21 +0900836 private final String TAG = SpellCheckerBindGroup.class.getSimpleName();
satok6be6d752011-07-28 20:40:38 +0900837 private final InternalServiceConnection mInternalConnection;
satok4e713f12012-02-28 16:51:15 +0900838 private final CopyOnWriteArrayList<InternalDeathRecipient> mListeners =
Yohei Yukawa074637f2016-03-06 14:34:55 -0800839 new CopyOnWriteArrayList<>();
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700840 public boolean mBound;
satok6be6d752011-07-28 20:40:38 +0900841 public ISpellCheckerService mSpellChecker;
842 public boolean mConnected;
satok988323c2011-06-22 16:38:13 +0900843
844 public SpellCheckerBindGroup(InternalServiceConnection connection,
845 ITextServicesSessionListener listener, String locale,
satok53578062011-08-03 16:08:59 +0900846 ISpellCheckerSessionListener scListener, int uid, Bundle bundle) {
satok988323c2011-06-22 16:38:13 +0900847 mInternalConnection = connection;
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700848 mBound = true;
satok6be6d752011-07-28 20:40:38 +0900849 mConnected = false;
satok53578062011-08-03 16:08:59 +0900850 addListener(listener, locale, scListener, uid, bundle);
satok988323c2011-06-22 16:38:13 +0900851 }
852
853 public void onServiceConnected(ISpellCheckerService spellChecker) {
satokda317ef2011-07-26 08:02:45 +0900854 if (DBG) {
855 Slog.d(TAG, "onServiceConnected");
856 }
satok4e713f12012-02-28 16:51:15 +0900857
858 for (InternalDeathRecipient listener : mListeners) {
859 try {
860 final ISpellCheckerSession session = spellChecker.getISpellCheckerSession(
861 listener.mScLocale, listener.mScListener, listener.mBundle);
862 synchronized(mSpellCheckerMap) {
863 if (mListeners.contains(listener)) {
864 listener.mTsListener.onServiceConnected(session);
865 }
satok988323c2011-06-22 16:38:13 +0900866 }
satok4e713f12012-02-28 16:51:15 +0900867 } catch (RemoteException e) {
868 Slog.e(TAG, "Exception in getting the spell checker session."
869 + "Reconnect to the spellchecker. ", e);
870 removeAll();
871 return;
satok988323c2011-06-22 16:38:13 +0900872 }
satok4e713f12012-02-28 16:51:15 +0900873 }
874 synchronized(mSpellCheckerMap) {
satok6be6d752011-07-28 20:40:38 +0900875 mSpellChecker = spellChecker;
876 mConnected = true;
satok988323c2011-06-22 16:38:13 +0900877 }
878 }
879
satok6be6d752011-07-28 20:40:38 +0900880 public InternalDeathRecipient addListener(ITextServicesSessionListener tsListener,
satok53578062011-08-03 16:08:59 +0900881 String locale, ISpellCheckerSessionListener scListener, int uid, Bundle bundle) {
satokda317ef2011-07-26 08:02:45 +0900882 if (DBG) {
883 Slog.d(TAG, "addListener: " + locale);
884 }
satok6be6d752011-07-28 20:40:38 +0900885 InternalDeathRecipient recipient = null;
satok988323c2011-06-22 16:38:13 +0900886 synchronized(mSpellCheckerMap) {
887 try {
888 final int size = mListeners.size();
889 for (int i = 0; i < size; ++i) {
890 if (mListeners.get(i).hasSpellCheckerListener(scListener)) {
891 // do not add the lister if the group already contains this.
satok6be6d752011-07-28 20:40:38 +0900892 return null;
satok988323c2011-06-22 16:38:13 +0900893 }
894 }
satok6be6d752011-07-28 20:40:38 +0900895 recipient = new InternalDeathRecipient(
satok53578062011-08-03 16:08:59 +0900896 this, tsListener, locale, scListener, uid, bundle);
satok988323c2011-06-22 16:38:13 +0900897 scListener.asBinder().linkToDeath(recipient, 0);
satokdf5659d2011-07-29 18:38:21 +0900898 mListeners.add(recipient);
satok988323c2011-06-22 16:38:13 +0900899 } catch(RemoteException e) {
900 // do nothing
901 }
902 cleanLocked();
903 }
satok6be6d752011-07-28 20:40:38 +0900904 return recipient;
satok988323c2011-06-22 16:38:13 +0900905 }
906
907 public void removeListener(ISpellCheckerSessionListener listener) {
satokda317ef2011-07-26 08:02:45 +0900908 if (DBG) {
satokdf5659d2011-07-29 18:38:21 +0900909 Slog.w(TAG, "remove listener: " + listener.hashCode());
satokda317ef2011-07-26 08:02:45 +0900910 }
satok988323c2011-06-22 16:38:13 +0900911 synchronized(mSpellCheckerMap) {
912 final int size = mListeners.size();
Yohei Yukawa074637f2016-03-06 14:34:55 -0800913 final ArrayList<InternalDeathRecipient> removeList = new ArrayList<>();
satok988323c2011-06-22 16:38:13 +0900914 for (int i = 0; i < size; ++i) {
915 final InternalDeathRecipient tempRecipient = mListeners.get(i);
916 if(tempRecipient.hasSpellCheckerListener(listener)) {
satokdf5659d2011-07-29 18:38:21 +0900917 if (DBG) {
918 Slog.w(TAG, "found existing listener.");
919 }
satok988323c2011-06-22 16:38:13 +0900920 removeList.add(tempRecipient);
921 }
922 }
923 final int removeSize = removeList.size();
924 for (int i = 0; i < removeSize; ++i) {
satokdf5659d2011-07-29 18:38:21 +0900925 if (DBG) {
926 Slog.w(TAG, "Remove " + removeList.get(i));
927 }
satok2520ed82011-10-31 19:38:05 +0900928 final InternalDeathRecipient idr = removeList.get(i);
929 idr.mScListener.asBinder().unlinkToDeath(idr, 0);
930 mListeners.remove(idr);
satok988323c2011-06-22 16:38:13 +0900931 }
932 cleanLocked();
933 }
934 }
935
satok4c3fa642011-11-30 18:17:59 +0900936 // cleanLocked may remove elements from mSpellCheckerBindGroups
satok988323c2011-06-22 16:38:13 +0900937 private void cleanLocked() {
satokda317ef2011-07-26 08:02:45 +0900938 if (DBG) {
939 Slog.d(TAG, "cleanLocked");
940 }
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700941 // If there are no more active listeners, clean up. Only do this
942 // once.
943 if (mBound && mListeners.isEmpty()) {
944 mBound = false;
satokc7b60f722011-08-31 16:30:27 +0900945 final String sciId = mInternalConnection.mSciId;
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700946 SpellCheckerBindGroup cur = mSpellCheckerBindGroups.get(sciId);
947 if (cur == this) {
satokc7b60f722011-08-31 16:30:27 +0900948 if (DBG) {
949 Slog.d(TAG, "Remove bind group.");
950 }
951 mSpellCheckerBindGroups.remove(sciId);
satok6be6d752011-07-28 20:40:38 +0900952 }
satok988323c2011-06-22 16:38:13 +0900953 mContext.unbindService(mInternalConnection);
954 }
955 }
satok6be6d752011-07-28 20:40:38 +0900956
957 public void removeAll() {
958 Slog.e(TAG, "Remove the spell checker bind unexpectedly.");
satokdf5659d2011-07-29 18:38:21 +0900959 synchronized(mSpellCheckerMap) {
satok2520ed82011-10-31 19:38:05 +0900960 final int size = mListeners.size();
961 for (int i = 0; i < size; ++i) {
962 final InternalDeathRecipient idr = mListeners.get(i);
963 idr.mScListener.asBinder().unlinkToDeath(idr, 0);
964 }
satokdf5659d2011-07-29 18:38:21 +0900965 mListeners.clear();
966 cleanLocked();
967 }
satok6be6d752011-07-28 20:40:38 +0900968 }
satok988323c2011-06-22 16:38:13 +0900969 }
970
971 private class InternalServiceConnection implements ServiceConnection {
satok988323c2011-06-22 16:38:13 +0900972 private final String mSciId;
973 private final String mLocale;
satok53578062011-08-03 16:08:59 +0900974 private final Bundle mBundle;
satok988323c2011-06-22 16:38:13 +0900975 public InternalServiceConnection(
satok060677f2011-11-17 09:40:56 +0900976 String id, String locale, Bundle bundle) {
satok988323c2011-06-22 16:38:13 +0900977 mSciId = id;
978 mLocale = locale;
satok53578062011-08-03 16:08:59 +0900979 mBundle = bundle;
satok988323c2011-06-22 16:38:13 +0900980 }
981
982 @Override
983 public void onServiceConnected(ComponentName name, IBinder service) {
984 synchronized(mSpellCheckerMap) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900985 onServiceConnectedInnerLocked(name, service);
986 }
987 }
988
989 private void onServiceConnectedInnerLocked(ComponentName name, IBinder service) {
990 if (DBG) {
991 Slog.w(TAG, "onServiceConnected: " + name);
992 }
993 final ISpellCheckerService spellChecker =
994 ISpellCheckerService.Stub.asInterface(service);
995 final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId);
996 if (group != null && this == group.mInternalConnection) {
997 group.onServiceConnected(spellChecker);
satok988323c2011-06-22 16:38:13 +0900998 }
999 }
1000
1001 @Override
1002 public void onServiceDisconnected(ComponentName name) {
Dianne Hackborn71e14da2011-10-16 16:28:10 -07001003 synchronized(mSpellCheckerMap) {
1004 final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId);
satok2cf1cf02011-10-21 15:25:23 +09001005 if (group != null && this == group.mInternalConnection) {
Dianne Hackborn71e14da2011-10-16 16:28:10 -07001006 mSpellCheckerBindGroups.remove(mSciId);
1007 }
1008 }
satok988323c2011-06-22 16:38:13 +09001009 }
1010 }
1011
1012 private class InternalDeathRecipient implements IBinder.DeathRecipient {
1013 public final ITextServicesSessionListener mTsListener;
1014 public final ISpellCheckerSessionListener mScListener;
1015 public final String mScLocale;
1016 private final SpellCheckerBindGroup mGroup;
satokdf5659d2011-07-29 18:38:21 +09001017 public final int mUid;
satok53578062011-08-03 16:08:59 +09001018 public final Bundle mBundle;
satok988323c2011-06-22 16:38:13 +09001019 public InternalDeathRecipient(SpellCheckerBindGroup group,
1020 ITextServicesSessionListener tsListener, String scLocale,
satok53578062011-08-03 16:08:59 +09001021 ISpellCheckerSessionListener scListener, int uid, Bundle bundle) {
satok988323c2011-06-22 16:38:13 +09001022 mTsListener = tsListener;
1023 mScListener = scListener;
1024 mScLocale = scLocale;
1025 mGroup = group;
satokdf5659d2011-07-29 18:38:21 +09001026 mUid = uid;
satok53578062011-08-03 16:08:59 +09001027 mBundle = bundle;
satok988323c2011-06-22 16:38:13 +09001028 }
1029
1030 public boolean hasSpellCheckerListener(ISpellCheckerSessionListener listener) {
satokdf5659d2011-07-29 18:38:21 +09001031 return listener.asBinder().equals(mScListener.asBinder());
satok988323c2011-06-22 16:38:13 +09001032 }
1033
1034 @Override
1035 public void binderDied() {
1036 mGroup.removeListener(mScListener);
1037 }
1038 }
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001039
1040 private static class TextServicesSettings {
1041 private final ContentResolver mResolver;
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -08001042 @UserIdInt
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001043 private int mCurrentUserId;
Yohei Yukawa095fa372014-10-27 14:02:23 +09001044 @GuardedBy("mLock")
1045 private int[] mCurrentProfileIds = new int[0];
1046 private Object mLock = new Object();
1047
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001048 /**
1049 * On-memory data store to emulate when {@link #mCopyOnWrite} is {@code true}.
1050 */
1051 private final HashMap<String, String> mCopyOnWriteDataStore = new HashMap<>();
1052 private boolean mCopyOnWrite = false;
1053
1054 public TextServicesSettings(ContentResolver resolver, @UserIdInt int userId,
1055 boolean copyOnWrite) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001056 mResolver = resolver;
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001057 switchCurrentUser(userId, copyOnWrite);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001058 }
1059
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001060 /**
1061 * Must be called when the current user is changed.
1062 *
1063 * @param userId The user ID.
1064 * @param copyOnWrite If {@code true}, for each settings key
1065 * (e.g. {@link Settings.Secure#SELECTED_SPELL_CHECKER}) we use the actual settings on the
1066 * {@link Settings.Secure} until we do the first write operation.
1067 */
1068 public void switchCurrentUser(@UserIdInt int userId, boolean copyOnWrite) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001069 if (DBG) {
1070 Slog.d(TAG, "--- Swtich the current user from " + mCurrentUserId + " to "
1071 + userId + ", new ime = " + getSelectedSpellChecker());
1072 }
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001073 if (mCurrentUserId != userId || mCopyOnWrite != copyOnWrite) {
1074 mCopyOnWriteDataStore.clear();
1075 // TODO: mCurrentProfileIds should be cleared here.
1076 }
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001077 // TSMS settings are kept per user, so keep track of current user
1078 mCurrentUserId = userId;
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001079 mCopyOnWrite = copyOnWrite;
1080 // TODO: mCurrentProfileIds should be updated here.
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001081 }
1082
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001083 private void putString(final String key, final String str) {
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001084 if (mCopyOnWrite) {
1085 mCopyOnWriteDataStore.put(key, str);
1086 } else {
1087 Settings.Secure.putStringForUser(mResolver, key, str, mCurrentUserId);
1088 }
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001089 }
1090
Yohei Yukawa08ce1872016-03-16 17:22:30 -07001091 @Nullable
1092 private String getString(@NonNull final String key, @Nullable final String defaultValue) {
1093 final String result;
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001094 if (mCopyOnWrite && mCopyOnWriteDataStore.containsKey(key)) {
Yohei Yukawa08ce1872016-03-16 17:22:30 -07001095 result = mCopyOnWriteDataStore.get(key);
1096 } else {
1097 result = Settings.Secure.getStringForUser(mResolver, key, mCurrentUserId);
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001098 }
Yohei Yukawa08ce1872016-03-16 17:22:30 -07001099 return result != null ? result : defaultValue;
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001100 }
1101
1102 private void putInt(final String key, final int value) {
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001103 if (mCopyOnWrite) {
1104 mCopyOnWriteDataStore.put(key, String.valueOf(value));
1105 } else {
1106 Settings.Secure.putIntForUser(mResolver, key, value, mCurrentUserId);
1107 }
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001108 }
1109
1110 private int getInt(final String key, final int defaultValue) {
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001111 if (mCopyOnWrite && mCopyOnWriteDataStore.containsKey(key)) {
1112 final String result = mCopyOnWriteDataStore.get(key);
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001113 return result != null ? Integer.parseInt(result) : 0;
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001114 }
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001115 return Settings.Secure.getIntForUser(mResolver, key, defaultValue, mCurrentUserId);
1116 }
1117
1118 private void putBoolean(final String key, final boolean value) {
1119 putInt(key, value ? 1 : 0);
1120 }
1121
1122 private boolean getBoolean(final String key, final boolean defaultValue) {
1123 return getInt(key, defaultValue ? 1 : 0) == 1;
1124 }
1125
Yohei Yukawa095fa372014-10-27 14:02:23 +09001126 public void setCurrentProfileIds(int[] currentProfileIds) {
1127 synchronized (mLock) {
1128 mCurrentProfileIds = currentProfileIds;
1129 }
1130 }
1131
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -08001132 public boolean isCurrentProfile(@UserIdInt int userId) {
Yohei Yukawa095fa372014-10-27 14:02:23 +09001133 synchronized (mLock) {
1134 if (userId == mCurrentUserId) return true;
1135 for (int i = 0; i < mCurrentProfileIds.length; i++) {
1136 if (userId == mCurrentProfileIds[i]) return true;
1137 }
1138 return false;
1139 }
1140 }
1141
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -08001142 @UserIdInt
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001143 public int getCurrentUserId() {
1144 return mCurrentUserId;
1145 }
1146
Yohei Yukawa08ce1872016-03-16 17:22:30 -07001147 public void putSelectedSpellChecker(@Nullable String sciId) {
1148 if (TextUtils.isEmpty(sciId)) {
1149 // OK to coalesce to null, since getSelectedSpellChecker() can take care of the
1150 // empty data scenario.
1151 putString(Settings.Secure.SELECTED_SPELL_CHECKER, null);
1152 } else {
1153 putString(Settings.Secure.SELECTED_SPELL_CHECKER, sciId);
1154 }
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001155 }
1156
1157 public void putSelectedSpellCheckerSubtype(int hashCode) {
Yohei Yukawaad150ee2016-03-16 17:22:27 -07001158 putInt(Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, hashCode);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001159 }
1160
1161 public void setSpellCheckerEnabled(boolean enabled) {
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001162 putBoolean(Settings.Secure.SPELL_CHECKER_ENABLED, enabled);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001163 }
1164
Yohei Yukawa08ce1872016-03-16 17:22:30 -07001165 @NonNull
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001166 public String getSelectedSpellChecker() {
Yohei Yukawa08ce1872016-03-16 17:22:30 -07001167 return getString(Settings.Secure.SELECTED_SPELL_CHECKER, "");
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001168 }
1169
Yohei Yukawaad150ee2016-03-16 17:22:27 -07001170 public int getSelectedSpellCheckerSubtype(final int defaultValue) {
1171 return getInt(Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, defaultValue);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001172 }
1173
1174 public boolean isSpellCheckerEnabled() {
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001175 return getBoolean(Settings.Secure.SPELL_CHECKER_ENABLED, true);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001176 }
Yohei Yukawa85df6982016-03-08 15:16:07 -08001177
1178 public void dumpLocked(final PrintWriter pw, final String prefix) {
1179 pw.println(prefix + "mCurrentUserId=" + mCurrentUserId);
1180 pw.println(prefix + "mCurrentProfileIds=" + Arrays.toString(mCurrentProfileIds));
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001181 pw.println(prefix + "mCopyOnWrite=" + mCopyOnWrite);
Yohei Yukawa85df6982016-03-08 15:16:07 -08001182 }
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001183 }
1184
1185 // ----------------------------------------------------------------------
1186 // Utilities for debug
1187 private static String getStackTrace() {
1188 final StringBuilder sb = new StringBuilder();
1189 try {
1190 throw new RuntimeException();
1191 } catch (RuntimeException e) {
1192 final StackTraceElement[] frames = e.getStackTrace();
1193 // Start at 1 because the first frame is here and we don't care about it
1194 for (int j = 1; j < frames.length; ++j) {
1195 sb.append(frames[j].toString() + "\n");
1196 }
1197 }
1198 return sb.toString();
1199 }
satok988323c2011-06-22 16:38:13 +09001200}