blob: 93f7f1d12922d299096f48955488b83c03a979e5 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 * use this file except in compliance with the License. You may obtain a copy of
5 * the License at
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007 * http://www.apache.org/licenses/LICENSE-2.0
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 * License for the specific language governing permissions and limitations under
13 * the License.
14 */
15
16package com.android.server;
17
Wale Ogunwaleac2561e2016-11-01 15:43:46 -070018import static android.view.Display.DEFAULT_DISPLAY;
Wale Ogunwale3a931692016-11-02 16:49:48 -070019import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
Wale Ogunwaleac2561e2016-11-01 15:43:46 -070020import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
Wale Ogunwale3a931692016-11-02 16:49:48 -070021import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG;
Yohei Yukawafa0e47e2016-04-05 09:55:56 -070022import static java.lang.annotation.RetentionPolicy.SOURCE;
23
Yohei Yukawac4e44912017-02-09 19:30:22 -080024import com.android.internal.annotations.GuardedBy;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080025import com.android.internal.content.PackageMonitor;
Yohei Yukawa25e08132016-06-22 16:31:41 -070026import com.android.internal.inputmethod.IInputContentUriToken;
Satoshi Kataokad7443c82013-10-15 17:45:43 +090027import com.android.internal.inputmethod.InputMethodSubtypeSwitchingController;
Satoshi Kataokad787f692013-10-26 04:44:21 +090028import com.android.internal.inputmethod.InputMethodSubtypeSwitchingController.ImeSubtypeListItem;
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +090029import com.android.internal.inputmethod.InputMethodUtils;
30import com.android.internal.inputmethod.InputMethodUtils.InputMethodSettings;
Chris Wren282cfef2017-03-27 15:01:44 -040031import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -050032import com.android.internal.notification.SystemNotificationChannels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import com.android.internal.os.HandlerCaller;
Svetoslav Ganov758143e2012-08-06 16:40:27 -070034import com.android.internal.os.SomeArgs;
Jeff Sharkey850c83e2016-11-09 12:25:44 -070035import com.android.internal.os.TransferPipe;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060036import com.android.internal.util.DumpUtils;
satoke7c6998e2011-06-03 17:57:59 +090037import com.android.internal.util.FastXmlSerializer;
Yohei Yukawacac97722017-12-15 16:52:05 -080038import com.android.internal.util.IndentingPrintWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import com.android.internal.view.IInputContext;
40import com.android.internal.view.IInputMethod;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import com.android.internal.view.IInputMethodClient;
42import com.android.internal.view.IInputMethodManager;
43import com.android.internal.view.IInputMethodSession;
Yohei Yukawa6ab1a822015-08-25 14:01:28 -070044import com.android.internal.view.IInputSessionCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import com.android.internal.view.InputBindResult;
Yohei Yukawa33e81792015-11-17 21:14:42 -080046import com.android.internal.view.InputMethodClient;
Adam Lesinskief2ea1f2013-12-05 16:48:06 -080047import com.android.server.statusbar.StatusBarManagerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048
satoke7c6998e2011-06-03 17:57:59 +090049import org.xmlpull.v1.XmlPullParser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import org.xmlpull.v1.XmlPullParserException;
satoke7c6998e2011-06-03 17:57:59 +090051import org.xmlpull.v1.XmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052
Yohei Yukawa926488d2017-12-11 17:24:55 -080053import android.Manifest;
Tarandeep Singh75a92392018-01-12 14:58:59 -080054import android.annotation.AnyThread;
Yohei Yukawad6475a62017-04-17 10:35:27 -070055import android.annotation.BinderThread;
Tadashi G. Takaoka01065a52017-07-19 14:10:24 +090056import android.annotation.ColorInt;
Yohei Yukawafa0e47e2016-04-05 09:55:56 -070057import android.annotation.IntDef;
Yohei Yukawa930328c2017-10-18 20:19:53 -070058import android.annotation.MainThread;
Yohei Yukawa6ab1a822015-08-25 14:01:28 -070059import android.annotation.NonNull;
Yohei Yukawae13a20fa2015-09-30 19:11:32 -070060import android.annotation.Nullable;
Yohei Yukawa926488d2017-12-11 17:24:55 -080061import android.annotation.RequiresPermission;
Tarandeep Singheb570612018-01-29 16:20:32 -080062import android.annotation.TestApi;
Yohei Yukawa7b18aec2016-03-07 13:04:32 -080063import android.annotation.UserIdInt;
Sudheer Shankadc589ac2016-11-10 15:30:17 -080064import android.app.ActivityManager;
Sudheer Shankafc46e9b2016-10-21 17:55:27 -070065import android.app.ActivityManagerInternal;
Andrew Sapperstein8a3b4cb2017-04-28 14:35:31 -070066import android.app.ActivityThread;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.app.AlertDialog;
Yohei Yukawa6ab1a822015-08-25 14:01:28 -070068import android.app.AppGlobals;
Yohei Yukawae63b5fa2014-09-19 13:14:55 +090069import android.app.AppOpsManager;
satokf90a33e2011-07-19 11:55:52 +090070import android.app.KeyguardManager;
satok7cfc0ed2011-06-20 21:29:36 +090071import android.app.Notification;
72import android.app.NotificationManager;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070073import android.app.PendingIntent;
satok5b927c432012-05-01 20:09:34 +090074import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.content.ComponentName;
Yohei Yukawa3933a6e2016-11-10 00:47:48 -080076import android.content.ContentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.content.ContentResolver;
78import android.content.Context;
79import android.content.DialogInterface;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.content.DialogInterface.OnCancelListener;
Tadashi G. Takaokad130b802014-08-01 14:05:47 +090081import android.content.DialogInterface.OnClickListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.content.Intent;
satoke7c6998e2011-06-03 17:57:59 +090083import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.content.ServiceConnection;
Brandon Ballinger6da35a02009-10-21 00:38:13 -070085import android.content.pm.ApplicationInfo;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +090086import android.content.pm.IPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.content.pm.PackageManager;
88import android.content.pm.ResolveInfo;
89import android.content.pm.ServiceInfo;
Amith Yamasanie861ec12010-03-24 21:39:27 -070090import android.content.res.Configuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.content.res.Resources;
92import android.content.res.TypedArray;
93import android.database.ContentObserver;
Alan Viverette505e3ab2014-11-24 15:22:11 -080094import android.graphics.drawable.Drawable;
Yohei Yukawab097b822015-12-01 10:43:08 -080095import android.hardware.input.InputManagerInternal;
Joe Onorato857fd9b2011-01-27 15:08:35 -080096import android.inputmethodservice.InputMethodService;
Michael Wright7b5a96b2014-08-09 19:28:42 -070097import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import android.os.Binder;
Chris Wren1ce4b6d2015-06-11 10:19:43 -040099import android.os.Bundle;
Seigo Nonakae27dc2b2015-08-14 18:21:27 -0700100import android.os.Debug;
satoke7c6998e2011-06-03 17:57:59 +0900101import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102import android.os.Handler;
103import android.os.IBinder;
104import android.os.IInterface;
105import android.os.Message;
Yohei Yukawa23cbe852016-05-17 16:42:58 -0700106import android.os.LocaleList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import android.os.Parcel;
Yohei Yukawa6ab1a822015-08-25 14:01:28 -0700108import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import android.os.RemoteException;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800110import android.os.ResultReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import android.os.ServiceManager;
Yohei Yukawa926488d2017-12-11 17:24:55 -0800112import android.os.ShellCallback;
113import android.os.ShellCommand;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import android.os.SystemClock;
Tarandeep Singh75a92392018-01-12 14:58:59 -0800115import android.os.SystemProperties;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +0900116import android.os.UserHandle;
Amith Yamasani734983f2014-03-04 16:48:05 -0800117import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import android.provider.Settings;
Tarandeep Singh89a6c482017-11-21 14:26:11 -0800119import android.service.vr.IVrManager;
120import android.service.vr.IVrStateCallbacks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121import android.text.TextUtils;
satokf9f01002011-05-19 21:31:50 +0900122import android.text.style.SuggestionSpan;
Christopher Tate7b9a28c2015-03-18 13:06:16 -0700123import android.util.ArrayMap;
124import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700125import android.util.AtomicFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126import android.util.EventLog;
satokf9f01002011-05-19 21:31:50 +0900127import android.util.LruCache;
satokab751aa2010-09-14 19:17:36 +0900128import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129import android.util.PrintWriterPrinter;
130import android.util.Printer;
satoke7c6998e2011-06-03 17:57:59 +0900131import android.util.Slog;
132import android.util.Xml;
Tadashi G. Takaokad130b802014-08-01 14:05:47 +0900133import android.view.ContextThemeWrapper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134import android.view.IWindowManager;
Jeff Brownc28867a2013-03-26 15:42:39 -0700135import android.view.InputChannel;
Ken Wakasa05dbb652011-08-22 15:22:43 +0900136import android.view.LayoutInflater;
137import android.view.View;
138import android.view.ViewGroup;
Wale Ogunwale3a931692016-11-02 16:49:48 -0700139import android.view.Window;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140import android.view.WindowManager;
satokab751aa2010-09-14 19:17:36 +0900141import android.view.inputmethod.EditorInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142import android.view.inputmethod.InputBinding;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800143import android.view.inputmethod.InputConnection;
Yohei Yukawa19a80a12016-03-14 22:57:37 -0700144import android.view.inputmethod.InputConnectionInspector;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145import android.view.inputmethod.InputMethod;
146import android.view.inputmethod.InputMethodInfo;
147import android.view.inputmethod.InputMethodManager;
Yohei Yukawafa6e0a82015-07-23 15:08:59 -0700148import android.view.inputmethod.InputMethodManagerInternal;
satokab751aa2010-09-14 19:17:36 +0900149import android.view.inputmethod.InputMethodSubtype;
Yohei Yukawa443c2ba2014-09-10 14:10:30 +0900150import android.view.inputmethod.InputMethodSubtype.InputMethodSubtypeBuilder;
Ken Wakasa05dbb652011-08-22 15:22:43 +0900151import android.widget.ArrayAdapter;
satok01038492012-04-09 21:08:27 +0900152import android.widget.CompoundButton;
153import android.widget.CompoundButton.OnCheckedChangeListener;
Ken Wakasa05dbb652011-08-22 15:22:43 +0900154import android.widget.RadioButton;
satok01038492012-04-09 21:08:27 +0900155import android.widget.Switch;
Ken Wakasa05dbb652011-08-22 15:22:43 +0900156import android.widget.TextView;
Yohei Yukawaebda7d72016-04-02 17:39:23 -0700157import android.widget.Toast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158
Adrian Roose99bc052017-11-20 17:55:31 +0100159import com.android.server.wm.WindowManagerInternal;
160
satoke7c6998e2011-06-03 17:57:59 +0900161import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162import java.io.FileDescriptor;
satoke7c6998e2011-06-03 17:57:59 +0900163import java.io.FileInputStream;
164import java.io.FileOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165import java.io.IOException;
166import java.io.PrintWriter;
Yohei Yukawafa0e47e2016-04-05 09:55:56 -0700167import java.lang.annotation.Retention;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100168import java.nio.charset.StandardCharsets;
Yohei Yukawa25e08132016-06-22 16:31:41 -0700169import java.security.InvalidParameterException;
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800170import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171import java.util.ArrayList;
satok688bd472012-02-09 20:09:17 +0900172import java.util.Collections;
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800173import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174import java.util.HashMap;
175import java.util.List;
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800176import java.util.Locale;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800177import java.util.WeakHashMap;
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800178import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179
180/**
181 * This class provides a system service that manages input methods.
182 */
183public class InputMethodManagerService extends IInputMethodManager.Stub
184 implements ServiceConnection, Handler.Callback {
185 static final boolean DEBUG = false;
Christopher Tate7b9a28c2015-03-18 13:06:16 -0700186 static final boolean DEBUG_RESTORE = DEBUG || false;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700187 static final String TAG = "InputMethodManagerService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188
Yohei Yukawa926488d2017-12-11 17:24:55 -0800189 @Retention(SOURCE)
190 @IntDef({ShellCommandResult.SUCCESS, ShellCommandResult.FAILURE})
191 private @interface ShellCommandResult {
192 int SUCCESS = 0;
193 int FAILURE = -1;
194 }
195
Seigo Nonakad4474cb2015-05-04 16:53:24 -0700196 static final int MSG_SHOW_IM_SUBTYPE_PICKER = 1;
197 static final int MSG_SHOW_IM_SUBTYPE_ENABLER = 2;
198 static final int MSG_SHOW_IM_CONFIG = 3;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 static final int MSG_UNBIND_INPUT = 1000;
201 static final int MSG_BIND_INPUT = 1010;
202 static final int MSG_SHOW_SOFT_INPUT = 1020;
203 static final int MSG_HIDE_SOFT_INPUT = 1030;
Jorim Jaggi3c5d0f12016-05-24 19:04:30 -0700204 static final int MSG_HIDE_CURRENT_INPUT_METHOD = 1035;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 static final int MSG_ATTACH_TOKEN = 1040;
206 static final int MSG_CREATE_SESSION = 1050;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 static final int MSG_START_INPUT = 2000;
Tarandeep Singh89a6c482017-11-21 14:26:11 -0800209 static final int MSG_START_VR_INPUT = 2010;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800210
Yohei Yukawa33e81792015-11-17 21:14:42 -0800211 static final int MSG_UNBIND_CLIENT = 3000;
212 static final int MSG_BIND_CLIENT = 3010;
Dianne Hackborna6e41342012-05-22 16:30:34 -0700213 static final int MSG_SET_ACTIVE = 3020;
Yohei Yukawafa6e0a82015-07-23 15:08:59 -0700214 static final int MSG_SET_INTERACTIVE = 3030;
Yohei Yukawa3d1e8122014-06-06 19:12:47 +0900215 static final int MSG_SET_USER_ACTION_NOTIFICATION_SEQUENCE_NUMBER = 3040;
Yohei Yukawa2bc66172017-02-08 11:13:25 -0800216 static final int MSG_REPORT_FULLSCREEN_MODE = 3045;
Yohei Yukawaae61f712015-12-09 13:00:10 -0800217 static final int MSG_SWITCH_IME = 3050;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800218
satok01038492012-04-09 21:08:27 +0900219 static final int MSG_HARD_KEYBOARD_SWITCH_CHANGED = 4000;
220
Fyodor Kupolov7877b8a2016-06-29 14:39:19 -0700221 static final int MSG_SYSTEM_UNLOCK_USER = 5000;
222
Satoshi Kataokabcacc322013-10-21 17:57:27 -0700223 static final long TIME_TO_RECONNECT = 3 * 1000;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800224
satokf9f01002011-05-19 21:31:50 +0900225 static final int SECURE_SUGGESTION_SPANS_MAX_SIZE = 20;
226
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +0900227 private static final int NOT_A_SUBTYPE_ID = InputMethodUtils.NOT_A_SUBTYPE_ID;
satokb6359412011-06-28 17:47:41 +0900228 private static final String TAG_TRY_SUPPRESSING_IME_SWITCHER = "TrySuppressingImeSwitcher";
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +0900229
Yohei Yukawaa67a4592017-03-30 15:57:02 -0700230 /**
231 * Binding flags for establishing connection to the {@link InputMethodService}.
232 */
233 private static final int IME_CONNECTION_BIND_FLAGS =
234 Context.BIND_AUTO_CREATE
235 | Context.BIND_NOT_VISIBLE
236 | Context.BIND_NOT_FOREGROUND
Yohei Yukawaad78a612017-08-04 01:57:27 -0700237 | Context.BIND_IMPORTANT_BACKGROUND;
Yohei Yukawaa67a4592017-03-30 15:57:02 -0700238
239 /**
240 * Binding flags used only while the {@link InputMethodService} is showing window.
241 */
242 private static final int IME_VISIBLE_BIND_FLAGS =
243 Context.BIND_AUTO_CREATE
244 | Context.BIND_TREAT_LIKE_ACTIVITY
Yohei Yukawaad78a612017-08-04 01:57:27 -0700245 | Context.BIND_FOREGROUND_SERVICE
246 | Context.BIND_SHOWING_UI;
Yohei Yukawaa67a4592017-03-30 15:57:02 -0700247
Yohei Yukawafa0e47e2016-04-05 09:55:56 -0700248 @Retention(SOURCE)
249 @IntDef({HardKeyboardBehavior.WIRELESS_AFFORDANCE, HardKeyboardBehavior.WIRED_AFFORDANCE})
250 private @interface HardKeyboardBehavior {
251 int WIRELESS_AFFORDANCE = 0;
252 int WIRED_AFFORDANCE = 1;
253 }
satok4e4569d2010-11-19 18:45:53 +0900254
Tadashi G. Takaoka01065a52017-07-19 14:10:24 +0900255 /**
256 * A protected broadcast intent action for internal use for {@link PendingIntent} in
257 * the notification.
258 */
259 private static final String ACTION_SHOW_INPUT_METHOD_PICKER =
260 "com.android.server.InputMethodManagerService.SHOW_INPUT_METHOD_PICKER";
261
Tarandeep Singh75a92392018-01-12 14:58:59 -0800262 /**
263 * Debug flag for overriding runtime {@link SystemProperties}.
264 */
265 @AnyThread
266 private static final class DebugFlag {
267 private static final Object LOCK = new Object();
268 private final String mKey;
269 @GuardedBy("LOCK")
270 private boolean mValue;
271
272 public DebugFlag(String key) {
273 mKey = key;
274 refresh();
275 }
276
277 void refresh() {
278 synchronized (LOCK) {
279 mValue = SystemProperties.getBoolean(mKey, true);
280 }
281 }
282
283 boolean value() {
284 synchronized (LOCK) {
285 return mValue;
286 }
287 }
288 }
289
290 /**
291 * Debug flags that can be overridden using "adb shell setprop <key>"
292 * Note: These flags are cached. To refresh, run "adb shell ime refresh_debug_properties".
293 */
294 private static final class DebugFlags {
295 static final DebugFlag FLAG_OPTIMIZE_START_INPUT =
296 new DebugFlag("debug.optimize_startinput");
297 }
298
299
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800300 final Context mContext;
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -0800301 final Resources mRes;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302 final Handler mHandler;
satokd87c2592010-09-29 11:52:06 +0900303 final InputMethodSettings mSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 final SettingsObserver mSettingsObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800305 final IWindowManager mIWindowManager;
Seigo Nonaka7309b122015-08-17 18:34:13 -0700306 final WindowManagerInternal mWindowManagerInternal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800307 final HandlerCaller mCaller;
Dianne Hackborn119bbc32013-03-22 17:27:25 -0700308 final boolean mHasFeature;
Satoshi Kataoka5ade83b2012-09-26 22:59:41 +0900309 private InputMethodFileManager mFileManager;
satok01038492012-04-09 21:08:27 +0900310 private final HardKeyboardListener mHardKeyboardListener;
Yohei Yukawae63b5fa2014-09-19 13:14:55 +0900311 private final AppOpsManager mAppOpsManager;
Yohei Yukawaed4952a2016-02-17 07:57:25 -0800312 private final UserManager mUserManager;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314 // All known input methods. mMethodMap also serves as the global
315 // lock for this class.
Yohei Yukawab0377bb2015-08-10 21:06:30 -0700316 final ArrayList<InputMethodInfo> mMethodList = new ArrayList<>();
317 final HashMap<String, InputMethodInfo> mMethodMap = new HashMap<>();
satokf9f01002011-05-19 21:31:50 +0900318 private final LruCache<SuggestionSpan, InputMethodInfo> mSecureSuggestionSpans =
Yohei Yukawab0377bb2015-08-10 21:06:30 -0700319 new LruCache<>(SECURE_SUGGESTION_SPANS_MAX_SIZE);
Satoshi Kataokad787f692013-10-26 04:44:21 +0900320 private final InputMethodSubtypeSwitchingController mSwitchingController;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800321
Yohei Yukawae0733062017-02-09 22:49:35 -0800322 /**
323 * Tracks how many times {@link #mMethodMap} was updated.
324 */
325 @GuardedBy("mMethodMap")
326 private int mMethodMapUpdateCount = 0;
327
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -0700328 // Used to bring IME service up to visible adjustment while it is being shown.
329 final ServiceConnection mVisibleConnection = new ServiceConnection() {
330 @Override public void onServiceConnected(ComponentName name, IBinder service) {
331 }
332
333 @Override public void onServiceDisconnected(ComponentName name) {
334 }
335 };
336 boolean mVisibleBound = false;
337
satok7cfc0ed2011-06-20 21:29:36 +0900338 // Ongoing notification
Dianne Hackborn661cd522011-08-22 00:26:20 -0700339 private NotificationManager mNotificationManager;
340 private KeyguardManager mKeyguardManager;
Griff Hazen6090c262016-03-25 08:11:24 -0700341 private @Nullable StatusBarManagerService mStatusBar;
Chris Wren1ce4b6d2015-06-11 10:19:43 -0400342 private Notification.Builder mImeSwitcherNotification;
Dianne Hackborn661cd522011-08-22 00:26:20 -0700343 private PendingIntent mImeSwitchPendingIntent;
satokb858c732011-07-22 19:54:34 +0900344 private boolean mShowOngoingImeSwitcherForPhones;
satok7cfc0ed2011-06-20 21:29:36 +0900345 private boolean mNotificationShown;
346
Tadashi G. Takaoka8c6d4772014-08-05 15:29:17 +0900347 static class SessionState {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800348 final ClientState client;
349 final IInputMethod method;
Jeff Brownc28867a2013-03-26 15:42:39 -0700350
351 IInputMethodSession session;
352 InputChannel channel;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800354 @Override
355 public String toString() {
356 return "SessionState{uid " + client.uid + " pid " + client.pid
357 + " method " + Integer.toHexString(
358 System.identityHashCode(method))
359 + " session " + Integer.toHexString(
360 System.identityHashCode(session))
Jeff Brownc28867a2013-03-26 15:42:39 -0700361 + " channel " + channel
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362 + "}";
363 }
364
365 SessionState(ClientState _client, IInputMethod _method,
Jeff Brownc28867a2013-03-26 15:42:39 -0700366 IInputMethodSession _session, InputChannel _channel) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367 client = _client;
368 method = _method;
369 session = _session;
Jeff Brownc28867a2013-03-26 15:42:39 -0700370 channel = _channel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371 }
372 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800373
Tarandeep Singh89a6c482017-11-21 14:26:11 -0800374 /**
375 * VR state callback.
376 * Listens for when VR mode finishes.
377 */
378 private final IVrStateCallbacks mVrStateCallbacks = new IVrStateCallbacks.Stub() {
379 @Override
380 public void onVrStateChanged(boolean enabled) {
381 if (!enabled) {
382 restoreNonVrImeFromSettingsNoCheck();
383 }
384 }
385 };
386
387 private void restoreNonVrImeFromSettingsNoCheck() {
388 // switch back to non-VR InputMethod from settings.
389 synchronized (mMethodMap) {
390 final String lastInputId = mSettings.getSelectedInputMethod();
391 setInputMethodLocked(lastInputId,
392 mSettings.getSelectedInputMethodSubtypeId(lastInputId));
393 }
394 }
395
Jeff Brownc28867a2013-03-26 15:42:39 -0700396 static final class ClientState {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800397 final IInputMethodClient client;
398 final IInputContext inputContext;
399 final int uid;
400 final int pid;
401 final InputBinding binding;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 boolean sessionRequested;
404 SessionState curSession;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800406 @Override
407 public String toString() {
408 return "ClientState{" + Integer.toHexString(
409 System.identityHashCode(this)) + " uid " + uid
410 + " pid " + pid + "}";
411 }
412
413 ClientState(IInputMethodClient _client, IInputContext _inputContext,
414 int _uid, int _pid) {
415 client = _client;
416 inputContext = _inputContext;
417 uid = _uid;
418 pid = _pid;
419 binding = new InputBinding(null, inputContext.asBinder(), uid, pid);
420 }
421 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800422
Yohei Yukawab0377bb2015-08-10 21:06:30 -0700423 final HashMap<IBinder, ClientState> mClients = new HashMap<>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 /**
Dianne Hackborna34f1ad2009-09-02 13:26:28 -0700426 * Set once the system is ready to run third party code.
427 */
428 boolean mSystemReady;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800429
Dianne Hackborna34f1ad2009-09-02 13:26:28 -0700430 /**
Yohei Yukawae13a20fa2015-09-30 19:11:32 -0700431 * Id obtained with {@link InputMethodInfo#getId()} for the currently selected input method.
432 * method. This is to be synchronized with the secure settings keyed with
433 * {@link Settings.Secure#DEFAULT_INPUT_METHOD}.
434 *
435 * <p>This can be transiently {@code null} when the system is re-initializing input method
436 * settings, e.g., the system locale is just changed.</p>
437 *
438 * <p>Note that {@link #mCurId} is used to track which IME is being connected to
439 * {@link InputMethodManagerService}.</p>
440 *
441 * @see #mCurId
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800442 */
Yohei Yukawae13a20fa2015-09-30 19:11:32 -0700443 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800444 String mCurMethodId;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800446 /**
447 * The current binding sequence number, incremented every time there is
448 * a new bind performed.
449 */
450 int mCurSeq;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 /**
453 * The client that is currently bound to an input method.
454 */
455 ClientState mCurClient;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800457 /**
Yohei Yukawae39d4ed2015-11-19 03:38:49 -0800458 * The last window token that we confirmed to be focused. This is always updated upon reports
459 * from the input method client. If the window state is already changed before the report is
460 * handled, this field just keeps the last value.
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700461 */
462 IBinder mCurFocusedWindow;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800463
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700464 /**
Yohei Yukawa22a89232017-02-12 16:38:59 -0800465 * {@link WindowManager.LayoutParams#softInputMode} of {@link #mCurFocusedWindow}.
466 *
467 * @see #mCurFocusedWindow
468 */
469 int mCurFocusedWindowSoftInputMode;
470
471 /**
Tarandeep Singheb570612018-01-29 16:20:32 -0800472 * The client by which {@link #mCurFocusedWindow} was reported.
Yohei Yukawae39d4ed2015-11-19 03:38:49 -0800473 */
474 ClientState mCurFocusedWindowClient;
475
476 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 * The input context last provided by the current client.
478 */
479 IInputContext mCurInputContext;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800481 /**
Yohei Yukawa19a80a12016-03-14 22:57:37 -0700482 * The missing method flags for the input context last provided by the current client.
483 *
484 * @see android.view.inputmethod.InputConnectionInspector.MissingMethodFlags
485 */
486 int mCurInputContextMissingMethods;
487
488 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 * The attributes last provided by the current client.
490 */
491 EditorInfo mCurAttribute;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493 /**
Yohei Yukawae13a20fa2015-09-30 19:11:32 -0700494 * Id obtained with {@link InputMethodInfo#getId()} for the input method that we are currently
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495 * connected to or in the process of connecting to.
Yohei Yukawae13a20fa2015-09-30 19:11:32 -0700496 *
497 * <p>This can be {@code null} when no input method is connected.</p>
498 *
499 * @see #mCurMethodId
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800500 */
Yohei Yukawae13a20fa2015-09-30 19:11:32 -0700501 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800502 String mCurId;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 /**
satokab751aa2010-09-14 19:17:36 +0900505 * The current subtype of the current input method.
506 */
507 private InputMethodSubtype mCurrentSubtype;
508
satok4e4569d2010-11-19 18:45:53 +0900509 // This list contains the pairs of InputMethodInfo and InputMethodSubtype.
satokf3db1af2010-11-23 13:34:33 +0900510 private final HashMap<InputMethodInfo, ArrayList<InputMethodSubtype>>
Yohei Yukawab0377bb2015-08-10 21:06:30 -0700511 mShortcutInputMethodsAndSubtypes = new HashMap<>();
satokab751aa2010-09-14 19:17:36 +0900512
John Spurlocke0980502013-10-25 11:59:29 -0400513 // Was the keyguard locked when this client became current?
514 private boolean mCurClientInKeyguard;
515
satokab751aa2010-09-14 19:17:36 +0900516 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 * Set to true if our ServiceConnection is currently actively bound to
518 * a service (whether or not we have gotten its IBinder back yet).
519 */
520 boolean mHaveConnection;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 /**
523 * Set if the client has asked for the input method to be shown.
524 */
525 boolean mShowRequested;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527 /**
528 * Set if we were explicitly told to show the input method.
529 */
530 boolean mShowExplicitlyRequested;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532 /**
533 * Set if we were forced to be shown.
534 */
535 boolean mShowForced;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800537 /**
538 * Set if we last told the input method to show itself.
539 */
540 boolean mInputShown;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542 /**
Yohei Yukawa2bc66172017-02-08 11:13:25 -0800543 * {@code true} if the current input method is in fullscreen mode.
544 */
545 boolean mInFullscreenMode;
546
547 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800548 * The Intent used to connect to the current input method.
549 */
550 Intent mCurIntent;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 /**
553 * The token we have made for the currently active input method, to
554 * identify it in the future.
555 */
556 IBinder mCurToken;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558 /**
559 * If non-null, this is the input method service we are currently connected
560 * to.
561 */
562 IInputMethod mCurMethod;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 /**
565 * Time that we last initiated a bind to the input method, to determine
566 * if we should try to disconnect and reconnect to it.
567 */
568 long mLastBindTime;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570 /**
571 * Have we called mCurMethod.bindInput()?
572 */
573 boolean mBoundToMethod;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 /**
576 * Currently enabled session. Only touched by service thread, not
577 * protected by a lock.
578 */
579 SessionState mEnabledSession;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 /**
Yohei Yukawafa6e0a82015-07-23 15:08:59 -0700582 * True if the device is currently interactive with user. The value is true initially.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 */
Yohei Yukawafa6e0a82015-07-23 15:08:59 -0700584 boolean mIsInteractive = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800585
Yohei Yukawa3d1e8122014-06-06 19:12:47 +0900586 int mCurUserActionNotificationSequenceNumber = 0;
587
Joe Onorato857fd9b2011-01-27 15:08:35 -0800588 int mBackDisposition = InputMethodService.BACK_DISPOSITION_DEFAULT;
Seigo Nonakad9eb9112015-05-26 20:54:43 +0900589
590 /**
591 * A set of status bits regarding the active IME.
592 *
593 * <p>This value is a combination of following two bits:</p>
594 * <dl>
595 * <dt>{@link InputMethodService#IME_ACTIVE}</dt>
596 * <dd>
597 * If this bit is ON, connected IME is ready to accept touch/key events.
598 * </dd>
599 * <dt>{@link InputMethodService#IME_VISIBLE}</dt>
600 * <dd>
601 * If this bit is ON, some of IME view, e.g. software input, candidate view, is visible.
602 * </dd>
603 * </dl>
604 * <em>Do not update this value outside of setImeWindowStatus.</em>
605 */
Joe Onorato857fd9b2011-01-27 15:08:35 -0800606 int mImeWindowVis;
607
Ken Wakasa05dbb652011-08-22 15:22:43 +0900608 private AlertDialog.Builder mDialogBuilder;
609 private AlertDialog mSwitchingDialog;
Wale Ogunwale3a931692016-11-02 16:49:48 -0700610 private IBinder mSwitchingDialogToken = new Binder();
satok01038492012-04-09 21:08:27 +0900611 private View mSwitchingDialogTitleView;
Yohei Yukawaebda7d72016-04-02 17:39:23 -0700612 private Toast mSubtypeSwitchedByShortCutToast;
Ken Wakasa05dbb652011-08-22 15:22:43 +0900613 private InputMethodInfo[] mIms;
614 private int[] mSubtypeIds;
Yohei Yukawae985c242016-02-24 18:27:04 -0800615 private LocaleList mLastSystemLocales;
Michael Wright7b5a96b2014-08-09 19:28:42 -0700616 private boolean mShowImeWithHardKeyboard;
Anna Galusza9b278112016-01-04 11:37:37 -0800617 private boolean mAccessibilityRequestingNoSoftKeyboard;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +0900618 private final MyPackageMonitor mMyPackageMonitor = new MyPackageMonitor();
619 private final IPackageManager mIPackageManager;
Jason Monk3e189872016-01-12 09:10:34 -0500620 private final String mSlotIme;
Yohei Yukawafa0e47e2016-04-05 09:55:56 -0700621 @HardKeyboardBehavior
622 private final int mHardKeyboardBehavior;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800623
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800624 /**
625 * Internal state snapshot when {@link #MSG_START_INPUT} message is about to be posted to the
626 * internal message queue. Any subsequent state change inside {@link InputMethodManagerService}
627 * will not affect those tasks that are already posted.
628 *
629 * <p>Posting {@link #MSG_START_INPUT} message basically means that
630 * {@link InputMethodService#doStartInput(InputConnection, EditorInfo, boolean)} will be called
631 * back in the current IME process shortly, which will also affect what the current IME starts
632 * receiving from {@link InputMethodService#getCurrentInputConnection()}. In other words, this
633 * snapshot will be taken every time when {@link InputMethodManagerService} is initiating a new
634 * logical input session between the client application and the current IME.</p>
635 *
636 * <p>Be careful to not keep strong references to this object forever, which can prevent
637 * {@link StartInputInfo#mImeToken} and {@link StartInputInfo#mTargetWindow} from being GC-ed.
638 * </p>
639 */
640 private static class StartInputInfo {
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800641 private static final AtomicInteger sSequenceNumber = new AtomicInteger(0);
642
643 final int mSequenceNumber;
644 final long mTimestamp;
645 final long mWallTime;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800646 @NonNull
647 final IBinder mImeToken;
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800648 @NonNull
649 final String mImeId;
650 // @InputMethodClient.StartInputReason
651 final int mStartInputReason;
652 final boolean mRestarting;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800653 @Nullable
654 final IBinder mTargetWindow;
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800655 @NonNull
656 final EditorInfo mEditorInfo;
657 final int mTargetWindowSoftInputMode;
658 final int mClientBindSequenceNumber;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800659
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800660 StartInputInfo(@NonNull IBinder imeToken, @NonNull String imeId,
661 /* @InputMethodClient.StartInputReason */ int startInputReason, boolean restarting,
662 @Nullable IBinder targetWindow, @NonNull EditorInfo editorInfo,
663 int targetWindowSoftInputMode, int clientBindSequenceNumber) {
664 mSequenceNumber = sSequenceNumber.getAndIncrement();
665 mTimestamp = SystemClock.uptimeMillis();
666 mWallTime = System.currentTimeMillis();
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800667 mImeToken = imeToken;
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800668 mImeId = imeId;
669 mStartInputReason = startInputReason;
670 mRestarting = restarting;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800671 mTargetWindow = targetWindow;
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800672 mEditorInfo = editorInfo;
673 mTargetWindowSoftInputMode = targetWindowSoftInputMode;
674 mClientBindSequenceNumber = clientBindSequenceNumber;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800675 }
676 }
677
Yohei Yukawab37d8bd2017-02-13 18:29:05 -0800678 @GuardedBy("mMethodMap")
679 private final WeakHashMap<IBinder, StartInputInfo> mStartInputMap = new WeakHashMap<>();
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800680
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800681 /**
682 * A ring buffer to store the history of {@link StartInputInfo}.
683 */
684 private static final class StartInputHistory {
685 /**
686 * Entry size for non low-RAM devices.
687 *
688 * <p>TODO: Consider to follow what other system services have been doing to manage
689 * constants (e.g. {@link android.provider.Settings.Global#ACTIVITY_MANAGER_CONSTANTS}).</p>
690 */
691 private final static int ENTRY_SIZE_FOR_HIGH_RAM_DEVICE = 16;
692
693 /**
694 * Entry size for non low-RAM devices.
695 *
696 * <p>TODO: Consider to follow what other system services have been doing to manage
697 * constants (e.g. {@link android.provider.Settings.Global#ACTIVITY_MANAGER_CONSTANTS}).</p>
698 */
699 private final static int ENTRY_SIZE_FOR_LOW_RAM_DEVICE = 5;
700
701 private static int getEntrySize() {
702 if (ActivityManager.isLowRamDeviceStatic()) {
703 return ENTRY_SIZE_FOR_LOW_RAM_DEVICE;
704 } else {
705 return ENTRY_SIZE_FOR_HIGH_RAM_DEVICE;
706 }
707 }
708
709 /**
710 * Backing store for the ring bugger.
711 */
712 private final Entry[] mEntries = new Entry[getEntrySize()];
713
714 /**
715 * An index of {@link #mEntries}, to which next {@link #addEntry(StartInputInfo)} should
716 * write.
717 */
718 private int mNextIndex = 0;
719
720 /**
721 * Recyclable entry to store the information in {@link StartInputInfo}.
722 */
723 private static final class Entry {
724 int mSequenceNumber;
725 long mTimestamp;
726 long mWallTime;
727 @NonNull
728 String mImeTokenString;
729 @NonNull
730 String mImeId;
731 /* @InputMethodClient.StartInputReason */
732 int mStartInputReason;
733 boolean mRestarting;
734 @NonNull
735 String mTargetWindowString;
736 @NonNull
737 EditorInfo mEditorInfo;
738 int mTargetWindowSoftInputMode;
739 int mClientBindSequenceNumber;
740
741 Entry(@NonNull StartInputInfo original) {
742 set(original);
743 }
744
745 void set(@NonNull StartInputInfo original) {
746 mSequenceNumber = original.mSequenceNumber;
747 mTimestamp = original.mTimestamp;
748 mWallTime = original.mWallTime;
749 // Intentionally convert to String so as not to keep a strong reference to a Binder
750 // object.
751 mImeTokenString = String.valueOf(original.mImeToken);
752 mImeId = original.mImeId;
753 mStartInputReason = original.mStartInputReason;
754 mRestarting = original.mRestarting;
755 // Intentionally convert to String so as not to keep a strong reference to a Binder
756 // object.
757 mTargetWindowString = String.valueOf(original.mTargetWindow);
758 mEditorInfo = original.mEditorInfo;
759 mTargetWindowSoftInputMode = original.mTargetWindowSoftInputMode;
760 mClientBindSequenceNumber = original.mClientBindSequenceNumber;
761 }
762 }
763
764 /**
765 * Add a new entry and discard the oldest entry as needed.
766 * @param info {@lin StartInputInfo} to be added.
767 */
768 void addEntry(@NonNull StartInputInfo info) {
769 final int index = mNextIndex;
770 if (mEntries[index] == null) {
771 mEntries[index] = new Entry(info);
772 } else {
773 mEntries[index].set(info);
774 }
775 mNextIndex = (mNextIndex + 1) % mEntries.length;
776 }
777
778 void dump(@NonNull PrintWriter pw, @NonNull String prefix) {
779 final SimpleDateFormat dataFormat =
780 new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US);
781
782 for (int i = 0; i < mEntries.length; ++i) {
783 final Entry entry = mEntries[(i + mNextIndex) % mEntries.length];
784 if (entry == null) {
785 continue;
786 }
787 pw.print(prefix);
788 pw.println("StartInput #" + entry.mSequenceNumber + ":");
789
790 pw.print(prefix);
791 pw.println(" time=" + dataFormat.format(new Date(entry.mWallTime))
792 + " (timestamp=" + entry.mTimestamp + ")"
793 + " reason="
794 + InputMethodClient.getStartInputReason(entry.mStartInputReason)
795 + " restarting=" + entry.mRestarting);
796
797 pw.print(prefix);
798 pw.println(" imeToken=" + entry.mImeTokenString + " [" + entry.mImeId + "]");
799
800 pw.print(prefix);
801 pw.println(" targetWin=" + entry.mTargetWindowString
802 + " [" + entry.mEditorInfo.packageName + "]"
803 + " clientBindSeq=" + entry.mClientBindSequenceNumber);
804
805 pw.print(prefix);
806 pw.println(" softInputMode=" + InputMethodClient.softInputModeToString(
807 entry.mTargetWindowSoftInputMode));
808
809 pw.print(prefix);
810 pw.println(" inputType=0x" + Integer.toHexString(entry.mEditorInfo.inputType)
811 + " imeOptions=0x" + Integer.toHexString(entry.mEditorInfo.imeOptions)
812 + " fieldId=0x" + Integer.toHexString(entry.mEditorInfo.fieldId)
813 + " fieldName=" + entry.mEditorInfo.fieldName
814 + " actionId=" + entry.mEditorInfo.actionId
815 + " actionLabel=" + entry.mEditorInfo.actionLabel);
816 }
817 }
818 }
819
820 @GuardedBy("mMethodMap")
821 @NonNull
822 private final StartInputHistory mStartInputHistory = new StartInputHistory();
823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 class SettingsObserver extends ContentObserver {
Yohei Yukawa81482972015-06-04 00:58:59 -0700825 int mUserId;
826 boolean mRegistered = false;
Yohei Yukawa7b574cb2016-03-16 17:22:22 -0700827 @NonNull
Dianne Hackbornfd7aded2013-01-22 17:10:23 -0800828 String mLastEnabled = "";
829
Yohei Yukawa81482972015-06-04 00:58:59 -0700830 /**
831 * <em>This constructor must be called within the lock.</em>
832 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 SettingsObserver(Handler handler) {
834 super(handler);
Yohei Yukawa81482972015-06-04 00:58:59 -0700835 }
836
Yohei Yukawa7b18aec2016-03-07 13:04:32 -0800837 public void registerContentObserverLocked(@UserIdInt int userId) {
Yohei Yukawa81482972015-06-04 00:58:59 -0700838 if (mRegistered && mUserId == userId) {
839 return;
840 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 ContentResolver resolver = mContext.getContentResolver();
Yohei Yukawa81482972015-06-04 00:58:59 -0700842 if (mRegistered) {
843 mContext.getContentResolver().unregisterContentObserver(this);
844 mRegistered = false;
845 }
846 if (mUserId != userId) {
847 mLastEnabled = "";
848 mUserId = userId;
849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 resolver.registerContentObserver(Settings.Secure.getUriFor(
Yohei Yukawa81482972015-06-04 00:58:59 -0700851 Settings.Secure.DEFAULT_INPUT_METHOD), false, this, userId);
satokab751aa2010-09-14 19:17:36 +0900852 resolver.registerContentObserver(Settings.Secure.getUriFor(
Yohei Yukawa81482972015-06-04 00:58:59 -0700853 Settings.Secure.ENABLED_INPUT_METHODS), false, this, userId);
satokb6109bb2011-02-03 22:24:54 +0900854 resolver.registerContentObserver(Settings.Secure.getUriFor(
Yohei Yukawa81482972015-06-04 00:58:59 -0700855 Settings.Secure.SELECTED_INPUT_METHOD_SUBTYPE), false, this, userId);
Michael Wright7b5a96b2014-08-09 19:28:42 -0700856 resolver.registerContentObserver(Settings.Secure.getUriFor(
Yohei Yukawa81482972015-06-04 00:58:59 -0700857 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD), false, this, userId);
Anna Galusza9b278112016-01-04 11:37:37 -0800858 resolver.registerContentObserver(Settings.Secure.getUriFor(
859 Settings.Secure.ACCESSIBILITY_SOFT_KEYBOARD_MODE), false, this, userId);
Yohei Yukawa81482972015-06-04 00:58:59 -0700860 mRegistered = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800862
Michael Wright7b5a96b2014-08-09 19:28:42 -0700863 @Override public void onChange(boolean selfChange, Uri uri) {
Anna Galusza9b278112016-01-04 11:37:37 -0800864 final Uri showImeUri = Settings.Secure.getUriFor(
865 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
866 final Uri accessibilityRequestingNoImeUri = Settings.Secure.getUriFor(
867 Settings.Secure.ACCESSIBILITY_SOFT_KEYBOARD_MODE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 synchronized (mMethodMap) {
Michael Wright7b5a96b2014-08-09 19:28:42 -0700869 if (showImeUri.equals(uri)) {
870 updateKeyboardFromSettingsLocked();
Anna Galusza9b278112016-01-04 11:37:37 -0800871 } else if (accessibilityRequestingNoImeUri.equals(uri)) {
872 mAccessibilityRequestingNoSoftKeyboard = Settings.Secure.getIntForUser(
873 mContext.getContentResolver(),
874 Settings.Secure.ACCESSIBILITY_SOFT_KEYBOARD_MODE,
875 0, mUserId) == 1;
876 if (mAccessibilityRequestingNoSoftKeyboard) {
877 final boolean showRequested = mShowRequested;
878 hideCurrentInputLocked(0, null);
879 mShowRequested = showRequested;
880 } else if (mShowRequested) {
881 showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
882 }
Michael Wright7b5a96b2014-08-09 19:28:42 -0700883 } else {
884 boolean enabledChanged = false;
885 String newEnabled = mSettings.getEnabledInputMethodsStr();
886 if (!mLastEnabled.equals(newEnabled)) {
887 mLastEnabled = newEnabled;
888 enabledChanged = true;
889 }
890 updateInputMethodsFromSettingsLocked(enabledChanged);
Dianne Hackbornfd7aded2013-01-22 17:10:23 -0800891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 }
893 }
Yohei Yukawa81482972015-06-04 00:58:59 -0700894
895 @Override
896 public String toString() {
897 return "SettingsObserver{mUserId=" + mUserId + " mRegistered=" + mRegistered
898 + " mLastEnabled=" + mLastEnabled + "}";
899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800901
Yohei Yukawa79247822017-01-23 15:26:15 -0800902 class ImmsBroadcastReceiver extends BroadcastReceiver {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +0900903 @Override
904 public void onReceive(Context context, Intent intent) {
905 final String action = intent.getAction();
Yohei Yukawafa6e0a82015-07-23 15:08:59 -0700906 if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +0900907 hideInputMethodMenu();
Yohei Yukawafa6e0a82015-07-23 15:08:59 -0700908 // No need to update mIsInteractive
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +0900909 return;
Amith Yamasani734983f2014-03-04 16:48:05 -0800910 } else if (Intent.ACTION_USER_ADDED.equals(action)
911 || Intent.ACTION_USER_REMOVED.equals(action)) {
Kenny Guy2a764942014-04-02 13:29:20 +0100912 updateCurrentProfileIds();
Amith Yamasani734983f2014-03-04 16:48:05 -0800913 return;
Christopher Tate7b9a28c2015-03-18 13:06:16 -0700914 } else if (Intent.ACTION_SETTING_RESTORED.equals(action)) {
915 final String name = intent.getStringExtra(Intent.EXTRA_SETTING_NAME);
916 if (Settings.Secure.ENABLED_INPUT_METHODS.equals(name)) {
917 final String prevValue = intent.getStringExtra(
918 Intent.EXTRA_SETTING_PREVIOUS_VALUE);
919 final String newValue = intent.getStringExtra(
920 Intent.EXTRA_SETTING_NEW_VALUE);
921 restoreEnabledInputMethods(mContext, prevValue, newValue);
922 }
Yohei Yukawa79247822017-01-23 15:26:15 -0800923 } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Yohei Yukawa0d7aff82017-02-10 00:40:51 -0800924 onActionLocaleChanged();
Tadashi G. Takaoka01065a52017-07-19 14:10:24 +0900925 } else if (ACTION_SHOW_INPUT_METHOD_PICKER.equals(action)) {
926 // ACTION_SHOW_INPUT_METHOD_PICKER action is a protected-broadcast and it is
927 // guaranteed to be send only from the system, so that there is no need for extra
928 // security check such as
929 // {@link #canShowInputMethodPickerLocked(IInputMethodClient)}.
930 mHandler.obtainMessage(
931 MSG_SHOW_IM_SUBTYPE_PICKER,
932 InputMethodManager.SHOW_IM_PICKER_MODE_INCLUDE_AUXILIARY_SUBTYPES,
933 0 /* arg2 */)
934 .sendToTarget();
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +0900935 } else {
936 Slog.w(TAG, "Unexpected intent " + intent);
937 }
938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800940
Yohei Yukawa0d7aff82017-02-10 00:40:51 -0800941 /**
Tarandeep Singh89a6c482017-11-21 14:26:11 -0800942 * Start a VR InputMethod that matches IME with package name of {@param component}.
Yohei Yukawa7a46c282017-12-10 18:15:19 -0800943 * Note: This method is called from {@link android.app.VrManager}.
Tarandeep Singh89a6c482017-11-21 14:26:11 -0800944 */
945 private void startVrInputMethodNoCheck(@Nullable ComponentName component) {
946 if (component == null) {
947 // clear the current VR-only IME (if any) and restore normal IME.
948 restoreNonVrImeFromSettingsNoCheck();
949 return;
950 }
951
952 synchronized (mMethodMap) {
953 String packageName = component.getPackageName();
954 for (InputMethodInfo info : mMethodList) {
955 if (TextUtils.equals(info.getPackageName(), packageName) && info.isVrOnly()) {
956 // set this is as current inputMethod without updating settings.
Yohei Yukawa7a46c282017-12-10 18:15:19 -0800957 setInputMethodEnabledLocked(info.getId(), true);
Tarandeep Singh89a6c482017-11-21 14:26:11 -0800958 setInputMethodLocked(info.getId(), NOT_A_SUBTYPE_ID);
959 break;
960 }
961 }
962 }
963 }
964
965 /**
Yohei Yukawa0d7aff82017-02-10 00:40:51 -0800966 * Handles {@link Intent#ACTION_LOCALE_CHANGED}.
967 *
968 * <p>Note: For historical reasons, {@link Intent#ACTION_LOCALE_CHANGED} has been sent to all
969 * the users. We should ignore this event if this is about any background user's locale.</p>
970 *
971 * <p>Caution: This method must not be called when system is not ready.</p>
972 */
973 void onActionLocaleChanged() {
974 synchronized (mMethodMap) {
975 final LocaleList possibleNewLocale = mRes.getConfiguration().getLocales();
976 if (possibleNewLocale != null && possibleNewLocale.equals(mLastSystemLocales)) {
977 return;
978 }
979 buildInputMethodListLocked(true);
980 // If the locale is changed, needs to reset the default ime
981 resetDefaultImeLocked(mContext);
982 updateFromSettingsLocked(true);
983 mLastSystemLocales = possibleNewLocale;
984 }
985 }
986
Christopher Tate7b9a28c2015-03-18 13:06:16 -0700987 // Apply the results of a restore operation to the set of enabled IMEs. Note that this
988 // does not attempt to validate on the fly with any installed device policy, so must only
989 // be run in the context of initial device setup.
990 //
991 // TODO: Move this method to InputMethodUtils with adding unit tests.
992 static void restoreEnabledInputMethods(Context context, String prevValue, String newValue) {
993 if (DEBUG_RESTORE) {
994 Slog.i(TAG, "Restoring enabled input methods:");
995 Slog.i(TAG, "prev=" + prevValue);
996 Slog.i(TAG, " new=" + newValue);
997 }
998 // 'new' is the just-restored state, 'prev' is what was in settings prior to the restore
Seigo Nonaka2028dda2015-07-06 17:41:24 +0900999 ArrayMap<String, ArraySet<String>> prevMap =
1000 InputMethodUtils.parseInputMethodsAndSubtypesString(prevValue);
1001 ArrayMap<String, ArraySet<String>> newMap =
1002 InputMethodUtils.parseInputMethodsAndSubtypesString(newValue);
Christopher Tate7b9a28c2015-03-18 13:06:16 -07001003
1004 // Merge the restored ime+subtype enabled states into the live state
1005 for (ArrayMap.Entry<String, ArraySet<String>> entry : newMap.entrySet()) {
1006 final String imeId = entry.getKey();
1007 ArraySet<String> prevSubtypes = prevMap.get(imeId);
1008 if (prevSubtypes == null) {
Yohei Yukawab0377bb2015-08-10 21:06:30 -07001009 prevSubtypes = new ArraySet<>(2);
Christopher Tate7b9a28c2015-03-18 13:06:16 -07001010 prevMap.put(imeId, prevSubtypes);
1011 }
1012 prevSubtypes.addAll(entry.getValue());
1013 }
1014
Seigo Nonaka2a099bc2015-08-14 19:29:45 -07001015 final String mergedImesAndSubtypesString =
1016 InputMethodUtils.buildInputMethodsAndSubtypesString(prevMap);
Christopher Tate7b9a28c2015-03-18 13:06:16 -07001017 if (DEBUG_RESTORE) {
1018 Slog.i(TAG, "Merged IME string:");
1019 Slog.i(TAG, " " + mergedImesAndSubtypesString);
1020 }
1021 Settings.Secure.putString(context.getContentResolver(),
1022 Settings.Secure.ENABLED_INPUT_METHODS, mergedImesAndSubtypesString);
1023 }
1024
Yohei Yukawac4e44912017-02-09 19:30:22 -08001025 final class MyPackageMonitor extends PackageMonitor {
1026 /**
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08001027 * Package names that are known to contain {@link InputMethodService}.
Yohei Yukawac4e44912017-02-09 19:30:22 -08001028 *
1029 * <p>No need to include packages because of direct-boot unaware IMEs since we always rescan
1030 * all the packages when the user is unlocked, and direct-boot awareness will not be changed
1031 * dynamically unless the entire package is updated, which also always triggers package
1032 * rescanning.</p>
1033 */
1034 @GuardedBy("mMethodMap")
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08001035 final private ArraySet<String> mKnownImePackageNames = new ArraySet<>();
1036
1037 /**
1038 * Packages that are appeared, disappeared, or modified for whatever reason.
1039 *
1040 * <p>Note: For now we intentionally use {@link ArrayList} instead of {@link ArraySet}
1041 * because 1) the number of elements is almost always 1 or so, and 2) we do not care
1042 * duplicate elements for our use case.</p>
1043 *
1044 * <p>This object must be accessed only from callback methods in {@link PackageMonitor},
1045 * which should be bound to {@link #getRegisteredHandler()}.</p>
1046 */
1047 private final ArrayList<String> mChangedPackages = new ArrayList<>();
1048
1049 /**
1050 * {@code true} if one or more packages that contain {@link InputMethodService} appeared.
1051 *
1052 * <p>This field must be accessed only from callback methods in {@link PackageMonitor},
1053 * which should be bound to {@link #getRegisteredHandler()}.</p>
1054 */
1055 private boolean mImePackageAppeared = false;
Yohei Yukawac4e44912017-02-09 19:30:22 -08001056
1057 @GuardedBy("mMethodMap")
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08001058 void clearKnownImePackageNamesLocked() {
1059 mKnownImePackageNames.clear();
Yohei Yukawac4e44912017-02-09 19:30:22 -08001060 }
1061
1062 @GuardedBy("mMethodMap")
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08001063 final void addKnownImePackageNameLocked(@NonNull String packageName) {
1064 mKnownImePackageNames.add(packageName);
Yohei Yukawac4e44912017-02-09 19:30:22 -08001065 }
1066
Yohei Yukawa278f2ab2017-02-14 19:51:33 -08001067 @GuardedBy("mMethodMap")
1068 private boolean isChangingPackagesOfCurrentUserLocked() {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001069 final int userId = getChangingUserId();
1070 final boolean retval = userId == mSettings.getCurrentUserId();
1071 if (DEBUG) {
satok81f8b7c2012-12-04 20:42:56 +09001072 if (!retval) {
1073 Slog.d(TAG, "--- ignore this call back from a background user: " + userId);
1074 }
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001075 }
1076 return retval;
1077 }
1078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 @Override
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001080 public boolean onHandleForceStop(Intent intent, String[] packages, int uid, boolean doit) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 synchronized (mMethodMap) {
Yohei Yukawa278f2ab2017-02-14 19:51:33 -08001082 if (!isChangingPackagesOfCurrentUserLocked()) {
1083 return false;
1084 }
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001085 String curInputMethodId = mSettings.getSelectedInputMethod();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 final int N = mMethodList.size();
1087 if (curInputMethodId != null) {
1088 for (int i=0; i<N; i++) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001089 InputMethodInfo imi = mMethodList.get(i);
1090 if (imi.getId().equals(curInputMethodId)) {
1091 for (String pkg : packages) {
1092 if (imi.getPackageName().equals(pkg)) {
1093 if (!doit) {
1094 return true;
1095 }
satok723a27e2010-11-11 14:58:11 +09001096 resetSelectedInputMethodAndSubtypeLocked("");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001097 chooseNewDefaultIMELocked();
1098 return true;
1099 }
1100 }
1101 }
1102 }
1103 }
1104 }
1105 return false;
1106 }
1107
1108 @Override
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08001109 public void onBeginPackageChanges() {
1110 clearPackageChangeState();
1111 }
1112
1113 @Override
1114 public void onPackageAppeared(String packageName, int reason) {
1115 if (!mImePackageAppeared) {
1116 final PackageManager pm = mContext.getPackageManager();
1117 final List<ResolveInfo> services = pm.queryIntentServicesAsUser(
1118 new Intent(InputMethod.SERVICE_INTERFACE).setPackage(packageName),
1119 PackageManager.MATCH_DISABLED_COMPONENTS, getChangingUserId());
1120 // No need to lock this because we access it only on getRegisteredHandler().
1121 if (!services.isEmpty()) {
1122 mImePackageAppeared = true;
1123 }
1124 }
1125 // No need to lock this because we access it only on getRegisteredHandler().
1126 mChangedPackages.add(packageName);
1127 }
1128
1129 @Override
1130 public void onPackageDisappeared(String packageName, int reason) {
1131 // No need to lock this because we access it only on getRegisteredHandler().
1132 mChangedPackages.add(packageName);
1133 }
1134
1135 @Override
1136 public void onPackageModified(String packageName) {
1137 // No need to lock this because we access it only on getRegisteredHandler().
1138 mChangedPackages.add(packageName);
1139 }
1140
1141 @Override
1142 public void onPackagesSuspended(String[] packages) {
1143 // No need to lock this because we access it only on getRegisteredHandler().
1144 for (String packageName : packages) {
1145 mChangedPackages.add(packageName);
Yohei Yukawac4e44912017-02-09 19:30:22 -08001146 }
1147 }
1148
1149 @Override
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08001150 public void onPackagesUnsuspended(String[] packages) {
1151 // No need to lock this because we access it only on getRegisteredHandler().
1152 for (String packageName : packages) {
1153 mChangedPackages.add(packageName);
1154 }
1155 }
1156
1157 @Override
1158 public void onFinishPackageChanges() {
1159 onFinishPackageChangesInternal();
1160 clearPackageChangeState();
1161 }
1162
1163 private void clearPackageChangeState() {
1164 // No need to lock them because we access these fields only on getRegisteredHandler().
1165 mChangedPackages.clear();
1166 mImePackageAppeared = false;
1167 }
1168
1169 private boolean shouldRebuildInputMethodListLocked() {
1170 // This method is guaranteed to be called only by getRegisteredHandler().
1171
1172 // If there is any new package that contains at least one IME, then rebuilt the list
1173 // of IMEs.
1174 if (mImePackageAppeared) {
1175 return true;
1176 }
1177
1178 // Otherwise, check if mKnownImePackageNames and mChangedPackages have any intersection.
1179 // TODO: Consider to create a utility method to do the following test. List.retainAll()
1180 // is an option, but it may still do some extra operations that we do not need here.
1181 final int N = mChangedPackages.size();
1182 for (int i = 0; i < N; ++i) {
1183 final String packageName = mChangedPackages.get(i);
1184 if (mKnownImePackageNames.contains(packageName)) {
1185 return true;
1186 }
1187 }
1188 return false;
1189 }
1190
1191 private void onFinishPackageChangesInternal() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001192 synchronized (mMethodMap) {
Yohei Yukawa278f2ab2017-02-14 19:51:33 -08001193 if (!isChangingPackagesOfCurrentUserLocked()) {
1194 return;
1195 }
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08001196 if (!shouldRebuildInputMethodListLocked()) {
1197 return;
1198 }
1199
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001200 InputMethodInfo curIm = null;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001201 String curInputMethodId = mSettings.getSelectedInputMethod();
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001202 final int N = mMethodList.size();
1203 if (curInputMethodId != null) {
1204 for (int i=0; i<N; i++) {
1205 InputMethodInfo imi = mMethodList.get(i);
satoke7c6998e2011-06-03 17:57:59 +09001206 final String imiId = imi.getId();
1207 if (imiId.equals(curInputMethodId)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001208 curIm = imi;
1209 }
satoke7c6998e2011-06-03 17:57:59 +09001210
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001211 int change = isPackageDisappearing(imi.getPackageName());
satoke7c6998e2011-06-03 17:57:59 +09001212 if (isPackageModified(imi.getPackageName())) {
1213 mFileManager.deleteAllInputMethodSubtypes(imiId);
1214 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001215 if (change == PACKAGE_TEMPORARY_CHANGE
1216 || change == PACKAGE_PERMANENT_CHANGE) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001217 Slog.i(TAG, "Input method uninstalled, disabling: "
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001218 + imi.getComponent());
1219 setInputMethodEnabledLocked(imi.getId(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 }
1221 }
1222 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001223
Yohei Yukawa94e33302016-02-12 19:37:03 -08001224 buildInputMethodListLocked(false /* resetDefaultEnabledIme */);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 boolean changed = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001227
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001228 if (curIm != null) {
Anna Galusza9b278112016-01-04 11:37:37 -08001229 int change = isPackageDisappearing(curIm.getPackageName());
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001230 if (change == PACKAGE_TEMPORARY_CHANGE
1231 || change == PACKAGE_PERMANENT_CHANGE) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001232 ServiceInfo si = null;
1233 try {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001234 si = mIPackageManager.getServiceInfo(
1235 curIm.getComponent(), 0, mSettings.getCurrentUserId());
1236 } catch (RemoteException ex) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001237 }
1238 if (si == null) {
1239 // Uh oh, current input method is no longer around!
1240 // Pick another one...
Joe Onorato8a9b2202010-02-26 18:56:32 -08001241 Slog.i(TAG, "Current input method removed: " + curInputMethodId);
Seigo Nonakad9eb9112015-05-26 20:54:43 +09001242 updateSystemUiLocked(mCurToken, 0 /* vis */, mBackDisposition);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001243 if (!chooseNewDefaultIMELocked()) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001244 changed = true;
1245 curIm = null;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001246 Slog.i(TAG, "Unsetting current input method");
satok723a27e2010-11-11 14:58:11 +09001247 resetSelectedInputMethodAndSubtypeLocked("");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001248 }
1249 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001250 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001251 }
satokab751aa2010-09-14 19:17:36 +09001252
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001253 if (curIm == null) {
1254 // We currently don't have a default input method... is
1255 // one now available?
1256 changed = chooseNewDefaultIMELocked();
Yohei Yukawa54d512c2015-05-19 22:15:02 -07001257 } else if (!changed && isPackageModified(curIm.getPackageName())) {
1258 // Even if the current input method is still available, mCurrentSubtype could
1259 // be obsolete when the package is modified in practice.
1260 changed = true;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001261 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001262
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001263 if (changed) {
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08001264 updateFromSettingsLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 }
1266 }
1267 }
1268 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001269
Jeff Brownc28867a2013-03-26 15:42:39 -07001270 private static final class MethodCallback extends IInputSessionCallback.Stub {
Jean Chalarde0d32a62011-10-20 20:36:07 +09001271 private final InputMethodManagerService mParentIMMS;
Jeff Brownc28867a2013-03-26 15:42:39 -07001272 private final IInputMethod mMethod;
1273 private final InputChannel mChannel;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001274
Jeff Brownc28867a2013-03-26 15:42:39 -07001275 MethodCallback(InputMethodManagerService imms, IInputMethod method,
1276 InputChannel channel) {
Jean Chalarde0d32a62011-10-20 20:36:07 +09001277 mParentIMMS = imms;
Jeff Brownc28867a2013-03-26 15:42:39 -07001278 mMethod = method;
1279 mChannel = channel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001281
satoke7c6998e2011-06-03 17:57:59 +09001282 @Override
Jeff Brownc28867a2013-03-26 15:42:39 -07001283 public void sessionCreated(IInputMethodSession session) {
Dianne Hackborn6b6b3fd2014-03-24 11:27:18 -07001284 long ident = Binder.clearCallingIdentity();
1285 try {
1286 mParentIMMS.onSessionCreated(mMethod, session, mChannel);
1287 } finally {
1288 Binder.restoreCallingIdentity(ident);
1289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 }
1291 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001292
satok01038492012-04-09 21:08:27 +09001293 private class HardKeyboardListener
Seigo Nonaka7309b122015-08-17 18:34:13 -07001294 implements WindowManagerInternal.OnHardKeyboardStatusChangeListener {
satok01038492012-04-09 21:08:27 +09001295 @Override
Michael Wright7b5a96b2014-08-09 19:28:42 -07001296 public void onHardKeyboardStatusChange(boolean available) {
1297 mHandler.sendMessage(mHandler.obtainMessage(MSG_HARD_KEYBOARD_SWITCH_CHANGED,
1298 available ? 1 : 0));
satok01038492012-04-09 21:08:27 +09001299 }
1300
Michael Wright7b5a96b2014-08-09 19:28:42 -07001301 public void handleHardKeyboardStatusChange(boolean available) {
satok01038492012-04-09 21:08:27 +09001302 if (DEBUG) {
Michael Wright7b5a96b2014-08-09 19:28:42 -07001303 Slog.w(TAG, "HardKeyboardStatusChanged: available=" + available);
satok01038492012-04-09 21:08:27 +09001304 }
1305 synchronized(mMethodMap) {
1306 if (mSwitchingDialog != null && mSwitchingDialogTitleView != null
1307 && mSwitchingDialog.isShowing()) {
1308 mSwitchingDialogTitleView.findViewById(
1309 com.android.internal.R.id.hard_keyboard_section).setVisibility(
1310 available ? View.VISIBLE : View.GONE);
1311 }
1312 }
1313 }
1314 }
1315
Fyodor Kupolov1e33dc82016-01-21 12:02:58 -08001316 public static final class Lifecycle extends SystemService {
1317 private InputMethodManagerService mService;
1318
1319 public Lifecycle(Context context) {
1320 super(context);
1321 mService = new InputMethodManagerService(context);
1322 }
1323
1324 @Override
1325 public void onStart() {
1326 LocalServices.addService(InputMethodManagerInternal.class,
1327 new LocalServiceImpl(mService.mHandler));
1328 publishBinderService(Context.INPUT_METHOD_SERVICE, mService);
1329 }
1330
1331 @Override
Yohei Yukawa7b18aec2016-03-07 13:04:32 -08001332 public void onSwitchUser(@UserIdInt int userHandle) {
Fyodor Kupolov7877b8a2016-06-29 14:39:19 -07001333 // Called on ActivityManager thread.
Yohei Yukawa7b18aec2016-03-07 13:04:32 -08001334 // TODO: Dispatch this to a worker thread as needed.
1335 mService.onSwitchUser(userHandle);
1336 }
1337
1338 @Override
Fyodor Kupolov1e33dc82016-01-21 12:02:58 -08001339 public void onBootPhase(int phase) {
Fyodor Kupolov7877b8a2016-06-29 14:39:19 -07001340 // Called on ActivityManager thread.
Yohei Yukawa7b18aec2016-03-07 13:04:32 -08001341 // TODO: Dispatch this to a worker thread as needed.
Fyodor Kupolov1e33dc82016-01-21 12:02:58 -08001342 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
1343 StatusBarManagerService statusBarService = (StatusBarManagerService) ServiceManager
1344 .getService(Context.STATUS_BAR_SERVICE);
1345 mService.systemRunning(statusBarService);
1346 }
1347 }
Yohei Yukawaed4952a2016-02-17 07:57:25 -08001348
1349 @Override
Fyodor Kupolov7877b8a2016-06-29 14:39:19 -07001350 public void onUnlockUser(final @UserIdInt int userHandle) {
1351 // Called on ActivityManager thread.
1352 mService.mHandler.sendMessage(mService.mHandler.obtainMessage(MSG_SYSTEM_UNLOCK_USER,
Fyodor Kupolov0f57cce2016-09-09 10:36:30 -07001353 userHandle /* arg1 */, 0 /* arg2 */));
Yohei Yukawaed4952a2016-02-17 07:57:25 -08001354 }
1355 }
1356
Yohei Yukawa7b18aec2016-03-07 13:04:32 -08001357 void onUnlockUser(@UserIdInt int userId) {
Yohei Yukawaed4952a2016-02-17 07:57:25 -08001358 synchronized(mMethodMap) {
1359 final int currentUserId = mSettings.getCurrentUserId();
1360 if (DEBUG) {
1361 Slog.d(TAG, "onUnlockUser: userId=" + userId + " curUserId=" + currentUserId);
1362 }
1363 if (userId != currentUserId) {
1364 return;
1365 }
1366 mSettings.switchCurrentUser(currentUserId, !mSystemReady);
Yohei Yukawa79247822017-01-23 15:26:15 -08001367 if (mSystemReady) {
1368 // We need to rebuild IMEs.
1369 buildInputMethodListLocked(false /* resetDefaultEnabledIme */);
1370 updateInputMethodsFromSettingsLocked(true /* enabledChanged */);
1371 }
Yohei Yukawaed4952a2016-02-17 07:57:25 -08001372 }
Fyodor Kupolov1e33dc82016-01-21 12:02:58 -08001373 }
1374
Yohei Yukawa7b18aec2016-03-07 13:04:32 -08001375 void onSwitchUser(@UserIdInt int userId) {
1376 synchronized (mMethodMap) {
1377 switchUserLocked(userId);
1378 }
1379 }
1380
Seigo Nonaka7309b122015-08-17 18:34:13 -07001381 public InputMethodManagerService(Context context) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001382 mIPackageManager = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 mContext = context;
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -08001384 mRes = context.getResources();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 mHandler = new Handler(this);
Yohei Yukawa81482972015-06-04 00:58:59 -07001386 // Note: SettingsObserver doesn't register observers in its constructor.
1387 mSettingsObserver = new SettingsObserver(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 mIWindowManager = IWindowManager.Stub.asInterface(
1389 ServiceManager.getService(Context.WINDOW_SERVICE));
Seigo Nonaka7309b122015-08-17 18:34:13 -07001390 mWindowManagerInternal = LocalServices.getService(WindowManagerInternal.class);
Mita Yuned218c72012-12-06 17:18:25 -08001391 mCaller = new HandlerCaller(context, null, new HandlerCaller.Callback() {
satoke7c6998e2011-06-03 17:57:59 +09001392 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 public void executeMessage(Message msg) {
1394 handleMessage(msg);
1395 }
Mita Yuned218c72012-12-06 17:18:25 -08001396 }, true /*asyncHandler*/);
Yohei Yukawad34e1482016-02-11 08:03:52 -08001397 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Yohei Yukawaed4952a2016-02-17 07:57:25 -08001398 mUserManager = mContext.getSystemService(UserManager.class);
satok01038492012-04-09 21:08:27 +09001399 mHardKeyboardListener = new HardKeyboardListener();
Dianne Hackborn119bbc32013-03-22 17:27:25 -07001400 mHasFeature = context.getPackageManager().hasSystemFeature(
1401 PackageManager.FEATURE_INPUT_METHODS);
Jason Monk3e189872016-01-12 09:10:34 -05001402 mSlotIme = mContext.getString(com.android.internal.R.string.status_bar_ime);
Yohei Yukawafa0e47e2016-04-05 09:55:56 -07001403 mHardKeyboardBehavior = mContext.getResources().getInteger(
1404 com.android.internal.R.integer.config_externalHardKeyboardBehavior);
satok7cfc0ed2011-06-20 21:29:36 +09001405
Chris Wren1ce4b6d2015-06-11 10:19:43 -04001406 Bundle extras = new Bundle();
1407 extras.putBoolean(Notification.EXTRA_ALLOW_DURING_SETUP, true);
Tadashi G. Takaoka01065a52017-07-19 14:10:24 +09001408 @ColorInt final int accentColor = mContext.getColor(
1409 com.android.internal.R.color.system_notification_accent_color);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001410 mImeSwitcherNotification =
1411 new Notification.Builder(mContext, SystemNotificationChannels.VIRTUAL_KEYBOARD)
1412 .setSmallIcon(com.android.internal.R.drawable.ic_notification_ime_default)
1413 .setWhen(0)
1414 .setOngoing(true)
1415 .addExtras(extras)
1416 .setCategory(Notification.CATEGORY_SYSTEM)
Tadashi G. Takaoka01065a52017-07-19 14:10:24 +09001417 .setColor(accentColor);
Daniel Sandler590d5152012-06-14 16:10:13 -04001418
Tadashi G. Takaoka01065a52017-07-19 14:10:24 +09001419 Intent intent = new Intent(ACTION_SHOW_INPUT_METHOD_PICKER)
1420 .setPackage(mContext.getPackageName());
satok683e2382011-07-12 08:28:52 +09001421 mImeSwitchPendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
satokb858c732011-07-22 19:54:34 +09001422
1423 mShowOngoingImeSwitcherForPhones = false;
satok7cfc0ed2011-06-20 21:29:36 +09001424
satok7cfc0ed2011-06-20 21:29:36 +09001425 mNotificationShown = false;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001426 int userId = 0;
1427 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001428 userId = ActivityManager.getService().getCurrentUser().id;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001429 } catch (RemoteException e) {
1430 Slog.w(TAG, "Couldn't get current user ID; guessing it's 0", e);
1431 }
satok913a8922010-08-26 21:53:41 +09001432
satokd87c2592010-09-29 11:52:06 +09001433 // mSettings should be created before buildInputMethodListLocked
satokdf31ae62011-01-15 06:19:44 +09001434 mSettings = new InputMethodSettings(
Yohei Yukawa68645a62016-02-17 07:54:20 -08001435 mRes, context.getContentResolver(), mMethodMap, mMethodList, userId, !mSystemReady);
Svet Ganovadc1cf42015-06-15 16:36:24 -07001436
Kenny Guy2a764942014-04-02 13:29:20 +01001437 updateCurrentProfileIds();
Satoshi Kataoka5ade83b2012-09-26 22:59:41 +09001438 mFileManager = new InputMethodFileManager(mMethodMap, userId);
Yohei Yukawa79247822017-01-23 15:26:15 -08001439 mSwitchingController = InputMethodSubtypeSwitchingController.createInstanceLocked(
1440 mSettings, context);
Tarandeep Singh89a6c482017-11-21 14:26:11 -08001441 // Register VR-state listener.
1442 IVrManager vrManager = (IVrManager) ServiceManager.getService(Context.VR_SERVICE);
1443 if (vrManager != null) {
1444 try {
1445 vrManager.registerListener(mVrStateCallbacks);
1446 } catch (RemoteException e) {
1447 Slog.e(TAG, "Failed to register VR mode state listener.");
1448 }
1449 }
satok5b927c432012-05-01 20:09:34 +09001450 }
1451
satok5b927c432012-05-01 20:09:34 +09001452 private void resetDefaultImeLocked(Context context) {
1453 // Do not reset the default (current) IME when it is a 3rd-party IME
Yohei Yukawac2393ac2016-02-18 00:30:45 -08001454 if (mCurMethodId != null && !InputMethodUtils.isSystemIme(mMethodMap.get(mCurMethodId))) {
satok5b927c432012-05-01 20:09:34 +09001455 return;
1456 }
Yohei Yukawac2393ac2016-02-18 00:30:45 -08001457 final List<InputMethodInfo> suitableImes = InputMethodUtils.getDefaultEnabledImes(
Yohei Yukawaaf5cee82017-01-23 16:17:11 -08001458 context, mSettings.getEnabledInputMethodListLocked());
Yohei Yukawac2393ac2016-02-18 00:30:45 -08001459 if (suitableImes.isEmpty()) {
1460 Slog.i(TAG, "No default found");
1461 return;
satok5b927c432012-05-01 20:09:34 +09001462 }
Yohei Yukawac2393ac2016-02-18 00:30:45 -08001463 final InputMethodInfo defIm = suitableImes.get(0);
Yohei Yukawad0332832017-02-01 13:59:43 -08001464 if (DEBUG) {
1465 Slog.i(TAG, "Default found, using " + defIm.getId());
1466 }
Yohei Yukawac2393ac2016-02-18 00:30:45 -08001467 setSelectedInputMethodAndSubtypeLocked(defIm, NOT_A_SUBTYPE_ID, false);
satok5b927c432012-05-01 20:09:34 +09001468 }
1469
Satoshi Kataoka5ade83b2012-09-26 22:59:41 +09001470 private void switchUserLocked(int newUserId) {
Yohei Yukawa90bf7082015-06-03 23:50:27 -07001471 if (DEBUG) Slog.d(TAG, "Switching user stage 1/3. newUserId=" + newUserId
1472 + " currentUserId=" + mSettings.getCurrentUserId());
1473
Yohei Yukawa81482972015-06-04 00:58:59 -07001474 // ContentObserver should be registered again when the user is changed
1475 mSettingsObserver.registerContentObserverLocked(newUserId);
Yohei Yukawa68645a62016-02-17 07:54:20 -08001476
Yohei Yukawaed4952a2016-02-17 07:57:25 -08001477 // If the system is not ready or the device is not yed unlocked by the user, then we use
1478 // copy-on-write settings.
1479 final boolean useCopyOnWriteSettings =
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001480 !mSystemReady || !mUserManager.isUserUnlockingOrUnlocked(newUserId);
Yohei Yukawa68645a62016-02-17 07:54:20 -08001481 mSettings.switchCurrentUser(newUserId, useCopyOnWriteSettings);
Kenny Guy2a764942014-04-02 13:29:20 +01001482 updateCurrentProfileIds();
Satoshi Kataoka5ade83b2012-09-26 22:59:41 +09001483 // InputMethodFileManager should be reset when the user is changed
1484 mFileManager = new InputMethodFileManager(mMethodMap, newUserId);
Satoshi Kataoka7f7535f2013-02-18 12:54:16 +09001485 final String defaultImiId = mSettings.getSelectedInputMethod();
Yohei Yukawa90bf7082015-06-03 23:50:27 -07001486
1487 if (DEBUG) Slog.d(TAG, "Switching user stage 2/3. newUserId=" + newUserId
1488 + " defaultImiId=" + defaultImiId);
1489
Satoshi Kataoka7c4a2a12013-02-25 15:25:43 +09001490 // For secondary users, the list of enabled IMEs may not have been updated since the
1491 // callbacks to PackageMonitor are ignored for the secondary user. Here, defaultImiId may
1492 // not be empty even if the IME has been uninstalled by the primary user.
1493 // Even in such cases, IMMS works fine because it will find the most applicable
1494 // IME for that user.
Satoshi Kataokaed1cdb22013-04-17 16:41:58 +09001495 final boolean initialUserSwitch = TextUtils.isEmpty(defaultImiId);
Yohei Yukawa0d7aff82017-02-10 00:40:51 -08001496 mLastSystemLocales = mRes.getConfiguration().getLocales();
1497
1498 // TODO: Is it really possible that switchUserLocked() happens before system ready?
1499 if (mSystemReady) {
1500 hideCurrentInputLocked(0, null);
1501 resetCurrentMethodAndClient(InputMethodClient.UNBIND_REASON_SWITCH_USER);
1502 buildInputMethodListLocked(initialUserSwitch);
1503 if (TextUtils.isEmpty(mSettings.getSelectedInputMethod())) {
1504 // This is the first time of the user switch and
1505 // set the current ime to the proper one.
1506 resetDefaultImeLocked(mContext);
1507 }
1508 updateFromSettingsLocked(true);
1509 try {
1510 startInputInnerLocked();
1511 } catch (RuntimeException e) {
1512 Slog.w(TAG, "Unexpected exception", e);
1513 }
1514 }
1515
Satoshi Kataokaed1cdb22013-04-17 16:41:58 +09001516 if (initialUserSwitch) {
Yohei Yukawa094c71f2015-06-20 00:41:31 -07001517 InputMethodUtils.setNonSelectedSystemImesDisabledUntilUsed(mIPackageManager,
1518 mSettings.getEnabledInputMethodListLocked(), newUserId,
1519 mContext.getBasePackageName());
Satoshi Kataokaed1cdb22013-04-17 16:41:58 +09001520 }
Yohei Yukawa90bf7082015-06-03 23:50:27 -07001521
1522 if (DEBUG) Slog.d(TAG, "Switching user stage 3/3. newUserId=" + newUserId
1523 + " selectedIme=" + mSettings.getSelectedInputMethod());
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001524 }
1525
Kenny Guy2a764942014-04-02 13:29:20 +01001526 void updateCurrentProfileIds() {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07001527 mSettings.setCurrentProfileIds(
1528 mUserManager.getProfileIdsWithDisabled(mSettings.getCurrentUserId()));
Amith Yamasani734983f2014-03-04 16:48:05 -08001529 }
1530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 @Override
1532 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1533 throws RemoteException {
1534 try {
1535 return super.onTransact(code, data, reply, flags);
1536 } catch (RuntimeException e) {
1537 // The input method manager only throws security exceptions, so let's
1538 // log all others.
1539 if (!(e instanceof SecurityException)) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07001540 Slog.wtf(TAG, "Input Method Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 }
1542 throw e;
1543 }
1544 }
1545
Svetoslav Ganova0027152013-06-25 14:59:53 -07001546 public void systemRunning(StatusBarManagerService statusBar) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001547 synchronized (mMethodMap) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001548 if (DEBUG) {
1549 Slog.d(TAG, "--- systemReady");
1550 }
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001551 if (!mSystemReady) {
1552 mSystemReady = true;
Yohei Yukawa79247822017-01-23 15:26:15 -08001553 mLastSystemLocales = mRes.getConfiguration().getLocales();
Yohei Yukawa68645a62016-02-17 07:54:20 -08001554 final int currentUserId = mSettings.getCurrentUserId();
Yohei Yukawaed4952a2016-02-17 07:57:25 -08001555 mSettings.switchCurrentUser(currentUserId,
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001556 !mUserManager.isUserUnlockingOrUnlocked(currentUserId));
Yohei Yukawad34e1482016-02-11 08:03:52 -08001557 mKeyguardManager = mContext.getSystemService(KeyguardManager.class);
1558 mNotificationManager = mContext.getSystemService(NotificationManager.class);
Dianne Hackborn661cd522011-08-22 00:26:20 -07001559 mStatusBar = statusBar;
Griff Hazen6090c262016-03-25 08:11:24 -07001560 if (mStatusBar != null) {
1561 mStatusBar.setIconVisibility(mSlotIme, false);
1562 }
Seigo Nonakad9eb9112015-05-26 20:54:43 +09001563 updateSystemUiLocked(mCurToken, mImeWindowVis, mBackDisposition);
satokb858c732011-07-22 19:54:34 +09001564 mShowOngoingImeSwitcherForPhones = mRes.getBoolean(
1565 com.android.internal.R.bool.show_ongoing_ime_switcher);
satok01038492012-04-09 21:08:27 +09001566 if (mShowOngoingImeSwitcherForPhones) {
Seigo Nonaka7309b122015-08-17 18:34:13 -07001567 mWindowManagerInternal.setOnHardKeyboardStatusChangeListener(
satok01038492012-04-09 21:08:27 +09001568 mHardKeyboardListener);
1569 }
Yohei Yukawa79247822017-01-23 15:26:15 -08001570
1571 mMyPackageMonitor.register(mContext, null, UserHandle.ALL, true);
1572 mSettingsObserver.registerContentObserverLocked(currentUserId);
1573
1574 final IntentFilter broadcastFilter = new IntentFilter();
1575 broadcastFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
1576 broadcastFilter.addAction(Intent.ACTION_USER_ADDED);
1577 broadcastFilter.addAction(Intent.ACTION_USER_REMOVED);
1578 broadcastFilter.addAction(Intent.ACTION_SETTING_RESTORED);
1579 broadcastFilter.addAction(Intent.ACTION_LOCALE_CHANGED);
Tadashi G. Takaoka01065a52017-07-19 14:10:24 +09001580 broadcastFilter.addAction(ACTION_SHOW_INPUT_METHOD_PICKER);
Yohei Yukawa79247822017-01-23 15:26:15 -08001581 mContext.registerReceiver(new ImmsBroadcastReceiver(), broadcastFilter);
1582
Yohei Yukawa1f9a3cb2017-10-26 15:00:59 -07001583 final String defaultImiId = mSettings.getSelectedInputMethod();
1584 final boolean imeSelectedOnBoot = !TextUtils.isEmpty(defaultImiId);
1585 buildInputMethodListLocked(!imeSelectedOnBoot /* resetDefaultEnabledIme */);
Yohei Yukawa79247822017-01-23 15:26:15 -08001586 resetDefaultImeLocked(mContext);
1587 updateFromSettingsLocked(true);
1588 InputMethodUtils.setNonSelectedSystemImesDisabledUntilUsed(mIPackageManager,
1589 mSettings.getEnabledInputMethodListLocked(), currentUserId,
1590 mContext.getBasePackageName());
1591
Dianne Hackborncc278702009-09-02 23:07:23 -07001592 try {
1593 startInputInnerLocked();
1594 } catch (RuntimeException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001595 Slog.w(TAG, "Unexpected exception", e);
Dianne Hackborncc278702009-09-02 23:07:23 -07001596 }
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001597 }
1598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001600
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001601 // ---------------------------------------------------------------------------------------
1602 // Check whether or not this is a valid IPC. Assumes an IPC is valid when either
1603 // 1) it comes from the system process
1604 // 2) the calling process' user id is identical to the current user id IMMS thinks.
1605 private boolean calledFromValidUser() {
1606 final int uid = Binder.getCallingUid();
1607 final int userId = UserHandle.getUserId(uid);
1608 if (DEBUG) {
1609 Slog.d(TAG, "--- calledFromForegroundUserOrSystemProcess ? "
1610 + "calling uid = " + uid + " system uid = " + Process.SYSTEM_UID
1611 + " calling userId = " + userId + ", foreground user id = "
Satoshi Kataoka87c29142013-07-31 23:11:54 +09001612 + mSettings.getCurrentUserId() + ", calling pid = " + Binder.getCallingPid()
1613 + InputMethodUtils.getApiCallStack());
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001614 }
Kenny Guy2a764942014-04-02 13:29:20 +01001615 if (uid == Process.SYSTEM_UID || mSettings.isCurrentProfile(userId)) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001616 return true;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001617 }
Satoshi Kataoka135e5fb2012-09-28 18:25:06 +09001618
1619 // Caveat: A process which has INTERACT_ACROSS_USERS_FULL gets results for the
1620 // foreground user, not for the user of that process. Accordingly InputMethodManagerService
1621 // must not manage background users' states in any functions.
1622 // Note that privacy-sensitive IPCs, such as setInputMethod, are still securely guarded
1623 // by a token.
1624 if (mContext.checkCallingOrSelfPermission(
1625 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1626 == PackageManager.PERMISSION_GRANTED) {
1627 if (DEBUG) {
1628 Slog.d(TAG, "--- Access granted because the calling process has "
1629 + "the INTERACT_ACROSS_USERS_FULL permission");
1630 }
1631 return true;
1632 }
Yohei Yukawad0332832017-02-01 13:59:43 -08001633 // TODO(b/34886274): The semantics of this verification is actually not well-defined.
Seigo Nonakae27dc2b2015-08-14 18:21:27 -07001634 Slog.w(TAG, "--- IPC called from background users. Ignore. callers="
1635 + Debug.getCallers(10));
Satoshi Kataoka135e5fb2012-09-28 18:25:06 +09001636 return false;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001637 }
1638
Yohei Yukawa22c97be2014-06-04 19:43:36 +09001639
1640 /**
1641 * Returns true iff the caller is identified to be the current input method with the token.
1642 * @param token The window token given to the input method when it was started.
1643 * @return true if and only if non-null valid token is specified.
1644 */
Yohei Yukawad0332832017-02-01 13:59:43 -08001645 private boolean calledWithValidToken(@Nullable IBinder token) {
1646 if (token == null && Binder.getCallingPid() == Process.myPid()) {
1647 if (DEBUG) {
1648 // TODO(b/34851776): Basically it's the caller's fault if we reach here.
1649 Slog.d(TAG, "Bug 34851776 is detected callers=" + Debug.getCallers(10));
1650 }
1651 return false;
1652 }
1653 if (token == null || token != mCurToken) {
1654 // TODO(b/34886274): The semantics of this verification is actually not well-defined.
1655 Slog.e(TAG, "Ignoring " + Debug.getCaller() + " due to an invalid token."
1656 + " uid:" + Binder.getCallingUid() + " token:" + token);
Yohei Yukawa22c97be2014-06-04 19:43:36 +09001657 return false;
1658 }
1659 return true;
1660 }
1661
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001662 private boolean bindCurrentInputMethodService(
1663 Intent service, ServiceConnection conn, int flags) {
1664 if (service == null || conn == null) {
1665 Slog.e(TAG, "--- bind failed: service = " + service + ", conn = " + conn);
1666 return false;
1667 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08001668 return mContext.bindServiceAsUser(service, conn, flags,
1669 new UserHandle(mSettings.getCurrentUserId()));
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001670 }
1671
satoke7c6998e2011-06-03 17:57:59 +09001672 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 public List<InputMethodInfo> getInputMethodList() {
Tarandeep Singh89a6c482017-11-21 14:26:11 -08001674 return getInputMethodList(false /* isVrOnly */);
1675 }
1676
1677 public List<InputMethodInfo> getVrInputMethodList() {
1678 return getInputMethodList(true /* isVrOnly */);
1679 }
1680
1681 private List<InputMethodInfo> getInputMethodList(final boolean isVrOnly) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001682 // TODO: Make this work even for non-current users?
1683 if (!calledFromValidUser()) {
1684 return Collections.emptyList();
1685 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 synchronized (mMethodMap) {
Tarandeep Singh89a6c482017-11-21 14:26:11 -08001687 ArrayList<InputMethodInfo> methodList = new ArrayList<>();
1688 for (InputMethodInfo info : mMethodList) {
1689
1690 if (info.isVrOnly() == isVrOnly) {
1691 methodList.add(info);
1692 }
1693 }
1694 return methodList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 }
1696 }
1697
satoke7c6998e2011-06-03 17:57:59 +09001698 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 public List<InputMethodInfo> getEnabledInputMethodList() {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001700 // TODO: Make this work even for non-current users?
1701 if (!calledFromValidUser()) {
1702 return Collections.emptyList();
1703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 synchronized (mMethodMap) {
satokd87c2592010-09-29 11:52:06 +09001705 return mSettings.getEnabledInputMethodListLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 }
1707 }
1708
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09001709 /**
Satoshi Kataokab3c21ac2013-08-07 15:43:29 +09001710 * @param imiId if null, returns enabled subtypes for the current imi
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09001711 * @return enabled subtypes of the specified imi
1712 */
satoke7c6998e2011-06-03 17:57:59 +09001713 @Override
Satoshi Kataokab3c21ac2013-08-07 15:43:29 +09001714 public List<InputMethodSubtype> getEnabledInputMethodSubtypeList(String imiId,
satok16331c82010-12-20 23:48:46 +09001715 boolean allowsImplicitlySelectedSubtypes) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001716 // TODO: Make this work even for non-current users?
1717 if (!calledFromValidUser()) {
Yohei Yukawab0377bb2015-08-10 21:06:30 -07001718 return Collections.emptyList();
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001719 }
satok67ddf9c2010-11-17 09:45:54 +09001720 synchronized (mMethodMap) {
Satoshi Kataokab3c21ac2013-08-07 15:43:29 +09001721 final InputMethodInfo imi;
1722 if (imiId == null && mCurMethodId != null) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09001723 imi = mMethodMap.get(mCurMethodId);
Satoshi Kataokab3c21ac2013-08-07 15:43:29 +09001724 } else {
1725 imi = mMethodMap.get(imiId);
1726 }
1727 if (imi == null) {
Yohei Yukawab0377bb2015-08-10 21:06:30 -07001728 return Collections.emptyList();
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09001729 }
1730 return mSettings.getEnabledInputMethodSubtypeListLocked(
1731 mContext, imi, allowsImplicitlySelectedSubtypes);
satok67ddf9c2010-11-17 09:45:54 +09001732 }
1733 }
1734
satoke7c6998e2011-06-03 17:57:59 +09001735 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 public void addClient(IInputMethodClient client,
1737 IInputContext inputContext, int uid, int pid) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001738 if (!calledFromValidUser()) {
1739 return;
1740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 synchronized (mMethodMap) {
1742 mClients.put(client.asBinder(), new ClientState(client,
1743 inputContext, uid, pid));
1744 }
1745 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001746
satoke7c6998e2011-06-03 17:57:59 +09001747 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 public void removeClient(IInputMethodClient client) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001749 if (!calledFromValidUser()) {
1750 return;
1751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 synchronized (mMethodMap) {
Jeff Brownc28867a2013-03-26 15:42:39 -07001753 ClientState cs = mClients.remove(client.asBinder());
1754 if (cs != null) {
1755 clearClientSessionLocked(cs);
Yohei Yukawa072b1b52015-11-18 15:54:34 -08001756 if (mCurClient == cs) {
1757 mCurClient = null;
1758 }
Yohei Yukawae39d4ed2015-11-19 03:38:49 -08001759 if (mCurFocusedWindowClient == cs) {
1760 mCurFocusedWindowClient = null;
1761 }
Jeff Brownc28867a2013-03-26 15:42:39 -07001762 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763 }
1764 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 void executeOrSendMessage(IInterface target, Message msg) {
1767 if (target.asBinder() instanceof Binder) {
1768 mCaller.sendMessage(msg);
1769 } else {
1770 handleMessage(msg);
1771 msg.recycle();
1772 }
1773 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001774
Yohei Yukawa33e81792015-11-17 21:14:42 -08001775 void unbindCurrentClientLocked(
1776 /* @InputMethodClient.UnbindReason */ final int unbindClientReason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 if (mCurClient != null) {
Yohei Yukawa35d3f372015-11-25 11:07:19 -08001778 if (DEBUG) Slog.v(TAG, "unbindCurrentInputLocked: client="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 + mCurClient.client.asBinder());
1780 if (mBoundToMethod) {
1781 mBoundToMethod = false;
1782 if (mCurMethod != null) {
1783 executeOrSendMessage(mCurMethod, mCaller.obtainMessageO(
1784 MSG_UNBIND_INPUT, mCurMethod));
1785 }
1786 }
Dianne Hackborna6e41342012-05-22 16:30:34 -07001787
Yohei Yukawa2bc66172017-02-08 11:13:25 -08001788 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIIO(
1789 MSG_SET_ACTIVE, 0, 0, mCurClient));
Yohei Yukawa33e81792015-11-17 21:14:42 -08001790 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIIO(
1791 MSG_UNBIND_CLIENT, mCurSeq, unbindClientReason, mCurClient.client));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 mCurClient.sessionRequested = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 mCurClient = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001794
The Android Open Source Project10592532009-03-18 17:39:46 -07001795 hideInputMethodMenuLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 }
1797 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001799 private int getImeShowFlags() {
1800 int flags = 0;
1801 if (mShowForced) {
1802 flags |= InputMethod.SHOW_FORCED
1803 | InputMethod.SHOW_EXPLICIT;
1804 } else if (mShowExplicitlyRequested) {
1805 flags |= InputMethod.SHOW_EXPLICIT;
1806 }
1807 return flags;
1808 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 private int getAppShowFlags() {
1811 int flags = 0;
1812 if (mShowForced) {
1813 flags |= InputMethodManager.SHOW_FORCED;
1814 } else if (!mShowExplicitlyRequested) {
1815 flags |= InputMethodManager.SHOW_IMPLICIT;
1816 }
1817 return flags;
1818 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001819
Yohei Yukawa2553e482017-12-15 15:47:33 -08001820 @NonNull
Yohei Yukawa87ca8402017-02-07 00:13:14 -08001821 InputBindResult attachNewInputLocked(
1822 /* @InputMethodClient.StartInputReason */ final int startInputReason, boolean initial) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 if (!mBoundToMethod) {
1824 executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
1825 MSG_BIND_INPUT, mCurMethod, mCurClient.binding));
1826 mBoundToMethod = true;
1827 }
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08001828
1829 final Binder startInputToken = new Binder();
Yohei Yukawa357b2f62017-02-14 09:40:03 -08001830 final StartInputInfo info = new StartInputInfo(mCurToken, mCurId, startInputReason,
1831 !initial, mCurFocusedWindow, mCurAttribute, mCurFocusedWindowSoftInputMode,
1832 mCurSeq);
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08001833 mStartInputMap.put(startInputToken, info);
Yohei Yukawa357b2f62017-02-14 09:40:03 -08001834 mStartInputHistory.addEntry(info);
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08001835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 final SessionState session = mCurClient.curSession;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08001837 executeOrSendMessage(session.method, mCaller.obtainMessageIIOOOO(
Yohei Yukawaf7526b52017-02-11 20:57:10 -08001838 MSG_START_INPUT, mCurInputContextMissingMethods, initial ? 0 : 1 /* restarting */,
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08001839 startInputToken, session, mCurInputContext, mCurAttribute));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 if (mShowRequested) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001841 if (DEBUG) Slog.v(TAG, "Attach new input asks to show input");
The Android Open Source Project4df24232009-03-05 14:34:35 -08001842 showCurrentInputLocked(getAppShowFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08001844 return new InputBindResult(InputBindResult.ResultCode.SUCCESS_WITH_IME_SESSION,
1845 session.session, (session.channel != null ? session.channel.dup() : null),
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09001846 mCurId, mCurSeq, mCurUserActionNotificationSequenceNumber);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001847 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001848
Yohei Yukawa2553e482017-12-15 15:47:33 -08001849 @NonNull
Yohei Yukawa35d3f372015-11-25 11:07:19 -08001850 InputBindResult startInputLocked(
1851 /* @InputMethodClient.StartInputReason */ final int startInputReason,
Yohei Yukawa19a80a12016-03-14 22:57:37 -07001852 IInputMethodClient client, IInputContext inputContext,
1853 /* @InputConnectionInspector.missingMethods */ final int missingMethods,
Yohei Yukawa74750f22016-03-22 12:54:22 -07001854 @Nullable EditorInfo attribute, int controlFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 // If no method is currently selected, do nothing.
1856 if (mCurMethodId == null) {
Yohei Yukawa2553e482017-12-15 15:47:33 -08001857 return InputBindResult.NO_IME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 ClientState cs = mClients.get(client.asBinder());
1861 if (cs == null) {
1862 throw new IllegalArgumentException("unknown client "
1863 + client.asBinder());
1864 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001865
Yohei Yukawa74750f22016-03-22 12:54:22 -07001866 if (attribute == null) {
1867 Slog.w(TAG, "Ignoring startInput with null EditorInfo."
1868 + " uid=" + cs.uid + " pid=" + cs.pid);
Yohei Yukawa2553e482017-12-15 15:47:33 -08001869 return InputBindResult.NULL_EDITOR_INFO;
Yohei Yukawa74750f22016-03-22 12:54:22 -07001870 }
1871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 try {
1873 if (!mIWindowManager.inputMethodClientHasFocus(cs.client)) {
1874 // Check with the window manager to make sure this client actually
1875 // has a window with focus. If not, reject. This is thread safe
1876 // because if the focus changes some time before or after, the
1877 // next client receiving focus that has any interest in input will
1878 // be calling through here after that change happens.
Yohei Yukawad0332832017-02-01 13:59:43 -08001879 if (DEBUG) {
1880 Slog.w(TAG, "Starting input on non-focused client " + cs.client
1881 + " (uid=" + cs.uid + " pid=" + cs.pid + ")");
1882 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08001883 return InputBindResult.NOT_IME_TARGET_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884 }
1885 } catch (RemoteException e) {
1886 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001887
Yohei Yukawa19a80a12016-03-14 22:57:37 -07001888 return startInputUncheckedLocked(cs, inputContext, missingMethods, attribute,
Yohei Yukawa87ca8402017-02-07 00:13:14 -08001889 controlFlags, startInputReason);
Dianne Hackborn7663d802012-02-24 13:08:49 -08001890 }
1891
Yohei Yukawa2553e482017-12-15 15:47:33 -08001892 @NonNull
Yohei Yukawa35d3f372015-11-25 11:07:19 -08001893 InputBindResult startInputUncheckedLocked(@NonNull ClientState cs, IInputContext inputContext,
Yohei Yukawa19a80a12016-03-14 22:57:37 -07001894 /* @InputConnectionInspector.missingMethods */ final int missingMethods,
Yohei Yukawa87ca8402017-02-07 00:13:14 -08001895 @NonNull EditorInfo attribute, int controlFlags,
1896 /* @InputMethodClient.StartInputReason */ final int startInputReason) {
Dianne Hackborn7663d802012-02-24 13:08:49 -08001897 // If no method is currently selected, do nothing.
1898 if (mCurMethodId == null) {
Yohei Yukawa2553e482017-12-15 15:47:33 -08001899 return InputBindResult.NO_IME;
Dianne Hackborn7663d802012-02-24 13:08:49 -08001900 }
1901
Yohei Yukawad57ba672015-06-08 16:39:46 -07001902 if (!InputMethodUtils.checkIfPackageBelongsToUid(mAppOpsManager, cs.uid,
1903 attribute.packageName)) {
1904 Slog.e(TAG, "Rejecting this client as it reported an invalid package name."
1905 + " uid=" + cs.uid + " package=" + attribute.packageName);
Yohei Yukawa2553e482017-12-15 15:47:33 -08001906 return InputBindResult.INVALID_PACKAGE_NAME;
Yohei Yukawa0f3ad12015-04-06 16:48:24 -07001907 }
1908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 if (mCurClient != cs) {
John Spurlocke0980502013-10-25 11:59:29 -04001910 // Was the keyguard locked when switching over to the new client?
1911 mCurClientInKeyguard = isKeyguardLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912 // If the client is changing, we need to switch over to the new
1913 // one.
Yohei Yukawa33e81792015-11-17 21:14:42 -08001914 unbindCurrentClientLocked(InputMethodClient.UNBIND_REASON_SWITCH_CLIENT);
Yohei Yukawa35d3f372015-11-25 11:07:19 -08001915 if (DEBUG) Slog.v(TAG, "switching to client: client="
John Spurlocke0980502013-10-25 11:59:29 -04001916 + cs.client.asBinder() + " keyguard=" + mCurClientInKeyguard);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917
1918 // If the screen is on, inform the new client it is active
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07001919 if (mIsInteractive) {
Dianne Hackborna6e41342012-05-22 16:30:34 -07001920 executeOrSendMessage(cs.client, mCaller.obtainMessageIO(
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07001921 MSG_SET_ACTIVE, mIsInteractive ? 1 : 0, cs));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001922 }
1923 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001925 // Bump up the sequence for this client and attach it.
1926 mCurSeq++;
1927 if (mCurSeq <= 0) mCurSeq = 1;
1928 mCurClient = cs;
1929 mCurInputContext = inputContext;
Yohei Yukawa19a80a12016-03-14 22:57:37 -07001930 mCurInputContextMissingMethods = missingMethods;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 mCurAttribute = attribute;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 // Check if the input method is changing.
1934 if (mCurId != null && mCurId.equals(mCurMethodId)) {
1935 if (cs.curSession != null) {
1936 // Fast case: if we are already connected to the input method,
1937 // then just return it.
Yohei Yukawa87ca8402017-02-07 00:13:14 -08001938 return attachNewInputLocked(startInputReason,
Dianne Hackborn7663d802012-02-24 13:08:49 -08001939 (controlFlags&InputMethodManager.CONTROL_START_INITIAL) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 }
1941 if (mHaveConnection) {
1942 if (mCurMethod != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 // Return to client, and we will get back with it when
1944 // we have had a session made for it.
Jeff Brownc28867a2013-03-26 15:42:39 -07001945 requestClientSessionLocked(cs);
Yohei Yukawa2553e482017-12-15 15:47:33 -08001946 return new InputBindResult(
1947 InputBindResult.ResultCode.SUCCESS_WAITING_IME_SESSION,
1948 null, null, mCurId, mCurSeq,
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09001949 mCurUserActionNotificationSequenceNumber);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 } else if (SystemClock.uptimeMillis()
1951 < (mLastBindTime+TIME_TO_RECONNECT)) {
1952 // In this case we have connected to the service, but
1953 // don't yet have its interface. If it hasn't been too
1954 // long since we did the connection, we'll return to
1955 // the client and wait to get the service interface so
1956 // we can report back. If it has been too long, we want
1957 // to fall through so we can try a disconnect/reconnect
1958 // to see if we can get back in touch with the service.
Yohei Yukawa2553e482017-12-15 15:47:33 -08001959 return new InputBindResult(
1960 InputBindResult.ResultCode.SUCCESS_WAITING_IME_BINDING,
1961 null, null, mCurId, mCurSeq,
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09001962 mCurUserActionNotificationSequenceNumber);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001964 EventLog.writeEvent(EventLogTags.IMF_FORCE_RECONNECT_IME,
1965 mCurMethodId, SystemClock.uptimeMillis()-mLastBindTime, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 }
1967 }
1968 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001969
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001970 return startInputInnerLocked();
1971 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001972
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001973 InputBindResult startInputInnerLocked() {
1974 if (mCurMethodId == null) {
Yohei Yukawa2553e482017-12-15 15:47:33 -08001975 return InputBindResult.NO_IME;
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001976 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001977
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001978 if (!mSystemReady) {
1979 // If the system is not yet ready, we shouldn't be running third
1980 // party code.
Yohei Yukawa2553e482017-12-15 15:47:33 -08001981 return new InputBindResult(
1982 InputBindResult.ResultCode.ERROR_SYSTEM_NOT_READY,
1983 null, null, mCurMethodId, mCurSeq,
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09001984 mCurUserActionNotificationSequenceNumber);
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001985 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 InputMethodInfo info = mMethodMap.get(mCurMethodId);
1988 if (info == null) {
1989 throw new IllegalArgumentException("Unknown id: " + mCurMethodId);
1990 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001991
Yohei Yukawabc7b5262015-11-17 17:38:41 -08001992 unbindCurrentMethodLocked(true);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 mCurIntent = new Intent(InputMethod.SERVICE_INTERFACE);
1995 mCurIntent.setComponent(info.getComponent());
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07001996 mCurIntent.putExtra(Intent.EXTRA_CLIENT_LABEL,
1997 com.android.internal.R.string.input_method_binding_label);
1998 mCurIntent.putExtra(Intent.EXTRA_CLIENT_INTENT, PendingIntent.getActivity(
1999 mContext, 0, new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS), 0));
Yohei Yukawaa67a4592017-03-30 15:57:02 -07002000 if (bindCurrentInputMethodService(mCurIntent, this, IME_CONNECTION_BIND_FLAGS)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 mLastBindTime = SystemClock.uptimeMillis();
2002 mHaveConnection = true;
2003 mCurId = info.getId();
2004 mCurToken = new Binder();
2005 try {
Yohei Yukawad0332832017-02-01 13:59:43 -08002006 if (DEBUG) Slog.v(TAG, "Adding window token: " + mCurToken);
Wale Ogunwaleac2561e2016-11-01 15:43:46 -07002007 mIWindowManager.addWindowToken(mCurToken, TYPE_INPUT_METHOD, DEFAULT_DISPLAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 } catch (RemoteException e) {
2009 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08002010 return new InputBindResult(
2011 InputBindResult.ResultCode.SUCCESS_WAITING_IME_BINDING,
2012 null, null, mCurId, mCurSeq,
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09002013 mCurUserActionNotificationSequenceNumber);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002014 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08002015 mCurIntent = null;
2016 Slog.w(TAG, "Failure connecting to input method service: " + mCurIntent);
2017 return InputBindResult.IME_NOT_CONNECTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002018 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002019
Yohei Yukawa2553e482017-12-15 15:47:33 -08002020 @NonNull
Yohei Yukawa05c25f82016-02-22 12:41:17 -08002021 private InputBindResult startInput(
Yohei Yukawa35d3f372015-11-25 11:07:19 -08002022 /* @InputMethodClient.StartInputReason */ final int startInputReason,
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002023 IInputMethodClient client, IInputContext inputContext,
2024 /* @InputConnectionInspector.missingMethods */ final int missingMethods,
Yohei Yukawa74750f22016-03-22 12:54:22 -07002025 @Nullable EditorInfo attribute, int controlFlags) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002026 if (!calledFromValidUser()) {
Yohei Yukawa2553e482017-12-15 15:47:33 -08002027 return InputBindResult.INVALID_USER;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002028 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002029 synchronized (mMethodMap) {
Yohei Yukawa35d3f372015-11-25 11:07:19 -08002030 if (DEBUG) {
2031 Slog.v(TAG, "startInput: reason="
2032 + InputMethodClient.getStartInputReason(startInputReason)
2033 + " client = " + client.asBinder()
2034 + " inputContext=" + inputContext
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002035 + " missingMethods="
2036 + InputConnectionInspector.getMissingMethodFlagsAsString(missingMethods)
Yohei Yukawa35d3f372015-11-25 11:07:19 -08002037 + " attribute=" + attribute
2038 + " controlFlags=#" + Integer.toHexString(controlFlags));
2039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 final long ident = Binder.clearCallingIdentity();
2041 try {
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002042 return startInputLocked(startInputReason, client, inputContext, missingMethods,
2043 attribute, controlFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 } finally {
2045 Binder.restoreCallingIdentity(ident);
2046 }
2047 }
2048 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002049
satoke7c6998e2011-06-03 17:57:59 +09002050 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 public void finishInput(IInputMethodClient client) {
2052 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002053
satoke7c6998e2011-06-03 17:57:59 +09002054 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002055 public void onServiceConnected(ComponentName name, IBinder service) {
2056 synchronized (mMethodMap) {
2057 if (mCurIntent != null && name.equals(mCurIntent.getComponent())) {
2058 mCurMethod = IInputMethod.Stub.asInterface(service);
Dianne Hackborncc278702009-09-02 23:07:23 -07002059 if (mCurToken == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002060 Slog.w(TAG, "Service connected without a token!");
Yohei Yukawabc7b5262015-11-17 17:38:41 -08002061 unbindCurrentMethodLocked(false);
Dianne Hackborncc278702009-09-02 23:07:23 -07002062 return;
2063 }
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07002064 if (DEBUG) Slog.v(TAG, "Initiating attach with token: " + mCurToken);
Dianne Hackborncc278702009-09-02 23:07:23 -07002065 executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
2066 MSG_ATTACH_TOKEN, mCurMethod, mCurToken));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002067 if (mCurClient != null) {
Jeff Brownc28867a2013-03-26 15:42:39 -07002068 clearClientSessionLocked(mCurClient);
2069 requestClientSessionLocked(mCurClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 }
2071 }
2072 }
2073 }
2074
Jeff Brownc28867a2013-03-26 15:42:39 -07002075 void onSessionCreated(IInputMethod method, IInputMethodSession session,
2076 InputChannel channel) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 synchronized (mMethodMap) {
2078 if (mCurMethod != null && method != null
2079 && mCurMethod.asBinder() == method.asBinder()) {
2080 if (mCurClient != null) {
Jeff Brownc28867a2013-03-26 15:42:39 -07002081 clearClientSessionLocked(mCurClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002082 mCurClient.curSession = new SessionState(mCurClient,
Jeff Brownc28867a2013-03-26 15:42:39 -07002083 method, session, channel);
Yohei Yukawa87ca8402017-02-07 00:13:14 -08002084 InputBindResult res = attachNewInputLocked(
2085 InputMethodClient.START_INPUT_REASON_SESSION_CREATED_BY_IME, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086 if (res.method != null) {
2087 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageOO(
Yohei Yukawa33e81792015-11-17 21:14:42 -08002088 MSG_BIND_CLIENT, mCurClient.client, res));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 }
Jeff Brownc28867a2013-03-26 15:42:39 -07002090 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 }
2092 }
2093 }
Jeff Brownc28867a2013-03-26 15:42:39 -07002094
2095 // Session abandoned. Close its associated input channel.
2096 channel.dispose();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002098
Yohei Yukawabc7b5262015-11-17 17:38:41 -08002099 void unbindCurrentMethodLocked(boolean savePosition) {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -07002100 if (mVisibleBound) {
2101 mContext.unbindService(mVisibleConnection);
2102 mVisibleBound = false;
2103 }
2104
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002105 if (mHaveConnection) {
2106 mContext.unbindService(this);
2107 mHaveConnection = false;
2108 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002109
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002110 if (mCurToken != null) {
2111 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002112 if (DEBUG) Slog.v(TAG, "Removing window token: " + mCurToken);
Dianne Hackborn2ea9bae2012-11-02 18:43:48 -07002113 if ((mImeWindowVis & InputMethodService.IME_ACTIVE) != 0 && savePosition) {
satoke0a99412012-05-10 02:22:58 +09002114 // The current IME is shown. Hence an IME switch (transition) is happening.
Seigo Nonaka7309b122015-08-17 18:34:13 -07002115 mWindowManagerInternal.saveLastInputMethodWindowForTransition();
satoke0a99412012-05-10 02:22:58 +09002116 }
Wale Ogunwaleac2561e2016-11-01 15:43:46 -07002117 mIWindowManager.removeWindowToken(mCurToken, DEFAULT_DISPLAY);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002118 } catch (RemoteException e) {
2119 }
2120 mCurToken = null;
2121 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002122
The Android Open Source Project10592532009-03-18 17:39:46 -07002123 mCurId = null;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002124 clearCurMethodLocked();
Yohei Yukawabc7b5262015-11-17 17:38:41 -08002125 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002126
Yohei Yukawa33e81792015-11-17 21:14:42 -08002127 void resetCurrentMethodAndClient(
2128 /* @InputMethodClient.UnbindReason */ final int unbindClientReason) {
Yohei Yukawabc7b5262015-11-17 17:38:41 -08002129 mCurMethodId = null;
2130 unbindCurrentMethodLocked(false);
Yohei Yukawa33e81792015-11-17 21:14:42 -08002131 unbindCurrentClientLocked(unbindClientReason);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002132 }
Jeff Brownc28867a2013-03-26 15:42:39 -07002133
2134 void requestClientSessionLocked(ClientState cs) {
2135 if (!cs.sessionRequested) {
2136 if (DEBUG) Slog.v(TAG, "Creating new session for client " + cs);
2137 InputChannel[] channels = InputChannel.openInputChannelPair(cs.toString());
2138 cs.sessionRequested = true;
2139 executeOrSendMessage(mCurMethod, mCaller.obtainMessageOOO(
2140 MSG_CREATE_SESSION, mCurMethod, channels[1],
2141 new MethodCallback(this, mCurMethod, channels[0])));
2142 }
2143 }
2144
2145 void clearClientSessionLocked(ClientState cs) {
2146 finishSessionLocked(cs.curSession);
2147 cs.curSession = null;
2148 cs.sessionRequested = false;
2149 }
2150
2151 private void finishSessionLocked(SessionState sessionState) {
2152 if (sessionState != null) {
2153 if (sessionState.session != null) {
2154 try {
2155 sessionState.session.finishSession();
2156 } catch (RemoteException e) {
2157 Slog.w(TAG, "Session failed to close due to remote exception", e);
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002158 updateSystemUiLocked(mCurToken, 0 /* vis */, mBackDisposition);
Jeff Brownc28867a2013-03-26 15:42:39 -07002159 }
2160 sessionState.session = null;
2161 }
2162 if (sessionState.channel != null) {
2163 sessionState.channel.dispose();
2164 sessionState.channel = null;
Devin Taylor0c33ed22010-02-23 13:26:46 -06002165 }
2166 }
2167 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002168
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002169 void clearCurMethodLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002170 if (mCurMethod != null) {
2171 for (ClientState cs : mClients.values()) {
Jeff Brownc28867a2013-03-26 15:42:39 -07002172 clearClientSessionLocked(cs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173 }
Devin Taylor0c33ed22010-02-23 13:26:46 -06002174
Jeff Brownc28867a2013-03-26 15:42:39 -07002175 finishSessionLocked(mEnabledSession);
Devin Taylor0c33ed22010-02-23 13:26:46 -06002176 mEnabledSession = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002177 mCurMethod = null;
2178 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07002179 if (mStatusBar != null) {
Jason Monk3e189872016-01-12 09:10:34 -05002180 mStatusBar.setIconVisibility(mSlotIme, false);
Dianne Hackborn661cd522011-08-22 00:26:20 -07002181 }
Yohei Yukawa2bc66172017-02-08 11:13:25 -08002182 mInFullscreenMode = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002183 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002184
satoke7c6998e2011-06-03 17:57:59 +09002185 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002186 public void onServiceDisconnected(ComponentName name) {
Yohei Yukawa817d5f72017-01-04 20:15:02 -08002187 // Note that mContext.unbindService(this) does not trigger this. Hence if we are here the
2188 // disconnection is not intended by IMMS (e.g. triggered because the current IMS crashed),
2189 // which is irregular but can eventually happen for everyone just by continuing using the
2190 // device. Thus it is important to make sure that all the internal states are properly
2191 // refreshed when this method is called back. Running
2192 // adb install -r <APK that implements the current IME>
2193 // would be a good way to trigger such a situation.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002194 synchronized (mMethodMap) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002195 if (DEBUG) Slog.v(TAG, "Service disconnected: " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002196 + " mCurIntent=" + mCurIntent);
2197 if (mCurMethod != null && mCurIntent != null
2198 && name.equals(mCurIntent.getComponent())) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002199 clearCurMethodLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200 // We consider this to be a new bind attempt, since the system
2201 // should now try to restart the service for us.
2202 mLastBindTime = SystemClock.uptimeMillis();
2203 mShowRequested = mInputShown;
2204 mInputShown = false;
Yohei Yukawa817d5f72017-01-04 20:15:02 -08002205 unbindCurrentClientLocked(InputMethodClient.UNBIND_REASON_DISCONNECT_IME);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002206 }
2207 }
2208 }
2209
satokf9f01002011-05-19 21:31:50 +09002210 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002211 public void updateStatusIcon(IBinder token, String packageName, int iconId) {
Yohei Yukawa59377ca2017-01-31 21:32:26 -08002212 synchronized (mMethodMap) {
2213 if (!calledWithValidToken(token)) {
Yohei Yukawa59377ca2017-01-31 21:32:26 -08002214 return;
2215 }
2216 final long ident = Binder.clearCallingIdentity();
2217 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218 if (iconId == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002219 if (DEBUG) Slog.d(TAG, "hide the small icon for the input method");
Dianne Hackborn661cd522011-08-22 00:26:20 -07002220 if (mStatusBar != null) {
Jason Monk3e189872016-01-12 09:10:34 -05002221 mStatusBar.setIconVisibility(mSlotIme, false);
Dianne Hackborn661cd522011-08-22 00:26:20 -07002222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002223 } else if (packageName != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002224 if (DEBUG) Slog.d(TAG, "show a small icon for the input method");
Svetoslav Ganov6179ea32011-06-28 01:12:41 -07002225 CharSequence contentDescription = null;
2226 try {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002227 // Use PackageManager to load label
2228 final PackageManager packageManager = mContext.getPackageManager();
Svetoslav Ganov6179ea32011-06-28 01:12:41 -07002229 contentDescription = packageManager.getApplicationLabel(
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002230 mIPackageManager.getApplicationInfo(packageName, 0,
2231 mSettings.getCurrentUserId()));
2232 } catch (RemoteException e) {
Svetoslav Ganov6179ea32011-06-28 01:12:41 -07002233 /* ignore */
2234 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07002235 if (mStatusBar != null) {
Jason Monk3e189872016-01-12 09:10:34 -05002236 mStatusBar.setIcon(mSlotIme, packageName, iconId, 0,
Dianne Hackborn661cd522011-08-22 00:26:20 -07002237 contentDescription != null
2238 ? contentDescription.toString() : null);
Jason Monk3e189872016-01-12 09:10:34 -05002239 mStatusBar.setIconVisibility(mSlotIme, true);
Dianne Hackborn661cd522011-08-22 00:26:20 -07002240 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002241 }
Yohei Yukawa59377ca2017-01-31 21:32:26 -08002242 } finally {
2243 Binder.restoreCallingIdentity(ident);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002245 }
2246 }
2247
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002248 private boolean shouldShowImeSwitcherLocked(int visibility) {
satok7cfc0ed2011-06-20 21:29:36 +09002249 if (!mShowOngoingImeSwitcherForPhones) return false;
Jason Monk807ef762014-05-08 15:47:46 -04002250 if (mSwitchingDialog != null) return false;
Yohei Yukawad2bc3092017-07-31 15:37:14 -07002251 if (mWindowManagerInternal.isKeyguardShowingAndNotOccluded()
2252 && mKeyguardManager != null && mKeyguardManager.isKeyguardSecure()) return false;
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002253 if ((visibility & InputMethodService.IME_ACTIVE) == 0) return false;
Seigo Nonaka7309b122015-08-17 18:34:13 -07002254 if (mWindowManagerInternal.isHardKeyboardAvailable()) {
Yohei Yukawafa0e47e2016-04-05 09:55:56 -07002255 if (mHardKeyboardBehavior == HardKeyboardBehavior.WIRELESS_AFFORDANCE) {
2256 // When physical keyboard is attached, we show the ime switcher (or notification if
2257 // NavBar is not available) because SHOW_IME_WITH_HARD_KEYBOARD settings currently
2258 // exists in the IME switcher dialog. Might be OK to remove this condition once
2259 // SHOW_IME_WITH_HARD_KEYBOARD settings finds a good place to live.
2260 return true;
2261 }
Yohei Yukawa89398382016-03-29 11:37:04 -07002262 } else if ((visibility & InputMethodService.IME_VISIBLE) == 0) {
2263 return false;
Yohei Yukawac6c7cd22015-05-12 15:00:33 -07002264 }
Yohei Yukawac6c7cd22015-05-12 15:00:33 -07002265
2266 List<InputMethodInfo> imis = mSettings.getEnabledInputMethodListLocked();
2267 final int N = imis.size();
2268 if (N > 2) return true;
2269 if (N < 1) return false;
2270 int nonAuxCount = 0;
2271 int auxCount = 0;
2272 InputMethodSubtype nonAuxSubtype = null;
2273 InputMethodSubtype auxSubtype = null;
2274 for(int i = 0; i < N; ++i) {
2275 final InputMethodInfo imi = imis.get(i);
2276 final List<InputMethodSubtype> subtypes =
2277 mSettings.getEnabledInputMethodSubtypeListLocked(mContext, imi, true);
2278 final int subtypeCount = subtypes.size();
2279 if (subtypeCount == 0) {
2280 ++nonAuxCount;
2281 } else {
2282 for (int j = 0; j < subtypeCount; ++j) {
2283 final InputMethodSubtype subtype = subtypes.get(j);
2284 if (!subtype.isAuxiliary()) {
2285 ++nonAuxCount;
2286 nonAuxSubtype = subtype;
2287 } else {
2288 ++auxCount;
2289 auxSubtype = subtype;
satok7cfc0ed2011-06-20 21:29:36 +09002290 }
2291 }
satok7cfc0ed2011-06-20 21:29:36 +09002292 }
2293 }
Yohei Yukawac6c7cd22015-05-12 15:00:33 -07002294 if (nonAuxCount > 1 || auxCount > 1) {
2295 return true;
2296 } else if (nonAuxCount == 1 && auxCount == 1) {
2297 if (nonAuxSubtype != null && auxSubtype != null
2298 && (nonAuxSubtype.getLocale().equals(auxSubtype.getLocale())
2299 || auxSubtype.overridesImplicitlyEnabledSubtype()
2300 || nonAuxSubtype.overridesImplicitlyEnabledSubtype())
2301 && nonAuxSubtype.containsExtraValueKey(TAG_TRY_SUPPRESSING_IME_SWITCHER)) {
2302 return false;
2303 }
2304 return true;
2305 }
2306 return false;
satok7cfc0ed2011-06-20 21:29:36 +09002307 }
2308
John Spurlocke0980502013-10-25 11:59:29 -04002309 private boolean isKeyguardLocked() {
2310 return mKeyguardManager != null && mKeyguardManager.isKeyguardLocked();
2311 }
2312
Yohei Yukawad6475a62017-04-17 10:35:27 -07002313 @BinderThread
satokdbf29502011-08-25 15:28:23 +09002314 @SuppressWarnings("deprecation")
satokf9f01002011-05-19 21:31:50 +09002315 @Override
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08002316 public void setImeWindowStatus(IBinder token, IBinder startInputToken, int vis,
2317 int backDisposition) {
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002318 if (!calledWithValidToken(token)) {
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002319 return;
2320 }
2321
Yohei Yukawa69e68022017-02-13 12:04:50 -08002322 final StartInputInfo info;
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002323 synchronized (mMethodMap) {
Yohei Yukawa69e68022017-02-13 12:04:50 -08002324 info = mStartInputMap.get(startInputToken);
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002325 mImeWindowVis = vis;
2326 mBackDisposition = backDisposition;
2327 updateSystemUiLocked(token, vis, backDisposition);
2328 }
Yohei Yukawad6475a62017-04-17 10:35:27 -07002329
2330 final boolean dismissImeOnBackKeyPressed;
2331 switch (backDisposition) {
2332 case InputMethodService.BACK_DISPOSITION_WILL_DISMISS:
2333 dismissImeOnBackKeyPressed = true;
2334 break;
2335 case InputMethodService.BACK_DISPOSITION_WILL_NOT_DISMISS:
2336 dismissImeOnBackKeyPressed = false;
2337 break;
2338 default:
2339 case InputMethodService.BACK_DISPOSITION_DEFAULT:
2340 dismissImeOnBackKeyPressed = ((vis & InputMethodService.IME_VISIBLE) != 0);
2341 break;
2342 }
Yohei Yukawaee2a7ed2017-02-15 21:38:57 -08002343 mWindowManagerInternal.updateInputMethodWindowStatus(token,
2344 (vis & InputMethodService.IME_VISIBLE) != 0,
Yohei Yukawad6475a62017-04-17 10:35:27 -07002345 dismissImeOnBackKeyPressed, info != null ? info.mTargetWindow : null);
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002346 }
2347
2348 private void updateSystemUi(IBinder token, int vis, int backDisposition) {
2349 synchronized (mMethodMap) {
2350 updateSystemUiLocked(token, vis, backDisposition);
2351 }
2352 }
2353
2354 // Caution! This method is called in this class. Handle multi-user carefully
2355 private void updateSystemUiLocked(IBinder token, int vis, int backDisposition) {
2356 if (!calledWithValidToken(token)) {
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002357 return;
2358 }
2359
2360 // TODO: Move this clearing calling identity block to setImeWindowStatus after making sure
2361 // all updateSystemUi happens on system previlege.
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002362 final long ident = Binder.clearCallingIdentity();
satok06487a52010-10-29 11:37:18 +09002363 try {
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002364 // apply policy for binder calls
2365 if (vis != 0 && isKeyguardLocked() && !mCurClientInKeyguard) {
2366 vis = 0;
satok06487a52010-10-29 11:37:18 +09002367 }
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002368 // mImeWindowVis should be updated before calling shouldShowImeSwitcherLocked().
2369 final boolean needsToShowImeSwitcher = shouldShowImeSwitcherLocked(vis);
2370 if (mStatusBar != null) {
2371 mStatusBar.setImeWindowStatus(token, vis, backDisposition,
2372 needsToShowImeSwitcher);
2373 }
2374 final InputMethodInfo imi = mMethodMap.get(mCurMethodId);
2375 if (imi != null && needsToShowImeSwitcher) {
2376 // Used to load label
2377 final CharSequence title = mRes.getText(
2378 com.android.internal.R.string.select_input_method);
2379 final CharSequence summary = InputMethodUtils.getImeAndSubtypeDisplayName(
2380 mContext, imi, mCurrentSubtype);
Chris Wren1ce4b6d2015-06-11 10:19:43 -04002381 mImeSwitcherNotification.setContentTitle(title)
2382 .setContentText(summary)
2383 .setContentIntent(mImeSwitchPendingIntent);
Seigo Nonaka7309b122015-08-17 18:34:13 -07002384 try {
2385 if ((mNotificationManager != null)
2386 && !mIWindowManager.hasNavigationBar()) {
2387 if (DEBUG) {
2388 Slog.d(TAG, "--- show notification: label = " + summary);
2389 }
2390 mNotificationManager.notifyAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04002391 SystemMessage.NOTE_SELECT_INPUT_METHOD,
Seigo Nonaka7309b122015-08-17 18:34:13 -07002392 mImeSwitcherNotification.build(), UserHandle.ALL);
2393 mNotificationShown = true;
Dianne Hackborn661cd522011-08-22 00:26:20 -07002394 }
Seigo Nonaka7309b122015-08-17 18:34:13 -07002395 } catch (RemoteException e) {
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002396 }
2397 } else {
2398 if (mNotificationShown && mNotificationManager != null) {
2399 if (DEBUG) {
2400 Slog.d(TAG, "--- hide notification");
satok7cfc0ed2011-06-20 21:29:36 +09002401 }
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002402 mNotificationManager.cancelAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04002403 SystemMessage.NOTE_SELECT_INPUT_METHOD, UserHandle.ALL);
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002404 mNotificationShown = false;
satok7cfc0ed2011-06-20 21:29:36 +09002405 }
satok06487a52010-10-29 11:37:18 +09002406 }
2407 } finally {
2408 Binder.restoreCallingIdentity(ident);
2409 }
2410 }
2411
satoke7c6998e2011-06-03 17:57:59 +09002412 @Override
satokf9f01002011-05-19 21:31:50 +09002413 public void registerSuggestionSpansForNotification(SuggestionSpan[] spans) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002414 if (!calledFromValidUser()) {
2415 return;
2416 }
satokf9f01002011-05-19 21:31:50 +09002417 synchronized (mMethodMap) {
2418 final InputMethodInfo currentImi = mMethodMap.get(mCurMethodId);
2419 for (int i = 0; i < spans.length; ++i) {
2420 SuggestionSpan ss = spans[i];
satok42c5a162011-05-26 16:46:14 +09002421 if (!TextUtils.isEmpty(ss.getNotificationTargetClassName())) {
satokf9f01002011-05-19 21:31:50 +09002422 mSecureSuggestionSpans.put(ss, currentImi);
2423 }
2424 }
2425 }
2426 }
2427
satoke7c6998e2011-06-03 17:57:59 +09002428 @Override
satokf9f01002011-05-19 21:31:50 +09002429 public boolean notifySuggestionPicked(SuggestionSpan span, String originalString, int index) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002430 if (!calledFromValidUser()) {
2431 return false;
2432 }
satokf9f01002011-05-19 21:31:50 +09002433 synchronized (mMethodMap) {
2434 final InputMethodInfo targetImi = mSecureSuggestionSpans.get(span);
2435 // TODO: Do not send the intent if the process of the targetImi is already dead.
2436 if (targetImi != null) {
2437 final String[] suggestions = span.getSuggestions();
2438 if (index < 0 || index >= suggestions.length) return false;
satok42c5a162011-05-26 16:46:14 +09002439 final String className = span.getNotificationTargetClassName();
satokf9f01002011-05-19 21:31:50 +09002440 final Intent intent = new Intent();
2441 // Ensures that only a class in the original IME package will receive the
2442 // notification.
satok42c5a162011-05-26 16:46:14 +09002443 intent.setClassName(targetImi.getPackageName(), className);
satokf9f01002011-05-19 21:31:50 +09002444 intent.setAction(SuggestionSpan.ACTION_SUGGESTION_PICKED);
2445 intent.putExtra(SuggestionSpan.SUGGESTION_SPAN_PICKED_BEFORE, originalString);
2446 intent.putExtra(SuggestionSpan.SUGGESTION_SPAN_PICKED_AFTER, suggestions[index]);
2447 intent.putExtra(SuggestionSpan.SUGGESTION_SPAN_PICKED_HASHCODE, span.hashCode());
Amith Yamasanif043de92012-10-24 06:42:40 -07002448 final long ident = Binder.clearCallingIdentity();
2449 try {
2450 mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT);
2451 } finally {
2452 Binder.restoreCallingIdentity(ident);
2453 }
satokf9f01002011-05-19 21:31:50 +09002454 return true;
2455 }
2456 }
2457 return false;
2458 }
2459
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08002460 void updateFromSettingsLocked(boolean enabledMayChange) {
Michael Wright7b5a96b2014-08-09 19:28:42 -07002461 updateInputMethodsFromSettingsLocked(enabledMayChange);
2462 updateKeyboardFromSettingsLocked();
2463 }
2464
2465 void updateInputMethodsFromSettingsLocked(boolean enabledMayChange) {
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08002466 if (enabledMayChange) {
2467 List<InputMethodInfo> enabled = mSettings.getEnabledInputMethodListLocked();
2468 for (int i=0; i<enabled.size(); i++) {
2469 // We allow the user to select "disabled until used" apps, so if they
2470 // are enabling one of those here we now need to make it enabled.
2471 InputMethodInfo imm = enabled.get(i);
2472 try {
2473 ApplicationInfo ai = mIPackageManager.getApplicationInfo(imm.getPackageName(),
2474 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
2475 mSettings.getCurrentUserId());
Satoshi Kataoka7987a312013-04-17 18:59:33 +09002476 if (ai != null && ai.enabledSetting
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08002477 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
Satoshi Kataokaed1cdb22013-04-17 16:41:58 +09002478 if (DEBUG) {
2479 Slog.d(TAG, "Update state(" + imm.getId()
2480 + "): DISABLED_UNTIL_USED -> DEFAULT");
2481 }
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08002482 mIPackageManager.setApplicationEnabledSetting(imm.getPackageName(),
2483 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07002484 PackageManager.DONT_KILL_APP, mSettings.getCurrentUserId(),
2485 mContext.getBasePackageName());
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08002486 }
2487 } catch (RemoteException e) {
2488 }
2489 }
2490 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002491 // We are assuming that whoever is changing DEFAULT_INPUT_METHOD and
2492 // ENABLED_INPUT_METHODS is taking care of keeping them correctly in
2493 // sync, so we will never have a DEFAULT_INPUT_METHOD that is not
2494 // enabled.
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002495 String id = mSettings.getSelectedInputMethod();
satok03eb319a2010-11-11 18:17:42 +09002496 // There is no input method selected, try to choose new applicable input method.
2497 if (TextUtils.isEmpty(id) && chooseNewDefaultIMELocked()) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002498 id = mSettings.getSelectedInputMethod();
satok03eb319a2010-11-11 18:17:42 +09002499 }
2500 if (!TextUtils.isEmpty(id)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002501 try {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09002502 setInputMethodLocked(id, mSettings.getSelectedInputMethodSubtypeId(id));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 } catch (IllegalArgumentException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002504 Slog.w(TAG, "Unknown input method from prefs: " + id, e);
Yohei Yukawa33e81792015-11-17 21:14:42 -08002505 resetCurrentMethodAndClient(InputMethodClient.UNBIND_REASON_SWITCH_IME_FAILED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002506 }
satokf3db1af2010-11-23 13:34:33 +09002507 mShortcutInputMethodsAndSubtypes.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002508 } else {
2509 // There is no longer an input method set, so stop any current one.
Yohei Yukawa33e81792015-11-17 21:14:42 -08002510 resetCurrentMethodAndClient(InputMethodClient.UNBIND_REASON_NO_IME);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002511 }
Yohei Yukawa3d46bab2014-05-30 18:10:18 +09002512 // Here is not the perfect place to reset the switching controller. Ideally
2513 // mSwitchingController and mSettings should be able to share the same state.
2514 // TODO: Make sure that mSwitchingController and mSettings are sharing the
2515 // the same enabled IMEs list.
2516 mSwitchingController.resetCircularListLocked(mContext);
Michael Wright7b5a96b2014-08-09 19:28:42 -07002517
2518 }
2519
2520 public void updateKeyboardFromSettingsLocked() {
2521 mShowImeWithHardKeyboard = mSettings.isShowImeWithHardKeyboardEnabled();
2522 if (mSwitchingDialog != null
2523 && mSwitchingDialogTitleView != null
2524 && mSwitchingDialog.isShowing()) {
2525 final Switch hardKeySwitch = (Switch)mSwitchingDialogTitleView.findViewById(
2526 com.android.internal.R.id.hard_keyboard_switch);
2527 hardKeySwitch.setChecked(mShowImeWithHardKeyboard);
2528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002530
Yohei Yukawab097b822015-12-01 10:43:08 -08002531 private void notifyInputMethodSubtypeChanged(final int userId,
2532 @Nullable final InputMethodInfo inputMethodInfo,
2533 @Nullable final InputMethodSubtype subtype) {
2534 final InputManagerInternal inputManagerInternal =
2535 LocalServices.getService(InputManagerInternal.class);
2536 if (inputManagerInternal != null) {
2537 inputManagerInternal.onInputMethodSubtypeChanged(userId, inputMethodInfo, subtype);
2538 }
2539 }
2540
satokab751aa2010-09-14 19:17:36 +09002541 /* package */ void setInputMethodLocked(String id, int subtypeId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 InputMethodInfo info = mMethodMap.get(id);
2543 if (info == null) {
satok913a8922010-08-26 21:53:41 +09002544 throw new IllegalArgumentException("Unknown id: " + id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002546
satokd81e9502012-05-21 12:58:45 +09002547 // See if we need to notify a subtype change within the same IME.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002548 if (id.equals(mCurMethodId)) {
satokd81e9502012-05-21 12:58:45 +09002549 final int subtypeCount = info.getSubtypeCount();
2550 if (subtypeCount <= 0) {
2551 return;
satokcd7cd292010-11-20 15:46:23 +09002552 }
satokd81e9502012-05-21 12:58:45 +09002553 final InputMethodSubtype oldSubtype = mCurrentSubtype;
2554 final InputMethodSubtype newSubtype;
2555 if (subtypeId >= 0 && subtypeId < subtypeCount) {
2556 newSubtype = info.getSubtypeAt(subtypeId);
2557 } else {
2558 // If subtype is null, try to find the most applicable one from
2559 // getCurrentInputMethodSubtype.
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002560 newSubtype = getCurrentInputMethodSubtypeLocked();
satokd81e9502012-05-21 12:58:45 +09002561 }
2562 if (newSubtype == null || oldSubtype == null) {
2563 Slog.w(TAG, "Illegal subtype state: old subtype = " + oldSubtype
2564 + ", new subtype = " + newSubtype);
2565 return;
2566 }
2567 if (newSubtype != oldSubtype) {
2568 setSelectedInputMethodAndSubtypeLocked(info, subtypeId, true);
2569 if (mCurMethod != null) {
2570 try {
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002571 updateSystemUiLocked(mCurToken, mImeWindowVis, mBackDisposition);
satokd81e9502012-05-21 12:58:45 +09002572 mCurMethod.changeInputMethodSubtype(newSubtype);
2573 } catch (RemoteException e) {
2574 Slog.w(TAG, "Failed to call changeInputMethodSubtype");
Yohei Yukawab097b822015-12-01 10:43:08 -08002575 return;
satokab751aa2010-09-14 19:17:36 +09002576 }
2577 }
Yohei Yukawab097b822015-12-01 10:43:08 -08002578 notifyInputMethodSubtypeChanged(mSettings.getCurrentUserId(), info, newSubtype);
satokab751aa2010-09-14 19:17:36 +09002579 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 return;
2581 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002582
satokd81e9502012-05-21 12:58:45 +09002583 // Changing to a different IME.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 final long ident = Binder.clearCallingIdentity();
2585 try {
satokab751aa2010-09-14 19:17:36 +09002586 // Set a subtype to this input method.
2587 // subtypeId the name of a subtype which will be set.
satok723a27e2010-11-11 14:58:11 +09002588 setSelectedInputMethodAndSubtypeLocked(info, subtypeId, false);
2589 // mCurMethodId should be updated after setSelectedInputMethodAndSubtypeLocked()
2590 // because mCurMethodId is stored as a history in
2591 // setSelectedInputMethodAndSubtypeLocked().
2592 mCurMethodId = id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002593
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07002594 if (LocalServices.getService(ActivityManagerInternal.class).isSystemReady()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002595 Intent intent = new Intent(Intent.ACTION_INPUT_METHOD_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002596 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002597 intent.putExtra("input_method_id", id);
Amith Yamasanicd757062012-10-19 18:23:52 -07002598 mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002599 }
Yohei Yukawa33e81792015-11-17 21:14:42 -08002600 unbindCurrentClientLocked(InputMethodClient.UNBIND_REASON_SWITCH_IME);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 } finally {
2602 Binder.restoreCallingIdentity(ident);
2603 }
Yohei Yukawab097b822015-12-01 10:43:08 -08002604
2605 notifyInputMethodSubtypeChanged(mSettings.getCurrentUserId(), info,
2606 getCurrentInputMethodSubtypeLocked());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002607 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002608
satok42c5a162011-05-26 16:46:14 +09002609 @Override
The Android Open Source Project4df24232009-03-05 14:34:35 -08002610 public boolean showSoftInput(IInputMethodClient client, int flags,
2611 ResultReceiver resultReceiver) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002612 if (!calledFromValidUser()) {
2613 return false;
2614 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002615 int uid = Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002616 long ident = Binder.clearCallingIdentity();
2617 try {
2618 synchronized (mMethodMap) {
2619 if (mCurClient == null || client == null
2620 || mCurClient.client.asBinder() != client.asBinder()) {
2621 try {
2622 // We need to check if this is the current client with
2623 // focus in the window manager, to allow this call to
2624 // be made before input is started in it.
2625 if (!mIWindowManager.inputMethodClientHasFocus(client)) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002626 Slog.w(TAG, "Ignoring showSoftInput of uid " + uid + ": " + client);
The Android Open Source Project4df24232009-03-05 14:34:35 -08002627 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628 }
2629 } catch (RemoteException e) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08002630 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002631 }
2632 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002633
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07002634 if (DEBUG) Slog.v(TAG, "Client requesting input be shown");
The Android Open Source Project4df24232009-03-05 14:34:35 -08002635 return showCurrentInputLocked(flags, resultReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636 }
2637 } finally {
2638 Binder.restoreCallingIdentity(ident);
2639 }
2640 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002641
The Android Open Source Project4df24232009-03-05 14:34:35 -08002642 boolean showCurrentInputLocked(int flags, ResultReceiver resultReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002643 mShowRequested = true;
Anna Galusza9b278112016-01-04 11:37:37 -08002644 if (mAccessibilityRequestingNoSoftKeyboard) {
2645 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002646 }
Anna Galusza9b278112016-01-04 11:37:37 -08002647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002648 if ((flags&InputMethodManager.SHOW_FORCED) != 0) {
2649 mShowExplicitlyRequested = true;
2650 mShowForced = true;
Anna Galusza9b278112016-01-04 11:37:37 -08002651 } else if ((flags&InputMethodManager.SHOW_IMPLICIT) == 0) {
2652 mShowExplicitlyRequested = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002654
Dianne Hackborncc278702009-09-02 23:07:23 -07002655 if (!mSystemReady) {
2656 return false;
2657 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002658
The Android Open Source Project4df24232009-03-05 14:34:35 -08002659 boolean res = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002660 if (mCurMethod != null) {
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07002661 if (DEBUG) Slog.d(TAG, "showCurrentInputLocked: mCurToken=" + mCurToken);
The Android Open Source Project4df24232009-03-05 14:34:35 -08002662 executeOrSendMessage(mCurMethod, mCaller.obtainMessageIOO(
2663 MSG_SHOW_SOFT_INPUT, getImeShowFlags(), mCurMethod,
2664 resultReceiver));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002665 mInputShown = true;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -07002666 if (mHaveConnection && !mVisibleBound) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002667 bindCurrentInputMethodService(
Yohei Yukawaa67a4592017-03-30 15:57:02 -07002668 mCurIntent, mVisibleConnection, IME_VISIBLE_BIND_FLAGS);
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -07002669 mVisibleBound = true;
2670 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08002671 res = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 } else if (mHaveConnection && SystemClock.uptimeMillis()
satok59b424c2011-09-30 17:21:46 +09002673 >= (mLastBindTime+TIME_TO_RECONNECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674 // The client has asked to have the input method shown, but
2675 // we have been sitting here too long with a connection to the
2676 // service and no interface received, so let's disconnect/connect
2677 // to try to prod things along.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002678 EventLog.writeEvent(EventLogTags.IMF_FORCE_RECONNECT_IME, mCurMethodId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 SystemClock.uptimeMillis()-mLastBindTime,1);
satok59b424c2011-09-30 17:21:46 +09002680 Slog.w(TAG, "Force disconnect/connect to the IME in showCurrentInputLocked()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002681 mContext.unbindService(this);
Yohei Yukawaa67a4592017-03-30 15:57:02 -07002682 bindCurrentInputMethodService(mCurIntent, this, IME_CONNECTION_BIND_FLAGS);
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002683 } else {
2684 if (DEBUG) {
2685 Slog.d(TAG, "Can't show input: connection = " + mHaveConnection + ", time = "
2686 + ((mLastBindTime+TIME_TO_RECONNECT) - SystemClock.uptimeMillis()));
2687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002689
The Android Open Source Project4df24232009-03-05 14:34:35 -08002690 return res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002691 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002692
satok42c5a162011-05-26 16:46:14 +09002693 @Override
The Android Open Source Project4df24232009-03-05 14:34:35 -08002694 public boolean hideSoftInput(IInputMethodClient client, int flags,
2695 ResultReceiver resultReceiver) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002696 if (!calledFromValidUser()) {
2697 return false;
2698 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002699 int uid = Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002700 long ident = Binder.clearCallingIdentity();
2701 try {
2702 synchronized (mMethodMap) {
2703 if (mCurClient == null || client == null
2704 || mCurClient.client.asBinder() != client.asBinder()) {
2705 try {
2706 // We need to check if this is the current client with
2707 // focus in the window manager, to allow this call to
2708 // be made before input is started in it.
2709 if (!mIWindowManager.inputMethodClientHasFocus(client)) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002710 if (DEBUG) Slog.w(TAG, "Ignoring hideSoftInput of uid "
2711 + uid + ": " + client);
The Android Open Source Project4df24232009-03-05 14:34:35 -08002712 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002713 }
2714 } catch (RemoteException e) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08002715 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 }
2717 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002718
Joe Onorato8a9b2202010-02-26 18:56:32 -08002719 if (DEBUG) Slog.v(TAG, "Client requesting input be hidden");
The Android Open Source Project4df24232009-03-05 14:34:35 -08002720 return hideCurrentInputLocked(flags, resultReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002721 }
2722 } finally {
2723 Binder.restoreCallingIdentity(ident);
2724 }
2725 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002726
The Android Open Source Project4df24232009-03-05 14:34:35 -08002727 boolean hideCurrentInputLocked(int flags, ResultReceiver resultReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002728 if ((flags&InputMethodManager.HIDE_IMPLICIT_ONLY) != 0
2729 && (mShowExplicitlyRequested || mShowForced)) {
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07002730 if (DEBUG) Slog.v(TAG, "Not hiding: explicit show not cancelled by non-explicit hide");
The Android Open Source Project4df24232009-03-05 14:34:35 -08002731 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002732 }
2733 if (mShowForced && (flags&InputMethodManager.HIDE_NOT_ALWAYS) != 0) {
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07002734 if (DEBUG) Slog.v(TAG, "Not hiding: forced show not cancelled by not-always hide");
The Android Open Source Project4df24232009-03-05 14:34:35 -08002735 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002736 }
Seigo Nonakaec928652015-06-10 15:31:20 +09002737
2738 // There is a chance that IMM#hideSoftInput() is called in a transient state where
2739 // IMMS#InputShown is already updated to be true whereas IMMS#mImeWindowVis is still waiting
2740 // to be updated with the new value sent from IME process. Even in such a transient state
2741 // historically we have accepted an incoming call of IMM#hideSoftInput() from the
2742 // application process as a valid request, and have even promised such a behavior with CTS
2743 // since Android Eclair. That's why we need to accept IMM#hideSoftInput() even when only
2744 // IMMS#InputShown indicates that the software keyboard is shown.
2745 // TODO: Clean up, IMMS#mInputShown, IMMS#mImeWindowVis and mShowRequested.
2746 final boolean shouldHideSoftInput = (mCurMethod != null) && (mInputShown ||
2747 (mImeWindowVis & InputMethodService.IME_ACTIVE) != 0);
The Android Open Source Project4df24232009-03-05 14:34:35 -08002748 boolean res;
Seigo Nonakaec928652015-06-10 15:31:20 +09002749 if (shouldHideSoftInput) {
2750 // The IME will report its visible state again after the following message finally
2751 // delivered to the IME process as an IPC. Hence the inconsistency between
2752 // IMMS#mInputShown and IMMS#mImeWindowVis should be resolved spontaneously in
2753 // the final state.
The Android Open Source Project4df24232009-03-05 14:34:35 -08002754 executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
2755 MSG_HIDE_SOFT_INPUT, mCurMethod, resultReceiver));
2756 res = true;
2757 } else {
2758 res = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 }
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -07002760 if (mHaveConnection && mVisibleBound) {
2761 mContext.unbindService(mVisibleConnection);
2762 mVisibleBound = false;
2763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002764 mInputShown = false;
2765 mShowRequested = false;
2766 mShowExplicitlyRequested = false;
2767 mShowForced = false;
The Android Open Source Project4df24232009-03-05 14:34:35 -08002768 return res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002770
Yohei Yukawa2553e482017-12-15 15:47:33 -08002771 @NonNull
satok42c5a162011-05-26 16:46:14 +09002772 @Override
Yohei Yukawa05c25f82016-02-22 12:41:17 -08002773 public InputBindResult startInputOrWindowGainedFocus(
2774 /* @InputMethodClient.StartInputReason */ final int startInputReason,
2775 IInputMethodClient client, IBinder windowToken, int controlFlags, int softInputMode,
Yohei Yukawa74750f22016-03-22 12:54:22 -07002776 int windowFlags, @Nullable EditorInfo attribute, IInputContext inputContext,
Yohei Yukawacf68d522017-12-12 09:33:26 -08002777 /* @InputConnectionInspector.missingMethods */ final int missingMethods,
2778 int unverifiedTargetSdkVersion) {
Yohei Yukawa2553e482017-12-15 15:47:33 -08002779 final InputBindResult result;
Yohei Yukawa05c25f82016-02-22 12:41:17 -08002780 if (windowToken != null) {
Yohei Yukawa2553e482017-12-15 15:47:33 -08002781 result = windowGainedFocus(startInputReason, client, windowToken, controlFlags,
Yohei Yukawacf68d522017-12-12 09:33:26 -08002782 softInputMode, windowFlags, attribute, inputContext, missingMethods,
2783 unverifiedTargetSdkVersion);
Yohei Yukawa05c25f82016-02-22 12:41:17 -08002784 } else {
Yohei Yukawa2553e482017-12-15 15:47:33 -08002785 result = startInput(startInputReason, client, inputContext, missingMethods, attribute,
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002786 controlFlags);
Yohei Yukawa05c25f82016-02-22 12:41:17 -08002787 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08002788 if (result == null) {
2789 // This must never happen, but just in case.
2790 Slog.wtf(TAG, "InputBindResult is @NonNull. startInputReason="
2791 + InputMethodClient.getStartInputReason(startInputReason)
2792 + " windowFlags=#" + Integer.toHexString(windowFlags)
2793 + " editorInfo=" + attribute);
2794 return InputBindResult.NULL;
2795 }
2796 return result;
Yohei Yukawa05c25f82016-02-22 12:41:17 -08002797 }
2798
Yohei Yukawa2553e482017-12-15 15:47:33 -08002799 @NonNull
Yohei Yukawa05c25f82016-02-22 12:41:17 -08002800 private InputBindResult windowGainedFocus(
Yohei Yukawa35d3f372015-11-25 11:07:19 -08002801 /* @InputMethodClient.StartInputReason */ final int startInputReason,
Yohei Yukawa22dac1c2017-02-12 16:54:16 -08002802 IInputMethodClient client, IBinder windowToken, int controlFlags,
2803 /* @android.view.WindowManager.LayoutParams.SoftInputModeFlags */ int softInputMode,
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002804 int windowFlags, EditorInfo attribute, IInputContext inputContext,
Yohei Yukawacf68d522017-12-12 09:33:26 -08002805 /* @InputConnectionInspector.missingMethods */ final int missingMethods,
2806 int unverifiedTargetSdkVersion) {
Satoshi Kataoka8d033052012-11-19 17:30:40 +09002807 // Needs to check the validity before clearing calling identity
2808 final boolean calledFromValidUser = calledFromValidUser();
Dianne Hackborn7663d802012-02-24 13:08:49 -08002809 InputBindResult res = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002810 long ident = Binder.clearCallingIdentity();
2811 try {
2812 synchronized (mMethodMap) {
Yohei Yukawa35d3f372015-11-25 11:07:19 -08002813 if (DEBUG) Slog.v(TAG, "windowGainedFocus: reason="
2814 + InputMethodClient.getStartInputReason(startInputReason)
2815 + " client=" + client.asBinder()
2816 + " inputContext=" + inputContext
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002817 + " missingMethods="
2818 + InputConnectionInspector.getMissingMethodFlagsAsString(missingMethods)
Yohei Yukawa35d3f372015-11-25 11:07:19 -08002819 + " attribute=" + attribute
Dianne Hackborn7663d802012-02-24 13:08:49 -08002820 + " controlFlags=#" + Integer.toHexString(controlFlags)
Yohei Yukawa22a89232017-02-12 16:38:59 -08002821 + " softInputMode=" + InputMethodClient.softInputModeToString(softInputMode)
Yohei Yukawacf68d522017-12-12 09:33:26 -08002822 + " windowFlags=#" + Integer.toHexString(windowFlags)
2823 + " unverifiedTargetSdkVersion=" + unverifiedTargetSdkVersion);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002824
Dianne Hackborn7663d802012-02-24 13:08:49 -08002825 ClientState cs = mClients.get(client.asBinder());
2826 if (cs == null) {
2827 throw new IllegalArgumentException("unknown client "
2828 + client.asBinder());
2829 }
2830
2831 try {
2832 if (!mIWindowManager.inputMethodClientHasFocus(cs.client)) {
2833 // Check with the window manager to make sure this client actually
2834 // has a window with focus. If not, reject. This is thread safe
2835 // because if the focus changes some time before or after, the
2836 // next client receiving focus that has any interest in input will
2837 // be calling through here after that change happens.
Yohei Yukawad0332832017-02-01 13:59:43 -08002838 if (DEBUG) {
2839 Slog.w(TAG, "Focus gain on non-focused client " + cs.client
2840 + " (uid=" + cs.uid + " pid=" + cs.pid + ")");
2841 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08002842 return InputBindResult.NOT_IME_TARGET_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002843 }
Dianne Hackborn7663d802012-02-24 13:08:49 -08002844 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002846
Satoshi Kataoka8d033052012-11-19 17:30:40 +09002847 if (!calledFromValidUser) {
2848 Slog.w(TAG, "A background user is requesting window. Hiding IME.");
2849 Slog.w(TAG, "If you want to interect with IME, you need "
2850 + "android.permission.INTERACT_ACROSS_USERS_FULL");
2851 hideCurrentInputLocked(0, null);
Yohei Yukawa2553e482017-12-15 15:47:33 -08002852 return InputBindResult.INVALID_USER;
Satoshi Kataoka8d033052012-11-19 17:30:40 +09002853 }
2854
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002855 if (mCurFocusedWindow == windowToken) {
Yohei Yukawad0332832017-02-01 13:59:43 -08002856 if (DEBUG) {
2857 Slog.w(TAG, "Window already focused, ignoring focus gain of: " + client
2858 + " attribute=" + attribute + ", token = " + windowToken);
2859 }
Dianne Hackborn7663d802012-02-24 13:08:49 -08002860 if (attribute != null) {
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002861 return startInputUncheckedLocked(cs, inputContext, missingMethods,
Yohei Yukawa87ca8402017-02-07 00:13:14 -08002862 attribute, controlFlags, startInputReason);
Dianne Hackborn7663d802012-02-24 13:08:49 -08002863 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08002864 return new InputBindResult(
2865 InputBindResult.ResultCode.SUCCESS_REPORT_WINDOW_FOCUS_ONLY,
2866 null, null, null, -1, -1);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002867 }
2868 mCurFocusedWindow = windowToken;
Yohei Yukawa22a89232017-02-12 16:38:59 -08002869 mCurFocusedWindowSoftInputMode = softInputMode;
Yohei Yukawae39d4ed2015-11-19 03:38:49 -08002870 mCurFocusedWindowClient = cs;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002871
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -08002872 // Should we auto-show the IME even if the caller has not
2873 // specified what should be done with it?
2874 // We only do this automatically if the window can resize
2875 // to accommodate the IME (so what the user sees will give
2876 // them good context without input information being obscured
2877 // by the IME) or if running on a large screen where there
2878 // is more room for the target window + IME.
2879 final boolean doAutoShow =
2880 (softInputMode & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
2881 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
2882 || mRes.getConfiguration().isLayoutSizeAtLeast(
2883 Configuration.SCREENLAYOUT_SIZE_LARGE);
Dianne Hackborn7663d802012-02-24 13:08:49 -08002884 final boolean isTextEditor =
2885 (controlFlags&InputMethodManager.CONTROL_WINDOW_IS_TEXT_EDITOR) != 0;
2886
2887 // We want to start input before showing the IME, but after closing
2888 // it. We want to do this after closing it to help the IME disappear
2889 // more quickly (not get stuck behind it initializing itself for the
2890 // new focused input, even if its window wants to hide the IME).
2891 boolean didStart = false;
Yohei Yukawa0f3ad12015-04-06 16:48:24 -07002892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 switch (softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_STATE) {
2894 case WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED:
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -08002895 if (!isTextEditor || !doAutoShow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002896 if (WindowManager.LayoutParams.mayUseInputMethod(windowFlags)) {
2897 // There is no focus view, and this window will
2898 // be behind any soft input window, so hide the
2899 // soft input window if it is shown.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002900 if (DEBUG) Slog.v(TAG, "Unspecified window will hide input");
The Android Open Source Project4df24232009-03-05 14:34:35 -08002901 hideCurrentInputLocked(InputMethodManager.HIDE_NOT_ALWAYS, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902 }
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -08002903 } else if (isTextEditor && doAutoShow && (softInputMode &
2904 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 // There is a focus view, and we are navigating forward
2906 // into the window, so show the input window for the user.
Dianne Hackborn7663d802012-02-24 13:08:49 -08002907 // We only do this automatically if the window can resize
2908 // to accommodate the IME (so what the user sees will give
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -08002909 // them good context without input information being obscured
2910 // by the IME) or if running on a large screen where there
2911 // is more room for the target window + IME.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002912 if (DEBUG) Slog.v(TAG, "Unspecified window will show input");
Dianne Hackborn7663d802012-02-24 13:08:49 -08002913 if (attribute != null) {
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002914 res = startInputUncheckedLocked(cs, inputContext,
Yohei Yukawa87ca8402017-02-07 00:13:14 -08002915 missingMethods, attribute, controlFlags, startInputReason);
Dianne Hackborn7663d802012-02-24 13:08:49 -08002916 didStart = true;
2917 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08002918 showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002919 }
2920 break;
2921 case WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED:
2922 // Do nothing.
2923 break;
2924 case WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN:
2925 if ((softInputMode &
2926 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002927 if (DEBUG) Slog.v(TAG, "Window asks to hide input going forward");
The Android Open Source Project4df24232009-03-05 14:34:35 -08002928 hideCurrentInputLocked(0, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002929 }
2930 break;
2931 case WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN:
Joe Onorato8a9b2202010-02-26 18:56:32 -08002932 if (DEBUG) Slog.v(TAG, "Window asks to hide input");
The Android Open Source Project4df24232009-03-05 14:34:35 -08002933 hideCurrentInputLocked(0, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002934 break;
2935 case WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE:
2936 if ((softInputMode &
2937 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002938 if (DEBUG) Slog.v(TAG, "Window asks to show input going forward");
Yohei Yukawacf68d522017-12-12 09:33:26 -08002939 if (InputMethodUtils.isSoftInputModeStateVisibleAllowed(
2940 unverifiedTargetSdkVersion, controlFlags)) {
2941 if (attribute != null) {
2942 res = startInputUncheckedLocked(cs, inputContext,
2943 missingMethods, attribute, controlFlags,
2944 startInputReason);
2945 didStart = true;
2946 }
2947 showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
2948 } else {
2949 Slog.e(TAG, "SOFT_INPUT_STATE_VISIBLE is ignored because"
2950 + " there is no focused view that also returns true from"
2951 + " View#onCheckIsTextEditor()");
Dianne Hackborn7663d802012-02-24 13:08:49 -08002952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002953 }
2954 break;
2955 case WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE:
Joe Onorato8a9b2202010-02-26 18:56:32 -08002956 if (DEBUG) Slog.v(TAG, "Window asks to always show input");
Yohei Yukawacf68d522017-12-12 09:33:26 -08002957 if (InputMethodUtils.isSoftInputModeStateVisibleAllowed(
2958 unverifiedTargetSdkVersion, controlFlags)) {
2959 if (attribute != null) {
2960 res = startInputUncheckedLocked(cs, inputContext, missingMethods,
2961 attribute, controlFlags, startInputReason);
2962 didStart = true;
2963 }
2964 showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
2965 } else {
2966 Slog.e(TAG, "SOFT_INPUT_STATE_ALWAYS_VISIBLE is ignored because"
2967 + " there is no focused view that also returns true from"
2968 + " View#onCheckIsTextEditor()");
Dianne Hackborn7663d802012-02-24 13:08:49 -08002969 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002970 break;
2971 }
Dianne Hackborn7663d802012-02-24 13:08:49 -08002972
Tarandeep Singh2f731c552018-02-05 13:55:06 -08002973 if (!didStart) {
2974 if (attribute != null) {
2975 if (!DebugFlags.FLAG_OPTIMIZE_START_INPUT.value()
2976 || (controlFlags
2977 & InputMethodManager.CONTROL_WINDOW_IS_TEXT_EDITOR) != 0) {
2978 res = startInputUncheckedLocked(cs, inputContext, missingMethods,
2979 attribute,
2980 controlFlags, startInputReason);
2981 } else {
2982 res = InputBindResult.NO_EDITOR;
2983 }
2984 } else {
2985 res = InputBindResult.NULL_EDITOR_INFO;
Tarandeep Singh75a92392018-01-12 14:58:59 -08002986 }
Dianne Hackborn7663d802012-02-24 13:08:49 -08002987 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002988 }
2989 } finally {
2990 Binder.restoreCallingIdentity(ident);
2991 }
Dianne Hackborn7663d802012-02-24 13:08:49 -08002992
2993 return res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002994 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002995
Guliz Tuncay6908c152017-06-02 16:06:10 -07002996 private boolean canShowInputMethodPickerLocked(IInputMethodClient client) {
2997 final int uid = Binder.getCallingUid();
2998 if (UserHandle.getAppId(uid) == Process.SYSTEM_UID) {
2999 return true;
Tarandeep Singheb570612018-01-29 16:20:32 -08003000 } else if (mCurFocusedWindowClient != null && client != null
3001 && mCurFocusedWindowClient.client.asBinder() == client.asBinder()) {
Guliz Tuncay6908c152017-06-02 16:06:10 -07003002 return true;
3003 } else if (mCurIntent != null && InputMethodUtils.checkIfPackageBelongsToUid(
3004 mAppOpsManager,
3005 uid,
3006 mCurIntent.getComponent().getPackageName())) {
3007 return true;
3008 } else if (mContext.checkCallingPermission(
3009 android.Manifest.permission.WRITE_SECURE_SETTINGS)
3010 == PackageManager.PERMISSION_GRANTED) {
3011 return true;
3012 }
3013
3014 return false;
3015 }
3016
satok42c5a162011-05-26 16:46:14 +09003017 @Override
Seigo Nonaka14e13912015-05-06 21:04:13 -07003018 public void showInputMethodPickerFromClient(
3019 IInputMethodClient client, int auxiliarySubtypeMode) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003020 if (!calledFromValidUser()) {
3021 return;
3022 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003023 synchronized (mMethodMap) {
Guliz Tuncay6908c152017-06-02 16:06:10 -07003024 if(!canShowInputMethodPickerLocked(client)) {
satok47a44912010-10-06 16:03:58 +09003025 Slog.w(TAG, "Ignoring showInputMethodPickerFromClient of uid "
Dianne Hackborncef65ee2010-09-30 18:27:22 -07003026 + Binder.getCallingUid() + ": " + client);
Guliz Tuncay6908c152017-06-02 16:06:10 -07003027 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003028 }
3029
satok440aab52010-11-25 09:43:11 +09003030 // Always call subtype picker, because subtype picker is a superset of input method
3031 // picker.
Seigo Nonaka14e13912015-05-06 21:04:13 -07003032 mHandler.sendMessage(mCaller.obtainMessageI(
3033 MSG_SHOW_IM_SUBTYPE_PICKER, auxiliarySubtypeMode));
satokab751aa2010-09-14 19:17:36 +09003034 }
3035 }
3036
Tarandeep Singheb570612018-01-29 16:20:32 -08003037 public boolean isInputMethodPickerShownForTest() {
3038 synchronized(mMethodMap) {
3039 if (mSwitchingDialog == null) {
3040 return false;
3041 }
3042 return mSwitchingDialog.isShowing();
3043 }
3044 }
3045
satok42c5a162011-05-26 16:46:14 +09003046 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003047 public void setInputMethod(IBinder token, String id) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003048 if (!calledFromValidUser()) {
3049 return;
3050 }
satok28203512010-11-24 11:06:49 +09003051 setInputMethodWithSubtypeId(token, id, NOT_A_SUBTYPE_ID);
3052 }
3053
satok42c5a162011-05-26 16:46:14 +09003054 @Override
satok28203512010-11-24 11:06:49 +09003055 public void setInputMethodAndSubtype(IBinder token, String id, InputMethodSubtype subtype) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003056 if (!calledFromValidUser()) {
3057 return;
3058 }
satok28203512010-11-24 11:06:49 +09003059 synchronized (mMethodMap) {
3060 if (subtype != null) {
Yohei Yukawa4e02bc62014-06-04 18:37:20 +09003061 setInputMethodWithSubtypeIdLocked(token, id,
3062 InputMethodUtils.getSubtypeIdFromHashCode(mMethodMap.get(id),
3063 subtype.hashCode()));
satok28203512010-11-24 11:06:49 +09003064 } else {
3065 setInputMethod(token, id);
3066 }
3067 }
satokab751aa2010-09-14 19:17:36 +09003068 }
3069
satok42c5a162011-05-26 16:46:14 +09003070 @Override
satokb416a712010-11-25 20:42:14 +09003071 public void showInputMethodAndSubtypeEnablerFromClient(
satok217f5482010-12-15 05:19:19 +09003072 IInputMethodClient client, String inputMethodId) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003073 if (!calledFromValidUser()) {
3074 return;
3075 }
satokb416a712010-11-25 20:42:14 +09003076 synchronized (mMethodMap) {
satok7fee71f2010-12-17 18:54:26 +09003077 executeOrSendMessage(mCurMethod, mCaller.obtainMessageO(
3078 MSG_SHOW_IM_SUBTYPE_ENABLER, inputMethodId));
satokb416a712010-11-25 20:42:14 +09003079 }
3080 }
3081
satok4fc87d62011-05-20 16:13:43 +09003082 @Override
satok735cf382010-11-11 20:40:09 +09003083 public boolean switchToLastInputMethod(IBinder token) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003084 if (!calledFromValidUser()) {
3085 return false;
3086 }
satok735cf382010-11-11 20:40:09 +09003087 synchronized (mMethodMap) {
satokc445bcd2011-01-25 18:57:24 +09003088 final Pair<String, String> lastIme = mSettings.getLastInputMethodAndSubtypeLocked();
satok4fc87d62011-05-20 16:13:43 +09003089 final InputMethodInfo lastImi;
satok208d5632011-05-20 22:13:38 +09003090 if (lastIme != null) {
satok4fc87d62011-05-20 16:13:43 +09003091 lastImi = mMethodMap.get(lastIme.first);
3092 } else {
3093 lastImi = null;
satok735cf382010-11-11 20:40:09 +09003094 }
satok4fc87d62011-05-20 16:13:43 +09003095 String targetLastImiId = null;
3096 int subtypeId = NOT_A_SUBTYPE_ID;
3097 if (lastIme != null && lastImi != null) {
3098 final boolean imiIdIsSame = lastImi.getId().equals(mCurMethodId);
Narayan Kamatha09b4d22016-04-15 18:32:45 +01003099 final int lastSubtypeHash = Integer.parseInt(lastIme.second);
satok4fc87d62011-05-20 16:13:43 +09003100 final int currentSubtypeHash = mCurrentSubtype == null ? NOT_A_SUBTYPE_ID
3101 : mCurrentSubtype.hashCode();
3102 // If the last IME is the same as the current IME and the last subtype is not
3103 // defined, there is no need to switch to the last IME.
3104 if (!imiIdIsSame || lastSubtypeHash != currentSubtypeHash) {
3105 targetLastImiId = lastIme.first;
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003106 subtypeId = InputMethodUtils.getSubtypeIdFromHashCode(lastImi, lastSubtypeHash);
satok4fc87d62011-05-20 16:13:43 +09003107 }
3108 }
3109
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003110 if (TextUtils.isEmpty(targetLastImiId)
3111 && !InputMethodUtils.canAddToLastInputMethod(mCurrentSubtype)) {
satok4fc87d62011-05-20 16:13:43 +09003112 // This is a safety net. If the currentSubtype can't be added to the history
3113 // and the framework couldn't find the last ime, we will make the last ime be
3114 // the most applicable enabled keyboard subtype of the system imes.
3115 final List<InputMethodInfo> enabled = mSettings.getEnabledInputMethodListLocked();
3116 if (enabled != null) {
3117 final int N = enabled.size();
3118 final String locale = mCurrentSubtype == null
3119 ? mRes.getConfiguration().locale.toString()
3120 : mCurrentSubtype.getLocale();
3121 for (int i = 0; i < N; ++i) {
3122 final InputMethodInfo imi = enabled.get(i);
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003123 if (imi.getSubtypeCount() > 0 && InputMethodUtils.isSystemIme(imi)) {
satok4fc87d62011-05-20 16:13:43 +09003124 InputMethodSubtype keyboardSubtype =
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003125 InputMethodUtils.findLastResortApplicableSubtypeLocked(mRes,
3126 InputMethodUtils.getSubtypes(imi),
3127 InputMethodUtils.SUBTYPE_MODE_KEYBOARD, locale, true);
satok4fc87d62011-05-20 16:13:43 +09003128 if (keyboardSubtype != null) {
3129 targetLastImiId = imi.getId();
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003130 subtypeId = InputMethodUtils.getSubtypeIdFromHashCode(
satok4fc87d62011-05-20 16:13:43 +09003131 imi, keyboardSubtype.hashCode());
3132 if(keyboardSubtype.getLocale().equals(locale)) {
3133 break;
3134 }
3135 }
3136 }
3137 }
3138 }
3139 }
3140
3141 if (!TextUtils.isEmpty(targetLastImiId)) {
3142 if (DEBUG) {
3143 Slog.d(TAG, "Switch to: " + lastImi.getId() + ", " + lastIme.second
3144 + ", from: " + mCurMethodId + ", " + subtypeId);
3145 }
Yohei Yukawa4e02bc62014-06-04 18:37:20 +09003146 setInputMethodWithSubtypeIdLocked(token, targetLastImiId, subtypeId);
satok4fc87d62011-05-20 16:13:43 +09003147 return true;
3148 } else {
3149 return false;
3150 }
satok735cf382010-11-11 20:40:09 +09003151 }
3152 }
3153
satoke7c6998e2011-06-03 17:57:59 +09003154 @Override
satok688bd472012-02-09 20:09:17 +09003155 public boolean switchToNextInputMethod(IBinder token, boolean onlyCurrentIme) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003156 if (!calledFromValidUser()) {
3157 return false;
3158 }
satok688bd472012-02-09 20:09:17 +09003159 synchronized (mMethodMap) {
Yohei Yukawaa0755742014-06-04 20:28:18 +09003160 if (!calledWithValidToken(token)) {
Yohei Yukawaa0755742014-06-04 20:28:18 +09003161 return false;
3162 }
Yohei Yukawa5a647b692014-05-22 12:49:00 +09003163 final ImeSubtypeListItem nextSubtype = mSwitchingController.getNextInputMethodLocked(
Yohei Yukawad39ae852016-04-10 20:28:40 -07003164 onlyCurrentIme, mMethodMap.get(mCurMethodId), mCurrentSubtype,
3165 true /* forward */);
satok688bd472012-02-09 20:09:17 +09003166 if (nextSubtype == null) {
3167 return false;
3168 }
Yohei Yukawa4e02bc62014-06-04 18:37:20 +09003169 setInputMethodWithSubtypeIdLocked(token, nextSubtype.mImi.getId(),
3170 nextSubtype.mSubtypeId);
satok688bd472012-02-09 20:09:17 +09003171 return true;
3172 }
3173 }
3174
3175 @Override
Satoshi Kataoka2b10b522013-08-21 20:39:12 +09003176 public boolean shouldOfferSwitchingToNextInputMethod(IBinder token) {
3177 if (!calledFromValidUser()) {
3178 return false;
3179 }
3180 synchronized (mMethodMap) {
Yohei Yukawaa0755742014-06-04 20:28:18 +09003181 if (!calledWithValidToken(token)) {
Yohei Yukawaa0755742014-06-04 20:28:18 +09003182 return false;
3183 }
Yohei Yukawa5a647b692014-05-22 12:49:00 +09003184 final ImeSubtypeListItem nextSubtype = mSwitchingController.getNextInputMethodLocked(
Yohei Yukawad39ae852016-04-10 20:28:40 -07003185 false /* onlyCurrentIme */, mMethodMap.get(mCurMethodId), mCurrentSubtype,
3186 true /* forward */);
Satoshi Kataoka2b10b522013-08-21 20:39:12 +09003187 if (nextSubtype == null) {
3188 return false;
3189 }
3190 return true;
3191 }
3192 }
3193
3194 @Override
satok68f1b782011-04-11 14:26:04 +09003195 public InputMethodSubtype getLastInputMethodSubtype() {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003196 if (!calledFromValidUser()) {
3197 return null;
3198 }
satok68f1b782011-04-11 14:26:04 +09003199 synchronized (mMethodMap) {
3200 final Pair<String, String> lastIme = mSettings.getLastInputMethodAndSubtypeLocked();
3201 // TODO: Handle the case of the last IME with no subtypes
3202 if (lastIme == null || TextUtils.isEmpty(lastIme.first)
3203 || TextUtils.isEmpty(lastIme.second)) return null;
3204 final InputMethodInfo lastImi = mMethodMap.get(lastIme.first);
3205 if (lastImi == null) return null;
3206 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01003207 final int lastSubtypeHash = Integer.parseInt(lastIme.second);
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003208 final int lastSubtypeId =
3209 InputMethodUtils.getSubtypeIdFromHashCode(lastImi, lastSubtypeHash);
satok0e7d7d62011-07-05 13:28:06 +09003210 if (lastSubtypeId < 0 || lastSubtypeId >= lastImi.getSubtypeCount()) {
3211 return null;
3212 }
3213 return lastImi.getSubtypeAt(lastSubtypeId);
satok68f1b782011-04-11 14:26:04 +09003214 } catch (NumberFormatException e) {
3215 return null;
3216 }
3217 }
3218 }
3219
satoke7c6998e2011-06-03 17:57:59 +09003220 @Override
satokee5e77c2011-09-02 18:50:15 +09003221 public void setAdditionalInputMethodSubtypes(String imiId, InputMethodSubtype[] subtypes) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003222 if (!calledFromValidUser()) {
3223 return;
3224 }
satok91e88122011-07-18 11:11:42 +09003225 // By this IPC call, only a process which shares the same uid with the IME can add
3226 // additional input method subtypes to the IME.
Yohei Yukawa70f5c482016-01-04 19:42:36 -08003227 if (TextUtils.isEmpty(imiId) || subtypes == null) return;
satoke7c6998e2011-06-03 17:57:59 +09003228 synchronized (mMethodMap) {
Yohei Yukawa79247822017-01-23 15:26:15 -08003229 if (!mSystemReady) {
3230 return;
3231 }
satok91e88122011-07-18 11:11:42 +09003232 final InputMethodInfo imi = mMethodMap.get(imiId);
satokee5e77c2011-09-02 18:50:15 +09003233 if (imi == null) return;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003234 final String[] packageInfos;
3235 try {
3236 packageInfos = mIPackageManager.getPackagesForUid(Binder.getCallingUid());
3237 } catch (RemoteException e) {
3238 Slog.e(TAG, "Failed to get package infos");
3239 return;
3240 }
satok91e88122011-07-18 11:11:42 +09003241 if (packageInfos != null) {
3242 final int packageNum = packageInfos.length;
3243 for (int i = 0; i < packageNum; ++i) {
3244 if (packageInfos[i].equals(imi.getPackageName())) {
3245 mFileManager.addInputMethodSubtypes(imi, subtypes);
satokc5933802011-08-31 21:26:04 +09003246 final long ident = Binder.clearCallingIdentity();
3247 try {
Yohei Yukawa94e33302016-02-12 19:37:03 -08003248 buildInputMethodListLocked(false /* resetDefaultEnabledIme */);
satokc5933802011-08-31 21:26:04 +09003249 } finally {
3250 Binder.restoreCallingIdentity(ident);
3251 }
satokee5e77c2011-09-02 18:50:15 +09003252 return;
satok91e88122011-07-18 11:11:42 +09003253 }
3254 }
3255 }
satoke7c6998e2011-06-03 17:57:59 +09003256 }
satokee5e77c2011-09-02 18:50:15 +09003257 return;
satoke7c6998e2011-06-03 17:57:59 +09003258 }
3259
Satoshi Kataoka658c7b82013-10-10 17:03:51 +09003260 @Override
3261 public int getInputMethodWindowVisibleHeight() {
Seigo Nonaka7309b122015-08-17 18:34:13 -07003262 return mWindowManagerInternal.getInputMethodWindowVisibleHeight();
Satoshi Kataoka658c7b82013-10-10 17:03:51 +09003263 }
3264
Satoshi Kataokad7443c82013-10-15 17:45:43 +09003265 @Override
Yohei Yukawa833bdce2016-05-15 20:05:56 -07003266 public void clearLastInputMethodWindowForTransition(IBinder token) {
3267 if (!calledFromValidUser()) {
3268 return;
3269 }
Yohei Yukawafa49c002017-01-31 19:15:00 -08003270 synchronized (mMethodMap) {
3271 if (!calledWithValidToken(token)) {
Yohei Yukawafa49c002017-01-31 19:15:00 -08003272 return;
Yohei Yukawa833bdce2016-05-15 20:05:56 -07003273 }
Yohei Yukawa833bdce2016-05-15 20:05:56 -07003274 }
Yohei Yukawafa49c002017-01-31 19:15:00 -08003275 mWindowManagerInternal.clearLastInputMethodWindowForTransition();
Yohei Yukawa833bdce2016-05-15 20:05:56 -07003276 }
3277
3278 @Override
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003279 public void notifyUserAction(int sequenceNumber) {
Satoshi Kataokad7443c82013-10-15 17:45:43 +09003280 if (DEBUG) {
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003281 Slog.d(TAG, "Got the notification of a user action. sequenceNumber:" + sequenceNumber);
Satoshi Kataokad7443c82013-10-15 17:45:43 +09003282 }
Yohei Yukawa5a647b692014-05-22 12:49:00 +09003283 synchronized (mMethodMap) {
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003284 if (mCurUserActionNotificationSequenceNumber != sequenceNumber) {
3285 if (DEBUG) {
3286 Slog.d(TAG, "Ignoring the user action notification due to the sequence number "
3287 + "mismatch. expected:" + mCurUserActionNotificationSequenceNumber
3288 + " actual: " + sequenceNumber);
3289 }
3290 return;
3291 }
Yohei Yukawa5a647b692014-05-22 12:49:00 +09003292 final InputMethodInfo imi = mMethodMap.get(mCurMethodId);
3293 if (imi != null) {
Yohei Yukawa02970512014-06-05 16:16:18 +09003294 mSwitchingController.onUserActionLocked(imi, mCurrentSubtype);
Yohei Yukawa5a647b692014-05-22 12:49:00 +09003295 }
Satoshi Kataokad7443c82013-10-15 17:45:43 +09003296 }
3297 }
3298
satok28203512010-11-24 11:06:49 +09003299 private void setInputMethodWithSubtypeId(IBinder token, String id, int subtypeId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 synchronized (mMethodMap) {
Yohei Yukawa4e02bc62014-06-04 18:37:20 +09003301 setInputMethodWithSubtypeIdLocked(token, id, subtypeId);
3302 }
3303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003304
Yohei Yukawa4e02bc62014-06-04 18:37:20 +09003305 private void setInputMethodWithSubtypeIdLocked(IBinder token, String id, int subtypeId) {
3306 if (token == null) {
3307 if (mContext.checkCallingOrSelfPermission(
3308 android.Manifest.permission.WRITE_SECURE_SETTINGS)
3309 != PackageManager.PERMISSION_GRANTED) {
3310 throw new SecurityException(
3311 "Using null token requires permission "
3312 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313 }
Yohei Yukawa4e02bc62014-06-04 18:37:20 +09003314 } else if (mCurToken != token) {
3315 Slog.w(TAG, "Ignoring setInputMethod of uid " + Binder.getCallingUid()
3316 + " token: " + token);
3317 return;
3318 }
3319
3320 final long ident = Binder.clearCallingIdentity();
3321 try {
3322 setInputMethodLocked(id, subtypeId);
3323 } finally {
3324 Binder.restoreCallingIdentity(ident);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 }
3326 }
3327
satok42c5a162011-05-26 16:46:14 +09003328 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329 public void hideMySoftInput(IBinder token, int flags) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003330 if (!calledFromValidUser()) {
3331 return;
3332 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003333 synchronized (mMethodMap) {
Yohei Yukawa22c97be2014-06-04 19:43:36 +09003334 if (!calledWithValidToken(token)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003335 return;
3336 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003337 long ident = Binder.clearCallingIdentity();
3338 try {
The Android Open Source Project4df24232009-03-05 14:34:35 -08003339 hideCurrentInputLocked(flags, null);
3340 } finally {
3341 Binder.restoreCallingIdentity(ident);
3342 }
3343 }
3344 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003345
satok42c5a162011-05-26 16:46:14 +09003346 @Override
The Android Open Source Project4df24232009-03-05 14:34:35 -08003347 public void showMySoftInput(IBinder token, int flags) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003348 if (!calledFromValidUser()) {
3349 return;
3350 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08003351 synchronized (mMethodMap) {
Yohei Yukawa22c97be2014-06-04 19:43:36 +09003352 if (!calledWithValidToken(token)) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08003353 return;
3354 }
3355 long ident = Binder.clearCallingIdentity();
3356 try {
3357 showCurrentInputLocked(flags, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 } finally {
3359 Binder.restoreCallingIdentity(ident);
3360 }
3361 }
3362 }
3363
3364 void setEnabledSessionInMainThread(SessionState session) {
3365 if (mEnabledSession != session) {
Yohei Yukawa9d91b432014-05-19 16:03:24 +09003366 if (mEnabledSession != null && mEnabledSession.session != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003367 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003368 if (DEBUG) Slog.v(TAG, "Disabling: " + mEnabledSession);
Yohei Yukawa9d91b432014-05-19 16:03:24 +09003369 mEnabledSession.method.setSessionEnabled(mEnabledSession.session, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370 } catch (RemoteException e) {
3371 }
3372 }
3373 mEnabledSession = session;
Yohei Yukawa9d91b432014-05-19 16:03:24 +09003374 if (mEnabledSession != null && mEnabledSession.session != null) {
3375 try {
3376 if (DEBUG) Slog.v(TAG, "Enabling: " + mEnabledSession);
3377 mEnabledSession.method.setSessionEnabled(mEnabledSession.session, true);
3378 } catch (RemoteException e) {
3379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 }
3381 }
3382 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003383
Yohei Yukawa930328c2017-10-18 20:19:53 -07003384 @MainThread
satok42c5a162011-05-26 16:46:14 +09003385 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003386 public boolean handleMessage(Message msg) {
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003387 SomeArgs args;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003388 switch (msg.what) {
satokab751aa2010-09-14 19:17:36 +09003389 case MSG_SHOW_IM_SUBTYPE_PICKER:
Seigo Nonaka14e13912015-05-06 21:04:13 -07003390 final boolean showAuxSubtypes;
3391 switch (msg.arg1) {
3392 case InputMethodManager.SHOW_IM_PICKER_MODE_AUTO:
3393 // This is undocumented so far, but IMM#showInputMethodPicker() has been
3394 // implemented so that auxiliary subtypes will be excluded when the soft
3395 // keyboard is invisible.
3396 showAuxSubtypes = mInputShown;
3397 break;
3398 case InputMethodManager.SHOW_IM_PICKER_MODE_INCLUDE_AUXILIARY_SUBTYPES:
3399 showAuxSubtypes = true;
3400 break;
3401 case InputMethodManager.SHOW_IM_PICKER_MODE_EXCLUDE_AUXILIARY_SUBTYPES:
3402 showAuxSubtypes = false;
3403 break;
3404 default:
3405 Slog.e(TAG, "Unknown subtype picker mode = " + msg.arg1);
3406 return false;
3407 }
3408 showInputMethodMenu(showAuxSubtypes);
satokab751aa2010-09-14 19:17:36 +09003409 return true;
3410
satok47a44912010-10-06 16:03:58 +09003411 case MSG_SHOW_IM_SUBTYPE_ENABLER:
Yohei Yukawa41f34272015-12-14 15:41:52 -08003412 showInputMethodAndSubtypeEnabler((String)msg.obj);
satok217f5482010-12-15 05:19:19 +09003413 return true;
3414
3415 case MSG_SHOW_IM_CONFIG:
3416 showConfigureInputMethods();
satok47a44912010-10-06 16:03:58 +09003417 return true;
3418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003419 // ---------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003421 case MSG_UNBIND_INPUT:
3422 try {
3423 ((IInputMethod)msg.obj).unbindInput();
3424 } catch (RemoteException e) {
3425 // There is nothing interesting about the method dying.
3426 }
3427 return true;
3428 case MSG_BIND_INPUT:
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003429 args = (SomeArgs)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003430 try {
3431 ((IInputMethod)args.arg1).bindInput((InputBinding)args.arg2);
3432 } catch (RemoteException e) {
3433 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003434 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 return true;
3436 case MSG_SHOW_SOFT_INPUT:
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003437 args = (SomeArgs)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003438 try {
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07003439 if (DEBUG) Slog.v(TAG, "Calling " + args.arg1 + ".showSoftInput("
Craig Mautner6efb4c72013-03-13 10:17:41 -07003440 + msg.arg1 + ", " + args.arg2 + ")");
Craig Mautnerca0ac712013-03-14 09:43:02 -07003441 ((IInputMethod)args.arg1).showSoftInput(msg.arg1, (ResultReceiver)args.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003442 } catch (RemoteException e) {
3443 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003444 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003445 return true;
3446 case MSG_HIDE_SOFT_INPUT:
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003447 args = (SomeArgs)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003448 try {
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07003449 if (DEBUG) Slog.v(TAG, "Calling " + args.arg1 + ".hideSoftInput(0, "
Craig Mautner6efb4c72013-03-13 10:17:41 -07003450 + args.arg2 + ")");
Craig Mautnerca0ac712013-03-14 09:43:02 -07003451 ((IInputMethod)args.arg1).hideSoftInput(0, (ResultReceiver)args.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003452 } catch (RemoteException e) {
3453 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003454 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003455 return true;
Jorim Jaggi3c5d0f12016-05-24 19:04:30 -07003456 case MSG_HIDE_CURRENT_INPUT_METHOD:
3457 synchronized (mMethodMap) {
3458 hideCurrentInputLocked(0, null);
3459 }
3460 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003461 case MSG_ATTACH_TOKEN:
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003462 args = (SomeArgs)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003463 try {
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07003464 if (DEBUG) Slog.v(TAG, "Sending attach of token: " + args.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003465 ((IInputMethod)args.arg1).attachToken((IBinder)args.arg2);
3466 } catch (RemoteException e) {
3467 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003468 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003469 return true;
Jeff Brownc28867a2013-03-26 15:42:39 -07003470 case MSG_CREATE_SESSION: {
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003471 args = (SomeArgs)msg.obj;
Jeff Brown1951ce82013-04-04 22:45:12 -07003472 IInputMethod method = (IInputMethod)args.arg1;
Jeff Brownc28867a2013-03-26 15:42:39 -07003473 InputChannel channel = (InputChannel)args.arg2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003474 try {
Jeff Brown1951ce82013-04-04 22:45:12 -07003475 method.createSession(channel, (IInputSessionCallback)args.arg3);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003476 } catch (RemoteException e) {
Jeff Brownc28867a2013-03-26 15:42:39 -07003477 } finally {
Jeff Brown1951ce82013-04-04 22:45:12 -07003478 // Dispose the channel if the input method is not local to this process
3479 // because the remote proxy will get its own copy when unparceled.
3480 if (channel != null && Binder.isProxy(method)) {
Jeff Brownc28867a2013-03-26 15:42:39 -07003481 channel.dispose();
3482 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003483 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003484 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485 return true;
Jeff Brownc28867a2013-03-26 15:42:39 -07003486 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003487 // ---------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003488
Yohei Yukawa19a80a12016-03-14 22:57:37 -07003489 case MSG_START_INPUT: {
Yohei Yukawaf7526b52017-02-11 20:57:10 -08003490 final int missingMethods = msg.arg1;
3491 final boolean restarting = msg.arg2 != 0;
Yohei Yukawa19a80a12016-03-14 22:57:37 -07003492 args = (SomeArgs) msg.obj;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08003493 final IBinder startInputToken = (IBinder) args.arg1;
3494 final SessionState session = (SessionState) args.arg2;
3495 final IInputContext inputContext = (IInputContext) args.arg3;
3496 final EditorInfo editorInfo = (EditorInfo) args.arg4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003497 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003498 setEnabledSessionInMainThread(session);
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08003499 session.method.startInput(startInputToken, inputContext, missingMethods,
3500 editorInfo, restarting);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003501 } catch (RemoteException e) {
3502 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003503 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003504 return true;
Yohei Yukawa19a80a12016-03-14 22:57:37 -07003505 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003507 // ---------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003508
Yohei Yukawa33e81792015-11-17 21:14:42 -08003509 case MSG_UNBIND_CLIENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003510 try {
Yohei Yukawa33e81792015-11-17 21:14:42 -08003511 ((IInputMethodClient)msg.obj).onUnbindMethod(msg.arg1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003512 } catch (RemoteException e) {
3513 // There is nothing interesting about the last client dying.
3514 }
3515 return true;
Yohei Yukawa33e81792015-11-17 21:14:42 -08003516 case MSG_BIND_CLIENT: {
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003517 args = (SomeArgs)msg.obj;
Jeff Brown1951ce82013-04-04 22:45:12 -07003518 IInputMethodClient client = (IInputMethodClient)args.arg1;
3519 InputBindResult res = (InputBindResult)args.arg2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003520 try {
Jeff Brown1951ce82013-04-04 22:45:12 -07003521 client.onBindMethod(res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003522 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003523 Slog.w(TAG, "Client died receiving input method " + args.arg2);
Jeff Brown1951ce82013-04-04 22:45:12 -07003524 } finally {
3525 // Dispose the channel if the input method is not local to this process
3526 // because the remote proxy will get its own copy when unparceled.
3527 if (res.channel != null && Binder.isProxy(client)) {
3528 res.channel.dispose();
3529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003530 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003531 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003532 return true;
Jeff Brown1951ce82013-04-04 22:45:12 -07003533 }
Dianne Hackborna6e41342012-05-22 16:30:34 -07003534 case MSG_SET_ACTIVE:
3535 try {
Yohei Yukawa2bc66172017-02-08 11:13:25 -08003536 ((ClientState)msg.obj).client.setActive(msg.arg1 != 0, msg.arg2 != 0);
Dianne Hackborna6e41342012-05-22 16:30:34 -07003537 } catch (RemoteException e) {
3538 Slog.w(TAG, "Got RemoteException sending setActive(false) notification to pid "
3539 + ((ClientState)msg.obj).pid + " uid "
3540 + ((ClientState)msg.obj).uid);
3541 }
3542 return true;
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07003543 case MSG_SET_INTERACTIVE:
3544 handleSetInteractive(msg.arg1 != 0);
3545 return true;
Tarandeep Singh89a6c482017-11-21 14:26:11 -08003546 case MSG_START_VR_INPUT:
3547 startVrInputMethodNoCheck((ComponentName) msg.obj);
3548 return true;
Yohei Yukawaae61f712015-12-09 13:00:10 -08003549 case MSG_SWITCH_IME:
3550 handleSwitchInputMethod(msg.arg1 != 0);
3551 return true;
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003552 case MSG_SET_USER_ACTION_NOTIFICATION_SEQUENCE_NUMBER: {
3553 final int sequenceNumber = msg.arg1;
Yohei Yukawa080fa342014-08-31 16:10:05 -07003554 final ClientState clientState = (ClientState)msg.obj;
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003555 try {
Yohei Yukawa080fa342014-08-31 16:10:05 -07003556 clientState.client.setUserActionNotificationSequenceNumber(sequenceNumber);
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003557 } catch (RemoteException e) {
3558 Slog.w(TAG, "Got RemoteException sending "
3559 + "setUserActionNotificationSequenceNumber("
3560 + sequenceNumber + ") notification to pid "
Yohei Yukawa080fa342014-08-31 16:10:05 -07003561 + clientState.pid + " uid "
3562 + clientState.uid);
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003563 }
3564 return true;
3565 }
Yohei Yukawa2bc66172017-02-08 11:13:25 -08003566 case MSG_REPORT_FULLSCREEN_MODE: {
3567 final boolean fullscreen = msg.arg1 != 0;
3568 final ClientState clientState = (ClientState)msg.obj;
3569 try {
3570 clientState.client.reportFullscreenMode(fullscreen);
3571 } catch (RemoteException e) {
3572 Slog.w(TAG, "Got RemoteException sending "
3573 + "reportFullscreen(" + fullscreen + ") notification to pid="
3574 + clientState.pid + " uid=" + clientState.uid);
3575 }
3576 return true;
3577 }
satok01038492012-04-09 21:08:27 +09003578
3579 // --------------------------------------------------------------
3580 case MSG_HARD_KEYBOARD_SWITCH_CHANGED:
Michael Wright7b5a96b2014-08-09 19:28:42 -07003581 mHardKeyboardListener.handleHardKeyboardStatusChange(msg.arg1 == 1);
satok01038492012-04-09 21:08:27 +09003582 return true;
Fyodor Kupolov7877b8a2016-06-29 14:39:19 -07003583 case MSG_SYSTEM_UNLOCK_USER:
3584 final int userId = msg.arg1;
3585 onUnlockUser(userId);
3586 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003587 }
3588 return false;
3589 }
3590
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07003591 private void handleSetInteractive(final boolean interactive) {
3592 synchronized (mMethodMap) {
3593 mIsInteractive = interactive;
3594 updateSystemUiLocked(mCurToken, interactive ? mImeWindowVis : 0, mBackDisposition);
3595
3596 // Inform the current client of the change in active status
3597 if (mCurClient != null && mCurClient.client != null) {
Yohei Yukawa2bc66172017-02-08 11:13:25 -08003598 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIIO(
3599 MSG_SET_ACTIVE, mIsInteractive ? 1 : 0, mInFullscreenMode ? 1 : 0,
3600 mCurClient));
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07003601 }
3602 }
3603 }
3604
Yohei Yukawaae61f712015-12-09 13:00:10 -08003605 private void handleSwitchInputMethod(final boolean forwardDirection) {
3606 synchronized (mMethodMap) {
Yohei Yukawaae61f712015-12-09 13:00:10 -08003607 final ImeSubtypeListItem nextSubtype = mSwitchingController.getNextInputMethodLocked(
Yohei Yukawad39ae852016-04-10 20:28:40 -07003608 false, mMethodMap.get(mCurMethodId), mCurrentSubtype, forwardDirection);
Yohei Yukawaae61f712015-12-09 13:00:10 -08003609 if (nextSubtype == null) {
3610 return;
3611 }
3612 setInputMethodLocked(nextSubtype.mImi.getId(), nextSubtype.mSubtypeId);
Yohei Yukawaebda7d72016-04-02 17:39:23 -07003613 final InputMethodInfo newInputMethodInfo = mMethodMap.get(mCurMethodId);
3614 if (newInputMethodInfo == null) {
3615 return;
3616 }
3617 final CharSequence toastText = InputMethodUtils.getImeAndSubtypeDisplayName(mContext,
3618 newInputMethodInfo, mCurrentSubtype);
3619 if (!TextUtils.isEmpty(toastText)) {
Yohei Yukawab2f901a2016-04-12 01:19:31 -07003620 if (mSubtypeSwitchedByShortCutToast == null) {
3621 mSubtypeSwitchedByShortCutToast = Toast.makeText(mContext, toastText,
3622 Toast.LENGTH_SHORT);
3623 } else {
3624 mSubtypeSwitchedByShortCutToast.setText(toastText);
3625 }
Yohei Yukawaebda7d72016-04-02 17:39:23 -07003626 mSubtypeSwitchedByShortCutToast.show();
3627 }
Yohei Yukawaae61f712015-12-09 13:00:10 -08003628 }
3629 }
3630
satokdc9ddae2011-10-06 12:22:36 +09003631 private boolean chooseNewDefaultIMELocked() {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003632 final InputMethodInfo imi = InputMethodUtils.getMostApplicableDefaultIME(
3633 mSettings.getEnabledInputMethodListLocked());
satokdc9ddae2011-10-06 12:22:36 +09003634 if (imi != null) {
satok03eb319a2010-11-11 18:17:42 +09003635 if (DEBUG) {
3636 Slog.d(TAG, "New default IME was selected: " + imi.getId());
3637 }
satok723a27e2010-11-11 14:58:11 +09003638 resetSelectedInputMethodAndSubtypeLocked(imi.getId());
Brandon Ballinger6da35a02009-10-21 00:38:13 -07003639 return true;
3640 }
3641
3642 return false;
3643 }
3644
Yohei Yukawa94e33302016-02-12 19:37:03 -08003645 void buildInputMethodListLocked(boolean resetDefaultEnabledIme) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003646 if (DEBUG) {
Satoshi Kataokaf1367b72013-01-25 17:20:12 +09003647 Slog.d(TAG, "--- re-buildInputMethodList reset = " + resetDefaultEnabledIme
Seigo Nonakae27dc2b2015-08-14 18:21:27 -07003648 + " \n ------ caller=" + Debug.getCallers(10));
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003649 }
Yohei Yukawa79247822017-01-23 15:26:15 -08003650 if (!mSystemReady) {
3651 Slog.e(TAG, "buildInputMethodListLocked is not allowed until system is ready");
3652 return;
3653 }
Yohei Yukawa94e33302016-02-12 19:37:03 -08003654 mMethodList.clear();
3655 mMethodMap.clear();
Yohei Yukawae0733062017-02-09 22:49:35 -08003656 mMethodMapUpdateCount++;
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08003657 mMyPackageMonitor.clearKnownImePackageNamesLocked();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003658
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003659 // Use for queryIntentServicesAsUser
3660 final PackageManager pm = mContext.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661
Yohei Yukawaed4952a2016-02-17 07:57:25 -08003662 // Note: We do not specify PackageManager.MATCH_ENCRYPTION_* flags here because the default
3663 // behavior of PackageManager is exactly what we want. It by default picks up appropriate
3664 // services depending on the unlock state for the specified user.
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003665 final List<ResolveInfo> services = pm.queryIntentServicesAsUser(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003666 new Intent(InputMethod.SERVICE_INTERFACE),
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08003667 PackageManager.GET_META_DATA | PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
3668 mSettings.getCurrentUserId());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003669
Yohei Yukawaddad4b92017-02-02 01:46:13 -08003670 final HashMap<String, List<InputMethodSubtype>> additionalSubtypeMap =
satoke7c6998e2011-06-03 17:57:59 +09003671 mFileManager.getAllAdditionalInputMethodSubtypes();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003672 for (int i = 0; i < services.size(); ++i) {
3673 ResolveInfo ri = services.get(i);
3674 ServiceInfo si = ri.serviceInfo;
Yohei Yukawaddad4b92017-02-02 01:46:13 -08003675 final String imeId = InputMethodInfo.computeId(ri);
3676 if (!android.Manifest.permission.BIND_INPUT_METHOD.equals(si.permission)) {
3677 Slog.w(TAG, "Skipping input method " + imeId
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003678 + ": it does not require the permission "
3679 + android.Manifest.permission.BIND_INPUT_METHOD);
3680 continue;
3681 }
3682
Yohei Yukawaddad4b92017-02-02 01:46:13 -08003683 if (DEBUG) Slog.d(TAG, "Checking " + imeId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003684
Yohei Yukawaddad4b92017-02-02 01:46:13 -08003685 final List<InputMethodSubtype> additionalSubtypes = additionalSubtypeMap.get(imeId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003686 try {
satoke7c6998e2011-06-03 17:57:59 +09003687 InputMethodInfo p = new InputMethodInfo(mContext, ri, additionalSubtypes);
Yohei Yukawa94e33302016-02-12 19:37:03 -08003688 mMethodList.add(p);
Amith Yamasanie861ec12010-03-24 21:39:27 -07003689 final String id = p.getId();
Yohei Yukawa94e33302016-02-12 19:37:03 -08003690 mMethodMap.put(id, p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003691
3692 if (DEBUG) {
Satoshi Kataokaf1367b72013-01-25 17:20:12 +09003693 Slog.d(TAG, "Found an input method " + p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003694 }
Tadashi G. Takaoka3c23d5b2016-09-16 11:41:07 +09003695 } catch (Exception e) {
Yohei Yukawaddad4b92017-02-02 01:46:13 -08003696 Slog.wtf(TAG, "Unable to load input method " + imeId, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003697 }
3698 }
Brandon Ballinger6da35a02009-10-21 00:38:13 -07003699
Yohei Yukawac4e44912017-02-09 19:30:22 -08003700 // Construct the set of possible IME packages for onPackageChanged() to avoid false
3701 // negatives when the package state remains to be the same but only the component state is
3702 // changed.
3703 {
3704 // Here we intentionally use PackageManager.MATCH_DISABLED_COMPONENTS since the purpose
3705 // of this query is to avoid false negatives. PackageManager.MATCH_ALL could be more
3706 // conservative, but it seems we cannot use it for now (Issue 35176630).
3707 final List<ResolveInfo> allInputMethodServices = pm.queryIntentServicesAsUser(
3708 new Intent(InputMethod.SERVICE_INTERFACE),
3709 PackageManager.MATCH_DISABLED_COMPONENTS, mSettings.getCurrentUserId());
3710 final int N = allInputMethodServices.size();
3711 for (int i = 0; i < N; ++i) {
3712 final ServiceInfo si = allInputMethodServices.get(i).serviceInfo;
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08003713 if (android.Manifest.permission.BIND_INPUT_METHOD.equals(si.permission)) {
3714 mMyPackageMonitor.addKnownImePackageNameLocked(si.packageName);
Yohei Yukawac4e44912017-02-09 19:30:22 -08003715 }
Yohei Yukawac4e44912017-02-09 19:30:22 -08003716 }
3717 }
3718
Yohei Yukawa859df052016-02-17 07:56:46 -08003719 // TODO: The following code should find better place to live.
3720 if (!resetDefaultEnabledIme) {
3721 boolean enabledImeFound = false;
3722 final List<InputMethodInfo> enabledImes = mSettings.getEnabledInputMethodListLocked();
3723 final int N = enabledImes.size();
3724 for (int i = 0; i < N; ++i) {
3725 final InputMethodInfo imi = enabledImes.get(i);
3726 if (mMethodList.contains(imi)) {
3727 enabledImeFound = true;
3728 break;
3729 }
3730 }
3731 if (!enabledImeFound) {
Yohei Yukawad0332832017-02-01 13:59:43 -08003732 if (DEBUG) {
3733 Slog.i(TAG, "All the enabled IMEs are gone. Reset default enabled IMEs.");
3734 }
Yohei Yukawa859df052016-02-17 07:56:46 -08003735 resetDefaultEnabledIme = true;
3736 resetSelectedInputMethodAndSubtypeLocked("");
3737 }
3738 }
3739
Satoshi Kataokaf1367b72013-01-25 17:20:12 +09003740 if (resetDefaultEnabledIme) {
3741 final ArrayList<InputMethodInfo> defaultEnabledIme =
Yohei Yukawaaf5cee82017-01-23 16:17:11 -08003742 InputMethodUtils.getDefaultEnabledImes(mContext, mMethodList);
Yohei Yukawa68645a62016-02-17 07:54:20 -08003743 final int N = defaultEnabledIme.size();
3744 for (int i = 0; i < N; ++i) {
Satoshi Kataokaf1367b72013-01-25 17:20:12 +09003745 final InputMethodInfo imi = defaultEnabledIme.get(i);
3746 if (DEBUG) {
3747 Slog.d(TAG, "--- enable ime = " + imi);
3748 }
3749 setInputMethodEnabledLocked(imi.getId(), true);
3750 }
3751 }
3752
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003753 final String defaultImiId = mSettings.getSelectedInputMethod();
satok0a1bcf42012-05-16 19:26:31 +09003754 if (!TextUtils.isEmpty(defaultImiId)) {
Yohei Yukawa94e33302016-02-12 19:37:03 -08003755 if (!mMethodMap.containsKey(defaultImiId)) {
satok0a1bcf42012-05-16 19:26:31 +09003756 Slog.w(TAG, "Default IME is uninstalled. Choose new default IME.");
3757 if (chooseNewDefaultIMELocked()) {
Michael Wright7b5a96b2014-08-09 19:28:42 -07003758 updateInputMethodsFromSettingsLocked(true);
satok0a1bcf42012-05-16 19:26:31 +09003759 }
3760 } else {
3761 // Double check that the default IME is certainly enabled.
3762 setInputMethodEnabledLocked(defaultImiId, true);
Brandon Ballinger6da35a02009-10-21 00:38:13 -07003763 }
3764 }
Yohei Yukawa3d46bab2014-05-30 18:10:18 +09003765 // Here is not the perfect place to reset the switching controller. Ideally
3766 // mSwitchingController and mSettings should be able to share the same state.
3767 // TODO: Make sure that mSwitchingController and mSettings are sharing the
3768 // the same enabled IMEs list.
Yohei Yukawac834a252014-05-21 22:42:32 +09003769 mSwitchingController.resetCircularListLocked(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003770 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003772 // ----------------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003773
satok217f5482010-12-15 05:19:19 +09003774 private void showInputMethodAndSubtypeEnabler(String inputMethodId) {
Tadashi G. Takaokaf49688f2011-01-20 17:56:13 +09003775 Intent intent = new Intent(Settings.ACTION_INPUT_METHOD_SUBTYPE_SETTINGS);
satok47a44912010-10-06 16:03:58 +09003776 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
satok86417ea2010-10-27 14:11:03 +09003777 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
3778 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
satok7fee71f2010-12-17 18:54:26 +09003779 if (!TextUtils.isEmpty(inputMethodId)) {
Tadashi G. Takaoka25480202011-01-20 23:13:02 +09003780 intent.putExtra(Settings.EXTRA_INPUT_METHOD_ID, inputMethodId);
satok7fee71f2010-12-17 18:54:26 +09003781 }
Yohei Yukawa41f34272015-12-14 15:41:52 -08003782 final int userId;
3783 synchronized (mMethodMap) {
3784 userId = mSettings.getCurrentUserId();
3785 }
3786 mContext.startActivityAsUser(intent, null, UserHandle.of(userId));
satok217f5482010-12-15 05:19:19 +09003787 }
3788
3789 private void showConfigureInputMethods() {
3790 Intent intent = new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS);
3791 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
3792 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
3793 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Satoshi Kataoka3ba439d2012-10-05 18:30:13 +09003794 mContext.startActivityAsUser(intent, null, UserHandle.CURRENT);
satok47a44912010-10-06 16:03:58 +09003795 }
3796
satok2c93efc2012-04-02 19:33:47 +09003797 private boolean isScreenLocked() {
3798 return mKeyguardManager != null
3799 && mKeyguardManager.isKeyguardLocked() && mKeyguardManager.isKeyguardSecure();
3800 }
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003801
Seigo Nonaka14e13912015-05-06 21:04:13 -07003802 private void showInputMethodMenu(boolean showAuxSubtypes) {
3803 if (DEBUG) Slog.v(TAG, "Show switching menu. showAuxSubtypes=" + showAuxSubtypes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804
satok2c93efc2012-04-02 19:33:47 +09003805 final boolean isScreenLocked = isScreenLocked();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003806
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003807 final String lastInputMethodId = mSettings.getSelectedInputMethod();
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003808 int lastInputMethodSubtypeId = mSettings.getSelectedInputMethodSubtypeId(lastInputMethodId);
Joe Onorato8a9b2202010-02-26 18:56:32 -08003809 if (DEBUG) Slog.v(TAG, "Current IME: " + lastInputMethodId);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003810
Dianne Hackborn8cf1bcd2010-03-16 13:06:10 -07003811 synchronized (mMethodMap) {
satokbb4aa062011-01-19 21:40:27 +09003812 final HashMap<InputMethodInfo, List<InputMethodSubtype>> immis =
Satoshi Kataokad787f692013-10-26 04:44:21 +09003813 mSettings.getExplicitlyOrImplicitlyEnabledInputMethodsAndSubtypeListLocked(
3814 mContext);
satok7f35c8c2010-10-07 21:13:11 +09003815 if (immis == null || immis.size() == 0) {
3816 return;
3817 }
3818
Dianne Hackborn8cf1bcd2010-03-16 13:06:10 -07003819 hideInputMethodMenuLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003820
satok688bd472012-02-09 20:09:17 +09003821 final List<ImeSubtypeListItem> imList =
Yohei Yukawa5a647b692014-05-22 12:49:00 +09003822 mSwitchingController.getSortedInputMethodAndSubtypeListLocked(
Yohei Yukawa5f8e7312015-12-10 00:58:55 -08003823 showAuxSubtypes, isScreenLocked);
satok913a8922010-08-26 21:53:41 +09003824
satokc3690562012-01-10 20:14:43 +09003825 if (lastInputMethodSubtypeId == NOT_A_SUBTYPE_ID) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003826 final InputMethodSubtype currentSubtype = getCurrentInputMethodSubtypeLocked();
satokc3690562012-01-10 20:14:43 +09003827 if (currentSubtype != null) {
3828 final InputMethodInfo currentImi = mMethodMap.get(mCurMethodId);
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003829 lastInputMethodSubtypeId = InputMethodUtils.getSubtypeIdFromHashCode(
3830 currentImi, currentSubtype.hashCode());
satokc3690562012-01-10 20:14:43 +09003831 }
3832 }
3833
Ken Wakasa761eb372011-03-04 19:06:18 +09003834 final int N = imList.size();
satokab751aa2010-09-14 19:17:36 +09003835 mIms = new InputMethodInfo[N];
3836 mSubtypeIds = new int[N];
Dianne Hackborn8cf1bcd2010-03-16 13:06:10 -07003837 int checkedItem = 0;
3838 for (int i = 0; i < N; ++i) {
Ken Wakasa05dbb652011-08-22 15:22:43 +09003839 final ImeSubtypeListItem item = imList.get(i);
3840 mIms[i] = item.mImi;
3841 mSubtypeIds[i] = item.mSubtypeId;
Dianne Hackborn8cf1bcd2010-03-16 13:06:10 -07003842 if (mIms[i].getId().equals(lastInputMethodId)) {
satokab751aa2010-09-14 19:17:36 +09003843 int subtypeId = mSubtypeIds[i];
3844 if ((subtypeId == NOT_A_SUBTYPE_ID)
3845 || (lastInputMethodSubtypeId == NOT_A_SUBTYPE_ID && subtypeId == 0)
3846 || (subtypeId == lastInputMethodSubtypeId)) {
3847 checkedItem = i;
3848 }
Dianne Hackborn8cf1bcd2010-03-16 13:06:10 -07003849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003850 }
Alan Viverette505e3ab2014-11-24 15:22:11 -08003851
Andrew Sapperstein8a3b4cb2017-04-28 14:35:31 -07003852 final Context settingsContext = new ContextThemeWrapper(
3853 ActivityThread.currentActivityThread().getSystemUiContext(),
Alan Viverette505e3ab2014-11-24 15:22:11 -08003854 com.android.internal.R.style.Theme_DeviceDefault_Settings);
3855
3856 mDialogBuilder = new AlertDialog.Builder(settingsContext);
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003857 mDialogBuilder.setOnCancelListener(new OnCancelListener() {
3858 @Override
3859 public void onCancel(DialogInterface dialog) {
3860 hideInputMethodMenu();
3861 }
3862 });
Alan Viverette505e3ab2014-11-24 15:22:11 -08003863
3864 final Context dialogContext = mDialogBuilder.getContext();
3865 final TypedArray a = dialogContext.obtainStyledAttributes(null,
3866 com.android.internal.R.styleable.DialogPreference,
3867 com.android.internal.R.attr.alertDialogStyle, 0);
3868 final Drawable dialogIcon = a.getDrawable(
3869 com.android.internal.R.styleable.DialogPreference_dialogIcon);
3870 a.recycle();
3871
3872 mDialogBuilder.setIcon(dialogIcon);
3873
Yohei Yukawad34e1482016-02-11 08:03:52 -08003874 final LayoutInflater inflater = dialogContext.getSystemService(LayoutInflater.class);
satok01038492012-04-09 21:08:27 +09003875 final View tv = inflater.inflate(
3876 com.android.internal.R.layout.input_method_switch_dialog_title, null);
3877 mDialogBuilder.setCustomTitle(tv);
3878
3879 // Setup layout for a toggle switch of the hardware keyboard
3880 mSwitchingDialogTitleView = tv;
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003881 mSwitchingDialogTitleView
3882 .findViewById(com.android.internal.R.id.hard_keyboard_section)
Seigo Nonaka7309b122015-08-17 18:34:13 -07003883 .setVisibility(mWindowManagerInternal.isHardKeyboardAvailable()
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003884 ? View.VISIBLE : View.GONE);
Alan Viverette505e3ab2014-11-24 15:22:11 -08003885 final Switch hardKeySwitch = (Switch) mSwitchingDialogTitleView.findViewById(
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003886 com.android.internal.R.id.hard_keyboard_switch);
Michael Wright7b5a96b2014-08-09 19:28:42 -07003887 hardKeySwitch.setChecked(mShowImeWithHardKeyboard);
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003888 hardKeySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
3889 @Override
3890 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Michael Wright7b5a96b2014-08-09 19:28:42 -07003891 mSettings.setShowImeWithHardKeyboard(isChecked);
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003892 // Ensure that the input method dialog is dismissed when changing
3893 // the hardware keyboard state.
3894 hideInputMethodMenu();
3895 }
3896 });
3897
Alan Viverette505e3ab2014-11-24 15:22:11 -08003898 final ImeSubtypeListAdapter adapter = new ImeSubtypeListAdapter(dialogContext,
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003899 com.android.internal.R.layout.input_method_switch_item, imList, checkedItem);
3900 final OnClickListener choiceListener = new OnClickListener() {
3901 @Override
3902 public void onClick(final DialogInterface dialog, final int which) {
3903 synchronized (mMethodMap) {
3904 if (mIms == null || mIms.length <= which || mSubtypeIds == null
3905 || mSubtypeIds.length <= which) {
3906 return;
satok01038492012-04-09 21:08:27 +09003907 }
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003908 final InputMethodInfo im = mIms[which];
3909 int subtypeId = mSubtypeIds[which];
3910 adapter.mCheckedItem = which;
3911 adapter.notifyDataSetChanged();
3912 hideInputMethodMenu();
3913 if (im != null) {
3914 if (subtypeId < 0 || subtypeId >= im.getSubtypeCount()) {
3915 subtypeId = NOT_A_SUBTYPE_ID;
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08003916 }
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003917 setInputMethodLocked(im.getId(), subtypeId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003918 }
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003919 }
3920 }
3921 };
3922 mDialogBuilder.setSingleChoiceItems(adapter, checkedItem, choiceListener);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 mSwitchingDialog = mDialogBuilder.create();
Dianne Hackborne3a7f622011-03-03 21:48:24 -08003925 mSwitchingDialog.setCanceledOnTouchOutside(true);
Wale Ogunwale3a931692016-11-02 16:49:48 -07003926 final Window w = mSwitchingDialog.getWindow();
3927 final WindowManager.LayoutParams attrs = w.getAttributes();
3928 w.setType(TYPE_INPUT_METHOD_DIALOG);
3929 // Use an alternate token for the dialog for that window manager can group the token
3930 // with other IME windows based on type vs. grouping based on whichever token happens
3931 // to get selected by the system later on.
3932 attrs.token = mSwitchingDialogToken;
3933 attrs.privateFlags |= PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
3934 attrs.setTitle("Select input method");
3935 w.setAttributes(attrs);
Seigo Nonakad9eb9112015-05-26 20:54:43 +09003936 updateSystemUi(mCurToken, mImeWindowVis, mBackDisposition);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003937 mSwitchingDialog.show();
3938 }
3939 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003940
Ken Wakasa05dbb652011-08-22 15:22:43 +09003941 private static class ImeSubtypeListAdapter extends ArrayAdapter<ImeSubtypeListItem> {
3942 private final LayoutInflater mInflater;
3943 private final int mTextViewResourceId;
3944 private final List<ImeSubtypeListItem> mItemsList;
Satoshi Kataokad2142962012-11-12 18:43:06 +09003945 public int mCheckedItem;
Ken Wakasa05dbb652011-08-22 15:22:43 +09003946 public ImeSubtypeListAdapter(Context context, int textViewResourceId,
3947 List<ImeSubtypeListItem> itemsList, int checkedItem) {
3948 super(context, textViewResourceId, itemsList);
Alan Viverette505e3ab2014-11-24 15:22:11 -08003949
Ken Wakasa05dbb652011-08-22 15:22:43 +09003950 mTextViewResourceId = textViewResourceId;
3951 mItemsList = itemsList;
3952 mCheckedItem = checkedItem;
Yohei Yukawad34e1482016-02-11 08:03:52 -08003953 mInflater = context.getSystemService(LayoutInflater.class);
Ken Wakasa05dbb652011-08-22 15:22:43 +09003954 }
3955
3956 @Override
3957 public View getView(int position, View convertView, ViewGroup parent) {
3958 final View view = convertView != null ? convertView
3959 : mInflater.inflate(mTextViewResourceId, null);
3960 if (position < 0 || position >= mItemsList.size()) return view;
3961 final ImeSubtypeListItem item = mItemsList.get(position);
3962 final CharSequence imeName = item.mImeName;
3963 final CharSequence subtypeName = item.mSubtypeName;
3964 final TextView firstTextView = (TextView)view.findViewById(android.R.id.text1);
3965 final TextView secondTextView = (TextView)view.findViewById(android.R.id.text2);
3966 if (TextUtils.isEmpty(subtypeName)) {
3967 firstTextView.setText(imeName);
3968 secondTextView.setVisibility(View.GONE);
3969 } else {
3970 firstTextView.setText(subtypeName);
3971 secondTextView.setText(imeName);
3972 secondTextView.setVisibility(View.VISIBLE);
3973 }
3974 final RadioButton radioButton =
3975 (RadioButton)view.findViewById(com.android.internal.R.id.radio);
3976 radioButton.setChecked(position == mCheckedItem);
3977 return view;
3978 }
3979 }
3980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003981 void hideInputMethodMenu() {
The Android Open Source Project10592532009-03-18 17:39:46 -07003982 synchronized (mMethodMap) {
3983 hideInputMethodMenuLocked();
3984 }
3985 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003986
The Android Open Source Project10592532009-03-18 17:39:46 -07003987 void hideInputMethodMenuLocked() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003988 if (DEBUG) Slog.v(TAG, "Hide switching menu");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003989
The Android Open Source Project10592532009-03-18 17:39:46 -07003990 if (mSwitchingDialog != null) {
3991 mSwitchingDialog.dismiss();
3992 mSwitchingDialog = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003993 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003994
Seigo Nonakad9eb9112015-05-26 20:54:43 +09003995 updateSystemUiLocked(mCurToken, mImeWindowVis, mBackDisposition);
The Android Open Source Project10592532009-03-18 17:39:46 -07003996 mDialogBuilder = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07003997 mIms = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003998 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004000 // ----------------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004001
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004002 boolean setInputMethodEnabledLocked(String id, boolean enabled) {
4003 // Make sure this is a valid input method.
4004 InputMethodInfo imm = mMethodMap.get(id);
4005 if (imm == null) {
satokd87c2592010-09-29 11:52:06 +09004006 throw new IllegalArgumentException("Unknown id: " + mCurMethodId);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004007 }
4008
satokd87c2592010-09-29 11:52:06 +09004009 List<Pair<String, ArrayList<String>>> enabledInputMethodsList = mSettings
4010 .getEnabledInputMethodsAndSubtypeListLocked();
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004011
satokd87c2592010-09-29 11:52:06 +09004012 if (enabled) {
4013 for (Pair<String, ArrayList<String>> pair: enabledInputMethodsList) {
4014 if (pair.first.equals(id)) {
4015 // We are enabling this input method, but it is already enabled.
4016 // Nothing to do. The previous state was enabled.
4017 return true;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004018 }
4019 }
satokd87c2592010-09-29 11:52:06 +09004020 mSettings.appendAndPutEnabledInputMethodLocked(id, false);
4021 // Previous state was disabled.
4022 return false;
4023 } else {
4024 StringBuilder builder = new StringBuilder();
4025 if (mSettings.buildAndPutEnabledInputMethodsStrRemovingIdLocked(
4026 builder, enabledInputMethodsList, id)) {
4027 // Disabled input method is currently selected, switch to another one.
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004028 final String selId = mSettings.getSelectedInputMethod();
satok03eb319a2010-11-11 18:17:42 +09004029 if (id.equals(selId) && !chooseNewDefaultIMELocked()) {
4030 Slog.i(TAG, "Can't find new IME, unsetting the current input method.");
4031 resetSelectedInputMethodAndSubtypeLocked("");
satokd87c2592010-09-29 11:52:06 +09004032 }
4033 // Previous state was enabled.
4034 return true;
4035 } else {
4036 // We are disabling the input method but it is already disabled.
4037 // Nothing to do. The previous state was disabled.
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004038 return false;
4039 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004040 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004041 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08004042
satok723a27e2010-11-11 14:58:11 +09004043 private void setSelectedInputMethodAndSubtypeLocked(InputMethodInfo imi, int subtypeId,
4044 boolean setSubtypeOnly) {
Tarandeep Singh89a6c482017-11-21 14:26:11 -08004045 // Updates to InputMethod are transient in VR mode. Its not included in history.
4046 final boolean isVrInput = imi != null && imi.isVrOnly();
4047 if (!isVrInput) {
4048 // Update the history of InputMethod and Subtype
4049 mSettings.saveCurrentInputMethodAndSubtypeToHistory(mCurMethodId, mCurrentSubtype);
4050 }
satok723a27e2010-11-11 14:58:11 +09004051
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09004052 mCurUserActionNotificationSequenceNumber =
4053 Math.max(mCurUserActionNotificationSequenceNumber + 1, 1);
4054 if (DEBUG) {
4055 Slog.d(TAG, "Bump mCurUserActionNotificationSequenceNumber:"
4056 + mCurUserActionNotificationSequenceNumber);
4057 }
4058
4059 if (mCurClient != null && mCurClient.client != null) {
4060 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
4061 MSG_SET_USER_ACTION_NOTIFICATION_SEQUENCE_NUMBER,
Yohei Yukawa080fa342014-08-31 16:10:05 -07004062 mCurUserActionNotificationSequenceNumber, mCurClient));
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09004063 }
4064
Tarandeep Singh89a6c482017-11-21 14:26:11 -08004065 if (isVrInput) {
4066 // Updates to InputMethod are transient in VR mode. Any changes to Settings are skipped.
4067 return;
4068 }
4069
satok723a27e2010-11-11 14:58:11 +09004070 // Set Subtype here
4071 if (imi == null || subtypeId < 0) {
4072 mSettings.putSelectedSubtype(NOT_A_SUBTYPE_ID);
Tadashi G. Takaoka0ba75bb2010-11-09 12:19:32 -08004073 mCurrentSubtype = null;
satok723a27e2010-11-11 14:58:11 +09004074 } else {
Ken Wakasa586f0512011-01-20 22:31:01 +09004075 if (subtypeId < imi.getSubtypeCount()) {
4076 InputMethodSubtype subtype = imi.getSubtypeAt(subtypeId);
4077 mSettings.putSelectedSubtype(subtype.hashCode());
4078 mCurrentSubtype = subtype;
satok723a27e2010-11-11 14:58:11 +09004079 } else {
4080 mSettings.putSelectedSubtype(NOT_A_SUBTYPE_ID);
satokd81e9502012-05-21 12:58:45 +09004081 // If the subtype is not specified, choose the most applicable one
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004082 mCurrentSubtype = getCurrentInputMethodSubtypeLocked();
satok723a27e2010-11-11 14:58:11 +09004083 }
satokab751aa2010-09-14 19:17:36 +09004084 }
satok723a27e2010-11-11 14:58:11 +09004085
Yohei Yukawa68645a62016-02-17 07:54:20 -08004086 if (!setSubtypeOnly) {
satok723a27e2010-11-11 14:58:11 +09004087 // Set InputMethod here
4088 mSettings.putSelectedInputMethod(imi != null ? imi.getId() : "");
4089 }
4090 }
4091
4092 private void resetSelectedInputMethodAndSubtypeLocked(String newDefaultIme) {
4093 InputMethodInfo imi = mMethodMap.get(newDefaultIme);
4094 int lastSubtypeId = NOT_A_SUBTYPE_ID;
4095 // newDefaultIme is empty when there is no candidate for the selected IME.
4096 if (imi != null && !TextUtils.isEmpty(newDefaultIme)) {
4097 String subtypeHashCode = mSettings.getLastSubtypeForInputMethodLocked(newDefaultIme);
4098 if (subtypeHashCode != null) {
4099 try {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004100 lastSubtypeId = InputMethodUtils.getSubtypeIdFromHashCode(
Narayan Kamatha09b4d22016-04-15 18:32:45 +01004101 imi, Integer.parseInt(subtypeHashCode));
satok723a27e2010-11-11 14:58:11 +09004102 } catch (NumberFormatException e) {
4103 Slog.w(TAG, "HashCode for subtype looks broken: " + subtypeHashCode, e);
4104 }
4105 }
4106 }
4107 setSelectedInputMethodAndSubtypeLocked(imi, lastSubtypeId, false);
satokab751aa2010-09-14 19:17:36 +09004108 }
4109
satok4e4569d2010-11-19 18:45:53 +09004110 // If there are no selected shortcuts, tries finding the most applicable ones.
4111 private Pair<InputMethodInfo, InputMethodSubtype>
4112 findLastResortApplicableShortcutInputMethodAndSubtypeLocked(String mode) {
4113 List<InputMethodInfo> imis = mSettings.getEnabledInputMethodListLocked();
4114 InputMethodInfo mostApplicableIMI = null;
satokcd7cd292010-11-20 15:46:23 +09004115 InputMethodSubtype mostApplicableSubtype = null;
satok4e4569d2010-11-19 18:45:53 +09004116 boolean foundInSystemIME = false;
4117
4118 // Search applicable subtype for each InputMethodInfo
4119 for (InputMethodInfo imi: imis) {
satok7599a7f2010-12-22 13:45:23 +09004120 final String imiId = imi.getId();
4121 if (foundInSystemIME && !imiId.equals(mCurMethodId)) {
4122 continue;
4123 }
satokcd7cd292010-11-20 15:46:23 +09004124 InputMethodSubtype subtype = null;
satokdf31ae62011-01-15 06:19:44 +09004125 final List<InputMethodSubtype> enabledSubtypes =
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004126 mSettings.getEnabledInputMethodSubtypeListLocked(mContext, imi, true);
satokdf31ae62011-01-15 06:19:44 +09004127 // 1. Search by the current subtype's locale from enabledSubtypes.
satok4e4569d2010-11-19 18:45:53 +09004128 if (mCurrentSubtype != null) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004129 subtype = InputMethodUtils.findLastResortApplicableSubtypeLocked(
satokdf31ae62011-01-15 06:19:44 +09004130 mRes, enabledSubtypes, mode, mCurrentSubtype.getLocale(), false);
satok4e4569d2010-11-19 18:45:53 +09004131 }
satokdf31ae62011-01-15 06:19:44 +09004132 // 2. Search by the system locale from enabledSubtypes.
4133 // 3. Search the first enabled subtype matched with mode from enabledSubtypes.
satokcd7cd292010-11-20 15:46:23 +09004134 if (subtype == null) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004135 subtype = InputMethodUtils.findLastResortApplicableSubtypeLocked(
satokdf31ae62011-01-15 06:19:44 +09004136 mRes, enabledSubtypes, mode, null, true);
satok4e4569d2010-11-19 18:45:53 +09004137 }
satoka86f5e42011-09-02 17:12:42 +09004138 final ArrayList<InputMethodSubtype> overridingImplicitlyEnabledSubtypes =
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004139 InputMethodUtils.getOverridingImplicitlyEnabledSubtypes(imi, mode);
satoka86f5e42011-09-02 17:12:42 +09004140 final ArrayList<InputMethodSubtype> subtypesForSearch =
4141 overridingImplicitlyEnabledSubtypes.isEmpty()
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004142 ? InputMethodUtils.getSubtypes(imi)
4143 : overridingImplicitlyEnabledSubtypes;
satok7599a7f2010-12-22 13:45:23 +09004144 // 4. Search by the current subtype's locale from all subtypes.
4145 if (subtype == null && mCurrentSubtype != null) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004146 subtype = InputMethodUtils.findLastResortApplicableSubtypeLocked(
satoka86f5e42011-09-02 17:12:42 +09004147 mRes, subtypesForSearch, mode, mCurrentSubtype.getLocale(), false);
satok7599a7f2010-12-22 13:45:23 +09004148 }
4149 // 5. Search by the system locale from all subtypes.
4150 // 6. Search the first enabled subtype matched with mode from all subtypes.
satokcd7cd292010-11-20 15:46:23 +09004151 if (subtype == null) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004152 subtype = InputMethodUtils.findLastResortApplicableSubtypeLocked(
satoka86f5e42011-09-02 17:12:42 +09004153 mRes, subtypesForSearch, mode, null, true);
satok4e4569d2010-11-19 18:45:53 +09004154 }
satokcd7cd292010-11-20 15:46:23 +09004155 if (subtype != null) {
satok7599a7f2010-12-22 13:45:23 +09004156 if (imiId.equals(mCurMethodId)) {
satok4e4569d2010-11-19 18:45:53 +09004157 // The current input method is the most applicable IME.
4158 mostApplicableIMI = imi;
satokcd7cd292010-11-20 15:46:23 +09004159 mostApplicableSubtype = subtype;
satok4e4569d2010-11-19 18:45:53 +09004160 break;
satok7599a7f2010-12-22 13:45:23 +09004161 } else if (!foundInSystemIME) {
satok4e4569d2010-11-19 18:45:53 +09004162 // The system input method is 2nd applicable IME.
4163 mostApplicableIMI = imi;
satokcd7cd292010-11-20 15:46:23 +09004164 mostApplicableSubtype = subtype;
satok7599a7f2010-12-22 13:45:23 +09004165 if ((imi.getServiceInfo().applicationInfo.flags
4166 & ApplicationInfo.FLAG_SYSTEM) != 0) {
4167 foundInSystemIME = true;
4168 }
satok4e4569d2010-11-19 18:45:53 +09004169 }
4170 }
4171 }
4172 if (DEBUG) {
satokcd7cd292010-11-20 15:46:23 +09004173 if (mostApplicableIMI != null) {
4174 Slog.w(TAG, "Most applicable shortcut input method was:"
4175 + mostApplicableIMI.getId());
4176 if (mostApplicableSubtype != null) {
4177 Slog.w(TAG, "Most applicable shortcut input method subtype was:"
4178 + "," + mostApplicableSubtype.getMode() + ","
4179 + mostApplicableSubtype.getLocale());
4180 }
4181 }
satok4e4569d2010-11-19 18:45:53 +09004182 }
satokcd7cd292010-11-20 15:46:23 +09004183 if (mostApplicableIMI != null) {
Yohei Yukawab0377bb2015-08-10 21:06:30 -07004184 return new Pair<> (mostApplicableIMI, mostApplicableSubtype);
satok4e4569d2010-11-19 18:45:53 +09004185 } else {
4186 return null;
4187 }
4188 }
4189
satokab751aa2010-09-14 19:17:36 +09004190 /**
4191 * @return Return the current subtype of this input method.
4192 */
satok42c5a162011-05-26 16:46:14 +09004193 @Override
satokab751aa2010-09-14 19:17:36 +09004194 public InputMethodSubtype getCurrentInputMethodSubtype() {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004195 // TODO: Make this work even for non-current users?
4196 if (!calledFromValidUser()) {
4197 return null;
4198 }
4199 synchronized (mMethodMap) {
4200 return getCurrentInputMethodSubtypeLocked();
4201 }
4202 }
4203
4204 private InputMethodSubtype getCurrentInputMethodSubtypeLocked() {
satokfdf419e2012-05-08 16:52:08 +09004205 if (mCurMethodId == null) {
4206 return null;
4207 }
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004208 final boolean subtypeIsSelected = mSettings.isSubtypeSelected();
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004209 final InputMethodInfo imi = mMethodMap.get(mCurMethodId);
4210 if (imi == null || imi.getSubtypeCount() == 0) {
4211 return null;
satok4e4569d2010-11-19 18:45:53 +09004212 }
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004213 if (!subtypeIsSelected || mCurrentSubtype == null
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004214 || !InputMethodUtils.isValidSubtypeId(imi, mCurrentSubtype.hashCode())) {
4215 int subtypeId = mSettings.getSelectedInputMethodSubtypeId(mCurMethodId);
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004216 if (subtypeId == NOT_A_SUBTYPE_ID) {
4217 // If there are no selected subtypes, the framework will try to find
4218 // the most applicable subtype from explicitly or implicitly enabled
4219 // subtypes.
4220 List<InputMethodSubtype> explicitlyOrImplicitlyEnabledSubtypes =
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004221 mSettings.getEnabledInputMethodSubtypeListLocked(mContext, imi, true);
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004222 // If there is only one explicitly or implicitly enabled subtype,
4223 // just returns it.
4224 if (explicitlyOrImplicitlyEnabledSubtypes.size() == 1) {
4225 mCurrentSubtype = explicitlyOrImplicitlyEnabledSubtypes.get(0);
4226 } else if (explicitlyOrImplicitlyEnabledSubtypes.size() > 1) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004227 mCurrentSubtype = InputMethodUtils.findLastResortApplicableSubtypeLocked(
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004228 mRes, explicitlyOrImplicitlyEnabledSubtypes,
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004229 InputMethodUtils.SUBTYPE_MODE_KEYBOARD, null, true);
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004230 if (mCurrentSubtype == null) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004231 mCurrentSubtype = InputMethodUtils.findLastResortApplicableSubtypeLocked(
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004232 mRes, explicitlyOrImplicitlyEnabledSubtypes, null, null,
4233 true);
satok4e4569d2010-11-19 18:45:53 +09004234 }
satok3ef8b292010-11-23 06:06:29 +09004235 }
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004236 } else {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004237 mCurrentSubtype = InputMethodUtils.getSubtypes(imi).get(subtypeId);
satok8fbb1e82010-11-02 23:15:58 +09004238 }
4239 }
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004240 return mCurrentSubtype;
satokab751aa2010-09-14 19:17:36 +09004241 }
4242
satok4e4569d2010-11-19 18:45:53 +09004243 // TODO: We should change the return type from List to List<Parcelable>
satokdbf29502011-08-25 15:28:23 +09004244 @SuppressWarnings("rawtypes")
satoke7c6998e2011-06-03 17:57:59 +09004245 @Override
satok4e4569d2010-11-19 18:45:53 +09004246 public List getShortcutInputMethodsAndSubtypes() {
4247 synchronized (mMethodMap) {
Yohei Yukawab0377bb2015-08-10 21:06:30 -07004248 ArrayList<Object> ret = new ArrayList<>();
satokf3db1af2010-11-23 13:34:33 +09004249 if (mShortcutInputMethodsAndSubtypes.size() == 0) {
satok4e4569d2010-11-19 18:45:53 +09004250 // If there are no selected shortcut subtypes, the framework will try to find
4251 // the most applicable subtype from all subtypes whose mode is
4252 // SUBTYPE_MODE_VOICE. This is an exceptional case, so we will hardcode the mode.
satokf3db1af2010-11-23 13:34:33 +09004253 Pair<InputMethodInfo, InputMethodSubtype> info =
4254 findLastResortApplicableShortcutInputMethodAndSubtypeLocked(
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004255 InputMethodUtils.SUBTYPE_MODE_VOICE);
satok7599a7f2010-12-22 13:45:23 +09004256 if (info != null) {
satok3da92232011-01-11 22:46:30 +09004257 ret.add(info.first);
4258 ret.add(info.second);
satok7599a7f2010-12-22 13:45:23 +09004259 }
satok3da92232011-01-11 22:46:30 +09004260 return ret;
satokf3db1af2010-11-23 13:34:33 +09004261 }
satokf3db1af2010-11-23 13:34:33 +09004262 for (InputMethodInfo imi: mShortcutInputMethodsAndSubtypes.keySet()) {
4263 ret.add(imi);
4264 for (InputMethodSubtype subtype: mShortcutInputMethodsAndSubtypes.get(imi)) {
4265 ret.add(subtype);
satok4e4569d2010-11-19 18:45:53 +09004266 }
4267 }
satokf3db1af2010-11-23 13:34:33 +09004268 return ret;
satok4e4569d2010-11-19 18:45:53 +09004269 }
4270 }
4271
satok42c5a162011-05-26 16:46:14 +09004272 @Override
satokb66d2872010-11-10 01:04:04 +09004273 public boolean setCurrentInputMethodSubtype(InputMethodSubtype subtype) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004274 // TODO: Make this work even for non-current users?
4275 if (!calledFromValidUser()) {
4276 return false;
4277 }
satokb66d2872010-11-10 01:04:04 +09004278 synchronized (mMethodMap) {
4279 if (subtype != null && mCurMethodId != null) {
4280 InputMethodInfo imi = mMethodMap.get(mCurMethodId);
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004281 int subtypeId = InputMethodUtils.getSubtypeIdFromHashCode(imi, subtype.hashCode());
satokb66d2872010-11-10 01:04:04 +09004282 if (subtypeId != NOT_A_SUBTYPE_ID) {
4283 setInputMethodLocked(mCurMethodId, subtypeId);
4284 return true;
4285 }
4286 }
4287 return false;
4288 }
4289 }
4290
Satoshi Kataoka5ade83b2012-09-26 22:59:41 +09004291 // TODO: Cache the state for each user and reset when the cached user is removed.
satoke7c6998e2011-06-03 17:57:59 +09004292 private static class InputMethodFileManager {
4293 private static final String SYSTEM_PATH = "system";
4294 private static final String INPUT_METHOD_PATH = "inputmethod";
4295 private static final String ADDITIONAL_SUBTYPES_FILE_NAME = "subtypes.xml";
4296 private static final String NODE_SUBTYPES = "subtypes";
4297 private static final String NODE_SUBTYPE = "subtype";
4298 private static final String NODE_IMI = "imi";
4299 private static final String ATTR_ID = "id";
4300 private static final String ATTR_LABEL = "label";
4301 private static final String ATTR_ICON = "icon";
Yohei Yukawa66baf692016-04-11 02:29:35 -07004302 private static final String ATTR_IME_SUBTYPE_ID = "subtypeId";
satoke7c6998e2011-06-03 17:57:59 +09004303 private static final String ATTR_IME_SUBTYPE_LOCALE = "imeSubtypeLocale";
Yohei Yukawa868d19b2015-12-07 15:58:57 -08004304 private static final String ATTR_IME_SUBTYPE_LANGUAGE_TAG = "languageTag";
satoke7c6998e2011-06-03 17:57:59 +09004305 private static final String ATTR_IME_SUBTYPE_MODE = "imeSubtypeMode";
4306 private static final String ATTR_IME_SUBTYPE_EXTRA_VALUE = "imeSubtypeExtraValue";
4307 private static final String ATTR_IS_AUXILIARY = "isAuxiliary";
Yohei Yukawa1e1a4472016-03-10 23:46:07 -08004308 private static final String ATTR_IS_ASCII_CAPABLE = "isAsciiCapable";
satoke7c6998e2011-06-03 17:57:59 +09004309 private final AtomicFile mAdditionalInputMethodSubtypeFile;
4310 private final HashMap<String, InputMethodInfo> mMethodMap;
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004311 private final HashMap<String, List<InputMethodSubtype>> mAdditionalSubtypesMap =
Yohei Yukawab0377bb2015-08-10 21:06:30 -07004312 new HashMap<>();
Satoshi Kataoka5ade83b2012-09-26 22:59:41 +09004313 public InputMethodFileManager(HashMap<String, InputMethodInfo> methodMap, int userId) {
satoke7c6998e2011-06-03 17:57:59 +09004314 if (methodMap == null) {
4315 throw new NullPointerException("methodMap is null");
4316 }
4317 mMethodMap = methodMap;
Xiaohui Chen7c696362015-09-16 09:56:14 -07004318 final File systemDir = userId == UserHandle.USER_SYSTEM
Satoshi Kataoka5ade83b2012-09-26 22:59:41 +09004319 ? new File(Environment.getDataDirectory(), SYSTEM_PATH)
4320 : Environment.getUserSystemDirectory(userId);
satoke7c6998e2011-06-03 17:57:59 +09004321 final File inputMethodDir = new File(systemDir, INPUT_METHOD_PATH);
Yohei Yukawadf5af482015-08-04 22:11:11 -07004322 if (!inputMethodDir.exists() && !inputMethodDir.mkdirs()) {
satoke7c6998e2011-06-03 17:57:59 +09004323 Slog.w(TAG, "Couldn't create dir.: " + inputMethodDir.getAbsolutePath());
4324 }
4325 final File subtypeFile = new File(inputMethodDir, ADDITIONAL_SUBTYPES_FILE_NAME);
Dianne Hackborne17b4452018-01-10 13:15:40 -08004326 mAdditionalInputMethodSubtypeFile = new AtomicFile(subtypeFile, "input-subtypes");
satoke7c6998e2011-06-03 17:57:59 +09004327 if (!subtypeFile.exists()) {
4328 // If "subtypes.xml" doesn't exist, create a blank file.
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004329 writeAdditionalInputMethodSubtypes(
4330 mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile, methodMap);
satoke7c6998e2011-06-03 17:57:59 +09004331 } else {
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004332 readAdditionalInputMethodSubtypes(
4333 mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile);
satoke7c6998e2011-06-03 17:57:59 +09004334 }
4335 }
4336
4337 private void deleteAllInputMethodSubtypes(String imiId) {
4338 synchronized (mMethodMap) {
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004339 mAdditionalSubtypesMap.remove(imiId);
4340 writeAdditionalInputMethodSubtypes(
4341 mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile, mMethodMap);
satoke7c6998e2011-06-03 17:57:59 +09004342 }
4343 }
4344
4345 public void addInputMethodSubtypes(
satok4a28bde2011-06-29 21:03:40 +09004346 InputMethodInfo imi, InputMethodSubtype[] additionalSubtypes) {
satoke7c6998e2011-06-03 17:57:59 +09004347 synchronized (mMethodMap) {
Yohei Yukawab0377bb2015-08-10 21:06:30 -07004348 final ArrayList<InputMethodSubtype> subtypes = new ArrayList<>();
satoke7c6998e2011-06-03 17:57:59 +09004349 final int N = additionalSubtypes.length;
4350 for (int i = 0; i < N; ++i) {
4351 final InputMethodSubtype subtype = additionalSubtypes[i];
satoked2b24e2011-08-31 18:03:21 +09004352 if (!subtypes.contains(subtype)) {
satoke7c6998e2011-06-03 17:57:59 +09004353 subtypes.add(subtype);
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004354 } else {
4355 Slog.w(TAG, "Duplicated subtype definition found: "
4356 + subtype.getLocale() + ", " + subtype.getMode());
satoke7c6998e2011-06-03 17:57:59 +09004357 }
4358 }
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004359 mAdditionalSubtypesMap.put(imi.getId(), subtypes);
4360 writeAdditionalInputMethodSubtypes(
4361 mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile, mMethodMap);
satoke7c6998e2011-06-03 17:57:59 +09004362 }
4363 }
4364
4365 public HashMap<String, List<InputMethodSubtype>> getAllAdditionalInputMethodSubtypes() {
4366 synchronized (mMethodMap) {
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004367 return mAdditionalSubtypesMap;
satoke7c6998e2011-06-03 17:57:59 +09004368 }
4369 }
4370
4371 private static void writeAdditionalInputMethodSubtypes(
4372 HashMap<String, List<InputMethodSubtype>> allSubtypes, AtomicFile subtypesFile,
4373 HashMap<String, InputMethodInfo> methodMap) {
4374 // Safety net for the case that this function is called before methodMap is set.
4375 final boolean isSetMethodMap = methodMap != null && methodMap.size() > 0;
4376 FileOutputStream fos = null;
4377 try {
4378 fos = subtypesFile.startWrite();
4379 final XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01004380 out.setOutput(fos, StandardCharsets.UTF_8.name());
satoke7c6998e2011-06-03 17:57:59 +09004381 out.startDocument(null, true);
4382 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
4383 out.startTag(null, NODE_SUBTYPES);
4384 for (String imiId : allSubtypes.keySet()) {
4385 if (isSetMethodMap && !methodMap.containsKey(imiId)) {
4386 Slog.w(TAG, "IME uninstalled or not valid.: " + imiId);
4387 continue;
4388 }
4389 out.startTag(null, NODE_IMI);
4390 out.attribute(null, ATTR_ID, imiId);
4391 final List<InputMethodSubtype> subtypesList = allSubtypes.get(imiId);
4392 final int N = subtypesList.size();
4393 for (int i = 0; i < N; ++i) {
4394 final InputMethodSubtype subtype = subtypesList.get(i);
4395 out.startTag(null, NODE_SUBTYPE);
Yohei Yukawa66baf692016-04-11 02:29:35 -07004396 if (subtype.hasSubtypeId()) {
4397 out.attribute(null, ATTR_IME_SUBTYPE_ID,
4398 String.valueOf(subtype.getSubtypeId()));
4399 }
satoke7c6998e2011-06-03 17:57:59 +09004400 out.attribute(null, ATTR_ICON, String.valueOf(subtype.getIconResId()));
4401 out.attribute(null, ATTR_LABEL, String.valueOf(subtype.getNameResId()));
4402 out.attribute(null, ATTR_IME_SUBTYPE_LOCALE, subtype.getLocale());
Yohei Yukawa868d19b2015-12-07 15:58:57 -08004403 out.attribute(null, ATTR_IME_SUBTYPE_LANGUAGE_TAG,
4404 subtype.getLanguageTag());
satoke7c6998e2011-06-03 17:57:59 +09004405 out.attribute(null, ATTR_IME_SUBTYPE_MODE, subtype.getMode());
4406 out.attribute(null, ATTR_IME_SUBTYPE_EXTRA_VALUE, subtype.getExtraValue());
4407 out.attribute(null, ATTR_IS_AUXILIARY,
4408 String.valueOf(subtype.isAuxiliary() ? 1 : 0));
Yohei Yukawa1e1a4472016-03-10 23:46:07 -08004409 out.attribute(null, ATTR_IS_ASCII_CAPABLE,
4410 String.valueOf(subtype.isAsciiCapable() ? 1 : 0));
satoke7c6998e2011-06-03 17:57:59 +09004411 out.endTag(null, NODE_SUBTYPE);
4412 }
4413 out.endTag(null, NODE_IMI);
4414 }
4415 out.endTag(null, NODE_SUBTYPES);
4416 out.endDocument();
4417 subtypesFile.finishWrite(fos);
4418 } catch (java.io.IOException e) {
4419 Slog.w(TAG, "Error writing subtypes", e);
4420 if (fos != null) {
4421 subtypesFile.failWrite(fos);
4422 }
4423 }
4424 }
4425
4426 private static void readAdditionalInputMethodSubtypes(
4427 HashMap<String, List<InputMethodSubtype>> allSubtypes, AtomicFile subtypesFile) {
4428 if (allSubtypes == null || subtypesFile == null) return;
4429 allSubtypes.clear();
Yohei Yukawa5894b432015-08-11 13:29:24 -07004430 try (final FileInputStream fis = subtypesFile.openRead()) {
satoke7c6998e2011-06-03 17:57:59 +09004431 final XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01004432 parser.setInput(fis, StandardCharsets.UTF_8.name());
satoke7c6998e2011-06-03 17:57:59 +09004433 int type = parser.getEventType();
4434 // Skip parsing until START_TAG
4435 while ((type = parser.next()) != XmlPullParser.START_TAG
4436 && type != XmlPullParser.END_DOCUMENT) {}
4437 String firstNodeName = parser.getName();
4438 if (!NODE_SUBTYPES.equals(firstNodeName)) {
4439 throw new XmlPullParserException("Xml doesn't start with subtypes");
4440 }
4441 final int depth =parser.getDepth();
4442 String currentImiId = null;
4443 ArrayList<InputMethodSubtype> tempSubtypesArray = null;
4444 while (((type = parser.next()) != XmlPullParser.END_TAG
4445 || parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
4446 if (type != XmlPullParser.START_TAG)
4447 continue;
4448 final String nodeName = parser.getName();
4449 if (NODE_IMI.equals(nodeName)) {
4450 currentImiId = parser.getAttributeValue(null, ATTR_ID);
4451 if (TextUtils.isEmpty(currentImiId)) {
4452 Slog.w(TAG, "Invalid imi id found in subtypes.xml");
4453 continue;
4454 }
Yohei Yukawab0377bb2015-08-10 21:06:30 -07004455 tempSubtypesArray = new ArrayList<>();
satoke7c6998e2011-06-03 17:57:59 +09004456 allSubtypes.put(currentImiId, tempSubtypesArray);
4457 } else if (NODE_SUBTYPE.equals(nodeName)) {
4458 if (TextUtils.isEmpty(currentImiId) || tempSubtypesArray == null) {
4459 Slog.w(TAG, "IME uninstalled or not valid.: " + currentImiId);
4460 continue;
4461 }
Narayan Kamatha09b4d22016-04-15 18:32:45 +01004462 final int icon = Integer.parseInt(
satoke7c6998e2011-06-03 17:57:59 +09004463 parser.getAttributeValue(null, ATTR_ICON));
Narayan Kamatha09b4d22016-04-15 18:32:45 +01004464 final int label = Integer.parseInt(
satoke7c6998e2011-06-03 17:57:59 +09004465 parser.getAttributeValue(null, ATTR_LABEL));
4466 final String imeSubtypeLocale =
4467 parser.getAttributeValue(null, ATTR_IME_SUBTYPE_LOCALE);
Yohei Yukawa868d19b2015-12-07 15:58:57 -08004468 final String languageTag =
4469 parser.getAttributeValue(null, ATTR_IME_SUBTYPE_LANGUAGE_TAG);
satoke7c6998e2011-06-03 17:57:59 +09004470 final String imeSubtypeMode =
4471 parser.getAttributeValue(null, ATTR_IME_SUBTYPE_MODE);
4472 final String imeSubtypeExtraValue =
4473 parser.getAttributeValue(null, ATTR_IME_SUBTYPE_EXTRA_VALUE);
satok4a28bde2011-06-29 21:03:40 +09004474 final boolean isAuxiliary = "1".equals(String.valueOf(
4475 parser.getAttributeValue(null, ATTR_IS_AUXILIARY)));
Yohei Yukawa1e1a4472016-03-10 23:46:07 -08004476 final boolean isAsciiCapable = "1".equals(String.valueOf(
4477 parser.getAttributeValue(null, ATTR_IS_ASCII_CAPABLE)));
Yohei Yukawa66baf692016-04-11 02:29:35 -07004478 final InputMethodSubtypeBuilder builder = new InputMethodSubtypeBuilder()
Yohei Yukawa443c2ba2014-09-10 14:10:30 +09004479 .setSubtypeNameResId(label)
4480 .setSubtypeIconResId(icon)
4481 .setSubtypeLocale(imeSubtypeLocale)
Yohei Yukawa868d19b2015-12-07 15:58:57 -08004482 .setLanguageTag(languageTag)
Yohei Yukawa443c2ba2014-09-10 14:10:30 +09004483 .setSubtypeMode(imeSubtypeMode)
4484 .setSubtypeExtraValue(imeSubtypeExtraValue)
4485 .setIsAuxiliary(isAuxiliary)
Yohei Yukawa66baf692016-04-11 02:29:35 -07004486 .setIsAsciiCapable(isAsciiCapable);
4487 final String subtypeIdString =
4488 parser.getAttributeValue(null, ATTR_IME_SUBTYPE_ID);
4489 if (subtypeIdString != null) {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01004490 builder.setSubtypeId(Integer.parseInt(subtypeIdString));
Yohei Yukawa66baf692016-04-11 02:29:35 -07004491 }
4492 tempSubtypesArray.add(builder.build());
satoke7c6998e2011-06-03 17:57:59 +09004493 }
4494 }
Yohei Yukawa5894b432015-08-11 13:29:24 -07004495 } catch (XmlPullParserException | IOException | NumberFormatException e) {
4496 Slog.w(TAG, "Error reading subtypes", e);
satoke7c6998e2011-06-03 17:57:59 +09004497 return;
satoke7c6998e2011-06-03 17:57:59 +09004498 }
4499 }
4500 }
4501
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07004502 private static final class LocalServiceImpl implements InputMethodManagerInternal {
4503 @NonNull
4504 private final Handler mHandler;
4505
4506 LocalServiceImpl(@NonNull final Handler handler) {
4507 mHandler = handler;
4508 }
4509
4510 @Override
4511 public void setInteractive(boolean interactive) {
4512 // Do everything in handler so as not to block the caller.
4513 mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_INTERACTIVE,
4514 interactive ? 1 : 0, 0));
4515 }
Yohei Yukawaae61f712015-12-09 13:00:10 -08004516
4517 @Override
4518 public void switchInputMethod(boolean forwardDirection) {
4519 // Do everything in handler so as not to block the caller.
4520 mHandler.sendMessage(mHandler.obtainMessage(MSG_SWITCH_IME,
4521 forwardDirection ? 1 : 0, 0));
4522 }
Jorim Jaggi3c5d0f12016-05-24 19:04:30 -07004523
4524 @Override
4525 public void hideCurrentInputMethod() {
4526 mHandler.removeMessages(MSG_HIDE_CURRENT_INPUT_METHOD);
4527 mHandler.sendEmptyMessage(MSG_HIDE_CURRENT_INPUT_METHOD);
4528 }
Tarandeep Singh89a6c482017-11-21 14:26:11 -08004529
4530 @Override
4531 public void startVrInputMethodNoCheck(@Nullable ComponentName componentName) {
4532 mHandler.sendMessage(mHandler.obtainMessage(MSG_START_VR_INPUT, componentName));
4533 }
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07004534 }
4535
Yohei Yukawaebda7d72016-04-02 17:39:23 -07004536 private static String imeWindowStatusToString(final int imeWindowVis) {
4537 final StringBuilder sb = new StringBuilder();
4538 boolean first = true;
4539 if ((imeWindowVis & InputMethodService.IME_ACTIVE) != 0) {
4540 sb.append("Active");
4541 first = false;
4542 }
4543 if ((imeWindowVis & InputMethodService.IME_VISIBLE) != 0) {
4544 if (!first) {
4545 sb.append("|");
4546 }
4547 sb.append("Visible");
4548 }
4549 return sb.toString();
4550 }
4551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004552 @Override
Yohei Yukawa25e08132016-06-22 16:31:41 -07004553 public IInputContentUriToken createInputContentUriToken(@Nullable IBinder token,
4554 @Nullable Uri contentUri, @Nullable String packageName) {
4555 if (!calledFromValidUser()) {
4556 return null;
4557 }
4558
4559 if (token == null) {
4560 throw new NullPointerException("token");
4561 }
4562 if (packageName == null) {
4563 throw new NullPointerException("packageName");
4564 }
4565 if (contentUri == null) {
4566 throw new NullPointerException("contentUri");
4567 }
4568 final String contentUriScheme = contentUri.getScheme();
4569 if (!"content".equals(contentUriScheme)) {
4570 throw new InvalidParameterException("contentUri must have content scheme");
4571 }
4572
4573 synchronized (mMethodMap) {
4574 final int uid = Binder.getCallingUid();
4575 if (mCurMethodId == null) {
4576 return null;
4577 }
4578 if (mCurToken != token) {
4579 Slog.e(TAG, "Ignoring createInputContentUriToken mCurToken=" + mCurToken
4580 + " token=" + token);
4581 return null;
4582 }
4583 // We cannot simply distinguish a bad IME that reports an arbitrary package name from
4584 // an unfortunate IME whose internal state is already obsolete due to the asynchronous
4585 // nature of our system. Let's compare it with our internal record.
4586 if (!TextUtils.equals(mCurAttribute.packageName, packageName)) {
4587 Slog.e(TAG, "Ignoring createInputContentUriToken mCurAttribute.packageName="
4588 + mCurAttribute.packageName + " packageName=" + packageName);
4589 return null;
4590 }
Yohei Yukawa3933a6e2016-11-10 00:47:48 -08004591 // This user ID can never bee spoofed.
Yohei Yukawa25e08132016-06-22 16:31:41 -07004592 final int imeUserId = UserHandle.getUserId(uid);
Yohei Yukawa3933a6e2016-11-10 00:47:48 -08004593 // This user ID can never bee spoofed.
Yohei Yukawa25e08132016-06-22 16:31:41 -07004594 final int appUserId = UserHandle.getUserId(mCurClient.uid);
Yohei Yukawa3933a6e2016-11-10 00:47:48 -08004595 // This user ID may be invalid if "contentUri" embedded an invalid user ID.
4596 final int contentUriOwnerUserId = ContentProvider.getUserIdFromUri(contentUri,
4597 imeUserId);
4598 final Uri contentUriWithoutUserId = ContentProvider.getUriWithoutUserId(contentUri);
4599 // Note: InputContentUriTokenHandler.take() checks whether the IME (specified by "uid")
4600 // actually has the right to grant a read permission for "contentUriWithoutUserId" that
4601 // is claimed to belong to "contentUriOwnerUserId". For example, specifying random
4602 // content URI and/or contentUriOwnerUserId just results in a SecurityException thrown
4603 // from InputContentUriTokenHandler.take() and can never be allowed beyond what is
4604 // actually allowed to "uid", which is guaranteed to be the IME's one.
4605 return new InputContentUriTokenHandler(contentUriWithoutUserId, uid,
4606 packageName, contentUriOwnerUserId, appUserId);
Yohei Yukawa25e08132016-06-22 16:31:41 -07004607 }
4608 }
4609
4610 @Override
Yohei Yukawa2bc66172017-02-08 11:13:25 -08004611 public void reportFullscreenMode(IBinder token, boolean fullscreen) {
4612 if (!calledFromValidUser()) {
4613 return;
4614 }
4615 synchronized (mMethodMap) {
4616 if (!calledWithValidToken(token)) {
4617 return;
4618 }
4619 if (mCurClient != null && mCurClient.client != null) {
4620 mInFullscreenMode = fullscreen;
4621 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
4622 MSG_REPORT_FULLSCREEN_MODE, fullscreen ? 1 : 0, mCurClient));
4623 }
4624 }
4625 }
4626
4627 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004628 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06004629 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004630
4631 IInputMethod method;
4632 ClientState client;
Yohei Yukawae39d4ed2015-11-19 03:38:49 -08004633 ClientState focusedWindowClient;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004635 final Printer p = new PrintWriterPrinter(pw);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004637 synchronized (mMethodMap) {
4638 p.println("Current Input Method Manager state:");
4639 int N = mMethodList.size();
Yohei Yukawae0733062017-02-09 22:49:35 -08004640 p.println(" Input Methods: mMethodMapUpdateCount=" + mMethodMapUpdateCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004641 for (int i=0; i<N; i++) {
4642 InputMethodInfo info = mMethodList.get(i);
4643 p.println(" InputMethod #" + i + ":");
4644 info.dump(p, " ");
4645 }
4646 p.println(" Clients:");
4647 for (ClientState ci : mClients.values()) {
4648 p.println(" Client " + ci + ":");
4649 p.println(" client=" + ci.client);
4650 p.println(" inputContext=" + ci.inputContext);
4651 p.println(" sessionRequested=" + ci.sessionRequested);
4652 p.println(" curSession=" + ci.curSession);
4653 }
The Android Open Source Project10592532009-03-18 17:39:46 -07004654 p.println(" mCurMethodId=" + mCurMethodId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004655 client = mCurClient;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004656 p.println(" mCurClient=" + client + " mCurSeq=" + mCurSeq);
Yohei Yukawa22a89232017-02-12 16:38:59 -08004657 p.println(" mCurFocusedWindow=" + mCurFocusedWindow
4658 + " softInputMode=" +
4659 InputMethodClient.softInputModeToString(mCurFocusedWindowSoftInputMode)
4660 + " client=" + mCurFocusedWindowClient);
Yohei Yukawae39d4ed2015-11-19 03:38:49 -08004661 focusedWindowClient = mCurFocusedWindowClient;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004662 p.println(" mCurId=" + mCurId + " mHaveConnect=" + mHaveConnection
4663 + " mBoundToMethod=" + mBoundToMethod);
4664 p.println(" mCurToken=" + mCurToken);
4665 p.println(" mCurIntent=" + mCurIntent);
4666 method = mCurMethod;
4667 p.println(" mCurMethod=" + mCurMethod);
4668 p.println(" mEnabledSession=" + mEnabledSession);
Yohei Yukawaebda7d72016-04-02 17:39:23 -07004669 p.println(" mImeWindowVis=" + imeWindowStatusToString(mImeWindowVis));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004670 p.println(" mShowRequested=" + mShowRequested
4671 + " mShowExplicitlyRequested=" + mShowExplicitlyRequested
4672 + " mShowForced=" + mShowForced
4673 + " mInputShown=" + mInputShown);
Yohei Yukawa2bc66172017-02-08 11:13:25 -08004674 p.println(" mInFullscreenMode=" + mInFullscreenMode);
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09004675 p.println(" mCurUserActionNotificationSequenceNumber="
4676 + mCurUserActionNotificationSequenceNumber);
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07004677 p.println(" mSystemReady=" + mSystemReady + " mInteractive=" + mIsInteractive);
Yohei Yukawa81482972015-06-04 00:58:59 -07004678 p.println(" mSettingsObserver=" + mSettingsObserver);
Yohei Yukawad7248862015-06-03 23:56:12 -07004679 p.println(" mSwitchingController:");
4680 mSwitchingController.dump(p);
Yohei Yukawa68645a62016-02-17 07:54:20 -08004681 p.println(" mSettings:");
4682 mSettings.dumpLocked(p, " ");
Yohei Yukawa357b2f62017-02-14 09:40:03 -08004683
4684 p.println(" mStartInputHistory:");
4685 mStartInputHistory.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004686 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004687
Jeff Brownb88102f2010-09-08 11:49:43 -07004688 p.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004689 if (client != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004690 pw.flush();
4691 try {
Jeff Sharkey850c83e2016-11-09 12:25:44 -07004692 TransferPipe.dumpAsync(client.client.asBinder(), fd, args);
4693 } catch (IOException | RemoteException e) {
4694 p.println("Failed to dump input method client: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004695 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004696 } else {
4697 p.println("No input method client.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004698 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004699
Yohei Yukawae39d4ed2015-11-19 03:38:49 -08004700 if (focusedWindowClient != null && client != focusedWindowClient) {
4701 p.println(" ");
4702 p.println("Warning: Current input method client doesn't match the last focused. "
4703 + "window.");
4704 p.println("Dumping input method client in the last focused window just in case.");
4705 p.println(" ");
4706 pw.flush();
4707 try {
Jeff Sharkey850c83e2016-11-09 12:25:44 -07004708 TransferPipe.dumpAsync(focusedWindowClient.client.asBinder(), fd, args);
4709 } catch (IOException | RemoteException e) {
4710 p.println("Failed to dump input method client in focused window: " + e);
Yohei Yukawae39d4ed2015-11-19 03:38:49 -08004711 }
4712 }
4713
Jeff Brownb88102f2010-09-08 11:49:43 -07004714 p.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004715 if (method != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004716 pw.flush();
4717 try {
Jeff Sharkey850c83e2016-11-09 12:25:44 -07004718 TransferPipe.dumpAsync(method.asBinder(), fd, args);
4719 } catch (IOException | RemoteException e) {
4720 p.println("Failed to dump input method service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004721 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004722 } else {
4723 p.println("No input method service.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004724 }
4725 }
Yohei Yukawa926488d2017-12-11 17:24:55 -08004726
4727 @BinderThread
4728 @Override
4729 public void onShellCommand(@Nullable FileDescriptor in, @Nullable FileDescriptor out,
4730 @Nullable FileDescriptor err,
4731 @NonNull String[] args, @Nullable ShellCallback callback,
4732 @NonNull ResultReceiver resultReceiver) throws RemoteException {
4733 new ShellCommandImpl(this).exec(
4734 this, in, out, err, args, callback, resultReceiver);
4735 }
4736
4737 private static final class ShellCommandImpl extends ShellCommand {
4738 @NonNull
4739 final InputMethodManagerService mService;
4740
4741 ShellCommandImpl(InputMethodManagerService service) {
4742 mService = service;
4743 }
4744
4745 @BinderThread
4746 @ShellCommandResult
4747 @Override
4748 public int onCommand(@Nullable String cmd) {
Yohei Yukawacac97722017-12-15 16:52:05 -08004749 // For existing "adb shell ime <command>".
4750 if ("ime".equals(cmd)) {
4751 final String imeCommand = getNextArg();
4752 if (imeCommand == null || "help".equals(imeCommand) || "-h".equals(imeCommand)) {
4753 onImeCommandHelp();
4754 return ShellCommandResult.SUCCESS;
4755 }
4756 switch (imeCommand) {
4757 case "list":
4758 return mService.handleShellCommandListInputMethods(this);
4759 case "enable":
4760 return mService.handleShellCommandEnableDisableInputMethod(this, true);
4761 case "disable":
4762 return mService.handleShellCommandEnableDisableInputMethod(this, false);
4763 case "set":
4764 return mService.handleShellCommandSetInputMethod(this);
4765 case "reset":
4766 return mService.handleShellCommandResetInputMethod(this);
Tarandeep Singh75a92392018-01-12 14:58:59 -08004767 case "refresh_debug_properties":
4768 return refreshDebugProperties();
Yohei Yukawacac97722017-12-15 16:52:05 -08004769 default:
4770 getOutPrintWriter().println("Unknown command: " + imeCommand);
4771 return ShellCommandResult.FAILURE;
4772 }
Yohei Yukawa926488d2017-12-11 17:24:55 -08004773 }
Yohei Yukawacac97722017-12-15 16:52:05 -08004774
4775 return handleDefaultCommands(cmd);
Yohei Yukawa926488d2017-12-11 17:24:55 -08004776 }
4777
4778 @BinderThread
Tarandeep Singh75a92392018-01-12 14:58:59 -08004779 @ShellCommandResult
4780 private int refreshDebugProperties() {
4781 DebugFlags.FLAG_OPTIMIZE_START_INPUT.refresh();
4782 return ShellCommandResult.SUCCESS;
4783 }
4784
4785 @BinderThread
Yohei Yukawa926488d2017-12-11 17:24:55 -08004786 @Override
4787 public void onHelp() {
4788 try (PrintWriter pw = getOutPrintWriter()) {
4789 pw.println("InputMethodManagerService commands:");
4790 pw.println(" help");
4791 pw.println(" Prints this help text.");
4792 pw.println(" dump [options]");
4793 pw.println(" Synonym of dumpsys.");
Yohei Yukawacac97722017-12-15 16:52:05 -08004794 pw.println(" ime <command> [options]");
4795 pw.println(" Manipulate IMEs. Run \"ime help\" for details.");
4796 }
4797 }
4798
4799 private void onImeCommandHelp() {
4800 try (IndentingPrintWriter pw =
4801 new IndentingPrintWriter(getOutPrintWriter(), " ", 100)) {
4802 pw.println("ime <command>:");
4803 pw.increaseIndent();
4804
4805 pw.println("list [-a] [-s]");
4806 pw.increaseIndent();
4807 pw.println("prints all enabled input methods.");
4808 pw.increaseIndent();
4809 pw.println("-a: see all input methods");
4810 pw.println("-s: only a single summary line of each");
4811 pw.decreaseIndent();
4812 pw.decreaseIndent();
4813
4814 pw.println("enable <ID>");
4815 pw.increaseIndent();
4816 pw.println("allows the given input method ID to be used.");
4817 pw.decreaseIndent();
4818
4819 pw.println("disable <ID>");
4820 pw.increaseIndent();
4821 pw.println("disallows the given input method ID to be used.");
4822 pw.decreaseIndent();
4823
4824 pw.println("set <ID>");
4825 pw.increaseIndent();
4826 pw.println("switches to the given input method ID.");
4827 pw.decreaseIndent();
4828
4829 pw.println("reset");
4830 pw.increaseIndent();
4831 pw.println("reset currently selected/enabled IMEs to the default ones as if "
4832 + "the device is initially booted with the current locale.");
4833 pw.decreaseIndent();
4834
4835 pw.decreaseIndent();
Yohei Yukawa926488d2017-12-11 17:24:55 -08004836 }
4837 }
4838 }
4839
4840 // ----------------------------------------------------------------------
4841 // Shell command handlers:
4842
4843 /**
4844 * Handles {@code adb shell ime list}.
4845 * @param shellCommand {@link ShellCommand} object that is handling this command.
4846 * @return Exit code of the command.
4847 */
4848 @BinderThread
4849 @ShellCommandResult
4850 private int handleShellCommandListInputMethods(@NonNull ShellCommand shellCommand) {
4851 boolean all = false;
4852 boolean brief = false;
4853 while (true) {
4854 final String nextOption = shellCommand.getNextOption();
4855 if (nextOption == null) {
4856 break;
4857 }
4858 switch (nextOption) {
4859 case "-a":
4860 all = true;
4861 break;
4862 case "-s":
4863 brief = true;
4864 break;
4865 }
4866 }
4867 final List<InputMethodInfo> methods = all ?
4868 getInputMethodList() : getEnabledInputMethodList();
4869 final PrintWriter pr = shellCommand.getOutPrintWriter();
4870 final Printer printer = x -> pr.println(x);
4871 final int N = methods.size();
4872 for (int i = 0; i < N; ++i) {
4873 if (brief) {
4874 pr.println(methods.get(i).getId());
4875 } else {
4876 pr.print(methods.get(i).getId()); pr.println(":");
4877 methods.get(i).dump(printer, " ");
4878 }
4879 }
4880 return ShellCommandResult.SUCCESS;
4881 }
4882
4883 /**
4884 * Handles {@code adb shell ime enable} and {@code adb shell ime disable}.
4885 * @param shellCommand {@link ShellCommand} object that is handling this command.
4886 * @param enabled {@code true} if the command was {@code adb shell ime enable}.
4887 * @return Exit code of the command.
4888 */
4889 @BinderThread
4890 @ShellCommandResult
4891 @RequiresPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
4892 private int handleShellCommandEnableDisableInputMethod(
4893 @NonNull ShellCommand shellCommand, boolean enabled) {
4894 if (!calledFromValidUser()) {
4895 shellCommand.getErrPrintWriter().print(
4896 "Must be called from the foreground user or with INTERACT_ACROSS_USERS_FULL");
4897 return ShellCommandResult.FAILURE;
4898 }
4899 final String id = shellCommand.getNextArgRequired();
4900
4901 final boolean previouslyEnabled;
4902 synchronized (mMethodMap) {
4903 if (mContext.checkCallingOrSelfPermission(
4904 android.Manifest.permission.WRITE_SECURE_SETTINGS)
4905 != PackageManager.PERMISSION_GRANTED) {
4906 shellCommand.getErrPrintWriter().print(
4907 "Caller must have WRITE_SECURE_SETTINGS permission");
4908 throw new SecurityException(
4909 "Requires permission "
4910 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
4911 }
4912
4913 final long ident = Binder.clearCallingIdentity();
4914 try {
4915 previouslyEnabled = setInputMethodEnabledLocked(id, enabled);
4916 } finally {
4917 Binder.restoreCallingIdentity(ident);
4918 }
4919 }
4920 final PrintWriter pr = shellCommand.getOutPrintWriter();
4921 pr.print("Input method ");
4922 pr.print(id);
4923 pr.print(": ");
4924 pr.print((enabled == previouslyEnabled) ? "already " : "now ");
4925 pr.println(enabled ? "enabled" : "disabled");
4926 return ShellCommandResult.SUCCESS;
4927 }
4928
4929 /**
4930 * Handles {@code adb shell ime set}.
4931 * @param shellCommand {@link ShellCommand} object that is handling this command.
4932 * @return Exit code of the command.
4933 */
4934 @BinderThread
4935 @ShellCommandResult
4936 private int handleShellCommandSetInputMethod(@NonNull ShellCommand shellCommand) {
4937 final String id = shellCommand.getNextArgRequired();
4938 setInputMethod(null, id);
4939 final PrintWriter pr = shellCommand.getOutPrintWriter();
4940 pr.print("Input method ");
4941 pr.print(id);
4942 pr.println(" selected");
4943 return ShellCommandResult.SUCCESS;
4944 }
Yohei Yukawacc97ebd2017-12-11 17:54:43 -08004945
4946 /**
4947 * Handles {@code adb shell ime reset-ime}.
4948 * @param shellCommand {@link ShellCommand} object that is handling this command.
4949 * @return Exit code of the command.
4950 */
4951 @BinderThread
4952 @ShellCommandResult
4953 @RequiresPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
4954 private int handleShellCommandResetInputMethod(@NonNull ShellCommand shellCommand) {
4955 if (!calledFromValidUser()) {
4956 shellCommand.getErrPrintWriter().print(
4957 "Must be called from the foreground user or with INTERACT_ACROSS_USERS_FULL");
4958 return ShellCommandResult.FAILURE;
4959 }
4960 synchronized (mMethodMap) {
4961 if (mContext.checkCallingOrSelfPermission(
4962 android.Manifest.permission.WRITE_SECURE_SETTINGS)
4963 != PackageManager.PERMISSION_GRANTED) {
4964 shellCommand.getErrPrintWriter().print(
4965 "Caller must have WRITE_SECURE_SETTINGS permission");
4966 throw new SecurityException(
4967 "Requires permission "
4968 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
4969 }
4970 final String nextIme;
4971 final List<InputMethodInfo> nextEnabledImes;
4972 final long ident = Binder.clearCallingIdentity();
4973 try {
4974 synchronized (mMethodMap) {
4975 hideCurrentInputLocked(0, null);
4976 unbindCurrentMethodLocked(false);
4977 // Reset the current IME
4978 resetSelectedInputMethodAndSubtypeLocked(null);
4979 // Also reset the settings of the current IME
4980 mSettings.putSelectedInputMethod(null);
4981 // Disable all enabled IMEs.
4982 {
4983 final ArrayList<InputMethodInfo> enabledImes =
4984 mSettings.getEnabledInputMethodListLocked();
4985 final int N = enabledImes.size();
4986 for (int i = 0; i < N; ++i) {
4987 setInputMethodEnabledLocked(enabledImes.get(i).getId(), false);
4988 }
4989 }
4990 // Re-enable with default enabled IMEs.
4991 {
4992 final ArrayList<InputMethodInfo> defaultEnabledIme =
4993 InputMethodUtils.getDefaultEnabledImes(mContext, mMethodList);
4994 final int N = defaultEnabledIme.size();
4995 for (int i = 0; i < N; ++i) {
4996 setInputMethodEnabledLocked(defaultEnabledIme.get(i).getId(), true);
4997 }
4998 }
4999 updateInputMethodsFromSettingsLocked(true /* enabledMayChange */);
5000 InputMethodUtils.setNonSelectedSystemImesDisabledUntilUsed(mIPackageManager,
5001 mSettings.getEnabledInputMethodListLocked(),
5002 mSettings.getCurrentUserId(),
5003 mContext.getBasePackageName());
5004 nextIme = mSettings.getSelectedInputMethod();
5005 nextEnabledImes = getEnabledInputMethodList();
5006 }
5007 } finally {
5008 Binder.restoreCallingIdentity(ident);
5009 }
5010 final PrintWriter pr = shellCommand.getOutPrintWriter();
5011 pr.println("Reset current and enabled IMEs");
5012 pr.println("Newly selected IME:");
5013 pr.print(" "); pr.println(nextIme);
5014 pr.println("Newly enabled IMEs:");
5015 {
5016 final int N = nextEnabledImes.size();
5017 for (int i = 0; i < N; ++i) {
5018 pr.print(" ");
5019 pr.println(nextEnabledImes.get(i).getId());
5020 }
5021 }
5022 return ShellCommandResult.SUCCESS;
5023 }
5024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005025}