blob: 306e9331671ec6a1615a9741dfce2358f62bd578 [file] [log] [blame]
satok988323c2011-06-22 16:38:13 +09001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Yohei Yukawa095fa372014-10-27 14:02:23 +090019import com.android.internal.annotations.GuardedBy;
satok988323c2011-06-22 16:38:13 +090020import com.android.internal.content.PackageMonitor;
Yohei Yukawa174843a2015-06-26 18:02:54 -070021import com.android.internal.inputmethod.InputMethodUtils;
satok988323c2011-06-22 16:38:13 +090022import com.android.internal.textservice.ISpellCheckerService;
23import com.android.internal.textservice.ISpellCheckerSession;
24import com.android.internal.textservice.ISpellCheckerSessionListener;
25import com.android.internal.textservice.ITextServicesManager;
26import com.android.internal.textservice.ITextServicesSessionListener;
27
satok03b2ea12011-08-03 17:36:14 +090028import org.xmlpull.v1.XmlPullParserException;
29
Yohei Yukawaf0f16802016-03-08 16:04:58 -080030import android.annotation.NonNull;
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -080031import android.annotation.UserIdInt;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090032import android.app.ActivityManagerNative;
33import android.app.AppGlobals;
Yohei Yukawa095fa372014-10-27 14:02:23 +090034import android.content.BroadcastReceiver;
satok988323c2011-06-22 16:38:13 +090035import android.content.ComponentName;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090036import android.content.ContentResolver;
satok988323c2011-06-22 16:38:13 +090037import android.content.Context;
38import android.content.Intent;
Yohei Yukawa095fa372014-10-27 14:02:23 +090039import android.content.IntentFilter;
satok988323c2011-06-22 16:38:13 +090040import android.content.ServiceConnection;
Yohei Yukawa095fa372014-10-27 14:02:23 +090041import android.content.pm.ApplicationInfo;
satok988323c2011-06-22 16:38:13 +090042import android.content.pm.PackageManager;
43import android.content.pm.ResolveInfo;
44import android.content.pm.ServiceInfo;
Yohei Yukawa095fa372014-10-27 14:02:23 +090045import android.content.pm.UserInfo;
satok6be6d752011-07-28 20:40:38 +090046import android.os.Binder;
satok53578062011-08-03 16:08:59 +090047import android.os.Bundle;
satok988323c2011-06-22 16:38:13 +090048import android.os.IBinder;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090049import android.os.Process;
satok988323c2011-06-22 16:38:13 +090050import android.os.RemoteException;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090051import android.os.UserHandle;
Yohei Yukawa095fa372014-10-27 14:02:23 +090052import android.os.UserManager;
satok988323c2011-06-22 16:38:13 +090053import android.provider.Settings;
satok988323c2011-06-22 16:38:13 +090054import android.service.textservice.SpellCheckerService;
satok53578062011-08-03 16:08:59 +090055import android.text.TextUtils;
satok988323c2011-06-22 16:38:13 +090056import android.util.Slog;
satok05f24702011-11-02 19:29:35 +090057import android.view.inputmethod.InputMethodManager;
58import android.view.inputmethod.InputMethodSubtype;
satok988323c2011-06-22 16:38:13 +090059import android.view.textservice.SpellCheckerInfo;
satokada8c4e2011-08-23 14:56:56 +090060import android.view.textservice.SpellCheckerSubtype;
satok988323c2011-06-22 16:38:13 +090061
Dianne Hackborn71e14da2011-10-16 16:28:10 -070062import java.io.FileDescriptor;
satok03b2ea12011-08-03 17:36:14 +090063import java.io.IOException;
Dianne Hackborn71e14da2011-10-16 16:28:10 -070064import java.io.PrintWriter;
Yohei Yukawa174843a2015-06-26 18:02:54 -070065import java.util.Arrays;
satok988323c2011-06-22 16:38:13 +090066import java.util.ArrayList;
67import java.util.HashMap;
satok988323c2011-06-22 16:38:13 +090068import java.util.List;
Yohei Yukawa174843a2015-06-26 18:02:54 -070069import java.util.Locale;
Dianne Hackborn71e14da2011-10-16 16:28:10 -070070import java.util.Map;
satok4e713f12012-02-28 16:51:15 +090071import java.util.concurrent.CopyOnWriteArrayList;
satok988323c2011-06-22 16:38:13 +090072
73public class TextServicesManagerService extends ITextServicesManager.Stub {
74 private static final String TAG = TextServicesManagerService.class.getSimpleName();
75 private static final boolean DBG = false;
76
77 private final Context mContext;
78 private boolean mSystemReady;
79 private final TextServicesMonitor mMonitor;
Yohei Yukawa074637f2016-03-06 14:34:55 -080080 private final HashMap<String, SpellCheckerInfo> mSpellCheckerMap = new HashMap<>();
81 private final ArrayList<SpellCheckerInfo> mSpellCheckerList = new ArrayList<>();
82 private final HashMap<String, SpellCheckerBindGroup> mSpellCheckerBindGroups = new HashMap<>();
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090083 private final TextServicesSettings mSettings;
Yohei Yukawaf0f16802016-03-08 16:04:58 -080084 @NonNull
85 private final UserManager mUserManager;
satok988323c2011-06-22 16:38:13 +090086
Yohei Yukawaa6a152e2016-03-07 13:41:15 -080087 public static final class Lifecycle extends SystemService {
88 private TextServicesManagerService mService;
89
90 public Lifecycle(Context context) {
91 super(context);
92 mService = new TextServicesManagerService(context);
93 }
94
95 @Override
96 public void onStart() {
97 publishBinderService(Context.TEXT_SERVICES_MANAGER_SERVICE, mService);
98 }
99
100 @Override
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -0800101 public void onSwitchUser(@UserIdInt int userHandle) {
102 // Called on the system server's main looper thread.
103 // TODO: Dispatch this to a worker thread as needed.
104 mService.onSwitchUser(userHandle);
105 }
106
107 @Override
Yohei Yukawaa6a152e2016-03-07 13:41:15 -0800108 public void onBootPhase(int phase) {
109 // Called on the system server's main looper thread.
110 // TODO: Dispatch this to a worker thread as needed.
111 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
112 mService.systemRunning();
113 }
114 }
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800115
116 @Override
117 public void onUnlockUser(@UserIdInt int userHandle) {
118 // Called on the system server's main looper thread.
119 // TODO: Dispatch this to a worker thread as needed.
120 mService.onUnlockUser(userHandle);
121 }
Yohei Yukawaa6a152e2016-03-07 13:41:15 -0800122 }
123
124 void systemRunning() {
125 synchronized (mSpellCheckerMap) {
126 if (!mSystemReady) {
127 mSystemReady = true;
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800128 resetInternalState(mSettings.getCurrentUserId());
Yohei Yukawaa6a152e2016-03-07 13:41:15 -0800129 }
satok988323c2011-06-22 16:38:13 +0900130 }
131 }
132
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -0800133 void onSwitchUser(@UserIdInt int userId) {
134 synchronized (mSpellCheckerMap) {
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800135 resetInternalState(userId);
136 }
137 }
138
139 void onUnlockUser(@UserIdInt int userId) {
140 synchronized(mSpellCheckerMap) {
141 final int currentUserId = mSettings.getCurrentUserId();
142 if (userId != currentUserId) {
143 return;
144 }
145 resetInternalState(currentUserId);
satok988323c2011-06-22 16:38:13 +0900146 }
147 }
148
149 public TextServicesManagerService(Context context) {
150 mSystemReady = false;
151 mContext = context;
Yohei Yukawa095fa372014-10-27 14:02:23 +0900152
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800153 mUserManager = mContext.getSystemService(UserManager.class);
154
Yohei Yukawa095fa372014-10-27 14:02:23 +0900155 final IntentFilter broadcastFilter = new IntentFilter();
156 broadcastFilter.addAction(Intent.ACTION_USER_ADDED);
157 broadcastFilter.addAction(Intent.ACTION_USER_REMOVED);
158 mContext.registerReceiver(new TextServicesBroadcastReceiver(), broadcastFilter);
159
Xiaohui Chen7c696362015-09-16 09:56:14 -0700160 int userId = UserHandle.USER_SYSTEM;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900161 try {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900162 userId = ActivityManagerNative.getDefault().getCurrentUser().id;
163 } catch (RemoteException e) {
164 Slog.w(TAG, "Couldn't get current user ID; guessing it's 0", e);
165 }
satok988323c2011-06-22 16:38:13 +0900166 mMonitor = new TextServicesMonitor();
Dianne Hackbornd0d75032012-04-19 23:12:09 -0700167 mMonitor.register(context, null, true);
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800168 final boolean useCopyOnWriteSettings =
169 !mSystemReady || !mUserManager.isUserUnlocked(userId);
Yohei Yukawa49ed1402016-03-07 19:12:54 -0800170 mSettings = new TextServicesSettings(context.getContentResolver(), userId,
171 useCopyOnWriteSettings);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900172
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800173 // "resetInternalState" initializes the states for the foreground user
174 resetInternalState(userId);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900175 }
176
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800177 private void resetInternalState(@UserIdInt int userId) {
178 final boolean useCopyOnWriteSettings =
179 !mSystemReady || !mUserManager.isUserUnlocked(userId);
Yohei Yukawa49ed1402016-03-07 19:12:54 -0800180 mSettings.switchCurrentUser(userId, useCopyOnWriteSettings);
Yohei Yukawa095fa372014-10-27 14:02:23 +0900181 updateCurrentProfileIds();
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900182 unbindServiceLocked();
183 buildSpellCheckerMapLocked(mContext, mSpellCheckerList, mSpellCheckerMap, mSettings);
satokdf5659d2011-07-29 18:38:21 +0900184 SpellCheckerInfo sci = getCurrentSpellChecker(null);
185 if (sci == null) {
Yohei Yukawa174843a2015-06-26 18:02:54 -0700186 sci = findAvailSpellCheckerLocked(null);
satokdf5659d2011-07-29 18:38:21 +0900187 if (sci != null) {
188 // Set the current spell checker if there is one or more spell checkers
189 // available. In this case, "sci" is the first one in the available spell
190 // checkers.
satok5b9b5a92011-08-02 12:24:44 +0900191 setCurrentSpellCheckerLocked(sci.getId());
satokdf5659d2011-07-29 18:38:21 +0900192 }
193 }
satok988323c2011-06-22 16:38:13 +0900194 }
195
Yohei Yukawa095fa372014-10-27 14:02:23 +0900196 void updateCurrentProfileIds() {
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800197 final List<UserInfo> profiles = mUserManager.getProfiles(mSettings.getCurrentUserId());
Yohei Yukawa095fa372014-10-27 14:02:23 +0900198 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
199 for (int i = 0; i < currentProfileIds.length; i++) {
200 currentProfileIds[i] = profiles.get(i).id;
201 }
202 mSettings.setCurrentProfileIds(currentProfileIds);
203 }
204
satok988323c2011-06-22 16:38:13 +0900205 private class TextServicesMonitor extends PackageMonitor {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900206 private boolean isChangingPackagesOfCurrentUser() {
207 final int userId = getChangingUserId();
208 final boolean retval = userId == mSettings.getCurrentUserId();
209 if (DBG) {
210 Slog.d(TAG, "--- ignore this call back from a background user: " + userId);
211 }
212 return retval;
213 }
214
satok988323c2011-06-22 16:38:13 +0900215 @Override
216 public void onSomePackagesChanged() {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900217 if (!isChangingPackagesOfCurrentUser()) {
218 return;
219 }
satok988323c2011-06-22 16:38:13 +0900220 synchronized (mSpellCheckerMap) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900221 buildSpellCheckerMapLocked(
222 mContext, mSpellCheckerList, mSpellCheckerMap, mSettings);
satok988323c2011-06-22 16:38:13 +0900223 // TODO: Update for each locale
224 SpellCheckerInfo sci = getCurrentSpellChecker(null);
Satoshi Kataoka02260e22013-08-02 16:22:04 +0900225 // If no spell checker is enabled, just return. The user should explicitly
226 // enable the spell checker.
satokda317ef2011-07-26 08:02:45 +0900227 if (sci == null) return;
satok988323c2011-06-22 16:38:13 +0900228 final String packageName = sci.getPackageName();
229 final int change = isPackageDisappearing(packageName);
satok5b9b5a92011-08-02 12:24:44 +0900230 if (// Package disappearing
231 change == PACKAGE_PERMANENT_CHANGE || change == PACKAGE_TEMPORARY_CHANGE
232 // Package modified
233 || isPackageModified(packageName)) {
Yohei Yukawa174843a2015-06-26 18:02:54 -0700234 sci = findAvailSpellCheckerLocked(packageName);
satok5b9b5a92011-08-02 12:24:44 +0900235 if (sci != null) {
236 setCurrentSpellCheckerLocked(sci.getId());
237 }
satok988323c2011-06-22 16:38:13 +0900238 }
239 }
240 }
241 }
242
Yohei Yukawa095fa372014-10-27 14:02:23 +0900243 class TextServicesBroadcastReceiver extends BroadcastReceiver {
244 @Override
245 public void onReceive(Context context, Intent intent) {
246 final String action = intent.getAction();
247 if (Intent.ACTION_USER_ADDED.equals(action)
248 || Intent.ACTION_USER_REMOVED.equals(action)) {
249 updateCurrentProfileIds();
250 return;
251 }
252 Slog.w(TAG, "Unexpected intent " + intent);
253 }
254 }
255
satok988323c2011-06-22 16:38:13 +0900256 private static void buildSpellCheckerMapLocked(Context context,
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900257 ArrayList<SpellCheckerInfo> list, HashMap<String, SpellCheckerInfo> map,
258 TextServicesSettings settings) {
satok988323c2011-06-22 16:38:13 +0900259 list.clear();
260 map.clear();
261 final PackageManager pm = context.getPackageManager();
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800262 // Note: We do not specify PackageManager.MATCH_ENCRYPTION_* flags here because the default
263 // behavior of PackageManager is exactly what we want. It by default picks up appropriate
264 // services depending on the unlock state for the specified user.
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900265 final List<ResolveInfo> services = pm.queryIntentServicesAsUser(
266 new Intent(SpellCheckerService.SERVICE_INTERFACE), PackageManager.GET_META_DATA,
267 settings.getCurrentUserId());
satok988323c2011-06-22 16:38:13 +0900268 final int N = services.size();
269 for (int i = 0; i < N; ++i) {
270 final ResolveInfo ri = services.get(i);
271 final ServiceInfo si = ri.serviceInfo;
272 final ComponentName compName = new ComponentName(si.packageName, si.name);
273 if (!android.Manifest.permission.BIND_TEXT_SERVICE.equals(si.permission)) {
274 Slog.w(TAG, "Skipping text service " + compName
275 + ": it does not require the permission "
276 + android.Manifest.permission.BIND_TEXT_SERVICE);
277 continue;
278 }
279 if (DBG) Slog.d(TAG, "Add: " + compName);
satok03b2ea12011-08-03 17:36:14 +0900280 try {
281 final SpellCheckerInfo sci = new SpellCheckerInfo(context, ri);
satok3cb5b392011-08-26 11:55:21 +0900282 if (sci.getSubtypeCount() <= 0) {
283 Slog.w(TAG, "Skipping text service " + compName
284 + ": it does not contain subtypes.");
285 continue;
286 }
satok03b2ea12011-08-03 17:36:14 +0900287 list.add(sci);
288 map.put(sci.getId(), sci);
289 } catch (XmlPullParserException e) {
290 Slog.w(TAG, "Unable to load the spell checker " + compName, e);
291 } catch (IOException e) {
292 Slog.w(TAG, "Unable to load the spell checker " + compName, e);
293 }
satok988323c2011-06-22 16:38:13 +0900294 }
satokda317ef2011-07-26 08:02:45 +0900295 if (DBG) {
296 Slog.d(TAG, "buildSpellCheckerMapLocked: " + list.size() + "," + map.size());
297 }
satok988323c2011-06-22 16:38:13 +0900298 }
299
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900300 // ---------------------------------------------------------------------------------------
301 // Check whether or not this is a valid IPC. Assumes an IPC is valid when either
302 // 1) it comes from the system process
303 // 2) the calling process' user id is identical to the current user id TSMS thinks.
304 private boolean calledFromValidUser() {
305 final int uid = Binder.getCallingUid();
306 final int userId = UserHandle.getUserId(uid);
307 if (DBG) {
308 Slog.d(TAG, "--- calledFromForegroundUserOrSystemProcess ? "
309 + "calling uid = " + uid + " system uid = " + Process.SYSTEM_UID
310 + " calling userId = " + userId + ", foreground user id = "
Yohei Yukawa095fa372014-10-27 14:02:23 +0900311 + mSettings.getCurrentUserId() + ", calling pid = " + Binder.getCallingPid());
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900312 try {
313 final String[] packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
314 for (int i = 0; i < packageNames.length; ++i) {
315 if (DBG) {
316 Slog.d(TAG, "--- process name for "+ uid + " = " + packageNames[i]);
317 }
318 }
319 } catch (RemoteException e) {
320 }
321 }
322
323 if (uid == Process.SYSTEM_UID || userId == mSettings.getCurrentUserId()) {
324 return true;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900325 }
Yohei Yukawa095fa372014-10-27 14:02:23 +0900326
327 // Permits current profile to use TSFM as long as the current text service is the system's
328 // one. This is a tentative solution and should be replaced with fully functional multiuser
329 // support.
330 // TODO: Implement multiuser support in TSMS.
331 final boolean isCurrentProfile = mSettings.isCurrentProfile(userId);
332 if (DBG) {
333 Slog.d(TAG, "--- userId = "+ userId + " isCurrentProfile = " + isCurrentProfile);
334 }
335 if (mSettings.isCurrentProfile(userId)) {
336 final SpellCheckerInfo spellCheckerInfo = getCurrentSpellCheckerWithoutVerification();
337 if (spellCheckerInfo != null) {
338 final ServiceInfo serviceInfo = spellCheckerInfo.getServiceInfo();
339 final boolean isSystemSpellChecker =
340 (serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
341 if (DBG) {
342 Slog.d(TAG, "--- current spell checker = "+ spellCheckerInfo.getPackageName()
343 + " isSystem = " + isSystemSpellChecker);
344 }
345 if (isSystemSpellChecker) {
346 return true;
347 }
348 }
349 }
350
351 // Unlike InputMethodManagerService#calledFromValidUser, INTERACT_ACROSS_USERS_FULL isn't
352 // taken into account here. Anyway this method is supposed to be removed once multiuser
353 // support is implemented.
354 if (DBG) {
355 Slog.d(TAG, "--- IPC from userId:" + userId + " is being ignored. \n"
356 + getStackTrace());
357 }
358 return false;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900359 }
360
361 private boolean bindCurrentSpellCheckerService(
362 Intent service, ServiceConnection conn, int flags) {
363 if (service == null || conn == null) {
364 Slog.e(TAG, "--- bind failed: service = " + service + ", conn = " + conn);
365 return false;
366 }
Amith Yamasani27b89e62013-01-16 12:30:11 -0800367 return mContext.bindServiceAsUser(service, conn, flags,
368 new UserHandle(mSettings.getCurrentUserId()));
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900369 }
370
371 private void unbindServiceLocked() {
372 for (SpellCheckerBindGroup scbg : mSpellCheckerBindGroups.values()) {
373 scbg.removeAll();
374 }
375 mSpellCheckerBindGroups.clear();
376 }
377
Yohei Yukawa174843a2015-06-26 18:02:54 -0700378 private SpellCheckerInfo findAvailSpellCheckerLocked(String prefPackage) {
satok988323c2011-06-22 16:38:13 +0900379 final int spellCheckersCount = mSpellCheckerList.size();
380 if (spellCheckersCount == 0) {
381 Slog.w(TAG, "no available spell checker services found");
382 return null;
383 }
384 if (prefPackage != null) {
385 for (int i = 0; i < spellCheckersCount; ++i) {
386 final SpellCheckerInfo sci = mSpellCheckerList.get(i);
387 if (prefPackage.equals(sci.getPackageName())) {
satokda317ef2011-07-26 08:02:45 +0900388 if (DBG) {
389 Slog.d(TAG, "findAvailSpellCheckerLocked: " + sci.getPackageName());
390 }
satok988323c2011-06-22 16:38:13 +0900391 return sci;
392 }
393 }
394 }
Yohei Yukawa174843a2015-06-26 18:02:54 -0700395
396 // Look up a spell checker based on the system locale.
397 // TODO: Still there is a room to improve in the following logic: e.g., check if the package
398 // is pre-installed or not.
399 final Locale systemLocal = mContext.getResources().getConfiguration().locale;
400 final ArrayList<Locale> suitableLocales =
401 InputMethodUtils.getSuitableLocalesForSpellChecker(systemLocal);
402 if (DBG) {
403 Slog.w(TAG, "findAvailSpellCheckerLocked suitableLocales="
404 + Arrays.toString(suitableLocales.toArray(new Locale[suitableLocales.size()])));
405 }
406 final int localeCount = suitableLocales.size();
407 for (int localeIndex = 0; localeIndex < localeCount; ++localeIndex) {
408 final Locale locale = suitableLocales.get(localeIndex);
409 for (int spellCheckersIndex = 0; spellCheckersIndex < spellCheckersCount;
410 ++spellCheckersIndex) {
411 final SpellCheckerInfo info = mSpellCheckerList.get(spellCheckersIndex);
412 final int subtypeCount = info.getSubtypeCount();
413 for (int subtypeIndex = 0; subtypeIndex < subtypeCount; ++subtypeIndex) {
414 final SpellCheckerSubtype subtype = info.getSubtypeAt(subtypeIndex);
415 final Locale subtypeLocale = InputMethodUtils.constructLocaleFromString(
416 subtype.getLocale());
417 if (locale.equals(subtypeLocale)) {
418 // TODO: We may have more spell checkers that fall into this category.
419 // Ideally we should pick up the most suitable one instead of simply
420 // returning the first found one.
421 return info;
422 }
423 }
424 }
425 }
426
satok988323c2011-06-22 16:38:13 +0900427 if (spellCheckersCount > 1) {
428 Slog.w(TAG, "more than one spell checker service found, picking first");
429 }
430 return mSpellCheckerList.get(0);
431 }
432
433 // TODO: Save SpellCheckerService by supported languages. Currently only one spell
434 // checker is saved.
435 @Override
436 public SpellCheckerInfo getCurrentSpellChecker(String locale) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900437 // TODO: Make this work even for non-current users?
438 if (!calledFromValidUser()) {
439 return null;
440 }
Yohei Yukawa095fa372014-10-27 14:02:23 +0900441 return getCurrentSpellCheckerWithoutVerification();
442 }
443
444 private SpellCheckerInfo getCurrentSpellCheckerWithoutVerification() {
satok988323c2011-06-22 16:38:13 +0900445 synchronized (mSpellCheckerMap) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900446 final String curSpellCheckerId = mSettings.getSelectedSpellChecker();
satok562ab582011-07-25 10:12:21 +0900447 if (DBG) {
448 Slog.w(TAG, "getCurrentSpellChecker: " + curSpellCheckerId);
449 }
satok988323c2011-06-22 16:38:13 +0900450 if (TextUtils.isEmpty(curSpellCheckerId)) {
satokdf5659d2011-07-29 18:38:21 +0900451 return null;
satok988323c2011-06-22 16:38:13 +0900452 }
453 return mSpellCheckerMap.get(curSpellCheckerId);
454 }
455 }
456
satok3cb5b392011-08-26 11:55:21 +0900457 // TODO: Respect allowImplicitlySelectedSubtype
Satoshi Kataoka17150cf2012-05-30 20:05:44 +0900458 // TODO: Save SpellCheckerSubtype by supported languages by looking at "locale".
satokada8c4e2011-08-23 14:56:56 +0900459 @Override
satok3cb5b392011-08-26 11:55:21 +0900460 public SpellCheckerSubtype getCurrentSpellCheckerSubtype(
461 String locale, boolean allowImplicitlySelectedSubtype) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900462 // TODO: Make this work even for non-current users?
463 if (!calledFromValidUser()) {
464 return null;
465 }
satokada8c4e2011-08-23 14:56:56 +0900466 synchronized (mSpellCheckerMap) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900467 final String subtypeHashCodeStr = mSettings.getSelectedSpellCheckerSubtype();
satokada8c4e2011-08-23 14:56:56 +0900468 if (DBG) {
satokc7b60f722011-08-31 16:30:27 +0900469 Slog.w(TAG, "getCurrentSpellCheckerSubtype: " + subtypeHashCodeStr);
satokada8c4e2011-08-23 14:56:56 +0900470 }
471 final SpellCheckerInfo sci = getCurrentSpellChecker(null);
satoka33c4fc2011-08-25 16:50:11 +0900472 if (sci == null || sci.getSubtypeCount() == 0) {
473 if (DBG) {
474 Slog.w(TAG, "Subtype not found.");
475 }
satokada8c4e2011-08-23 14:56:56 +0900476 return null;
477 }
satokb3879542011-08-26 17:35:27 +0900478 final int hashCode;
479 if (!TextUtils.isEmpty(subtypeHashCodeStr)) {
480 hashCode = Integer.valueOf(subtypeHashCodeStr);
481 } else {
482 hashCode = 0;
483 }
484 if (hashCode == 0 && !allowImplicitlySelectedSubtype) {
satok3cb5b392011-08-26 11:55:21 +0900485 return null;
satokada8c4e2011-08-23 14:56:56 +0900486 }
satok05f24702011-11-02 19:29:35 +0900487 String candidateLocale = null;
488 if (hashCode == 0) {
489 // Spell checker language settings == "auto"
Yohei Yukawa777ef952015-11-25 20:32:24 -0800490 final InputMethodManager imm = mContext.getSystemService(InputMethodManager.class);
satok05f24702011-11-02 19:29:35 +0900491 if (imm != null) {
492 final InputMethodSubtype currentInputMethodSubtype =
493 imm.getCurrentInputMethodSubtype();
494 if (currentInputMethodSubtype != null) {
495 final String localeString = currentInputMethodSubtype.getLocale();
496 if (!TextUtils.isEmpty(localeString)) {
497 // 1. Use keyboard locale if available in the spell checker
498 candidateLocale = localeString;
499 }
500 }
501 }
502 if (candidateLocale == null) {
503 // 2. Use System locale if available in the spell checker
504 candidateLocale = mContext.getResources().getConfiguration().locale.toString();
505 }
506 }
satokb3879542011-08-26 17:35:27 +0900507 SpellCheckerSubtype candidate = null;
satokada8c4e2011-08-23 14:56:56 +0900508 for (int i = 0; i < sci.getSubtypeCount(); ++i) {
509 final SpellCheckerSubtype scs = sci.getSubtypeAt(i);
satokb3879542011-08-26 17:35:27 +0900510 if (hashCode == 0) {
Satoshi Kataoka17150cf2012-05-30 20:05:44 +0900511 final String scsLocale = scs.getLocale();
512 if (candidateLocale.equals(scsLocale)) {
satokb3879542011-08-26 17:35:27 +0900513 return scs;
514 } else if (candidate == null) {
satok7018a902012-05-24 18:10:37 +0900515 if (candidateLocale.length() >= 2 && scsLocale.length() >= 2
516 && candidateLocale.startsWith(scsLocale)) {
satok05f24702011-11-02 19:29:35 +0900517 // Fall back to the applicable language
satokb3879542011-08-26 17:35:27 +0900518 candidate = scs;
519 }
520 }
521 } else if (scs.hashCode() == hashCode) {
satoka33c4fc2011-08-25 16:50:11 +0900522 if (DBG) {
satok70deff42011-09-30 15:14:21 +0900523 Slog.w(TAG, "Return subtype " + scs.hashCode() + ", input= " + locale
524 + ", " + scs.getLocale());
satoka33c4fc2011-08-25 16:50:11 +0900525 }
satok05f24702011-11-02 19:29:35 +0900526 // 3. Use the user specified spell check language
satokada8c4e2011-08-23 14:56:56 +0900527 return scs;
528 }
529 }
satok05f24702011-11-02 19:29:35 +0900530 // 4. Fall back to the applicable language and return it if not null
531 // 5. Simply just return it even if it's null which means we could find no suitable
532 // spell check languages
satokb3879542011-08-26 17:35:27 +0900533 return candidate;
satokada8c4e2011-08-23 14:56:56 +0900534 }
535 }
536
satok988323c2011-06-22 16:38:13 +0900537 @Override
satok5b9b5a92011-08-02 12:24:44 +0900538 public void getSpellCheckerService(String sciId, String locale,
satok53578062011-08-03 16:08:59 +0900539 ITextServicesSessionListener tsListener, ISpellCheckerSessionListener scListener,
540 Bundle bundle) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900541 if (!calledFromValidUser()) {
542 return;
543 }
satok988323c2011-06-22 16:38:13 +0900544 if (!mSystemReady) {
545 return;
546 }
satok5b9b5a92011-08-02 12:24:44 +0900547 if (TextUtils.isEmpty(sciId) || tsListener == null || scListener == null) {
satok988323c2011-06-22 16:38:13 +0900548 Slog.e(TAG, "getSpellCheckerService: Invalid input.");
549 return;
550 }
satok988323c2011-06-22 16:38:13 +0900551 synchronized(mSpellCheckerMap) {
552 if (!mSpellCheckerMap.containsKey(sciId)) {
553 return;
554 }
satok5b9b5a92011-08-02 12:24:44 +0900555 final SpellCheckerInfo sci = mSpellCheckerMap.get(sciId);
satokdf5659d2011-07-29 18:38:21 +0900556 final int uid = Binder.getCallingUid();
satok988323c2011-06-22 16:38:13 +0900557 if (mSpellCheckerBindGroups.containsKey(sciId)) {
satok6be6d752011-07-28 20:40:38 +0900558 final SpellCheckerBindGroup bindGroup = mSpellCheckerBindGroups.get(sciId);
559 if (bindGroup != null) {
560 final InternalDeathRecipient recipient =
561 mSpellCheckerBindGroups.get(sciId).addListener(
satok53578062011-08-03 16:08:59 +0900562 tsListener, locale, scListener, uid, bundle);
satok6be6d752011-07-28 20:40:38 +0900563 if (recipient == null) {
564 if (DBG) {
565 Slog.w(TAG, "Didn't create a death recipient.");
566 }
567 return;
568 }
569 if (bindGroup.mSpellChecker == null & bindGroup.mConnected) {
570 Slog.e(TAG, "The state of the spell checker bind group is illegal.");
571 bindGroup.removeAll();
572 } else if (bindGroup.mSpellChecker != null) {
573 if (DBG) {
satokdf5659d2011-07-29 18:38:21 +0900574 Slog.w(TAG, "Existing bind found. Return a spell checker session now. "
575 + "Listeners count = " + bindGroup.mListeners.size());
satok6be6d752011-07-28 20:40:38 +0900576 }
577 try {
578 final ISpellCheckerSession session =
579 bindGroup.mSpellChecker.getISpellCheckerSession(
satok53578062011-08-03 16:08:59 +0900580 recipient.mScLocale, recipient.mScListener, bundle);
satokdf5659d2011-07-29 18:38:21 +0900581 if (session != null) {
582 tsListener.onServiceConnected(session);
583 return;
584 } else {
585 if (DBG) {
586 Slog.w(TAG, "Existing bind already expired. ");
587 }
588 bindGroup.removeAll();
589 }
satok6be6d752011-07-28 20:40:38 +0900590 } catch (RemoteException e) {
591 Slog.e(TAG, "Exception in getting spell checker session: " + e);
592 bindGroup.removeAll();
593 }
594 }
595 }
satok988323c2011-06-22 16:38:13 +0900596 }
satok6be6d752011-07-28 20:40:38 +0900597 final long ident = Binder.clearCallingIdentity();
598 try {
satok53578062011-08-03 16:08:59 +0900599 startSpellCheckerServiceInnerLocked(
600 sci, locale, tsListener, scListener, uid, bundle);
satok6be6d752011-07-28 20:40:38 +0900601 } finally {
602 Binder.restoreCallingIdentity(ident);
satok988323c2011-06-22 16:38:13 +0900603 }
satok988323c2011-06-22 16:38:13 +0900604 }
605 return;
606 }
607
satoka33c4fc2011-08-25 16:50:11 +0900608 @Override
609 public boolean isSpellCheckerEnabled() {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900610 if (!calledFromValidUser()) {
611 return false;
612 }
satoka33c4fc2011-08-25 16:50:11 +0900613 synchronized(mSpellCheckerMap) {
614 return isSpellCheckerEnabledLocked();
615 }
616 }
617
satok6be6d752011-07-28 20:40:38 +0900618 private void startSpellCheckerServiceInnerLocked(SpellCheckerInfo info, String locale,
satokdf5659d2011-07-29 18:38:21 +0900619 ITextServicesSessionListener tsListener, ISpellCheckerSessionListener scListener,
satok53578062011-08-03 16:08:59 +0900620 int uid, Bundle bundle) {
satokdf5659d2011-07-29 18:38:21 +0900621 if (DBG) {
622 Slog.w(TAG, "Start spell checker session inner locked.");
623 }
satok6be6d752011-07-28 20:40:38 +0900624 final String sciId = info.getId();
625 final InternalServiceConnection connection = new InternalServiceConnection(
satok060677f2011-11-17 09:40:56 +0900626 sciId, locale, bundle);
satok6be6d752011-07-28 20:40:38 +0900627 final Intent serviceIntent = new Intent(SpellCheckerService.SERVICE_INTERFACE);
628 serviceIntent.setComponent(info.getComponent());
629 if (DBG) {
630 Slog.w(TAG, "bind service: " + info.getId());
631 }
Dianne Hackbornd69e4c12015-04-24 09:54:54 -0700632 if (!bindCurrentSpellCheckerService(serviceIntent, connection,
633 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE_WHILE_AWAKE)) {
satok6be6d752011-07-28 20:40:38 +0900634 Slog.e(TAG, "Failed to get a spell checker service.");
635 return;
636 }
637 final SpellCheckerBindGroup group = new SpellCheckerBindGroup(
satok53578062011-08-03 16:08:59 +0900638 connection, tsListener, locale, scListener, uid, bundle);
satok6be6d752011-07-28 20:40:38 +0900639 mSpellCheckerBindGroups.put(sciId, group);
640 }
641
satok988323c2011-06-22 16:38:13 +0900642 @Override
satok562ab582011-07-25 10:12:21 +0900643 public SpellCheckerInfo[] getEnabledSpellCheckers() {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900644 // TODO: Make this work even for non-current users?
645 if (!calledFromValidUser()) {
646 return null;
647 }
satokda317ef2011-07-26 08:02:45 +0900648 if (DBG) {
649 Slog.d(TAG, "getEnabledSpellCheckers: " + mSpellCheckerList.size());
650 for (int i = 0; i < mSpellCheckerList.size(); ++i) {
651 Slog.d(TAG, "EnabledSpellCheckers: " + mSpellCheckerList.get(i).getPackageName());
652 }
653 }
satok562ab582011-07-25 10:12:21 +0900654 return mSpellCheckerList.toArray(new SpellCheckerInfo[mSpellCheckerList.size()]);
655 }
656
657 @Override
satok988323c2011-06-22 16:38:13 +0900658 public void finishSpellCheckerService(ISpellCheckerSessionListener listener) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900659 if (!calledFromValidUser()) {
660 return;
661 }
satokda317ef2011-07-26 08:02:45 +0900662 if (DBG) {
663 Slog.d(TAG, "FinishSpellCheckerService");
664 }
satok988323c2011-06-22 16:38:13 +0900665 synchronized(mSpellCheckerMap) {
Yohei Yukawa074637f2016-03-06 14:34:55 -0800666 final ArrayList<SpellCheckerBindGroup> removeList = new ArrayList<>();
satok988323c2011-06-22 16:38:13 +0900667 for (SpellCheckerBindGroup group : mSpellCheckerBindGroups.values()) {
668 if (group == null) continue;
satok4c3fa642011-11-30 18:17:59 +0900669 // Use removeList to avoid modifying mSpellCheckerBindGroups in this loop.
670 removeList.add(group);
671 }
672 final int removeSize = removeList.size();
673 for (int i = 0; i < removeSize; ++i) {
674 removeList.get(i).removeListener(listener);
satok988323c2011-06-22 16:38:13 +0900675 }
676 }
677 }
678
satokdf5659d2011-07-29 18:38:21 +0900679 @Override
satokada8c4e2011-08-23 14:56:56 +0900680 public void setCurrentSpellChecker(String locale, String sciId) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900681 if (!calledFromValidUser()) {
682 return;
683 }
satokdf5659d2011-07-29 18:38:21 +0900684 synchronized(mSpellCheckerMap) {
685 if (mContext.checkCallingOrSelfPermission(
686 android.Manifest.permission.WRITE_SECURE_SETTINGS)
687 != PackageManager.PERMISSION_GRANTED) {
688 throw new SecurityException(
689 "Requires permission "
690 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
691 }
satok5b9b5a92011-08-02 12:24:44 +0900692 setCurrentSpellCheckerLocked(sciId);
satokdf5659d2011-07-29 18:38:21 +0900693 }
694 }
695
satokada8c4e2011-08-23 14:56:56 +0900696 @Override
697 public void setCurrentSpellCheckerSubtype(String locale, int hashCode) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900698 if (!calledFromValidUser()) {
699 return;
700 }
satokada8c4e2011-08-23 14:56:56 +0900701 synchronized(mSpellCheckerMap) {
702 if (mContext.checkCallingOrSelfPermission(
703 android.Manifest.permission.WRITE_SECURE_SETTINGS)
704 != PackageManager.PERMISSION_GRANTED) {
705 throw new SecurityException(
706 "Requires permission "
707 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
708 }
satoka33c4fc2011-08-25 16:50:11 +0900709 setCurrentSpellCheckerSubtypeLocked(hashCode);
710 }
711 }
712
713 @Override
714 public void setSpellCheckerEnabled(boolean enabled) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900715 if (!calledFromValidUser()) {
716 return;
717 }
satoka33c4fc2011-08-25 16:50:11 +0900718 synchronized(mSpellCheckerMap) {
719 if (mContext.checkCallingOrSelfPermission(
720 android.Manifest.permission.WRITE_SECURE_SETTINGS)
721 != PackageManager.PERMISSION_GRANTED) {
722 throw new SecurityException(
723 "Requires permission "
724 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
725 }
726 setSpellCheckerEnabledLocked(enabled);
satokada8c4e2011-08-23 14:56:56 +0900727 }
728 }
729
satok5b9b5a92011-08-02 12:24:44 +0900730 private void setCurrentSpellCheckerLocked(String sciId) {
satok562ab582011-07-25 10:12:21 +0900731 if (DBG) {
satok5b9b5a92011-08-02 12:24:44 +0900732 Slog.w(TAG, "setCurrentSpellChecker: " + sciId);
satok562ab582011-07-25 10:12:21 +0900733 }
satok5b9b5a92011-08-02 12:24:44 +0900734 if (TextUtils.isEmpty(sciId) || !mSpellCheckerMap.containsKey(sciId)) return;
satokf39daef2011-08-26 19:54:27 +0900735 final SpellCheckerInfo currentSci = getCurrentSpellChecker(null);
736 if (currentSci != null && currentSci.getId().equals(sciId)) {
737 // Do nothing if the current spell checker is same as new spell checker.
738 return;
739 }
satokdf5659d2011-07-29 18:38:21 +0900740 final long ident = Binder.clearCallingIdentity();
741 try {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900742 mSettings.putSelectedSpellChecker(sciId);
satokf39daef2011-08-26 19:54:27 +0900743 setCurrentSpellCheckerSubtypeLocked(0);
satokada8c4e2011-08-23 14:56:56 +0900744 } finally {
745 Binder.restoreCallingIdentity(ident);
746 }
747 }
748
satoka33c4fc2011-08-25 16:50:11 +0900749 private void setCurrentSpellCheckerSubtypeLocked(int hashCode) {
satokada8c4e2011-08-23 14:56:56 +0900750 if (DBG) {
751 Slog.w(TAG, "setCurrentSpellCheckerSubtype: " + hashCode);
752 }
753 final SpellCheckerInfo sci = getCurrentSpellChecker(null);
satokfbedf1a2011-08-26 15:48:50 +0900754 int tempHashCode = 0;
755 for (int i = 0; sci != null && i < sci.getSubtypeCount(); ++i) {
satokada8c4e2011-08-23 14:56:56 +0900756 if(sci.getSubtypeAt(i).hashCode() == hashCode) {
satokfbedf1a2011-08-26 15:48:50 +0900757 tempHashCode = hashCode;
satokada8c4e2011-08-23 14:56:56 +0900758 break;
759 }
760 }
satokada8c4e2011-08-23 14:56:56 +0900761 final long ident = Binder.clearCallingIdentity();
762 try {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900763 mSettings.putSelectedSpellCheckerSubtype(tempHashCode);
satokdf5659d2011-07-29 18:38:21 +0900764 } finally {
765 Binder.restoreCallingIdentity(ident);
766 }
satok988323c2011-06-22 16:38:13 +0900767 }
768
satoka33c4fc2011-08-25 16:50:11 +0900769 private void setSpellCheckerEnabledLocked(boolean enabled) {
770 if (DBG) {
771 Slog.w(TAG, "setSpellCheckerEnabled: " + enabled);
772 }
773 final long ident = Binder.clearCallingIdentity();
774 try {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900775 mSettings.setSpellCheckerEnabled(enabled);
satoka33c4fc2011-08-25 16:50:11 +0900776 } finally {
777 Binder.restoreCallingIdentity(ident);
778 }
779 }
780
781 private boolean isSpellCheckerEnabledLocked() {
782 final long ident = Binder.clearCallingIdentity();
783 try {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900784 final boolean retval = mSettings.isSpellCheckerEnabled();
satoka33c4fc2011-08-25 16:50:11 +0900785 if (DBG) {
786 Slog.w(TAG, "getSpellCheckerEnabled: " + retval);
787 }
788 return retval;
789 } finally {
790 Binder.restoreCallingIdentity(ident);
791 }
792 }
793
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700794 @Override
795 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
796 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
797 != PackageManager.PERMISSION_GRANTED) {
798
799 pw.println("Permission Denial: can't dump TextServicesManagerService from from pid="
800 + Binder.getCallingPid()
801 + ", uid=" + Binder.getCallingUid());
802 return;
803 }
804
805 synchronized(mSpellCheckerMap) {
806 pw.println("Current Text Services Manager state:");
Yohei Yukawa85df6982016-03-08 15:16:07 -0800807 pw.println(" Spell Checkers:");
808 int spellCheckerIndex = 0;
809 for (final SpellCheckerInfo info : mSpellCheckerMap.values()) {
810 pw.println(" Spell Checker #" + spellCheckerIndex);
811 info.dump(pw, " ");
812 ++spellCheckerIndex;
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700813 }
814 pw.println("");
815 pw.println(" Spell Checker Bind Groups:");
Yohei Yukawa85df6982016-03-08 15:16:07 -0800816 for (final Map.Entry<String, SpellCheckerBindGroup> ent
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700817 : mSpellCheckerBindGroups.entrySet()) {
Yohei Yukawa85df6982016-03-08 15:16:07 -0800818 final SpellCheckerBindGroup grp = ent.getValue();
819 pw.println(" " + ent.getKey() + " " + grp + ":");
820 pw.println(" " + "mInternalConnection=" + grp.mInternalConnection);
821 pw.println(" " + "mSpellChecker=" + grp.mSpellChecker);
822 pw.println(" " + "mBound=" + grp.mBound + " mConnected=" + grp.mConnected);
823 final int N = grp.mListeners.size();
824 for (int i = 0; i < N; i++) {
825 final InternalDeathRecipient listener = grp.mListeners.get(i);
826 pw.println(" " + "Listener #" + i + ":");
827 pw.println(" " + "mTsListener=" + listener.mTsListener);
828 pw.println(" " + "mScListener=" + listener.mScListener);
829 pw.println(" " + "mGroup=" + listener.mGroup);
830 pw.println(" " + "mScLocale=" + listener.mScLocale
831 + " mUid=" + listener.mUid);
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700832 }
833 }
Yohei Yukawa85df6982016-03-08 15:16:07 -0800834 pw.println("");
835 pw.println(" mSettings:");
836 mSettings.dumpLocked(pw, " ");
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700837 }
838 }
839
satok988323c2011-06-22 16:38:13 +0900840 // SpellCheckerBindGroup contains active text service session listeners.
841 // If there are no listeners anymore, the SpellCheckerBindGroup instance will be removed from
842 // mSpellCheckerBindGroups
843 private class SpellCheckerBindGroup {
satokdf5659d2011-07-29 18:38:21 +0900844 private final String TAG = SpellCheckerBindGroup.class.getSimpleName();
satok6be6d752011-07-28 20:40:38 +0900845 private final InternalServiceConnection mInternalConnection;
satok4e713f12012-02-28 16:51:15 +0900846 private final CopyOnWriteArrayList<InternalDeathRecipient> mListeners =
Yohei Yukawa074637f2016-03-06 14:34:55 -0800847 new CopyOnWriteArrayList<>();
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700848 public boolean mBound;
satok6be6d752011-07-28 20:40:38 +0900849 public ISpellCheckerService mSpellChecker;
850 public boolean mConnected;
satok988323c2011-06-22 16:38:13 +0900851
852 public SpellCheckerBindGroup(InternalServiceConnection connection,
853 ITextServicesSessionListener listener, String locale,
satok53578062011-08-03 16:08:59 +0900854 ISpellCheckerSessionListener scListener, int uid, Bundle bundle) {
satok988323c2011-06-22 16:38:13 +0900855 mInternalConnection = connection;
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700856 mBound = true;
satok6be6d752011-07-28 20:40:38 +0900857 mConnected = false;
satok53578062011-08-03 16:08:59 +0900858 addListener(listener, locale, scListener, uid, bundle);
satok988323c2011-06-22 16:38:13 +0900859 }
860
861 public void onServiceConnected(ISpellCheckerService spellChecker) {
satokda317ef2011-07-26 08:02:45 +0900862 if (DBG) {
863 Slog.d(TAG, "onServiceConnected");
864 }
satok4e713f12012-02-28 16:51:15 +0900865
866 for (InternalDeathRecipient listener : mListeners) {
867 try {
868 final ISpellCheckerSession session = spellChecker.getISpellCheckerSession(
869 listener.mScLocale, listener.mScListener, listener.mBundle);
870 synchronized(mSpellCheckerMap) {
871 if (mListeners.contains(listener)) {
872 listener.mTsListener.onServiceConnected(session);
873 }
satok988323c2011-06-22 16:38:13 +0900874 }
satok4e713f12012-02-28 16:51:15 +0900875 } catch (RemoteException e) {
876 Slog.e(TAG, "Exception in getting the spell checker session."
877 + "Reconnect to the spellchecker. ", e);
878 removeAll();
879 return;
satok988323c2011-06-22 16:38:13 +0900880 }
satok4e713f12012-02-28 16:51:15 +0900881 }
882 synchronized(mSpellCheckerMap) {
satok6be6d752011-07-28 20:40:38 +0900883 mSpellChecker = spellChecker;
884 mConnected = true;
satok988323c2011-06-22 16:38:13 +0900885 }
886 }
887
satok6be6d752011-07-28 20:40:38 +0900888 public InternalDeathRecipient addListener(ITextServicesSessionListener tsListener,
satok53578062011-08-03 16:08:59 +0900889 String locale, ISpellCheckerSessionListener scListener, int uid, Bundle bundle) {
satokda317ef2011-07-26 08:02:45 +0900890 if (DBG) {
891 Slog.d(TAG, "addListener: " + locale);
892 }
satok6be6d752011-07-28 20:40:38 +0900893 InternalDeathRecipient recipient = null;
satok988323c2011-06-22 16:38:13 +0900894 synchronized(mSpellCheckerMap) {
895 try {
896 final int size = mListeners.size();
897 for (int i = 0; i < size; ++i) {
898 if (mListeners.get(i).hasSpellCheckerListener(scListener)) {
899 // do not add the lister if the group already contains this.
satok6be6d752011-07-28 20:40:38 +0900900 return null;
satok988323c2011-06-22 16:38:13 +0900901 }
902 }
satok6be6d752011-07-28 20:40:38 +0900903 recipient = new InternalDeathRecipient(
satok53578062011-08-03 16:08:59 +0900904 this, tsListener, locale, scListener, uid, bundle);
satok988323c2011-06-22 16:38:13 +0900905 scListener.asBinder().linkToDeath(recipient, 0);
satokdf5659d2011-07-29 18:38:21 +0900906 mListeners.add(recipient);
satok988323c2011-06-22 16:38:13 +0900907 } catch(RemoteException e) {
908 // do nothing
909 }
910 cleanLocked();
911 }
satok6be6d752011-07-28 20:40:38 +0900912 return recipient;
satok988323c2011-06-22 16:38:13 +0900913 }
914
915 public void removeListener(ISpellCheckerSessionListener listener) {
satokda317ef2011-07-26 08:02:45 +0900916 if (DBG) {
satokdf5659d2011-07-29 18:38:21 +0900917 Slog.w(TAG, "remove listener: " + listener.hashCode());
satokda317ef2011-07-26 08:02:45 +0900918 }
satok988323c2011-06-22 16:38:13 +0900919 synchronized(mSpellCheckerMap) {
920 final int size = mListeners.size();
Yohei Yukawa074637f2016-03-06 14:34:55 -0800921 final ArrayList<InternalDeathRecipient> removeList = new ArrayList<>();
satok988323c2011-06-22 16:38:13 +0900922 for (int i = 0; i < size; ++i) {
923 final InternalDeathRecipient tempRecipient = mListeners.get(i);
924 if(tempRecipient.hasSpellCheckerListener(listener)) {
satokdf5659d2011-07-29 18:38:21 +0900925 if (DBG) {
926 Slog.w(TAG, "found existing listener.");
927 }
satok988323c2011-06-22 16:38:13 +0900928 removeList.add(tempRecipient);
929 }
930 }
931 final int removeSize = removeList.size();
932 for (int i = 0; i < removeSize; ++i) {
satokdf5659d2011-07-29 18:38:21 +0900933 if (DBG) {
934 Slog.w(TAG, "Remove " + removeList.get(i));
935 }
satok2520ed82011-10-31 19:38:05 +0900936 final InternalDeathRecipient idr = removeList.get(i);
937 idr.mScListener.asBinder().unlinkToDeath(idr, 0);
938 mListeners.remove(idr);
satok988323c2011-06-22 16:38:13 +0900939 }
940 cleanLocked();
941 }
942 }
943
satok4c3fa642011-11-30 18:17:59 +0900944 // cleanLocked may remove elements from mSpellCheckerBindGroups
satok988323c2011-06-22 16:38:13 +0900945 private void cleanLocked() {
satokda317ef2011-07-26 08:02:45 +0900946 if (DBG) {
947 Slog.d(TAG, "cleanLocked");
948 }
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700949 // If there are no more active listeners, clean up. Only do this
950 // once.
951 if (mBound && mListeners.isEmpty()) {
952 mBound = false;
satokc7b60f722011-08-31 16:30:27 +0900953 final String sciId = mInternalConnection.mSciId;
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700954 SpellCheckerBindGroup cur = mSpellCheckerBindGroups.get(sciId);
955 if (cur == this) {
satokc7b60f722011-08-31 16:30:27 +0900956 if (DBG) {
957 Slog.d(TAG, "Remove bind group.");
958 }
959 mSpellCheckerBindGroups.remove(sciId);
satok6be6d752011-07-28 20:40:38 +0900960 }
satok988323c2011-06-22 16:38:13 +0900961 mContext.unbindService(mInternalConnection);
962 }
963 }
satok6be6d752011-07-28 20:40:38 +0900964
965 public void removeAll() {
966 Slog.e(TAG, "Remove the spell checker bind unexpectedly.");
satokdf5659d2011-07-29 18:38:21 +0900967 synchronized(mSpellCheckerMap) {
satok2520ed82011-10-31 19:38:05 +0900968 final int size = mListeners.size();
969 for (int i = 0; i < size; ++i) {
970 final InternalDeathRecipient idr = mListeners.get(i);
971 idr.mScListener.asBinder().unlinkToDeath(idr, 0);
972 }
satokdf5659d2011-07-29 18:38:21 +0900973 mListeners.clear();
974 cleanLocked();
975 }
satok6be6d752011-07-28 20:40:38 +0900976 }
satok988323c2011-06-22 16:38:13 +0900977 }
978
979 private class InternalServiceConnection implements ServiceConnection {
satok988323c2011-06-22 16:38:13 +0900980 private final String mSciId;
981 private final String mLocale;
satok53578062011-08-03 16:08:59 +0900982 private final Bundle mBundle;
satok988323c2011-06-22 16:38:13 +0900983 public InternalServiceConnection(
satok060677f2011-11-17 09:40:56 +0900984 String id, String locale, Bundle bundle) {
satok988323c2011-06-22 16:38:13 +0900985 mSciId = id;
986 mLocale = locale;
satok53578062011-08-03 16:08:59 +0900987 mBundle = bundle;
satok988323c2011-06-22 16:38:13 +0900988 }
989
990 @Override
991 public void onServiceConnected(ComponentName name, IBinder service) {
992 synchronized(mSpellCheckerMap) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900993 onServiceConnectedInnerLocked(name, service);
994 }
995 }
996
997 private void onServiceConnectedInnerLocked(ComponentName name, IBinder service) {
998 if (DBG) {
999 Slog.w(TAG, "onServiceConnected: " + name);
1000 }
1001 final ISpellCheckerService spellChecker =
1002 ISpellCheckerService.Stub.asInterface(service);
1003 final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId);
1004 if (group != null && this == group.mInternalConnection) {
1005 group.onServiceConnected(spellChecker);
satok988323c2011-06-22 16:38:13 +09001006 }
1007 }
1008
1009 @Override
1010 public void onServiceDisconnected(ComponentName name) {
Dianne Hackborn71e14da2011-10-16 16:28:10 -07001011 synchronized(mSpellCheckerMap) {
1012 final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId);
satok2cf1cf02011-10-21 15:25:23 +09001013 if (group != null && this == group.mInternalConnection) {
Dianne Hackborn71e14da2011-10-16 16:28:10 -07001014 mSpellCheckerBindGroups.remove(mSciId);
1015 }
1016 }
satok988323c2011-06-22 16:38:13 +09001017 }
1018 }
1019
1020 private class InternalDeathRecipient implements IBinder.DeathRecipient {
1021 public final ITextServicesSessionListener mTsListener;
1022 public final ISpellCheckerSessionListener mScListener;
1023 public final String mScLocale;
1024 private final SpellCheckerBindGroup mGroup;
satokdf5659d2011-07-29 18:38:21 +09001025 public final int mUid;
satok53578062011-08-03 16:08:59 +09001026 public final Bundle mBundle;
satok988323c2011-06-22 16:38:13 +09001027 public InternalDeathRecipient(SpellCheckerBindGroup group,
1028 ITextServicesSessionListener tsListener, String scLocale,
satok53578062011-08-03 16:08:59 +09001029 ISpellCheckerSessionListener scListener, int uid, Bundle bundle) {
satok988323c2011-06-22 16:38:13 +09001030 mTsListener = tsListener;
1031 mScListener = scListener;
1032 mScLocale = scLocale;
1033 mGroup = group;
satokdf5659d2011-07-29 18:38:21 +09001034 mUid = uid;
satok53578062011-08-03 16:08:59 +09001035 mBundle = bundle;
satok988323c2011-06-22 16:38:13 +09001036 }
1037
1038 public boolean hasSpellCheckerListener(ISpellCheckerSessionListener listener) {
satokdf5659d2011-07-29 18:38:21 +09001039 return listener.asBinder().equals(mScListener.asBinder());
satok988323c2011-06-22 16:38:13 +09001040 }
1041
1042 @Override
1043 public void binderDied() {
1044 mGroup.removeListener(mScListener);
1045 }
1046 }
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001047
1048 private static class TextServicesSettings {
1049 private final ContentResolver mResolver;
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -08001050 @UserIdInt
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001051 private int mCurrentUserId;
Yohei Yukawa095fa372014-10-27 14:02:23 +09001052 @GuardedBy("mLock")
1053 private int[] mCurrentProfileIds = new int[0];
1054 private Object mLock = new Object();
1055
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001056 /**
1057 * On-memory data store to emulate when {@link #mCopyOnWrite} is {@code true}.
1058 */
1059 private final HashMap<String, String> mCopyOnWriteDataStore = new HashMap<>();
1060 private boolean mCopyOnWrite = false;
1061
1062 public TextServicesSettings(ContentResolver resolver, @UserIdInt int userId,
1063 boolean copyOnWrite) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001064 mResolver = resolver;
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001065 switchCurrentUser(userId, copyOnWrite);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001066 }
1067
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001068 /**
1069 * Must be called when the current user is changed.
1070 *
1071 * @param userId The user ID.
1072 * @param copyOnWrite If {@code true}, for each settings key
1073 * (e.g. {@link Settings.Secure#SELECTED_SPELL_CHECKER}) we use the actual settings on the
1074 * {@link Settings.Secure} until we do the first write operation.
1075 */
1076 public void switchCurrentUser(@UserIdInt int userId, boolean copyOnWrite) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001077 if (DBG) {
1078 Slog.d(TAG, "--- Swtich the current user from " + mCurrentUserId + " to "
1079 + userId + ", new ime = " + getSelectedSpellChecker());
1080 }
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001081 if (mCurrentUserId != userId || mCopyOnWrite != copyOnWrite) {
1082 mCopyOnWriteDataStore.clear();
1083 // TODO: mCurrentProfileIds should be cleared here.
1084 }
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001085 // TSMS settings are kept per user, so keep track of current user
1086 mCurrentUserId = userId;
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001087 mCopyOnWrite = copyOnWrite;
1088 // TODO: mCurrentProfileIds should be updated here.
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001089 }
1090
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001091 private void putString(final String key, final String str) {
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001092 if (mCopyOnWrite) {
1093 mCopyOnWriteDataStore.put(key, str);
1094 } else {
1095 Settings.Secure.putStringForUser(mResolver, key, str, mCurrentUserId);
1096 }
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001097 }
1098
1099 private String getString(final String key) {
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001100 if (mCopyOnWrite && mCopyOnWriteDataStore.containsKey(key)) {
1101 final String result = mCopyOnWriteDataStore.get(key);
1102 return result != null ? result : "";
1103 }
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001104 return Settings.Secure.getStringForUser(mResolver, key, mCurrentUserId);
1105 }
1106
1107 private void putInt(final String key, final int value) {
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001108 if (mCopyOnWrite) {
1109 mCopyOnWriteDataStore.put(key, String.valueOf(value));
1110 } else {
1111 Settings.Secure.putIntForUser(mResolver, key, value, mCurrentUserId);
1112 }
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001113 }
1114
1115 private int getInt(final String key, final int defaultValue) {
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001116 if (mCopyOnWrite && mCopyOnWriteDataStore.containsKey(key)) {
1117 final String result = mCopyOnWriteDataStore.get(key);
1118 return result != null ? Integer.valueOf(result) : 0;
1119 }
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001120 return Settings.Secure.getIntForUser(mResolver, key, defaultValue, mCurrentUserId);
1121 }
1122
1123 private void putBoolean(final String key, final boolean value) {
1124 putInt(key, value ? 1 : 0);
1125 }
1126
1127 private boolean getBoolean(final String key, final boolean defaultValue) {
1128 return getInt(key, defaultValue ? 1 : 0) == 1;
1129 }
1130
Yohei Yukawa095fa372014-10-27 14:02:23 +09001131 public void setCurrentProfileIds(int[] currentProfileIds) {
1132 synchronized (mLock) {
1133 mCurrentProfileIds = currentProfileIds;
1134 }
1135 }
1136
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -08001137 public boolean isCurrentProfile(@UserIdInt int userId) {
Yohei Yukawa095fa372014-10-27 14:02:23 +09001138 synchronized (mLock) {
1139 if (userId == mCurrentUserId) return true;
1140 for (int i = 0; i < mCurrentProfileIds.length; i++) {
1141 if (userId == mCurrentProfileIds[i]) return true;
1142 }
1143 return false;
1144 }
1145 }
1146
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -08001147 @UserIdInt
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001148 public int getCurrentUserId() {
1149 return mCurrentUserId;
1150 }
1151
1152 public void putSelectedSpellChecker(String sciId) {
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001153 putString(Settings.Secure.SELECTED_SPELL_CHECKER, sciId);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001154 }
1155
1156 public void putSelectedSpellCheckerSubtype(int hashCode) {
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001157 putString(Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, String.valueOf(hashCode));
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001158 }
1159
1160 public void setSpellCheckerEnabled(boolean enabled) {
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001161 putBoolean(Settings.Secure.SPELL_CHECKER_ENABLED, enabled);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001162 }
1163
1164 public String getSelectedSpellChecker() {
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001165 return getString(Settings.Secure.SELECTED_SPELL_CHECKER);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001166 }
1167
1168 public String getSelectedSpellCheckerSubtype() {
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001169 return getString(Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001170 }
1171
1172 public boolean isSpellCheckerEnabled() {
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001173 return getBoolean(Settings.Secure.SPELL_CHECKER_ENABLED, true);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001174 }
Yohei Yukawa85df6982016-03-08 15:16:07 -08001175
1176 public void dumpLocked(final PrintWriter pw, final String prefix) {
1177 pw.println(prefix + "mCurrentUserId=" + mCurrentUserId);
1178 pw.println(prefix + "mCurrentProfileIds=" + Arrays.toString(mCurrentProfileIds));
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001179 pw.println(prefix + "mCopyOnWrite=" + mCopyOnWrite);
Yohei Yukawa85df6982016-03-08 15:16:07 -08001180 }
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001181 }
1182
1183 // ----------------------------------------------------------------------
1184 // Utilities for debug
1185 private static String getStackTrace() {
1186 final StringBuilder sb = new StringBuilder();
1187 try {
1188 throw new RuntimeException();
1189 } catch (RuntimeException e) {
1190 final StackTraceElement[] frames = e.getStackTrace();
1191 // Start at 1 because the first frame is here and we don't care about it
1192 for (int j = 1; j < frames.length; ++j) {
1193 sb.append(frames[j].toString() + "\n");
1194 }
1195 }
1196 return sb.toString();
1197 }
satok988323c2011-06-22 16:38:13 +09001198}