blob: c4b4cbeda3db8575f1d0d8084244dcbb34467cab [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;
Fyodor Kupolov6005b3f2015-11-23 17:41:50 -080032import android.app.SynchronousUserSwitchObserver;
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.Process;
satok988323c2011-06-22 16:38:13 +090049import android.os.RemoteException;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090050import android.os.UserHandle;
Yohei Yukawa095fa372014-10-27 14:02:23 +090051import android.os.UserManager;
satok988323c2011-06-22 16:38:13 +090052import android.provider.Settings;
satok988323c2011-06-22 16:38:13 +090053import android.service.textservice.SpellCheckerService;
satok53578062011-08-03 16:08:59 +090054import android.text.TextUtils;
satok988323c2011-06-22 16:38:13 +090055import android.util.Slog;
satok05f24702011-11-02 19:29:35 +090056import android.view.inputmethod.InputMethodManager;
57import android.view.inputmethod.InputMethodSubtype;
satok988323c2011-06-22 16:38:13 +090058import android.view.textservice.SpellCheckerInfo;
satokada8c4e2011-08-23 14:56:56 +090059import android.view.textservice.SpellCheckerSubtype;
satok988323c2011-06-22 16:38:13 +090060
Dianne Hackborn71e14da2011-10-16 16:28:10 -070061import java.io.FileDescriptor;
satok03b2ea12011-08-03 17:36:14 +090062import java.io.IOException;
Dianne Hackborn71e14da2011-10-16 16:28:10 -070063import java.io.PrintWriter;
Yohei Yukawa174843a2015-06-26 18:02:54 -070064import java.util.Arrays;
satok988323c2011-06-22 16:38:13 +090065import java.util.ArrayList;
66import java.util.HashMap;
satok988323c2011-06-22 16:38:13 +090067import java.util.List;
Yohei Yukawa174843a2015-06-26 18:02:54 -070068import java.util.Locale;
Dianne Hackborn71e14da2011-10-16 16:28:10 -070069import java.util.Map;
satok4e713f12012-02-28 16:51:15 +090070import java.util.concurrent.CopyOnWriteArrayList;
satok988323c2011-06-22 16:38:13 +090071
72public class TextServicesManagerService extends ITextServicesManager.Stub {
73 private static final String TAG = TextServicesManagerService.class.getSimpleName();
74 private static final boolean DBG = false;
75
76 private final Context mContext;
77 private boolean mSystemReady;
78 private final TextServicesMonitor mMonitor;
79 private final HashMap<String, SpellCheckerInfo> mSpellCheckerMap =
80 new HashMap<String, SpellCheckerInfo>();
81 private final ArrayList<SpellCheckerInfo> mSpellCheckerList = new ArrayList<SpellCheckerInfo>();
82 private final HashMap<String, SpellCheckerBindGroup> mSpellCheckerBindGroups =
83 new HashMap<String, SpellCheckerBindGroup>();
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090084 private final TextServicesSettings mSettings;
satok988323c2011-06-22 16:38:13 +090085
Svetoslav Ganova0027152013-06-25 14:59:53 -070086 public void systemRunning() {
satok988323c2011-06-22 16:38:13 +090087 if (!mSystemReady) {
88 mSystemReady = true;
89 }
90 }
91
92 public TextServicesManagerService(Context context) {
93 mSystemReady = false;
94 mContext = context;
Yohei Yukawa095fa372014-10-27 14:02:23 +090095
96 final IntentFilter broadcastFilter = new IntentFilter();
97 broadcastFilter.addAction(Intent.ACTION_USER_ADDED);
98 broadcastFilter.addAction(Intent.ACTION_USER_REMOVED);
99 mContext.registerReceiver(new TextServicesBroadcastReceiver(), broadcastFilter);
100
Xiaohui Chen7c696362015-09-16 09:56:14 -0700101 int userId = UserHandle.USER_SYSTEM;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900102 try {
103 ActivityManagerNative.getDefault().registerUserSwitchObserver(
Fyodor Kupolov6005b3f2015-11-23 17:41:50 -0800104 new SynchronousUserSwitchObserver() {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900105 @Override
Fyodor Kupolov6005b3f2015-11-23 17:41:50 -0800106 public void onUserSwitching(int newUserId) throws RemoteException {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900107 synchronized(mSpellCheckerMap) {
108 switchUserLocked(newUserId);
109 }
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900110 }
111
112 @Override
113 public void onUserSwitchComplete(int newUserId) throws RemoteException {
114 }
Kenny Guy42979622015-04-13 18:03:05 +0000115
116 @Override
117 public void onForegroundProfileSwitch(int newProfileId) {
118 // Ignore.
119 }
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900120 });
121 userId = ActivityManagerNative.getDefault().getCurrentUser().id;
122 } catch (RemoteException e) {
123 Slog.w(TAG, "Couldn't get current user ID; guessing it's 0", e);
124 }
satok988323c2011-06-22 16:38:13 +0900125 mMonitor = new TextServicesMonitor();
Dianne Hackbornd0d75032012-04-19 23:12:09 -0700126 mMonitor.register(context, null, true);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900127 mSettings = new TextServicesSettings(context.getContentResolver(), userId);
128
129 // "switchUserLocked" initializes the states for the foreground user
130 switchUserLocked(userId);
131 }
132
133 private void switchUserLocked(int userId) {
134 mSettings.setCurrentUserId(userId);
Yohei Yukawa095fa372014-10-27 14:02:23 +0900135 updateCurrentProfileIds();
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900136 unbindServiceLocked();
137 buildSpellCheckerMapLocked(mContext, mSpellCheckerList, mSpellCheckerMap, mSettings);
satokdf5659d2011-07-29 18:38:21 +0900138 SpellCheckerInfo sci = getCurrentSpellChecker(null);
139 if (sci == null) {
Yohei Yukawa174843a2015-06-26 18:02:54 -0700140 sci = findAvailSpellCheckerLocked(null);
satokdf5659d2011-07-29 18:38:21 +0900141 if (sci != null) {
142 // Set the current spell checker if there is one or more spell checkers
143 // available. In this case, "sci" is the first one in the available spell
144 // checkers.
satok5b9b5a92011-08-02 12:24:44 +0900145 setCurrentSpellCheckerLocked(sci.getId());
satokdf5659d2011-07-29 18:38:21 +0900146 }
147 }
satok988323c2011-06-22 16:38:13 +0900148 }
149
Yohei Yukawa095fa372014-10-27 14:02:23 +0900150 void updateCurrentProfileIds() {
151 List<UserInfo> profiles =
152 UserManager.get(mContext).getProfiles(mSettings.getCurrentUserId());
153 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
154 for (int i = 0; i < currentProfileIds.length; i++) {
155 currentProfileIds[i] = profiles.get(i).id;
156 }
157 mSettings.setCurrentProfileIds(currentProfileIds);
158 }
159
satok988323c2011-06-22 16:38:13 +0900160 private class TextServicesMonitor extends PackageMonitor {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900161 private boolean isChangingPackagesOfCurrentUser() {
162 final int userId = getChangingUserId();
163 final boolean retval = userId == mSettings.getCurrentUserId();
164 if (DBG) {
165 Slog.d(TAG, "--- ignore this call back from a background user: " + userId);
166 }
167 return retval;
168 }
169
satok988323c2011-06-22 16:38:13 +0900170 @Override
171 public void onSomePackagesChanged() {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900172 if (!isChangingPackagesOfCurrentUser()) {
173 return;
174 }
satok988323c2011-06-22 16:38:13 +0900175 synchronized (mSpellCheckerMap) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900176 buildSpellCheckerMapLocked(
177 mContext, mSpellCheckerList, mSpellCheckerMap, mSettings);
satok988323c2011-06-22 16:38:13 +0900178 // TODO: Update for each locale
179 SpellCheckerInfo sci = getCurrentSpellChecker(null);
Satoshi Kataoka02260e22013-08-02 16:22:04 +0900180 // If no spell checker is enabled, just return. The user should explicitly
181 // enable the spell checker.
satokda317ef2011-07-26 08:02:45 +0900182 if (sci == null) return;
satok988323c2011-06-22 16:38:13 +0900183 final String packageName = sci.getPackageName();
184 final int change = isPackageDisappearing(packageName);
satok5b9b5a92011-08-02 12:24:44 +0900185 if (// Package disappearing
186 change == PACKAGE_PERMANENT_CHANGE || change == PACKAGE_TEMPORARY_CHANGE
187 // Package modified
188 || isPackageModified(packageName)) {
Yohei Yukawa174843a2015-06-26 18:02:54 -0700189 sci = findAvailSpellCheckerLocked(packageName);
satok5b9b5a92011-08-02 12:24:44 +0900190 if (sci != null) {
191 setCurrentSpellCheckerLocked(sci.getId());
192 }
satok988323c2011-06-22 16:38:13 +0900193 }
194 }
195 }
196 }
197
Yohei Yukawa095fa372014-10-27 14:02:23 +0900198 class TextServicesBroadcastReceiver extends BroadcastReceiver {
199 @Override
200 public void onReceive(Context context, Intent intent) {
201 final String action = intent.getAction();
202 if (Intent.ACTION_USER_ADDED.equals(action)
203 || Intent.ACTION_USER_REMOVED.equals(action)) {
204 updateCurrentProfileIds();
205 return;
206 }
207 Slog.w(TAG, "Unexpected intent " + intent);
208 }
209 }
210
satok988323c2011-06-22 16:38:13 +0900211 private static void buildSpellCheckerMapLocked(Context context,
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900212 ArrayList<SpellCheckerInfo> list, HashMap<String, SpellCheckerInfo> map,
213 TextServicesSettings settings) {
satok988323c2011-06-22 16:38:13 +0900214 list.clear();
215 map.clear();
216 final PackageManager pm = context.getPackageManager();
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900217 final List<ResolveInfo> services = pm.queryIntentServicesAsUser(
218 new Intent(SpellCheckerService.SERVICE_INTERFACE), PackageManager.GET_META_DATA,
219 settings.getCurrentUserId());
satok988323c2011-06-22 16:38:13 +0900220 final int N = services.size();
221 for (int i = 0; i < N; ++i) {
222 final ResolveInfo ri = services.get(i);
223 final ServiceInfo si = ri.serviceInfo;
224 final ComponentName compName = new ComponentName(si.packageName, si.name);
225 if (!android.Manifest.permission.BIND_TEXT_SERVICE.equals(si.permission)) {
226 Slog.w(TAG, "Skipping text service " + compName
227 + ": it does not require the permission "
228 + android.Manifest.permission.BIND_TEXT_SERVICE);
229 continue;
230 }
231 if (DBG) Slog.d(TAG, "Add: " + compName);
satok03b2ea12011-08-03 17:36:14 +0900232 try {
233 final SpellCheckerInfo sci = new SpellCheckerInfo(context, ri);
satok3cb5b392011-08-26 11:55:21 +0900234 if (sci.getSubtypeCount() <= 0) {
235 Slog.w(TAG, "Skipping text service " + compName
236 + ": it does not contain subtypes.");
237 continue;
238 }
satok03b2ea12011-08-03 17:36:14 +0900239 list.add(sci);
240 map.put(sci.getId(), sci);
241 } catch (XmlPullParserException e) {
242 Slog.w(TAG, "Unable to load the spell checker " + compName, e);
243 } catch (IOException e) {
244 Slog.w(TAG, "Unable to load the spell checker " + compName, e);
245 }
satok988323c2011-06-22 16:38:13 +0900246 }
satokda317ef2011-07-26 08:02:45 +0900247 if (DBG) {
248 Slog.d(TAG, "buildSpellCheckerMapLocked: " + list.size() + "," + map.size());
249 }
satok988323c2011-06-22 16:38:13 +0900250 }
251
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900252 // ---------------------------------------------------------------------------------------
253 // Check whether or not this is a valid IPC. Assumes an IPC is valid when either
254 // 1) it comes from the system process
255 // 2) the calling process' user id is identical to the current user id TSMS thinks.
256 private boolean calledFromValidUser() {
257 final int uid = Binder.getCallingUid();
258 final int userId = UserHandle.getUserId(uid);
259 if (DBG) {
260 Slog.d(TAG, "--- calledFromForegroundUserOrSystemProcess ? "
261 + "calling uid = " + uid + " system uid = " + Process.SYSTEM_UID
262 + " calling userId = " + userId + ", foreground user id = "
Yohei Yukawa095fa372014-10-27 14:02:23 +0900263 + mSettings.getCurrentUserId() + ", calling pid = " + Binder.getCallingPid());
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900264 try {
265 final String[] packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
266 for (int i = 0; i < packageNames.length; ++i) {
267 if (DBG) {
268 Slog.d(TAG, "--- process name for "+ uid + " = " + packageNames[i]);
269 }
270 }
271 } catch (RemoteException e) {
272 }
273 }
274
275 if (uid == Process.SYSTEM_UID || userId == mSettings.getCurrentUserId()) {
276 return true;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900277 }
Yohei Yukawa095fa372014-10-27 14:02:23 +0900278
279 // Permits current profile to use TSFM as long as the current text service is the system's
280 // one. This is a tentative solution and should be replaced with fully functional multiuser
281 // support.
282 // TODO: Implement multiuser support in TSMS.
283 final boolean isCurrentProfile = mSettings.isCurrentProfile(userId);
284 if (DBG) {
285 Slog.d(TAG, "--- userId = "+ userId + " isCurrentProfile = " + isCurrentProfile);
286 }
287 if (mSettings.isCurrentProfile(userId)) {
288 final SpellCheckerInfo spellCheckerInfo = getCurrentSpellCheckerWithoutVerification();
289 if (spellCheckerInfo != null) {
290 final ServiceInfo serviceInfo = spellCheckerInfo.getServiceInfo();
291 final boolean isSystemSpellChecker =
292 (serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
293 if (DBG) {
294 Slog.d(TAG, "--- current spell checker = "+ spellCheckerInfo.getPackageName()
295 + " isSystem = " + isSystemSpellChecker);
296 }
297 if (isSystemSpellChecker) {
298 return true;
299 }
300 }
301 }
302
303 // Unlike InputMethodManagerService#calledFromValidUser, INTERACT_ACROSS_USERS_FULL isn't
304 // taken into account here. Anyway this method is supposed to be removed once multiuser
305 // support is implemented.
306 if (DBG) {
307 Slog.d(TAG, "--- IPC from userId:" + userId + " is being ignored. \n"
308 + getStackTrace());
309 }
310 return false;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900311 }
312
313 private boolean bindCurrentSpellCheckerService(
314 Intent service, ServiceConnection conn, int flags) {
315 if (service == null || conn == null) {
316 Slog.e(TAG, "--- bind failed: service = " + service + ", conn = " + conn);
317 return false;
318 }
Amith Yamasani27b89e62013-01-16 12:30:11 -0800319 return mContext.bindServiceAsUser(service, conn, flags,
320 new UserHandle(mSettings.getCurrentUserId()));
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900321 }
322
323 private void unbindServiceLocked() {
324 for (SpellCheckerBindGroup scbg : mSpellCheckerBindGroups.values()) {
325 scbg.removeAll();
326 }
327 mSpellCheckerBindGroups.clear();
328 }
329
Yohei Yukawa174843a2015-06-26 18:02:54 -0700330 private SpellCheckerInfo findAvailSpellCheckerLocked(String prefPackage) {
satok988323c2011-06-22 16:38:13 +0900331 final int spellCheckersCount = mSpellCheckerList.size();
332 if (spellCheckersCount == 0) {
333 Slog.w(TAG, "no available spell checker services found");
334 return null;
335 }
336 if (prefPackage != null) {
337 for (int i = 0; i < spellCheckersCount; ++i) {
338 final SpellCheckerInfo sci = mSpellCheckerList.get(i);
339 if (prefPackage.equals(sci.getPackageName())) {
satokda317ef2011-07-26 08:02:45 +0900340 if (DBG) {
341 Slog.d(TAG, "findAvailSpellCheckerLocked: " + sci.getPackageName());
342 }
satok988323c2011-06-22 16:38:13 +0900343 return sci;
344 }
345 }
346 }
Yohei Yukawa174843a2015-06-26 18:02:54 -0700347
348 // Look up a spell checker based on the system locale.
349 // TODO: Still there is a room to improve in the following logic: e.g., check if the package
350 // is pre-installed or not.
351 final Locale systemLocal = mContext.getResources().getConfiguration().locale;
352 final ArrayList<Locale> suitableLocales =
353 InputMethodUtils.getSuitableLocalesForSpellChecker(systemLocal);
354 if (DBG) {
355 Slog.w(TAG, "findAvailSpellCheckerLocked suitableLocales="
356 + Arrays.toString(suitableLocales.toArray(new Locale[suitableLocales.size()])));
357 }
358 final int localeCount = suitableLocales.size();
359 for (int localeIndex = 0; localeIndex < localeCount; ++localeIndex) {
360 final Locale locale = suitableLocales.get(localeIndex);
361 for (int spellCheckersIndex = 0; spellCheckersIndex < spellCheckersCount;
362 ++spellCheckersIndex) {
363 final SpellCheckerInfo info = mSpellCheckerList.get(spellCheckersIndex);
364 final int subtypeCount = info.getSubtypeCount();
365 for (int subtypeIndex = 0; subtypeIndex < subtypeCount; ++subtypeIndex) {
366 final SpellCheckerSubtype subtype = info.getSubtypeAt(subtypeIndex);
367 final Locale subtypeLocale = InputMethodUtils.constructLocaleFromString(
368 subtype.getLocale());
369 if (locale.equals(subtypeLocale)) {
370 // TODO: We may have more spell checkers that fall into this category.
371 // Ideally we should pick up the most suitable one instead of simply
372 // returning the first found one.
373 return info;
374 }
375 }
376 }
377 }
378
satok988323c2011-06-22 16:38:13 +0900379 if (spellCheckersCount > 1) {
380 Slog.w(TAG, "more than one spell checker service found, picking first");
381 }
382 return mSpellCheckerList.get(0);
383 }
384
385 // TODO: Save SpellCheckerService by supported languages. Currently only one spell
386 // checker is saved.
387 @Override
388 public SpellCheckerInfo getCurrentSpellChecker(String locale) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900389 // TODO: Make this work even for non-current users?
390 if (!calledFromValidUser()) {
391 return null;
392 }
Yohei Yukawa095fa372014-10-27 14:02:23 +0900393 return getCurrentSpellCheckerWithoutVerification();
394 }
395
396 private SpellCheckerInfo getCurrentSpellCheckerWithoutVerification() {
satok988323c2011-06-22 16:38:13 +0900397 synchronized (mSpellCheckerMap) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900398 final String curSpellCheckerId = mSettings.getSelectedSpellChecker();
satok562ab582011-07-25 10:12:21 +0900399 if (DBG) {
400 Slog.w(TAG, "getCurrentSpellChecker: " + curSpellCheckerId);
401 }
satok988323c2011-06-22 16:38:13 +0900402 if (TextUtils.isEmpty(curSpellCheckerId)) {
satokdf5659d2011-07-29 18:38:21 +0900403 return null;
satok988323c2011-06-22 16:38:13 +0900404 }
405 return mSpellCheckerMap.get(curSpellCheckerId);
406 }
407 }
408
satok3cb5b392011-08-26 11:55:21 +0900409 // TODO: Respect allowImplicitlySelectedSubtype
Satoshi Kataoka17150cf2012-05-30 20:05:44 +0900410 // TODO: Save SpellCheckerSubtype by supported languages by looking at "locale".
satokada8c4e2011-08-23 14:56:56 +0900411 @Override
satok3cb5b392011-08-26 11:55:21 +0900412 public SpellCheckerSubtype getCurrentSpellCheckerSubtype(
413 String locale, boolean allowImplicitlySelectedSubtype) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900414 // TODO: Make this work even for non-current users?
415 if (!calledFromValidUser()) {
416 return null;
417 }
satokada8c4e2011-08-23 14:56:56 +0900418 synchronized (mSpellCheckerMap) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900419 final String subtypeHashCodeStr = mSettings.getSelectedSpellCheckerSubtype();
satokada8c4e2011-08-23 14:56:56 +0900420 if (DBG) {
satokc7b60f722011-08-31 16:30:27 +0900421 Slog.w(TAG, "getCurrentSpellCheckerSubtype: " + subtypeHashCodeStr);
satokada8c4e2011-08-23 14:56:56 +0900422 }
423 final SpellCheckerInfo sci = getCurrentSpellChecker(null);
satoka33c4fc2011-08-25 16:50:11 +0900424 if (sci == null || sci.getSubtypeCount() == 0) {
425 if (DBG) {
426 Slog.w(TAG, "Subtype not found.");
427 }
satokada8c4e2011-08-23 14:56:56 +0900428 return null;
429 }
satokb3879542011-08-26 17:35:27 +0900430 final int hashCode;
431 if (!TextUtils.isEmpty(subtypeHashCodeStr)) {
432 hashCode = Integer.valueOf(subtypeHashCodeStr);
433 } else {
434 hashCode = 0;
435 }
436 if (hashCode == 0 && !allowImplicitlySelectedSubtype) {
satok3cb5b392011-08-26 11:55:21 +0900437 return null;
satokada8c4e2011-08-23 14:56:56 +0900438 }
satok05f24702011-11-02 19:29:35 +0900439 String candidateLocale = null;
440 if (hashCode == 0) {
441 // Spell checker language settings == "auto"
Yohei Yukawa777ef952015-11-25 20:32:24 -0800442 final InputMethodManager imm = mContext.getSystemService(InputMethodManager.class);
satok05f24702011-11-02 19:29:35 +0900443 if (imm != null) {
444 final InputMethodSubtype currentInputMethodSubtype =
445 imm.getCurrentInputMethodSubtype();
446 if (currentInputMethodSubtype != null) {
447 final String localeString = currentInputMethodSubtype.getLocale();
448 if (!TextUtils.isEmpty(localeString)) {
449 // 1. Use keyboard locale if available in the spell checker
450 candidateLocale = localeString;
451 }
452 }
453 }
454 if (candidateLocale == null) {
455 // 2. Use System locale if available in the spell checker
456 candidateLocale = mContext.getResources().getConfiguration().locale.toString();
457 }
458 }
satokb3879542011-08-26 17:35:27 +0900459 SpellCheckerSubtype candidate = null;
satokada8c4e2011-08-23 14:56:56 +0900460 for (int i = 0; i < sci.getSubtypeCount(); ++i) {
461 final SpellCheckerSubtype scs = sci.getSubtypeAt(i);
satokb3879542011-08-26 17:35:27 +0900462 if (hashCode == 0) {
Satoshi Kataoka17150cf2012-05-30 20:05:44 +0900463 final String scsLocale = scs.getLocale();
464 if (candidateLocale.equals(scsLocale)) {
satokb3879542011-08-26 17:35:27 +0900465 return scs;
466 } else if (candidate == null) {
satok7018a902012-05-24 18:10:37 +0900467 if (candidateLocale.length() >= 2 && scsLocale.length() >= 2
468 && candidateLocale.startsWith(scsLocale)) {
satok05f24702011-11-02 19:29:35 +0900469 // Fall back to the applicable language
satokb3879542011-08-26 17:35:27 +0900470 candidate = scs;
471 }
472 }
473 } else if (scs.hashCode() == hashCode) {
satoka33c4fc2011-08-25 16:50:11 +0900474 if (DBG) {
satok70deff42011-09-30 15:14:21 +0900475 Slog.w(TAG, "Return subtype " + scs.hashCode() + ", input= " + locale
476 + ", " + scs.getLocale());
satoka33c4fc2011-08-25 16:50:11 +0900477 }
satok05f24702011-11-02 19:29:35 +0900478 // 3. Use the user specified spell check language
satokada8c4e2011-08-23 14:56:56 +0900479 return scs;
480 }
481 }
satok05f24702011-11-02 19:29:35 +0900482 // 4. Fall back to the applicable language and return it if not null
483 // 5. Simply just return it even if it's null which means we could find no suitable
484 // spell check languages
satokb3879542011-08-26 17:35:27 +0900485 return candidate;
satokada8c4e2011-08-23 14:56:56 +0900486 }
487 }
488
satok988323c2011-06-22 16:38:13 +0900489 @Override
satok5b9b5a92011-08-02 12:24:44 +0900490 public void getSpellCheckerService(String sciId, String locale,
satok53578062011-08-03 16:08:59 +0900491 ITextServicesSessionListener tsListener, ISpellCheckerSessionListener scListener,
492 Bundle bundle) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900493 if (!calledFromValidUser()) {
494 return;
495 }
satok988323c2011-06-22 16:38:13 +0900496 if (!mSystemReady) {
497 return;
498 }
satok5b9b5a92011-08-02 12:24:44 +0900499 if (TextUtils.isEmpty(sciId) || tsListener == null || scListener == null) {
satok988323c2011-06-22 16:38:13 +0900500 Slog.e(TAG, "getSpellCheckerService: Invalid input.");
501 return;
502 }
satok988323c2011-06-22 16:38:13 +0900503 synchronized(mSpellCheckerMap) {
504 if (!mSpellCheckerMap.containsKey(sciId)) {
505 return;
506 }
satok5b9b5a92011-08-02 12:24:44 +0900507 final SpellCheckerInfo sci = mSpellCheckerMap.get(sciId);
satokdf5659d2011-07-29 18:38:21 +0900508 final int uid = Binder.getCallingUid();
satok988323c2011-06-22 16:38:13 +0900509 if (mSpellCheckerBindGroups.containsKey(sciId)) {
satok6be6d752011-07-28 20:40:38 +0900510 final SpellCheckerBindGroup bindGroup = mSpellCheckerBindGroups.get(sciId);
511 if (bindGroup != null) {
512 final InternalDeathRecipient recipient =
513 mSpellCheckerBindGroups.get(sciId).addListener(
satok53578062011-08-03 16:08:59 +0900514 tsListener, locale, scListener, uid, bundle);
satok6be6d752011-07-28 20:40:38 +0900515 if (recipient == null) {
516 if (DBG) {
517 Slog.w(TAG, "Didn't create a death recipient.");
518 }
519 return;
520 }
521 if (bindGroup.mSpellChecker == null & bindGroup.mConnected) {
522 Slog.e(TAG, "The state of the spell checker bind group is illegal.");
523 bindGroup.removeAll();
524 } else if (bindGroup.mSpellChecker != null) {
525 if (DBG) {
satokdf5659d2011-07-29 18:38:21 +0900526 Slog.w(TAG, "Existing bind found. Return a spell checker session now. "
527 + "Listeners count = " + bindGroup.mListeners.size());
satok6be6d752011-07-28 20:40:38 +0900528 }
529 try {
530 final ISpellCheckerSession session =
531 bindGroup.mSpellChecker.getISpellCheckerSession(
satok53578062011-08-03 16:08:59 +0900532 recipient.mScLocale, recipient.mScListener, bundle);
satokdf5659d2011-07-29 18:38:21 +0900533 if (session != null) {
534 tsListener.onServiceConnected(session);
535 return;
536 } else {
537 if (DBG) {
538 Slog.w(TAG, "Existing bind already expired. ");
539 }
540 bindGroup.removeAll();
541 }
satok6be6d752011-07-28 20:40:38 +0900542 } catch (RemoteException e) {
543 Slog.e(TAG, "Exception in getting spell checker session: " + e);
544 bindGroup.removeAll();
545 }
546 }
547 }
satok988323c2011-06-22 16:38:13 +0900548 }
satok6be6d752011-07-28 20:40:38 +0900549 final long ident = Binder.clearCallingIdentity();
550 try {
satok53578062011-08-03 16:08:59 +0900551 startSpellCheckerServiceInnerLocked(
552 sci, locale, tsListener, scListener, uid, bundle);
satok6be6d752011-07-28 20:40:38 +0900553 } finally {
554 Binder.restoreCallingIdentity(ident);
satok988323c2011-06-22 16:38:13 +0900555 }
satok988323c2011-06-22 16:38:13 +0900556 }
557 return;
558 }
559
satoka33c4fc2011-08-25 16:50:11 +0900560 @Override
561 public boolean isSpellCheckerEnabled() {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900562 if (!calledFromValidUser()) {
563 return false;
564 }
satoka33c4fc2011-08-25 16:50:11 +0900565 synchronized(mSpellCheckerMap) {
566 return isSpellCheckerEnabledLocked();
567 }
568 }
569
satok6be6d752011-07-28 20:40:38 +0900570 private void startSpellCheckerServiceInnerLocked(SpellCheckerInfo info, String locale,
satokdf5659d2011-07-29 18:38:21 +0900571 ITextServicesSessionListener tsListener, ISpellCheckerSessionListener scListener,
satok53578062011-08-03 16:08:59 +0900572 int uid, Bundle bundle) {
satokdf5659d2011-07-29 18:38:21 +0900573 if (DBG) {
574 Slog.w(TAG, "Start spell checker session inner locked.");
575 }
satok6be6d752011-07-28 20:40:38 +0900576 final String sciId = info.getId();
577 final InternalServiceConnection connection = new InternalServiceConnection(
satok060677f2011-11-17 09:40:56 +0900578 sciId, locale, bundle);
satok6be6d752011-07-28 20:40:38 +0900579 final Intent serviceIntent = new Intent(SpellCheckerService.SERVICE_INTERFACE);
580 serviceIntent.setComponent(info.getComponent());
581 if (DBG) {
582 Slog.w(TAG, "bind service: " + info.getId());
583 }
Dianne Hackbornd69e4c12015-04-24 09:54:54 -0700584 if (!bindCurrentSpellCheckerService(serviceIntent, connection,
585 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE_WHILE_AWAKE)) {
satok6be6d752011-07-28 20:40:38 +0900586 Slog.e(TAG, "Failed to get a spell checker service.");
587 return;
588 }
589 final SpellCheckerBindGroup group = new SpellCheckerBindGroup(
satok53578062011-08-03 16:08:59 +0900590 connection, tsListener, locale, scListener, uid, bundle);
satok6be6d752011-07-28 20:40:38 +0900591 mSpellCheckerBindGroups.put(sciId, group);
592 }
593
satok988323c2011-06-22 16:38:13 +0900594 @Override
satok562ab582011-07-25 10:12:21 +0900595 public SpellCheckerInfo[] getEnabledSpellCheckers() {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900596 // TODO: Make this work even for non-current users?
597 if (!calledFromValidUser()) {
598 return null;
599 }
satokda317ef2011-07-26 08:02:45 +0900600 if (DBG) {
601 Slog.d(TAG, "getEnabledSpellCheckers: " + mSpellCheckerList.size());
602 for (int i = 0; i < mSpellCheckerList.size(); ++i) {
603 Slog.d(TAG, "EnabledSpellCheckers: " + mSpellCheckerList.get(i).getPackageName());
604 }
605 }
satok562ab582011-07-25 10:12:21 +0900606 return mSpellCheckerList.toArray(new SpellCheckerInfo[mSpellCheckerList.size()]);
607 }
608
609 @Override
satok988323c2011-06-22 16:38:13 +0900610 public void finishSpellCheckerService(ISpellCheckerSessionListener listener) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900611 if (!calledFromValidUser()) {
612 return;
613 }
satokda317ef2011-07-26 08:02:45 +0900614 if (DBG) {
615 Slog.d(TAG, "FinishSpellCheckerService");
616 }
satok988323c2011-06-22 16:38:13 +0900617 synchronized(mSpellCheckerMap) {
satok4c3fa642011-11-30 18:17:59 +0900618 final ArrayList<SpellCheckerBindGroup> removeList =
619 new ArrayList<SpellCheckerBindGroup>();
satok988323c2011-06-22 16:38:13 +0900620 for (SpellCheckerBindGroup group : mSpellCheckerBindGroups.values()) {
621 if (group == null) continue;
satok4c3fa642011-11-30 18:17:59 +0900622 // Use removeList to avoid modifying mSpellCheckerBindGroups in this loop.
623 removeList.add(group);
624 }
625 final int removeSize = removeList.size();
626 for (int i = 0; i < removeSize; ++i) {
627 removeList.get(i).removeListener(listener);
satok988323c2011-06-22 16:38:13 +0900628 }
629 }
630 }
631
satokdf5659d2011-07-29 18:38:21 +0900632 @Override
satokada8c4e2011-08-23 14:56:56 +0900633 public void setCurrentSpellChecker(String locale, String sciId) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900634 if (!calledFromValidUser()) {
635 return;
636 }
satokdf5659d2011-07-29 18:38:21 +0900637 synchronized(mSpellCheckerMap) {
638 if (mContext.checkCallingOrSelfPermission(
639 android.Manifest.permission.WRITE_SECURE_SETTINGS)
640 != PackageManager.PERMISSION_GRANTED) {
641 throw new SecurityException(
642 "Requires permission "
643 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
644 }
satok5b9b5a92011-08-02 12:24:44 +0900645 setCurrentSpellCheckerLocked(sciId);
satokdf5659d2011-07-29 18:38:21 +0900646 }
647 }
648
satokada8c4e2011-08-23 14:56:56 +0900649 @Override
650 public void setCurrentSpellCheckerSubtype(String locale, int hashCode) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900651 if (!calledFromValidUser()) {
652 return;
653 }
satokada8c4e2011-08-23 14:56:56 +0900654 synchronized(mSpellCheckerMap) {
655 if (mContext.checkCallingOrSelfPermission(
656 android.Manifest.permission.WRITE_SECURE_SETTINGS)
657 != PackageManager.PERMISSION_GRANTED) {
658 throw new SecurityException(
659 "Requires permission "
660 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
661 }
satoka33c4fc2011-08-25 16:50:11 +0900662 setCurrentSpellCheckerSubtypeLocked(hashCode);
663 }
664 }
665
666 @Override
667 public void setSpellCheckerEnabled(boolean enabled) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900668 if (!calledFromValidUser()) {
669 return;
670 }
satoka33c4fc2011-08-25 16:50:11 +0900671 synchronized(mSpellCheckerMap) {
672 if (mContext.checkCallingOrSelfPermission(
673 android.Manifest.permission.WRITE_SECURE_SETTINGS)
674 != PackageManager.PERMISSION_GRANTED) {
675 throw new SecurityException(
676 "Requires permission "
677 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
678 }
679 setSpellCheckerEnabledLocked(enabled);
satokada8c4e2011-08-23 14:56:56 +0900680 }
681 }
682
satok5b9b5a92011-08-02 12:24:44 +0900683 private void setCurrentSpellCheckerLocked(String sciId) {
satok562ab582011-07-25 10:12:21 +0900684 if (DBG) {
satok5b9b5a92011-08-02 12:24:44 +0900685 Slog.w(TAG, "setCurrentSpellChecker: " + sciId);
satok562ab582011-07-25 10:12:21 +0900686 }
satok5b9b5a92011-08-02 12:24:44 +0900687 if (TextUtils.isEmpty(sciId) || !mSpellCheckerMap.containsKey(sciId)) return;
satokf39daef2011-08-26 19:54:27 +0900688 final SpellCheckerInfo currentSci = getCurrentSpellChecker(null);
689 if (currentSci != null && currentSci.getId().equals(sciId)) {
690 // Do nothing if the current spell checker is same as new spell checker.
691 return;
692 }
satokdf5659d2011-07-29 18:38:21 +0900693 final long ident = Binder.clearCallingIdentity();
694 try {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900695 mSettings.putSelectedSpellChecker(sciId);
satokf39daef2011-08-26 19:54:27 +0900696 setCurrentSpellCheckerSubtypeLocked(0);
satokada8c4e2011-08-23 14:56:56 +0900697 } finally {
698 Binder.restoreCallingIdentity(ident);
699 }
700 }
701
satoka33c4fc2011-08-25 16:50:11 +0900702 private void setCurrentSpellCheckerSubtypeLocked(int hashCode) {
satokada8c4e2011-08-23 14:56:56 +0900703 if (DBG) {
704 Slog.w(TAG, "setCurrentSpellCheckerSubtype: " + hashCode);
705 }
706 final SpellCheckerInfo sci = getCurrentSpellChecker(null);
satokfbedf1a2011-08-26 15:48:50 +0900707 int tempHashCode = 0;
708 for (int i = 0; sci != null && i < sci.getSubtypeCount(); ++i) {
satokada8c4e2011-08-23 14:56:56 +0900709 if(sci.getSubtypeAt(i).hashCode() == hashCode) {
satokfbedf1a2011-08-26 15:48:50 +0900710 tempHashCode = hashCode;
satokada8c4e2011-08-23 14:56:56 +0900711 break;
712 }
713 }
satokada8c4e2011-08-23 14:56:56 +0900714 final long ident = Binder.clearCallingIdentity();
715 try {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900716 mSettings.putSelectedSpellCheckerSubtype(tempHashCode);
satokdf5659d2011-07-29 18:38:21 +0900717 } finally {
718 Binder.restoreCallingIdentity(ident);
719 }
satok988323c2011-06-22 16:38:13 +0900720 }
721
satoka33c4fc2011-08-25 16:50:11 +0900722 private void setSpellCheckerEnabledLocked(boolean enabled) {
723 if (DBG) {
724 Slog.w(TAG, "setSpellCheckerEnabled: " + enabled);
725 }
726 final long ident = Binder.clearCallingIdentity();
727 try {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900728 mSettings.setSpellCheckerEnabled(enabled);
satoka33c4fc2011-08-25 16:50:11 +0900729 } finally {
730 Binder.restoreCallingIdentity(ident);
731 }
732 }
733
734 private boolean isSpellCheckerEnabledLocked() {
735 final long ident = Binder.clearCallingIdentity();
736 try {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900737 final boolean retval = mSettings.isSpellCheckerEnabled();
satoka33c4fc2011-08-25 16:50:11 +0900738 if (DBG) {
739 Slog.w(TAG, "getSpellCheckerEnabled: " + retval);
740 }
741 return retval;
742 } finally {
743 Binder.restoreCallingIdentity(ident);
744 }
745 }
746
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700747 @Override
748 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
749 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
750 != PackageManager.PERMISSION_GRANTED) {
751
752 pw.println("Permission Denial: can't dump TextServicesManagerService from from pid="
753 + Binder.getCallingPid()
754 + ", uid=" + Binder.getCallingUid());
755 return;
756 }
757
758 synchronized(mSpellCheckerMap) {
759 pw.println("Current Text Services Manager state:");
760 pw.println(" Spell Checker Map:");
761 for (Map.Entry<String, SpellCheckerInfo> ent : mSpellCheckerMap.entrySet()) {
762 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
763 SpellCheckerInfo info = ent.getValue();
764 pw.print(" "); pw.print("id="); pw.println(info.getId());
765 pw.print(" "); pw.print("comp=");
766 pw.println(info.getComponent().toShortString());
767 int NS = info.getSubtypeCount();
768 for (int i=0; i<NS; i++) {
769 SpellCheckerSubtype st = info.getSubtypeAt(i);
770 pw.print(" "); pw.print("Subtype #"); pw.print(i); pw.println(":");
771 pw.print(" "); pw.print("locale="); pw.println(st.getLocale());
772 pw.print(" "); pw.print("extraValue=");
773 pw.println(st.getExtraValue());
774 }
775 }
776 pw.println("");
777 pw.println(" Spell Checker Bind Groups:");
778 for (Map.Entry<String, SpellCheckerBindGroup> ent
779 : mSpellCheckerBindGroups.entrySet()) {
780 SpellCheckerBindGroup grp = ent.getValue();
781 pw.print(" "); pw.print(ent.getKey()); pw.print(" ");
782 pw.print(grp); pw.println(":");
783 pw.print(" "); pw.print("mInternalConnection=");
784 pw.println(grp.mInternalConnection);
785 pw.print(" "); pw.print("mSpellChecker=");
786 pw.println(grp.mSpellChecker);
787 pw.print(" "); pw.print("mBound="); pw.print(grp.mBound);
788 pw.print(" mConnected="); pw.println(grp.mConnected);
789 int NL = grp.mListeners.size();
790 for (int i=0; i<NL; i++) {
791 InternalDeathRecipient listener = grp.mListeners.get(i);
792 pw.print(" "); pw.print("Listener #"); pw.print(i); pw.println(":");
793 pw.print(" "); pw.print("mTsListener=");
794 pw.println(listener.mTsListener);
795 pw.print(" "); pw.print("mScListener=");
796 pw.println(listener.mScListener);
797 pw.print(" "); pw.print("mGroup=");
798 pw.println(listener.mGroup);
799 pw.print(" "); pw.print("mScLocale=");
800 pw.print(listener.mScLocale);
801 pw.print(" mUid="); pw.println(listener.mUid);
802 }
803 }
804 }
805 }
806
satok988323c2011-06-22 16:38:13 +0900807 // SpellCheckerBindGroup contains active text service session listeners.
808 // If there are no listeners anymore, the SpellCheckerBindGroup instance will be removed from
809 // mSpellCheckerBindGroups
810 private class SpellCheckerBindGroup {
satokdf5659d2011-07-29 18:38:21 +0900811 private final String TAG = SpellCheckerBindGroup.class.getSimpleName();
satok6be6d752011-07-28 20:40:38 +0900812 private final InternalServiceConnection mInternalConnection;
satok4e713f12012-02-28 16:51:15 +0900813 private final CopyOnWriteArrayList<InternalDeathRecipient> mListeners =
814 new CopyOnWriteArrayList<InternalDeathRecipient>();
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700815 public boolean mBound;
satok6be6d752011-07-28 20:40:38 +0900816 public ISpellCheckerService mSpellChecker;
817 public boolean mConnected;
satok988323c2011-06-22 16:38:13 +0900818
819 public SpellCheckerBindGroup(InternalServiceConnection connection,
820 ITextServicesSessionListener listener, String locale,
satok53578062011-08-03 16:08:59 +0900821 ISpellCheckerSessionListener scListener, int uid, Bundle bundle) {
satok988323c2011-06-22 16:38:13 +0900822 mInternalConnection = connection;
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700823 mBound = true;
satok6be6d752011-07-28 20:40:38 +0900824 mConnected = false;
satok53578062011-08-03 16:08:59 +0900825 addListener(listener, locale, scListener, uid, bundle);
satok988323c2011-06-22 16:38:13 +0900826 }
827
828 public void onServiceConnected(ISpellCheckerService spellChecker) {
satokda317ef2011-07-26 08:02:45 +0900829 if (DBG) {
830 Slog.d(TAG, "onServiceConnected");
831 }
satok4e713f12012-02-28 16:51:15 +0900832
833 for (InternalDeathRecipient listener : mListeners) {
834 try {
835 final ISpellCheckerSession session = spellChecker.getISpellCheckerSession(
836 listener.mScLocale, listener.mScListener, listener.mBundle);
837 synchronized(mSpellCheckerMap) {
838 if (mListeners.contains(listener)) {
839 listener.mTsListener.onServiceConnected(session);
840 }
satok988323c2011-06-22 16:38:13 +0900841 }
satok4e713f12012-02-28 16:51:15 +0900842 } catch (RemoteException e) {
843 Slog.e(TAG, "Exception in getting the spell checker session."
844 + "Reconnect to the spellchecker. ", e);
845 removeAll();
846 return;
satok988323c2011-06-22 16:38:13 +0900847 }
satok4e713f12012-02-28 16:51:15 +0900848 }
849 synchronized(mSpellCheckerMap) {
satok6be6d752011-07-28 20:40:38 +0900850 mSpellChecker = spellChecker;
851 mConnected = true;
satok988323c2011-06-22 16:38:13 +0900852 }
853 }
854
satok6be6d752011-07-28 20:40:38 +0900855 public InternalDeathRecipient addListener(ITextServicesSessionListener tsListener,
satok53578062011-08-03 16:08:59 +0900856 String locale, ISpellCheckerSessionListener scListener, int uid, Bundle bundle) {
satokda317ef2011-07-26 08:02:45 +0900857 if (DBG) {
858 Slog.d(TAG, "addListener: " + locale);
859 }
satok6be6d752011-07-28 20:40:38 +0900860 InternalDeathRecipient recipient = null;
satok988323c2011-06-22 16:38:13 +0900861 synchronized(mSpellCheckerMap) {
862 try {
863 final int size = mListeners.size();
864 for (int i = 0; i < size; ++i) {
865 if (mListeners.get(i).hasSpellCheckerListener(scListener)) {
866 // do not add the lister if the group already contains this.
satok6be6d752011-07-28 20:40:38 +0900867 return null;
satok988323c2011-06-22 16:38:13 +0900868 }
869 }
satok6be6d752011-07-28 20:40:38 +0900870 recipient = new InternalDeathRecipient(
satok53578062011-08-03 16:08:59 +0900871 this, tsListener, locale, scListener, uid, bundle);
satok988323c2011-06-22 16:38:13 +0900872 scListener.asBinder().linkToDeath(recipient, 0);
satokdf5659d2011-07-29 18:38:21 +0900873 mListeners.add(recipient);
satok988323c2011-06-22 16:38:13 +0900874 } catch(RemoteException e) {
875 // do nothing
876 }
877 cleanLocked();
878 }
satok6be6d752011-07-28 20:40:38 +0900879 return recipient;
satok988323c2011-06-22 16:38:13 +0900880 }
881
882 public void removeListener(ISpellCheckerSessionListener listener) {
satokda317ef2011-07-26 08:02:45 +0900883 if (DBG) {
satokdf5659d2011-07-29 18:38:21 +0900884 Slog.w(TAG, "remove listener: " + listener.hashCode());
satokda317ef2011-07-26 08:02:45 +0900885 }
satok988323c2011-06-22 16:38:13 +0900886 synchronized(mSpellCheckerMap) {
887 final int size = mListeners.size();
888 final ArrayList<InternalDeathRecipient> removeList =
889 new ArrayList<InternalDeathRecipient>();
890 for (int i = 0; i < size; ++i) {
891 final InternalDeathRecipient tempRecipient = mListeners.get(i);
892 if(tempRecipient.hasSpellCheckerListener(listener)) {
satokdf5659d2011-07-29 18:38:21 +0900893 if (DBG) {
894 Slog.w(TAG, "found existing listener.");
895 }
satok988323c2011-06-22 16:38:13 +0900896 removeList.add(tempRecipient);
897 }
898 }
899 final int removeSize = removeList.size();
900 for (int i = 0; i < removeSize; ++i) {
satokdf5659d2011-07-29 18:38:21 +0900901 if (DBG) {
902 Slog.w(TAG, "Remove " + removeList.get(i));
903 }
satok2520ed82011-10-31 19:38:05 +0900904 final InternalDeathRecipient idr = removeList.get(i);
905 idr.mScListener.asBinder().unlinkToDeath(idr, 0);
906 mListeners.remove(idr);
satok988323c2011-06-22 16:38:13 +0900907 }
908 cleanLocked();
909 }
910 }
911
satok4c3fa642011-11-30 18:17:59 +0900912 // cleanLocked may remove elements from mSpellCheckerBindGroups
satok988323c2011-06-22 16:38:13 +0900913 private void cleanLocked() {
satokda317ef2011-07-26 08:02:45 +0900914 if (DBG) {
915 Slog.d(TAG, "cleanLocked");
916 }
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700917 // If there are no more active listeners, clean up. Only do this
918 // once.
919 if (mBound && mListeners.isEmpty()) {
920 mBound = false;
satokc7b60f722011-08-31 16:30:27 +0900921 final String sciId = mInternalConnection.mSciId;
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700922 SpellCheckerBindGroup cur = mSpellCheckerBindGroups.get(sciId);
923 if (cur == this) {
satokc7b60f722011-08-31 16:30:27 +0900924 if (DBG) {
925 Slog.d(TAG, "Remove bind group.");
926 }
927 mSpellCheckerBindGroups.remove(sciId);
satok6be6d752011-07-28 20:40:38 +0900928 }
satok988323c2011-06-22 16:38:13 +0900929 mContext.unbindService(mInternalConnection);
930 }
931 }
satok6be6d752011-07-28 20:40:38 +0900932
933 public void removeAll() {
934 Slog.e(TAG, "Remove the spell checker bind unexpectedly.");
satokdf5659d2011-07-29 18:38:21 +0900935 synchronized(mSpellCheckerMap) {
satok2520ed82011-10-31 19:38:05 +0900936 final int size = mListeners.size();
937 for (int i = 0; i < size; ++i) {
938 final InternalDeathRecipient idr = mListeners.get(i);
939 idr.mScListener.asBinder().unlinkToDeath(idr, 0);
940 }
satokdf5659d2011-07-29 18:38:21 +0900941 mListeners.clear();
942 cleanLocked();
943 }
satok6be6d752011-07-28 20:40:38 +0900944 }
satok988323c2011-06-22 16:38:13 +0900945 }
946
947 private class InternalServiceConnection implements ServiceConnection {
satok988323c2011-06-22 16:38:13 +0900948 private final String mSciId;
949 private final String mLocale;
satok53578062011-08-03 16:08:59 +0900950 private final Bundle mBundle;
satok988323c2011-06-22 16:38:13 +0900951 public InternalServiceConnection(
satok060677f2011-11-17 09:40:56 +0900952 String id, String locale, Bundle bundle) {
satok988323c2011-06-22 16:38:13 +0900953 mSciId = id;
954 mLocale = locale;
satok53578062011-08-03 16:08:59 +0900955 mBundle = bundle;
satok988323c2011-06-22 16:38:13 +0900956 }
957
958 @Override
959 public void onServiceConnected(ComponentName name, IBinder service) {
960 synchronized(mSpellCheckerMap) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900961 onServiceConnectedInnerLocked(name, service);
962 }
963 }
964
965 private void onServiceConnectedInnerLocked(ComponentName name, IBinder service) {
966 if (DBG) {
967 Slog.w(TAG, "onServiceConnected: " + name);
968 }
969 final ISpellCheckerService spellChecker =
970 ISpellCheckerService.Stub.asInterface(service);
971 final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId);
972 if (group != null && this == group.mInternalConnection) {
973 group.onServiceConnected(spellChecker);
satok988323c2011-06-22 16:38:13 +0900974 }
975 }
976
977 @Override
978 public void onServiceDisconnected(ComponentName name) {
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700979 synchronized(mSpellCheckerMap) {
980 final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId);
satok2cf1cf02011-10-21 15:25:23 +0900981 if (group != null && this == group.mInternalConnection) {
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700982 mSpellCheckerBindGroups.remove(mSciId);
983 }
984 }
satok988323c2011-06-22 16:38:13 +0900985 }
986 }
987
988 private class InternalDeathRecipient implements IBinder.DeathRecipient {
989 public final ITextServicesSessionListener mTsListener;
990 public final ISpellCheckerSessionListener mScListener;
991 public final String mScLocale;
992 private final SpellCheckerBindGroup mGroup;
satokdf5659d2011-07-29 18:38:21 +0900993 public final int mUid;
satok53578062011-08-03 16:08:59 +0900994 public final Bundle mBundle;
satok988323c2011-06-22 16:38:13 +0900995 public InternalDeathRecipient(SpellCheckerBindGroup group,
996 ITextServicesSessionListener tsListener, String scLocale,
satok53578062011-08-03 16:08:59 +0900997 ISpellCheckerSessionListener scListener, int uid, Bundle bundle) {
satok988323c2011-06-22 16:38:13 +0900998 mTsListener = tsListener;
999 mScListener = scListener;
1000 mScLocale = scLocale;
1001 mGroup = group;
satokdf5659d2011-07-29 18:38:21 +09001002 mUid = uid;
satok53578062011-08-03 16:08:59 +09001003 mBundle = bundle;
satok988323c2011-06-22 16:38:13 +09001004 }
1005
1006 public boolean hasSpellCheckerListener(ISpellCheckerSessionListener listener) {
satokdf5659d2011-07-29 18:38:21 +09001007 return listener.asBinder().equals(mScListener.asBinder());
satok988323c2011-06-22 16:38:13 +09001008 }
1009
1010 @Override
1011 public void binderDied() {
1012 mGroup.removeListener(mScListener);
1013 }
1014 }
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001015
1016 private static class TextServicesSettings {
1017 private final ContentResolver mResolver;
1018 private int mCurrentUserId;
Yohei Yukawa095fa372014-10-27 14:02:23 +09001019 @GuardedBy("mLock")
1020 private int[] mCurrentProfileIds = new int[0];
1021 private Object mLock = new Object();
1022
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001023 public TextServicesSettings(ContentResolver resolver, int userId) {
1024 mResolver = resolver;
1025 mCurrentUserId = userId;
1026 }
1027
1028 public void setCurrentUserId(int userId) {
1029 if (DBG) {
1030 Slog.d(TAG, "--- Swtich the current user from " + mCurrentUserId + " to "
1031 + userId + ", new ime = " + getSelectedSpellChecker());
1032 }
1033 // TSMS settings are kept per user, so keep track of current user
1034 mCurrentUserId = userId;
1035 }
1036
Yohei Yukawa095fa372014-10-27 14:02:23 +09001037 public void setCurrentProfileIds(int[] currentProfileIds) {
1038 synchronized (mLock) {
1039 mCurrentProfileIds = currentProfileIds;
1040 }
1041 }
1042
1043 public boolean isCurrentProfile(int userId) {
1044 synchronized (mLock) {
1045 if (userId == mCurrentUserId) return true;
1046 for (int i = 0; i < mCurrentProfileIds.length; i++) {
1047 if (userId == mCurrentProfileIds[i]) return true;
1048 }
1049 return false;
1050 }
1051 }
1052
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001053 public int getCurrentUserId() {
1054 return mCurrentUserId;
1055 }
1056
1057 public void putSelectedSpellChecker(String sciId) {
1058 Settings.Secure.putStringForUser(mResolver,
1059 Settings.Secure.SELECTED_SPELL_CHECKER, sciId, mCurrentUserId);
1060 }
1061
1062 public void putSelectedSpellCheckerSubtype(int hashCode) {
1063 Settings.Secure.putStringForUser(mResolver,
1064 Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, String.valueOf(hashCode),
1065 mCurrentUserId);
1066 }
1067
1068 public void setSpellCheckerEnabled(boolean enabled) {
1069 Settings.Secure.putIntForUser(mResolver,
1070 Settings.Secure.SPELL_CHECKER_ENABLED, enabled ? 1 : 0, mCurrentUserId);
1071 }
1072
1073 public String getSelectedSpellChecker() {
1074 return Settings.Secure.getStringForUser(mResolver,
1075 Settings.Secure.SELECTED_SPELL_CHECKER, mCurrentUserId);
1076 }
1077
1078 public String getSelectedSpellCheckerSubtype() {
1079 return Settings.Secure.getStringForUser(mResolver,
1080 Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, mCurrentUserId);
1081 }
1082
1083 public boolean isSpellCheckerEnabled() {
1084 return Settings.Secure.getIntForUser(mResolver,
1085 Settings.Secure.SPELL_CHECKER_ENABLED, 1, mCurrentUserId) == 1;
1086 }
1087 }
1088
1089 // ----------------------------------------------------------------------
1090 // Utilities for debug
1091 private static String getStackTrace() {
1092 final StringBuilder sb = new StringBuilder();
1093 try {
1094 throw new RuntimeException();
1095 } catch (RuntimeException e) {
1096 final StackTraceElement[] frames = e.getStackTrace();
1097 // Start at 1 because the first frame is here and we don't care about it
1098 for (int j = 1; j < frames.length; ++j) {
1099 sb.append(frames[j].toString() + "\n");
1100 }
1101 }
1102 return sb.toString();
1103 }
satok988323c2011-06-22 16:38:13 +09001104}