blob: 44bf2a57912eb362688356bc4d212d9bfd2afa7d [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 updateFromSettingsLocked(true);
1548 InputMethodUtils.setNonSelectedSystemImesDisabledUntilUsed(mIPackageManager,
1549 mSettings.getEnabledInputMethodListLocked(), currentUserId,
1550 mContext.getBasePackageName());
1551
Dianne Hackborncc278702009-09-02 23:07:23 -07001552 try {
1553 startInputInnerLocked();
1554 } catch (RuntimeException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001555 Slog.w(TAG, "Unexpected exception", e);
Dianne Hackborncc278702009-09-02 23:07:23 -07001556 }
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001557 }
1558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001560
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001561 // ---------------------------------------------------------------------------------------
1562 // Check whether or not this is a valid IPC. Assumes an IPC is valid when either
1563 // 1) it comes from the system process
1564 // 2) the calling process' user id is identical to the current user id IMMS thinks.
1565 private boolean calledFromValidUser() {
1566 final int uid = Binder.getCallingUid();
1567 final int userId = UserHandle.getUserId(uid);
1568 if (DEBUG) {
1569 Slog.d(TAG, "--- calledFromForegroundUserOrSystemProcess ? "
1570 + "calling uid = " + uid + " system uid = " + Process.SYSTEM_UID
1571 + " calling userId = " + userId + ", foreground user id = "
Satoshi Kataoka87c29142013-07-31 23:11:54 +09001572 + mSettings.getCurrentUserId() + ", calling pid = " + Binder.getCallingPid()
1573 + InputMethodUtils.getApiCallStack());
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001574 }
Kenny Guy2a764942014-04-02 13:29:20 +01001575 if (uid == Process.SYSTEM_UID || mSettings.isCurrentProfile(userId)) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001576 return true;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001577 }
Satoshi Kataoka135e5fb2012-09-28 18:25:06 +09001578
1579 // Caveat: A process which has INTERACT_ACROSS_USERS_FULL gets results for the
1580 // foreground user, not for the user of that process. Accordingly InputMethodManagerService
1581 // must not manage background users' states in any functions.
1582 // Note that privacy-sensitive IPCs, such as setInputMethod, are still securely guarded
1583 // by a token.
1584 if (mContext.checkCallingOrSelfPermission(
1585 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1586 == PackageManager.PERMISSION_GRANTED) {
1587 if (DEBUG) {
1588 Slog.d(TAG, "--- Access granted because the calling process has "
1589 + "the INTERACT_ACROSS_USERS_FULL permission");
1590 }
1591 return true;
1592 }
Yohei Yukawad0332832017-02-01 13:59:43 -08001593 // TODO(b/34886274): The semantics of this verification is actually not well-defined.
Seigo Nonakae27dc2b2015-08-14 18:21:27 -07001594 Slog.w(TAG, "--- IPC called from background users. Ignore. callers="
1595 + Debug.getCallers(10));
Satoshi Kataoka135e5fb2012-09-28 18:25:06 +09001596 return false;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001597 }
1598
Yohei Yukawa22c97be2014-06-04 19:43:36 +09001599
1600 /**
1601 * Returns true iff the caller is identified to be the current input method with the token.
1602 * @param token The window token given to the input method when it was started.
1603 * @return true if and only if non-null valid token is specified.
1604 */
Yohei Yukawad0332832017-02-01 13:59:43 -08001605 private boolean calledWithValidToken(@Nullable IBinder token) {
1606 if (token == null && Binder.getCallingPid() == Process.myPid()) {
1607 if (DEBUG) {
1608 // TODO(b/34851776): Basically it's the caller's fault if we reach here.
1609 Slog.d(TAG, "Bug 34851776 is detected callers=" + Debug.getCallers(10));
1610 }
1611 return false;
1612 }
1613 if (token == null || token != mCurToken) {
1614 // TODO(b/34886274): The semantics of this verification is actually not well-defined.
1615 Slog.e(TAG, "Ignoring " + Debug.getCaller() + " due to an invalid token."
1616 + " uid:" + Binder.getCallingUid() + " token:" + token);
Yohei Yukawa22c97be2014-06-04 19:43:36 +09001617 return false;
1618 }
1619 return true;
1620 }
1621
Yohei Yukawaf80087c2018-05-21 09:47:53 -07001622 @GuardedBy("mMethodMap")
1623 private boolean bindCurrentInputMethodServiceLocked(
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001624 Intent service, ServiceConnection conn, int flags) {
1625 if (service == null || conn == null) {
1626 Slog.e(TAG, "--- bind failed: service = " + service + ", conn = " + conn);
1627 return false;
1628 }
Yohei Yukawaf80087c2018-05-21 09:47:53 -07001629 if (mBindInstantServiceAllowed) {
1630 flags |= Context.BIND_ALLOW_INSTANT;
1631 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08001632 return mContext.bindServiceAsUser(service, conn, flags,
1633 new UserHandle(mSettings.getCurrentUserId()));
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001634 }
1635
satoke7c6998e2011-06-03 17:57:59 +09001636 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 public List<InputMethodInfo> getInputMethodList() {
Tarandeep Singh89a6c482017-11-21 14:26:11 -08001638 return getInputMethodList(false /* isVrOnly */);
1639 }
1640
1641 public List<InputMethodInfo> getVrInputMethodList() {
1642 return getInputMethodList(true /* isVrOnly */);
1643 }
1644
1645 private List<InputMethodInfo> getInputMethodList(final boolean isVrOnly) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001646 // TODO: Make this work even for non-current users?
1647 if (!calledFromValidUser()) {
1648 return Collections.emptyList();
1649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 synchronized (mMethodMap) {
Tarandeep Singh89a6c482017-11-21 14:26:11 -08001651 ArrayList<InputMethodInfo> methodList = new ArrayList<>();
1652 for (InputMethodInfo info : mMethodList) {
1653
1654 if (info.isVrOnly() == isVrOnly) {
1655 methodList.add(info);
1656 }
1657 }
1658 return methodList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 }
1660 }
1661
satoke7c6998e2011-06-03 17:57:59 +09001662 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 public List<InputMethodInfo> getEnabledInputMethodList() {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001664 // TODO: Make this work even for non-current users?
1665 if (!calledFromValidUser()) {
1666 return Collections.emptyList();
1667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 synchronized (mMethodMap) {
satokd87c2592010-09-29 11:52:06 +09001669 return mSettings.getEnabledInputMethodListLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 }
1671 }
1672
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09001673 /**
Satoshi Kataokab3c21ac2013-08-07 15:43:29 +09001674 * @param imiId if null, returns enabled subtypes for the current imi
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09001675 * @return enabled subtypes of the specified imi
1676 */
satoke7c6998e2011-06-03 17:57:59 +09001677 @Override
Satoshi Kataokab3c21ac2013-08-07 15:43:29 +09001678 public List<InputMethodSubtype> getEnabledInputMethodSubtypeList(String imiId,
satok16331c82010-12-20 23:48:46 +09001679 boolean allowsImplicitlySelectedSubtypes) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001680 // TODO: Make this work even for non-current users?
1681 if (!calledFromValidUser()) {
Yohei Yukawab0377bb2015-08-10 21:06:30 -07001682 return Collections.emptyList();
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001683 }
satok67ddf9c2010-11-17 09:45:54 +09001684 synchronized (mMethodMap) {
Satoshi Kataokab3c21ac2013-08-07 15:43:29 +09001685 final InputMethodInfo imi;
1686 if (imiId == null && mCurMethodId != null) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09001687 imi = mMethodMap.get(mCurMethodId);
Satoshi Kataokab3c21ac2013-08-07 15:43:29 +09001688 } else {
1689 imi = mMethodMap.get(imiId);
1690 }
1691 if (imi == null) {
Yohei Yukawab0377bb2015-08-10 21:06:30 -07001692 return Collections.emptyList();
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09001693 }
1694 return mSettings.getEnabledInputMethodSubtypeListLocked(
1695 mContext, imi, allowsImplicitlySelectedSubtypes);
satok67ddf9c2010-11-17 09:45:54 +09001696 }
1697 }
1698
satoke7c6998e2011-06-03 17:57:59 +09001699 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 public void addClient(IInputMethodClient client,
1701 IInputContext inputContext, int uid, int pid) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001702 if (!calledFromValidUser()) {
1703 return;
1704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 synchronized (mMethodMap) {
1706 mClients.put(client.asBinder(), new ClientState(client,
1707 inputContext, uid, pid));
1708 }
1709 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001710
satoke7c6998e2011-06-03 17:57:59 +09001711 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 public void removeClient(IInputMethodClient client) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001713 if (!calledFromValidUser()) {
1714 return;
1715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 synchronized (mMethodMap) {
Jeff Brownc28867a2013-03-26 15:42:39 -07001717 ClientState cs = mClients.remove(client.asBinder());
1718 if (cs != null) {
1719 clearClientSessionLocked(cs);
Yohei Yukawa072b1b52015-11-18 15:54:34 -08001720 if (mCurClient == cs) {
Tarandeep Singh93c00cea2018-02-16 14:31:17 -08001721 if (mBoundToMethod) {
1722 mBoundToMethod = false;
1723 if (mCurMethod != null) {
1724 executeOrSendMessage(mCurMethod, mCaller.obtainMessageO(
1725 MSG_UNBIND_INPUT, mCurMethod));
1726 }
1727 }
Yohei Yukawa072b1b52015-11-18 15:54:34 -08001728 mCurClient = null;
1729 }
Yohei Yukawae39d4ed2015-11-19 03:38:49 -08001730 if (mCurFocusedWindowClient == cs) {
1731 mCurFocusedWindowClient = null;
1732 }
Jeff Brownc28867a2013-03-26 15:42:39 -07001733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 }
1735 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 void executeOrSendMessage(IInterface target, Message msg) {
1738 if (target.asBinder() instanceof Binder) {
1739 mCaller.sendMessage(msg);
1740 } else {
1741 handleMessage(msg);
1742 msg.recycle();
1743 }
1744 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001745
Yohei Yukawa33e81792015-11-17 21:14:42 -08001746 void unbindCurrentClientLocked(
1747 /* @InputMethodClient.UnbindReason */ final int unbindClientReason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 if (mCurClient != null) {
Yohei Yukawa35d3f372015-11-25 11:07:19 -08001749 if (DEBUG) Slog.v(TAG, "unbindCurrentInputLocked: client="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 + mCurClient.client.asBinder());
1751 if (mBoundToMethod) {
1752 mBoundToMethod = false;
1753 if (mCurMethod != null) {
1754 executeOrSendMessage(mCurMethod, mCaller.obtainMessageO(
1755 MSG_UNBIND_INPUT, mCurMethod));
1756 }
1757 }
Dianne Hackborna6e41342012-05-22 16:30:34 -07001758
Yohei Yukawa2bc66172017-02-08 11:13:25 -08001759 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIIO(
1760 MSG_SET_ACTIVE, 0, 0, mCurClient));
Yohei Yukawa33e81792015-11-17 21:14:42 -08001761 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIIO(
1762 MSG_UNBIND_CLIENT, mCurSeq, unbindClientReason, mCurClient.client));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763 mCurClient.sessionRequested = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 mCurClient = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001765
The Android Open Source Project10592532009-03-18 17:39:46 -07001766 hideInputMethodMenuLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 }
1768 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 private int getImeShowFlags() {
1771 int flags = 0;
1772 if (mShowForced) {
1773 flags |= InputMethod.SHOW_FORCED
1774 | InputMethod.SHOW_EXPLICIT;
1775 } else if (mShowExplicitlyRequested) {
1776 flags |= InputMethod.SHOW_EXPLICIT;
1777 }
1778 return flags;
1779 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 private int getAppShowFlags() {
1782 int flags = 0;
1783 if (mShowForced) {
1784 flags |= InputMethodManager.SHOW_FORCED;
1785 } else if (!mShowExplicitlyRequested) {
1786 flags |= InputMethodManager.SHOW_IMPLICIT;
1787 }
1788 return flags;
1789 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001790
Andreas Gampea36dc622018-02-05 17:19:22 -08001791 @GuardedBy("mMethodMap")
Yohei Yukawa2553e482017-12-15 15:47:33 -08001792 @NonNull
Yohei Yukawa87ca8402017-02-07 00:13:14 -08001793 InputBindResult attachNewInputLocked(
1794 /* @InputMethodClient.StartInputReason */ final int startInputReason, boolean initial) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 if (!mBoundToMethod) {
1796 executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
1797 MSG_BIND_INPUT, mCurMethod, mCurClient.binding));
1798 mBoundToMethod = true;
1799 }
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08001800
1801 final Binder startInputToken = new Binder();
Yohei Yukawa357b2f62017-02-14 09:40:03 -08001802 final StartInputInfo info = new StartInputInfo(mCurToken, mCurId, startInputReason,
1803 !initial, mCurFocusedWindow, mCurAttribute, mCurFocusedWindowSoftInputMode,
1804 mCurSeq);
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08001805 mStartInputMap.put(startInputToken, info);
Yohei Yukawa357b2f62017-02-14 09:40:03 -08001806 mStartInputHistory.addEntry(info);
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08001807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 final SessionState session = mCurClient.curSession;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08001809 executeOrSendMessage(session.method, mCaller.obtainMessageIIOOOO(
Yohei Yukawaf7526b52017-02-11 20:57:10 -08001810 MSG_START_INPUT, mCurInputContextMissingMethods, initial ? 0 : 1 /* restarting */,
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08001811 startInputToken, session, mCurInputContext, mCurAttribute));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 if (mShowRequested) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001813 if (DEBUG) Slog.v(TAG, "Attach new input asks to show input");
The Android Open Source Project4df24232009-03-05 14:34:35 -08001814 showCurrentInputLocked(getAppShowFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08001816 return new InputBindResult(InputBindResult.ResultCode.SUCCESS_WITH_IME_SESSION,
1817 session.session, (session.channel != null ? session.channel.dup() : null),
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09001818 mCurId, mCurSeq, mCurUserActionNotificationSequenceNumber);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001820
Andreas Gampea36dc622018-02-05 17:19:22 -08001821 @GuardedBy("mMethodMap")
Yohei Yukawa2553e482017-12-15 15:47:33 -08001822 @NonNull
Yohei Yukawa35d3f372015-11-25 11:07:19 -08001823 InputBindResult startInputLocked(
1824 /* @InputMethodClient.StartInputReason */ final int startInputReason,
Yohei Yukawa19a80a12016-03-14 22:57:37 -07001825 IInputMethodClient client, IInputContext inputContext,
1826 /* @InputConnectionInspector.missingMethods */ final int missingMethods,
Yohei Yukawa74750f22016-03-22 12:54:22 -07001827 @Nullable EditorInfo attribute, int controlFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 // If no method is currently selected, do nothing.
1829 if (mCurMethodId == null) {
Yohei Yukawa2553e482017-12-15 15:47:33 -08001830 return InputBindResult.NO_IME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 ClientState cs = mClients.get(client.asBinder());
1834 if (cs == null) {
1835 throw new IllegalArgumentException("unknown client "
1836 + client.asBinder());
1837 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001838
Yohei Yukawa74750f22016-03-22 12:54:22 -07001839 if (attribute == null) {
1840 Slog.w(TAG, "Ignoring startInput with null EditorInfo."
1841 + " uid=" + cs.uid + " pid=" + cs.pid);
Yohei Yukawa2553e482017-12-15 15:47:33 -08001842 return InputBindResult.NULL_EDITOR_INFO;
Yohei Yukawa74750f22016-03-22 12:54:22 -07001843 }
1844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 try {
1846 if (!mIWindowManager.inputMethodClientHasFocus(cs.client)) {
1847 // Check with the window manager to make sure this client actually
1848 // has a window with focus. If not, reject. This is thread safe
1849 // because if the focus changes some time before or after, the
1850 // next client receiving focus that has any interest in input will
1851 // be calling through here after that change happens.
Yohei Yukawad0332832017-02-01 13:59:43 -08001852 if (DEBUG) {
1853 Slog.w(TAG, "Starting input on non-focused client " + cs.client
1854 + " (uid=" + cs.uid + " pid=" + cs.pid + ")");
1855 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08001856 return InputBindResult.NOT_IME_TARGET_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 }
1858 } catch (RemoteException e) {
1859 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001860
Yohei Yukawa19a80a12016-03-14 22:57:37 -07001861 return startInputUncheckedLocked(cs, inputContext, missingMethods, attribute,
Yohei Yukawa87ca8402017-02-07 00:13:14 -08001862 controlFlags, startInputReason);
Dianne Hackborn7663d802012-02-24 13:08:49 -08001863 }
1864
Andreas Gampea36dc622018-02-05 17:19:22 -08001865 @GuardedBy("mMethodMap")
Yohei Yukawa2553e482017-12-15 15:47:33 -08001866 @NonNull
Yohei Yukawa35d3f372015-11-25 11:07:19 -08001867 InputBindResult startInputUncheckedLocked(@NonNull ClientState cs, IInputContext inputContext,
Yohei Yukawa19a80a12016-03-14 22:57:37 -07001868 /* @InputConnectionInspector.missingMethods */ final int missingMethods,
Yohei Yukawa87ca8402017-02-07 00:13:14 -08001869 @NonNull EditorInfo attribute, int controlFlags,
1870 /* @InputMethodClient.StartInputReason */ final int startInputReason) {
Dianne Hackborn7663d802012-02-24 13:08:49 -08001871 // If no method is currently selected, do nothing.
1872 if (mCurMethodId == null) {
Yohei Yukawa2553e482017-12-15 15:47:33 -08001873 return InputBindResult.NO_IME;
Dianne Hackborn7663d802012-02-24 13:08:49 -08001874 }
1875
Yohei Yukawad57ba672015-06-08 16:39:46 -07001876 if (!InputMethodUtils.checkIfPackageBelongsToUid(mAppOpsManager, cs.uid,
1877 attribute.packageName)) {
1878 Slog.e(TAG, "Rejecting this client as it reported an invalid package name."
1879 + " uid=" + cs.uid + " package=" + attribute.packageName);
Yohei Yukawa2553e482017-12-15 15:47:33 -08001880 return InputBindResult.INVALID_PACKAGE_NAME;
Yohei Yukawa0f3ad12015-04-06 16:48:24 -07001881 }
1882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 if (mCurClient != cs) {
John Spurlocke0980502013-10-25 11:59:29 -04001884 // Was the keyguard locked when switching over to the new client?
1885 mCurClientInKeyguard = isKeyguardLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 // If the client is changing, we need to switch over to the new
1887 // one.
Yohei Yukawa33e81792015-11-17 21:14:42 -08001888 unbindCurrentClientLocked(InputMethodClient.UNBIND_REASON_SWITCH_CLIENT);
Yohei Yukawa35d3f372015-11-25 11:07:19 -08001889 if (DEBUG) Slog.v(TAG, "switching to client: client="
John Spurlocke0980502013-10-25 11:59:29 -04001890 + cs.client.asBinder() + " keyguard=" + mCurClientInKeyguard);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891
1892 // If the screen is on, inform the new client it is active
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07001893 if (mIsInteractive) {
tiansiming [田思明]e102c972018-04-17 18:15:33 +08001894 executeOrSendMessage(cs.client, mCaller.obtainMessageIO(MSG_SET_ACTIVE, 1, cs));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895 }
1896 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 // Bump up the sequence for this client and attach it.
1899 mCurSeq++;
1900 if (mCurSeq <= 0) mCurSeq = 1;
1901 mCurClient = cs;
1902 mCurInputContext = inputContext;
Yohei Yukawa19a80a12016-03-14 22:57:37 -07001903 mCurInputContextMissingMethods = missingMethods;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 mCurAttribute = attribute;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 // Check if the input method is changing.
1907 if (mCurId != null && mCurId.equals(mCurMethodId)) {
1908 if (cs.curSession != null) {
1909 // Fast case: if we are already connected to the input method,
1910 // then just return it.
Yohei Yukawa87ca8402017-02-07 00:13:14 -08001911 return attachNewInputLocked(startInputReason,
Dianne Hackborn7663d802012-02-24 13:08:49 -08001912 (controlFlags&InputMethodManager.CONTROL_START_INITIAL) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 }
1914 if (mHaveConnection) {
1915 if (mCurMethod != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916 // Return to client, and we will get back with it when
1917 // we have had a session made for it.
Jeff Brownc28867a2013-03-26 15:42:39 -07001918 requestClientSessionLocked(cs);
Yohei Yukawa2553e482017-12-15 15:47:33 -08001919 return new InputBindResult(
1920 InputBindResult.ResultCode.SUCCESS_WAITING_IME_SESSION,
1921 null, null, mCurId, mCurSeq,
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09001922 mCurUserActionNotificationSequenceNumber);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 } else if (SystemClock.uptimeMillis()
1924 < (mLastBindTime+TIME_TO_RECONNECT)) {
1925 // In this case we have connected to the service, but
1926 // don't yet have its interface. If it hasn't been too
1927 // long since we did the connection, we'll return to
1928 // the client and wait to get the service interface so
1929 // we can report back. If it has been too long, we want
1930 // to fall through so we can try a disconnect/reconnect
1931 // to see if we can get back in touch with the service.
Yohei Yukawa2553e482017-12-15 15:47:33 -08001932 return new InputBindResult(
1933 InputBindResult.ResultCode.SUCCESS_WAITING_IME_BINDING,
1934 null, null, mCurId, mCurSeq,
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09001935 mCurUserActionNotificationSequenceNumber);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001937 EventLog.writeEvent(EventLogTags.IMF_FORCE_RECONNECT_IME,
1938 mCurMethodId, SystemClock.uptimeMillis()-mLastBindTime, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 }
1940 }
1941 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001942
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001943 return startInputInnerLocked();
1944 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001945
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001946 InputBindResult startInputInnerLocked() {
1947 if (mCurMethodId == null) {
Yohei Yukawa2553e482017-12-15 15:47:33 -08001948 return InputBindResult.NO_IME;
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001949 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001950
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001951 if (!mSystemReady) {
1952 // If the system is not yet ready, we shouldn't be running third
1953 // party code.
Yohei Yukawa2553e482017-12-15 15:47:33 -08001954 return new InputBindResult(
1955 InputBindResult.ResultCode.ERROR_SYSTEM_NOT_READY,
1956 null, null, mCurMethodId, mCurSeq,
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09001957 mCurUserActionNotificationSequenceNumber);
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07001958 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 InputMethodInfo info = mMethodMap.get(mCurMethodId);
1961 if (info == null) {
1962 throw new IllegalArgumentException("Unknown id: " + mCurMethodId);
1963 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001964
Yohei Yukawabc7b5262015-11-17 17:38:41 -08001965 unbindCurrentMethodLocked(true);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 mCurIntent = new Intent(InputMethod.SERVICE_INTERFACE);
1968 mCurIntent.setComponent(info.getComponent());
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07001969 mCurIntent.putExtra(Intent.EXTRA_CLIENT_LABEL,
1970 com.android.internal.R.string.input_method_binding_label);
1971 mCurIntent.putExtra(Intent.EXTRA_CLIENT_INTENT, PendingIntent.getActivity(
1972 mContext, 0, new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS), 0));
Yohei Yukawaf80087c2018-05-21 09:47:53 -07001973 if (bindCurrentInputMethodServiceLocked(mCurIntent, this, IME_CONNECTION_BIND_FLAGS)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 mLastBindTime = SystemClock.uptimeMillis();
1975 mHaveConnection = true;
1976 mCurId = info.getId();
1977 mCurToken = new Binder();
1978 try {
Yohei Yukawad0332832017-02-01 13:59:43 -08001979 if (DEBUG) Slog.v(TAG, "Adding window token: " + mCurToken);
Wale Ogunwaleac2561e2016-11-01 15:43:46 -07001980 mIWindowManager.addWindowToken(mCurToken, TYPE_INPUT_METHOD, DEFAULT_DISPLAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981 } catch (RemoteException e) {
1982 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08001983 return new InputBindResult(
1984 InputBindResult.ResultCode.SUCCESS_WAITING_IME_BINDING,
1985 null, null, mCurId, mCurSeq,
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09001986 mCurUserActionNotificationSequenceNumber);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08001988 mCurIntent = null;
1989 Slog.w(TAG, "Failure connecting to input method service: " + mCurIntent);
1990 return InputBindResult.IME_NOT_CONNECTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001992
Yohei Yukawa2553e482017-12-15 15:47:33 -08001993 @NonNull
Yohei Yukawa05c25f82016-02-22 12:41:17 -08001994 private InputBindResult startInput(
Yohei Yukawa35d3f372015-11-25 11:07:19 -08001995 /* @InputMethodClient.StartInputReason */ final int startInputReason,
Yohei Yukawa19a80a12016-03-14 22:57:37 -07001996 IInputMethodClient client, IInputContext inputContext,
1997 /* @InputConnectionInspector.missingMethods */ final int missingMethods,
Yohei Yukawa74750f22016-03-22 12:54:22 -07001998 @Nullable EditorInfo attribute, int controlFlags) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09001999 if (!calledFromValidUser()) {
Yohei Yukawa2553e482017-12-15 15:47:33 -08002000 return InputBindResult.INVALID_USER;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002001 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002 synchronized (mMethodMap) {
Yohei Yukawa35d3f372015-11-25 11:07:19 -08002003 if (DEBUG) {
2004 Slog.v(TAG, "startInput: reason="
2005 + InputMethodClient.getStartInputReason(startInputReason)
2006 + " client = " + client.asBinder()
2007 + " inputContext=" + inputContext
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002008 + " missingMethods="
2009 + InputConnectionInspector.getMissingMethodFlagsAsString(missingMethods)
Yohei Yukawa35d3f372015-11-25 11:07:19 -08002010 + " attribute=" + attribute
2011 + " controlFlags=#" + Integer.toHexString(controlFlags));
2012 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 final long ident = Binder.clearCallingIdentity();
2014 try {
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002015 return startInputLocked(startInputReason, client, inputContext, missingMethods,
2016 attribute, controlFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 } finally {
2018 Binder.restoreCallingIdentity(ident);
2019 }
2020 }
2021 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002022
satoke7c6998e2011-06-03 17:57:59 +09002023 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 public void finishInput(IInputMethodClient client) {
2025 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002026
satoke7c6998e2011-06-03 17:57:59 +09002027 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002028 public void onServiceConnected(ComponentName name, IBinder service) {
2029 synchronized (mMethodMap) {
2030 if (mCurIntent != null && name.equals(mCurIntent.getComponent())) {
2031 mCurMethod = IInputMethod.Stub.asInterface(service);
Dianne Hackborncc278702009-09-02 23:07:23 -07002032 if (mCurToken == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002033 Slog.w(TAG, "Service connected without a token!");
Yohei Yukawabc7b5262015-11-17 17:38:41 -08002034 unbindCurrentMethodLocked(false);
Dianne Hackborncc278702009-09-02 23:07:23 -07002035 return;
2036 }
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07002037 if (DEBUG) Slog.v(TAG, "Initiating attach with token: " + mCurToken);
Dianne Hackborncc278702009-09-02 23:07:23 -07002038 executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
2039 MSG_ATTACH_TOKEN, mCurMethod, mCurToken));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 if (mCurClient != null) {
Jeff Brownc28867a2013-03-26 15:42:39 -07002041 clearClientSessionLocked(mCurClient);
2042 requestClientSessionLocked(mCurClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002043 }
2044 }
2045 }
2046 }
2047
Jeff Brownc28867a2013-03-26 15:42:39 -07002048 void onSessionCreated(IInputMethod method, IInputMethodSession session,
2049 InputChannel channel) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 synchronized (mMethodMap) {
2051 if (mCurMethod != null && method != null
2052 && mCurMethod.asBinder() == method.asBinder()) {
2053 if (mCurClient != null) {
Jeff Brownc28867a2013-03-26 15:42:39 -07002054 clearClientSessionLocked(mCurClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002055 mCurClient.curSession = new SessionState(mCurClient,
Jeff Brownc28867a2013-03-26 15:42:39 -07002056 method, session, channel);
Yohei Yukawa87ca8402017-02-07 00:13:14 -08002057 InputBindResult res = attachNewInputLocked(
2058 InputMethodClient.START_INPUT_REASON_SESSION_CREATED_BY_IME, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 if (res.method != null) {
2060 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageOO(
Yohei Yukawa33e81792015-11-17 21:14:42 -08002061 MSG_BIND_CLIENT, mCurClient.client, res));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062 }
Jeff Brownc28867a2013-03-26 15:42:39 -07002063 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 }
2065 }
2066 }
Jeff Brownc28867a2013-03-26 15:42:39 -07002067
2068 // Session abandoned. Close its associated input channel.
2069 channel.dispose();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002071
Yohei Yukawabc7b5262015-11-17 17:38:41 -08002072 void unbindCurrentMethodLocked(boolean savePosition) {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -07002073 if (mVisibleBound) {
2074 mContext.unbindService(mVisibleConnection);
2075 mVisibleBound = false;
2076 }
2077
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002078 if (mHaveConnection) {
2079 mContext.unbindService(this);
2080 mHaveConnection = false;
2081 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002082
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002083 if (mCurToken != null) {
2084 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002085 if (DEBUG) Slog.v(TAG, "Removing window token: " + mCurToken);
Dianne Hackborn2ea9bae2012-11-02 18:43:48 -07002086 if ((mImeWindowVis & InputMethodService.IME_ACTIVE) != 0 && savePosition) {
satoke0a99412012-05-10 02:22:58 +09002087 // The current IME is shown. Hence an IME switch (transition) is happening.
Seigo Nonaka7309b122015-08-17 18:34:13 -07002088 mWindowManagerInternal.saveLastInputMethodWindowForTransition();
satoke0a99412012-05-10 02:22:58 +09002089 }
Wale Ogunwaleac2561e2016-11-01 15:43:46 -07002090 mIWindowManager.removeWindowToken(mCurToken, DEFAULT_DISPLAY);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002091 } catch (RemoteException e) {
2092 }
2093 mCurToken = null;
2094 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002095
The Android Open Source Project10592532009-03-18 17:39:46 -07002096 mCurId = null;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002097 clearCurMethodLocked();
Yohei Yukawabc7b5262015-11-17 17:38:41 -08002098 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002099
Yohei Yukawa33e81792015-11-17 21:14:42 -08002100 void resetCurrentMethodAndClient(
2101 /* @InputMethodClient.UnbindReason */ final int unbindClientReason) {
Yohei Yukawabc7b5262015-11-17 17:38:41 -08002102 mCurMethodId = null;
2103 unbindCurrentMethodLocked(false);
Yohei Yukawa33e81792015-11-17 21:14:42 -08002104 unbindCurrentClientLocked(unbindClientReason);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002105 }
Jeff Brownc28867a2013-03-26 15:42:39 -07002106
2107 void requestClientSessionLocked(ClientState cs) {
2108 if (!cs.sessionRequested) {
2109 if (DEBUG) Slog.v(TAG, "Creating new session for client " + cs);
2110 InputChannel[] channels = InputChannel.openInputChannelPair(cs.toString());
2111 cs.sessionRequested = true;
2112 executeOrSendMessage(mCurMethod, mCaller.obtainMessageOOO(
2113 MSG_CREATE_SESSION, mCurMethod, channels[1],
2114 new MethodCallback(this, mCurMethod, channels[0])));
2115 }
2116 }
2117
2118 void clearClientSessionLocked(ClientState cs) {
2119 finishSessionLocked(cs.curSession);
2120 cs.curSession = null;
2121 cs.sessionRequested = false;
2122 }
2123
2124 private void finishSessionLocked(SessionState sessionState) {
2125 if (sessionState != null) {
2126 if (sessionState.session != null) {
2127 try {
2128 sessionState.session.finishSession();
2129 } catch (RemoteException e) {
2130 Slog.w(TAG, "Session failed to close due to remote exception", e);
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002131 updateSystemUiLocked(mCurToken, 0 /* vis */, mBackDisposition);
Jeff Brownc28867a2013-03-26 15:42:39 -07002132 }
2133 sessionState.session = null;
2134 }
2135 if (sessionState.channel != null) {
2136 sessionState.channel.dispose();
2137 sessionState.channel = null;
Devin Taylor0c33ed22010-02-23 13:26:46 -06002138 }
2139 }
2140 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002141
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002142 void clearCurMethodLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143 if (mCurMethod != null) {
2144 for (ClientState cs : mClients.values()) {
Jeff Brownc28867a2013-03-26 15:42:39 -07002145 clearClientSessionLocked(cs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002146 }
Devin Taylor0c33ed22010-02-23 13:26:46 -06002147
Jeff Brownc28867a2013-03-26 15:42:39 -07002148 finishSessionLocked(mEnabledSession);
Devin Taylor0c33ed22010-02-23 13:26:46 -06002149 mEnabledSession = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002150 mCurMethod = null;
2151 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07002152 if (mStatusBar != null) {
Jason Monk3e189872016-01-12 09:10:34 -05002153 mStatusBar.setIconVisibility(mSlotIme, false);
Dianne Hackborn661cd522011-08-22 00:26:20 -07002154 }
Yohei Yukawa2bc66172017-02-08 11:13:25 -08002155 mInFullscreenMode = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002156 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002157
satoke7c6998e2011-06-03 17:57:59 +09002158 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002159 public void onServiceDisconnected(ComponentName name) {
Yohei Yukawa817d5f72017-01-04 20:15:02 -08002160 // Note that mContext.unbindService(this) does not trigger this. Hence if we are here the
2161 // disconnection is not intended by IMMS (e.g. triggered because the current IMS crashed),
2162 // which is irregular but can eventually happen for everyone just by continuing using the
2163 // device. Thus it is important to make sure that all the internal states are properly
2164 // refreshed when this method is called back. Running
2165 // adb install -r <APK that implements the current IME>
2166 // would be a good way to trigger such a situation.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002167 synchronized (mMethodMap) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002168 if (DEBUG) Slog.v(TAG, "Service disconnected: " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002169 + " mCurIntent=" + mCurIntent);
2170 if (mCurMethod != null && mCurIntent != null
2171 && name.equals(mCurIntent.getComponent())) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002172 clearCurMethodLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173 // We consider this to be a new bind attempt, since the system
2174 // should now try to restart the service for us.
2175 mLastBindTime = SystemClock.uptimeMillis();
2176 mShowRequested = mInputShown;
2177 mInputShown = false;
Yohei Yukawa817d5f72017-01-04 20:15:02 -08002178 unbindCurrentClientLocked(InputMethodClient.UNBIND_REASON_DISCONNECT_IME);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002179 }
2180 }
2181 }
2182
satokf9f01002011-05-19 21:31:50 +09002183 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184 public void updateStatusIcon(IBinder token, String packageName, int iconId) {
Yohei Yukawa59377ca2017-01-31 21:32:26 -08002185 synchronized (mMethodMap) {
2186 if (!calledWithValidToken(token)) {
Yohei Yukawa59377ca2017-01-31 21:32:26 -08002187 return;
2188 }
2189 final long ident = Binder.clearCallingIdentity();
2190 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002191 if (iconId == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002192 if (DEBUG) Slog.d(TAG, "hide the small icon for the input method");
Dianne Hackborn661cd522011-08-22 00:26:20 -07002193 if (mStatusBar != null) {
Jason Monk3e189872016-01-12 09:10:34 -05002194 mStatusBar.setIconVisibility(mSlotIme, false);
Dianne Hackborn661cd522011-08-22 00:26:20 -07002195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002196 } else if (packageName != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002197 if (DEBUG) Slog.d(TAG, "show a small icon for the input method");
Svetoslav Ganov6179ea32011-06-28 01:12:41 -07002198 CharSequence contentDescription = null;
2199 try {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002200 // Use PackageManager to load label
2201 final PackageManager packageManager = mContext.getPackageManager();
Svetoslav Ganov6179ea32011-06-28 01:12:41 -07002202 contentDescription = packageManager.getApplicationLabel(
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002203 mIPackageManager.getApplicationInfo(packageName, 0,
2204 mSettings.getCurrentUserId()));
2205 } catch (RemoteException e) {
Svetoslav Ganov6179ea32011-06-28 01:12:41 -07002206 /* ignore */
2207 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07002208 if (mStatusBar != null) {
Jason Monk3e189872016-01-12 09:10:34 -05002209 mStatusBar.setIcon(mSlotIme, packageName, iconId, 0,
Dianne Hackborn661cd522011-08-22 00:26:20 -07002210 contentDescription != null
2211 ? contentDescription.toString() : null);
Jason Monk3e189872016-01-12 09:10:34 -05002212 mStatusBar.setIconVisibility(mSlotIme, true);
Dianne Hackborn661cd522011-08-22 00:26:20 -07002213 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002214 }
Yohei Yukawa59377ca2017-01-31 21:32:26 -08002215 } finally {
2216 Binder.restoreCallingIdentity(ident);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218 }
2219 }
2220
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002221 private boolean shouldShowImeSwitcherLocked(int visibility) {
satok7cfc0ed2011-06-20 21:29:36 +09002222 if (!mShowOngoingImeSwitcherForPhones) return false;
Jason Monk807ef762014-05-08 15:47:46 -04002223 if (mSwitchingDialog != null) return false;
Yohei Yukawad2bc3092017-07-31 15:37:14 -07002224 if (mWindowManagerInternal.isKeyguardShowingAndNotOccluded()
2225 && mKeyguardManager != null && mKeyguardManager.isKeyguardSecure()) return false;
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002226 if ((visibility & InputMethodService.IME_ACTIVE) == 0) return false;
Seigo Nonaka7309b122015-08-17 18:34:13 -07002227 if (mWindowManagerInternal.isHardKeyboardAvailable()) {
Yohei Yukawafa0e47e2016-04-05 09:55:56 -07002228 if (mHardKeyboardBehavior == HardKeyboardBehavior.WIRELESS_AFFORDANCE) {
2229 // When physical keyboard is attached, we show the ime switcher (or notification if
2230 // NavBar is not available) because SHOW_IME_WITH_HARD_KEYBOARD settings currently
2231 // exists in the IME switcher dialog. Might be OK to remove this condition once
2232 // SHOW_IME_WITH_HARD_KEYBOARD settings finds a good place to live.
2233 return true;
2234 }
Yohei Yukawa89398382016-03-29 11:37:04 -07002235 } else if ((visibility & InputMethodService.IME_VISIBLE) == 0) {
2236 return false;
Yohei Yukawac6c7cd22015-05-12 15:00:33 -07002237 }
Yohei Yukawac6c7cd22015-05-12 15:00:33 -07002238
2239 List<InputMethodInfo> imis = mSettings.getEnabledInputMethodListLocked();
2240 final int N = imis.size();
2241 if (N > 2) return true;
2242 if (N < 1) return false;
2243 int nonAuxCount = 0;
2244 int auxCount = 0;
2245 InputMethodSubtype nonAuxSubtype = null;
2246 InputMethodSubtype auxSubtype = null;
2247 for(int i = 0; i < N; ++i) {
2248 final InputMethodInfo imi = imis.get(i);
2249 final List<InputMethodSubtype> subtypes =
2250 mSettings.getEnabledInputMethodSubtypeListLocked(mContext, imi, true);
2251 final int subtypeCount = subtypes.size();
2252 if (subtypeCount == 0) {
2253 ++nonAuxCount;
2254 } else {
2255 for (int j = 0; j < subtypeCount; ++j) {
2256 final InputMethodSubtype subtype = subtypes.get(j);
2257 if (!subtype.isAuxiliary()) {
2258 ++nonAuxCount;
2259 nonAuxSubtype = subtype;
2260 } else {
2261 ++auxCount;
2262 auxSubtype = subtype;
satok7cfc0ed2011-06-20 21:29:36 +09002263 }
2264 }
satok7cfc0ed2011-06-20 21:29:36 +09002265 }
2266 }
Yohei Yukawac6c7cd22015-05-12 15:00:33 -07002267 if (nonAuxCount > 1 || auxCount > 1) {
2268 return true;
2269 } else if (nonAuxCount == 1 && auxCount == 1) {
2270 if (nonAuxSubtype != null && auxSubtype != null
2271 && (nonAuxSubtype.getLocale().equals(auxSubtype.getLocale())
2272 || auxSubtype.overridesImplicitlyEnabledSubtype()
2273 || nonAuxSubtype.overridesImplicitlyEnabledSubtype())
2274 && nonAuxSubtype.containsExtraValueKey(TAG_TRY_SUPPRESSING_IME_SWITCHER)) {
2275 return false;
2276 }
2277 return true;
2278 }
2279 return false;
satok7cfc0ed2011-06-20 21:29:36 +09002280 }
2281
John Spurlocke0980502013-10-25 11:59:29 -04002282 private boolean isKeyguardLocked() {
2283 return mKeyguardManager != null && mKeyguardManager.isKeyguardLocked();
2284 }
2285
Yohei Yukawad6475a62017-04-17 10:35:27 -07002286 @BinderThread
satokdbf29502011-08-25 15:28:23 +09002287 @SuppressWarnings("deprecation")
satokf9f01002011-05-19 21:31:50 +09002288 @Override
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08002289 public void setImeWindowStatus(IBinder token, IBinder startInputToken, int vis,
2290 int backDisposition) {
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002291 if (!calledWithValidToken(token)) {
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002292 return;
2293 }
2294
Yohei Yukawa69e68022017-02-13 12:04:50 -08002295 final StartInputInfo info;
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002296 synchronized (mMethodMap) {
Yohei Yukawa69e68022017-02-13 12:04:50 -08002297 info = mStartInputMap.get(startInputToken);
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002298 mImeWindowVis = vis;
2299 mBackDisposition = backDisposition;
2300 updateSystemUiLocked(token, vis, backDisposition);
2301 }
Yohei Yukawad6475a62017-04-17 10:35:27 -07002302
2303 final boolean dismissImeOnBackKeyPressed;
2304 switch (backDisposition) {
2305 case InputMethodService.BACK_DISPOSITION_WILL_DISMISS:
2306 dismissImeOnBackKeyPressed = true;
2307 break;
2308 case InputMethodService.BACK_DISPOSITION_WILL_NOT_DISMISS:
2309 dismissImeOnBackKeyPressed = false;
2310 break;
2311 default:
2312 case InputMethodService.BACK_DISPOSITION_DEFAULT:
2313 dismissImeOnBackKeyPressed = ((vis & InputMethodService.IME_VISIBLE) != 0);
2314 break;
2315 }
Yohei Yukawaee2a7ed2017-02-15 21:38:57 -08002316 mWindowManagerInternal.updateInputMethodWindowStatus(token,
2317 (vis & InputMethodService.IME_VISIBLE) != 0,
Yohei Yukawad6475a62017-04-17 10:35:27 -07002318 dismissImeOnBackKeyPressed, info != null ? info.mTargetWindow : null);
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002319 }
2320
2321 private void updateSystemUi(IBinder token, int vis, int backDisposition) {
2322 synchronized (mMethodMap) {
2323 updateSystemUiLocked(token, vis, backDisposition);
2324 }
2325 }
2326
2327 // Caution! This method is called in this class. Handle multi-user carefully
2328 private void updateSystemUiLocked(IBinder token, int vis, int backDisposition) {
2329 if (!calledWithValidToken(token)) {
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002330 return;
2331 }
2332
2333 // TODO: Move this clearing calling identity block to setImeWindowStatus after making sure
2334 // all updateSystemUi happens on system previlege.
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002335 final long ident = Binder.clearCallingIdentity();
satok06487a52010-10-29 11:37:18 +09002336 try {
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002337 // apply policy for binder calls
2338 if (vis != 0 && isKeyguardLocked() && !mCurClientInKeyguard) {
2339 vis = 0;
satok06487a52010-10-29 11:37:18 +09002340 }
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002341 // mImeWindowVis should be updated before calling shouldShowImeSwitcherLocked().
2342 final boolean needsToShowImeSwitcher = shouldShowImeSwitcherLocked(vis);
2343 if (mStatusBar != null) {
2344 mStatusBar.setImeWindowStatus(token, vis, backDisposition,
2345 needsToShowImeSwitcher);
2346 }
2347 final InputMethodInfo imi = mMethodMap.get(mCurMethodId);
2348 if (imi != null && needsToShowImeSwitcher) {
2349 // Used to load label
2350 final CharSequence title = mRes.getText(
2351 com.android.internal.R.string.select_input_method);
2352 final CharSequence summary = InputMethodUtils.getImeAndSubtypeDisplayName(
2353 mContext, imi, mCurrentSubtype);
Chris Wren1ce4b6d2015-06-11 10:19:43 -04002354 mImeSwitcherNotification.setContentTitle(title)
2355 .setContentText(summary)
2356 .setContentIntent(mImeSwitchPendingIntent);
Seigo Nonaka7309b122015-08-17 18:34:13 -07002357 try {
2358 if ((mNotificationManager != null)
2359 && !mIWindowManager.hasNavigationBar()) {
2360 if (DEBUG) {
2361 Slog.d(TAG, "--- show notification: label = " + summary);
2362 }
2363 mNotificationManager.notifyAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04002364 SystemMessage.NOTE_SELECT_INPUT_METHOD,
Seigo Nonaka7309b122015-08-17 18:34:13 -07002365 mImeSwitcherNotification.build(), UserHandle.ALL);
2366 mNotificationShown = true;
Dianne Hackborn661cd522011-08-22 00:26:20 -07002367 }
Seigo Nonaka7309b122015-08-17 18:34:13 -07002368 } catch (RemoteException e) {
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002369 }
2370 } else {
2371 if (mNotificationShown && mNotificationManager != null) {
2372 if (DEBUG) {
2373 Slog.d(TAG, "--- hide notification");
satok7cfc0ed2011-06-20 21:29:36 +09002374 }
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002375 mNotificationManager.cancelAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04002376 SystemMessage.NOTE_SELECT_INPUT_METHOD, UserHandle.ALL);
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002377 mNotificationShown = false;
satok7cfc0ed2011-06-20 21:29:36 +09002378 }
satok06487a52010-10-29 11:37:18 +09002379 }
2380 } finally {
2381 Binder.restoreCallingIdentity(ident);
2382 }
2383 }
2384
satoke7c6998e2011-06-03 17:57:59 +09002385 @Override
satokf9f01002011-05-19 21:31:50 +09002386 public void registerSuggestionSpansForNotification(SuggestionSpan[] spans) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002387 if (!calledFromValidUser()) {
2388 return;
2389 }
satokf9f01002011-05-19 21:31:50 +09002390 synchronized (mMethodMap) {
2391 final InputMethodInfo currentImi = mMethodMap.get(mCurMethodId);
2392 for (int i = 0; i < spans.length; ++i) {
2393 SuggestionSpan ss = spans[i];
satok42c5a162011-05-26 16:46:14 +09002394 if (!TextUtils.isEmpty(ss.getNotificationTargetClassName())) {
satokf9f01002011-05-19 21:31:50 +09002395 mSecureSuggestionSpans.put(ss, currentImi);
2396 }
2397 }
2398 }
2399 }
2400
satoke7c6998e2011-06-03 17:57:59 +09002401 @Override
satokf9f01002011-05-19 21:31:50 +09002402 public boolean notifySuggestionPicked(SuggestionSpan span, String originalString, int index) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002403 if (!calledFromValidUser()) {
2404 return false;
2405 }
satokf9f01002011-05-19 21:31:50 +09002406 synchronized (mMethodMap) {
2407 final InputMethodInfo targetImi = mSecureSuggestionSpans.get(span);
2408 // TODO: Do not send the intent if the process of the targetImi is already dead.
2409 if (targetImi != null) {
2410 final String[] suggestions = span.getSuggestions();
2411 if (index < 0 || index >= suggestions.length) return false;
satok42c5a162011-05-26 16:46:14 +09002412 final String className = span.getNotificationTargetClassName();
satokf9f01002011-05-19 21:31:50 +09002413 final Intent intent = new Intent();
2414 // Ensures that only a class in the original IME package will receive the
2415 // notification.
satok42c5a162011-05-26 16:46:14 +09002416 intent.setClassName(targetImi.getPackageName(), className);
satokf9f01002011-05-19 21:31:50 +09002417 intent.setAction(SuggestionSpan.ACTION_SUGGESTION_PICKED);
2418 intent.putExtra(SuggestionSpan.SUGGESTION_SPAN_PICKED_BEFORE, originalString);
2419 intent.putExtra(SuggestionSpan.SUGGESTION_SPAN_PICKED_AFTER, suggestions[index]);
2420 intent.putExtra(SuggestionSpan.SUGGESTION_SPAN_PICKED_HASHCODE, span.hashCode());
Amith Yamasanif043de92012-10-24 06:42:40 -07002421 final long ident = Binder.clearCallingIdentity();
2422 try {
2423 mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT);
2424 } finally {
2425 Binder.restoreCallingIdentity(ident);
2426 }
satokf9f01002011-05-19 21:31:50 +09002427 return true;
2428 }
2429 }
2430 return false;
2431 }
2432
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08002433 void updateFromSettingsLocked(boolean enabledMayChange) {
Michael Wright7b5a96b2014-08-09 19:28:42 -07002434 updateInputMethodsFromSettingsLocked(enabledMayChange);
2435 updateKeyboardFromSettingsLocked();
2436 }
2437
2438 void updateInputMethodsFromSettingsLocked(boolean enabledMayChange) {
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08002439 if (enabledMayChange) {
2440 List<InputMethodInfo> enabled = mSettings.getEnabledInputMethodListLocked();
2441 for (int i=0; i<enabled.size(); i++) {
2442 // We allow the user to select "disabled until used" apps, so if they
2443 // are enabling one of those here we now need to make it enabled.
2444 InputMethodInfo imm = enabled.get(i);
2445 try {
2446 ApplicationInfo ai = mIPackageManager.getApplicationInfo(imm.getPackageName(),
2447 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
2448 mSettings.getCurrentUserId());
Satoshi Kataoka7987a312013-04-17 18:59:33 +09002449 if (ai != null && ai.enabledSetting
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08002450 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
Satoshi Kataokaed1cdb22013-04-17 16:41:58 +09002451 if (DEBUG) {
2452 Slog.d(TAG, "Update state(" + imm.getId()
2453 + "): DISABLED_UNTIL_USED -> DEFAULT");
2454 }
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08002455 mIPackageManager.setApplicationEnabledSetting(imm.getPackageName(),
2456 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
Dianne Hackborn3fa3c28a2013-03-26 16:15:41 -07002457 PackageManager.DONT_KILL_APP, mSettings.getCurrentUserId(),
2458 mContext.getBasePackageName());
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08002459 }
2460 } catch (RemoteException e) {
2461 }
2462 }
2463 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002464 // We are assuming that whoever is changing DEFAULT_INPUT_METHOD and
2465 // ENABLED_INPUT_METHODS is taking care of keeping them correctly in
2466 // sync, so we will never have a DEFAULT_INPUT_METHOD that is not
2467 // enabled.
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002468 String id = mSettings.getSelectedInputMethod();
satok03eb319a2010-11-11 18:17:42 +09002469 // There is no input method selected, try to choose new applicable input method.
2470 if (TextUtils.isEmpty(id) && chooseNewDefaultIMELocked()) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002471 id = mSettings.getSelectedInputMethod();
satok03eb319a2010-11-11 18:17:42 +09002472 }
2473 if (!TextUtils.isEmpty(id)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002474 try {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09002475 setInputMethodLocked(id, mSettings.getSelectedInputMethodSubtypeId(id));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476 } catch (IllegalArgumentException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002477 Slog.w(TAG, "Unknown input method from prefs: " + id, e);
Yohei Yukawa33e81792015-11-17 21:14:42 -08002478 resetCurrentMethodAndClient(InputMethodClient.UNBIND_REASON_SWITCH_IME_FAILED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002479 }
satokf3db1af2010-11-23 13:34:33 +09002480 mShortcutInputMethodsAndSubtypes.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002481 } else {
2482 // There is no longer an input method set, so stop any current one.
Yohei Yukawa33e81792015-11-17 21:14:42 -08002483 resetCurrentMethodAndClient(InputMethodClient.UNBIND_REASON_NO_IME);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002484 }
Yohei Yukawa3d46bab2014-05-30 18:10:18 +09002485 // Here is not the perfect place to reset the switching controller. Ideally
2486 // mSwitchingController and mSettings should be able to share the same state.
2487 // TODO: Make sure that mSwitchingController and mSettings are sharing the
2488 // the same enabled IMEs list.
2489 mSwitchingController.resetCircularListLocked(mContext);
Michael Wright7b5a96b2014-08-09 19:28:42 -07002490
2491 }
2492
2493 public void updateKeyboardFromSettingsLocked() {
2494 mShowImeWithHardKeyboard = mSettings.isShowImeWithHardKeyboardEnabled();
2495 if (mSwitchingDialog != null
2496 && mSwitchingDialogTitleView != null
2497 && mSwitchingDialog.isShowing()) {
2498 final Switch hardKeySwitch = (Switch)mSwitchingDialogTitleView.findViewById(
2499 com.android.internal.R.id.hard_keyboard_switch);
2500 hardKeySwitch.setChecked(mShowImeWithHardKeyboard);
2501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002502 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002503
satokab751aa2010-09-14 19:17:36 +09002504 /* package */ void setInputMethodLocked(String id, int subtypeId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002505 InputMethodInfo info = mMethodMap.get(id);
2506 if (info == null) {
satok913a8922010-08-26 21:53:41 +09002507 throw new IllegalArgumentException("Unknown id: " + id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002508 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002509
satokd81e9502012-05-21 12:58:45 +09002510 // See if we need to notify a subtype change within the same IME.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002511 if (id.equals(mCurMethodId)) {
satokd81e9502012-05-21 12:58:45 +09002512 final int subtypeCount = info.getSubtypeCount();
2513 if (subtypeCount <= 0) {
2514 return;
satokcd7cd292010-11-20 15:46:23 +09002515 }
satokd81e9502012-05-21 12:58:45 +09002516 final InputMethodSubtype oldSubtype = mCurrentSubtype;
2517 final InputMethodSubtype newSubtype;
2518 if (subtypeId >= 0 && subtypeId < subtypeCount) {
2519 newSubtype = info.getSubtypeAt(subtypeId);
2520 } else {
2521 // If subtype is null, try to find the most applicable one from
2522 // getCurrentInputMethodSubtype.
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002523 newSubtype = getCurrentInputMethodSubtypeLocked();
satokd81e9502012-05-21 12:58:45 +09002524 }
2525 if (newSubtype == null || oldSubtype == null) {
2526 Slog.w(TAG, "Illegal subtype state: old subtype = " + oldSubtype
2527 + ", new subtype = " + newSubtype);
2528 return;
2529 }
2530 if (newSubtype != oldSubtype) {
2531 setSelectedInputMethodAndSubtypeLocked(info, subtypeId, true);
2532 if (mCurMethod != null) {
2533 try {
Seigo Nonakad9eb9112015-05-26 20:54:43 +09002534 updateSystemUiLocked(mCurToken, mImeWindowVis, mBackDisposition);
satokd81e9502012-05-21 12:58:45 +09002535 mCurMethod.changeInputMethodSubtype(newSubtype);
2536 } catch (RemoteException e) {
2537 Slog.w(TAG, "Failed to call changeInputMethodSubtype");
satokab751aa2010-09-14 19:17:36 +09002538 }
2539 }
2540 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 return;
2542 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002543
satokd81e9502012-05-21 12:58:45 +09002544 // Changing to a different IME.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 final long ident = Binder.clearCallingIdentity();
2546 try {
satokab751aa2010-09-14 19:17:36 +09002547 // Set a subtype to this input method.
2548 // subtypeId the name of a subtype which will be set.
satok723a27e2010-11-11 14:58:11 +09002549 setSelectedInputMethodAndSubtypeLocked(info, subtypeId, false);
2550 // mCurMethodId should be updated after setSelectedInputMethodAndSubtypeLocked()
2551 // because mCurMethodId is stored as a history in
2552 // setSelectedInputMethodAndSubtypeLocked().
2553 mCurMethodId = id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07002555 if (LocalServices.getService(ActivityManagerInternal.class).isSystemReady()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 Intent intent = new Intent(Intent.ACTION_INPUT_METHOD_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002557 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 intent.putExtra("input_method_id", id);
Amith Yamasanicd757062012-10-19 18:23:52 -07002559 mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002560 }
Yohei Yukawa33e81792015-11-17 21:14:42 -08002561 unbindCurrentClientLocked(InputMethodClient.UNBIND_REASON_SWITCH_IME);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 } finally {
2563 Binder.restoreCallingIdentity(ident);
2564 }
2565 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002566
satok42c5a162011-05-26 16:46:14 +09002567 @Override
The Android Open Source Project4df24232009-03-05 14:34:35 -08002568 public boolean showSoftInput(IInputMethodClient client, int flags,
2569 ResultReceiver resultReceiver) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002570 if (!calledFromValidUser()) {
2571 return false;
2572 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002573 int uid = Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 long ident = Binder.clearCallingIdentity();
2575 try {
2576 synchronized (mMethodMap) {
2577 if (mCurClient == null || client == null
2578 || mCurClient.client.asBinder() != client.asBinder()) {
2579 try {
2580 // We need to check if this is the current client with
2581 // focus in the window manager, to allow this call to
2582 // be made before input is started in it.
2583 if (!mIWindowManager.inputMethodClientHasFocus(client)) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002584 Slog.w(TAG, "Ignoring showSoftInput of uid " + uid + ": " + client);
The Android Open Source Project4df24232009-03-05 14:34:35 -08002585 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 }
2587 } catch (RemoteException e) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08002588 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 }
2590 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002591
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07002592 if (DEBUG) Slog.v(TAG, "Client requesting input be shown");
The Android Open Source Project4df24232009-03-05 14:34:35 -08002593 return showCurrentInputLocked(flags, resultReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594 }
2595 } finally {
2596 Binder.restoreCallingIdentity(ident);
2597 }
2598 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002599
The Android Open Source Project4df24232009-03-05 14:34:35 -08002600 boolean showCurrentInputLocked(int flags, ResultReceiver resultReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 mShowRequested = true;
Anna Galusza9b278112016-01-04 11:37:37 -08002602 if (mAccessibilityRequestingNoSoftKeyboard) {
2603 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 }
Anna Galusza9b278112016-01-04 11:37:37 -08002605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002606 if ((flags&InputMethodManager.SHOW_FORCED) != 0) {
2607 mShowExplicitlyRequested = true;
2608 mShowForced = true;
Anna Galusza9b278112016-01-04 11:37:37 -08002609 } else if ((flags&InputMethodManager.SHOW_IMPLICIT) == 0) {
2610 mShowExplicitlyRequested = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002611 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002612
Dianne Hackborncc278702009-09-02 23:07:23 -07002613 if (!mSystemReady) {
2614 return false;
2615 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002616
The Android Open Source Project4df24232009-03-05 14:34:35 -08002617 boolean res = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002618 if (mCurMethod != null) {
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07002619 if (DEBUG) Slog.d(TAG, "showCurrentInputLocked: mCurToken=" + mCurToken);
The Android Open Source Project4df24232009-03-05 14:34:35 -08002620 executeOrSendMessage(mCurMethod, mCaller.obtainMessageIOO(
2621 MSG_SHOW_SOFT_INPUT, getImeShowFlags(), mCurMethod,
2622 resultReceiver));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002623 mInputShown = true;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -07002624 if (mHaveConnection && !mVisibleBound) {
Yohei Yukawaf80087c2018-05-21 09:47:53 -07002625 bindCurrentInputMethodServiceLocked(
Yohei Yukawaa67a4592017-03-30 15:57:02 -07002626 mCurIntent, mVisibleConnection, IME_VISIBLE_BIND_FLAGS);
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -07002627 mVisibleBound = true;
2628 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08002629 res = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002630 } else if (mHaveConnection && SystemClock.uptimeMillis()
satok59b424c2011-09-30 17:21:46 +09002631 >= (mLastBindTime+TIME_TO_RECONNECT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002632 // The client has asked to have the input method shown, but
2633 // we have been sitting here too long with a connection to the
2634 // service and no interface received, so let's disconnect/connect
2635 // to try to prod things along.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002636 EventLog.writeEvent(EventLogTags.IMF_FORCE_RECONNECT_IME, mCurMethodId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 SystemClock.uptimeMillis()-mLastBindTime,1);
satok59b424c2011-09-30 17:21:46 +09002638 Slog.w(TAG, "Force disconnect/connect to the IME in showCurrentInputLocked()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002639 mContext.unbindService(this);
Yohei Yukawaf80087c2018-05-21 09:47:53 -07002640 bindCurrentInputMethodServiceLocked(mCurIntent, this, IME_CONNECTION_BIND_FLAGS);
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002641 } else {
2642 if (DEBUG) {
2643 Slog.d(TAG, "Can't show input: connection = " + mHaveConnection + ", time = "
2644 + ((mLastBindTime+TIME_TO_RECONNECT) - SystemClock.uptimeMillis()));
2645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002646 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002647
The Android Open Source Project4df24232009-03-05 14:34:35 -08002648 return res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002650
satok42c5a162011-05-26 16:46:14 +09002651 @Override
The Android Open Source Project4df24232009-03-05 14:34:35 -08002652 public boolean hideSoftInput(IInputMethodClient client, int flags,
2653 ResultReceiver resultReceiver) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002654 if (!calledFromValidUser()) {
2655 return false;
2656 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002657 int uid = Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002658 long ident = Binder.clearCallingIdentity();
2659 try {
2660 synchronized (mMethodMap) {
2661 if (mCurClient == null || client == null
2662 || mCurClient.client.asBinder() != client.asBinder()) {
2663 try {
2664 // We need to check if this is the current client with
2665 // focus in the window manager, to allow this call to
2666 // be made before input is started in it.
2667 if (!mIWindowManager.inputMethodClientHasFocus(client)) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002668 if (DEBUG) Slog.w(TAG, "Ignoring hideSoftInput of uid "
2669 + uid + ": " + client);
The Android Open Source Project4df24232009-03-05 14:34:35 -08002670 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 }
2672 } catch (RemoteException e) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08002673 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674 }
2675 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002676
Joe Onorato8a9b2202010-02-26 18:56:32 -08002677 if (DEBUG) Slog.v(TAG, "Client requesting input be hidden");
The Android Open Source Project4df24232009-03-05 14:34:35 -08002678 return hideCurrentInputLocked(flags, resultReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 }
2680 } finally {
2681 Binder.restoreCallingIdentity(ident);
2682 }
2683 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002684
The Android Open Source Project4df24232009-03-05 14:34:35 -08002685 boolean hideCurrentInputLocked(int flags, ResultReceiver resultReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 if ((flags&InputMethodManager.HIDE_IMPLICIT_ONLY) != 0
2687 && (mShowExplicitlyRequested || mShowForced)) {
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07002688 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 -08002689 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 }
2691 if (mShowForced && (flags&InputMethodManager.HIDE_NOT_ALWAYS) != 0) {
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07002692 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 -08002693 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 }
Seigo Nonakaec928652015-06-10 15:31:20 +09002695
2696 // There is a chance that IMM#hideSoftInput() is called in a transient state where
2697 // IMMS#InputShown is already updated to be true whereas IMMS#mImeWindowVis is still waiting
2698 // to be updated with the new value sent from IME process. Even in such a transient state
2699 // historically we have accepted an incoming call of IMM#hideSoftInput() from the
2700 // application process as a valid request, and have even promised such a behavior with CTS
2701 // since Android Eclair. That's why we need to accept IMM#hideSoftInput() even when only
2702 // IMMS#InputShown indicates that the software keyboard is shown.
2703 // TODO: Clean up, IMMS#mInputShown, IMMS#mImeWindowVis and mShowRequested.
2704 final boolean shouldHideSoftInput = (mCurMethod != null) && (mInputShown ||
2705 (mImeWindowVis & InputMethodService.IME_ACTIVE) != 0);
The Android Open Source Project4df24232009-03-05 14:34:35 -08002706 boolean res;
Seigo Nonakaec928652015-06-10 15:31:20 +09002707 if (shouldHideSoftInput) {
2708 // The IME will report its visible state again after the following message finally
2709 // delivered to the IME process as an IPC. Hence the inconsistency between
2710 // IMMS#mInputShown and IMMS#mImeWindowVis should be resolved spontaneously in
2711 // the final state.
The Android Open Source Project4df24232009-03-05 14:34:35 -08002712 executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
2713 MSG_HIDE_SOFT_INPUT, mCurMethod, resultReceiver));
2714 res = true;
2715 } else {
2716 res = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002717 }
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -07002718 if (mHaveConnection && mVisibleBound) {
2719 mContext.unbindService(mVisibleConnection);
2720 mVisibleBound = false;
2721 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002722 mInputShown = false;
2723 mShowRequested = false;
2724 mShowExplicitlyRequested = false;
2725 mShowForced = false;
The Android Open Source Project4df24232009-03-05 14:34:35 -08002726 return res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002727 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002728
Yohei Yukawa2553e482017-12-15 15:47:33 -08002729 @NonNull
satok42c5a162011-05-26 16:46:14 +09002730 @Override
Yohei Yukawa05c25f82016-02-22 12:41:17 -08002731 public InputBindResult startInputOrWindowGainedFocus(
2732 /* @InputMethodClient.StartInputReason */ final int startInputReason,
2733 IInputMethodClient client, IBinder windowToken, int controlFlags, int softInputMode,
Yohei Yukawa74750f22016-03-22 12:54:22 -07002734 int windowFlags, @Nullable EditorInfo attribute, IInputContext inputContext,
Yohei Yukawacf68d522017-12-12 09:33:26 -08002735 /* @InputConnectionInspector.missingMethods */ final int missingMethods,
2736 int unverifiedTargetSdkVersion) {
Yohei Yukawa2553e482017-12-15 15:47:33 -08002737 final InputBindResult result;
Yohei Yukawa05c25f82016-02-22 12:41:17 -08002738 if (windowToken != null) {
Yohei Yukawa2553e482017-12-15 15:47:33 -08002739 result = windowGainedFocus(startInputReason, client, windowToken, controlFlags,
Yohei Yukawacf68d522017-12-12 09:33:26 -08002740 softInputMode, windowFlags, attribute, inputContext, missingMethods,
2741 unverifiedTargetSdkVersion);
Yohei Yukawa05c25f82016-02-22 12:41:17 -08002742 } else {
Yohei Yukawa2553e482017-12-15 15:47:33 -08002743 result = startInput(startInputReason, client, inputContext, missingMethods, attribute,
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002744 controlFlags);
Yohei Yukawa05c25f82016-02-22 12:41:17 -08002745 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08002746 if (result == null) {
2747 // This must never happen, but just in case.
2748 Slog.wtf(TAG, "InputBindResult is @NonNull. startInputReason="
2749 + InputMethodClient.getStartInputReason(startInputReason)
2750 + " windowFlags=#" + Integer.toHexString(windowFlags)
2751 + " editorInfo=" + attribute);
2752 return InputBindResult.NULL;
2753 }
2754 return result;
Yohei Yukawa05c25f82016-02-22 12:41:17 -08002755 }
2756
Yohei Yukawa2553e482017-12-15 15:47:33 -08002757 @NonNull
Yohei Yukawa05c25f82016-02-22 12:41:17 -08002758 private InputBindResult windowGainedFocus(
Yohei Yukawa35d3f372015-11-25 11:07:19 -08002759 /* @InputMethodClient.StartInputReason */ final int startInputReason,
Yohei Yukawa22dac1c2017-02-12 16:54:16 -08002760 IInputMethodClient client, IBinder windowToken, int controlFlags,
2761 /* @android.view.WindowManager.LayoutParams.SoftInputModeFlags */ int softInputMode,
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002762 int windowFlags, EditorInfo attribute, IInputContext inputContext,
Yohei Yukawacf68d522017-12-12 09:33:26 -08002763 /* @InputConnectionInspector.missingMethods */ final int missingMethods,
2764 int unverifiedTargetSdkVersion) {
Satoshi Kataoka8d033052012-11-19 17:30:40 +09002765 // Needs to check the validity before clearing calling identity
2766 final boolean calledFromValidUser = calledFromValidUser();
Dianne Hackborn7663d802012-02-24 13:08:49 -08002767 InputBindResult res = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002768 long ident = Binder.clearCallingIdentity();
2769 try {
2770 synchronized (mMethodMap) {
Yohei Yukawa35d3f372015-11-25 11:07:19 -08002771 if (DEBUG) Slog.v(TAG, "windowGainedFocus: reason="
2772 + InputMethodClient.getStartInputReason(startInputReason)
2773 + " client=" + client.asBinder()
2774 + " inputContext=" + inputContext
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002775 + " missingMethods="
2776 + InputConnectionInspector.getMissingMethodFlagsAsString(missingMethods)
Yohei Yukawa35d3f372015-11-25 11:07:19 -08002777 + " attribute=" + attribute
Dianne Hackborn7663d802012-02-24 13:08:49 -08002778 + " controlFlags=#" + Integer.toHexString(controlFlags)
Yohei Yukawa22a89232017-02-12 16:38:59 -08002779 + " softInputMode=" + InputMethodClient.softInputModeToString(softInputMode)
Yohei Yukawacf68d522017-12-12 09:33:26 -08002780 + " windowFlags=#" + Integer.toHexString(windowFlags)
2781 + " unverifiedTargetSdkVersion=" + unverifiedTargetSdkVersion);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002782
Dianne Hackborn7663d802012-02-24 13:08:49 -08002783 ClientState cs = mClients.get(client.asBinder());
2784 if (cs == null) {
2785 throw new IllegalArgumentException("unknown client "
2786 + client.asBinder());
2787 }
2788
2789 try {
2790 if (!mIWindowManager.inputMethodClientHasFocus(cs.client)) {
2791 // Check with the window manager to make sure this client actually
2792 // has a window with focus. If not, reject. This is thread safe
2793 // because if the focus changes some time before or after, the
2794 // next client receiving focus that has any interest in input will
2795 // be calling through here after that change happens.
Yohei Yukawad0332832017-02-01 13:59:43 -08002796 if (DEBUG) {
2797 Slog.w(TAG, "Focus gain on non-focused client " + cs.client
2798 + " (uid=" + cs.uid + " pid=" + cs.pid + ")");
2799 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08002800 return InputBindResult.NOT_IME_TARGET_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002801 }
Dianne Hackborn7663d802012-02-24 13:08:49 -08002802 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002804
Satoshi Kataoka8d033052012-11-19 17:30:40 +09002805 if (!calledFromValidUser) {
2806 Slog.w(TAG, "A background user is requesting window. Hiding IME.");
2807 Slog.w(TAG, "If you want to interect with IME, you need "
2808 + "android.permission.INTERACT_ACROSS_USERS_FULL");
2809 hideCurrentInputLocked(0, null);
Yohei Yukawa2553e482017-12-15 15:47:33 -08002810 return InputBindResult.INVALID_USER;
Satoshi Kataoka8d033052012-11-19 17:30:40 +09002811 }
2812
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002813 if (mCurFocusedWindow == windowToken) {
Yohei Yukawad0332832017-02-01 13:59:43 -08002814 if (DEBUG) {
2815 Slog.w(TAG, "Window already focused, ignoring focus gain of: " + client
2816 + " attribute=" + attribute + ", token = " + windowToken);
2817 }
Dianne Hackborn7663d802012-02-24 13:08:49 -08002818 if (attribute != null) {
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002819 return startInputUncheckedLocked(cs, inputContext, missingMethods,
Yohei Yukawa87ca8402017-02-07 00:13:14 -08002820 attribute, controlFlags, startInputReason);
Dianne Hackborn7663d802012-02-24 13:08:49 -08002821 }
Yohei Yukawa2553e482017-12-15 15:47:33 -08002822 return new InputBindResult(
2823 InputBindResult.ResultCode.SUCCESS_REPORT_WINDOW_FOCUS_ONLY,
2824 null, null, null, -1, -1);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002825 }
2826 mCurFocusedWindow = windowToken;
Yohei Yukawa22a89232017-02-12 16:38:59 -08002827 mCurFocusedWindowSoftInputMode = softInputMode;
Yohei Yukawae39d4ed2015-11-19 03:38:49 -08002828 mCurFocusedWindowClient = cs;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002829
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -08002830 // Should we auto-show the IME even if the caller has not
2831 // specified what should be done with it?
2832 // We only do this automatically if the window can resize
2833 // to accommodate the IME (so what the user sees will give
2834 // them good context without input information being obscured
2835 // by the IME) or if running on a large screen where there
2836 // is more room for the target window + IME.
2837 final boolean doAutoShow =
2838 (softInputMode & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
2839 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
2840 || mRes.getConfiguration().isLayoutSizeAtLeast(
2841 Configuration.SCREENLAYOUT_SIZE_LARGE);
Dianne Hackborn7663d802012-02-24 13:08:49 -08002842 final boolean isTextEditor =
2843 (controlFlags&InputMethodManager.CONTROL_WINDOW_IS_TEXT_EDITOR) != 0;
2844
2845 // We want to start input before showing the IME, but after closing
2846 // it. We want to do this after closing it to help the IME disappear
2847 // more quickly (not get stuck behind it initializing itself for the
2848 // new focused input, even if its window wants to hide the IME).
2849 boolean didStart = false;
Yohei Yukawa0f3ad12015-04-06 16:48:24 -07002850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 switch (softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_STATE) {
2852 case WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED:
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -08002853 if (!isTextEditor || !doAutoShow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002854 if (WindowManager.LayoutParams.mayUseInputMethod(windowFlags)) {
2855 // There is no focus view, and this window will
2856 // be behind any soft input window, so hide the
2857 // soft input window if it is shown.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002858 if (DEBUG) Slog.v(TAG, "Unspecified window will hide input");
The Android Open Source Project4df24232009-03-05 14:34:35 -08002859 hideCurrentInputLocked(InputMethodManager.HIDE_NOT_ALWAYS, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002860 }
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -08002861 } else if (isTextEditor && doAutoShow && (softInputMode &
2862 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 // There is a focus view, and we are navigating forward
2864 // into the window, so show the input window for the user.
Dianne Hackborn7663d802012-02-24 13:08:49 -08002865 // We only do this automatically if the window can resize
2866 // to accommodate the IME (so what the user sees will give
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -08002867 // them good context without input information being obscured
2868 // by the IME) or if running on a large screen where there
2869 // is more room for the target window + IME.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002870 if (DEBUG) Slog.v(TAG, "Unspecified window will show input");
Dianne Hackborn7663d802012-02-24 13:08:49 -08002871 if (attribute != null) {
Yohei Yukawa19a80a12016-03-14 22:57:37 -07002872 res = startInputUncheckedLocked(cs, inputContext,
Yohei Yukawa87ca8402017-02-07 00:13:14 -08002873 missingMethods, attribute, controlFlags, startInputReason);
Dianne Hackborn7663d802012-02-24 13:08:49 -08002874 didStart = true;
2875 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08002876 showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002877 }
2878 break;
2879 case WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED:
2880 // Do nothing.
2881 break;
2882 case WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN:
2883 if ((softInputMode &
2884 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002885 if (DEBUG) Slog.v(TAG, "Window asks to hide input going forward");
The Android Open Source Project4df24232009-03-05 14:34:35 -08002886 hideCurrentInputLocked(0, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002887 }
2888 break;
2889 case WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN:
Joe Onorato8a9b2202010-02-26 18:56:32 -08002890 if (DEBUG) Slog.v(TAG, "Window asks to hide input");
The Android Open Source Project4df24232009-03-05 14:34:35 -08002891 hideCurrentInputLocked(0, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892 break;
2893 case WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE:
2894 if ((softInputMode &
2895 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002896 if (DEBUG) Slog.v(TAG, "Window asks to show input going forward");
Yohei Yukawacf68d522017-12-12 09:33:26 -08002897 if (InputMethodUtils.isSoftInputModeStateVisibleAllowed(
2898 unverifiedTargetSdkVersion, controlFlags)) {
2899 if (attribute != null) {
2900 res = startInputUncheckedLocked(cs, inputContext,
2901 missingMethods, attribute, controlFlags,
2902 startInputReason);
2903 didStart = true;
2904 }
2905 showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
2906 } else {
2907 Slog.e(TAG, "SOFT_INPUT_STATE_VISIBLE is ignored because"
2908 + " there is no focused view that also returns true from"
2909 + " View#onCheckIsTextEditor()");
Dianne Hackborn7663d802012-02-24 13:08:49 -08002910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002911 }
2912 break;
2913 case WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE:
Joe Onorato8a9b2202010-02-26 18:56:32 -08002914 if (DEBUG) Slog.v(TAG, "Window asks to always show input");
Yohei Yukawacf68d522017-12-12 09:33:26 -08002915 if (InputMethodUtils.isSoftInputModeStateVisibleAllowed(
2916 unverifiedTargetSdkVersion, controlFlags)) {
2917 if (attribute != null) {
2918 res = startInputUncheckedLocked(cs, inputContext, missingMethods,
2919 attribute, controlFlags, startInputReason);
2920 didStart = true;
2921 }
2922 showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
2923 } else {
2924 Slog.e(TAG, "SOFT_INPUT_STATE_ALWAYS_VISIBLE is ignored because"
2925 + " there is no focused view that also returns true from"
2926 + " View#onCheckIsTextEditor()");
Dianne Hackborn7663d802012-02-24 13:08:49 -08002927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002928 break;
2929 }
Dianne Hackborn7663d802012-02-24 13:08:49 -08002930
Tarandeep Singh2f731c552018-02-05 13:55:06 -08002931 if (!didStart) {
2932 if (attribute != null) {
2933 if (!DebugFlags.FLAG_OPTIMIZE_START_INPUT.value()
2934 || (controlFlags
2935 & InputMethodManager.CONTROL_WINDOW_IS_TEXT_EDITOR) != 0) {
2936 res = startInputUncheckedLocked(cs, inputContext, missingMethods,
2937 attribute,
2938 controlFlags, startInputReason);
2939 } else {
2940 res = InputBindResult.NO_EDITOR;
2941 }
2942 } else {
2943 res = InputBindResult.NULL_EDITOR_INFO;
Tarandeep Singh75a92392018-01-12 14:58:59 -08002944 }
Dianne Hackborn7663d802012-02-24 13:08:49 -08002945 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002946 }
2947 } finally {
2948 Binder.restoreCallingIdentity(ident);
2949 }
Dianne Hackborn7663d802012-02-24 13:08:49 -08002950
2951 return res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002953
Guliz Tuncay6908c152017-06-02 16:06:10 -07002954 private boolean canShowInputMethodPickerLocked(IInputMethodClient client) {
2955 final int uid = Binder.getCallingUid();
2956 if (UserHandle.getAppId(uid) == Process.SYSTEM_UID) {
2957 return true;
Tarandeep Singheb570612018-01-29 16:20:32 -08002958 } else if (mCurFocusedWindowClient != null && client != null
2959 && mCurFocusedWindowClient.client.asBinder() == client.asBinder()) {
Guliz Tuncay6908c152017-06-02 16:06:10 -07002960 return true;
2961 } else if (mCurIntent != null && InputMethodUtils.checkIfPackageBelongsToUid(
2962 mAppOpsManager,
2963 uid,
2964 mCurIntent.getComponent().getPackageName())) {
2965 return true;
2966 } else if (mContext.checkCallingPermission(
2967 android.Manifest.permission.WRITE_SECURE_SETTINGS)
2968 == PackageManager.PERMISSION_GRANTED) {
2969 return true;
2970 }
2971
2972 return false;
2973 }
2974
satok42c5a162011-05-26 16:46:14 +09002975 @Override
Seigo Nonaka14e13912015-05-06 21:04:13 -07002976 public void showInputMethodPickerFromClient(
2977 IInputMethodClient client, int auxiliarySubtypeMode) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09002978 if (!calledFromValidUser()) {
2979 return;
2980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002981 synchronized (mMethodMap) {
Guliz Tuncay6908c152017-06-02 16:06:10 -07002982 if(!canShowInputMethodPickerLocked(client)) {
satok47a44912010-10-06 16:03:58 +09002983 Slog.w(TAG, "Ignoring showInputMethodPickerFromClient of uid "
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002984 + Binder.getCallingUid() + ": " + client);
Guliz Tuncay6908c152017-06-02 16:06:10 -07002985 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002986 }
2987
satok440aab52010-11-25 09:43:11 +09002988 // Always call subtype picker, because subtype picker is a superset of input method
2989 // picker.
Seigo Nonaka14e13912015-05-06 21:04:13 -07002990 mHandler.sendMessage(mCaller.obtainMessageI(
2991 MSG_SHOW_IM_SUBTYPE_PICKER, auxiliarySubtypeMode));
satokab751aa2010-09-14 19:17:36 +09002992 }
2993 }
2994
Tarandeep Singheb570612018-01-29 16:20:32 -08002995 public boolean isInputMethodPickerShownForTest() {
2996 synchronized(mMethodMap) {
2997 if (mSwitchingDialog == null) {
2998 return false;
2999 }
3000 return mSwitchingDialog.isShowing();
3001 }
3002 }
3003
satok42c5a162011-05-26 16:46:14 +09003004 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003005 public void setInputMethod(IBinder token, String id) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003006 if (!calledFromValidUser()) {
3007 return;
3008 }
satok28203512010-11-24 11:06:49 +09003009 setInputMethodWithSubtypeId(token, id, NOT_A_SUBTYPE_ID);
3010 }
3011
satok42c5a162011-05-26 16:46:14 +09003012 @Override
satok28203512010-11-24 11:06:49 +09003013 public void setInputMethodAndSubtype(IBinder token, String id, InputMethodSubtype subtype) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003014 if (!calledFromValidUser()) {
3015 return;
3016 }
satok28203512010-11-24 11:06:49 +09003017 synchronized (mMethodMap) {
3018 if (subtype != null) {
Yohei Yukawa4e02bc62014-06-04 18:37:20 +09003019 setInputMethodWithSubtypeIdLocked(token, id,
3020 InputMethodUtils.getSubtypeIdFromHashCode(mMethodMap.get(id),
3021 subtype.hashCode()));
satok28203512010-11-24 11:06:49 +09003022 } else {
3023 setInputMethod(token, id);
3024 }
3025 }
satokab751aa2010-09-14 19:17:36 +09003026 }
3027
satok42c5a162011-05-26 16:46:14 +09003028 @Override
satokb416a712010-11-25 20:42:14 +09003029 public void showInputMethodAndSubtypeEnablerFromClient(
satok217f5482010-12-15 05:19:19 +09003030 IInputMethodClient client, String inputMethodId) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003031 if (!calledFromValidUser()) {
3032 return;
3033 }
satokb416a712010-11-25 20:42:14 +09003034 synchronized (mMethodMap) {
satok7fee71f2010-12-17 18:54:26 +09003035 executeOrSendMessage(mCurMethod, mCaller.obtainMessageO(
3036 MSG_SHOW_IM_SUBTYPE_ENABLER, inputMethodId));
satokb416a712010-11-25 20:42:14 +09003037 }
3038 }
3039
satok4fc87d62011-05-20 16:13:43 +09003040 @Override
Tarandeep Singh164cfba2018-02-28 14:17:43 -08003041 public boolean switchToPreviousInputMethod(IBinder token) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003042 if (!calledFromValidUser()) {
3043 return false;
3044 }
satok735cf382010-11-11 20:40:09 +09003045 synchronized (mMethodMap) {
satokc445bcd2011-01-25 18:57:24 +09003046 final Pair<String, String> lastIme = mSettings.getLastInputMethodAndSubtypeLocked();
satok4fc87d62011-05-20 16:13:43 +09003047 final InputMethodInfo lastImi;
satok208d5632011-05-20 22:13:38 +09003048 if (lastIme != null) {
satok4fc87d62011-05-20 16:13:43 +09003049 lastImi = mMethodMap.get(lastIme.first);
3050 } else {
3051 lastImi = null;
satok735cf382010-11-11 20:40:09 +09003052 }
satok4fc87d62011-05-20 16:13:43 +09003053 String targetLastImiId = null;
3054 int subtypeId = NOT_A_SUBTYPE_ID;
3055 if (lastIme != null && lastImi != null) {
3056 final boolean imiIdIsSame = lastImi.getId().equals(mCurMethodId);
Narayan Kamatha09b4d22016-04-15 18:32:45 +01003057 final int lastSubtypeHash = Integer.parseInt(lastIme.second);
satok4fc87d62011-05-20 16:13:43 +09003058 final int currentSubtypeHash = mCurrentSubtype == null ? NOT_A_SUBTYPE_ID
3059 : mCurrentSubtype.hashCode();
3060 // If the last IME is the same as the current IME and the last subtype is not
3061 // defined, there is no need to switch to the last IME.
3062 if (!imiIdIsSame || lastSubtypeHash != currentSubtypeHash) {
3063 targetLastImiId = lastIme.first;
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003064 subtypeId = InputMethodUtils.getSubtypeIdFromHashCode(lastImi, lastSubtypeHash);
satok4fc87d62011-05-20 16:13:43 +09003065 }
3066 }
3067
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003068 if (TextUtils.isEmpty(targetLastImiId)
3069 && !InputMethodUtils.canAddToLastInputMethod(mCurrentSubtype)) {
satok4fc87d62011-05-20 16:13:43 +09003070 // This is a safety net. If the currentSubtype can't be added to the history
3071 // and the framework couldn't find the last ime, we will make the last ime be
3072 // the most applicable enabled keyboard subtype of the system imes.
3073 final List<InputMethodInfo> enabled = mSettings.getEnabledInputMethodListLocked();
3074 if (enabled != null) {
3075 final int N = enabled.size();
3076 final String locale = mCurrentSubtype == null
3077 ? mRes.getConfiguration().locale.toString()
3078 : mCurrentSubtype.getLocale();
3079 for (int i = 0; i < N; ++i) {
3080 final InputMethodInfo imi = enabled.get(i);
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003081 if (imi.getSubtypeCount() > 0 && InputMethodUtils.isSystemIme(imi)) {
satok4fc87d62011-05-20 16:13:43 +09003082 InputMethodSubtype keyboardSubtype =
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003083 InputMethodUtils.findLastResortApplicableSubtypeLocked(mRes,
3084 InputMethodUtils.getSubtypes(imi),
3085 InputMethodUtils.SUBTYPE_MODE_KEYBOARD, locale, true);
satok4fc87d62011-05-20 16:13:43 +09003086 if (keyboardSubtype != null) {
3087 targetLastImiId = imi.getId();
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003088 subtypeId = InputMethodUtils.getSubtypeIdFromHashCode(
satok4fc87d62011-05-20 16:13:43 +09003089 imi, keyboardSubtype.hashCode());
3090 if(keyboardSubtype.getLocale().equals(locale)) {
3091 break;
3092 }
3093 }
3094 }
3095 }
3096 }
3097 }
3098
3099 if (!TextUtils.isEmpty(targetLastImiId)) {
3100 if (DEBUG) {
3101 Slog.d(TAG, "Switch to: " + lastImi.getId() + ", " + lastIme.second
3102 + ", from: " + mCurMethodId + ", " + subtypeId);
3103 }
Yohei Yukawa4e02bc62014-06-04 18:37:20 +09003104 setInputMethodWithSubtypeIdLocked(token, targetLastImiId, subtypeId);
satok4fc87d62011-05-20 16:13:43 +09003105 return true;
3106 } else {
3107 return false;
3108 }
satok735cf382010-11-11 20:40:09 +09003109 }
3110 }
3111
satoke7c6998e2011-06-03 17:57:59 +09003112 @Override
satok688bd472012-02-09 20:09:17 +09003113 public boolean switchToNextInputMethod(IBinder token, boolean onlyCurrentIme) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003114 if (!calledFromValidUser()) {
3115 return false;
3116 }
satok688bd472012-02-09 20:09:17 +09003117 synchronized (mMethodMap) {
Yohei Yukawaa0755742014-06-04 20:28:18 +09003118 if (!calledWithValidToken(token)) {
Yohei Yukawaa0755742014-06-04 20:28:18 +09003119 return false;
3120 }
Yohei Yukawa5a647b692014-05-22 12:49:00 +09003121 final ImeSubtypeListItem nextSubtype = mSwitchingController.getNextInputMethodLocked(
Yohei Yukawad39ae852016-04-10 20:28:40 -07003122 onlyCurrentIme, mMethodMap.get(mCurMethodId), mCurrentSubtype,
3123 true /* forward */);
satok688bd472012-02-09 20:09:17 +09003124 if (nextSubtype == null) {
3125 return false;
3126 }
Yohei Yukawa4e02bc62014-06-04 18:37:20 +09003127 setInputMethodWithSubtypeIdLocked(token, nextSubtype.mImi.getId(),
3128 nextSubtype.mSubtypeId);
satok688bd472012-02-09 20:09:17 +09003129 return true;
3130 }
3131 }
3132
3133 @Override
Satoshi Kataoka2b10b522013-08-21 20:39:12 +09003134 public boolean shouldOfferSwitchingToNextInputMethod(IBinder token) {
3135 if (!calledFromValidUser()) {
3136 return false;
3137 }
3138 synchronized (mMethodMap) {
Yohei Yukawaa0755742014-06-04 20:28:18 +09003139 if (!calledWithValidToken(token)) {
Yohei Yukawaa0755742014-06-04 20:28:18 +09003140 return false;
3141 }
Yohei Yukawa5a647b692014-05-22 12:49:00 +09003142 final ImeSubtypeListItem nextSubtype = mSwitchingController.getNextInputMethodLocked(
Yohei Yukawad39ae852016-04-10 20:28:40 -07003143 false /* onlyCurrentIme */, mMethodMap.get(mCurMethodId), mCurrentSubtype,
3144 true /* forward */);
Satoshi Kataoka2b10b522013-08-21 20:39:12 +09003145 if (nextSubtype == null) {
3146 return false;
3147 }
3148 return true;
3149 }
3150 }
3151
3152 @Override
satok68f1b782011-04-11 14:26:04 +09003153 public InputMethodSubtype getLastInputMethodSubtype() {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003154 if (!calledFromValidUser()) {
3155 return null;
3156 }
satok68f1b782011-04-11 14:26:04 +09003157 synchronized (mMethodMap) {
3158 final Pair<String, String> lastIme = mSettings.getLastInputMethodAndSubtypeLocked();
3159 // TODO: Handle the case of the last IME with no subtypes
3160 if (lastIme == null || TextUtils.isEmpty(lastIme.first)
3161 || TextUtils.isEmpty(lastIme.second)) return null;
3162 final InputMethodInfo lastImi = mMethodMap.get(lastIme.first);
3163 if (lastImi == null) return null;
3164 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01003165 final int lastSubtypeHash = Integer.parseInt(lastIme.second);
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003166 final int lastSubtypeId =
3167 InputMethodUtils.getSubtypeIdFromHashCode(lastImi, lastSubtypeHash);
satok0e7d7d62011-07-05 13:28:06 +09003168 if (lastSubtypeId < 0 || lastSubtypeId >= lastImi.getSubtypeCount()) {
3169 return null;
3170 }
3171 return lastImi.getSubtypeAt(lastSubtypeId);
satok68f1b782011-04-11 14:26:04 +09003172 } catch (NumberFormatException e) {
3173 return null;
3174 }
3175 }
3176 }
3177
satoke7c6998e2011-06-03 17:57:59 +09003178 @Override
satokee5e77c2011-09-02 18:50:15 +09003179 public void setAdditionalInputMethodSubtypes(String imiId, InputMethodSubtype[] subtypes) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003180 if (!calledFromValidUser()) {
3181 return;
3182 }
satok91e88122011-07-18 11:11:42 +09003183 // By this IPC call, only a process which shares the same uid with the IME can add
3184 // additional input method subtypes to the IME.
Yohei Yukawa70f5c482016-01-04 19:42:36 -08003185 if (TextUtils.isEmpty(imiId) || subtypes == null) return;
satoke7c6998e2011-06-03 17:57:59 +09003186 synchronized (mMethodMap) {
Yohei Yukawa79247822017-01-23 15:26:15 -08003187 if (!mSystemReady) {
3188 return;
3189 }
satok91e88122011-07-18 11:11:42 +09003190 final InputMethodInfo imi = mMethodMap.get(imiId);
satokee5e77c2011-09-02 18:50:15 +09003191 if (imi == null) return;
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003192 final String[] packageInfos;
3193 try {
3194 packageInfos = mIPackageManager.getPackagesForUid(Binder.getCallingUid());
3195 } catch (RemoteException e) {
3196 Slog.e(TAG, "Failed to get package infos");
3197 return;
3198 }
satok91e88122011-07-18 11:11:42 +09003199 if (packageInfos != null) {
3200 final int packageNum = packageInfos.length;
3201 for (int i = 0; i < packageNum; ++i) {
3202 if (packageInfos[i].equals(imi.getPackageName())) {
3203 mFileManager.addInputMethodSubtypes(imi, subtypes);
satokc5933802011-08-31 21:26:04 +09003204 final long ident = Binder.clearCallingIdentity();
3205 try {
Yohei Yukawa94e33302016-02-12 19:37:03 -08003206 buildInputMethodListLocked(false /* resetDefaultEnabledIme */);
satokc5933802011-08-31 21:26:04 +09003207 } finally {
3208 Binder.restoreCallingIdentity(ident);
3209 }
satokee5e77c2011-09-02 18:50:15 +09003210 return;
satok91e88122011-07-18 11:11:42 +09003211 }
3212 }
3213 }
satoke7c6998e2011-06-03 17:57:59 +09003214 }
satokee5e77c2011-09-02 18:50:15 +09003215 return;
satoke7c6998e2011-06-03 17:57:59 +09003216 }
3217
Satoshi Kataoka658c7b82013-10-10 17:03:51 +09003218 @Override
3219 public int getInputMethodWindowVisibleHeight() {
Seigo Nonaka7309b122015-08-17 18:34:13 -07003220 return mWindowManagerInternal.getInputMethodWindowVisibleHeight();
Satoshi Kataoka658c7b82013-10-10 17:03:51 +09003221 }
3222
Satoshi Kataokad7443c82013-10-15 17:45:43 +09003223 @Override
Yohei Yukawa833bdce2016-05-15 20:05:56 -07003224 public void clearLastInputMethodWindowForTransition(IBinder token) {
3225 if (!calledFromValidUser()) {
3226 return;
3227 }
Yohei Yukawafa49c002017-01-31 19:15:00 -08003228 synchronized (mMethodMap) {
3229 if (!calledWithValidToken(token)) {
Yohei Yukawafa49c002017-01-31 19:15:00 -08003230 return;
Yohei Yukawa833bdce2016-05-15 20:05:56 -07003231 }
Yohei Yukawa833bdce2016-05-15 20:05:56 -07003232 }
Yohei Yukawafa49c002017-01-31 19:15:00 -08003233 mWindowManagerInternal.clearLastInputMethodWindowForTransition();
Yohei Yukawa833bdce2016-05-15 20:05:56 -07003234 }
3235
3236 @Override
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003237 public void notifyUserAction(int sequenceNumber) {
Satoshi Kataokad7443c82013-10-15 17:45:43 +09003238 if (DEBUG) {
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003239 Slog.d(TAG, "Got the notification of a user action. sequenceNumber:" + sequenceNumber);
Satoshi Kataokad7443c82013-10-15 17:45:43 +09003240 }
Yohei Yukawa5a647b692014-05-22 12:49:00 +09003241 synchronized (mMethodMap) {
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003242 if (mCurUserActionNotificationSequenceNumber != sequenceNumber) {
3243 if (DEBUG) {
3244 Slog.d(TAG, "Ignoring the user action notification due to the sequence number "
3245 + "mismatch. expected:" + mCurUserActionNotificationSequenceNumber
3246 + " actual: " + sequenceNumber);
3247 }
3248 return;
3249 }
Yohei Yukawa5a647b692014-05-22 12:49:00 +09003250 final InputMethodInfo imi = mMethodMap.get(mCurMethodId);
3251 if (imi != null) {
Yohei Yukawa02970512014-06-05 16:16:18 +09003252 mSwitchingController.onUserActionLocked(imi, mCurrentSubtype);
Yohei Yukawa5a647b692014-05-22 12:49:00 +09003253 }
Satoshi Kataokad7443c82013-10-15 17:45:43 +09003254 }
3255 }
3256
satok28203512010-11-24 11:06:49 +09003257 private void setInputMethodWithSubtypeId(IBinder token, String id, int subtypeId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003258 synchronized (mMethodMap) {
Yohei Yukawa4e02bc62014-06-04 18:37:20 +09003259 setInputMethodWithSubtypeIdLocked(token, id, subtypeId);
3260 }
3261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003262
Yohei Yukawa4e02bc62014-06-04 18:37:20 +09003263 private void setInputMethodWithSubtypeIdLocked(IBinder token, String id, int subtypeId) {
3264 if (token == null) {
3265 if (mContext.checkCallingOrSelfPermission(
3266 android.Manifest.permission.WRITE_SECURE_SETTINGS)
3267 != PackageManager.PERMISSION_GRANTED) {
3268 throw new SecurityException(
3269 "Using null token requires permission "
3270 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003271 }
Yohei Yukawa4e02bc62014-06-04 18:37:20 +09003272 } else if (mCurToken != token) {
3273 Slog.w(TAG, "Ignoring setInputMethod of uid " + Binder.getCallingUid()
3274 + " token: " + token);
3275 return;
3276 }
3277
3278 final long ident = Binder.clearCallingIdentity();
3279 try {
3280 setInputMethodLocked(id, subtypeId);
3281 } finally {
3282 Binder.restoreCallingIdentity(ident);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003283 }
3284 }
3285
satok42c5a162011-05-26 16:46:14 +09003286 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003287 public void hideMySoftInput(IBinder token, int flags) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003288 if (!calledFromValidUser()) {
3289 return;
3290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291 synchronized (mMethodMap) {
Yohei Yukawa22c97be2014-06-04 19:43:36 +09003292 if (!calledWithValidToken(token)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003293 return;
3294 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003295 long ident = Binder.clearCallingIdentity();
3296 try {
The Android Open Source Project4df24232009-03-05 14:34:35 -08003297 hideCurrentInputLocked(flags, null);
3298 } finally {
3299 Binder.restoreCallingIdentity(ident);
3300 }
3301 }
3302 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003303
satok42c5a162011-05-26 16:46:14 +09003304 @Override
The Android Open Source Project4df24232009-03-05 14:34:35 -08003305 public void showMySoftInput(IBinder token, int flags) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003306 if (!calledFromValidUser()) {
3307 return;
3308 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08003309 synchronized (mMethodMap) {
Yohei Yukawa22c97be2014-06-04 19:43:36 +09003310 if (!calledWithValidToken(token)) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08003311 return;
3312 }
3313 long ident = Binder.clearCallingIdentity();
3314 try {
3315 showCurrentInputLocked(flags, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316 } finally {
3317 Binder.restoreCallingIdentity(ident);
3318 }
3319 }
3320 }
3321
3322 void setEnabledSessionInMainThread(SessionState session) {
3323 if (mEnabledSession != session) {
Yohei Yukawa9d91b432014-05-19 16:03:24 +09003324 if (mEnabledSession != null && mEnabledSession.session != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003326 if (DEBUG) Slog.v(TAG, "Disabling: " + mEnabledSession);
Yohei Yukawa9d91b432014-05-19 16:03:24 +09003327 mEnabledSession.method.setSessionEnabled(mEnabledSession.session, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003328 } catch (RemoteException e) {
3329 }
3330 }
3331 mEnabledSession = session;
Yohei Yukawa9d91b432014-05-19 16:03:24 +09003332 if (mEnabledSession != null && mEnabledSession.session != null) {
3333 try {
3334 if (DEBUG) Slog.v(TAG, "Enabling: " + mEnabledSession);
3335 mEnabledSession.method.setSessionEnabled(mEnabledSession.session, true);
3336 } catch (RemoteException e) {
3337 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 }
3339 }
3340 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003341
Yohei Yukawa930328c2017-10-18 20:19:53 -07003342 @MainThread
satok42c5a162011-05-26 16:46:14 +09003343 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003344 public boolean handleMessage(Message msg) {
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003345 SomeArgs args;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003346 switch (msg.what) {
satokab751aa2010-09-14 19:17:36 +09003347 case MSG_SHOW_IM_SUBTYPE_PICKER:
Seigo Nonaka14e13912015-05-06 21:04:13 -07003348 final boolean showAuxSubtypes;
3349 switch (msg.arg1) {
3350 case InputMethodManager.SHOW_IM_PICKER_MODE_AUTO:
3351 // This is undocumented so far, but IMM#showInputMethodPicker() has been
3352 // implemented so that auxiliary subtypes will be excluded when the soft
3353 // keyboard is invisible.
3354 showAuxSubtypes = mInputShown;
3355 break;
3356 case InputMethodManager.SHOW_IM_PICKER_MODE_INCLUDE_AUXILIARY_SUBTYPES:
3357 showAuxSubtypes = true;
3358 break;
3359 case InputMethodManager.SHOW_IM_PICKER_MODE_EXCLUDE_AUXILIARY_SUBTYPES:
3360 showAuxSubtypes = false;
3361 break;
3362 default:
3363 Slog.e(TAG, "Unknown subtype picker mode = " + msg.arg1);
3364 return false;
3365 }
3366 showInputMethodMenu(showAuxSubtypes);
satokab751aa2010-09-14 19:17:36 +09003367 return true;
3368
satok47a44912010-10-06 16:03:58 +09003369 case MSG_SHOW_IM_SUBTYPE_ENABLER:
Yohei Yukawa41f34272015-12-14 15:41:52 -08003370 showInputMethodAndSubtypeEnabler((String)msg.obj);
satok217f5482010-12-15 05:19:19 +09003371 return true;
3372
3373 case MSG_SHOW_IM_CONFIG:
3374 showConfigureInputMethods();
satok47a44912010-10-06 16:03:58 +09003375 return true;
3376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003377 // ---------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003379 case MSG_UNBIND_INPUT:
3380 try {
3381 ((IInputMethod)msg.obj).unbindInput();
3382 } catch (RemoteException e) {
3383 // There is nothing interesting about the method dying.
3384 }
3385 return true;
3386 case MSG_BIND_INPUT:
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003387 args = (SomeArgs)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003388 try {
3389 ((IInputMethod)args.arg1).bindInput((InputBinding)args.arg2);
3390 } catch (RemoteException e) {
3391 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003392 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 return true;
3394 case MSG_SHOW_SOFT_INPUT:
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003395 args = (SomeArgs)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003396 try {
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07003397 if (DEBUG) Slog.v(TAG, "Calling " + args.arg1 + ".showSoftInput("
Craig Mautner6efb4c72013-03-13 10:17:41 -07003398 + msg.arg1 + ", " + args.arg2 + ")");
Craig Mautnerca0ac712013-03-14 09:43:02 -07003399 ((IInputMethod)args.arg1).showSoftInput(msg.arg1, (ResultReceiver)args.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003400 } catch (RemoteException e) {
3401 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003402 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003403 return true;
3404 case MSG_HIDE_SOFT_INPUT:
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003405 args = (SomeArgs)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003406 try {
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07003407 if (DEBUG) Slog.v(TAG, "Calling " + args.arg1 + ".hideSoftInput(0, "
Craig Mautner6efb4c72013-03-13 10:17:41 -07003408 + args.arg2 + ")");
Craig Mautnerca0ac712013-03-14 09:43:02 -07003409 ((IInputMethod)args.arg1).hideSoftInput(0, (ResultReceiver)args.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003410 } catch (RemoteException e) {
3411 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003412 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003413 return true;
Jorim Jaggi3c5d0f12016-05-24 19:04:30 -07003414 case MSG_HIDE_CURRENT_INPUT_METHOD:
3415 synchronized (mMethodMap) {
3416 hideCurrentInputLocked(0, null);
3417 }
3418 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003419 case MSG_ATTACH_TOKEN:
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003420 args = (SomeArgs)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003421 try {
Craig Mautnere4bbb1c2013-03-15 11:38:44 -07003422 if (DEBUG) Slog.v(TAG, "Sending attach of token: " + args.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003423 ((IInputMethod)args.arg1).attachToken((IBinder)args.arg2);
3424 } catch (RemoteException e) {
3425 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003426 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 return true;
Jeff Brownc28867a2013-03-26 15:42:39 -07003428 case MSG_CREATE_SESSION: {
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003429 args = (SomeArgs)msg.obj;
Jeff Brown1951ce82013-04-04 22:45:12 -07003430 IInputMethod method = (IInputMethod)args.arg1;
Jeff Brownc28867a2013-03-26 15:42:39 -07003431 InputChannel channel = (InputChannel)args.arg2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003432 try {
Jeff Brown1951ce82013-04-04 22:45:12 -07003433 method.createSession(channel, (IInputSessionCallback)args.arg3);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003434 } catch (RemoteException e) {
Jeff Brownc28867a2013-03-26 15:42:39 -07003435 } finally {
Jeff Brown1951ce82013-04-04 22:45:12 -07003436 // Dispose the channel if the input method is not local to this process
3437 // because the remote proxy will get its own copy when unparceled.
3438 if (channel != null && Binder.isProxy(method)) {
Jeff Brownc28867a2013-03-26 15:42:39 -07003439 channel.dispose();
3440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003441 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003442 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443 return true;
Jeff Brownc28867a2013-03-26 15:42:39 -07003444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003445 // ---------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003446
Yohei Yukawa19a80a12016-03-14 22:57:37 -07003447 case MSG_START_INPUT: {
Yohei Yukawaf7526b52017-02-11 20:57:10 -08003448 final int missingMethods = msg.arg1;
3449 final boolean restarting = msg.arg2 != 0;
Yohei Yukawa19a80a12016-03-14 22:57:37 -07003450 args = (SomeArgs) msg.obj;
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08003451 final IBinder startInputToken = (IBinder) args.arg1;
3452 final SessionState session = (SessionState) args.arg2;
3453 final IInputContext inputContext = (IInputContext) args.arg3;
3454 final EditorInfo editorInfo = (EditorInfo) args.arg4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003455 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003456 setEnabledSessionInMainThread(session);
Yohei Yukawa6db3bfe2017-02-13 12:04:41 -08003457 session.method.startInput(startInputToken, inputContext, missingMethods,
3458 editorInfo, restarting);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003459 } catch (RemoteException e) {
3460 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003461 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003462 return true;
Yohei Yukawa19a80a12016-03-14 22:57:37 -07003463 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003465 // ---------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003466
Yohei Yukawa33e81792015-11-17 21:14:42 -08003467 case MSG_UNBIND_CLIENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468 try {
Yohei Yukawa33e81792015-11-17 21:14:42 -08003469 ((IInputMethodClient)msg.obj).onUnbindMethod(msg.arg1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003470 } catch (RemoteException e) {
3471 // There is nothing interesting about the last client dying.
3472 }
3473 return true;
Yohei Yukawa33e81792015-11-17 21:14:42 -08003474 case MSG_BIND_CLIENT: {
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003475 args = (SomeArgs)msg.obj;
Jeff Brown1951ce82013-04-04 22:45:12 -07003476 IInputMethodClient client = (IInputMethodClient)args.arg1;
3477 InputBindResult res = (InputBindResult)args.arg2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003478 try {
Jeff Brown1951ce82013-04-04 22:45:12 -07003479 client.onBindMethod(res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003480 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003481 Slog.w(TAG, "Client died receiving input method " + args.arg2);
Jeff Brown1951ce82013-04-04 22:45:12 -07003482 } finally {
3483 // Dispose the channel if the input method is not local to this process
3484 // because the remote proxy will get its own copy when unparceled.
3485 if (res.channel != null && Binder.isProxy(client)) {
3486 res.channel.dispose();
3487 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003488 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003489 args.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003490 return true;
Jeff Brown1951ce82013-04-04 22:45:12 -07003491 }
Dianne Hackborna6e41342012-05-22 16:30:34 -07003492 case MSG_SET_ACTIVE:
3493 try {
Yohei Yukawa2bc66172017-02-08 11:13:25 -08003494 ((ClientState)msg.obj).client.setActive(msg.arg1 != 0, msg.arg2 != 0);
Dianne Hackborna6e41342012-05-22 16:30:34 -07003495 } catch (RemoteException e) {
3496 Slog.w(TAG, "Got RemoteException sending setActive(false) notification to pid "
3497 + ((ClientState)msg.obj).pid + " uid "
3498 + ((ClientState)msg.obj).uid);
3499 }
3500 return true;
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07003501 case MSG_SET_INTERACTIVE:
3502 handleSetInteractive(msg.arg1 != 0);
3503 return true;
Tarandeep Singh89a6c482017-11-21 14:26:11 -08003504 case MSG_START_VR_INPUT:
3505 startVrInputMethodNoCheck((ComponentName) msg.obj);
3506 return true;
Yohei Yukawaae61f712015-12-09 13:00:10 -08003507 case MSG_SWITCH_IME:
3508 handleSwitchInputMethod(msg.arg1 != 0);
3509 return true;
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003510 case MSG_SET_USER_ACTION_NOTIFICATION_SEQUENCE_NUMBER: {
3511 final int sequenceNumber = msg.arg1;
Yohei Yukawa080fa342014-08-31 16:10:05 -07003512 final ClientState clientState = (ClientState)msg.obj;
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003513 try {
Yohei Yukawa080fa342014-08-31 16:10:05 -07003514 clientState.client.setUserActionNotificationSequenceNumber(sequenceNumber);
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003515 } catch (RemoteException e) {
3516 Slog.w(TAG, "Got RemoteException sending "
3517 + "setUserActionNotificationSequenceNumber("
3518 + sequenceNumber + ") notification to pid "
Yohei Yukawa080fa342014-08-31 16:10:05 -07003519 + clientState.pid + " uid "
3520 + clientState.uid);
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09003521 }
3522 return true;
3523 }
Yohei Yukawa2bc66172017-02-08 11:13:25 -08003524 case MSG_REPORT_FULLSCREEN_MODE: {
3525 final boolean fullscreen = msg.arg1 != 0;
3526 final ClientState clientState = (ClientState)msg.obj;
3527 try {
3528 clientState.client.reportFullscreenMode(fullscreen);
3529 } catch (RemoteException e) {
3530 Slog.w(TAG, "Got RemoteException sending "
3531 + "reportFullscreen(" + fullscreen + ") notification to pid="
3532 + clientState.pid + " uid=" + clientState.uid);
3533 }
3534 return true;
3535 }
satok01038492012-04-09 21:08:27 +09003536
3537 // --------------------------------------------------------------
3538 case MSG_HARD_KEYBOARD_SWITCH_CHANGED:
Michael Wright7b5a96b2014-08-09 19:28:42 -07003539 mHardKeyboardListener.handleHardKeyboardStatusChange(msg.arg1 == 1);
satok01038492012-04-09 21:08:27 +09003540 return true;
Fyodor Kupolov7877b8a2016-06-29 14:39:19 -07003541 case MSG_SYSTEM_UNLOCK_USER:
3542 final int userId = msg.arg1;
3543 onUnlockUser(userId);
3544 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003545 }
3546 return false;
3547 }
3548
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07003549 private void handleSetInteractive(final boolean interactive) {
3550 synchronized (mMethodMap) {
3551 mIsInteractive = interactive;
3552 updateSystemUiLocked(mCurToken, interactive ? mImeWindowVis : 0, mBackDisposition);
3553
3554 // Inform the current client of the change in active status
3555 if (mCurClient != null && mCurClient.client != null) {
Yohei Yukawa2bc66172017-02-08 11:13:25 -08003556 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIIO(
3557 MSG_SET_ACTIVE, mIsInteractive ? 1 : 0, mInFullscreenMode ? 1 : 0,
3558 mCurClient));
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07003559 }
3560 }
3561 }
3562
Yohei Yukawaae61f712015-12-09 13:00:10 -08003563 private void handleSwitchInputMethod(final boolean forwardDirection) {
3564 synchronized (mMethodMap) {
Yohei Yukawaae61f712015-12-09 13:00:10 -08003565 final ImeSubtypeListItem nextSubtype = mSwitchingController.getNextInputMethodLocked(
Yohei Yukawad39ae852016-04-10 20:28:40 -07003566 false, mMethodMap.get(mCurMethodId), mCurrentSubtype, forwardDirection);
Yohei Yukawaae61f712015-12-09 13:00:10 -08003567 if (nextSubtype == null) {
3568 return;
3569 }
3570 setInputMethodLocked(nextSubtype.mImi.getId(), nextSubtype.mSubtypeId);
Yohei Yukawaebda7d72016-04-02 17:39:23 -07003571 final InputMethodInfo newInputMethodInfo = mMethodMap.get(mCurMethodId);
3572 if (newInputMethodInfo == null) {
3573 return;
3574 }
3575 final CharSequence toastText = InputMethodUtils.getImeAndSubtypeDisplayName(mContext,
3576 newInputMethodInfo, mCurrentSubtype);
3577 if (!TextUtils.isEmpty(toastText)) {
Yohei Yukawab2f901a2016-04-12 01:19:31 -07003578 if (mSubtypeSwitchedByShortCutToast == null) {
3579 mSubtypeSwitchedByShortCutToast = Toast.makeText(mContext, toastText,
3580 Toast.LENGTH_SHORT);
3581 } else {
3582 mSubtypeSwitchedByShortCutToast.setText(toastText);
3583 }
Yohei Yukawaebda7d72016-04-02 17:39:23 -07003584 mSubtypeSwitchedByShortCutToast.show();
3585 }
Yohei Yukawaae61f712015-12-09 13:00:10 -08003586 }
3587 }
3588
satokdc9ddae2011-10-06 12:22:36 +09003589 private boolean chooseNewDefaultIMELocked() {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003590 final InputMethodInfo imi = InputMethodUtils.getMostApplicableDefaultIME(
3591 mSettings.getEnabledInputMethodListLocked());
satokdc9ddae2011-10-06 12:22:36 +09003592 if (imi != null) {
satok03eb319a2010-11-11 18:17:42 +09003593 if (DEBUG) {
3594 Slog.d(TAG, "New default IME was selected: " + imi.getId());
3595 }
satok723a27e2010-11-11 14:58:11 +09003596 resetSelectedInputMethodAndSubtypeLocked(imi.getId());
Brandon Ballinger6da35a02009-10-21 00:38:13 -07003597 return true;
3598 }
3599
3600 return false;
3601 }
3602
Yohei Yukawaf80087c2018-05-21 09:47:53 -07003603 @PackageManager.ResolveInfoFlags
3604 private int getComponentMatchingFlags(@PackageManager.ResolveInfoFlags int baseFlags) {
3605 synchronized (mMethodMap) {
3606 if (mBindInstantServiceAllowed) {
3607 baseFlags |= PackageManager.MATCH_INSTANT;
3608 }
3609 return baseFlags;
3610 }
3611 }
3612
Andreas Gampea36dc622018-02-05 17:19:22 -08003613 @GuardedBy("mMethodMap")
Yohei Yukawa94e33302016-02-12 19:37:03 -08003614 void buildInputMethodListLocked(boolean resetDefaultEnabledIme) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003615 if (DEBUG) {
Satoshi Kataokaf1367b72013-01-25 17:20:12 +09003616 Slog.d(TAG, "--- re-buildInputMethodList reset = " + resetDefaultEnabledIme
Seigo Nonakae27dc2b2015-08-14 18:21:27 -07003617 + " \n ------ caller=" + Debug.getCallers(10));
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003618 }
Yohei Yukawa79247822017-01-23 15:26:15 -08003619 if (!mSystemReady) {
3620 Slog.e(TAG, "buildInputMethodListLocked is not allowed until system is ready");
3621 return;
3622 }
Yohei Yukawa94e33302016-02-12 19:37:03 -08003623 mMethodList.clear();
3624 mMethodMap.clear();
Yohei Yukawae0733062017-02-09 22:49:35 -08003625 mMethodMapUpdateCount++;
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08003626 mMyPackageMonitor.clearKnownImePackageNamesLocked();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003627
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003628 // Use for queryIntentServicesAsUser
3629 final PackageManager pm = mContext.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003630
Yohei Yukawaed4952a2016-02-17 07:57:25 -08003631 // Note: We do not specify PackageManager.MATCH_ENCRYPTION_* flags here because the default
3632 // behavior of PackageManager is exactly what we want. It by default picks up appropriate
3633 // services depending on the unlock state for the specified user.
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003634 final List<ResolveInfo> services = pm.queryIntentServicesAsUser(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 new Intent(InputMethod.SERVICE_INTERFACE),
Yohei Yukawaf80087c2018-05-21 09:47:53 -07003636 getComponentMatchingFlags(PackageManager.GET_META_DATA
3637 | PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS),
Dianne Hackbornfd7aded2013-01-22 17:10:23 -08003638 mSettings.getCurrentUserId());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003639
Yohei Yukawaddad4b92017-02-02 01:46:13 -08003640 final HashMap<String, List<InputMethodSubtype>> additionalSubtypeMap =
satoke7c6998e2011-06-03 17:57:59 +09003641 mFileManager.getAllAdditionalInputMethodSubtypes();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003642 for (int i = 0; i < services.size(); ++i) {
3643 ResolveInfo ri = services.get(i);
3644 ServiceInfo si = ri.serviceInfo;
Yohei Yukawaddad4b92017-02-02 01:46:13 -08003645 final String imeId = InputMethodInfo.computeId(ri);
3646 if (!android.Manifest.permission.BIND_INPUT_METHOD.equals(si.permission)) {
3647 Slog.w(TAG, "Skipping input method " + imeId
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003648 + ": it does not require the permission "
3649 + android.Manifest.permission.BIND_INPUT_METHOD);
3650 continue;
3651 }
3652
Yohei Yukawaddad4b92017-02-02 01:46:13 -08003653 if (DEBUG) Slog.d(TAG, "Checking " + imeId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654
Yohei Yukawaddad4b92017-02-02 01:46:13 -08003655 final List<InputMethodSubtype> additionalSubtypes = additionalSubtypeMap.get(imeId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003656 try {
satoke7c6998e2011-06-03 17:57:59 +09003657 InputMethodInfo p = new InputMethodInfo(mContext, ri, additionalSubtypes);
Yohei Yukawa94e33302016-02-12 19:37:03 -08003658 mMethodList.add(p);
Amith Yamasanie861ec12010-03-24 21:39:27 -07003659 final String id = p.getId();
Yohei Yukawa94e33302016-02-12 19:37:03 -08003660 mMethodMap.put(id, p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661
3662 if (DEBUG) {
Satoshi Kataokaf1367b72013-01-25 17:20:12 +09003663 Slog.d(TAG, "Found an input method " + p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003664 }
Tadashi G. Takaoka3c23d5b2016-09-16 11:41:07 +09003665 } catch (Exception e) {
Yohei Yukawaddad4b92017-02-02 01:46:13 -08003666 Slog.wtf(TAG, "Unable to load input method " + imeId, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003667 }
3668 }
Brandon Ballinger6da35a02009-10-21 00:38:13 -07003669
Yohei Yukawac4e44912017-02-09 19:30:22 -08003670 // Construct the set of possible IME packages for onPackageChanged() to avoid false
3671 // negatives when the package state remains to be the same but only the component state is
3672 // changed.
3673 {
3674 // Here we intentionally use PackageManager.MATCH_DISABLED_COMPONENTS since the purpose
3675 // of this query is to avoid false negatives. PackageManager.MATCH_ALL could be more
3676 // conservative, but it seems we cannot use it for now (Issue 35176630).
3677 final List<ResolveInfo> allInputMethodServices = pm.queryIntentServicesAsUser(
3678 new Intent(InputMethod.SERVICE_INTERFACE),
Yohei Yukawaf80087c2018-05-21 09:47:53 -07003679 getComponentMatchingFlags(PackageManager.MATCH_DISABLED_COMPONENTS),
3680 mSettings.getCurrentUserId());
Yohei Yukawac4e44912017-02-09 19:30:22 -08003681 final int N = allInputMethodServices.size();
3682 for (int i = 0; i < N; ++i) {
3683 final ServiceInfo si = allInputMethodServices.get(i).serviceInfo;
Yohei Yukawa5e3e8a52017-02-14 20:05:17 -08003684 if (android.Manifest.permission.BIND_INPUT_METHOD.equals(si.permission)) {
3685 mMyPackageMonitor.addKnownImePackageNameLocked(si.packageName);
Yohei Yukawac4e44912017-02-09 19:30:22 -08003686 }
Yohei Yukawac4e44912017-02-09 19:30:22 -08003687 }
3688 }
3689
Yohei Yukawa9c372192018-03-20 22:54:56 -07003690 boolean reenableMinimumNonAuxSystemImes = false;
Yohei Yukawa859df052016-02-17 07:56:46 -08003691 // TODO: The following code should find better place to live.
3692 if (!resetDefaultEnabledIme) {
3693 boolean enabledImeFound = false;
Yohei Yukawa9c372192018-03-20 22:54:56 -07003694 boolean enabledNonAuxImeFound = false;
Yohei Yukawa859df052016-02-17 07:56:46 -08003695 final List<InputMethodInfo> enabledImes = mSettings.getEnabledInputMethodListLocked();
3696 final int N = enabledImes.size();
3697 for (int i = 0; i < N; ++i) {
3698 final InputMethodInfo imi = enabledImes.get(i);
3699 if (mMethodList.contains(imi)) {
3700 enabledImeFound = true;
Yohei Yukawa9c372192018-03-20 22:54:56 -07003701 if (!imi.isAuxiliaryIme()) {
3702 enabledNonAuxImeFound = true;
3703 break;
3704 }
Yohei Yukawa859df052016-02-17 07:56:46 -08003705 }
3706 }
3707 if (!enabledImeFound) {
Yohei Yukawad0332832017-02-01 13:59:43 -08003708 if (DEBUG) {
3709 Slog.i(TAG, "All the enabled IMEs are gone. Reset default enabled IMEs.");
3710 }
Yohei Yukawa859df052016-02-17 07:56:46 -08003711 resetDefaultEnabledIme = true;
3712 resetSelectedInputMethodAndSubtypeLocked("");
Yohei Yukawa9c372192018-03-20 22:54:56 -07003713 } else if (!enabledNonAuxImeFound) {
3714 if (DEBUG) {
3715 Slog.i(TAG, "All the enabled non-Aux IMEs are gone. Do partial reset.");
3716 }
3717 reenableMinimumNonAuxSystemImes = true;
Yohei Yukawa859df052016-02-17 07:56:46 -08003718 }
3719 }
3720
Yohei Yukawa9c372192018-03-20 22:54:56 -07003721 if (resetDefaultEnabledIme || reenableMinimumNonAuxSystemImes) {
Satoshi Kataokaf1367b72013-01-25 17:20:12 +09003722 final ArrayList<InputMethodInfo> defaultEnabledIme =
Yohei Yukawa9c372192018-03-20 22:54:56 -07003723 InputMethodUtils.getDefaultEnabledImes(mContext, mMethodList,
3724 reenableMinimumNonAuxSystemImes);
Yohei Yukawa68645a62016-02-17 07:54:20 -08003725 final int N = defaultEnabledIme.size();
3726 for (int i = 0; i < N; ++i) {
Satoshi Kataokaf1367b72013-01-25 17:20:12 +09003727 final InputMethodInfo imi = defaultEnabledIme.get(i);
3728 if (DEBUG) {
3729 Slog.d(TAG, "--- enable ime = " + imi);
3730 }
3731 setInputMethodEnabledLocked(imi.getId(), true);
3732 }
3733 }
3734
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003735 final String defaultImiId = mSettings.getSelectedInputMethod();
satok0a1bcf42012-05-16 19:26:31 +09003736 if (!TextUtils.isEmpty(defaultImiId)) {
Yohei Yukawa94e33302016-02-12 19:37:03 -08003737 if (!mMethodMap.containsKey(defaultImiId)) {
satok0a1bcf42012-05-16 19:26:31 +09003738 Slog.w(TAG, "Default IME is uninstalled. Choose new default IME.");
3739 if (chooseNewDefaultIMELocked()) {
Michael Wright7b5a96b2014-08-09 19:28:42 -07003740 updateInputMethodsFromSettingsLocked(true);
satok0a1bcf42012-05-16 19:26:31 +09003741 }
3742 } else {
3743 // Double check that the default IME is certainly enabled.
3744 setInputMethodEnabledLocked(defaultImiId, true);
Brandon Ballinger6da35a02009-10-21 00:38:13 -07003745 }
3746 }
Yohei Yukawa3d46bab2014-05-30 18:10:18 +09003747 // Here is not the perfect place to reset the switching controller. Ideally
3748 // mSwitchingController and mSettings should be able to share the same state.
3749 // TODO: Make sure that mSwitchingController and mSettings are sharing the
3750 // the same enabled IMEs list.
Yohei Yukawac834a252014-05-21 22:42:32 +09003751 mSwitchingController.resetCircularListLocked(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003752 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003754 // ----------------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003755
satok217f5482010-12-15 05:19:19 +09003756 private void showInputMethodAndSubtypeEnabler(String inputMethodId) {
Tadashi G. Takaokaf49688f2011-01-20 17:56:13 +09003757 Intent intent = new Intent(Settings.ACTION_INPUT_METHOD_SUBTYPE_SETTINGS);
satok47a44912010-10-06 16:03:58 +09003758 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
satok86417ea2010-10-27 14:11:03 +09003759 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
3760 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
satok7fee71f2010-12-17 18:54:26 +09003761 if (!TextUtils.isEmpty(inputMethodId)) {
Tadashi G. Takaoka25480202011-01-20 23:13:02 +09003762 intent.putExtra(Settings.EXTRA_INPUT_METHOD_ID, inputMethodId);
satok7fee71f2010-12-17 18:54:26 +09003763 }
Yohei Yukawa41f34272015-12-14 15:41:52 -08003764 final int userId;
3765 synchronized (mMethodMap) {
3766 userId = mSettings.getCurrentUserId();
3767 }
3768 mContext.startActivityAsUser(intent, null, UserHandle.of(userId));
satok217f5482010-12-15 05:19:19 +09003769 }
3770
3771 private void showConfigureInputMethods() {
3772 Intent intent = new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS);
3773 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
3774 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
3775 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Satoshi Kataoka3ba439d2012-10-05 18:30:13 +09003776 mContext.startActivityAsUser(intent, null, UserHandle.CURRENT);
satok47a44912010-10-06 16:03:58 +09003777 }
3778
satok2c93efc2012-04-02 19:33:47 +09003779 private boolean isScreenLocked() {
3780 return mKeyguardManager != null
3781 && mKeyguardManager.isKeyguardLocked() && mKeyguardManager.isKeyguardSecure();
3782 }
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003783
Seigo Nonaka14e13912015-05-06 21:04:13 -07003784 private void showInputMethodMenu(boolean showAuxSubtypes) {
3785 if (DEBUG) Slog.v(TAG, "Show switching menu. showAuxSubtypes=" + showAuxSubtypes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003786
satok2c93efc2012-04-02 19:33:47 +09003787 final boolean isScreenLocked = isScreenLocked();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003788
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003789 final String lastInputMethodId = mSettings.getSelectedInputMethod();
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003790 int lastInputMethodSubtypeId = mSettings.getSelectedInputMethodSubtypeId(lastInputMethodId);
Joe Onorato8a9b2202010-02-26 18:56:32 -08003791 if (DEBUG) Slog.v(TAG, "Current IME: " + lastInputMethodId);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003792
Dianne Hackborn8cf1bcd2010-03-16 13:06:10 -07003793 synchronized (mMethodMap) {
satokbb4aa062011-01-19 21:40:27 +09003794 final HashMap<InputMethodInfo, List<InputMethodSubtype>> immis =
Satoshi Kataokad787f692013-10-26 04:44:21 +09003795 mSettings.getExplicitlyOrImplicitlyEnabledInputMethodsAndSubtypeListLocked(
3796 mContext);
satok7f35c8c2010-10-07 21:13:11 +09003797 if (immis == null || immis.size() == 0) {
3798 return;
3799 }
3800
Dianne Hackborn8cf1bcd2010-03-16 13:06:10 -07003801 hideInputMethodMenuLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003802
satok688bd472012-02-09 20:09:17 +09003803 final List<ImeSubtypeListItem> imList =
Yohei Yukawa5a647b692014-05-22 12:49:00 +09003804 mSwitchingController.getSortedInputMethodAndSubtypeListLocked(
Yohei Yukawa5f8e7312015-12-10 00:58:55 -08003805 showAuxSubtypes, isScreenLocked);
satok913a8922010-08-26 21:53:41 +09003806
satokc3690562012-01-10 20:14:43 +09003807 if (lastInputMethodSubtypeId == NOT_A_SUBTYPE_ID) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09003808 final InputMethodSubtype currentSubtype = getCurrentInputMethodSubtypeLocked();
satokc3690562012-01-10 20:14:43 +09003809 if (currentSubtype != null) {
3810 final InputMethodInfo currentImi = mMethodMap.get(mCurMethodId);
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09003811 lastInputMethodSubtypeId = InputMethodUtils.getSubtypeIdFromHashCode(
3812 currentImi, currentSubtype.hashCode());
satokc3690562012-01-10 20:14:43 +09003813 }
3814 }
3815
Ken Wakasa761eb372011-03-04 19:06:18 +09003816 final int N = imList.size();
satokab751aa2010-09-14 19:17:36 +09003817 mIms = new InputMethodInfo[N];
3818 mSubtypeIds = new int[N];
Dianne Hackborn8cf1bcd2010-03-16 13:06:10 -07003819 int checkedItem = 0;
3820 for (int i = 0; i < N; ++i) {
Ken Wakasa05dbb652011-08-22 15:22:43 +09003821 final ImeSubtypeListItem item = imList.get(i);
3822 mIms[i] = item.mImi;
3823 mSubtypeIds[i] = item.mSubtypeId;
Dianne Hackborn8cf1bcd2010-03-16 13:06:10 -07003824 if (mIms[i].getId().equals(lastInputMethodId)) {
satokab751aa2010-09-14 19:17:36 +09003825 int subtypeId = mSubtypeIds[i];
3826 if ((subtypeId == NOT_A_SUBTYPE_ID)
3827 || (lastInputMethodSubtypeId == NOT_A_SUBTYPE_ID && subtypeId == 0)
3828 || (subtypeId == lastInputMethodSubtypeId)) {
3829 checkedItem = i;
3830 }
Dianne Hackborn8cf1bcd2010-03-16 13:06:10 -07003831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 }
Alan Viverette505e3ab2014-11-24 15:22:11 -08003833
Andrew Sapperstein8a3b4cb2017-04-28 14:35:31 -07003834 final Context settingsContext = new ContextThemeWrapper(
3835 ActivityThread.currentActivityThread().getSystemUiContext(),
Alan Viverette505e3ab2014-11-24 15:22:11 -08003836 com.android.internal.R.style.Theme_DeviceDefault_Settings);
3837
3838 mDialogBuilder = new AlertDialog.Builder(settingsContext);
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003839 mDialogBuilder.setOnCancelListener(new OnCancelListener() {
3840 @Override
3841 public void onCancel(DialogInterface dialog) {
3842 hideInputMethodMenu();
3843 }
3844 });
Alan Viverette505e3ab2014-11-24 15:22:11 -08003845
3846 final Context dialogContext = mDialogBuilder.getContext();
3847 final TypedArray a = dialogContext.obtainStyledAttributes(null,
3848 com.android.internal.R.styleable.DialogPreference,
3849 com.android.internal.R.attr.alertDialogStyle, 0);
3850 final Drawable dialogIcon = a.getDrawable(
3851 com.android.internal.R.styleable.DialogPreference_dialogIcon);
3852 a.recycle();
3853
3854 mDialogBuilder.setIcon(dialogIcon);
3855
Yohei Yukawad34e1482016-02-11 08:03:52 -08003856 final LayoutInflater inflater = dialogContext.getSystemService(LayoutInflater.class);
satok01038492012-04-09 21:08:27 +09003857 final View tv = inflater.inflate(
3858 com.android.internal.R.layout.input_method_switch_dialog_title, null);
3859 mDialogBuilder.setCustomTitle(tv);
3860
3861 // Setup layout for a toggle switch of the hardware keyboard
3862 mSwitchingDialogTitleView = tv;
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003863 mSwitchingDialogTitleView
3864 .findViewById(com.android.internal.R.id.hard_keyboard_section)
Seigo Nonaka7309b122015-08-17 18:34:13 -07003865 .setVisibility(mWindowManagerInternal.isHardKeyboardAvailable()
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003866 ? View.VISIBLE : View.GONE);
Alan Viverette505e3ab2014-11-24 15:22:11 -08003867 final Switch hardKeySwitch = (Switch) mSwitchingDialogTitleView.findViewById(
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003868 com.android.internal.R.id.hard_keyboard_switch);
Michael Wright7b5a96b2014-08-09 19:28:42 -07003869 hardKeySwitch.setChecked(mShowImeWithHardKeyboard);
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003870 hardKeySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
3871 @Override
3872 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Michael Wright7b5a96b2014-08-09 19:28:42 -07003873 mSettings.setShowImeWithHardKeyboard(isChecked);
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003874 // Ensure that the input method dialog is dismissed when changing
3875 // the hardware keyboard state.
3876 hideInputMethodMenu();
3877 }
3878 });
3879
Alan Viverette505e3ab2014-11-24 15:22:11 -08003880 final ImeSubtypeListAdapter adapter = new ImeSubtypeListAdapter(dialogContext,
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003881 com.android.internal.R.layout.input_method_switch_item, imList, checkedItem);
3882 final OnClickListener choiceListener = new OnClickListener() {
3883 @Override
3884 public void onClick(final DialogInterface dialog, final int which) {
3885 synchronized (mMethodMap) {
3886 if (mIms == null || mIms.length <= which || mSubtypeIds == null
3887 || mSubtypeIds.length <= which) {
3888 return;
satok01038492012-04-09 21:08:27 +09003889 }
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003890 final InputMethodInfo im = mIms[which];
3891 int subtypeId = mSubtypeIds[which];
3892 adapter.mCheckedItem = which;
3893 adapter.notifyDataSetChanged();
3894 hideInputMethodMenu();
3895 if (im != null) {
3896 if (subtypeId < 0 || subtypeId >= im.getSubtypeCount()) {
3897 subtypeId = NOT_A_SUBTYPE_ID;
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08003898 }
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003899 setInputMethodLocked(im.getId(), subtypeId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 }
Tadashi G. Takaokad130b802014-08-01 14:05:47 +09003901 }
3902 }
3903 };
3904 mDialogBuilder.setSingleChoiceItems(adapter, checkedItem, choiceListener);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003906 mSwitchingDialog = mDialogBuilder.create();
Dianne Hackborne3a7f622011-03-03 21:48:24 -08003907 mSwitchingDialog.setCanceledOnTouchOutside(true);
Wale Ogunwale3a931692016-11-02 16:49:48 -07003908 final Window w = mSwitchingDialog.getWindow();
3909 final WindowManager.LayoutParams attrs = w.getAttributes();
3910 w.setType(TYPE_INPUT_METHOD_DIALOG);
3911 // Use an alternate token for the dialog for that window manager can group the token
3912 // with other IME windows based on type vs. grouping based on whichever token happens
3913 // to get selected by the system later on.
3914 attrs.token = mSwitchingDialogToken;
3915 attrs.privateFlags |= PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
3916 attrs.setTitle("Select input method");
3917 w.setAttributes(attrs);
Seigo Nonakad9eb9112015-05-26 20:54:43 +09003918 updateSystemUi(mCurToken, mImeWindowVis, mBackDisposition);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003919 mSwitchingDialog.show();
3920 }
3921 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003922
Ken Wakasa05dbb652011-08-22 15:22:43 +09003923 private static class ImeSubtypeListAdapter extends ArrayAdapter<ImeSubtypeListItem> {
3924 private final LayoutInflater mInflater;
3925 private final int mTextViewResourceId;
3926 private final List<ImeSubtypeListItem> mItemsList;
Satoshi Kataokad2142962012-11-12 18:43:06 +09003927 public int mCheckedItem;
Ken Wakasa05dbb652011-08-22 15:22:43 +09003928 public ImeSubtypeListAdapter(Context context, int textViewResourceId,
3929 List<ImeSubtypeListItem> itemsList, int checkedItem) {
3930 super(context, textViewResourceId, itemsList);
Alan Viverette505e3ab2014-11-24 15:22:11 -08003931
Ken Wakasa05dbb652011-08-22 15:22:43 +09003932 mTextViewResourceId = textViewResourceId;
3933 mItemsList = itemsList;
3934 mCheckedItem = checkedItem;
Yohei Yukawad34e1482016-02-11 08:03:52 -08003935 mInflater = context.getSystemService(LayoutInflater.class);
Ken Wakasa05dbb652011-08-22 15:22:43 +09003936 }
3937
3938 @Override
3939 public View getView(int position, View convertView, ViewGroup parent) {
3940 final View view = convertView != null ? convertView
3941 : mInflater.inflate(mTextViewResourceId, null);
3942 if (position < 0 || position >= mItemsList.size()) return view;
3943 final ImeSubtypeListItem item = mItemsList.get(position);
3944 final CharSequence imeName = item.mImeName;
3945 final CharSequence subtypeName = item.mSubtypeName;
3946 final TextView firstTextView = (TextView)view.findViewById(android.R.id.text1);
3947 final TextView secondTextView = (TextView)view.findViewById(android.R.id.text2);
3948 if (TextUtils.isEmpty(subtypeName)) {
3949 firstTextView.setText(imeName);
3950 secondTextView.setVisibility(View.GONE);
3951 } else {
3952 firstTextView.setText(subtypeName);
3953 secondTextView.setText(imeName);
3954 secondTextView.setVisibility(View.VISIBLE);
3955 }
3956 final RadioButton radioButton =
3957 (RadioButton)view.findViewById(com.android.internal.R.id.radio);
3958 radioButton.setChecked(position == mCheckedItem);
3959 return view;
3960 }
3961 }
3962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003963 void hideInputMethodMenu() {
The Android Open Source Project10592532009-03-18 17:39:46 -07003964 synchronized (mMethodMap) {
3965 hideInputMethodMenuLocked();
3966 }
3967 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003968
The Android Open Source Project10592532009-03-18 17:39:46 -07003969 void hideInputMethodMenuLocked() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003970 if (DEBUG) Slog.v(TAG, "Hide switching menu");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003971
The Android Open Source Project10592532009-03-18 17:39:46 -07003972 if (mSwitchingDialog != null) {
3973 mSwitchingDialog.dismiss();
3974 mSwitchingDialog = null;
Yohei Yukawa1fc7a1d2018-04-18 17:31:27 -07003975 mSwitchingDialogTitleView = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003976 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003977
Seigo Nonakad9eb9112015-05-26 20:54:43 +09003978 updateSystemUiLocked(mCurToken, mImeWindowVis, mBackDisposition);
The Android Open Source Project10592532009-03-18 17:39:46 -07003979 mDialogBuilder = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07003980 mIms = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003981 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003982
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003983 // ----------------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003984
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003985 boolean setInputMethodEnabledLocked(String id, boolean enabled) {
3986 // Make sure this is a valid input method.
3987 InputMethodInfo imm = mMethodMap.get(id);
3988 if (imm == null) {
satokd87c2592010-09-29 11:52:06 +09003989 throw new IllegalArgumentException("Unknown id: " + mCurMethodId);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003990 }
3991
satokd87c2592010-09-29 11:52:06 +09003992 List<Pair<String, ArrayList<String>>> enabledInputMethodsList = mSettings
3993 .getEnabledInputMethodsAndSubtypeListLocked();
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003994
satokd87c2592010-09-29 11:52:06 +09003995 if (enabled) {
3996 for (Pair<String, ArrayList<String>> pair: enabledInputMethodsList) {
3997 if (pair.first.equals(id)) {
3998 // We are enabling this input method, but it is already enabled.
3999 // Nothing to do. The previous state was enabled.
4000 return true;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004001 }
4002 }
satokd87c2592010-09-29 11:52:06 +09004003 mSettings.appendAndPutEnabledInputMethodLocked(id, false);
4004 // Previous state was disabled.
4005 return false;
4006 } else {
4007 StringBuilder builder = new StringBuilder();
4008 if (mSettings.buildAndPutEnabledInputMethodsStrRemovingIdLocked(
4009 builder, enabledInputMethodsList, id)) {
4010 // Disabled input method is currently selected, switch to another one.
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004011 final String selId = mSettings.getSelectedInputMethod();
satok03eb319a2010-11-11 18:17:42 +09004012 if (id.equals(selId) && !chooseNewDefaultIMELocked()) {
4013 Slog.i(TAG, "Can't find new IME, unsetting the current input method.");
4014 resetSelectedInputMethodAndSubtypeLocked("");
satokd87c2592010-09-29 11:52:06 +09004015 }
4016 // Previous state was enabled.
4017 return true;
4018 } else {
4019 // We are disabling the input method but it is already disabled.
4020 // Nothing to do. The previous state was disabled.
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004021 return false;
4022 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004023 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004024 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08004025
satok723a27e2010-11-11 14:58:11 +09004026 private void setSelectedInputMethodAndSubtypeLocked(InputMethodInfo imi, int subtypeId,
4027 boolean setSubtypeOnly) {
Tarandeep Singh89a6c482017-11-21 14:26:11 -08004028 // Updates to InputMethod are transient in VR mode. Its not included in history.
4029 final boolean isVrInput = imi != null && imi.isVrOnly();
4030 if (!isVrInput) {
4031 // Update the history of InputMethod and Subtype
4032 mSettings.saveCurrentInputMethodAndSubtypeToHistory(mCurMethodId, mCurrentSubtype);
4033 }
satok723a27e2010-11-11 14:58:11 +09004034
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09004035 mCurUserActionNotificationSequenceNumber =
4036 Math.max(mCurUserActionNotificationSequenceNumber + 1, 1);
4037 if (DEBUG) {
4038 Slog.d(TAG, "Bump mCurUserActionNotificationSequenceNumber:"
4039 + mCurUserActionNotificationSequenceNumber);
4040 }
4041
4042 if (mCurClient != null && mCurClient.client != null) {
4043 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
4044 MSG_SET_USER_ACTION_NOTIFICATION_SEQUENCE_NUMBER,
Yohei Yukawa080fa342014-08-31 16:10:05 -07004045 mCurUserActionNotificationSequenceNumber, mCurClient));
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09004046 }
4047
Tarandeep Singh89a6c482017-11-21 14:26:11 -08004048 if (isVrInput) {
4049 // Updates to InputMethod are transient in VR mode. Any changes to Settings are skipped.
4050 return;
4051 }
4052
satok723a27e2010-11-11 14:58:11 +09004053 // Set Subtype here
4054 if (imi == null || subtypeId < 0) {
4055 mSettings.putSelectedSubtype(NOT_A_SUBTYPE_ID);
Tadashi G. Takaoka0ba75bb2010-11-09 12:19:32 -08004056 mCurrentSubtype = null;
satok723a27e2010-11-11 14:58:11 +09004057 } else {
Ken Wakasa586f0512011-01-20 22:31:01 +09004058 if (subtypeId < imi.getSubtypeCount()) {
4059 InputMethodSubtype subtype = imi.getSubtypeAt(subtypeId);
4060 mSettings.putSelectedSubtype(subtype.hashCode());
4061 mCurrentSubtype = subtype;
satok723a27e2010-11-11 14:58:11 +09004062 } else {
4063 mSettings.putSelectedSubtype(NOT_A_SUBTYPE_ID);
satokd81e9502012-05-21 12:58:45 +09004064 // If the subtype is not specified, choose the most applicable one
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004065 mCurrentSubtype = getCurrentInputMethodSubtypeLocked();
satok723a27e2010-11-11 14:58:11 +09004066 }
satokab751aa2010-09-14 19:17:36 +09004067 }
satok723a27e2010-11-11 14:58:11 +09004068
Yohei Yukawa68645a62016-02-17 07:54:20 -08004069 if (!setSubtypeOnly) {
satok723a27e2010-11-11 14:58:11 +09004070 // Set InputMethod here
4071 mSettings.putSelectedInputMethod(imi != null ? imi.getId() : "");
4072 }
4073 }
4074
4075 private void resetSelectedInputMethodAndSubtypeLocked(String newDefaultIme) {
4076 InputMethodInfo imi = mMethodMap.get(newDefaultIme);
4077 int lastSubtypeId = NOT_A_SUBTYPE_ID;
4078 // newDefaultIme is empty when there is no candidate for the selected IME.
4079 if (imi != null && !TextUtils.isEmpty(newDefaultIme)) {
4080 String subtypeHashCode = mSettings.getLastSubtypeForInputMethodLocked(newDefaultIme);
4081 if (subtypeHashCode != null) {
4082 try {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004083 lastSubtypeId = InputMethodUtils.getSubtypeIdFromHashCode(
Narayan Kamatha09b4d22016-04-15 18:32:45 +01004084 imi, Integer.parseInt(subtypeHashCode));
satok723a27e2010-11-11 14:58:11 +09004085 } catch (NumberFormatException e) {
4086 Slog.w(TAG, "HashCode for subtype looks broken: " + subtypeHashCode, e);
4087 }
4088 }
4089 }
4090 setSelectedInputMethodAndSubtypeLocked(imi, lastSubtypeId, false);
satokab751aa2010-09-14 19:17:36 +09004091 }
4092
satok4e4569d2010-11-19 18:45:53 +09004093 // If there are no selected shortcuts, tries finding the most applicable ones.
4094 private Pair<InputMethodInfo, InputMethodSubtype>
4095 findLastResortApplicableShortcutInputMethodAndSubtypeLocked(String mode) {
4096 List<InputMethodInfo> imis = mSettings.getEnabledInputMethodListLocked();
4097 InputMethodInfo mostApplicableIMI = null;
satokcd7cd292010-11-20 15:46:23 +09004098 InputMethodSubtype mostApplicableSubtype = null;
satok4e4569d2010-11-19 18:45:53 +09004099 boolean foundInSystemIME = false;
4100
4101 // Search applicable subtype for each InputMethodInfo
4102 for (InputMethodInfo imi: imis) {
satok7599a7f2010-12-22 13:45:23 +09004103 final String imiId = imi.getId();
4104 if (foundInSystemIME && !imiId.equals(mCurMethodId)) {
4105 continue;
4106 }
satokcd7cd292010-11-20 15:46:23 +09004107 InputMethodSubtype subtype = null;
satokdf31ae62011-01-15 06:19:44 +09004108 final List<InputMethodSubtype> enabledSubtypes =
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004109 mSettings.getEnabledInputMethodSubtypeListLocked(mContext, imi, true);
satokdf31ae62011-01-15 06:19:44 +09004110 // 1. Search by the current subtype's locale from enabledSubtypes.
satok4e4569d2010-11-19 18:45:53 +09004111 if (mCurrentSubtype != null) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004112 subtype = InputMethodUtils.findLastResortApplicableSubtypeLocked(
satokdf31ae62011-01-15 06:19:44 +09004113 mRes, enabledSubtypes, mode, mCurrentSubtype.getLocale(), false);
satok4e4569d2010-11-19 18:45:53 +09004114 }
satokdf31ae62011-01-15 06:19:44 +09004115 // 2. Search by the system locale from enabledSubtypes.
4116 // 3. Search the first enabled subtype matched with mode from enabledSubtypes.
satokcd7cd292010-11-20 15:46:23 +09004117 if (subtype == null) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004118 subtype = InputMethodUtils.findLastResortApplicableSubtypeLocked(
satokdf31ae62011-01-15 06:19:44 +09004119 mRes, enabledSubtypes, mode, null, true);
satok4e4569d2010-11-19 18:45:53 +09004120 }
satoka86f5e42011-09-02 17:12:42 +09004121 final ArrayList<InputMethodSubtype> overridingImplicitlyEnabledSubtypes =
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004122 InputMethodUtils.getOverridingImplicitlyEnabledSubtypes(imi, mode);
satoka86f5e42011-09-02 17:12:42 +09004123 final ArrayList<InputMethodSubtype> subtypesForSearch =
4124 overridingImplicitlyEnabledSubtypes.isEmpty()
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004125 ? InputMethodUtils.getSubtypes(imi)
4126 : overridingImplicitlyEnabledSubtypes;
satok7599a7f2010-12-22 13:45:23 +09004127 // 4. Search by the current subtype's locale from all subtypes.
4128 if (subtype == null && mCurrentSubtype != null) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004129 subtype = InputMethodUtils.findLastResortApplicableSubtypeLocked(
satoka86f5e42011-09-02 17:12:42 +09004130 mRes, subtypesForSearch, mode, mCurrentSubtype.getLocale(), false);
satok7599a7f2010-12-22 13:45:23 +09004131 }
4132 // 5. Search by the system locale from all subtypes.
4133 // 6. Search the first enabled subtype matched with mode from all subtypes.
satokcd7cd292010-11-20 15:46:23 +09004134 if (subtype == null) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004135 subtype = InputMethodUtils.findLastResortApplicableSubtypeLocked(
satoka86f5e42011-09-02 17:12:42 +09004136 mRes, subtypesForSearch, mode, null, true);
satok4e4569d2010-11-19 18:45:53 +09004137 }
satokcd7cd292010-11-20 15:46:23 +09004138 if (subtype != null) {
satok7599a7f2010-12-22 13:45:23 +09004139 if (imiId.equals(mCurMethodId)) {
satok4e4569d2010-11-19 18:45:53 +09004140 // The current input method is the most applicable IME.
4141 mostApplicableIMI = imi;
satokcd7cd292010-11-20 15:46:23 +09004142 mostApplicableSubtype = subtype;
satok4e4569d2010-11-19 18:45:53 +09004143 break;
satok7599a7f2010-12-22 13:45:23 +09004144 } else if (!foundInSystemIME) {
satok4e4569d2010-11-19 18:45:53 +09004145 // The system input method is 2nd applicable IME.
4146 mostApplicableIMI = imi;
satokcd7cd292010-11-20 15:46:23 +09004147 mostApplicableSubtype = subtype;
satok7599a7f2010-12-22 13:45:23 +09004148 if ((imi.getServiceInfo().applicationInfo.flags
4149 & ApplicationInfo.FLAG_SYSTEM) != 0) {
4150 foundInSystemIME = true;
4151 }
satok4e4569d2010-11-19 18:45:53 +09004152 }
4153 }
4154 }
4155 if (DEBUG) {
satokcd7cd292010-11-20 15:46:23 +09004156 if (mostApplicableIMI != null) {
4157 Slog.w(TAG, "Most applicable shortcut input method was:"
4158 + mostApplicableIMI.getId());
4159 if (mostApplicableSubtype != null) {
4160 Slog.w(TAG, "Most applicable shortcut input method subtype was:"
4161 + "," + mostApplicableSubtype.getMode() + ","
4162 + mostApplicableSubtype.getLocale());
4163 }
4164 }
satok4e4569d2010-11-19 18:45:53 +09004165 }
satokcd7cd292010-11-20 15:46:23 +09004166 if (mostApplicableIMI != null) {
Yohei Yukawab0377bb2015-08-10 21:06:30 -07004167 return new Pair<> (mostApplicableIMI, mostApplicableSubtype);
satok4e4569d2010-11-19 18:45:53 +09004168 } else {
4169 return null;
4170 }
4171 }
4172
satokab751aa2010-09-14 19:17:36 +09004173 /**
4174 * @return Return the current subtype of this input method.
4175 */
satok42c5a162011-05-26 16:46:14 +09004176 @Override
satokab751aa2010-09-14 19:17:36 +09004177 public InputMethodSubtype getCurrentInputMethodSubtype() {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004178 // TODO: Make this work even for non-current users?
4179 if (!calledFromValidUser()) {
4180 return null;
4181 }
4182 synchronized (mMethodMap) {
4183 return getCurrentInputMethodSubtypeLocked();
4184 }
4185 }
4186
4187 private InputMethodSubtype getCurrentInputMethodSubtypeLocked() {
satokfdf419e2012-05-08 16:52:08 +09004188 if (mCurMethodId == null) {
4189 return null;
4190 }
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004191 final boolean subtypeIsSelected = mSettings.isSubtypeSelected();
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004192 final InputMethodInfo imi = mMethodMap.get(mCurMethodId);
4193 if (imi == null || imi.getSubtypeCount() == 0) {
4194 return null;
satok4e4569d2010-11-19 18:45:53 +09004195 }
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004196 if (!subtypeIsSelected || mCurrentSubtype == null
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004197 || !InputMethodUtils.isValidSubtypeId(imi, mCurrentSubtype.hashCode())) {
4198 int subtypeId = mSettings.getSelectedInputMethodSubtypeId(mCurMethodId);
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004199 if (subtypeId == NOT_A_SUBTYPE_ID) {
4200 // If there are no selected subtypes, the framework will try to find
4201 // the most applicable subtype from explicitly or implicitly enabled
4202 // subtypes.
4203 List<InputMethodSubtype> explicitlyOrImplicitlyEnabledSubtypes =
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004204 mSettings.getEnabledInputMethodSubtypeListLocked(mContext, imi, true);
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004205 // If there is only one explicitly or implicitly enabled subtype,
4206 // just returns it.
4207 if (explicitlyOrImplicitlyEnabledSubtypes.size() == 1) {
4208 mCurrentSubtype = explicitlyOrImplicitlyEnabledSubtypes.get(0);
4209 } else if (explicitlyOrImplicitlyEnabledSubtypes.size() > 1) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004210 mCurrentSubtype = InputMethodUtils.findLastResortApplicableSubtypeLocked(
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004211 mRes, explicitlyOrImplicitlyEnabledSubtypes,
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004212 InputMethodUtils.SUBTYPE_MODE_KEYBOARD, null, true);
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004213 if (mCurrentSubtype == null) {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004214 mCurrentSubtype = InputMethodUtils.findLastResortApplicableSubtypeLocked(
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004215 mRes, explicitlyOrImplicitlyEnabledSubtypes, null, null,
4216 true);
satok4e4569d2010-11-19 18:45:53 +09004217 }
satok3ef8b292010-11-23 06:06:29 +09004218 }
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004219 } else {
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004220 mCurrentSubtype = InputMethodUtils.getSubtypes(imi).get(subtypeId);
satok8fbb1e82010-11-02 23:15:58 +09004221 }
4222 }
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004223 return mCurrentSubtype;
satokab751aa2010-09-14 19:17:36 +09004224 }
4225
satok4e4569d2010-11-19 18:45:53 +09004226 // TODO: We should change the return type from List to List<Parcelable>
satokdbf29502011-08-25 15:28:23 +09004227 @SuppressWarnings("rawtypes")
satoke7c6998e2011-06-03 17:57:59 +09004228 @Override
satok4e4569d2010-11-19 18:45:53 +09004229 public List getShortcutInputMethodsAndSubtypes() {
4230 synchronized (mMethodMap) {
Yohei Yukawab0377bb2015-08-10 21:06:30 -07004231 ArrayList<Object> ret = new ArrayList<>();
satokf3db1af2010-11-23 13:34:33 +09004232 if (mShortcutInputMethodsAndSubtypes.size() == 0) {
satok4e4569d2010-11-19 18:45:53 +09004233 // If there are no selected shortcut subtypes, the framework will try to find
4234 // the most applicable subtype from all subtypes whose mode is
4235 // SUBTYPE_MODE_VOICE. This is an exceptional case, so we will hardcode the mode.
satokf3db1af2010-11-23 13:34:33 +09004236 Pair<InputMethodInfo, InputMethodSubtype> info =
4237 findLastResortApplicableShortcutInputMethodAndSubtypeLocked(
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004238 InputMethodUtils.SUBTYPE_MODE_VOICE);
satok7599a7f2010-12-22 13:45:23 +09004239 if (info != null) {
satok3da92232011-01-11 22:46:30 +09004240 ret.add(info.first);
4241 ret.add(info.second);
satok7599a7f2010-12-22 13:45:23 +09004242 }
satok3da92232011-01-11 22:46:30 +09004243 return ret;
satokf3db1af2010-11-23 13:34:33 +09004244 }
satokf3db1af2010-11-23 13:34:33 +09004245 for (InputMethodInfo imi: mShortcutInputMethodsAndSubtypes.keySet()) {
4246 ret.add(imi);
4247 for (InputMethodSubtype subtype: mShortcutInputMethodsAndSubtypes.get(imi)) {
4248 ret.add(subtype);
satok4e4569d2010-11-19 18:45:53 +09004249 }
4250 }
satokf3db1af2010-11-23 13:34:33 +09004251 return ret;
satok4e4569d2010-11-19 18:45:53 +09004252 }
4253 }
4254
satok42c5a162011-05-26 16:46:14 +09004255 @Override
satokb66d2872010-11-10 01:04:04 +09004256 public boolean setCurrentInputMethodSubtype(InputMethodSubtype subtype) {
Satoshi Kataoka4e1ab152012-09-13 21:34:20 +09004257 // TODO: Make this work even for non-current users?
4258 if (!calledFromValidUser()) {
4259 return false;
4260 }
satokb66d2872010-11-10 01:04:04 +09004261 synchronized (mMethodMap) {
4262 if (subtype != null && mCurMethodId != null) {
4263 InputMethodInfo imi = mMethodMap.get(mCurMethodId);
Satoshi Kataoka8e303cc2013-01-11 15:55:28 +09004264 int subtypeId = InputMethodUtils.getSubtypeIdFromHashCode(imi, subtype.hashCode());
satokb66d2872010-11-10 01:04:04 +09004265 if (subtypeId != NOT_A_SUBTYPE_ID) {
4266 setInputMethodLocked(mCurMethodId, subtypeId);
4267 return true;
4268 }
4269 }
4270 return false;
4271 }
4272 }
4273
Satoshi Kataoka5ade83b2012-09-26 22:59:41 +09004274 // TODO: Cache the state for each user and reset when the cached user is removed.
satoke7c6998e2011-06-03 17:57:59 +09004275 private static class InputMethodFileManager {
4276 private static final String SYSTEM_PATH = "system";
4277 private static final String INPUT_METHOD_PATH = "inputmethod";
4278 private static final String ADDITIONAL_SUBTYPES_FILE_NAME = "subtypes.xml";
4279 private static final String NODE_SUBTYPES = "subtypes";
4280 private static final String NODE_SUBTYPE = "subtype";
4281 private static final String NODE_IMI = "imi";
4282 private static final String ATTR_ID = "id";
4283 private static final String ATTR_LABEL = "label";
4284 private static final String ATTR_ICON = "icon";
Yohei Yukawa66baf692016-04-11 02:29:35 -07004285 private static final String ATTR_IME_SUBTYPE_ID = "subtypeId";
satoke7c6998e2011-06-03 17:57:59 +09004286 private static final String ATTR_IME_SUBTYPE_LOCALE = "imeSubtypeLocale";
Yohei Yukawa868d19b2015-12-07 15:58:57 -08004287 private static final String ATTR_IME_SUBTYPE_LANGUAGE_TAG = "languageTag";
satoke7c6998e2011-06-03 17:57:59 +09004288 private static final String ATTR_IME_SUBTYPE_MODE = "imeSubtypeMode";
4289 private static final String ATTR_IME_SUBTYPE_EXTRA_VALUE = "imeSubtypeExtraValue";
4290 private static final String ATTR_IS_AUXILIARY = "isAuxiliary";
Yohei Yukawa1e1a4472016-03-10 23:46:07 -08004291 private static final String ATTR_IS_ASCII_CAPABLE = "isAsciiCapable";
satoke7c6998e2011-06-03 17:57:59 +09004292 private final AtomicFile mAdditionalInputMethodSubtypeFile;
4293 private final HashMap<String, InputMethodInfo> mMethodMap;
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004294 private final HashMap<String, List<InputMethodSubtype>> mAdditionalSubtypesMap =
Yohei Yukawab0377bb2015-08-10 21:06:30 -07004295 new HashMap<>();
Satoshi Kataoka5ade83b2012-09-26 22:59:41 +09004296 public InputMethodFileManager(HashMap<String, InputMethodInfo> methodMap, int userId) {
satoke7c6998e2011-06-03 17:57:59 +09004297 if (methodMap == null) {
4298 throw new NullPointerException("methodMap is null");
4299 }
4300 mMethodMap = methodMap;
Xiaohui Chen7c696362015-09-16 09:56:14 -07004301 final File systemDir = userId == UserHandle.USER_SYSTEM
Satoshi Kataoka5ade83b2012-09-26 22:59:41 +09004302 ? new File(Environment.getDataDirectory(), SYSTEM_PATH)
4303 : Environment.getUserSystemDirectory(userId);
satoke7c6998e2011-06-03 17:57:59 +09004304 final File inputMethodDir = new File(systemDir, INPUT_METHOD_PATH);
Yohei Yukawadf5af482015-08-04 22:11:11 -07004305 if (!inputMethodDir.exists() && !inputMethodDir.mkdirs()) {
satoke7c6998e2011-06-03 17:57:59 +09004306 Slog.w(TAG, "Couldn't create dir.: " + inputMethodDir.getAbsolutePath());
4307 }
4308 final File subtypeFile = new File(inputMethodDir, ADDITIONAL_SUBTYPES_FILE_NAME);
Dianne Hackborne17b4452018-01-10 13:15:40 -08004309 mAdditionalInputMethodSubtypeFile = new AtomicFile(subtypeFile, "input-subtypes");
satoke7c6998e2011-06-03 17:57:59 +09004310 if (!subtypeFile.exists()) {
4311 // If "subtypes.xml" doesn't exist, create a blank file.
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004312 writeAdditionalInputMethodSubtypes(
4313 mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile, methodMap);
satoke7c6998e2011-06-03 17:57:59 +09004314 } else {
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004315 readAdditionalInputMethodSubtypes(
4316 mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile);
satoke7c6998e2011-06-03 17:57:59 +09004317 }
4318 }
4319
4320 private void deleteAllInputMethodSubtypes(String imiId) {
4321 synchronized (mMethodMap) {
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004322 mAdditionalSubtypesMap.remove(imiId);
4323 writeAdditionalInputMethodSubtypes(
4324 mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile, mMethodMap);
satoke7c6998e2011-06-03 17:57:59 +09004325 }
4326 }
4327
4328 public void addInputMethodSubtypes(
satok4a28bde2011-06-29 21:03:40 +09004329 InputMethodInfo imi, InputMethodSubtype[] additionalSubtypes) {
satoke7c6998e2011-06-03 17:57:59 +09004330 synchronized (mMethodMap) {
Yohei Yukawab0377bb2015-08-10 21:06:30 -07004331 final ArrayList<InputMethodSubtype> subtypes = new ArrayList<>();
satoke7c6998e2011-06-03 17:57:59 +09004332 final int N = additionalSubtypes.length;
4333 for (int i = 0; i < N; ++i) {
4334 final InputMethodSubtype subtype = additionalSubtypes[i];
satoked2b24e2011-08-31 18:03:21 +09004335 if (!subtypes.contains(subtype)) {
satoke7c6998e2011-06-03 17:57:59 +09004336 subtypes.add(subtype);
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004337 } else {
4338 Slog.w(TAG, "Duplicated subtype definition found: "
4339 + subtype.getLocale() + ", " + subtype.getMode());
satoke7c6998e2011-06-03 17:57:59 +09004340 }
4341 }
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004342 mAdditionalSubtypesMap.put(imi.getId(), subtypes);
4343 writeAdditionalInputMethodSubtypes(
4344 mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile, mMethodMap);
satoke7c6998e2011-06-03 17:57:59 +09004345 }
4346 }
4347
4348 public HashMap<String, List<InputMethodSubtype>> getAllAdditionalInputMethodSubtypes() {
4349 synchronized (mMethodMap) {
Satoshi Kataokae62e6d82012-07-02 18:45:43 +09004350 return mAdditionalSubtypesMap;
satoke7c6998e2011-06-03 17:57:59 +09004351 }
4352 }
4353
4354 private static void writeAdditionalInputMethodSubtypes(
4355 HashMap<String, List<InputMethodSubtype>> allSubtypes, AtomicFile subtypesFile,
4356 HashMap<String, InputMethodInfo> methodMap) {
4357 // Safety net for the case that this function is called before methodMap is set.
4358 final boolean isSetMethodMap = methodMap != null && methodMap.size() > 0;
4359 FileOutputStream fos = null;
4360 try {
4361 fos = subtypesFile.startWrite();
4362 final XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01004363 out.setOutput(fos, StandardCharsets.UTF_8.name());
satoke7c6998e2011-06-03 17:57:59 +09004364 out.startDocument(null, true);
4365 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
4366 out.startTag(null, NODE_SUBTYPES);
4367 for (String imiId : allSubtypes.keySet()) {
4368 if (isSetMethodMap && !methodMap.containsKey(imiId)) {
4369 Slog.w(TAG, "IME uninstalled or not valid.: " + imiId);
4370 continue;
4371 }
4372 out.startTag(null, NODE_IMI);
4373 out.attribute(null, ATTR_ID, imiId);
4374 final List<InputMethodSubtype> subtypesList = allSubtypes.get(imiId);
4375 final int N = subtypesList.size();
4376 for (int i = 0; i < N; ++i) {
4377 final InputMethodSubtype subtype = subtypesList.get(i);
4378 out.startTag(null, NODE_SUBTYPE);
Yohei Yukawa66baf692016-04-11 02:29:35 -07004379 if (subtype.hasSubtypeId()) {
4380 out.attribute(null, ATTR_IME_SUBTYPE_ID,
4381 String.valueOf(subtype.getSubtypeId()));
4382 }
satoke7c6998e2011-06-03 17:57:59 +09004383 out.attribute(null, ATTR_ICON, String.valueOf(subtype.getIconResId()));
4384 out.attribute(null, ATTR_LABEL, String.valueOf(subtype.getNameResId()));
4385 out.attribute(null, ATTR_IME_SUBTYPE_LOCALE, subtype.getLocale());
Yohei Yukawa868d19b2015-12-07 15:58:57 -08004386 out.attribute(null, ATTR_IME_SUBTYPE_LANGUAGE_TAG,
4387 subtype.getLanguageTag());
satoke7c6998e2011-06-03 17:57:59 +09004388 out.attribute(null, ATTR_IME_SUBTYPE_MODE, subtype.getMode());
4389 out.attribute(null, ATTR_IME_SUBTYPE_EXTRA_VALUE, subtype.getExtraValue());
4390 out.attribute(null, ATTR_IS_AUXILIARY,
4391 String.valueOf(subtype.isAuxiliary() ? 1 : 0));
Yohei Yukawa1e1a4472016-03-10 23:46:07 -08004392 out.attribute(null, ATTR_IS_ASCII_CAPABLE,
4393 String.valueOf(subtype.isAsciiCapable() ? 1 : 0));
satoke7c6998e2011-06-03 17:57:59 +09004394 out.endTag(null, NODE_SUBTYPE);
4395 }
4396 out.endTag(null, NODE_IMI);
4397 }
4398 out.endTag(null, NODE_SUBTYPES);
4399 out.endDocument();
4400 subtypesFile.finishWrite(fos);
4401 } catch (java.io.IOException e) {
4402 Slog.w(TAG, "Error writing subtypes", e);
4403 if (fos != null) {
4404 subtypesFile.failWrite(fos);
4405 }
4406 }
4407 }
4408
4409 private static void readAdditionalInputMethodSubtypes(
4410 HashMap<String, List<InputMethodSubtype>> allSubtypes, AtomicFile subtypesFile) {
4411 if (allSubtypes == null || subtypesFile == null) return;
4412 allSubtypes.clear();
Yohei Yukawa5894b432015-08-11 13:29:24 -07004413 try (final FileInputStream fis = subtypesFile.openRead()) {
satoke7c6998e2011-06-03 17:57:59 +09004414 final XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01004415 parser.setInput(fis, StandardCharsets.UTF_8.name());
satoke7c6998e2011-06-03 17:57:59 +09004416 int type = parser.getEventType();
4417 // Skip parsing until START_TAG
4418 while ((type = parser.next()) != XmlPullParser.START_TAG
4419 && type != XmlPullParser.END_DOCUMENT) {}
4420 String firstNodeName = parser.getName();
4421 if (!NODE_SUBTYPES.equals(firstNodeName)) {
4422 throw new XmlPullParserException("Xml doesn't start with subtypes");
4423 }
4424 final int depth =parser.getDepth();
4425 String currentImiId = null;
4426 ArrayList<InputMethodSubtype> tempSubtypesArray = null;
4427 while (((type = parser.next()) != XmlPullParser.END_TAG
4428 || parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
4429 if (type != XmlPullParser.START_TAG)
4430 continue;
4431 final String nodeName = parser.getName();
4432 if (NODE_IMI.equals(nodeName)) {
4433 currentImiId = parser.getAttributeValue(null, ATTR_ID);
4434 if (TextUtils.isEmpty(currentImiId)) {
4435 Slog.w(TAG, "Invalid imi id found in subtypes.xml");
4436 continue;
4437 }
Yohei Yukawab0377bb2015-08-10 21:06:30 -07004438 tempSubtypesArray = new ArrayList<>();
satoke7c6998e2011-06-03 17:57:59 +09004439 allSubtypes.put(currentImiId, tempSubtypesArray);
4440 } else if (NODE_SUBTYPE.equals(nodeName)) {
4441 if (TextUtils.isEmpty(currentImiId) || tempSubtypesArray == null) {
4442 Slog.w(TAG, "IME uninstalled or not valid.: " + currentImiId);
4443 continue;
4444 }
Narayan Kamatha09b4d22016-04-15 18:32:45 +01004445 final int icon = Integer.parseInt(
satoke7c6998e2011-06-03 17:57:59 +09004446 parser.getAttributeValue(null, ATTR_ICON));
Narayan Kamatha09b4d22016-04-15 18:32:45 +01004447 final int label = Integer.parseInt(
satoke7c6998e2011-06-03 17:57:59 +09004448 parser.getAttributeValue(null, ATTR_LABEL));
4449 final String imeSubtypeLocale =
4450 parser.getAttributeValue(null, ATTR_IME_SUBTYPE_LOCALE);
Yohei Yukawa868d19b2015-12-07 15:58:57 -08004451 final String languageTag =
4452 parser.getAttributeValue(null, ATTR_IME_SUBTYPE_LANGUAGE_TAG);
satoke7c6998e2011-06-03 17:57:59 +09004453 final String imeSubtypeMode =
4454 parser.getAttributeValue(null, ATTR_IME_SUBTYPE_MODE);
4455 final String imeSubtypeExtraValue =
4456 parser.getAttributeValue(null, ATTR_IME_SUBTYPE_EXTRA_VALUE);
satok4a28bde2011-06-29 21:03:40 +09004457 final boolean isAuxiliary = "1".equals(String.valueOf(
4458 parser.getAttributeValue(null, ATTR_IS_AUXILIARY)));
Yohei Yukawa1e1a4472016-03-10 23:46:07 -08004459 final boolean isAsciiCapable = "1".equals(String.valueOf(
4460 parser.getAttributeValue(null, ATTR_IS_ASCII_CAPABLE)));
Yohei Yukawa66baf692016-04-11 02:29:35 -07004461 final InputMethodSubtypeBuilder builder = new InputMethodSubtypeBuilder()
Yohei Yukawa443c2ba2014-09-10 14:10:30 +09004462 .setSubtypeNameResId(label)
4463 .setSubtypeIconResId(icon)
4464 .setSubtypeLocale(imeSubtypeLocale)
Yohei Yukawa868d19b2015-12-07 15:58:57 -08004465 .setLanguageTag(languageTag)
Yohei Yukawa443c2ba2014-09-10 14:10:30 +09004466 .setSubtypeMode(imeSubtypeMode)
4467 .setSubtypeExtraValue(imeSubtypeExtraValue)
4468 .setIsAuxiliary(isAuxiliary)
Yohei Yukawa66baf692016-04-11 02:29:35 -07004469 .setIsAsciiCapable(isAsciiCapable);
4470 final String subtypeIdString =
4471 parser.getAttributeValue(null, ATTR_IME_SUBTYPE_ID);
4472 if (subtypeIdString != null) {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01004473 builder.setSubtypeId(Integer.parseInt(subtypeIdString));
Yohei Yukawa66baf692016-04-11 02:29:35 -07004474 }
4475 tempSubtypesArray.add(builder.build());
satoke7c6998e2011-06-03 17:57:59 +09004476 }
4477 }
Yohei Yukawa5894b432015-08-11 13:29:24 -07004478 } catch (XmlPullParserException | IOException | NumberFormatException e) {
4479 Slog.w(TAG, "Error reading subtypes", e);
satoke7c6998e2011-06-03 17:57:59 +09004480 return;
satoke7c6998e2011-06-03 17:57:59 +09004481 }
4482 }
4483 }
4484
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07004485 private static final class LocalServiceImpl implements InputMethodManagerInternal {
4486 @NonNull
4487 private final Handler mHandler;
4488
4489 LocalServiceImpl(@NonNull final Handler handler) {
4490 mHandler = handler;
4491 }
4492
4493 @Override
4494 public void setInteractive(boolean interactive) {
4495 // Do everything in handler so as not to block the caller.
4496 mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_INTERACTIVE,
4497 interactive ? 1 : 0, 0));
4498 }
Yohei Yukawaae61f712015-12-09 13:00:10 -08004499
4500 @Override
4501 public void switchInputMethod(boolean forwardDirection) {
4502 // Do everything in handler so as not to block the caller.
4503 mHandler.sendMessage(mHandler.obtainMessage(MSG_SWITCH_IME,
4504 forwardDirection ? 1 : 0, 0));
4505 }
Jorim Jaggi3c5d0f12016-05-24 19:04:30 -07004506
4507 @Override
4508 public void hideCurrentInputMethod() {
4509 mHandler.removeMessages(MSG_HIDE_CURRENT_INPUT_METHOD);
4510 mHandler.sendEmptyMessage(MSG_HIDE_CURRENT_INPUT_METHOD);
4511 }
Tarandeep Singh89a6c482017-11-21 14:26:11 -08004512
4513 @Override
4514 public void startVrInputMethodNoCheck(@Nullable ComponentName componentName) {
4515 mHandler.sendMessage(mHandler.obtainMessage(MSG_START_VR_INPUT, componentName));
4516 }
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07004517 }
4518
Yohei Yukawaebda7d72016-04-02 17:39:23 -07004519 private static String imeWindowStatusToString(final int imeWindowVis) {
4520 final StringBuilder sb = new StringBuilder();
4521 boolean first = true;
4522 if ((imeWindowVis & InputMethodService.IME_ACTIVE) != 0) {
4523 sb.append("Active");
4524 first = false;
4525 }
4526 if ((imeWindowVis & InputMethodService.IME_VISIBLE) != 0) {
4527 if (!first) {
4528 sb.append("|");
4529 }
4530 sb.append("Visible");
4531 }
4532 return sb.toString();
4533 }
4534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004535 @Override
Yohei Yukawa25e08132016-06-22 16:31:41 -07004536 public IInputContentUriToken createInputContentUriToken(@Nullable IBinder token,
4537 @Nullable Uri contentUri, @Nullable String packageName) {
4538 if (!calledFromValidUser()) {
4539 return null;
4540 }
4541
4542 if (token == null) {
4543 throw new NullPointerException("token");
4544 }
4545 if (packageName == null) {
4546 throw new NullPointerException("packageName");
4547 }
4548 if (contentUri == null) {
4549 throw new NullPointerException("contentUri");
4550 }
4551 final String contentUriScheme = contentUri.getScheme();
4552 if (!"content".equals(contentUriScheme)) {
4553 throw new InvalidParameterException("contentUri must have content scheme");
4554 }
4555
4556 synchronized (mMethodMap) {
4557 final int uid = Binder.getCallingUid();
4558 if (mCurMethodId == null) {
4559 return null;
4560 }
4561 if (mCurToken != token) {
4562 Slog.e(TAG, "Ignoring createInputContentUriToken mCurToken=" + mCurToken
4563 + " token=" + token);
4564 return null;
4565 }
4566 // We cannot simply distinguish a bad IME that reports an arbitrary package name from
4567 // an unfortunate IME whose internal state is already obsolete due to the asynchronous
4568 // nature of our system. Let's compare it with our internal record.
4569 if (!TextUtils.equals(mCurAttribute.packageName, packageName)) {
4570 Slog.e(TAG, "Ignoring createInputContentUriToken mCurAttribute.packageName="
4571 + mCurAttribute.packageName + " packageName=" + packageName);
4572 return null;
4573 }
Yohei Yukawa3933a6e2016-11-10 00:47:48 -08004574 // This user ID can never bee spoofed.
Yohei Yukawa25e08132016-06-22 16:31:41 -07004575 final int imeUserId = UserHandle.getUserId(uid);
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 appUserId = UserHandle.getUserId(mCurClient.uid);
Yohei Yukawa3933a6e2016-11-10 00:47:48 -08004578 // This user ID may be invalid if "contentUri" embedded an invalid user ID.
4579 final int contentUriOwnerUserId = ContentProvider.getUserIdFromUri(contentUri,
4580 imeUserId);
4581 final Uri contentUriWithoutUserId = ContentProvider.getUriWithoutUserId(contentUri);
4582 // Note: InputContentUriTokenHandler.take() checks whether the IME (specified by "uid")
4583 // actually has the right to grant a read permission for "contentUriWithoutUserId" that
4584 // is claimed to belong to "contentUriOwnerUserId". For example, specifying random
4585 // content URI and/or contentUriOwnerUserId just results in a SecurityException thrown
4586 // from InputContentUriTokenHandler.take() and can never be allowed beyond what is
4587 // actually allowed to "uid", which is guaranteed to be the IME's one.
4588 return new InputContentUriTokenHandler(contentUriWithoutUserId, uid,
4589 packageName, contentUriOwnerUserId, appUserId);
Yohei Yukawa25e08132016-06-22 16:31:41 -07004590 }
4591 }
4592
4593 @Override
Yohei Yukawa2bc66172017-02-08 11:13:25 -08004594 public void reportFullscreenMode(IBinder token, boolean fullscreen) {
4595 if (!calledFromValidUser()) {
4596 return;
4597 }
4598 synchronized (mMethodMap) {
4599 if (!calledWithValidToken(token)) {
4600 return;
4601 }
4602 if (mCurClient != null && mCurClient.client != null) {
4603 mInFullscreenMode = fullscreen;
4604 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
4605 MSG_REPORT_FULLSCREEN_MODE, fullscreen ? 1 : 0, mCurClient));
4606 }
4607 }
4608 }
4609
4610 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004611 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06004612 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004613
4614 IInputMethod method;
4615 ClientState client;
Yohei Yukawae39d4ed2015-11-19 03:38:49 -08004616 ClientState focusedWindowClient;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004618 final Printer p = new PrintWriterPrinter(pw);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004620 synchronized (mMethodMap) {
4621 p.println("Current Input Method Manager state:");
4622 int N = mMethodList.size();
Yohei Yukawaf80087c2018-05-21 09:47:53 -07004623 p.println(" Input Methods: mMethodMapUpdateCount=" + mMethodMapUpdateCount
4624 + " mBindInstantServiceAllowed=" + mBindInstantServiceAllowed);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004625 for (int i=0; i<N; i++) {
4626 InputMethodInfo info = mMethodList.get(i);
4627 p.println(" InputMethod #" + i + ":");
4628 info.dump(p, " ");
4629 }
4630 p.println(" Clients:");
4631 for (ClientState ci : mClients.values()) {
4632 p.println(" Client " + ci + ":");
4633 p.println(" client=" + ci.client);
4634 p.println(" inputContext=" + ci.inputContext);
4635 p.println(" sessionRequested=" + ci.sessionRequested);
4636 p.println(" curSession=" + ci.curSession);
4637 }
The Android Open Source Project10592532009-03-18 17:39:46 -07004638 p.println(" mCurMethodId=" + mCurMethodId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004639 client = mCurClient;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004640 p.println(" mCurClient=" + client + " mCurSeq=" + mCurSeq);
Yohei Yukawa22a89232017-02-12 16:38:59 -08004641 p.println(" mCurFocusedWindow=" + mCurFocusedWindow
4642 + " softInputMode=" +
4643 InputMethodClient.softInputModeToString(mCurFocusedWindowSoftInputMode)
4644 + " client=" + mCurFocusedWindowClient);
Yohei Yukawae39d4ed2015-11-19 03:38:49 -08004645 focusedWindowClient = mCurFocusedWindowClient;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004646 p.println(" mCurId=" + mCurId + " mHaveConnect=" + mHaveConnection
4647 + " mBoundToMethod=" + mBoundToMethod);
4648 p.println(" mCurToken=" + mCurToken);
4649 p.println(" mCurIntent=" + mCurIntent);
4650 method = mCurMethod;
4651 p.println(" mCurMethod=" + mCurMethod);
4652 p.println(" mEnabledSession=" + mEnabledSession);
Yohei Yukawaebda7d72016-04-02 17:39:23 -07004653 p.println(" mImeWindowVis=" + imeWindowStatusToString(mImeWindowVis));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004654 p.println(" mShowRequested=" + mShowRequested
4655 + " mShowExplicitlyRequested=" + mShowExplicitlyRequested
4656 + " mShowForced=" + mShowForced
4657 + " mInputShown=" + mInputShown);
Yohei Yukawa2bc66172017-02-08 11:13:25 -08004658 p.println(" mInFullscreenMode=" + mInFullscreenMode);
Yohei Yukawa3d1e8122014-06-06 19:12:47 +09004659 p.println(" mCurUserActionNotificationSequenceNumber="
4660 + mCurUserActionNotificationSequenceNumber);
Yohei Yukawafa6e0a82015-07-23 15:08:59 -07004661 p.println(" mSystemReady=" + mSystemReady + " mInteractive=" + mIsInteractive);
Yohei Yukawa81482972015-06-04 00:58:59 -07004662 p.println(" mSettingsObserver=" + mSettingsObserver);
Yohei Yukawad7248862015-06-03 23:56:12 -07004663 p.println(" mSwitchingController:");
4664 mSwitchingController.dump(p);
Yohei Yukawa68645a62016-02-17 07:54:20 -08004665 p.println(" mSettings:");
4666 mSettings.dumpLocked(p, " ");
Yohei Yukawa357b2f62017-02-14 09:40:03 -08004667
4668 p.println(" mStartInputHistory:");
4669 mStartInputHistory.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004670 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004671
Jeff Brownb88102f2010-09-08 11:49:43 -07004672 p.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004673 if (client != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004674 pw.flush();
4675 try {
Jeff Sharkey850c83e2016-11-09 12:25:44 -07004676 TransferPipe.dumpAsync(client.client.asBinder(), fd, args);
4677 } catch (IOException | RemoteException e) {
4678 p.println("Failed to dump input method client: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004679 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004680 } else {
4681 p.println("No input method client.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004682 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004683
Yohei Yukawae39d4ed2015-11-19 03:38:49 -08004684 if (focusedWindowClient != null && client != focusedWindowClient) {
4685 p.println(" ");
4686 p.println("Warning: Current input method client doesn't match the last focused. "
4687 + "window.");
4688 p.println("Dumping input method client in the last focused window just in case.");
4689 p.println(" ");
4690 pw.flush();
4691 try {
Jeff Sharkey850c83e2016-11-09 12:25:44 -07004692 TransferPipe.dumpAsync(focusedWindowClient.client.asBinder(), fd, args);
4693 } catch (IOException | RemoteException e) {
4694 p.println("Failed to dump input method client in focused window: " + e);
Yohei Yukawae39d4ed2015-11-19 03:38:49 -08004695 }
4696 }
4697
Jeff Brownb88102f2010-09-08 11:49:43 -07004698 p.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004699 if (method != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004700 pw.flush();
4701 try {
Jeff Sharkey850c83e2016-11-09 12:25:44 -07004702 TransferPipe.dumpAsync(method.asBinder(), fd, args);
4703 } catch (IOException | RemoteException e) {
4704 p.println("Failed to dump input method service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004705 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004706 } else {
4707 p.println("No input method service.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004708 }
4709 }
Yohei Yukawa926488d2017-12-11 17:24:55 -08004710
4711 @BinderThread
4712 @Override
4713 public void onShellCommand(@Nullable FileDescriptor in, @Nullable FileDescriptor out,
4714 @Nullable FileDescriptor err,
4715 @NonNull String[] args, @Nullable ShellCallback callback,
4716 @NonNull ResultReceiver resultReceiver) throws RemoteException {
4717 new ShellCommandImpl(this).exec(
4718 this, in, out, err, args, callback, resultReceiver);
4719 }
4720
4721 private static final class ShellCommandImpl extends ShellCommand {
4722 @NonNull
4723 final InputMethodManagerService mService;
4724
4725 ShellCommandImpl(InputMethodManagerService service) {
4726 mService = service;
4727 }
4728
4729 @BinderThread
4730 @ShellCommandResult
4731 @Override
4732 public int onCommand(@Nullable String cmd) {
Yohei Yukawadfdab732018-02-21 07:16:30 +09004733 if ("refresh_debug_properties".equals(cmd)) {
4734 return refreshDebugProperties();
4735 }
Yohei Yukawaf80087c2018-05-21 09:47:53 -07004736 if ("set-bind-instant-service-allowed".equals(cmd)) {
4737 return setBindInstantServiceAllowed();
4738 }
Yohei Yukawadfdab732018-02-21 07:16:30 +09004739
Yohei Yukawacac97722017-12-15 16:52:05 -08004740 // For existing "adb shell ime <command>".
4741 if ("ime".equals(cmd)) {
4742 final String imeCommand = getNextArg();
4743 if (imeCommand == null || "help".equals(imeCommand) || "-h".equals(imeCommand)) {
4744 onImeCommandHelp();
4745 return ShellCommandResult.SUCCESS;
4746 }
4747 switch (imeCommand) {
4748 case "list":
4749 return mService.handleShellCommandListInputMethods(this);
4750 case "enable":
4751 return mService.handleShellCommandEnableDisableInputMethod(this, true);
4752 case "disable":
4753 return mService.handleShellCommandEnableDisableInputMethod(this, false);
4754 case "set":
4755 return mService.handleShellCommandSetInputMethod(this);
4756 case "reset":
4757 return mService.handleShellCommandResetInputMethod(this);
4758 default:
4759 getOutPrintWriter().println("Unknown command: " + imeCommand);
4760 return ShellCommandResult.FAILURE;
4761 }
Yohei Yukawa926488d2017-12-11 17:24:55 -08004762 }
Yohei Yukawacac97722017-12-15 16:52:05 -08004763
4764 return handleDefaultCommands(cmd);
Yohei Yukawa926488d2017-12-11 17:24:55 -08004765 }
4766
4767 @BinderThread
Tarandeep Singh75a92392018-01-12 14:58:59 -08004768 @ShellCommandResult
Yohei Yukawaf80087c2018-05-21 09:47:53 -07004769 private int setBindInstantServiceAllowed() {
4770 return mService.handleSetBindInstantServiceAllowed(this);
4771 }
4772
4773 @BinderThread
4774 @ShellCommandResult
Tarandeep Singh75a92392018-01-12 14:58:59 -08004775 private int refreshDebugProperties() {
4776 DebugFlags.FLAG_OPTIMIZE_START_INPUT.refresh();
4777 return ShellCommandResult.SUCCESS;
4778 }
4779
4780 @BinderThread
Yohei Yukawa926488d2017-12-11 17:24:55 -08004781 @Override
4782 public void onHelp() {
4783 try (PrintWriter pw = getOutPrintWriter()) {
4784 pw.println("InputMethodManagerService commands:");
4785 pw.println(" help");
4786 pw.println(" Prints this help text.");
4787 pw.println(" dump [options]");
4788 pw.println(" Synonym of dumpsys.");
Yohei Yukawacac97722017-12-15 16:52:05 -08004789 pw.println(" ime <command> [options]");
4790 pw.println(" Manipulate IMEs. Run \"ime help\" for details.");
Yohei Yukawaf80087c2018-05-21 09:47:53 -07004791 pw.println(" set-bind-instant-service-allowed true|false ");
4792 pw.println(" Set whether binding to services provided by instant apps is "
4793 + "allowed.");
Yohei Yukawacac97722017-12-15 16:52:05 -08004794 }
4795 }
4796
4797 private void onImeCommandHelp() {
4798 try (IndentingPrintWriter pw =
4799 new IndentingPrintWriter(getOutPrintWriter(), " ", 100)) {
4800 pw.println("ime <command>:");
4801 pw.increaseIndent();
4802
4803 pw.println("list [-a] [-s]");
4804 pw.increaseIndent();
4805 pw.println("prints all enabled input methods.");
4806 pw.increaseIndent();
4807 pw.println("-a: see all input methods");
4808 pw.println("-s: only a single summary line of each");
4809 pw.decreaseIndent();
4810 pw.decreaseIndent();
4811
4812 pw.println("enable <ID>");
4813 pw.increaseIndent();
4814 pw.println("allows the given input method ID to be used.");
4815 pw.decreaseIndent();
4816
4817 pw.println("disable <ID>");
4818 pw.increaseIndent();
4819 pw.println("disallows the given input method ID to be used.");
4820 pw.decreaseIndent();
4821
4822 pw.println("set <ID>");
4823 pw.increaseIndent();
4824 pw.println("switches to the given input method ID.");
4825 pw.decreaseIndent();
4826
4827 pw.println("reset");
4828 pw.increaseIndent();
4829 pw.println("reset currently selected/enabled IMEs to the default ones as if "
4830 + "the device is initially booted with the current locale.");
4831 pw.decreaseIndent();
4832
4833 pw.decreaseIndent();
Yohei Yukawa926488d2017-12-11 17:24:55 -08004834 }
4835 }
4836 }
4837
4838 // ----------------------------------------------------------------------
4839 // Shell command handlers:
4840
4841 /**
Yohei Yukawaf80087c2018-05-21 09:47:53 -07004842 * Handles {@code adb shell cmd input_method set-bind-instant-service-allowed}.
4843 *
4844 * @param shellCommand {@link ShellCommand} object that is handling this command.
4845 * @return Exit code of the command.
4846 */
4847 @BinderThread
4848 @RequiresPermission(android.Manifest.permission.MANAGE_BIND_INSTANT_SERVICE)
4849 @ShellCommandResult
4850 private int handleSetBindInstantServiceAllowed(@NonNull ShellCommand shellCommand) {
4851 final String allowedString = shellCommand.getNextArgRequired();
4852 if (allowedString == null) {
4853 shellCommand.getErrPrintWriter().println("Error: no true/false specified");
4854 return ShellCommandResult.FAILURE;
4855 }
4856 final boolean allowed = Boolean.parseBoolean(allowedString);
4857 synchronized (mMethodMap) {
4858 if (mContext.checkCallingOrSelfPermission(
4859 android.Manifest.permission.MANAGE_BIND_INSTANT_SERVICE)
4860 != PackageManager.PERMISSION_GRANTED) {
4861 shellCommand.getErrPrintWriter().print(
4862 "Caller must have MANAGE_BIND_INSTANT_SERVICE permission");
4863 return ShellCommandResult.FAILURE;
4864 }
4865
4866 if (mBindInstantServiceAllowed == allowed) {
4867 // Nothing to do.
4868 return ShellCommandResult.SUCCESS;
4869 }
4870 mBindInstantServiceAllowed = allowed;
4871
4872 // Rebuild everything.
4873 final long ident = Binder.clearCallingIdentity();
4874 try {
4875 // Reset the current IME
4876 resetSelectedInputMethodAndSubtypeLocked(null);
4877 // Also reset the settings of the current IME
4878 mSettings.putSelectedInputMethod(null);
4879 buildInputMethodListLocked(false /* resetDefaultEnabledIme */);
4880 updateInputMethodsFromSettingsLocked(true /* enabledMayChange */);
4881 } finally {
4882 Binder.restoreCallingIdentity(ident);
4883 }
4884 }
4885 return ShellCommandResult.SUCCESS;
4886 }
4887
4888 /**
Yohei Yukawa926488d2017-12-11 17:24:55 -08004889 * Handles {@code adb shell ime list}.
4890 * @param shellCommand {@link ShellCommand} object that is handling this command.
4891 * @return Exit code of the command.
4892 */
4893 @BinderThread
4894 @ShellCommandResult
4895 private int handleShellCommandListInputMethods(@NonNull ShellCommand shellCommand) {
4896 boolean all = false;
4897 boolean brief = false;
4898 while (true) {
4899 final String nextOption = shellCommand.getNextOption();
4900 if (nextOption == null) {
4901 break;
4902 }
4903 switch (nextOption) {
4904 case "-a":
4905 all = true;
4906 break;
4907 case "-s":
4908 brief = true;
4909 break;
4910 }
4911 }
4912 final List<InputMethodInfo> methods = all ?
4913 getInputMethodList() : getEnabledInputMethodList();
4914 final PrintWriter pr = shellCommand.getOutPrintWriter();
4915 final Printer printer = x -> pr.println(x);
4916 final int N = methods.size();
4917 for (int i = 0; i < N; ++i) {
4918 if (brief) {
4919 pr.println(methods.get(i).getId());
4920 } else {
4921 pr.print(methods.get(i).getId()); pr.println(":");
4922 methods.get(i).dump(printer, " ");
4923 }
4924 }
4925 return ShellCommandResult.SUCCESS;
4926 }
4927
4928 /**
4929 * Handles {@code adb shell ime enable} and {@code adb shell ime disable}.
4930 * @param shellCommand {@link ShellCommand} object that is handling this command.
4931 * @param enabled {@code true} if the command was {@code adb shell ime enable}.
4932 * @return Exit code of the command.
4933 */
4934 @BinderThread
4935 @ShellCommandResult
4936 @RequiresPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
4937 private int handleShellCommandEnableDisableInputMethod(
4938 @NonNull ShellCommand shellCommand, boolean enabled) {
4939 if (!calledFromValidUser()) {
4940 shellCommand.getErrPrintWriter().print(
4941 "Must be called from the foreground user or with INTERACT_ACROSS_USERS_FULL");
4942 return ShellCommandResult.FAILURE;
4943 }
4944 final String id = shellCommand.getNextArgRequired();
4945
4946 final boolean previouslyEnabled;
4947 synchronized (mMethodMap) {
4948 if (mContext.checkCallingOrSelfPermission(
4949 android.Manifest.permission.WRITE_SECURE_SETTINGS)
4950 != PackageManager.PERMISSION_GRANTED) {
4951 shellCommand.getErrPrintWriter().print(
4952 "Caller must have WRITE_SECURE_SETTINGS permission");
4953 throw new SecurityException(
4954 "Requires permission "
4955 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
4956 }
4957
4958 final long ident = Binder.clearCallingIdentity();
4959 try {
4960 previouslyEnabled = setInputMethodEnabledLocked(id, enabled);
4961 } finally {
4962 Binder.restoreCallingIdentity(ident);
4963 }
4964 }
4965 final PrintWriter pr = shellCommand.getOutPrintWriter();
4966 pr.print("Input method ");
4967 pr.print(id);
4968 pr.print(": ");
4969 pr.print((enabled == previouslyEnabled) ? "already " : "now ");
4970 pr.println(enabled ? "enabled" : "disabled");
4971 return ShellCommandResult.SUCCESS;
4972 }
4973
4974 /**
4975 * Handles {@code adb shell ime set}.
4976 * @param shellCommand {@link ShellCommand} object that is handling this command.
4977 * @return Exit code of the command.
4978 */
4979 @BinderThread
4980 @ShellCommandResult
4981 private int handleShellCommandSetInputMethod(@NonNull ShellCommand shellCommand) {
4982 final String id = shellCommand.getNextArgRequired();
4983 setInputMethod(null, id);
4984 final PrintWriter pr = shellCommand.getOutPrintWriter();
4985 pr.print("Input method ");
4986 pr.print(id);
4987 pr.println(" selected");
4988 return ShellCommandResult.SUCCESS;
4989 }
Yohei Yukawacc97ebd2017-12-11 17:54:43 -08004990
4991 /**
4992 * Handles {@code adb shell ime reset-ime}.
4993 * @param shellCommand {@link ShellCommand} object that is handling this command.
4994 * @return Exit code of the command.
4995 */
4996 @BinderThread
4997 @ShellCommandResult
4998 @RequiresPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
4999 private int handleShellCommandResetInputMethod(@NonNull ShellCommand shellCommand) {
5000 if (!calledFromValidUser()) {
5001 shellCommand.getErrPrintWriter().print(
5002 "Must be called from the foreground user or with INTERACT_ACROSS_USERS_FULL");
5003 return ShellCommandResult.FAILURE;
5004 }
5005 synchronized (mMethodMap) {
5006 if (mContext.checkCallingOrSelfPermission(
5007 android.Manifest.permission.WRITE_SECURE_SETTINGS)
5008 != PackageManager.PERMISSION_GRANTED) {
5009 shellCommand.getErrPrintWriter().print(
5010 "Caller must have WRITE_SECURE_SETTINGS permission");
5011 throw new SecurityException(
5012 "Requires permission "
5013 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
5014 }
5015 final String nextIme;
5016 final List<InputMethodInfo> nextEnabledImes;
5017 final long ident = Binder.clearCallingIdentity();
5018 try {
5019 synchronized (mMethodMap) {
5020 hideCurrentInputLocked(0, null);
5021 unbindCurrentMethodLocked(false);
5022 // Reset the current IME
5023 resetSelectedInputMethodAndSubtypeLocked(null);
5024 // Also reset the settings of the current IME
5025 mSettings.putSelectedInputMethod(null);
5026 // Disable all enabled IMEs.
5027 {
5028 final ArrayList<InputMethodInfo> enabledImes =
5029 mSettings.getEnabledInputMethodListLocked();
5030 final int N = enabledImes.size();
5031 for (int i = 0; i < N; ++i) {
5032 setInputMethodEnabledLocked(enabledImes.get(i).getId(), false);
5033 }
5034 }
5035 // Re-enable with default enabled IMEs.
5036 {
5037 final ArrayList<InputMethodInfo> defaultEnabledIme =
5038 InputMethodUtils.getDefaultEnabledImes(mContext, mMethodList);
5039 final int N = defaultEnabledIme.size();
5040 for (int i = 0; i < N; ++i) {
5041 setInputMethodEnabledLocked(defaultEnabledIme.get(i).getId(), true);
5042 }
5043 }
5044 updateInputMethodsFromSettingsLocked(true /* enabledMayChange */);
5045 InputMethodUtils.setNonSelectedSystemImesDisabledUntilUsed(mIPackageManager,
5046 mSettings.getEnabledInputMethodListLocked(),
5047 mSettings.getCurrentUserId(),
5048 mContext.getBasePackageName());
5049 nextIme = mSettings.getSelectedInputMethod();
5050 nextEnabledImes = getEnabledInputMethodList();
5051 }
5052 } finally {
5053 Binder.restoreCallingIdentity(ident);
5054 }
5055 final PrintWriter pr = shellCommand.getOutPrintWriter();
5056 pr.println("Reset current and enabled IMEs");
5057 pr.println("Newly selected IME:");
5058 pr.print(" "); pr.println(nextIme);
5059 pr.println("Newly enabled IMEs:");
5060 {
5061 final int N = nextEnabledImes.size();
5062 for (int i = 0; i < N; ++i) {
5063 pr.print(" ");
5064 pr.println(nextEnabledImes.get(i).getId());
5065 }
5066 }
5067 return ShellCommandResult.SUCCESS;
5068 }
5069 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005070}