blob: 19170f8ff5b0106bf794691d2b0de3c7ce4d0aae [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 /**
Yohei Yukawaf80087c2018-05-21 09:47:53 -0700624 * Whether we temporarily allow IMEs implemented in instant apps to run for testing.
625 *
626 * <p>Note: This is quite dangerous. Don't forget to reset after you finish testing.</p>
627 */
628 private boolean mBindInstantServiceAllowed = false;
629
630 /**
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800631 * Internal state snapshot when {@link #MSG_START_INPUT} message is about to be posted to the
632 * internal message queue. Any subsequent state change inside {@link InputMethodManagerService}
633 * will not affect those tasks that are already posted.
634 *
635 * <p>Posting {@link #MSG_START_INPUT} message basically means that
636 * {@link InputMethodService#doStartInput(InputConnection, EditorInfo, boolean)} will be called
637 * back in the current IME process shortly, which will also affect what the current IME starts
638 * receiving from {@link InputMethodService#getCurrentInputConnection()}. In other words, this
639 * snapshot will be taken every time when {@link InputMethodManagerService} is initiating a new
640 * logical input session between the client application and the current IME.</p>
641 *
642 * <p>Be careful to not keep strong references to this object forever, which can prevent
643 * {@link StartInputInfo#mImeToken} and {@link StartInputInfo#mTargetWindow} from being GC-ed.
644 * </p>
645 */
646 private static class StartInputInfo {
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800647 private static final AtomicInteger sSequenceNumber = new AtomicInteger(0);
648
649 final int mSequenceNumber;
650 final long mTimestamp;
651 final long mWallTime;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800652 @NonNull
653 final IBinder mImeToken;
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800654 @NonNull
655 final String mImeId;
656 // @InputMethodClient.StartInputReason
657 final int mStartInputReason;
658 final boolean mRestarting;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800659 @Nullable
660 final IBinder mTargetWindow;
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800661 @NonNull
662 final EditorInfo mEditorInfo;
663 final int mTargetWindowSoftInputMode;
664 final int mClientBindSequenceNumber;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800665
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800666 StartInputInfo(@NonNull IBinder imeToken, @NonNull String imeId,
667 /* @InputMethodClient.StartInputReason */ int startInputReason, boolean restarting,
668 @Nullable IBinder targetWindow, @NonNull EditorInfo editorInfo,
669 int targetWindowSoftInputMode, int clientBindSequenceNumber) {
670 mSequenceNumber = sSequenceNumber.getAndIncrement();
671 mTimestamp = SystemClock.uptimeMillis();
672 mWallTime = System.currentTimeMillis();
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800673 mImeToken = imeToken;
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800674 mImeId = imeId;
675 mStartInputReason = startInputReason;
676 mRestarting = restarting;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800677 mTargetWindow = targetWindow;
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800678 mEditorInfo = editorInfo;
679 mTargetWindowSoftInputMode = targetWindowSoftInputMode;
680 mClientBindSequenceNumber = clientBindSequenceNumber;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800681 }
682 }
683
Yohei Yukawab37d8bd2017-02-13 18:29:05 -0800684 @GuardedBy("mMethodMap")
685 private final WeakHashMap<IBinder, StartInputInfo> mStartInputMap = new WeakHashMap<>();
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -0800686
Yohei Yukawa357b2f62017-02-14 09:40:03 -0800687 /**
688 * A ring buffer to store the history of {@link StartInputInfo}.
689 */
690 private static final class StartInputHistory {
691 /**
692 * Entry size for non low-RAM devices.
693 *
694 * <p>TODO: Consider to follow what other system services have been doing to manage
695 * constants (e.g. {@link android.provider.Settings.Global#ACTIVITY_MANAGER_CONSTANTS}).</p>
696 */
697 private final static int ENTRY_SIZE_FOR_HIGH_RAM_DEVICE = 16;
698
699 /**
700 * Entry size for non low-RAM devices.
701 *
702 * <p>TODO: Consider to follow what other system services have been doing to manage
703 * constants (e.g. {@link android.provider.Settings.Global#ACTIVITY_MANAGER_CONSTANTS}).</p>
704 */
705 private final static int ENTRY_SIZE_FOR_LOW_RAM_DEVICE = 5;
706
707 private static int getEntrySize() {
708 if (ActivityManager.isLowRamDeviceStatic()) {
709 return ENTRY_SIZE_FOR_LOW_RAM_DEVICE;
710 } else {
711 return ENTRY_SIZE_FOR_HIGH_RAM_DEVICE;
712 }
713 }
714
715 /**
716 * Backing store for the ring bugger.
717 */
718 private final Entry[] mEntries = new Entry[getEntrySize()];
719
720 /**
721 * An index of {@link #mEntries}, to which next {@link #addEntry(StartInputInfo)} should
722 * write.
723 */
724 private int mNextIndex = 0;
725
726 /**
727 * Recyclable entry to store the information in {@link StartInputInfo}.
728 */
729 private static final class Entry {
730 int mSequenceNumber;
731 long mTimestamp;
732 long mWallTime;
733 @NonNull
734 String mImeTokenString;
735 @NonNull
736 String mImeId;
737 /* @InputMethodClient.StartInputReason */
738 int mStartInputReason;
739 boolean mRestarting;
740 @NonNull
741 String mTargetWindowString;
742 @NonNull
743 EditorInfo mEditorInfo;
744 int mTargetWindowSoftInputMode;
745 int mClientBindSequenceNumber;
746
747 Entry(@NonNull StartInputInfo original) {
748 set(original);
749 }
750
751 void set(@NonNull StartInputInfo original) {
752 mSequenceNumber = original.mSequenceNumber;
753 mTimestamp = original.mTimestamp;
754 mWallTime = original.mWallTime;
755 // Intentionally convert to String so as not to keep a strong reference to a Binder
756 // object.
757 mImeTokenString = String.valueOf(original.mImeToken);
758 mImeId = original.mImeId;
759 mStartInputReason = original.mStartInputReason;
760 mRestarting = original.mRestarting;
761 // Intentionally convert to String so as not to keep a strong reference to a Binder
762 // object.
763 mTargetWindowString = String.valueOf(original.mTargetWindow);
764 mEditorInfo = original.mEditorInfo;
765 mTargetWindowSoftInputMode = original.mTargetWindowSoftInputMode;
766 mClientBindSequenceNumber = original.mClientBindSequenceNumber;
767 }
768 }
769
770 /**
771 * Add a new entry and discard the oldest entry as needed.
772 * @param info {@lin StartInputInfo} to be added.
773 */
774 void addEntry(@NonNull StartInputInfo info) {
775 final int index = mNextIndex;
776 if (mEntries[index] == null) {
777 mEntries[index] = new Entry(info);
778 } else {
779 mEntries[index].set(info);
780 }
781 mNextIndex = (mNextIndex + 1) % mEntries.length;
782 }
783
784 void dump(@NonNull PrintWriter pw, @NonNull String prefix) {
785 final SimpleDateFormat dataFormat =
786 new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US);
787
788 for (int i = 0; i < mEntries.length; ++i) {
789 final Entry entry = mEntries[(i + mNextIndex) % mEntries.length];
790 if (entry == null) {
791 continue;
792 }
793 pw.print(prefix);
794 pw.println("StartInput #" + entry.mSequenceNumber + ":");
795
796 pw.print(prefix);
797 pw.println(" time=" + dataFormat.format(new Date(entry.mWallTime))
798 + " (timestamp=" + entry.mTimestamp + ")"
799 + " reason="
800 + InputMethodClient.getStartInputReason(entry.mStartInputReason)
801 + " restarting=" + entry.mRestarting);
802
803 pw.print(prefix);
804 pw.println(" imeToken=" + entry.mImeTokenString + " [" + entry.mImeId + "]");
805
806 pw.print(prefix);
807 pw.println(" targetWin=" + entry.mTargetWindowString
808 + " [" + entry.mEditorInfo.packageName + "]"
809 + " clientBindSeq=" + entry.mClientBindSequenceNumber);
810
811 pw.print(prefix);
812 pw.println(" softInputMode=" + InputMethodClient.softInputModeToString(
813 entry.mTargetWindowSoftInputMode));
814
815 pw.print(prefix);
816 pw.println(" inputType=0x" + Integer.toHexString(entry.mEditorInfo.inputType)
817 + " imeOptions=0x" + Integer.toHexString(entry.mEditorInfo.imeOptions)
818 + " fieldId=0x" + Integer.toHexString(entry.mEditorInfo.fieldId)
819 + " fieldName=" + entry.mEditorInfo.fieldName
820 + " actionId=" + entry.mEditorInfo.actionId
821 + " actionLabel=" + entry.mEditorInfo.actionLabel);
822 }
823 }
824 }
825
826 @GuardedBy("mMethodMap")
827 @NonNull
828 private final StartInputHistory mStartInputHistory = new StartInputHistory();
829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 class SettingsObserver extends ContentObserver {
Yohei Yukawa81482972015-06-04 00:58:59 -0700831 int mUserId;
832 boolean mRegistered = false;
Yohei Yukawa7b574cb2016-03-16 17:22:22 -0700833 @NonNull
Dianne Hackbornfd7aded2013-01-22 17:10:23 -0800834 String mLastEnabled = "";
835
Yohei Yukawa81482972015-06-04 00:58:59 -0700836 /**
837 * <em>This constructor must be called within the lock.</em>
838 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 SettingsObserver(Handler handler) {
840 super(handler);
Yohei Yukawa81482972015-06-04 00:58:59 -0700841 }
842
Yohei Yukawa7b18aec2016-03-07 13:04:32 -0800843 public void registerContentObserverLocked(@UserIdInt int userId) {
Yohei Yukawa81482972015-06-04 00:58:59 -0700844 if (mRegistered && mUserId == userId) {
845 return;
846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 ContentResolver resolver = mContext.getContentResolver();
Yohei Yukawa81482972015-06-04 00:58:59 -0700848 if (mRegistered) {
849 mContext.getContentResolver().unregisterContentObserver(this);
850 mRegistered = false;
851 }
852 if (mUserId != userId) {
853 mLastEnabled = "";
854 mUserId = userId;
855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 resolver.registerContentObserver(Settings.Secure.getUriFor(
Yohei Yukawa81482972015-06-04 00:58:59 -0700857 Settings.Secure.DEFAULT_INPUT_METHOD), false, this, userId);
satokab751aa2010-09-14 19:17:36 +0900858 resolver.registerContentObserver(Settings.Secure.getUriFor(
Yohei Yukawa81482972015-06-04 00:58:59 -0700859 Settings.Secure.ENABLED_INPUT_METHODS), false, this, userId);
satokb6109bb2011-02-03 22:24:54 +0900860 resolver.registerContentObserver(Settings.Secure.getUriFor(
Yohei Yukawa81482972015-06-04 00:58:59 -0700861 Settings.Secure.SELECTED_INPUT_METHOD_SUBTYPE), false, this, userId);
Michael Wright7b5a96b2014-08-09 19:28:42 -0700862 resolver.registerContentObserver(Settings.Secure.getUriFor(
Yohei Yukawa81482972015-06-04 00:58:59 -0700863 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD), false, this, userId);
Anna Galusza9b278112016-01-04 11:37:37 -0800864 resolver.registerContentObserver(Settings.Secure.getUriFor(
865 Settings.Secure.ACCESSIBILITY_SOFT_KEYBOARD_MODE), false, this, userId);
Yohei Yukawa81482972015-06-04 00:58:59 -0700866 mRegistered = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800868
Michael Wright7b5a96b2014-08-09 19:28:42 -0700869 @Override public void onChange(boolean selfChange, Uri uri) {
Anna Galusza9b278112016-01-04 11:37:37 -0800870 final Uri showImeUri = Settings.Secure.getUriFor(
871 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
872 final Uri accessibilityRequestingNoImeUri = Settings.Secure.getUriFor(
873 Settings.Secure.ACCESSIBILITY_SOFT_KEYBOARD_MODE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 synchronized (mMethodMap) {
Michael Wright7b5a96b2014-08-09 19:28:42 -0700875 if (showImeUri.equals(uri)) {
876 updateKeyboardFromSettingsLocked();
Anna Galusza9b278112016-01-04 11:37:37 -0800877 } else if (accessibilityRequestingNoImeUri.equals(uri)) {
878 mAccessibilityRequestingNoSoftKeyboard = Settings.Secure.getIntForUser(
879 mContext.getContentResolver(),
880 Settings.Secure.ACCESSIBILITY_SOFT_KEYBOARD_MODE,
881 0, mUserId) == 1;
882 if (mAccessibilityRequestingNoSoftKeyboard) {
883 final boolean showRequested = mShowRequested;
884 hideCurrentInputLocked(0, null);
885 mShowRequested = showRequested;
886 } else if (mShowRequested) {
887 showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
888 }
Michael Wright7b5a96b2014-08-09 19:28:42 -0700889 } else {
890 boolean enabledChanged = false;
891 String newEnabled = mSettings.getEnabledInputMethodsStr();
892 if (!mLastEnabled.equals(newEnabled)) {
893 mLastEnabled = newEnabled;
894 enabledChanged = true;
895 }
896 updateInputMethodsFromSettingsLocked(enabledChanged);
Dianne Hackbornfd7aded2013-01-22 17:10:23 -0800897 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 }
899 }
Yohei Yukawa81482972015-06-04 00:58:59 -0700900
901 @Override
902 public String toString() {
903 return "SettingsObserver{mUserId=" + mUserId + " mRegistered=" + mRegistered
904 + " mLastEnabled=" + mLastEnabled + "}";
905 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800907
Yohei Yukawa79247822017-01-23 15:26:15 -0800908 class ImmsBroadcastReceiver extends BroadcastReceiver {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +0900909 @Override
910 public void onReceive(Context context, Intent intent) {
911 final String action = intent.getAction();
Yohei Yukawafa6e0a82015-07-23 15:08:59 -0700912 if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +0900913 hideInputMethodMenu();
Yohei Yukawafa6e0a82015-07-23 15:08:59 -0700914 // No need to update mIsInteractive
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +0900915 return;
Amith Yamasani734983f2014-03-04 16:48:05 -0800916 } else if (Intent.ACTION_USER_ADDED.equals(action)
917 || Intent.ACTION_USER_REMOVED.equals(action)) {
Kenny Guy2a764942014-04-02 13:29:20 +0100918 updateCurrentProfileIds();
Amith Yamasani734983f2014-03-04 16:48:05 -0800919 return;
Yohei Yukawa79247822017-01-23 15:26:15 -0800920 } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Yohei Yukawa0d7aff82017-02-10 00:40:51 -0800921 onActionLocaleChanged();
Tadashi G. Takaoka01065a52017-07-19 14:10:24 +0900922 } else if (ACTION_SHOW_INPUT_METHOD_PICKER.equals(action)) {
923 // ACTION_SHOW_INPUT_METHOD_PICKER action is a protected-broadcast and it is
924 // guaranteed to be send only from the system, so that there is no need for extra
925 // security check such as
926 // {@link #canShowInputMethodPickerLocked(IInputMethodClient)}.
927 mHandler.obtainMessage(
928 MSG_SHOW_IM_SUBTYPE_PICKER,
929 InputMethodManager.SHOW_IM_PICKER_MODE_INCLUDE_AUXILIARY_SUBTYPES,
930 0 /* arg2 */)
931 .sendToTarget();
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +0900932 } else {
933 Slog.w(TAG, "Unexpected intent " + intent);
934 }
935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800937
Yohei Yukawa0d7aff82017-02-10 00:40:51 -0800938 /**
Tarandeep Singh89a6c482017-11-21 14:26:11 -0800939 * Start a VR InputMethod that matches IME with package name of {@param component}.
Yohei Yukawa7a46c282017-12-10 18:15:19 -0800940 * Note: This method is called from {@link android.app.VrManager}.
Tarandeep Singh89a6c482017-11-21 14:26:11 -0800941 */
942 private void startVrInputMethodNoCheck(@Nullable ComponentName component) {
943 if (component == null) {
944 // clear the current VR-only IME (if any) and restore normal IME.
945 restoreNonVrImeFromSettingsNoCheck();
946 return;
947 }
948
949 synchronized (mMethodMap) {
950 String packageName = component.getPackageName();
951 for (InputMethodInfo info : mMethodList) {
952 if (TextUtils.equals(info.getPackageName(), packageName) && info.isVrOnly()) {
953 // set this is as current inputMethod without updating settings.
Yohei Yukawa7a46c282017-12-10 18:15:19 -0800954 setInputMethodEnabledLocked(info.getId(), true);
Tarandeep Singh89a6c482017-11-21 14:26:11 -0800955 setInputMethodLocked(info.getId(), NOT_A_SUBTYPE_ID);
956 break;
957 }
958 }
959 }
960 }
961
962 /**
Yohei Yukawa0d7aff82017-02-10 00:40:51 -0800963 * Handles {@link Intent#ACTION_LOCALE_CHANGED}.
964 *
965 * <p>Note: For historical reasons, {@link Intent#ACTION_LOCALE_CHANGED} has been sent to all
966 * the users. We should ignore this event if this is about any background user's locale.</p>
967 *
968 * <p>Caution: This method must not be called when system is not ready.</p>
969 */
970 void onActionLocaleChanged() {
971 synchronized (mMethodMap) {
972 final LocaleList possibleNewLocale = mRes.getConfiguration().getLocales();
973 if (possibleNewLocale != null && possibleNewLocale.equals(mLastSystemLocales)) {
974 return;
975 }
976 buildInputMethodListLocked(true);
977 // If the locale is changed, needs to reset the default ime
978 resetDefaultImeLocked(mContext);
979 updateFromSettingsLocked(true);
980 mLastSystemLocales = possibleNewLocale;
981 }
982 }
983
Yohei Yukawac4e44912017-02-09 19:30:22 -0800984 final class MyPackageMonitor extends PackageMonitor {
985 /**
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -0800986 * Package names that are known to contain {@link InputMethodService}.
Yohei Yukawac4e44912017-02-09 19:30:22 -0800987 *
988 * <p>No need to include packages because of direct-boot unaware IMEs since we always rescan
989 * all the packages when the user is unlocked, and direct-boot awareness will not be changed
990 * dynamically unless the entire package is updated, which also always triggers package
991 * rescanning.</p>
992 */
993 @GuardedBy("mMethodMap")
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -0800994 final private ArraySet<String> mKnownImePackageNames = new ArraySet<>();
995
996 /**
997 * Packages that are appeared, disappeared, or modified for whatever reason.
998 *
999 * <p>Note: For now we intentionally use {@link ArrayList} instead of {@link ArraySet}
1000 * because 1) the number of elements is almost always 1 or so, and 2) we do not care
1001 * duplicate elements for our use case.</p>
1002 *
1003 * <p>This object must be accessed only from callback methods in {@link PackageMonitor},
1004 * which should be bound to {@link #getRegisteredHandler()}.</p>
1005 */
1006 private final ArrayList<String> mChangedPackages = new ArrayList<>();
1007
1008 /**
1009 * {@code true} if one or more packages that contain {@link InputMethodService} appeared.
1010 *
1011 * <p>This field must be accessed only from callback methods in {@link PackageMonitor},
1012 * which should be bound to {@link #getRegisteredHandler()}.</p>
1013 */
1014 private boolean mImePackageAppeared = false;
Yohei Yukawac4e44912017-02-09 19:30:22 -08001015
1016 @GuardedBy("mMethodMap")
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08001017 void clearKnownImePackageNamesLocked() {
1018 mKnownImePackageNames.clear();
Yohei Yukawac4e44912017-02-09 19:30:22 -08001019 }
1020
1021 @GuardedBy("mMethodMap")
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08001022 final void addKnownImePackageNameLocked(@NonNull String packageName) {
1023 mKnownImePackageNames.add(packageName);
Yohei Yukawac4e44912017-02-09 19:30:22 -08001024 }
1025
Yohei Yukawa278f2ab2017-02-14 19:51:33 -08001026 @GuardedBy("mMethodMap")
1027 private boolean isChangingPackagesOfCurrentUserLocked() {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001028 final int userId = getChangingUserId();
1029 final boolean retval = userId == mSettings.getCurrentUserId();
1030 if (DEBUG) {
satok81f8b7c2012-12-04 20:42:56 +09001031 if (!retval) {
1032 Slog.d(TAG, "--- ignore this call back from a background user: " + userId);
1033 }
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001034 }
1035 return retval;
1036 }
1037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 @Override
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001039 public boolean onHandleForceStop(Intent intent, String[] packages, int uid, boolean doit) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 synchronized (mMethodMap) {
Yohei Yukawa278f2ab2017-02-14 19:51:33 -08001041 if (!isChangingPackagesOfCurrentUserLocked()) {
1042 return false;
1043 }
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001044 String curInputMethodId = mSettings.getSelectedInputMethod();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 final int N = mMethodList.size();
1046 if (curInputMethodId != null) {
1047 for (int i=0; i<N; i++) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001048 InputMethodInfo imi = mMethodList.get(i);
1049 if (imi.getId().equals(curInputMethodId)) {
1050 for (String pkg : packages) {
1051 if (imi.getPackageName().equals(pkg)) {
1052 if (!doit) {
1053 return true;
1054 }
satok723a27e2010-11-11 14:58:11 +09001055 resetSelectedInputMethodAndSubtypeLocked("");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001056 chooseNewDefaultIMELocked();
1057 return true;
1058 }
1059 }
1060 }
1061 }
1062 }
1063 }
1064 return false;
1065 }
1066
1067 @Override
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08001068 public void onBeginPackageChanges() {
1069 clearPackageChangeState();
1070 }
1071
1072 @Override
1073 public void onPackageAppeared(String packageName, int reason) {
1074 if (!mImePackageAppeared) {
1075 final PackageManager pm = mContext.getPackageManager();
1076 final List<ResolveInfo> services = pm.queryIntentServicesAsUser(
1077 new Intent(InputMethod.SERVICE_INTERFACE).setPackage(packageName),
Yohei Yukawaf80087c2018-05-21 09:47:53 -07001078 getComponentMatchingFlags(PackageManager.MATCH_DISABLED_COMPONENTS),
1079 getChangingUserId());
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08001080 // No need to lock this because we access it only on getRegisteredHandler().
1081 if (!services.isEmpty()) {
1082 mImePackageAppeared = true;
1083 }
1084 }
1085 // No need to lock this because we access it only on getRegisteredHandler().
1086 mChangedPackages.add(packageName);
1087 }
1088
1089 @Override
1090 public void onPackageDisappeared(String packageName, int reason) {
1091 // No need to lock this because we access it only on getRegisteredHandler().
1092 mChangedPackages.add(packageName);
1093 }
1094
1095 @Override
1096 public void onPackageModified(String packageName) {
1097 // No need to lock this because we access it only on getRegisteredHandler().
1098 mChangedPackages.add(packageName);
1099 }
1100
1101 @Override
1102 public void onPackagesSuspended(String[] packages) {
1103 // No need to lock this because we access it only on getRegisteredHandler().
1104 for (String packageName : packages) {
1105 mChangedPackages.add(packageName);
Yohei Yukawac4e44912017-02-09 19:30:22 -08001106 }
1107 }
1108
1109 @Override
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08001110 public void onPackagesUnsuspended(String[] packages) {
1111 // No need to lock this because we access it only on getRegisteredHandler().
1112 for (String packageName : packages) {
1113 mChangedPackages.add(packageName);
1114 }
1115 }
1116
1117 @Override
1118 public void onFinishPackageChanges() {
1119 onFinishPackageChangesInternal();
1120 clearPackageChangeState();
1121 }
1122
1123 private void clearPackageChangeState() {
1124 // No need to lock them because we access these fields only on getRegisteredHandler().
1125 mChangedPackages.clear();
1126 mImePackageAppeared = false;
1127 }
1128
Andreas Gampea36dc622018-02-05 17:19:22 -08001129 @GuardedBy("mMethodMap")
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08001130 private boolean shouldRebuildInputMethodListLocked() {
1131 // This method is guaranteed to be called only by getRegisteredHandler().
1132
1133 // If there is any new package that contains at least one IME, then rebuilt the list
1134 // of IMEs.
1135 if (mImePackageAppeared) {
1136 return true;
1137 }
1138
1139 // Otherwise, check if mKnownImePackageNames and mChangedPackages have any intersection.
1140 // TODO: Consider to create a utility method to do the following test. List.retainAll()
1141 // is an option, but it may still do some extra operations that we do not need here.
1142 final int N = mChangedPackages.size();
1143 for (int i = 0; i < N; ++i) {
1144 final String packageName = mChangedPackages.get(i);
1145 if (mKnownImePackageNames.contains(packageName)) {
1146 return true;
1147 }
1148 }
1149 return false;
1150 }
1151
1152 private void onFinishPackageChangesInternal() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001153 synchronized (mMethodMap) {
Yohei Yukawa278f2ab2017-02-14 19:51:33 -08001154 if (!isChangingPackagesOfCurrentUserLocked()) {
1155 return;
1156 }
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08001157 if (!shouldRebuildInputMethodListLocked()) {
1158 return;
1159 }
1160
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001161 InputMethodInfo curIm = null;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001162 String curInputMethodId = mSettings.getSelectedInputMethod();
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001163 final int N = mMethodList.size();
1164 if (curInputMethodId != null) {
1165 for (int i=0; i<N; i++) {
1166 InputMethodInfo imi = mMethodList.get(i);
satoke7c6998e2011-06-03 17:57:59 +09001167 final String imiId = imi.getId();
1168 if (imiId.equals(curInputMethodId)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001169 curIm = imi;
1170 }
satoke7c6998e2011-06-03 17:57:59 +09001171
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001172 int change = isPackageDisappearing(imi.getPackageName());
satoke7c6998e2011-06-03 17:57:59 +09001173 if (isPackageModified(imi.getPackageName())) {
1174 mFileManager.deleteAllInputMethodSubtypes(imiId);
1175 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001176 if (change == PACKAGE_TEMPORARY_CHANGE
1177 || change == PACKAGE_PERMANENT_CHANGE) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001178 Slog.i(TAG, "Input method uninstalled, disabling: "
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001179 + imi.getComponent());
1180 setInputMethodEnabledLocked(imi.getId(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 }
1182 }
1183 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001184
Yohei Yukawa94e33302016-02-12 19:37:03 -08001185 buildInputMethodListLocked(false /* resetDefaultEnabledIme */);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187 boolean changed = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001188
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001189 if (curIm != null) {
Anna Galusza9b278112016-01-04 11:37:37 -08001190 int change = isPackageDisappearing(curIm.getPackageName());
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001191 if (change == PACKAGE_TEMPORARY_CHANGE
1192 || change == PACKAGE_PERMANENT_CHANGE) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001193 ServiceInfo si = null;
1194 try {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001195 si = mIPackageManager.getServiceInfo(
1196 curIm.getComponent(), 0, mSettings.getCurrentUserId());
1197 } catch (RemoteException ex) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001198 }
1199 if (si == null) {
1200 // Uh oh, current input method is no longer around!
1201 // Pick another one...
Joe Onorato8a9b2202010-02-26 18:56:32 -08001202 Slog.i(TAG, "Current input method removed: " + curInputMethodId);
Seigo Nonakad9eb9112015-05-26 20:54:43 +09001203 updateSystemUiLocked(mCurToken, 0 /* vis */, mBackDisposition);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001204 if (!chooseNewDefaultIMELocked()) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001205 changed = true;
1206 curIm = null;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001207 Slog.i(TAG, "Unsetting current input method");
satok723a27e2010-11-11 14:58:11 +09001208 resetSelectedInputMethodAndSubtypeLocked("");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001209 }
1210 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001211 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001212 }
satokab751aa2010-09-14 19:17:36 +09001213
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001214 if (curIm == null) {
1215 // We currently don't have a default input method... is
1216 // one now available?
1217 changed = chooseNewDefaultIMELocked();
Yohei Yukawa54d512c2015-05-19 22:15:02 -07001218 } else if (!changed && isPackageModified(curIm.getPackageName())) {
1219 // Even if the current input method is still available, mCurrentSubtype could
1220 // be obsolete when the package is modified in practice.
1221 changed = true;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001222 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001223
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001224 if (changed) {
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08001225 updateFromSettingsLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 }
1227 }
1228 }
1229 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001230
Jeff Brownc28867a2013-03-26 15:42:39 -07001231 private static final class MethodCallback extends IInputSessionCallback.Stub {
Jean Chalarde0d32a62011-10-20 20:36:07 +09001232 private final InputMethodManagerService mParentIMMS;
Jeff Brownc28867a2013-03-26 15:42:39 -07001233 private final IInputMethod mMethod;
1234 private final InputChannel mChannel;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001235
Jeff Brownc28867a2013-03-26 15:42:39 -07001236 MethodCallback(InputMethodManagerService imms, IInputMethod method,
1237 InputChannel channel) {
Jean Chalarde0d32a62011-10-20 20:36:07 +09001238 mParentIMMS = imms;
Jeff Brownc28867a2013-03-26 15:42:39 -07001239 mMethod = method;
1240 mChannel = channel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001242
satoke7c6998e2011-06-03 17:57:59 +09001243 @Override
Jeff Brownc28867a2013-03-26 15:42:39 -07001244 public void sessionCreated(IInputMethodSession session) {
Dianne Hackborn6b6b3fd2014-03-24 11:27:18 -07001245 long ident = Binder.clearCallingIdentity();
1246 try {
1247 mParentIMMS.onSessionCreated(mMethod, session, mChannel);
1248 } finally {
1249 Binder.restoreCallingIdentity(ident);
1250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251 }
1252 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001253
satok01038492012-04-09 21:08:27 +09001254 private class HardKeyboardListener
Seigo Nonaka7309b122015-08-17 18:34:13 -07001255 implements WindowManagerInternal.OnHardKeyboardStatusChangeListener {
satok01038492012-04-09 21:08:27 +09001256 @Override
Michael Wright7b5a96b2014-08-09 19:28:42 -07001257 public void onHardKeyboardStatusChange(boolean available) {
1258 mHandler.sendMessage(mHandler.obtainMessage(MSG_HARD_KEYBOARD_SWITCH_CHANGED,
1259 available ? 1 : 0));
satok01038492012-04-09 21:08:27 +09001260 }
1261
Michael Wright7b5a96b2014-08-09 19:28:42 -07001262 public void handleHardKeyboardStatusChange(boolean available) {
satok01038492012-04-09 21:08:27 +09001263 if (DEBUG) {
Michael Wright7b5a96b2014-08-09 19:28:42 -07001264 Slog.w(TAG, "HardKeyboardStatusChanged: available=" + available);
satok01038492012-04-09 21:08:27 +09001265 }
1266 synchronized(mMethodMap) {
1267 if (mSwitchingDialog != null && mSwitchingDialogTitleView != null
1268 && mSwitchingDialog.isShowing()) {
1269 mSwitchingDialogTitleView.findViewById(
1270 com.android.internal.R.id.hard_keyboard_section).setVisibility(
1271 available ? View.VISIBLE : View.GONE);
1272 }
1273 }
1274 }
1275 }
1276
Fyodor Kupolov1e33dc82016-01-21 12:02:58 -08001277 public static final class Lifecycle extends SystemService {
1278 private InputMethodManagerService mService;
1279
1280 public Lifecycle(Context context) {
1281 super(context);
1282 mService = new InputMethodManagerService(context);
1283 }
1284
1285 @Override
1286 public void onStart() {
1287 LocalServices.addService(InputMethodManagerInternal.class,
1288 new LocalServiceImpl(mService.mHandler));
1289 publishBinderService(Context.INPUT_METHOD_SERVICE, mService);
1290 }
1291
1292 @Override
Yohei Yukawa7b18aec2016-03-07 13:04:32 -08001293 public void onSwitchUser(@UserIdInt int userHandle) {
Fyodor Kupolov7877b8a2016-06-29 14:39:19 -07001294 // Called on ActivityManager thread.
Yohei Yukawa7b18aec2016-03-07 13:04:32 -08001295 // TODO: Dispatch this to a worker thread as needed.
1296 mService.onSwitchUser(userHandle);
1297 }
1298
1299 @Override
Fyodor Kupolov1e33dc82016-01-21 12:02:58 -08001300 public void onBootPhase(int phase) {
Fyodor Kupolov7877b8a2016-06-29 14:39:19 -07001301 // Called on ActivityManager thread.
Yohei Yukawa7b18aec2016-03-07 13:04:32 -08001302 // TODO: Dispatch this to a worker thread as needed.
Fyodor Kupolov1e33dc82016-01-21 12:02:58 -08001303 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
1304 StatusBarManagerService statusBarService = (StatusBarManagerService) ServiceManager
1305 .getService(Context.STATUS_BAR_SERVICE);
1306 mService.systemRunning(statusBarService);
1307 }
1308 }
Yohei Yukawaed4952a2016-02-17 07:57:25 -08001309
1310 @Override
Fyodor Kupolov7877b8a2016-06-29 14:39:19 -07001311 public void onUnlockUser(final @UserIdInt int userHandle) {
1312 // Called on ActivityManager thread.
1313 mService.mHandler.sendMessage(mService.mHandler.obtainMessage(MSG_SYSTEM_UNLOCK_USER,
Fyodor Kupolov0f57cce2016-09-09 10:36:30 -07001314 userHandle /* arg1 */, 0 /* arg2 */));
Yohei Yukawaed4952a2016-02-17 07:57:25 -08001315 }
1316 }
1317
Yohei Yukawa7b18aec2016-03-07 13:04:32 -08001318 void onUnlockUser(@UserIdInt int userId) {
Yohei Yukawaed4952a2016-02-17 07:57:25 -08001319 synchronized(mMethodMap) {
1320 final int currentUserId = mSettings.getCurrentUserId();
1321 if (DEBUG) {
1322 Slog.d(TAG, "onUnlockUser: userId=" + userId + " curUserId=" + currentUserId);
1323 }
1324 if (userId != currentUserId) {
1325 return;
1326 }
1327 mSettings.switchCurrentUser(currentUserId, !mSystemReady);
Yohei Yukawa79247822017-01-23 15:26:15 -08001328 if (mSystemReady) {
1329 // We need to rebuild IMEs.
1330 buildInputMethodListLocked(false /* resetDefaultEnabledIme */);
1331 updateInputMethodsFromSettingsLocked(true /* enabledChanged */);
1332 }
Yohei Yukawaed4952a2016-02-17 07:57:25 -08001333 }
Fyodor Kupolov1e33dc82016-01-21 12:02:58 -08001334 }
1335
Yohei Yukawa7b18aec2016-03-07 13:04:32 -08001336 void onSwitchUser(@UserIdInt int userId) {
1337 synchronized (mMethodMap) {
1338 switchUserLocked(userId);
1339 }
1340 }
1341
Seigo Nonaka7309b122015-08-17 18:34:13 -07001342 public InputMethodManagerService(Context context) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001343 mIPackageManager = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 mContext = context;
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -08001345 mRes = context.getResources();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346 mHandler = new Handler(this);
Yohei Yukawa81482972015-06-04 00:58:59 -07001347 // Note: SettingsObserver doesn't register observers in its constructor.
1348 mSettingsObserver = new SettingsObserver(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 mIWindowManager = IWindowManager.Stub.asInterface(
1350 ServiceManager.getService(Context.WINDOW_SERVICE));
Seigo Nonaka7309b122015-08-17 18:34:13 -07001351 mWindowManagerInternal = LocalServices.getService(WindowManagerInternal.class);
Mita Yuned218c72012-12-06 17:18:25 -08001352 mCaller = new HandlerCaller(context, null, new HandlerCaller.Callback() {
satoke7c6998e2011-06-03 17:57:59 +09001353 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 public void executeMessage(Message msg) {
1355 handleMessage(msg);
1356 }
Mita Yuned218c72012-12-06 17:18:25 -08001357 }, true /*asyncHandler*/);
Yohei Yukawad34e1482016-02-11 08:03:52 -08001358 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Yohei Yukawaed4952a2016-02-17 07:57:25 -08001359 mUserManager = mContext.getSystemService(UserManager.class);
satok01038492012-04-09 21:08:27 +09001360 mHardKeyboardListener = new HardKeyboardListener();
Dianne Hackborn119bbc32013-03-22 17:27:25 -07001361 mHasFeature = context.getPackageManager().hasSystemFeature(
1362 PackageManager.FEATURE_INPUT_METHODS);
Jason Monk3e189872016-01-12 09:10:34 -05001363 mSlotIme = mContext.getString(com.android.internal.R.string.status_bar_ime);
Yohei Yukawafa0e47e2016-04-05 09:55:56 -07001364 mHardKeyboardBehavior = mContext.getResources().getInteger(
1365 com.android.internal.R.integer.config_externalHardKeyboardBehavior);
satok7cfc0ed2011-06-20 21:29:36 +09001366
Chris Wren1ce4b6d2015-06-11 10:19:43 -04001367 Bundle extras = new Bundle();
1368 extras.putBoolean(Notification.EXTRA_ALLOW_DURING_SETUP, true);
Tadashi G. Takaoka01065a52017-07-19 14:10:24 +09001369 @ColorInt final int accentColor = mContext.getColor(
1370 com.android.internal.R.color.system_notification_accent_color);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001371 mImeSwitcherNotification =
1372 new Notification.Builder(mContext, SystemNotificationChannels.VIRTUAL_KEYBOARD)
1373 .setSmallIcon(com.android.internal.R.drawable.ic_notification_ime_default)
1374 .setWhen(0)
1375 .setOngoing(true)
1376 .addExtras(extras)
1377 .setCategory(Notification.CATEGORY_SYSTEM)
Tadashi G. Takaoka01065a52017-07-19 14:10:24 +09001378 .setColor(accentColor);
Daniel Sandler590d5152012-06-14 16:10:13 -04001379
Tadashi G. Takaoka01065a52017-07-19 14:10:24 +09001380 Intent intent = new Intent(ACTION_SHOW_INPUT_METHOD_PICKER)
1381 .setPackage(mContext.getPackageName());
satok683e2382011-07-12 08:28:52 +09001382 mImeSwitchPendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
satokb858c732011-07-22 19:54:34 +09001383
1384 mShowOngoingImeSwitcherForPhones = false;
satok7cfc0ed2011-06-20 21:29:36 +09001385
satok7cfc0ed2011-06-20 21:29:36 +09001386 mNotificationShown = false;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001387 int userId = 0;
1388 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001389 userId = ActivityManager.getService().getCurrentUser().id;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001390 } catch (RemoteException e) {
1391 Slog.w(TAG, "Couldn't get current user ID; guessing it's 0", e);
1392 }
satok913a8922010-08-26 21:53:41 +09001393
satokd87c2592010-09-29 11:52:06 +09001394 // mSettings should be created before buildInputMethodListLocked
satokdf31ae62011-01-15 06:19:44 +09001395 mSettings = new InputMethodSettings(
Yohei Yukawa68645a62016-02-17 07:54:20 -08001396 mRes, context.getContentResolver(), mMethodMap, mMethodList, userId, !mSystemReady);
Svet Ganovadc1cf42015-06-15 16:36:24 -07001397
Kenny Guy2a764942014-04-02 13:29:20 +01001398 updateCurrentProfileIds();
Satoshi Kataoka5ade83b2012-09-26 22:59:41 +09001399 mFileManager = new InputMethodFileManager(mMethodMap, userId);
Yohei Yukawa79247822017-01-23 15:26:15 -08001400 mSwitchingController = InputMethodSubtypeSwitchingController.createInstanceLocked(
1401 mSettings, context);
Tarandeep Singh89a6c482017-11-21 14:26:11 -08001402 // Register VR-state listener.
1403 IVrManager vrManager = (IVrManager) ServiceManager.getService(Context.VR_SERVICE);
1404 if (vrManager != null) {
1405 try {
1406 vrManager.registerListener(mVrStateCallbacks);
1407 } catch (RemoteException e) {
1408 Slog.e(TAG, "Failed to register VR mode state listener.");
1409 }
1410 }
satok5b927c432012-05-01 20:09:34 +09001411 }
1412
satok5b927c432012-05-01 20:09:34 +09001413 private void resetDefaultImeLocked(Context context) {
1414 // Do not reset the default (current) IME when it is a 3rd-party IME
Yohei Yukawac2393ac2016-02-18 00:30:45 -08001415 if (mCurMethodId != null && !InputMethodUtils.isSystemIme(mMethodMap.get(mCurMethodId))) {
satok5b927c432012-05-01 20:09:34 +09001416 return;
1417 }
Yohei Yukawac2393ac2016-02-18 00:30:45 -08001418 final List<InputMethodInfo> suitableImes = InputMethodUtils.getDefaultEnabledImes(
Yohei Yukawaaf5cee82017-01-23 16:17:11 -08001419 context, mSettings.getEnabledInputMethodListLocked());
Yohei Yukawac2393ac2016-02-18 00:30:45 -08001420 if (suitableImes.isEmpty()) {
1421 Slog.i(TAG, "No default found");
1422 return;
satok5b927c432012-05-01 20:09:34 +09001423 }
Yohei Yukawac2393ac2016-02-18 00:30:45 -08001424 final InputMethodInfo defIm = suitableImes.get(0);
Yohei Yukawad0332832017-02-01 13:59:43 -08001425 if (DEBUG) {
1426 Slog.i(TAG, "Default found, using " + defIm.getId());
1427 }
Yohei Yukawac2393ac2016-02-18 00:30:45 -08001428 setSelectedInputMethodAndSubtypeLocked(defIm, NOT_A_SUBTYPE_ID, false);
satok5b927c432012-05-01 20:09:34 +09001429 }
1430
Andreas Gampea36dc622018-02-05 17:19:22 -08001431 @GuardedBy("mMethodMap")
Satoshi Kataoka5ade83b2012-09-26 22:59:41 +09001432 private void switchUserLocked(int newUserId) {
Yohei Yukawa90bf7082015-06-03 23:50:27 -07001433 if (DEBUG) Slog.d(TAG, "Switching user stage 1/3. newUserId=" + newUserId
1434 + " currentUserId=" + mSettings.getCurrentUserId());
1435
Yohei Yukawa81482972015-06-04 00:58:59 -07001436 // ContentObserver should be registered again when the user is changed
1437 mSettingsObserver.registerContentObserverLocked(newUserId);
Yohei Yukawa68645a62016-02-17 07:54:20 -08001438
Yohei Yukawaed4952a2016-02-17 07:57:25 -08001439 // If the system is not ready or the device is not yed unlocked by the user, then we use
1440 // copy-on-write settings.
1441 final boolean useCopyOnWriteSettings =
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001442 !mSystemReady || !mUserManager.isUserUnlockingOrUnlocked(newUserId);
Yohei Yukawa68645a62016-02-17 07:54:20 -08001443 mSettings.switchCurrentUser(newUserId, useCopyOnWriteSettings);
Kenny Guy2a764942014-04-02 13:29:20 +01001444 updateCurrentProfileIds();
Satoshi Kataoka5ade83b2012-09-26 22:59:41 +09001445 // InputMethodFileManager should be reset when the user is changed
1446 mFileManager = new InputMethodFileManager(mMethodMap, newUserId);
Satoshi Kataoka7f7535f2013-02-18 12:54:16 +09001447 final String defaultImiId = mSettings.getSelectedInputMethod();
Yohei Yukawa90bf7082015-06-03 23:50:27 -07001448
1449 if (DEBUG) Slog.d(TAG, "Switching user stage 2/3. newUserId=" + newUserId
1450 + " defaultImiId=" + defaultImiId);
1451
Satoshi Kataoka7c4a2a12013-02-25 15:25:43 +09001452 // For secondary users, the list of enabled IMEs may not have been updated since the
1453 // callbacks to PackageMonitor are ignored for the secondary user. Here, defaultImiId may
1454 // not be empty even if the IME has been uninstalled by the primary user.
1455 // Even in such cases, IMMS works fine because it will find the most applicable
1456 // IME for that user.
Satoshi Kataokaed1cdb22013-04-17 16:41:58 +09001457 final boolean initialUserSwitch = TextUtils.isEmpty(defaultImiId);
Yohei Yukawa0d7aff82017-02-10 00:40:51 -08001458 mLastSystemLocales = mRes.getConfiguration().getLocales();
1459
1460 // TODO: Is it really possible that switchUserLocked() happens before system ready?
1461 if (mSystemReady) {
1462 hideCurrentInputLocked(0, null);
1463 resetCurrentMethodAndClient(InputMethodClient.UNBIND_REASON_SWITCH_USER);
1464 buildInputMethodListLocked(initialUserSwitch);
1465 if (TextUtils.isEmpty(mSettings.getSelectedInputMethod())) {
1466 // This is the first time of the user switch and
1467 // set the current ime to the proper one.
1468 resetDefaultImeLocked(mContext);
1469 }
1470 updateFromSettingsLocked(true);
1471 try {
1472 startInputInnerLocked();
1473 } catch (RuntimeException e) {
1474 Slog.w(TAG, "Unexpected exception", e);
1475 }
1476 }
1477
Satoshi Kataokaed1cdb22013-04-17 16:41:58 +09001478 if (initialUserSwitch) {
Yohei Yukawa094c71f2015-06-20 00:41:31 -07001479 InputMethodUtils.setNonSelectedSystemImesDisabledUntilUsed(mIPackageManager,
1480 mSettings.getEnabledInputMethodListLocked(), newUserId,
1481 mContext.getBasePackageName());
Satoshi Kataokaed1cdb22013-04-17 16:41:58 +09001482 }
Yohei Yukawa90bf7082015-06-03 23:50:27 -07001483
1484 if (DEBUG) Slog.d(TAG, "Switching user stage 3/3. newUserId=" + newUserId
1485 + " selectedIme=" + mSettings.getSelectedInputMethod());
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001486 }
1487
Kenny Guy2a764942014-04-02 13:29:20 +01001488 void updateCurrentProfileIds() {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07001489 mSettings.setCurrentProfileIds(
1490 mUserManager.getProfileIdsWithDisabled(mSettings.getCurrentUserId()));
Amith Yamasani734983f2014-03-04 16:48:05 -08001491 }
1492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 @Override
1494 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1495 throws RemoteException {
1496 try {
1497 return super.onTransact(code, data, reply, flags);
1498 } catch (RuntimeException e) {
1499 // The input method manager only throws security exceptions, so let's
1500 // log all others.
1501 if (!(e instanceof SecurityException)) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07001502 Slog.wtf(TAG, "Input Method Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 }
1504 throw e;
1505 }
1506 }
1507
Svetoslav Ganova0027152013-06-25 14:59:53 -07001508 public void systemRunning(StatusBarManagerService statusBar) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001509 synchronized (mMethodMap) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001510 if (DEBUG) {
1511 Slog.d(TAG, "--- systemReady");
1512 }
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001513 if (!mSystemReady) {
1514 mSystemReady = true;
Yohei Yukawa79247822017-01-23 15:26:15 -08001515 mLastSystemLocales = mRes.getConfiguration().getLocales();
Yohei Yukawa68645a62016-02-17 07:54:20 -08001516 final int currentUserId = mSettings.getCurrentUserId();
Yohei Yukawaed4952a2016-02-17 07:57:25 -08001517 mSettings.switchCurrentUser(currentUserId,
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001518 !mUserManager.isUserUnlockingOrUnlocked(currentUserId));
Yohei Yukawad34e1482016-02-11 08:03:52 -08001519 mKeyguardManager = mContext.getSystemService(KeyguardManager.class);
1520 mNotificationManager = mContext.getSystemService(NotificationManager.class);
Dianne Hackborn661cd522011-08-22 00:26:20 -07001521 mStatusBar = statusBar;
Griff Hazen6090c262016-03-25 08:11:24 -07001522 if (mStatusBar != null) {
1523 mStatusBar.setIconVisibility(mSlotIme, false);
1524 }
Seigo Nonakad9eb9112015-05-26 20:54:43 +09001525 updateSystemUiLocked(mCurToken, mImeWindowVis, mBackDisposition);
satokb858c732011-07-22 19:54:34 +09001526 mShowOngoingImeSwitcherForPhones = mRes.getBoolean(
1527 com.android.internal.R.bool.show_ongoing_ime_switcher);
satok01038492012-04-09 21:08:27 +09001528 if (mShowOngoingImeSwitcherForPhones) {
Seigo Nonaka7309b122015-08-17 18:34:13 -07001529 mWindowManagerInternal.setOnHardKeyboardStatusChangeListener(
satok01038492012-04-09 21:08:27 +09001530 mHardKeyboardListener);
1531 }
Yohei Yukawa79247822017-01-23 15:26:15 -08001532
1533 mMyPackageMonitor.register(mContext, null, UserHandle.ALL, true);
1534 mSettingsObserver.registerContentObserverLocked(currentUserId);
1535
1536 final IntentFilter broadcastFilter = new IntentFilter();
1537 broadcastFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
1538 broadcastFilter.addAction(Intent.ACTION_USER_ADDED);
1539 broadcastFilter.addAction(Intent.ACTION_USER_REMOVED);
Yohei Yukawa79247822017-01-23 15:26:15 -08001540 broadcastFilter.addAction(Intent.ACTION_LOCALE_CHANGED);
Tadashi G. Takaoka01065a52017-07-19 14:10:24 +09001541 broadcastFilter.addAction(ACTION_SHOW_INPUT_METHOD_PICKER);
Yohei Yukawa79247822017-01-23 15:26:15 -08001542 mContext.registerReceiver(new ImmsBroadcastReceiver(), broadcastFilter);
1543
Yohei Yukawa1f9a3cb2017-10-26 15:00:59 -07001544 final String defaultImiId = mSettings.getSelectedInputMethod();
1545 final boolean imeSelectedOnBoot = !TextUtils.isEmpty(defaultImiId);
1546 buildInputMethodListLocked(!imeSelectedOnBoot /* resetDefaultEnabledIme */);
Yohei Yukawa79247822017-01-23 15:26:15 -08001547 resetDefaultImeLocked(mContext);
1548 updateFromSettingsLocked(true);
1549 InputMethodUtils.setNonSelectedSystemImesDisabledUntilUsed(mIPackageManager,
1550 mSettings.getEnabledInputMethodListLocked(), currentUserId,
1551 mContext.getBasePackageName());
1552
Dianne Hackborncc278702009-09-02 23:07:23 -07001553 try {
1554 startInputInnerLocked();
1555 } catch (RuntimeException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001556 Slog.w(TAG, "Unexpected exception", e);
Dianne Hackborncc278702009-09-02 23:07:23 -07001557 }
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001558 }
1559 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001561
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001562 // ---------------------------------------------------------------------------------------
1563 // Check whether or not this is a valid IPC. Assumes an IPC is valid when either
1564 // 1) it comes from the system process
1565 // 2) the calling process' user id is identical to the current user id IMMS thinks.
1566 private boolean calledFromValidUser() {
1567 final int uid = Binder.getCallingUid();
1568 final int userId = UserHandle.getUserId(uid);
1569 if (DEBUG) {
1570 Slog.d(TAG, "--- calledFromForegroundUserOrSystemProcess ? "
1571 + "calling uid = " + uid + " system uid = " + Process.SYSTEM_UID
1572 + " calling userId = " + userId + ", foreground user id = "
Satoshi Kataoka87c29142013-07-31 23:11:54 +09001573 + mSettings.getCurrentUserId() + ", calling pid = " + Binder.getCallingPid()
1574 + InputMethodUtils.getApiCallStack());
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001575 }
Kenny Guy2a764942014-04-02 13:29:20 +01001576 if (uid == Process.SYSTEM_UID || mSettings.isCurrentProfile(userId)) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001577 return true;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001578 }
Satoshi Kataoka135e5fb2012-09-28 18:25:06 +09001579
1580 // Caveat: A process which has INTERACT_ACROSS_USERS_FULL gets results for the
1581 // foreground user, not for the user of that process. Accordingly InputMethodManagerService
1582 // must not manage background users' states in any functions.
1583 // Note that privacy-sensitive IPCs, such as setInputMethod, are still securely guarded
1584 // by a token.
1585 if (mContext.checkCallingOrSelfPermission(
1586 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1587 == PackageManager.PERMISSION_GRANTED) {
1588 if (DEBUG) {
1589 Slog.d(TAG, "--- Access granted because the calling process has "
1590 + "the INTERACT_ACROSS_USERS_FULL permission");
1591 }
1592 return true;
1593 }
Yohei Yukawad0332832017-02-01 13:59:43 -08001594 // TODO(b/34886274): The semantics of this verification is actually not well-defined.
Seigo Nonakae27dc2b2015-08-14 18:21:27 -07001595 Slog.w(TAG, "--- IPC called from background users. Ignore. callers="
1596 + Debug.getCallers(10));
Satoshi Kataoka135e5fb2012-09-28 18:25:06 +09001597 return false;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001598 }
1599
Yohei Yukawa22c97be2014-06-04 19:43:36 +09001600
1601 /**
1602 * Returns true iff the caller is identified to be the current input method with the token.
1603 * @param token The window token given to the input method when it was started.
1604 * @return true if and only if non-null valid token is specified.
1605 */
Yohei Yukawad0332832017-02-01 13:59:43 -08001606 private boolean calledWithValidToken(@Nullable IBinder token) {
1607 if (token == null && Binder.getCallingPid() == Process.myPid()) {
1608 if (DEBUG) {
1609 // TODO(b/34851776): Basically it's the caller's fault if we reach here.
1610 Slog.d(TAG, "Bug 34851776 is detected callers=" + Debug.getCallers(10));
1611 }
1612 return false;
1613 }
1614 if (token == null || token != mCurToken) {
1615 // TODO(b/34886274): The semantics of this verification is actually not well-defined.
1616 Slog.e(TAG, "Ignoring " + Debug.getCaller() + " due to an invalid token."
1617 + " uid:" + Binder.getCallingUid() + " token:" + token);
Yohei Yukawa22c97be2014-06-04 19:43:36 +09001618 return false;
1619 }
1620 return true;
1621 }
1622
Yohei Yukawaf80087c2018-05-21 09:47:53 -07001623 @GuardedBy("mMethodMap")
1624 private boolean bindCurrentInputMethodServiceLocked(
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001625 Intent service, ServiceConnection conn, int flags) {
1626 if (service == null || conn == null) {
1627 Slog.e(TAG, "--- bind failed: service = " + service + ", conn = " + conn);
1628 return false;
1629 }
Yohei Yukawaf80087c2018-05-21 09:47:53 -07001630 if (mBindInstantServiceAllowed) {
1631 flags |= Context.BIND_ALLOW_INSTANT;
1632 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08001633 return mContext.bindServiceAsUser(service, conn, flags,
1634 new UserHandle(mSettings.getCurrentUserId()));
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001635 }
1636
satoke7c6998e2011-06-03 17:57:59 +09001637 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 public List<InputMethodInfo> getInputMethodList() {
Tarandeep Singh89a6c482017-11-21 14:26:11 -08001639 return getInputMethodList(false /* isVrOnly */);
1640 }
1641
1642 public List<InputMethodInfo> getVrInputMethodList() {
1643 return getInputMethodList(true /* isVrOnly */);
1644 }
1645
1646 private List<InputMethodInfo> getInputMethodList(final boolean isVrOnly) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001647 // TODO: Make this work even for non-current users?
1648 if (!calledFromValidUser()) {
1649 return Collections.emptyList();
1650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 synchronized (mMethodMap) {
Tarandeep Singh89a6c482017-11-21 14:26:11 -08001652 ArrayList<InputMethodInfo> methodList = new ArrayList<>();
1653 for (InputMethodInfo info : mMethodList) {
1654
1655 if (info.isVrOnly() == isVrOnly) {
1656 methodList.add(info);
1657 }
1658 }
1659 return methodList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 }
1661 }
1662
satoke7c6998e2011-06-03 17:57:59 +09001663 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 public List<InputMethodInfo> getEnabledInputMethodList() {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001665 // TODO: Make this work even for non-current users?
1666 if (!calledFromValidUser()) {
1667 return Collections.emptyList();
1668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 synchronized (mMethodMap) {
satokd87c2592010-09-29 11:52:06 +09001670 return mSettings.getEnabledInputMethodListLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 }
1672 }
1673
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09001674 /**
Satoshi Kataokab3c21ac2013-08-07 15:43:29 +09001675 * @param imiId if null, returns enabled subtypes for the current imi
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09001676 * @return enabled subtypes of the specified imi
1677 */
satoke7c6998e2011-06-03 17:57:59 +09001678 @Override
Satoshi Kataokab3c21ac2013-08-07 15:43:29 +09001679 public List<InputMethodSubtype> getEnabledInputMethodSubtypeList(String imiId,
satok16331c82010-12-20 23:48:46 +09001680 boolean allowsImplicitlySelectedSubtypes) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001681 // TODO: Make this work even for non-current users?
1682 if (!calledFromValidUser()) {
Yohei Yukawab0377bb2015-08-10 21:06:30 -07001683 return Collections.emptyList();
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001684 }
satok67ddf9c2010-11-17 09:45:54 +09001685 synchronized (mMethodMap) {
Satoshi Kataokab3c21ac2013-08-07 15:43:29 +09001686 final InputMethodInfo imi;
1687 if (imiId == null && mCurMethodId != null) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09001688 imi = mMethodMap.get(mCurMethodId);
Satoshi Kataokab3c21ac2013-08-07 15:43:29 +09001689 } else {
1690 imi = mMethodMap.get(imiId);
1691 }
1692 if (imi == null) {
Yohei Yukawab0377bb2015-08-10 21:06:30 -07001693 return Collections.emptyList();
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09001694 }
1695 return mSettings.getEnabledInputMethodSubtypeListLocked(
1696 mContext, imi, allowsImplicitlySelectedSubtypes);
satok67ddf9c2010-11-17 09:45:54 +09001697 }
1698 }
1699
satoke7c6998e2011-06-03 17:57:59 +09001700 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 public void addClient(IInputMethodClient client,
1702 IInputContext inputContext, int uid, int pid) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001703 if (!calledFromValidUser()) {
1704 return;
1705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 synchronized (mMethodMap) {
1707 mClients.put(client.asBinder(), new ClientState(client,
1708 inputContext, uid, pid));
1709 }
1710 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001711
satoke7c6998e2011-06-03 17:57:59 +09001712 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 public void removeClient(IInputMethodClient client) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001714 if (!calledFromValidUser()) {
1715 return;
1716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 synchronized (mMethodMap) {
Jeff Brownc28867a2013-03-26 15:42:39 -07001718 ClientState cs = mClients.remove(client.asBinder());
1719 if (cs != null) {
1720 clearClientSessionLocked(cs);
Yohei Yukawa072b1b52015-11-18 15:54:34 -08001721 if (mCurClient == cs) {
Tarandeep Singh93c00cea2018-02-16 14:31:17 -08001722 if (mBoundToMethod) {
1723 mBoundToMethod = false;
1724 if (mCurMethod != null) {
1725 executeOrSendMessage(mCurMethod, mCaller.obtainMessageO(
1726 MSG_UNBIND_INPUT, mCurMethod));
1727 }
1728 }
Yohei Yukawa072b1b52015-11-18 15:54:34 -08001729 mCurClient = null;
1730 }
Yohei Yukawae39d4ed2015-11-19 03:38:49 -08001731 if (mCurFocusedWindowClient == cs) {
1732 mCurFocusedWindowClient = null;
1733 }
Jeff Brownc28867a2013-03-26 15:42:39 -07001734 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 }
1736 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 void executeOrSendMessage(IInterface target, Message msg) {
1739 if (target.asBinder() instanceof Binder) {
1740 mCaller.sendMessage(msg);
1741 } else {
1742 handleMessage(msg);
1743 msg.recycle();
1744 }
1745 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001746
Yohei Yukawa33e81792015-11-17 21:14:42 -08001747 void unbindCurrentClientLocked(
1748 /* @InputMethodClient.UnbindReason */ final int unbindClientReason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 if (mCurClient != null) {
Yohei Yukawa35d3f372015-11-25 11:07:19 -08001750 if (DEBUG) Slog.v(TAG, "unbindCurrentInputLocked: client="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 + mCurClient.client.asBinder());
1752 if (mBoundToMethod) {
1753 mBoundToMethod = false;
1754 if (mCurMethod != null) {
1755 executeOrSendMessage(mCurMethod, mCaller.obtainMessageO(
1756 MSG_UNBIND_INPUT, mCurMethod));
1757 }
1758 }
Dianne Hackborna6e41342012-05-22 16:30:34 -07001759
Yohei Yukawa2bc66172017-02-08 11:13:25 -08001760 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIIO(
1761 MSG_SET_ACTIVE, 0, 0, mCurClient));
Yohei Yukawa33e81792015-11-17 21:14:42 -08001762 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIIO(
1763 MSG_UNBIND_CLIENT, mCurSeq, unbindClientReason, mCurClient.client));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 mCurClient.sessionRequested = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 mCurClient = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001766
The Android Open Source Project10592532009-03-18 17:39:46 -07001767 hideInputMethodMenuLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 }
1769 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 private int getImeShowFlags() {
1772 int flags = 0;
1773 if (mShowForced) {
1774 flags |= InputMethod.SHOW_FORCED
1775 | InputMethod.SHOW_EXPLICIT;
1776 } else if (mShowExplicitlyRequested) {
1777 flags |= InputMethod.SHOW_EXPLICIT;
1778 }
1779 return flags;
1780 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 private int getAppShowFlags() {
1783 int flags = 0;
1784 if (mShowForced) {
1785 flags |= InputMethodManager.SHOW_FORCED;
1786 } else if (!mShowExplicitlyRequested) {
1787 flags |= InputMethodManager.SHOW_IMPLICIT;
1788 }
1789 return flags;
1790 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001791
Andreas Gampea36dc622018-02-05 17:19:22 -08001792 @GuardedBy("mMethodMap")
Yohei Yukawa2553e482017-12-15 15:47:33 -08001793 @NonNull
Yohei Yukawa87ca8402017-02-07 00:13:14 -08001794 InputBindResult attachNewInputLocked(
1795 /* @InputMethodClient.StartInputReason */ final int startInputReason, boolean initial) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 if (!mBoundToMethod) {
1797 executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
1798 MSG_BIND_INPUT, mCurMethod, mCurClient.binding));
1799 mBoundToMethod = true;
1800 }
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08001801
1802 final Binder startInputToken = new Binder();
Yohei Yukawa357b2f62017-02-14 09:40:03 -08001803 final StartInputInfo info = new StartInputInfo(mCurToken, mCurId, startInputReason,
1804 !initial, mCurFocusedWindow, mCurAttribute, mCurFocusedWindowSoftInputMode,
1805 mCurSeq);
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08001806 mStartInputMap.put(startInputToken, info);
Yohei Yukawa357b2f62017-02-14 09:40:03 -08001807 mStartInputHistory.addEntry(info);
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08001808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 final SessionState session = mCurClient.curSession;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08001810 executeOrSendMessage(session.method, mCaller.obtainMessageIIOOOO(
Yohei Yukawaf7526b52017-02-11 20:57:10 -08001811 MSG_START_INPUT, mCurInputContextMissingMethods, initial ? 0 : 1 /* restarting */,
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08001812 startInputToken, session, mCurInputContext, mCurAttribute));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 if (mShowRequested) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001814 if (DEBUG) Slog.v(TAG, "Attach new input asks to show input");
The Android Open Source Project4df24232009-03-05 14:34:35 -08001815 showCurrentInputLocked(getAppShowFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001816 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08001817 return new InputBindResult(InputBindResult.ResultCode.SUCCESS_WITH_IME_SESSION,
1818 session.session, (session.channel != null ? session.channel.dup() : null),
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09001819 mCurId, mCurSeq, mCurUserActionNotificationSequenceNumber);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001821
Andreas Gampea36dc622018-02-05 17:19:22 -08001822 @GuardedBy("mMethodMap")
Yohei Yukawa2553e482017-12-15 15:47:33 -08001823 @NonNull
Yohei Yukawa35d3f372015-11-25 11:07:19 -08001824 InputBindResult startInputLocked(
1825 /* @InputMethodClient.StartInputReason */ final int startInputReason,
Yohei Yukawa19a80a12016-03-14 22:57:37 -07001826 IInputMethodClient client, IInputContext inputContext,
1827 /* @InputConnectionInspector.missingMethods */ final int missingMethods,
Yohei Yukawa74750f22016-03-22 12:54:22 -07001828 @Nullable EditorInfo attribute, int controlFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 // If no method is currently selected, do nothing.
1830 if (mCurMethodId == null) {
Yohei Yukawa2553e482017-12-15 15:47:33 -08001831 return InputBindResult.NO_IME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 ClientState cs = mClients.get(client.asBinder());
1835 if (cs == null) {
1836 throw new IllegalArgumentException("unknown client "
1837 + client.asBinder());
1838 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001839
Yohei Yukawa74750f22016-03-22 12:54:22 -07001840 if (attribute == null) {
1841 Slog.w(TAG, "Ignoring startInput with null EditorInfo."
1842 + " uid=" + cs.uid + " pid=" + cs.pid);
Yohei Yukawa2553e482017-12-15 15:47:33 -08001843 return InputBindResult.NULL_EDITOR_INFO;
Yohei Yukawa74750f22016-03-22 12:54:22 -07001844 }
1845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 try {
1847 if (!mIWindowManager.inputMethodClientHasFocus(cs.client)) {
1848 // Check with the window manager to make sure this client actually
1849 // has a window with focus. If not, reject. This is thread safe
1850 // because if the focus changes some time before or after, the
1851 // next client receiving focus that has any interest in input will
1852 // be calling through here after that change happens.
Yohei Yukawad0332832017-02-01 13:59:43 -08001853 if (DEBUG) {
1854 Slog.w(TAG, "Starting input on non-focused client " + cs.client
1855 + " (uid=" + cs.uid + " pid=" + cs.pid + ")");
1856 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08001857 return InputBindResult.NOT_IME_TARGET_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 }
1859 } catch (RemoteException e) {
1860 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001861
Yohei Yukawa19a80a12016-03-14 22:57:37 -07001862 return startInputUncheckedLocked(cs, inputContext, missingMethods, attribute,
Yohei Yukawa87ca8402017-02-07 00:13:14 -08001863 controlFlags, startInputReason);
Dianne Hackborn7663d802012-02-24 13:08:49 -08001864 }
1865
Andreas Gampea36dc622018-02-05 17:19:22 -08001866 @GuardedBy("mMethodMap")
Yohei Yukawa2553e482017-12-15 15:47:33 -08001867 @NonNull
Yohei Yukawa35d3f372015-11-25 11:07:19 -08001868 InputBindResult startInputUncheckedLocked(@NonNull ClientState cs, IInputContext inputContext,
Yohei Yukawa19a80a12016-03-14 22:57:37 -07001869 /* @InputConnectionInspector.missingMethods */ final int missingMethods,
Yohei Yukawa87ca8402017-02-07 00:13:14 -08001870 @NonNull EditorInfo attribute, int controlFlags,
1871 /* @InputMethodClient.StartInputReason */ final int startInputReason) {
Dianne Hackborn7663d802012-02-24 13:08:49 -08001872 // If no method is currently selected, do nothing.
1873 if (mCurMethodId == null) {
Yohei Yukawa2553e482017-12-15 15:47:33 -08001874 return InputBindResult.NO_IME;
Dianne Hackborn7663d802012-02-24 13:08:49 -08001875 }
1876
Yohei Yukawad57ba672015-06-08 16:39:46 -07001877 if (!InputMethodUtils.checkIfPackageBelongsToUid(mAppOpsManager, cs.uid,
1878 attribute.packageName)) {
1879 Slog.e(TAG, "Rejecting this client as it reported an invalid package name."
1880 + " uid=" + cs.uid + " package=" + attribute.packageName);
Yohei Yukawa2553e482017-12-15 15:47:33 -08001881 return InputBindResult.INVALID_PACKAGE_NAME;
Yohei Yukawa0f3ad12015-04-06 16:48:24 -07001882 }
1883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884 if (mCurClient != cs) {
John Spurlocke0980502013-10-25 11:59:29 -04001885 // Was the keyguard locked when switching over to the new client?
1886 mCurClientInKeyguard = isKeyguardLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 // If the client is changing, we need to switch over to the new
1888 // one.
Yohei Yukawa33e81792015-11-17 21:14:42 -08001889 unbindCurrentClientLocked(InputMethodClient.UNBIND_REASON_SWITCH_CLIENT);
Yohei Yukawa35d3f372015-11-25 11:07:19 -08001890 if (DEBUG) Slog.v(TAG, "switching to client: client="
John Spurlocke0980502013-10-25 11:59:29 -04001891 + cs.client.asBinder() + " keyguard=" + mCurClientInKeyguard);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892
1893 // If the screen is on, inform the new client it is active
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07001894 if (mIsInteractive) {
Dianne Hackborna6e41342012-05-22 16:30:34 -07001895 executeOrSendMessage(cs.client, mCaller.obtainMessageIO(
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07001896 MSG_SET_ACTIVE, mIsInteractive ? 1 : 0, cs));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001897 }
1898 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 // Bump up the sequence for this client and attach it.
1901 mCurSeq++;
1902 if (mCurSeq <= 0) mCurSeq = 1;
1903 mCurClient = cs;
1904 mCurInputContext = inputContext;
Yohei Yukawa19a80a12016-03-14 22:57:37 -07001905 mCurInputContextMissingMethods = missingMethods;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 mCurAttribute = attribute;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 // Check if the input method is changing.
1909 if (mCurId != null && mCurId.equals(mCurMethodId)) {
1910 if (cs.curSession != null) {
1911 // Fast case: if we are already connected to the input method,
1912 // then just return it.
Yohei Yukawa87ca8402017-02-07 00:13:14 -08001913 return attachNewInputLocked(startInputReason,
Dianne Hackborn7663d802012-02-24 13:08:49 -08001914 (controlFlags&InputMethodManager.CONTROL_START_INITIAL) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 }
1916 if (mHaveConnection) {
1917 if (mCurMethod != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001918 // Return to client, and we will get back with it when
1919 // we have had a session made for it.
Jeff Brownc28867a2013-03-26 15:42:39 -07001920 requestClientSessionLocked(cs);
Yohei Yukawa2553e482017-12-15 15:47:33 -08001921 return new InputBindResult(
1922 InputBindResult.ResultCode.SUCCESS_WAITING_IME_SESSION,
1923 null, null, mCurId, mCurSeq,
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09001924 mCurUserActionNotificationSequenceNumber);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001925 } else if (SystemClock.uptimeMillis()
1926 < (mLastBindTime+TIME_TO_RECONNECT)) {
1927 // In this case we have connected to the service, but
1928 // don't yet have its interface. If it hasn't been too
1929 // long since we did the connection, we'll return to
1930 // the client and wait to get the service interface so
1931 // we can report back. If it has been too long, we want
1932 // to fall through so we can try a disconnect/reconnect
1933 // to see if we can get back in touch with the service.
Yohei Yukawa2553e482017-12-15 15:47:33 -08001934 return new InputBindResult(
1935 InputBindResult.ResultCode.SUCCESS_WAITING_IME_BINDING,
1936 null, null, mCurId, mCurSeq,
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09001937 mCurUserActionNotificationSequenceNumber);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001939 EventLog.writeEvent(EventLogTags.IMF_FORCE_RECONNECT_IME,
1940 mCurMethodId, SystemClock.uptimeMillis()-mLastBindTime, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 }
1942 }
1943 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001944
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001945 return startInputInnerLocked();
1946 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001947
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001948 InputBindResult startInputInnerLocked() {
1949 if (mCurMethodId == null) {
Yohei Yukawa2553e482017-12-15 15:47:33 -08001950 return InputBindResult.NO_IME;
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001951 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001952
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001953 if (!mSystemReady) {
1954 // If the system is not yet ready, we shouldn't be running third
1955 // party code.
Yohei Yukawa2553e482017-12-15 15:47:33 -08001956 return new InputBindResult(
1957 InputBindResult.ResultCode.ERROR_SYSTEM_NOT_READY,
1958 null, null, mCurMethodId, mCurSeq,
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09001959 mCurUserActionNotificationSequenceNumber);
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001960 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001961
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 InputMethodInfo info = mMethodMap.get(mCurMethodId);
1963 if (info == null) {
1964 throw new IllegalArgumentException("Unknown id: " + mCurMethodId);
1965 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001966
Yohei Yukawabc7b5262015-11-17 17:38:41 -08001967 unbindCurrentMethodLocked(true);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001968
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 mCurIntent = new Intent(InputMethod.SERVICE_INTERFACE);
1970 mCurIntent.setComponent(info.getComponent());
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07001971 mCurIntent.putExtra(Intent.EXTRA_CLIENT_LABEL,
1972 com.android.internal.R.string.input_method_binding_label);
1973 mCurIntent.putExtra(Intent.EXTRA_CLIENT_INTENT, PendingIntent.getActivity(
1974 mContext, 0, new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS), 0));
Yohei Yukawaf80087c2018-05-21 09:47:53 -07001975 if (bindCurrentInputMethodServiceLocked(mCurIntent, this, IME_CONNECTION_BIND_FLAGS)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 mLastBindTime = SystemClock.uptimeMillis();
1977 mHaveConnection = true;
1978 mCurId = info.getId();
1979 mCurToken = new Binder();
1980 try {
Yohei Yukawad0332832017-02-01 13:59:43 -08001981 if (DEBUG) Slog.v(TAG, "Adding window token: " + mCurToken);
Wale Ogunwaleac2561e2016-11-01 15:43:46 -07001982 mIWindowManager.addWindowToken(mCurToken, TYPE_INPUT_METHOD, DEFAULT_DISPLAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001983 } catch (RemoteException e) {
1984 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08001985 return new InputBindResult(
1986 InputBindResult.ResultCode.SUCCESS_WAITING_IME_BINDING,
1987 null, null, mCurId, mCurSeq,
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09001988 mCurUserActionNotificationSequenceNumber);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001989 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08001990 mCurIntent = null;
1991 Slog.w(TAG, "Failure connecting to input method service: " + mCurIntent);
1992 return InputBindResult.IME_NOT_CONNECTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001994
Yohei Yukawa2553e482017-12-15 15:47:33 -08001995 @NonNull
Yohei Yukawa05c25f82016-02-22 12:41:17 -08001996 private InputBindResult startInput(
Yohei Yukawa35d3f372015-11-25 11:07:19 -08001997 /* @InputMethodClient.StartInputReason */ final int startInputReason,
Yohei Yukawa19a80a12016-03-14 22:57:37 -07001998 IInputMethodClient client, IInputContext inputContext,
1999 /* @InputConnectionInspector.missingMethods */ final int missingMethods,
Yohei Yukawa74750f22016-03-22 12:54:22 -07002000 @Nullable EditorInfo attribute, int controlFlags) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002001 if (!calledFromValidUser()) {
Yohei Yukawa2553e482017-12-15 15:47:33 -08002002 return InputBindResult.INVALID_USER;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 synchronized (mMethodMap) {
Yohei Yukawa35d3f372015-11-25 11:07:19 -08002005 if (DEBUG) {
2006 Slog.v(TAG, "startInput: reason="
2007 + InputMethodClient.getStartInputReason(startInputReason)
2008 + " client = " + client.asBinder()
2009 + " inputContext=" + inputContext
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002010 + " missingMethods="
2011 + InputConnectionInspector.getMissingMethodFlagsAsString(missingMethods)
Yohei Yukawa35d3f372015-11-25 11:07:19 -08002012 + " attribute=" + attribute
2013 + " controlFlags=#" + Integer.toHexString(controlFlags));
2014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002015 final long ident = Binder.clearCallingIdentity();
2016 try {
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002017 return startInputLocked(startInputReason, client, inputContext, missingMethods,
2018 attribute, controlFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 } finally {
2020 Binder.restoreCallingIdentity(ident);
2021 }
2022 }
2023 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002024
satoke7c6998e2011-06-03 17:57:59 +09002025 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 public void finishInput(IInputMethodClient client) {
2027 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002028
satoke7c6998e2011-06-03 17:57:59 +09002029 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 public void onServiceConnected(ComponentName name, IBinder service) {
2031 synchronized (mMethodMap) {
2032 if (mCurIntent != null && name.equals(mCurIntent.getComponent())) {
2033 mCurMethod = IInputMethod.Stub.asInterface(service);
Dianne Hackborncc278702009-09-02 23:07:23 -07002034 if (mCurToken == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002035 Slog.w(TAG, "Service connected without a token!");
Yohei Yukawabc7b5262015-11-17 17:38:41 -08002036 unbindCurrentMethodLocked(false);
Dianne Hackborncc278702009-09-02 23:07:23 -07002037 return;
2038 }
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07002039 if (DEBUG) Slog.v(TAG, "Initiating attach with token: " + mCurToken);
Dianne Hackborncc278702009-09-02 23:07:23 -07002040 executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
2041 MSG_ATTACH_TOKEN, mCurMethod, mCurToken));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 if (mCurClient != null) {
Jeff Brownc28867a2013-03-26 15:42:39 -07002043 clearClientSessionLocked(mCurClient);
2044 requestClientSessionLocked(mCurClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 }
2046 }
2047 }
2048 }
2049
Jeff Brownc28867a2013-03-26 15:42:39 -07002050 void onSessionCreated(IInputMethod method, IInputMethodSession session,
2051 InputChannel channel) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 synchronized (mMethodMap) {
2053 if (mCurMethod != null && method != null
2054 && mCurMethod.asBinder() == method.asBinder()) {
2055 if (mCurClient != null) {
Jeff Brownc28867a2013-03-26 15:42:39 -07002056 clearClientSessionLocked(mCurClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057 mCurClient.curSession = new SessionState(mCurClient,
Jeff Brownc28867a2013-03-26 15:42:39 -07002058 method, session, channel);
Yohei Yukawa87ca8402017-02-07 00:13:14 -08002059 InputBindResult res = attachNewInputLocked(
2060 InputMethodClient.START_INPUT_REASON_SESSION_CREATED_BY_IME, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061 if (res.method != null) {
2062 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageOO(
Yohei Yukawa33e81792015-11-17 21:14:42 -08002063 MSG_BIND_CLIENT, mCurClient.client, res));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 }
Jeff Brownc28867a2013-03-26 15:42:39 -07002065 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 }
2067 }
2068 }
Jeff Brownc28867a2013-03-26 15:42:39 -07002069
2070 // Session abandoned. Close its associated input channel.
2071 channel.dispose();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002073
Yohei Yukawabc7b5262015-11-17 17:38:41 -08002074 void unbindCurrentMethodLocked(boolean savePosition) {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -07002075 if (mVisibleBound) {
2076 mContext.unbindService(mVisibleConnection);
2077 mVisibleBound = false;
2078 }
2079
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002080 if (mHaveConnection) {
2081 mContext.unbindService(this);
2082 mHaveConnection = false;
2083 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002084
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002085 if (mCurToken != null) {
2086 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002087 if (DEBUG) Slog.v(TAG, "Removing window token: " + mCurToken);
Dianne Hackborn2ea9bae2012-11-02 18:43:48 -07002088 if ((mImeWindowVis & InputMethodService.IME_ACTIVE) != 0 && savePosition) {
satoke0a99412012-05-10 02:22:58 +09002089 // The current IME is shown. Hence an IME switch (transition) is happening.
Seigo Nonaka7309b122015-08-17 18:34:13 -07002090 mWindowManagerInternal.saveLastInputMethodWindowForTransition();
satoke0a99412012-05-10 02:22:58 +09002091 }
Wale Ogunwaleac2561e2016-11-01 15:43:46 -07002092 mIWindowManager.removeWindowToken(mCurToken, DEFAULT_DISPLAY);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002093 } catch (RemoteException e) {
2094 }
2095 mCurToken = null;
2096 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002097
The Android Open Source Project10592532009-03-18 17:39:46 -07002098 mCurId = null;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002099 clearCurMethodLocked();
Yohei Yukawabc7b5262015-11-17 17:38:41 -08002100 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002101
Yohei Yukawa33e81792015-11-17 21:14:42 -08002102 void resetCurrentMethodAndClient(
2103 /* @InputMethodClient.UnbindReason */ final int unbindClientReason) {
Yohei Yukawabc7b5262015-11-17 17:38:41 -08002104 mCurMethodId = null;
2105 unbindCurrentMethodLocked(false);
Yohei Yukawa33e81792015-11-17 21:14:42 -08002106 unbindCurrentClientLocked(unbindClientReason);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002107 }
Jeff Brownc28867a2013-03-26 15:42:39 -07002108
2109 void requestClientSessionLocked(ClientState cs) {
2110 if (!cs.sessionRequested) {
2111 if (DEBUG) Slog.v(TAG, "Creating new session for client " + cs);
2112 InputChannel[] channels = InputChannel.openInputChannelPair(cs.toString());
2113 cs.sessionRequested = true;
2114 executeOrSendMessage(mCurMethod, mCaller.obtainMessageOOO(
2115 MSG_CREATE_SESSION, mCurMethod, channels[1],
2116 new MethodCallback(this, mCurMethod, channels[0])));
2117 }
2118 }
2119
2120 void clearClientSessionLocked(ClientState cs) {
2121 finishSessionLocked(cs.curSession);
2122 cs.curSession = null;
2123 cs.sessionRequested = false;
2124 }
2125
2126 private void finishSessionLocked(SessionState sessionState) {
2127 if (sessionState != null) {
2128 if (sessionState.session != null) {
2129 try {
2130 sessionState.session.finishSession();
2131 } catch (RemoteException e) {
2132 Slog.w(TAG, "Session failed to close due to remote exception", e);
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002133 updateSystemUiLocked(mCurToken, 0 /* vis */, mBackDisposition);
Jeff Brownc28867a2013-03-26 15:42:39 -07002134 }
2135 sessionState.session = null;
2136 }
2137 if (sessionState.channel != null) {
2138 sessionState.channel.dispose();
2139 sessionState.channel = null;
Devin Taylor0c33ed22010-02-23 13:26:46 -06002140 }
2141 }
2142 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002143
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002144 void clearCurMethodLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002145 if (mCurMethod != null) {
2146 for (ClientState cs : mClients.values()) {
Jeff Brownc28867a2013-03-26 15:42:39 -07002147 clearClientSessionLocked(cs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002148 }
Devin Taylor0c33ed22010-02-23 13:26:46 -06002149
Jeff Brownc28867a2013-03-26 15:42:39 -07002150 finishSessionLocked(mEnabledSession);
Devin Taylor0c33ed22010-02-23 13:26:46 -06002151 mEnabledSession = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152 mCurMethod = null;
2153 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07002154 if (mStatusBar != null) {
Jason Monk3e189872016-01-12 09:10:34 -05002155 mStatusBar.setIconVisibility(mSlotIme, false);
Dianne Hackborn661cd522011-08-22 00:26:20 -07002156 }
Yohei Yukawa2bc66172017-02-08 11:13:25 -08002157 mInFullscreenMode = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002158 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002159
satoke7c6998e2011-06-03 17:57:59 +09002160 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002161 public void onServiceDisconnected(ComponentName name) {
Yohei Yukawa817d5f72017-01-04 20:15:02 -08002162 // Note that mContext.unbindService(this) does not trigger this. Hence if we are here the
2163 // disconnection is not intended by IMMS (e.g. triggered because the current IMS crashed),
2164 // which is irregular but can eventually happen for everyone just by continuing using the
2165 // device. Thus it is important to make sure that all the internal states are properly
2166 // refreshed when this method is called back. Running
2167 // adb install -r <APK that implements the current IME>
2168 // would be a good way to trigger such a situation.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002169 synchronized (mMethodMap) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002170 if (DEBUG) Slog.v(TAG, "Service disconnected: " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002171 + " mCurIntent=" + mCurIntent);
2172 if (mCurMethod != null && mCurIntent != null
2173 && name.equals(mCurIntent.getComponent())) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002174 clearCurMethodLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002175 // We consider this to be a new bind attempt, since the system
2176 // should now try to restart the service for us.
2177 mLastBindTime = SystemClock.uptimeMillis();
2178 mShowRequested = mInputShown;
2179 mInputShown = false;
Yohei Yukawa817d5f72017-01-04 20:15:02 -08002180 unbindCurrentClientLocked(InputMethodClient.UNBIND_REASON_DISCONNECT_IME);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002181 }
2182 }
2183 }
2184
satokf9f01002011-05-19 21:31:50 +09002185 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002186 public void updateStatusIcon(IBinder token, String packageName, int iconId) {
Yohei Yukawa59377ca2017-01-31 21:32:26 -08002187 synchronized (mMethodMap) {
2188 if (!calledWithValidToken(token)) {
Yohei Yukawa59377ca2017-01-31 21:32:26 -08002189 return;
2190 }
2191 final long ident = Binder.clearCallingIdentity();
2192 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002193 if (iconId == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002194 if (DEBUG) Slog.d(TAG, "hide the small icon for the input method");
Dianne Hackborn661cd522011-08-22 00:26:20 -07002195 if (mStatusBar != null) {
Jason Monk3e189872016-01-12 09:10:34 -05002196 mStatusBar.setIconVisibility(mSlotIme, false);
Dianne Hackborn661cd522011-08-22 00:26:20 -07002197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002198 } else if (packageName != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002199 if (DEBUG) Slog.d(TAG, "show a small icon for the input method");
Svetoslav Ganov6179ea32011-06-28 01:12:41 -07002200 CharSequence contentDescription = null;
2201 try {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002202 // Use PackageManager to load label
2203 final PackageManager packageManager = mContext.getPackageManager();
Svetoslav Ganov6179ea32011-06-28 01:12:41 -07002204 contentDescription = packageManager.getApplicationLabel(
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002205 mIPackageManager.getApplicationInfo(packageName, 0,
2206 mSettings.getCurrentUserId()));
2207 } catch (RemoteException e) {
Svetoslav Ganov6179ea32011-06-28 01:12:41 -07002208 /* ignore */
2209 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07002210 if (mStatusBar != null) {
Jason Monk3e189872016-01-12 09:10:34 -05002211 mStatusBar.setIcon(mSlotIme, packageName, iconId, 0,
Dianne Hackborn661cd522011-08-22 00:26:20 -07002212 contentDescription != null
2213 ? contentDescription.toString() : null);
Jason Monk3e189872016-01-12 09:10:34 -05002214 mStatusBar.setIconVisibility(mSlotIme, true);
Dianne Hackborn661cd522011-08-22 00:26:20 -07002215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002216 }
Yohei Yukawa59377ca2017-01-31 21:32:26 -08002217 } finally {
2218 Binder.restoreCallingIdentity(ident);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002219 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002220 }
2221 }
2222
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002223 private boolean shouldShowImeSwitcherLocked(int visibility) {
satok7cfc0ed2011-06-20 21:29:36 +09002224 if (!mShowOngoingImeSwitcherForPhones) return false;
Jason Monk807ef762014-05-08 15:47:46 -04002225 if (mSwitchingDialog != null) return false;
Yohei Yukawad2bc3092017-07-31 15:37:14 -07002226 if (mWindowManagerInternal.isKeyguardShowingAndNotOccluded()
2227 && mKeyguardManager != null && mKeyguardManager.isKeyguardSecure()) return false;
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002228 if ((visibility & InputMethodService.IME_ACTIVE) == 0) return false;
Seigo Nonaka7309b122015-08-17 18:34:13 -07002229 if (mWindowManagerInternal.isHardKeyboardAvailable()) {
Yohei Yukawafa0e47e2016-04-05 09:55:56 -07002230 if (mHardKeyboardBehavior == HardKeyboardBehavior.WIRELESS_AFFORDANCE) {
2231 // When physical keyboard is attached, we show the ime switcher (or notification if
2232 // NavBar is not available) because SHOW_IME_WITH_HARD_KEYBOARD settings currently
2233 // exists in the IME switcher dialog. Might be OK to remove this condition once
2234 // SHOW_IME_WITH_HARD_KEYBOARD settings finds a good place to live.
2235 return true;
2236 }
Yohei Yukawa89398382016-03-29 11:37:04 -07002237 } else if ((visibility & InputMethodService.IME_VISIBLE) == 0) {
2238 return false;
Yohei Yukawac6c7cd22015-05-12 15:00:33 -07002239 }
Yohei Yukawac6c7cd22015-05-12 15:00:33 -07002240
2241 List<InputMethodInfo> imis = mSettings.getEnabledInputMethodListLocked();
2242 final int N = imis.size();
2243 if (N > 2) return true;
2244 if (N < 1) return false;
2245 int nonAuxCount = 0;
2246 int auxCount = 0;
2247 InputMethodSubtype nonAuxSubtype = null;
2248 InputMethodSubtype auxSubtype = null;
2249 for(int i = 0; i < N; ++i) {
2250 final InputMethodInfo imi = imis.get(i);
2251 final List<InputMethodSubtype> subtypes =
2252 mSettings.getEnabledInputMethodSubtypeListLocked(mContext, imi, true);
2253 final int subtypeCount = subtypes.size();
2254 if (subtypeCount == 0) {
2255 ++nonAuxCount;
2256 } else {
2257 for (int j = 0; j < subtypeCount; ++j) {
2258 final InputMethodSubtype subtype = subtypes.get(j);
2259 if (!subtype.isAuxiliary()) {
2260 ++nonAuxCount;
2261 nonAuxSubtype = subtype;
2262 } else {
2263 ++auxCount;
2264 auxSubtype = subtype;
satok7cfc0ed2011-06-20 21:29:36 +09002265 }
2266 }
satok7cfc0ed2011-06-20 21:29:36 +09002267 }
2268 }
Yohei Yukawac6c7cd22015-05-12 15:00:33 -07002269 if (nonAuxCount > 1 || auxCount > 1) {
2270 return true;
2271 } else if (nonAuxCount == 1 && auxCount == 1) {
2272 if (nonAuxSubtype != null && auxSubtype != null
2273 && (nonAuxSubtype.getLocale().equals(auxSubtype.getLocale())
2274 || auxSubtype.overridesImplicitlyEnabledSubtype()
2275 || nonAuxSubtype.overridesImplicitlyEnabledSubtype())
2276 && nonAuxSubtype.containsExtraValueKey(TAG_TRY_SUPPRESSING_IME_SWITCHER)) {
2277 return false;
2278 }
2279 return true;
2280 }
2281 return false;
satok7cfc0ed2011-06-20 21:29:36 +09002282 }
2283
John Spurlocke0980502013-10-25 11:59:29 -04002284 private boolean isKeyguardLocked() {
2285 return mKeyguardManager != null && mKeyguardManager.isKeyguardLocked();
2286 }
2287
Yohei Yukawad6475a62017-04-17 10:35:27 -07002288 @BinderThread
satokdbf29502011-08-25 15:28:23 +09002289 @SuppressWarnings("deprecation")
satokf9f01002011-05-19 21:31:50 +09002290 @Override
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08002291 public void setImeWindowStatus(IBinder token, IBinder startInputToken, int vis,
2292 int backDisposition) {
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002293 if (!calledWithValidToken(token)) {
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002294 return;
2295 }
2296
Yohei Yukawa69e68022017-02-13 12:04:50 -08002297 final StartInputInfo info;
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002298 synchronized (mMethodMap) {
Yohei Yukawa69e68022017-02-13 12:04:50 -08002299 info = mStartInputMap.get(startInputToken);
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002300 mImeWindowVis = vis;
2301 mBackDisposition = backDisposition;
2302 updateSystemUiLocked(token, vis, backDisposition);
2303 }
Yohei Yukawad6475a62017-04-17 10:35:27 -07002304
2305 final boolean dismissImeOnBackKeyPressed;
2306 switch (backDisposition) {
2307 case InputMethodService.BACK_DISPOSITION_WILL_DISMISS:
2308 dismissImeOnBackKeyPressed = true;
2309 break;
2310 case InputMethodService.BACK_DISPOSITION_WILL_NOT_DISMISS:
2311 dismissImeOnBackKeyPressed = false;
2312 break;
2313 default:
2314 case InputMethodService.BACK_DISPOSITION_DEFAULT:
2315 dismissImeOnBackKeyPressed = ((vis & InputMethodService.IME_VISIBLE) != 0);
2316 break;
2317 }
Yohei Yukawaee2a7ed2017-02-15 21:38:57 -08002318 mWindowManagerInternal.updateInputMethodWindowStatus(token,
2319 (vis & InputMethodService.IME_VISIBLE) != 0,
Yohei Yukawad6475a62017-04-17 10:35:27 -07002320 dismissImeOnBackKeyPressed, info != null ? info.mTargetWindow : null);
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002321 }
2322
2323 private void updateSystemUi(IBinder token, int vis, int backDisposition) {
2324 synchronized (mMethodMap) {
2325 updateSystemUiLocked(token, vis, backDisposition);
2326 }
2327 }
2328
2329 // Caution! This method is called in this class. Handle multi-user carefully
2330 private void updateSystemUiLocked(IBinder token, int vis, int backDisposition) {
2331 if (!calledWithValidToken(token)) {
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002332 return;
2333 }
2334
2335 // TODO: Move this clearing calling identity block to setImeWindowStatus after making sure
2336 // all updateSystemUi happens on system previlege.
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002337 final long ident = Binder.clearCallingIdentity();
satok06487a52010-10-29 11:37:18 +09002338 try {
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002339 // apply policy for binder calls
2340 if (vis != 0 && isKeyguardLocked() && !mCurClientInKeyguard) {
2341 vis = 0;
satok06487a52010-10-29 11:37:18 +09002342 }
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002343 // mImeWindowVis should be updated before calling shouldShowImeSwitcherLocked().
2344 final boolean needsToShowImeSwitcher = shouldShowImeSwitcherLocked(vis);
2345 if (mStatusBar != null) {
2346 mStatusBar.setImeWindowStatus(token, vis, backDisposition,
2347 needsToShowImeSwitcher);
2348 }
2349 final InputMethodInfo imi = mMethodMap.get(mCurMethodId);
2350 if (imi != null && needsToShowImeSwitcher) {
2351 // Used to load label
2352 final CharSequence title = mRes.getText(
2353 com.android.internal.R.string.select_input_method);
2354 final CharSequence summary = InputMethodUtils.getImeAndSubtypeDisplayName(
2355 mContext, imi, mCurrentSubtype);
Chris Wren1ce4b6d2015-06-11 10:19:43 -04002356 mImeSwitcherNotification.setContentTitle(title)
2357 .setContentText(summary)
2358 .setContentIntent(mImeSwitchPendingIntent);
Seigo Nonaka7309b122015-08-17 18:34:13 -07002359 try {
2360 if ((mNotificationManager != null)
2361 && !mIWindowManager.hasNavigationBar()) {
2362 if (DEBUG) {
2363 Slog.d(TAG, "--- show notification: label = " + summary);
2364 }
2365 mNotificationManager.notifyAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04002366 SystemMessage.NOTE_SELECT_INPUT_METHOD,
Seigo Nonaka7309b122015-08-17 18:34:13 -07002367 mImeSwitcherNotification.build(), UserHandle.ALL);
2368 mNotificationShown = true;
Dianne Hackborn661cd522011-08-22 00:26:20 -07002369 }
Seigo Nonaka7309b122015-08-17 18:34:13 -07002370 } catch (RemoteException e) {
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002371 }
2372 } else {
2373 if (mNotificationShown && mNotificationManager != null) {
2374 if (DEBUG) {
2375 Slog.d(TAG, "--- hide notification");
satok7cfc0ed2011-06-20 21:29:36 +09002376 }
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002377 mNotificationManager.cancelAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04002378 SystemMessage.NOTE_SELECT_INPUT_METHOD, UserHandle.ALL);
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002379 mNotificationShown = false;
satok7cfc0ed2011-06-20 21:29:36 +09002380 }
satok06487a52010-10-29 11:37:18 +09002381 }
2382 } finally {
2383 Binder.restoreCallingIdentity(ident);
2384 }
2385 }
2386
satoke7c6998e2011-06-03 17:57:59 +09002387 @Override
satokf9f01002011-05-19 21:31:50 +09002388 public void registerSuggestionSpansForNotification(SuggestionSpan[] spans) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002389 if (!calledFromValidUser()) {
2390 return;
2391 }
satokf9f01002011-05-19 21:31:50 +09002392 synchronized (mMethodMap) {
2393 final InputMethodInfo currentImi = mMethodMap.get(mCurMethodId);
2394 for (int i = 0; i < spans.length; ++i) {
2395 SuggestionSpan ss = spans[i];
satok42c5a162011-05-26 16:46:14 +09002396 if (!TextUtils.isEmpty(ss.getNotificationTargetClassName())) {
satokf9f01002011-05-19 21:31:50 +09002397 mSecureSuggestionSpans.put(ss, currentImi);
2398 }
2399 }
2400 }
2401 }
2402
satoke7c6998e2011-06-03 17:57:59 +09002403 @Override
satokf9f01002011-05-19 21:31:50 +09002404 public boolean notifySuggestionPicked(SuggestionSpan span, String originalString, int index) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002405 if (!calledFromValidUser()) {
2406 return false;
2407 }
satokf9f01002011-05-19 21:31:50 +09002408 synchronized (mMethodMap) {
2409 final InputMethodInfo targetImi = mSecureSuggestionSpans.get(span);
2410 // TODO: Do not send the intent if the process of the targetImi is already dead.
2411 if (targetImi != null) {
2412 final String[] suggestions = span.getSuggestions();
2413 if (index < 0 || index >= suggestions.length) return false;
satok42c5a162011-05-26 16:46:14 +09002414 final String className = span.getNotificationTargetClassName();
satokf9f01002011-05-19 21:31:50 +09002415 final Intent intent = new Intent();
2416 // Ensures that only a class in the original IME package will receive the
2417 // notification.
satok42c5a162011-05-26 16:46:14 +09002418 intent.setClassName(targetImi.getPackageName(), className);
satokf9f01002011-05-19 21:31:50 +09002419 intent.setAction(SuggestionSpan.ACTION_SUGGESTION_PICKED);
2420 intent.putExtra(SuggestionSpan.SUGGESTION_SPAN_PICKED_BEFORE, originalString);
2421 intent.putExtra(SuggestionSpan.SUGGESTION_SPAN_PICKED_AFTER, suggestions[index]);
2422 intent.putExtra(SuggestionSpan.SUGGESTION_SPAN_PICKED_HASHCODE, span.hashCode());
Amith Yamasanif043de92012-10-24 06:42:40 -07002423 final long ident = Binder.clearCallingIdentity();
2424 try {
2425 mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT);
2426 } finally {
2427 Binder.restoreCallingIdentity(ident);
2428 }
satokf9f01002011-05-19 21:31:50 +09002429 return true;
2430 }
2431 }
2432 return false;
2433 }
2434
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08002435 void updateFromSettingsLocked(boolean enabledMayChange) {
Michael Wright7b5a96b2014-08-09 19:28:42 -07002436 updateInputMethodsFromSettingsLocked(enabledMayChange);
2437 updateKeyboardFromSettingsLocked();
2438 }
2439
2440 void updateInputMethodsFromSettingsLocked(boolean enabledMayChange) {
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08002441 if (enabledMayChange) {
2442 List<InputMethodInfo> enabled = mSettings.getEnabledInputMethodListLocked();
2443 for (int i=0; i<enabled.size(); i++) {
2444 // We allow the user to select "disabled until used" apps, so if they
2445 // are enabling one of those here we now need to make it enabled.
2446 InputMethodInfo imm = enabled.get(i);
2447 try {
2448 ApplicationInfo ai = mIPackageManager.getApplicationInfo(imm.getPackageName(),
2449 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
2450 mSettings.getCurrentUserId());
Satoshi Kataoka7987a312013-04-17 18:59:33 +09002451 if (ai != null && ai.enabledSetting
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08002452 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
Satoshi Kataokaed1cdb22013-04-17 16:41:58 +09002453 if (DEBUG) {
2454 Slog.d(TAG, "Update state(" + imm.getId()
2455 + "): DISABLED_UNTIL_USED -> DEFAULT");
2456 }
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08002457 mIPackageManager.setApplicationEnabledSetting(imm.getPackageName(),
2458 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07002459 PackageManager.DONT_KILL_APP, mSettings.getCurrentUserId(),
2460 mContext.getBasePackageName());
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08002461 }
2462 } catch (RemoteException e) {
2463 }
2464 }
2465 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002466 // We are assuming that whoever is changing DEFAULT_INPUT_METHOD and
2467 // ENABLED_INPUT_METHODS is taking care of keeping them correctly in
2468 // sync, so we will never have a DEFAULT_INPUT_METHOD that is not
2469 // enabled.
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002470 String id = mSettings.getSelectedInputMethod();
satok03eb319a2010-11-11 18:17:42 +09002471 // There is no input method selected, try to choose new applicable input method.
2472 if (TextUtils.isEmpty(id) && chooseNewDefaultIMELocked()) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002473 id = mSettings.getSelectedInputMethod();
satok03eb319a2010-11-11 18:17:42 +09002474 }
2475 if (!TextUtils.isEmpty(id)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476 try {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09002477 setInputMethodLocked(id, mSettings.getSelectedInputMethodSubtypeId(id));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 } catch (IllegalArgumentException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002479 Slog.w(TAG, "Unknown input method from prefs: " + id, e);
Yohei Yukawa33e81792015-11-17 21:14:42 -08002480 resetCurrentMethodAndClient(InputMethodClient.UNBIND_REASON_SWITCH_IME_FAILED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002481 }
satokf3db1af2010-11-23 13:34:33 +09002482 mShortcutInputMethodsAndSubtypes.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002483 } else {
2484 // There is no longer an input method set, so stop any current one.
Yohei Yukawa33e81792015-11-17 21:14:42 -08002485 resetCurrentMethodAndClient(InputMethodClient.UNBIND_REASON_NO_IME);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 }
Yohei Yukawa3d46bab2014-05-30 18:10:18 +09002487 // Here is not the perfect place to reset the switching controller. Ideally
2488 // mSwitchingController and mSettings should be able to share the same state.
2489 // TODO: Make sure that mSwitchingController and mSettings are sharing the
2490 // the same enabled IMEs list.
2491 mSwitchingController.resetCircularListLocked(mContext);
Michael Wright7b5a96b2014-08-09 19:28:42 -07002492
2493 }
2494
2495 public void updateKeyboardFromSettingsLocked() {
2496 mShowImeWithHardKeyboard = mSettings.isShowImeWithHardKeyboardEnabled();
2497 if (mSwitchingDialog != null
2498 && mSwitchingDialogTitleView != null
2499 && mSwitchingDialog.isShowing()) {
2500 final Switch hardKeySwitch = (Switch)mSwitchingDialogTitleView.findViewById(
2501 com.android.internal.R.id.hard_keyboard_switch);
2502 hardKeySwitch.setChecked(mShowImeWithHardKeyboard);
2503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002505
satokab751aa2010-09-14 19:17:36 +09002506 /* package */ void setInputMethodLocked(String id, int subtypeId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002507 InputMethodInfo info = mMethodMap.get(id);
2508 if (info == null) {
satok913a8922010-08-26 21:53:41 +09002509 throw new IllegalArgumentException("Unknown id: " + id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002510 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002511
satokd81e9502012-05-21 12:58:45 +09002512 // See if we need to notify a subtype change within the same IME.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002513 if (id.equals(mCurMethodId)) {
satokd81e9502012-05-21 12:58:45 +09002514 final int subtypeCount = info.getSubtypeCount();
2515 if (subtypeCount <= 0) {
2516 return;
satokcd7cd292010-11-20 15:46:23 +09002517 }
satokd81e9502012-05-21 12:58:45 +09002518 final InputMethodSubtype oldSubtype = mCurrentSubtype;
2519 final InputMethodSubtype newSubtype;
2520 if (subtypeId >= 0 && subtypeId < subtypeCount) {
2521 newSubtype = info.getSubtypeAt(subtypeId);
2522 } else {
2523 // If subtype is null, try to find the most applicable one from
2524 // getCurrentInputMethodSubtype.
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002525 newSubtype = getCurrentInputMethodSubtypeLocked();
satokd81e9502012-05-21 12:58:45 +09002526 }
2527 if (newSubtype == null || oldSubtype == null) {
2528 Slog.w(TAG, "Illegal subtype state: old subtype = " + oldSubtype
2529 + ", new subtype = " + newSubtype);
2530 return;
2531 }
2532 if (newSubtype != oldSubtype) {
2533 setSelectedInputMethodAndSubtypeLocked(info, subtypeId, true);
2534 if (mCurMethod != null) {
2535 try {
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002536 updateSystemUiLocked(mCurToken, mImeWindowVis, mBackDisposition);
satokd81e9502012-05-21 12:58:45 +09002537 mCurMethod.changeInputMethodSubtype(newSubtype);
2538 } catch (RemoteException e) {
2539 Slog.w(TAG, "Failed to call changeInputMethodSubtype");
satokab751aa2010-09-14 19:17:36 +09002540 }
2541 }
2542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543 return;
2544 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002545
satokd81e9502012-05-21 12:58:45 +09002546 // Changing to a different IME.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002547 final long ident = Binder.clearCallingIdentity();
2548 try {
satokab751aa2010-09-14 19:17:36 +09002549 // Set a subtype to this input method.
2550 // subtypeId the name of a subtype which will be set.
satok723a27e2010-11-11 14:58:11 +09002551 setSelectedInputMethodAndSubtypeLocked(info, subtypeId, false);
2552 // mCurMethodId should be updated after setSelectedInputMethodAndSubtypeLocked()
2553 // because mCurMethodId is stored as a history in
2554 // setSelectedInputMethodAndSubtypeLocked().
2555 mCurMethodId = id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07002557 if (LocalServices.getService(ActivityManagerInternal.class).isSystemReady()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 Intent intent = new Intent(Intent.ACTION_INPUT_METHOD_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002559 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002560 intent.putExtra("input_method_id", id);
Amith Yamasanicd757062012-10-19 18:23:52 -07002561 mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 }
Yohei Yukawa33e81792015-11-17 21:14:42 -08002563 unbindCurrentClientLocked(InputMethodClient.UNBIND_REASON_SWITCH_IME);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 } finally {
2565 Binder.restoreCallingIdentity(ident);
2566 }
2567 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002568
satok42c5a162011-05-26 16:46:14 +09002569 @Override
The Android Open Source Project4df24232009-03-05 14:34:35 -08002570 public boolean showSoftInput(IInputMethodClient client, int flags,
2571 ResultReceiver resultReceiver) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002572 if (!calledFromValidUser()) {
2573 return false;
2574 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002575 int uid = Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 long ident = Binder.clearCallingIdentity();
2577 try {
2578 synchronized (mMethodMap) {
2579 if (mCurClient == null || client == null
2580 || mCurClient.client.asBinder() != client.asBinder()) {
2581 try {
2582 // We need to check if this is the current client with
2583 // focus in the window manager, to allow this call to
2584 // be made before input is started in it.
2585 if (!mIWindowManager.inputMethodClientHasFocus(client)) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002586 Slog.w(TAG, "Ignoring showSoftInput of uid " + uid + ": " + client);
The Android Open Source Project4df24232009-03-05 14:34:35 -08002587 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 }
2589 } catch (RemoteException e) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08002590 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 }
2592 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002593
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07002594 if (DEBUG) Slog.v(TAG, "Client requesting input be shown");
The Android Open Source Project4df24232009-03-05 14:34:35 -08002595 return showCurrentInputLocked(flags, resultReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 }
2597 } finally {
2598 Binder.restoreCallingIdentity(ident);
2599 }
2600 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002601
The Android Open Source Project4df24232009-03-05 14:34:35 -08002602 boolean showCurrentInputLocked(int flags, ResultReceiver resultReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002603 mShowRequested = true;
Anna Galusza9b278112016-01-04 11:37:37 -08002604 if (mAccessibilityRequestingNoSoftKeyboard) {
2605 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002606 }
Anna Galusza9b278112016-01-04 11:37:37 -08002607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 if ((flags&InputMethodManager.SHOW_FORCED) != 0) {
2609 mShowExplicitlyRequested = true;
2610 mShowForced = true;
Anna Galusza9b278112016-01-04 11:37:37 -08002611 } else if ((flags&InputMethodManager.SHOW_IMPLICIT) == 0) {
2612 mShowExplicitlyRequested = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002613 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002614
Dianne Hackborncc278702009-09-02 23:07:23 -07002615 if (!mSystemReady) {
2616 return false;
2617 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002618
The Android Open Source Project4df24232009-03-05 14:34:35 -08002619 boolean res = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002620 if (mCurMethod != null) {
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07002621 if (DEBUG) Slog.d(TAG, "showCurrentInputLocked: mCurToken=" + mCurToken);
The Android Open Source Project4df24232009-03-05 14:34:35 -08002622 executeOrSendMessage(mCurMethod, mCaller.obtainMessageIOO(
2623 MSG_SHOW_SOFT_INPUT, getImeShowFlags(), mCurMethod,
2624 resultReceiver));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625 mInputShown = true;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -07002626 if (mHaveConnection && !mVisibleBound) {
Yohei Yukawaf80087c2018-05-21 09:47:53 -07002627 bindCurrentInputMethodServiceLocked(
Yohei Yukawaa67a4592017-03-30 15:57:02 -07002628 mCurIntent, mVisibleConnection, IME_VISIBLE_BIND_FLAGS);
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -07002629 mVisibleBound = true;
2630 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08002631 res = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002632 } else if (mHaveConnection && SystemClock.uptimeMillis()
satok59b424c2011-09-30 17:21:46 +09002633 >= (mLastBindTime+TIME_TO_RECONNECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002634 // The client has asked to have the input method shown, but
2635 // we have been sitting here too long with a connection to the
2636 // service and no interface received, so let's disconnect/connect
2637 // to try to prod things along.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002638 EventLog.writeEvent(EventLogTags.IMF_FORCE_RECONNECT_IME, mCurMethodId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002639 SystemClock.uptimeMillis()-mLastBindTime,1);
satok59b424c2011-09-30 17:21:46 +09002640 Slog.w(TAG, "Force disconnect/connect to the IME in showCurrentInputLocked()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641 mContext.unbindService(this);
Yohei Yukawaf80087c2018-05-21 09:47:53 -07002642 bindCurrentInputMethodServiceLocked(mCurIntent, this, IME_CONNECTION_BIND_FLAGS);
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002643 } else {
2644 if (DEBUG) {
2645 Slog.d(TAG, "Can't show input: connection = " + mHaveConnection + ", time = "
2646 + ((mLastBindTime+TIME_TO_RECONNECT) - SystemClock.uptimeMillis()));
2647 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002648 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002649
The Android Open Source Project4df24232009-03-05 14:34:35 -08002650 return res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002652
satok42c5a162011-05-26 16:46:14 +09002653 @Override
The Android Open Source Project4df24232009-03-05 14:34:35 -08002654 public boolean hideSoftInput(IInputMethodClient client, int flags,
2655 ResultReceiver resultReceiver) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002656 if (!calledFromValidUser()) {
2657 return false;
2658 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002659 int uid = Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002660 long ident = Binder.clearCallingIdentity();
2661 try {
2662 synchronized (mMethodMap) {
2663 if (mCurClient == null || client == null
2664 || mCurClient.client.asBinder() != client.asBinder()) {
2665 try {
2666 // We need to check if this is the current client with
2667 // focus in the window manager, to allow this call to
2668 // be made before input is started in it.
2669 if (!mIWindowManager.inputMethodClientHasFocus(client)) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002670 if (DEBUG) Slog.w(TAG, "Ignoring hideSoftInput of uid "
2671 + uid + ": " + client);
The Android Open Source Project4df24232009-03-05 14:34:35 -08002672 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 }
2674 } catch (RemoteException e) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08002675 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002676 }
2677 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002678
Joe Onorato8a9b2202010-02-26 18:56:32 -08002679 if (DEBUG) Slog.v(TAG, "Client requesting input be hidden");
The Android Open Source Project4df24232009-03-05 14:34:35 -08002680 return hideCurrentInputLocked(flags, resultReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002681 }
2682 } finally {
2683 Binder.restoreCallingIdentity(ident);
2684 }
2685 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002686
The Android Open Source Project4df24232009-03-05 14:34:35 -08002687 boolean hideCurrentInputLocked(int flags, ResultReceiver resultReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 if ((flags&InputMethodManager.HIDE_IMPLICIT_ONLY) != 0
2689 && (mShowExplicitlyRequested || mShowForced)) {
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07002690 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 -08002691 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 }
2693 if (mShowForced && (flags&InputMethodManager.HIDE_NOT_ALWAYS) != 0) {
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07002694 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 -08002695 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002696 }
Seigo Nonakaec928652015-06-10 15:31:20 +09002697
2698 // There is a chance that IMM#hideSoftInput() is called in a transient state where
2699 // IMMS#InputShown is already updated to be true whereas IMMS#mImeWindowVis is still waiting
2700 // to be updated with the new value sent from IME process. Even in such a transient state
2701 // historically we have accepted an incoming call of IMM#hideSoftInput() from the
2702 // application process as a valid request, and have even promised such a behavior with CTS
2703 // since Android Eclair. That's why we need to accept IMM#hideSoftInput() even when only
2704 // IMMS#InputShown indicates that the software keyboard is shown.
2705 // TODO: Clean up, IMMS#mInputShown, IMMS#mImeWindowVis and mShowRequested.
2706 final boolean shouldHideSoftInput = (mCurMethod != null) && (mInputShown ||
2707 (mImeWindowVis & InputMethodService.IME_ACTIVE) != 0);
The Android Open Source Project4df24232009-03-05 14:34:35 -08002708 boolean res;
Seigo Nonakaec928652015-06-10 15:31:20 +09002709 if (shouldHideSoftInput) {
2710 // The IME will report its visible state again after the following message finally
2711 // delivered to the IME process as an IPC. Hence the inconsistency between
2712 // IMMS#mInputShown and IMMS#mImeWindowVis should be resolved spontaneously in
2713 // the final state.
The Android Open Source Project4df24232009-03-05 14:34:35 -08002714 executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
2715 MSG_HIDE_SOFT_INPUT, mCurMethod, resultReceiver));
2716 res = true;
2717 } else {
2718 res = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002719 }
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -07002720 if (mHaveConnection && mVisibleBound) {
2721 mContext.unbindService(mVisibleConnection);
2722 mVisibleBound = false;
2723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 mInputShown = false;
2725 mShowRequested = false;
2726 mShowExplicitlyRequested = false;
2727 mShowForced = false;
The Android Open Source Project4df24232009-03-05 14:34:35 -08002728 return res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002730
Yohei Yukawa2553e482017-12-15 15:47:33 -08002731 @NonNull
satok42c5a162011-05-26 16:46:14 +09002732 @Override
Yohei Yukawa05c25f82016-02-22 12:41:17 -08002733 public InputBindResult startInputOrWindowGainedFocus(
2734 /* @InputMethodClient.StartInputReason */ final int startInputReason,
2735 IInputMethodClient client, IBinder windowToken, int controlFlags, int softInputMode,
Yohei Yukawa74750f22016-03-22 12:54:22 -07002736 int windowFlags, @Nullable EditorInfo attribute, IInputContext inputContext,
Yohei Yukawacf68d522017-12-12 09:33:26 -08002737 /* @InputConnectionInspector.missingMethods */ final int missingMethods,
2738 int unverifiedTargetSdkVersion) {
Yohei Yukawa2553e482017-12-15 15:47:33 -08002739 final InputBindResult result;
Yohei Yukawa05c25f82016-02-22 12:41:17 -08002740 if (windowToken != null) {
Yohei Yukawa2553e482017-12-15 15:47:33 -08002741 result = windowGainedFocus(startInputReason, client, windowToken, controlFlags,
Yohei Yukawacf68d522017-12-12 09:33:26 -08002742 softInputMode, windowFlags, attribute, inputContext, missingMethods,
2743 unverifiedTargetSdkVersion);
Yohei Yukawa05c25f82016-02-22 12:41:17 -08002744 } else {
Yohei Yukawa2553e482017-12-15 15:47:33 -08002745 result = startInput(startInputReason, client, inputContext, missingMethods, attribute,
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002746 controlFlags);
Yohei Yukawa05c25f82016-02-22 12:41:17 -08002747 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08002748 if (result == null) {
2749 // This must never happen, but just in case.
2750 Slog.wtf(TAG, "InputBindResult is @NonNull. startInputReason="
2751 + InputMethodClient.getStartInputReason(startInputReason)
2752 + " windowFlags=#" + Integer.toHexString(windowFlags)
2753 + " editorInfo=" + attribute);
2754 return InputBindResult.NULL;
2755 }
2756 return result;
Yohei Yukawa05c25f82016-02-22 12:41:17 -08002757 }
2758
Yohei Yukawa2553e482017-12-15 15:47:33 -08002759 @NonNull
Yohei Yukawa05c25f82016-02-22 12:41:17 -08002760 private InputBindResult windowGainedFocus(
Yohei Yukawa35d3f372015-11-25 11:07:19 -08002761 /* @InputMethodClient.StartInputReason */ final int startInputReason,
Yohei Yukawa22dac1c2017-02-12 16:54:16 -08002762 IInputMethodClient client, IBinder windowToken, int controlFlags,
2763 /* @android.view.WindowManager.LayoutParams.SoftInputModeFlags */ int softInputMode,
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002764 int windowFlags, EditorInfo attribute, IInputContext inputContext,
Yohei Yukawacf68d522017-12-12 09:33:26 -08002765 /* @InputConnectionInspector.missingMethods */ final int missingMethods,
2766 int unverifiedTargetSdkVersion) {
Satoshi Kataoka8d033052012-11-19 17:30:40 +09002767 // Needs to check the validity before clearing calling identity
2768 final boolean calledFromValidUser = calledFromValidUser();
Dianne Hackborn7663d802012-02-24 13:08:49 -08002769 InputBindResult res = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002770 long ident = Binder.clearCallingIdentity();
2771 try {
2772 synchronized (mMethodMap) {
Yohei Yukawa35d3f372015-11-25 11:07:19 -08002773 if (DEBUG) Slog.v(TAG, "windowGainedFocus: reason="
2774 + InputMethodClient.getStartInputReason(startInputReason)
2775 + " client=" + client.asBinder()
2776 + " inputContext=" + inputContext
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002777 + " missingMethods="
2778 + InputConnectionInspector.getMissingMethodFlagsAsString(missingMethods)
Yohei Yukawa35d3f372015-11-25 11:07:19 -08002779 + " attribute=" + attribute
Dianne Hackborn7663d802012-02-24 13:08:49 -08002780 + " controlFlags=#" + Integer.toHexString(controlFlags)
Yohei Yukawa22a89232017-02-12 16:38:59 -08002781 + " softInputMode=" + InputMethodClient.softInputModeToString(softInputMode)
Yohei Yukawacf68d522017-12-12 09:33:26 -08002782 + " windowFlags=#" + Integer.toHexString(windowFlags)
2783 + " unverifiedTargetSdkVersion=" + unverifiedTargetSdkVersion);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002784
Dianne Hackborn7663d802012-02-24 13:08:49 -08002785 ClientState cs = mClients.get(client.asBinder());
2786 if (cs == null) {
2787 throw new IllegalArgumentException("unknown client "
2788 + client.asBinder());
2789 }
2790
2791 try {
2792 if (!mIWindowManager.inputMethodClientHasFocus(cs.client)) {
2793 // Check with the window manager to make sure this client actually
2794 // has a window with focus. If not, reject. This is thread safe
2795 // because if the focus changes some time before or after, the
2796 // next client receiving focus that has any interest in input will
2797 // be calling through here after that change happens.
Yohei Yukawad0332832017-02-01 13:59:43 -08002798 if (DEBUG) {
2799 Slog.w(TAG, "Focus gain on non-focused client " + cs.client
2800 + " (uid=" + cs.uid + " pid=" + cs.pid + ")");
2801 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08002802 return InputBindResult.NOT_IME_TARGET_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803 }
Dianne Hackborn7663d802012-02-24 13:08:49 -08002804 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002805 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002806
Satoshi Kataoka8d033052012-11-19 17:30:40 +09002807 if (!calledFromValidUser) {
2808 Slog.w(TAG, "A background user is requesting window. Hiding IME.");
2809 Slog.w(TAG, "If you want to interect with IME, you need "
2810 + "android.permission.INTERACT_ACROSS_USERS_FULL");
2811 hideCurrentInputLocked(0, null);
Yohei Yukawa2553e482017-12-15 15:47:33 -08002812 return InputBindResult.INVALID_USER;
Satoshi Kataoka8d033052012-11-19 17:30:40 +09002813 }
2814
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002815 if (mCurFocusedWindow == windowToken) {
Yohei Yukawad0332832017-02-01 13:59:43 -08002816 if (DEBUG) {
2817 Slog.w(TAG, "Window already focused, ignoring focus gain of: " + client
2818 + " attribute=" + attribute + ", token = " + windowToken);
2819 }
Dianne Hackborn7663d802012-02-24 13:08:49 -08002820 if (attribute != null) {
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002821 return startInputUncheckedLocked(cs, inputContext, missingMethods,
Yohei Yukawa87ca8402017-02-07 00:13:14 -08002822 attribute, controlFlags, startInputReason);
Dianne Hackborn7663d802012-02-24 13:08:49 -08002823 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08002824 return new InputBindResult(
2825 InputBindResult.ResultCode.SUCCESS_REPORT_WINDOW_FOCUS_ONLY,
2826 null, null, null, -1, -1);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002827 }
2828 mCurFocusedWindow = windowToken;
Yohei Yukawa22a89232017-02-12 16:38:59 -08002829 mCurFocusedWindowSoftInputMode = softInputMode;
Yohei Yukawae39d4ed2015-11-19 03:38:49 -08002830 mCurFocusedWindowClient = cs;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002831
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -08002832 // Should we auto-show the IME even if the caller has not
2833 // specified what should be done with it?
2834 // We only do this automatically if the window can resize
2835 // to accommodate the IME (so what the user sees will give
2836 // them good context without input information being obscured
2837 // by the IME) or if running on a large screen where there
2838 // is more room for the target window + IME.
2839 final boolean doAutoShow =
2840 (softInputMode & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
2841 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
2842 || mRes.getConfiguration().isLayoutSizeAtLeast(
2843 Configuration.SCREENLAYOUT_SIZE_LARGE);
Dianne Hackborn7663d802012-02-24 13:08:49 -08002844 final boolean isTextEditor =
2845 (controlFlags&InputMethodManager.CONTROL_WINDOW_IS_TEXT_EDITOR) != 0;
2846
2847 // We want to start input before showing the IME, but after closing
2848 // it. We want to do this after closing it to help the IME disappear
2849 // more quickly (not get stuck behind it initializing itself for the
2850 // new focused input, even if its window wants to hide the IME).
2851 boolean didStart = false;
Yohei Yukawa0f3ad12015-04-06 16:48:24 -07002852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 switch (softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_STATE) {
2854 case WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED:
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -08002855 if (!isTextEditor || !doAutoShow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002856 if (WindowManager.LayoutParams.mayUseInputMethod(windowFlags)) {
2857 // There is no focus view, and this window will
2858 // be behind any soft input window, so hide the
2859 // soft input window if it is shown.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002860 if (DEBUG) Slog.v(TAG, "Unspecified window will hide input");
The Android Open Source Project4df24232009-03-05 14:34:35 -08002861 hideCurrentInputLocked(InputMethodManager.HIDE_NOT_ALWAYS, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 }
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -08002863 } else if (isTextEditor && doAutoShow && (softInputMode &
2864 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002865 // There is a focus view, and we are navigating forward
2866 // into the window, so show the input window for the user.
Dianne Hackborn7663d802012-02-24 13:08:49 -08002867 // We only do this automatically if the window can resize
2868 // to accommodate the IME (so what the user sees will give
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -08002869 // them good context without input information being obscured
2870 // by the IME) or if running on a large screen where there
2871 // is more room for the target window + IME.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002872 if (DEBUG) Slog.v(TAG, "Unspecified window will show input");
Dianne Hackborn7663d802012-02-24 13:08:49 -08002873 if (attribute != null) {
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002874 res = startInputUncheckedLocked(cs, inputContext,
Yohei Yukawa87ca8402017-02-07 00:13:14 -08002875 missingMethods, attribute, controlFlags, startInputReason);
Dianne Hackborn7663d802012-02-24 13:08:49 -08002876 didStart = true;
2877 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08002878 showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002879 }
2880 break;
2881 case WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED:
2882 // Do nothing.
2883 break;
2884 case WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN:
2885 if ((softInputMode &
2886 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002887 if (DEBUG) Slog.v(TAG, "Window asks to hide input going forward");
The Android Open Source Project4df24232009-03-05 14:34:35 -08002888 hideCurrentInputLocked(0, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002889 }
2890 break;
2891 case WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN:
Joe Onorato8a9b2202010-02-26 18:56:32 -08002892 if (DEBUG) Slog.v(TAG, "Window asks to hide input");
The Android Open Source Project4df24232009-03-05 14:34:35 -08002893 hideCurrentInputLocked(0, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002894 break;
2895 case WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE:
2896 if ((softInputMode &
2897 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002898 if (DEBUG) Slog.v(TAG, "Window asks to show input going forward");
Yohei Yukawacf68d522017-12-12 09:33:26 -08002899 if (InputMethodUtils.isSoftInputModeStateVisibleAllowed(
2900 unverifiedTargetSdkVersion, controlFlags)) {
2901 if (attribute != null) {
2902 res = startInputUncheckedLocked(cs, inputContext,
2903 missingMethods, attribute, controlFlags,
2904 startInputReason);
2905 didStart = true;
2906 }
2907 showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
2908 } else {
2909 Slog.e(TAG, "SOFT_INPUT_STATE_VISIBLE is ignored because"
2910 + " there is no focused view that also returns true from"
2911 + " View#onCheckIsTextEditor()");
Dianne Hackborn7663d802012-02-24 13:08:49 -08002912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 }
2914 break;
2915 case WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE:
Joe Onorato8a9b2202010-02-26 18:56:32 -08002916 if (DEBUG) Slog.v(TAG, "Window asks to always show input");
Yohei Yukawacf68d522017-12-12 09:33:26 -08002917 if (InputMethodUtils.isSoftInputModeStateVisibleAllowed(
2918 unverifiedTargetSdkVersion, controlFlags)) {
2919 if (attribute != null) {
2920 res = startInputUncheckedLocked(cs, inputContext, missingMethods,
2921 attribute, controlFlags, startInputReason);
2922 didStart = true;
2923 }
2924 showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
2925 } else {
2926 Slog.e(TAG, "SOFT_INPUT_STATE_ALWAYS_VISIBLE is ignored because"
2927 + " there is no focused view that also returns true from"
2928 + " View#onCheckIsTextEditor()");
Dianne Hackborn7663d802012-02-24 13:08:49 -08002929 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002930 break;
2931 }
Dianne Hackborn7663d802012-02-24 13:08:49 -08002932
Tarandeep Singh2f731c552018-02-05 13:55:06 -08002933 if (!didStart) {
2934 if (attribute != null) {
2935 if (!DebugFlags.FLAG_OPTIMIZE_START_INPUT.value()
2936 || (controlFlags
2937 & InputMethodManager.CONTROL_WINDOW_IS_TEXT_EDITOR) != 0) {
2938 res = startInputUncheckedLocked(cs, inputContext, missingMethods,
2939 attribute,
2940 controlFlags, startInputReason);
2941 } else {
2942 res = InputBindResult.NO_EDITOR;
2943 }
2944 } else {
2945 res = InputBindResult.NULL_EDITOR_INFO;
Tarandeep Singh75a92392018-01-12 14:58:59 -08002946 }
Dianne Hackborn7663d802012-02-24 13:08:49 -08002947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002948 }
2949 } finally {
2950 Binder.restoreCallingIdentity(ident);
2951 }
Dianne Hackborn7663d802012-02-24 13:08:49 -08002952
2953 return res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002954 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002955
Guliz Tuncay6908c152017-06-02 16:06:10 -07002956 private boolean canShowInputMethodPickerLocked(IInputMethodClient client) {
2957 final int uid = Binder.getCallingUid();
2958 if (UserHandle.getAppId(uid) == Process.SYSTEM_UID) {
2959 return true;
Tarandeep Singheb570612018-01-29 16:20:32 -08002960 } else if (mCurFocusedWindowClient != null && client != null
2961 && mCurFocusedWindowClient.client.asBinder() == client.asBinder()) {
Guliz Tuncay6908c152017-06-02 16:06:10 -07002962 return true;
2963 } else if (mCurIntent != null && InputMethodUtils.checkIfPackageBelongsToUid(
2964 mAppOpsManager,
2965 uid,
2966 mCurIntent.getComponent().getPackageName())) {
2967 return true;
2968 } else if (mContext.checkCallingPermission(
2969 android.Manifest.permission.WRITE_SECURE_SETTINGS)
2970 == PackageManager.PERMISSION_GRANTED) {
2971 return true;
2972 }
2973
2974 return false;
2975 }
2976
satok42c5a162011-05-26 16:46:14 +09002977 @Override
Seigo Nonaka14e13912015-05-06 21:04:13 -07002978 public void showInputMethodPickerFromClient(
2979 IInputMethodClient client, int auxiliarySubtypeMode) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002980 if (!calledFromValidUser()) {
2981 return;
2982 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002983 synchronized (mMethodMap) {
Guliz Tuncay6908c152017-06-02 16:06:10 -07002984 if(!canShowInputMethodPickerLocked(client)) {
satok47a44912010-10-06 16:03:58 +09002985 Slog.w(TAG, "Ignoring showInputMethodPickerFromClient of uid "
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002986 + Binder.getCallingUid() + ": " + client);
Guliz Tuncay6908c152017-06-02 16:06:10 -07002987 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002988 }
2989
satok440aab52010-11-25 09:43:11 +09002990 // Always call subtype picker, because subtype picker is a superset of input method
2991 // picker.
Seigo Nonaka14e13912015-05-06 21:04:13 -07002992 mHandler.sendMessage(mCaller.obtainMessageI(
2993 MSG_SHOW_IM_SUBTYPE_PICKER, auxiliarySubtypeMode));
satokab751aa2010-09-14 19:17:36 +09002994 }
2995 }
2996
Tarandeep Singheb570612018-01-29 16:20:32 -08002997 public boolean isInputMethodPickerShownForTest() {
2998 synchronized(mMethodMap) {
2999 if (mSwitchingDialog == null) {
3000 return false;
3001 }
3002 return mSwitchingDialog.isShowing();
3003 }
3004 }
3005
satok42c5a162011-05-26 16:46:14 +09003006 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003007 public void setInputMethod(IBinder token, String id) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003008 if (!calledFromValidUser()) {
3009 return;
3010 }
satok28203512010-11-24 11:06:49 +09003011 setInputMethodWithSubtypeId(token, id, NOT_A_SUBTYPE_ID);
3012 }
3013
satok42c5a162011-05-26 16:46:14 +09003014 @Override
satok28203512010-11-24 11:06:49 +09003015 public void setInputMethodAndSubtype(IBinder token, String id, InputMethodSubtype subtype) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003016 if (!calledFromValidUser()) {
3017 return;
3018 }
satok28203512010-11-24 11:06:49 +09003019 synchronized (mMethodMap) {
3020 if (subtype != null) {
Yohei Yukawa4e02bc62014-06-04 18:37:20 +09003021 setInputMethodWithSubtypeIdLocked(token, id,
3022 InputMethodUtils.getSubtypeIdFromHashCode(mMethodMap.get(id),
3023 subtype.hashCode()));
satok28203512010-11-24 11:06:49 +09003024 } else {
3025 setInputMethod(token, id);
3026 }
3027 }
satokab751aa2010-09-14 19:17:36 +09003028 }
3029
satok42c5a162011-05-26 16:46:14 +09003030 @Override
satokb416a712010-11-25 20:42:14 +09003031 public void showInputMethodAndSubtypeEnablerFromClient(
satok217f5482010-12-15 05:19:19 +09003032 IInputMethodClient client, String inputMethodId) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003033 if (!calledFromValidUser()) {
3034 return;
3035 }
satokb416a712010-11-25 20:42:14 +09003036 synchronized (mMethodMap) {
satok7fee71f2010-12-17 18:54:26 +09003037 executeOrSendMessage(mCurMethod, mCaller.obtainMessageO(
3038 MSG_SHOW_IM_SUBTYPE_ENABLER, inputMethodId));
satokb416a712010-11-25 20:42:14 +09003039 }
3040 }
3041
satok4fc87d62011-05-20 16:13:43 +09003042 @Override
Tarandeep Singh164cfba2018-02-28 14:17:43 -08003043 public boolean switchToPreviousInputMethod(IBinder token) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003044 if (!calledFromValidUser()) {
3045 return false;
3046 }
satok735cf382010-11-11 20:40:09 +09003047 synchronized (mMethodMap) {
satokc445bcd2011-01-25 18:57:24 +09003048 final Pair<String, String> lastIme = mSettings.getLastInputMethodAndSubtypeLocked();
satok4fc87d62011-05-20 16:13:43 +09003049 final InputMethodInfo lastImi;
satok208d5632011-05-20 22:13:38 +09003050 if (lastIme != null) {
satok4fc87d62011-05-20 16:13:43 +09003051 lastImi = mMethodMap.get(lastIme.first);
3052 } else {
3053 lastImi = null;
satok735cf382010-11-11 20:40:09 +09003054 }
satok4fc87d62011-05-20 16:13:43 +09003055 String targetLastImiId = null;
3056 int subtypeId = NOT_A_SUBTYPE_ID;
3057 if (lastIme != null && lastImi != null) {
3058 final boolean imiIdIsSame = lastImi.getId().equals(mCurMethodId);
Narayan Kamatha09b4d22016-04-15 18:32:45 +01003059 final int lastSubtypeHash = Integer.parseInt(lastIme.second);
satok4fc87d62011-05-20 16:13:43 +09003060 final int currentSubtypeHash = mCurrentSubtype == null ? NOT_A_SUBTYPE_ID
3061 : mCurrentSubtype.hashCode();
3062 // If the last IME is the same as the current IME and the last subtype is not
3063 // defined, there is no need to switch to the last IME.
3064 if (!imiIdIsSame || lastSubtypeHash != currentSubtypeHash) {
3065 targetLastImiId = lastIme.first;
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003066 subtypeId = InputMethodUtils.getSubtypeIdFromHashCode(lastImi, lastSubtypeHash);
satok4fc87d62011-05-20 16:13:43 +09003067 }
3068 }
3069
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003070 if (TextUtils.isEmpty(targetLastImiId)
3071 && !InputMethodUtils.canAddToLastInputMethod(mCurrentSubtype)) {
satok4fc87d62011-05-20 16:13:43 +09003072 // This is a safety net. If the currentSubtype can't be added to the history
3073 // and the framework couldn't find the last ime, we will make the last ime be
3074 // the most applicable enabled keyboard subtype of the system imes.
3075 final List<InputMethodInfo> enabled = mSettings.getEnabledInputMethodListLocked();
3076 if (enabled != null) {
3077 final int N = enabled.size();
3078 final String locale = mCurrentSubtype == null
3079 ? mRes.getConfiguration().locale.toString()
3080 : mCurrentSubtype.getLocale();
3081 for (int i = 0; i < N; ++i) {
3082 final InputMethodInfo imi = enabled.get(i);
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003083 if (imi.getSubtypeCount() > 0 && InputMethodUtils.isSystemIme(imi)) {
satok4fc87d62011-05-20 16:13:43 +09003084 InputMethodSubtype keyboardSubtype =
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003085 InputMethodUtils.findLastResortApplicableSubtypeLocked(mRes,
3086 InputMethodUtils.getSubtypes(imi),
3087 InputMethodUtils.SUBTYPE_MODE_KEYBOARD, locale, true);
satok4fc87d62011-05-20 16:13:43 +09003088 if (keyboardSubtype != null) {
3089 targetLastImiId = imi.getId();
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003090 subtypeId = InputMethodUtils.getSubtypeIdFromHashCode(
satok4fc87d62011-05-20 16:13:43 +09003091 imi, keyboardSubtype.hashCode());
3092 if(keyboardSubtype.getLocale().equals(locale)) {
3093 break;
3094 }
3095 }
3096 }
3097 }
3098 }
3099 }
3100
3101 if (!TextUtils.isEmpty(targetLastImiId)) {
3102 if (DEBUG) {
3103 Slog.d(TAG, "Switch to: " + lastImi.getId() + ", " + lastIme.second
3104 + ", from: " + mCurMethodId + ", " + subtypeId);
3105 }
Yohei Yukawa4e02bc62014-06-04 18:37:20 +09003106 setInputMethodWithSubtypeIdLocked(token, targetLastImiId, subtypeId);
satok4fc87d62011-05-20 16:13:43 +09003107 return true;
3108 } else {
3109 return false;
3110 }
satok735cf382010-11-11 20:40:09 +09003111 }
3112 }
3113
satoke7c6998e2011-06-03 17:57:59 +09003114 @Override
satok688bd472012-02-09 20:09:17 +09003115 public boolean switchToNextInputMethod(IBinder token, boolean onlyCurrentIme) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003116 if (!calledFromValidUser()) {
3117 return false;
3118 }
satok688bd472012-02-09 20:09:17 +09003119 synchronized (mMethodMap) {
Yohei Yukawaa0755742014-06-04 20:28:18 +09003120 if (!calledWithValidToken(token)) {
Yohei Yukawaa0755742014-06-04 20:28:18 +09003121 return false;
3122 }
Yohei Yukawa5a647b692014-05-22 12:49:00 +09003123 final ImeSubtypeListItem nextSubtype = mSwitchingController.getNextInputMethodLocked(
Yohei Yukawad39ae852016-04-10 20:28:40 -07003124 onlyCurrentIme, mMethodMap.get(mCurMethodId), mCurrentSubtype,
3125 true /* forward */);
satok688bd472012-02-09 20:09:17 +09003126 if (nextSubtype == null) {
3127 return false;
3128 }
Yohei Yukawa4e02bc62014-06-04 18:37:20 +09003129 setInputMethodWithSubtypeIdLocked(token, nextSubtype.mImi.getId(),
3130 nextSubtype.mSubtypeId);
satok688bd472012-02-09 20:09:17 +09003131 return true;
3132 }
3133 }
3134
3135 @Override
Satoshi Kataoka2b10b522013-08-21 20:39:12 +09003136 public boolean shouldOfferSwitchingToNextInputMethod(IBinder token) {
3137 if (!calledFromValidUser()) {
3138 return false;
3139 }
3140 synchronized (mMethodMap) {
Yohei Yukawaa0755742014-06-04 20:28:18 +09003141 if (!calledWithValidToken(token)) {
Yohei Yukawaa0755742014-06-04 20:28:18 +09003142 return false;
3143 }
Yohei Yukawa5a647b692014-05-22 12:49:00 +09003144 final ImeSubtypeListItem nextSubtype = mSwitchingController.getNextInputMethodLocked(
Yohei Yukawad39ae852016-04-10 20:28:40 -07003145 false /* onlyCurrentIme */, mMethodMap.get(mCurMethodId), mCurrentSubtype,
3146 true /* forward */);
Satoshi Kataoka2b10b522013-08-21 20:39:12 +09003147 if (nextSubtype == null) {
3148 return false;
3149 }
3150 return true;
3151 }
3152 }
3153
3154 @Override
satok68f1b782011-04-11 14:26:04 +09003155 public InputMethodSubtype getLastInputMethodSubtype() {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003156 if (!calledFromValidUser()) {
3157 return null;
3158 }
satok68f1b782011-04-11 14:26:04 +09003159 synchronized (mMethodMap) {
3160 final Pair<String, String> lastIme = mSettings.getLastInputMethodAndSubtypeLocked();
3161 // TODO: Handle the case of the last IME with no subtypes
3162 if (lastIme == null || TextUtils.isEmpty(lastIme.first)
3163 || TextUtils.isEmpty(lastIme.second)) return null;
3164 final InputMethodInfo lastImi = mMethodMap.get(lastIme.first);
3165 if (lastImi == null) return null;
3166 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01003167 final int lastSubtypeHash = Integer.parseInt(lastIme.second);
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003168 final int lastSubtypeId =
3169 InputMethodUtils.getSubtypeIdFromHashCode(lastImi, lastSubtypeHash);
satok0e7d7d62011-07-05 13:28:06 +09003170 if (lastSubtypeId < 0 || lastSubtypeId >= lastImi.getSubtypeCount()) {
3171 return null;
3172 }
3173 return lastImi.getSubtypeAt(lastSubtypeId);
satok68f1b782011-04-11 14:26:04 +09003174 } catch (NumberFormatException e) {
3175 return null;
3176 }
3177 }
3178 }
3179
satoke7c6998e2011-06-03 17:57:59 +09003180 @Override
satokee5e77c2011-09-02 18:50:15 +09003181 public void setAdditionalInputMethodSubtypes(String imiId, InputMethodSubtype[] subtypes) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003182 if (!calledFromValidUser()) {
3183 return;
3184 }
satok91e88122011-07-18 11:11:42 +09003185 // By this IPC call, only a process which shares the same uid with the IME can add
3186 // additional input method subtypes to the IME.
Yohei Yukawa70f5c482016-01-04 19:42:36 -08003187 if (TextUtils.isEmpty(imiId) || subtypes == null) return;
satoke7c6998e2011-06-03 17:57:59 +09003188 synchronized (mMethodMap) {
Yohei Yukawa79247822017-01-23 15:26:15 -08003189 if (!mSystemReady) {
3190 return;
3191 }
satok91e88122011-07-18 11:11:42 +09003192 final InputMethodInfo imi = mMethodMap.get(imiId);
satokee5e77c2011-09-02 18:50:15 +09003193 if (imi == null) return;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003194 final String[] packageInfos;
3195 try {
3196 packageInfos = mIPackageManager.getPackagesForUid(Binder.getCallingUid());
3197 } catch (RemoteException e) {
3198 Slog.e(TAG, "Failed to get package infos");
3199 return;
3200 }
satok91e88122011-07-18 11:11:42 +09003201 if (packageInfos != null) {
3202 final int packageNum = packageInfos.length;
3203 for (int i = 0; i < packageNum; ++i) {
3204 if (packageInfos[i].equals(imi.getPackageName())) {
3205 mFileManager.addInputMethodSubtypes(imi, subtypes);
satokc5933802011-08-31 21:26:04 +09003206 final long ident = Binder.clearCallingIdentity();
3207 try {
Yohei Yukawa94e33302016-02-12 19:37:03 -08003208 buildInputMethodListLocked(false /* resetDefaultEnabledIme */);
satokc5933802011-08-31 21:26:04 +09003209 } finally {
3210 Binder.restoreCallingIdentity(ident);
3211 }
satokee5e77c2011-09-02 18:50:15 +09003212 return;
satok91e88122011-07-18 11:11:42 +09003213 }
3214 }
3215 }
satoke7c6998e2011-06-03 17:57:59 +09003216 }
satokee5e77c2011-09-02 18:50:15 +09003217 return;
satoke7c6998e2011-06-03 17:57:59 +09003218 }
3219
Satoshi Kataoka658c7b82013-10-10 17:03:51 +09003220 @Override
3221 public int getInputMethodWindowVisibleHeight() {
Seigo Nonaka7309b122015-08-17 18:34:13 -07003222 return mWindowManagerInternal.getInputMethodWindowVisibleHeight();
Satoshi Kataoka658c7b82013-10-10 17:03:51 +09003223 }
3224
Satoshi Kataokad7443c82013-10-15 17:45:43 +09003225 @Override
Yohei Yukawa833bdce2016-05-15 20:05:56 -07003226 public void clearLastInputMethodWindowForTransition(IBinder token) {
3227 if (!calledFromValidUser()) {
3228 return;
3229 }
Yohei Yukawafa49c002017-01-31 19:15:00 -08003230 synchronized (mMethodMap) {
3231 if (!calledWithValidToken(token)) {
Yohei Yukawafa49c002017-01-31 19:15:00 -08003232 return;
Yohei Yukawa833bdce2016-05-15 20:05:56 -07003233 }
Yohei Yukawa833bdce2016-05-15 20:05:56 -07003234 }
Yohei Yukawafa49c002017-01-31 19:15:00 -08003235 mWindowManagerInternal.clearLastInputMethodWindowForTransition();
Yohei Yukawa833bdce2016-05-15 20:05:56 -07003236 }
3237
3238 @Override
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003239 public void notifyUserAction(int sequenceNumber) {
Satoshi Kataokad7443c82013-10-15 17:45:43 +09003240 if (DEBUG) {
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003241 Slog.d(TAG, "Got the notification of a user action. sequenceNumber:" + sequenceNumber);
Satoshi Kataokad7443c82013-10-15 17:45:43 +09003242 }
Yohei Yukawa5a647b692014-05-22 12:49:00 +09003243 synchronized (mMethodMap) {
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003244 if (mCurUserActionNotificationSequenceNumber != sequenceNumber) {
3245 if (DEBUG) {
3246 Slog.d(TAG, "Ignoring the user action notification due to the sequence number "
3247 + "mismatch. expected:" + mCurUserActionNotificationSequenceNumber
3248 + " actual: " + sequenceNumber);
3249 }
3250 return;
3251 }
Yohei Yukawa5a647b692014-05-22 12:49:00 +09003252 final InputMethodInfo imi = mMethodMap.get(mCurMethodId);
3253 if (imi != null) {
Yohei Yukawa02970512014-06-05 16:16:18 +09003254 mSwitchingController.onUserActionLocked(imi, mCurrentSubtype);
Yohei Yukawa5a647b692014-05-22 12:49:00 +09003255 }
Satoshi Kataokad7443c82013-10-15 17:45:43 +09003256 }
3257 }
3258
satok28203512010-11-24 11:06:49 +09003259 private void setInputMethodWithSubtypeId(IBinder token, String id, int subtypeId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003260 synchronized (mMethodMap) {
Yohei Yukawa4e02bc62014-06-04 18:37:20 +09003261 setInputMethodWithSubtypeIdLocked(token, id, subtypeId);
3262 }
3263 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264
Yohei Yukawa4e02bc62014-06-04 18:37:20 +09003265 private void setInputMethodWithSubtypeIdLocked(IBinder token, String id, int subtypeId) {
3266 if (token == null) {
3267 if (mContext.checkCallingOrSelfPermission(
3268 android.Manifest.permission.WRITE_SECURE_SETTINGS)
3269 != PackageManager.PERMISSION_GRANTED) {
3270 throw new SecurityException(
3271 "Using null token requires permission "
3272 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003273 }
Yohei Yukawa4e02bc62014-06-04 18:37:20 +09003274 } else if (mCurToken != token) {
3275 Slog.w(TAG, "Ignoring setInputMethod of uid " + Binder.getCallingUid()
3276 + " token: " + token);
3277 return;
3278 }
3279
3280 final long ident = Binder.clearCallingIdentity();
3281 try {
3282 setInputMethodLocked(id, subtypeId);
3283 } finally {
3284 Binder.restoreCallingIdentity(ident);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285 }
3286 }
3287
satok42c5a162011-05-26 16:46:14 +09003288 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 public void hideMySoftInput(IBinder token, int flags) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003290 if (!calledFromValidUser()) {
3291 return;
3292 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003293 synchronized (mMethodMap) {
Yohei Yukawa22c97be2014-06-04 19:43:36 +09003294 if (!calledWithValidToken(token)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003295 return;
3296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003297 long ident = Binder.clearCallingIdentity();
3298 try {
The Android Open Source Project4df24232009-03-05 14:34:35 -08003299 hideCurrentInputLocked(flags, null);
3300 } finally {
3301 Binder.restoreCallingIdentity(ident);
3302 }
3303 }
3304 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003305
satok42c5a162011-05-26 16:46:14 +09003306 @Override
The Android Open Source Project4df24232009-03-05 14:34:35 -08003307 public void showMySoftInput(IBinder token, int flags) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003308 if (!calledFromValidUser()) {
3309 return;
3310 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08003311 synchronized (mMethodMap) {
Yohei Yukawa22c97be2014-06-04 19:43:36 +09003312 if (!calledWithValidToken(token)) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08003313 return;
3314 }
3315 long ident = Binder.clearCallingIdentity();
3316 try {
3317 showCurrentInputLocked(flags, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003318 } finally {
3319 Binder.restoreCallingIdentity(ident);
3320 }
3321 }
3322 }
3323
3324 void setEnabledSessionInMainThread(SessionState session) {
3325 if (mEnabledSession != session) {
Yohei Yukawa9d91b432014-05-19 16:03:24 +09003326 if (mEnabledSession != null && mEnabledSession.session != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003327 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003328 if (DEBUG) Slog.v(TAG, "Disabling: " + mEnabledSession);
Yohei Yukawa9d91b432014-05-19 16:03:24 +09003329 mEnabledSession.method.setSessionEnabled(mEnabledSession.session, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003330 } catch (RemoteException e) {
3331 }
3332 }
3333 mEnabledSession = session;
Yohei Yukawa9d91b432014-05-19 16:03:24 +09003334 if (mEnabledSession != null && mEnabledSession.session != null) {
3335 try {
3336 if (DEBUG) Slog.v(TAG, "Enabling: " + mEnabledSession);
3337 mEnabledSession.method.setSessionEnabled(mEnabledSession.session, true);
3338 } catch (RemoteException e) {
3339 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003340 }
3341 }
3342 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003343
Yohei Yukawa930328c2017-10-18 20:19:53 -07003344 @MainThread
satok42c5a162011-05-26 16:46:14 +09003345 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003346 public boolean handleMessage(Message msg) {
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003347 SomeArgs args;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003348 switch (msg.what) {
satokab751aa2010-09-14 19:17:36 +09003349 case MSG_SHOW_IM_SUBTYPE_PICKER:
Seigo Nonaka14e13912015-05-06 21:04:13 -07003350 final boolean showAuxSubtypes;
3351 switch (msg.arg1) {
3352 case InputMethodManager.SHOW_IM_PICKER_MODE_AUTO:
3353 // This is undocumented so far, but IMM#showInputMethodPicker() has been
3354 // implemented so that auxiliary subtypes will be excluded when the soft
3355 // keyboard is invisible.
3356 showAuxSubtypes = mInputShown;
3357 break;
3358 case InputMethodManager.SHOW_IM_PICKER_MODE_INCLUDE_AUXILIARY_SUBTYPES:
3359 showAuxSubtypes = true;
3360 break;
3361 case InputMethodManager.SHOW_IM_PICKER_MODE_EXCLUDE_AUXILIARY_SUBTYPES:
3362 showAuxSubtypes = false;
3363 break;
3364 default:
3365 Slog.e(TAG, "Unknown subtype picker mode = " + msg.arg1);
3366 return false;
3367 }
3368 showInputMethodMenu(showAuxSubtypes);
satokab751aa2010-09-14 19:17:36 +09003369 return true;
3370
satok47a44912010-10-06 16:03:58 +09003371 case MSG_SHOW_IM_SUBTYPE_ENABLER:
Yohei Yukawa41f34272015-12-14 15:41:52 -08003372 showInputMethodAndSubtypeEnabler((String)msg.obj);
satok217f5482010-12-15 05:19:19 +09003373 return true;
3374
3375 case MSG_SHOW_IM_CONFIG:
3376 showConfigureInputMethods();
satok47a44912010-10-06 16:03:58 +09003377 return true;
3378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003379 // ---------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 case MSG_UNBIND_INPUT:
3382 try {
3383 ((IInputMethod)msg.obj).unbindInput();
3384 } catch (RemoteException e) {
3385 // There is nothing interesting about the method dying.
3386 }
3387 return true;
3388 case MSG_BIND_INPUT:
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003389 args = (SomeArgs)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003390 try {
3391 ((IInputMethod)args.arg1).bindInput((InputBinding)args.arg2);
3392 } catch (RemoteException e) {
3393 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003394 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003395 return true;
3396 case MSG_SHOW_SOFT_INPUT:
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003397 args = (SomeArgs)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398 try {
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07003399 if (DEBUG) Slog.v(TAG, "Calling " + args.arg1 + ".showSoftInput("
Craig Mautner6efb4c72013-03-13 10:17:41 -07003400 + msg.arg1 + ", " + args.arg2 + ")");
Craig Mautnerca0ac712013-03-14 09:43:02 -07003401 ((IInputMethod)args.arg1).showSoftInput(msg.arg1, (ResultReceiver)args.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003402 } catch (RemoteException e) {
3403 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003404 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003405 return true;
3406 case MSG_HIDE_SOFT_INPUT:
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003407 args = (SomeArgs)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003408 try {
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07003409 if (DEBUG) Slog.v(TAG, "Calling " + args.arg1 + ".hideSoftInput(0, "
Craig Mautner6efb4c72013-03-13 10:17:41 -07003410 + args.arg2 + ")");
Craig Mautnerca0ac712013-03-14 09:43:02 -07003411 ((IInputMethod)args.arg1).hideSoftInput(0, (ResultReceiver)args.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003412 } catch (RemoteException e) {
3413 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003414 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003415 return true;
Jorim Jaggi3c5d0f12016-05-24 19:04:30 -07003416 case MSG_HIDE_CURRENT_INPUT_METHOD:
3417 synchronized (mMethodMap) {
3418 hideCurrentInputLocked(0, null);
3419 }
3420 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003421 case MSG_ATTACH_TOKEN:
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003422 args = (SomeArgs)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003423 try {
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07003424 if (DEBUG) Slog.v(TAG, "Sending attach of token: " + args.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003425 ((IInputMethod)args.arg1).attachToken((IBinder)args.arg2);
3426 } catch (RemoteException e) {
3427 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003428 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003429 return true;
Jeff Brownc28867a2013-03-26 15:42:39 -07003430 case MSG_CREATE_SESSION: {
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003431 args = (SomeArgs)msg.obj;
Jeff Brown1951ce82013-04-04 22:45:12 -07003432 IInputMethod method = (IInputMethod)args.arg1;
Jeff Brownc28867a2013-03-26 15:42:39 -07003433 InputChannel channel = (InputChannel)args.arg2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003434 try {
Jeff Brown1951ce82013-04-04 22:45:12 -07003435 method.createSession(channel, (IInputSessionCallback)args.arg3);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003436 } catch (RemoteException e) {
Jeff Brownc28867a2013-03-26 15:42:39 -07003437 } finally {
Jeff Brown1951ce82013-04-04 22:45:12 -07003438 // Dispose the channel if the input method is not local to this process
3439 // because the remote proxy will get its own copy when unparceled.
3440 if (channel != null && Binder.isProxy(method)) {
Jeff Brownc28867a2013-03-26 15:42:39 -07003441 channel.dispose();
3442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003444 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003445 return true;
Jeff Brownc28867a2013-03-26 15:42:39 -07003446 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003447 // ---------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003448
Yohei Yukawa19a80a12016-03-14 22:57:37 -07003449 case MSG_START_INPUT: {
Yohei Yukawaf7526b52017-02-11 20:57:10 -08003450 final int missingMethods = msg.arg1;
3451 final boolean restarting = msg.arg2 != 0;
Yohei Yukawa19a80a12016-03-14 22:57:37 -07003452 args = (SomeArgs) msg.obj;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08003453 final IBinder startInputToken = (IBinder) args.arg1;
3454 final SessionState session = (SessionState) args.arg2;
3455 final IInputContext inputContext = (IInputContext) args.arg3;
3456 final EditorInfo editorInfo = (EditorInfo) args.arg4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003457 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003458 setEnabledSessionInMainThread(session);
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08003459 session.method.startInput(startInputToken, inputContext, missingMethods,
3460 editorInfo, restarting);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003461 } catch (RemoteException e) {
3462 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003463 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003464 return true;
Yohei Yukawa19a80a12016-03-14 22:57:37 -07003465 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003467 // ---------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003468
Yohei Yukawa33e81792015-11-17 21:14:42 -08003469 case MSG_UNBIND_CLIENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003470 try {
Yohei Yukawa33e81792015-11-17 21:14:42 -08003471 ((IInputMethodClient)msg.obj).onUnbindMethod(msg.arg1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003472 } catch (RemoteException e) {
3473 // There is nothing interesting about the last client dying.
3474 }
3475 return true;
Yohei Yukawa33e81792015-11-17 21:14:42 -08003476 case MSG_BIND_CLIENT: {
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003477 args = (SomeArgs)msg.obj;
Jeff Brown1951ce82013-04-04 22:45:12 -07003478 IInputMethodClient client = (IInputMethodClient)args.arg1;
3479 InputBindResult res = (InputBindResult)args.arg2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003480 try {
Jeff Brown1951ce82013-04-04 22:45:12 -07003481 client.onBindMethod(res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003482 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003483 Slog.w(TAG, "Client died receiving input method " + args.arg2);
Jeff Brown1951ce82013-04-04 22:45:12 -07003484 } finally {
3485 // Dispose the channel if the input method is not local to this process
3486 // because the remote proxy will get its own copy when unparceled.
3487 if (res.channel != null && Binder.isProxy(client)) {
3488 res.channel.dispose();
3489 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003490 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003491 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003492 return true;
Jeff Brown1951ce82013-04-04 22:45:12 -07003493 }
Dianne Hackborna6e41342012-05-22 16:30:34 -07003494 case MSG_SET_ACTIVE:
3495 try {
Yohei Yukawa2bc66172017-02-08 11:13:25 -08003496 ((ClientState)msg.obj).client.setActive(msg.arg1 != 0, msg.arg2 != 0);
Dianne Hackborna6e41342012-05-22 16:30:34 -07003497 } catch (RemoteException e) {
3498 Slog.w(TAG, "Got RemoteException sending setActive(false) notification to pid "
3499 + ((ClientState)msg.obj).pid + " uid "
3500 + ((ClientState)msg.obj).uid);
3501 }
3502 return true;
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07003503 case MSG_SET_INTERACTIVE:
3504 handleSetInteractive(msg.arg1 != 0);
3505 return true;
Tarandeep Singh89a6c482017-11-21 14:26:11 -08003506 case MSG_START_VR_INPUT:
3507 startVrInputMethodNoCheck((ComponentName) msg.obj);
3508 return true;
Yohei Yukawaae61f712015-12-09 13:00:10 -08003509 case MSG_SWITCH_IME:
3510 handleSwitchInputMethod(msg.arg1 != 0);
3511 return true;
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003512 case MSG_SET_USER_ACTION_NOTIFICATION_SEQUENCE_NUMBER: {
3513 final int sequenceNumber = msg.arg1;
Yohei Yukawa080fa342014-08-31 16:10:05 -07003514 final ClientState clientState = (ClientState)msg.obj;
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003515 try {
Yohei Yukawa080fa342014-08-31 16:10:05 -07003516 clientState.client.setUserActionNotificationSequenceNumber(sequenceNumber);
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003517 } catch (RemoteException e) {
3518 Slog.w(TAG, "Got RemoteException sending "
3519 + "setUserActionNotificationSequenceNumber("
3520 + sequenceNumber + ") notification to pid "
Yohei Yukawa080fa342014-08-31 16:10:05 -07003521 + clientState.pid + " uid "
3522 + clientState.uid);
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003523 }
3524 return true;
3525 }
Yohei Yukawa2bc66172017-02-08 11:13:25 -08003526 case MSG_REPORT_FULLSCREEN_MODE: {
3527 final boolean fullscreen = msg.arg1 != 0;
3528 final ClientState clientState = (ClientState)msg.obj;
3529 try {
3530 clientState.client.reportFullscreenMode(fullscreen);
3531 } catch (RemoteException e) {
3532 Slog.w(TAG, "Got RemoteException sending "
3533 + "reportFullscreen(" + fullscreen + ") notification to pid="
3534 + clientState.pid + " uid=" + clientState.uid);
3535 }
3536 return true;
3537 }
satok01038492012-04-09 21:08:27 +09003538
3539 // --------------------------------------------------------------
3540 case MSG_HARD_KEYBOARD_SWITCH_CHANGED:
Michael Wright7b5a96b2014-08-09 19:28:42 -07003541 mHardKeyboardListener.handleHardKeyboardStatusChange(msg.arg1 == 1);
satok01038492012-04-09 21:08:27 +09003542 return true;
Fyodor Kupolov7877b8a2016-06-29 14:39:19 -07003543 case MSG_SYSTEM_UNLOCK_USER:
3544 final int userId = msg.arg1;
3545 onUnlockUser(userId);
3546 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003547 }
3548 return false;
3549 }
3550
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07003551 private void handleSetInteractive(final boolean interactive) {
3552 synchronized (mMethodMap) {
3553 mIsInteractive = interactive;
3554 updateSystemUiLocked(mCurToken, interactive ? mImeWindowVis : 0, mBackDisposition);
3555
3556 // Inform the current client of the change in active status
3557 if (mCurClient != null && mCurClient.client != null) {
Yohei Yukawa2bc66172017-02-08 11:13:25 -08003558 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIIO(
3559 MSG_SET_ACTIVE, mIsInteractive ? 1 : 0, mInFullscreenMode ? 1 : 0,
3560 mCurClient));
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07003561 }
3562 }
3563 }
3564
Yohei Yukawaae61f712015-12-09 13:00:10 -08003565 private void handleSwitchInputMethod(final boolean forwardDirection) {
3566 synchronized (mMethodMap) {
Yohei Yukawaae61f712015-12-09 13:00:10 -08003567 final ImeSubtypeListItem nextSubtype = mSwitchingController.getNextInputMethodLocked(
Yohei Yukawad39ae852016-04-10 20:28:40 -07003568 false, mMethodMap.get(mCurMethodId), mCurrentSubtype, forwardDirection);
Yohei Yukawaae61f712015-12-09 13:00:10 -08003569 if (nextSubtype == null) {
3570 return;
3571 }
3572 setInputMethodLocked(nextSubtype.mImi.getId(), nextSubtype.mSubtypeId);
Yohei Yukawaebda7d72016-04-02 17:39:23 -07003573 final InputMethodInfo newInputMethodInfo = mMethodMap.get(mCurMethodId);
3574 if (newInputMethodInfo == null) {
3575 return;
3576 }
3577 final CharSequence toastText = InputMethodUtils.getImeAndSubtypeDisplayName(mContext,
3578 newInputMethodInfo, mCurrentSubtype);
3579 if (!TextUtils.isEmpty(toastText)) {
Yohei Yukawab2f901a2016-04-12 01:19:31 -07003580 if (mSubtypeSwitchedByShortCutToast == null) {
3581 mSubtypeSwitchedByShortCutToast = Toast.makeText(mContext, toastText,
3582 Toast.LENGTH_SHORT);
3583 } else {
3584 mSubtypeSwitchedByShortCutToast.setText(toastText);
3585 }
Yohei Yukawaebda7d72016-04-02 17:39:23 -07003586 mSubtypeSwitchedByShortCutToast.show();
3587 }
Yohei Yukawaae61f712015-12-09 13:00:10 -08003588 }
3589 }
3590
satokdc9ddae2011-10-06 12:22:36 +09003591 private boolean chooseNewDefaultIMELocked() {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003592 final InputMethodInfo imi = InputMethodUtils.getMostApplicableDefaultIME(
3593 mSettings.getEnabledInputMethodListLocked());
satokdc9ddae2011-10-06 12:22:36 +09003594 if (imi != null) {
satok03eb319a2010-11-11 18:17:42 +09003595 if (DEBUG) {
3596 Slog.d(TAG, "New default IME was selected: " + imi.getId());
3597 }
satok723a27e2010-11-11 14:58:11 +09003598 resetSelectedInputMethodAndSubtypeLocked(imi.getId());
Brandon Ballinger6da35a02009-10-21 00:38:13 -07003599 return true;
3600 }
3601
3602 return false;
3603 }
3604
Yohei Yukawaf80087c2018-05-21 09:47:53 -07003605 @PackageManager.ResolveInfoFlags
3606 private int getComponentMatchingFlags(@PackageManager.ResolveInfoFlags int baseFlags) {
3607 synchronized (mMethodMap) {
3608 if (mBindInstantServiceAllowed) {
3609 baseFlags |= PackageManager.MATCH_INSTANT;
3610 }
3611 return baseFlags;
3612 }
3613 }
3614
Andreas Gampea36dc622018-02-05 17:19:22 -08003615 @GuardedBy("mMethodMap")
Yohei Yukawa94e33302016-02-12 19:37:03 -08003616 void buildInputMethodListLocked(boolean resetDefaultEnabledIme) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003617 if (DEBUG) {
Satoshi Kataokaf1367b72013-01-25 17:20:12 +09003618 Slog.d(TAG, "--- re-buildInputMethodList reset = " + resetDefaultEnabledIme
Seigo Nonakae27dc2b2015-08-14 18:21:27 -07003619 + " \n ------ caller=" + Debug.getCallers(10));
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003620 }
Yohei Yukawa79247822017-01-23 15:26:15 -08003621 if (!mSystemReady) {
3622 Slog.e(TAG, "buildInputMethodListLocked is not allowed until system is ready");
3623 return;
3624 }
Yohei Yukawa94e33302016-02-12 19:37:03 -08003625 mMethodList.clear();
3626 mMethodMap.clear();
Yohei Yukawae0733062017-02-09 22:49:35 -08003627 mMethodMapUpdateCount++;
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08003628 mMyPackageMonitor.clearKnownImePackageNamesLocked();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003629
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003630 // Use for queryIntentServicesAsUser
3631 final PackageManager pm = mContext.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003632
Yohei Yukawaed4952a2016-02-17 07:57:25 -08003633 // Note: We do not specify PackageManager.MATCH_ENCRYPTION_* flags here because the default
3634 // behavior of PackageManager is exactly what we want. It by default picks up appropriate
3635 // services depending on the unlock state for the specified user.
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003636 final List<ResolveInfo> services = pm.queryIntentServicesAsUser(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003637 new Intent(InputMethod.SERVICE_INTERFACE),
Yohei Yukawaf80087c2018-05-21 09:47:53 -07003638 getComponentMatchingFlags(PackageManager.GET_META_DATA
3639 | PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS),
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08003640 mSettings.getCurrentUserId());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003641
Yohei Yukawaddad4b92017-02-02 01:46:13 -08003642 final HashMap<String, List<InputMethodSubtype>> additionalSubtypeMap =
satoke7c6998e2011-06-03 17:57:59 +09003643 mFileManager.getAllAdditionalInputMethodSubtypes();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003644 for (int i = 0; i < services.size(); ++i) {
3645 ResolveInfo ri = services.get(i);
3646 ServiceInfo si = ri.serviceInfo;
Yohei Yukawaddad4b92017-02-02 01:46:13 -08003647 final String imeId = InputMethodInfo.computeId(ri);
3648 if (!android.Manifest.permission.BIND_INPUT_METHOD.equals(si.permission)) {
3649 Slog.w(TAG, "Skipping input method " + imeId
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003650 + ": it does not require the permission "
3651 + android.Manifest.permission.BIND_INPUT_METHOD);
3652 continue;
3653 }
3654
Yohei Yukawaddad4b92017-02-02 01:46:13 -08003655 if (DEBUG) Slog.d(TAG, "Checking " + imeId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003656
Yohei Yukawaddad4b92017-02-02 01:46:13 -08003657 final List<InputMethodSubtype> additionalSubtypes = additionalSubtypeMap.get(imeId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658 try {
satoke7c6998e2011-06-03 17:57:59 +09003659 InputMethodInfo p = new InputMethodInfo(mContext, ri, additionalSubtypes);
Yohei Yukawa94e33302016-02-12 19:37:03 -08003660 mMethodList.add(p);
Amith Yamasanie861ec12010-03-24 21:39:27 -07003661 final String id = p.getId();
Yohei Yukawa94e33302016-02-12 19:37:03 -08003662 mMethodMap.put(id, p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003663
3664 if (DEBUG) {
Satoshi Kataokaf1367b72013-01-25 17:20:12 +09003665 Slog.d(TAG, "Found an input method " + p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003666 }
Tadashi G. Takaoka3c23d5b2016-09-16 11:41:07 +09003667 } catch (Exception e) {
Yohei Yukawaddad4b92017-02-02 01:46:13 -08003668 Slog.wtf(TAG, "Unable to load input method " + imeId, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003669 }
3670 }
Brandon Ballinger6da35a02009-10-21 00:38:13 -07003671
Yohei Yukawac4e44912017-02-09 19:30:22 -08003672 // Construct the set of possible IME packages for onPackageChanged() to avoid false
3673 // negatives when the package state remains to be the same but only the component state is
3674 // changed.
3675 {
3676 // Here we intentionally use PackageManager.MATCH_DISABLED_COMPONENTS since the purpose
3677 // of this query is to avoid false negatives. PackageManager.MATCH_ALL could be more
3678 // conservative, but it seems we cannot use it for now (Issue 35176630).
3679 final List<ResolveInfo> allInputMethodServices = pm.queryIntentServicesAsUser(
3680 new Intent(InputMethod.SERVICE_INTERFACE),
Yohei Yukawaf80087c2018-05-21 09:47:53 -07003681 getComponentMatchingFlags(PackageManager.MATCH_DISABLED_COMPONENTS),
3682 mSettings.getCurrentUserId());
Yohei Yukawac4e44912017-02-09 19:30:22 -08003683 final int N = allInputMethodServices.size();
3684 for (int i = 0; i < N; ++i) {
3685 final ServiceInfo si = allInputMethodServices.get(i).serviceInfo;
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08003686 if (android.Manifest.permission.BIND_INPUT_METHOD.equals(si.permission)) {
3687 mMyPackageMonitor.addKnownImePackageNameLocked(si.packageName);
Yohei Yukawac4e44912017-02-09 19:30:22 -08003688 }
Yohei Yukawac4e44912017-02-09 19:30:22 -08003689 }
3690 }
3691
Yohei Yukawa9c372192018-03-20 22:54:56 -07003692 boolean reenableMinimumNonAuxSystemImes = false;
Yohei Yukawa859df052016-02-17 07:56:46 -08003693 // TODO: The following code should find better place to live.
3694 if (!resetDefaultEnabledIme) {
3695 boolean enabledImeFound = false;
Yohei Yukawa9c372192018-03-20 22:54:56 -07003696 boolean enabledNonAuxImeFound = false;
Yohei Yukawa859df052016-02-17 07:56:46 -08003697 final List<InputMethodInfo> enabledImes = mSettings.getEnabledInputMethodListLocked();
3698 final int N = enabledImes.size();
3699 for (int i = 0; i < N; ++i) {
3700 final InputMethodInfo imi = enabledImes.get(i);
3701 if (mMethodList.contains(imi)) {
3702 enabledImeFound = true;
Yohei Yukawa9c372192018-03-20 22:54:56 -07003703 if (!imi.isAuxiliaryIme()) {
3704 enabledNonAuxImeFound = true;
3705 break;
3706 }
Yohei Yukawa859df052016-02-17 07:56:46 -08003707 }
3708 }
3709 if (!enabledImeFound) {
Yohei Yukawad0332832017-02-01 13:59:43 -08003710 if (DEBUG) {
3711 Slog.i(TAG, "All the enabled IMEs are gone. Reset default enabled IMEs.");
3712 }
Yohei Yukawa859df052016-02-17 07:56:46 -08003713 resetDefaultEnabledIme = true;
3714 resetSelectedInputMethodAndSubtypeLocked("");
Yohei Yukawa9c372192018-03-20 22:54:56 -07003715 } else if (!enabledNonAuxImeFound) {
3716 if (DEBUG) {
3717 Slog.i(TAG, "All the enabled non-Aux IMEs are gone. Do partial reset.");
3718 }
3719 reenableMinimumNonAuxSystemImes = true;
Yohei Yukawa859df052016-02-17 07:56:46 -08003720 }
3721 }
3722
Yohei Yukawa9c372192018-03-20 22:54:56 -07003723 if (resetDefaultEnabledIme || reenableMinimumNonAuxSystemImes) {
Satoshi Kataokaf1367b72013-01-25 17:20:12 +09003724 final ArrayList<InputMethodInfo> defaultEnabledIme =
Yohei Yukawa9c372192018-03-20 22:54:56 -07003725 InputMethodUtils.getDefaultEnabledImes(mContext, mMethodList,
3726 reenableMinimumNonAuxSystemImes);
Yohei Yukawa68645a62016-02-17 07:54:20 -08003727 final int N = defaultEnabledIme.size();
3728 for (int i = 0; i < N; ++i) {
Satoshi Kataokaf1367b72013-01-25 17:20:12 +09003729 final InputMethodInfo imi = defaultEnabledIme.get(i);
3730 if (DEBUG) {
3731 Slog.d(TAG, "--- enable ime = " + imi);
3732 }
3733 setInputMethodEnabledLocked(imi.getId(), true);
3734 }
3735 }
3736
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003737 final String defaultImiId = mSettings.getSelectedInputMethod();
satok0a1bcf42012-05-16 19:26:31 +09003738 if (!TextUtils.isEmpty(defaultImiId)) {
Yohei Yukawa94e33302016-02-12 19:37:03 -08003739 if (!mMethodMap.containsKey(defaultImiId)) {
satok0a1bcf42012-05-16 19:26:31 +09003740 Slog.w(TAG, "Default IME is uninstalled. Choose new default IME.");
3741 if (chooseNewDefaultIMELocked()) {
Michael Wright7b5a96b2014-08-09 19:28:42 -07003742 updateInputMethodsFromSettingsLocked(true);
satok0a1bcf42012-05-16 19:26:31 +09003743 }
3744 } else {
3745 // Double check that the default IME is certainly enabled.
3746 setInputMethodEnabledLocked(defaultImiId, true);
Brandon Ballinger6da35a02009-10-21 00:38:13 -07003747 }
3748 }
Yohei Yukawa3d46bab2014-05-30 18:10:18 +09003749 // Here is not the perfect place to reset the switching controller. Ideally
3750 // mSwitchingController and mSettings should be able to share the same state.
3751 // TODO: Make sure that mSwitchingController and mSettings are sharing the
3752 // the same enabled IMEs list.
Yohei Yukawac834a252014-05-21 22:42:32 +09003753 mSwitchingController.resetCircularListLocked(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003754 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756 // ----------------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003757
satok217f5482010-12-15 05:19:19 +09003758 private void showInputMethodAndSubtypeEnabler(String inputMethodId) {
Tadashi G. Takaokaf49688f2011-01-20 17:56:13 +09003759 Intent intent = new Intent(Settings.ACTION_INPUT_METHOD_SUBTYPE_SETTINGS);
satok47a44912010-10-06 16:03:58 +09003760 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
satok86417ea2010-10-27 14:11:03 +09003761 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
3762 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
satok7fee71f2010-12-17 18:54:26 +09003763 if (!TextUtils.isEmpty(inputMethodId)) {
Tadashi G. Takaoka25480202011-01-20 23:13:02 +09003764 intent.putExtra(Settings.EXTRA_INPUT_METHOD_ID, inputMethodId);
satok7fee71f2010-12-17 18:54:26 +09003765 }
Yohei Yukawa41f34272015-12-14 15:41:52 -08003766 final int userId;
3767 synchronized (mMethodMap) {
3768 userId = mSettings.getCurrentUserId();
3769 }
3770 mContext.startActivityAsUser(intent, null, UserHandle.of(userId));
satok217f5482010-12-15 05:19:19 +09003771 }
3772
3773 private void showConfigureInputMethods() {
3774 Intent intent = new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS);
3775 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
3776 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
3777 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Satoshi Kataoka3ba439d2012-10-05 18:30:13 +09003778 mContext.startActivityAsUser(intent, null, UserHandle.CURRENT);
satok47a44912010-10-06 16:03:58 +09003779 }
3780
satok2c93efc2012-04-02 19:33:47 +09003781 private boolean isScreenLocked() {
3782 return mKeyguardManager != null
3783 && mKeyguardManager.isKeyguardLocked() && mKeyguardManager.isKeyguardSecure();
3784 }
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003785
Seigo Nonaka14e13912015-05-06 21:04:13 -07003786 private void showInputMethodMenu(boolean showAuxSubtypes) {
3787 if (DEBUG) Slog.v(TAG, "Show switching menu. showAuxSubtypes=" + showAuxSubtypes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003788
satok2c93efc2012-04-02 19:33:47 +09003789 final boolean isScreenLocked = isScreenLocked();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003790
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003791 final String lastInputMethodId = mSettings.getSelectedInputMethod();
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003792 int lastInputMethodSubtypeId = mSettings.getSelectedInputMethodSubtypeId(lastInputMethodId);
Joe Onorato8a9b2202010-02-26 18:56:32 -08003793 if (DEBUG) Slog.v(TAG, "Current IME: " + lastInputMethodId);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003794
Dianne Hackborn8cf1bcd2010-03-16 13:06:10 -07003795 synchronized (mMethodMap) {
satokbb4aa062011-01-19 21:40:27 +09003796 final HashMap<InputMethodInfo, List<InputMethodSubtype>> immis =
Satoshi Kataokad787f692013-10-26 04:44:21 +09003797 mSettings.getExplicitlyOrImplicitlyEnabledInputMethodsAndSubtypeListLocked(
3798 mContext);
satok7f35c8c2010-10-07 21:13:11 +09003799 if (immis == null || immis.size() == 0) {
3800 return;
3801 }
3802
Dianne Hackborn8cf1bcd2010-03-16 13:06:10 -07003803 hideInputMethodMenuLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804
satok688bd472012-02-09 20:09:17 +09003805 final List<ImeSubtypeListItem> imList =
Yohei Yukawa5a647b692014-05-22 12:49:00 +09003806 mSwitchingController.getSortedInputMethodAndSubtypeListLocked(
Yohei Yukawa5f8e7312015-12-10 00:58:55 -08003807 showAuxSubtypes, isScreenLocked);
satok913a8922010-08-26 21:53:41 +09003808
satokc3690562012-01-10 20:14:43 +09003809 if (lastInputMethodSubtypeId == NOT_A_SUBTYPE_ID) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003810 final InputMethodSubtype currentSubtype = getCurrentInputMethodSubtypeLocked();
satokc3690562012-01-10 20:14:43 +09003811 if (currentSubtype != null) {
3812 final InputMethodInfo currentImi = mMethodMap.get(mCurMethodId);
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003813 lastInputMethodSubtypeId = InputMethodUtils.getSubtypeIdFromHashCode(
3814 currentImi, currentSubtype.hashCode());
satokc3690562012-01-10 20:14:43 +09003815 }
3816 }
3817
Ken Wakasa761eb372011-03-04 19:06:18 +09003818 final int N = imList.size();
satokab751aa2010-09-14 19:17:36 +09003819 mIms = new InputMethodInfo[N];
3820 mSubtypeIds = new int[N];
Dianne Hackborn8cf1bcd2010-03-16 13:06:10 -07003821 int checkedItem = 0;
3822 for (int i = 0; i < N; ++i) {
Ken Wakasa05dbb652011-08-22 15:22:43 +09003823 final ImeSubtypeListItem item = imList.get(i);
3824 mIms[i] = item.mImi;
3825 mSubtypeIds[i] = item.mSubtypeId;
Dianne Hackborn8cf1bcd2010-03-16 13:06:10 -07003826 if (mIms[i].getId().equals(lastInputMethodId)) {
satokab751aa2010-09-14 19:17:36 +09003827 int subtypeId = mSubtypeIds[i];
3828 if ((subtypeId == NOT_A_SUBTYPE_ID)
3829 || (lastInputMethodSubtypeId == NOT_A_SUBTYPE_ID && subtypeId == 0)
3830 || (subtypeId == lastInputMethodSubtypeId)) {
3831 checkedItem = i;
3832 }
Dianne Hackborn8cf1bcd2010-03-16 13:06:10 -07003833 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003834 }
Alan Viverette505e3ab2014-11-24 15:22:11 -08003835
Andrew Sapperstein8a3b4cb2017-04-28 14:35:31 -07003836 final Context settingsContext = new ContextThemeWrapper(
3837 ActivityThread.currentActivityThread().getSystemUiContext(),
Alan Viverette505e3ab2014-11-24 15:22:11 -08003838 com.android.internal.R.style.Theme_DeviceDefault_Settings);
3839
3840 mDialogBuilder = new AlertDialog.Builder(settingsContext);
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003841 mDialogBuilder.setOnCancelListener(new OnCancelListener() {
3842 @Override
3843 public void onCancel(DialogInterface dialog) {
3844 hideInputMethodMenu();
3845 }
3846 });
Alan Viverette505e3ab2014-11-24 15:22:11 -08003847
3848 final Context dialogContext = mDialogBuilder.getContext();
3849 final TypedArray a = dialogContext.obtainStyledAttributes(null,
3850 com.android.internal.R.styleable.DialogPreference,
3851 com.android.internal.R.attr.alertDialogStyle, 0);
3852 final Drawable dialogIcon = a.getDrawable(
3853 com.android.internal.R.styleable.DialogPreference_dialogIcon);
3854 a.recycle();
3855
3856 mDialogBuilder.setIcon(dialogIcon);
3857
Yohei Yukawad34e1482016-02-11 08:03:52 -08003858 final LayoutInflater inflater = dialogContext.getSystemService(LayoutInflater.class);
satok01038492012-04-09 21:08:27 +09003859 final View tv = inflater.inflate(
3860 com.android.internal.R.layout.input_method_switch_dialog_title, null);
3861 mDialogBuilder.setCustomTitle(tv);
3862
3863 // Setup layout for a toggle switch of the hardware keyboard
3864 mSwitchingDialogTitleView = tv;
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003865 mSwitchingDialogTitleView
3866 .findViewById(com.android.internal.R.id.hard_keyboard_section)
Seigo Nonaka7309b122015-08-17 18:34:13 -07003867 .setVisibility(mWindowManagerInternal.isHardKeyboardAvailable()
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003868 ? View.VISIBLE : View.GONE);
Alan Viverette505e3ab2014-11-24 15:22:11 -08003869 final Switch hardKeySwitch = (Switch) mSwitchingDialogTitleView.findViewById(
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003870 com.android.internal.R.id.hard_keyboard_switch);
Michael Wright7b5a96b2014-08-09 19:28:42 -07003871 hardKeySwitch.setChecked(mShowImeWithHardKeyboard);
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003872 hardKeySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
3873 @Override
3874 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Michael Wright7b5a96b2014-08-09 19:28:42 -07003875 mSettings.setShowImeWithHardKeyboard(isChecked);
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003876 // Ensure that the input method dialog is dismissed when changing
3877 // the hardware keyboard state.
3878 hideInputMethodMenu();
3879 }
3880 });
3881
Alan Viverette505e3ab2014-11-24 15:22:11 -08003882 final ImeSubtypeListAdapter adapter = new ImeSubtypeListAdapter(dialogContext,
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003883 com.android.internal.R.layout.input_method_switch_item, imList, checkedItem);
3884 final OnClickListener choiceListener = new OnClickListener() {
3885 @Override
3886 public void onClick(final DialogInterface dialog, final int which) {
3887 synchronized (mMethodMap) {
3888 if (mIms == null || mIms.length <= which || mSubtypeIds == null
3889 || mSubtypeIds.length <= which) {
3890 return;
satok01038492012-04-09 21:08:27 +09003891 }
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003892 final InputMethodInfo im = mIms[which];
3893 int subtypeId = mSubtypeIds[which];
3894 adapter.mCheckedItem = which;
3895 adapter.notifyDataSetChanged();
3896 hideInputMethodMenu();
3897 if (im != null) {
3898 if (subtypeId < 0 || subtypeId >= im.getSubtypeCount()) {
3899 subtypeId = NOT_A_SUBTYPE_ID;
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08003900 }
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003901 setInputMethodLocked(im.getId(), subtypeId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003902 }
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003903 }
3904 }
3905 };
3906 mDialogBuilder.setSingleChoiceItems(adapter, checkedItem, choiceListener);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 mSwitchingDialog = mDialogBuilder.create();
Dianne Hackborne3a7f622011-03-03 21:48:24 -08003909 mSwitchingDialog.setCanceledOnTouchOutside(true);
Wale Ogunwale3a931692016-11-02 16:49:48 -07003910 final Window w = mSwitchingDialog.getWindow();
3911 final WindowManager.LayoutParams attrs = w.getAttributes();
3912 w.setType(TYPE_INPUT_METHOD_DIALOG);
3913 // Use an alternate token for the dialog for that window manager can group the token
3914 // with other IME windows based on type vs. grouping based on whichever token happens
3915 // to get selected by the system later on.
3916 attrs.token = mSwitchingDialogToken;
3917 attrs.privateFlags |= PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
3918 attrs.setTitle("Select input method");
3919 w.setAttributes(attrs);
Seigo Nonakad9eb9112015-05-26 20:54:43 +09003920 updateSystemUi(mCurToken, mImeWindowVis, mBackDisposition);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003921 mSwitchingDialog.show();
3922 }
3923 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003924
Ken Wakasa05dbb652011-08-22 15:22:43 +09003925 private static class ImeSubtypeListAdapter extends ArrayAdapter<ImeSubtypeListItem> {
3926 private final LayoutInflater mInflater;
3927 private final int mTextViewResourceId;
3928 private final List<ImeSubtypeListItem> mItemsList;
Satoshi Kataokad2142962012-11-12 18:43:06 +09003929 public int mCheckedItem;
Ken Wakasa05dbb652011-08-22 15:22:43 +09003930 public ImeSubtypeListAdapter(Context context, int textViewResourceId,
3931 List<ImeSubtypeListItem> itemsList, int checkedItem) {
3932 super(context, textViewResourceId, itemsList);
Alan Viverette505e3ab2014-11-24 15:22:11 -08003933
Ken Wakasa05dbb652011-08-22 15:22:43 +09003934 mTextViewResourceId = textViewResourceId;
3935 mItemsList = itemsList;
3936 mCheckedItem = checkedItem;
Yohei Yukawad34e1482016-02-11 08:03:52 -08003937 mInflater = context.getSystemService(LayoutInflater.class);
Ken Wakasa05dbb652011-08-22 15:22:43 +09003938 }
3939
3940 @Override
3941 public View getView(int position, View convertView, ViewGroup parent) {
3942 final View view = convertView != null ? convertView
3943 : mInflater.inflate(mTextViewResourceId, null);
3944 if (position < 0 || position >= mItemsList.size()) return view;
3945 final ImeSubtypeListItem item = mItemsList.get(position);
3946 final CharSequence imeName = item.mImeName;
3947 final CharSequence subtypeName = item.mSubtypeName;
3948 final TextView firstTextView = (TextView)view.findViewById(android.R.id.text1);
3949 final TextView secondTextView = (TextView)view.findViewById(android.R.id.text2);
3950 if (TextUtils.isEmpty(subtypeName)) {
3951 firstTextView.setText(imeName);
3952 secondTextView.setVisibility(View.GONE);
3953 } else {
3954 firstTextView.setText(subtypeName);
3955 secondTextView.setText(imeName);
3956 secondTextView.setVisibility(View.VISIBLE);
3957 }
3958 final RadioButton radioButton =
3959 (RadioButton)view.findViewById(com.android.internal.R.id.radio);
3960 radioButton.setChecked(position == mCheckedItem);
3961 return view;
3962 }
3963 }
3964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003965 void hideInputMethodMenu() {
The Android Open Source Project10592532009-03-18 17:39:46 -07003966 synchronized (mMethodMap) {
3967 hideInputMethodMenuLocked();
3968 }
3969 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003970
The Android Open Source Project10592532009-03-18 17:39:46 -07003971 void hideInputMethodMenuLocked() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003972 if (DEBUG) Slog.v(TAG, "Hide switching menu");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003973
The Android Open Source Project10592532009-03-18 17:39:46 -07003974 if (mSwitchingDialog != null) {
3975 mSwitchingDialog.dismiss();
3976 mSwitchingDialog = null;
Yohei Yukawa1fc7a1d2018-04-18 17:31:27 -07003977 mSwitchingDialogTitleView = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003978 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003979
Seigo Nonakad9eb9112015-05-26 20:54:43 +09003980 updateSystemUiLocked(mCurToken, mImeWindowVis, mBackDisposition);
The Android Open Source Project10592532009-03-18 17:39:46 -07003981 mDialogBuilder = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07003982 mIms = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003983 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003985 // ----------------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003986
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003987 boolean setInputMethodEnabledLocked(String id, boolean enabled) {
3988 // Make sure this is a valid input method.
3989 InputMethodInfo imm = mMethodMap.get(id);
3990 if (imm == null) {
satokd87c2592010-09-29 11:52:06 +09003991 throw new IllegalArgumentException("Unknown id: " + mCurMethodId);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003992 }
3993
satokd87c2592010-09-29 11:52:06 +09003994 List<Pair<String, ArrayList<String>>> enabledInputMethodsList = mSettings
3995 .getEnabledInputMethodsAndSubtypeListLocked();
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003996
satokd87c2592010-09-29 11:52:06 +09003997 if (enabled) {
3998 for (Pair<String, ArrayList<String>> pair: enabledInputMethodsList) {
3999 if (pair.first.equals(id)) {
4000 // We are enabling this input method, but it is already enabled.
4001 // Nothing to do. The previous state was enabled.
4002 return true;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004003 }
4004 }
satokd87c2592010-09-29 11:52:06 +09004005 mSettings.appendAndPutEnabledInputMethodLocked(id, false);
4006 // Previous state was disabled.
4007 return false;
4008 } else {
4009 StringBuilder builder = new StringBuilder();
4010 if (mSettings.buildAndPutEnabledInputMethodsStrRemovingIdLocked(
4011 builder, enabledInputMethodsList, id)) {
4012 // Disabled input method is currently selected, switch to another one.
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004013 final String selId = mSettings.getSelectedInputMethod();
satok03eb319a2010-11-11 18:17:42 +09004014 if (id.equals(selId) && !chooseNewDefaultIMELocked()) {
4015 Slog.i(TAG, "Can't find new IME, unsetting the current input method.");
4016 resetSelectedInputMethodAndSubtypeLocked("");
satokd87c2592010-09-29 11:52:06 +09004017 }
4018 // Previous state was enabled.
4019 return true;
4020 } else {
4021 // We are disabling the input method but it is already disabled.
4022 // Nothing to do. The previous state was disabled.
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004023 return false;
4024 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004025 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004026 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08004027
satok723a27e2010-11-11 14:58:11 +09004028 private void setSelectedInputMethodAndSubtypeLocked(InputMethodInfo imi, int subtypeId,
4029 boolean setSubtypeOnly) {
Tarandeep Singh89a6c482017-11-21 14:26:11 -08004030 // Updates to InputMethod are transient in VR mode. Its not included in history.
4031 final boolean isVrInput = imi != null && imi.isVrOnly();
4032 if (!isVrInput) {
4033 // Update the history of InputMethod and Subtype
4034 mSettings.saveCurrentInputMethodAndSubtypeToHistory(mCurMethodId, mCurrentSubtype);
4035 }
satok723a27e2010-11-11 14:58:11 +09004036
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09004037 mCurUserActionNotificationSequenceNumber =
4038 Math.max(mCurUserActionNotificationSequenceNumber + 1, 1);
4039 if (DEBUG) {
4040 Slog.d(TAG, "Bump mCurUserActionNotificationSequenceNumber:"
4041 + mCurUserActionNotificationSequenceNumber);
4042 }
4043
4044 if (mCurClient != null && mCurClient.client != null) {
4045 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
4046 MSG_SET_USER_ACTION_NOTIFICATION_SEQUENCE_NUMBER,
Yohei Yukawa080fa342014-08-31 16:10:05 -07004047 mCurUserActionNotificationSequenceNumber, mCurClient));
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09004048 }
4049
Tarandeep Singh89a6c482017-11-21 14:26:11 -08004050 if (isVrInput) {
4051 // Updates to InputMethod are transient in VR mode. Any changes to Settings are skipped.
4052 return;
4053 }
4054
satok723a27e2010-11-11 14:58:11 +09004055 // Set Subtype here
4056 if (imi == null || subtypeId < 0) {
4057 mSettings.putSelectedSubtype(NOT_A_SUBTYPE_ID);
Tadashi G. Takaoka0ba75bb2010-11-09 12:19:32 -08004058 mCurrentSubtype = null;
satok723a27e2010-11-11 14:58:11 +09004059 } else {
Ken Wakasa586f0512011-01-20 22:31:01 +09004060 if (subtypeId < imi.getSubtypeCount()) {
4061 InputMethodSubtype subtype = imi.getSubtypeAt(subtypeId);
4062 mSettings.putSelectedSubtype(subtype.hashCode());
4063 mCurrentSubtype = subtype;
satok723a27e2010-11-11 14:58:11 +09004064 } else {
4065 mSettings.putSelectedSubtype(NOT_A_SUBTYPE_ID);
satokd81e9502012-05-21 12:58:45 +09004066 // If the subtype is not specified, choose the most applicable one
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004067 mCurrentSubtype = getCurrentInputMethodSubtypeLocked();
satok723a27e2010-11-11 14:58:11 +09004068 }
satokab751aa2010-09-14 19:17:36 +09004069 }
satok723a27e2010-11-11 14:58:11 +09004070
Yohei Yukawa68645a62016-02-17 07:54:20 -08004071 if (!setSubtypeOnly) {
satok723a27e2010-11-11 14:58:11 +09004072 // Set InputMethod here
4073 mSettings.putSelectedInputMethod(imi != null ? imi.getId() : "");
4074 }
4075 }
4076
4077 private void resetSelectedInputMethodAndSubtypeLocked(String newDefaultIme) {
4078 InputMethodInfo imi = mMethodMap.get(newDefaultIme);
4079 int lastSubtypeId = NOT_A_SUBTYPE_ID;
4080 // newDefaultIme is empty when there is no candidate for the selected IME.
4081 if (imi != null && !TextUtils.isEmpty(newDefaultIme)) {
4082 String subtypeHashCode = mSettings.getLastSubtypeForInputMethodLocked(newDefaultIme);
4083 if (subtypeHashCode != null) {
4084 try {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004085 lastSubtypeId = InputMethodUtils.getSubtypeIdFromHashCode(
Narayan Kamatha09b4d22016-04-15 18:32:45 +01004086 imi, Integer.parseInt(subtypeHashCode));
satok723a27e2010-11-11 14:58:11 +09004087 } catch (NumberFormatException e) {
4088 Slog.w(TAG, "HashCode for subtype looks broken: " + subtypeHashCode, e);
4089 }
4090 }
4091 }
4092 setSelectedInputMethodAndSubtypeLocked(imi, lastSubtypeId, false);
satokab751aa2010-09-14 19:17:36 +09004093 }
4094
satok4e4569d2010-11-19 18:45:53 +09004095 // If there are no selected shortcuts, tries finding the most applicable ones.
4096 private Pair<InputMethodInfo, InputMethodSubtype>
4097 findLastResortApplicableShortcutInputMethodAndSubtypeLocked(String mode) {
4098 List<InputMethodInfo> imis = mSettings.getEnabledInputMethodListLocked();
4099 InputMethodInfo mostApplicableIMI = null;
satokcd7cd292010-11-20 15:46:23 +09004100 InputMethodSubtype mostApplicableSubtype = null;
satok4e4569d2010-11-19 18:45:53 +09004101 boolean foundInSystemIME = false;
4102
4103 // Search applicable subtype for each InputMethodInfo
4104 for (InputMethodInfo imi: imis) {
satok7599a7f2010-12-22 13:45:23 +09004105 final String imiId = imi.getId();
4106 if (foundInSystemIME && !imiId.equals(mCurMethodId)) {
4107 continue;
4108 }
satokcd7cd292010-11-20 15:46:23 +09004109 InputMethodSubtype subtype = null;
satokdf31ae62011-01-15 06:19:44 +09004110 final List<InputMethodSubtype> enabledSubtypes =
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004111 mSettings.getEnabledInputMethodSubtypeListLocked(mContext, imi, true);
satokdf31ae62011-01-15 06:19:44 +09004112 // 1. Search by the current subtype's locale from enabledSubtypes.
satok4e4569d2010-11-19 18:45:53 +09004113 if (mCurrentSubtype != null) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004114 subtype = InputMethodUtils.findLastResortApplicableSubtypeLocked(
satokdf31ae62011-01-15 06:19:44 +09004115 mRes, enabledSubtypes, mode, mCurrentSubtype.getLocale(), false);
satok4e4569d2010-11-19 18:45:53 +09004116 }
satokdf31ae62011-01-15 06:19:44 +09004117 // 2. Search by the system locale from enabledSubtypes.
4118 // 3. Search the first enabled subtype matched with mode from enabledSubtypes.
satokcd7cd292010-11-20 15:46:23 +09004119 if (subtype == null) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004120 subtype = InputMethodUtils.findLastResortApplicableSubtypeLocked(
satokdf31ae62011-01-15 06:19:44 +09004121 mRes, enabledSubtypes, mode, null, true);
satok4e4569d2010-11-19 18:45:53 +09004122 }
satoka86f5e42011-09-02 17:12:42 +09004123 final ArrayList<InputMethodSubtype> overridingImplicitlyEnabledSubtypes =
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004124 InputMethodUtils.getOverridingImplicitlyEnabledSubtypes(imi, mode);
satoka86f5e42011-09-02 17:12:42 +09004125 final ArrayList<InputMethodSubtype> subtypesForSearch =
4126 overridingImplicitlyEnabledSubtypes.isEmpty()
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004127 ? InputMethodUtils.getSubtypes(imi)
4128 : overridingImplicitlyEnabledSubtypes;
satok7599a7f2010-12-22 13:45:23 +09004129 // 4. Search by the current subtype's locale from all subtypes.
4130 if (subtype == null && mCurrentSubtype != null) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004131 subtype = InputMethodUtils.findLastResortApplicableSubtypeLocked(
satoka86f5e42011-09-02 17:12:42 +09004132 mRes, subtypesForSearch, mode, mCurrentSubtype.getLocale(), false);
satok7599a7f2010-12-22 13:45:23 +09004133 }
4134 // 5. Search by the system locale from all subtypes.
4135 // 6. Search the first enabled subtype matched with mode from all subtypes.
satokcd7cd292010-11-20 15:46:23 +09004136 if (subtype == null) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004137 subtype = InputMethodUtils.findLastResortApplicableSubtypeLocked(
satoka86f5e42011-09-02 17:12:42 +09004138 mRes, subtypesForSearch, mode, null, true);
satok4e4569d2010-11-19 18:45:53 +09004139 }
satokcd7cd292010-11-20 15:46:23 +09004140 if (subtype != null) {
satok7599a7f2010-12-22 13:45:23 +09004141 if (imiId.equals(mCurMethodId)) {
satok4e4569d2010-11-19 18:45:53 +09004142 // The current input method is the most applicable IME.
4143 mostApplicableIMI = imi;
satokcd7cd292010-11-20 15:46:23 +09004144 mostApplicableSubtype = subtype;
satok4e4569d2010-11-19 18:45:53 +09004145 break;
satok7599a7f2010-12-22 13:45:23 +09004146 } else if (!foundInSystemIME) {
satok4e4569d2010-11-19 18:45:53 +09004147 // The system input method is 2nd applicable IME.
4148 mostApplicableIMI = imi;
satokcd7cd292010-11-20 15:46:23 +09004149 mostApplicableSubtype = subtype;
satok7599a7f2010-12-22 13:45:23 +09004150 if ((imi.getServiceInfo().applicationInfo.flags
4151 & ApplicationInfo.FLAG_SYSTEM) != 0) {
4152 foundInSystemIME = true;
4153 }
satok4e4569d2010-11-19 18:45:53 +09004154 }
4155 }
4156 }
4157 if (DEBUG) {
satokcd7cd292010-11-20 15:46:23 +09004158 if (mostApplicableIMI != null) {
4159 Slog.w(TAG, "Most applicable shortcut input method was:"
4160 + mostApplicableIMI.getId());
4161 if (mostApplicableSubtype != null) {
4162 Slog.w(TAG, "Most applicable shortcut input method subtype was:"
4163 + "," + mostApplicableSubtype.getMode() + ","
4164 + mostApplicableSubtype.getLocale());
4165 }
4166 }
satok4e4569d2010-11-19 18:45:53 +09004167 }
satokcd7cd292010-11-20 15:46:23 +09004168 if (mostApplicableIMI != null) {
Yohei Yukawab0377bb2015-08-10 21:06:30 -07004169 return new Pair<> (mostApplicableIMI, mostApplicableSubtype);
satok4e4569d2010-11-19 18:45:53 +09004170 } else {
4171 return null;
4172 }
4173 }
4174
satokab751aa2010-09-14 19:17:36 +09004175 /**
4176 * @return Return the current subtype of this input method.
4177 */
satok42c5a162011-05-26 16:46:14 +09004178 @Override
satokab751aa2010-09-14 19:17:36 +09004179 public InputMethodSubtype getCurrentInputMethodSubtype() {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004180 // TODO: Make this work even for non-current users?
4181 if (!calledFromValidUser()) {
4182 return null;
4183 }
4184 synchronized (mMethodMap) {
4185 return getCurrentInputMethodSubtypeLocked();
4186 }
4187 }
4188
4189 private InputMethodSubtype getCurrentInputMethodSubtypeLocked() {
satokfdf419e2012-05-08 16:52:08 +09004190 if (mCurMethodId == null) {
4191 return null;
4192 }
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004193 final boolean subtypeIsSelected = mSettings.isSubtypeSelected();
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004194 final InputMethodInfo imi = mMethodMap.get(mCurMethodId);
4195 if (imi == null || imi.getSubtypeCount() == 0) {
4196 return null;
satok4e4569d2010-11-19 18:45:53 +09004197 }
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004198 if (!subtypeIsSelected || mCurrentSubtype == null
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004199 || !InputMethodUtils.isValidSubtypeId(imi, mCurrentSubtype.hashCode())) {
4200 int subtypeId = mSettings.getSelectedInputMethodSubtypeId(mCurMethodId);
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004201 if (subtypeId == NOT_A_SUBTYPE_ID) {
4202 // If there are no selected subtypes, the framework will try to find
4203 // the most applicable subtype from explicitly or implicitly enabled
4204 // subtypes.
4205 List<InputMethodSubtype> explicitlyOrImplicitlyEnabledSubtypes =
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004206 mSettings.getEnabledInputMethodSubtypeListLocked(mContext, imi, true);
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004207 // If there is only one explicitly or implicitly enabled subtype,
4208 // just returns it.
4209 if (explicitlyOrImplicitlyEnabledSubtypes.size() == 1) {
4210 mCurrentSubtype = explicitlyOrImplicitlyEnabledSubtypes.get(0);
4211 } else if (explicitlyOrImplicitlyEnabledSubtypes.size() > 1) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004212 mCurrentSubtype = InputMethodUtils.findLastResortApplicableSubtypeLocked(
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004213 mRes, explicitlyOrImplicitlyEnabledSubtypes,
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004214 InputMethodUtils.SUBTYPE_MODE_KEYBOARD, null, true);
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004215 if (mCurrentSubtype == null) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004216 mCurrentSubtype = InputMethodUtils.findLastResortApplicableSubtypeLocked(
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004217 mRes, explicitlyOrImplicitlyEnabledSubtypes, null, null,
4218 true);
satok4e4569d2010-11-19 18:45:53 +09004219 }
satok3ef8b292010-11-23 06:06:29 +09004220 }
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004221 } else {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004222 mCurrentSubtype = InputMethodUtils.getSubtypes(imi).get(subtypeId);
satok8fbb1e82010-11-02 23:15:58 +09004223 }
4224 }
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004225 return mCurrentSubtype;
satokab751aa2010-09-14 19:17:36 +09004226 }
4227
satok4e4569d2010-11-19 18:45:53 +09004228 // TODO: We should change the return type from List to List<Parcelable>
satokdbf29502011-08-25 15:28:23 +09004229 @SuppressWarnings("rawtypes")
satoke7c6998e2011-06-03 17:57:59 +09004230 @Override
satok4e4569d2010-11-19 18:45:53 +09004231 public List getShortcutInputMethodsAndSubtypes() {
4232 synchronized (mMethodMap) {
Yohei Yukawab0377bb2015-08-10 21:06:30 -07004233 ArrayList<Object> ret = new ArrayList<>();
satokf3db1af2010-11-23 13:34:33 +09004234 if (mShortcutInputMethodsAndSubtypes.size() == 0) {
satok4e4569d2010-11-19 18:45:53 +09004235 // If there are no selected shortcut subtypes, the framework will try to find
4236 // the most applicable subtype from all subtypes whose mode is
4237 // SUBTYPE_MODE_VOICE. This is an exceptional case, so we will hardcode the mode.
satokf3db1af2010-11-23 13:34:33 +09004238 Pair<InputMethodInfo, InputMethodSubtype> info =
4239 findLastResortApplicableShortcutInputMethodAndSubtypeLocked(
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004240 InputMethodUtils.SUBTYPE_MODE_VOICE);
satok7599a7f2010-12-22 13:45:23 +09004241 if (info != null) {
satok3da92232011-01-11 22:46:30 +09004242 ret.add(info.first);
4243 ret.add(info.second);
satok7599a7f2010-12-22 13:45:23 +09004244 }
satok3da92232011-01-11 22:46:30 +09004245 return ret;
satokf3db1af2010-11-23 13:34:33 +09004246 }
satokf3db1af2010-11-23 13:34:33 +09004247 for (InputMethodInfo imi: mShortcutInputMethodsAndSubtypes.keySet()) {
4248 ret.add(imi);
4249 for (InputMethodSubtype subtype: mShortcutInputMethodsAndSubtypes.get(imi)) {
4250 ret.add(subtype);
satok4e4569d2010-11-19 18:45:53 +09004251 }
4252 }
satokf3db1af2010-11-23 13:34:33 +09004253 return ret;
satok4e4569d2010-11-19 18:45:53 +09004254 }
4255 }
4256
satok42c5a162011-05-26 16:46:14 +09004257 @Override
satokb66d2872010-11-10 01:04:04 +09004258 public boolean setCurrentInputMethodSubtype(InputMethodSubtype subtype) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004259 // TODO: Make this work even for non-current users?
4260 if (!calledFromValidUser()) {
4261 return false;
4262 }
satokb66d2872010-11-10 01:04:04 +09004263 synchronized (mMethodMap) {
4264 if (subtype != null && mCurMethodId != null) {
4265 InputMethodInfo imi = mMethodMap.get(mCurMethodId);
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004266 int subtypeId = InputMethodUtils.getSubtypeIdFromHashCode(imi, subtype.hashCode());
satokb66d2872010-11-10 01:04:04 +09004267 if (subtypeId != NOT_A_SUBTYPE_ID) {
4268 setInputMethodLocked(mCurMethodId, subtypeId);
4269 return true;
4270 }
4271 }
4272 return false;
4273 }
4274 }
4275
Satoshi Kataoka5ade83b2012-09-26 22:59:41 +09004276 // TODO: Cache the state for each user and reset when the cached user is removed.
satoke7c6998e2011-06-03 17:57:59 +09004277 private static class InputMethodFileManager {
4278 private static final String SYSTEM_PATH = "system";
4279 private static final String INPUT_METHOD_PATH = "inputmethod";
4280 private static final String ADDITIONAL_SUBTYPES_FILE_NAME = "subtypes.xml";
4281 private static final String NODE_SUBTYPES = "subtypes";
4282 private static final String NODE_SUBTYPE = "subtype";
4283 private static final String NODE_IMI = "imi";
4284 private static final String ATTR_ID = "id";
4285 private static final String ATTR_LABEL = "label";
4286 private static final String ATTR_ICON = "icon";
Yohei Yukawa66baf692016-04-11 02:29:35 -07004287 private static final String ATTR_IME_SUBTYPE_ID = "subtypeId";
satoke7c6998e2011-06-03 17:57:59 +09004288 private static final String ATTR_IME_SUBTYPE_LOCALE = "imeSubtypeLocale";
Yohei Yukawa868d19b2015-12-07 15:58:57 -08004289 private static final String ATTR_IME_SUBTYPE_LANGUAGE_TAG = "languageTag";
satoke7c6998e2011-06-03 17:57:59 +09004290 private static final String ATTR_IME_SUBTYPE_MODE = "imeSubtypeMode";
4291 private static final String ATTR_IME_SUBTYPE_EXTRA_VALUE = "imeSubtypeExtraValue";
4292 private static final String ATTR_IS_AUXILIARY = "isAuxiliary";
Yohei Yukawa1e1a4472016-03-10 23:46:07 -08004293 private static final String ATTR_IS_ASCII_CAPABLE = "isAsciiCapable";
satoke7c6998e2011-06-03 17:57:59 +09004294 private final AtomicFile mAdditionalInputMethodSubtypeFile;
4295 private final HashMap<String, InputMethodInfo> mMethodMap;
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004296 private final HashMap<String, List<InputMethodSubtype>> mAdditionalSubtypesMap =
Yohei Yukawab0377bb2015-08-10 21:06:30 -07004297 new HashMap<>();
Satoshi Kataoka5ade83b2012-09-26 22:59:41 +09004298 public InputMethodFileManager(HashMap<String, InputMethodInfo> methodMap, int userId) {
satoke7c6998e2011-06-03 17:57:59 +09004299 if (methodMap == null) {
4300 throw new NullPointerException("methodMap is null");
4301 }
4302 mMethodMap = methodMap;
Xiaohui Chen7c696362015-09-16 09:56:14 -07004303 final File systemDir = userId == UserHandle.USER_SYSTEM
Satoshi Kataoka5ade83b2012-09-26 22:59:41 +09004304 ? new File(Environment.getDataDirectory(), SYSTEM_PATH)
4305 : Environment.getUserSystemDirectory(userId);
satoke7c6998e2011-06-03 17:57:59 +09004306 final File inputMethodDir = new File(systemDir, INPUT_METHOD_PATH);
Yohei Yukawadf5af482015-08-04 22:11:11 -07004307 if (!inputMethodDir.exists() && !inputMethodDir.mkdirs()) {
satoke7c6998e2011-06-03 17:57:59 +09004308 Slog.w(TAG, "Couldn't create dir.: " + inputMethodDir.getAbsolutePath());
4309 }
4310 final File subtypeFile = new File(inputMethodDir, ADDITIONAL_SUBTYPES_FILE_NAME);
Dianne Hackborne17b4452018-01-10 13:15:40 -08004311 mAdditionalInputMethodSubtypeFile = new AtomicFile(subtypeFile, "input-subtypes");
satoke7c6998e2011-06-03 17:57:59 +09004312 if (!subtypeFile.exists()) {
4313 // If "subtypes.xml" doesn't exist, create a blank file.
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004314 writeAdditionalInputMethodSubtypes(
4315 mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile, methodMap);
satoke7c6998e2011-06-03 17:57:59 +09004316 } else {
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004317 readAdditionalInputMethodSubtypes(
4318 mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile);
satoke7c6998e2011-06-03 17:57:59 +09004319 }
4320 }
4321
4322 private void deleteAllInputMethodSubtypes(String imiId) {
4323 synchronized (mMethodMap) {
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004324 mAdditionalSubtypesMap.remove(imiId);
4325 writeAdditionalInputMethodSubtypes(
4326 mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile, mMethodMap);
satoke7c6998e2011-06-03 17:57:59 +09004327 }
4328 }
4329
4330 public void addInputMethodSubtypes(
satok4a28bde2011-06-29 21:03:40 +09004331 InputMethodInfo imi, InputMethodSubtype[] additionalSubtypes) {
satoke7c6998e2011-06-03 17:57:59 +09004332 synchronized (mMethodMap) {
Yohei Yukawab0377bb2015-08-10 21:06:30 -07004333 final ArrayList<InputMethodSubtype> subtypes = new ArrayList<>();
satoke7c6998e2011-06-03 17:57:59 +09004334 final int N = additionalSubtypes.length;
4335 for (int i = 0; i < N; ++i) {
4336 final InputMethodSubtype subtype = additionalSubtypes[i];
satoked2b24e2011-08-31 18:03:21 +09004337 if (!subtypes.contains(subtype)) {
satoke7c6998e2011-06-03 17:57:59 +09004338 subtypes.add(subtype);
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004339 } else {
4340 Slog.w(TAG, "Duplicated subtype definition found: "
4341 + subtype.getLocale() + ", " + subtype.getMode());
satoke7c6998e2011-06-03 17:57:59 +09004342 }
4343 }
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004344 mAdditionalSubtypesMap.put(imi.getId(), subtypes);
4345 writeAdditionalInputMethodSubtypes(
4346 mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile, mMethodMap);
satoke7c6998e2011-06-03 17:57:59 +09004347 }
4348 }
4349
4350 public HashMap<String, List<InputMethodSubtype>> getAllAdditionalInputMethodSubtypes() {
4351 synchronized (mMethodMap) {
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004352 return mAdditionalSubtypesMap;
satoke7c6998e2011-06-03 17:57:59 +09004353 }
4354 }
4355
4356 private static void writeAdditionalInputMethodSubtypes(
4357 HashMap<String, List<InputMethodSubtype>> allSubtypes, AtomicFile subtypesFile,
4358 HashMap<String, InputMethodInfo> methodMap) {
4359 // Safety net for the case that this function is called before methodMap is set.
4360 final boolean isSetMethodMap = methodMap != null && methodMap.size() > 0;
4361 FileOutputStream fos = null;
4362 try {
4363 fos = subtypesFile.startWrite();
4364 final XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01004365 out.setOutput(fos, StandardCharsets.UTF_8.name());
satoke7c6998e2011-06-03 17:57:59 +09004366 out.startDocument(null, true);
4367 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
4368 out.startTag(null, NODE_SUBTYPES);
4369 for (String imiId : allSubtypes.keySet()) {
4370 if (isSetMethodMap && !methodMap.containsKey(imiId)) {
4371 Slog.w(TAG, "IME uninstalled or not valid.: " + imiId);
4372 continue;
4373 }
4374 out.startTag(null, NODE_IMI);
4375 out.attribute(null, ATTR_ID, imiId);
4376 final List<InputMethodSubtype> subtypesList = allSubtypes.get(imiId);
4377 final int N = subtypesList.size();
4378 for (int i = 0; i < N; ++i) {
4379 final InputMethodSubtype subtype = subtypesList.get(i);
4380 out.startTag(null, NODE_SUBTYPE);
Yohei Yukawa66baf692016-04-11 02:29:35 -07004381 if (subtype.hasSubtypeId()) {
4382 out.attribute(null, ATTR_IME_SUBTYPE_ID,
4383 String.valueOf(subtype.getSubtypeId()));
4384 }
satoke7c6998e2011-06-03 17:57:59 +09004385 out.attribute(null, ATTR_ICON, String.valueOf(subtype.getIconResId()));
4386 out.attribute(null, ATTR_LABEL, String.valueOf(subtype.getNameResId()));
4387 out.attribute(null, ATTR_IME_SUBTYPE_LOCALE, subtype.getLocale());
Yohei Yukawa868d19b2015-12-07 15:58:57 -08004388 out.attribute(null, ATTR_IME_SUBTYPE_LANGUAGE_TAG,
4389 subtype.getLanguageTag());
satoke7c6998e2011-06-03 17:57:59 +09004390 out.attribute(null, ATTR_IME_SUBTYPE_MODE, subtype.getMode());
4391 out.attribute(null, ATTR_IME_SUBTYPE_EXTRA_VALUE, subtype.getExtraValue());
4392 out.attribute(null, ATTR_IS_AUXILIARY,
4393 String.valueOf(subtype.isAuxiliary() ? 1 : 0));
Yohei Yukawa1e1a4472016-03-10 23:46:07 -08004394 out.attribute(null, ATTR_IS_ASCII_CAPABLE,
4395 String.valueOf(subtype.isAsciiCapable() ? 1 : 0));
satoke7c6998e2011-06-03 17:57:59 +09004396 out.endTag(null, NODE_SUBTYPE);
4397 }
4398 out.endTag(null, NODE_IMI);
4399 }
4400 out.endTag(null, NODE_SUBTYPES);
4401 out.endDocument();
4402 subtypesFile.finishWrite(fos);
4403 } catch (java.io.IOException e) {
4404 Slog.w(TAG, "Error writing subtypes", e);
4405 if (fos != null) {
4406 subtypesFile.failWrite(fos);
4407 }
4408 }
4409 }
4410
4411 private static void readAdditionalInputMethodSubtypes(
4412 HashMap<String, List<InputMethodSubtype>> allSubtypes, AtomicFile subtypesFile) {
4413 if (allSubtypes == null || subtypesFile == null) return;
4414 allSubtypes.clear();
Yohei Yukawa5894b432015-08-11 13:29:24 -07004415 try (final FileInputStream fis = subtypesFile.openRead()) {
satoke7c6998e2011-06-03 17:57:59 +09004416 final XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01004417 parser.setInput(fis, StandardCharsets.UTF_8.name());
satoke7c6998e2011-06-03 17:57:59 +09004418 int type = parser.getEventType();
4419 // Skip parsing until START_TAG
4420 while ((type = parser.next()) != XmlPullParser.START_TAG
4421 && type != XmlPullParser.END_DOCUMENT) {}
4422 String firstNodeName = parser.getName();
4423 if (!NODE_SUBTYPES.equals(firstNodeName)) {
4424 throw new XmlPullParserException("Xml doesn't start with subtypes");
4425 }
4426 final int depth =parser.getDepth();
4427 String currentImiId = null;
4428 ArrayList<InputMethodSubtype> tempSubtypesArray = null;
4429 while (((type = parser.next()) != XmlPullParser.END_TAG
4430 || parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
4431 if (type != XmlPullParser.START_TAG)
4432 continue;
4433 final String nodeName = parser.getName();
4434 if (NODE_IMI.equals(nodeName)) {
4435 currentImiId = parser.getAttributeValue(null, ATTR_ID);
4436 if (TextUtils.isEmpty(currentImiId)) {
4437 Slog.w(TAG, "Invalid imi id found in subtypes.xml");
4438 continue;
4439 }
Yohei Yukawab0377bb2015-08-10 21:06:30 -07004440 tempSubtypesArray = new ArrayList<>();
satoke7c6998e2011-06-03 17:57:59 +09004441 allSubtypes.put(currentImiId, tempSubtypesArray);
4442 } else if (NODE_SUBTYPE.equals(nodeName)) {
4443 if (TextUtils.isEmpty(currentImiId) || tempSubtypesArray == null) {
4444 Slog.w(TAG, "IME uninstalled or not valid.: " + currentImiId);
4445 continue;
4446 }
Narayan Kamatha09b4d22016-04-15 18:32:45 +01004447 final int icon = Integer.parseInt(
satoke7c6998e2011-06-03 17:57:59 +09004448 parser.getAttributeValue(null, ATTR_ICON));
Narayan Kamatha09b4d22016-04-15 18:32:45 +01004449 final int label = Integer.parseInt(
satoke7c6998e2011-06-03 17:57:59 +09004450 parser.getAttributeValue(null, ATTR_LABEL));
4451 final String imeSubtypeLocale =
4452 parser.getAttributeValue(null, ATTR_IME_SUBTYPE_LOCALE);
Yohei Yukawa868d19b2015-12-07 15:58:57 -08004453 final String languageTag =
4454 parser.getAttributeValue(null, ATTR_IME_SUBTYPE_LANGUAGE_TAG);
satoke7c6998e2011-06-03 17:57:59 +09004455 final String imeSubtypeMode =
4456 parser.getAttributeValue(null, ATTR_IME_SUBTYPE_MODE);
4457 final String imeSubtypeExtraValue =
4458 parser.getAttributeValue(null, ATTR_IME_SUBTYPE_EXTRA_VALUE);
satok4a28bde2011-06-29 21:03:40 +09004459 final boolean isAuxiliary = "1".equals(String.valueOf(
4460 parser.getAttributeValue(null, ATTR_IS_AUXILIARY)));
Yohei Yukawa1e1a4472016-03-10 23:46:07 -08004461 final boolean isAsciiCapable = "1".equals(String.valueOf(
4462 parser.getAttributeValue(null, ATTR_IS_ASCII_CAPABLE)));
Yohei Yukawa66baf692016-04-11 02:29:35 -07004463 final InputMethodSubtypeBuilder builder = new InputMethodSubtypeBuilder()
Yohei Yukawa443c2ba2014-09-10 14:10:30 +09004464 .setSubtypeNameResId(label)
4465 .setSubtypeIconResId(icon)
4466 .setSubtypeLocale(imeSubtypeLocale)
Yohei Yukawa868d19b2015-12-07 15:58:57 -08004467 .setLanguageTag(languageTag)
Yohei Yukawa443c2ba2014-09-10 14:10:30 +09004468 .setSubtypeMode(imeSubtypeMode)
4469 .setSubtypeExtraValue(imeSubtypeExtraValue)
4470 .setIsAuxiliary(isAuxiliary)
Yohei Yukawa66baf692016-04-11 02:29:35 -07004471 .setIsAsciiCapable(isAsciiCapable);
4472 final String subtypeIdString =
4473 parser.getAttributeValue(null, ATTR_IME_SUBTYPE_ID);
4474 if (subtypeIdString != null) {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01004475 builder.setSubtypeId(Integer.parseInt(subtypeIdString));
Yohei Yukawa66baf692016-04-11 02:29:35 -07004476 }
4477 tempSubtypesArray.add(builder.build());
satoke7c6998e2011-06-03 17:57:59 +09004478 }
4479 }
Yohei Yukawa5894b432015-08-11 13:29:24 -07004480 } catch (XmlPullParserException | IOException | NumberFormatException e) {
4481 Slog.w(TAG, "Error reading subtypes", e);
satoke7c6998e2011-06-03 17:57:59 +09004482 return;
satoke7c6998e2011-06-03 17:57:59 +09004483 }
4484 }
4485 }
4486
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07004487 private static final class LocalServiceImpl implements InputMethodManagerInternal {
4488 @NonNull
4489 private final Handler mHandler;
4490
4491 LocalServiceImpl(@NonNull final Handler handler) {
4492 mHandler = handler;
4493 }
4494
4495 @Override
4496 public void setInteractive(boolean interactive) {
4497 // Do everything in handler so as not to block the caller.
4498 mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_INTERACTIVE,
4499 interactive ? 1 : 0, 0));
4500 }
Yohei Yukawaae61f712015-12-09 13:00:10 -08004501
4502 @Override
4503 public void switchInputMethod(boolean forwardDirection) {
4504 // Do everything in handler so as not to block the caller.
4505 mHandler.sendMessage(mHandler.obtainMessage(MSG_SWITCH_IME,
4506 forwardDirection ? 1 : 0, 0));
4507 }
Jorim Jaggi3c5d0f12016-05-24 19:04:30 -07004508
4509 @Override
4510 public void hideCurrentInputMethod() {
4511 mHandler.removeMessages(MSG_HIDE_CURRENT_INPUT_METHOD);
4512 mHandler.sendEmptyMessage(MSG_HIDE_CURRENT_INPUT_METHOD);
4513 }
Tarandeep Singh89a6c482017-11-21 14:26:11 -08004514
4515 @Override
4516 public void startVrInputMethodNoCheck(@Nullable ComponentName componentName) {
4517 mHandler.sendMessage(mHandler.obtainMessage(MSG_START_VR_INPUT, componentName));
4518 }
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07004519 }
4520
Yohei Yukawaebda7d72016-04-02 17:39:23 -07004521 private static String imeWindowStatusToString(final int imeWindowVis) {
4522 final StringBuilder sb = new StringBuilder();
4523 boolean first = true;
4524 if ((imeWindowVis & InputMethodService.IME_ACTIVE) != 0) {
4525 sb.append("Active");
4526 first = false;
4527 }
4528 if ((imeWindowVis & InputMethodService.IME_VISIBLE) != 0) {
4529 if (!first) {
4530 sb.append("|");
4531 }
4532 sb.append("Visible");
4533 }
4534 return sb.toString();
4535 }
4536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004537 @Override
Yohei Yukawa25e08132016-06-22 16:31:41 -07004538 public IInputContentUriToken createInputContentUriToken(@Nullable IBinder token,
4539 @Nullable Uri contentUri, @Nullable String packageName) {
4540 if (!calledFromValidUser()) {
4541 return null;
4542 }
4543
4544 if (token == null) {
4545 throw new NullPointerException("token");
4546 }
4547 if (packageName == null) {
4548 throw new NullPointerException("packageName");
4549 }
4550 if (contentUri == null) {
4551 throw new NullPointerException("contentUri");
4552 }
4553 final String contentUriScheme = contentUri.getScheme();
4554 if (!"content".equals(contentUriScheme)) {
4555 throw new InvalidParameterException("contentUri must have content scheme");
4556 }
4557
4558 synchronized (mMethodMap) {
4559 final int uid = Binder.getCallingUid();
4560 if (mCurMethodId == null) {
4561 return null;
4562 }
4563 if (mCurToken != token) {
4564 Slog.e(TAG, "Ignoring createInputContentUriToken mCurToken=" + mCurToken
4565 + " token=" + token);
4566 return null;
4567 }
4568 // We cannot simply distinguish a bad IME that reports an arbitrary package name from
4569 // an unfortunate IME whose internal state is already obsolete due to the asynchronous
4570 // nature of our system. Let's compare it with our internal record.
4571 if (!TextUtils.equals(mCurAttribute.packageName, packageName)) {
4572 Slog.e(TAG, "Ignoring createInputContentUriToken mCurAttribute.packageName="
4573 + mCurAttribute.packageName + " packageName=" + packageName);
4574 return null;
4575 }
Yohei Yukawa3933a6e2016-11-10 00:47:48 -08004576 // This user ID can never bee spoofed.
Yohei Yukawa25e08132016-06-22 16:31:41 -07004577 final int imeUserId = UserHandle.getUserId(uid);
Yohei Yukawa3933a6e2016-11-10 00:47:48 -08004578 // This user ID can never bee spoofed.
Yohei Yukawa25e08132016-06-22 16:31:41 -07004579 final int appUserId = UserHandle.getUserId(mCurClient.uid);
Yohei Yukawa3933a6e2016-11-10 00:47:48 -08004580 // This user ID may be invalid if "contentUri" embedded an invalid user ID.
4581 final int contentUriOwnerUserId = ContentProvider.getUserIdFromUri(contentUri,
4582 imeUserId);
4583 final Uri contentUriWithoutUserId = ContentProvider.getUriWithoutUserId(contentUri);
4584 // Note: InputContentUriTokenHandler.take() checks whether the IME (specified by "uid")
4585 // actually has the right to grant a read permission for "contentUriWithoutUserId" that
4586 // is claimed to belong to "contentUriOwnerUserId". For example, specifying random
4587 // content URI and/or contentUriOwnerUserId just results in a SecurityException thrown
4588 // from InputContentUriTokenHandler.take() and can never be allowed beyond what is
4589 // actually allowed to "uid", which is guaranteed to be the IME's one.
4590 return new InputContentUriTokenHandler(contentUriWithoutUserId, uid,
4591 packageName, contentUriOwnerUserId, appUserId);
Yohei Yukawa25e08132016-06-22 16:31:41 -07004592 }
4593 }
4594
4595 @Override
Yohei Yukawa2bc66172017-02-08 11:13:25 -08004596 public void reportFullscreenMode(IBinder token, boolean fullscreen) {
4597 if (!calledFromValidUser()) {
4598 return;
4599 }
4600 synchronized (mMethodMap) {
4601 if (!calledWithValidToken(token)) {
4602 return;
4603 }
4604 if (mCurClient != null && mCurClient.client != null) {
4605 mInFullscreenMode = fullscreen;
4606 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
4607 MSG_REPORT_FULLSCREEN_MODE, fullscreen ? 1 : 0, mCurClient));
4608 }
4609 }
4610 }
4611
4612 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004613 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06004614 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004615
4616 IInputMethod method;
4617 ClientState client;
Yohei Yukawae39d4ed2015-11-19 03:38:49 -08004618 ClientState focusedWindowClient;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004620 final Printer p = new PrintWriterPrinter(pw);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004622 synchronized (mMethodMap) {
4623 p.println("Current Input Method Manager state:");
4624 int N = mMethodList.size();
Yohei Yukawaf80087c2018-05-21 09:47:53 -07004625 p.println(" Input Methods: mMethodMapUpdateCount=" + mMethodMapUpdateCount
4626 + " mBindInstantServiceAllowed=" + mBindInstantServiceAllowed);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004627 for (int i=0; i<N; i++) {
4628 InputMethodInfo info = mMethodList.get(i);
4629 p.println(" InputMethod #" + i + ":");
4630 info.dump(p, " ");
4631 }
4632 p.println(" Clients:");
4633 for (ClientState ci : mClients.values()) {
4634 p.println(" Client " + ci + ":");
4635 p.println(" client=" + ci.client);
4636 p.println(" inputContext=" + ci.inputContext);
4637 p.println(" sessionRequested=" + ci.sessionRequested);
4638 p.println(" curSession=" + ci.curSession);
4639 }
The Android Open Source Project10592532009-03-18 17:39:46 -07004640 p.println(" mCurMethodId=" + mCurMethodId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004641 client = mCurClient;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004642 p.println(" mCurClient=" + client + " mCurSeq=" + mCurSeq);
Yohei Yukawa22a89232017-02-12 16:38:59 -08004643 p.println(" mCurFocusedWindow=" + mCurFocusedWindow
4644 + " softInputMode=" +
4645 InputMethodClient.softInputModeToString(mCurFocusedWindowSoftInputMode)
4646 + " client=" + mCurFocusedWindowClient);
Yohei Yukawae39d4ed2015-11-19 03:38:49 -08004647 focusedWindowClient = mCurFocusedWindowClient;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004648 p.println(" mCurId=" + mCurId + " mHaveConnect=" + mHaveConnection
4649 + " mBoundToMethod=" + mBoundToMethod);
4650 p.println(" mCurToken=" + mCurToken);
4651 p.println(" mCurIntent=" + mCurIntent);
4652 method = mCurMethod;
4653 p.println(" mCurMethod=" + mCurMethod);
4654 p.println(" mEnabledSession=" + mEnabledSession);
Yohei Yukawaebda7d72016-04-02 17:39:23 -07004655 p.println(" mImeWindowVis=" + imeWindowStatusToString(mImeWindowVis));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004656 p.println(" mShowRequested=" + mShowRequested
4657 + " mShowExplicitlyRequested=" + mShowExplicitlyRequested
4658 + " mShowForced=" + mShowForced
4659 + " mInputShown=" + mInputShown);
Yohei Yukawa2bc66172017-02-08 11:13:25 -08004660 p.println(" mInFullscreenMode=" + mInFullscreenMode);
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09004661 p.println(" mCurUserActionNotificationSequenceNumber="
4662 + mCurUserActionNotificationSequenceNumber);
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07004663 p.println(" mSystemReady=" + mSystemReady + " mInteractive=" + mIsInteractive);
Yohei Yukawa81482972015-06-04 00:58:59 -07004664 p.println(" mSettingsObserver=" + mSettingsObserver);
Yohei Yukawad7248862015-06-03 23:56:12 -07004665 p.println(" mSwitchingController:");
4666 mSwitchingController.dump(p);
Yohei Yukawa68645a62016-02-17 07:54:20 -08004667 p.println(" mSettings:");
4668 mSettings.dumpLocked(p, " ");
Yohei Yukawa357b2f62017-02-14 09:40:03 -08004669
4670 p.println(" mStartInputHistory:");
4671 mStartInputHistory.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004672 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004673
Jeff Brownb88102f2010-09-08 11:49:43 -07004674 p.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004675 if (client != 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(client.client.asBinder(), fd, args);
4679 } catch (IOException | RemoteException e) {
4680 p.println("Failed to dump input method client: " + 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 client.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004684 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004685
Yohei Yukawae39d4ed2015-11-19 03:38:49 -08004686 if (focusedWindowClient != null && client != focusedWindowClient) {
4687 p.println(" ");
4688 p.println("Warning: Current input method client doesn't match the last focused. "
4689 + "window.");
4690 p.println("Dumping input method client in the last focused window just in case.");
4691 p.println(" ");
4692 pw.flush();
4693 try {
Jeff Sharkey850c83e2016-11-09 12:25:44 -07004694 TransferPipe.dumpAsync(focusedWindowClient.client.asBinder(), fd, args);
4695 } catch (IOException | RemoteException e) {
4696 p.println("Failed to dump input method client in focused window: " + e);
Yohei Yukawae39d4ed2015-11-19 03:38:49 -08004697 }
4698 }
4699
Jeff Brownb88102f2010-09-08 11:49:43 -07004700 p.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004701 if (method != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004702 pw.flush();
4703 try {
Jeff Sharkey850c83e2016-11-09 12:25:44 -07004704 TransferPipe.dumpAsync(method.asBinder(), fd, args);
4705 } catch (IOException | RemoteException e) {
4706 p.println("Failed to dump input method service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004707 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004708 } else {
4709 p.println("No input method service.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004710 }
4711 }
Yohei Yukawa926488d2017-12-11 17:24:55 -08004712
4713 @BinderThread
4714 @Override
4715 public void onShellCommand(@Nullable FileDescriptor in, @Nullable FileDescriptor out,
4716 @Nullable FileDescriptor err,
4717 @NonNull String[] args, @Nullable ShellCallback callback,
4718 @NonNull ResultReceiver resultReceiver) throws RemoteException {
4719 new ShellCommandImpl(this).exec(
4720 this, in, out, err, args, callback, resultReceiver);
4721 }
4722
4723 private static final class ShellCommandImpl extends ShellCommand {
4724 @NonNull
4725 final InputMethodManagerService mService;
4726
4727 ShellCommandImpl(InputMethodManagerService service) {
4728 mService = service;
4729 }
4730
4731 @BinderThread
4732 @ShellCommandResult
4733 @Override
4734 public int onCommand(@Nullable String cmd) {
Yohei Yukawadfdab732018-02-21 07:16:30 +09004735 if ("refresh_debug_properties".equals(cmd)) {
4736 return refreshDebugProperties();
4737 }
Yohei Yukawaf80087c2018-05-21 09:47:53 -07004738 if ("set-bind-instant-service-allowed".equals(cmd)) {
4739 return setBindInstantServiceAllowed();
4740 }
Yohei Yukawadfdab732018-02-21 07:16:30 +09004741
Yohei Yukawacac97722017-12-15 16:52:05 -08004742 // For existing "adb shell ime <command>".
4743 if ("ime".equals(cmd)) {
4744 final String imeCommand = getNextArg();
4745 if (imeCommand == null || "help".equals(imeCommand) || "-h".equals(imeCommand)) {
4746 onImeCommandHelp();
4747 return ShellCommandResult.SUCCESS;
4748 }
4749 switch (imeCommand) {
4750 case "list":
4751 return mService.handleShellCommandListInputMethods(this);
4752 case "enable":
4753 return mService.handleShellCommandEnableDisableInputMethod(this, true);
4754 case "disable":
4755 return mService.handleShellCommandEnableDisableInputMethod(this, false);
4756 case "set":
4757 return mService.handleShellCommandSetInputMethod(this);
4758 case "reset":
4759 return mService.handleShellCommandResetInputMethod(this);
4760 default:
4761 getOutPrintWriter().println("Unknown command: " + imeCommand);
4762 return ShellCommandResult.FAILURE;
4763 }
Yohei Yukawa926488d2017-12-11 17:24:55 -08004764 }
Yohei Yukawacac97722017-12-15 16:52:05 -08004765
4766 return handleDefaultCommands(cmd);
Yohei Yukawa926488d2017-12-11 17:24:55 -08004767 }
4768
4769 @BinderThread
Tarandeep Singh75a92392018-01-12 14:58:59 -08004770 @ShellCommandResult
Yohei Yukawaf80087c2018-05-21 09:47:53 -07004771 private int setBindInstantServiceAllowed() {
4772 return mService.handleSetBindInstantServiceAllowed(this);
4773 }
4774
4775 @BinderThread
4776 @ShellCommandResult
Tarandeep Singh75a92392018-01-12 14:58:59 -08004777 private int refreshDebugProperties() {
4778 DebugFlags.FLAG_OPTIMIZE_START_INPUT.refresh();
4779 return ShellCommandResult.SUCCESS;
4780 }
4781
4782 @BinderThread
Yohei Yukawa926488d2017-12-11 17:24:55 -08004783 @Override
4784 public void onHelp() {
4785 try (PrintWriter pw = getOutPrintWriter()) {
4786 pw.println("InputMethodManagerService commands:");
4787 pw.println(" help");
4788 pw.println(" Prints this help text.");
4789 pw.println(" dump [options]");
4790 pw.println(" Synonym of dumpsys.");
Yohei Yukawacac97722017-12-15 16:52:05 -08004791 pw.println(" ime <command> [options]");
4792 pw.println(" Manipulate IMEs. Run \"ime help\" for details.");
Yohei Yukawaf80087c2018-05-21 09:47:53 -07004793 pw.println(" set-bind-instant-service-allowed true|false ");
4794 pw.println(" Set whether binding to services provided by instant apps is "
4795 + "allowed.");
Yohei Yukawacac97722017-12-15 16:52:05 -08004796 }
4797 }
4798
4799 private void onImeCommandHelp() {
4800 try (IndentingPrintWriter pw =
4801 new IndentingPrintWriter(getOutPrintWriter(), " ", 100)) {
4802 pw.println("ime <command>:");
4803 pw.increaseIndent();
4804
4805 pw.println("list [-a] [-s]");
4806 pw.increaseIndent();
4807 pw.println("prints all enabled input methods.");
4808 pw.increaseIndent();
4809 pw.println("-a: see all input methods");
4810 pw.println("-s: only a single summary line of each");
4811 pw.decreaseIndent();
4812 pw.decreaseIndent();
4813
4814 pw.println("enable <ID>");
4815 pw.increaseIndent();
4816 pw.println("allows the given input method ID to be used.");
4817 pw.decreaseIndent();
4818
4819 pw.println("disable <ID>");
4820 pw.increaseIndent();
4821 pw.println("disallows the given input method ID to be used.");
4822 pw.decreaseIndent();
4823
4824 pw.println("set <ID>");
4825 pw.increaseIndent();
4826 pw.println("switches to the given input method ID.");
4827 pw.decreaseIndent();
4828
4829 pw.println("reset");
4830 pw.increaseIndent();
4831 pw.println("reset currently selected/enabled IMEs to the default ones as if "
4832 + "the device is initially booted with the current locale.");
4833 pw.decreaseIndent();
4834
4835 pw.decreaseIndent();
Yohei Yukawa926488d2017-12-11 17:24:55 -08004836 }
4837 }
4838 }
4839
4840 // ----------------------------------------------------------------------
4841 // Shell command handlers:
4842
4843 /**
Yohei Yukawaf80087c2018-05-21 09:47:53 -07004844 * Handles {@code adb shell cmd input_method set-bind-instant-service-allowed}.
4845 *
4846 * @param shellCommand {@link ShellCommand} object that is handling this command.
4847 * @return Exit code of the command.
4848 */
4849 @BinderThread
4850 @RequiresPermission(android.Manifest.permission.MANAGE_BIND_INSTANT_SERVICE)
4851 @ShellCommandResult
4852 private int handleSetBindInstantServiceAllowed(@NonNull ShellCommand shellCommand) {
4853 final String allowedString = shellCommand.getNextArgRequired();
4854 if (allowedString == null) {
4855 shellCommand.getErrPrintWriter().println("Error: no true/false specified");
4856 return ShellCommandResult.FAILURE;
4857 }
4858 final boolean allowed = Boolean.parseBoolean(allowedString);
4859 synchronized (mMethodMap) {
4860 if (mContext.checkCallingOrSelfPermission(
4861 android.Manifest.permission.MANAGE_BIND_INSTANT_SERVICE)
4862 != PackageManager.PERMISSION_GRANTED) {
4863 shellCommand.getErrPrintWriter().print(
4864 "Caller must have MANAGE_BIND_INSTANT_SERVICE permission");
4865 return ShellCommandResult.FAILURE;
4866 }
4867
4868 if (mBindInstantServiceAllowed == allowed) {
4869 // Nothing to do.
4870 return ShellCommandResult.SUCCESS;
4871 }
4872 mBindInstantServiceAllowed = allowed;
4873
4874 // Rebuild everything.
4875 final long ident = Binder.clearCallingIdentity();
4876 try {
4877 // Reset the current IME
4878 resetSelectedInputMethodAndSubtypeLocked(null);
4879 // Also reset the settings of the current IME
4880 mSettings.putSelectedInputMethod(null);
4881 buildInputMethodListLocked(false /* resetDefaultEnabledIme */);
4882 updateInputMethodsFromSettingsLocked(true /* enabledMayChange */);
4883 } finally {
4884 Binder.restoreCallingIdentity(ident);
4885 }
4886 }
4887 return ShellCommandResult.SUCCESS;
4888 }
4889
4890 /**
Yohei Yukawa926488d2017-12-11 17:24:55 -08004891 * Handles {@code adb shell ime list}.
4892 * @param shellCommand {@link ShellCommand} object that is handling this command.
4893 * @return Exit code of the command.
4894 */
4895 @BinderThread
4896 @ShellCommandResult
4897 private int handleShellCommandListInputMethods(@NonNull ShellCommand shellCommand) {
4898 boolean all = false;
4899 boolean brief = false;
4900 while (true) {
4901 final String nextOption = shellCommand.getNextOption();
4902 if (nextOption == null) {
4903 break;
4904 }
4905 switch (nextOption) {
4906 case "-a":
4907 all = true;
4908 break;
4909 case "-s":
4910 brief = true;
4911 break;
4912 }
4913 }
4914 final List<InputMethodInfo> methods = all ?
4915 getInputMethodList() : getEnabledInputMethodList();
4916 final PrintWriter pr = shellCommand.getOutPrintWriter();
4917 final Printer printer = x -> pr.println(x);
4918 final int N = methods.size();
4919 for (int i = 0; i < N; ++i) {
4920 if (brief) {
4921 pr.println(methods.get(i).getId());
4922 } else {
4923 pr.print(methods.get(i).getId()); pr.println(":");
4924 methods.get(i).dump(printer, " ");
4925 }
4926 }
4927 return ShellCommandResult.SUCCESS;
4928 }
4929
4930 /**
4931 * Handles {@code adb shell ime enable} and {@code adb shell ime disable}.
4932 * @param shellCommand {@link ShellCommand} object that is handling this command.
4933 * @param enabled {@code true} if the command was {@code adb shell ime enable}.
4934 * @return Exit code of the command.
4935 */
4936 @BinderThread
4937 @ShellCommandResult
4938 @RequiresPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
4939 private int handleShellCommandEnableDisableInputMethod(
4940 @NonNull ShellCommand shellCommand, boolean enabled) {
4941 if (!calledFromValidUser()) {
4942 shellCommand.getErrPrintWriter().print(
4943 "Must be called from the foreground user or with INTERACT_ACROSS_USERS_FULL");
4944 return ShellCommandResult.FAILURE;
4945 }
4946 final String id = shellCommand.getNextArgRequired();
4947
4948 final boolean previouslyEnabled;
4949 synchronized (mMethodMap) {
4950 if (mContext.checkCallingOrSelfPermission(
4951 android.Manifest.permission.WRITE_SECURE_SETTINGS)
4952 != PackageManager.PERMISSION_GRANTED) {
4953 shellCommand.getErrPrintWriter().print(
4954 "Caller must have WRITE_SECURE_SETTINGS permission");
4955 throw new SecurityException(
4956 "Requires permission "
4957 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
4958 }
4959
4960 final long ident = Binder.clearCallingIdentity();
4961 try {
4962 previouslyEnabled = setInputMethodEnabledLocked(id, enabled);
4963 } finally {
4964 Binder.restoreCallingIdentity(ident);
4965 }
4966 }
4967 final PrintWriter pr = shellCommand.getOutPrintWriter();
4968 pr.print("Input method ");
4969 pr.print(id);
4970 pr.print(": ");
4971 pr.print((enabled == previouslyEnabled) ? "already " : "now ");
4972 pr.println(enabled ? "enabled" : "disabled");
4973 return ShellCommandResult.SUCCESS;
4974 }
4975
4976 /**
4977 * Handles {@code adb shell ime set}.
4978 * @param shellCommand {@link ShellCommand} object that is handling this command.
4979 * @return Exit code of the command.
4980 */
4981 @BinderThread
4982 @ShellCommandResult
4983 private int handleShellCommandSetInputMethod(@NonNull ShellCommand shellCommand) {
4984 final String id = shellCommand.getNextArgRequired();
4985 setInputMethod(null, id);
4986 final PrintWriter pr = shellCommand.getOutPrintWriter();
4987 pr.print("Input method ");
4988 pr.print(id);
4989 pr.println(" selected");
4990 return ShellCommandResult.SUCCESS;
4991 }
Yohei Yukawacc97ebd2017-12-11 17:54:43 -08004992
4993 /**
4994 * Handles {@code adb shell ime reset-ime}.
4995 * @param shellCommand {@link ShellCommand} object that is handling this command.
4996 * @return Exit code of the command.
4997 */
4998 @BinderThread
4999 @ShellCommandResult
5000 @RequiresPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
5001 private int handleShellCommandResetInputMethod(@NonNull ShellCommand shellCommand) {
5002 if (!calledFromValidUser()) {
5003 shellCommand.getErrPrintWriter().print(
5004 "Must be called from the foreground user or with INTERACT_ACROSS_USERS_FULL");
5005 return ShellCommandResult.FAILURE;
5006 }
5007 synchronized (mMethodMap) {
5008 if (mContext.checkCallingOrSelfPermission(
5009 android.Manifest.permission.WRITE_SECURE_SETTINGS)
5010 != PackageManager.PERMISSION_GRANTED) {
5011 shellCommand.getErrPrintWriter().print(
5012 "Caller must have WRITE_SECURE_SETTINGS permission");
5013 throw new SecurityException(
5014 "Requires permission "
5015 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
5016 }
5017 final String nextIme;
5018 final List<InputMethodInfo> nextEnabledImes;
5019 final long ident = Binder.clearCallingIdentity();
5020 try {
5021 synchronized (mMethodMap) {
5022 hideCurrentInputLocked(0, null);
5023 unbindCurrentMethodLocked(false);
5024 // Reset the current IME
5025 resetSelectedInputMethodAndSubtypeLocked(null);
5026 // Also reset the settings of the current IME
5027 mSettings.putSelectedInputMethod(null);
5028 // Disable all enabled IMEs.
5029 {
5030 final ArrayList<InputMethodInfo> enabledImes =
5031 mSettings.getEnabledInputMethodListLocked();
5032 final int N = enabledImes.size();
5033 for (int i = 0; i < N; ++i) {
5034 setInputMethodEnabledLocked(enabledImes.get(i).getId(), false);
5035 }
5036 }
5037 // Re-enable with default enabled IMEs.
5038 {
5039 final ArrayList<InputMethodInfo> defaultEnabledIme =
5040 InputMethodUtils.getDefaultEnabledImes(mContext, mMethodList);
5041 final int N = defaultEnabledIme.size();
5042 for (int i = 0; i < N; ++i) {
5043 setInputMethodEnabledLocked(defaultEnabledIme.get(i).getId(), true);
5044 }
5045 }
5046 updateInputMethodsFromSettingsLocked(true /* enabledMayChange */);
5047 InputMethodUtils.setNonSelectedSystemImesDisabledUntilUsed(mIPackageManager,
5048 mSettings.getEnabledInputMethodListLocked(),
5049 mSettings.getCurrentUserId(),
5050 mContext.getBasePackageName());
5051 nextIme = mSettings.getSelectedInputMethod();
5052 nextEnabledImes = getEnabledInputMethodList();
5053 }
5054 } finally {
5055 Binder.restoreCallingIdentity(ident);
5056 }
5057 final PrintWriter pr = shellCommand.getOutPrintWriter();
5058 pr.println("Reset current and enabled IMEs");
5059 pr.println("Newly selected IME:");
5060 pr.print(" "); pr.println(nextIme);
5061 pr.println("Newly enabled IMEs:");
5062 {
5063 final int N = nextEnabledImes.size();
5064 for (int i = 0; i < N; ++i) {
5065 pr.print(" ");
5066 pr.println(nextEnabledImes.get(i).getId());
5067 }
5068 }
5069 return ShellCommandResult.SUCCESS;
5070 }
5071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005072}