blob: cbd7be7343bb9ba9cf6159f49121c69eddbe7d69 [file] [log] [blame]
satok988323c2011-06-22 16:38:13 +09001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Yohei Yukawa095fa372014-10-27 14:02:23 +090019import com.android.internal.annotations.GuardedBy;
satok988323c2011-06-22 16:38:13 +090020import com.android.internal.content.PackageMonitor;
Yohei Yukawa174843a2015-06-26 18:02:54 -070021import com.android.internal.inputmethod.InputMethodUtils;
satok988323c2011-06-22 16:38:13 +090022import com.android.internal.textservice.ISpellCheckerService;
23import com.android.internal.textservice.ISpellCheckerSession;
24import com.android.internal.textservice.ISpellCheckerSessionListener;
25import com.android.internal.textservice.ITextServicesManager;
26import com.android.internal.textservice.ITextServicesSessionListener;
27
satok03b2ea12011-08-03 17:36:14 +090028import org.xmlpull.v1.XmlPullParserException;
29
Yohei Yukawaf0f16802016-03-08 16:04:58 -080030import android.annotation.NonNull;
Yohei Yukawa08ce1872016-03-16 17:22:30 -070031import android.annotation.Nullable;
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -080032import android.annotation.UserIdInt;
Sudheer Shankadc589ac2016-11-10 15:30:17 -080033import android.app.ActivityManager;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090034import android.app.AppGlobals;
Yohei Yukawa095fa372014-10-27 14:02:23 +090035import android.content.BroadcastReceiver;
satok988323c2011-06-22 16:38:13 +090036import android.content.ComponentName;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090037import android.content.ContentResolver;
satok988323c2011-06-22 16:38:13 +090038import android.content.Context;
39import android.content.Intent;
Yohei Yukawa095fa372014-10-27 14:02:23 +090040import android.content.IntentFilter;
satok988323c2011-06-22 16:38:13 +090041import android.content.ServiceConnection;
Yohei Yukawa095fa372014-10-27 14:02:23 +090042import android.content.pm.ApplicationInfo;
satok988323c2011-06-22 16:38:13 +090043import android.content.pm.PackageManager;
44import android.content.pm.ResolveInfo;
45import android.content.pm.ServiceInfo;
satok6be6d752011-07-28 20:40:38 +090046import android.os.Binder;
satok53578062011-08-03 16:08:59 +090047import android.os.Bundle;
satok988323c2011-06-22 16:38:13 +090048import android.os.IBinder;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090049import android.os.Process;
satok988323c2011-06-22 16:38:13 +090050import android.os.RemoteException;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090051import android.os.UserHandle;
Yohei Yukawa095fa372014-10-27 14:02:23 +090052import android.os.UserManager;
satok988323c2011-06-22 16:38:13 +090053import android.provider.Settings;
satok988323c2011-06-22 16:38:13 +090054import android.service.textservice.SpellCheckerService;
satok53578062011-08-03 16:08:59 +090055import android.text.TextUtils;
satok988323c2011-06-22 16:38:13 +090056import android.util.Slog;
satok05f24702011-11-02 19:29:35 +090057import android.view.inputmethod.InputMethodManager;
58import android.view.inputmethod.InputMethodSubtype;
satok988323c2011-06-22 16:38:13 +090059import android.view.textservice.SpellCheckerInfo;
satokada8c4e2011-08-23 14:56:56 +090060import android.view.textservice.SpellCheckerSubtype;
satok988323c2011-06-22 16:38:13 +090061
Dianne Hackborn71e14da2011-10-16 16:28:10 -070062import java.io.FileDescriptor;
satok03b2ea12011-08-03 17:36:14 +090063import java.io.IOException;
Dianne Hackborn71e14da2011-10-16 16:28:10 -070064import java.io.PrintWriter;
Yohei Yukawa174843a2015-06-26 18:02:54 -070065import java.util.Arrays;
satok988323c2011-06-22 16:38:13 +090066import java.util.ArrayList;
67import java.util.HashMap;
satok988323c2011-06-22 16:38:13 +090068import java.util.List;
Yohei Yukawa174843a2015-06-26 18:02:54 -070069import java.util.Locale;
Dianne Hackborn71e14da2011-10-16 16:28:10 -070070import java.util.Map;
satok4e713f12012-02-28 16:51:15 +090071import java.util.concurrent.CopyOnWriteArrayList;
satok988323c2011-06-22 16:38:13 +090072
73public class TextServicesManagerService extends ITextServicesManager.Stub {
74 private static final String TAG = TextServicesManagerService.class.getSimpleName();
75 private static final boolean DBG = false;
76
77 private final Context mContext;
78 private boolean mSystemReady;
79 private final TextServicesMonitor mMonitor;
Yohei Yukawa074637f2016-03-06 14:34:55 -080080 private final HashMap<String, SpellCheckerInfo> mSpellCheckerMap = new HashMap<>();
81 private final ArrayList<SpellCheckerInfo> mSpellCheckerList = new ArrayList<>();
82 private final HashMap<String, SpellCheckerBindGroup> mSpellCheckerBindGroups = new HashMap<>();
Satoshi Kataoka00d2d412012-09-28 20:32:33 +090083 private final TextServicesSettings mSettings;
Yohei Yukawaf0f16802016-03-08 16:04:58 -080084 @NonNull
85 private final UserManager mUserManager;
satok988323c2011-06-22 16:38:13 +090086
Yohei Yukawaa6a152e2016-03-07 13:41:15 -080087 public static final class Lifecycle extends SystemService {
88 private TextServicesManagerService mService;
89
90 public Lifecycle(Context context) {
91 super(context);
92 mService = new TextServicesManagerService(context);
93 }
94
95 @Override
96 public void onStart() {
97 publishBinderService(Context.TEXT_SERVICES_MANAGER_SERVICE, mService);
98 }
99
100 @Override
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -0800101 public void onSwitchUser(@UserIdInt int userHandle) {
102 // Called on the system server's main looper thread.
103 // TODO: Dispatch this to a worker thread as needed.
104 mService.onSwitchUser(userHandle);
105 }
106
107 @Override
Yohei Yukawaa6a152e2016-03-07 13:41:15 -0800108 public void onBootPhase(int phase) {
109 // Called on the system server's main looper thread.
110 // TODO: Dispatch this to a worker thread as needed.
111 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
112 mService.systemRunning();
113 }
114 }
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800115
116 @Override
117 public void onUnlockUser(@UserIdInt int userHandle) {
118 // Called on the system server's main looper thread.
119 // TODO: Dispatch this to a worker thread as needed.
120 mService.onUnlockUser(userHandle);
121 }
Yohei Yukawaa6a152e2016-03-07 13:41:15 -0800122 }
123
124 void systemRunning() {
125 synchronized (mSpellCheckerMap) {
126 if (!mSystemReady) {
127 mSystemReady = true;
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800128 resetInternalState(mSettings.getCurrentUserId());
Yohei Yukawaa6a152e2016-03-07 13:41:15 -0800129 }
satok988323c2011-06-22 16:38:13 +0900130 }
131 }
132
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -0800133 void onSwitchUser(@UserIdInt int userId) {
134 synchronized (mSpellCheckerMap) {
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800135 resetInternalState(userId);
136 }
137 }
138
139 void onUnlockUser(@UserIdInt int userId) {
140 synchronized(mSpellCheckerMap) {
141 final int currentUserId = mSettings.getCurrentUserId();
142 if (userId != currentUserId) {
143 return;
144 }
145 resetInternalState(currentUserId);
satok988323c2011-06-22 16:38:13 +0900146 }
147 }
148
149 public TextServicesManagerService(Context context) {
150 mSystemReady = false;
151 mContext = context;
Yohei Yukawa095fa372014-10-27 14:02:23 +0900152
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800153 mUserManager = mContext.getSystemService(UserManager.class);
154
Yohei Yukawa095fa372014-10-27 14:02:23 +0900155 final IntentFilter broadcastFilter = new IntentFilter();
156 broadcastFilter.addAction(Intent.ACTION_USER_ADDED);
157 broadcastFilter.addAction(Intent.ACTION_USER_REMOVED);
158 mContext.registerReceiver(new TextServicesBroadcastReceiver(), broadcastFilter);
159
Xiaohui Chen7c696362015-09-16 09:56:14 -0700160 int userId = UserHandle.USER_SYSTEM;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900161 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800162 userId = ActivityManager.getService().getCurrentUser().id;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900163 } catch (RemoteException e) {
164 Slog.w(TAG, "Couldn't get current user ID; guessing it's 0", e);
165 }
satok988323c2011-06-22 16:38:13 +0900166 mMonitor = new TextServicesMonitor();
Dianne Hackbornd0d75032012-04-19 23:12:09 -0700167 mMonitor.register(context, null, true);
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800168 final boolean useCopyOnWriteSettings =
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600169 !mSystemReady || !mUserManager.isUserUnlockingOrUnlocked(userId);
Yohei Yukawa49ed1402016-03-07 19:12:54 -0800170 mSettings = new TextServicesSettings(context.getContentResolver(), userId,
171 useCopyOnWriteSettings);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900172
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800173 // "resetInternalState" initializes the states for the foreground user
174 resetInternalState(userId);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900175 }
176
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800177 private void resetInternalState(@UserIdInt int userId) {
178 final boolean useCopyOnWriteSettings =
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600179 !mSystemReady || !mUserManager.isUserUnlockingOrUnlocked(userId);
Yohei Yukawa49ed1402016-03-07 19:12:54 -0800180 mSettings.switchCurrentUser(userId, useCopyOnWriteSettings);
Yohei Yukawa095fa372014-10-27 14:02:23 +0900181 updateCurrentProfileIds();
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900182 unbindServiceLocked();
183 buildSpellCheckerMapLocked(mContext, mSpellCheckerList, mSpellCheckerMap, mSettings);
satokdf5659d2011-07-29 18:38:21 +0900184 SpellCheckerInfo sci = getCurrentSpellChecker(null);
185 if (sci == null) {
Yohei Yukawa174843a2015-06-26 18:02:54 -0700186 sci = findAvailSpellCheckerLocked(null);
satokdf5659d2011-07-29 18:38:21 +0900187 if (sci != null) {
188 // Set the current spell checker if there is one or more spell checkers
189 // available. In this case, "sci" is the first one in the available spell
190 // checkers.
satok5b9b5a92011-08-02 12:24:44 +0900191 setCurrentSpellCheckerLocked(sci.getId());
satokdf5659d2011-07-29 18:38:21 +0900192 }
193 }
satok988323c2011-06-22 16:38:13 +0900194 }
195
Yohei Yukawa095fa372014-10-27 14:02:23 +0900196 void updateCurrentProfileIds() {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700197 mSettings.setCurrentProfileIds(
198 mUserManager.getProfileIdsWithDisabled(mSettings.getCurrentUserId()));
Yohei Yukawa095fa372014-10-27 14:02:23 +0900199 }
200
satok988323c2011-06-22 16:38:13 +0900201 private class TextServicesMonitor extends PackageMonitor {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900202 private boolean isChangingPackagesOfCurrentUser() {
203 final int userId = getChangingUserId();
204 final boolean retval = userId == mSettings.getCurrentUserId();
205 if (DBG) {
206 Slog.d(TAG, "--- ignore this call back from a background user: " + userId);
207 }
208 return retval;
209 }
210
satok988323c2011-06-22 16:38:13 +0900211 @Override
212 public void onSomePackagesChanged() {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900213 if (!isChangingPackagesOfCurrentUser()) {
214 return;
215 }
satok988323c2011-06-22 16:38:13 +0900216 synchronized (mSpellCheckerMap) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900217 buildSpellCheckerMapLocked(
218 mContext, mSpellCheckerList, mSpellCheckerMap, mSettings);
satok988323c2011-06-22 16:38:13 +0900219 // TODO: Update for each locale
220 SpellCheckerInfo sci = getCurrentSpellChecker(null);
Satoshi Kataoka02260e22013-08-02 16:22:04 +0900221 // If no spell checker is enabled, just return. The user should explicitly
222 // enable the spell checker.
satokda317ef2011-07-26 08:02:45 +0900223 if (sci == null) return;
satok988323c2011-06-22 16:38:13 +0900224 final String packageName = sci.getPackageName();
225 final int change = isPackageDisappearing(packageName);
satok5b9b5a92011-08-02 12:24:44 +0900226 if (// Package disappearing
227 change == PACKAGE_PERMANENT_CHANGE || change == PACKAGE_TEMPORARY_CHANGE
228 // Package modified
229 || isPackageModified(packageName)) {
Yohei Yukawa174843a2015-06-26 18:02:54 -0700230 sci = findAvailSpellCheckerLocked(packageName);
satok5b9b5a92011-08-02 12:24:44 +0900231 if (sci != null) {
232 setCurrentSpellCheckerLocked(sci.getId());
233 }
satok988323c2011-06-22 16:38:13 +0900234 }
235 }
236 }
237 }
238
Yohei Yukawa095fa372014-10-27 14:02:23 +0900239 class TextServicesBroadcastReceiver extends BroadcastReceiver {
240 @Override
241 public void onReceive(Context context, Intent intent) {
242 final String action = intent.getAction();
243 if (Intent.ACTION_USER_ADDED.equals(action)
244 || Intent.ACTION_USER_REMOVED.equals(action)) {
245 updateCurrentProfileIds();
246 return;
247 }
248 Slog.w(TAG, "Unexpected intent " + intent);
249 }
250 }
251
satok988323c2011-06-22 16:38:13 +0900252 private static void buildSpellCheckerMapLocked(Context context,
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900253 ArrayList<SpellCheckerInfo> list, HashMap<String, SpellCheckerInfo> map,
254 TextServicesSettings settings) {
satok988323c2011-06-22 16:38:13 +0900255 list.clear();
256 map.clear();
257 final PackageManager pm = context.getPackageManager();
Yohei Yukawaf0f16802016-03-08 16:04:58 -0800258 // Note: We do not specify PackageManager.MATCH_ENCRYPTION_* flags here because the default
259 // behavior of PackageManager is exactly what we want. It by default picks up appropriate
260 // services depending on the unlock state for the specified user.
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900261 final List<ResolveInfo> services = pm.queryIntentServicesAsUser(
262 new Intent(SpellCheckerService.SERVICE_INTERFACE), PackageManager.GET_META_DATA,
263 settings.getCurrentUserId());
satok988323c2011-06-22 16:38:13 +0900264 final int N = services.size();
265 for (int i = 0; i < N; ++i) {
266 final ResolveInfo ri = services.get(i);
267 final ServiceInfo si = ri.serviceInfo;
268 final ComponentName compName = new ComponentName(si.packageName, si.name);
269 if (!android.Manifest.permission.BIND_TEXT_SERVICE.equals(si.permission)) {
270 Slog.w(TAG, "Skipping text service " + compName
271 + ": it does not require the permission "
272 + android.Manifest.permission.BIND_TEXT_SERVICE);
273 continue;
274 }
275 if (DBG) Slog.d(TAG, "Add: " + compName);
satok03b2ea12011-08-03 17:36:14 +0900276 try {
277 final SpellCheckerInfo sci = new SpellCheckerInfo(context, ri);
satok3cb5b392011-08-26 11:55:21 +0900278 if (sci.getSubtypeCount() <= 0) {
279 Slog.w(TAG, "Skipping text service " + compName
280 + ": it does not contain subtypes.");
281 continue;
282 }
satok03b2ea12011-08-03 17:36:14 +0900283 list.add(sci);
284 map.put(sci.getId(), sci);
285 } catch (XmlPullParserException e) {
286 Slog.w(TAG, "Unable to load the spell checker " + compName, e);
287 } catch (IOException e) {
288 Slog.w(TAG, "Unable to load the spell checker " + compName, e);
289 }
satok988323c2011-06-22 16:38:13 +0900290 }
satokda317ef2011-07-26 08:02:45 +0900291 if (DBG) {
292 Slog.d(TAG, "buildSpellCheckerMapLocked: " + list.size() + "," + map.size());
293 }
satok988323c2011-06-22 16:38:13 +0900294 }
295
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900296 // ---------------------------------------------------------------------------------------
297 // Check whether or not this is a valid IPC. Assumes an IPC is valid when either
298 // 1) it comes from the system process
299 // 2) the calling process' user id is identical to the current user id TSMS thinks.
300 private boolean calledFromValidUser() {
301 final int uid = Binder.getCallingUid();
302 final int userId = UserHandle.getUserId(uid);
303 if (DBG) {
304 Slog.d(TAG, "--- calledFromForegroundUserOrSystemProcess ? "
305 + "calling uid = " + uid + " system uid = " + Process.SYSTEM_UID
306 + " calling userId = " + userId + ", foreground user id = "
Yohei Yukawa095fa372014-10-27 14:02:23 +0900307 + mSettings.getCurrentUserId() + ", calling pid = " + Binder.getCallingPid());
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900308 try {
309 final String[] packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
310 for (int i = 0; i < packageNames.length; ++i) {
311 if (DBG) {
312 Slog.d(TAG, "--- process name for "+ uid + " = " + packageNames[i]);
313 }
314 }
315 } catch (RemoteException e) {
316 }
317 }
318
319 if (uid == Process.SYSTEM_UID || userId == mSettings.getCurrentUserId()) {
320 return true;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900321 }
Yohei Yukawa095fa372014-10-27 14:02:23 +0900322
323 // Permits current profile to use TSFM as long as the current text service is the system's
324 // one. This is a tentative solution and should be replaced with fully functional multiuser
325 // support.
326 // TODO: Implement multiuser support in TSMS.
327 final boolean isCurrentProfile = mSettings.isCurrentProfile(userId);
328 if (DBG) {
329 Slog.d(TAG, "--- userId = "+ userId + " isCurrentProfile = " + isCurrentProfile);
330 }
331 if (mSettings.isCurrentProfile(userId)) {
332 final SpellCheckerInfo spellCheckerInfo = getCurrentSpellCheckerWithoutVerification();
333 if (spellCheckerInfo != null) {
334 final ServiceInfo serviceInfo = spellCheckerInfo.getServiceInfo();
335 final boolean isSystemSpellChecker =
336 (serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
337 if (DBG) {
338 Slog.d(TAG, "--- current spell checker = "+ spellCheckerInfo.getPackageName()
339 + " isSystem = " + isSystemSpellChecker);
340 }
341 if (isSystemSpellChecker) {
342 return true;
343 }
344 }
345 }
346
347 // Unlike InputMethodManagerService#calledFromValidUser, INTERACT_ACROSS_USERS_FULL isn't
348 // taken into account here. Anyway this method is supposed to be removed once multiuser
349 // support is implemented.
350 if (DBG) {
351 Slog.d(TAG, "--- IPC from userId:" + userId + " is being ignored. \n"
352 + getStackTrace());
353 }
354 return false;
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900355 }
356
357 private boolean bindCurrentSpellCheckerService(
358 Intent service, ServiceConnection conn, int flags) {
359 if (service == null || conn == null) {
360 Slog.e(TAG, "--- bind failed: service = " + service + ", conn = " + conn);
361 return false;
362 }
Amith Yamasani27b89e62013-01-16 12:30:11 -0800363 return mContext.bindServiceAsUser(service, conn, flags,
364 new UserHandle(mSettings.getCurrentUserId()));
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900365 }
366
367 private void unbindServiceLocked() {
368 for (SpellCheckerBindGroup scbg : mSpellCheckerBindGroups.values()) {
369 scbg.removeAll();
370 }
371 mSpellCheckerBindGroups.clear();
372 }
373
Yohei Yukawa174843a2015-06-26 18:02:54 -0700374 private SpellCheckerInfo findAvailSpellCheckerLocked(String prefPackage) {
satok988323c2011-06-22 16:38:13 +0900375 final int spellCheckersCount = mSpellCheckerList.size();
376 if (spellCheckersCount == 0) {
377 Slog.w(TAG, "no available spell checker services found");
378 return null;
379 }
380 if (prefPackage != null) {
381 for (int i = 0; i < spellCheckersCount; ++i) {
382 final SpellCheckerInfo sci = mSpellCheckerList.get(i);
383 if (prefPackage.equals(sci.getPackageName())) {
satokda317ef2011-07-26 08:02:45 +0900384 if (DBG) {
385 Slog.d(TAG, "findAvailSpellCheckerLocked: " + sci.getPackageName());
386 }
satok988323c2011-06-22 16:38:13 +0900387 return sci;
388 }
389 }
390 }
Yohei Yukawa174843a2015-06-26 18:02:54 -0700391
392 // Look up a spell checker based on the system locale.
393 // TODO: Still there is a room to improve in the following logic: e.g., check if the package
394 // is pre-installed or not.
395 final Locale systemLocal = mContext.getResources().getConfiguration().locale;
396 final ArrayList<Locale> suitableLocales =
397 InputMethodUtils.getSuitableLocalesForSpellChecker(systemLocal);
398 if (DBG) {
399 Slog.w(TAG, "findAvailSpellCheckerLocked suitableLocales="
400 + Arrays.toString(suitableLocales.toArray(new Locale[suitableLocales.size()])));
401 }
402 final int localeCount = suitableLocales.size();
403 for (int localeIndex = 0; localeIndex < localeCount; ++localeIndex) {
404 final Locale locale = suitableLocales.get(localeIndex);
405 for (int spellCheckersIndex = 0; spellCheckersIndex < spellCheckersCount;
406 ++spellCheckersIndex) {
407 final SpellCheckerInfo info = mSpellCheckerList.get(spellCheckersIndex);
408 final int subtypeCount = info.getSubtypeCount();
409 for (int subtypeIndex = 0; subtypeIndex < subtypeCount; ++subtypeIndex) {
410 final SpellCheckerSubtype subtype = info.getSubtypeAt(subtypeIndex);
411 final Locale subtypeLocale = InputMethodUtils.constructLocaleFromString(
412 subtype.getLocale());
413 if (locale.equals(subtypeLocale)) {
414 // TODO: We may have more spell checkers that fall into this category.
415 // Ideally we should pick up the most suitable one instead of simply
416 // returning the first found one.
417 return info;
418 }
419 }
420 }
421 }
422
satok988323c2011-06-22 16:38:13 +0900423 if (spellCheckersCount > 1) {
424 Slog.w(TAG, "more than one spell checker service found, picking first");
425 }
426 return mSpellCheckerList.get(0);
427 }
428
429 // TODO: Save SpellCheckerService by supported languages. Currently only one spell
430 // checker is saved.
431 @Override
432 public SpellCheckerInfo getCurrentSpellChecker(String locale) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900433 // TODO: Make this work even for non-current users?
434 if (!calledFromValidUser()) {
435 return null;
436 }
Yohei Yukawa095fa372014-10-27 14:02:23 +0900437 return getCurrentSpellCheckerWithoutVerification();
438 }
439
440 private SpellCheckerInfo getCurrentSpellCheckerWithoutVerification() {
satok988323c2011-06-22 16:38:13 +0900441 synchronized (mSpellCheckerMap) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900442 final String curSpellCheckerId = mSettings.getSelectedSpellChecker();
satok562ab582011-07-25 10:12:21 +0900443 if (DBG) {
444 Slog.w(TAG, "getCurrentSpellChecker: " + curSpellCheckerId);
445 }
satok988323c2011-06-22 16:38:13 +0900446 if (TextUtils.isEmpty(curSpellCheckerId)) {
satokdf5659d2011-07-29 18:38:21 +0900447 return null;
satok988323c2011-06-22 16:38:13 +0900448 }
449 return mSpellCheckerMap.get(curSpellCheckerId);
450 }
451 }
452
satok3cb5b392011-08-26 11:55:21 +0900453 // TODO: Respect allowImplicitlySelectedSubtype
Satoshi Kataoka17150cf2012-05-30 20:05:44 +0900454 // TODO: Save SpellCheckerSubtype by supported languages by looking at "locale".
satokada8c4e2011-08-23 14:56:56 +0900455 @Override
satok3cb5b392011-08-26 11:55:21 +0900456 public SpellCheckerSubtype getCurrentSpellCheckerSubtype(
457 String locale, boolean allowImplicitlySelectedSubtype) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900458 // TODO: Make this work even for non-current users?
459 if (!calledFromValidUser()) {
460 return null;
461 }
Yohei Yukawae3e31a82016-09-20 06:43:03 -0700462 final int subtypeHashCode;
463 final SpellCheckerInfo sci;
464 final Locale systemLocale;
satokada8c4e2011-08-23 14:56:56 +0900465 synchronized (mSpellCheckerMap) {
Yohei Yukawae3e31a82016-09-20 06:43:03 -0700466 subtypeHashCode =
Yohei Yukawaad150ee2016-03-16 17:22:27 -0700467 mSettings.getSelectedSpellCheckerSubtype(SpellCheckerSubtype.SUBTYPE_ID_NONE);
satokada8c4e2011-08-23 14:56:56 +0900468 if (DBG) {
Yohei Yukawaad150ee2016-03-16 17:22:27 -0700469 Slog.w(TAG, "getCurrentSpellCheckerSubtype: " + subtypeHashCode);
satokada8c4e2011-08-23 14:56:56 +0900470 }
Yohei Yukawae3e31a82016-09-20 06:43:03 -0700471 sci = getCurrentSpellChecker(null);
472 systemLocale = mContext.getResources().getConfiguration().locale;
satokada8c4e2011-08-23 14:56:56 +0900473 }
Yohei Yukawae3e31a82016-09-20 06:43:03 -0700474 if (sci == null || sci.getSubtypeCount() == 0) {
475 if (DBG) {
476 Slog.w(TAG, "Subtype not found.");
477 }
478 return null;
479 }
480 if (subtypeHashCode == SpellCheckerSubtype.SUBTYPE_ID_NONE
481 && !allowImplicitlySelectedSubtype) {
482 return null;
483 }
484 String candidateLocale = null;
485 if (subtypeHashCode == 0) {
486 // Spell checker language settings == "auto"
487 final InputMethodManager imm = mContext.getSystemService(InputMethodManager.class);
488 if (imm != null) {
489 final InputMethodSubtype currentInputMethodSubtype =
490 imm.getCurrentInputMethodSubtype();
491 if (currentInputMethodSubtype != null) {
492 final String localeString = currentInputMethodSubtype.getLocale();
493 if (!TextUtils.isEmpty(localeString)) {
494 // 1. Use keyboard locale if available in the spell checker
495 candidateLocale = localeString;
496 }
497 }
498 }
499 if (candidateLocale == null) {
500 // 2. Use System locale if available in the spell checker
501 candidateLocale = systemLocale.toString();
502 }
503 }
504 SpellCheckerSubtype candidate = null;
505 for (int i = 0; i < sci.getSubtypeCount(); ++i) {
506 final SpellCheckerSubtype scs = sci.getSubtypeAt(i);
507 if (subtypeHashCode == 0) {
508 final String scsLocale = scs.getLocale();
509 if (candidateLocale.equals(scsLocale)) {
510 return scs;
511 } else if (candidate == null) {
512 if (candidateLocale.length() >= 2 && scsLocale.length() >= 2
513 && candidateLocale.startsWith(scsLocale)) {
514 // Fall back to the applicable language
515 candidate = scs;
516 }
517 }
518 } else if (scs.hashCode() == subtypeHashCode) {
519 if (DBG) {
520 Slog.w(TAG, "Return subtype " + scs.hashCode() + ", input= " + locale
521 + ", " + scs.getLocale());
522 }
523 // 3. Use the user specified spell check language
524 return scs;
525 }
526 }
527 // 4. Fall back to the applicable language and return it if not null
528 // 5. Simply just return it even if it's null which means we could find no suitable
529 // spell check languages
530 return candidate;
satokada8c4e2011-08-23 14:56:56 +0900531 }
532
satok988323c2011-06-22 16:38:13 +0900533 @Override
satok5b9b5a92011-08-02 12:24:44 +0900534 public void getSpellCheckerService(String sciId, String locale,
satok53578062011-08-03 16:08:59 +0900535 ITextServicesSessionListener tsListener, ISpellCheckerSessionListener scListener,
536 Bundle bundle) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900537 if (!calledFromValidUser()) {
538 return;
539 }
satok988323c2011-06-22 16:38:13 +0900540 if (!mSystemReady) {
541 return;
542 }
satok5b9b5a92011-08-02 12:24:44 +0900543 if (TextUtils.isEmpty(sciId) || tsListener == null || scListener == null) {
satok988323c2011-06-22 16:38:13 +0900544 Slog.e(TAG, "getSpellCheckerService: Invalid input.");
545 return;
546 }
satok988323c2011-06-22 16:38:13 +0900547 synchronized(mSpellCheckerMap) {
548 if (!mSpellCheckerMap.containsKey(sciId)) {
549 return;
550 }
satok5b9b5a92011-08-02 12:24:44 +0900551 final SpellCheckerInfo sci = mSpellCheckerMap.get(sciId);
satokdf5659d2011-07-29 18:38:21 +0900552 final int uid = Binder.getCallingUid();
satok988323c2011-06-22 16:38:13 +0900553 if (mSpellCheckerBindGroups.containsKey(sciId)) {
satok6be6d752011-07-28 20:40:38 +0900554 final SpellCheckerBindGroup bindGroup = mSpellCheckerBindGroups.get(sciId);
555 if (bindGroup != null) {
556 final InternalDeathRecipient recipient =
557 mSpellCheckerBindGroups.get(sciId).addListener(
satok53578062011-08-03 16:08:59 +0900558 tsListener, locale, scListener, uid, bundle);
satok6be6d752011-07-28 20:40:38 +0900559 if (recipient == null) {
560 if (DBG) {
561 Slog.w(TAG, "Didn't create a death recipient.");
562 }
563 return;
564 }
565 if (bindGroup.mSpellChecker == null & bindGroup.mConnected) {
566 Slog.e(TAG, "The state of the spell checker bind group is illegal.");
567 bindGroup.removeAll();
568 } else if (bindGroup.mSpellChecker != null) {
569 if (DBG) {
satokdf5659d2011-07-29 18:38:21 +0900570 Slog.w(TAG, "Existing bind found. Return a spell checker session now. "
571 + "Listeners count = " + bindGroup.mListeners.size());
satok6be6d752011-07-28 20:40:38 +0900572 }
573 try {
574 final ISpellCheckerSession session =
575 bindGroup.mSpellChecker.getISpellCheckerSession(
satok53578062011-08-03 16:08:59 +0900576 recipient.mScLocale, recipient.mScListener, bundle);
satokdf5659d2011-07-29 18:38:21 +0900577 if (session != null) {
578 tsListener.onServiceConnected(session);
579 return;
580 } else {
581 if (DBG) {
582 Slog.w(TAG, "Existing bind already expired. ");
583 }
584 bindGroup.removeAll();
585 }
satok6be6d752011-07-28 20:40:38 +0900586 } catch (RemoteException e) {
587 Slog.e(TAG, "Exception in getting spell checker session: " + e);
588 bindGroup.removeAll();
589 }
590 }
591 }
satok988323c2011-06-22 16:38:13 +0900592 }
satok6be6d752011-07-28 20:40:38 +0900593 final long ident = Binder.clearCallingIdentity();
594 try {
satok53578062011-08-03 16:08:59 +0900595 startSpellCheckerServiceInnerLocked(
596 sci, locale, tsListener, scListener, uid, bundle);
satok6be6d752011-07-28 20:40:38 +0900597 } finally {
598 Binder.restoreCallingIdentity(ident);
satok988323c2011-06-22 16:38:13 +0900599 }
satok988323c2011-06-22 16:38:13 +0900600 }
601 return;
602 }
603
satoka33c4fc2011-08-25 16:50:11 +0900604 @Override
605 public boolean isSpellCheckerEnabled() {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900606 if (!calledFromValidUser()) {
607 return false;
608 }
satoka33c4fc2011-08-25 16:50:11 +0900609 synchronized(mSpellCheckerMap) {
610 return isSpellCheckerEnabledLocked();
611 }
612 }
613
satok6be6d752011-07-28 20:40:38 +0900614 private void startSpellCheckerServiceInnerLocked(SpellCheckerInfo info, String locale,
satokdf5659d2011-07-29 18:38:21 +0900615 ITextServicesSessionListener tsListener, ISpellCheckerSessionListener scListener,
satok53578062011-08-03 16:08:59 +0900616 int uid, Bundle bundle) {
satokdf5659d2011-07-29 18:38:21 +0900617 if (DBG) {
618 Slog.w(TAG, "Start spell checker session inner locked.");
619 }
satok6be6d752011-07-28 20:40:38 +0900620 final String sciId = info.getId();
621 final InternalServiceConnection connection = new InternalServiceConnection(
satok060677f2011-11-17 09:40:56 +0900622 sciId, locale, bundle);
satok6be6d752011-07-28 20:40:38 +0900623 final Intent serviceIntent = new Intent(SpellCheckerService.SERVICE_INTERFACE);
624 serviceIntent.setComponent(info.getComponent());
625 if (DBG) {
626 Slog.w(TAG, "bind service: " + info.getId());
627 }
Dianne Hackbornd69e4c12015-04-24 09:54:54 -0700628 if (!bindCurrentSpellCheckerService(serviceIntent, connection,
629 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE_WHILE_AWAKE)) {
satok6be6d752011-07-28 20:40:38 +0900630 Slog.e(TAG, "Failed to get a spell checker service.");
631 return;
632 }
633 final SpellCheckerBindGroup group = new SpellCheckerBindGroup(
satok53578062011-08-03 16:08:59 +0900634 connection, tsListener, locale, scListener, uid, bundle);
satok6be6d752011-07-28 20:40:38 +0900635 mSpellCheckerBindGroups.put(sciId, group);
636 }
637
satok988323c2011-06-22 16:38:13 +0900638 @Override
satok562ab582011-07-25 10:12:21 +0900639 public SpellCheckerInfo[] getEnabledSpellCheckers() {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900640 // TODO: Make this work even for non-current users?
641 if (!calledFromValidUser()) {
642 return null;
643 }
satokda317ef2011-07-26 08:02:45 +0900644 if (DBG) {
645 Slog.d(TAG, "getEnabledSpellCheckers: " + mSpellCheckerList.size());
646 for (int i = 0; i < mSpellCheckerList.size(); ++i) {
647 Slog.d(TAG, "EnabledSpellCheckers: " + mSpellCheckerList.get(i).getPackageName());
648 }
649 }
satok562ab582011-07-25 10:12:21 +0900650 return mSpellCheckerList.toArray(new SpellCheckerInfo[mSpellCheckerList.size()]);
651 }
652
653 @Override
satok988323c2011-06-22 16:38:13 +0900654 public void finishSpellCheckerService(ISpellCheckerSessionListener listener) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900655 if (!calledFromValidUser()) {
656 return;
657 }
satokda317ef2011-07-26 08:02:45 +0900658 if (DBG) {
659 Slog.d(TAG, "FinishSpellCheckerService");
660 }
satok988323c2011-06-22 16:38:13 +0900661 synchronized(mSpellCheckerMap) {
Yohei Yukawa074637f2016-03-06 14:34:55 -0800662 final ArrayList<SpellCheckerBindGroup> removeList = new ArrayList<>();
satok988323c2011-06-22 16:38:13 +0900663 for (SpellCheckerBindGroup group : mSpellCheckerBindGroups.values()) {
664 if (group == null) continue;
satok4c3fa642011-11-30 18:17:59 +0900665 // Use removeList to avoid modifying mSpellCheckerBindGroups in this loop.
666 removeList.add(group);
667 }
668 final int removeSize = removeList.size();
669 for (int i = 0; i < removeSize; ++i) {
670 removeList.get(i).removeListener(listener);
satok988323c2011-06-22 16:38:13 +0900671 }
672 }
673 }
674
satokdf5659d2011-07-29 18:38:21 +0900675 @Override
satokada8c4e2011-08-23 14:56:56 +0900676 public void setCurrentSpellChecker(String locale, String sciId) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900677 if (!calledFromValidUser()) {
678 return;
679 }
satokdf5659d2011-07-29 18:38:21 +0900680 synchronized(mSpellCheckerMap) {
681 if (mContext.checkCallingOrSelfPermission(
682 android.Manifest.permission.WRITE_SECURE_SETTINGS)
683 != PackageManager.PERMISSION_GRANTED) {
684 throw new SecurityException(
685 "Requires permission "
686 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
687 }
satok5b9b5a92011-08-02 12:24:44 +0900688 setCurrentSpellCheckerLocked(sciId);
satokdf5659d2011-07-29 18:38:21 +0900689 }
690 }
691
satokada8c4e2011-08-23 14:56:56 +0900692 @Override
693 public void setCurrentSpellCheckerSubtype(String locale, int hashCode) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900694 if (!calledFromValidUser()) {
695 return;
696 }
satokada8c4e2011-08-23 14:56:56 +0900697 synchronized(mSpellCheckerMap) {
698 if (mContext.checkCallingOrSelfPermission(
699 android.Manifest.permission.WRITE_SECURE_SETTINGS)
700 != PackageManager.PERMISSION_GRANTED) {
701 throw new SecurityException(
702 "Requires permission "
703 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
704 }
satoka33c4fc2011-08-25 16:50:11 +0900705 setCurrentSpellCheckerSubtypeLocked(hashCode);
706 }
707 }
708
709 @Override
710 public void setSpellCheckerEnabled(boolean enabled) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900711 if (!calledFromValidUser()) {
712 return;
713 }
satoka33c4fc2011-08-25 16:50:11 +0900714 synchronized(mSpellCheckerMap) {
715 if (mContext.checkCallingOrSelfPermission(
716 android.Manifest.permission.WRITE_SECURE_SETTINGS)
717 != PackageManager.PERMISSION_GRANTED) {
718 throw new SecurityException(
719 "Requires permission "
720 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
721 }
722 setSpellCheckerEnabledLocked(enabled);
satokada8c4e2011-08-23 14:56:56 +0900723 }
724 }
725
satok5b9b5a92011-08-02 12:24:44 +0900726 private void setCurrentSpellCheckerLocked(String sciId) {
satok562ab582011-07-25 10:12:21 +0900727 if (DBG) {
satok5b9b5a92011-08-02 12:24:44 +0900728 Slog.w(TAG, "setCurrentSpellChecker: " + sciId);
satok562ab582011-07-25 10:12:21 +0900729 }
satok5b9b5a92011-08-02 12:24:44 +0900730 if (TextUtils.isEmpty(sciId) || !mSpellCheckerMap.containsKey(sciId)) return;
satokf39daef2011-08-26 19:54:27 +0900731 final SpellCheckerInfo currentSci = getCurrentSpellChecker(null);
732 if (currentSci != null && currentSci.getId().equals(sciId)) {
733 // Do nothing if the current spell checker is same as new spell checker.
734 return;
735 }
satokdf5659d2011-07-29 18:38:21 +0900736 final long ident = Binder.clearCallingIdentity();
737 try {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900738 mSettings.putSelectedSpellChecker(sciId);
satokf39daef2011-08-26 19:54:27 +0900739 setCurrentSpellCheckerSubtypeLocked(0);
satokada8c4e2011-08-23 14:56:56 +0900740 } finally {
741 Binder.restoreCallingIdentity(ident);
742 }
743 }
744
satoka33c4fc2011-08-25 16:50:11 +0900745 private void setCurrentSpellCheckerSubtypeLocked(int hashCode) {
satokada8c4e2011-08-23 14:56:56 +0900746 if (DBG) {
747 Slog.w(TAG, "setCurrentSpellCheckerSubtype: " + hashCode);
748 }
749 final SpellCheckerInfo sci = getCurrentSpellChecker(null);
satokfbedf1a2011-08-26 15:48:50 +0900750 int tempHashCode = 0;
751 for (int i = 0; sci != null && i < sci.getSubtypeCount(); ++i) {
satokada8c4e2011-08-23 14:56:56 +0900752 if(sci.getSubtypeAt(i).hashCode() == hashCode) {
satokfbedf1a2011-08-26 15:48:50 +0900753 tempHashCode = hashCode;
satokada8c4e2011-08-23 14:56:56 +0900754 break;
755 }
756 }
satokada8c4e2011-08-23 14:56:56 +0900757 final long ident = Binder.clearCallingIdentity();
758 try {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900759 mSettings.putSelectedSpellCheckerSubtype(tempHashCode);
satokdf5659d2011-07-29 18:38:21 +0900760 } finally {
761 Binder.restoreCallingIdentity(ident);
762 }
satok988323c2011-06-22 16:38:13 +0900763 }
764
satoka33c4fc2011-08-25 16:50:11 +0900765 private void setSpellCheckerEnabledLocked(boolean enabled) {
766 if (DBG) {
767 Slog.w(TAG, "setSpellCheckerEnabled: " + enabled);
768 }
769 final long ident = Binder.clearCallingIdentity();
770 try {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900771 mSettings.setSpellCheckerEnabled(enabled);
satoka33c4fc2011-08-25 16:50:11 +0900772 } finally {
773 Binder.restoreCallingIdentity(ident);
774 }
775 }
776
777 private boolean isSpellCheckerEnabledLocked() {
778 final long ident = Binder.clearCallingIdentity();
779 try {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900780 final boolean retval = mSettings.isSpellCheckerEnabled();
satoka33c4fc2011-08-25 16:50:11 +0900781 if (DBG) {
782 Slog.w(TAG, "getSpellCheckerEnabled: " + retval);
783 }
784 return retval;
785 } finally {
786 Binder.restoreCallingIdentity(ident);
787 }
788 }
789
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700790 @Override
791 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
792 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
793 != PackageManager.PERMISSION_GRANTED) {
794
795 pw.println("Permission Denial: can't dump TextServicesManagerService from from pid="
796 + Binder.getCallingPid()
797 + ", uid=" + Binder.getCallingUid());
798 return;
799 }
800
801 synchronized(mSpellCheckerMap) {
802 pw.println("Current Text Services Manager state:");
Yohei Yukawa85df6982016-03-08 15:16:07 -0800803 pw.println(" Spell Checkers:");
804 int spellCheckerIndex = 0;
805 for (final SpellCheckerInfo info : mSpellCheckerMap.values()) {
806 pw.println(" Spell Checker #" + spellCheckerIndex);
807 info.dump(pw, " ");
808 ++spellCheckerIndex;
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700809 }
810 pw.println("");
811 pw.println(" Spell Checker Bind Groups:");
Yohei Yukawa85df6982016-03-08 15:16:07 -0800812 for (final Map.Entry<String, SpellCheckerBindGroup> ent
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700813 : mSpellCheckerBindGroups.entrySet()) {
Yohei Yukawa85df6982016-03-08 15:16:07 -0800814 final SpellCheckerBindGroup grp = ent.getValue();
815 pw.println(" " + ent.getKey() + " " + grp + ":");
816 pw.println(" " + "mInternalConnection=" + grp.mInternalConnection);
817 pw.println(" " + "mSpellChecker=" + grp.mSpellChecker);
818 pw.println(" " + "mBound=" + grp.mBound + " mConnected=" + grp.mConnected);
819 final int N = grp.mListeners.size();
820 for (int i = 0; i < N; i++) {
821 final InternalDeathRecipient listener = grp.mListeners.get(i);
822 pw.println(" " + "Listener #" + i + ":");
823 pw.println(" " + "mTsListener=" + listener.mTsListener);
824 pw.println(" " + "mScListener=" + listener.mScListener);
825 pw.println(" " + "mGroup=" + listener.mGroup);
826 pw.println(" " + "mScLocale=" + listener.mScLocale
827 + " mUid=" + listener.mUid);
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700828 }
829 }
Yohei Yukawa85df6982016-03-08 15:16:07 -0800830 pw.println("");
831 pw.println(" mSettings:");
832 mSettings.dumpLocked(pw, " ");
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700833 }
834 }
835
satok988323c2011-06-22 16:38:13 +0900836 // SpellCheckerBindGroup contains active text service session listeners.
837 // If there are no listeners anymore, the SpellCheckerBindGroup instance will be removed from
838 // mSpellCheckerBindGroups
839 private class SpellCheckerBindGroup {
satokdf5659d2011-07-29 18:38:21 +0900840 private final String TAG = SpellCheckerBindGroup.class.getSimpleName();
satok6be6d752011-07-28 20:40:38 +0900841 private final InternalServiceConnection mInternalConnection;
satok4e713f12012-02-28 16:51:15 +0900842 private final CopyOnWriteArrayList<InternalDeathRecipient> mListeners =
Yohei Yukawa074637f2016-03-06 14:34:55 -0800843 new CopyOnWriteArrayList<>();
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700844 public boolean mBound;
satok6be6d752011-07-28 20:40:38 +0900845 public ISpellCheckerService mSpellChecker;
846 public boolean mConnected;
satok988323c2011-06-22 16:38:13 +0900847
848 public SpellCheckerBindGroup(InternalServiceConnection connection,
849 ITextServicesSessionListener listener, String locale,
satok53578062011-08-03 16:08:59 +0900850 ISpellCheckerSessionListener scListener, int uid, Bundle bundle) {
satok988323c2011-06-22 16:38:13 +0900851 mInternalConnection = connection;
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700852 mBound = true;
satok6be6d752011-07-28 20:40:38 +0900853 mConnected = false;
satok53578062011-08-03 16:08:59 +0900854 addListener(listener, locale, scListener, uid, bundle);
satok988323c2011-06-22 16:38:13 +0900855 }
856
857 public void onServiceConnected(ISpellCheckerService spellChecker) {
satokda317ef2011-07-26 08:02:45 +0900858 if (DBG) {
859 Slog.d(TAG, "onServiceConnected");
860 }
satok4e713f12012-02-28 16:51:15 +0900861
862 for (InternalDeathRecipient listener : mListeners) {
863 try {
864 final ISpellCheckerSession session = spellChecker.getISpellCheckerSession(
865 listener.mScLocale, listener.mScListener, listener.mBundle);
866 synchronized(mSpellCheckerMap) {
867 if (mListeners.contains(listener)) {
868 listener.mTsListener.onServiceConnected(session);
869 }
satok988323c2011-06-22 16:38:13 +0900870 }
satok4e713f12012-02-28 16:51:15 +0900871 } catch (RemoteException e) {
872 Slog.e(TAG, "Exception in getting the spell checker session."
873 + "Reconnect to the spellchecker. ", e);
874 removeAll();
875 return;
satok988323c2011-06-22 16:38:13 +0900876 }
satok4e713f12012-02-28 16:51:15 +0900877 }
878 synchronized(mSpellCheckerMap) {
satok6be6d752011-07-28 20:40:38 +0900879 mSpellChecker = spellChecker;
880 mConnected = true;
satok988323c2011-06-22 16:38:13 +0900881 }
882 }
883
satok6be6d752011-07-28 20:40:38 +0900884 public InternalDeathRecipient addListener(ITextServicesSessionListener tsListener,
satok53578062011-08-03 16:08:59 +0900885 String locale, ISpellCheckerSessionListener scListener, int uid, Bundle bundle) {
satokda317ef2011-07-26 08:02:45 +0900886 if (DBG) {
887 Slog.d(TAG, "addListener: " + locale);
888 }
satok6be6d752011-07-28 20:40:38 +0900889 InternalDeathRecipient recipient = null;
satok988323c2011-06-22 16:38:13 +0900890 synchronized(mSpellCheckerMap) {
891 try {
892 final int size = mListeners.size();
893 for (int i = 0; i < size; ++i) {
894 if (mListeners.get(i).hasSpellCheckerListener(scListener)) {
895 // do not add the lister if the group already contains this.
satok6be6d752011-07-28 20:40:38 +0900896 return null;
satok988323c2011-06-22 16:38:13 +0900897 }
898 }
satok6be6d752011-07-28 20:40:38 +0900899 recipient = new InternalDeathRecipient(
satok53578062011-08-03 16:08:59 +0900900 this, tsListener, locale, scListener, uid, bundle);
satok988323c2011-06-22 16:38:13 +0900901 scListener.asBinder().linkToDeath(recipient, 0);
satokdf5659d2011-07-29 18:38:21 +0900902 mListeners.add(recipient);
satok988323c2011-06-22 16:38:13 +0900903 } catch(RemoteException e) {
904 // do nothing
905 }
906 cleanLocked();
907 }
satok6be6d752011-07-28 20:40:38 +0900908 return recipient;
satok988323c2011-06-22 16:38:13 +0900909 }
910
911 public void removeListener(ISpellCheckerSessionListener listener) {
satokda317ef2011-07-26 08:02:45 +0900912 if (DBG) {
satokdf5659d2011-07-29 18:38:21 +0900913 Slog.w(TAG, "remove listener: " + listener.hashCode());
satokda317ef2011-07-26 08:02:45 +0900914 }
satok988323c2011-06-22 16:38:13 +0900915 synchronized(mSpellCheckerMap) {
916 final int size = mListeners.size();
Yohei Yukawa074637f2016-03-06 14:34:55 -0800917 final ArrayList<InternalDeathRecipient> removeList = new ArrayList<>();
satok988323c2011-06-22 16:38:13 +0900918 for (int i = 0; i < size; ++i) {
919 final InternalDeathRecipient tempRecipient = mListeners.get(i);
920 if(tempRecipient.hasSpellCheckerListener(listener)) {
satokdf5659d2011-07-29 18:38:21 +0900921 if (DBG) {
922 Slog.w(TAG, "found existing listener.");
923 }
satok988323c2011-06-22 16:38:13 +0900924 removeList.add(tempRecipient);
925 }
926 }
927 final int removeSize = removeList.size();
928 for (int i = 0; i < removeSize; ++i) {
satokdf5659d2011-07-29 18:38:21 +0900929 if (DBG) {
930 Slog.w(TAG, "Remove " + removeList.get(i));
931 }
satok2520ed82011-10-31 19:38:05 +0900932 final InternalDeathRecipient idr = removeList.get(i);
933 idr.mScListener.asBinder().unlinkToDeath(idr, 0);
934 mListeners.remove(idr);
satok988323c2011-06-22 16:38:13 +0900935 }
936 cleanLocked();
937 }
938 }
939
satok4c3fa642011-11-30 18:17:59 +0900940 // cleanLocked may remove elements from mSpellCheckerBindGroups
satok988323c2011-06-22 16:38:13 +0900941 private void cleanLocked() {
satokda317ef2011-07-26 08:02:45 +0900942 if (DBG) {
943 Slog.d(TAG, "cleanLocked");
944 }
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700945 // If there are no more active listeners, clean up. Only do this
946 // once.
947 if (mBound && mListeners.isEmpty()) {
948 mBound = false;
satokc7b60f722011-08-31 16:30:27 +0900949 final String sciId = mInternalConnection.mSciId;
Dianne Hackborn71e14da2011-10-16 16:28:10 -0700950 SpellCheckerBindGroup cur = mSpellCheckerBindGroups.get(sciId);
951 if (cur == this) {
satokc7b60f722011-08-31 16:30:27 +0900952 if (DBG) {
953 Slog.d(TAG, "Remove bind group.");
954 }
955 mSpellCheckerBindGroups.remove(sciId);
satok6be6d752011-07-28 20:40:38 +0900956 }
satok988323c2011-06-22 16:38:13 +0900957 mContext.unbindService(mInternalConnection);
958 }
959 }
satok6be6d752011-07-28 20:40:38 +0900960
961 public void removeAll() {
962 Slog.e(TAG, "Remove the spell checker bind unexpectedly.");
satokdf5659d2011-07-29 18:38:21 +0900963 synchronized(mSpellCheckerMap) {
satok2520ed82011-10-31 19:38:05 +0900964 final int size = mListeners.size();
965 for (int i = 0; i < size; ++i) {
966 final InternalDeathRecipient idr = mListeners.get(i);
967 idr.mScListener.asBinder().unlinkToDeath(idr, 0);
968 }
satokdf5659d2011-07-29 18:38:21 +0900969 mListeners.clear();
970 cleanLocked();
971 }
satok6be6d752011-07-28 20:40:38 +0900972 }
satok988323c2011-06-22 16:38:13 +0900973 }
974
975 private class InternalServiceConnection implements ServiceConnection {
satok988323c2011-06-22 16:38:13 +0900976 private final String mSciId;
977 private final String mLocale;
satok53578062011-08-03 16:08:59 +0900978 private final Bundle mBundle;
satok988323c2011-06-22 16:38:13 +0900979 public InternalServiceConnection(
satok060677f2011-11-17 09:40:56 +0900980 String id, String locale, Bundle bundle) {
satok988323c2011-06-22 16:38:13 +0900981 mSciId = id;
982 mLocale = locale;
satok53578062011-08-03 16:08:59 +0900983 mBundle = bundle;
satok988323c2011-06-22 16:38:13 +0900984 }
985
986 @Override
987 public void onServiceConnected(ComponentName name, IBinder service) {
988 synchronized(mSpellCheckerMap) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +0900989 onServiceConnectedInnerLocked(name, service);
990 }
991 }
992
993 private void onServiceConnectedInnerLocked(ComponentName name, IBinder service) {
994 if (DBG) {
995 Slog.w(TAG, "onServiceConnected: " + name);
996 }
997 final ISpellCheckerService spellChecker =
998 ISpellCheckerService.Stub.asInterface(service);
999 final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId);
1000 if (group != null && this == group.mInternalConnection) {
1001 group.onServiceConnected(spellChecker);
satok988323c2011-06-22 16:38:13 +09001002 }
1003 }
1004
1005 @Override
1006 public void onServiceDisconnected(ComponentName name) {
Dianne Hackborn71e14da2011-10-16 16:28:10 -07001007 synchronized(mSpellCheckerMap) {
1008 final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId);
satok2cf1cf02011-10-21 15:25:23 +09001009 if (group != null && this == group.mInternalConnection) {
Dianne Hackborn71e14da2011-10-16 16:28:10 -07001010 mSpellCheckerBindGroups.remove(mSciId);
1011 }
1012 }
satok988323c2011-06-22 16:38:13 +09001013 }
1014 }
1015
1016 private class InternalDeathRecipient implements IBinder.DeathRecipient {
1017 public final ITextServicesSessionListener mTsListener;
1018 public final ISpellCheckerSessionListener mScListener;
1019 public final String mScLocale;
1020 private final SpellCheckerBindGroup mGroup;
satokdf5659d2011-07-29 18:38:21 +09001021 public final int mUid;
satok53578062011-08-03 16:08:59 +09001022 public final Bundle mBundle;
satok988323c2011-06-22 16:38:13 +09001023 public InternalDeathRecipient(SpellCheckerBindGroup group,
1024 ITextServicesSessionListener tsListener, String scLocale,
satok53578062011-08-03 16:08:59 +09001025 ISpellCheckerSessionListener scListener, int uid, Bundle bundle) {
satok988323c2011-06-22 16:38:13 +09001026 mTsListener = tsListener;
1027 mScListener = scListener;
1028 mScLocale = scLocale;
1029 mGroup = group;
satokdf5659d2011-07-29 18:38:21 +09001030 mUid = uid;
satok53578062011-08-03 16:08:59 +09001031 mBundle = bundle;
satok988323c2011-06-22 16:38:13 +09001032 }
1033
1034 public boolean hasSpellCheckerListener(ISpellCheckerSessionListener listener) {
satokdf5659d2011-07-29 18:38:21 +09001035 return listener.asBinder().equals(mScListener.asBinder());
satok988323c2011-06-22 16:38:13 +09001036 }
1037
1038 @Override
1039 public void binderDied() {
1040 mGroup.removeListener(mScListener);
1041 }
1042 }
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001043
1044 private static class TextServicesSettings {
1045 private final ContentResolver mResolver;
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -08001046 @UserIdInt
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001047 private int mCurrentUserId;
Yohei Yukawa095fa372014-10-27 14:02:23 +09001048 @GuardedBy("mLock")
1049 private int[] mCurrentProfileIds = new int[0];
1050 private Object mLock = new Object();
1051
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001052 /**
1053 * On-memory data store to emulate when {@link #mCopyOnWrite} is {@code true}.
1054 */
1055 private final HashMap<String, String> mCopyOnWriteDataStore = new HashMap<>();
1056 private boolean mCopyOnWrite = false;
1057
1058 public TextServicesSettings(ContentResolver resolver, @UserIdInt int userId,
1059 boolean copyOnWrite) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001060 mResolver = resolver;
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001061 switchCurrentUser(userId, copyOnWrite);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001062 }
1063
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001064 /**
1065 * Must be called when the current user is changed.
1066 *
1067 * @param userId The user ID.
1068 * @param copyOnWrite If {@code true}, for each settings key
1069 * (e.g. {@link Settings.Secure#SELECTED_SPELL_CHECKER}) we use the actual settings on the
1070 * {@link Settings.Secure} until we do the first write operation.
1071 */
1072 public void switchCurrentUser(@UserIdInt int userId, boolean copyOnWrite) {
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001073 if (DBG) {
1074 Slog.d(TAG, "--- Swtich the current user from " + mCurrentUserId + " to "
1075 + userId + ", new ime = " + getSelectedSpellChecker());
1076 }
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001077 if (mCurrentUserId != userId || mCopyOnWrite != copyOnWrite) {
1078 mCopyOnWriteDataStore.clear();
1079 // TODO: mCurrentProfileIds should be cleared here.
1080 }
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001081 // TSMS settings are kept per user, so keep track of current user
1082 mCurrentUserId = userId;
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001083 mCopyOnWrite = copyOnWrite;
1084 // TODO: mCurrentProfileIds should be updated here.
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001085 }
1086
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001087 private void putString(final String key, final String str) {
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001088 if (mCopyOnWrite) {
1089 mCopyOnWriteDataStore.put(key, str);
1090 } else {
1091 Settings.Secure.putStringForUser(mResolver, key, str, mCurrentUserId);
1092 }
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001093 }
1094
Yohei Yukawa08ce1872016-03-16 17:22:30 -07001095 @Nullable
1096 private String getString(@NonNull final String key, @Nullable final String defaultValue) {
1097 final String result;
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001098 if (mCopyOnWrite && mCopyOnWriteDataStore.containsKey(key)) {
Yohei Yukawa08ce1872016-03-16 17:22:30 -07001099 result = mCopyOnWriteDataStore.get(key);
1100 } else {
1101 result = Settings.Secure.getStringForUser(mResolver, key, mCurrentUserId);
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001102 }
Yohei Yukawa08ce1872016-03-16 17:22:30 -07001103 return result != null ? result : defaultValue;
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001104 }
1105
1106 private void putInt(final String key, final int value) {
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001107 if (mCopyOnWrite) {
1108 mCopyOnWriteDataStore.put(key, String.valueOf(value));
1109 } else {
1110 Settings.Secure.putIntForUser(mResolver, key, value, mCurrentUserId);
1111 }
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001112 }
1113
1114 private int getInt(final String key, final int defaultValue) {
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001115 if (mCopyOnWrite && mCopyOnWriteDataStore.containsKey(key)) {
1116 final String result = mCopyOnWriteDataStore.get(key);
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001117 return result != null ? Integer.parseInt(result) : 0;
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001118 }
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001119 return Settings.Secure.getIntForUser(mResolver, key, defaultValue, mCurrentUserId);
1120 }
1121
1122 private void putBoolean(final String key, final boolean value) {
1123 putInt(key, value ? 1 : 0);
1124 }
1125
1126 private boolean getBoolean(final String key, final boolean defaultValue) {
1127 return getInt(key, defaultValue ? 1 : 0) == 1;
1128 }
1129
Yohei Yukawa095fa372014-10-27 14:02:23 +09001130 public void setCurrentProfileIds(int[] currentProfileIds) {
1131 synchronized (mLock) {
1132 mCurrentProfileIds = currentProfileIds;
1133 }
1134 }
1135
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -08001136 public boolean isCurrentProfile(@UserIdInt int userId) {
Yohei Yukawa095fa372014-10-27 14:02:23 +09001137 synchronized (mLock) {
1138 if (userId == mCurrentUserId) return true;
1139 for (int i = 0; i < mCurrentProfileIds.length; i++) {
1140 if (userId == mCurrentProfileIds[i]) return true;
1141 }
1142 return false;
1143 }
1144 }
1145
Yohei Yukawa9faa2ae2016-03-07 13:42:07 -08001146 @UserIdInt
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001147 public int getCurrentUserId() {
1148 return mCurrentUserId;
1149 }
1150
Yohei Yukawa08ce1872016-03-16 17:22:30 -07001151 public void putSelectedSpellChecker(@Nullable String sciId) {
1152 if (TextUtils.isEmpty(sciId)) {
1153 // OK to coalesce to null, since getSelectedSpellChecker() can take care of the
1154 // empty data scenario.
1155 putString(Settings.Secure.SELECTED_SPELL_CHECKER, null);
1156 } else {
1157 putString(Settings.Secure.SELECTED_SPELL_CHECKER, sciId);
1158 }
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001159 }
1160
1161 public void putSelectedSpellCheckerSubtype(int hashCode) {
Yohei Yukawaad150ee2016-03-16 17:22:27 -07001162 putInt(Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, hashCode);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001163 }
1164
1165 public void setSpellCheckerEnabled(boolean enabled) {
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001166 putBoolean(Settings.Secure.SPELL_CHECKER_ENABLED, enabled);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001167 }
1168
Yohei Yukawa08ce1872016-03-16 17:22:30 -07001169 @NonNull
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001170 public String getSelectedSpellChecker() {
Yohei Yukawa08ce1872016-03-16 17:22:30 -07001171 return getString(Settings.Secure.SELECTED_SPELL_CHECKER, "");
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001172 }
1173
Yohei Yukawaad150ee2016-03-16 17:22:27 -07001174 public int getSelectedSpellCheckerSubtype(final int defaultValue) {
1175 return getInt(Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, defaultValue);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001176 }
1177
1178 public boolean isSpellCheckerEnabled() {
Yohei Yukawaf0ed48d2016-03-07 21:26:38 -08001179 return getBoolean(Settings.Secure.SPELL_CHECKER_ENABLED, true);
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001180 }
Yohei Yukawa85df6982016-03-08 15:16:07 -08001181
1182 public void dumpLocked(final PrintWriter pw, final String prefix) {
1183 pw.println(prefix + "mCurrentUserId=" + mCurrentUserId);
1184 pw.println(prefix + "mCurrentProfileIds=" + Arrays.toString(mCurrentProfileIds));
Yohei Yukawa49ed1402016-03-07 19:12:54 -08001185 pw.println(prefix + "mCopyOnWrite=" + mCopyOnWrite);
Yohei Yukawa85df6982016-03-08 15:16:07 -08001186 }
Satoshi Kataoka00d2d412012-09-28 20:32:33 +09001187 }
1188
1189 // ----------------------------------------------------------------------
1190 // Utilities for debug
1191 private static String getStackTrace() {
1192 final StringBuilder sb = new StringBuilder();
1193 try {
1194 throw new RuntimeException();
1195 } catch (RuntimeException e) {
1196 final StackTraceElement[] frames = e.getStackTrace();
1197 // Start at 1 because the first frame is here and we don't care about it
1198 for (int j = 1; j < frames.length; ++j) {
1199 sb.append(frames[j].toString() + "\n");
1200 }
1201 }
1202 return sb.toString();
1203 }
satok988323c2011-06-22 16:38:13 +09001204}