blob: aace66c7745de7494981a277b854d44290f10940 [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
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090030import android.app.ActivityManagerNative;
31import android.app.AppGlobals;
32import android.app.IUserSwitchObserver;
Yohei Yukawa095fa372014-10-27 14:02:23 +090033import android.content.BroadcastReceiver;
satok988323c2011-06-22 16:38:13 +090034import android.content.ComponentName;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090035import android.content.ContentResolver;
satok988323c2011-06-22 16:38:13 +090036import android.content.Context;
37import android.content.Intent;
Yohei Yukawa095fa372014-10-27 14:02:23 +090038import android.content.IntentFilter;
satok988323c2011-06-22 16:38:13 +090039import android.content.ServiceConnection;
Yohei Yukawa095fa372014-10-27 14:02:23 +090040import android.content.pm.ApplicationInfo;
satok988323c2011-06-22 16:38:13 +090041import android.content.pm.PackageManager;
42import android.content.pm.ResolveInfo;
43import android.content.pm.ServiceInfo;
Yohei Yukawa095fa372014-10-27 14:02:23 +090044import android.content.pm.UserInfo;
satok6be6d752011-07-28 20:40:38 +090045import android.os.Binder;
satok53578062011-08-03 16:08:59 +090046import android.os.Bundle;
satok988323c2011-06-22 16:38:13 +090047import android.os.IBinder;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090048import android.os.IRemoteCallback;
49import 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;
80 private final HashMap<String, SpellCheckerInfo> mSpellCheckerMap =
81 new HashMap<String, SpellCheckerInfo>();
82 private final ArrayList<SpellCheckerInfo> mSpellCheckerList = new ArrayList<SpellCheckerInfo>();
83 private final HashMap<String, SpellCheckerBindGroup> mSpellCheckerBindGroups =
84 new HashMap<String, SpellCheckerBindGroup>();
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090085 private final TextServicesSettings mSettings;
satok988323c2011-06-22 16:38:13 +090086
Svetoslav Ganova0027152013-06-25 14:59:53 -070087 public void systemRunning() {
satok988323c2011-06-22 16:38:13 +090088 if (!mSystemReady) {
89 mSystemReady = true;
90 }
91 }
92
93 public TextServicesManagerService(Context context) {
94 mSystemReady = false;
95 mContext = context;
Yohei Yukawa095fa372014-10-27 14:02:23 +090096
97 final IntentFilter broadcastFilter = new IntentFilter();
98 broadcastFilter.addAction(Intent.ACTION_USER_ADDED);
99 broadcastFilter.addAction(Intent.ACTION_USER_REMOVED);
100 mContext.registerReceiver(new TextServicesBroadcastReceiver(), broadcastFilter);
101
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900102 int userId = UserHandle.USER_OWNER;
103 try {
104 ActivityManagerNative.getDefault().registerUserSwitchObserver(
105 new IUserSwitchObserver.Stub() {
106 @Override
107 public void onUserSwitching(int newUserId, IRemoteCallback reply) {
108 synchronized(mSpellCheckerMap) {
109 switchUserLocked(newUserId);
110 }
111 if (reply != null) {
112 try {
113 reply.sendResult(null);
114 } catch (RemoteException e) {
115 }
116 }
117 }
118
119 @Override
120 public void onUserSwitchComplete(int newUserId) throws RemoteException {
121 }
Kenny Guy42979622015-04-13 18:03:05 +0000122
123 @Override
124 public void onForegroundProfileSwitch(int newProfileId) {
125 // Ignore.
126 }
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900127 });
128 userId = ActivityManagerNative.getDefault().getCurrentUser().id;
129 } catch (RemoteException e) {
130 Slog.w(TAG, "Couldn't get current user ID; guessing it's 0", e);
131 }
satok988323c2011-06-22 16:38:13 +0900132 mMonitor = new TextServicesMonitor();
Dianne Hackbornd0d75032012-04-19 23:12:09 -0700133 mMonitor.register(context, null, true);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900134 mSettings = new TextServicesSettings(context.getContentResolver(), userId);
135
136 // "switchUserLocked" initializes the states for the foreground user
137 switchUserLocked(userId);
138 }
139
140 private void switchUserLocked(int userId) {
141 mSettings.setCurrentUserId(userId);
Yohei Yukawa095fa372014-10-27 14:02:23 +0900142 updateCurrentProfileIds();
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900143 unbindServiceLocked();
144 buildSpellCheckerMapLocked(mContext, mSpellCheckerList, mSpellCheckerMap, mSettings);
satokdf5659d2011-07-29 18:38:21 +0900145 SpellCheckerInfo sci = getCurrentSpellChecker(null);
146 if (sci == null) {
Yohei Yukawa174843a2015-06-26 18:02:54 -0700147 sci = findAvailSpellCheckerLocked(null);
satokdf5659d2011-07-29 18:38:21 +0900148 if (sci != null) {
149 // Set the current spell checker if there is one or more spell checkers
150 // available. In this case, "sci" is the first one in the available spell
151 // checkers.
satok5b9b5a92011-08-02 12:24:44 +0900152 setCurrentSpellCheckerLocked(sci.getId());
satokdf5659d2011-07-29 18:38:21 +0900153 }
154 }
satok988323c2011-06-22 16:38:13 +0900155 }
156
Yohei Yukawa095fa372014-10-27 14:02:23 +0900157 void updateCurrentProfileIds() {
158 List<UserInfo> profiles =
159 UserManager.get(mContext).getProfiles(mSettings.getCurrentUserId());
160 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
161 for (int i = 0; i < currentProfileIds.length; i++) {
162 currentProfileIds[i] = profiles.get(i).id;
163 }
164 mSettings.setCurrentProfileIds(currentProfileIds);
165 }
166
satok988323c2011-06-22 16:38:13 +0900167 private class TextServicesMonitor extends PackageMonitor {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900168 private boolean isChangingPackagesOfCurrentUser() {
169 final int userId = getChangingUserId();
170 final boolean retval = userId == mSettings.getCurrentUserId();
171 if (DBG) {
172 Slog.d(TAG, "--- ignore this call back from a background user: " + userId);
173 }
174 return retval;
175 }
176
satok988323c2011-06-22 16:38:13 +0900177 @Override
178 public void onSomePackagesChanged() {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900179 if (!isChangingPackagesOfCurrentUser()) {
180 return;
181 }
satok988323c2011-06-22 16:38:13 +0900182 synchronized (mSpellCheckerMap) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900183 buildSpellCheckerMapLocked(
184 mContext, mSpellCheckerList, mSpellCheckerMap, mSettings);
satok988323c2011-06-22 16:38:13 +0900185 // TODO: Update for each locale
186 SpellCheckerInfo sci = getCurrentSpellChecker(null);
Satoshi Kataoka02260e22013-08-02 16:22:04 +0900187 // If no spell checker is enabled, just return. The user should explicitly
188 // enable the spell checker.
satokda317ef2011-07-26 08:02:45 +0900189 if (sci == null) return;
satok988323c2011-06-22 16:38:13 +0900190 final String packageName = sci.getPackageName();
191 final int change = isPackageDisappearing(packageName);
satok5b9b5a92011-08-02 12:24:44 +0900192 if (// Package disappearing
193 change == PACKAGE_PERMANENT_CHANGE || change == PACKAGE_TEMPORARY_CHANGE
194 // Package modified
195 || isPackageModified(packageName)) {
Yohei Yukawa174843a2015-06-26 18:02:54 -0700196 sci = findAvailSpellCheckerLocked(packageName);
satok5b9b5a92011-08-02 12:24:44 +0900197 if (sci != null) {
198 setCurrentSpellCheckerLocked(sci.getId());
199 }
satok988323c2011-06-22 16:38:13 +0900200 }
201 }
202 }
203 }
204
Yohei Yukawa095fa372014-10-27 14:02:23 +0900205 class TextServicesBroadcastReceiver extends BroadcastReceiver {
206 @Override
207 public void onReceive(Context context, Intent intent) {
208 final String action = intent.getAction();
209 if (Intent.ACTION_USER_ADDED.equals(action)
210 || Intent.ACTION_USER_REMOVED.equals(action)) {
211 updateCurrentProfileIds();
212 return;
213 }
214 Slog.w(TAG, "Unexpected intent " + intent);
215 }
216 }
217
satok988323c2011-06-22 16:38:13 +0900218 private static void buildSpellCheckerMapLocked(Context context,
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900219 ArrayList<SpellCheckerInfo> list, HashMap<String, SpellCheckerInfo> map,
220 TextServicesSettings settings) {
satok988323c2011-06-22 16:38:13 +0900221 list.clear();
222 map.clear();
223 final PackageManager pm = context.getPackageManager();
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900224 final List<ResolveInfo> services = pm.queryIntentServicesAsUser(
225 new Intent(SpellCheckerService.SERVICE_INTERFACE), PackageManager.GET_META_DATA,
226 settings.getCurrentUserId());
satok988323c2011-06-22 16:38:13 +0900227 final int N = services.size();
228 for (int i = 0; i < N; ++i) {
229 final ResolveInfo ri = services.get(i);
230 final ServiceInfo si = ri.serviceInfo;
231 final ComponentName compName = new ComponentName(si.packageName, si.name);
232 if (!android.Manifest.permission.BIND_TEXT_SERVICE.equals(si.permission)) {
233 Slog.w(TAG, "Skipping text service " + compName
234 + ": it does not require the permission "
235 + android.Manifest.permission.BIND_TEXT_SERVICE);
236 continue;
237 }
238 if (DBG) Slog.d(TAG, "Add: " + compName);
satok03b2ea12011-08-03 17:36:14 +0900239 try {
240 final SpellCheckerInfo sci = new SpellCheckerInfo(context, ri);
satok3cb5b392011-08-26 11:55:21 +0900241 if (sci.getSubtypeCount() <= 0) {
242 Slog.w(TAG, "Skipping text service " + compName
243 + ": it does not contain subtypes.");
244 continue;
245 }
satok03b2ea12011-08-03 17:36:14 +0900246 list.add(sci);
247 map.put(sci.getId(), sci);
248 } catch (XmlPullParserException e) {
249 Slog.w(TAG, "Unable to load the spell checker " + compName, e);
250 } catch (IOException e) {
251 Slog.w(TAG, "Unable to load the spell checker " + compName, e);
252 }
satok988323c2011-06-22 16:38:13 +0900253 }
satokda317ef2011-07-26 08:02:45 +0900254 if (DBG) {
255 Slog.d(TAG, "buildSpellCheckerMapLocked: " + list.size() + "," + map.size());
256 }
satok988323c2011-06-22 16:38:13 +0900257 }
258
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900259 // ---------------------------------------------------------------------------------------
260 // Check whether or not this is a valid IPC. Assumes an IPC is valid when either
261 // 1) it comes from the system process
262 // 2) the calling process' user id is identical to the current user id TSMS thinks.
263 private boolean calledFromValidUser() {
264 final int uid = Binder.getCallingUid();
265 final int userId = UserHandle.getUserId(uid);
266 if (DBG) {
267 Slog.d(TAG, "--- calledFromForegroundUserOrSystemProcess ? "
268 + "calling uid = " + uid + " system uid = " + Process.SYSTEM_UID
269 + " calling userId = " + userId + ", foreground user id = "
Yohei Yukawa095fa372014-10-27 14:02:23 +0900270 + mSettings.getCurrentUserId() + ", calling pid = " + Binder.getCallingPid());
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900271 try {
272 final String[] packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
273 for (int i = 0; i < packageNames.length; ++i) {
274 if (DBG) {
275 Slog.d(TAG, "--- process name for "+ uid + " = " + packageNames[i]);
276 }
277 }
278 } catch (RemoteException e) {
279 }
280 }
281
282 if (uid == Process.SYSTEM_UID || userId == mSettings.getCurrentUserId()) {
283 return true;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900284 }
Yohei Yukawa095fa372014-10-27 14:02:23 +0900285
286 // Permits current profile to use TSFM as long as the current text service is the system's
287 // one. This is a tentative solution and should be replaced with fully functional multiuser
288 // support.
289 // TODO: Implement multiuser support in TSMS.
290 final boolean isCurrentProfile = mSettings.isCurrentProfile(userId);
291 if (DBG) {
292 Slog.d(TAG, "--- userId = "+ userId + " isCurrentProfile = " + isCurrentProfile);
293 }
294 if (mSettings.isCurrentProfile(userId)) {
295 final SpellCheckerInfo spellCheckerInfo = getCurrentSpellCheckerWithoutVerification();
296 if (spellCheckerInfo != null) {
297 final ServiceInfo serviceInfo = spellCheckerInfo.getServiceInfo();
298 final boolean isSystemSpellChecker =
299 (serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
300 if (DBG) {
301 Slog.d(TAG, "--- current spell checker = "+ spellCheckerInfo.getPackageName()
302 + " isSystem = " + isSystemSpellChecker);
303 }
304 if (isSystemSpellChecker) {
305 return true;
306 }
307 }
308 }
309
310 // Unlike InputMethodManagerService#calledFromValidUser, INTERACT_ACROSS_USERS_FULL isn't
311 // taken into account here. Anyway this method is supposed to be removed once multiuser
312 // support is implemented.
313 if (DBG) {
314 Slog.d(TAG, "--- IPC from userId:" + userId + " is being ignored. \n"
315 + getStackTrace());
316 }
317 return false;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900318 }
319
320 private boolean bindCurrentSpellCheckerService(
321 Intent service, ServiceConnection conn, int flags) {
322 if (service == null || conn == null) {
323 Slog.e(TAG, "--- bind failed: service = " + service + ", conn = " + conn);
324 return false;
325 }
Amith Yamasani27b89e62013-01-16 12:30:11 -0800326 return mContext.bindServiceAsUser(service, conn, flags,
327 new UserHandle(mSettings.getCurrentUserId()));
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900328 }
329
330 private void unbindServiceLocked() {
331 for (SpellCheckerBindGroup scbg : mSpellCheckerBindGroups.values()) {
332 scbg.removeAll();
333 }
334 mSpellCheckerBindGroups.clear();
335 }
336
Yohei Yukawa174843a2015-06-26 18:02:54 -0700337 private SpellCheckerInfo findAvailSpellCheckerLocked(String prefPackage) {
satok988323c2011-06-22 16:38:13 +0900338 final int spellCheckersCount = mSpellCheckerList.size();
339 if (spellCheckersCount == 0) {
340 Slog.w(TAG, "no available spell checker services found");
341 return null;
342 }
343 if (prefPackage != null) {
344 for (int i = 0; i < spellCheckersCount; ++i) {
345 final SpellCheckerInfo sci = mSpellCheckerList.get(i);
346 if (prefPackage.equals(sci.getPackageName())) {
satokda317ef2011-07-26 08:02:45 +0900347 if (DBG) {
348 Slog.d(TAG, "findAvailSpellCheckerLocked: " + sci.getPackageName());
349 }
satok988323c2011-06-22 16:38:13 +0900350 return sci;
351 }
352 }
353 }
Yohei Yukawa174843a2015-06-26 18:02:54 -0700354
355 // Look up a spell checker based on the system locale.
356 // TODO: Still there is a room to improve in the following logic: e.g., check if the package
357 // is pre-installed or not.
358 final Locale systemLocal = mContext.getResources().getConfiguration().locale;
359 final ArrayList<Locale> suitableLocales =
360 InputMethodUtils.getSuitableLocalesForSpellChecker(systemLocal);
361 if (DBG) {
362 Slog.w(TAG, "findAvailSpellCheckerLocked suitableLocales="
363 + Arrays.toString(suitableLocales.toArray(new Locale[suitableLocales.size()])));
364 }
365 final int localeCount = suitableLocales.size();
366 for (int localeIndex = 0; localeIndex < localeCount; ++localeIndex) {
367 final Locale locale = suitableLocales.get(localeIndex);
368 for (int spellCheckersIndex = 0; spellCheckersIndex < spellCheckersCount;
369 ++spellCheckersIndex) {
370 final SpellCheckerInfo info = mSpellCheckerList.get(spellCheckersIndex);
371 final int subtypeCount = info.getSubtypeCount();
372 for (int subtypeIndex = 0; subtypeIndex < subtypeCount; ++subtypeIndex) {
373 final SpellCheckerSubtype subtype = info.getSubtypeAt(subtypeIndex);
374 final Locale subtypeLocale = InputMethodUtils.constructLocaleFromString(
375 subtype.getLocale());
376 if (locale.equals(subtypeLocale)) {
377 // TODO: We may have more spell checkers that fall into this category.
378 // Ideally we should pick up the most suitable one instead of simply
379 // returning the first found one.
380 return info;
381 }
382 }
383 }
384 }
385
satok988323c2011-06-22 16:38:13 +0900386 if (spellCheckersCount > 1) {
387 Slog.w(TAG, "more than one spell checker service found, picking first");
388 }
389 return mSpellCheckerList.get(0);
390 }
391
392 // TODO: Save SpellCheckerService by supported languages. Currently only one spell
393 // checker is saved.
394 @Override
395 public SpellCheckerInfo getCurrentSpellChecker(String locale) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900396 // TODO: Make this work even for non-current users?
397 if (!calledFromValidUser()) {
398 return null;
399 }
Yohei Yukawa095fa372014-10-27 14:02:23 +0900400 return getCurrentSpellCheckerWithoutVerification();
401 }
402
403 private SpellCheckerInfo getCurrentSpellCheckerWithoutVerification() {
satok988323c2011-06-22 16:38:13 +0900404 synchronized (mSpellCheckerMap) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900405 final String curSpellCheckerId = mSettings.getSelectedSpellChecker();
satok562ab582011-07-25 10:12:21 +0900406 if (DBG) {
407 Slog.w(TAG, "getCurrentSpellChecker: " + curSpellCheckerId);
408 }
satok988323c2011-06-22 16:38:13 +0900409 if (TextUtils.isEmpty(curSpellCheckerId)) {
satokdf5659d2011-07-29 18:38:21 +0900410 return null;
satok988323c2011-06-22 16:38:13 +0900411 }
412 return mSpellCheckerMap.get(curSpellCheckerId);
413 }
414 }
415
satok3cb5b392011-08-26 11:55:21 +0900416 // TODO: Respect allowImplicitlySelectedSubtype
Satoshi Kataoka17150cf2012-05-30 20:05:44 +0900417 // TODO: Save SpellCheckerSubtype by supported languages by looking at "locale".
satokada8c4e2011-08-23 14:56:56 +0900418 @Override
satok3cb5b392011-08-26 11:55:21 +0900419 public SpellCheckerSubtype getCurrentSpellCheckerSubtype(
420 String locale, boolean allowImplicitlySelectedSubtype) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900421 // TODO: Make this work even for non-current users?
422 if (!calledFromValidUser()) {
423 return null;
424 }
satokada8c4e2011-08-23 14:56:56 +0900425 synchronized (mSpellCheckerMap) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900426 final String subtypeHashCodeStr = mSettings.getSelectedSpellCheckerSubtype();
satokada8c4e2011-08-23 14:56:56 +0900427 if (DBG) {
satokc7b60f722011-08-31 16:30:27 +0900428 Slog.w(TAG, "getCurrentSpellCheckerSubtype: " + subtypeHashCodeStr);
satokada8c4e2011-08-23 14:56:56 +0900429 }
430 final SpellCheckerInfo sci = getCurrentSpellChecker(null);
satoka33c4fc2011-08-25 16:50:11 +0900431 if (sci == null || sci.getSubtypeCount() == 0) {
432 if (DBG) {
433 Slog.w(TAG, "Subtype not found.");
434 }
satokada8c4e2011-08-23 14:56:56 +0900435 return null;
436 }
satokb3879542011-08-26 17:35:27 +0900437 final int hashCode;
438 if (!TextUtils.isEmpty(subtypeHashCodeStr)) {
439 hashCode = Integer.valueOf(subtypeHashCodeStr);
440 } else {
441 hashCode = 0;
442 }
443 if (hashCode == 0 && !allowImplicitlySelectedSubtype) {
satok3cb5b392011-08-26 11:55:21 +0900444 return null;
satokada8c4e2011-08-23 14:56:56 +0900445 }
satok05f24702011-11-02 19:29:35 +0900446 String candidateLocale = null;
447 if (hashCode == 0) {
448 // Spell checker language settings == "auto"
449 final InputMethodManager imm =
450 (InputMethodManager)mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
451 if (imm != null) {
452 final InputMethodSubtype currentInputMethodSubtype =
453 imm.getCurrentInputMethodSubtype();
454 if (currentInputMethodSubtype != null) {
455 final String localeString = currentInputMethodSubtype.getLocale();
456 if (!TextUtils.isEmpty(localeString)) {
457 // 1. Use keyboard locale if available in the spell checker
458 candidateLocale = localeString;
459 }
460 }
461 }
462 if (candidateLocale == null) {
463 // 2. Use System locale if available in the spell checker
464 candidateLocale = mContext.getResources().getConfiguration().locale.toString();
465 }
466 }
satokb3879542011-08-26 17:35:27 +0900467 SpellCheckerSubtype candidate = null;
satokada8c4e2011-08-23 14:56:56 +0900468 for (int i = 0; i < sci.getSubtypeCount(); ++i) {
469 final SpellCheckerSubtype scs = sci.getSubtypeAt(i);
satokb3879542011-08-26 17:35:27 +0900470 if (hashCode == 0) {
Satoshi Kataoka17150cf2012-05-30 20:05:44 +0900471 final String scsLocale = scs.getLocale();
472 if (candidateLocale.equals(scsLocale)) {
satokb3879542011-08-26 17:35:27 +0900473 return scs;
474 } else if (candidate == null) {
satok7018a902012-05-24 18:10:37 +0900475 if (candidateLocale.length() >= 2 && scsLocale.length() >= 2
476 && candidateLocale.startsWith(scsLocale)) {
satok05f24702011-11-02 19:29:35 +0900477 // Fall back to the applicable language
satokb3879542011-08-26 17:35:27 +0900478 candidate = scs;
479 }
480 }
481 } else if (scs.hashCode() == hashCode) {
satoka33c4fc2011-08-25 16:50:11 +0900482 if (DBG) {
satok70deff42011-09-30 15:14:21 +0900483 Slog.w(TAG, "Return subtype " + scs.hashCode() + ", input= " + locale
484 + ", " + scs.getLocale());
satoka33c4fc2011-08-25 16:50:11 +0900485 }
satok05f24702011-11-02 19:29:35 +0900486 // 3. Use the user specified spell check language
satokada8c4e2011-08-23 14:56:56 +0900487 return scs;
488 }
489 }
satok05f24702011-11-02 19:29:35 +0900490 // 4. Fall back to the applicable language and return it if not null
491 // 5. Simply just return it even if it's null which means we could find no suitable
492 // spell check languages
satokb3879542011-08-26 17:35:27 +0900493 return candidate;
satokada8c4e2011-08-23 14:56:56 +0900494 }
495 }
496
satok988323c2011-06-22 16:38:13 +0900497 @Override
satok5b9b5a92011-08-02 12:24:44 +0900498 public void getSpellCheckerService(String sciId, String locale,
satok53578062011-08-03 16:08:59 +0900499 ITextServicesSessionListener tsListener, ISpellCheckerSessionListener scListener,
500 Bundle bundle) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900501 if (!calledFromValidUser()) {
502 return;
503 }
satok988323c2011-06-22 16:38:13 +0900504 if (!mSystemReady) {
505 return;
506 }
satok5b9b5a92011-08-02 12:24:44 +0900507 if (TextUtils.isEmpty(sciId) || tsListener == null || scListener == null) {
satok988323c2011-06-22 16:38:13 +0900508 Slog.e(TAG, "getSpellCheckerService: Invalid input.");
509 return;
510 }
satok988323c2011-06-22 16:38:13 +0900511 synchronized(mSpellCheckerMap) {
512 if (!mSpellCheckerMap.containsKey(sciId)) {
513 return;
514 }
satok5b9b5a92011-08-02 12:24:44 +0900515 final SpellCheckerInfo sci = mSpellCheckerMap.get(sciId);
satokdf5659d2011-07-29 18:38:21 +0900516 final int uid = Binder.getCallingUid();
satok988323c2011-06-22 16:38:13 +0900517 if (mSpellCheckerBindGroups.containsKey(sciId)) {
satok6be6d752011-07-28 20:40:38 +0900518 final SpellCheckerBindGroup bindGroup = mSpellCheckerBindGroups.get(sciId);
519 if (bindGroup != null) {
520 final InternalDeathRecipient recipient =
521 mSpellCheckerBindGroups.get(sciId).addListener(
satok53578062011-08-03 16:08:59 +0900522 tsListener, locale, scListener, uid, bundle);
satok6be6d752011-07-28 20:40:38 +0900523 if (recipient == null) {
524 if (DBG) {
525 Slog.w(TAG, "Didn't create a death recipient.");
526 }
527 return;
528 }
529 if (bindGroup.mSpellChecker == null & bindGroup.mConnected) {
530 Slog.e(TAG, "The state of the spell checker bind group is illegal.");
531 bindGroup.removeAll();
532 } else if (bindGroup.mSpellChecker != null) {
533 if (DBG) {
satokdf5659d2011-07-29 18:38:21 +0900534 Slog.w(TAG, "Existing bind found. Return a spell checker session now. "
535 + "Listeners count = " + bindGroup.mListeners.size());
satok6be6d752011-07-28 20:40:38 +0900536 }
537 try {
538 final ISpellCheckerSession session =
539 bindGroup.mSpellChecker.getISpellCheckerSession(
satok53578062011-08-03 16:08:59 +0900540 recipient.mScLocale, recipient.mScListener, bundle);
satokdf5659d2011-07-29 18:38:21 +0900541 if (session != null) {
542 tsListener.onServiceConnected(session);
543 return;
544 } else {
545 if (DBG) {
546 Slog.w(TAG, "Existing bind already expired. ");
547 }
548 bindGroup.removeAll();
549 }
satok6be6d752011-07-28 20:40:38 +0900550 } catch (RemoteException e) {
551 Slog.e(TAG, "Exception in getting spell checker session: " + e);
552 bindGroup.removeAll();
553 }
554 }
555 }
satok988323c2011-06-22 16:38:13 +0900556 }
satok6be6d752011-07-28 20:40:38 +0900557 final long ident = Binder.clearCallingIdentity();
558 try {
satok53578062011-08-03 16:08:59 +0900559 startSpellCheckerServiceInnerLocked(
560 sci, locale, tsListener, scListener, uid, bundle);
satok6be6d752011-07-28 20:40:38 +0900561 } finally {
562 Binder.restoreCallingIdentity(ident);
satok988323c2011-06-22 16:38:13 +0900563 }
satok988323c2011-06-22 16:38:13 +0900564 }
565 return;
566 }
567
satoka33c4fc2011-08-25 16:50:11 +0900568 @Override
569 public boolean isSpellCheckerEnabled() {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900570 if (!calledFromValidUser()) {
571 return false;
572 }
satoka33c4fc2011-08-25 16:50:11 +0900573 synchronized(mSpellCheckerMap) {
574 return isSpellCheckerEnabledLocked();
575 }
576 }
577
satok6be6d752011-07-28 20:40:38 +0900578 private void startSpellCheckerServiceInnerLocked(SpellCheckerInfo info, String locale,
satokdf5659d2011-07-29 18:38:21 +0900579 ITextServicesSessionListener tsListener, ISpellCheckerSessionListener scListener,
satok53578062011-08-03 16:08:59 +0900580 int uid, Bundle bundle) {
satokdf5659d2011-07-29 18:38:21 +0900581 if (DBG) {
582 Slog.w(TAG, "Start spell checker session inner locked.");
583 }
satok6be6d752011-07-28 20:40:38 +0900584 final String sciId = info.getId();
585 final InternalServiceConnection connection = new InternalServiceConnection(
satok060677f2011-11-17 09:40:56 +0900586 sciId, locale, bundle);
satok6be6d752011-07-28 20:40:38 +0900587 final Intent serviceIntent = new Intent(SpellCheckerService.SERVICE_INTERFACE);
588 serviceIntent.setComponent(info.getComponent());
589 if (DBG) {
590 Slog.w(TAG, "bind service: " + info.getId());
591 }
Dianne Hackbornd69e4c12015-04-24 09:54:54 -0700592 if (!bindCurrentSpellCheckerService(serviceIntent, connection,
593 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE_WHILE_AWAKE)) {
satok6be6d752011-07-28 20:40:38 +0900594 Slog.e(TAG, "Failed to get a spell checker service.");
595 return;
596 }
597 final SpellCheckerBindGroup group = new SpellCheckerBindGroup(
satok53578062011-08-03 16:08:59 +0900598 connection, tsListener, locale, scListener, uid, bundle);
satok6be6d752011-07-28 20:40:38 +0900599 mSpellCheckerBindGroups.put(sciId, group);
600 }
601
satok988323c2011-06-22 16:38:13 +0900602 @Override
satok562ab582011-07-25 10:12:21 +0900603 public SpellCheckerInfo[] getEnabledSpellCheckers() {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900604 // TODO: Make this work even for non-current users?
605 if (!calledFromValidUser()) {
606 return null;
607 }
satokda317ef2011-07-26 08:02:45 +0900608 if (DBG) {
609 Slog.d(TAG, "getEnabledSpellCheckers: " + mSpellCheckerList.size());
610 for (int i = 0; i < mSpellCheckerList.size(); ++i) {
611 Slog.d(TAG, "EnabledSpellCheckers: " + mSpellCheckerList.get(i).getPackageName());
612 }
613 }
satok562ab582011-07-25 10:12:21 +0900614 return mSpellCheckerList.toArray(new SpellCheckerInfo[mSpellCheckerList.size()]);
615 }
616
617 @Override
satok988323c2011-06-22 16:38:13 +0900618 public void finishSpellCheckerService(ISpellCheckerSessionListener listener) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900619 if (!calledFromValidUser()) {
620 return;
621 }
satokda317ef2011-07-26 08:02:45 +0900622 if (DBG) {
623 Slog.d(TAG, "FinishSpellCheckerService");
624 }
satok988323c2011-06-22 16:38:13 +0900625 synchronized(mSpellCheckerMap) {
satok4c3fa642011-11-30 18:17:59 +0900626 final ArrayList<SpellCheckerBindGroup> removeList =
627 new ArrayList<SpellCheckerBindGroup>();
satok988323c2011-06-22 16:38:13 +0900628 for (SpellCheckerBindGroup group : mSpellCheckerBindGroups.values()) {
629 if (group == null) continue;
satok4c3fa642011-11-30 18:17:59 +0900630 // Use removeList to avoid modifying mSpellCheckerBindGroups in this loop.
631 removeList.add(group);
632 }
633 final int removeSize = removeList.size();
634 for (int i = 0; i < removeSize; ++i) {
635 removeList.get(i).removeListener(listener);
satok988323c2011-06-22 16:38:13 +0900636 }
637 }
638 }
639
satokdf5659d2011-07-29 18:38:21 +0900640 @Override
satokada8c4e2011-08-23 14:56:56 +0900641 public void setCurrentSpellChecker(String locale, String sciId) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900642 if (!calledFromValidUser()) {
643 return;
644 }
satokdf5659d2011-07-29 18:38:21 +0900645 synchronized(mSpellCheckerMap) {
646 if (mContext.checkCallingOrSelfPermission(
647 android.Manifest.permission.WRITE_SECURE_SETTINGS)
648 != PackageManager.PERMISSION_GRANTED) {
649 throw new SecurityException(
650 "Requires permission "
651 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
652 }
satok5b9b5a92011-08-02 12:24:44 +0900653 setCurrentSpellCheckerLocked(sciId);
satokdf5659d2011-07-29 18:38:21 +0900654 }
655 }
656
satokada8c4e2011-08-23 14:56:56 +0900657 @Override
658 public void setCurrentSpellCheckerSubtype(String locale, int hashCode) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900659 if (!calledFromValidUser()) {
660 return;
661 }
satokada8c4e2011-08-23 14:56:56 +0900662 synchronized(mSpellCheckerMap) {
663 if (mContext.checkCallingOrSelfPermission(
664 android.Manifest.permission.WRITE_SECURE_SETTINGS)
665 != PackageManager.PERMISSION_GRANTED) {
666 throw new SecurityException(
667 "Requires permission "
668 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
669 }
satoka33c4fc2011-08-25 16:50:11 +0900670 setCurrentSpellCheckerSubtypeLocked(hashCode);
671 }
672 }
673
674 @Override
675 public void setSpellCheckerEnabled(boolean enabled) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900676 if (!calledFromValidUser()) {
677 return;
678 }
satoka33c4fc2011-08-25 16:50:11 +0900679 synchronized(mSpellCheckerMap) {
680 if (mContext.checkCallingOrSelfPermission(
681 android.Manifest.permission.WRITE_SECURE_SETTINGS)
682 != PackageManager.PERMISSION_GRANTED) {
683 throw new SecurityException(
684 "Requires permission "
685 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
686 }
687 setSpellCheckerEnabledLocked(enabled);
satokada8c4e2011-08-23 14:56:56 +0900688 }
689 }
690
satok5b9b5a92011-08-02 12:24:44 +0900691 private void setCurrentSpellCheckerLocked(String sciId) {
satok562ab582011-07-25 10:12:21 +0900692 if (DBG) {
satok5b9b5a92011-08-02 12:24:44 +0900693 Slog.w(TAG, "setCurrentSpellChecker: " + sciId);
satok562ab582011-07-25 10:12:21 +0900694 }
satok5b9b5a92011-08-02 12:24:44 +0900695 if (TextUtils.isEmpty(sciId) || !mSpellCheckerMap.containsKey(sciId)) return;
satokf39daef2011-08-26 19:54:27 +0900696 final SpellCheckerInfo currentSci = getCurrentSpellChecker(null);
697 if (currentSci != null && currentSci.getId().equals(sciId)) {
698 // Do nothing if the current spell checker is same as new spell checker.
699 return;
700 }
satokdf5659d2011-07-29 18:38:21 +0900701 final long ident = Binder.clearCallingIdentity();
702 try {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900703 mSettings.putSelectedSpellChecker(sciId);
satokf39daef2011-08-26 19:54:27 +0900704 setCurrentSpellCheckerSubtypeLocked(0);
satokada8c4e2011-08-23 14:56:56 +0900705 } finally {
706 Binder.restoreCallingIdentity(ident);
707 }
708 }
709
satoka33c4fc2011-08-25 16:50:11 +0900710 private void setCurrentSpellCheckerSubtypeLocked(int hashCode) {
satokada8c4e2011-08-23 14:56:56 +0900711 if (DBG) {
712 Slog.w(TAG, "setCurrentSpellCheckerSubtype: " + hashCode);
713 }
714 final SpellCheckerInfo sci = getCurrentSpellChecker(null);
satokfbedf1a2011-08-26 15:48:50 +0900715 int tempHashCode = 0;
716 for (int i = 0; sci != null && i < sci.getSubtypeCount(); ++i) {
satokada8c4e2011-08-23 14:56:56 +0900717 if(sci.getSubtypeAt(i).hashCode() == hashCode) {
satokfbedf1a2011-08-26 15:48:50 +0900718 tempHashCode = hashCode;
satokada8c4e2011-08-23 14:56:56 +0900719 break;
720 }
721 }
satokada8c4e2011-08-23 14:56:56 +0900722 final long ident = Binder.clearCallingIdentity();
723 try {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900724 mSettings.putSelectedSpellCheckerSubtype(tempHashCode);
satokdf5659d2011-07-29 18:38:21 +0900725 } finally {
726 Binder.restoreCallingIdentity(ident);
727 }
satok988323c2011-06-22 16:38:13 +0900728 }
729
satoka33c4fc2011-08-25 16:50:11 +0900730 private void setSpellCheckerEnabledLocked(boolean enabled) {
731 if (DBG) {
732 Slog.w(TAG, "setSpellCheckerEnabled: " + enabled);
733 }
734 final long ident = Binder.clearCallingIdentity();
735 try {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900736 mSettings.setSpellCheckerEnabled(enabled);
satoka33c4fc2011-08-25 16:50:11 +0900737 } finally {
738 Binder.restoreCallingIdentity(ident);
739 }
740 }
741
742 private boolean isSpellCheckerEnabledLocked() {
743 final long ident = Binder.clearCallingIdentity();
744 try {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900745 final boolean retval = mSettings.isSpellCheckerEnabled();
satoka33c4fc2011-08-25 16:50:11 +0900746 if (DBG) {
747 Slog.w(TAG, "getSpellCheckerEnabled: " + retval);
748 }
749 return retval;
750 } finally {
751 Binder.restoreCallingIdentity(ident);
752 }
753 }
754
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700755 @Override
756 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
757 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
758 != PackageManager.PERMISSION_GRANTED) {
759
760 pw.println("Permission Denial: can't dump TextServicesManagerService from from pid="
761 + Binder.getCallingPid()
762 + ", uid=" + Binder.getCallingUid());
763 return;
764 }
765
766 synchronized(mSpellCheckerMap) {
767 pw.println("Current Text Services Manager state:");
768 pw.println(" Spell Checker Map:");
769 for (Map.Entry<String, SpellCheckerInfo> ent : mSpellCheckerMap.entrySet()) {
770 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
771 SpellCheckerInfo info = ent.getValue();
772 pw.print(" "); pw.print("id="); pw.println(info.getId());
773 pw.print(" "); pw.print("comp=");
774 pw.println(info.getComponent().toShortString());
775 int NS = info.getSubtypeCount();
776 for (int i=0; i<NS; i++) {
777 SpellCheckerSubtype st = info.getSubtypeAt(i);
778 pw.print(" "); pw.print("Subtype #"); pw.print(i); pw.println(":");
779 pw.print(" "); pw.print("locale="); pw.println(st.getLocale());
780 pw.print(" "); pw.print("extraValue=");
781 pw.println(st.getExtraValue());
782 }
783 }
784 pw.println("");
785 pw.println(" Spell Checker Bind Groups:");
786 for (Map.Entry<String, SpellCheckerBindGroup> ent
787 : mSpellCheckerBindGroups.entrySet()) {
788 SpellCheckerBindGroup grp = ent.getValue();
789 pw.print(" "); pw.print(ent.getKey()); pw.print(" ");
790 pw.print(grp); pw.println(":");
791 pw.print(" "); pw.print("mInternalConnection=");
792 pw.println(grp.mInternalConnection);
793 pw.print(" "); pw.print("mSpellChecker=");
794 pw.println(grp.mSpellChecker);
795 pw.print(" "); pw.print("mBound="); pw.print(grp.mBound);
796 pw.print(" mConnected="); pw.println(grp.mConnected);
797 int NL = grp.mListeners.size();
798 for (int i=0; i<NL; i++) {
799 InternalDeathRecipient listener = grp.mListeners.get(i);
800 pw.print(" "); pw.print("Listener #"); pw.print(i); pw.println(":");
801 pw.print(" "); pw.print("mTsListener=");
802 pw.println(listener.mTsListener);
803 pw.print(" "); pw.print("mScListener=");
804 pw.println(listener.mScListener);
805 pw.print(" "); pw.print("mGroup=");
806 pw.println(listener.mGroup);
807 pw.print(" "); pw.print("mScLocale=");
808 pw.print(listener.mScLocale);
809 pw.print(" mUid="); pw.println(listener.mUid);
810 }
811 }
812 }
813 }
814
satok988323c2011-06-22 16:38:13 +0900815 // SpellCheckerBindGroup contains active text service session listeners.
816 // If there are no listeners anymore, the SpellCheckerBindGroup instance will be removed from
817 // mSpellCheckerBindGroups
818 private class SpellCheckerBindGroup {
satokdf5659d2011-07-29 18:38:21 +0900819 private final String TAG = SpellCheckerBindGroup.class.getSimpleName();
satok6be6d752011-07-28 20:40:38 +0900820 private final InternalServiceConnection mInternalConnection;
satok4e713f12012-02-28 16:51:15 +0900821 private final CopyOnWriteArrayList<InternalDeathRecipient> mListeners =
822 new CopyOnWriteArrayList<InternalDeathRecipient>();
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700823 public boolean mBound;
satok6be6d752011-07-28 20:40:38 +0900824 public ISpellCheckerService mSpellChecker;
825 public boolean mConnected;
satok988323c2011-06-22 16:38:13 +0900826
827 public SpellCheckerBindGroup(InternalServiceConnection connection,
828 ITextServicesSessionListener listener, String locale,
satok53578062011-08-03 16:08:59 +0900829 ISpellCheckerSessionListener scListener, int uid, Bundle bundle) {
satok988323c2011-06-22 16:38:13 +0900830 mInternalConnection = connection;
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700831 mBound = true;
satok6be6d752011-07-28 20:40:38 +0900832 mConnected = false;
satok53578062011-08-03 16:08:59 +0900833 addListener(listener, locale, scListener, uid, bundle);
satok988323c2011-06-22 16:38:13 +0900834 }
835
836 public void onServiceConnected(ISpellCheckerService spellChecker) {
satokda317ef2011-07-26 08:02:45 +0900837 if (DBG) {
838 Slog.d(TAG, "onServiceConnected");
839 }
satok4e713f12012-02-28 16:51:15 +0900840
841 for (InternalDeathRecipient listener : mListeners) {
842 try {
843 final ISpellCheckerSession session = spellChecker.getISpellCheckerSession(
844 listener.mScLocale, listener.mScListener, listener.mBundle);
845 synchronized(mSpellCheckerMap) {
846 if (mListeners.contains(listener)) {
847 listener.mTsListener.onServiceConnected(session);
848 }
satok988323c2011-06-22 16:38:13 +0900849 }
satok4e713f12012-02-28 16:51:15 +0900850 } catch (RemoteException e) {
851 Slog.e(TAG, "Exception in getting the spell checker session."
852 + "Reconnect to the spellchecker. ", e);
853 removeAll();
854 return;
satok988323c2011-06-22 16:38:13 +0900855 }
satok4e713f12012-02-28 16:51:15 +0900856 }
857 synchronized(mSpellCheckerMap) {
satok6be6d752011-07-28 20:40:38 +0900858 mSpellChecker = spellChecker;
859 mConnected = true;
satok988323c2011-06-22 16:38:13 +0900860 }
861 }
862
satok6be6d752011-07-28 20:40:38 +0900863 public InternalDeathRecipient addListener(ITextServicesSessionListener tsListener,
satok53578062011-08-03 16:08:59 +0900864 String locale, ISpellCheckerSessionListener scListener, int uid, Bundle bundle) {
satokda317ef2011-07-26 08:02:45 +0900865 if (DBG) {
866 Slog.d(TAG, "addListener: " + locale);
867 }
satok6be6d752011-07-28 20:40:38 +0900868 InternalDeathRecipient recipient = null;
satok988323c2011-06-22 16:38:13 +0900869 synchronized(mSpellCheckerMap) {
870 try {
871 final int size = mListeners.size();
872 for (int i = 0; i < size; ++i) {
873 if (mListeners.get(i).hasSpellCheckerListener(scListener)) {
874 // do not add the lister if the group already contains this.
satok6be6d752011-07-28 20:40:38 +0900875 return null;
satok988323c2011-06-22 16:38:13 +0900876 }
877 }
satok6be6d752011-07-28 20:40:38 +0900878 recipient = new InternalDeathRecipient(
satok53578062011-08-03 16:08:59 +0900879 this, tsListener, locale, scListener, uid, bundle);
satok988323c2011-06-22 16:38:13 +0900880 scListener.asBinder().linkToDeath(recipient, 0);
satokdf5659d2011-07-29 18:38:21 +0900881 mListeners.add(recipient);
satok988323c2011-06-22 16:38:13 +0900882 } catch(RemoteException e) {
883 // do nothing
884 }
885 cleanLocked();
886 }
satok6be6d752011-07-28 20:40:38 +0900887 return recipient;
satok988323c2011-06-22 16:38:13 +0900888 }
889
890 public void removeListener(ISpellCheckerSessionListener listener) {
satokda317ef2011-07-26 08:02:45 +0900891 if (DBG) {
satokdf5659d2011-07-29 18:38:21 +0900892 Slog.w(TAG, "remove listener: " + listener.hashCode());
satokda317ef2011-07-26 08:02:45 +0900893 }
satok988323c2011-06-22 16:38:13 +0900894 synchronized(mSpellCheckerMap) {
895 final int size = mListeners.size();
896 final ArrayList<InternalDeathRecipient> removeList =
897 new ArrayList<InternalDeathRecipient>();
898 for (int i = 0; i < size; ++i) {
899 final InternalDeathRecipient tempRecipient = mListeners.get(i);
900 if(tempRecipient.hasSpellCheckerListener(listener)) {
satokdf5659d2011-07-29 18:38:21 +0900901 if (DBG) {
902 Slog.w(TAG, "found existing listener.");
903 }
satok988323c2011-06-22 16:38:13 +0900904 removeList.add(tempRecipient);
905 }
906 }
907 final int removeSize = removeList.size();
908 for (int i = 0; i < removeSize; ++i) {
satokdf5659d2011-07-29 18:38:21 +0900909 if (DBG) {
910 Slog.w(TAG, "Remove " + removeList.get(i));
911 }
satok2520ed82011-10-31 19:38:05 +0900912 final InternalDeathRecipient idr = removeList.get(i);
913 idr.mScListener.asBinder().unlinkToDeath(idr, 0);
914 mListeners.remove(idr);
satok988323c2011-06-22 16:38:13 +0900915 }
916 cleanLocked();
917 }
918 }
919
satok4c3fa642011-11-30 18:17:59 +0900920 // cleanLocked may remove elements from mSpellCheckerBindGroups
satok988323c2011-06-22 16:38:13 +0900921 private void cleanLocked() {
satokda317ef2011-07-26 08:02:45 +0900922 if (DBG) {
923 Slog.d(TAG, "cleanLocked");
924 }
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700925 // If there are no more active listeners, clean up. Only do this
926 // once.
927 if (mBound && mListeners.isEmpty()) {
928 mBound = false;
satokc7b60f722011-08-31 16:30:27 +0900929 final String sciId = mInternalConnection.mSciId;
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700930 SpellCheckerBindGroup cur = mSpellCheckerBindGroups.get(sciId);
931 if (cur == this) {
satokc7b60f722011-08-31 16:30:27 +0900932 if (DBG) {
933 Slog.d(TAG, "Remove bind group.");
934 }
935 mSpellCheckerBindGroups.remove(sciId);
satok6be6d752011-07-28 20:40:38 +0900936 }
satok988323c2011-06-22 16:38:13 +0900937 mContext.unbindService(mInternalConnection);
938 }
939 }
satok6be6d752011-07-28 20:40:38 +0900940
941 public void removeAll() {
942 Slog.e(TAG, "Remove the spell checker bind unexpectedly.");
satokdf5659d2011-07-29 18:38:21 +0900943 synchronized(mSpellCheckerMap) {
satok2520ed82011-10-31 19:38:05 +0900944 final int size = mListeners.size();
945 for (int i = 0; i < size; ++i) {
946 final InternalDeathRecipient idr = mListeners.get(i);
947 idr.mScListener.asBinder().unlinkToDeath(idr, 0);
948 }
satokdf5659d2011-07-29 18:38:21 +0900949 mListeners.clear();
950 cleanLocked();
951 }
satok6be6d752011-07-28 20:40:38 +0900952 }
satok988323c2011-06-22 16:38:13 +0900953 }
954
955 private class InternalServiceConnection implements ServiceConnection {
satok988323c2011-06-22 16:38:13 +0900956 private final String mSciId;
957 private final String mLocale;
satok53578062011-08-03 16:08:59 +0900958 private final Bundle mBundle;
satok988323c2011-06-22 16:38:13 +0900959 public InternalServiceConnection(
satok060677f2011-11-17 09:40:56 +0900960 String id, String locale, Bundle bundle) {
satok988323c2011-06-22 16:38:13 +0900961 mSciId = id;
962 mLocale = locale;
satok53578062011-08-03 16:08:59 +0900963 mBundle = bundle;
satok988323c2011-06-22 16:38:13 +0900964 }
965
966 @Override
967 public void onServiceConnected(ComponentName name, IBinder service) {
968 synchronized(mSpellCheckerMap) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900969 onServiceConnectedInnerLocked(name, service);
970 }
971 }
972
973 private void onServiceConnectedInnerLocked(ComponentName name, IBinder service) {
974 if (DBG) {
975 Slog.w(TAG, "onServiceConnected: " + name);
976 }
977 final ISpellCheckerService spellChecker =
978 ISpellCheckerService.Stub.asInterface(service);
979 final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId);
980 if (group != null && this == group.mInternalConnection) {
981 group.onServiceConnected(spellChecker);
satok988323c2011-06-22 16:38:13 +0900982 }
983 }
984
985 @Override
986 public void onServiceDisconnected(ComponentName name) {
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700987 synchronized(mSpellCheckerMap) {
988 final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId);
satok2cf1cf02011-10-21 15:25:23 +0900989 if (group != null && this == group.mInternalConnection) {
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700990 mSpellCheckerBindGroups.remove(mSciId);
991 }
992 }
satok988323c2011-06-22 16:38:13 +0900993 }
994 }
995
996 private class InternalDeathRecipient implements IBinder.DeathRecipient {
997 public final ITextServicesSessionListener mTsListener;
998 public final ISpellCheckerSessionListener mScListener;
999 public final String mScLocale;
1000 private final SpellCheckerBindGroup mGroup;
satokdf5659d2011-07-29 18:38:21 +09001001 public final int mUid;
satok53578062011-08-03 16:08:59 +09001002 public final Bundle mBundle;
satok988323c2011-06-22 16:38:13 +09001003 public InternalDeathRecipient(SpellCheckerBindGroup group,
1004 ITextServicesSessionListener tsListener, String scLocale,
satok53578062011-08-03 16:08:59 +09001005 ISpellCheckerSessionListener scListener, int uid, Bundle bundle) {
satok988323c2011-06-22 16:38:13 +09001006 mTsListener = tsListener;
1007 mScListener = scListener;
1008 mScLocale = scLocale;
1009 mGroup = group;
satokdf5659d2011-07-29 18:38:21 +09001010 mUid = uid;
satok53578062011-08-03 16:08:59 +09001011 mBundle = bundle;
satok988323c2011-06-22 16:38:13 +09001012 }
1013
1014 public boolean hasSpellCheckerListener(ISpellCheckerSessionListener listener) {
satokdf5659d2011-07-29 18:38:21 +09001015 return listener.asBinder().equals(mScListener.asBinder());
satok988323c2011-06-22 16:38:13 +09001016 }
1017
1018 @Override
1019 public void binderDied() {
1020 mGroup.removeListener(mScListener);
1021 }
1022 }
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001023
1024 private static class TextServicesSettings {
1025 private final ContentResolver mResolver;
1026 private int mCurrentUserId;
Yohei Yukawa095fa372014-10-27 14:02:23 +09001027 @GuardedBy("mLock")
1028 private int[] mCurrentProfileIds = new int[0];
1029 private Object mLock = new Object();
1030
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001031 public TextServicesSettings(ContentResolver resolver, int userId) {
1032 mResolver = resolver;
1033 mCurrentUserId = userId;
1034 }
1035
1036 public void setCurrentUserId(int userId) {
1037 if (DBG) {
1038 Slog.d(TAG, "--- Swtich the current user from " + mCurrentUserId + " to "
1039 + userId + ", new ime = " + getSelectedSpellChecker());
1040 }
1041 // TSMS settings are kept per user, so keep track of current user
1042 mCurrentUserId = userId;
1043 }
1044
Yohei Yukawa095fa372014-10-27 14:02:23 +09001045 public void setCurrentProfileIds(int[] currentProfileIds) {
1046 synchronized (mLock) {
1047 mCurrentProfileIds = currentProfileIds;
1048 }
1049 }
1050
1051 public boolean isCurrentProfile(int userId) {
1052 synchronized (mLock) {
1053 if (userId == mCurrentUserId) return true;
1054 for (int i = 0; i < mCurrentProfileIds.length; i++) {
1055 if (userId == mCurrentProfileIds[i]) return true;
1056 }
1057 return false;
1058 }
1059 }
1060
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001061 public int getCurrentUserId() {
1062 return mCurrentUserId;
1063 }
1064
1065 public void putSelectedSpellChecker(String sciId) {
1066 Settings.Secure.putStringForUser(mResolver,
1067 Settings.Secure.SELECTED_SPELL_CHECKER, sciId, mCurrentUserId);
1068 }
1069
1070 public void putSelectedSpellCheckerSubtype(int hashCode) {
1071 Settings.Secure.putStringForUser(mResolver,
1072 Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, String.valueOf(hashCode),
1073 mCurrentUserId);
1074 }
1075
1076 public void setSpellCheckerEnabled(boolean enabled) {
1077 Settings.Secure.putIntForUser(mResolver,
1078 Settings.Secure.SPELL_CHECKER_ENABLED, enabled ? 1 : 0, mCurrentUserId);
1079 }
1080
1081 public String getSelectedSpellChecker() {
1082 return Settings.Secure.getStringForUser(mResolver,
1083 Settings.Secure.SELECTED_SPELL_CHECKER, mCurrentUserId);
1084 }
1085
1086 public String getSelectedSpellCheckerSubtype() {
1087 return Settings.Secure.getStringForUser(mResolver,
1088 Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, mCurrentUserId);
1089 }
1090
1091 public boolean isSpellCheckerEnabled() {
1092 return Settings.Secure.getIntForUser(mResolver,
1093 Settings.Secure.SPELL_CHECKER_ENABLED, 1, mCurrentUserId) == 1;
1094 }
1095 }
1096
1097 // ----------------------------------------------------------------------
1098 // Utilities for debug
1099 private static String getStackTrace() {
1100 final StringBuilder sb = new StringBuilder();
1101 try {
1102 throw new RuntimeException();
1103 } catch (RuntimeException e) {
1104 final StackTraceElement[] frames = e.getStackTrace();
1105 // Start at 1 because the first frame is here and we don't care about it
1106 for (int j = 1; j < frames.length; ++j) {
1107 sb.append(frames[j].toString() + "\n");
1108 }
1109 }
1110 return sb.toString();
1111 }
satok988323c2011-06-22 16:38:13 +09001112}