blob: f678eed8305ce3eacf4a2ce1b05dc6d0b7b8c4d6 [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;
Joe Onorato857fd9b2011-01-27 15:08:35 -080095import android.inputmethodservice.InputMethodService;
Michael Wright7b5a96b2014-08-09 19:28:42 -070096import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import android.os.Binder;
Chris Wren1ce4b6d2015-06-11 10:19:43 -040098import android.os.Bundle;
Seigo Nonakae27dc2b2015-08-14 18:21:27 -070099import android.os.Debug;
satoke7c6998e2011-06-03 17:57:59 +0900100import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import android.os.Handler;
102import android.os.IBinder;
103import android.os.IInterface;
104import android.os.Message;
Yohei Yukawa23cbe852016-05-17 16:42:58 -0700105import android.os.LocaleList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import android.os.Parcel;
Yohei Yukawa6ab1a822015-08-25 14:01:28 -0700107import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import android.os.RemoteException;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800109import android.os.ResultReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import android.os.ServiceManager;
Yohei Yukawa926488d2017-12-11 17:24:55 -0800111import android.os.ShellCallback;
112import android.os.ShellCommand;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import android.os.SystemClock;
Tarandeep Singh75a92392018-01-12 14:58:59 -0800114import android.os.SystemProperties;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +0900115import android.os.UserHandle;
Amith Yamasani734983f2014-03-04 16:48:05 -0800116import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117import android.provider.Settings;
Tarandeep Singh89a6c482017-11-21 14:26:11 -0800118import android.service.vr.IVrManager;
119import android.service.vr.IVrStateCallbacks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120import android.text.TextUtils;
satokf9f01002011-05-19 21:31:50 +0900121import android.text.style.SuggestionSpan;
Christopher Tate7b9a28c2015-03-18 13:06:16 -0700122import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700123import android.util.AtomicFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124import android.util.EventLog;
satokf9f01002011-05-19 21:31:50 +0900125import android.util.LruCache;
satokab751aa2010-09-14 19:17:36 +0900126import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127import android.util.PrintWriterPrinter;
128import android.util.Printer;
satoke7c6998e2011-06-03 17:57:59 +0900129import android.util.Slog;
130import android.util.Xml;
Tadashi G. Takaokad130b802014-08-01 14:05:47 +0900131import android.view.ContextThemeWrapper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132import android.view.IWindowManager;
Jeff Brownc28867a2013-03-26 15:42:39 -0700133import android.view.InputChannel;
Ken Wakasa05dbb652011-08-22 15:22:43 +0900134import android.view.LayoutInflater;
135import android.view.View;
136import android.view.ViewGroup;
Wale Ogunwale3a931692016-11-02 16:49:48 -0700137import android.view.Window;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138import android.view.WindowManager;
satokab751aa2010-09-14 19:17:36 +0900139import android.view.inputmethod.EditorInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140import android.view.inputmethod.InputBinding;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800141import android.view.inputmethod.InputConnection;
Yohei Yukawa19a80a12016-03-14 22:57:37 -0700142import android.view.inputmethod.InputConnectionInspector;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143import android.view.inputmethod.InputMethod;
144import android.view.inputmethod.InputMethodInfo;
145import android.view.inputmethod.InputMethodManager;
Yohei Yukawafa6e0a82015-07-23 15:08:59 -0700146import android.view.inputmethod.InputMethodManagerInternal;
satokab751aa2010-09-14 19:17:36 +0900147import android.view.inputmethod.InputMethodSubtype;
Yohei Yukawa443c2ba2014-09-10 14:10:30 +0900148import android.view.inputmethod.InputMethodSubtype.InputMethodSubtypeBuilder;
Ken Wakasa05dbb652011-08-22 15:22:43 +0900149import android.widget.ArrayAdapter;
satok01038492012-04-09 21:08:27 +0900150import android.widget.CompoundButton;
151import android.widget.CompoundButton.OnCheckedChangeListener;
Ken Wakasa05dbb652011-08-22 15:22:43 +0900152import android.widget.RadioButton;
satok01038492012-04-09 21:08:27 +0900153import android.widget.Switch;
Ken Wakasa05dbb652011-08-22 15:22:43 +0900154import android.widget.TextView;
Yohei Yukawaebda7d72016-04-02 17:39:23 -0700155import android.widget.Toast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156
Adrian Roose99bc052017-11-20 17:55:31 +0100157import com.android.server.wm.WindowManagerInternal;
158
satoke7c6998e2011-06-03 17:57:59 +0900159import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160import java.io.FileDescriptor;
satoke7c6998e2011-06-03 17:57:59 +0900161import java.io.FileInputStream;
162import java.io.FileOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163import java.io.IOException;
164import java.io.PrintWriter;
Yohei Yukawafa0e47e2016-04-05 09:55:56 -0700165import java.lang.annotation.Retention;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100166import java.nio.charset.StandardCharsets;
Yohei Yukawa25e08132016-06-22 16:31:41 -0700167import java.security.InvalidParameterException;
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800168import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169import java.util.ArrayList;
satok688bd472012-02-09 20:09:17 +0900170import java.util.Collections;
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800171import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172import java.util.HashMap;
173import java.util.List;
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800174import java.util.Locale;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800175import java.util.WeakHashMap;
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800176import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177
178/**
179 * This class provides a system service that manages input methods.
180 */
181public class InputMethodManagerService extends IInputMethodManager.Stub
182 implements ServiceConnection, Handler.Callback {
183 static final boolean DEBUG = false;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700184 static final String TAG = "InputMethodManagerService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185
Yohei Yukawa926488d2017-12-11 17:24:55 -0800186 @Retention(SOURCE)
187 @IntDef({ShellCommandResult.SUCCESS, ShellCommandResult.FAILURE})
188 private @interface ShellCommandResult {
189 int SUCCESS = 0;
190 int FAILURE = -1;
191 }
192
Seigo Nonakad4474cb2015-05-04 16:53:24 -0700193 static final int MSG_SHOW_IM_SUBTYPE_PICKER = 1;
194 static final int MSG_SHOW_IM_SUBTYPE_ENABLER = 2;
195 static final int MSG_SHOW_IM_CONFIG = 3;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 static final int MSG_UNBIND_INPUT = 1000;
198 static final int MSG_BIND_INPUT = 1010;
199 static final int MSG_SHOW_SOFT_INPUT = 1020;
200 static final int MSG_HIDE_SOFT_INPUT = 1030;
Jorim Jaggi3c5d0f12016-05-24 19:04:30 -0700201 static final int MSG_HIDE_CURRENT_INPUT_METHOD = 1035;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 static final int MSG_ATTACH_TOKEN = 1040;
203 static final int MSG_CREATE_SESSION = 1050;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 static final int MSG_START_INPUT = 2000;
Tarandeep Singh89a6c482017-11-21 14:26:11 -0800206 static final int MSG_START_VR_INPUT = 2010;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800207
Yohei Yukawa33e81792015-11-17 21:14:42 -0800208 static final int MSG_UNBIND_CLIENT = 3000;
209 static final int MSG_BIND_CLIENT = 3010;
Dianne Hackborna6e41342012-05-22 16:30:34 -0700210 static final int MSG_SET_ACTIVE = 3020;
Yohei Yukawafa6e0a82015-07-23 15:08:59 -0700211 static final int MSG_SET_INTERACTIVE = 3030;
Yohei Yukawa3d1e8122014-06-06 19:12:47 +0900212 static final int MSG_SET_USER_ACTION_NOTIFICATION_SEQUENCE_NUMBER = 3040;
Yohei Yukawa2bc66172017-02-08 11:13:25 -0800213 static final int MSG_REPORT_FULLSCREEN_MODE = 3045;
Yohei Yukawaae61f712015-12-09 13:00:10 -0800214 static final int MSG_SWITCH_IME = 3050;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800215
satok01038492012-04-09 21:08:27 +0900216 static final int MSG_HARD_KEYBOARD_SWITCH_CHANGED = 4000;
217
Fyodor Kupolov7877b8a2016-06-29 14:39:19 -0700218 static final int MSG_SYSTEM_UNLOCK_USER = 5000;
219
Satoshi Kataokabcacc322013-10-21 17:57:27 -0700220 static final long TIME_TO_RECONNECT = 3 * 1000;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800221
satokf9f01002011-05-19 21:31:50 +0900222 static final int SECURE_SUGGESTION_SPANS_MAX_SIZE = 20;
223
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +0900224 private static final int NOT_A_SUBTYPE_ID = InputMethodUtils.NOT_A_SUBTYPE_ID;
satokb6359412011-06-28 17:47:41 +0900225 private static final String TAG_TRY_SUPPRESSING_IME_SWITCHER = "TrySuppressingImeSwitcher";
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +0900226
Yohei Yukawaa67a4592017-03-30 15:57:02 -0700227 /**
228 * Binding flags for establishing connection to the {@link InputMethodService}.
229 */
230 private static final int IME_CONNECTION_BIND_FLAGS =
231 Context.BIND_AUTO_CREATE
232 | Context.BIND_NOT_VISIBLE
233 | Context.BIND_NOT_FOREGROUND
Yohei Yukawaad78a612017-08-04 01:57:27 -0700234 | Context.BIND_IMPORTANT_BACKGROUND;
Yohei Yukawaa67a4592017-03-30 15:57:02 -0700235
236 /**
237 * Binding flags used only while the {@link InputMethodService} is showing window.
238 */
239 private static final int IME_VISIBLE_BIND_FLAGS =
240 Context.BIND_AUTO_CREATE
241 | Context.BIND_TREAT_LIKE_ACTIVITY
Yohei Yukawaad78a612017-08-04 01:57:27 -0700242 | Context.BIND_FOREGROUND_SERVICE
243 | Context.BIND_SHOWING_UI;
Yohei Yukawaa67a4592017-03-30 15:57:02 -0700244
Yohei Yukawafa0e47e2016-04-05 09:55:56 -0700245 @Retention(SOURCE)
246 @IntDef({HardKeyboardBehavior.WIRELESS_AFFORDANCE, HardKeyboardBehavior.WIRED_AFFORDANCE})
247 private @interface HardKeyboardBehavior {
248 int WIRELESS_AFFORDANCE = 0;
249 int WIRED_AFFORDANCE = 1;
250 }
satok4e4569d2010-11-19 18:45:53 +0900251
Tadashi G. Takaoka01065a52017-07-19 14:10:24 +0900252 /**
253 * A protected broadcast intent action for internal use for {@link PendingIntent} in
254 * the notification.
255 */
256 private static final String ACTION_SHOW_INPUT_METHOD_PICKER =
257 "com.android.server.InputMethodManagerService.SHOW_INPUT_METHOD_PICKER";
258
Tarandeep Singh75a92392018-01-12 14:58:59 -0800259 /**
260 * Debug flag for overriding runtime {@link SystemProperties}.
261 */
262 @AnyThread
263 private static final class DebugFlag {
264 private static final Object LOCK = new Object();
265 private final String mKey;
Tarandeep Singh9df4ad12018-04-03 13:35:50 -0700266 private final boolean mDefaultValue;
Tarandeep Singh75a92392018-01-12 14:58:59 -0800267 @GuardedBy("LOCK")
268 private boolean mValue;
269
Tarandeep Singh1c042c52018-03-29 17:04:44 -0700270 public DebugFlag(String key, boolean defaultValue) {
Tarandeep Singh75a92392018-01-12 14:58:59 -0800271 mKey = key;
Tarandeep Singh9df4ad12018-04-03 13:35:50 -0700272 mDefaultValue = defaultValue;
Tarandeep Singh1c042c52018-03-29 17:04:44 -0700273 mValue = SystemProperties.getBoolean(key, defaultValue);
Tarandeep Singh75a92392018-01-12 14:58:59 -0800274 }
275
276 void refresh() {
277 synchronized (LOCK) {
Tarandeep Singh9df4ad12018-04-03 13:35:50 -0700278 mValue = SystemProperties.getBoolean(mKey, mDefaultValue);
Tarandeep Singh75a92392018-01-12 14:58:59 -0800279 }
280 }
281
282 boolean value() {
283 synchronized (LOCK) {
284 return mValue;
285 }
286 }
287 }
288
289 /**
290 * Debug flags that can be overridden using "adb shell setprop <key>"
291 * Note: These flags are cached. To refresh, run "adb shell ime refresh_debug_properties".
292 */
293 private static final class DebugFlags {
294 static final DebugFlag FLAG_OPTIMIZE_START_INPUT =
Tarandeep Singh1c042c52018-03-29 17:04:44 -0700295 new DebugFlag("debug.optimize_startinput", false);
Tarandeep Singh75a92392018-01-12 14:58:59 -0800296 }
297
298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299 final Context mContext;
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -0800300 final Resources mRes;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301 final Handler mHandler;
satokd87c2592010-09-29 11:52:06 +0900302 final InputMethodSettings mSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303 final SettingsObserver mSettingsObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 final IWindowManager mIWindowManager;
Seigo Nonaka7309b122015-08-17 18:34:13 -0700305 final WindowManagerInternal mWindowManagerInternal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800306 final HandlerCaller mCaller;
Dianne Hackborn119bbc32013-03-22 17:27:25 -0700307 final boolean mHasFeature;
Satoshi Kataoka5ade83b2012-09-26 22:59:41 +0900308 private InputMethodFileManager mFileManager;
satok01038492012-04-09 21:08:27 +0900309 private final HardKeyboardListener mHardKeyboardListener;
Yohei Yukawae63b5fa2014-09-19 13:14:55 +0900310 private final AppOpsManager mAppOpsManager;
Yohei Yukawaed4952a2016-02-17 07:57:25 -0800311 private final UserManager mUserManager;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313 // All known input methods. mMethodMap also serves as the global
314 // lock for this class.
Yohei Yukawab0377bb2015-08-10 21:06:30 -0700315 final ArrayList<InputMethodInfo> mMethodList = new ArrayList<>();
316 final HashMap<String, InputMethodInfo> mMethodMap = new HashMap<>();
satokf9f01002011-05-19 21:31:50 +0900317 private final LruCache<SuggestionSpan, InputMethodInfo> mSecureSuggestionSpans =
Yohei Yukawab0377bb2015-08-10 21:06:30 -0700318 new LruCache<>(SECURE_SUGGESTION_SPANS_MAX_SIZE);
Satoshi Kataokad787f692013-10-26 04:44:21 +0900319 private final InputMethodSubtypeSwitchingController mSwitchingController;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800320
Yohei Yukawae0733062017-02-09 22:49:35 -0800321 /**
322 * Tracks how many times {@link #mMethodMap} was updated.
323 */
324 @GuardedBy("mMethodMap")
325 private int mMethodMapUpdateCount = 0;
326
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -0700327 // Used to bring IME service up to visible adjustment while it is being shown.
328 final ServiceConnection mVisibleConnection = new ServiceConnection() {
329 @Override public void onServiceConnected(ComponentName name, IBinder service) {
330 }
331
332 @Override public void onServiceDisconnected(ComponentName name) {
333 }
334 };
335 boolean mVisibleBound = false;
336
satok7cfc0ed2011-06-20 21:29:36 +0900337 // Ongoing notification
Dianne Hackborn661cd522011-08-22 00:26:20 -0700338 private NotificationManager mNotificationManager;
339 private KeyguardManager mKeyguardManager;
Griff Hazen6090c262016-03-25 08:11:24 -0700340 private @Nullable StatusBarManagerService mStatusBar;
Chris Wren1ce4b6d2015-06-11 10:19:43 -0400341 private Notification.Builder mImeSwitcherNotification;
Dianne Hackborn661cd522011-08-22 00:26:20 -0700342 private PendingIntent mImeSwitchPendingIntent;
satokb858c732011-07-22 19:54:34 +0900343 private boolean mShowOngoingImeSwitcherForPhones;
satok7cfc0ed2011-06-20 21:29:36 +0900344 private boolean mNotificationShown;
345
Tadashi G. Takaoka8c6d4772014-08-05 15:29:17 +0900346 static class SessionState {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347 final ClientState client;
348 final IInputMethod method;
Jeff Brownc28867a2013-03-26 15:42:39 -0700349
350 IInputMethodSession session;
351 InputChannel channel;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 @Override
354 public String toString() {
355 return "SessionState{uid " + client.uid + " pid " + client.pid
356 + " method " + Integer.toHexString(
357 System.identityHashCode(method))
358 + " session " + Integer.toHexString(
359 System.identityHashCode(session))
Jeff Brownc28867a2013-03-26 15:42:39 -0700360 + " channel " + channel
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 + "}";
362 }
363
364 SessionState(ClientState _client, IInputMethod _method,
Jeff Brownc28867a2013-03-26 15:42:39 -0700365 IInputMethodSession _session, InputChannel _channel) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366 client = _client;
367 method = _method;
368 session = _session;
Jeff Brownc28867a2013-03-26 15:42:39 -0700369 channel = _channel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 }
371 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800372
Tarandeep Singh89a6c482017-11-21 14:26:11 -0800373 /**
374 * VR state callback.
375 * Listens for when VR mode finishes.
376 */
377 private final IVrStateCallbacks mVrStateCallbacks = new IVrStateCallbacks.Stub() {
378 @Override
379 public void onVrStateChanged(boolean enabled) {
380 if (!enabled) {
381 restoreNonVrImeFromSettingsNoCheck();
382 }
383 }
384 };
385
386 private void restoreNonVrImeFromSettingsNoCheck() {
387 // switch back to non-VR InputMethod from settings.
388 synchronized (mMethodMap) {
389 final String lastInputId = mSettings.getSelectedInputMethod();
390 setInputMethodLocked(lastInputId,
391 mSettings.getSelectedInputMethodSubtypeId(lastInputId));
392 }
393 }
394
Jeff Brownc28867a2013-03-26 15:42:39 -0700395 static final class ClientState {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 final IInputMethodClient client;
397 final IInputContext inputContext;
398 final int uid;
399 final int pid;
400 final InputBinding binding;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800402 boolean sessionRequested;
403 SessionState curSession;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 @Override
406 public String toString() {
407 return "ClientState{" + Integer.toHexString(
408 System.identityHashCode(this)) + " uid " + uid
409 + " pid " + pid + "}";
410 }
411
412 ClientState(IInputMethodClient _client, IInputContext _inputContext,
413 int _uid, int _pid) {
414 client = _client;
415 inputContext = _inputContext;
416 uid = _uid;
417 pid = _pid;
418 binding = new InputBinding(null, inputContext.asBinder(), uid, pid);
419 }
420 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800421
Yohei Yukawab0377bb2015-08-10 21:06:30 -0700422 final HashMap<IBinder, ClientState> mClients = new HashMap<>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 /**
Dianne Hackborna34f1ad2009-09-02 13:26:28 -0700425 * Set once the system is ready to run third party code.
426 */
427 boolean mSystemReady;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800428
Dianne Hackborna34f1ad2009-09-02 13:26:28 -0700429 /**
Yohei Yukawae13a20fa2015-09-30 19:11:32 -0700430 * Id obtained with {@link InputMethodInfo#getId()} for the currently selected input method.
431 * method. This is to be synchronized with the secure settings keyed with
432 * {@link Settings.Secure#DEFAULT_INPUT_METHOD}.
433 *
434 * <p>This can be transiently {@code null} when the system is re-initializing input method
435 * settings, e.g., the system locale is just changed.</p>
436 *
437 * <p>Note that {@link #mCurId} is used to track which IME is being connected to
438 * {@link InputMethodManagerService}.</p>
439 *
440 * @see #mCurId
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800441 */
Yohei Yukawae13a20fa2015-09-30 19:11:32 -0700442 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443 String mCurMethodId;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445 /**
446 * The current binding sequence number, incremented every time there is
447 * a new bind performed.
448 */
449 int mCurSeq;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 /**
452 * The client that is currently bound to an input method.
453 */
454 ClientState mCurClient;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 /**
Yohei Yukawae39d4ed2015-11-19 03:38:49 -0800457 * The last window token that we confirmed to be focused. This is always updated upon reports
458 * from the input method client. If the window state is already changed before the report is
459 * handled, this field just keeps the last value.
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700460 */
461 IBinder mCurFocusedWindow;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800462
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700463 /**
Yohei Yukawa22a89232017-02-12 16:38:59 -0800464 * {@link WindowManager.LayoutParams#softInputMode} of {@link #mCurFocusedWindow}.
465 *
466 * @see #mCurFocusedWindow
467 */
468 int mCurFocusedWindowSoftInputMode;
469
470 /**
Tarandeep Singheb570612018-01-29 16:20:32 -0800471 * The client by which {@link #mCurFocusedWindow} was reported.
Yohei Yukawae39d4ed2015-11-19 03:38:49 -0800472 */
473 ClientState mCurFocusedWindowClient;
474
475 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 * The input context last provided by the current client.
477 */
478 IInputContext mCurInputContext;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 /**
Yohei Yukawa19a80a12016-03-14 22:57:37 -0700481 * The missing method flags for the input context last provided by the current client.
482 *
483 * @see android.view.inputmethod.InputConnectionInspector.MissingMethodFlags
484 */
485 int mCurInputContextMissingMethods;
486
487 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800488 * The attributes last provided by the current client.
489 */
490 EditorInfo mCurAttribute;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 /**
Yohei Yukawae13a20fa2015-09-30 19:11:32 -0700493 * Id obtained with {@link InputMethodInfo#getId()} for the input method that we are currently
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 * connected to or in the process of connecting to.
Yohei Yukawae13a20fa2015-09-30 19:11:32 -0700495 *
496 * <p>This can be {@code null} when no input method is connected.</p>
497 *
498 * @see #mCurMethodId
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 */
Yohei Yukawae13a20fa2015-09-30 19:11:32 -0700500 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501 String mCurId;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 /**
satokab751aa2010-09-14 19:17:36 +0900504 * The current subtype of the current input method.
505 */
506 private InputMethodSubtype mCurrentSubtype;
507
satok4e4569d2010-11-19 18:45:53 +0900508 // This list contains the pairs of InputMethodInfo and InputMethodSubtype.
satokf3db1af2010-11-23 13:34:33 +0900509 private final HashMap<InputMethodInfo, ArrayList<InputMethodSubtype>>
Yohei Yukawab0377bb2015-08-10 21:06:30 -0700510 mShortcutInputMethodsAndSubtypes = new HashMap<>();
satokab751aa2010-09-14 19:17:36 +0900511
John Spurlocke0980502013-10-25 11:59:29 -0400512 // Was the keyguard locked when this client became current?
513 private boolean mCurClientInKeyguard;
514
satokab751aa2010-09-14 19:17:36 +0900515 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800516 * Set to true if our ServiceConnection is currently actively bound to
517 * a service (whether or not we have gotten its IBinder back yet).
518 */
519 boolean mHaveConnection;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 /**
522 * Set if the client has asked for the input method to be shown.
523 */
524 boolean mShowRequested;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526 /**
527 * Set if we were explicitly told to show the input method.
528 */
529 boolean mShowExplicitlyRequested;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800531 /**
532 * Set if we were forced to be shown.
533 */
534 boolean mShowForced;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 /**
537 * Set if we last told the input method to show itself.
538 */
539 boolean mInputShown;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800541 /**
Yohei Yukawa2bc66172017-02-08 11:13:25 -0800542 * {@code true} if the current input method is in fullscreen mode.
543 */
544 boolean mInFullscreenMode;
545
546 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547 * The Intent used to connect to the current input method.
548 */
549 Intent mCurIntent;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800551 /**
552 * The token we have made for the currently active input method, to
553 * identify it in the future.
554 */
555 IBinder mCurToken;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800556
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 /**
558 * If non-null, this is the input method service we are currently connected
559 * to.
560 */
561 IInputMethod mCurMethod;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563 /**
564 * Time that we last initiated a bind to the input method, to determine
565 * if we should try to disconnect and reconnect to it.
566 */
567 long mLastBindTime;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569 /**
570 * Have we called mCurMethod.bindInput()?
571 */
572 boolean mBoundToMethod;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574 /**
575 * Currently enabled session. Only touched by service thread, not
576 * protected by a lock.
577 */
578 SessionState mEnabledSession;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580 /**
Yohei Yukawafa6e0a82015-07-23 15:08:59 -0700581 * True if the device is currently interactive with user. The value is true initially.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 */
Yohei Yukawafa6e0a82015-07-23 15:08:59 -0700583 boolean mIsInteractive = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800584
Yohei Yukawa3d1e8122014-06-06 19:12:47 +0900585 int mCurUserActionNotificationSequenceNumber = 0;
586
Joe Onorato857fd9b2011-01-27 15:08:35 -0800587 int mBackDisposition = InputMethodService.BACK_DISPOSITION_DEFAULT;
Seigo Nonakad9eb9112015-05-26 20:54:43 +0900588
589 /**
590 * A set of status bits regarding the active IME.
591 *
592 * <p>This value is a combination of following two bits:</p>
593 * <dl>
594 * <dt>{@link InputMethodService#IME_ACTIVE}</dt>
595 * <dd>
596 * If this bit is ON, connected IME is ready to accept touch/key events.
597 * </dd>
598 * <dt>{@link InputMethodService#IME_VISIBLE}</dt>
599 * <dd>
600 * If this bit is ON, some of IME view, e.g. software input, candidate view, is visible.
601 * </dd>
602 * </dl>
603 * <em>Do not update this value outside of setImeWindowStatus.</em>
604 */
Joe Onorato857fd9b2011-01-27 15:08:35 -0800605 int mImeWindowVis;
606
Ken Wakasa05dbb652011-08-22 15:22:43 +0900607 private AlertDialog.Builder mDialogBuilder;
608 private AlertDialog mSwitchingDialog;
Wale Ogunwale3a931692016-11-02 16:49:48 -0700609 private IBinder mSwitchingDialogToken = new Binder();
satok01038492012-04-09 21:08:27 +0900610 private View mSwitchingDialogTitleView;
Yohei Yukawaebda7d72016-04-02 17:39:23 -0700611 private Toast mSubtypeSwitchedByShortCutToast;
Ken Wakasa05dbb652011-08-22 15:22:43 +0900612 private InputMethodInfo[] mIms;
613 private int[] mSubtypeIds;
Yohei Yukawae985c242016-02-24 18:27:04 -0800614 private LocaleList mLastSystemLocales;
Michael Wright7b5a96b2014-08-09 19:28:42 -0700615 private boolean mShowImeWithHardKeyboard;
Anna Galusza9b278112016-01-04 11:37:37 -0800616 private boolean mAccessibilityRequestingNoSoftKeyboard;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +0900617 private final MyPackageMonitor mMyPackageMonitor = new MyPackageMonitor();
618 private final IPackageManager mIPackageManager;
Jason Monk3e189872016-01-12 09:10:34 -0500619 private final String mSlotIme;
Yohei Yukawafa0e47e2016-04-05 09:55:56 -0700620 @HardKeyboardBehavior
621 private final int mHardKeyboardBehavior;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800622
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800623 /**
624 * Internal state snapshot when {@link #MSG_START_INPUT} message is about to be posted to the
625 * internal message queue. Any subsequent state change inside {@link InputMethodManagerService}
626 * will not affect those tasks that are already posted.
627 *
628 * <p>Posting {@link #MSG_START_INPUT} message basically means that
629 * {@link InputMethodService#doStartInput(InputConnection, EditorInfo, boolean)} will be called
630 * back in the current IME process shortly, which will also affect what the current IME starts
631 * receiving from {@link InputMethodService#getCurrentInputConnection()}. In other words, this
632 * snapshot will be taken every time when {@link InputMethodManagerService} is initiating a new
633 * logical input session between the client application and the current IME.</p>
634 *
635 * <p>Be careful to not keep strong references to this object forever, which can prevent
636 * {@link StartInputInfo#mImeToken} and {@link StartInputInfo#mTargetWindow} from being GC-ed.
637 * </p>
638 */
639 private static class StartInputInfo {
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800640 private static final AtomicInteger sSequenceNumber = new AtomicInteger(0);
641
642 final int mSequenceNumber;
643 final long mTimestamp;
644 final long mWallTime;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800645 @NonNull
646 final IBinder mImeToken;
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800647 @NonNull
648 final String mImeId;
649 // @InputMethodClient.StartInputReason
650 final int mStartInputReason;
651 final boolean mRestarting;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800652 @Nullable
653 final IBinder mTargetWindow;
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800654 @NonNull
655 final EditorInfo mEditorInfo;
656 final int mTargetWindowSoftInputMode;
657 final int mClientBindSequenceNumber;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800658
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800659 StartInputInfo(@NonNull IBinder imeToken, @NonNull String imeId,
660 /* @InputMethodClient.StartInputReason */ int startInputReason, boolean restarting,
661 @Nullable IBinder targetWindow, @NonNull EditorInfo editorInfo,
662 int targetWindowSoftInputMode, int clientBindSequenceNumber) {
663 mSequenceNumber = sSequenceNumber.getAndIncrement();
664 mTimestamp = SystemClock.uptimeMillis();
665 mWallTime = System.currentTimeMillis();
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800666 mImeToken = imeToken;
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800667 mImeId = imeId;
668 mStartInputReason = startInputReason;
669 mRestarting = restarting;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800670 mTargetWindow = targetWindow;
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800671 mEditorInfo = editorInfo;
672 mTargetWindowSoftInputMode = targetWindowSoftInputMode;
673 mClientBindSequenceNumber = clientBindSequenceNumber;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800674 }
675 }
676
Yohei Yukawab37d8bd2017-02-13 18:29:05 -0800677 @GuardedBy("mMethodMap")
678 private final WeakHashMap<IBinder, StartInputInfo> mStartInputMap = new WeakHashMap<>();
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800679
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800680 /**
681 * A ring buffer to store the history of {@link StartInputInfo}.
682 */
683 private static final class StartInputHistory {
684 /**
685 * Entry size for non low-RAM devices.
686 *
687 * <p>TODO: Consider to follow what other system services have been doing to manage
688 * constants (e.g. {@link android.provider.Settings.Global#ACTIVITY_MANAGER_CONSTANTS}).</p>
689 */
690 private final static int ENTRY_SIZE_FOR_HIGH_RAM_DEVICE = 16;
691
692 /**
693 * Entry size for non low-RAM devices.
694 *
695 * <p>TODO: Consider to follow what other system services have been doing to manage
696 * constants (e.g. {@link android.provider.Settings.Global#ACTIVITY_MANAGER_CONSTANTS}).</p>
697 */
698 private final static int ENTRY_SIZE_FOR_LOW_RAM_DEVICE = 5;
699
700 private static int getEntrySize() {
701 if (ActivityManager.isLowRamDeviceStatic()) {
702 return ENTRY_SIZE_FOR_LOW_RAM_DEVICE;
703 } else {
704 return ENTRY_SIZE_FOR_HIGH_RAM_DEVICE;
705 }
706 }
707
708 /**
709 * Backing store for the ring bugger.
710 */
711 private final Entry[] mEntries = new Entry[getEntrySize()];
712
713 /**
714 * An index of {@link #mEntries}, to which next {@link #addEntry(StartInputInfo)} should
715 * write.
716 */
717 private int mNextIndex = 0;
718
719 /**
720 * Recyclable entry to store the information in {@link StartInputInfo}.
721 */
722 private static final class Entry {
723 int mSequenceNumber;
724 long mTimestamp;
725 long mWallTime;
726 @NonNull
727 String mImeTokenString;
728 @NonNull
729 String mImeId;
730 /* @InputMethodClient.StartInputReason */
731 int mStartInputReason;
732 boolean mRestarting;
733 @NonNull
734 String mTargetWindowString;
735 @NonNull
736 EditorInfo mEditorInfo;
737 int mTargetWindowSoftInputMode;
738 int mClientBindSequenceNumber;
739
740 Entry(@NonNull StartInputInfo original) {
741 set(original);
742 }
743
744 void set(@NonNull StartInputInfo original) {
745 mSequenceNumber = original.mSequenceNumber;
746 mTimestamp = original.mTimestamp;
747 mWallTime = original.mWallTime;
748 // Intentionally convert to String so as not to keep a strong reference to a Binder
749 // object.
750 mImeTokenString = String.valueOf(original.mImeToken);
751 mImeId = original.mImeId;
752 mStartInputReason = original.mStartInputReason;
753 mRestarting = original.mRestarting;
754 // Intentionally convert to String so as not to keep a strong reference to a Binder
755 // object.
756 mTargetWindowString = String.valueOf(original.mTargetWindow);
757 mEditorInfo = original.mEditorInfo;
758 mTargetWindowSoftInputMode = original.mTargetWindowSoftInputMode;
759 mClientBindSequenceNumber = original.mClientBindSequenceNumber;
760 }
761 }
762
763 /**
764 * Add a new entry and discard the oldest entry as needed.
765 * @param info {@lin StartInputInfo} to be added.
766 */
767 void addEntry(@NonNull StartInputInfo info) {
768 final int index = mNextIndex;
769 if (mEntries[index] == null) {
770 mEntries[index] = new Entry(info);
771 } else {
772 mEntries[index].set(info);
773 }
774 mNextIndex = (mNextIndex + 1) % mEntries.length;
775 }
776
777 void dump(@NonNull PrintWriter pw, @NonNull String prefix) {
778 final SimpleDateFormat dataFormat =
779 new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US);
780
781 for (int i = 0; i < mEntries.length; ++i) {
782 final Entry entry = mEntries[(i + mNextIndex) % mEntries.length];
783 if (entry == null) {
784 continue;
785 }
786 pw.print(prefix);
787 pw.println("StartInput #" + entry.mSequenceNumber + ":");
788
789 pw.print(prefix);
790 pw.println(" time=" + dataFormat.format(new Date(entry.mWallTime))
791 + " (timestamp=" + entry.mTimestamp + ")"
792 + " reason="
793 + InputMethodClient.getStartInputReason(entry.mStartInputReason)
794 + " restarting=" + entry.mRestarting);
795
796 pw.print(prefix);
797 pw.println(" imeToken=" + entry.mImeTokenString + " [" + entry.mImeId + "]");
798
799 pw.print(prefix);
800 pw.println(" targetWin=" + entry.mTargetWindowString
801 + " [" + entry.mEditorInfo.packageName + "]"
802 + " clientBindSeq=" + entry.mClientBindSequenceNumber);
803
804 pw.print(prefix);
805 pw.println(" softInputMode=" + InputMethodClient.softInputModeToString(
806 entry.mTargetWindowSoftInputMode));
807
808 pw.print(prefix);
809 pw.println(" inputType=0x" + Integer.toHexString(entry.mEditorInfo.inputType)
810 + " imeOptions=0x" + Integer.toHexString(entry.mEditorInfo.imeOptions)
811 + " fieldId=0x" + Integer.toHexString(entry.mEditorInfo.fieldId)
812 + " fieldName=" + entry.mEditorInfo.fieldName
813 + " actionId=" + entry.mEditorInfo.actionId
814 + " actionLabel=" + entry.mEditorInfo.actionLabel);
815 }
816 }
817 }
818
819 @GuardedBy("mMethodMap")
820 @NonNull
821 private final StartInputHistory mStartInputHistory = new StartInputHistory();
822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 class SettingsObserver extends ContentObserver {
Yohei Yukawa81482972015-06-04 00:58:59 -0700824 int mUserId;
825 boolean mRegistered = false;
Yohei Yukawa7b574cb2016-03-16 17:22:22 -0700826 @NonNull
Dianne Hackbornfd7aded2013-01-22 17:10:23 -0800827 String mLastEnabled = "";
828
Yohei Yukawa81482972015-06-04 00:58:59 -0700829 /**
830 * <em>This constructor must be called within the lock.</em>
831 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 SettingsObserver(Handler handler) {
833 super(handler);
Yohei Yukawa81482972015-06-04 00:58:59 -0700834 }
835
Yohei Yukawa7b18aec2016-03-07 13:04:32 -0800836 public void registerContentObserverLocked(@UserIdInt int userId) {
Yohei Yukawa81482972015-06-04 00:58:59 -0700837 if (mRegistered && mUserId == userId) {
838 return;
839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 ContentResolver resolver = mContext.getContentResolver();
Yohei Yukawa81482972015-06-04 00:58:59 -0700841 if (mRegistered) {
842 mContext.getContentResolver().unregisterContentObserver(this);
843 mRegistered = false;
844 }
845 if (mUserId != userId) {
846 mLastEnabled = "";
847 mUserId = userId;
848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 resolver.registerContentObserver(Settings.Secure.getUriFor(
Yohei Yukawa81482972015-06-04 00:58:59 -0700850 Settings.Secure.DEFAULT_INPUT_METHOD), false, this, userId);
satokab751aa2010-09-14 19:17:36 +0900851 resolver.registerContentObserver(Settings.Secure.getUriFor(
Yohei Yukawa81482972015-06-04 00:58:59 -0700852 Settings.Secure.ENABLED_INPUT_METHODS), false, this, userId);
satokb6109bb2011-02-03 22:24:54 +0900853 resolver.registerContentObserver(Settings.Secure.getUriFor(
Yohei Yukawa81482972015-06-04 00:58:59 -0700854 Settings.Secure.SELECTED_INPUT_METHOD_SUBTYPE), false, this, userId);
Michael Wright7b5a96b2014-08-09 19:28:42 -0700855 resolver.registerContentObserver(Settings.Secure.getUriFor(
Yohei Yukawa81482972015-06-04 00:58:59 -0700856 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD), false, this, userId);
Anna Galusza9b278112016-01-04 11:37:37 -0800857 resolver.registerContentObserver(Settings.Secure.getUriFor(
858 Settings.Secure.ACCESSIBILITY_SOFT_KEYBOARD_MODE), false, this, userId);
Yohei Yukawa81482972015-06-04 00:58:59 -0700859 mRegistered = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800861
Michael Wright7b5a96b2014-08-09 19:28:42 -0700862 @Override public void onChange(boolean selfChange, Uri uri) {
Anna Galusza9b278112016-01-04 11:37:37 -0800863 final Uri showImeUri = Settings.Secure.getUriFor(
864 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
865 final Uri accessibilityRequestingNoImeUri = Settings.Secure.getUriFor(
866 Settings.Secure.ACCESSIBILITY_SOFT_KEYBOARD_MODE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 synchronized (mMethodMap) {
Michael Wright7b5a96b2014-08-09 19:28:42 -0700868 if (showImeUri.equals(uri)) {
869 updateKeyboardFromSettingsLocked();
Anna Galusza9b278112016-01-04 11:37:37 -0800870 } else if (accessibilityRequestingNoImeUri.equals(uri)) {
871 mAccessibilityRequestingNoSoftKeyboard = Settings.Secure.getIntForUser(
872 mContext.getContentResolver(),
873 Settings.Secure.ACCESSIBILITY_SOFT_KEYBOARD_MODE,
874 0, mUserId) == 1;
875 if (mAccessibilityRequestingNoSoftKeyboard) {
876 final boolean showRequested = mShowRequested;
877 hideCurrentInputLocked(0, null);
878 mShowRequested = showRequested;
879 } else if (mShowRequested) {
880 showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
881 }
Michael Wright7b5a96b2014-08-09 19:28:42 -0700882 } else {
883 boolean enabledChanged = false;
884 String newEnabled = mSettings.getEnabledInputMethodsStr();
885 if (!mLastEnabled.equals(newEnabled)) {
886 mLastEnabled = newEnabled;
887 enabledChanged = true;
888 }
889 updateInputMethodsFromSettingsLocked(enabledChanged);
Dianne Hackbornfd7aded2013-01-22 17:10:23 -0800890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 }
892 }
Yohei Yukawa81482972015-06-04 00:58:59 -0700893
894 @Override
895 public String toString() {
896 return "SettingsObserver{mUserId=" + mUserId + " mRegistered=" + mRegistered
897 + " mLastEnabled=" + mLastEnabled + "}";
898 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800900
Yohei Yukawa79247822017-01-23 15:26:15 -0800901 class ImmsBroadcastReceiver extends BroadcastReceiver {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +0900902 @Override
903 public void onReceive(Context context, Intent intent) {
904 final String action = intent.getAction();
Yohei Yukawafa6e0a82015-07-23 15:08:59 -0700905 if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +0900906 hideInputMethodMenu();
Yohei Yukawafa6e0a82015-07-23 15:08:59 -0700907 // No need to update mIsInteractive
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +0900908 return;
Amith Yamasani734983f2014-03-04 16:48:05 -0800909 } else if (Intent.ACTION_USER_ADDED.equals(action)
910 || Intent.ACTION_USER_REMOVED.equals(action)) {
Kenny Guy2a764942014-04-02 13:29:20 +0100911 updateCurrentProfileIds();
Amith Yamasani734983f2014-03-04 16:48:05 -0800912 return;
Yohei Yukawa79247822017-01-23 15:26:15 -0800913 } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Yohei Yukawa0d7aff82017-02-10 00:40:51 -0800914 onActionLocaleChanged();
Tadashi G. Takaoka01065a52017-07-19 14:10:24 +0900915 } else if (ACTION_SHOW_INPUT_METHOD_PICKER.equals(action)) {
916 // ACTION_SHOW_INPUT_METHOD_PICKER action is a protected-broadcast and it is
917 // guaranteed to be send only from the system, so that there is no need for extra
918 // security check such as
919 // {@link #canShowInputMethodPickerLocked(IInputMethodClient)}.
920 mHandler.obtainMessage(
921 MSG_SHOW_IM_SUBTYPE_PICKER,
922 InputMethodManager.SHOW_IM_PICKER_MODE_INCLUDE_AUXILIARY_SUBTYPES,
923 0 /* arg2 */)
924 .sendToTarget();
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +0900925 } else {
926 Slog.w(TAG, "Unexpected intent " + intent);
927 }
928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800930
Yohei Yukawa0d7aff82017-02-10 00:40:51 -0800931 /**
Tarandeep Singh89a6c482017-11-21 14:26:11 -0800932 * Start a VR InputMethod that matches IME with package name of {@param component}.
Yohei Yukawa7a46c282017-12-10 18:15:19 -0800933 * Note: This method is called from {@link android.app.VrManager}.
Tarandeep Singh89a6c482017-11-21 14:26:11 -0800934 */
935 private void startVrInputMethodNoCheck(@Nullable ComponentName component) {
936 if (component == null) {
937 // clear the current VR-only IME (if any) and restore normal IME.
938 restoreNonVrImeFromSettingsNoCheck();
939 return;
940 }
941
942 synchronized (mMethodMap) {
943 String packageName = component.getPackageName();
944 for (InputMethodInfo info : mMethodList) {
945 if (TextUtils.equals(info.getPackageName(), packageName) && info.isVrOnly()) {
946 // set this is as current inputMethod without updating settings.
Yohei Yukawa7a46c282017-12-10 18:15:19 -0800947 setInputMethodEnabledLocked(info.getId(), true);
Tarandeep Singh89a6c482017-11-21 14:26:11 -0800948 setInputMethodLocked(info.getId(), NOT_A_SUBTYPE_ID);
949 break;
950 }
951 }
952 }
953 }
954
955 /**
Yohei Yukawa0d7aff82017-02-10 00:40:51 -0800956 * Handles {@link Intent#ACTION_LOCALE_CHANGED}.
957 *
958 * <p>Note: For historical reasons, {@link Intent#ACTION_LOCALE_CHANGED} has been sent to all
959 * the users. We should ignore this event if this is about any background user's locale.</p>
960 *
961 * <p>Caution: This method must not be called when system is not ready.</p>
962 */
963 void onActionLocaleChanged() {
964 synchronized (mMethodMap) {
965 final LocaleList possibleNewLocale = mRes.getConfiguration().getLocales();
966 if (possibleNewLocale != null && possibleNewLocale.equals(mLastSystemLocales)) {
967 return;
968 }
969 buildInputMethodListLocked(true);
970 // If the locale is changed, needs to reset the default ime
971 resetDefaultImeLocked(mContext);
972 updateFromSettingsLocked(true);
973 mLastSystemLocales = possibleNewLocale;
974 }
975 }
976
Yohei Yukawac4e44912017-02-09 19:30:22 -0800977 final class MyPackageMonitor extends PackageMonitor {
978 /**
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -0800979 * Package names that are known to contain {@link InputMethodService}.
Yohei Yukawac4e44912017-02-09 19:30:22 -0800980 *
981 * <p>No need to include packages because of direct-boot unaware IMEs since we always rescan
982 * all the packages when the user is unlocked, and direct-boot awareness will not be changed
983 * dynamically unless the entire package is updated, which also always triggers package
984 * rescanning.</p>
985 */
986 @GuardedBy("mMethodMap")
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -0800987 final private ArraySet<String> mKnownImePackageNames = new ArraySet<>();
988
989 /**
990 * Packages that are appeared, disappeared, or modified for whatever reason.
991 *
992 * <p>Note: For now we intentionally use {@link ArrayList} instead of {@link ArraySet}
993 * because 1) the number of elements is almost always 1 or so, and 2) we do not care
994 * duplicate elements for our use case.</p>
995 *
996 * <p>This object must be accessed only from callback methods in {@link PackageMonitor},
997 * which should be bound to {@link #getRegisteredHandler()}.</p>
998 */
999 private final ArrayList<String> mChangedPackages = new ArrayList<>();
1000
1001 /**
1002 * {@code true} if one or more packages that contain {@link InputMethodService} appeared.
1003 *
1004 * <p>This field must be accessed only from callback methods in {@link PackageMonitor},
1005 * which should be bound to {@link #getRegisteredHandler()}.</p>
1006 */
1007 private boolean mImePackageAppeared = false;
Yohei Yukawac4e44912017-02-09 19:30:22 -08001008
1009 @GuardedBy("mMethodMap")
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08001010 void clearKnownImePackageNamesLocked() {
1011 mKnownImePackageNames.clear();
Yohei Yukawac4e44912017-02-09 19:30:22 -08001012 }
1013
1014 @GuardedBy("mMethodMap")
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08001015 final void addKnownImePackageNameLocked(@NonNull String packageName) {
1016 mKnownImePackageNames.add(packageName);
Yohei Yukawac4e44912017-02-09 19:30:22 -08001017 }
1018
Yohei Yukawa278f2ab2017-02-14 19:51:33 -08001019 @GuardedBy("mMethodMap")
1020 private boolean isChangingPackagesOfCurrentUserLocked() {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001021 final int userId = getChangingUserId();
1022 final boolean retval = userId == mSettings.getCurrentUserId();
1023 if (DEBUG) {
satok81f8b7c2012-12-04 20:42:56 +09001024 if (!retval) {
1025 Slog.d(TAG, "--- ignore this call back from a background user: " + userId);
1026 }
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001027 }
1028 return retval;
1029 }
1030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 @Override
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001032 public boolean onHandleForceStop(Intent intent, String[] packages, int uid, boolean doit) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 synchronized (mMethodMap) {
Yohei Yukawa278f2ab2017-02-14 19:51:33 -08001034 if (!isChangingPackagesOfCurrentUserLocked()) {
1035 return false;
1036 }
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001037 String curInputMethodId = mSettings.getSelectedInputMethod();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 final int N = mMethodList.size();
1039 if (curInputMethodId != null) {
1040 for (int i=0; i<N; i++) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001041 InputMethodInfo imi = mMethodList.get(i);
1042 if (imi.getId().equals(curInputMethodId)) {
1043 for (String pkg : packages) {
1044 if (imi.getPackageName().equals(pkg)) {
1045 if (!doit) {
1046 return true;
1047 }
satok723a27e2010-11-11 14:58:11 +09001048 resetSelectedInputMethodAndSubtypeLocked("");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001049 chooseNewDefaultIMELocked();
1050 return true;
1051 }
1052 }
1053 }
1054 }
1055 }
1056 }
1057 return false;
1058 }
1059
1060 @Override
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08001061 public void onBeginPackageChanges() {
1062 clearPackageChangeState();
1063 }
1064
1065 @Override
1066 public void onPackageAppeared(String packageName, int reason) {
1067 if (!mImePackageAppeared) {
1068 final PackageManager pm = mContext.getPackageManager();
1069 final List<ResolveInfo> services = pm.queryIntentServicesAsUser(
1070 new Intent(InputMethod.SERVICE_INTERFACE).setPackage(packageName),
1071 PackageManager.MATCH_DISABLED_COMPONENTS, getChangingUserId());
1072 // No need to lock this because we access it only on getRegisteredHandler().
1073 if (!services.isEmpty()) {
1074 mImePackageAppeared = true;
1075 }
1076 }
1077 // No need to lock this because we access it only on getRegisteredHandler().
1078 mChangedPackages.add(packageName);
1079 }
1080
1081 @Override
1082 public void onPackageDisappeared(String packageName, int reason) {
1083 // No need to lock this because we access it only on getRegisteredHandler().
1084 mChangedPackages.add(packageName);
1085 }
1086
1087 @Override
1088 public void onPackageModified(String packageName) {
1089 // No need to lock this because we access it only on getRegisteredHandler().
1090 mChangedPackages.add(packageName);
1091 }
1092
1093 @Override
1094 public void onPackagesSuspended(String[] packages) {
1095 // No need to lock this because we access it only on getRegisteredHandler().
1096 for (String packageName : packages) {
1097 mChangedPackages.add(packageName);
Yohei Yukawac4e44912017-02-09 19:30:22 -08001098 }
1099 }
1100
1101 @Override
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08001102 public void onPackagesUnsuspended(String[] packages) {
1103 // No need to lock this because we access it only on getRegisteredHandler().
1104 for (String packageName : packages) {
1105 mChangedPackages.add(packageName);
1106 }
1107 }
1108
1109 @Override
1110 public void onFinishPackageChanges() {
1111 onFinishPackageChangesInternal();
1112 clearPackageChangeState();
1113 }
1114
1115 private void clearPackageChangeState() {
1116 // No need to lock them because we access these fields only on getRegisteredHandler().
1117 mChangedPackages.clear();
1118 mImePackageAppeared = false;
1119 }
1120
Andreas Gampea36dc622018-02-05 17:19:22 -08001121 @GuardedBy("mMethodMap")
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08001122 private boolean shouldRebuildInputMethodListLocked() {
1123 // This method is guaranteed to be called only by getRegisteredHandler().
1124
1125 // If there is any new package that contains at least one IME, then rebuilt the list
1126 // of IMEs.
1127 if (mImePackageAppeared) {
1128 return true;
1129 }
1130
1131 // Otherwise, check if mKnownImePackageNames and mChangedPackages have any intersection.
1132 // TODO: Consider to create a utility method to do the following test. List.retainAll()
1133 // is an option, but it may still do some extra operations that we do not need here.
1134 final int N = mChangedPackages.size();
1135 for (int i = 0; i < N; ++i) {
1136 final String packageName = mChangedPackages.get(i);
1137 if (mKnownImePackageNames.contains(packageName)) {
1138 return true;
1139 }
1140 }
1141 return false;
1142 }
1143
1144 private void onFinishPackageChangesInternal() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001145 synchronized (mMethodMap) {
Yohei Yukawa278f2ab2017-02-14 19:51:33 -08001146 if (!isChangingPackagesOfCurrentUserLocked()) {
1147 return;
1148 }
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08001149 if (!shouldRebuildInputMethodListLocked()) {
1150 return;
1151 }
1152
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001153 InputMethodInfo curIm = null;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001154 String curInputMethodId = mSettings.getSelectedInputMethod();
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001155 final int N = mMethodList.size();
1156 if (curInputMethodId != null) {
1157 for (int i=0; i<N; i++) {
1158 InputMethodInfo imi = mMethodList.get(i);
satoke7c6998e2011-06-03 17:57:59 +09001159 final String imiId = imi.getId();
1160 if (imiId.equals(curInputMethodId)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001161 curIm = imi;
1162 }
satoke7c6998e2011-06-03 17:57:59 +09001163
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001164 int change = isPackageDisappearing(imi.getPackageName());
satoke7c6998e2011-06-03 17:57:59 +09001165 if (isPackageModified(imi.getPackageName())) {
1166 mFileManager.deleteAllInputMethodSubtypes(imiId);
1167 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001168 if (change == PACKAGE_TEMPORARY_CHANGE
1169 || change == PACKAGE_PERMANENT_CHANGE) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001170 Slog.i(TAG, "Input method uninstalled, disabling: "
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001171 + imi.getComponent());
1172 setInputMethodEnabledLocked(imi.getId(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 }
1174 }
1175 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001176
Yohei Yukawa94e33302016-02-12 19:37:03 -08001177 buildInputMethodListLocked(false /* resetDefaultEnabledIme */);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 boolean changed = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001180
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001181 if (curIm != null) {
Anna Galusza9b278112016-01-04 11:37:37 -08001182 int change = isPackageDisappearing(curIm.getPackageName());
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001183 if (change == PACKAGE_TEMPORARY_CHANGE
1184 || change == PACKAGE_PERMANENT_CHANGE) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001185 ServiceInfo si = null;
1186 try {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001187 si = mIPackageManager.getServiceInfo(
1188 curIm.getComponent(), 0, mSettings.getCurrentUserId());
1189 } catch (RemoteException ex) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001190 }
1191 if (si == null) {
1192 // Uh oh, current input method is no longer around!
1193 // Pick another one...
Joe Onorato8a9b2202010-02-26 18:56:32 -08001194 Slog.i(TAG, "Current input method removed: " + curInputMethodId);
Seigo Nonakad9eb9112015-05-26 20:54:43 +09001195 updateSystemUiLocked(mCurToken, 0 /* vis */, mBackDisposition);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001196 if (!chooseNewDefaultIMELocked()) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001197 changed = true;
1198 curIm = null;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001199 Slog.i(TAG, "Unsetting current input method");
satok723a27e2010-11-11 14:58:11 +09001200 resetSelectedInputMethodAndSubtypeLocked("");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001201 }
1202 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001203 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001204 }
satokab751aa2010-09-14 19:17:36 +09001205
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001206 if (curIm == null) {
1207 // We currently don't have a default input method... is
1208 // one now available?
1209 changed = chooseNewDefaultIMELocked();
Yohei Yukawa54d512c2015-05-19 22:15:02 -07001210 } else if (!changed && isPackageModified(curIm.getPackageName())) {
1211 // Even if the current input method is still available, mCurrentSubtype could
1212 // be obsolete when the package is modified in practice.
1213 changed = true;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001214 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001215
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001216 if (changed) {
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08001217 updateFromSettingsLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 }
1219 }
1220 }
1221 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001222
Jeff Brownc28867a2013-03-26 15:42:39 -07001223 private static final class MethodCallback extends IInputSessionCallback.Stub {
Jean Chalarde0d32a62011-10-20 20:36:07 +09001224 private final InputMethodManagerService mParentIMMS;
Jeff Brownc28867a2013-03-26 15:42:39 -07001225 private final IInputMethod mMethod;
1226 private final InputChannel mChannel;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001227
Jeff Brownc28867a2013-03-26 15:42:39 -07001228 MethodCallback(InputMethodManagerService imms, IInputMethod method,
1229 InputChannel channel) {
Jean Chalarde0d32a62011-10-20 20:36:07 +09001230 mParentIMMS = imms;
Jeff Brownc28867a2013-03-26 15:42:39 -07001231 mMethod = method;
1232 mChannel = channel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001234
satoke7c6998e2011-06-03 17:57:59 +09001235 @Override
Jeff Brownc28867a2013-03-26 15:42:39 -07001236 public void sessionCreated(IInputMethodSession session) {
Dianne Hackborn6b6b3fd2014-03-24 11:27:18 -07001237 long ident = Binder.clearCallingIdentity();
1238 try {
1239 mParentIMMS.onSessionCreated(mMethod, session, mChannel);
1240 } finally {
1241 Binder.restoreCallingIdentity(ident);
1242 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 }
1244 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001245
satok01038492012-04-09 21:08:27 +09001246 private class HardKeyboardListener
Seigo Nonaka7309b122015-08-17 18:34:13 -07001247 implements WindowManagerInternal.OnHardKeyboardStatusChangeListener {
satok01038492012-04-09 21:08:27 +09001248 @Override
Michael Wright7b5a96b2014-08-09 19:28:42 -07001249 public void onHardKeyboardStatusChange(boolean available) {
1250 mHandler.sendMessage(mHandler.obtainMessage(MSG_HARD_KEYBOARD_SWITCH_CHANGED,
1251 available ? 1 : 0));
satok01038492012-04-09 21:08:27 +09001252 }
1253
Michael Wright7b5a96b2014-08-09 19:28:42 -07001254 public void handleHardKeyboardStatusChange(boolean available) {
satok01038492012-04-09 21:08:27 +09001255 if (DEBUG) {
Michael Wright7b5a96b2014-08-09 19:28:42 -07001256 Slog.w(TAG, "HardKeyboardStatusChanged: available=" + available);
satok01038492012-04-09 21:08:27 +09001257 }
1258 synchronized(mMethodMap) {
1259 if (mSwitchingDialog != null && mSwitchingDialogTitleView != null
1260 && mSwitchingDialog.isShowing()) {
1261 mSwitchingDialogTitleView.findViewById(
1262 com.android.internal.R.id.hard_keyboard_section).setVisibility(
1263 available ? View.VISIBLE : View.GONE);
1264 }
1265 }
1266 }
1267 }
1268
Fyodor Kupolov1e33dc82016-01-21 12:02:58 -08001269 public static final class Lifecycle extends SystemService {
1270 private InputMethodManagerService mService;
1271
1272 public Lifecycle(Context context) {
1273 super(context);
1274 mService = new InputMethodManagerService(context);
1275 }
1276
1277 @Override
1278 public void onStart() {
1279 LocalServices.addService(InputMethodManagerInternal.class,
1280 new LocalServiceImpl(mService.mHandler));
1281 publishBinderService(Context.INPUT_METHOD_SERVICE, mService);
1282 }
1283
1284 @Override
Yohei Yukawa7b18aec2016-03-07 13:04:32 -08001285 public void onSwitchUser(@UserIdInt int userHandle) {
Fyodor Kupolov7877b8a2016-06-29 14:39:19 -07001286 // Called on ActivityManager thread.
Yohei Yukawa7b18aec2016-03-07 13:04:32 -08001287 // TODO: Dispatch this to a worker thread as needed.
1288 mService.onSwitchUser(userHandle);
1289 }
1290
1291 @Override
Fyodor Kupolov1e33dc82016-01-21 12:02:58 -08001292 public void onBootPhase(int phase) {
Fyodor Kupolov7877b8a2016-06-29 14:39:19 -07001293 // Called on ActivityManager thread.
Yohei Yukawa7b18aec2016-03-07 13:04:32 -08001294 // TODO: Dispatch this to a worker thread as needed.
Fyodor Kupolov1e33dc82016-01-21 12:02:58 -08001295 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
1296 StatusBarManagerService statusBarService = (StatusBarManagerService) ServiceManager
1297 .getService(Context.STATUS_BAR_SERVICE);
1298 mService.systemRunning(statusBarService);
1299 }
1300 }
Yohei Yukawaed4952a2016-02-17 07:57:25 -08001301
1302 @Override
Fyodor Kupolov7877b8a2016-06-29 14:39:19 -07001303 public void onUnlockUser(final @UserIdInt int userHandle) {
1304 // Called on ActivityManager thread.
1305 mService.mHandler.sendMessage(mService.mHandler.obtainMessage(MSG_SYSTEM_UNLOCK_USER,
Fyodor Kupolov0f57cce2016-09-09 10:36:30 -07001306 userHandle /* arg1 */, 0 /* arg2 */));
Yohei Yukawaed4952a2016-02-17 07:57:25 -08001307 }
1308 }
1309
Yohei Yukawa7b18aec2016-03-07 13:04:32 -08001310 void onUnlockUser(@UserIdInt int userId) {
Yohei Yukawaed4952a2016-02-17 07:57:25 -08001311 synchronized(mMethodMap) {
1312 final int currentUserId = mSettings.getCurrentUserId();
1313 if (DEBUG) {
1314 Slog.d(TAG, "onUnlockUser: userId=" + userId + " curUserId=" + currentUserId);
1315 }
1316 if (userId != currentUserId) {
1317 return;
1318 }
1319 mSettings.switchCurrentUser(currentUserId, !mSystemReady);
Yohei Yukawa79247822017-01-23 15:26:15 -08001320 if (mSystemReady) {
1321 // We need to rebuild IMEs.
1322 buildInputMethodListLocked(false /* resetDefaultEnabledIme */);
1323 updateInputMethodsFromSettingsLocked(true /* enabledChanged */);
1324 }
Yohei Yukawaed4952a2016-02-17 07:57:25 -08001325 }
Fyodor Kupolov1e33dc82016-01-21 12:02:58 -08001326 }
1327
Yohei Yukawa7b18aec2016-03-07 13:04:32 -08001328 void onSwitchUser(@UserIdInt int userId) {
1329 synchronized (mMethodMap) {
1330 switchUserLocked(userId);
1331 }
1332 }
1333
Seigo Nonaka7309b122015-08-17 18:34:13 -07001334 public InputMethodManagerService(Context context) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001335 mIPackageManager = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 mContext = context;
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -08001337 mRes = context.getResources();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 mHandler = new Handler(this);
Yohei Yukawa81482972015-06-04 00:58:59 -07001339 // Note: SettingsObserver doesn't register observers in its constructor.
1340 mSettingsObserver = new SettingsObserver(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 mIWindowManager = IWindowManager.Stub.asInterface(
1342 ServiceManager.getService(Context.WINDOW_SERVICE));
Seigo Nonaka7309b122015-08-17 18:34:13 -07001343 mWindowManagerInternal = LocalServices.getService(WindowManagerInternal.class);
Mita Yuned218c72012-12-06 17:18:25 -08001344 mCaller = new HandlerCaller(context, null, new HandlerCaller.Callback() {
satoke7c6998e2011-06-03 17:57:59 +09001345 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346 public void executeMessage(Message msg) {
1347 handleMessage(msg);
1348 }
Mita Yuned218c72012-12-06 17:18:25 -08001349 }, true /*asyncHandler*/);
Yohei Yukawad34e1482016-02-11 08:03:52 -08001350 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Yohei Yukawaed4952a2016-02-17 07:57:25 -08001351 mUserManager = mContext.getSystemService(UserManager.class);
satok01038492012-04-09 21:08:27 +09001352 mHardKeyboardListener = new HardKeyboardListener();
Dianne Hackborn119bbc32013-03-22 17:27:25 -07001353 mHasFeature = context.getPackageManager().hasSystemFeature(
1354 PackageManager.FEATURE_INPUT_METHODS);
Jason Monk3e189872016-01-12 09:10:34 -05001355 mSlotIme = mContext.getString(com.android.internal.R.string.status_bar_ime);
Yohei Yukawafa0e47e2016-04-05 09:55:56 -07001356 mHardKeyboardBehavior = mContext.getResources().getInteger(
1357 com.android.internal.R.integer.config_externalHardKeyboardBehavior);
satok7cfc0ed2011-06-20 21:29:36 +09001358
Chris Wren1ce4b6d2015-06-11 10:19:43 -04001359 Bundle extras = new Bundle();
1360 extras.putBoolean(Notification.EXTRA_ALLOW_DURING_SETUP, true);
Tadashi G. Takaoka01065a52017-07-19 14:10:24 +09001361 @ColorInt final int accentColor = mContext.getColor(
1362 com.android.internal.R.color.system_notification_accent_color);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001363 mImeSwitcherNotification =
1364 new Notification.Builder(mContext, SystemNotificationChannels.VIRTUAL_KEYBOARD)
1365 .setSmallIcon(com.android.internal.R.drawable.ic_notification_ime_default)
1366 .setWhen(0)
1367 .setOngoing(true)
1368 .addExtras(extras)
1369 .setCategory(Notification.CATEGORY_SYSTEM)
Tadashi G. Takaoka01065a52017-07-19 14:10:24 +09001370 .setColor(accentColor);
Daniel Sandler590d5152012-06-14 16:10:13 -04001371
Tadashi G. Takaoka01065a52017-07-19 14:10:24 +09001372 Intent intent = new Intent(ACTION_SHOW_INPUT_METHOD_PICKER)
1373 .setPackage(mContext.getPackageName());
satok683e2382011-07-12 08:28:52 +09001374 mImeSwitchPendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
satokb858c732011-07-22 19:54:34 +09001375
1376 mShowOngoingImeSwitcherForPhones = false;
satok7cfc0ed2011-06-20 21:29:36 +09001377
satok7cfc0ed2011-06-20 21:29:36 +09001378 mNotificationShown = false;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001379 int userId = 0;
1380 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001381 userId = ActivityManager.getService().getCurrentUser().id;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001382 } catch (RemoteException e) {
1383 Slog.w(TAG, "Couldn't get current user ID; guessing it's 0", e);
1384 }
satok913a8922010-08-26 21:53:41 +09001385
satokd87c2592010-09-29 11:52:06 +09001386 // mSettings should be created before buildInputMethodListLocked
satokdf31ae62011-01-15 06:19:44 +09001387 mSettings = new InputMethodSettings(
Yohei Yukawa68645a62016-02-17 07:54:20 -08001388 mRes, context.getContentResolver(), mMethodMap, mMethodList, userId, !mSystemReady);
Svet Ganovadc1cf42015-06-15 16:36:24 -07001389
Kenny Guy2a764942014-04-02 13:29:20 +01001390 updateCurrentProfileIds();
Satoshi Kataoka5ade83b2012-09-26 22:59:41 +09001391 mFileManager = new InputMethodFileManager(mMethodMap, userId);
Yohei Yukawa79247822017-01-23 15:26:15 -08001392 mSwitchingController = InputMethodSubtypeSwitchingController.createInstanceLocked(
1393 mSettings, context);
Tarandeep Singh89a6c482017-11-21 14:26:11 -08001394 // Register VR-state listener.
1395 IVrManager vrManager = (IVrManager) ServiceManager.getService(Context.VR_SERVICE);
1396 if (vrManager != null) {
1397 try {
1398 vrManager.registerListener(mVrStateCallbacks);
1399 } catch (RemoteException e) {
1400 Slog.e(TAG, "Failed to register VR mode state listener.");
1401 }
1402 }
satok5b927c432012-05-01 20:09:34 +09001403 }
1404
satok5b927c432012-05-01 20:09:34 +09001405 private void resetDefaultImeLocked(Context context) {
1406 // Do not reset the default (current) IME when it is a 3rd-party IME
Yohei Yukawac2393ac2016-02-18 00:30:45 -08001407 if (mCurMethodId != null && !InputMethodUtils.isSystemIme(mMethodMap.get(mCurMethodId))) {
satok5b927c432012-05-01 20:09:34 +09001408 return;
1409 }
Yohei Yukawac2393ac2016-02-18 00:30:45 -08001410 final List<InputMethodInfo> suitableImes = InputMethodUtils.getDefaultEnabledImes(
Yohei Yukawaaf5cee82017-01-23 16:17:11 -08001411 context, mSettings.getEnabledInputMethodListLocked());
Yohei Yukawac2393ac2016-02-18 00:30:45 -08001412 if (suitableImes.isEmpty()) {
1413 Slog.i(TAG, "No default found");
1414 return;
satok5b927c432012-05-01 20:09:34 +09001415 }
Yohei Yukawac2393ac2016-02-18 00:30:45 -08001416 final InputMethodInfo defIm = suitableImes.get(0);
Yohei Yukawad0332832017-02-01 13:59:43 -08001417 if (DEBUG) {
1418 Slog.i(TAG, "Default found, using " + defIm.getId());
1419 }
Yohei Yukawac2393ac2016-02-18 00:30:45 -08001420 setSelectedInputMethodAndSubtypeLocked(defIm, NOT_A_SUBTYPE_ID, false);
satok5b927c432012-05-01 20:09:34 +09001421 }
1422
Andreas Gampea36dc622018-02-05 17:19:22 -08001423 @GuardedBy("mMethodMap")
Satoshi Kataoka5ade83b2012-09-26 22:59:41 +09001424 private void switchUserLocked(int newUserId) {
Yohei Yukawa90bf7082015-06-03 23:50:27 -07001425 if (DEBUG) Slog.d(TAG, "Switching user stage 1/3. newUserId=" + newUserId
1426 + " currentUserId=" + mSettings.getCurrentUserId());
1427
Yohei Yukawa81482972015-06-04 00:58:59 -07001428 // ContentObserver should be registered again when the user is changed
1429 mSettingsObserver.registerContentObserverLocked(newUserId);
Yohei Yukawa68645a62016-02-17 07:54:20 -08001430
Yohei Yukawaed4952a2016-02-17 07:57:25 -08001431 // If the system is not ready or the device is not yed unlocked by the user, then we use
1432 // copy-on-write settings.
1433 final boolean useCopyOnWriteSettings =
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001434 !mSystemReady || !mUserManager.isUserUnlockingOrUnlocked(newUserId);
Yohei Yukawa68645a62016-02-17 07:54:20 -08001435 mSettings.switchCurrentUser(newUserId, useCopyOnWriteSettings);
Kenny Guy2a764942014-04-02 13:29:20 +01001436 updateCurrentProfileIds();
Satoshi Kataoka5ade83b2012-09-26 22:59:41 +09001437 // InputMethodFileManager should be reset when the user is changed
1438 mFileManager = new InputMethodFileManager(mMethodMap, newUserId);
Satoshi Kataoka7f7535f2013-02-18 12:54:16 +09001439 final String defaultImiId = mSettings.getSelectedInputMethod();
Yohei Yukawa90bf7082015-06-03 23:50:27 -07001440
1441 if (DEBUG) Slog.d(TAG, "Switching user stage 2/3. newUserId=" + newUserId
1442 + " defaultImiId=" + defaultImiId);
1443
Satoshi Kataoka7c4a2a12013-02-25 15:25:43 +09001444 // For secondary users, the list of enabled IMEs may not have been updated since the
1445 // callbacks to PackageMonitor are ignored for the secondary user. Here, defaultImiId may
1446 // not be empty even if the IME has been uninstalled by the primary user.
1447 // Even in such cases, IMMS works fine because it will find the most applicable
1448 // IME for that user.
Satoshi Kataokaed1cdb22013-04-17 16:41:58 +09001449 final boolean initialUserSwitch = TextUtils.isEmpty(defaultImiId);
Yohei Yukawa0d7aff82017-02-10 00:40:51 -08001450 mLastSystemLocales = mRes.getConfiguration().getLocales();
1451
1452 // TODO: Is it really possible that switchUserLocked() happens before system ready?
1453 if (mSystemReady) {
1454 hideCurrentInputLocked(0, null);
1455 resetCurrentMethodAndClient(InputMethodClient.UNBIND_REASON_SWITCH_USER);
1456 buildInputMethodListLocked(initialUserSwitch);
1457 if (TextUtils.isEmpty(mSettings.getSelectedInputMethod())) {
1458 // This is the first time of the user switch and
1459 // set the current ime to the proper one.
1460 resetDefaultImeLocked(mContext);
1461 }
1462 updateFromSettingsLocked(true);
1463 try {
1464 startInputInnerLocked();
1465 } catch (RuntimeException e) {
1466 Slog.w(TAG, "Unexpected exception", e);
1467 }
1468 }
1469
Satoshi Kataokaed1cdb22013-04-17 16:41:58 +09001470 if (initialUserSwitch) {
Yohei Yukawa094c71f2015-06-20 00:41:31 -07001471 InputMethodUtils.setNonSelectedSystemImesDisabledUntilUsed(mIPackageManager,
1472 mSettings.getEnabledInputMethodListLocked(), newUserId,
1473 mContext.getBasePackageName());
Satoshi Kataokaed1cdb22013-04-17 16:41:58 +09001474 }
Yohei Yukawa90bf7082015-06-03 23:50:27 -07001475
1476 if (DEBUG) Slog.d(TAG, "Switching user stage 3/3. newUserId=" + newUserId
1477 + " selectedIme=" + mSettings.getSelectedInputMethod());
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001478 }
1479
Kenny Guy2a764942014-04-02 13:29:20 +01001480 void updateCurrentProfileIds() {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07001481 mSettings.setCurrentProfileIds(
1482 mUserManager.getProfileIdsWithDisabled(mSettings.getCurrentUserId()));
Amith Yamasani734983f2014-03-04 16:48:05 -08001483 }
1484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 @Override
1486 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1487 throws RemoteException {
1488 try {
1489 return super.onTransact(code, data, reply, flags);
1490 } catch (RuntimeException e) {
1491 // The input method manager only throws security exceptions, so let's
1492 // log all others.
1493 if (!(e instanceof SecurityException)) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07001494 Slog.wtf(TAG, "Input Method Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 }
1496 throw e;
1497 }
1498 }
1499
Svetoslav Ganova0027152013-06-25 14:59:53 -07001500 public void systemRunning(StatusBarManagerService statusBar) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001501 synchronized (mMethodMap) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001502 if (DEBUG) {
1503 Slog.d(TAG, "--- systemReady");
1504 }
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001505 if (!mSystemReady) {
1506 mSystemReady = true;
Yohei Yukawa79247822017-01-23 15:26:15 -08001507 mLastSystemLocales = mRes.getConfiguration().getLocales();
Yohei Yukawa68645a62016-02-17 07:54:20 -08001508 final int currentUserId = mSettings.getCurrentUserId();
Yohei Yukawaed4952a2016-02-17 07:57:25 -08001509 mSettings.switchCurrentUser(currentUserId,
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001510 !mUserManager.isUserUnlockingOrUnlocked(currentUserId));
Yohei Yukawad34e1482016-02-11 08:03:52 -08001511 mKeyguardManager = mContext.getSystemService(KeyguardManager.class);
1512 mNotificationManager = mContext.getSystemService(NotificationManager.class);
Dianne Hackborn661cd522011-08-22 00:26:20 -07001513 mStatusBar = statusBar;
Griff Hazen6090c262016-03-25 08:11:24 -07001514 if (mStatusBar != null) {
1515 mStatusBar.setIconVisibility(mSlotIme, false);
1516 }
Seigo Nonakad9eb9112015-05-26 20:54:43 +09001517 updateSystemUiLocked(mCurToken, mImeWindowVis, mBackDisposition);
satokb858c732011-07-22 19:54:34 +09001518 mShowOngoingImeSwitcherForPhones = mRes.getBoolean(
1519 com.android.internal.R.bool.show_ongoing_ime_switcher);
satok01038492012-04-09 21:08:27 +09001520 if (mShowOngoingImeSwitcherForPhones) {
Seigo Nonaka7309b122015-08-17 18:34:13 -07001521 mWindowManagerInternal.setOnHardKeyboardStatusChangeListener(
satok01038492012-04-09 21:08:27 +09001522 mHardKeyboardListener);
1523 }
Yohei Yukawa79247822017-01-23 15:26:15 -08001524
1525 mMyPackageMonitor.register(mContext, null, UserHandle.ALL, true);
1526 mSettingsObserver.registerContentObserverLocked(currentUserId);
1527
1528 final IntentFilter broadcastFilter = new IntentFilter();
1529 broadcastFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
1530 broadcastFilter.addAction(Intent.ACTION_USER_ADDED);
1531 broadcastFilter.addAction(Intent.ACTION_USER_REMOVED);
Yohei Yukawa79247822017-01-23 15:26:15 -08001532 broadcastFilter.addAction(Intent.ACTION_LOCALE_CHANGED);
Tadashi G. Takaoka01065a52017-07-19 14:10:24 +09001533 broadcastFilter.addAction(ACTION_SHOW_INPUT_METHOD_PICKER);
Yohei Yukawa79247822017-01-23 15:26:15 -08001534 mContext.registerReceiver(new ImmsBroadcastReceiver(), broadcastFilter);
1535
Yohei Yukawa1f9a3cb2017-10-26 15:00:59 -07001536 final String defaultImiId = mSettings.getSelectedInputMethod();
1537 final boolean imeSelectedOnBoot = !TextUtils.isEmpty(defaultImiId);
1538 buildInputMethodListLocked(!imeSelectedOnBoot /* resetDefaultEnabledIme */);
Yohei Yukawa79247822017-01-23 15:26:15 -08001539 resetDefaultImeLocked(mContext);
1540 updateFromSettingsLocked(true);
1541 InputMethodUtils.setNonSelectedSystemImesDisabledUntilUsed(mIPackageManager,
1542 mSettings.getEnabledInputMethodListLocked(), currentUserId,
1543 mContext.getBasePackageName());
1544
Dianne Hackborncc278702009-09-02 23:07:23 -07001545 try {
1546 startInputInnerLocked();
1547 } catch (RuntimeException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001548 Slog.w(TAG, "Unexpected exception", e);
Dianne Hackborncc278702009-09-02 23:07:23 -07001549 }
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001550 }
1551 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001553
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001554 // ---------------------------------------------------------------------------------------
1555 // Check whether or not this is a valid IPC. Assumes an IPC is valid when either
1556 // 1) it comes from the system process
1557 // 2) the calling process' user id is identical to the current user id IMMS thinks.
1558 private boolean calledFromValidUser() {
1559 final int uid = Binder.getCallingUid();
1560 final int userId = UserHandle.getUserId(uid);
1561 if (DEBUG) {
1562 Slog.d(TAG, "--- calledFromForegroundUserOrSystemProcess ? "
1563 + "calling uid = " + uid + " system uid = " + Process.SYSTEM_UID
1564 + " calling userId = " + userId + ", foreground user id = "
Satoshi Kataoka87c29142013-07-31 23:11:54 +09001565 + mSettings.getCurrentUserId() + ", calling pid = " + Binder.getCallingPid()
1566 + InputMethodUtils.getApiCallStack());
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001567 }
Kenny Guy2a764942014-04-02 13:29:20 +01001568 if (uid == Process.SYSTEM_UID || mSettings.isCurrentProfile(userId)) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001569 return true;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001570 }
Satoshi Kataoka135e5fb2012-09-28 18:25:06 +09001571
1572 // Caveat: A process which has INTERACT_ACROSS_USERS_FULL gets results for the
1573 // foreground user, not for the user of that process. Accordingly InputMethodManagerService
1574 // must not manage background users' states in any functions.
1575 // Note that privacy-sensitive IPCs, such as setInputMethod, are still securely guarded
1576 // by a token.
1577 if (mContext.checkCallingOrSelfPermission(
1578 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1579 == PackageManager.PERMISSION_GRANTED) {
1580 if (DEBUG) {
1581 Slog.d(TAG, "--- Access granted because the calling process has "
1582 + "the INTERACT_ACROSS_USERS_FULL permission");
1583 }
1584 return true;
1585 }
Yohei Yukawad0332832017-02-01 13:59:43 -08001586 // TODO(b/34886274): The semantics of this verification is actually not well-defined.
Seigo Nonakae27dc2b2015-08-14 18:21:27 -07001587 Slog.w(TAG, "--- IPC called from background users. Ignore. callers="
1588 + Debug.getCallers(10));
Satoshi Kataoka135e5fb2012-09-28 18:25:06 +09001589 return false;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001590 }
1591
Yohei Yukawa22c97be2014-06-04 19:43:36 +09001592
1593 /**
1594 * Returns true iff the caller is identified to be the current input method with the token.
1595 * @param token The window token given to the input method when it was started.
1596 * @return true if and only if non-null valid token is specified.
1597 */
Yohei Yukawad0332832017-02-01 13:59:43 -08001598 private boolean calledWithValidToken(@Nullable IBinder token) {
1599 if (token == null && Binder.getCallingPid() == Process.myPid()) {
1600 if (DEBUG) {
1601 // TODO(b/34851776): Basically it's the caller's fault if we reach here.
1602 Slog.d(TAG, "Bug 34851776 is detected callers=" + Debug.getCallers(10));
1603 }
1604 return false;
1605 }
1606 if (token == null || token != mCurToken) {
1607 // TODO(b/34886274): The semantics of this verification is actually not well-defined.
1608 Slog.e(TAG, "Ignoring " + Debug.getCaller() + " due to an invalid token."
1609 + " uid:" + Binder.getCallingUid() + " token:" + token);
Yohei Yukawa22c97be2014-06-04 19:43:36 +09001610 return false;
1611 }
1612 return true;
1613 }
1614
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001615 private boolean bindCurrentInputMethodService(
1616 Intent service, ServiceConnection conn, int flags) {
1617 if (service == null || conn == null) {
1618 Slog.e(TAG, "--- bind failed: service = " + service + ", conn = " + conn);
1619 return false;
1620 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08001621 return mContext.bindServiceAsUser(service, conn, flags,
1622 new UserHandle(mSettings.getCurrentUserId()));
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001623 }
1624
satoke7c6998e2011-06-03 17:57:59 +09001625 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 public List<InputMethodInfo> getInputMethodList() {
Tarandeep Singh89a6c482017-11-21 14:26:11 -08001627 return getInputMethodList(false /* isVrOnly */);
1628 }
1629
1630 public List<InputMethodInfo> getVrInputMethodList() {
1631 return getInputMethodList(true /* isVrOnly */);
1632 }
1633
1634 private List<InputMethodInfo> getInputMethodList(final boolean isVrOnly) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001635 // TODO: Make this work even for non-current users?
1636 if (!calledFromValidUser()) {
1637 return Collections.emptyList();
1638 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 synchronized (mMethodMap) {
Tarandeep Singh89a6c482017-11-21 14:26:11 -08001640 ArrayList<InputMethodInfo> methodList = new ArrayList<>();
1641 for (InputMethodInfo info : mMethodList) {
1642
1643 if (info.isVrOnly() == isVrOnly) {
1644 methodList.add(info);
1645 }
1646 }
1647 return methodList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 }
1649 }
1650
satoke7c6998e2011-06-03 17:57:59 +09001651 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 public List<InputMethodInfo> getEnabledInputMethodList() {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001653 // TODO: Make this work even for non-current users?
1654 if (!calledFromValidUser()) {
1655 return Collections.emptyList();
1656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 synchronized (mMethodMap) {
satokd87c2592010-09-29 11:52:06 +09001658 return mSettings.getEnabledInputMethodListLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 }
1660 }
1661
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09001662 /**
Satoshi Kataokab3c21ac2013-08-07 15:43:29 +09001663 * @param imiId if null, returns enabled subtypes for the current imi
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09001664 * @return enabled subtypes of the specified imi
1665 */
satoke7c6998e2011-06-03 17:57:59 +09001666 @Override
Satoshi Kataokab3c21ac2013-08-07 15:43:29 +09001667 public List<InputMethodSubtype> getEnabledInputMethodSubtypeList(String imiId,
satok16331c82010-12-20 23:48:46 +09001668 boolean allowsImplicitlySelectedSubtypes) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001669 // TODO: Make this work even for non-current users?
1670 if (!calledFromValidUser()) {
Yohei Yukawab0377bb2015-08-10 21:06:30 -07001671 return Collections.emptyList();
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001672 }
satok67ddf9c2010-11-17 09:45:54 +09001673 synchronized (mMethodMap) {
Satoshi Kataokab3c21ac2013-08-07 15:43:29 +09001674 final InputMethodInfo imi;
1675 if (imiId == null && mCurMethodId != null) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09001676 imi = mMethodMap.get(mCurMethodId);
Satoshi Kataokab3c21ac2013-08-07 15:43:29 +09001677 } else {
1678 imi = mMethodMap.get(imiId);
1679 }
1680 if (imi == null) {
Yohei Yukawab0377bb2015-08-10 21:06:30 -07001681 return Collections.emptyList();
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09001682 }
1683 return mSettings.getEnabledInputMethodSubtypeListLocked(
1684 mContext, imi, allowsImplicitlySelectedSubtypes);
satok67ddf9c2010-11-17 09:45:54 +09001685 }
1686 }
1687
satoke7c6998e2011-06-03 17:57:59 +09001688 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 public void addClient(IInputMethodClient client,
1690 IInputContext inputContext, int uid, int pid) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001691 if (!calledFromValidUser()) {
1692 return;
1693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 synchronized (mMethodMap) {
1695 mClients.put(client.asBinder(), new ClientState(client,
1696 inputContext, uid, pid));
1697 }
1698 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001699
satoke7c6998e2011-06-03 17:57:59 +09001700 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 public void removeClient(IInputMethodClient client) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001702 if (!calledFromValidUser()) {
1703 return;
1704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 synchronized (mMethodMap) {
Jeff Brownc28867a2013-03-26 15:42:39 -07001706 ClientState cs = mClients.remove(client.asBinder());
1707 if (cs != null) {
1708 clearClientSessionLocked(cs);
Yohei Yukawa072b1b52015-11-18 15:54:34 -08001709 if (mCurClient == cs) {
Tarandeep Singh93c00cea2018-02-16 14:31:17 -08001710 if (mBoundToMethod) {
1711 mBoundToMethod = false;
1712 if (mCurMethod != null) {
1713 executeOrSendMessage(mCurMethod, mCaller.obtainMessageO(
1714 MSG_UNBIND_INPUT, mCurMethod));
1715 }
1716 }
Yohei Yukawa072b1b52015-11-18 15:54:34 -08001717 mCurClient = null;
1718 }
Yohei Yukawae39d4ed2015-11-19 03:38:49 -08001719 if (mCurFocusedWindowClient == cs) {
1720 mCurFocusedWindowClient = null;
1721 }
Jeff Brownc28867a2013-03-26 15:42:39 -07001722 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 }
1724 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 void executeOrSendMessage(IInterface target, Message msg) {
1727 if (target.asBinder() instanceof Binder) {
1728 mCaller.sendMessage(msg);
1729 } else {
1730 handleMessage(msg);
1731 msg.recycle();
1732 }
1733 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001734
Yohei Yukawa33e81792015-11-17 21:14:42 -08001735 void unbindCurrentClientLocked(
1736 /* @InputMethodClient.UnbindReason */ final int unbindClientReason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 if (mCurClient != null) {
Yohei Yukawa35d3f372015-11-25 11:07:19 -08001738 if (DEBUG) Slog.v(TAG, "unbindCurrentInputLocked: client="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 + mCurClient.client.asBinder());
1740 if (mBoundToMethod) {
1741 mBoundToMethod = false;
1742 if (mCurMethod != null) {
1743 executeOrSendMessage(mCurMethod, mCaller.obtainMessageO(
1744 MSG_UNBIND_INPUT, mCurMethod));
1745 }
1746 }
Dianne Hackborna6e41342012-05-22 16:30:34 -07001747
Yohei Yukawa2bc66172017-02-08 11:13:25 -08001748 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIIO(
1749 MSG_SET_ACTIVE, 0, 0, mCurClient));
Yohei Yukawa33e81792015-11-17 21:14:42 -08001750 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIIO(
1751 MSG_UNBIND_CLIENT, mCurSeq, unbindClientReason, mCurClient.client));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 mCurClient.sessionRequested = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 mCurClient = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001754
The Android Open Source Project10592532009-03-18 17:39:46 -07001755 hideInputMethodMenuLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 }
1757 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 private int getImeShowFlags() {
1760 int flags = 0;
1761 if (mShowForced) {
1762 flags |= InputMethod.SHOW_FORCED
1763 | InputMethod.SHOW_EXPLICIT;
1764 } else if (mShowExplicitlyRequested) {
1765 flags |= InputMethod.SHOW_EXPLICIT;
1766 }
1767 return flags;
1768 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 private int getAppShowFlags() {
1771 int flags = 0;
1772 if (mShowForced) {
1773 flags |= InputMethodManager.SHOW_FORCED;
1774 } else if (!mShowExplicitlyRequested) {
1775 flags |= InputMethodManager.SHOW_IMPLICIT;
1776 }
1777 return flags;
1778 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001779
Andreas Gampea36dc622018-02-05 17:19:22 -08001780 @GuardedBy("mMethodMap")
Yohei Yukawa2553e482017-12-15 15:47:33 -08001781 @NonNull
Yohei Yukawa87ca8402017-02-07 00:13:14 -08001782 InputBindResult attachNewInputLocked(
1783 /* @InputMethodClient.StartInputReason */ final int startInputReason, boolean initial) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 if (!mBoundToMethod) {
1785 executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
1786 MSG_BIND_INPUT, mCurMethod, mCurClient.binding));
1787 mBoundToMethod = true;
1788 }
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08001789
1790 final Binder startInputToken = new Binder();
Yohei Yukawa357b2f62017-02-14 09:40:03 -08001791 final StartInputInfo info = new StartInputInfo(mCurToken, mCurId, startInputReason,
1792 !initial, mCurFocusedWindow, mCurAttribute, mCurFocusedWindowSoftInputMode,
1793 mCurSeq);
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08001794 mStartInputMap.put(startInputToken, info);
Yohei Yukawa357b2f62017-02-14 09:40:03 -08001795 mStartInputHistory.addEntry(info);
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08001796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 final SessionState session = mCurClient.curSession;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08001798 executeOrSendMessage(session.method, mCaller.obtainMessageIIOOOO(
Yohei Yukawaf7526b52017-02-11 20:57:10 -08001799 MSG_START_INPUT, mCurInputContextMissingMethods, initial ? 0 : 1 /* restarting */,
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08001800 startInputToken, session, mCurInputContext, mCurAttribute));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 if (mShowRequested) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001802 if (DEBUG) Slog.v(TAG, "Attach new input asks to show input");
The Android Open Source Project4df24232009-03-05 14:34:35 -08001803 showCurrentInputLocked(getAppShowFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08001805 return new InputBindResult(InputBindResult.ResultCode.SUCCESS_WITH_IME_SESSION,
1806 session.session, (session.channel != null ? session.channel.dup() : null),
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09001807 mCurId, mCurSeq, mCurUserActionNotificationSequenceNumber);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001809
Andreas Gampea36dc622018-02-05 17:19:22 -08001810 @GuardedBy("mMethodMap")
Yohei Yukawa2553e482017-12-15 15:47:33 -08001811 @NonNull
Yohei Yukawa35d3f372015-11-25 11:07:19 -08001812 InputBindResult startInputLocked(
1813 /* @InputMethodClient.StartInputReason */ final int startInputReason,
Yohei Yukawa19a80a12016-03-14 22:57:37 -07001814 IInputMethodClient client, IInputContext inputContext,
1815 /* @InputConnectionInspector.missingMethods */ final int missingMethods,
Yohei Yukawa74750f22016-03-22 12:54:22 -07001816 @Nullable EditorInfo attribute, int controlFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 // If no method is currently selected, do nothing.
1818 if (mCurMethodId == null) {
Yohei Yukawa2553e482017-12-15 15:47:33 -08001819 return InputBindResult.NO_IME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 ClientState cs = mClients.get(client.asBinder());
1823 if (cs == null) {
1824 throw new IllegalArgumentException("unknown client "
1825 + client.asBinder());
1826 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001827
Yohei Yukawa74750f22016-03-22 12:54:22 -07001828 if (attribute == null) {
1829 Slog.w(TAG, "Ignoring startInput with null EditorInfo."
1830 + " uid=" + cs.uid + " pid=" + cs.pid);
Yohei Yukawa2553e482017-12-15 15:47:33 -08001831 return InputBindResult.NULL_EDITOR_INFO;
Yohei Yukawa74750f22016-03-22 12:54:22 -07001832 }
1833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 try {
1835 if (!mIWindowManager.inputMethodClientHasFocus(cs.client)) {
1836 // Check with the window manager to make sure this client actually
1837 // has a window with focus. If not, reject. This is thread safe
1838 // because if the focus changes some time before or after, the
1839 // next client receiving focus that has any interest in input will
1840 // be calling through here after that change happens.
Yohei Yukawad0332832017-02-01 13:59:43 -08001841 if (DEBUG) {
1842 Slog.w(TAG, "Starting input on non-focused client " + cs.client
1843 + " (uid=" + cs.uid + " pid=" + cs.pid + ")");
1844 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08001845 return InputBindResult.NOT_IME_TARGET_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 }
1847 } catch (RemoteException e) {
1848 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001849
Yohei Yukawa19a80a12016-03-14 22:57:37 -07001850 return startInputUncheckedLocked(cs, inputContext, missingMethods, attribute,
Yohei Yukawa87ca8402017-02-07 00:13:14 -08001851 controlFlags, startInputReason);
Dianne Hackborn7663d802012-02-24 13:08:49 -08001852 }
1853
Andreas Gampea36dc622018-02-05 17:19:22 -08001854 @GuardedBy("mMethodMap")
Yohei Yukawa2553e482017-12-15 15:47:33 -08001855 @NonNull
Yohei Yukawa35d3f372015-11-25 11:07:19 -08001856 InputBindResult startInputUncheckedLocked(@NonNull ClientState cs, IInputContext inputContext,
Yohei Yukawa19a80a12016-03-14 22:57:37 -07001857 /* @InputConnectionInspector.missingMethods */ final int missingMethods,
Yohei Yukawa87ca8402017-02-07 00:13:14 -08001858 @NonNull EditorInfo attribute, int controlFlags,
1859 /* @InputMethodClient.StartInputReason */ final int startInputReason) {
Dianne Hackborn7663d802012-02-24 13:08:49 -08001860 // If no method is currently selected, do nothing.
1861 if (mCurMethodId == null) {
Yohei Yukawa2553e482017-12-15 15:47:33 -08001862 return InputBindResult.NO_IME;
Dianne Hackborn7663d802012-02-24 13:08:49 -08001863 }
1864
Yohei Yukawad57ba672015-06-08 16:39:46 -07001865 if (!InputMethodUtils.checkIfPackageBelongsToUid(mAppOpsManager, cs.uid,
1866 attribute.packageName)) {
1867 Slog.e(TAG, "Rejecting this client as it reported an invalid package name."
1868 + " uid=" + cs.uid + " package=" + attribute.packageName);
Yohei Yukawa2553e482017-12-15 15:47:33 -08001869 return InputBindResult.INVALID_PACKAGE_NAME;
Yohei Yukawa0f3ad12015-04-06 16:48:24 -07001870 }
1871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 if (mCurClient != cs) {
John Spurlocke0980502013-10-25 11:59:29 -04001873 // Was the keyguard locked when switching over to the new client?
1874 mCurClientInKeyguard = isKeyguardLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 // If the client is changing, we need to switch over to the new
1876 // one.
Yohei Yukawa33e81792015-11-17 21:14:42 -08001877 unbindCurrentClientLocked(InputMethodClient.UNBIND_REASON_SWITCH_CLIENT);
Yohei Yukawa35d3f372015-11-25 11:07:19 -08001878 if (DEBUG) Slog.v(TAG, "switching to client: client="
John Spurlocke0980502013-10-25 11:59:29 -04001879 + cs.client.asBinder() + " keyguard=" + mCurClientInKeyguard);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880
1881 // If the screen is on, inform the new client it is active
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07001882 if (mIsInteractive) {
Dianne Hackborna6e41342012-05-22 16:30:34 -07001883 executeOrSendMessage(cs.client, mCaller.obtainMessageIO(
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07001884 MSG_SET_ACTIVE, mIsInteractive ? 1 : 0, cs));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 }
1886 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 // Bump up the sequence for this client and attach it.
1889 mCurSeq++;
1890 if (mCurSeq <= 0) mCurSeq = 1;
1891 mCurClient = cs;
1892 mCurInputContext = inputContext;
Yohei Yukawa19a80a12016-03-14 22:57:37 -07001893 mCurInputContextMissingMethods = missingMethods;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 mCurAttribute = attribute;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 // Check if the input method is changing.
1897 if (mCurId != null && mCurId.equals(mCurMethodId)) {
1898 if (cs.curSession != null) {
1899 // Fast case: if we are already connected to the input method,
1900 // then just return it.
Yohei Yukawa87ca8402017-02-07 00:13:14 -08001901 return attachNewInputLocked(startInputReason,
Dianne Hackborn7663d802012-02-24 13:08:49 -08001902 (controlFlags&InputMethodManager.CONTROL_START_INITIAL) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001903 }
1904 if (mHaveConnection) {
1905 if (mCurMethod != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 // Return to client, and we will get back with it when
1907 // we have had a session made for it.
Jeff Brownc28867a2013-03-26 15:42:39 -07001908 requestClientSessionLocked(cs);
Yohei Yukawa2553e482017-12-15 15:47:33 -08001909 return new InputBindResult(
1910 InputBindResult.ResultCode.SUCCESS_WAITING_IME_SESSION,
1911 null, null, mCurId, mCurSeq,
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09001912 mCurUserActionNotificationSequenceNumber);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 } else if (SystemClock.uptimeMillis()
1914 < (mLastBindTime+TIME_TO_RECONNECT)) {
1915 // In this case we have connected to the service, but
1916 // don't yet have its interface. If it hasn't been too
1917 // long since we did the connection, we'll return to
1918 // the client and wait to get the service interface so
1919 // we can report back. If it has been too long, we want
1920 // to fall through so we can try a disconnect/reconnect
1921 // to see if we can get back in touch with the service.
Yohei Yukawa2553e482017-12-15 15:47:33 -08001922 return new InputBindResult(
1923 InputBindResult.ResultCode.SUCCESS_WAITING_IME_BINDING,
1924 null, null, mCurId, mCurSeq,
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09001925 mCurUserActionNotificationSequenceNumber);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001927 EventLog.writeEvent(EventLogTags.IMF_FORCE_RECONNECT_IME,
1928 mCurMethodId, SystemClock.uptimeMillis()-mLastBindTime, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 }
1930 }
1931 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001932
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001933 return startInputInnerLocked();
1934 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001935
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001936 InputBindResult startInputInnerLocked() {
1937 if (mCurMethodId == null) {
Yohei Yukawa2553e482017-12-15 15:47:33 -08001938 return InputBindResult.NO_IME;
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001939 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001940
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001941 if (!mSystemReady) {
1942 // If the system is not yet ready, we shouldn't be running third
1943 // party code.
Yohei Yukawa2553e482017-12-15 15:47:33 -08001944 return new InputBindResult(
1945 InputBindResult.ResultCode.ERROR_SYSTEM_NOT_READY,
1946 null, null, mCurMethodId, mCurSeq,
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09001947 mCurUserActionNotificationSequenceNumber);
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001948 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 InputMethodInfo info = mMethodMap.get(mCurMethodId);
1951 if (info == null) {
1952 throw new IllegalArgumentException("Unknown id: " + mCurMethodId);
1953 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001954
Yohei Yukawabc7b5262015-11-17 17:38:41 -08001955 unbindCurrentMethodLocked(true);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957 mCurIntent = new Intent(InputMethod.SERVICE_INTERFACE);
1958 mCurIntent.setComponent(info.getComponent());
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07001959 mCurIntent.putExtra(Intent.EXTRA_CLIENT_LABEL,
1960 com.android.internal.R.string.input_method_binding_label);
1961 mCurIntent.putExtra(Intent.EXTRA_CLIENT_INTENT, PendingIntent.getActivity(
1962 mContext, 0, new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS), 0));
Yohei Yukawaa67a4592017-03-30 15:57:02 -07001963 if (bindCurrentInputMethodService(mCurIntent, this, IME_CONNECTION_BIND_FLAGS)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 mLastBindTime = SystemClock.uptimeMillis();
1965 mHaveConnection = true;
1966 mCurId = info.getId();
1967 mCurToken = new Binder();
1968 try {
Yohei Yukawad0332832017-02-01 13:59:43 -08001969 if (DEBUG) Slog.v(TAG, "Adding window token: " + mCurToken);
Wale Ogunwaleac2561e2016-11-01 15:43:46 -07001970 mIWindowManager.addWindowToken(mCurToken, TYPE_INPUT_METHOD, DEFAULT_DISPLAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971 } catch (RemoteException e) {
1972 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08001973 return new InputBindResult(
1974 InputBindResult.ResultCode.SUCCESS_WAITING_IME_BINDING,
1975 null, null, mCurId, mCurSeq,
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09001976 mCurUserActionNotificationSequenceNumber);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08001978 mCurIntent = null;
1979 Slog.w(TAG, "Failure connecting to input method service: " + mCurIntent);
1980 return InputBindResult.IME_NOT_CONNECTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001982
Yohei Yukawa2553e482017-12-15 15:47:33 -08001983 @NonNull
Yohei Yukawa05c25f82016-02-22 12:41:17 -08001984 private InputBindResult startInput(
Yohei Yukawa35d3f372015-11-25 11:07:19 -08001985 /* @InputMethodClient.StartInputReason */ final int startInputReason,
Yohei Yukawa19a80a12016-03-14 22:57:37 -07001986 IInputMethodClient client, IInputContext inputContext,
1987 /* @InputConnectionInspector.missingMethods */ final int missingMethods,
Yohei Yukawa74750f22016-03-22 12:54:22 -07001988 @Nullable EditorInfo attribute, int controlFlags) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001989 if (!calledFromValidUser()) {
Yohei Yukawa2553e482017-12-15 15:47:33 -08001990 return InputBindResult.INVALID_USER;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 synchronized (mMethodMap) {
Yohei Yukawa35d3f372015-11-25 11:07:19 -08001993 if (DEBUG) {
1994 Slog.v(TAG, "startInput: reason="
1995 + InputMethodClient.getStartInputReason(startInputReason)
1996 + " client = " + client.asBinder()
1997 + " inputContext=" + inputContext
Yohei Yukawa19a80a12016-03-14 22:57:37 -07001998 + " missingMethods="
1999 + InputConnectionInspector.getMissingMethodFlagsAsString(missingMethods)
Yohei Yukawa35d3f372015-11-25 11:07:19 -08002000 + " attribute=" + attribute
2001 + " controlFlags=#" + Integer.toHexString(controlFlags));
2002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 final long ident = Binder.clearCallingIdentity();
2004 try {
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002005 return startInputLocked(startInputReason, client, inputContext, missingMethods,
2006 attribute, controlFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 } finally {
2008 Binder.restoreCallingIdentity(ident);
2009 }
2010 }
2011 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002012
satoke7c6998e2011-06-03 17:57:59 +09002013 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002014 public void finishInput(IInputMethodClient client) {
2015 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002016
satoke7c6998e2011-06-03 17:57:59 +09002017 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002018 public void onServiceConnected(ComponentName name, IBinder service) {
2019 synchronized (mMethodMap) {
2020 if (mCurIntent != null && name.equals(mCurIntent.getComponent())) {
2021 mCurMethod = IInputMethod.Stub.asInterface(service);
Dianne Hackborncc278702009-09-02 23:07:23 -07002022 if (mCurToken == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002023 Slog.w(TAG, "Service connected without a token!");
Yohei Yukawabc7b5262015-11-17 17:38:41 -08002024 unbindCurrentMethodLocked(false);
Dianne Hackborncc278702009-09-02 23:07:23 -07002025 return;
2026 }
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07002027 if (DEBUG) Slog.v(TAG, "Initiating attach with token: " + mCurToken);
Dianne Hackborncc278702009-09-02 23:07:23 -07002028 executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
2029 MSG_ATTACH_TOKEN, mCurMethod, mCurToken));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 if (mCurClient != null) {
Jeff Brownc28867a2013-03-26 15:42:39 -07002031 clearClientSessionLocked(mCurClient);
2032 requestClientSessionLocked(mCurClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 }
2034 }
2035 }
2036 }
2037
Jeff Brownc28867a2013-03-26 15:42:39 -07002038 void onSessionCreated(IInputMethod method, IInputMethodSession session,
2039 InputChannel channel) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 synchronized (mMethodMap) {
2041 if (mCurMethod != null && method != null
2042 && mCurMethod.asBinder() == method.asBinder()) {
2043 if (mCurClient != null) {
Jeff Brownc28867a2013-03-26 15:42:39 -07002044 clearClientSessionLocked(mCurClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 mCurClient.curSession = new SessionState(mCurClient,
Jeff Brownc28867a2013-03-26 15:42:39 -07002046 method, session, channel);
Yohei Yukawa87ca8402017-02-07 00:13:14 -08002047 InputBindResult res = attachNewInputLocked(
2048 InputMethodClient.START_INPUT_REASON_SESSION_CREATED_BY_IME, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002049 if (res.method != null) {
2050 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageOO(
Yohei Yukawa33e81792015-11-17 21:14:42 -08002051 MSG_BIND_CLIENT, mCurClient.client, res));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 }
Jeff Brownc28867a2013-03-26 15:42:39 -07002053 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 }
2055 }
2056 }
Jeff Brownc28867a2013-03-26 15:42:39 -07002057
2058 // Session abandoned. Close its associated input channel.
2059 channel.dispose();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002061
Yohei Yukawabc7b5262015-11-17 17:38:41 -08002062 void unbindCurrentMethodLocked(boolean savePosition) {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -07002063 if (mVisibleBound) {
2064 mContext.unbindService(mVisibleConnection);
2065 mVisibleBound = false;
2066 }
2067
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002068 if (mHaveConnection) {
2069 mContext.unbindService(this);
2070 mHaveConnection = false;
2071 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002072
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002073 if (mCurToken != null) {
2074 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002075 if (DEBUG) Slog.v(TAG, "Removing window token: " + mCurToken);
Dianne Hackborn2ea9bae2012-11-02 18:43:48 -07002076 if ((mImeWindowVis & InputMethodService.IME_ACTIVE) != 0 && savePosition) {
satoke0a99412012-05-10 02:22:58 +09002077 // The current IME is shown. Hence an IME switch (transition) is happening.
Seigo Nonaka7309b122015-08-17 18:34:13 -07002078 mWindowManagerInternal.saveLastInputMethodWindowForTransition();
satoke0a99412012-05-10 02:22:58 +09002079 }
Wale Ogunwaleac2561e2016-11-01 15:43:46 -07002080 mIWindowManager.removeWindowToken(mCurToken, DEFAULT_DISPLAY);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002081 } catch (RemoteException e) {
2082 }
2083 mCurToken = null;
2084 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002085
The Android Open Source Project10592532009-03-18 17:39:46 -07002086 mCurId = null;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002087 clearCurMethodLocked();
Yohei Yukawabc7b5262015-11-17 17:38:41 -08002088 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002089
Yohei Yukawa33e81792015-11-17 21:14:42 -08002090 void resetCurrentMethodAndClient(
2091 /* @InputMethodClient.UnbindReason */ final int unbindClientReason) {
Yohei Yukawabc7b5262015-11-17 17:38:41 -08002092 mCurMethodId = null;
2093 unbindCurrentMethodLocked(false);
Yohei Yukawa33e81792015-11-17 21:14:42 -08002094 unbindCurrentClientLocked(unbindClientReason);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002095 }
Jeff Brownc28867a2013-03-26 15:42:39 -07002096
2097 void requestClientSessionLocked(ClientState cs) {
2098 if (!cs.sessionRequested) {
2099 if (DEBUG) Slog.v(TAG, "Creating new session for client " + cs);
2100 InputChannel[] channels = InputChannel.openInputChannelPair(cs.toString());
2101 cs.sessionRequested = true;
2102 executeOrSendMessage(mCurMethod, mCaller.obtainMessageOOO(
2103 MSG_CREATE_SESSION, mCurMethod, channels[1],
2104 new MethodCallback(this, mCurMethod, channels[0])));
2105 }
2106 }
2107
2108 void clearClientSessionLocked(ClientState cs) {
2109 finishSessionLocked(cs.curSession);
2110 cs.curSession = null;
2111 cs.sessionRequested = false;
2112 }
2113
2114 private void finishSessionLocked(SessionState sessionState) {
2115 if (sessionState != null) {
2116 if (sessionState.session != null) {
2117 try {
2118 sessionState.session.finishSession();
2119 } catch (RemoteException e) {
2120 Slog.w(TAG, "Session failed to close due to remote exception", e);
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002121 updateSystemUiLocked(mCurToken, 0 /* vis */, mBackDisposition);
Jeff Brownc28867a2013-03-26 15:42:39 -07002122 }
2123 sessionState.session = null;
2124 }
2125 if (sessionState.channel != null) {
2126 sessionState.channel.dispose();
2127 sessionState.channel = null;
Devin Taylor0c33ed22010-02-23 13:26:46 -06002128 }
2129 }
2130 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002131
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002132 void clearCurMethodLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002133 if (mCurMethod != null) {
2134 for (ClientState cs : mClients.values()) {
Jeff Brownc28867a2013-03-26 15:42:39 -07002135 clearClientSessionLocked(cs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002136 }
Devin Taylor0c33ed22010-02-23 13:26:46 -06002137
Jeff Brownc28867a2013-03-26 15:42:39 -07002138 finishSessionLocked(mEnabledSession);
Devin Taylor0c33ed22010-02-23 13:26:46 -06002139 mEnabledSession = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002140 mCurMethod = null;
2141 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07002142 if (mStatusBar != null) {
Jason Monk3e189872016-01-12 09:10:34 -05002143 mStatusBar.setIconVisibility(mSlotIme, false);
Dianne Hackborn661cd522011-08-22 00:26:20 -07002144 }
Yohei Yukawa2bc66172017-02-08 11:13:25 -08002145 mInFullscreenMode = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002146 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002147
satoke7c6998e2011-06-03 17:57:59 +09002148 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149 public void onServiceDisconnected(ComponentName name) {
Yohei Yukawa817d5f72017-01-04 20:15:02 -08002150 // Note that mContext.unbindService(this) does not trigger this. Hence if we are here the
2151 // disconnection is not intended by IMMS (e.g. triggered because the current IMS crashed),
2152 // which is irregular but can eventually happen for everyone just by continuing using the
2153 // device. Thus it is important to make sure that all the internal states are properly
2154 // refreshed when this method is called back. Running
2155 // adb install -r <APK that implements the current IME>
2156 // would be a good way to trigger such a situation.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157 synchronized (mMethodMap) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002158 if (DEBUG) Slog.v(TAG, "Service disconnected: " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002159 + " mCurIntent=" + mCurIntent);
2160 if (mCurMethod != null && mCurIntent != null
2161 && name.equals(mCurIntent.getComponent())) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002162 clearCurMethodLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002163 // We consider this to be a new bind attempt, since the system
2164 // should now try to restart the service for us.
2165 mLastBindTime = SystemClock.uptimeMillis();
2166 mShowRequested = mInputShown;
2167 mInputShown = false;
Yohei Yukawa817d5f72017-01-04 20:15:02 -08002168 unbindCurrentClientLocked(InputMethodClient.UNBIND_REASON_DISCONNECT_IME);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002169 }
2170 }
2171 }
2172
satokf9f01002011-05-19 21:31:50 +09002173 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 public void updateStatusIcon(IBinder token, String packageName, int iconId) {
Yohei Yukawa59377ca2017-01-31 21:32:26 -08002175 synchronized (mMethodMap) {
2176 if (!calledWithValidToken(token)) {
Yohei Yukawa59377ca2017-01-31 21:32:26 -08002177 return;
2178 }
2179 final long ident = Binder.clearCallingIdentity();
2180 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002181 if (iconId == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002182 if (DEBUG) Slog.d(TAG, "hide the small icon for the input method");
Dianne Hackborn661cd522011-08-22 00:26:20 -07002183 if (mStatusBar != null) {
Jason Monk3e189872016-01-12 09:10:34 -05002184 mStatusBar.setIconVisibility(mSlotIme, false);
Dianne Hackborn661cd522011-08-22 00:26:20 -07002185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002186 } else if (packageName != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002187 if (DEBUG) Slog.d(TAG, "show a small icon for the input method");
Svetoslav Ganov6179ea32011-06-28 01:12:41 -07002188 CharSequence contentDescription = null;
2189 try {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002190 // Use PackageManager to load label
2191 final PackageManager packageManager = mContext.getPackageManager();
Svetoslav Ganov6179ea32011-06-28 01:12:41 -07002192 contentDescription = packageManager.getApplicationLabel(
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002193 mIPackageManager.getApplicationInfo(packageName, 0,
2194 mSettings.getCurrentUserId()));
2195 } catch (RemoteException e) {
Svetoslav Ganov6179ea32011-06-28 01:12:41 -07002196 /* ignore */
2197 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07002198 if (mStatusBar != null) {
Jason Monk3e189872016-01-12 09:10:34 -05002199 mStatusBar.setIcon(mSlotIme, packageName, iconId, 0,
Dianne Hackborn661cd522011-08-22 00:26:20 -07002200 contentDescription != null
2201 ? contentDescription.toString() : null);
Jason Monk3e189872016-01-12 09:10:34 -05002202 mStatusBar.setIconVisibility(mSlotIme, true);
Dianne Hackborn661cd522011-08-22 00:26:20 -07002203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 }
Yohei Yukawa59377ca2017-01-31 21:32:26 -08002205 } finally {
2206 Binder.restoreCallingIdentity(ident);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002208 }
2209 }
2210
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002211 private boolean shouldShowImeSwitcherLocked(int visibility) {
satok7cfc0ed2011-06-20 21:29:36 +09002212 if (!mShowOngoingImeSwitcherForPhones) return false;
Jason Monk807ef762014-05-08 15:47:46 -04002213 if (mSwitchingDialog != null) return false;
Yohei Yukawad2bc3092017-07-31 15:37:14 -07002214 if (mWindowManagerInternal.isKeyguardShowingAndNotOccluded()
2215 && mKeyguardManager != null && mKeyguardManager.isKeyguardSecure()) return false;
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002216 if ((visibility & InputMethodService.IME_ACTIVE) == 0) return false;
Seigo Nonaka7309b122015-08-17 18:34:13 -07002217 if (mWindowManagerInternal.isHardKeyboardAvailable()) {
Yohei Yukawafa0e47e2016-04-05 09:55:56 -07002218 if (mHardKeyboardBehavior == HardKeyboardBehavior.WIRELESS_AFFORDANCE) {
2219 // When physical keyboard is attached, we show the ime switcher (or notification if
2220 // NavBar is not available) because SHOW_IME_WITH_HARD_KEYBOARD settings currently
2221 // exists in the IME switcher dialog. Might be OK to remove this condition once
2222 // SHOW_IME_WITH_HARD_KEYBOARD settings finds a good place to live.
2223 return true;
2224 }
Yohei Yukawa89398382016-03-29 11:37:04 -07002225 } else if ((visibility & InputMethodService.IME_VISIBLE) == 0) {
2226 return false;
Yohei Yukawac6c7cd22015-05-12 15:00:33 -07002227 }
Yohei Yukawac6c7cd22015-05-12 15:00:33 -07002228
2229 List<InputMethodInfo> imis = mSettings.getEnabledInputMethodListLocked();
2230 final int N = imis.size();
2231 if (N > 2) return true;
2232 if (N < 1) return false;
2233 int nonAuxCount = 0;
2234 int auxCount = 0;
2235 InputMethodSubtype nonAuxSubtype = null;
2236 InputMethodSubtype auxSubtype = null;
2237 for(int i = 0; i < N; ++i) {
2238 final InputMethodInfo imi = imis.get(i);
2239 final List<InputMethodSubtype> subtypes =
2240 mSettings.getEnabledInputMethodSubtypeListLocked(mContext, imi, true);
2241 final int subtypeCount = subtypes.size();
2242 if (subtypeCount == 0) {
2243 ++nonAuxCount;
2244 } else {
2245 for (int j = 0; j < subtypeCount; ++j) {
2246 final InputMethodSubtype subtype = subtypes.get(j);
2247 if (!subtype.isAuxiliary()) {
2248 ++nonAuxCount;
2249 nonAuxSubtype = subtype;
2250 } else {
2251 ++auxCount;
2252 auxSubtype = subtype;
satok7cfc0ed2011-06-20 21:29:36 +09002253 }
2254 }
satok7cfc0ed2011-06-20 21:29:36 +09002255 }
2256 }
Yohei Yukawac6c7cd22015-05-12 15:00:33 -07002257 if (nonAuxCount > 1 || auxCount > 1) {
2258 return true;
2259 } else if (nonAuxCount == 1 && auxCount == 1) {
2260 if (nonAuxSubtype != null && auxSubtype != null
2261 && (nonAuxSubtype.getLocale().equals(auxSubtype.getLocale())
2262 || auxSubtype.overridesImplicitlyEnabledSubtype()
2263 || nonAuxSubtype.overridesImplicitlyEnabledSubtype())
2264 && nonAuxSubtype.containsExtraValueKey(TAG_TRY_SUPPRESSING_IME_SWITCHER)) {
2265 return false;
2266 }
2267 return true;
2268 }
2269 return false;
satok7cfc0ed2011-06-20 21:29:36 +09002270 }
2271
John Spurlocke0980502013-10-25 11:59:29 -04002272 private boolean isKeyguardLocked() {
2273 return mKeyguardManager != null && mKeyguardManager.isKeyguardLocked();
2274 }
2275
Yohei Yukawad6475a62017-04-17 10:35:27 -07002276 @BinderThread
satokdbf29502011-08-25 15:28:23 +09002277 @SuppressWarnings("deprecation")
satokf9f01002011-05-19 21:31:50 +09002278 @Override
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08002279 public void setImeWindowStatus(IBinder token, IBinder startInputToken, int vis,
2280 int backDisposition) {
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002281 if (!calledWithValidToken(token)) {
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002282 return;
2283 }
2284
Yohei Yukawa69e68022017-02-13 12:04:50 -08002285 final StartInputInfo info;
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002286 synchronized (mMethodMap) {
Yohei Yukawa69e68022017-02-13 12:04:50 -08002287 info = mStartInputMap.get(startInputToken);
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002288 mImeWindowVis = vis;
2289 mBackDisposition = backDisposition;
2290 updateSystemUiLocked(token, vis, backDisposition);
2291 }
Yohei Yukawad6475a62017-04-17 10:35:27 -07002292
2293 final boolean dismissImeOnBackKeyPressed;
2294 switch (backDisposition) {
2295 case InputMethodService.BACK_DISPOSITION_WILL_DISMISS:
2296 dismissImeOnBackKeyPressed = true;
2297 break;
2298 case InputMethodService.BACK_DISPOSITION_WILL_NOT_DISMISS:
2299 dismissImeOnBackKeyPressed = false;
2300 break;
2301 default:
2302 case InputMethodService.BACK_DISPOSITION_DEFAULT:
2303 dismissImeOnBackKeyPressed = ((vis & InputMethodService.IME_VISIBLE) != 0);
2304 break;
2305 }
Yohei Yukawaee2a7ed2017-02-15 21:38:57 -08002306 mWindowManagerInternal.updateInputMethodWindowStatus(token,
2307 (vis & InputMethodService.IME_VISIBLE) != 0,
Yohei Yukawad6475a62017-04-17 10:35:27 -07002308 dismissImeOnBackKeyPressed, info != null ? info.mTargetWindow : null);
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002309 }
2310
2311 private void updateSystemUi(IBinder token, int vis, int backDisposition) {
2312 synchronized (mMethodMap) {
2313 updateSystemUiLocked(token, vis, backDisposition);
2314 }
2315 }
2316
2317 // Caution! This method is called in this class. Handle multi-user carefully
2318 private void updateSystemUiLocked(IBinder token, int vis, int backDisposition) {
2319 if (!calledWithValidToken(token)) {
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002320 return;
2321 }
2322
2323 // TODO: Move this clearing calling identity block to setImeWindowStatus after making sure
2324 // all updateSystemUi happens on system previlege.
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002325 final long ident = Binder.clearCallingIdentity();
satok06487a52010-10-29 11:37:18 +09002326 try {
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002327 // apply policy for binder calls
2328 if (vis != 0 && isKeyguardLocked() && !mCurClientInKeyguard) {
2329 vis = 0;
satok06487a52010-10-29 11:37:18 +09002330 }
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002331 // mImeWindowVis should be updated before calling shouldShowImeSwitcherLocked().
2332 final boolean needsToShowImeSwitcher = shouldShowImeSwitcherLocked(vis);
2333 if (mStatusBar != null) {
2334 mStatusBar.setImeWindowStatus(token, vis, backDisposition,
2335 needsToShowImeSwitcher);
2336 }
2337 final InputMethodInfo imi = mMethodMap.get(mCurMethodId);
2338 if (imi != null && needsToShowImeSwitcher) {
2339 // Used to load label
2340 final CharSequence title = mRes.getText(
2341 com.android.internal.R.string.select_input_method);
2342 final CharSequence summary = InputMethodUtils.getImeAndSubtypeDisplayName(
2343 mContext, imi, mCurrentSubtype);
Chris Wren1ce4b6d2015-06-11 10:19:43 -04002344 mImeSwitcherNotification.setContentTitle(title)
2345 .setContentText(summary)
2346 .setContentIntent(mImeSwitchPendingIntent);
Seigo Nonaka7309b122015-08-17 18:34:13 -07002347 try {
2348 if ((mNotificationManager != null)
2349 && !mIWindowManager.hasNavigationBar()) {
2350 if (DEBUG) {
2351 Slog.d(TAG, "--- show notification: label = " + summary);
2352 }
2353 mNotificationManager.notifyAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04002354 SystemMessage.NOTE_SELECT_INPUT_METHOD,
Seigo Nonaka7309b122015-08-17 18:34:13 -07002355 mImeSwitcherNotification.build(), UserHandle.ALL);
2356 mNotificationShown = true;
Dianne Hackborn661cd522011-08-22 00:26:20 -07002357 }
Seigo Nonaka7309b122015-08-17 18:34:13 -07002358 } catch (RemoteException e) {
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002359 }
2360 } else {
2361 if (mNotificationShown && mNotificationManager != null) {
2362 if (DEBUG) {
2363 Slog.d(TAG, "--- hide notification");
satok7cfc0ed2011-06-20 21:29:36 +09002364 }
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002365 mNotificationManager.cancelAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04002366 SystemMessage.NOTE_SELECT_INPUT_METHOD, UserHandle.ALL);
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002367 mNotificationShown = false;
satok7cfc0ed2011-06-20 21:29:36 +09002368 }
satok06487a52010-10-29 11:37:18 +09002369 }
2370 } finally {
2371 Binder.restoreCallingIdentity(ident);
2372 }
2373 }
2374
satoke7c6998e2011-06-03 17:57:59 +09002375 @Override
satokf9f01002011-05-19 21:31:50 +09002376 public void registerSuggestionSpansForNotification(SuggestionSpan[] spans) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002377 if (!calledFromValidUser()) {
2378 return;
2379 }
satokf9f01002011-05-19 21:31:50 +09002380 synchronized (mMethodMap) {
2381 final InputMethodInfo currentImi = mMethodMap.get(mCurMethodId);
2382 for (int i = 0; i < spans.length; ++i) {
2383 SuggestionSpan ss = spans[i];
satok42c5a162011-05-26 16:46:14 +09002384 if (!TextUtils.isEmpty(ss.getNotificationTargetClassName())) {
satokf9f01002011-05-19 21:31:50 +09002385 mSecureSuggestionSpans.put(ss, currentImi);
2386 }
2387 }
2388 }
2389 }
2390
satoke7c6998e2011-06-03 17:57:59 +09002391 @Override
satokf9f01002011-05-19 21:31:50 +09002392 public boolean notifySuggestionPicked(SuggestionSpan span, String originalString, int index) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002393 if (!calledFromValidUser()) {
2394 return false;
2395 }
satokf9f01002011-05-19 21:31:50 +09002396 synchronized (mMethodMap) {
2397 final InputMethodInfo targetImi = mSecureSuggestionSpans.get(span);
2398 // TODO: Do not send the intent if the process of the targetImi is already dead.
2399 if (targetImi != null) {
2400 final String[] suggestions = span.getSuggestions();
2401 if (index < 0 || index >= suggestions.length) return false;
satok42c5a162011-05-26 16:46:14 +09002402 final String className = span.getNotificationTargetClassName();
satokf9f01002011-05-19 21:31:50 +09002403 final Intent intent = new Intent();
2404 // Ensures that only a class in the original IME package will receive the
2405 // notification.
satok42c5a162011-05-26 16:46:14 +09002406 intent.setClassName(targetImi.getPackageName(), className);
satokf9f01002011-05-19 21:31:50 +09002407 intent.setAction(SuggestionSpan.ACTION_SUGGESTION_PICKED);
2408 intent.putExtra(SuggestionSpan.SUGGESTION_SPAN_PICKED_BEFORE, originalString);
2409 intent.putExtra(SuggestionSpan.SUGGESTION_SPAN_PICKED_AFTER, suggestions[index]);
2410 intent.putExtra(SuggestionSpan.SUGGESTION_SPAN_PICKED_HASHCODE, span.hashCode());
Amith Yamasanif043de92012-10-24 06:42:40 -07002411 final long ident = Binder.clearCallingIdentity();
2412 try {
2413 mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT);
2414 } finally {
2415 Binder.restoreCallingIdentity(ident);
2416 }
satokf9f01002011-05-19 21:31:50 +09002417 return true;
2418 }
2419 }
2420 return false;
2421 }
2422
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08002423 void updateFromSettingsLocked(boolean enabledMayChange) {
Michael Wright7b5a96b2014-08-09 19:28:42 -07002424 updateInputMethodsFromSettingsLocked(enabledMayChange);
2425 updateKeyboardFromSettingsLocked();
2426 }
2427
2428 void updateInputMethodsFromSettingsLocked(boolean enabledMayChange) {
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08002429 if (enabledMayChange) {
2430 List<InputMethodInfo> enabled = mSettings.getEnabledInputMethodListLocked();
2431 for (int i=0; i<enabled.size(); i++) {
2432 // We allow the user to select "disabled until used" apps, so if they
2433 // are enabling one of those here we now need to make it enabled.
2434 InputMethodInfo imm = enabled.get(i);
2435 try {
2436 ApplicationInfo ai = mIPackageManager.getApplicationInfo(imm.getPackageName(),
2437 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
2438 mSettings.getCurrentUserId());
Satoshi Kataoka7987a312013-04-17 18:59:33 +09002439 if (ai != null && ai.enabledSetting
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08002440 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
Satoshi Kataokaed1cdb22013-04-17 16:41:58 +09002441 if (DEBUG) {
2442 Slog.d(TAG, "Update state(" + imm.getId()
2443 + "): DISABLED_UNTIL_USED -> DEFAULT");
2444 }
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08002445 mIPackageManager.setApplicationEnabledSetting(imm.getPackageName(),
2446 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07002447 PackageManager.DONT_KILL_APP, mSettings.getCurrentUserId(),
2448 mContext.getBasePackageName());
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08002449 }
2450 } catch (RemoteException e) {
2451 }
2452 }
2453 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002454 // We are assuming that whoever is changing DEFAULT_INPUT_METHOD and
2455 // ENABLED_INPUT_METHODS is taking care of keeping them correctly in
2456 // sync, so we will never have a DEFAULT_INPUT_METHOD that is not
2457 // enabled.
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002458 String id = mSettings.getSelectedInputMethod();
satok03eb319a2010-11-11 18:17:42 +09002459 // There is no input method selected, try to choose new applicable input method.
2460 if (TextUtils.isEmpty(id) && chooseNewDefaultIMELocked()) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002461 id = mSettings.getSelectedInputMethod();
satok03eb319a2010-11-11 18:17:42 +09002462 }
2463 if (!TextUtils.isEmpty(id)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002464 try {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09002465 setInputMethodLocked(id, mSettings.getSelectedInputMethodSubtypeId(id));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002466 } catch (IllegalArgumentException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002467 Slog.w(TAG, "Unknown input method from prefs: " + id, e);
Yohei Yukawa33e81792015-11-17 21:14:42 -08002468 resetCurrentMethodAndClient(InputMethodClient.UNBIND_REASON_SWITCH_IME_FAILED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002469 }
satokf3db1af2010-11-23 13:34:33 +09002470 mShortcutInputMethodsAndSubtypes.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002471 } else {
2472 // There is no longer an input method set, so stop any current one.
Yohei Yukawa33e81792015-11-17 21:14:42 -08002473 resetCurrentMethodAndClient(InputMethodClient.UNBIND_REASON_NO_IME);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002474 }
Yohei Yukawa3d46bab2014-05-30 18:10:18 +09002475 // Here is not the perfect place to reset the switching controller. Ideally
2476 // mSwitchingController and mSettings should be able to share the same state.
2477 // TODO: Make sure that mSwitchingController and mSettings are sharing the
2478 // the same enabled IMEs list.
2479 mSwitchingController.resetCircularListLocked(mContext);
Michael Wright7b5a96b2014-08-09 19:28:42 -07002480
2481 }
2482
2483 public void updateKeyboardFromSettingsLocked() {
2484 mShowImeWithHardKeyboard = mSettings.isShowImeWithHardKeyboardEnabled();
2485 if (mSwitchingDialog != null
2486 && mSwitchingDialogTitleView != null
2487 && mSwitchingDialog.isShowing()) {
2488 final Switch hardKeySwitch = (Switch)mSwitchingDialogTitleView.findViewById(
2489 com.android.internal.R.id.hard_keyboard_switch);
2490 hardKeySwitch.setChecked(mShowImeWithHardKeyboard);
2491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002493
satokab751aa2010-09-14 19:17:36 +09002494 /* package */ void setInputMethodLocked(String id, int subtypeId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 InputMethodInfo info = mMethodMap.get(id);
2496 if (info == null) {
satok913a8922010-08-26 21:53:41 +09002497 throw new IllegalArgumentException("Unknown id: " + id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002499
satokd81e9502012-05-21 12:58:45 +09002500 // See if we need to notify a subtype change within the same IME.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002501 if (id.equals(mCurMethodId)) {
satokd81e9502012-05-21 12:58:45 +09002502 final int subtypeCount = info.getSubtypeCount();
2503 if (subtypeCount <= 0) {
2504 return;
satokcd7cd292010-11-20 15:46:23 +09002505 }
satokd81e9502012-05-21 12:58:45 +09002506 final InputMethodSubtype oldSubtype = mCurrentSubtype;
2507 final InputMethodSubtype newSubtype;
2508 if (subtypeId >= 0 && subtypeId < subtypeCount) {
2509 newSubtype = info.getSubtypeAt(subtypeId);
2510 } else {
2511 // If subtype is null, try to find the most applicable one from
2512 // getCurrentInputMethodSubtype.
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002513 newSubtype = getCurrentInputMethodSubtypeLocked();
satokd81e9502012-05-21 12:58:45 +09002514 }
2515 if (newSubtype == null || oldSubtype == null) {
2516 Slog.w(TAG, "Illegal subtype state: old subtype = " + oldSubtype
2517 + ", new subtype = " + newSubtype);
2518 return;
2519 }
2520 if (newSubtype != oldSubtype) {
2521 setSelectedInputMethodAndSubtypeLocked(info, subtypeId, true);
2522 if (mCurMethod != null) {
2523 try {
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002524 updateSystemUiLocked(mCurToken, mImeWindowVis, mBackDisposition);
satokd81e9502012-05-21 12:58:45 +09002525 mCurMethod.changeInputMethodSubtype(newSubtype);
2526 } catch (RemoteException e) {
2527 Slog.w(TAG, "Failed to call changeInputMethodSubtype");
satokab751aa2010-09-14 19:17:36 +09002528 }
2529 }
2530 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002531 return;
2532 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002533
satokd81e9502012-05-21 12:58:45 +09002534 // Changing to a different IME.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535 final long ident = Binder.clearCallingIdentity();
2536 try {
satokab751aa2010-09-14 19:17:36 +09002537 // Set a subtype to this input method.
2538 // subtypeId the name of a subtype which will be set.
satok723a27e2010-11-11 14:58:11 +09002539 setSelectedInputMethodAndSubtypeLocked(info, subtypeId, false);
2540 // mCurMethodId should be updated after setSelectedInputMethodAndSubtypeLocked()
2541 // because mCurMethodId is stored as a history in
2542 // setSelectedInputMethodAndSubtypeLocked().
2543 mCurMethodId = id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07002545 if (LocalServices.getService(ActivityManagerInternal.class).isSystemReady()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 Intent intent = new Intent(Intent.ACTION_INPUT_METHOD_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002547 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002548 intent.putExtra("input_method_id", id);
Amith Yamasanicd757062012-10-19 18:23:52 -07002549 mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 }
Yohei Yukawa33e81792015-11-17 21:14:42 -08002551 unbindCurrentClientLocked(InputMethodClient.UNBIND_REASON_SWITCH_IME);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002552 } finally {
2553 Binder.restoreCallingIdentity(ident);
2554 }
2555 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002556
satok42c5a162011-05-26 16:46:14 +09002557 @Override
The Android Open Source Project4df24232009-03-05 14:34:35 -08002558 public boolean showSoftInput(IInputMethodClient client, int flags,
2559 ResultReceiver resultReceiver) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002560 if (!calledFromValidUser()) {
2561 return false;
2562 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002563 int uid = Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 long ident = Binder.clearCallingIdentity();
2565 try {
2566 synchronized (mMethodMap) {
2567 if (mCurClient == null || client == null
2568 || mCurClient.client.asBinder() != client.asBinder()) {
2569 try {
2570 // We need to check if this is the current client with
2571 // focus in the window manager, to allow this call to
2572 // be made before input is started in it.
2573 if (!mIWindowManager.inputMethodClientHasFocus(client)) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002574 Slog.w(TAG, "Ignoring showSoftInput of uid " + uid + ": " + client);
The Android Open Source Project4df24232009-03-05 14:34:35 -08002575 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 }
2577 } catch (RemoteException e) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08002578 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 }
2580 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002581
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07002582 if (DEBUG) Slog.v(TAG, "Client requesting input be shown");
The Android Open Source Project4df24232009-03-05 14:34:35 -08002583 return showCurrentInputLocked(flags, resultReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 }
2585 } finally {
2586 Binder.restoreCallingIdentity(ident);
2587 }
2588 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002589
The Android Open Source Project4df24232009-03-05 14:34:35 -08002590 boolean showCurrentInputLocked(int flags, ResultReceiver resultReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 mShowRequested = true;
Anna Galusza9b278112016-01-04 11:37:37 -08002592 if (mAccessibilityRequestingNoSoftKeyboard) {
2593 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594 }
Anna Galusza9b278112016-01-04 11:37:37 -08002595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 if ((flags&InputMethodManager.SHOW_FORCED) != 0) {
2597 mShowExplicitlyRequested = true;
2598 mShowForced = true;
Anna Galusza9b278112016-01-04 11:37:37 -08002599 } else if ((flags&InputMethodManager.SHOW_IMPLICIT) == 0) {
2600 mShowExplicitlyRequested = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002602
Dianne Hackborncc278702009-09-02 23:07:23 -07002603 if (!mSystemReady) {
2604 return false;
2605 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002606
The Android Open Source Project4df24232009-03-05 14:34:35 -08002607 boolean res = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 if (mCurMethod != null) {
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07002609 if (DEBUG) Slog.d(TAG, "showCurrentInputLocked: mCurToken=" + mCurToken);
The Android Open Source Project4df24232009-03-05 14:34:35 -08002610 executeOrSendMessage(mCurMethod, mCaller.obtainMessageIOO(
2611 MSG_SHOW_SOFT_INPUT, getImeShowFlags(), mCurMethod,
2612 resultReceiver));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002613 mInputShown = true;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -07002614 if (mHaveConnection && !mVisibleBound) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002615 bindCurrentInputMethodService(
Yohei Yukawaa67a4592017-03-30 15:57:02 -07002616 mCurIntent, mVisibleConnection, IME_VISIBLE_BIND_FLAGS);
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -07002617 mVisibleBound = true;
2618 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08002619 res = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002620 } else if (mHaveConnection && SystemClock.uptimeMillis()
satok59b424c2011-09-30 17:21:46 +09002621 >= (mLastBindTime+TIME_TO_RECONNECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002622 // The client has asked to have the input method shown, but
2623 // we have been sitting here too long with a connection to the
2624 // service and no interface received, so let's disconnect/connect
2625 // to try to prod things along.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002626 EventLog.writeEvent(EventLogTags.IMF_FORCE_RECONNECT_IME, mCurMethodId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002627 SystemClock.uptimeMillis()-mLastBindTime,1);
satok59b424c2011-09-30 17:21:46 +09002628 Slog.w(TAG, "Force disconnect/connect to the IME in showCurrentInputLocked()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 mContext.unbindService(this);
Yohei Yukawaa67a4592017-03-30 15:57:02 -07002630 bindCurrentInputMethodService(mCurIntent, this, IME_CONNECTION_BIND_FLAGS);
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002631 } else {
2632 if (DEBUG) {
2633 Slog.d(TAG, "Can't show input: connection = " + mHaveConnection + ", time = "
2634 + ((mLastBindTime+TIME_TO_RECONNECT) - SystemClock.uptimeMillis()));
2635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002637
The Android Open Source Project4df24232009-03-05 14:34:35 -08002638 return res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002639 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002640
satok42c5a162011-05-26 16:46:14 +09002641 @Override
The Android Open Source Project4df24232009-03-05 14:34:35 -08002642 public boolean hideSoftInput(IInputMethodClient client, int flags,
2643 ResultReceiver resultReceiver) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002644 if (!calledFromValidUser()) {
2645 return false;
2646 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002647 int uid = Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002648 long ident = Binder.clearCallingIdentity();
2649 try {
2650 synchronized (mMethodMap) {
2651 if (mCurClient == null || client == null
2652 || mCurClient.client.asBinder() != client.asBinder()) {
2653 try {
2654 // We need to check if this is the current client with
2655 // focus in the window manager, to allow this call to
2656 // be made before input is started in it.
2657 if (!mIWindowManager.inputMethodClientHasFocus(client)) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002658 if (DEBUG) Slog.w(TAG, "Ignoring hideSoftInput of uid "
2659 + uid + ": " + client);
The Android Open Source Project4df24232009-03-05 14:34:35 -08002660 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 }
2662 } catch (RemoteException e) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08002663 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 }
2665 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002666
Joe Onorato8a9b2202010-02-26 18:56:32 -08002667 if (DEBUG) Slog.v(TAG, "Client requesting input be hidden");
The Android Open Source Project4df24232009-03-05 14:34:35 -08002668 return hideCurrentInputLocked(flags, resultReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002669 }
2670 } finally {
2671 Binder.restoreCallingIdentity(ident);
2672 }
2673 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002674
The Android Open Source Project4df24232009-03-05 14:34:35 -08002675 boolean hideCurrentInputLocked(int flags, ResultReceiver resultReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002676 if ((flags&InputMethodManager.HIDE_IMPLICIT_ONLY) != 0
2677 && (mShowExplicitlyRequested || mShowForced)) {
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07002678 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 -08002679 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002680 }
2681 if (mShowForced && (flags&InputMethodManager.HIDE_NOT_ALWAYS) != 0) {
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07002682 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 -08002683 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 }
Seigo Nonakaec928652015-06-10 15:31:20 +09002685
2686 // There is a chance that IMM#hideSoftInput() is called in a transient state where
2687 // IMMS#InputShown is already updated to be true whereas IMMS#mImeWindowVis is still waiting
2688 // to be updated with the new value sent from IME process. Even in such a transient state
2689 // historically we have accepted an incoming call of IMM#hideSoftInput() from the
2690 // application process as a valid request, and have even promised such a behavior with CTS
2691 // since Android Eclair. That's why we need to accept IMM#hideSoftInput() even when only
2692 // IMMS#InputShown indicates that the software keyboard is shown.
2693 // TODO: Clean up, IMMS#mInputShown, IMMS#mImeWindowVis and mShowRequested.
2694 final boolean shouldHideSoftInput = (mCurMethod != null) && (mInputShown ||
2695 (mImeWindowVis & InputMethodService.IME_ACTIVE) != 0);
The Android Open Source Project4df24232009-03-05 14:34:35 -08002696 boolean res;
Seigo Nonakaec928652015-06-10 15:31:20 +09002697 if (shouldHideSoftInput) {
2698 // The IME will report its visible state again after the following message finally
2699 // delivered to the IME process as an IPC. Hence the inconsistency between
2700 // IMMS#mInputShown and IMMS#mImeWindowVis should be resolved spontaneously in
2701 // the final state.
The Android Open Source Project4df24232009-03-05 14:34:35 -08002702 executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
2703 MSG_HIDE_SOFT_INPUT, mCurMethod, resultReceiver));
2704 res = true;
2705 } else {
2706 res = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002707 }
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -07002708 if (mHaveConnection && mVisibleBound) {
2709 mContext.unbindService(mVisibleConnection);
2710 mVisibleBound = false;
2711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002712 mInputShown = false;
2713 mShowRequested = false;
2714 mShowExplicitlyRequested = false;
2715 mShowForced = false;
The Android Open Source Project4df24232009-03-05 14:34:35 -08002716 return res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002717 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002718
Yohei Yukawa2553e482017-12-15 15:47:33 -08002719 @NonNull
satok42c5a162011-05-26 16:46:14 +09002720 @Override
Yohei Yukawa05c25f82016-02-22 12:41:17 -08002721 public InputBindResult startInputOrWindowGainedFocus(
2722 /* @InputMethodClient.StartInputReason */ final int startInputReason,
2723 IInputMethodClient client, IBinder windowToken, int controlFlags, int softInputMode,
Yohei Yukawa74750f22016-03-22 12:54:22 -07002724 int windowFlags, @Nullable EditorInfo attribute, IInputContext inputContext,
Yohei Yukawacf68d522017-12-12 09:33:26 -08002725 /* @InputConnectionInspector.missingMethods */ final int missingMethods,
2726 int unverifiedTargetSdkVersion) {
Yohei Yukawa2553e482017-12-15 15:47:33 -08002727 final InputBindResult result;
Yohei Yukawa05c25f82016-02-22 12:41:17 -08002728 if (windowToken != null) {
Yohei Yukawa2553e482017-12-15 15:47:33 -08002729 result = windowGainedFocus(startInputReason, client, windowToken, controlFlags,
Yohei Yukawacf68d522017-12-12 09:33:26 -08002730 softInputMode, windowFlags, attribute, inputContext, missingMethods,
2731 unverifiedTargetSdkVersion);
Yohei Yukawa05c25f82016-02-22 12:41:17 -08002732 } else {
Yohei Yukawa2553e482017-12-15 15:47:33 -08002733 result = startInput(startInputReason, client, inputContext, missingMethods, attribute,
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002734 controlFlags);
Yohei Yukawa05c25f82016-02-22 12:41:17 -08002735 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08002736 if (result == null) {
2737 // This must never happen, but just in case.
2738 Slog.wtf(TAG, "InputBindResult is @NonNull. startInputReason="
2739 + InputMethodClient.getStartInputReason(startInputReason)
2740 + " windowFlags=#" + Integer.toHexString(windowFlags)
2741 + " editorInfo=" + attribute);
2742 return InputBindResult.NULL;
2743 }
2744 return result;
Yohei Yukawa05c25f82016-02-22 12:41:17 -08002745 }
2746
Yohei Yukawa2553e482017-12-15 15:47:33 -08002747 @NonNull
Yohei Yukawa05c25f82016-02-22 12:41:17 -08002748 private InputBindResult windowGainedFocus(
Yohei Yukawa35d3f372015-11-25 11:07:19 -08002749 /* @InputMethodClient.StartInputReason */ final int startInputReason,
Yohei Yukawa22dac1c2017-02-12 16:54:16 -08002750 IInputMethodClient client, IBinder windowToken, int controlFlags,
2751 /* @android.view.WindowManager.LayoutParams.SoftInputModeFlags */ int softInputMode,
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002752 int windowFlags, EditorInfo attribute, IInputContext inputContext,
Yohei Yukawacf68d522017-12-12 09:33:26 -08002753 /* @InputConnectionInspector.missingMethods */ final int missingMethods,
2754 int unverifiedTargetSdkVersion) {
Satoshi Kataoka8d033052012-11-19 17:30:40 +09002755 // Needs to check the validity before clearing calling identity
2756 final boolean calledFromValidUser = calledFromValidUser();
Dianne Hackborn7663d802012-02-24 13:08:49 -08002757 InputBindResult res = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758 long ident = Binder.clearCallingIdentity();
2759 try {
2760 synchronized (mMethodMap) {
Yohei Yukawa35d3f372015-11-25 11:07:19 -08002761 if (DEBUG) Slog.v(TAG, "windowGainedFocus: reason="
2762 + InputMethodClient.getStartInputReason(startInputReason)
2763 + " client=" + client.asBinder()
2764 + " inputContext=" + inputContext
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002765 + " missingMethods="
2766 + InputConnectionInspector.getMissingMethodFlagsAsString(missingMethods)
Yohei Yukawa35d3f372015-11-25 11:07:19 -08002767 + " attribute=" + attribute
Dianne Hackborn7663d802012-02-24 13:08:49 -08002768 + " controlFlags=#" + Integer.toHexString(controlFlags)
Yohei Yukawa22a89232017-02-12 16:38:59 -08002769 + " softInputMode=" + InputMethodClient.softInputModeToString(softInputMode)
Yohei Yukawacf68d522017-12-12 09:33:26 -08002770 + " windowFlags=#" + Integer.toHexString(windowFlags)
2771 + " unverifiedTargetSdkVersion=" + unverifiedTargetSdkVersion);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002772
Dianne Hackborn7663d802012-02-24 13:08:49 -08002773 ClientState cs = mClients.get(client.asBinder());
2774 if (cs == null) {
2775 throw new IllegalArgumentException("unknown client "
2776 + client.asBinder());
2777 }
2778
2779 try {
2780 if (!mIWindowManager.inputMethodClientHasFocus(cs.client)) {
2781 // Check with the window manager to make sure this client actually
2782 // has a window with focus. If not, reject. This is thread safe
2783 // because if the focus changes some time before or after, the
2784 // next client receiving focus that has any interest in input will
2785 // be calling through here after that change happens.
Yohei Yukawad0332832017-02-01 13:59:43 -08002786 if (DEBUG) {
2787 Slog.w(TAG, "Focus gain on non-focused client " + cs.client
2788 + " (uid=" + cs.uid + " pid=" + cs.pid + ")");
2789 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08002790 return InputBindResult.NOT_IME_TARGET_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002791 }
Dianne Hackborn7663d802012-02-24 13:08:49 -08002792 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002794
Satoshi Kataoka8d033052012-11-19 17:30:40 +09002795 if (!calledFromValidUser) {
2796 Slog.w(TAG, "A background user is requesting window. Hiding IME.");
2797 Slog.w(TAG, "If you want to interect with IME, you need "
2798 + "android.permission.INTERACT_ACROSS_USERS_FULL");
2799 hideCurrentInputLocked(0, null);
Yohei Yukawa2553e482017-12-15 15:47:33 -08002800 return InputBindResult.INVALID_USER;
Satoshi Kataoka8d033052012-11-19 17:30:40 +09002801 }
2802
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002803 if (mCurFocusedWindow == windowToken) {
Yohei Yukawad0332832017-02-01 13:59:43 -08002804 if (DEBUG) {
2805 Slog.w(TAG, "Window already focused, ignoring focus gain of: " + client
2806 + " attribute=" + attribute + ", token = " + windowToken);
2807 }
Dianne Hackborn7663d802012-02-24 13:08:49 -08002808 if (attribute != null) {
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002809 return startInputUncheckedLocked(cs, inputContext, missingMethods,
Yohei Yukawa87ca8402017-02-07 00:13:14 -08002810 attribute, controlFlags, startInputReason);
Dianne Hackborn7663d802012-02-24 13:08:49 -08002811 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08002812 return new InputBindResult(
2813 InputBindResult.ResultCode.SUCCESS_REPORT_WINDOW_FOCUS_ONLY,
2814 null, null, null, -1, -1);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002815 }
2816 mCurFocusedWindow = windowToken;
Yohei Yukawa22a89232017-02-12 16:38:59 -08002817 mCurFocusedWindowSoftInputMode = softInputMode;
Yohei Yukawae39d4ed2015-11-19 03:38:49 -08002818 mCurFocusedWindowClient = cs;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002819
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -08002820 // Should we auto-show the IME even if the caller has not
2821 // specified what should be done with it?
2822 // We only do this automatically if the window can resize
2823 // to accommodate the IME (so what the user sees will give
2824 // them good context without input information being obscured
2825 // by the IME) or if running on a large screen where there
2826 // is more room for the target window + IME.
2827 final boolean doAutoShow =
2828 (softInputMode & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
2829 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
2830 || mRes.getConfiguration().isLayoutSizeAtLeast(
2831 Configuration.SCREENLAYOUT_SIZE_LARGE);
Dianne Hackborn7663d802012-02-24 13:08:49 -08002832 final boolean isTextEditor =
2833 (controlFlags&InputMethodManager.CONTROL_WINDOW_IS_TEXT_EDITOR) != 0;
2834
2835 // We want to start input before showing the IME, but after closing
2836 // it. We want to do this after closing it to help the IME disappear
2837 // more quickly (not get stuck behind it initializing itself for the
2838 // new focused input, even if its window wants to hide the IME).
2839 boolean didStart = false;
Yohei Yukawa0f3ad12015-04-06 16:48:24 -07002840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 switch (softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_STATE) {
2842 case WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED:
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -08002843 if (!isTextEditor || !doAutoShow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002844 if (WindowManager.LayoutParams.mayUseInputMethod(windowFlags)) {
2845 // There is no focus view, and this window will
2846 // be behind any soft input window, so hide the
2847 // soft input window if it is shown.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002848 if (DEBUG) Slog.v(TAG, "Unspecified window will hide input");
The Android Open Source Project4df24232009-03-05 14:34:35 -08002849 hideCurrentInputLocked(InputMethodManager.HIDE_NOT_ALWAYS, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002850 }
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -08002851 } else if (isTextEditor && doAutoShow && (softInputMode &
2852 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 // There is a focus view, and we are navigating forward
2854 // into the window, so show the input window for the user.
Dianne Hackborn7663d802012-02-24 13:08:49 -08002855 // We only do this automatically if the window can resize
2856 // to accommodate the IME (so what the user sees will give
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -08002857 // them good context without input information being obscured
2858 // by the IME) or if running on a large screen where there
2859 // is more room for the target window + IME.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002860 if (DEBUG) Slog.v(TAG, "Unspecified window will show input");
Dianne Hackborn7663d802012-02-24 13:08:49 -08002861 if (attribute != null) {
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002862 res = startInputUncheckedLocked(cs, inputContext,
Yohei Yukawa87ca8402017-02-07 00:13:14 -08002863 missingMethods, attribute, controlFlags, startInputReason);
Dianne Hackborn7663d802012-02-24 13:08:49 -08002864 didStart = true;
2865 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08002866 showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002867 }
2868 break;
2869 case WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED:
2870 // Do nothing.
2871 break;
2872 case WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN:
2873 if ((softInputMode &
2874 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002875 if (DEBUG) Slog.v(TAG, "Window asks to hide input going forward");
The Android Open Source Project4df24232009-03-05 14:34:35 -08002876 hideCurrentInputLocked(0, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002877 }
2878 break;
2879 case WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN:
Joe Onorato8a9b2202010-02-26 18:56:32 -08002880 if (DEBUG) Slog.v(TAG, "Window asks to hide input");
The Android Open Source Project4df24232009-03-05 14:34:35 -08002881 hideCurrentInputLocked(0, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 break;
2883 case WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE:
2884 if ((softInputMode &
2885 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002886 if (DEBUG) Slog.v(TAG, "Window asks to show input going forward");
Yohei Yukawacf68d522017-12-12 09:33:26 -08002887 if (InputMethodUtils.isSoftInputModeStateVisibleAllowed(
2888 unverifiedTargetSdkVersion, controlFlags)) {
2889 if (attribute != null) {
2890 res = startInputUncheckedLocked(cs, inputContext,
2891 missingMethods, attribute, controlFlags,
2892 startInputReason);
2893 didStart = true;
2894 }
2895 showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
2896 } else {
2897 Slog.e(TAG, "SOFT_INPUT_STATE_VISIBLE is ignored because"
2898 + " there is no focused view that also returns true from"
2899 + " View#onCheckIsTextEditor()");
Dianne Hackborn7663d802012-02-24 13:08:49 -08002900 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002901 }
2902 break;
2903 case WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE:
Joe Onorato8a9b2202010-02-26 18:56:32 -08002904 if (DEBUG) Slog.v(TAG, "Window asks to always show input");
Yohei Yukawacf68d522017-12-12 09:33:26 -08002905 if (InputMethodUtils.isSoftInputModeStateVisibleAllowed(
2906 unverifiedTargetSdkVersion, controlFlags)) {
2907 if (attribute != null) {
2908 res = startInputUncheckedLocked(cs, inputContext, missingMethods,
2909 attribute, controlFlags, startInputReason);
2910 didStart = true;
2911 }
2912 showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
2913 } else {
2914 Slog.e(TAG, "SOFT_INPUT_STATE_ALWAYS_VISIBLE is ignored because"
2915 + " there is no focused view that also returns true from"
2916 + " View#onCheckIsTextEditor()");
Dianne Hackborn7663d802012-02-24 13:08:49 -08002917 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002918 break;
2919 }
Dianne Hackborn7663d802012-02-24 13:08:49 -08002920
Tarandeep Singh2f731c552018-02-05 13:55:06 -08002921 if (!didStart) {
2922 if (attribute != null) {
2923 if (!DebugFlags.FLAG_OPTIMIZE_START_INPUT.value()
2924 || (controlFlags
2925 & InputMethodManager.CONTROL_WINDOW_IS_TEXT_EDITOR) != 0) {
2926 res = startInputUncheckedLocked(cs, inputContext, missingMethods,
2927 attribute,
2928 controlFlags, startInputReason);
2929 } else {
2930 res = InputBindResult.NO_EDITOR;
2931 }
2932 } else {
2933 res = InputBindResult.NULL_EDITOR_INFO;
Tarandeep Singh75a92392018-01-12 14:58:59 -08002934 }
Dianne Hackborn7663d802012-02-24 13:08:49 -08002935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936 }
2937 } finally {
2938 Binder.restoreCallingIdentity(ident);
2939 }
Dianne Hackborn7663d802012-02-24 13:08:49 -08002940
2941 return res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002942 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002943
Guliz Tuncay6908c152017-06-02 16:06:10 -07002944 private boolean canShowInputMethodPickerLocked(IInputMethodClient client) {
2945 final int uid = Binder.getCallingUid();
2946 if (UserHandle.getAppId(uid) == Process.SYSTEM_UID) {
2947 return true;
Tarandeep Singheb570612018-01-29 16:20:32 -08002948 } else if (mCurFocusedWindowClient != null && client != null
2949 && mCurFocusedWindowClient.client.asBinder() == client.asBinder()) {
Guliz Tuncay6908c152017-06-02 16:06:10 -07002950 return true;
2951 } else if (mCurIntent != null && InputMethodUtils.checkIfPackageBelongsToUid(
2952 mAppOpsManager,
2953 uid,
2954 mCurIntent.getComponent().getPackageName())) {
2955 return true;
2956 } else if (mContext.checkCallingPermission(
2957 android.Manifest.permission.WRITE_SECURE_SETTINGS)
2958 == PackageManager.PERMISSION_GRANTED) {
2959 return true;
2960 }
2961
2962 return false;
2963 }
2964
satok42c5a162011-05-26 16:46:14 +09002965 @Override
Seigo Nonaka14e13912015-05-06 21:04:13 -07002966 public void showInputMethodPickerFromClient(
2967 IInputMethodClient client, int auxiliarySubtypeMode) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002968 if (!calledFromValidUser()) {
2969 return;
2970 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 synchronized (mMethodMap) {
Guliz Tuncay6908c152017-06-02 16:06:10 -07002972 if(!canShowInputMethodPickerLocked(client)) {
satok47a44912010-10-06 16:03:58 +09002973 Slog.w(TAG, "Ignoring showInputMethodPickerFromClient of uid "
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002974 + Binder.getCallingUid() + ": " + client);
Guliz Tuncay6908c152017-06-02 16:06:10 -07002975 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976 }
2977
satok440aab52010-11-25 09:43:11 +09002978 // Always call subtype picker, because subtype picker is a superset of input method
2979 // picker.
Seigo Nonaka14e13912015-05-06 21:04:13 -07002980 mHandler.sendMessage(mCaller.obtainMessageI(
2981 MSG_SHOW_IM_SUBTYPE_PICKER, auxiliarySubtypeMode));
satokab751aa2010-09-14 19:17:36 +09002982 }
2983 }
2984
Tarandeep Singheb570612018-01-29 16:20:32 -08002985 public boolean isInputMethodPickerShownForTest() {
2986 synchronized(mMethodMap) {
2987 if (mSwitchingDialog == null) {
2988 return false;
2989 }
2990 return mSwitchingDialog.isShowing();
2991 }
2992 }
2993
satok42c5a162011-05-26 16:46:14 +09002994 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002995 public void setInputMethod(IBinder token, String id) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002996 if (!calledFromValidUser()) {
2997 return;
2998 }
satok28203512010-11-24 11:06:49 +09002999 setInputMethodWithSubtypeId(token, id, NOT_A_SUBTYPE_ID);
3000 }
3001
satok42c5a162011-05-26 16:46:14 +09003002 @Override
satok28203512010-11-24 11:06:49 +09003003 public void setInputMethodAndSubtype(IBinder token, String id, InputMethodSubtype subtype) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003004 if (!calledFromValidUser()) {
3005 return;
3006 }
satok28203512010-11-24 11:06:49 +09003007 synchronized (mMethodMap) {
3008 if (subtype != null) {
Yohei Yukawa4e02bc62014-06-04 18:37:20 +09003009 setInputMethodWithSubtypeIdLocked(token, id,
3010 InputMethodUtils.getSubtypeIdFromHashCode(mMethodMap.get(id),
3011 subtype.hashCode()));
satok28203512010-11-24 11:06:49 +09003012 } else {
3013 setInputMethod(token, id);
3014 }
3015 }
satokab751aa2010-09-14 19:17:36 +09003016 }
3017
satok42c5a162011-05-26 16:46:14 +09003018 @Override
satokb416a712010-11-25 20:42:14 +09003019 public void showInputMethodAndSubtypeEnablerFromClient(
satok217f5482010-12-15 05:19:19 +09003020 IInputMethodClient client, String inputMethodId) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003021 if (!calledFromValidUser()) {
3022 return;
3023 }
satokb416a712010-11-25 20:42:14 +09003024 synchronized (mMethodMap) {
satok7fee71f2010-12-17 18:54:26 +09003025 executeOrSendMessage(mCurMethod, mCaller.obtainMessageO(
3026 MSG_SHOW_IM_SUBTYPE_ENABLER, inputMethodId));
satokb416a712010-11-25 20:42:14 +09003027 }
3028 }
3029
satok4fc87d62011-05-20 16:13:43 +09003030 @Override
Tarandeep Singh164cfba2018-02-28 14:17:43 -08003031 public boolean switchToPreviousInputMethod(IBinder token) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003032 if (!calledFromValidUser()) {
3033 return false;
3034 }
satok735cf382010-11-11 20:40:09 +09003035 synchronized (mMethodMap) {
satokc445bcd2011-01-25 18:57:24 +09003036 final Pair<String, String> lastIme = mSettings.getLastInputMethodAndSubtypeLocked();
satok4fc87d62011-05-20 16:13:43 +09003037 final InputMethodInfo lastImi;
satok208d5632011-05-20 22:13:38 +09003038 if (lastIme != null) {
satok4fc87d62011-05-20 16:13:43 +09003039 lastImi = mMethodMap.get(lastIme.first);
3040 } else {
3041 lastImi = null;
satok735cf382010-11-11 20:40:09 +09003042 }
satok4fc87d62011-05-20 16:13:43 +09003043 String targetLastImiId = null;
3044 int subtypeId = NOT_A_SUBTYPE_ID;
3045 if (lastIme != null && lastImi != null) {
3046 final boolean imiIdIsSame = lastImi.getId().equals(mCurMethodId);
Narayan Kamatha09b4d22016-04-15 18:32:45 +01003047 final int lastSubtypeHash = Integer.parseInt(lastIme.second);
satok4fc87d62011-05-20 16:13:43 +09003048 final int currentSubtypeHash = mCurrentSubtype == null ? NOT_A_SUBTYPE_ID
3049 : mCurrentSubtype.hashCode();
3050 // If the last IME is the same as the current IME and the last subtype is not
3051 // defined, there is no need to switch to the last IME.
3052 if (!imiIdIsSame || lastSubtypeHash != currentSubtypeHash) {
3053 targetLastImiId = lastIme.first;
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003054 subtypeId = InputMethodUtils.getSubtypeIdFromHashCode(lastImi, lastSubtypeHash);
satok4fc87d62011-05-20 16:13:43 +09003055 }
3056 }
3057
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003058 if (TextUtils.isEmpty(targetLastImiId)
3059 && !InputMethodUtils.canAddToLastInputMethod(mCurrentSubtype)) {
satok4fc87d62011-05-20 16:13:43 +09003060 // This is a safety net. If the currentSubtype can't be added to the history
3061 // and the framework couldn't find the last ime, we will make the last ime be
3062 // the most applicable enabled keyboard subtype of the system imes.
3063 final List<InputMethodInfo> enabled = mSettings.getEnabledInputMethodListLocked();
3064 if (enabled != null) {
3065 final int N = enabled.size();
3066 final String locale = mCurrentSubtype == null
3067 ? mRes.getConfiguration().locale.toString()
3068 : mCurrentSubtype.getLocale();
3069 for (int i = 0; i < N; ++i) {
3070 final InputMethodInfo imi = enabled.get(i);
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003071 if (imi.getSubtypeCount() > 0 && InputMethodUtils.isSystemIme(imi)) {
satok4fc87d62011-05-20 16:13:43 +09003072 InputMethodSubtype keyboardSubtype =
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003073 InputMethodUtils.findLastResortApplicableSubtypeLocked(mRes,
3074 InputMethodUtils.getSubtypes(imi),
3075 InputMethodUtils.SUBTYPE_MODE_KEYBOARD, locale, true);
satok4fc87d62011-05-20 16:13:43 +09003076 if (keyboardSubtype != null) {
3077 targetLastImiId = imi.getId();
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003078 subtypeId = InputMethodUtils.getSubtypeIdFromHashCode(
satok4fc87d62011-05-20 16:13:43 +09003079 imi, keyboardSubtype.hashCode());
3080 if(keyboardSubtype.getLocale().equals(locale)) {
3081 break;
3082 }
3083 }
3084 }
3085 }
3086 }
3087 }
3088
3089 if (!TextUtils.isEmpty(targetLastImiId)) {
3090 if (DEBUG) {
3091 Slog.d(TAG, "Switch to: " + lastImi.getId() + ", " + lastIme.second
3092 + ", from: " + mCurMethodId + ", " + subtypeId);
3093 }
Yohei Yukawa4e02bc62014-06-04 18:37:20 +09003094 setInputMethodWithSubtypeIdLocked(token, targetLastImiId, subtypeId);
satok4fc87d62011-05-20 16:13:43 +09003095 return true;
3096 } else {
3097 return false;
3098 }
satok735cf382010-11-11 20:40:09 +09003099 }
3100 }
3101
satoke7c6998e2011-06-03 17:57:59 +09003102 @Override
satok688bd472012-02-09 20:09:17 +09003103 public boolean switchToNextInputMethod(IBinder token, boolean onlyCurrentIme) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003104 if (!calledFromValidUser()) {
3105 return false;
3106 }
satok688bd472012-02-09 20:09:17 +09003107 synchronized (mMethodMap) {
Yohei Yukawaa0755742014-06-04 20:28:18 +09003108 if (!calledWithValidToken(token)) {
Yohei Yukawaa0755742014-06-04 20:28:18 +09003109 return false;
3110 }
Yohei Yukawa5a647b692014-05-22 12:49:00 +09003111 final ImeSubtypeListItem nextSubtype = mSwitchingController.getNextInputMethodLocked(
Yohei Yukawad39ae852016-04-10 20:28:40 -07003112 onlyCurrentIme, mMethodMap.get(mCurMethodId), mCurrentSubtype,
3113 true /* forward */);
satok688bd472012-02-09 20:09:17 +09003114 if (nextSubtype == null) {
3115 return false;
3116 }
Yohei Yukawa4e02bc62014-06-04 18:37:20 +09003117 setInputMethodWithSubtypeIdLocked(token, nextSubtype.mImi.getId(),
3118 nextSubtype.mSubtypeId);
satok688bd472012-02-09 20:09:17 +09003119 return true;
3120 }
3121 }
3122
3123 @Override
Satoshi Kataoka2b10b522013-08-21 20:39:12 +09003124 public boolean shouldOfferSwitchingToNextInputMethod(IBinder token) {
3125 if (!calledFromValidUser()) {
3126 return false;
3127 }
3128 synchronized (mMethodMap) {
Yohei Yukawaa0755742014-06-04 20:28:18 +09003129 if (!calledWithValidToken(token)) {
Yohei Yukawaa0755742014-06-04 20:28:18 +09003130 return false;
3131 }
Yohei Yukawa5a647b692014-05-22 12:49:00 +09003132 final ImeSubtypeListItem nextSubtype = mSwitchingController.getNextInputMethodLocked(
Yohei Yukawad39ae852016-04-10 20:28:40 -07003133 false /* onlyCurrentIme */, mMethodMap.get(mCurMethodId), mCurrentSubtype,
3134 true /* forward */);
Satoshi Kataoka2b10b522013-08-21 20:39:12 +09003135 if (nextSubtype == null) {
3136 return false;
3137 }
3138 return true;
3139 }
3140 }
3141
3142 @Override
satok68f1b782011-04-11 14:26:04 +09003143 public InputMethodSubtype getLastInputMethodSubtype() {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003144 if (!calledFromValidUser()) {
3145 return null;
3146 }
satok68f1b782011-04-11 14:26:04 +09003147 synchronized (mMethodMap) {
3148 final Pair<String, String> lastIme = mSettings.getLastInputMethodAndSubtypeLocked();
3149 // TODO: Handle the case of the last IME with no subtypes
3150 if (lastIme == null || TextUtils.isEmpty(lastIme.first)
3151 || TextUtils.isEmpty(lastIme.second)) return null;
3152 final InputMethodInfo lastImi = mMethodMap.get(lastIme.first);
3153 if (lastImi == null) return null;
3154 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01003155 final int lastSubtypeHash = Integer.parseInt(lastIme.second);
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003156 final int lastSubtypeId =
3157 InputMethodUtils.getSubtypeIdFromHashCode(lastImi, lastSubtypeHash);
satok0e7d7d62011-07-05 13:28:06 +09003158 if (lastSubtypeId < 0 || lastSubtypeId >= lastImi.getSubtypeCount()) {
3159 return null;
3160 }
3161 return lastImi.getSubtypeAt(lastSubtypeId);
satok68f1b782011-04-11 14:26:04 +09003162 } catch (NumberFormatException e) {
3163 return null;
3164 }
3165 }
3166 }
3167
satoke7c6998e2011-06-03 17:57:59 +09003168 @Override
satokee5e77c2011-09-02 18:50:15 +09003169 public void setAdditionalInputMethodSubtypes(String imiId, InputMethodSubtype[] subtypes) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003170 if (!calledFromValidUser()) {
3171 return;
3172 }
satok91e88122011-07-18 11:11:42 +09003173 // By this IPC call, only a process which shares the same uid with the IME can add
3174 // additional input method subtypes to the IME.
Yohei Yukawa70f5c482016-01-04 19:42:36 -08003175 if (TextUtils.isEmpty(imiId) || subtypes == null) return;
satoke7c6998e2011-06-03 17:57:59 +09003176 synchronized (mMethodMap) {
Yohei Yukawa79247822017-01-23 15:26:15 -08003177 if (!mSystemReady) {
3178 return;
3179 }
satok91e88122011-07-18 11:11:42 +09003180 final InputMethodInfo imi = mMethodMap.get(imiId);
satokee5e77c2011-09-02 18:50:15 +09003181 if (imi == null) return;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003182 final String[] packageInfos;
3183 try {
3184 packageInfos = mIPackageManager.getPackagesForUid(Binder.getCallingUid());
3185 } catch (RemoteException e) {
3186 Slog.e(TAG, "Failed to get package infos");
3187 return;
3188 }
satok91e88122011-07-18 11:11:42 +09003189 if (packageInfos != null) {
3190 final int packageNum = packageInfos.length;
3191 for (int i = 0; i < packageNum; ++i) {
3192 if (packageInfos[i].equals(imi.getPackageName())) {
3193 mFileManager.addInputMethodSubtypes(imi, subtypes);
satokc5933802011-08-31 21:26:04 +09003194 final long ident = Binder.clearCallingIdentity();
3195 try {
Yohei Yukawa94e33302016-02-12 19:37:03 -08003196 buildInputMethodListLocked(false /* resetDefaultEnabledIme */);
satokc5933802011-08-31 21:26:04 +09003197 } finally {
3198 Binder.restoreCallingIdentity(ident);
3199 }
satokee5e77c2011-09-02 18:50:15 +09003200 return;
satok91e88122011-07-18 11:11:42 +09003201 }
3202 }
3203 }
satoke7c6998e2011-06-03 17:57:59 +09003204 }
satokee5e77c2011-09-02 18:50:15 +09003205 return;
satoke7c6998e2011-06-03 17:57:59 +09003206 }
3207
Satoshi Kataoka658c7b82013-10-10 17:03:51 +09003208 @Override
3209 public int getInputMethodWindowVisibleHeight() {
Seigo Nonaka7309b122015-08-17 18:34:13 -07003210 return mWindowManagerInternal.getInputMethodWindowVisibleHeight();
Satoshi Kataoka658c7b82013-10-10 17:03:51 +09003211 }
3212
Satoshi Kataokad7443c82013-10-15 17:45:43 +09003213 @Override
Yohei Yukawa833bdce2016-05-15 20:05:56 -07003214 public void clearLastInputMethodWindowForTransition(IBinder token) {
3215 if (!calledFromValidUser()) {
3216 return;
3217 }
Yohei Yukawafa49c002017-01-31 19:15:00 -08003218 synchronized (mMethodMap) {
3219 if (!calledWithValidToken(token)) {
Yohei Yukawafa49c002017-01-31 19:15:00 -08003220 return;
Yohei Yukawa833bdce2016-05-15 20:05:56 -07003221 }
Yohei Yukawa833bdce2016-05-15 20:05:56 -07003222 }
Yohei Yukawafa49c002017-01-31 19:15:00 -08003223 mWindowManagerInternal.clearLastInputMethodWindowForTransition();
Yohei Yukawa833bdce2016-05-15 20:05:56 -07003224 }
3225
3226 @Override
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003227 public void notifyUserAction(int sequenceNumber) {
Satoshi Kataokad7443c82013-10-15 17:45:43 +09003228 if (DEBUG) {
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003229 Slog.d(TAG, "Got the notification of a user action. sequenceNumber:" + sequenceNumber);
Satoshi Kataokad7443c82013-10-15 17:45:43 +09003230 }
Yohei Yukawa5a647b692014-05-22 12:49:00 +09003231 synchronized (mMethodMap) {
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003232 if (mCurUserActionNotificationSequenceNumber != sequenceNumber) {
3233 if (DEBUG) {
3234 Slog.d(TAG, "Ignoring the user action notification due to the sequence number "
3235 + "mismatch. expected:" + mCurUserActionNotificationSequenceNumber
3236 + " actual: " + sequenceNumber);
3237 }
3238 return;
3239 }
Yohei Yukawa5a647b692014-05-22 12:49:00 +09003240 final InputMethodInfo imi = mMethodMap.get(mCurMethodId);
3241 if (imi != null) {
Yohei Yukawa02970512014-06-05 16:16:18 +09003242 mSwitchingController.onUserActionLocked(imi, mCurrentSubtype);
Yohei Yukawa5a647b692014-05-22 12:49:00 +09003243 }
Satoshi Kataokad7443c82013-10-15 17:45:43 +09003244 }
3245 }
3246
satok28203512010-11-24 11:06:49 +09003247 private void setInputMethodWithSubtypeId(IBinder token, String id, int subtypeId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003248 synchronized (mMethodMap) {
Yohei Yukawa4e02bc62014-06-04 18:37:20 +09003249 setInputMethodWithSubtypeIdLocked(token, id, subtypeId);
3250 }
3251 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003252
Yohei Yukawa4e02bc62014-06-04 18:37:20 +09003253 private void setInputMethodWithSubtypeIdLocked(IBinder token, String id, int subtypeId) {
3254 if (token == null) {
3255 if (mContext.checkCallingOrSelfPermission(
3256 android.Manifest.permission.WRITE_SECURE_SETTINGS)
3257 != PackageManager.PERMISSION_GRANTED) {
3258 throw new SecurityException(
3259 "Using null token requires permission "
3260 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003261 }
Yohei Yukawa4e02bc62014-06-04 18:37:20 +09003262 } else if (mCurToken != token) {
3263 Slog.w(TAG, "Ignoring setInputMethod of uid " + Binder.getCallingUid()
3264 + " token: " + token);
3265 return;
3266 }
3267
3268 final long ident = Binder.clearCallingIdentity();
3269 try {
3270 setInputMethodLocked(id, subtypeId);
3271 } finally {
3272 Binder.restoreCallingIdentity(ident);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003273 }
3274 }
3275
satok42c5a162011-05-26 16:46:14 +09003276 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003277 public void hideMySoftInput(IBinder token, int flags) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003278 if (!calledFromValidUser()) {
3279 return;
3280 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003281 synchronized (mMethodMap) {
Yohei Yukawa22c97be2014-06-04 19:43:36 +09003282 if (!calledWithValidToken(token)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003283 return;
3284 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285 long ident = Binder.clearCallingIdentity();
3286 try {
The Android Open Source Project4df24232009-03-05 14:34:35 -08003287 hideCurrentInputLocked(flags, null);
3288 } finally {
3289 Binder.restoreCallingIdentity(ident);
3290 }
3291 }
3292 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003293
satok42c5a162011-05-26 16:46:14 +09003294 @Override
The Android Open Source Project4df24232009-03-05 14:34:35 -08003295 public void showMySoftInput(IBinder token, int flags) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003296 if (!calledFromValidUser()) {
3297 return;
3298 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08003299 synchronized (mMethodMap) {
Yohei Yukawa22c97be2014-06-04 19:43:36 +09003300 if (!calledWithValidToken(token)) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08003301 return;
3302 }
3303 long ident = Binder.clearCallingIdentity();
3304 try {
3305 showCurrentInputLocked(flags, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306 } finally {
3307 Binder.restoreCallingIdentity(ident);
3308 }
3309 }
3310 }
3311
3312 void setEnabledSessionInMainThread(SessionState session) {
3313 if (mEnabledSession != session) {
Yohei Yukawa9d91b432014-05-19 16:03:24 +09003314 if (mEnabledSession != null && mEnabledSession.session != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003315 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003316 if (DEBUG) Slog.v(TAG, "Disabling: " + mEnabledSession);
Yohei Yukawa9d91b432014-05-19 16:03:24 +09003317 mEnabledSession.method.setSessionEnabled(mEnabledSession.session, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003318 } catch (RemoteException e) {
3319 }
3320 }
3321 mEnabledSession = session;
Yohei Yukawa9d91b432014-05-19 16:03:24 +09003322 if (mEnabledSession != null && mEnabledSession.session != null) {
3323 try {
3324 if (DEBUG) Slog.v(TAG, "Enabling: " + mEnabledSession);
3325 mEnabledSession.method.setSessionEnabled(mEnabledSession.session, true);
3326 } catch (RemoteException e) {
3327 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003328 }
3329 }
3330 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003331
Yohei Yukawa930328c2017-10-18 20:19:53 -07003332 @MainThread
satok42c5a162011-05-26 16:46:14 +09003333 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003334 public boolean handleMessage(Message msg) {
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003335 SomeArgs args;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003336 switch (msg.what) {
satokab751aa2010-09-14 19:17:36 +09003337 case MSG_SHOW_IM_SUBTYPE_PICKER:
Seigo Nonaka14e13912015-05-06 21:04:13 -07003338 final boolean showAuxSubtypes;
3339 switch (msg.arg1) {
3340 case InputMethodManager.SHOW_IM_PICKER_MODE_AUTO:
3341 // This is undocumented so far, but IMM#showInputMethodPicker() has been
3342 // implemented so that auxiliary subtypes will be excluded when the soft
3343 // keyboard is invisible.
3344 showAuxSubtypes = mInputShown;
3345 break;
3346 case InputMethodManager.SHOW_IM_PICKER_MODE_INCLUDE_AUXILIARY_SUBTYPES:
3347 showAuxSubtypes = true;
3348 break;
3349 case InputMethodManager.SHOW_IM_PICKER_MODE_EXCLUDE_AUXILIARY_SUBTYPES:
3350 showAuxSubtypes = false;
3351 break;
3352 default:
3353 Slog.e(TAG, "Unknown subtype picker mode = " + msg.arg1);
3354 return false;
3355 }
3356 showInputMethodMenu(showAuxSubtypes);
satokab751aa2010-09-14 19:17:36 +09003357 return true;
3358
satok47a44912010-10-06 16:03:58 +09003359 case MSG_SHOW_IM_SUBTYPE_ENABLER:
Yohei Yukawa41f34272015-12-14 15:41:52 -08003360 showInputMethodAndSubtypeEnabler((String)msg.obj);
satok217f5482010-12-15 05:19:19 +09003361 return true;
3362
3363 case MSG_SHOW_IM_CONFIG:
3364 showConfigureInputMethods();
satok47a44912010-10-06 16:03:58 +09003365 return true;
3366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003367 // ---------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 case MSG_UNBIND_INPUT:
3370 try {
3371 ((IInputMethod)msg.obj).unbindInput();
3372 } catch (RemoteException e) {
3373 // There is nothing interesting about the method dying.
3374 }
3375 return true;
3376 case MSG_BIND_INPUT:
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003377 args = (SomeArgs)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003378 try {
3379 ((IInputMethod)args.arg1).bindInput((InputBinding)args.arg2);
3380 } catch (RemoteException e) {
3381 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003382 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003383 return true;
3384 case MSG_SHOW_SOFT_INPUT:
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003385 args = (SomeArgs)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003386 try {
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07003387 if (DEBUG) Slog.v(TAG, "Calling " + args.arg1 + ".showSoftInput("
Craig Mautner6efb4c72013-03-13 10:17:41 -07003388 + msg.arg1 + ", " + args.arg2 + ")");
Craig Mautnerca0ac712013-03-14 09:43:02 -07003389 ((IInputMethod)args.arg1).showSoftInput(msg.arg1, (ResultReceiver)args.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003390 } catch (RemoteException e) {
3391 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003392 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 return true;
3394 case MSG_HIDE_SOFT_INPUT:
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003395 args = (SomeArgs)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003396 try {
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07003397 if (DEBUG) Slog.v(TAG, "Calling " + args.arg1 + ".hideSoftInput(0, "
Craig Mautner6efb4c72013-03-13 10:17:41 -07003398 + args.arg2 + ")");
Craig Mautnerca0ac712013-03-14 09:43:02 -07003399 ((IInputMethod)args.arg1).hideSoftInput(0, (ResultReceiver)args.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003400 } catch (RemoteException e) {
3401 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003402 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003403 return true;
Jorim Jaggi3c5d0f12016-05-24 19:04:30 -07003404 case MSG_HIDE_CURRENT_INPUT_METHOD:
3405 synchronized (mMethodMap) {
3406 hideCurrentInputLocked(0, null);
3407 }
3408 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003409 case MSG_ATTACH_TOKEN:
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003410 args = (SomeArgs)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003411 try {
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07003412 if (DEBUG) Slog.v(TAG, "Sending attach of token: " + args.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003413 ((IInputMethod)args.arg1).attachToken((IBinder)args.arg2);
3414 } catch (RemoteException e) {
3415 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003416 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003417 return true;
Jeff Brownc28867a2013-03-26 15:42:39 -07003418 case MSG_CREATE_SESSION: {
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003419 args = (SomeArgs)msg.obj;
Jeff Brown1951ce82013-04-04 22:45:12 -07003420 IInputMethod method = (IInputMethod)args.arg1;
Jeff Brownc28867a2013-03-26 15:42:39 -07003421 InputChannel channel = (InputChannel)args.arg2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003422 try {
Jeff Brown1951ce82013-04-04 22:45:12 -07003423 method.createSession(channel, (IInputSessionCallback)args.arg3);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003424 } catch (RemoteException e) {
Jeff Brownc28867a2013-03-26 15:42:39 -07003425 } finally {
Jeff Brown1951ce82013-04-04 22:45:12 -07003426 // Dispose the channel if the input method is not local to this process
3427 // because the remote proxy will get its own copy when unparceled.
3428 if (channel != null && Binder.isProxy(method)) {
Jeff Brownc28867a2013-03-26 15:42:39 -07003429 channel.dispose();
3430 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003432 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003433 return true;
Jeff Brownc28867a2013-03-26 15:42:39 -07003434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 // ---------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003436
Yohei Yukawa19a80a12016-03-14 22:57:37 -07003437 case MSG_START_INPUT: {
Yohei Yukawaf7526b52017-02-11 20:57:10 -08003438 final int missingMethods = msg.arg1;
3439 final boolean restarting = msg.arg2 != 0;
Yohei Yukawa19a80a12016-03-14 22:57:37 -07003440 args = (SomeArgs) msg.obj;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08003441 final IBinder startInputToken = (IBinder) args.arg1;
3442 final SessionState session = (SessionState) args.arg2;
3443 final IInputContext inputContext = (IInputContext) args.arg3;
3444 final EditorInfo editorInfo = (EditorInfo) args.arg4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003445 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003446 setEnabledSessionInMainThread(session);
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08003447 session.method.startInput(startInputToken, inputContext, missingMethods,
3448 editorInfo, restarting);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003449 } catch (RemoteException e) {
3450 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003451 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003452 return true;
Yohei Yukawa19a80a12016-03-14 22:57:37 -07003453 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003455 // ---------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003456
Yohei Yukawa33e81792015-11-17 21:14:42 -08003457 case MSG_UNBIND_CLIENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003458 try {
Yohei Yukawa33e81792015-11-17 21:14:42 -08003459 ((IInputMethodClient)msg.obj).onUnbindMethod(msg.arg1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003460 } catch (RemoteException e) {
3461 // There is nothing interesting about the last client dying.
3462 }
3463 return true;
Yohei Yukawa33e81792015-11-17 21:14:42 -08003464 case MSG_BIND_CLIENT: {
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003465 args = (SomeArgs)msg.obj;
Jeff Brown1951ce82013-04-04 22:45:12 -07003466 IInputMethodClient client = (IInputMethodClient)args.arg1;
3467 InputBindResult res = (InputBindResult)args.arg2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468 try {
Jeff Brown1951ce82013-04-04 22:45:12 -07003469 client.onBindMethod(res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003470 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003471 Slog.w(TAG, "Client died receiving input method " + args.arg2);
Jeff Brown1951ce82013-04-04 22:45:12 -07003472 } finally {
3473 // Dispose the channel if the input method is not local to this process
3474 // because the remote proxy will get its own copy when unparceled.
3475 if (res.channel != null && Binder.isProxy(client)) {
3476 res.channel.dispose();
3477 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003478 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003479 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003480 return true;
Jeff Brown1951ce82013-04-04 22:45:12 -07003481 }
Dianne Hackborna6e41342012-05-22 16:30:34 -07003482 case MSG_SET_ACTIVE:
3483 try {
Yohei Yukawa2bc66172017-02-08 11:13:25 -08003484 ((ClientState)msg.obj).client.setActive(msg.arg1 != 0, msg.arg2 != 0);
Dianne Hackborna6e41342012-05-22 16:30:34 -07003485 } catch (RemoteException e) {
3486 Slog.w(TAG, "Got RemoteException sending setActive(false) notification to pid "
3487 + ((ClientState)msg.obj).pid + " uid "
3488 + ((ClientState)msg.obj).uid);
3489 }
3490 return true;
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07003491 case MSG_SET_INTERACTIVE:
3492 handleSetInteractive(msg.arg1 != 0);
3493 return true;
Tarandeep Singh89a6c482017-11-21 14:26:11 -08003494 case MSG_START_VR_INPUT:
3495 startVrInputMethodNoCheck((ComponentName) msg.obj);
3496 return true;
Yohei Yukawaae61f712015-12-09 13:00:10 -08003497 case MSG_SWITCH_IME:
3498 handleSwitchInputMethod(msg.arg1 != 0);
3499 return true;
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003500 case MSG_SET_USER_ACTION_NOTIFICATION_SEQUENCE_NUMBER: {
3501 final int sequenceNumber = msg.arg1;
Yohei Yukawa080fa342014-08-31 16:10:05 -07003502 final ClientState clientState = (ClientState)msg.obj;
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003503 try {
Yohei Yukawa080fa342014-08-31 16:10:05 -07003504 clientState.client.setUserActionNotificationSequenceNumber(sequenceNumber);
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003505 } catch (RemoteException e) {
3506 Slog.w(TAG, "Got RemoteException sending "
3507 + "setUserActionNotificationSequenceNumber("
3508 + sequenceNumber + ") notification to pid "
Yohei Yukawa080fa342014-08-31 16:10:05 -07003509 + clientState.pid + " uid "
3510 + clientState.uid);
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003511 }
3512 return true;
3513 }
Yohei Yukawa2bc66172017-02-08 11:13:25 -08003514 case MSG_REPORT_FULLSCREEN_MODE: {
3515 final boolean fullscreen = msg.arg1 != 0;
3516 final ClientState clientState = (ClientState)msg.obj;
3517 try {
3518 clientState.client.reportFullscreenMode(fullscreen);
3519 } catch (RemoteException e) {
3520 Slog.w(TAG, "Got RemoteException sending "
3521 + "reportFullscreen(" + fullscreen + ") notification to pid="
3522 + clientState.pid + " uid=" + clientState.uid);
3523 }
3524 return true;
3525 }
satok01038492012-04-09 21:08:27 +09003526
3527 // --------------------------------------------------------------
3528 case MSG_HARD_KEYBOARD_SWITCH_CHANGED:
Michael Wright7b5a96b2014-08-09 19:28:42 -07003529 mHardKeyboardListener.handleHardKeyboardStatusChange(msg.arg1 == 1);
satok01038492012-04-09 21:08:27 +09003530 return true;
Fyodor Kupolov7877b8a2016-06-29 14:39:19 -07003531 case MSG_SYSTEM_UNLOCK_USER:
3532 final int userId = msg.arg1;
3533 onUnlockUser(userId);
3534 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003535 }
3536 return false;
3537 }
3538
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07003539 private void handleSetInteractive(final boolean interactive) {
3540 synchronized (mMethodMap) {
3541 mIsInteractive = interactive;
3542 updateSystemUiLocked(mCurToken, interactive ? mImeWindowVis : 0, mBackDisposition);
3543
3544 // Inform the current client of the change in active status
3545 if (mCurClient != null && mCurClient.client != null) {
Yohei Yukawa2bc66172017-02-08 11:13:25 -08003546 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIIO(
3547 MSG_SET_ACTIVE, mIsInteractive ? 1 : 0, mInFullscreenMode ? 1 : 0,
3548 mCurClient));
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07003549 }
3550 }
3551 }
3552
Yohei Yukawaae61f712015-12-09 13:00:10 -08003553 private void handleSwitchInputMethod(final boolean forwardDirection) {
3554 synchronized (mMethodMap) {
Yohei Yukawaae61f712015-12-09 13:00:10 -08003555 final ImeSubtypeListItem nextSubtype = mSwitchingController.getNextInputMethodLocked(
Yohei Yukawad39ae852016-04-10 20:28:40 -07003556 false, mMethodMap.get(mCurMethodId), mCurrentSubtype, forwardDirection);
Yohei Yukawaae61f712015-12-09 13:00:10 -08003557 if (nextSubtype == null) {
3558 return;
3559 }
3560 setInputMethodLocked(nextSubtype.mImi.getId(), nextSubtype.mSubtypeId);
Yohei Yukawaebda7d72016-04-02 17:39:23 -07003561 final InputMethodInfo newInputMethodInfo = mMethodMap.get(mCurMethodId);
3562 if (newInputMethodInfo == null) {
3563 return;
3564 }
3565 final CharSequence toastText = InputMethodUtils.getImeAndSubtypeDisplayName(mContext,
3566 newInputMethodInfo, mCurrentSubtype);
3567 if (!TextUtils.isEmpty(toastText)) {
Yohei Yukawab2f901a2016-04-12 01:19:31 -07003568 if (mSubtypeSwitchedByShortCutToast == null) {
3569 mSubtypeSwitchedByShortCutToast = Toast.makeText(mContext, toastText,
3570 Toast.LENGTH_SHORT);
3571 } else {
3572 mSubtypeSwitchedByShortCutToast.setText(toastText);
3573 }
Yohei Yukawaebda7d72016-04-02 17:39:23 -07003574 mSubtypeSwitchedByShortCutToast.show();
3575 }
Yohei Yukawaae61f712015-12-09 13:00:10 -08003576 }
3577 }
3578
satokdc9ddae2011-10-06 12:22:36 +09003579 private boolean chooseNewDefaultIMELocked() {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003580 final InputMethodInfo imi = InputMethodUtils.getMostApplicableDefaultIME(
3581 mSettings.getEnabledInputMethodListLocked());
satokdc9ddae2011-10-06 12:22:36 +09003582 if (imi != null) {
satok03eb319a2010-11-11 18:17:42 +09003583 if (DEBUG) {
3584 Slog.d(TAG, "New default IME was selected: " + imi.getId());
3585 }
satok723a27e2010-11-11 14:58:11 +09003586 resetSelectedInputMethodAndSubtypeLocked(imi.getId());
Brandon Ballinger6da35a02009-10-21 00:38:13 -07003587 return true;
3588 }
3589
3590 return false;
3591 }
3592
Andreas Gampea36dc622018-02-05 17:19:22 -08003593 @GuardedBy("mMethodMap")
Yohei Yukawa94e33302016-02-12 19:37:03 -08003594 void buildInputMethodListLocked(boolean resetDefaultEnabledIme) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003595 if (DEBUG) {
Satoshi Kataokaf1367b72013-01-25 17:20:12 +09003596 Slog.d(TAG, "--- re-buildInputMethodList reset = " + resetDefaultEnabledIme
Seigo Nonakae27dc2b2015-08-14 18:21:27 -07003597 + " \n ------ caller=" + Debug.getCallers(10));
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003598 }
Yohei Yukawa79247822017-01-23 15:26:15 -08003599 if (!mSystemReady) {
3600 Slog.e(TAG, "buildInputMethodListLocked is not allowed until system is ready");
3601 return;
3602 }
Yohei Yukawa94e33302016-02-12 19:37:03 -08003603 mMethodList.clear();
3604 mMethodMap.clear();
Yohei Yukawae0733062017-02-09 22:49:35 -08003605 mMethodMapUpdateCount++;
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08003606 mMyPackageMonitor.clearKnownImePackageNamesLocked();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003607
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003608 // Use for queryIntentServicesAsUser
3609 final PackageManager pm = mContext.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003610
Yohei Yukawaed4952a2016-02-17 07:57:25 -08003611 // Note: We do not specify PackageManager.MATCH_ENCRYPTION_* flags here because the default
3612 // behavior of PackageManager is exactly what we want. It by default picks up appropriate
3613 // services depending on the unlock state for the specified user.
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003614 final List<ResolveInfo> services = pm.queryIntentServicesAsUser(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003615 new Intent(InputMethod.SERVICE_INTERFACE),
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08003616 PackageManager.GET_META_DATA | PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
3617 mSettings.getCurrentUserId());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003618
Yohei Yukawaddad4b92017-02-02 01:46:13 -08003619 final HashMap<String, List<InputMethodSubtype>> additionalSubtypeMap =
satoke7c6998e2011-06-03 17:57:59 +09003620 mFileManager.getAllAdditionalInputMethodSubtypes();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003621 for (int i = 0; i < services.size(); ++i) {
3622 ResolveInfo ri = services.get(i);
3623 ServiceInfo si = ri.serviceInfo;
Yohei Yukawaddad4b92017-02-02 01:46:13 -08003624 final String imeId = InputMethodInfo.computeId(ri);
3625 if (!android.Manifest.permission.BIND_INPUT_METHOD.equals(si.permission)) {
3626 Slog.w(TAG, "Skipping input method " + imeId
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003627 + ": it does not require the permission "
3628 + android.Manifest.permission.BIND_INPUT_METHOD);
3629 continue;
3630 }
3631
Yohei Yukawaddad4b92017-02-02 01:46:13 -08003632 if (DEBUG) Slog.d(TAG, "Checking " + imeId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003633
Yohei Yukawaddad4b92017-02-02 01:46:13 -08003634 final List<InputMethodSubtype> additionalSubtypes = additionalSubtypeMap.get(imeId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 try {
satoke7c6998e2011-06-03 17:57:59 +09003636 InputMethodInfo p = new InputMethodInfo(mContext, ri, additionalSubtypes);
Yohei Yukawa94e33302016-02-12 19:37:03 -08003637 mMethodList.add(p);
Amith Yamasanie861ec12010-03-24 21:39:27 -07003638 final String id = p.getId();
Yohei Yukawa94e33302016-02-12 19:37:03 -08003639 mMethodMap.put(id, p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003640
3641 if (DEBUG) {
Satoshi Kataokaf1367b72013-01-25 17:20:12 +09003642 Slog.d(TAG, "Found an input method " + p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003643 }
Tadashi G. Takaoka3c23d5b2016-09-16 11:41:07 +09003644 } catch (Exception e) {
Yohei Yukawaddad4b92017-02-02 01:46:13 -08003645 Slog.wtf(TAG, "Unable to load input method " + imeId, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003646 }
3647 }
Brandon Ballinger6da35a02009-10-21 00:38:13 -07003648
Yohei Yukawac4e44912017-02-09 19:30:22 -08003649 // Construct the set of possible IME packages for onPackageChanged() to avoid false
3650 // negatives when the package state remains to be the same but only the component state is
3651 // changed.
3652 {
3653 // Here we intentionally use PackageManager.MATCH_DISABLED_COMPONENTS since the purpose
3654 // of this query is to avoid false negatives. PackageManager.MATCH_ALL could be more
3655 // conservative, but it seems we cannot use it for now (Issue 35176630).
3656 final List<ResolveInfo> allInputMethodServices = pm.queryIntentServicesAsUser(
3657 new Intent(InputMethod.SERVICE_INTERFACE),
3658 PackageManager.MATCH_DISABLED_COMPONENTS, mSettings.getCurrentUserId());
3659 final int N = allInputMethodServices.size();
3660 for (int i = 0; i < N; ++i) {
3661 final ServiceInfo si = allInputMethodServices.get(i).serviceInfo;
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08003662 if (android.Manifest.permission.BIND_INPUT_METHOD.equals(si.permission)) {
3663 mMyPackageMonitor.addKnownImePackageNameLocked(si.packageName);
Yohei Yukawac4e44912017-02-09 19:30:22 -08003664 }
Yohei Yukawac4e44912017-02-09 19:30:22 -08003665 }
3666 }
3667
Yohei Yukawa9c372192018-03-20 22:54:56 -07003668 boolean reenableMinimumNonAuxSystemImes = false;
Yohei Yukawa859df052016-02-17 07:56:46 -08003669 // TODO: The following code should find better place to live.
3670 if (!resetDefaultEnabledIme) {
3671 boolean enabledImeFound = false;
Yohei Yukawa9c372192018-03-20 22:54:56 -07003672 boolean enabledNonAuxImeFound = false;
Yohei Yukawa859df052016-02-17 07:56:46 -08003673 final List<InputMethodInfo> enabledImes = mSettings.getEnabledInputMethodListLocked();
3674 final int N = enabledImes.size();
3675 for (int i = 0; i < N; ++i) {
3676 final InputMethodInfo imi = enabledImes.get(i);
3677 if (mMethodList.contains(imi)) {
3678 enabledImeFound = true;
Yohei Yukawa9c372192018-03-20 22:54:56 -07003679 if (!imi.isAuxiliaryIme()) {
3680 enabledNonAuxImeFound = true;
3681 break;
3682 }
Yohei Yukawa859df052016-02-17 07:56:46 -08003683 }
3684 }
3685 if (!enabledImeFound) {
Yohei Yukawad0332832017-02-01 13:59:43 -08003686 if (DEBUG) {
3687 Slog.i(TAG, "All the enabled IMEs are gone. Reset default enabled IMEs.");
3688 }
Yohei Yukawa859df052016-02-17 07:56:46 -08003689 resetDefaultEnabledIme = true;
3690 resetSelectedInputMethodAndSubtypeLocked("");
Yohei Yukawa9c372192018-03-20 22:54:56 -07003691 } else if (!enabledNonAuxImeFound) {
3692 if (DEBUG) {
3693 Slog.i(TAG, "All the enabled non-Aux IMEs are gone. Do partial reset.");
3694 }
3695 reenableMinimumNonAuxSystemImes = true;
Yohei Yukawa859df052016-02-17 07:56:46 -08003696 }
3697 }
3698
Yohei Yukawa9c372192018-03-20 22:54:56 -07003699 if (resetDefaultEnabledIme || reenableMinimumNonAuxSystemImes) {
Satoshi Kataokaf1367b72013-01-25 17:20:12 +09003700 final ArrayList<InputMethodInfo> defaultEnabledIme =
Yohei Yukawa9c372192018-03-20 22:54:56 -07003701 InputMethodUtils.getDefaultEnabledImes(mContext, mMethodList,
3702 reenableMinimumNonAuxSystemImes);
Yohei Yukawa68645a62016-02-17 07:54:20 -08003703 final int N = defaultEnabledIme.size();
3704 for (int i = 0; i < N; ++i) {
Satoshi Kataokaf1367b72013-01-25 17:20:12 +09003705 final InputMethodInfo imi = defaultEnabledIme.get(i);
3706 if (DEBUG) {
3707 Slog.d(TAG, "--- enable ime = " + imi);
3708 }
3709 setInputMethodEnabledLocked(imi.getId(), true);
3710 }
3711 }
3712
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003713 final String defaultImiId = mSettings.getSelectedInputMethod();
satok0a1bcf42012-05-16 19:26:31 +09003714 if (!TextUtils.isEmpty(defaultImiId)) {
Yohei Yukawa94e33302016-02-12 19:37:03 -08003715 if (!mMethodMap.containsKey(defaultImiId)) {
satok0a1bcf42012-05-16 19:26:31 +09003716 Slog.w(TAG, "Default IME is uninstalled. Choose new default IME.");
3717 if (chooseNewDefaultIMELocked()) {
Michael Wright7b5a96b2014-08-09 19:28:42 -07003718 updateInputMethodsFromSettingsLocked(true);
satok0a1bcf42012-05-16 19:26:31 +09003719 }
3720 } else {
3721 // Double check that the default IME is certainly enabled.
3722 setInputMethodEnabledLocked(defaultImiId, true);
Brandon Ballinger6da35a02009-10-21 00:38:13 -07003723 }
3724 }
Yohei Yukawa3d46bab2014-05-30 18:10:18 +09003725 // Here is not the perfect place to reset the switching controller. Ideally
3726 // mSwitchingController and mSettings should be able to share the same state.
3727 // TODO: Make sure that mSwitchingController and mSettings are sharing the
3728 // the same enabled IMEs list.
Yohei Yukawac834a252014-05-21 22:42:32 +09003729 mSwitchingController.resetCircularListLocked(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003730 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003732 // ----------------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003733
satok217f5482010-12-15 05:19:19 +09003734 private void showInputMethodAndSubtypeEnabler(String inputMethodId) {
Tadashi G. Takaokaf49688f2011-01-20 17:56:13 +09003735 Intent intent = new Intent(Settings.ACTION_INPUT_METHOD_SUBTYPE_SETTINGS);
satok47a44912010-10-06 16:03:58 +09003736 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
satok86417ea2010-10-27 14:11:03 +09003737 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
3738 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
satok7fee71f2010-12-17 18:54:26 +09003739 if (!TextUtils.isEmpty(inputMethodId)) {
Tadashi G. Takaoka25480202011-01-20 23:13:02 +09003740 intent.putExtra(Settings.EXTRA_INPUT_METHOD_ID, inputMethodId);
satok7fee71f2010-12-17 18:54:26 +09003741 }
Yohei Yukawa41f34272015-12-14 15:41:52 -08003742 final int userId;
3743 synchronized (mMethodMap) {
3744 userId = mSettings.getCurrentUserId();
3745 }
3746 mContext.startActivityAsUser(intent, null, UserHandle.of(userId));
satok217f5482010-12-15 05:19:19 +09003747 }
3748
3749 private void showConfigureInputMethods() {
3750 Intent intent = new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS);
3751 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
3752 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
3753 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Satoshi Kataoka3ba439d2012-10-05 18:30:13 +09003754 mContext.startActivityAsUser(intent, null, UserHandle.CURRENT);
satok47a44912010-10-06 16:03:58 +09003755 }
3756
satok2c93efc2012-04-02 19:33:47 +09003757 private boolean isScreenLocked() {
3758 return mKeyguardManager != null
3759 && mKeyguardManager.isKeyguardLocked() && mKeyguardManager.isKeyguardSecure();
3760 }
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003761
Seigo Nonaka14e13912015-05-06 21:04:13 -07003762 private void showInputMethodMenu(boolean showAuxSubtypes) {
3763 if (DEBUG) Slog.v(TAG, "Show switching menu. showAuxSubtypes=" + showAuxSubtypes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003764
satok2c93efc2012-04-02 19:33:47 +09003765 final boolean isScreenLocked = isScreenLocked();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003766
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003767 final String lastInputMethodId = mSettings.getSelectedInputMethod();
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003768 int lastInputMethodSubtypeId = mSettings.getSelectedInputMethodSubtypeId(lastInputMethodId);
Joe Onorato8a9b2202010-02-26 18:56:32 -08003769 if (DEBUG) Slog.v(TAG, "Current IME: " + lastInputMethodId);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003770
Dianne Hackborn8cf1bcd2010-03-16 13:06:10 -07003771 synchronized (mMethodMap) {
satokbb4aa062011-01-19 21:40:27 +09003772 final HashMap<InputMethodInfo, List<InputMethodSubtype>> immis =
Satoshi Kataokad787f692013-10-26 04:44:21 +09003773 mSettings.getExplicitlyOrImplicitlyEnabledInputMethodsAndSubtypeListLocked(
3774 mContext);
satok7f35c8c2010-10-07 21:13:11 +09003775 if (immis == null || immis.size() == 0) {
3776 return;
3777 }
3778
Dianne Hackborn8cf1bcd2010-03-16 13:06:10 -07003779 hideInputMethodMenuLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003780
satok688bd472012-02-09 20:09:17 +09003781 final List<ImeSubtypeListItem> imList =
Yohei Yukawa5a647b692014-05-22 12:49:00 +09003782 mSwitchingController.getSortedInputMethodAndSubtypeListLocked(
Yohei Yukawa5f8e7312015-12-10 00:58:55 -08003783 showAuxSubtypes, isScreenLocked);
satok913a8922010-08-26 21:53:41 +09003784
satokc3690562012-01-10 20:14:43 +09003785 if (lastInputMethodSubtypeId == NOT_A_SUBTYPE_ID) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003786 final InputMethodSubtype currentSubtype = getCurrentInputMethodSubtypeLocked();
satokc3690562012-01-10 20:14:43 +09003787 if (currentSubtype != null) {
3788 final InputMethodInfo currentImi = mMethodMap.get(mCurMethodId);
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003789 lastInputMethodSubtypeId = InputMethodUtils.getSubtypeIdFromHashCode(
3790 currentImi, currentSubtype.hashCode());
satokc3690562012-01-10 20:14:43 +09003791 }
3792 }
3793
Ken Wakasa761eb372011-03-04 19:06:18 +09003794 final int N = imList.size();
satokab751aa2010-09-14 19:17:36 +09003795 mIms = new InputMethodInfo[N];
3796 mSubtypeIds = new int[N];
Dianne Hackborn8cf1bcd2010-03-16 13:06:10 -07003797 int checkedItem = 0;
3798 for (int i = 0; i < N; ++i) {
Ken Wakasa05dbb652011-08-22 15:22:43 +09003799 final ImeSubtypeListItem item = imList.get(i);
3800 mIms[i] = item.mImi;
3801 mSubtypeIds[i] = item.mSubtypeId;
Dianne Hackborn8cf1bcd2010-03-16 13:06:10 -07003802 if (mIms[i].getId().equals(lastInputMethodId)) {
satokab751aa2010-09-14 19:17:36 +09003803 int subtypeId = mSubtypeIds[i];
3804 if ((subtypeId == NOT_A_SUBTYPE_ID)
3805 || (lastInputMethodSubtypeId == NOT_A_SUBTYPE_ID && subtypeId == 0)
3806 || (subtypeId == lastInputMethodSubtypeId)) {
3807 checkedItem = i;
3808 }
Dianne Hackborn8cf1bcd2010-03-16 13:06:10 -07003809 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003810 }
Alan Viverette505e3ab2014-11-24 15:22:11 -08003811
Andrew Sapperstein8a3b4cb2017-04-28 14:35:31 -07003812 final Context settingsContext = new ContextThemeWrapper(
3813 ActivityThread.currentActivityThread().getSystemUiContext(),
Alan Viverette505e3ab2014-11-24 15:22:11 -08003814 com.android.internal.R.style.Theme_DeviceDefault_Settings);
3815
3816 mDialogBuilder = new AlertDialog.Builder(settingsContext);
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003817 mDialogBuilder.setOnCancelListener(new OnCancelListener() {
3818 @Override
3819 public void onCancel(DialogInterface dialog) {
3820 hideInputMethodMenu();
3821 }
3822 });
Alan Viverette505e3ab2014-11-24 15:22:11 -08003823
3824 final Context dialogContext = mDialogBuilder.getContext();
3825 final TypedArray a = dialogContext.obtainStyledAttributes(null,
3826 com.android.internal.R.styleable.DialogPreference,
3827 com.android.internal.R.attr.alertDialogStyle, 0);
3828 final Drawable dialogIcon = a.getDrawable(
3829 com.android.internal.R.styleable.DialogPreference_dialogIcon);
3830 a.recycle();
3831
3832 mDialogBuilder.setIcon(dialogIcon);
3833
Yohei Yukawad34e1482016-02-11 08:03:52 -08003834 final LayoutInflater inflater = dialogContext.getSystemService(LayoutInflater.class);
satok01038492012-04-09 21:08:27 +09003835 final View tv = inflater.inflate(
3836 com.android.internal.R.layout.input_method_switch_dialog_title, null);
3837 mDialogBuilder.setCustomTitle(tv);
3838
3839 // Setup layout for a toggle switch of the hardware keyboard
3840 mSwitchingDialogTitleView = tv;
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003841 mSwitchingDialogTitleView
3842 .findViewById(com.android.internal.R.id.hard_keyboard_section)
Seigo Nonaka7309b122015-08-17 18:34:13 -07003843 .setVisibility(mWindowManagerInternal.isHardKeyboardAvailable()
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003844 ? View.VISIBLE : View.GONE);
Alan Viverette505e3ab2014-11-24 15:22:11 -08003845 final Switch hardKeySwitch = (Switch) mSwitchingDialogTitleView.findViewById(
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003846 com.android.internal.R.id.hard_keyboard_switch);
Michael Wright7b5a96b2014-08-09 19:28:42 -07003847 hardKeySwitch.setChecked(mShowImeWithHardKeyboard);
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003848 hardKeySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
3849 @Override
3850 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Michael Wright7b5a96b2014-08-09 19:28:42 -07003851 mSettings.setShowImeWithHardKeyboard(isChecked);
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003852 // Ensure that the input method dialog is dismissed when changing
3853 // the hardware keyboard state.
3854 hideInputMethodMenu();
3855 }
3856 });
3857
Alan Viverette505e3ab2014-11-24 15:22:11 -08003858 final ImeSubtypeListAdapter adapter = new ImeSubtypeListAdapter(dialogContext,
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003859 com.android.internal.R.layout.input_method_switch_item, imList, checkedItem);
3860 final OnClickListener choiceListener = new OnClickListener() {
3861 @Override
3862 public void onClick(final DialogInterface dialog, final int which) {
3863 synchronized (mMethodMap) {
3864 if (mIms == null || mIms.length <= which || mSubtypeIds == null
3865 || mSubtypeIds.length <= which) {
3866 return;
satok01038492012-04-09 21:08:27 +09003867 }
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003868 final InputMethodInfo im = mIms[which];
3869 int subtypeId = mSubtypeIds[which];
3870 adapter.mCheckedItem = which;
3871 adapter.notifyDataSetChanged();
3872 hideInputMethodMenu();
3873 if (im != null) {
3874 if (subtypeId < 0 || subtypeId >= im.getSubtypeCount()) {
3875 subtypeId = NOT_A_SUBTYPE_ID;
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08003876 }
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003877 setInputMethodLocked(im.getId(), subtypeId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003878 }
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003879 }
3880 }
3881 };
3882 mDialogBuilder.setSingleChoiceItems(adapter, checkedItem, choiceListener);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003884 mSwitchingDialog = mDialogBuilder.create();
Dianne Hackborne3a7f622011-03-03 21:48:24 -08003885 mSwitchingDialog.setCanceledOnTouchOutside(true);
Wale Ogunwale3a931692016-11-02 16:49:48 -07003886 final Window w = mSwitchingDialog.getWindow();
3887 final WindowManager.LayoutParams attrs = w.getAttributes();
3888 w.setType(TYPE_INPUT_METHOD_DIALOG);
3889 // Use an alternate token for the dialog for that window manager can group the token
3890 // with other IME windows based on type vs. grouping based on whichever token happens
3891 // to get selected by the system later on.
3892 attrs.token = mSwitchingDialogToken;
3893 attrs.privateFlags |= PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
3894 attrs.setTitle("Select input method");
3895 w.setAttributes(attrs);
Seigo Nonakad9eb9112015-05-26 20:54:43 +09003896 updateSystemUi(mCurToken, mImeWindowVis, mBackDisposition);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003897 mSwitchingDialog.show();
3898 }
3899 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003900
Ken Wakasa05dbb652011-08-22 15:22:43 +09003901 private static class ImeSubtypeListAdapter extends ArrayAdapter<ImeSubtypeListItem> {
3902 private final LayoutInflater mInflater;
3903 private final int mTextViewResourceId;
3904 private final List<ImeSubtypeListItem> mItemsList;
Satoshi Kataokad2142962012-11-12 18:43:06 +09003905 public int mCheckedItem;
Ken Wakasa05dbb652011-08-22 15:22:43 +09003906 public ImeSubtypeListAdapter(Context context, int textViewResourceId,
3907 List<ImeSubtypeListItem> itemsList, int checkedItem) {
3908 super(context, textViewResourceId, itemsList);
Alan Viverette505e3ab2014-11-24 15:22:11 -08003909
Ken Wakasa05dbb652011-08-22 15:22:43 +09003910 mTextViewResourceId = textViewResourceId;
3911 mItemsList = itemsList;
3912 mCheckedItem = checkedItem;
Yohei Yukawad34e1482016-02-11 08:03:52 -08003913 mInflater = context.getSystemService(LayoutInflater.class);
Ken Wakasa05dbb652011-08-22 15:22:43 +09003914 }
3915
3916 @Override
3917 public View getView(int position, View convertView, ViewGroup parent) {
3918 final View view = convertView != null ? convertView
3919 : mInflater.inflate(mTextViewResourceId, null);
3920 if (position < 0 || position >= mItemsList.size()) return view;
3921 final ImeSubtypeListItem item = mItemsList.get(position);
3922 final CharSequence imeName = item.mImeName;
3923 final CharSequence subtypeName = item.mSubtypeName;
3924 final TextView firstTextView = (TextView)view.findViewById(android.R.id.text1);
3925 final TextView secondTextView = (TextView)view.findViewById(android.R.id.text2);
3926 if (TextUtils.isEmpty(subtypeName)) {
3927 firstTextView.setText(imeName);
3928 secondTextView.setVisibility(View.GONE);
3929 } else {
3930 firstTextView.setText(subtypeName);
3931 secondTextView.setText(imeName);
3932 secondTextView.setVisibility(View.VISIBLE);
3933 }
3934 final RadioButton radioButton =
3935 (RadioButton)view.findViewById(com.android.internal.R.id.radio);
3936 radioButton.setChecked(position == mCheckedItem);
3937 return view;
3938 }
3939 }
3940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003941 void hideInputMethodMenu() {
The Android Open Source Project10592532009-03-18 17:39:46 -07003942 synchronized (mMethodMap) {
3943 hideInputMethodMenuLocked();
3944 }
3945 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003946
The Android Open Source Project10592532009-03-18 17:39:46 -07003947 void hideInputMethodMenuLocked() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003948 if (DEBUG) Slog.v(TAG, "Hide switching menu");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003949
The Android Open Source Project10592532009-03-18 17:39:46 -07003950 if (mSwitchingDialog != null) {
3951 mSwitchingDialog.dismiss();
3952 mSwitchingDialog = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003953 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003954
Seigo Nonakad9eb9112015-05-26 20:54:43 +09003955 updateSystemUiLocked(mCurToken, mImeWindowVis, mBackDisposition);
The Android Open Source Project10592532009-03-18 17:39:46 -07003956 mDialogBuilder = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07003957 mIms = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003958 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003960 // ----------------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003961
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003962 boolean setInputMethodEnabledLocked(String id, boolean enabled) {
3963 // Make sure this is a valid input method.
3964 InputMethodInfo imm = mMethodMap.get(id);
3965 if (imm == null) {
satokd87c2592010-09-29 11:52:06 +09003966 throw new IllegalArgumentException("Unknown id: " + mCurMethodId);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003967 }
3968
satokd87c2592010-09-29 11:52:06 +09003969 List<Pair<String, ArrayList<String>>> enabledInputMethodsList = mSettings
3970 .getEnabledInputMethodsAndSubtypeListLocked();
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003971
satokd87c2592010-09-29 11:52:06 +09003972 if (enabled) {
3973 for (Pair<String, ArrayList<String>> pair: enabledInputMethodsList) {
3974 if (pair.first.equals(id)) {
3975 // We are enabling this input method, but it is already enabled.
3976 // Nothing to do. The previous state was enabled.
3977 return true;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003978 }
3979 }
satokd87c2592010-09-29 11:52:06 +09003980 mSettings.appendAndPutEnabledInputMethodLocked(id, false);
3981 // Previous state was disabled.
3982 return false;
3983 } else {
3984 StringBuilder builder = new StringBuilder();
3985 if (mSettings.buildAndPutEnabledInputMethodsStrRemovingIdLocked(
3986 builder, enabledInputMethodsList, id)) {
3987 // Disabled input method is currently selected, switch to another one.
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003988 final String selId = mSettings.getSelectedInputMethod();
satok03eb319a2010-11-11 18:17:42 +09003989 if (id.equals(selId) && !chooseNewDefaultIMELocked()) {
3990 Slog.i(TAG, "Can't find new IME, unsetting the current input method.");
3991 resetSelectedInputMethodAndSubtypeLocked("");
satokd87c2592010-09-29 11:52:06 +09003992 }
3993 // Previous state was enabled.
3994 return true;
3995 } else {
3996 // We are disabling the input method but it is already disabled.
3997 // Nothing to do. The previous state was disabled.
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003998 return false;
3999 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004000 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004001 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08004002
satok723a27e2010-11-11 14:58:11 +09004003 private void setSelectedInputMethodAndSubtypeLocked(InputMethodInfo imi, int subtypeId,
4004 boolean setSubtypeOnly) {
Tarandeep Singh89a6c482017-11-21 14:26:11 -08004005 // Updates to InputMethod are transient in VR mode. Its not included in history.
4006 final boolean isVrInput = imi != null && imi.isVrOnly();
4007 if (!isVrInput) {
4008 // Update the history of InputMethod and Subtype
4009 mSettings.saveCurrentInputMethodAndSubtypeToHistory(mCurMethodId, mCurrentSubtype);
4010 }
satok723a27e2010-11-11 14:58:11 +09004011
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09004012 mCurUserActionNotificationSequenceNumber =
4013 Math.max(mCurUserActionNotificationSequenceNumber + 1, 1);
4014 if (DEBUG) {
4015 Slog.d(TAG, "Bump mCurUserActionNotificationSequenceNumber:"
4016 + mCurUserActionNotificationSequenceNumber);
4017 }
4018
4019 if (mCurClient != null && mCurClient.client != null) {
4020 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
4021 MSG_SET_USER_ACTION_NOTIFICATION_SEQUENCE_NUMBER,
Yohei Yukawa080fa342014-08-31 16:10:05 -07004022 mCurUserActionNotificationSequenceNumber, mCurClient));
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09004023 }
4024
Tarandeep Singh89a6c482017-11-21 14:26:11 -08004025 if (isVrInput) {
4026 // Updates to InputMethod are transient in VR mode. Any changes to Settings are skipped.
4027 return;
4028 }
4029
satok723a27e2010-11-11 14:58:11 +09004030 // Set Subtype here
4031 if (imi == null || subtypeId < 0) {
4032 mSettings.putSelectedSubtype(NOT_A_SUBTYPE_ID);
Tadashi G. Takaoka0ba75bb2010-11-09 12:19:32 -08004033 mCurrentSubtype = null;
satok723a27e2010-11-11 14:58:11 +09004034 } else {
Ken Wakasa586f0512011-01-20 22:31:01 +09004035 if (subtypeId < imi.getSubtypeCount()) {
4036 InputMethodSubtype subtype = imi.getSubtypeAt(subtypeId);
4037 mSettings.putSelectedSubtype(subtype.hashCode());
4038 mCurrentSubtype = subtype;
satok723a27e2010-11-11 14:58:11 +09004039 } else {
4040 mSettings.putSelectedSubtype(NOT_A_SUBTYPE_ID);
satokd81e9502012-05-21 12:58:45 +09004041 // If the subtype is not specified, choose the most applicable one
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004042 mCurrentSubtype = getCurrentInputMethodSubtypeLocked();
satok723a27e2010-11-11 14:58:11 +09004043 }
satokab751aa2010-09-14 19:17:36 +09004044 }
satok723a27e2010-11-11 14:58:11 +09004045
Yohei Yukawa68645a62016-02-17 07:54:20 -08004046 if (!setSubtypeOnly) {
satok723a27e2010-11-11 14:58:11 +09004047 // Set InputMethod here
4048 mSettings.putSelectedInputMethod(imi != null ? imi.getId() : "");
4049 }
4050 }
4051
4052 private void resetSelectedInputMethodAndSubtypeLocked(String newDefaultIme) {
4053 InputMethodInfo imi = mMethodMap.get(newDefaultIme);
4054 int lastSubtypeId = NOT_A_SUBTYPE_ID;
4055 // newDefaultIme is empty when there is no candidate for the selected IME.
4056 if (imi != null && !TextUtils.isEmpty(newDefaultIme)) {
4057 String subtypeHashCode = mSettings.getLastSubtypeForInputMethodLocked(newDefaultIme);
4058 if (subtypeHashCode != null) {
4059 try {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004060 lastSubtypeId = InputMethodUtils.getSubtypeIdFromHashCode(
Narayan Kamatha09b4d22016-04-15 18:32:45 +01004061 imi, Integer.parseInt(subtypeHashCode));
satok723a27e2010-11-11 14:58:11 +09004062 } catch (NumberFormatException e) {
4063 Slog.w(TAG, "HashCode for subtype looks broken: " + subtypeHashCode, e);
4064 }
4065 }
4066 }
4067 setSelectedInputMethodAndSubtypeLocked(imi, lastSubtypeId, false);
satokab751aa2010-09-14 19:17:36 +09004068 }
4069
satok4e4569d2010-11-19 18:45:53 +09004070 // If there are no selected shortcuts, tries finding the most applicable ones.
4071 private Pair<InputMethodInfo, InputMethodSubtype>
4072 findLastResortApplicableShortcutInputMethodAndSubtypeLocked(String mode) {
4073 List<InputMethodInfo> imis = mSettings.getEnabledInputMethodListLocked();
4074 InputMethodInfo mostApplicableIMI = null;
satokcd7cd292010-11-20 15:46:23 +09004075 InputMethodSubtype mostApplicableSubtype = null;
satok4e4569d2010-11-19 18:45:53 +09004076 boolean foundInSystemIME = false;
4077
4078 // Search applicable subtype for each InputMethodInfo
4079 for (InputMethodInfo imi: imis) {
satok7599a7f2010-12-22 13:45:23 +09004080 final String imiId = imi.getId();
4081 if (foundInSystemIME && !imiId.equals(mCurMethodId)) {
4082 continue;
4083 }
satokcd7cd292010-11-20 15:46:23 +09004084 InputMethodSubtype subtype = null;
satokdf31ae62011-01-15 06:19:44 +09004085 final List<InputMethodSubtype> enabledSubtypes =
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004086 mSettings.getEnabledInputMethodSubtypeListLocked(mContext, imi, true);
satokdf31ae62011-01-15 06:19:44 +09004087 // 1. Search by the current subtype's locale from enabledSubtypes.
satok4e4569d2010-11-19 18:45:53 +09004088 if (mCurrentSubtype != null) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004089 subtype = InputMethodUtils.findLastResortApplicableSubtypeLocked(
satokdf31ae62011-01-15 06:19:44 +09004090 mRes, enabledSubtypes, mode, mCurrentSubtype.getLocale(), false);
satok4e4569d2010-11-19 18:45:53 +09004091 }
satokdf31ae62011-01-15 06:19:44 +09004092 // 2. Search by the system locale from enabledSubtypes.
4093 // 3. Search the first enabled subtype matched with mode from enabledSubtypes.
satokcd7cd292010-11-20 15:46:23 +09004094 if (subtype == null) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004095 subtype = InputMethodUtils.findLastResortApplicableSubtypeLocked(
satokdf31ae62011-01-15 06:19:44 +09004096 mRes, enabledSubtypes, mode, null, true);
satok4e4569d2010-11-19 18:45:53 +09004097 }
satoka86f5e42011-09-02 17:12:42 +09004098 final ArrayList<InputMethodSubtype> overridingImplicitlyEnabledSubtypes =
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004099 InputMethodUtils.getOverridingImplicitlyEnabledSubtypes(imi, mode);
satoka86f5e42011-09-02 17:12:42 +09004100 final ArrayList<InputMethodSubtype> subtypesForSearch =
4101 overridingImplicitlyEnabledSubtypes.isEmpty()
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004102 ? InputMethodUtils.getSubtypes(imi)
4103 : overridingImplicitlyEnabledSubtypes;
satok7599a7f2010-12-22 13:45:23 +09004104 // 4. Search by the current subtype's locale from all subtypes.
4105 if (subtype == null && mCurrentSubtype != null) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004106 subtype = InputMethodUtils.findLastResortApplicableSubtypeLocked(
satoka86f5e42011-09-02 17:12:42 +09004107 mRes, subtypesForSearch, mode, mCurrentSubtype.getLocale(), false);
satok7599a7f2010-12-22 13:45:23 +09004108 }
4109 // 5. Search by the system locale from all subtypes.
4110 // 6. Search the first enabled subtype matched with mode from all subtypes.
satokcd7cd292010-11-20 15:46:23 +09004111 if (subtype == null) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004112 subtype = InputMethodUtils.findLastResortApplicableSubtypeLocked(
satoka86f5e42011-09-02 17:12:42 +09004113 mRes, subtypesForSearch, mode, null, true);
satok4e4569d2010-11-19 18:45:53 +09004114 }
satokcd7cd292010-11-20 15:46:23 +09004115 if (subtype != null) {
satok7599a7f2010-12-22 13:45:23 +09004116 if (imiId.equals(mCurMethodId)) {
satok4e4569d2010-11-19 18:45:53 +09004117 // The current input method is the most applicable IME.
4118 mostApplicableIMI = imi;
satokcd7cd292010-11-20 15:46:23 +09004119 mostApplicableSubtype = subtype;
satok4e4569d2010-11-19 18:45:53 +09004120 break;
satok7599a7f2010-12-22 13:45:23 +09004121 } else if (!foundInSystemIME) {
satok4e4569d2010-11-19 18:45:53 +09004122 // The system input method is 2nd applicable IME.
4123 mostApplicableIMI = imi;
satokcd7cd292010-11-20 15:46:23 +09004124 mostApplicableSubtype = subtype;
satok7599a7f2010-12-22 13:45:23 +09004125 if ((imi.getServiceInfo().applicationInfo.flags
4126 & ApplicationInfo.FLAG_SYSTEM) != 0) {
4127 foundInSystemIME = true;
4128 }
satok4e4569d2010-11-19 18:45:53 +09004129 }
4130 }
4131 }
4132 if (DEBUG) {
satokcd7cd292010-11-20 15:46:23 +09004133 if (mostApplicableIMI != null) {
4134 Slog.w(TAG, "Most applicable shortcut input method was:"
4135 + mostApplicableIMI.getId());
4136 if (mostApplicableSubtype != null) {
4137 Slog.w(TAG, "Most applicable shortcut input method subtype was:"
4138 + "," + mostApplicableSubtype.getMode() + ","
4139 + mostApplicableSubtype.getLocale());
4140 }
4141 }
satok4e4569d2010-11-19 18:45:53 +09004142 }
satokcd7cd292010-11-20 15:46:23 +09004143 if (mostApplicableIMI != null) {
Yohei Yukawab0377bb2015-08-10 21:06:30 -07004144 return new Pair<> (mostApplicableIMI, mostApplicableSubtype);
satok4e4569d2010-11-19 18:45:53 +09004145 } else {
4146 return null;
4147 }
4148 }
4149
satokab751aa2010-09-14 19:17:36 +09004150 /**
4151 * @return Return the current subtype of this input method.
4152 */
satok42c5a162011-05-26 16:46:14 +09004153 @Override
satokab751aa2010-09-14 19:17:36 +09004154 public InputMethodSubtype getCurrentInputMethodSubtype() {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004155 // TODO: Make this work even for non-current users?
4156 if (!calledFromValidUser()) {
4157 return null;
4158 }
4159 synchronized (mMethodMap) {
4160 return getCurrentInputMethodSubtypeLocked();
4161 }
4162 }
4163
4164 private InputMethodSubtype getCurrentInputMethodSubtypeLocked() {
satokfdf419e2012-05-08 16:52:08 +09004165 if (mCurMethodId == null) {
4166 return null;
4167 }
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004168 final boolean subtypeIsSelected = mSettings.isSubtypeSelected();
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004169 final InputMethodInfo imi = mMethodMap.get(mCurMethodId);
4170 if (imi == null || imi.getSubtypeCount() == 0) {
4171 return null;
satok4e4569d2010-11-19 18:45:53 +09004172 }
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004173 if (!subtypeIsSelected || mCurrentSubtype == null
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004174 || !InputMethodUtils.isValidSubtypeId(imi, mCurrentSubtype.hashCode())) {
4175 int subtypeId = mSettings.getSelectedInputMethodSubtypeId(mCurMethodId);
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004176 if (subtypeId == NOT_A_SUBTYPE_ID) {
4177 // If there are no selected subtypes, the framework will try to find
4178 // the most applicable subtype from explicitly or implicitly enabled
4179 // subtypes.
4180 List<InputMethodSubtype> explicitlyOrImplicitlyEnabledSubtypes =
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004181 mSettings.getEnabledInputMethodSubtypeListLocked(mContext, imi, true);
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004182 // If there is only one explicitly or implicitly enabled subtype,
4183 // just returns it.
4184 if (explicitlyOrImplicitlyEnabledSubtypes.size() == 1) {
4185 mCurrentSubtype = explicitlyOrImplicitlyEnabledSubtypes.get(0);
4186 } else if (explicitlyOrImplicitlyEnabledSubtypes.size() > 1) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004187 mCurrentSubtype = InputMethodUtils.findLastResortApplicableSubtypeLocked(
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004188 mRes, explicitlyOrImplicitlyEnabledSubtypes,
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004189 InputMethodUtils.SUBTYPE_MODE_KEYBOARD, null, true);
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004190 if (mCurrentSubtype == null) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004191 mCurrentSubtype = InputMethodUtils.findLastResortApplicableSubtypeLocked(
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004192 mRes, explicitlyOrImplicitlyEnabledSubtypes, null, null,
4193 true);
satok4e4569d2010-11-19 18:45:53 +09004194 }
satok3ef8b292010-11-23 06:06:29 +09004195 }
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004196 } else {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004197 mCurrentSubtype = InputMethodUtils.getSubtypes(imi).get(subtypeId);
satok8fbb1e82010-11-02 23:15:58 +09004198 }
4199 }
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004200 return mCurrentSubtype;
satokab751aa2010-09-14 19:17:36 +09004201 }
4202
satok4e4569d2010-11-19 18:45:53 +09004203 // TODO: We should change the return type from List to List<Parcelable>
satokdbf29502011-08-25 15:28:23 +09004204 @SuppressWarnings("rawtypes")
satoke7c6998e2011-06-03 17:57:59 +09004205 @Override
satok4e4569d2010-11-19 18:45:53 +09004206 public List getShortcutInputMethodsAndSubtypes() {
4207 synchronized (mMethodMap) {
Yohei Yukawab0377bb2015-08-10 21:06:30 -07004208 ArrayList<Object> ret = new ArrayList<>();
satokf3db1af2010-11-23 13:34:33 +09004209 if (mShortcutInputMethodsAndSubtypes.size() == 0) {
satok4e4569d2010-11-19 18:45:53 +09004210 // If there are no selected shortcut subtypes, the framework will try to find
4211 // the most applicable subtype from all subtypes whose mode is
4212 // SUBTYPE_MODE_VOICE. This is an exceptional case, so we will hardcode the mode.
satokf3db1af2010-11-23 13:34:33 +09004213 Pair<InputMethodInfo, InputMethodSubtype> info =
4214 findLastResortApplicableShortcutInputMethodAndSubtypeLocked(
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004215 InputMethodUtils.SUBTYPE_MODE_VOICE);
satok7599a7f2010-12-22 13:45:23 +09004216 if (info != null) {
satok3da92232011-01-11 22:46:30 +09004217 ret.add(info.first);
4218 ret.add(info.second);
satok7599a7f2010-12-22 13:45:23 +09004219 }
satok3da92232011-01-11 22:46:30 +09004220 return ret;
satokf3db1af2010-11-23 13:34:33 +09004221 }
satokf3db1af2010-11-23 13:34:33 +09004222 for (InputMethodInfo imi: mShortcutInputMethodsAndSubtypes.keySet()) {
4223 ret.add(imi);
4224 for (InputMethodSubtype subtype: mShortcutInputMethodsAndSubtypes.get(imi)) {
4225 ret.add(subtype);
satok4e4569d2010-11-19 18:45:53 +09004226 }
4227 }
satokf3db1af2010-11-23 13:34:33 +09004228 return ret;
satok4e4569d2010-11-19 18:45:53 +09004229 }
4230 }
4231
satok42c5a162011-05-26 16:46:14 +09004232 @Override
satokb66d2872010-11-10 01:04:04 +09004233 public boolean setCurrentInputMethodSubtype(InputMethodSubtype subtype) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004234 // TODO: Make this work even for non-current users?
4235 if (!calledFromValidUser()) {
4236 return false;
4237 }
satokb66d2872010-11-10 01:04:04 +09004238 synchronized (mMethodMap) {
4239 if (subtype != null && mCurMethodId != null) {
4240 InputMethodInfo imi = mMethodMap.get(mCurMethodId);
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004241 int subtypeId = InputMethodUtils.getSubtypeIdFromHashCode(imi, subtype.hashCode());
satokb66d2872010-11-10 01:04:04 +09004242 if (subtypeId != NOT_A_SUBTYPE_ID) {
4243 setInputMethodLocked(mCurMethodId, subtypeId);
4244 return true;
4245 }
4246 }
4247 return false;
4248 }
4249 }
4250
Satoshi Kataoka5ade83b2012-09-26 22:59:41 +09004251 // TODO: Cache the state for each user and reset when the cached user is removed.
satoke7c6998e2011-06-03 17:57:59 +09004252 private static class InputMethodFileManager {
4253 private static final String SYSTEM_PATH = "system";
4254 private static final String INPUT_METHOD_PATH = "inputmethod";
4255 private static final String ADDITIONAL_SUBTYPES_FILE_NAME = "subtypes.xml";
4256 private static final String NODE_SUBTYPES = "subtypes";
4257 private static final String NODE_SUBTYPE = "subtype";
4258 private static final String NODE_IMI = "imi";
4259 private static final String ATTR_ID = "id";
4260 private static final String ATTR_LABEL = "label";
4261 private static final String ATTR_ICON = "icon";
Yohei Yukawa66baf692016-04-11 02:29:35 -07004262 private static final String ATTR_IME_SUBTYPE_ID = "subtypeId";
satoke7c6998e2011-06-03 17:57:59 +09004263 private static final String ATTR_IME_SUBTYPE_LOCALE = "imeSubtypeLocale";
Yohei Yukawa868d19b2015-12-07 15:58:57 -08004264 private static final String ATTR_IME_SUBTYPE_LANGUAGE_TAG = "languageTag";
satoke7c6998e2011-06-03 17:57:59 +09004265 private static final String ATTR_IME_SUBTYPE_MODE = "imeSubtypeMode";
4266 private static final String ATTR_IME_SUBTYPE_EXTRA_VALUE = "imeSubtypeExtraValue";
4267 private static final String ATTR_IS_AUXILIARY = "isAuxiliary";
Yohei Yukawa1e1a4472016-03-10 23:46:07 -08004268 private static final String ATTR_IS_ASCII_CAPABLE = "isAsciiCapable";
satoke7c6998e2011-06-03 17:57:59 +09004269 private final AtomicFile mAdditionalInputMethodSubtypeFile;
4270 private final HashMap<String, InputMethodInfo> mMethodMap;
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004271 private final HashMap<String, List<InputMethodSubtype>> mAdditionalSubtypesMap =
Yohei Yukawab0377bb2015-08-10 21:06:30 -07004272 new HashMap<>();
Satoshi Kataoka5ade83b2012-09-26 22:59:41 +09004273 public InputMethodFileManager(HashMap<String, InputMethodInfo> methodMap, int userId) {
satoke7c6998e2011-06-03 17:57:59 +09004274 if (methodMap == null) {
4275 throw new NullPointerException("methodMap is null");
4276 }
4277 mMethodMap = methodMap;
Xiaohui Chen7c696362015-09-16 09:56:14 -07004278 final File systemDir = userId == UserHandle.USER_SYSTEM
Satoshi Kataoka5ade83b2012-09-26 22:59:41 +09004279 ? new File(Environment.getDataDirectory(), SYSTEM_PATH)
4280 : Environment.getUserSystemDirectory(userId);
satoke7c6998e2011-06-03 17:57:59 +09004281 final File inputMethodDir = new File(systemDir, INPUT_METHOD_PATH);
Yohei Yukawadf5af482015-08-04 22:11:11 -07004282 if (!inputMethodDir.exists() && !inputMethodDir.mkdirs()) {
satoke7c6998e2011-06-03 17:57:59 +09004283 Slog.w(TAG, "Couldn't create dir.: " + inputMethodDir.getAbsolutePath());
4284 }
4285 final File subtypeFile = new File(inputMethodDir, ADDITIONAL_SUBTYPES_FILE_NAME);
Dianne Hackborne17b4452018-01-10 13:15:40 -08004286 mAdditionalInputMethodSubtypeFile = new AtomicFile(subtypeFile, "input-subtypes");
satoke7c6998e2011-06-03 17:57:59 +09004287 if (!subtypeFile.exists()) {
4288 // If "subtypes.xml" doesn't exist, create a blank file.
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004289 writeAdditionalInputMethodSubtypes(
4290 mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile, methodMap);
satoke7c6998e2011-06-03 17:57:59 +09004291 } else {
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004292 readAdditionalInputMethodSubtypes(
4293 mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile);
satoke7c6998e2011-06-03 17:57:59 +09004294 }
4295 }
4296
4297 private void deleteAllInputMethodSubtypes(String imiId) {
4298 synchronized (mMethodMap) {
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004299 mAdditionalSubtypesMap.remove(imiId);
4300 writeAdditionalInputMethodSubtypes(
4301 mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile, mMethodMap);
satoke7c6998e2011-06-03 17:57:59 +09004302 }
4303 }
4304
4305 public void addInputMethodSubtypes(
satok4a28bde2011-06-29 21:03:40 +09004306 InputMethodInfo imi, InputMethodSubtype[] additionalSubtypes) {
satoke7c6998e2011-06-03 17:57:59 +09004307 synchronized (mMethodMap) {
Yohei Yukawab0377bb2015-08-10 21:06:30 -07004308 final ArrayList<InputMethodSubtype> subtypes = new ArrayList<>();
satoke7c6998e2011-06-03 17:57:59 +09004309 final int N = additionalSubtypes.length;
4310 for (int i = 0; i < N; ++i) {
4311 final InputMethodSubtype subtype = additionalSubtypes[i];
satoked2b24e2011-08-31 18:03:21 +09004312 if (!subtypes.contains(subtype)) {
satoke7c6998e2011-06-03 17:57:59 +09004313 subtypes.add(subtype);
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004314 } else {
4315 Slog.w(TAG, "Duplicated subtype definition found: "
4316 + subtype.getLocale() + ", " + subtype.getMode());
satoke7c6998e2011-06-03 17:57:59 +09004317 }
4318 }
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004319 mAdditionalSubtypesMap.put(imi.getId(), subtypes);
4320 writeAdditionalInputMethodSubtypes(
4321 mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile, mMethodMap);
satoke7c6998e2011-06-03 17:57:59 +09004322 }
4323 }
4324
4325 public HashMap<String, List<InputMethodSubtype>> getAllAdditionalInputMethodSubtypes() {
4326 synchronized (mMethodMap) {
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004327 return mAdditionalSubtypesMap;
satoke7c6998e2011-06-03 17:57:59 +09004328 }
4329 }
4330
4331 private static void writeAdditionalInputMethodSubtypes(
4332 HashMap<String, List<InputMethodSubtype>> allSubtypes, AtomicFile subtypesFile,
4333 HashMap<String, InputMethodInfo> methodMap) {
4334 // Safety net for the case that this function is called before methodMap is set.
4335 final boolean isSetMethodMap = methodMap != null && methodMap.size() > 0;
4336 FileOutputStream fos = null;
4337 try {
4338 fos = subtypesFile.startWrite();
4339 final XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01004340 out.setOutput(fos, StandardCharsets.UTF_8.name());
satoke7c6998e2011-06-03 17:57:59 +09004341 out.startDocument(null, true);
4342 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
4343 out.startTag(null, NODE_SUBTYPES);
4344 for (String imiId : allSubtypes.keySet()) {
4345 if (isSetMethodMap && !methodMap.containsKey(imiId)) {
4346 Slog.w(TAG, "IME uninstalled or not valid.: " + imiId);
4347 continue;
4348 }
4349 out.startTag(null, NODE_IMI);
4350 out.attribute(null, ATTR_ID, imiId);
4351 final List<InputMethodSubtype> subtypesList = allSubtypes.get(imiId);
4352 final int N = subtypesList.size();
4353 for (int i = 0; i < N; ++i) {
4354 final InputMethodSubtype subtype = subtypesList.get(i);
4355 out.startTag(null, NODE_SUBTYPE);
Yohei Yukawa66baf692016-04-11 02:29:35 -07004356 if (subtype.hasSubtypeId()) {
4357 out.attribute(null, ATTR_IME_SUBTYPE_ID,
4358 String.valueOf(subtype.getSubtypeId()));
4359 }
satoke7c6998e2011-06-03 17:57:59 +09004360 out.attribute(null, ATTR_ICON, String.valueOf(subtype.getIconResId()));
4361 out.attribute(null, ATTR_LABEL, String.valueOf(subtype.getNameResId()));
4362 out.attribute(null, ATTR_IME_SUBTYPE_LOCALE, subtype.getLocale());
Yohei Yukawa868d19b2015-12-07 15:58:57 -08004363 out.attribute(null, ATTR_IME_SUBTYPE_LANGUAGE_TAG,
4364 subtype.getLanguageTag());
satoke7c6998e2011-06-03 17:57:59 +09004365 out.attribute(null, ATTR_IME_SUBTYPE_MODE, subtype.getMode());
4366 out.attribute(null, ATTR_IME_SUBTYPE_EXTRA_VALUE, subtype.getExtraValue());
4367 out.attribute(null, ATTR_IS_AUXILIARY,
4368 String.valueOf(subtype.isAuxiliary() ? 1 : 0));
Yohei Yukawa1e1a4472016-03-10 23:46:07 -08004369 out.attribute(null, ATTR_IS_ASCII_CAPABLE,
4370 String.valueOf(subtype.isAsciiCapable() ? 1 : 0));
satoke7c6998e2011-06-03 17:57:59 +09004371 out.endTag(null, NODE_SUBTYPE);
4372 }
4373 out.endTag(null, NODE_IMI);
4374 }
4375 out.endTag(null, NODE_SUBTYPES);
4376 out.endDocument();
4377 subtypesFile.finishWrite(fos);
4378 } catch (java.io.IOException e) {
4379 Slog.w(TAG, "Error writing subtypes", e);
4380 if (fos != null) {
4381 subtypesFile.failWrite(fos);
4382 }
4383 }
4384 }
4385
4386 private static void readAdditionalInputMethodSubtypes(
4387 HashMap<String, List<InputMethodSubtype>> allSubtypes, AtomicFile subtypesFile) {
4388 if (allSubtypes == null || subtypesFile == null) return;
4389 allSubtypes.clear();
Yohei Yukawa5894b432015-08-11 13:29:24 -07004390 try (final FileInputStream fis = subtypesFile.openRead()) {
satoke7c6998e2011-06-03 17:57:59 +09004391 final XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01004392 parser.setInput(fis, StandardCharsets.UTF_8.name());
satoke7c6998e2011-06-03 17:57:59 +09004393 int type = parser.getEventType();
4394 // Skip parsing until START_TAG
4395 while ((type = parser.next()) != XmlPullParser.START_TAG
4396 && type != XmlPullParser.END_DOCUMENT) {}
4397 String firstNodeName = parser.getName();
4398 if (!NODE_SUBTYPES.equals(firstNodeName)) {
4399 throw new XmlPullParserException("Xml doesn't start with subtypes");
4400 }
4401 final int depth =parser.getDepth();
4402 String currentImiId = null;
4403 ArrayList<InputMethodSubtype> tempSubtypesArray = null;
4404 while (((type = parser.next()) != XmlPullParser.END_TAG
4405 || parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
4406 if (type != XmlPullParser.START_TAG)
4407 continue;
4408 final String nodeName = parser.getName();
4409 if (NODE_IMI.equals(nodeName)) {
4410 currentImiId = parser.getAttributeValue(null, ATTR_ID);
4411 if (TextUtils.isEmpty(currentImiId)) {
4412 Slog.w(TAG, "Invalid imi id found in subtypes.xml");
4413 continue;
4414 }
Yohei Yukawab0377bb2015-08-10 21:06:30 -07004415 tempSubtypesArray = new ArrayList<>();
satoke7c6998e2011-06-03 17:57:59 +09004416 allSubtypes.put(currentImiId, tempSubtypesArray);
4417 } else if (NODE_SUBTYPE.equals(nodeName)) {
4418 if (TextUtils.isEmpty(currentImiId) || tempSubtypesArray == null) {
4419 Slog.w(TAG, "IME uninstalled or not valid.: " + currentImiId);
4420 continue;
4421 }
Narayan Kamatha09b4d22016-04-15 18:32:45 +01004422 final int icon = Integer.parseInt(
satoke7c6998e2011-06-03 17:57:59 +09004423 parser.getAttributeValue(null, ATTR_ICON));
Narayan Kamatha09b4d22016-04-15 18:32:45 +01004424 final int label = Integer.parseInt(
satoke7c6998e2011-06-03 17:57:59 +09004425 parser.getAttributeValue(null, ATTR_LABEL));
4426 final String imeSubtypeLocale =
4427 parser.getAttributeValue(null, ATTR_IME_SUBTYPE_LOCALE);
Yohei Yukawa868d19b2015-12-07 15:58:57 -08004428 final String languageTag =
4429 parser.getAttributeValue(null, ATTR_IME_SUBTYPE_LANGUAGE_TAG);
satoke7c6998e2011-06-03 17:57:59 +09004430 final String imeSubtypeMode =
4431 parser.getAttributeValue(null, ATTR_IME_SUBTYPE_MODE);
4432 final String imeSubtypeExtraValue =
4433 parser.getAttributeValue(null, ATTR_IME_SUBTYPE_EXTRA_VALUE);
satok4a28bde2011-06-29 21:03:40 +09004434 final boolean isAuxiliary = "1".equals(String.valueOf(
4435 parser.getAttributeValue(null, ATTR_IS_AUXILIARY)));
Yohei Yukawa1e1a4472016-03-10 23:46:07 -08004436 final boolean isAsciiCapable = "1".equals(String.valueOf(
4437 parser.getAttributeValue(null, ATTR_IS_ASCII_CAPABLE)));
Yohei Yukawa66baf692016-04-11 02:29:35 -07004438 final InputMethodSubtypeBuilder builder = new InputMethodSubtypeBuilder()
Yohei Yukawa443c2ba2014-09-10 14:10:30 +09004439 .setSubtypeNameResId(label)
4440 .setSubtypeIconResId(icon)
4441 .setSubtypeLocale(imeSubtypeLocale)
Yohei Yukawa868d19b2015-12-07 15:58:57 -08004442 .setLanguageTag(languageTag)
Yohei Yukawa443c2ba2014-09-10 14:10:30 +09004443 .setSubtypeMode(imeSubtypeMode)
4444 .setSubtypeExtraValue(imeSubtypeExtraValue)
4445 .setIsAuxiliary(isAuxiliary)
Yohei Yukawa66baf692016-04-11 02:29:35 -07004446 .setIsAsciiCapable(isAsciiCapable);
4447 final String subtypeIdString =
4448 parser.getAttributeValue(null, ATTR_IME_SUBTYPE_ID);
4449 if (subtypeIdString != null) {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01004450 builder.setSubtypeId(Integer.parseInt(subtypeIdString));
Yohei Yukawa66baf692016-04-11 02:29:35 -07004451 }
4452 tempSubtypesArray.add(builder.build());
satoke7c6998e2011-06-03 17:57:59 +09004453 }
4454 }
Yohei Yukawa5894b432015-08-11 13:29:24 -07004455 } catch (XmlPullParserException | IOException | NumberFormatException e) {
4456 Slog.w(TAG, "Error reading subtypes", e);
satoke7c6998e2011-06-03 17:57:59 +09004457 return;
satoke7c6998e2011-06-03 17:57:59 +09004458 }
4459 }
4460 }
4461
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07004462 private static final class LocalServiceImpl implements InputMethodManagerInternal {
4463 @NonNull
4464 private final Handler mHandler;
4465
4466 LocalServiceImpl(@NonNull final Handler handler) {
4467 mHandler = handler;
4468 }
4469
4470 @Override
4471 public void setInteractive(boolean interactive) {
4472 // Do everything in handler so as not to block the caller.
4473 mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_INTERACTIVE,
4474 interactive ? 1 : 0, 0));
4475 }
Yohei Yukawaae61f712015-12-09 13:00:10 -08004476
4477 @Override
4478 public void switchInputMethod(boolean forwardDirection) {
4479 // Do everything in handler so as not to block the caller.
4480 mHandler.sendMessage(mHandler.obtainMessage(MSG_SWITCH_IME,
4481 forwardDirection ? 1 : 0, 0));
4482 }
Jorim Jaggi3c5d0f12016-05-24 19:04:30 -07004483
4484 @Override
4485 public void hideCurrentInputMethod() {
4486 mHandler.removeMessages(MSG_HIDE_CURRENT_INPUT_METHOD);
4487 mHandler.sendEmptyMessage(MSG_HIDE_CURRENT_INPUT_METHOD);
4488 }
Tarandeep Singh89a6c482017-11-21 14:26:11 -08004489
4490 @Override
4491 public void startVrInputMethodNoCheck(@Nullable ComponentName componentName) {
4492 mHandler.sendMessage(mHandler.obtainMessage(MSG_START_VR_INPUT, componentName));
4493 }
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07004494 }
4495
Yohei Yukawaebda7d72016-04-02 17:39:23 -07004496 private static String imeWindowStatusToString(final int imeWindowVis) {
4497 final StringBuilder sb = new StringBuilder();
4498 boolean first = true;
4499 if ((imeWindowVis & InputMethodService.IME_ACTIVE) != 0) {
4500 sb.append("Active");
4501 first = false;
4502 }
4503 if ((imeWindowVis & InputMethodService.IME_VISIBLE) != 0) {
4504 if (!first) {
4505 sb.append("|");
4506 }
4507 sb.append("Visible");
4508 }
4509 return sb.toString();
4510 }
4511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004512 @Override
Yohei Yukawa25e08132016-06-22 16:31:41 -07004513 public IInputContentUriToken createInputContentUriToken(@Nullable IBinder token,
4514 @Nullable Uri contentUri, @Nullable String packageName) {
4515 if (!calledFromValidUser()) {
4516 return null;
4517 }
4518
4519 if (token == null) {
4520 throw new NullPointerException("token");
4521 }
4522 if (packageName == null) {
4523 throw new NullPointerException("packageName");
4524 }
4525 if (contentUri == null) {
4526 throw new NullPointerException("contentUri");
4527 }
4528 final String contentUriScheme = contentUri.getScheme();
4529 if (!"content".equals(contentUriScheme)) {
4530 throw new InvalidParameterException("contentUri must have content scheme");
4531 }
4532
4533 synchronized (mMethodMap) {
4534 final int uid = Binder.getCallingUid();
4535 if (mCurMethodId == null) {
4536 return null;
4537 }
4538 if (mCurToken != token) {
4539 Slog.e(TAG, "Ignoring createInputContentUriToken mCurToken=" + mCurToken
4540 + " token=" + token);
4541 return null;
4542 }
4543 // We cannot simply distinguish a bad IME that reports an arbitrary package name from
4544 // an unfortunate IME whose internal state is already obsolete due to the asynchronous
4545 // nature of our system. Let's compare it with our internal record.
4546 if (!TextUtils.equals(mCurAttribute.packageName, packageName)) {
4547 Slog.e(TAG, "Ignoring createInputContentUriToken mCurAttribute.packageName="
4548 + mCurAttribute.packageName + " packageName=" + packageName);
4549 return null;
4550 }
Yohei Yukawa3933a6e2016-11-10 00:47:48 -08004551 // This user ID can never bee spoofed.
Yohei Yukawa25e08132016-06-22 16:31:41 -07004552 final int imeUserId = UserHandle.getUserId(uid);
Yohei Yukawa3933a6e2016-11-10 00:47:48 -08004553 // This user ID can never bee spoofed.
Yohei Yukawa25e08132016-06-22 16:31:41 -07004554 final int appUserId = UserHandle.getUserId(mCurClient.uid);
Yohei Yukawa3933a6e2016-11-10 00:47:48 -08004555 // This user ID may be invalid if "contentUri" embedded an invalid user ID.
4556 final int contentUriOwnerUserId = ContentProvider.getUserIdFromUri(contentUri,
4557 imeUserId);
4558 final Uri contentUriWithoutUserId = ContentProvider.getUriWithoutUserId(contentUri);
4559 // Note: InputContentUriTokenHandler.take() checks whether the IME (specified by "uid")
4560 // actually has the right to grant a read permission for "contentUriWithoutUserId" that
4561 // is claimed to belong to "contentUriOwnerUserId". For example, specifying random
4562 // content URI and/or contentUriOwnerUserId just results in a SecurityException thrown
4563 // from InputContentUriTokenHandler.take() and can never be allowed beyond what is
4564 // actually allowed to "uid", which is guaranteed to be the IME's one.
4565 return new InputContentUriTokenHandler(contentUriWithoutUserId, uid,
4566 packageName, contentUriOwnerUserId, appUserId);
Yohei Yukawa25e08132016-06-22 16:31:41 -07004567 }
4568 }
4569
4570 @Override
Yohei Yukawa2bc66172017-02-08 11:13:25 -08004571 public void reportFullscreenMode(IBinder token, boolean fullscreen) {
4572 if (!calledFromValidUser()) {
4573 return;
4574 }
4575 synchronized (mMethodMap) {
4576 if (!calledWithValidToken(token)) {
4577 return;
4578 }
4579 if (mCurClient != null && mCurClient.client != null) {
4580 mInFullscreenMode = fullscreen;
4581 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
4582 MSG_REPORT_FULLSCREEN_MODE, fullscreen ? 1 : 0, mCurClient));
4583 }
4584 }
4585 }
4586
4587 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004588 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06004589 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004590
4591 IInputMethod method;
4592 ClientState client;
Yohei Yukawae39d4ed2015-11-19 03:38:49 -08004593 ClientState focusedWindowClient;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004595 final Printer p = new PrintWriterPrinter(pw);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004597 synchronized (mMethodMap) {
4598 p.println("Current Input Method Manager state:");
4599 int N = mMethodList.size();
Yohei Yukawae0733062017-02-09 22:49:35 -08004600 p.println(" Input Methods: mMethodMapUpdateCount=" + mMethodMapUpdateCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004601 for (int i=0; i<N; i++) {
4602 InputMethodInfo info = mMethodList.get(i);
4603 p.println(" InputMethod #" + i + ":");
4604 info.dump(p, " ");
4605 }
4606 p.println(" Clients:");
4607 for (ClientState ci : mClients.values()) {
4608 p.println(" Client " + ci + ":");
4609 p.println(" client=" + ci.client);
4610 p.println(" inputContext=" + ci.inputContext);
4611 p.println(" sessionRequested=" + ci.sessionRequested);
4612 p.println(" curSession=" + ci.curSession);
4613 }
The Android Open Source Project10592532009-03-18 17:39:46 -07004614 p.println(" mCurMethodId=" + mCurMethodId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004615 client = mCurClient;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004616 p.println(" mCurClient=" + client + " mCurSeq=" + mCurSeq);
Yohei Yukawa22a89232017-02-12 16:38:59 -08004617 p.println(" mCurFocusedWindow=" + mCurFocusedWindow
4618 + " softInputMode=" +
4619 InputMethodClient.softInputModeToString(mCurFocusedWindowSoftInputMode)
4620 + " client=" + mCurFocusedWindowClient);
Yohei Yukawae39d4ed2015-11-19 03:38:49 -08004621 focusedWindowClient = mCurFocusedWindowClient;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004622 p.println(" mCurId=" + mCurId + " mHaveConnect=" + mHaveConnection
4623 + " mBoundToMethod=" + mBoundToMethod);
4624 p.println(" mCurToken=" + mCurToken);
4625 p.println(" mCurIntent=" + mCurIntent);
4626 method = mCurMethod;
4627 p.println(" mCurMethod=" + mCurMethod);
4628 p.println(" mEnabledSession=" + mEnabledSession);
Yohei Yukawaebda7d72016-04-02 17:39:23 -07004629 p.println(" mImeWindowVis=" + imeWindowStatusToString(mImeWindowVis));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004630 p.println(" mShowRequested=" + mShowRequested
4631 + " mShowExplicitlyRequested=" + mShowExplicitlyRequested
4632 + " mShowForced=" + mShowForced
4633 + " mInputShown=" + mInputShown);
Yohei Yukawa2bc66172017-02-08 11:13:25 -08004634 p.println(" mInFullscreenMode=" + mInFullscreenMode);
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09004635 p.println(" mCurUserActionNotificationSequenceNumber="
4636 + mCurUserActionNotificationSequenceNumber);
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07004637 p.println(" mSystemReady=" + mSystemReady + " mInteractive=" + mIsInteractive);
Yohei Yukawa81482972015-06-04 00:58:59 -07004638 p.println(" mSettingsObserver=" + mSettingsObserver);
Yohei Yukawad7248862015-06-03 23:56:12 -07004639 p.println(" mSwitchingController:");
4640 mSwitchingController.dump(p);
Yohei Yukawa68645a62016-02-17 07:54:20 -08004641 p.println(" mSettings:");
4642 mSettings.dumpLocked(p, " ");
Yohei Yukawa357b2f62017-02-14 09:40:03 -08004643
4644 p.println(" mStartInputHistory:");
4645 mStartInputHistory.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004646 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004647
Jeff Brownb88102f2010-09-08 11:49:43 -07004648 p.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004649 if (client != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004650 pw.flush();
4651 try {
Jeff Sharkey850c83e2016-11-09 12:25:44 -07004652 TransferPipe.dumpAsync(client.client.asBinder(), fd, args);
4653 } catch (IOException | RemoteException e) {
4654 p.println("Failed to dump input method client: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004655 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004656 } else {
4657 p.println("No input method client.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004658 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004659
Yohei Yukawae39d4ed2015-11-19 03:38:49 -08004660 if (focusedWindowClient != null && client != focusedWindowClient) {
4661 p.println(" ");
4662 p.println("Warning: Current input method client doesn't match the last focused. "
4663 + "window.");
4664 p.println("Dumping input method client in the last focused window just in case.");
4665 p.println(" ");
4666 pw.flush();
4667 try {
Jeff Sharkey850c83e2016-11-09 12:25:44 -07004668 TransferPipe.dumpAsync(focusedWindowClient.client.asBinder(), fd, args);
4669 } catch (IOException | RemoteException e) {
4670 p.println("Failed to dump input method client in focused window: " + e);
Yohei Yukawae39d4ed2015-11-19 03:38:49 -08004671 }
4672 }
4673
Jeff Brownb88102f2010-09-08 11:49:43 -07004674 p.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004675 if (method != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004676 pw.flush();
4677 try {
Jeff Sharkey850c83e2016-11-09 12:25:44 -07004678 TransferPipe.dumpAsync(method.asBinder(), fd, args);
4679 } catch (IOException | RemoteException e) {
4680 p.println("Failed to dump input method service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004681 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004682 } else {
4683 p.println("No input method service.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004684 }
4685 }
Yohei Yukawa926488d2017-12-11 17:24:55 -08004686
4687 @BinderThread
4688 @Override
4689 public void onShellCommand(@Nullable FileDescriptor in, @Nullable FileDescriptor out,
4690 @Nullable FileDescriptor err,
4691 @NonNull String[] args, @Nullable ShellCallback callback,
4692 @NonNull ResultReceiver resultReceiver) throws RemoteException {
4693 new ShellCommandImpl(this).exec(
4694 this, in, out, err, args, callback, resultReceiver);
4695 }
4696
4697 private static final class ShellCommandImpl extends ShellCommand {
4698 @NonNull
4699 final InputMethodManagerService mService;
4700
4701 ShellCommandImpl(InputMethodManagerService service) {
4702 mService = service;
4703 }
4704
4705 @BinderThread
4706 @ShellCommandResult
4707 @Override
4708 public int onCommand(@Nullable String cmd) {
Yohei Yukawadfdab732018-02-21 07:16:30 +09004709 if ("refresh_debug_properties".equals(cmd)) {
4710 return refreshDebugProperties();
4711 }
4712
Yohei Yukawacac97722017-12-15 16:52:05 -08004713 // For existing "adb shell ime <command>".
4714 if ("ime".equals(cmd)) {
4715 final String imeCommand = getNextArg();
4716 if (imeCommand == null || "help".equals(imeCommand) || "-h".equals(imeCommand)) {
4717 onImeCommandHelp();
4718 return ShellCommandResult.SUCCESS;
4719 }
4720 switch (imeCommand) {
4721 case "list":
4722 return mService.handleShellCommandListInputMethods(this);
4723 case "enable":
4724 return mService.handleShellCommandEnableDisableInputMethod(this, true);
4725 case "disable":
4726 return mService.handleShellCommandEnableDisableInputMethod(this, false);
4727 case "set":
4728 return mService.handleShellCommandSetInputMethod(this);
4729 case "reset":
4730 return mService.handleShellCommandResetInputMethod(this);
4731 default:
4732 getOutPrintWriter().println("Unknown command: " + imeCommand);
4733 return ShellCommandResult.FAILURE;
4734 }
Yohei Yukawa926488d2017-12-11 17:24:55 -08004735 }
Yohei Yukawacac97722017-12-15 16:52:05 -08004736
4737 return handleDefaultCommands(cmd);
Yohei Yukawa926488d2017-12-11 17:24:55 -08004738 }
4739
4740 @BinderThread
Tarandeep Singh75a92392018-01-12 14:58:59 -08004741 @ShellCommandResult
4742 private int refreshDebugProperties() {
4743 DebugFlags.FLAG_OPTIMIZE_START_INPUT.refresh();
4744 return ShellCommandResult.SUCCESS;
4745 }
4746
4747 @BinderThread
Yohei Yukawa926488d2017-12-11 17:24:55 -08004748 @Override
4749 public void onHelp() {
4750 try (PrintWriter pw = getOutPrintWriter()) {
4751 pw.println("InputMethodManagerService commands:");
4752 pw.println(" help");
4753 pw.println(" Prints this help text.");
4754 pw.println(" dump [options]");
4755 pw.println(" Synonym of dumpsys.");
Yohei Yukawacac97722017-12-15 16:52:05 -08004756 pw.println(" ime <command> [options]");
4757 pw.println(" Manipulate IMEs. Run \"ime help\" for details.");
4758 }
4759 }
4760
4761 private void onImeCommandHelp() {
4762 try (IndentingPrintWriter pw =
4763 new IndentingPrintWriter(getOutPrintWriter(), " ", 100)) {
4764 pw.println("ime <command>:");
4765 pw.increaseIndent();
4766
4767 pw.println("list [-a] [-s]");
4768 pw.increaseIndent();
4769 pw.println("prints all enabled input methods.");
4770 pw.increaseIndent();
4771 pw.println("-a: see all input methods");
4772 pw.println("-s: only a single summary line of each");
4773 pw.decreaseIndent();
4774 pw.decreaseIndent();
4775
4776 pw.println("enable <ID>");
4777 pw.increaseIndent();
4778 pw.println("allows the given input method ID to be used.");
4779 pw.decreaseIndent();
4780
4781 pw.println("disable <ID>");
4782 pw.increaseIndent();
4783 pw.println("disallows the given input method ID to be used.");
4784 pw.decreaseIndent();
4785
4786 pw.println("set <ID>");
4787 pw.increaseIndent();
4788 pw.println("switches to the given input method ID.");
4789 pw.decreaseIndent();
4790
4791 pw.println("reset");
4792 pw.increaseIndent();
4793 pw.println("reset currently selected/enabled IMEs to the default ones as if "
4794 + "the device is initially booted with the current locale.");
4795 pw.decreaseIndent();
4796
4797 pw.decreaseIndent();
Yohei Yukawa926488d2017-12-11 17:24:55 -08004798 }
4799 }
4800 }
4801
4802 // ----------------------------------------------------------------------
4803 // Shell command handlers:
4804
4805 /**
4806 * Handles {@code adb shell ime list}.
4807 * @param shellCommand {@link ShellCommand} object that is handling this command.
4808 * @return Exit code of the command.
4809 */
4810 @BinderThread
4811 @ShellCommandResult
4812 private int handleShellCommandListInputMethods(@NonNull ShellCommand shellCommand) {
4813 boolean all = false;
4814 boolean brief = false;
4815 while (true) {
4816 final String nextOption = shellCommand.getNextOption();
4817 if (nextOption == null) {
4818 break;
4819 }
4820 switch (nextOption) {
4821 case "-a":
4822 all = true;
4823 break;
4824 case "-s":
4825 brief = true;
4826 break;
4827 }
4828 }
4829 final List<InputMethodInfo> methods = all ?
4830 getInputMethodList() : getEnabledInputMethodList();
4831 final PrintWriter pr = shellCommand.getOutPrintWriter();
4832 final Printer printer = x -> pr.println(x);
4833 final int N = methods.size();
4834 for (int i = 0; i < N; ++i) {
4835 if (brief) {
4836 pr.println(methods.get(i).getId());
4837 } else {
4838 pr.print(methods.get(i).getId()); pr.println(":");
4839 methods.get(i).dump(printer, " ");
4840 }
4841 }
4842 return ShellCommandResult.SUCCESS;
4843 }
4844
4845 /**
4846 * Handles {@code adb shell ime enable} and {@code adb shell ime disable}.
4847 * @param shellCommand {@link ShellCommand} object that is handling this command.
4848 * @param enabled {@code true} if the command was {@code adb shell ime enable}.
4849 * @return Exit code of the command.
4850 */
4851 @BinderThread
4852 @ShellCommandResult
4853 @RequiresPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
4854 private int handleShellCommandEnableDisableInputMethod(
4855 @NonNull ShellCommand shellCommand, boolean enabled) {
4856 if (!calledFromValidUser()) {
4857 shellCommand.getErrPrintWriter().print(
4858 "Must be called from the foreground user or with INTERACT_ACROSS_USERS_FULL");
4859 return ShellCommandResult.FAILURE;
4860 }
4861 final String id = shellCommand.getNextArgRequired();
4862
4863 final boolean previouslyEnabled;
4864 synchronized (mMethodMap) {
4865 if (mContext.checkCallingOrSelfPermission(
4866 android.Manifest.permission.WRITE_SECURE_SETTINGS)
4867 != PackageManager.PERMISSION_GRANTED) {
4868 shellCommand.getErrPrintWriter().print(
4869 "Caller must have WRITE_SECURE_SETTINGS permission");
4870 throw new SecurityException(
4871 "Requires permission "
4872 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
4873 }
4874
4875 final long ident = Binder.clearCallingIdentity();
4876 try {
4877 previouslyEnabled = setInputMethodEnabledLocked(id, enabled);
4878 } finally {
4879 Binder.restoreCallingIdentity(ident);
4880 }
4881 }
4882 final PrintWriter pr = shellCommand.getOutPrintWriter();
4883 pr.print("Input method ");
4884 pr.print(id);
4885 pr.print(": ");
4886 pr.print((enabled == previouslyEnabled) ? "already " : "now ");
4887 pr.println(enabled ? "enabled" : "disabled");
4888 return ShellCommandResult.SUCCESS;
4889 }
4890
4891 /**
4892 * Handles {@code adb shell ime set}.
4893 * @param shellCommand {@link ShellCommand} object that is handling this command.
4894 * @return Exit code of the command.
4895 */
4896 @BinderThread
4897 @ShellCommandResult
4898 private int handleShellCommandSetInputMethod(@NonNull ShellCommand shellCommand) {
4899 final String id = shellCommand.getNextArgRequired();
4900 setInputMethod(null, id);
4901 final PrintWriter pr = shellCommand.getOutPrintWriter();
4902 pr.print("Input method ");
4903 pr.print(id);
4904 pr.println(" selected");
4905 return ShellCommandResult.SUCCESS;
4906 }
Yohei Yukawacc97ebd2017-12-11 17:54:43 -08004907
4908 /**
4909 * Handles {@code adb shell ime reset-ime}.
4910 * @param shellCommand {@link ShellCommand} object that is handling this command.
4911 * @return Exit code of the command.
4912 */
4913 @BinderThread
4914 @ShellCommandResult
4915 @RequiresPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
4916 private int handleShellCommandResetInputMethod(@NonNull ShellCommand shellCommand) {
4917 if (!calledFromValidUser()) {
4918 shellCommand.getErrPrintWriter().print(
4919 "Must be called from the foreground user or with INTERACT_ACROSS_USERS_FULL");
4920 return ShellCommandResult.FAILURE;
4921 }
4922 synchronized (mMethodMap) {
4923 if (mContext.checkCallingOrSelfPermission(
4924 android.Manifest.permission.WRITE_SECURE_SETTINGS)
4925 != PackageManager.PERMISSION_GRANTED) {
4926 shellCommand.getErrPrintWriter().print(
4927 "Caller must have WRITE_SECURE_SETTINGS permission");
4928 throw new SecurityException(
4929 "Requires permission "
4930 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
4931 }
4932 final String nextIme;
4933 final List<InputMethodInfo> nextEnabledImes;
4934 final long ident = Binder.clearCallingIdentity();
4935 try {
4936 synchronized (mMethodMap) {
4937 hideCurrentInputLocked(0, null);
4938 unbindCurrentMethodLocked(false);
4939 // Reset the current IME
4940 resetSelectedInputMethodAndSubtypeLocked(null);
4941 // Also reset the settings of the current IME
4942 mSettings.putSelectedInputMethod(null);
4943 // Disable all enabled IMEs.
4944 {
4945 final ArrayList<InputMethodInfo> enabledImes =
4946 mSettings.getEnabledInputMethodListLocked();
4947 final int N = enabledImes.size();
4948 for (int i = 0; i < N; ++i) {
4949 setInputMethodEnabledLocked(enabledImes.get(i).getId(), false);
4950 }
4951 }
4952 // Re-enable with default enabled IMEs.
4953 {
4954 final ArrayList<InputMethodInfo> defaultEnabledIme =
4955 InputMethodUtils.getDefaultEnabledImes(mContext, mMethodList);
4956 final int N = defaultEnabledIme.size();
4957 for (int i = 0; i < N; ++i) {
4958 setInputMethodEnabledLocked(defaultEnabledIme.get(i).getId(), true);
4959 }
4960 }
4961 updateInputMethodsFromSettingsLocked(true /* enabledMayChange */);
4962 InputMethodUtils.setNonSelectedSystemImesDisabledUntilUsed(mIPackageManager,
4963 mSettings.getEnabledInputMethodListLocked(),
4964 mSettings.getCurrentUserId(),
4965 mContext.getBasePackageName());
4966 nextIme = mSettings.getSelectedInputMethod();
4967 nextEnabledImes = getEnabledInputMethodList();
4968 }
4969 } finally {
4970 Binder.restoreCallingIdentity(ident);
4971 }
4972 final PrintWriter pr = shellCommand.getOutPrintWriter();
4973 pr.println("Reset current and enabled IMEs");
4974 pr.println("Newly selected IME:");
4975 pr.print(" "); pr.println(nextIme);
4976 pr.println("Newly enabled IMEs:");
4977 {
4978 final int N = nextEnabledImes.size();
4979 for (int i = 0; i < N; ++i) {
4980 pr.print(" ");
4981 pr.println(nextEnabledImes.get(i).getId());
4982 }
4983 }
4984 return ShellCommandResult.SUCCESS;
4985 }
4986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004987}