aboutsummaryrefslogtreecommitdiffstats
path: root/java/src/com/android/inputmethod
diff options
context:
space:
mode:
Diffstat (limited to 'java/src/com/android/inputmethod')
-rw-r--r--java/src/com/android/inputmethod/compat/AbstractCompatWrapper.java39
-rw-r--r--java/src/com/android/inputmethod/compat/CompatUtils.java156
-rw-r--r--java/src/com/android/inputmethod/compat/EditorInfoCompatUtils.java102
-rw-r--r--java/src/com/android/inputmethod/compat/InputConnectionCompatUtils.java80
-rw-r--r--java/src/com/android/inputmethod/compat/InputMethodInfoCompatWrapper.java59
-rw-r--r--java/src/com/android/inputmethod/compat/InputMethodManagerCompatWrapper.java227
-rw-r--r--java/src/com/android/inputmethod/compat/InputMethodServiceCompatWrapper.java84
-rw-r--r--java/src/com/android/inputmethod/compat/InputMethodSubtypeCompatWrapper.java155
-rw-r--r--java/src/com/android/inputmethod/compat/InputTypeCompatUtils.java118
-rw-r--r--java/src/com/android/inputmethod/compat/SuggestionSpanUtils.java78
-rw-r--r--java/src/com/android/inputmethod/compat/VibratorCompatWrapper.java47
-rw-r--r--java/src/com/android/inputmethod/deprecated/LanguageSwitcherProxy.java90
-rw-r--r--java/src/com/android/inputmethod/deprecated/VoiceProxy.java (renamed from java/src/com/android/inputmethod/voice/VoiceIMEConnector.java)156
-rw-r--r--java/src/com/android/inputmethod/deprecated/compat/VoiceInputLoggerCompatUtils.java36
-rw-r--r--java/src/com/android/inputmethod/deprecated/languageswitcher/InputLanguageSelection.java255
-rw-r--r--java/src/com/android/inputmethod/deprecated/languageswitcher/LanguageSwitcher.java (renamed from java/src/com/android/inputmethod/latin/LanguageSwitcher.java)67
-rw-r--r--java/src/com/android/inputmethod/deprecated/recorrection/Recorrection.java287
-rw-r--r--java/src/com/android/inputmethod/deprecated/recorrection/RecorrectionSuggestionEntries.java62
-rw-r--r--java/src/com/android/inputmethod/deprecated/voice/FieldContext.java (renamed from java/src/com/android/inputmethod/voice/FieldContext.java)2
-rw-r--r--java/src/com/android/inputmethod/deprecated/voice/Hints.java (renamed from java/src/com/android/inputmethod/voice/Hints.java)2
-rw-r--r--java/src/com/android/inputmethod/deprecated/voice/RecognitionView.java (renamed from java/src/com/android/inputmethod/voice/RecognitionView.java)3
-rw-r--r--java/src/com/android/inputmethod/deprecated/voice/SettingsUtil.java (renamed from java/src/com/android/inputmethod/voice/SettingsUtil.java)2
-rw-r--r--java/src/com/android/inputmethod/deprecated/voice/SoundIndicator.java (renamed from java/src/com/android/inputmethod/voice/SoundIndicator.java)2
-rw-r--r--java/src/com/android/inputmethod/deprecated/voice/VoiceInput.java (renamed from java/src/com/android/inputmethod/voice/VoiceInput.java)4
-rw-r--r--java/src/com/android/inputmethod/deprecated/voice/VoiceInputLogger.java (renamed from java/src/com/android/inputmethod/voice/VoiceInputLogger.java)13
-rw-r--r--java/src/com/android/inputmethod/deprecated/voice/WaveformImage.java (renamed from java/src/com/android/inputmethod/voice/WaveformImage.java)2
-rw-r--r--java/src/com/android/inputmethod/deprecated/voice/Whitelist.java (renamed from java/src/com/android/inputmethod/voice/Whitelist.java)2
-rw-r--r--java/src/com/android/inputmethod/keyboard/Key.java69
-rw-r--r--java/src/com/android/inputmethod/keyboard/KeyDetector.java162
-rw-r--r--java/src/com/android/inputmethod/keyboard/KeyStyles.java2
-rw-r--r--java/src/com/android/inputmethod/keyboard/Keyboard.java79
-rw-r--r--java/src/com/android/inputmethod/keyboard/KeyboardId.java62
-rw-r--r--java/src/com/android/inputmethod/keyboard/KeyboardParser.java66
-rw-r--r--java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java414
-rw-r--r--java/src/com/android/inputmethod/keyboard/KeyboardView.java1057
-rw-r--r--java/src/com/android/inputmethod/keyboard/LatinKeyboard.java226
-rw-r--r--java/src/com/android/inputmethod/keyboard/LatinKeyboardView.java51
-rw-r--r--java/src/com/android/inputmethod/keyboard/MiniKeyboard.java7
-rw-r--r--java/src/com/android/inputmethod/keyboard/MiniKeyboardBuilder.java3
-rw-r--r--java/src/com/android/inputmethod/keyboard/MiniKeyboardKeyDetector.java15
-rw-r--r--java/src/com/android/inputmethod/keyboard/PointerTracker.java330
-rw-r--r--java/src/com/android/inputmethod/keyboard/PointerTrackerKeyState.java1
-rw-r--r--java/src/com/android/inputmethod/keyboard/PointerTrackerQueue.java13
-rw-r--r--java/src/com/android/inputmethod/keyboard/PopupMiniKeyboardView.java125
-rw-r--r--java/src/com/android/inputmethod/keyboard/PopupPanel.java46
-rw-r--r--java/src/com/android/inputmethod/keyboard/ProximityKeyDetector.java126
-rw-r--r--java/src/com/android/inputmethod/keyboard/SlidingLocaleDrawable.java8
-rw-r--r--java/src/com/android/inputmethod/latin/AccessibilityUtils.java211
-rw-r--r--java/src/com/android/inputmethod/latin/AssetFileAddress.java52
-rw-r--r--java/src/com/android/inputmethod/latin/AutoCorrection.java10
-rw-r--r--java/src/com/android/inputmethod/latin/AutoDictionary.java11
-rw-r--r--java/src/com/android/inputmethod/latin/BinaryDictionary.java162
-rw-r--r--java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java151
-rw-r--r--java/src/com/android/inputmethod/latin/BinaryDictionaryGetter.java97
-rw-r--r--java/src/com/android/inputmethod/latin/CandidateView.java5
-rw-r--r--java/src/com/android/inputmethod/latin/ContactsDictionary.java15
-rw-r--r--java/src/com/android/inputmethod/latin/DebugSettings.java8
-rw-r--r--java/src/com/android/inputmethod/latin/Dictionary.java10
-rw-r--r--java/src/com/android/inputmethod/latin/DictionaryCollection.java71
-rw-r--r--java/src/com/android/inputmethod/latin/DictionaryFactory.java177
-rw-r--r--java/src/com/android/inputmethod/latin/DictionaryPackInstallBroadcastReceiver.java89
-rw-r--r--java/src/com/android/inputmethod/latin/EditingUtils.java147
-rw-r--r--java/src/com/android/inputmethod/latin/ExpandableDictionary.java71
-rw-r--r--java/src/com/android/inputmethod/latin/Flag.java64
-rw-r--r--java/src/com/android/inputmethod/latin/InputLanguageSelection.java211
-rw-r--r--java/src/com/android/inputmethod/latin/LatinIME.java1236
-rw-r--r--java/src/com/android/inputmethod/latin/LatinImeLogger.java7
-rw-r--r--java/src/com/android/inputmethod/latin/PrivateBinaryDictionaryGetter.java29
-rw-r--r--java/src/com/android/inputmethod/latin/Settings.java331
-rw-r--r--java/src/com/android/inputmethod/latin/SubtypeSwitcher.java389
-rw-r--r--java/src/com/android/inputmethod/latin/Suggest.java184
-rw-r--r--java/src/com/android/inputmethod/latin/SuggestedWords.java8
-rw-r--r--java/src/com/android/inputmethod/latin/SuggestionSpanPickedNotificationReceiver.java43
-rw-r--r--java/src/com/android/inputmethod/latin/TextEntryState.java18
-rw-r--r--java/src/com/android/inputmethod/latin/UserBigramDictionary.java12
-rw-r--r--java/src/com/android/inputmethod/latin/Utils.java235
-rw-r--r--java/src/com/android/inputmethod/latin/WhitelistDictionary.java1
-rw-r--r--java/src/com/android/inputmethod/latin/WordComposer.java14
78 files changed, 5884 insertions, 3177 deletions
diff --git a/java/src/com/android/inputmethod/compat/AbstractCompatWrapper.java b/java/src/com/android/inputmethod/compat/AbstractCompatWrapper.java
new file mode 100644
index 000000000..65949357f
--- /dev/null
+++ b/java/src/com/android/inputmethod/compat/AbstractCompatWrapper.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.inputmethod.compat;
+
+import android.util.Log;
+
+public abstract class AbstractCompatWrapper {
+ private static final String TAG = AbstractCompatWrapper.class.getSimpleName();
+ protected final Object mObj;
+
+ public AbstractCompatWrapper(Object obj) {
+ if (obj == null) {
+ Log.e(TAG, "Invalid input to AbstructCompatWrapper");
+ }
+ mObj = obj;
+ }
+
+ public Object getOriginalObject() {
+ return mObj;
+ }
+
+ public boolean hasOriginalObject() {
+ return mObj != null;
+ }
+}
diff --git a/java/src/com/android/inputmethod/compat/CompatUtils.java b/java/src/com/android/inputmethod/compat/CompatUtils.java
new file mode 100644
index 000000000..6e14bfa8b
--- /dev/null
+++ b/java/src/com/android/inputmethod/compat/CompatUtils.java
@@ -0,0 +1,156 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.inputmethod.compat;
+
+import android.content.Intent;
+import android.text.TextUtils;
+import android.util.Log;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+
+public class CompatUtils {
+ private static final String TAG = CompatUtils.class.getSimpleName();
+ private static final String EXTRA_INPUT_METHOD_ID = "input_method_id";
+ // TODO: Can these be constants instead of literal String constants?
+ private static final String INPUT_METHOD_SUBTYPE_SETTINGS =
+ "android.settings.INPUT_METHOD_SUBTYPE_SETTINGS";
+ private static final String INPUT_LANGUAGE_SELECTION =
+ "com.android.inputmethod.latin.INPUT_LANGUAGE_SELECTION";
+
+ public static Intent getInputLanguageSelectionIntent(String inputMethodId,
+ int flagsForSubtypeSettings) {
+ final String action;
+ Intent intent;
+ if (InputMethodServiceCompatWrapper.CAN_HANDLE_ON_CURRENT_INPUT_METHOD_SUBTYPE_CHANGED
+ /* android.os.Build.VERSION_CODES.HONEYCOMB */
+ && android.os.Build.VERSION.SDK_INT >= 11) {
+ // Refer to android.provider.Settings.ACTION_INPUT_METHOD_SUBTYPE_SETTINGS
+ action = INPUT_METHOD_SUBTYPE_SETTINGS;
+ intent = new Intent(action);
+ if (!TextUtils.isEmpty(inputMethodId)) {
+ intent.putExtra(EXTRA_INPUT_METHOD_ID, inputMethodId);
+ }
+ if (flagsForSubtypeSettings > 0) {
+ intent.setFlags(flagsForSubtypeSettings);
+ }
+ } else {
+ action = INPUT_LANGUAGE_SELECTION;
+ intent = new Intent(action);
+ }
+ return intent;
+ }
+
+ public static Class<?> getClass(String className) {
+ try {
+ return Class.forName(className);
+ } catch (ClassNotFoundException e) {
+ return null;
+ }
+ }
+
+ public static Method getMethod(Class<?> targetClass, String name,
+ Class<?>... parameterTypes) {
+ if (targetClass == null || TextUtils.isEmpty(name)) return null;
+ try {
+ return targetClass.getMethod(name, parameterTypes);
+ } catch (SecurityException e) {
+ // ignore
+ } catch (NoSuchMethodException e) {
+ // ignore
+ }
+ return null;
+ }
+
+ public static Field getField(Class<?> targetClass, String name) {
+ if (targetClass == null || TextUtils.isEmpty(name)) return null;
+ try {
+ return targetClass.getField(name);
+ } catch (SecurityException e) {
+ // ignore
+ } catch (NoSuchFieldException e) {
+ // ignore
+ }
+ return null;
+ }
+
+ public static Constructor<?> getConstructor(Class<?> targetClass, Class<?>[] types) {
+ if (targetClass == null || types == null) return null;
+ try {
+ return targetClass.getConstructor(types);
+ } catch (SecurityException e) {
+ // ignore
+ } catch (NoSuchMethodException e) {
+ // ignore
+ }
+ return null;
+ }
+
+ public static Object newInstance(Constructor<?> constructor, Object[] args) {
+ if (constructor == null) return null;
+ try {
+ return constructor.newInstance(args);
+ } catch (Exception e) {
+ Log.e(TAG, "Exception in newInstance: " + e.getClass().getSimpleName());
+ }
+ return null;
+ }
+
+ public static Object invoke(
+ Object receiver, Object defaultValue, Method method, Object... args) {
+ if (method == null) return defaultValue;
+ try {
+ return method.invoke(receiver, args);
+ } catch (Exception e) {
+ Log.e(TAG, "Exception in invoke: " + e.getClass().getSimpleName());
+ }
+ return defaultValue;
+ }
+
+ public static Object getFieldValue(Object receiver, Object defaultValue, Field field) {
+ if (field == null) return defaultValue;
+ try {
+ return field.get(receiver);
+ } catch (Exception e) {
+ Log.e(TAG, "Exception in getFieldValue: " + e.getClass().getSimpleName());
+ }
+ return defaultValue;
+ }
+
+ public static void setFieldValue(Object receiver, Field field, Object value) {
+ if (field == null) return;
+ try {
+ field.set(receiver, value);
+ } catch (Exception e) {
+ Log.e(TAG, "Exception in setFieldValue: " + e.getClass().getSimpleName());
+ }
+ }
+
+ public static List<InputMethodSubtypeCompatWrapper> copyInputMethodSubtypeListToWrapper(
+ Object listObject) {
+ if (!(listObject instanceof List<?>)) return null;
+ final List<InputMethodSubtypeCompatWrapper> subtypes =
+ new ArrayList<InputMethodSubtypeCompatWrapper>();
+ for (Object o: (List<?>)listObject) {
+ subtypes.add(new InputMethodSubtypeCompatWrapper(o));
+ }
+ return subtypes;
+ }
+}
diff --git a/java/src/com/android/inputmethod/compat/EditorInfoCompatUtils.java b/java/src/com/android/inputmethod/compat/EditorInfoCompatUtils.java
new file mode 100644
index 000000000..2789bcb39
--- /dev/null
+++ b/java/src/com/android/inputmethod/compat/EditorInfoCompatUtils.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.inputmethod.compat;
+
+import android.view.inputmethod.EditorInfo;
+import android.view.inputmethod.InputConnection;
+
+import java.lang.reflect.Field;
+
+public class EditorInfoCompatUtils {
+ private static final Field FIELD_IME_FLAG_NAVIGATE_NEXT = CompatUtils.getField(
+ EditorInfo.class, "IME_FLAG_NAVIGATE_NEXT");
+ private static final Field FIELD_IME_FLAG_NAVIGATE_PREVIOUS = CompatUtils.getField(
+ EditorInfo.class, "IME_FLAG_NAVIGATE_PREVIOUS");
+ private static final Field FIELD_IME_ACTION_PREVIOUS = CompatUtils.getField(
+ EditorInfo.class, "IME_FLAG_ACTION_PREVIOUS");
+ private static final Integer OBJ_IME_FLAG_NAVIGATE_NEXT = (Integer) CompatUtils
+ .getFieldValue(null, null, FIELD_IME_FLAG_NAVIGATE_NEXT);
+ private static final Integer OBJ_IME_FLAG_NAVIGATE_PREVIOUS = (Integer) CompatUtils
+ .getFieldValue(null, null, FIELD_IME_FLAG_NAVIGATE_PREVIOUS);
+ private static final Integer OBJ_IME_ACTION_PREVIOUS = (Integer) CompatUtils
+ .getFieldValue(null, null, FIELD_IME_ACTION_PREVIOUS);
+
+ public static boolean hasFlagNavigateNext(int imeOptions) {
+ if (OBJ_IME_FLAG_NAVIGATE_NEXT == null)
+ return false;
+ return (imeOptions & OBJ_IME_FLAG_NAVIGATE_NEXT) != 0;
+ }
+
+ public static boolean hasFlagNavigatePrevious(int imeOptions) {
+ if (OBJ_IME_FLAG_NAVIGATE_PREVIOUS == null)
+ return false;
+ return (imeOptions & OBJ_IME_FLAG_NAVIGATE_PREVIOUS) != 0;
+ }
+
+ public static void performEditorActionNext(InputConnection ic) {
+ ic.performEditorAction(EditorInfo.IME_ACTION_NEXT);
+ }
+
+ public static void performEditorActionPrevious(InputConnection ic) {
+ if (OBJ_IME_ACTION_PREVIOUS == null)
+ return;
+ ic.performEditorAction(OBJ_IME_ACTION_PREVIOUS);
+ }
+
+ public static String imeOptionsName(int imeOptions) {
+ if (imeOptions == -1)
+ return null;
+ final int actionId = imeOptions & EditorInfo.IME_MASK_ACTION;
+ final String action;
+ switch (actionId) {
+ case EditorInfo.IME_ACTION_UNSPECIFIED:
+ action = "actionUnspecified";
+ break;
+ case EditorInfo.IME_ACTION_NONE:
+ action = "actionNone";
+ break;
+ case EditorInfo.IME_ACTION_GO:
+ action = "actionGo";
+ break;
+ case EditorInfo.IME_ACTION_SEARCH:
+ action = "actionSearch";
+ break;
+ case EditorInfo.IME_ACTION_SEND:
+ action = "actionSend";
+ break;
+ case EditorInfo.IME_ACTION_NEXT:
+ action = "actionNext";
+ break;
+ case EditorInfo.IME_ACTION_DONE:
+ action = "actionDone";
+ break;
+ default: {
+ if (OBJ_IME_ACTION_PREVIOUS != null && actionId == OBJ_IME_ACTION_PREVIOUS) {
+ action = "actionPrevious";
+ } else {
+ action = "actionUnknown(" + actionId + ")";
+ }
+ break;
+ }
+ }
+ if ((imeOptions & EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0) {
+ return "flagNoEnterAction|" + action;
+ } else {
+ return action;
+ }
+ }
+}
diff --git a/java/src/com/android/inputmethod/compat/InputConnectionCompatUtils.java b/java/src/com/android/inputmethod/compat/InputConnectionCompatUtils.java
new file mode 100644
index 000000000..7d00b6007
--- /dev/null
+++ b/java/src/com/android/inputmethod/compat/InputConnectionCompatUtils.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.inputmethod.compat;
+
+import com.android.inputmethod.latin.EditingUtils.SelectedWord;
+
+import android.view.inputmethod.InputConnection;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+
+public class InputConnectionCompatUtils {
+ private static final Class<?> CLASS_CorrectionInfo = CompatUtils
+ .getClass("android.view.inputmethod.CorrectionInfo");
+ private static final Class<?>[] INPUT_TYPE_CorrectionInfo = new Class<?>[] { int.class,
+ CharSequence.class, CharSequence.class };
+ private static final Constructor<?> CONSTRUCTOR_CorrectionInfo = CompatUtils
+ .getConstructor(CLASS_CorrectionInfo, INPUT_TYPE_CorrectionInfo);
+ private static final Method METHOD_InputConnection_commitCorrection = CompatUtils
+ .getMethod(InputConnection.class, "commitCorrection", CLASS_CorrectionInfo);
+ private static final Method METHOD_getSelectedText = CompatUtils
+ .getMethod(InputConnection.class, "getSelectedText", int.class);
+ private static final Method METHOD_setComposingRegion = CompatUtils
+ .getMethod(InputConnection.class, "setComposingRegion", int.class, int.class);
+ public static final boolean RECORRECTION_SUPPORTED;
+
+ static {
+ RECORRECTION_SUPPORTED = METHOD_getSelectedText != null
+ && METHOD_setComposingRegion != null;
+ }
+
+ public static void commitCorrection(InputConnection ic, int offset, CharSequence oldText,
+ CharSequence newText) {
+ if (ic == null || CONSTRUCTOR_CorrectionInfo == null
+ || METHOD_InputConnection_commitCorrection == null) {
+ return;
+ }
+ Object[] args = { offset, oldText, newText };
+ Object correctionInfo = CompatUtils.newInstance(CONSTRUCTOR_CorrectionInfo, args);
+ if (correctionInfo != null) {
+ CompatUtils.invoke(ic, null, METHOD_InputConnection_commitCorrection,
+ correctionInfo);
+ }
+ }
+
+
+ /**
+ * Returns the selected text between the selStart and selEnd positions.
+ */
+ public static CharSequence getSelectedText(InputConnection ic, int selStart, int selEnd) {
+ // Use reflection, for backward compatibility
+ return (CharSequence) CompatUtils.invoke(
+ ic, null, METHOD_getSelectedText, 0);
+ }
+
+ /**
+ * Tries to set the text into composition mode if there is support for it in the framework.
+ */
+ public static void underlineWord(InputConnection ic, SelectedWord word) {
+ // Use reflection, for backward compatibility
+ // If method not found, there's nothing we can do. It still works but just wont underline
+ // the word.
+ CompatUtils.invoke(
+ ic, null, METHOD_setComposingRegion, word.mStart, word.mEnd);
+ }
+}
diff --git a/java/src/com/android/inputmethod/compat/InputMethodInfoCompatWrapper.java b/java/src/com/android/inputmethod/compat/InputMethodInfoCompatWrapper.java
new file mode 100644
index 000000000..8e22bbc79
--- /dev/null
+++ b/java/src/com/android/inputmethod/compat/InputMethodInfoCompatWrapper.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.inputmethod.compat;
+
+import android.content.pm.ServiceInfo;
+import android.view.inputmethod.InputMethodInfo;
+
+import java.lang.reflect.Method;
+
+public class InputMethodInfoCompatWrapper {
+ private final InputMethodInfo mImi;
+ private static final Method METHOD_getSubtypeAt = CompatUtils.getMethod(
+ InputMethodInfo.class, "getSubtypeAt", int.class);
+ private static final Method METHOD_getSubtypeCount = CompatUtils.getMethod(
+ InputMethodInfo.class, "getSubtypeCount");
+
+ public InputMethodInfoCompatWrapper(InputMethodInfo imi) {
+ mImi = imi;
+ }
+
+ public InputMethodInfo getInputMethodInfo() {
+ return mImi;
+ }
+
+ public String getId() {
+ return mImi.getId();
+ }
+
+ public String getPackageName() {
+ return mImi.getPackageName();
+ }
+
+ public ServiceInfo getServiceInfo() {
+ return mImi.getServiceInfo();
+ }
+
+ public int getSubtypeCount() {
+ return (Integer) CompatUtils.invoke(mImi, 0, METHOD_getSubtypeCount);
+ }
+
+ public InputMethodSubtypeCompatWrapper getSubtypeAt(int index) {
+ return new InputMethodSubtypeCompatWrapper(CompatUtils.invoke(mImi, null,
+ METHOD_getSubtypeAt, index));
+ }
+}
diff --git a/java/src/com/android/inputmethod/compat/InputMethodManagerCompatWrapper.java b/java/src/com/android/inputmethod/compat/InputMethodManagerCompatWrapper.java
new file mode 100644
index 000000000..1cc13f249
--- /dev/null
+++ b/java/src/com/android/inputmethod/compat/InputMethodManagerCompatWrapper.java
@@ -0,0 +1,227 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.inputmethod.compat;
+
+import com.android.inputmethod.deprecated.LanguageSwitcherProxy;
+import com.android.inputmethod.latin.LatinIME;
+import com.android.inputmethod.latin.SubtypeSwitcher;
+import com.android.inputmethod.latin.Utils;
+
+import android.content.Context;
+import android.os.IBinder;
+import android.text.TextUtils;
+import android.util.Log;
+import android.view.inputmethod.InputMethodInfo;
+import android.view.inputmethod.InputMethodManager;
+
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+// TODO: Override this class with the concrete implementation if we need to take care of the
+// performance.
+public class InputMethodManagerCompatWrapper {
+ private static final String TAG = InputMethodManagerCompatWrapper.class.getSimpleName();
+ private static final Method METHOD_getCurrentInputMethodSubtype =
+ CompatUtils.getMethod(InputMethodManager.class, "getCurrentInputMethodSubtype");
+ private static final Method METHOD_getEnabledInputMethodSubtypeList =
+ CompatUtils.getMethod(InputMethodManager.class, "getEnabledInputMethodSubtypeList",
+ InputMethodInfo.class, boolean.class);
+ private static final Method METHOD_getShortcutInputMethodsAndSubtypes =
+ CompatUtils.getMethod(InputMethodManager.class, "getShortcutInputMethodsAndSubtypes");
+ private static final Method METHOD_setInputMethodAndSubtype =
+ CompatUtils.getMethod(
+ InputMethodManager.class, "setInputMethodAndSubtype", IBinder.class,
+ String.class, InputMethodSubtypeCompatWrapper.CLASS_InputMethodSubtype);
+ private static final Method METHOD_switchToLastInputMethod = CompatUtils.getMethod(
+ InputMethodManager.class, "switchToLastInputMethod", IBinder.class);
+
+ private static final InputMethodManagerCompatWrapper sInstance =
+ new InputMethodManagerCompatWrapper();
+
+ public static final boolean SUBTYPE_SUPPORTED;
+
+ static {
+ // This static initializer guarantees that METHOD_getShortcutInputMethodsAndSubtypes is
+ // already instantiated.
+ SUBTYPE_SUPPORTED = METHOD_getShortcutInputMethodsAndSubtypes != null;
+ }
+
+ // For the compatibility, IMM will create dummy subtypes if subtypes are not found.
+ // This is required to be false if the current behavior is broken. For now, it's ok to be true.
+ public static final boolean FORCE_ENABLE_VOICE_EVEN_WITH_NO_VOICE_SUBTYPES =
+ !InputMethodServiceCompatWrapper.CAN_HANDLE_ON_CURRENT_INPUT_METHOD_SUBTYPE_CHANGED;
+ private static final String VOICE_MODE = "voice";
+ private static final String KEYBOARD_MODE = "keyboard";
+
+ private InputMethodManager mImm;
+ private LanguageSwitcherProxy mLanguageSwitcherProxy;
+ private String mLatinImePackageName;
+
+ private InputMethodManagerCompatWrapper() {
+ }
+
+ public static InputMethodManagerCompatWrapper getInstance(Context context) {
+ if (sInstance.mImm == null) {
+ sInstance.init(context);
+ }
+ return sInstance;
+ }
+
+ private synchronized void init(Context context) {
+ mImm = (InputMethodManager) context.getSystemService(
+ Context.INPUT_METHOD_SERVICE);
+ if (context instanceof LatinIME) {
+ mLatinImePackageName = context.getPackageName();
+ }
+ mLanguageSwitcherProxy = LanguageSwitcherProxy.getInstance();
+ }
+
+ public InputMethodSubtypeCompatWrapper getCurrentInputMethodSubtype() {
+ if (!SUBTYPE_SUPPORTED) {
+ return new InputMethodSubtypeCompatWrapper(
+ 0, 0, mLanguageSwitcherProxy.getInputLocale().toString(), KEYBOARD_MODE, "");
+ }
+ Object o = CompatUtils.invoke(mImm, null, METHOD_getCurrentInputMethodSubtype);
+ return new InputMethodSubtypeCompatWrapper(o);
+ }
+
+ public List<InputMethodSubtypeCompatWrapper> getEnabledInputMethodSubtypeList(
+ InputMethodInfoCompatWrapper imi, boolean allowsImplicitlySelectedSubtypes) {
+ if (!SUBTYPE_SUPPORTED) {
+ String[] languages = mLanguageSwitcherProxy.getEnabledLanguages(
+ allowsImplicitlySelectedSubtypes);
+ List<InputMethodSubtypeCompatWrapper> subtypeList =
+ new ArrayList<InputMethodSubtypeCompatWrapper>();
+ for (String lang: languages) {
+ subtypeList.add(new InputMethodSubtypeCompatWrapper(0, 0, lang, KEYBOARD_MODE, ""));
+ }
+ return subtypeList;
+ }
+ Object retval = CompatUtils.invoke(mImm, null, METHOD_getEnabledInputMethodSubtypeList,
+ (imi != null ? imi.getInputMethodInfo() : null), allowsImplicitlySelectedSubtypes);
+ if (retval == null || !(retval instanceof List<?>) || ((List<?>)retval).isEmpty()) {
+ if (!FORCE_ENABLE_VOICE_EVEN_WITH_NO_VOICE_SUBTYPES) {
+ // Returns an empty list
+ return Collections.emptyList();
+ }
+ // Creates dummy subtypes
+ @SuppressWarnings("unused")
+ List<InputMethodSubtypeCompatWrapper> subtypeList =
+ new ArrayList<InputMethodSubtypeCompatWrapper>();
+ InputMethodSubtypeCompatWrapper keyboardSubtype = getLastResortSubtype(KEYBOARD_MODE);
+ InputMethodSubtypeCompatWrapper voiceSubtype = getLastResortSubtype(VOICE_MODE);
+ if (keyboardSubtype != null) {
+ subtypeList.add(keyboardSubtype);
+ }
+ if (voiceSubtype != null) {
+ subtypeList.add(voiceSubtype);
+ }
+ return subtypeList;
+ }
+ return CompatUtils.copyInputMethodSubtypeListToWrapper(retval);
+ }
+
+ private InputMethodInfoCompatWrapper getLatinImeInputMethodInfo() {
+ if (TextUtils.isEmpty(mLatinImePackageName))
+ return null;
+ return Utils.getInputMethodInfo(this, mLatinImePackageName);
+ }
+
+ @SuppressWarnings("unused")
+ private InputMethodSubtypeCompatWrapper getLastResortSubtype(String mode) {
+ if (VOICE_MODE.equals(mode) && !FORCE_ENABLE_VOICE_EVEN_WITH_NO_VOICE_SUBTYPES)
+ return null;
+ Locale inputLocale = SubtypeSwitcher.getInstance().getInputLocale();
+ if (inputLocale == null)
+ return null;
+ return new InputMethodSubtypeCompatWrapper(0, 0, inputLocale.toString(), mode, "");
+ }
+
+ public Map<InputMethodInfoCompatWrapper, List<InputMethodSubtypeCompatWrapper>>
+ getShortcutInputMethodsAndSubtypes() {
+ Object retval = CompatUtils.invoke(mImm, null, METHOD_getShortcutInputMethodsAndSubtypes);
+ if (retval == null || !(retval instanceof Map<?, ?>) || ((Map<?, ?>)retval).isEmpty()) {
+ if (!FORCE_ENABLE_VOICE_EVEN_WITH_NO_VOICE_SUBTYPES) {
+ // Returns an empty map
+ return Collections.emptyMap();
+ }
+ // Creates dummy subtypes
+ @SuppressWarnings("unused")
+ InputMethodInfoCompatWrapper imi = getLatinImeInputMethodInfo();
+ InputMethodSubtypeCompatWrapper voiceSubtype = getLastResortSubtype(VOICE_MODE);
+ if (imi != null && voiceSubtype != null) {
+ Map<InputMethodInfoCompatWrapper, List<InputMethodSubtypeCompatWrapper>>
+ shortcutMap =
+ new HashMap<InputMethodInfoCompatWrapper,
+ List<InputMethodSubtypeCompatWrapper>>();
+ List<InputMethodSubtypeCompatWrapper> subtypeList =
+ new ArrayList<InputMethodSubtypeCompatWrapper>();
+ subtypeList.add(voiceSubtype);
+ shortcutMap.put(imi, subtypeList);
+ return shortcutMap;
+ } else {
+ return Collections.emptyMap();
+ }
+ }
+ Map<InputMethodInfoCompatWrapper, List<InputMethodSubtypeCompatWrapper>> shortcutMap =
+ new HashMap<InputMethodInfoCompatWrapper, List<InputMethodSubtypeCompatWrapper>>();
+ final Map<?, ?> retvalMap = (Map<?, ?>)retval;
+ for (Object key : retvalMap.keySet()) {
+ if (!(key instanceof InputMethodInfo)) {
+ Log.e(TAG, "Class type error.");
+ return null;
+ }
+ shortcutMap.put(new InputMethodInfoCompatWrapper((InputMethodInfo)key),
+ CompatUtils.copyInputMethodSubtypeListToWrapper(retvalMap.get(key)));
+ }
+ return shortcutMap;
+ }
+
+ public void setInputMethodAndSubtype(
+ IBinder token, String id, InputMethodSubtypeCompatWrapper subtype) {
+ if (subtype != null && subtype.hasOriginalObject()) {
+ CompatUtils.invoke(mImm, null, METHOD_setInputMethodAndSubtype,
+ token, id, subtype.getOriginalObject());
+ }
+ }
+
+ public boolean switchToLastInputMethod(IBinder token) {
+ if (SubtypeSwitcher.getInstance().isDummyVoiceMode()) {
+ return true;
+ }
+ return (Boolean)CompatUtils.invoke(mImm, false, METHOD_switchToLastInputMethod, token);
+ }
+
+ public List<InputMethodInfoCompatWrapper> getEnabledInputMethodList() {
+ if (mImm == null) return null;
+ List<InputMethodInfoCompatWrapper> imis = new ArrayList<InputMethodInfoCompatWrapper>();
+ for (InputMethodInfo imi : mImm.getEnabledInputMethodList()) {
+ imis.add(new InputMethodInfoCompatWrapper(imi));
+ }
+ return imis;
+ }
+
+ public void showInputMethodPicker() {
+ if (mImm == null) return;
+ mImm.showInputMethodPicker();
+ }
+}
diff --git a/java/src/com/android/inputmethod/compat/InputMethodServiceCompatWrapper.java b/java/src/com/android/inputmethod/compat/InputMethodServiceCompatWrapper.java
new file mode 100644
index 000000000..828aea41f
--- /dev/null
+++ b/java/src/com/android/inputmethod/compat/InputMethodServiceCompatWrapper.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.inputmethod.compat;
+
+import com.android.inputmethod.deprecated.LanguageSwitcherProxy;
+import com.android.inputmethod.latin.SubtypeSwitcher;
+
+import android.inputmethodservice.InputMethodService;
+import android.view.inputmethod.InputMethodSubtype;
+
+public class InputMethodServiceCompatWrapper extends InputMethodService {
+ // CAN_HANDLE_ON_CURRENT_INPUT_METHOD_SUBTYPE_CHANGED needs to be false if the API level is 10
+ // or previous. Note that InputMethodSubtype was added in the API level 11.
+ // For the API level 11 or later, LatinIME should override onCurrentInputMethodSubtypeChanged().
+ // For the API level 10 or previous, we handle the "subtype changed" events by ourselves
+ // without having support from framework -- onCurrentInputMethodSubtypeChanged().
+ public static final boolean CAN_HANDLE_ON_CURRENT_INPUT_METHOD_SUBTYPE_CHANGED = true;
+
+ private InputMethodManagerCompatWrapper mImm;
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ mImm = InputMethodManagerCompatWrapper.getInstance(this);
+ }
+
+ // When the API level is 10 or previous, notifyOnCurrentInputMethodSubtypeChanged should
+ // handle the event the current subtype was changed. LatinIME calls
+ // notifyOnCurrentInputMethodSubtypeChanged every time LatinIME
+ // changes the current subtype.
+ // This call is required to let LatinIME itself know a subtype changed
+ // event when the API level is 10 or previous.
+ @SuppressWarnings("unused")
+ public void notifyOnCurrentInputMethodSubtypeChanged(InputMethodSubtypeCompatWrapper subtype) {
+ // Do nothing when the API level is 11 or later
+ // and FORCE_ENABLE_VOICE_EVEN_WITH_NO_VOICE_SUBTYPES is not true
+ if (CAN_HANDLE_ON_CURRENT_INPUT_METHOD_SUBTYPE_CHANGED && !InputMethodManagerCompatWrapper.
+ FORCE_ENABLE_VOICE_EVEN_WITH_NO_VOICE_SUBTYPES) {
+ return;
+ }
+ if (subtype == null) {
+ subtype = mImm.getCurrentInputMethodSubtype();
+ }
+ if (subtype != null) {
+ if (!InputMethodManagerCompatWrapper.FORCE_ENABLE_VOICE_EVEN_WITH_NO_VOICE_SUBTYPES
+ && !subtype.isDummy()) return;
+ if (!InputMethodManagerCompatWrapper.SUBTYPE_SUPPORTED) {
+ LanguageSwitcherProxy.getInstance().setLocale(subtype.getLocale());
+ }
+ SubtypeSwitcher.getInstance().updateSubtype(subtype);
+ }
+ }
+
+ //////////////////////////////////////
+ // Functions using API v11 or later //
+ //////////////////////////////////////
+ @Override
+ public void onCurrentInputMethodSubtypeChanged(InputMethodSubtype subtype) {
+ // Do nothing when the API level is 10 or previous
+ if (!CAN_HANDLE_ON_CURRENT_INPUT_METHOD_SUBTYPE_CHANGED) return;
+ SubtypeSwitcher.getInstance().updateSubtype(
+ new InputMethodSubtypeCompatWrapper(subtype));
+ }
+
+ protected static void setTouchableRegionCompat(InputMethodService.Insets outInsets,
+ int x, int y, int width, int height) {
+ outInsets.touchableInsets = InputMethodService.Insets.TOUCHABLE_INSETS_REGION;
+ outInsets.touchableRegion.set(x, y, width, height);
+ }
+}
diff --git a/java/src/com/android/inputmethod/compat/InputMethodSubtypeCompatWrapper.java b/java/src/com/android/inputmethod/compat/InputMethodSubtypeCompatWrapper.java
new file mode 100644
index 000000000..806c355a9
--- /dev/null
+++ b/java/src/com/android/inputmethod/compat/InputMethodSubtypeCompatWrapper.java
@@ -0,0 +1,155 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.inputmethod.compat;
+
+import com.android.inputmethod.latin.LatinImeLogger;
+
+import android.text.TextUtils;
+import android.util.Log;
+
+import java.lang.reflect.Method;
+import java.util.Arrays;
+
+// TODO: Override this class with the concrete implementation if we need to take care of the
+// performance.
+public final class InputMethodSubtypeCompatWrapper extends AbstractCompatWrapper {
+ private static final boolean DBG = LatinImeLogger.sDBG;
+ private static final String TAG = InputMethodSubtypeCompatWrapper.class.getSimpleName();
+ private static final String DEFAULT_LOCALE = "en_US";
+ private static final String DEFAULT_MODE = "keyboard";
+
+ public static final Class<?> CLASS_InputMethodSubtype =
+ CompatUtils.getClass("android.view.inputmethod.InputMethodSubtype");
+ private static final Method METHOD_getNameResId =
+ CompatUtils.getMethod(CLASS_InputMethodSubtype, "getNameResId");
+ private static final Method METHOD_getIconResId =
+ CompatUtils.getMethod(CLASS_InputMethodSubtype, "getIconResId");
+ private static final Method METHOD_getLocale =
+ CompatUtils.getMethod(CLASS_InputMethodSubtype, "getLocale");
+ private static final Method METHOD_getMode =
+ CompatUtils.getMethod(CLASS_InputMethodSubtype, "getMode");
+ private static final Method METHOD_getExtraValue =
+ CompatUtils.getMethod(CLASS_InputMethodSubtype, "getExtraValue");
+ private static final Method METHOD_containsExtraValueKey =
+ CompatUtils.getMethod(CLASS_InputMethodSubtype, "containsExtraValueKey", String.class);
+ private static final Method METHOD_getExtraValueOf =
+ CompatUtils.getMethod(CLASS_InputMethodSubtype, "getExtraValueOf", String.class);
+
+ private final int mDummyNameResId;
+ private final int mDummyIconResId;
+ private final String mDummyLocale;
+ private final String mDummyMode;
+ private final String mDummyExtraValues;
+
+ public InputMethodSubtypeCompatWrapper(Object subtype) {
+ super((CLASS_InputMethodSubtype != null && CLASS_InputMethodSubtype.isInstance(subtype))
+ ? subtype : null);
+ mDummyNameResId = 0;
+ mDummyIconResId = 0;
+ mDummyLocale = DEFAULT_LOCALE;
+ mDummyMode = DEFAULT_MODE;
+ mDummyExtraValues = "";
+ }
+
+ // Constructor for creating a dummy subtype.
+ public InputMethodSubtypeCompatWrapper(int nameResId, int iconResId, String locale,
+ String mode, String extraValues) {
+ super(null);
+ if (DBG) {
+ Log.d(TAG, "CreateInputMethodSubtypeCompatWrapper");
+ }
+ mDummyNameResId = nameResId;
+ mDummyIconResId = iconResId;
+ mDummyLocale = locale != null ? locale : "";
+ mDummyMode = mode != null ? mode : "";
+ mDummyExtraValues = extraValues != null ? extraValues : "";
+ }
+
+ public int getNameResId() {
+ if (mObj == null) return mDummyNameResId;
+ return (Integer)CompatUtils.invoke(mObj, 0, METHOD_getNameResId);
+ }
+
+ public int getIconResId() {
+ if (mObj == null) return mDummyIconResId;
+ return (Integer)CompatUtils.invoke(mObj, 0, METHOD_getIconResId);
+ }
+
+ public String getLocale() {
+ if (mObj == null) return mDummyLocale;
+ final String s = (String)CompatUtils.invoke(mObj, null, METHOD_getLocale);
+ if (TextUtils.isEmpty(s)) return DEFAULT_LOCALE;
+ return s;
+ }
+
+ public String getMode() {
+ if (mObj == null) return mDummyMode;
+ String s = (String)CompatUtils.invoke(mObj, null, METHOD_getMode);
+ if (TextUtils.isEmpty(s)) return DEFAULT_MODE;
+ return s;
+ }
+
+ public String getExtraValue() {
+ if (mObj == null) return mDummyExtraValues;
+ return (String)CompatUtils.invoke(mObj, null, METHOD_getExtraValue);
+ }
+
+ public boolean containsExtraValueKey(String key) {
+ return (Boolean)CompatUtils.invoke(mObj, false, METHOD_containsExtraValueKey, key);
+ }
+
+ public String getExtraValueOf(String key) {
+ return (String)CompatUtils.invoke(mObj, null, METHOD_getExtraValueOf, key);
+ }
+
+ public boolean isDummy() {
+ return !hasOriginalObject();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o instanceof InputMethodSubtypeCompatWrapper) {
+ InputMethodSubtypeCompatWrapper subtype = (InputMethodSubtypeCompatWrapper)o;
+ if (mObj == null) {
+ // easy check of dummy subtypes
+ return (mDummyNameResId == subtype.mDummyNameResId
+ && mDummyIconResId == subtype.mDummyIconResId
+ && mDummyLocale.equals(subtype.mDummyLocale)
+ && mDummyMode.equals(subtype.mDummyMode)
+ && mDummyExtraValues.equals(subtype.mDummyExtraValues));
+ }
+ return mObj.equals(subtype.getOriginalObject());
+ } else {
+ return mObj.equals(o);
+ }
+ }
+
+ @Override
+ public int hashCode() {
+ if (mObj == null) {
+ return hashCodeInternal(mDummyNameResId, mDummyIconResId, mDummyLocale,
+ mDummyMode, mDummyExtraValues);
+ }
+ return mObj.hashCode();
+ }
+
+ private static int hashCodeInternal(int nameResId, int iconResId, String locale,
+ String mode, String extraValue) {
+ return Arrays
+ .hashCode(new Object[] { nameResId, iconResId, locale, mode, extraValue });
+ }
+}
diff --git a/java/src/com/android/inputmethod/compat/InputTypeCompatUtils.java b/java/src/com/android/inputmethod/compat/InputTypeCompatUtils.java
new file mode 100644
index 000000000..6c2f0f799
--- /dev/null
+++ b/java/src/com/android/inputmethod/compat/InputTypeCompatUtils.java
@@ -0,0 +1,118 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package com.android.inputmethod.compat;
+
+import android.text.InputType;
+
+import java.lang.reflect.Field;
+
+public class InputTypeCompatUtils {
+ private static final Field FIELD_InputType_TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS =
+ CompatUtils.getField(InputType.class, "TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS");
+ private static final Field FIELD_InputType_TYPE_TEXT_VARIATION_WEB_PASSWORD = CompatUtils
+ .getField(InputType.class, "TYPE_TEXT_VARIATION_WEB_PASSWORD");
+ private static final Field FIELD_InputType_TYPE_NUMBER_VARIATION_PASSWORD = CompatUtils
+ .getField(InputType.class, "TYPE_NUMBER_VARIATION_PASSWORD");
+ private static final Integer OBJ_InputType_TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS =
+ (Integer) CompatUtils.getFieldValue(null, null,
+ FIELD_InputType_TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS);
+ private static final Integer OBJ_InputType_TYPE_TEXT_VARIATION_WEB_PASSWORD =
+ (Integer) CompatUtils.getFieldValue(null, null,
+ FIELD_InputType_TYPE_TEXT_VARIATION_WEB_PASSWORD);
+ private static final Integer OBJ_InputType_TYPE_NUMBER_VARIATION_PASSWORD =
+ (Integer) CompatUtils.getFieldValue(null, null,
+ FIELD_InputType_TYPE_NUMBER_VARIATION_PASSWORD);
+ private static final int WEB_TEXT_PASSWORD_INPUT_TYPE;
+ private static final int WEB_TEXT_EMAIL_ADDRESS_INPUT_TYPE;
+ private static final int NUMBER_PASSWORD_INPUT_TYPE;
+ private static final int TEXT_PASSWORD_INPUT_TYPE =
+ InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
+ private static final int TEXT_VISIBLE_PASSWORD_INPUT_TYPE =
+ InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;
+
+ static {
+ WEB_TEXT_PASSWORD_INPUT_TYPE =
+ OBJ_InputType_TYPE_TEXT_VARIATION_WEB_PASSWORD != null
+ ? InputType.TYPE_CLASS_TEXT | OBJ_InputType_TYPE_TEXT_VARIATION_WEB_PASSWORD
+ : 0;
+ WEB_TEXT_EMAIL_ADDRESS_INPUT_TYPE =
+ OBJ_InputType_TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS != null
+ ? InputType.TYPE_CLASS_TEXT
+ | OBJ_InputType_TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS
+ : 0;
+ NUMBER_PASSWORD_INPUT_TYPE =
+ OBJ_InputType_TYPE_NUMBER_VARIATION_PASSWORD != null
+ ? InputType.TYPE_CLASS_NUMBER | OBJ_InputType_TYPE_NUMBER_VARIATION_PASSWORD
+ : 0;
+ }
+
+ private static boolean isWebEditTextInputType(int inputType) {
+ return inputType == (InputType.TYPE_CLASS_TEXT
+ | InputType.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT);
+ }
+
+ private static boolean isWebPasswordInputType(int inputType) {
+ return WEB_TEXT_PASSWORD_INPUT_TYPE != 0
+ && inputType == WEB_TEXT_PASSWORD_INPUT_TYPE;
+ }
+
+ private static boolean isWebEmailAddressInputType(int inputType) {
+ return WEB_TEXT_EMAIL_ADDRESS_INPUT_TYPE != 0
+ && inputType == WEB_TEXT_EMAIL_ADDRESS_INPUT_TYPE;
+ }
+
+ private static boolean isNumberPasswordInputType(int inputType) {
+ return NUMBER_PASSWORD_INPUT_TYPE != 0
+ && inputType == NUMBER_PASSWORD_INPUT_TYPE;
+ }
+
+ private static boolean isTextPasswordInputType(int inputType) {
+ return inputType == TEXT_PASSWORD_INPUT_TYPE;
+ }
+
+ private static boolean isWebEmailAddressVariation(int variation) {
+ return OBJ_InputType_TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS != null
+ && variation == OBJ_InputType_TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS;
+ }
+
+ public static boolean isEmailVariation(int variation) {
+ return variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
+ || isWebEmailAddressVariation(variation);
+ }
+
+ public static boolean isWebInputType(int inputType) {
+ final int maskedInputType =
+ inputType & (InputType.TYPE_MASK_CLASS | InputType.TYPE_MASK_VARIATION);
+ return isWebEditTextInputType(maskedInputType) || isWebPasswordInputType(maskedInputType)
+ || isWebEmailAddressInputType(maskedInputType);
+ }
+
+ // Please refer to TextView.isPasswordInputType
+ public static boolean isPasswordInputType(int inputType) {
+ final int maskedInputType =
+ inputType & (InputType.TYPE_MASK_CLASS | InputType.TYPE_MASK_VARIATION);
+ return isTextPasswordInputType(maskedInputType) || isWebPasswordInputType(maskedInputType)
+ || isNumberPasswordInputType(maskedInputType);
+ }
+
+ // Please refer to TextView.isVisiblePasswordInputType
+ public static boolean isVisiblePasswordInputType(int inputType) {
+ final int maskedInputType =
+ inputType & (InputType.TYPE_MASK_CLASS | InputType.TYPE_MASK_VARIATION);
+ return maskedInputType == TEXT_VISIBLE_PASSWORD_INPUT_TYPE;
+ }
+}
diff --git a/java/src/com/android/inputmethod/compat/SuggestionSpanUtils.java b/java/src/com/android/inputmethod/compat/SuggestionSpanUtils.java
new file mode 100644
index 000000000..5b02de36e
--- /dev/null
+++ b/java/src/com/android/inputmethod/compat/SuggestionSpanUtils.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.inputmethod.compat;
+
+import com.android.inputmethod.latin.SuggestedWords;
+import com.android.inputmethod.latin.SuggestionSpanPickedNotificationReceiver;
+
+import android.content.Context;
+import android.text.Spannable;
+import android.text.SpannableString;
+import android.text.Spanned;
+
+import java.lang.reflect.Constructor;
+import java.util.Locale;
+
+public class SuggestionSpanUtils {
+ public static final String ACTION_SUGGESTION_PICKED =
+ "android.text.style.SUGGESTION_PICKED";
+ public static final String SUGGESTION_SPAN_PICKED_AFTER = "after";
+ public static final String SUGGESTION_SPAN_PICKED_BEFORE = "before";
+ public static final String SUGGESTION_SPAN_PICKED_HASHCODE = "hashcode";
+
+ private static final Class<?> CLASS_SuggestionSpan = CompatUtils
+ .getClass("android.text.style.SuggestionSpan");
+ private static final Class<?>[] INPUT_TYPE_SuggestionSpan = new Class<?>[] {
+ Context.class, Locale.class, String[].class, int.class, Class.class };
+ private static final Constructor<?> CONSTRUCTOR_SuggestionSpan = CompatUtils
+ .getConstructor(CLASS_SuggestionSpan, INPUT_TYPE_SuggestionSpan);
+ public static final boolean SUGGESTION_SPAN_IS_SUPPORTED;
+ static {
+ SUGGESTION_SPAN_IS_SUPPORTED =
+ CLASS_SuggestionSpan != null && CONSTRUCTOR_SuggestionSpan != null;
+ }
+
+ public static CharSequence getTextWithSuggestionSpan(Context context,
+ CharSequence suggestion, SuggestedWords suggestedWords) {
+ if (CONSTRUCTOR_SuggestionSpan == null || suggestedWords == null
+ || suggestedWords.size() == 0) {
+ return suggestion;
+ }
+
+ final Spannable spannable;
+ if (suggestion instanceof Spannable) {
+ spannable = (Spannable) suggestion;
+ } else {
+ spannable = new SpannableString(suggestion);
+ }
+ // TODO: Use SUGGESTIONS_MAX_SIZE instead of 5.
+ final int N = Math.min(5, suggestedWords.size());
+ final String[] suggestionsArray = new String[N];
+ for (int i = 0; i < N; ++i) {
+ suggestionsArray[i] = suggestedWords.getWord(i).toString();
+ }
+ final Object[] args =
+ { context, null, suggestionsArray, 0,
+ (Class<?>) SuggestionSpanPickedNotificationReceiver.class };
+ final Object ss = CompatUtils.newInstance(CONSTRUCTOR_SuggestionSpan, args);
+ if (ss == null) {
+ return suggestion;
+ }
+ spannable.setSpan(ss, 0, suggestion.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
+ return spannable;
+ }
+}
diff --git a/java/src/com/android/inputmethod/compat/VibratorCompatWrapper.java b/java/src/com/android/inputmethod/compat/VibratorCompatWrapper.java
new file mode 100644
index 000000000..8e2a2e0b8
--- /dev/null
+++ b/java/src/com/android/inputmethod/compat/VibratorCompatWrapper.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.inputmethod.compat;
+
+import android.content.Context;
+import android.os.Vibrator;
+
+import java.lang.reflect.Method;
+
+public class VibratorCompatWrapper {
+ private static final Method METHOD_hasVibrator = CompatUtils.getMethod(Vibrator.class,
+ "hasVibrator", int.class);
+
+ private static final VibratorCompatWrapper sInstance = new VibratorCompatWrapper();
+ private Vibrator mVibrator;
+
+ private VibratorCompatWrapper() {
+ }
+
+ public static VibratorCompatWrapper getInstance(Context context) {
+ if (sInstance.mVibrator == null) {
+ sInstance.mVibrator =
+ (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
+ }
+ return sInstance;
+ }
+
+ public boolean hasVibrator() {
+ if (mVibrator == null)
+ return false;
+ return (Boolean) CompatUtils.invoke(mVibrator, true, METHOD_hasVibrator);
+ }
+}
diff --git a/java/src/com/android/inputmethod/deprecated/LanguageSwitcherProxy.java b/java/src/com/android/inputmethod/deprecated/LanguageSwitcherProxy.java
new file mode 100644
index 000000000..290e6b554
--- /dev/null
+++ b/java/src/com/android/inputmethod/deprecated/LanguageSwitcherProxy.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package com.android.inputmethod.deprecated;
+
+import com.android.inputmethod.compat.InputMethodManagerCompatWrapper;
+import com.android.inputmethod.deprecated.languageswitcher.LanguageSwitcher;
+import com.android.inputmethod.latin.LatinIME;
+import com.android.inputmethod.latin.Settings;
+
+import android.content.SharedPreferences;
+import android.content.res.Configuration;
+
+import java.util.Locale;
+
+// This class is used only when the IME doesn't use method.xml for language switching.
+public class LanguageSwitcherProxy implements SharedPreferences.OnSharedPreferenceChangeListener {
+ private static final LanguageSwitcherProxy sInstance = new LanguageSwitcherProxy();
+ private LatinIME mService;
+ private LanguageSwitcher mLanguageSwitcher;
+ private SharedPreferences mPrefs;
+
+ public static LanguageSwitcherProxy getInstance() {
+ if (InputMethodManagerCompatWrapper.SUBTYPE_SUPPORTED) return null;
+ return sInstance;
+ }
+
+ public static void init(LatinIME service, SharedPreferences prefs) {
+ if (InputMethodManagerCompatWrapper.SUBTYPE_SUPPORTED) return;
+ final Configuration conf = service.getResources().getConfiguration();
+ sInstance.mLanguageSwitcher = new LanguageSwitcher(service);
+ sInstance.mLanguageSwitcher.loadLocales(prefs, conf.locale);
+ sInstance.mPrefs = prefs;
+ sInstance.mService = service;
+ prefs.registerOnSharedPreferenceChangeListener(sInstance);
+ }
+
+ public static void onConfigurationChanged(Configuration conf) {
+ if (InputMethodManagerCompatWrapper.SUBTYPE_SUPPORTED) return;
+ sInstance.mLanguageSwitcher.onConfigurationChanged(conf, sInstance.mPrefs);
+ }
+
+ public static void loadSettings() {
+ if (InputMethodManagerCompatWrapper.SUBTYPE_SUPPORTED) return;
+ sInstance.mLanguageSwitcher.loadLocales(sInstance.mPrefs, null);
+ }
+
+ public int getLocaleCount() {
+ return mLanguageSwitcher.getLocaleCount();
+ }
+
+ public String[] getEnabledLanguages(boolean allowImplicitlySelectedLanguages) {
+ return mLanguageSwitcher.getEnabledLanguages(allowImplicitlySelectedLanguages);
+ }
+
+ public Locale getInputLocale() {
+ return mLanguageSwitcher.getInputLocale();
+ }
+
+ public void setLocale(String localeStr) {
+ mLanguageSwitcher.setLocale(localeStr);
+ mLanguageSwitcher.persist(mPrefs);
+ }
+
+ @Override
+ public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
+ // PREF_SELECTED_LANGUAGES: enabled input subtypes
+ // PREF_INPUT_LANGUAGE: current input subtype
+ if (key.equals(Settings.PREF_SELECTED_LANGUAGES)
+ || key.equals(Settings.PREF_INPUT_LANGUAGE)) {
+ mLanguageSwitcher.loadLocales(prefs, null);
+ if (mService != null) {
+ mService.onRefreshKeyboard();
+ }
+ }
+ }
+}
diff --git a/java/src/com/android/inputmethod/voice/VoiceIMEConnector.java b/java/src/com/android/inputmethod/deprecated/VoiceProxy.java
index a244c9e41..85993ea4d 100644
--- a/java/src/com/android/inputmethod/voice/VoiceIMEConnector.java
+++ b/java/src/com/android/inputmethod/deprecated/VoiceProxy.java
@@ -14,8 +14,14 @@
* the License.
*/
-package com.android.inputmethod.voice;
-
+package com.android.inputmethod.deprecated;
+
+import com.android.inputmethod.compat.InputMethodManagerCompatWrapper;
+import com.android.inputmethod.deprecated.voice.FieldContext;
+import com.android.inputmethod.deprecated.voice.Hints;
+import com.android.inputmethod.deprecated.voice.SettingsUtil;
+import com.android.inputmethod.deprecated.voice.VoiceInput;
+import com.android.inputmethod.deprecated.voice.VoiceInputLogger;
import com.android.inputmethod.keyboard.KeyboardSwitcher;
import com.android.inputmethod.latin.EditingUtils;
import com.android.inputmethod.latin.LatinIME;
@@ -28,6 +34,7 @@ import com.android.inputmethod.latin.SuggestedWords;
import com.android.inputmethod.latin.Utils;
import android.app.AlertDialog;
+import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
@@ -54,7 +61,6 @@ import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
-import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import java.util.ArrayList;
@@ -62,8 +68,8 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-public class VoiceIMEConnector implements VoiceInput.UiListener {
- private static final VoiceIMEConnector sInstance = new VoiceIMEConnector();
+public class VoiceProxy implements VoiceInput.UiListener {
+ private static final VoiceProxy sInstance = new VoiceProxy();
public static final boolean VOICE_INSTALLED = true;
private static final boolean ENABLE_VOICE_BUTTON = true;
@@ -76,8 +82,10 @@ public class VoiceIMEConnector implements VoiceInput.UiListener {
private static final String PREF_HAS_USED_VOICE_INPUT_UNSUPPORTED_LOCALE =
"has_used_voice_input_unsupported_locale";
private static final int RECOGNITIONVIEW_HEIGHT_THRESHOLD_RATIO = 6;
+ // TODO: Adjusted on phones for now
+ private static final int RECOGNITIONVIEW_MINIMUM_HEIGHT_DIP = 244;
- private static final String TAG = VoiceIMEConnector.class.getSimpleName();
+ private static final String TAG = VoiceProxy.class.getSimpleName();
private static final boolean DEBUG = LatinImeLogger.sDBG;
private boolean mAfterVoiceInput;
@@ -93,7 +101,8 @@ public class VoiceIMEConnector implements VoiceInput.UiListener {
private boolean mVoiceButtonOnPrimary;
private boolean mVoiceInputHighlighted;
- private InputMethodManager mImm;
+ private int mMinimumVoiceRecognitionViewHeightPixel;
+ private InputMethodManagerCompatWrapper mImm;
private LatinIME mService;
private AlertDialog mVoiceWarningDialog;
private VoiceInput mVoiceInput;
@@ -101,23 +110,26 @@ public class VoiceIMEConnector implements VoiceInput.UiListener {
private Hints mHints;
private UIHandler mHandler;
private SubtypeSwitcher mSubtypeSwitcher;
+
// For each word, a list of potential replacements, usually from voice.
private final Map<String, List<CharSequence>> mWordToSuggestions =
new HashMap<String, List<CharSequence>>();
- public static VoiceIMEConnector init(LatinIME context, SharedPreferences prefs, UIHandler h) {
+ public static VoiceProxy init(LatinIME context, SharedPreferences prefs, UIHandler h) {
sInstance.initInternal(context, prefs, h);
return sInstance;
}
- public static VoiceIMEConnector getInstance() {
+ public static VoiceProxy getInstance() {
return sInstance;
}
private void initInternal(LatinIME service, SharedPreferences prefs, UIHandler h) {
mService = service;
mHandler = h;
- mImm = (InputMethodManager) service.getSystemService(Context.INPUT_METHOD_SERVICE);
+ mMinimumVoiceRecognitionViewHeightPixel = Utils.dipToPixel(
+ Utils.getDipScale(service), RECOGNITIONVIEW_MINIMUM_HEIGHT_DIP);
+ mImm = InputMethodManagerCompatWrapper.getInstance(service);
mSubtypeSwitcher = SubtypeSwitcher.getInstance();
if (VOICE_INSTALLED) {
mVoiceInput = new VoiceInput(service, this);
@@ -125,15 +137,15 @@ public class VoiceIMEConnector implements VoiceInput.UiListener {
@Override
public void showHint(int viewResource) {
View view = LayoutInflater.from(mService).inflate(viewResource, null);
- mService.setCandidatesView(view);
- mService.setCandidatesViewShown(true);
+// mService.setCandidatesView(view);
+// mService.setCandidatesViewShown(true);
mIsShowingHint = true;
}
});
}
}
- private VoiceIMEConnector() {
+ private VoiceProxy() {
// Intentional empty constructor for singleton.
}
@@ -429,7 +441,7 @@ public class VoiceIMEConnector implements VoiceInput.UiListener {
}
builder.setTypedWordValid(true).setHasMinimalSuggestion(true);
mService.setSuggestions(builder.build());
- mService.setCandidatesViewShown(true);
+// mService.setCandidatesViewShown(true);
return true;
}
return false;
@@ -514,7 +526,7 @@ public class VoiceIMEConnector implements VoiceInput.UiListener {
mHandler.post(new Runnable() {
@Override
public void run() {
- mService.setCandidatesViewShown(false);
+// mService.setCandidatesViewShown(false);
mRecognizing = true;
mVoiceInput.newView();
View v = mVoiceInput.getView();
@@ -524,7 +536,7 @@ public class VoiceIMEConnector implements VoiceInput.UiListener {
((ViewGroup) p).removeView(v);
}
- View keyboardView = KeyboardSwitcher.getInstance().getInputView();
+ View keyboardView = KeyboardSwitcher.getInstance().getKeyboardView();
// The full height of the keyboard is difficult to calculate
// as the dimension is expressed in "mm" and not in "pixel"
@@ -536,7 +548,11 @@ public class VoiceIMEConnector implements VoiceInput.UiListener {
mService.getResources().getDisplayMetrics().heightPixels;
final int currentHeight = popupLayout.getLayoutParams().height;
final int keyboardHeight = keyboardView.getHeight();
- if (keyboardHeight > currentHeight || keyboardHeight
+ if (mMinimumVoiceRecognitionViewHeightPixel > keyboardHeight
+ || mMinimumVoiceRecognitionViewHeightPixel > currentHeight) {
+ popupLayout.getLayoutParams().height =
+ mMinimumVoiceRecognitionViewHeightPixel;
+ } else if (keyboardHeight > currentHeight || keyboardHeight
> (displayHeight / RECOGNITIONVIEW_HEIGHT_THRESHOLD_RATIO)) {
popupLayout.getLayoutParams().height = keyboardHeight;
}
@@ -560,14 +576,24 @@ public class VoiceIMEConnector implements VoiceInput.UiListener {
@Override
protected void onPostExecute(Boolean result) {
+ // Calls in this method need to be done in the same thread as the thread which
+ // called switchToLastInputMethod()
if (!result) {
if (DEBUG) {
Log.d(TAG, "Couldn't switch back to last IME.");
}
- // Needs to reset here because LatinIME failed to back to any IME and
- // the same voice subtype will be triggered in the next time.
+ // Because the current IME and subtype failed to switch to any other IME and
+ // subtype by switchToLastInputMethod, the current IME and subtype should keep
+ // being LatinIME and voice subtype in the next time. And for re-showing voice
+ // mode, the state of voice input should be reset and the voice view should be
+ // hidden.
mVoiceInput.reset();
mService.requestHideSelf(0);
+ } else {
+ // Notify an event that the current subtype was changed. This event will be
+ // handled if "onCurrentInputMethodSubtypeChanged" can't be implemented
+ // when the API level is 10 or previous.
+ mService.notifyOnCurrentInputMethodSubtypeChanged(null);
}
}
}.execute();
@@ -624,6 +650,7 @@ public class VoiceIMEConnector implements VoiceInput.UiListener {
}
private boolean shouldShowVoiceButton(FieldContext fieldContext, EditorInfo attribute) {
+ @SuppressWarnings("deprecation")
final boolean noMic = Utils.inPrivateImeOptions(null,
LatinIME.IME_OPTION_NO_MICROPHONE_COMPAT, attribute)
|| Utils.inPrivateImeOptions(mService.getPackageName(),
@@ -664,7 +691,7 @@ public class VoiceIMEConnector implements VoiceInput.UiListener {
if (mSubtypeSwitcher.isVoiceMode() && windowToken != null) {
// Close keyboard view if it is been shown.
if (KeyboardSwitcher.getInstance().isInputViewShown())
- KeyboardSwitcher.getInstance().getInputView().purgeKeyboardAndClosing();
+ KeyboardSwitcher.getInstance().getKeyboardView().purgeKeyboardAndClosing();
startListening(false, windowToken);
}
// If we have no token, onAttachedToWindow will take care of showing dialog and start
@@ -674,7 +701,7 @@ public class VoiceIMEConnector implements VoiceInput.UiListener {
public void onAttachedToWindow() {
// After onAttachedToWindow, we can show the voice warning dialog. See startListening()
// above.
- mSubtypeSwitcher.setVoiceInput(mVoiceInput);
+ VoiceInputWrapper.getInstance().setVoiceInput(mVoiceInput, mSubtypeSwitcher);
}
public void onConfigurationChanged(Configuration configuration) {
@@ -725,4 +752,91 @@ public class VoiceIMEConnector implements VoiceInput.UiListener {
List<String> candidates;
Map<String, List<CharSequence>> alternatives;
}
+
+ public static class VoiceLoggerWrapper {
+ private static final VoiceLoggerWrapper sLoggerWrapperInstance = new VoiceLoggerWrapper();
+ private VoiceInputLogger mLogger;
+
+ public static VoiceLoggerWrapper getInstance(Context context) {
+ if (sLoggerWrapperInstance.mLogger == null) {
+ // Not thread safe, but it's ok.
+ sLoggerWrapperInstance.mLogger = VoiceInputLogger.getLogger(context);
+ }
+ return sLoggerWrapperInstance;
+ }
+
+ // private for the singleton
+ private VoiceLoggerWrapper() {
+ }
+
+ public void settingsWarningDialogCancel() {
+ mLogger.settingsWarningDialogCancel();
+ }
+
+ public void settingsWarningDialogOk() {
+ mLogger.settingsWarningDialogOk();
+ }
+
+ public void settingsWarningDialogShown() {
+ mLogger.settingsWarningDialogShown();
+ }
+
+ public void settingsWarningDialogDismissed() {
+ mLogger.settingsWarningDialogDismissed();
+ }
+
+ public void voiceInputSettingEnabled(boolean enabled) {
+ if (enabled) {
+ mLogger.voiceInputSettingEnabled();
+ } else {
+ mLogger.voiceInputSettingDisabled();
+ }
+ }
+ }
+
+ public static class VoiceInputWrapper {
+ private static final VoiceInputWrapper sInputWrapperInstance = new VoiceInputWrapper();
+ private VoiceInput mVoiceInput;
+ public static VoiceInputWrapper getInstance() {
+ return sInputWrapperInstance;
+ }
+ public void setVoiceInput(VoiceInput voiceInput, SubtypeSwitcher switcher) {
+ if (mVoiceInput == null && voiceInput != null) {
+ mVoiceInput = voiceInput;
+ }
+ switcher.setVoiceInputWrapper(this);
+ }
+
+ private VoiceInputWrapper() {
+ }
+
+ public void cancel() {
+ if (mVoiceInput != null) mVoiceInput.cancel();
+ }
+
+ public void reset() {
+ if (mVoiceInput != null) mVoiceInput.reset();
+ }
+ }
+
+ // A list of locales which are supported by default for voice input, unless we get a
+ // different list from Gservices.
+ private static final String DEFAULT_VOICE_INPUT_SUPPORTED_LOCALES =
+ "en " +
+ "en_US " +
+ "en_GB " +
+ "en_AU " +
+ "en_CA " +
+ "en_IE " +
+ "en_IN " +
+ "en_NZ " +
+ "en_SG " +
+ "en_ZA ";
+
+ public static String getSupportedLocalesString (ContentResolver resolver) {
+ return SettingsUtil.getSettingsString(
+ resolver,
+ SettingsUtil.LATIN_IME_VOICE_INPUT_SUPPORTED_LOCALES,
+ DEFAULT_VOICE_INPUT_SUPPORTED_LOCALES);
+ }
}
diff --git a/java/src/com/android/inputmethod/deprecated/compat/VoiceInputLoggerCompatUtils.java b/java/src/com/android/inputmethod/deprecated/compat/VoiceInputLoggerCompatUtils.java
new file mode 100644
index 000000000..488390fbc
--- /dev/null
+++ b/java/src/com/android/inputmethod/deprecated/compat/VoiceInputLoggerCompatUtils.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.inputmethod.deprecated.compat;
+
+import com.android.common.userhappiness.UserHappinessSignals;
+import com.android.inputmethod.compat.CompatUtils;
+
+import java.lang.reflect.Method;
+
+public class VoiceInputLoggerCompatUtils {
+ public static final String EXTRA_TEXT_REPLACED_LENGTH = "length";
+ public static final String EXTRA_BEFORE_N_BEST_CHOOSE = "before";
+ public static final String EXTRA_AFTER_N_BEST_CHOOSE = "after";
+ private static final Method METHOD_UserHappinessSignals_setHasVoiceLoggingInfo =
+ CompatUtils.getMethod(UserHappinessSignals.class, "setHasVoiceLoggingInfo",
+ boolean.class);
+
+ public static void setHasVoiceLoggingInfoCompat(boolean hasLoggingInfo) {
+ CompatUtils.invoke(null, null, METHOD_UserHappinessSignals_setHasVoiceLoggingInfo,
+ hasLoggingInfo);
+ }
+}
diff --git a/java/src/com/android/inputmethod/deprecated/languageswitcher/InputLanguageSelection.java b/java/src/com/android/inputmethod/deprecated/languageswitcher/InputLanguageSelection.java
new file mode 100644
index 000000000..fe70eef96
--- /dev/null
+++ b/java/src/com/android/inputmethod/deprecated/languageswitcher/InputLanguageSelection.java
@@ -0,0 +1,255 @@
+/*
+ * Copyright (C) 2008-2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package com.android.inputmethod.deprecated.languageswitcher;
+
+import com.android.inputmethod.keyboard.KeyboardParser;
+import com.android.inputmethod.latin.DictionaryFactory;
+import com.android.inputmethod.latin.R;
+import com.android.inputmethod.latin.Settings;
+import com.android.inputmethod.latin.SharedPreferencesCompat;
+import com.android.inputmethod.latin.SubtypeSwitcher;
+import com.android.inputmethod.latin.Utils;
+
+import org.xmlpull.v1.XmlPullParserException;
+
+import android.content.SharedPreferences;
+import android.content.SharedPreferences.Editor;
+import android.content.res.Resources;
+import android.os.Bundle;
+import android.preference.CheckBoxPreference;
+import android.preference.PreferenceActivity;
+import android.preference.PreferenceGroup;
+import android.preference.PreferenceManager;
+import android.text.TextUtils;
+import android.util.Pair;
+
+import java.io.IOException;
+import java.text.Collator;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map.Entry;
+import java.util.TreeMap;
+
+public class InputLanguageSelection extends PreferenceActivity {
+
+ private SharedPreferences mPrefs;
+ private String mSelectedLanguages;
+ private HashMap<CheckBoxPreference, Locale> mLocaleMap =
+ new HashMap<CheckBoxPreference, Locale>();
+
+ private static class LocaleEntry implements Comparable<Object> {
+ private static Collator sCollator = Collator.getInstance();
+
+ private String mLabel;
+ public final Locale mLocale;
+
+ public LocaleEntry(String label, Locale locale) {
+ this.mLabel = label;
+ this.mLocale = locale;
+ }
+
+ @Override
+ public String toString() {
+ return this.mLabel;
+ }
+
+ @Override
+ public int compareTo(Object o) {
+ return sCollator.compare(this.mLabel, ((LocaleEntry) o).mLabel);
+ }
+ }
+
+ @Override
+ protected void onCreate(Bundle icicle) {
+ super.onCreate(icicle);
+ addPreferencesFromResource(R.xml.language_prefs);
+ // Get the settings preferences
+ mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
+ mSelectedLanguages = mPrefs.getString(Settings.PREF_SELECTED_LANGUAGES, "");
+ String[] languageList = mSelectedLanguages.split(",");
+ ArrayList<LocaleEntry> availableLanguages = getUniqueLocales();
+ PreferenceGroup parent = getPreferenceScreen();
+ final HashMap<Long, LocaleEntry> dictionaryIdLocaleMap = new HashMap<Long, LocaleEntry>();
+ final TreeMap<LocaleEntry, Boolean> localeHasDictionaryMap =
+ new TreeMap<LocaleEntry, Boolean>();
+ for (int i = 0; i < availableLanguages.size(); i++) {
+ LocaleEntry loc = availableLanguages.get(i);
+ Locale locale = loc.mLocale;
+ final Pair<Long, Boolean> hasDictionaryOrLayout = hasDictionaryOrLayout(locale);
+ final Long dictionaryId = hasDictionaryOrLayout.first;
+ final boolean hasLayout = hasDictionaryOrLayout.second;
+ final boolean hasDictionary = dictionaryId != null;
+ // Add this locale to the supported list if:
+ // 1) this locale has a layout/ 2) this locale has a dictionary
+ // If some locales have no layout but have a same dictionary, the shortest locale
+ // will be added to the supported list.
+ if (!hasLayout && !hasDictionary) {
+ continue;
+ }
+ if (hasLayout) {
+ localeHasDictionaryMap.put(loc, hasDictionary);
+ }
+ if (!hasDictionary) {
+ continue;
+ }
+ if (dictionaryIdLocaleMap.containsKey(dictionaryId)) {
+ final String newLocale = locale.toString();
+ final String oldLocale =
+ dictionaryIdLocaleMap.get(dictionaryId).mLocale.toString();
+ // Check if this locale is more appropriate to be the candidate of the input locale.
+ if (oldLocale.length() <= newLocale.length() && !hasLayout) {
+ // Don't add this new locale to the map<dictionary id, locale> if:
+ // 1) the new locale's name is longer than the existing one, and
+ // 2) the new locale doesn't have its layout
+ continue;
+ }
+ }
+ dictionaryIdLocaleMap.put(dictionaryId, loc);
+ }
+
+ for (LocaleEntry localeEntry : dictionaryIdLocaleMap.values()) {
+ if (!localeHasDictionaryMap.containsKey(localeEntry)) {
+ localeHasDictionaryMap.put(localeEntry, true);
+ }
+ }
+
+ for (Entry<LocaleEntry, Boolean> entry : localeHasDictionaryMap.entrySet()) {
+ final LocaleEntry localeEntry = entry.getKey();
+ final Locale locale = localeEntry.mLocale;
+ final Boolean hasDictionary = entry.getValue();
+ CheckBoxPreference pref = new CheckBoxPreference(this);
+ pref.setTitle(localeEntry.mLabel);
+ boolean checked = isLocaleIn(locale, languageList);
+ pref.setChecked(checked);
+ if (hasDictionary) {
+ pref.setSummary(R.string.has_dictionary);
+ }
+ mLocaleMap.put(pref, locale);
+ parent.addPreference(pref);
+ }
+ }
+
+ private boolean isLocaleIn(Locale locale, String[] list) {
+ String lang = get5Code(locale);
+ for (int i = 0; i < list.length; i++) {
+ if (lang.equalsIgnoreCase(list[i])) return true;
+ }
+ return false;
+ }
+
+ private Pair<Long, Boolean> hasDictionaryOrLayout(Locale locale) {
+ if (locale == null) return new Pair<Long, Boolean>(null, false);
+ final Resources res = getResources();
+ final Locale saveLocale = Utils.setSystemLocale(res, locale);
+ final Long dictionaryId = DictionaryFactory.getDictionaryId(this, locale);
+ boolean hasLayout = false;
+
+ try {
+ final String localeStr = locale.toString();
+ final String[] layoutCountryCodes = KeyboardParser.parseKeyboardLocale(
+ this, R.xml.kbd_qwerty).split(",", -1);
+ if (!TextUtils.isEmpty(localeStr) && layoutCountryCodes.length > 0) {
+ for (String s : layoutCountryCodes) {
+ if (s.equals(localeStr)) {
+ hasLayout = true;
+ break;
+ }
+ }
+ }
+ } catch (XmlPullParserException e) {
+ } catch (IOException e) {
+ }
+ Utils.setSystemLocale(res, saveLocale);
+ return new Pair<Long, Boolean>(dictionaryId, hasLayout);
+ }
+
+ private String get5Code(Locale locale) {
+ String country = locale.getCountry();
+ return locale.getLanguage()
+ + (TextUtils.isEmpty(country) ? "" : "_" + country);
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ }
+
+ @Override
+ protected void onPause() {
+ super.onPause();
+ // Save the selected languages
+ String checkedLanguages = "";
+ PreferenceGroup parent = getPreferenceScreen();
+ int count = parent.getPreferenceCount();
+ for (int i = 0; i < count; i++) {
+ CheckBoxPreference pref = (CheckBoxPreference) parent.getPreference(i);
+ if (pref.isChecked()) {
+ checkedLanguages += get5Code(mLocaleMap.get(pref)) + ",";
+ }
+ }
+ if (checkedLanguages.length() < 1) checkedLanguages = null; // Save null
+ Editor editor = mPrefs.edit();
+ editor.putString(Settings.PREF_SELECTED_LANGUAGES, checkedLanguages);
+ SharedPreferencesCompat.apply(editor);
+ }
+
+ public ArrayList<LocaleEntry> getUniqueLocales() {
+ String[] locales = getAssets().getLocales();
+ Arrays.sort(locales);
+ ArrayList<LocaleEntry> uniqueLocales = new ArrayList<LocaleEntry>();
+
+ final int origSize = locales.length;
+ LocaleEntry[] preprocess = new LocaleEntry[origSize];
+ int finalSize = 0;
+ for (int i = 0 ; i < origSize; i++ ) {
+ String s = locales[i];
+ int len = s.length();
+ String language = "";
+ String country = "";
+ if (len == 5) {
+ language = s.substring(0, 2);
+ country = s.substring(3, 5);
+ } else if (len < 5) {
+ language = s;
+ }
+ Locale l = new Locale(language, country);
+
+ // Exclude languages that are not relevant to LatinIME
+ if (TextUtils.isEmpty(language)) {
+ continue;
+ }
+
+ if (finalSize == 0) {
+ preprocess[finalSize++] =
+ new LocaleEntry(SubtypeSwitcher.getFullDisplayName(l, false), l);
+ } else {
+ if (s.equals("zz_ZZ")) {
+ // ignore this locale
+ } else {
+ final String displayName = SubtypeSwitcher.getFullDisplayName(l, false);
+ preprocess[finalSize++] = new LocaleEntry(displayName, l);
+ }
+ }
+ }
+ for (int i = 0; i < finalSize ; i++) {
+ uniqueLocales.add(preprocess[i]);
+ }
+ return uniqueLocales;
+ }
+}
diff --git a/java/src/com/android/inputmethod/latin/LanguageSwitcher.java b/java/src/com/android/inputmethod/deprecated/languageswitcher/LanguageSwitcher.java
index 2dd3038f9..1eedb5ee1 100644
--- a/java/src/com/android/inputmethod/latin/LanguageSwitcher.java
+++ b/java/src/com/android/inputmethod/deprecated/languageswitcher/LanguageSwitcher.java
@@ -14,11 +14,19 @@
* the License.
*/
-package com.android.inputmethod.latin;
+package com.android.inputmethod.deprecated.languageswitcher;
+
+import com.android.inputmethod.latin.LatinIME;
+import com.android.inputmethod.latin.LatinImeLogger;
+import com.android.inputmethod.latin.Settings;
+import com.android.inputmethod.latin.SharedPreferencesCompat;
+import com.android.inputmethod.latin.Utils;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
+import android.content.res.Configuration;
import android.text.TextUtils;
+import android.util.Log;
import java.util.ArrayList;
import java.util.Locale;
@@ -28,10 +36,15 @@ import java.util.Locale;
* input language that the user has selected.
*/
public class LanguageSwitcher {
+ private static final String TAG = LanguageSwitcher.class.getSimpleName();
+
+ @SuppressWarnings("unused")
+ private static final String KEYBOARD_MODE = "keyboard";
+ private static final String[] EMPTY_STIRNG_ARRAY = new String[0];
private final ArrayList<Locale> mLocales = new ArrayList<Locale>();
private final LatinIME mIme;
- private String[] mSelectedLanguageArray;
+ private String[] mSelectedLanguageArray = EMPTY_STIRNG_ARRAY;
private String mSelectedLanguages;
private int mCurrentIndex = 0;
private String mDefaultInputLanguage;
@@ -46,15 +59,32 @@ public class LanguageSwitcher {
return mLocales.size();
}
+ public void onConfigurationChanged(Configuration conf, SharedPreferences prefs) {
+ final Locale newLocale = conf.locale;
+ if (!getSystemLocale().toString().equals(newLocale.toString())) {
+ loadLocales(prefs, newLocale);
+ }
+ }
+
/**
* Loads the currently selected input languages from shared preferences.
- * @param sp
+ * @param sp shared preference for getting the current input language and enabled languages
+ * @param systemLocale the current system locale, stored for changing the current input language
+ * based on the system current system locale.
* @return whether there was any change
*/
- public boolean loadLocales(SharedPreferences sp) {
+ public boolean loadLocales(SharedPreferences sp, Locale systemLocale) {
+ if (LatinImeLogger.sDBG) {
+ Log.d(TAG, "load locales");
+ }
+ if (systemLocale != null) {
+ setSystemLocale(systemLocale);
+ }
String selectedLanguages = sp.getString(Settings.PREF_SELECTED_LANGUAGES, null);
String currentLanguage = sp.getString(Settings.PREF_INPUT_LANGUAGE, null);
- if (selectedLanguages == null || selectedLanguages.length() < 1) {
+ if (TextUtils.isEmpty(selectedLanguages)) {
+ mSelectedLanguageArray = EMPTY_STIRNG_ARRAY;
+ mSelectedLanguages = null;
loadDefaults();
if (mLocales.size() == 0) {
return false;
@@ -84,6 +114,9 @@ public class LanguageSwitcher {
}
private void loadDefaults() {
+ if (LatinImeLogger.sDBG) {
+ Log.d(TAG, "load default locales:");
+ }
mDefaultInputLocale = mIme.getResources().getConfiguration().locale;
String country = mDefaultInputLocale.getCountry();
mDefaultInputLanguage = mDefaultInputLocale.getLanguage() +
@@ -93,8 +126,7 @@ public class LanguageSwitcher {
private void constructLocales() {
mLocales.clear();
for (final String lang : mSelectedLanguageArray) {
- final Locale locale = new Locale(lang.substring(0, 2),
- lang.length() > 4 ? lang.substring(3, 5) : "");
+ final Locale locale = Utils.constructLocaleFromString(lang);
mLocales.add(locale);
}
}
@@ -112,14 +144,16 @@ public class LanguageSwitcher {
/**
* Returns the list of enabled language codes.
*/
- public String[] getEnabledLanguages() {
+ public String[] getEnabledLanguages(boolean allowImplicitlySelectedLanguages) {
+ if (mSelectedLanguageArray.length == 0 && allowImplicitlySelectedLanguages) {
+ return new String[] { mDefaultInputLanguage };
+ }
return mSelectedLanguageArray;
}
/**
* Returns the currently selected input locale, or the display locale if no specific
* locale was selected for input.
- * @return
*/
public Locale getInputLocale() {
if (getLocaleCount() == 0) return mDefaultInputLocale;
@@ -140,7 +174,6 @@ public class LanguageSwitcher {
/**
* Returns the next input locale in the list. Wraps around to the beginning of the
* list if we're at the end of the list.
- * @return
*/
public Locale getNextInputLocale() {
if (getLocaleCount() == 0) return mDefaultInputLocale;
@@ -151,7 +184,7 @@ public class LanguageSwitcher {
* Sets the system locale (display UI) used for comparing with the input language.
* @param locale the locale of the system
*/
- public void setSystemLocale(Locale locale) {
+ private void setSystemLocale(Locale locale) {
mSystemLocale = locale;
}
@@ -159,14 +192,13 @@ public class LanguageSwitcher {
* Returns the system locale.
* @return the system locale
*/
- public Locale getSystemLocale() {
+ private Locale getSystemLocale() {
return mSystemLocale;
}
/**
* Returns the previous input locale in the list. Wraps around to the end of the
* list if we're at the beginning of the list.
- * @return
*/
public Locale getPrevInputLocale() {
if (getLocaleCount() == 0) return mDefaultInputLocale;
@@ -185,6 +217,15 @@ public class LanguageSwitcher {
mCurrentIndex = prevLocaleIndex();
}
+ public void setLocale(String localeStr) {
+ final int N = mLocales.size();
+ for (int i = 0; i < N; ++i) {
+ if (mLocales.get(i).toString().equals(localeStr)) {
+ mCurrentIndex = i;
+ }
+ }
+ }
+
public void persist(SharedPreferences prefs) {
Editor editor = prefs.edit();
editor.putString(Settings.PREF_INPUT_LANGUAGE, getInputLanguage());
diff --git a/java/src/com/android/inputmethod/deprecated/recorrection/Recorrection.java b/java/src/com/android/inputmethod/deprecated/recorrection/Recorrection.java
new file mode 100644
index 000000000..d40728d25
--- /dev/null
+++ b/java/src/com/android/inputmethod/deprecated/recorrection/Recorrection.java
@@ -0,0 +1,287 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package com.android.inputmethod.deprecated.recorrection;
+
+import com.android.inputmethod.compat.InputConnectionCompatUtils;
+import com.android.inputmethod.compat.SuggestionSpanUtils;
+import com.android.inputmethod.deprecated.VoiceProxy;
+import com.android.inputmethod.keyboard.KeyboardSwitcher;
+import com.android.inputmethod.latin.AutoCorrection;
+import com.android.inputmethod.latin.CandidateView;
+import com.android.inputmethod.latin.EditingUtils;
+import com.android.inputmethod.latin.LatinIME;
+import com.android.inputmethod.latin.R;
+import com.android.inputmethod.latin.Settings;
+import com.android.inputmethod.latin.Suggest;
+import com.android.inputmethod.latin.SuggestedWords;
+import com.android.inputmethod.latin.TextEntryState;
+import com.android.inputmethod.latin.WordComposer;
+
+import android.content.SharedPreferences;
+import android.content.res.Resources;
+import android.text.TextUtils;
+import android.view.inputmethod.ExtractedText;
+import android.view.inputmethod.ExtractedTextRequest;
+import android.view.inputmethod.InputConnection;
+
+import java.util.ArrayList;
+
+/**
+ * Manager of re-correction functionalities
+ */
+public class Recorrection implements SharedPreferences.OnSharedPreferenceChangeListener {
+ private static final Recorrection sInstance = new Recorrection();
+
+ private LatinIME mService;
+ private boolean mRecorrectionEnabled = false;
+ private final ArrayList<RecorrectionSuggestionEntries> mRecorrectionSuggestionsList =
+ new ArrayList<RecorrectionSuggestionEntries>();
+
+ public static Recorrection getInstance() {
+ return sInstance;
+ }
+
+ public static void init(LatinIME context, SharedPreferences prefs) {
+ if (context == null || prefs == null) {
+ return;
+ }
+ sInstance.initInternal(context, prefs);
+ }
+
+ private Recorrection() {
+ }
+
+ public boolean isRecorrectionEnabled() {
+ return mRecorrectionEnabled;
+ }
+
+ private void initInternal(LatinIME context, SharedPreferences prefs) {
+ if (SuggestionSpanUtils.SUGGESTION_SPAN_IS_SUPPORTED) {
+ mRecorrectionEnabled = false;
+ return;
+ }
+ updateRecorrectionEnabled(context.getResources(), prefs);
+ mService = context;
+ prefs.registerOnSharedPreferenceChangeListener(this);
+ }
+
+ public void checkRecorrectionOnStart() {
+ if (SuggestionSpanUtils.SUGGESTION_SPAN_IS_SUPPORTED || !mRecorrectionEnabled) return;
+
+ final InputConnection ic = mService.getCurrentInputConnection();
+ if (ic == null) return;
+ // There could be a pending composing span. Clean it up first.
+ ic.finishComposingText();
+
+ if (mService.isShowingSuggestionsStrip() && mService.isSuggestionsRequested()) {
+ // First get the cursor position. This is required by setOldSuggestions(), so that
+ // it can pass the correct range to setComposingRegion(). At this point, we don't
+ // have valid values for mLastSelectionStart/End because onUpdateSelection() has
+ // not been called yet.
+ ExtractedTextRequest etr = new ExtractedTextRequest();
+ etr.token = 0; // anything is fine here
+ ExtractedText et = ic.getExtractedText(etr, 0);
+ if (et == null) return;
+ mService.setLastSelection(
+ et.startOffset + et.selectionStart, et.startOffset + et.selectionEnd);
+
+ // Then look for possible corrections in a delayed fashion
+ if (!TextUtils.isEmpty(et.text) && mService.isCursorTouchingWord()) {
+ mService.mHandler.postUpdateOldSuggestions();
+ }
+ }
+ }
+
+ public void updateRecorrectionSelection(KeyboardSwitcher keyboardSwitcher,
+ CandidateView candidateView, int candidatesStart, int candidatesEnd,
+ int newSelStart, int newSelEnd, int oldSelStart, int lastSelectionStart,
+ int lastSelectionEnd, boolean hasUncommittedTypedChars) {
+ if (SuggestionSpanUtils.SUGGESTION_SPAN_IS_SUPPORTED || !mRecorrectionEnabled) return;
+ if (!mService.isShowingSuggestionsStrip()) return;
+ if (!keyboardSwitcher.isInputViewShown()) return;
+ if (!mService.isSuggestionsRequested()) return;
+ // Don't look for corrections if the keyboard is not visible
+ // Check if we should go in or out of correction mode.
+ if ((candidatesStart == candidatesEnd || newSelStart != oldSelStart || TextEntryState
+ .isRecorrecting())
+ && (newSelStart < newSelEnd - 1 || !hasUncommittedTypedChars)) {
+ if (mService.isCursorTouchingWord() || lastSelectionStart < lastSelectionEnd) {
+ mService.mHandler.cancelUpdateBigramPredictions();
+ mService.mHandler.postUpdateOldSuggestions();
+ } else {
+ abortRecorrection(false);
+ // If showing the "touch again to save" hint, do not replace it. Else,
+ // show the bigrams if we are at the end of the text, punctuation
+ // otherwise.
+ if (candidateView != null && !candidateView.isShowingAddToDictionaryHint()) {
+ InputConnection ic = mService.getCurrentInputConnection();
+ if (null == ic || !TextUtils.isEmpty(ic.getTextAfterCursor(1, 0))) {
+ if (!mService.isShowingPunctuationList()) {
+ mService.setPunctuationSuggestions();
+ }
+ } else {
+ mService.mHandler.postUpdateBigramPredictions();
+ }
+ }
+ }
+ }
+ }
+
+ public void saveRecorrectionSuggestion(WordComposer word, CharSequence result) {
+ if (SuggestionSpanUtils.SUGGESTION_SPAN_IS_SUPPORTED || !mRecorrectionEnabled) return;
+ if (word.size() <= 1) {
+ return;
+ }
+ // Skip if result is null. It happens in some edge case.
+ if (TextUtils.isEmpty(result)) {
+ return;
+ }
+
+ // Make a copy of the CharSequence, since it is/could be a mutable CharSequence
+ final String resultCopy = result.toString();
+ RecorrectionSuggestionEntries entry = new RecorrectionSuggestionEntries(
+ resultCopy, new WordComposer(word));
+ mRecorrectionSuggestionsList.add(entry);
+ }
+
+ public void clearWordsInHistory() {
+ mRecorrectionSuggestionsList.clear();
+ }
+
+ /**
+ * Tries to apply any typed alternatives for the word if we have any cached alternatives,
+ * otherwise tries to find new corrections and completions for the word.
+ * @param touching The word that the cursor is touching, with position information
+ * @return true if an alternative was found, false otherwise.
+ */
+ public boolean applyTypedAlternatives(WordComposer word, Suggest suggest,
+ KeyboardSwitcher keyboardSwitcher, EditingUtils.SelectedWord touching) {
+ if (SuggestionSpanUtils.SUGGESTION_SPAN_IS_SUPPORTED || !mRecorrectionEnabled) return false;
+ // If we didn't find a match, search for result in typed word history
+ WordComposer foundWord = null;
+ RecorrectionSuggestionEntries alternatives = null;
+ // Search old suggestions to suggest re-corrected suggestions.
+ for (RecorrectionSuggestionEntries entry : mRecorrectionSuggestionsList) {
+ if (TextUtils.equals(entry.getChosenWord(), touching.mWord)) {
+ foundWord = entry.mWordComposer;
+ alternatives = entry;
+ break;
+ }
+ }
+ // If we didn't find a match, at least suggest corrections as re-corrected suggestions.
+ if (foundWord == null
+ && (AutoCorrection.isValidWord(suggest.getUnigramDictionaries(),
+ touching.mWord, true))) {
+ foundWord = new WordComposer();
+ for (int i = 0; i < touching.mWord.length(); i++) {
+ foundWord.add(touching.mWord.charAt(i),
+ new int[] { touching.mWord.charAt(i) }, WordComposer.NOT_A_COORDINATE,
+ WordComposer.NOT_A_COORDINATE);
+ }
+ foundWord.setFirstCharCapitalized(Character.isUpperCase(touching.mWord.charAt(0)));
+ }
+ // Found a match, show suggestions
+ if (foundWord != null || alternatives != null) {
+ if (alternatives == null) {
+ alternatives = new RecorrectionSuggestionEntries(touching.mWord, foundWord);
+ }
+ showRecorrections(suggest, keyboardSwitcher, alternatives);
+ if (foundWord != null) {
+ word.init(foundWord);
+ } else {
+ word.reset();
+ }
+ return true;
+ }
+ return false;
+ }
+
+
+ private void showRecorrections(Suggest suggest, KeyboardSwitcher keyboardSwitcher,
+ RecorrectionSuggestionEntries entries) {
+ SuggestedWords.Builder builder = entries.getAlternatives(suggest, keyboardSwitcher);
+ builder.setTypedWordValid(false).setHasMinimalSuggestion(false);
+ mService.showSuggestions(builder.build(), entries.getOriginalWord());
+ }
+
+ public void fetchAndDisplayRecorrectionSuggestions(VoiceProxy voiceProxy,
+ CandidateView candidateView, Suggest suggest, KeyboardSwitcher keyboardSwitcher,
+ WordComposer word, boolean hasUncommittedTypedChars, int lastSelectionStart,
+ int lastSelectionEnd, String wordSeparators) {
+ if (!InputConnectionCompatUtils.RECORRECTION_SUPPORTED) return;
+ if (SuggestionSpanUtils.SUGGESTION_SPAN_IS_SUPPORTED || !mRecorrectionEnabled) return;
+ voiceProxy.setShowingVoiceSuggestions(false);
+ if (candidateView != null && candidateView.isShowingAddToDictionaryHint()) {
+ return;
+ }
+ InputConnection ic = mService.getCurrentInputConnection();
+ if (ic == null) return;
+ if (!hasUncommittedTypedChars) {
+ // Extract the selected or touching text
+ EditingUtils.SelectedWord touching = EditingUtils.getWordAtCursorOrSelection(ic,
+ lastSelectionStart, lastSelectionEnd, wordSeparators);
+
+ if (touching != null && touching.mWord.length() > 1) {
+ ic.beginBatchEdit();
+
+ if (applyTypedAlternatives(word, suggest, keyboardSwitcher, touching)
+ || voiceProxy.applyVoiceAlternatives(touching)) {
+ TextEntryState.selectedForRecorrection();
+ InputConnectionCompatUtils.underlineWord(ic, touching);
+ } else {
+ abortRecorrection(true);
+ }
+
+ ic.endBatchEdit();
+ } else {
+ abortRecorrection(true);
+ mService.updateBigramPredictions();
+ }
+ } else {
+ abortRecorrection(true);
+ }
+ }
+
+ public void abortRecorrection(boolean force) {
+ if (SuggestionSpanUtils.SUGGESTION_SPAN_IS_SUPPORTED) return;
+ if (force || TextEntryState.isRecorrecting()) {
+ TextEntryState.onAbortRecorrection();
+ mService.setCandidatesViewShown(mService.isCandidateStripVisible());
+ mService.getCurrentInputConnection().finishComposingText();
+ mService.clearSuggestions();
+ }
+ }
+
+ public void updateRecorrectionEnabled(Resources res, SharedPreferences prefs) {
+ // If the option should not be shown, do not read the re-correction preference
+ // but always use the default setting defined in the resources.
+ if (res.getBoolean(R.bool.config_enable_show_recorrection_option)) {
+ mRecorrectionEnabled = prefs.getBoolean(Settings.PREF_RECORRECTION_ENABLED,
+ res.getBoolean(R.bool.config_default_recorrection_enabled));
+ } else {
+ mRecorrectionEnabled = res.getBoolean(R.bool.config_default_recorrection_enabled);
+ }
+ }
+
+ @Override
+ public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
+ if (SuggestionSpanUtils.SUGGESTION_SPAN_IS_SUPPORTED) return;
+ if (key.equals(Settings.PREF_RECORRECTION_ENABLED)) {
+ updateRecorrectionEnabled(mService.getResources(), prefs);
+ }
+ }
+}
diff --git a/java/src/com/android/inputmethod/deprecated/recorrection/RecorrectionSuggestionEntries.java b/java/src/com/android/inputmethod/deprecated/recorrection/RecorrectionSuggestionEntries.java
new file mode 100644
index 000000000..5e6c87044
--- /dev/null
+++ b/java/src/com/android/inputmethod/deprecated/recorrection/RecorrectionSuggestionEntries.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package com.android.inputmethod.deprecated.recorrection;
+
+import com.android.inputmethod.keyboard.KeyboardSwitcher;
+import com.android.inputmethod.latin.Suggest;
+import com.android.inputmethod.latin.SuggestedWords;
+import com.android.inputmethod.latin.WordComposer;
+
+import android.text.TextUtils;
+
+public class RecorrectionSuggestionEntries {
+ public final CharSequence mChosenWord;
+ public final WordComposer mWordComposer;
+
+ public RecorrectionSuggestionEntries(CharSequence chosenWord, WordComposer wordComposer) {
+ mChosenWord = chosenWord;
+ mWordComposer = wordComposer;
+ }
+
+ public CharSequence getChosenWord() {
+ return mChosenWord;
+ }
+
+ public CharSequence getOriginalWord() {
+ return mWordComposer.getTypedWord();
+ }
+
+ public SuggestedWords.Builder getAlternatives(
+ Suggest suggest, KeyboardSwitcher keyboardSwitcher) {
+ return getTypedSuggestions(suggest, keyboardSwitcher, mWordComposer);
+ }
+
+ @Override
+ public int hashCode() {
+ return mChosenWord.hashCode();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ return o instanceof CharSequence && TextUtils.equals(mChosenWord, (CharSequence)o);
+ }
+
+ private static SuggestedWords.Builder getTypedSuggestions(
+ Suggest suggest, KeyboardSwitcher keyboardSwitcher, WordComposer word) {
+ return suggest.getSuggestedWordBuilder(keyboardSwitcher.getKeyboardView(), word, null);
+ }
+}
diff --git a/java/src/com/android/inputmethod/voice/FieldContext.java b/java/src/com/android/inputmethod/deprecated/voice/FieldContext.java
index 95c7f5be0..3c79cc218 100644
--- a/java/src/com/android/inputmethod/voice/FieldContext.java
+++ b/java/src/com/android/inputmethod/deprecated/voice/FieldContext.java
@@ -14,7 +14,7 @@
* the License.
*/
-package com.android.inputmethod.voice;
+package com.android.inputmethod.deprecated.voice;
import android.os.Bundle;
import android.util.Log;
diff --git a/java/src/com/android/inputmethod/voice/Hints.java b/java/src/com/android/inputmethod/deprecated/voice/Hints.java
index f5689092f..06b234381 100644
--- a/java/src/com/android/inputmethod/voice/Hints.java
+++ b/java/src/com/android/inputmethod/deprecated/voice/Hints.java
@@ -14,7 +14,7 @@
* the License.
*/
-package com.android.inputmethod.voice;
+package com.android.inputmethod.deprecated.voice;
import com.android.inputmethod.latin.R;
import com.android.inputmethod.latin.SharedPreferencesCompat;
diff --git a/java/src/com/android/inputmethod/voice/RecognitionView.java b/java/src/com/android/inputmethod/deprecated/voice/RecognitionView.java
index d26a877d5..dcb826e8f 100644
--- a/java/src/com/android/inputmethod/voice/RecognitionView.java
+++ b/java/src/com/android/inputmethod/deprecated/voice/RecognitionView.java
@@ -14,7 +14,7 @@
* the License.
*/
-package com.android.inputmethod.voice;
+package com.android.inputmethod.deprecated.voice;
import com.android.inputmethod.latin.R;
import com.android.inputmethod.latin.SubtypeSwitcher;
@@ -50,7 +50,6 @@ import java.util.Locale;
* plays beeps, shows errors, etc.
*/
public class RecognitionView {
- @SuppressWarnings("unused")
private static final String TAG = "RecognitionView";
private Handler mUiHandler; // Reference to UI thread
diff --git a/java/src/com/android/inputmethod/voice/SettingsUtil.java b/java/src/com/android/inputmethod/deprecated/voice/SettingsUtil.java
index 372e8d6da..855a09a1d 100644
--- a/java/src/com/android/inputmethod/voice/SettingsUtil.java
+++ b/java/src/com/android/inputmethod/deprecated/voice/SettingsUtil.java
@@ -14,7 +14,7 @@
* the License.
*/
-package com.android.inputmethod.voice;
+package com.android.inputmethod.deprecated.voice;
import android.content.ContentResolver;
import android.provider.Settings;
diff --git a/java/src/com/android/inputmethod/voice/SoundIndicator.java b/java/src/com/android/inputmethod/deprecated/voice/SoundIndicator.java
index 40b68996a..25b314085 100644
--- a/java/src/com/android/inputmethod/voice/SoundIndicator.java
+++ b/java/src/com/android/inputmethod/deprecated/voice/SoundIndicator.java
@@ -14,7 +14,7 @@
* the License.
*/
-package com.android.inputmethod.voice;
+package com.android.inputmethod.deprecated.voice;
import android.content.Context;
import android.graphics.Bitmap;
diff --git a/java/src/com/android/inputmethod/voice/VoiceInput.java b/java/src/com/android/inputmethod/deprecated/voice/VoiceInput.java
index 392eea364..92cc1c3b9 100644
--- a/java/src/com/android/inputmethod/voice/VoiceInput.java
+++ b/java/src/com/android/inputmethod/deprecated/voice/VoiceInput.java
@@ -14,7 +14,7 @@
* the License.
*/
-package com.android.inputmethod.voice;
+package com.android.inputmethod.deprecated.voice;
import com.android.inputmethod.latin.EditingUtils;
import com.android.inputmethod.latin.LatinImeLogger;
@@ -192,7 +192,7 @@ public class VoiceInput implements OnClickListener {
}
mBlacklist = new Whitelist();
- mBlacklist.addApp("com.android.setupwizard");
+ mBlacklist.addApp("com.google.android.setupwizard");
}
public void setCursorPos(int pos) {
diff --git a/java/src/com/android/inputmethod/voice/VoiceInputLogger.java b/java/src/com/android/inputmethod/deprecated/voice/VoiceInputLogger.java
index 07f2bd1c5..22e8207bf 100644
--- a/java/src/com/android/inputmethod/voice/VoiceInputLogger.java
+++ b/java/src/com/android/inputmethod/deprecated/voice/VoiceInputLogger.java
@@ -14,10 +14,10 @@
* the License.
*/
-package com.android.inputmethod.voice;
+package com.android.inputmethod.deprecated.voice;
import com.android.common.speech.LoggingEvents;
-import com.android.common.userhappiness.UserHappinessSignals;
+import com.android.inputmethod.deprecated.compat.VoiceInputLoggerCompatUtils;
import android.content.Context;
import android.content.Intent;
@@ -212,13 +212,12 @@ public class VoiceInputLogger {
setHasLoggingInfo(true);
Intent i = newLoggingBroadcast(LoggingEvents.VoiceIme.TEXT_MODIFIED);
i.putExtra(LoggingEvents.VoiceIme.EXTRA_TEXT_MODIFIED_LENGTH, suggestionLength);
- i.putExtra(LoggingEvents.VoiceIme.EXTRA_TEXT_REPLACED_LENGTH, replacedPhraseLength);
+ i.putExtra(VoiceInputLoggerCompatUtils.EXTRA_TEXT_REPLACED_LENGTH, replacedPhraseLength);
i.putExtra(LoggingEvents.VoiceIme.EXTRA_TEXT_MODIFIED_TYPE,
LoggingEvents.VoiceIme.TEXT_MODIFIED_TYPE_CHOOSE_SUGGESTION);
-
i.putExtra(LoggingEvents.VoiceIme.EXTRA_N_BEST_CHOOSE_INDEX, index);
- i.putExtra(LoggingEvents.VoiceIme.EXTRA_BEFORE_N_BEST_CHOOSE, before);
- i.putExtra(LoggingEvents.VoiceIme.EXTRA_AFTER_N_BEST_CHOOSE, after);
+ i.putExtra(VoiceInputLoggerCompatUtils.EXTRA_BEFORE_N_BEST_CHOOSE, before);
+ i.putExtra(VoiceInputLoggerCompatUtils.EXTRA_AFTER_N_BEST_CHOOSE, after);
mContext.sendBroadcast(i);
}
@@ -257,7 +256,7 @@ public class VoiceInputLogger {
// 2. type subject in subject field
// 3. speak message in message field
// 4. press send
- UserHappinessSignals.setHasVoiceLoggingInfo(hasLoggingInfo);
+ VoiceInputLoggerCompatUtils.setHasVoiceLoggingInfoCompat(hasLoggingInfo);
}
private boolean hasLoggingInfo(){
diff --git a/java/src/com/android/inputmethod/voice/WaveformImage.java b/java/src/com/android/inputmethod/deprecated/voice/WaveformImage.java
index b0ea99b79..8ed279f42 100644
--- a/java/src/com/android/inputmethod/voice/WaveformImage.java
+++ b/java/src/com/android/inputmethod/deprecated/voice/WaveformImage.java
@@ -14,7 +14,7 @@
* the License.
*/
-package com.android.inputmethod.voice;
+package com.android.inputmethod.deprecated.voice;
import android.graphics.Bitmap;
import android.graphics.Canvas;
diff --git a/java/src/com/android/inputmethod/voice/Whitelist.java b/java/src/com/android/inputmethod/deprecated/voice/Whitelist.java
index adbd59135..6c5f52ae2 100644
--- a/java/src/com/android/inputmethod/voice/Whitelist.java
+++ b/java/src/com/android/inputmethod/deprecated/voice/Whitelist.java
@@ -14,7 +14,7 @@
* the License.
*/
-package com.android.inputmethod.voice;
+package com.android.inputmethod.deprecated.voice;
import android.os.Bundle;
diff --git a/java/src/com/android/inputmethod/keyboard/Key.java b/java/src/com/android/inputmethod/keyboard/Key.java
index eccd0c822..cb529461a 100644
--- a/java/src/com/android/inputmethod/keyboard/Key.java
+++ b/java/src/com/android/inputmethod/keyboard/Key.java
@@ -16,6 +16,10 @@
package com.android.inputmethod.keyboard;
+import com.android.inputmethod.keyboard.KeyStyles.KeyStyle;
+import com.android.inputmethod.keyboard.KeyboardParser.ParseException;
+import com.android.inputmethod.latin.R;
+
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
@@ -23,10 +27,6 @@ import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Xml;
-import com.android.inputmethod.keyboard.KeyStyles.KeyStyle;
-import com.android.inputmethod.keyboard.KeyboardParser.ParseException;
-import com.android.inputmethod.latin.R;
-
import java.util.ArrayList;
/**
@@ -61,8 +61,11 @@ public class Key {
public final int mWidth;
/** Height of the key, not including the gap */
public final int mHeight;
- /** The horizontal gap before this key */
+ /** The horizontal gap around this key */
public final int mGap;
+ /** The visual insets */
+ public final int mVisualInsetsLeft;
+ public final int mVisualInsetsRight;
/** Whether this key is sticky, i.e., a toggle key */
public final boolean mSticky;
/** X coordinate of the key in the keyboard layout */
@@ -83,8 +86,8 @@ public class Key {
* {@link Keyboard#EDGE_TOP} and {@link Keyboard#EDGE_BOTTOM}.
*/
public final int mEdgeFlags;
- /** Whether this is a modifier key, such as Shift or Alt */
- public final boolean mModifier;
+ /** Whether this is a functional key which has different key top than normal key */
+ public final boolean mFunctional;
/** Whether this key repeats itself when held down */
public final boolean mRepeatable;
@@ -93,11 +96,15 @@ public class Key {
/** The current pressed state of this key */
public boolean mPressed;
- /** If this is a sticky key, is it on? */
- public boolean mOn;
+ /** If this is a sticky key, is its highlight on? */
+ public boolean mHighlightOn;
/** Key is enabled and responds on press */
public boolean mEnabled = true;
+ // keyWidth constants
+ private static final int KEYWIDTH_FILL_RIGHT = 0;
+ private static final int KEYWIDTH_FILL_BOTH = -1;
+
private final static int[] KEY_STATE_NORMAL_ON = {
android.R.attr.state_checkable,
android.R.attr.state_checked
@@ -144,13 +151,14 @@ public class Key {
mKeyboard = keyboard;
mHeight = height - keyboard.getVerticalGap();
mGap = keyboard.getHorizontalGap();
+ mVisualInsetsLeft = mVisualInsetsRight = 0;
mWidth = width - mGap;
mEdgeFlags = edgeFlags;
mHintIcon = null;
mManualTemporaryUpperCaseHintIcon = null;
mManualTemporaryUpperCaseCode = Keyboard.CODE_DUMMY;
mLabelOption = 0;
- mModifier = false;
+ mFunctional = false;
mSticky = false;
mRepeatable = false;
mPopupCharacters = null;
@@ -222,11 +230,11 @@ public class Key {
keyXPos = x;
}
}
- if (keyWidth == 0) {
+ if (keyWidth == KEYWIDTH_FILL_RIGHT) {
// If keyWidth is zero, the actual key width will be determined to fill out the
// area up to the right edge of the keyboard.
keyWidth = keyboardWidth - keyXPos;
- } else if (keyWidth < 0) {
+ } else if (keyWidth <= KEYWIDTH_FILL_BOTH) {
// If keyWidth is negative, the actual key width will be determined to fill out the
// area between the nearest key on the left hand side and the right edge of the
// keyboard.
@@ -251,12 +259,16 @@ public class Key {
mKeyboard.getMaxPopupKeyboardColumn());
mRepeatable = style.getBoolean(keyAttr, R.styleable.Keyboard_Key_isRepeatable, false);
- mModifier = style.getBoolean(keyAttr, R.styleable.Keyboard_Key_isModifier, false);
+ mFunctional = style.getBoolean(keyAttr, R.styleable.Keyboard_Key_isFunctional, false);
mSticky = style.getBoolean(keyAttr, R.styleable.Keyboard_Key_isSticky, false);
mEnabled = style.getBoolean(keyAttr, R.styleable.Keyboard_Key_enabled, true);
mEdgeFlags = style.getFlag(keyAttr, R.styleable.Keyboard_Key_keyEdgeFlags, 0)
| row.mRowEdgeFlags;
+ mVisualInsetsLeft = KeyboardParser.getDimensionOrFraction(keyAttr,
+ R.styleable.Keyboard_Key_visualInsetsLeft, mKeyboard.getDisplayHeight(), 0);
+ mVisualInsetsRight = KeyboardParser.getDimensionOrFraction(keyAttr,
+ R.styleable.Keyboard_Key_visualInsetsRight, mKeyboard.getDisplayHeight(), 0);
mPreviewIcon = style.getDrawable(keyAttr, R.styleable.Keyboard_Key_iconPreview);
Keyboard.setDefaultBounds(mPreviewIcon);
mIcon = style.getDrawable(keyAttr, R.styleable.Keyboard_Key_keyIcon);
@@ -342,26 +354,19 @@ public class Key {
/**
* Informs the key that it has been pressed, in case it needs to change its appearance or
* state.
- * @see #onReleased(boolean)
+ * @see #onReleased()
*/
public void onPressed() {
- mPressed = !mPressed;
+ mPressed = true;
}
/**
- * Changes the pressed state of the key. If it is a sticky key, it will also change the
- * toggled state of the key if the finger was release inside.
- * @param inside whether the finger was released inside the key
+ * Informs the key that it has been released, in case it needs to change its appearance or
+ * state.
* @see #onPressed()
*/
- public void onReleased(boolean inside) {
- mPressed = !mPressed;
- if (mSticky && !mKeyboard.isShiftLockEnabled(this))
- mOn = !mOn;
- }
-
- public boolean isInside(int x, int y) {
- return mKeyboard.isInside(this, x, y);
+ public void onReleased() {
+ mPressed = false;
}
/**
@@ -404,20 +409,14 @@ public class Key {
return dx * dx + dy * dy;
}
- // sticky is used for shift key. If a key is not sticky and is modifier,
- // the key will be treated as functional.
- private boolean isFunctionalKey() {
- return !mSticky && mModifier;
- }
-
/**
* Returns the drawable state for the key, based on the current state and type of the key.
* @return the drawable state of the key.
* @see android.graphics.drawable.StateListDrawable#setState(int[])
*/
public int[] getCurrentDrawableState() {
- final boolean pressed = mEnabled && mPressed;
- if (isFunctionalKey()) {
+ final boolean pressed = mPressed;
+ if (!mSticky && mFunctional) {
if (pressed) {
return KEY_STATE_FUNCTIONAL_PRESSED;
} else {
@@ -427,7 +426,7 @@ public class Key {
int[] states = KEY_STATE_NORMAL;
- if (mOn) {
+ if (mHighlightOn) {
if (pressed) {
states = KEY_STATE_PRESSED_ON;
} else {
diff --git a/java/src/com/android/inputmethod/keyboard/KeyDetector.java b/java/src/com/android/inputmethod/keyboard/KeyDetector.java
index a8346c581..7add43a6d 100644
--- a/java/src/com/android/inputmethod/keyboard/KeyDetector.java
+++ b/java/src/com/android/inputmethod/keyboard/KeyDetector.java
@@ -16,36 +16,35 @@
package com.android.inputmethod.keyboard;
+import android.util.Log;
+
import java.util.Arrays;
-import java.util.HashMap;
import java.util.List;
-public abstract class KeyDetector {
- public static final int NOT_A_KEY = -1;
- public static final int NOT_A_CODE = -1;
-
- protected Keyboard mKeyboard;
-
- private Key[] mKeys;
+public class KeyDetector {
+ private static final String TAG = KeyDetector.class.getSimpleName();
+ private static final boolean DEBUG = false;
- protected int mCorrectionX;
-
- protected int mCorrectionY;
+ public static final int NOT_A_CODE = -1;
+ public static final int NOT_A_KEY = -1;
- protected boolean mProximityCorrectOn;
+ private Keyboard mKeyboard;
+ private int mCorrectionX;
+ private int mCorrectionY;
+ private boolean mProximityCorrectOn;
+ private int mProximityThresholdSquare;
- protected int mProximityThresholdSquare;
+ // working area
+ private static final int MAX_NEARBY_KEYS = 12;
+ private final int[] mDistances = new int[MAX_NEARBY_KEYS];
+ private final int[] mIndices = new int[MAX_NEARBY_KEYS];
- public Key[] setKeyboard(Keyboard keyboard, float correctionX, float correctionY) {
+ public void setKeyboard(Keyboard keyboard, float correctionX, float correctionY) {
if (keyboard == null)
throw new NullPointerException();
mCorrectionX = (int)correctionX;
mCorrectionY = (int)correctionY;
mKeyboard = keyboard;
- List<Key> keys = mKeyboard.getKeys();
- Key[] array = keys.toArray(new Key[keys.size()]);
- mKeys = array;
- return array;
}
protected int getTouchX(int x) {
@@ -56,11 +55,11 @@ public abstract class KeyDetector {
return y + mCorrectionY;
}
- protected Key[] getKeys() {
- if (mKeys == null)
+ protected List<Key> getKeys() {
+ if (mKeyboard == null)
throw new IllegalStateException("keyboard isn't set");
// mKeyboard is guaranteed not to be null at setKeybaord() method if mKeys is not null
- return mKeys;
+ return mKeyboard.getKeys();
}
public void setProximityCorrectionEnabled(boolean enabled) {
@@ -76,6 +75,17 @@ public abstract class KeyDetector {
}
/**
+ * Computes maximum size of the array that can contain all nearby key indices returned by
+ * {@link #getKeyIndexAndNearbyCodes}.
+ *
+ * @return Returns maximum size of the array that can contain all nearby key indices returned
+ * by {@link #getKeyIndexAndNearbyCodes}.
+ */
+ protected int getMaxNearbyKeys() {
+ return MAX_NEARBY_KEYS;
+ }
+
+ /**
* Allocates array that can hold all key indices returned by {@link #getKeyIndexAndNearbyCodes}
* method. The maximum size of the array should be computed by {@link #getMaxNearbyKeys}.
*
@@ -89,14 +99,64 @@ public abstract class KeyDetector {
return codes;
}
+ private void initializeNearbyKeys() {
+ Arrays.fill(mDistances, Integer.MAX_VALUE);
+ Arrays.fill(mIndices, NOT_A_KEY);
+ }
+
/**
- * Computes maximum size of the array that can contain all nearby key indices returned by
- * {@link #getKeyIndexAndNearbyCodes}.
+ * Insert the key into nearby keys buffer and sort nearby keys by ascending order of distance.
+ * If the distance of two keys are the same, the key which the point is on should be considered
+ * as a closer one.
*
- * @return Returns maximum size of the array that can contain all nearby key indices returned
- * by {@link #getKeyIndexAndNearbyCodes}.
+ * @param keyIndex index of the key.
+ * @param distance distance between the key's edge and user touched point.
+ * @param isOnKey true if the point is on the key.
+ * @return order of the key in the nearby buffer, 0 if it is the nearest key.
*/
- abstract protected int getMaxNearbyKeys();
+ private int sortNearbyKeys(int keyIndex, int distance, boolean isOnKey) {
+ final int[] distances = mDistances;
+ final int[] indices = mIndices;
+ for (int insertPos = 0; insertPos < distances.length; insertPos++) {
+ final int comparingDistance = distances[insertPos];
+ if (distance < comparingDistance || (distance == comparingDistance && isOnKey)) {
+ final int nextPos = insertPos + 1;
+ if (nextPos < distances.length) {
+ System.arraycopy(distances, insertPos, distances, nextPos,
+ distances.length - nextPos);
+ System.arraycopy(indices, insertPos, indices, nextPos,
+ indices.length - nextPos);
+ }
+ distances[insertPos] = distance;
+ indices[insertPos] = keyIndex;
+ return insertPos;
+ }
+ }
+ return distances.length;
+ }
+
+ private void getNearbyKeyCodes(final int[] allCodes) {
+ final List<Key> keys = getKeys();
+ final int[] indices = mIndices;
+
+ // allCodes[0] should always have the key code even if it is a non-letter key.
+ if (indices[0] == NOT_A_KEY) {
+ allCodes[0] = NOT_A_CODE;
+ return;
+ }
+
+ int numCodes = 0;
+ for (int j = 0; j < indices.length && numCodes < allCodes.length; j++) {
+ final int index = indices[j];
+ if (index == NOT_A_KEY)
+ break;
+ final int code = keys.get(index).mCode;
+ // filter out a non-letter key from nearby keys
+ if (code < Keyboard.CODE_SPACE)
+ continue;
+ allCodes[numCodes++] = code;
+ }
+ }
/**
* Finds all possible nearby key indices around a touch event point and returns the nearest key
@@ -109,32 +169,34 @@ public abstract class KeyDetector {
* @param allCodes All nearby key code except functional key are returned in this array
* @return The nearest key index
*/
- abstract public int getKeyIndexAndNearbyCodes(int x, int y, final int[] allCodes);
+ public int getKeyIndexAndNearbyCodes(int x, int y, final int[] allCodes) {
+ final List<Key> keys = getKeys();
+ final int touchX = getTouchX(x);
+ final int touchY = getTouchY(y);
+
+ initializeNearbyKeys();
+ int primaryIndex = NOT_A_KEY;
+ for (final int index : mKeyboard.getNearestKeys(touchX, touchY)) {
+ final Key key = keys.get(index);
+ final boolean isOnKey = key.isOnKey(touchX, touchY);
+ final int distance = key.squaredDistanceToEdge(touchX, touchY);
+ if (isOnKey || (mProximityCorrectOn && distance < mProximityThresholdSquare)) {
+ final int insertedPosition = sortNearbyKeys(index, distance, isOnKey);
+ if (insertedPosition == 0 && isOnKey)
+ primaryIndex = index;
+ }
+ }
- /**
- * Compute the most common key width in order to use it as proximity key detection threshold.
- *
- * @param keyboard The keyboard to compute the most common key width
- * @return The most common key width in the keyboard
- */
- public static int getMostCommonKeyWidth(final Keyboard keyboard) {
- if (keyboard == null) return 0;
- final List<Key> keys = keyboard.getKeys();
- if (keys == null || keys.size() == 0) return 0;
- final HashMap<Integer, Integer> histogram = new HashMap<Integer, Integer>();
- int maxCount = 0;
- int mostCommonWidth = 0;
- for (final Key key : keys) {
- final Integer width = key.mWidth + key.mGap;
- Integer count = histogram.get(width);
- if (count == null)
- count = 0;
- histogram.put(width, ++count);
- if (count > maxCount) {
- maxCount = count;
- mostCommonWidth = width;
+ if (allCodes != null && allCodes.length > 0) {
+ getNearbyKeyCodes(allCodes);
+ if (DEBUG) {
+ Log.d(TAG, "x=" + x + " y=" + y
+ + " primary="
+ + (primaryIndex == NOT_A_KEY ? "none" : keys.get(primaryIndex).mCode)
+ + " codes=" + Arrays.toString(allCodes));
}
}
- return mostCommonWidth;
+
+ return primaryIndex;
}
}
diff --git a/java/src/com/android/inputmethod/keyboard/KeyStyles.java b/java/src/com/android/inputmethod/keyboard/KeyStyles.java
index 8d9b1b41e..d53df788f 100644
--- a/java/src/com/android/inputmethod/keyboard/KeyStyles.java
+++ b/java/src/com/android/inputmethod/keyboard/KeyStyles.java
@@ -185,7 +185,7 @@ public class KeyStyles {
readDrawable(keyAttr, R.styleable.Keyboard_Key_iconPreview);
readDrawable(keyAttr, R.styleable.Keyboard_Key_keyHintIcon);
readDrawable(keyAttr, R.styleable.Keyboard_Key_shiftedIcon);
- readBoolean(keyAttr, R.styleable.Keyboard_Key_isModifier);
+ readBoolean(keyAttr, R.styleable.Keyboard_Key_isFunctional);
readBoolean(keyAttr, R.styleable.Keyboard_Key_isSticky);
readBoolean(keyAttr, R.styleable.Keyboard_Key_isRepeatable);
readBoolean(keyAttr, R.styleable.Keyboard_Key_enabled);
diff --git a/java/src/com/android/inputmethod/keyboard/Keyboard.java b/java/src/com/android/inputmethod/keyboard/Keyboard.java
index 0b545d9c2..267abccb3 100644
--- a/java/src/com/android/inputmethod/keyboard/Keyboard.java
+++ b/java/src/com/android/inputmethod/keyboard/Keyboard.java
@@ -63,24 +63,22 @@ public class Keyboard {
public static final int CODE_TAB = '\t';
public static final int CODE_SPACE = ' ';
public static final int CODE_PERIOD = '.';
+ public static final int CODE_DASH = '-';
+ public static final int CODE_SINGLE_QUOTE = '\'';
+ public static final int CODE_DOUBLE_QUOTE = '"';
/** Special keys code. These should be aligned with values/keycodes.xml */
public static final int CODE_DUMMY = 0;
public static final int CODE_SHIFT = -1;
public static final int CODE_SWITCH_ALPHA_SYMBOL = -2;
- public static final int CODE_CANCEL = -3;
- public static final int CODE_DONE = -4;
+ public static final int CODE_CAPSLOCK = -3;
+ public static final int CODE_CANCEL = -4;
public static final int CODE_DELETE = -5;
- public static final int CODE_ALT = -6;
+ public static final int CODE_SETTINGS = -6;
+ public static final int CODE_SETTINGS_LONGPRESS = -7;
+ public static final int CODE_SHORTCUT = -8;
// Code value representing the code is not specified.
public static final int CODE_UNSPECIFIED = -99;
- public static final int CODE_SETTINGS = -100;
- public static final int CODE_SETTINGS_LONGPRESS = -101;
- // TODO: remove this once LatinIME stops referring to this.
- public static final int CODE_VOICE = -102;
- public static final int CODE_CAPSLOCK = -103;
- public static final int CODE_NEXT_LANGUAGE = -104;
- public static final int CODE_PREV_LANGUAGE = -105;
/** Horizontal gap default for all rows */
private int mDefaultHorizontalGap;
@@ -128,6 +126,8 @@ public class Keyboard {
/** Height of keyboard */
private int mKeyboardHeight;
+ private int mMostCommonKeyWidth = 0;
+
public final KeyboardId mId;
// Variables for pre-computing nearest keys.
@@ -151,22 +151,20 @@ public class Keyboard {
* @param context the application or service context
* @param xmlLayoutResId the resource file that contains the keyboard layout and keys.
* @param id keyboard identifier
+ * @param width keyboard width
*/
- public Keyboard(Context context, int xmlLayoutResId, KeyboardId id) {
- this(context, xmlLayoutResId, id,
- context.getResources().getDisplayMetrics().widthPixels,
- context.getResources().getDisplayMetrics().heightPixels);
- }
- private Keyboard(Context context, int xmlLayoutResId, KeyboardId id, int width,
- int height) {
- Resources res = context.getResources();
+ public Keyboard(Context context, int xmlLayoutResId, KeyboardId id, int width) {
+ final Resources res = context.getResources();
GRID_WIDTH = res.getInteger(R.integer.config_keyboard_grid_width);
GRID_HEIGHT = res.getInteger(R.integer.config_keyboard_grid_height);
GRID_SIZE = GRID_WIDTH * GRID_HEIGHT;
- mDisplayWidth = width;
- mDisplayHeight = height;
+ final int horizontalEdgesPadding = (int)res.getDimension(
+ R.dimen.keyboard_horizontal_edges_padding);
+ mDisplayWidth = width - horizontalEdgesPadding * 2;
+ // TODO: Adjust the height by referring to the height of area available for drawing as well.
+ mDisplayHeight = res.getDisplayMetrics().heightPixels;
mDefaultHorizontalGap = 0;
setKeyWidth(mDisplayWidth / 10);
@@ -293,7 +291,7 @@ public class Keyboard {
public boolean setShiftLocked(boolean newShiftLockState) {
final Map<Key, Drawable> shiftedIcons = getShiftedIcons();
for (final Key key : getShiftKeys()) {
- key.mOn = newShiftLockState;
+ key.mHighlightOn = newShiftLockState;
key.setIcon(newShiftLockState ? shiftedIcons.get(key) : mNormalShiftIcons.get(key));
}
mShiftState.setShiftLocked(newShiftLockState);
@@ -381,10 +379,6 @@ public class Keyboard {
mProximityInfo.setProximityInfo(mGridNeighbors, getMinWidth(), getHeight(), mKeys);
}
- public boolean isInside(Key key, int x, int y) {
- return key.isOnKey(x, y);
- }
-
/**
* Returns the indices of the keys that are closest to the given point.
* @param x the x-coordinate of the point
@@ -403,6 +397,41 @@ public class Keyboard {
return EMPTY_INT_ARRAY;
}
+ /**
+ * Compute the most common key width in order to use it as proximity key detection threshold.
+ *
+ * @return The most common key width in the keyboard
+ */
+ public int getMostCommonKeyWidth() {
+ if (mMostCommonKeyWidth == 0) {
+ final HashMap<Integer, Integer> histogram = new HashMap<Integer, Integer>();
+ int maxCount = 0;
+ int mostCommonWidth = 0;
+ for (final Key key : mKeys) {
+ final Integer width = key.mWidth + key.mGap;
+ Integer count = histogram.get(width);
+ if (count == null)
+ count = 0;
+ histogram.put(width, ++count);
+ if (count > maxCount) {
+ maxCount = count;
+ mostCommonWidth = width;
+ }
+ }
+ mMostCommonKeyWidth = mostCommonWidth;
+ }
+ return mMostCommonKeyWidth;
+ }
+
+ /**
+ * Return true if spacebar needs showing preview even when "popup on keypress" is off.
+ * @param keyIndex index of the pressing key
+ * @return true if spacebar needs showing preview
+ */
+ public boolean needSpacebarPreview(int keyIndex) {
+ return false;
+ }
+
private void loadKeyboard(Context context, int xmlLayoutResId) {
try {
KeyboardParser parser = new KeyboardParser(this, context.getResources());
diff --git a/java/src/com/android/inputmethod/keyboard/KeyboardId.java b/java/src/com/android/inputmethod/keyboard/KeyboardId.java
index d0e8b32c3..7c03ec71e 100644
--- a/java/src/com/android/inputmethod/keyboard/KeyboardId.java
+++ b/java/src/com/android/inputmethod/keyboard/KeyboardId.java
@@ -16,8 +16,9 @@
package com.android.inputmethod.keyboard;
+import com.android.inputmethod.compat.EditorInfoCompatUtils;
+import com.android.inputmethod.compat.InputTypeCompatUtils;
import com.android.inputmethod.latin.R;
-import com.android.inputmethod.latin.Utils;
import android.view.inputmethod.EditorInfo;
@@ -38,6 +39,7 @@ public class KeyboardId {
public final Locale mLocale;
public final int mOrientation;
+ public final int mWidth;
public final int mMode;
public final int mXmlId;
public final int mColorScheme;
@@ -48,23 +50,26 @@ public class KeyboardId {
public final boolean mHasVoiceKey;
public final int mImeAction;
public final boolean mEnableShiftLock;
+
public final String mXmlName;
+ public final EditorInfo mAttribute;
private final int mHashCode;
public KeyboardId(String xmlName, int xmlId, int colorScheme, Locale locale, int orientation,
- int mode, EditorInfo attribute, boolean hasSettingsKey, boolean voiceKeyEnabled,
- boolean hasVoiceKey, boolean enableShiftLock) {
+ int width, int mode, EditorInfo attribute, boolean hasSettingsKey,
+ boolean voiceKeyEnabled, boolean hasVoiceKey, boolean enableShiftLock) {
final int inputType = (attribute != null) ? attribute.inputType : 0;
final int imeOptions = (attribute != null) ? attribute.imeOptions : 0;
this.mLocale = locale;
this.mOrientation = orientation;
+ this.mWidth = width;
this.mMode = mode;
this.mXmlId = xmlId;
this.mColorScheme = colorScheme;
- this.mWebInput = Utils.isWebInputType(inputType);
- this.mPasswordInput = Utils.isPasswordInputType(inputType)
- || Utils.isVisiblePasswordInputType(inputType);
+ this.mWebInput = InputTypeCompatUtils.isWebInputType(inputType);
+ this.mPasswordInput = InputTypeCompatUtils.isPasswordInputType(inputType)
+ || InputTypeCompatUtils.isVisiblePasswordInputType(inputType);
this.mHasSettingsKey = hasSettingsKey;
this.mVoiceKeyEnabled = voiceKeyEnabled;
this.mHasVoiceKey = hasVoiceKey;
@@ -73,11 +78,14 @@ public class KeyboardId {
this.mImeAction = imeOptions & (
EditorInfo.IME_MASK_ACTION | EditorInfo.IME_FLAG_NO_ENTER_ACTION);
this.mEnableShiftLock = enableShiftLock;
+
this.mXmlName = xmlName;
+ this.mAttribute = attribute;
this.mHashCode = Arrays.hashCode(new Object[] {
locale,
orientation,
+ width,
mode,
xmlId,
colorScheme,
@@ -91,6 +99,18 @@ public class KeyboardId {
});
}
+ public KeyboardId cloneWithNewLayout(String xmlName, int xmlId) {
+ return new KeyboardId(xmlName, xmlId, mColorScheme, mLocale, mOrientation, mWidth, mMode,
+ mAttribute, mHasSettingsKey, mVoiceKeyEnabled, mHasVoiceKey, mEnableShiftLock);
+ }
+
+ public KeyboardId cloneWithNewGeometry(int width) {
+ if (mWidth == width)
+ return this;
+ return new KeyboardId(mXmlName, mXmlId, mColorScheme, mLocale, mOrientation, width, mMode,
+ mAttribute, mHasSettingsKey, mVoiceKeyEnabled, mHasVoiceKey, mEnableShiftLock);
+ }
+
public int getXmlId() {
return mXmlId;
}
@@ -119,6 +139,7 @@ public class KeyboardId {
boolean equals(KeyboardId other) {
return other.mLocale.equals(this.mLocale)
&& other.mOrientation == this.mOrientation
+ && other.mWidth == this.mWidth
&& other.mMode == this.mMode
&& other.mXmlId == this.mXmlId
&& other.mColorScheme == this.mColorScheme
@@ -138,12 +159,12 @@ public class KeyboardId {
@Override
public String toString() {
- return String.format("[%s.xml %s %s %s %s %s%s%s%s%s%s%s]",
+ return String.format("[%s.xml %s %s%d %s %s %s%s%s%s%s%s%s]",
mXmlName,
mLocale,
- (mOrientation == 1 ? "port" : "land"),
+ (mOrientation == 1 ? "port" : "land"), mWidth,
modeName(mMode),
- imeOptionsName(mImeAction),
+ EditorInfoCompatUtils.imeOptionsName(mImeAction),
colorSchemeName(mColorScheme),
(mWebInput ? " webInput" : ""),
(mPasswordInput ? " passwordInput" : ""),
@@ -173,27 +194,4 @@ public class KeyboardId {
}
return null;
}
-
- public static String imeOptionsName(int imeOptions) {
- if (imeOptions == -1) return null;
- final int actionNo = imeOptions & EditorInfo.IME_MASK_ACTION;
- final String action;
- switch (actionNo) {
- case EditorInfo.IME_ACTION_UNSPECIFIED: action = "actionUnspecified"; break;
- case EditorInfo.IME_ACTION_NONE: action = "actionNone"; break;
- case EditorInfo.IME_ACTION_GO: action = "actionGo"; break;
- case EditorInfo.IME_ACTION_SEARCH: action = "actionSearch"; break;
- case EditorInfo.IME_ACTION_SEND: action = "actionSend"; break;
- case EditorInfo.IME_ACTION_DONE: action = "actionDone"; break;
- case EditorInfo.IME_ACTION_NEXT: action = "actionNext"; break;
- case EditorInfo.IME_ACTION_PREVIOUS: action = "actionPrevious"; break;
- default: action = "actionUnknown(" + actionNo + ")"; break;
- }
- if ((imeOptions & EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0) {
- return "flagNoEnterAction|" + action;
- } else {
- return action;
- }
- }
}
-
diff --git a/java/src/com/android/inputmethod/keyboard/KeyboardParser.java b/java/src/com/android/inputmethod/keyboard/KeyboardParser.java
index 308651a9e..4ae011347 100644
--- a/java/src/com/android/inputmethod/keyboard/KeyboardParser.java
+++ b/java/src/com/android/inputmethod/keyboard/KeyboardParser.java
@@ -16,11 +16,13 @@
package com.android.inputmethod.keyboard;
+import com.android.inputmethod.compat.EditorInfoCompatUtils;
import com.android.inputmethod.latin.R;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
+import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
@@ -121,6 +123,7 @@ public class KeyboardParser {
private final Keyboard mKeyboard;
private final Resources mResources;
+ private int mHorizontalEdgesPadding;
private int mCurrentX = 0;
private int mCurrentY = 0;
private int mMaxRowWidth = 0;
@@ -131,6 +134,7 @@ public class KeyboardParser {
public KeyboardParser(Keyboard keyboard, Resources res) {
mKeyboard = keyboard;
mResources = res;
+ mHorizontalEdgesPadding = (int)res.getDimension(R.dimen.keyboard_horizontal_edges_padding);
}
public int getMaxRowWidth() {
@@ -150,6 +154,7 @@ public class KeyboardParser {
final String tag = parser.getName();
if (TAG_KEYBOARD.equals(tag)) {
parseKeyboardAttributes(parser);
+ startKeyboard();
parseKeyboardContent(parser, mKeyboard.getKeys());
break;
} else {
@@ -159,6 +164,27 @@ public class KeyboardParser {
}
}
+ public static String parseKeyboardLocale(
+ Context context, int resId) throws XmlPullParserException, IOException {
+ final Resources res = context.getResources();
+ final XmlResourceParser parser = res.getXml(resId);
+ if (parser == null) return "";
+ int event;
+ while ((event = parser.next()) != XmlPullParser.END_DOCUMENT) {
+ if (event == XmlPullParser.START_TAG) {
+ final String tag = parser.getName();
+ if (TAG_KEYBOARD.equals(tag)) {
+ final TypedArray keyboardAttr = res.obtainAttributes(Xml.asAttributeSet(parser),
+ R.styleable.Keyboard);
+ return keyboardAttr.getString(R.styleable.Keyboard_keyboardLocale);
+ } else {
+ throw new IllegalStartTag(parser, TAG_KEYBOARD);
+ }
+ }
+ }
+ return "";
+ }
+
private void parseKeyboardAttributes(XmlResourceParser parser) {
final Keyboard keyboard = mKeyboard;
final TypedArray keyboardAttr = mResources.obtainAttributes(Xml.asAttributeSet(parser),
@@ -170,9 +196,20 @@ public class KeyboardParser {
final int keyboardHeight = (int)keyboardAttr.getDimension(
R.styleable.Keyboard_keyboardHeight, displayHeight / 2);
final int maxKeyboardHeight = getDimensionOrFraction(keyboardAttr,
- R.styleable.Keyboard_maxKeyboardHeight, displayHeight, displayHeight / 2);
- // Keyboard height will not exceed maxKeyboardHeight.
- final int height = Math.min(keyboardHeight, maxKeyboardHeight);
+ R.styleable.Keyboard_maxKeyboardHeight, displayHeight, displayHeight / 2);
+ int minKeyboardHeight = getDimensionOrFraction(keyboardAttr,
+ R.styleable.Keyboard_minKeyboardHeight, displayHeight, displayHeight / 2);
+ if (minKeyboardHeight < 0) {
+ // Specified fraction was negative, so it should be calculated against display
+ // width.
+ final int displayWidth = keyboard.getDisplayWidth();
+ minKeyboardHeight = -getDimensionOrFraction(keyboardAttr,
+ R.styleable.Keyboard_minKeyboardHeight, displayWidth, displayWidth / 2);
+ }
+ // Keyboard height will not exceed maxKeyboardHeight and will not be less than
+ // minKeyboardHeight.
+ final int height = Math.max(
+ Math.min(keyboardHeight, maxKeyboardHeight), minKeyboardHeight);
final int width = keyboard.getDisplayWidth();
keyboard.setKeyboardHeight(height);
@@ -470,7 +507,7 @@ public class KeyboardParser {
booleanAttr(a, R.styleable.Keyboard_Case_hasSettingsKey, "hasSettingsKey"),
booleanAttr(a, R.styleable.Keyboard_Case_voiceKeyEnabled, "voiceKeyEnabled"),
booleanAttr(a, R.styleable.Keyboard_Case_hasVoiceKey, "hasVoiceKey"),
- textAttr(KeyboardId.imeOptionsName(
+ textAttr(EditorInfoCompatUtils.imeOptionsName(
a.getInt(R.styleable.Keyboard_Case_imeAction, -1)), "imeAction"),
textAttr(a.getString(R.styleable.Keyboard_Case_languageCode), "languageCode"),
textAttr(a.getString(R.styleable.Keyboard_Case_countryCode), "countryCode"),
@@ -536,25 +573,32 @@ public class KeyboardParser {
throw new NonEmptyTag(tag, parser);
}
+ private void startKeyboard() {
+ mCurrentY += (int)mResources.getDimension(R.dimen.keyboard_top_padding);
+ }
+
private void startRow(Row row) {
mCurrentX = 0;
+ setSpacer(mCurrentX, mHorizontalEdgesPadding);
mCurrentRow = row;
}
private void endRow() {
if (mCurrentRow == null)
throw new InflateException("orphant end row tag");
+ setSpacer(mCurrentX, mHorizontalEdgesPadding);
+ if (mCurrentX > mMaxRowWidth)
+ mMaxRowWidth = mCurrentX;
mCurrentY += mCurrentRow.mDefaultHeight;
mCurrentRow = null;
}
private void endKey(Key key) {
mCurrentX = key.mX + key.mGap + key.mWidth;
- if (mCurrentX > mMaxRowWidth)
- mMaxRowWidth = mCurrentX;
}
private void endKeyboard(int defaultVerticalGap) {
+ mCurrentY += (int)mResources.getDimension(R.dimen.keyboard_bottom_padding);
mTotalHeight = mCurrentY - defaultVerticalGap;
}
@@ -566,11 +610,15 @@ public class KeyboardParser {
final TypedValue value = a.peekValue(index);
if (value == null)
return defValue;
- if (value.type == TypedValue.TYPE_DIMENSION) {
- return a.getDimensionPixelOffset(index, defValue);
- } else if (value.type == TypedValue.TYPE_FRACTION) {
+ if (value.type == TypedValue.TYPE_FRACTION) {
// Round it to avoid values like 47.9999 from getting truncated
return Math.round(a.getFraction(index, base, base, defValue));
+ } else if (value.type == TypedValue.TYPE_DIMENSION) {
+ return a.getDimensionPixelOffset(index, defValue);
+ } else if (value.type >= TypedValue.TYPE_FIRST_INT
+ && value.type <= TypedValue.TYPE_LAST_INT) {
+ // For enum value.
+ return a.getInt(index, defValue);
}
return defValue;
}
diff --git a/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java b/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java
index 64a23ab92..2512118d4 100644
--- a/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java
+++ b/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java
@@ -16,47 +16,51 @@
package com.android.inputmethod.keyboard;
-import com.android.inputmethod.latin.LatinIME;
-import com.android.inputmethod.latin.LatinImeLogger;
-import com.android.inputmethod.latin.R;
-import com.android.inputmethod.latin.Settings;
-import com.android.inputmethod.latin.SubtypeSwitcher;
-import com.android.inputmethod.latin.Utils;
-
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.util.Log;
+import android.view.ContextThemeWrapper;
import android.view.InflateException;
+import android.view.LayoutInflater;
+import android.view.View;
import android.view.inputmethod.EditorInfo;
-import android.view.inputmethod.InputMethodManager;
+
+import com.android.inputmethod.compat.InputMethodManagerCompatWrapper;
+import com.android.inputmethod.latin.LatinIME;
+import com.android.inputmethod.latin.LatinImeLogger;
+import com.android.inputmethod.latin.R;
+import com.android.inputmethod.latin.Settings;
+import com.android.inputmethod.latin.SubtypeSwitcher;
+import com.android.inputmethod.latin.Utils;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Locale;
public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceChangeListener {
- private static final String TAG = "KeyboardSwitcher";
- private static final boolean DEBUG = false;
+ private static final String TAG = KeyboardSwitcher.class.getSimpleName();
+ private static final boolean DEBUG_CACHE = LatinImeLogger.sDBG;
public static final boolean DEBUG_STATE = false;
private static String sConfigDefaultKeyboardThemeId;
public static final String PREF_KEYBOARD_LAYOUT = "pref_keyboard_layout_20100902";
private static final int[] KEYBOARD_THEMES = {
- R.layout.input_basic,
- R.layout.input_basic_highcontrast,
- R.layout.input_stone_normal,
- R.layout.input_stone_bold,
- R.layout.input_gingerbread,
- R.layout.input_honeycomb,
+ R.style.KeyboardTheme,
+ R.style.KeyboardTheme_HighContrast,
+ R.style.KeyboardTheme_Stone,
+ R.style.KeyboardTheme_Stone_Bold,
+ R.style.KeyboardTheme_Gingerbread,
+ R.style.KeyboardTheme_Honeycomb,
};
private SubtypeSwitcher mSubtypeSwitcher;
private SharedPreferences mPrefs;
- private LatinKeyboardView mInputView;
+ private LatinKeyboardView mKeyboardView;
private LatinIME mInputMethodService;
+ // TODO: Combine these key state objects with auto mode switch state.
private ShiftKeyState mShiftKeyState = new ShiftKeyState("Shift");
private ModifierKeyState mSymbolKeyState = new ModifierKeyState("Symbol");
@@ -75,13 +79,17 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha
private boolean mVoiceKeyEnabled;
private boolean mVoiceButtonOnPrimary;
- private static final int AUTO_MODE_SWITCH_STATE_ALPHA = 0;
- private static final int AUTO_MODE_SWITCH_STATE_SYMBOL_BEGIN = 1;
- private static final int AUTO_MODE_SWITCH_STATE_SYMBOL = 2;
+ // TODO: Encapsulate these state handling to separate class and combine with ShiftKeyState
+ // and ModifierKeyState.
+ private static final int SWITCH_STATE_ALPHA = 0;
+ private static final int SWITCH_STATE_SYMBOL_BEGIN = 1;
+ private static final int SWITCH_STATE_SYMBOL = 2;
// The following states are used only on the distinct multi-touch panel devices.
- private static final int AUTO_MODE_SWITCH_STATE_MOMENTARY = 3;
- private static final int AUTO_MODE_SWITCH_STATE_CHORDING = 4;
- private int mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_ALPHA;
+ private static final int SWITCH_STATE_MOMENTARY_ALPHA_AND_SYMBOL = 3;
+ private static final int SWITCH_STATE_MOMENTARY_SYMBOL_AND_MORE = 4;
+ private static final int SWITCH_STATE_CHORDING_ALPHA = 5;
+ private static final int SWITCH_STATE_CHORDING_SYMBOL = 6;
+ private int mSwitchState = SWITCH_STATE_ALPHA;
// Indicates whether or not we have the settings key in option of settings
private boolean mSettingsKeyEnabledInSettings;
@@ -93,7 +101,8 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha
// Default is SETTINGS_KEY_MODE_AUTO.
private static final int DEFAULT_SETTINGS_KEY_MODE = SETTINGS_KEY_MODE_AUTO;
- private int mLayoutId;
+ private int mThemeIndex;
+ private int mKeyboardWidth;
private static final KeyboardSwitcher sInstance = new KeyboardSwitcher();
@@ -113,18 +122,18 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha
try {
sConfigDefaultKeyboardThemeId = ims.getString(
R.string.config_default_keyboard_theme_id);
- sInstance.mLayoutId = Integer.valueOf(
+ sInstance.mThemeIndex = Integer.valueOf(
prefs.getString(PREF_KEYBOARD_LAYOUT, sConfigDefaultKeyboardThemeId));
} catch (NumberFormatException e) {
sConfigDefaultKeyboardThemeId = "0";
- sInstance.mLayoutId = 0;
+ sInstance.mThemeIndex = 0;
}
prefs.registerOnSharedPreferenceChangeListener(sInstance);
}
public void loadKeyboard(EditorInfo attribute, boolean voiceKeyEnabled,
boolean voiceButtonOnPrimary) {
- mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_ALPHA;
+ mSwitchState = SWITCH_STATE_ALPHA;
try {
loadKeyboardInternal(attribute, voiceKeyEnabled, voiceButtonOnPrimary, false);
} catch (RuntimeException e) {
@@ -137,7 +146,7 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha
private void loadKeyboardInternal(EditorInfo attribute, boolean voiceButtonEnabled,
boolean voiceButtonOnPrimary, boolean isSymbols) {
- if (mInputView == null) return;
+ if (mKeyboardView == null) return;
mAttribute = attribute;
mVoiceKeyEnabled = voiceButtonEnabled;
@@ -147,19 +156,38 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha
mSettingsKeyEnabledInSettings = getSettingsKeyMode(mPrefs, mInputMethodService);
final KeyboardId id = getKeyboardId(attribute, isSymbols);
- final Keyboard oldKeyboard = mInputView.getKeyboard();
- if (oldKeyboard != null && oldKeyboard.mId.equals(id))
- return;
+ // Note: This comment is only applied for phone number keyboard layout.
+ // On non-xlarge device, "@integer/key_switch_alpha_symbol" key code is used to switch
+ // between "phone keyboard" and "phone symbols keyboard". But on xlarge device,
+ // "@integer/key_shift" key code is used for that purpose in order to properly display
+ // "more" and "locked more" key labels. To achieve these behavior, we should initialize
+ // mSymbolsId and mSymbolsShiftedId to "phone keyboard" and "phone symbols keyboard"
+ // respectively here for xlarge device's layout switching.
+ mSymbolsId = makeSiblingKeyboardId(id, R.xml.kbd_symbols, R.xml.kbd_phone);
+ mSymbolsShiftedId = makeSiblingKeyboardId(
+ id, R.xml.kbd_symbols_shift, R.xml.kbd_phone_symbols);
- makeSymbolsKeyboardIds(id.mMode, attribute);
- mCurrentId = id;
- mInputView.setPreviewEnabled(mInputMethodService.getPopupOn());
setKeyboard(getKeyboard(id));
}
+ public void onSizeChanged() {
+ final int width = mInputMethodService.getWindow().getWindow().getDecorView().getWidth();
+ if (width == 0)
+ return;
+ mKeyboardWidth = width;
+ // Set keyboard with new width.
+ final KeyboardId newId = mCurrentId.cloneWithNewGeometry(width);
+ setKeyboard(getKeyboard(newId));
+ }
+
private void setKeyboard(final Keyboard newKeyboard) {
- final Keyboard oldKeyboard = mInputView.getKeyboard();
- mInputView.setKeyboard(newKeyboard);
+ final Keyboard oldKeyboard = mKeyboardView.getKeyboard();
+ mKeyboardView.setKeyboard(newKeyboard);
+ mCurrentId = newKeyboard.mId;
+ final Resources res = mInputMethodService.getResources();
+ mKeyboardView.setKeyPreviewPopupEnabled(
+ Settings.Values.isKeyPreviewPopupEnabled(mPrefs, res),
+ Settings.Values.getKeyPreviewPopupDismissDelay(mPrefs, res));
final boolean localeChanged = (oldKeyboard == null)
|| !newKeyboard.mId.mLocale.equals(oldKeyboard.mId.mLocale);
mInputMethodService.mHandler.startDisplayLanguageOnSpacebar(localeChanged);
@@ -169,22 +197,23 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha
final SoftReference<LatinKeyboard> ref = mKeyboardCache.get(id);
LatinKeyboard keyboard = (ref == null) ? null : ref.get();
if (keyboard == null) {
- final Locale savedLocale = mSubtypeSwitcher.changeSystemLocale(
+ final Resources res = mInputMethodService.getResources();
+ final Locale savedLocale = Utils.setSystemLocale(res,
mSubtypeSwitcher.getInputLocale());
- keyboard = new LatinKeyboard(mInputMethodService, id);
+ keyboard = new LatinKeyboard(mInputMethodService, id, id.mWidth);
if (id.mEnableShiftLock) {
keyboard.enableShiftLock();
}
mKeyboardCache.put(id, new SoftReference<LatinKeyboard>(keyboard));
- if (DEBUG)
+ if (DEBUG_CACHE)
Log.d(TAG, "keyboard cache size=" + mKeyboardCache.size() + ": "
+ ((ref == null) ? "LOAD" : "GCed") + " id=" + id);
- mSubtypeSwitcher.changeSystemLocale(savedLocale);
- } else if (DEBUG) {
+ Utils.setSystemLocale(res, savedLocale);
+ } else if (DEBUG_CACHE) {
Log.d(TAG, "keyboard cache size=" + mKeyboardCache.size() + ": HIT id=" + id);
}
@@ -195,6 +224,7 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha
// we should reset the text fade factor. It is also applicable to shortcut key.
keyboard.setSpacebarTextFadeFactor(0.0f, null);
keyboard.updateShortcutKey(mSubtypeSwitcher.isShortcutImeReady(), null);
+ keyboard.setSpacebarSlidingLanguageSwitchDiff(0);
return keyboard;
}
@@ -240,33 +270,19 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha
final boolean hasSettingsKey = hasSettingsKey(attribute);
final Resources res = mInputMethodService.getResources();
final int orientation = res.getConfiguration().orientation;
+ if (mKeyboardWidth == 0)
+ mKeyboardWidth = res.getDisplayMetrics().widthPixels;
final Locale locale = mSubtypeSwitcher.getInputLocale();
return new KeyboardId(
- res.getResourceEntryName(xmlId), xmlId, charColorId, locale, orientation, mode,
- attribute, hasSettingsKey, mVoiceKeyEnabled, hasVoiceKey, enableShiftLock);
+ res.getResourceEntryName(xmlId), xmlId, charColorId, locale, orientation,
+ mKeyboardWidth, mode, attribute, hasSettingsKey, mVoiceKeyEnabled, hasVoiceKey,
+ enableShiftLock);
}
- private void makeSymbolsKeyboardIds(final int mode, EditorInfo attribute) {
- final Locale locale = mSubtypeSwitcher.getInputLocale();
- final Resources res = mInputMethodService.getResources();
- final int orientation = res.getConfiguration().orientation;
- final int colorScheme = getColorScheme();
- final boolean hasVoiceKey = mVoiceKeyEnabled && !mVoiceButtonOnPrimary;
- final boolean hasSettingsKey = hasSettingsKey(attribute);
- // Note: This comment is only applied for phone number keyboard layout.
- // On non-xlarge device, "@integer/key_switch_alpha_symbol" key code is used to switch
- // between "phone keyboard" and "phone symbols keyboard". But on xlarge device,
- // "@integer/key_shift" key code is used for that purpose in order to properly display
- // "more" and "locked more" key labels. To achieve these behavior, we should initialize
- // mSymbolsId and mSymbolsShiftedId to "phone keyboard" and "phone symbols keyboard"
- // respectively here for xlarge device's layout switching.
- int xmlId = mode == KeyboardId.MODE_PHONE ? R.xml.kbd_phone : R.xml.kbd_symbols;
- final String xmlName = res.getResourceEntryName(xmlId);
- mSymbolsId = new KeyboardId(xmlName, xmlId, colorScheme, locale, orientation, mode,
- attribute, hasSettingsKey, mVoiceKeyEnabled, hasVoiceKey, true);
- xmlId = mode == KeyboardId.MODE_PHONE ? R.xml.kbd_phone_symbols : R.xml.kbd_symbols_shift;
- mSymbolsShiftedId = new KeyboardId(xmlName, xmlId, colorScheme, locale, orientation, mode,
- attribute, hasSettingsKey, mVoiceKeyEnabled, hasVoiceKey, true);
+ private KeyboardId makeSiblingKeyboardId(KeyboardId base, int alphabet, int phone) {
+ final int xmlId = base.mMode == KeyboardId.MODE_PHONE ? phone : alphabet;
+ final String xmlName = mInputMethodService.getResources().getResourceEntryName(xmlId);
+ return base.cloneWithNewLayout(xmlName, xmlId);
}
public int getKeyboardMode() {
@@ -278,30 +294,24 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha
}
public boolean isInputViewShown() {
- return mInputView != null && mInputView.isShown();
+ return mKeyboardView != null && mKeyboardView.isShown();
}
public boolean isKeyboardAvailable() {
- if (mInputView != null)
- return mInputView.getKeyboard() != null;
+ if (mKeyboardView != null)
+ return mKeyboardView.getKeyboard() != null;
return false;
}
public LatinKeyboard getLatinKeyboard() {
- if (mInputView != null) {
- final Keyboard keyboard = mInputView.getKeyboard();
+ if (mKeyboardView != null) {
+ final Keyboard keyboard = mKeyboardView.getKeyboard();
if (keyboard instanceof LatinKeyboard)
return (LatinKeyboard)keyboard;
}
return null;
}
- public void keyReleased() {
- LatinKeyboard latinKeyboard = getLatinKeyboard();
- if (latinKeyboard != null)
- latinKeyboard.keyReleased();
- }
-
public boolean isShiftedOrShiftLocked() {
LatinKeyboard latinKeyboard = getLatinKeyboard();
if (latinKeyboard != null)
@@ -344,12 +354,11 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha
// state when shift key is pressed to go to normal mode.
// On the other hand, on distinct multi touch panel device, turning off the shift locked
// state with shift key pressing is handled by onReleaseShift().
- if ((!hasDistinctMultitouch() || isAccessibilityEnabled())
- && !shifted && latinKeyboard.isShiftLocked()) {
+ if (!hasDistinctMultitouch() && !shifted && latinKeyboard.isShiftLocked()) {
latinKeyboard.setShiftLocked(false);
}
if (latinKeyboard.setShifted(shifted)) {
- mInputView.invalidateAllKeys();
+ mKeyboardView.invalidateAllKeys();
}
}
}
@@ -357,7 +366,7 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha
private void setShiftLocked(boolean shiftLocked) {
LatinKeyboard latinKeyboard = getLatinKeyboard();
if (latinKeyboard != null && latinKeyboard.setShiftLocked(shiftLocked)) {
- mInputView.invalidateAllKeys();
+ mKeyboardView.invalidateAllKeys();
}
}
@@ -399,7 +408,7 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha
LatinKeyboard latinKeyboard = getLatinKeyboard();
if (latinKeyboard != null) {
latinKeyboard.setAutomaticTemporaryUpperCase();
- mInputView.invalidateAllKeys();
+ mKeyboardView.invalidateAllKeys();
}
}
@@ -443,9 +452,6 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha
public void onPressShift(boolean withSliding) {
if (!isKeyboardAvailable())
return;
- // If accessibility is enabled, disable momentary shift lock.
- if (isAccessibilityEnabled())
- return;
ShiftKeyState shiftKeyState = mShiftKeyState;
if (DEBUG_STATE)
Log.d(TAG, "onPressShift:"
@@ -475,15 +481,13 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha
// In symbol mode, just toggle symbol and symbol more keyboard.
shiftKeyState.onPress();
toggleShift();
+ mSwitchState = SWITCH_STATE_MOMENTARY_SYMBOL_AND_MORE;
}
}
public void onReleaseShift(boolean withSliding) {
if (!isKeyboardAvailable())
return;
- // If accessibility is enabled, disable momentary shift lock.
- if (isAccessibilityEnabled())
- return;
ShiftKeyState shiftKeyState = mShiftKeyState;
if (DEBUG_STATE)
Log.d(TAG, "onReleaseShift:"
@@ -496,6 +500,10 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha
} else if (isShiftLocked() && !shiftKeyState.isIgnoring() && !withSliding) {
// Shift has been pressed without chording while caps lock state.
toggleCapsLock();
+ // To be able to turn off caps lock by "double tap" on shift key, we should ignore
+ // the second tap of the "double tap" from now for a while because we just have
+ // already turned off caps lock above.
+ mKeyboardView.startIgnoringDoubleTap();
} else if (isShiftedOrShiftLocked() && shiftKeyState.isPressingOnShifted()
&& !withSliding) {
// Shift has been pressed without chording while shifted state.
@@ -506,42 +514,40 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha
// transited from automatic temporary upper case.
toggleShift();
}
+ } else {
+ // In symbol mode, snap back to the previous keyboard mode if the user chords the shift
+ // key and another key, then releases the shift key.
+ if (mSwitchState == SWITCH_STATE_CHORDING_SYMBOL) {
+ toggleShift();
+ }
}
shiftKeyState.onRelease();
}
public void onPressSymbol() {
- // If accessibility is enabled, disable momentary symbol lock.
- if (isAccessibilityEnabled())
- return;
if (DEBUG_STATE)
Log.d(TAG, "onPressSymbol:"
+ " keyboard=" + getLatinKeyboard().getKeyboardShiftState()
+ " symbolKeyState=" + mSymbolKeyState);
changeKeyboardMode();
mSymbolKeyState.onPress();
- mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_MOMENTARY;
+ mSwitchState = SWITCH_STATE_MOMENTARY_ALPHA_AND_SYMBOL;
}
public void onReleaseSymbol() {
- // If accessibility is enabled, disable momentary symbol lock.
- if (isAccessibilityEnabled())
- return;
if (DEBUG_STATE)
Log.d(TAG, "onReleaseSymbol:"
+ " keyboard=" + getLatinKeyboard().getKeyboardShiftState()
+ " symbolKeyState=" + mSymbolKeyState);
// Snap back to the previous keyboard mode if the user chords the mode change key and
- // other key, then released the mode change key.
- if (mAutoModeSwitchState == AUTO_MODE_SWITCH_STATE_CHORDING)
+ // another key, then releases the mode change key.
+ if (mSwitchState == SWITCH_STATE_CHORDING_ALPHA) {
changeKeyboardMode();
+ }
mSymbolKeyState.onRelease();
}
public void onOtherKeyPressed() {
- // If accessibility is enabled, disable momentary mode locking.
- if (isAccessibilityEnabled())
- return;
if (DEBUG_STATE)
Log.d(TAG, "onOtherKeyPressed:"
+ " keyboard=" + getLatinKeyboard().getKeyboardShiftState()
@@ -553,8 +559,13 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha
public void onCancelInput() {
// Snap back to the previous keyboard mode if the user cancels sliding input.
- if (mAutoModeSwitchState == AUTO_MODE_SWITCH_STATE_MOMENTARY && getPointerCount() == 1)
- changeKeyboardMode();
+ if (getPointerCount() == 1) {
+ if (mSwitchState == SWITCH_STATE_MOMENTARY_ALPHA_AND_SYMBOL) {
+ changeKeyboardMode();
+ } else if (mSwitchState == SWITCH_STATE_MOMENTARY_SYMBOL_AND_MORE) {
+ toggleShift();
+ }
+ }
}
private void toggleShiftInSymbol() {
@@ -562,74 +573,91 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha
return;
final LatinKeyboard keyboard;
if (mCurrentId.equals(mSymbolsId) || !mCurrentId.equals(mSymbolsShiftedId)) {
- mCurrentId = mSymbolsShiftedId;
- keyboard = getKeyboard(mCurrentId);
+ keyboard = getKeyboard(mSymbolsShiftedId);
// Symbol shifted keyboard has an ALT key that has a caps lock style indicator. To
- // enable the indicator, we need to call enableShiftLock() and setShiftLocked(true).
- // Thus we can keep the ALT key's Key.on value true while LatinKey.onRelease() is
- // called.
+ // enable the indicator, we need to call setShiftLocked(true).
keyboard.setShiftLocked(true);
} else {
- mCurrentId = mSymbolsId;
- keyboard = getKeyboard(mCurrentId);
+ keyboard = getKeyboard(mSymbolsId);
// Symbol keyboard has an ALT key that has a caps lock style indicator. To disable the
- // indicator, we need to call enableShiftLock() and setShiftLocked(false).
- keyboard.setShifted(false);
+ // indicator, we need to call setShiftLocked(false).
+ keyboard.setShiftLocked(false);
}
setKeyboard(keyboard);
}
- public boolean isInMomentaryAutoModeSwitchState() {
- return mAutoModeSwitchState == AUTO_MODE_SWITCH_STATE_MOMENTARY;
+ public boolean isInMomentarySwitchState() {
+ return mSwitchState == SWITCH_STATE_MOMENTARY_ALPHA_AND_SYMBOL
+ || mSwitchState == SWITCH_STATE_MOMENTARY_SYMBOL_AND_MORE;
}
public boolean isVibrateAndSoundFeedbackRequired() {
- return mInputView == null || !mInputView.isInSlidingKeyInput();
+ return mKeyboardView == null || !mKeyboardView.isInSlidingKeyInput();
}
private int getPointerCount() {
- return mInputView == null ? 0 : mInputView.getPointerCount();
+ return mKeyboardView == null ? 0 : mKeyboardView.getPointerCount();
}
private void toggleKeyboardMode() {
loadKeyboardInternal(mAttribute, mVoiceKeyEnabled, mVoiceButtonOnPrimary, !mIsSymbols);
if (mIsSymbols) {
- mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_SYMBOL_BEGIN;
+ mSwitchState = SWITCH_STATE_SYMBOL_BEGIN;
} else {
- mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_ALPHA;
+ mSwitchState = SWITCH_STATE_ALPHA;
}
}
- public boolean isAccessibilityEnabled() {
- return mInputView != null && mInputView.isAccessibilityEnabled();
- }
-
public boolean hasDistinctMultitouch() {
- return mInputView != null && mInputView.hasDistinctMultitouch();
+ return mKeyboardView != null && mKeyboardView.hasDistinctMultitouch();
+ }
+
+ private static boolean isSpaceCharacter(int c) {
+ return c == Keyboard.CODE_SPACE || c == Keyboard.CODE_ENTER;
+ }
+
+ private static boolean isQuoteCharacter(int c) {
+ // Apostrophe, quotation mark.
+ if (c == Keyboard.CODE_SINGLE_QUOTE || c == Keyboard.CODE_DOUBLE_QUOTE)
+ return true;
+ // \u2018: Left single quotation mark
+ // \u2019: Right single quotation mark
+ // \u201a: Single low-9 quotation mark
+ // \u201b: Single high-reversed-9 quotation mark
+ // \u201c: Left double quotation mark
+ // \u201d: Right double quotation mark
+ // \u201e: Double low-9 quotation mark
+ // \u201f: Double high-reversed-9 quotation mark
+ if (c >= '\u2018' && c <= '\u201f')
+ return true;
+ // \u00ab: Left-pointing double angle quotation mark
+ // \u00bb: Right-pointing double angle quotation mark
+ if (c == '\u00ab' || c == '\u00bb')
+ return true;
+ return false;
}
/**
* Updates state machine to figure out when to automatically snap back to the previous mode.
*/
- public void onKey(int key) {
+ public void onKey(int code) {
if (DEBUG_STATE)
- Log.d(TAG, "onKey: code=" + key + " autoModeSwitchState=" + mAutoModeSwitchState
+ Log.d(TAG, "onKey: code=" + code + " switchState=" + mSwitchState
+ " pointers=" + getPointerCount());
- switch (mAutoModeSwitchState) {
- case AUTO_MODE_SWITCH_STATE_MOMENTARY:
+ switch (mSwitchState) {
+ case SWITCH_STATE_MOMENTARY_ALPHA_AND_SYMBOL:
// Only distinct multi touch devices can be in this state.
// On non-distinct multi touch devices, mode change key is handled by
// {@link LatinIME#onCodeInput}, not by {@link LatinIME#onPress} and
- // {@link LatinIME#onRelease}. So, on such devices, {@link #mAutoModeSwitchState} starts
- // from {@link #AUTO_MODE_SWITCH_STATE_SYMBOL_BEGIN}, or
- // {@link #AUTO_MODE_SWITCH_STATE_ALPHA}, not from
- // {@link #AUTO_MODE_SWITCH_STATE_MOMENTARY}.
- if (key == Keyboard.CODE_SWITCH_ALPHA_SYMBOL) {
+ // {@link LatinIME#onRelease}. So, on such devices, {@link #mSwitchState} starts
+ // from {@link #SWITCH_STATE_SYMBOL_BEGIN}, or {@link #SWITCH_STATE_ALPHA}, not from
+ // {@link #SWITCH_STATE_MOMENTARY}.
+ if (code == Keyboard.CODE_SWITCH_ALPHA_SYMBOL) {
// Detected only the mode change key has been pressed, and then released.
if (mIsSymbols) {
- mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_SYMBOL_BEGIN;
+ mSwitchState = SWITCH_STATE_SYMBOL_BEGIN;
} else {
- mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_ALPHA;
+ mSwitchState = SWITCH_STATE_ALPHA;
}
} else if (getPointerCount() == 1) {
// Snap back to the previous keyboard mode if the user pressed the mode change key
@@ -640,71 +668,96 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha
} else {
// Chording input is being started. The keyboard mode will be snapped back to the
// previous mode in {@link onReleaseSymbol} when the mode change key is released.
- mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_CHORDING;
+ mSwitchState = SWITCH_STATE_CHORDING_ALPHA;
+ }
+ break;
+ case SWITCH_STATE_MOMENTARY_SYMBOL_AND_MORE:
+ if (code == Keyboard.CODE_SHIFT) {
+ // Detected only the shift key has been pressed on symbol layout, and then released.
+ mSwitchState = SWITCH_STATE_SYMBOL_BEGIN;
+ } else if (getPointerCount() == 1) {
+ // Snap back to the previous keyboard mode if the user pressed the shift key on
+ // symbol mode and slid to other key, then released the finger.
+ toggleShift();
+ mSwitchState = SWITCH_STATE_SYMBOL;
+ } else {
+ // Chording input is being started. The keyboard mode will be snapped back to the
+ // previous mode in {@link onReleaseShift} when the shift key is released.
+ mSwitchState = SWITCH_STATE_CHORDING_SYMBOL;
}
break;
- case AUTO_MODE_SWITCH_STATE_SYMBOL_BEGIN:
- if (key != Keyboard.CODE_SPACE && key != Keyboard.CODE_ENTER && key >= 0) {
- mAutoModeSwitchState = AUTO_MODE_SWITCH_STATE_SYMBOL;
+ case SWITCH_STATE_SYMBOL_BEGIN:
+ if (!isSpaceCharacter(code) && code >= 0) {
+ mSwitchState = SWITCH_STATE_SYMBOL;
+ }
+ // Snap back to alpha keyboard mode immediately if user types a quote character.
+ if (isQuoteCharacter(code)) {
+ changeKeyboardMode();
}
break;
- case AUTO_MODE_SWITCH_STATE_SYMBOL:
+ case SWITCH_STATE_SYMBOL:
+ case SWITCH_STATE_CHORDING_SYMBOL:
// Snap back to alpha keyboard mode if user types one or more non-space/enter
- // characters followed by a space/enter.
- if (key == Keyboard.CODE_ENTER || key == Keyboard.CODE_SPACE) {
+ // characters followed by a space/enter or a quote character.
+ if (isSpaceCharacter(code) || isQuoteCharacter(code)) {
changeKeyboardMode();
}
break;
}
}
- public LatinKeyboardView getInputView() {
- return mInputView;
+ public LatinKeyboardView getKeyboardView() {
+ return mKeyboardView;
}
- public LatinKeyboardView onCreateInputView() {
- createInputViewInternal(mLayoutId, true);
- return mInputView;
+ public View onCreateInputView() {
+ return createInputView(mThemeIndex, true);
}
- private void createInputViewInternal(int newLayout, boolean forceReset) {
- int layoutId = newLayout;
- if (mLayoutId != layoutId || mInputView == null || forceReset) {
- if (mInputView != null) {
- mInputView.closing();
- }
- if (KEYBOARD_THEMES.length <= layoutId) {
- layoutId = Integer.valueOf(sConfigDefaultKeyboardThemeId);
- }
+ // Instance variable only for {@link #createInputView(int, boolean)}.
+ private View mCurrentInputView;
- Utils.GCUtils.getInstance().reset();
- boolean tryGC = true;
- for (int i = 0; i < Utils.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) {
- try {
- mInputView = (LatinKeyboardView) mInputMethodService.getLayoutInflater(
- ).inflate(KEYBOARD_THEMES[layoutId], null);
- tryGC = false;
- } catch (OutOfMemoryError e) {
- Log.w(TAG, "load keyboard failed: " + e);
- tryGC = Utils.GCUtils.getInstance().tryGCOrWait(
- mLayoutId + "," + layoutId, e);
- } catch (InflateException e) {
- Log.w(TAG, "load keyboard failed: " + e);
- tryGC = Utils.GCUtils.getInstance().tryGCOrWait(
- mLayoutId + "," + layoutId, e);
- }
+ private View createInputView(final int newThemeIndex, final boolean forceRecreate) {
+ if (mCurrentInputView != null && mThemeIndex == newThemeIndex && !forceRecreate)
+ return mCurrentInputView;
+
+ if (mKeyboardView != null) {
+ mKeyboardView.closing();
+ }
+ final int themeIndex = (newThemeIndex < KEYBOARD_THEMES.length) ? newThemeIndex
+ : Integer.valueOf(sConfigDefaultKeyboardThemeId);
+
+ Utils.GCUtils.getInstance().reset();
+ boolean tryGC = true;
+ for (int i = 0; i < Utils.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) {
+ try {
+ final Context themeContext = new ContextThemeWrapper(mInputMethodService,
+ KEYBOARD_THEMES[themeIndex]);
+ mCurrentInputView = LayoutInflater.from(themeContext).inflate(
+ R.layout.input_view, null);
+ tryGC = false;
+ } catch (OutOfMemoryError e) {
+ Log.w(TAG, "load keyboard failed: " + e);
+ tryGC = Utils.GCUtils.getInstance().tryGCOrWait(mThemeIndex + "," + themeIndex, e);
+ } catch (InflateException e) {
+ Log.w(TAG, "load keyboard failed: " + e);
+ tryGC = Utils.GCUtils.getInstance().tryGCOrWait(mThemeIndex + "," + themeIndex, e);
}
- mInputView.setOnKeyboardActionListener(mInputMethodService);
- mLayoutId = layoutId;
}
+
+ mKeyboardView = (LatinKeyboardView) mCurrentInputView.findViewById(
+ R.id.latin_keyboard_view);
+ mKeyboardView.setOnKeyboardActionListener(mInputMethodService);
+ mThemeIndex = themeIndex;
+ return mCurrentInputView;
}
- private void postSetInputView() {
+ private void postSetInputView(final View newInputView) {
mInputMethodService.mHandler.post(new Runnable() {
@Override
public void run() {
- if (mInputView != null) {
- mInputMethodService.setInputView(mInputView);
+ if (newInputView != null) {
+ mInputMethodService.setInputView(newInputView);
}
mInputMethodService.updateInputViewShown();
}
@@ -716,24 +769,22 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha
if (PREF_KEYBOARD_LAYOUT.equals(key)) {
final int layoutId = Integer.valueOf(
sharedPreferences.getString(key, sConfigDefaultKeyboardThemeId));
- createInputViewInternal(layoutId, false);
- postSetInputView();
+ postSetInputView(createInputView(layoutId, false));
} else if (Settings.PREF_SETTINGS_KEY.equals(key)) {
mSettingsKeyEnabledInSettings = getSettingsKeyMode(sharedPreferences,
mInputMethodService);
- createInputViewInternal(mLayoutId, true);
- postSetInputView();
+ postSetInputView(createInputView(mThemeIndex, true));
}
}
private int getColorScheme() {
- return (mInputView != null)
- ? mInputView.getColorScheme() : KeyboardView.COLOR_SCHEME_WHITE;
+ return (mKeyboardView != null)
+ ? mKeyboardView.getColorScheme() : KeyboardView.COLOR_SCHEME_WHITE;
}
public void onAutoCorrectionStateChanged(boolean isAutoCorrection) {
if (isAutoCorrection != mIsAutoCorrectionActive) {
- LatinKeyboardView keyboardView = getInputView();
+ LatinKeyboardView keyboardView = getKeyboardView();
mIsAutoCorrectionActive = isAutoCorrection;
keyboardView.invalidateKey(((LatinKeyboard) keyboardView.getKeyboard())
.onAutoCorrectionStateChanged(isAutoCorrection));
@@ -752,8 +803,7 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha
if (settingsKeyMode.equals(resources.getString(SETTINGS_KEY_MODE_ALWAYS_SHOW))
|| (settingsKeyMode.equals(resources.getString(SETTINGS_KEY_MODE_AUTO))
&& Utils.hasMultipleEnabledIMEsOrSubtypes(
- ((InputMethodManager) context.getSystemService(
- Context.INPUT_METHOD_SERVICE))))) {
+ (InputMethodManagerCompatWrapper.getInstance(context))))) {
return true;
}
return false;
diff --git a/java/src/com/android/inputmethod/keyboard/KeyboardView.java b/java/src/com/android/inputmethod/keyboard/KeyboardView.java
index 5736b1ef7..f8bce40b1 100644
--- a/java/src/com/android/inputmethod/keyboard/KeyboardView.java
+++ b/java/src/com/android/inputmethod/keyboard/KeyboardView.java
@@ -18,7 +18,6 @@ package com.android.inputmethod.keyboard;
import com.android.inputmethod.latin.LatinImeLogger;
import com.android.inputmethod.latin.R;
-import com.android.inputmethod.latin.SubtypeSwitcher;
import android.content.Context;
import android.content.pm.PackageManager;
@@ -36,17 +35,18 @@ import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
-import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.GestureDetector;
-import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
-import android.view.ViewGroup.LayoutParams;
-import android.view.WindowManager;
+import android.view.ViewConfiguration;
+import android.view.ViewGroup;
+import android.view.ViewGroup.MarginLayoutParams;
+import android.widget.FrameLayout;
+import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
@@ -58,21 +58,29 @@ import java.util.WeakHashMap;
* A view that renders a virtual {@link Keyboard}. It handles rendering of keys and detecting key
* presses and touch movements.
*
+ * @attr ref R.styleable#KeyboardView_backgroundDimAmount
+ * @attr ref R.styleable#KeyboardView_colorScheme
* @attr ref R.styleable#KeyboardView_keyBackground
+ * @attr ref R.styleable#KeyboardView_keyHysteresisDistance
+ * @attr ref R.styleable#KeyboardView_keyLetterRatio
+ * @attr ref R.styleable#KeyboardView_keyLetterStyle
* @attr ref R.styleable#KeyboardView_keyPreviewLayout
* @attr ref R.styleable#KeyboardView_keyPreviewOffset
- * @attr ref R.styleable#KeyboardView_labelTextSize
- * @attr ref R.styleable#KeyboardView_keyTextSize
+ * @attr ref R.styleable#KeyboardView_keyPreviewHeight
* @attr ref R.styleable#KeyboardView_keyTextColor
+ * @attr ref R.styleable#KeyboardView_keyTextColorDisabled
+ * @attr ref R.styleable#KeyboardView_labelTextRatio
* @attr ref R.styleable#KeyboardView_verticalCorrection
* @attr ref R.styleable#KeyboardView_popupLayout
+ * @attr ref R.styleable#KeyboardView_shadowColor
+ * @attr ref R.styleable#KeyboardView_shadowRadius
*/
public class KeyboardView extends View implements PointerTracker.UIProxy {
private static final String TAG = KeyboardView.class.getSimpleName();
private static final boolean DEBUG_SHOW_ALIGN = false;
private static final boolean DEBUG_KEYBOARD_GRID = false;
- private static final boolean ENABLE_CAPSLOCK_BY_LONGPRESS = false;
+ private static final boolean ENABLE_CAPSLOCK_BY_LONGPRESS = true;
private static final boolean ENABLE_CAPSLOCK_BY_DOUBLETAP = true;
public static final int COLOR_SCHEME_WHITE = 0;
@@ -86,53 +94,44 @@ public class KeyboardView extends View implements PointerTracker.UIProxy {
private static final int HINT_ICON_VERTICAL_ADJUSTMENT_PIXEL = -1;
// XML attribute
- private int mKeyLetterSize;
- private int mKeyTextColor;
- private int mKeyTextColorDisabled;
- private Typeface mKeyLetterStyle = Typeface.DEFAULT;
- private int mLabelTextSize;
- private int mColorScheme = COLOR_SCHEME_WHITE;
- private int mShadowColor;
- private float mShadowRadius;
- private Drawable mKeyBackground;
- private float mBackgroundDimAmount;
- private float mKeyHysteresisDistance;
- private float mVerticalCorrection;
- private int mPreviewOffset;
- private int mPreviewHeight;
- private int mPopupLayout;
+ private final float mKeyLetterRatio;
+ private final int mKeyTextColor;
+ private final int mKeyTextColorDisabled;
+ private final Typeface mKeyLetterStyle;
+ private final float mLabelTextRatio;
+ private final int mColorScheme;
+ private final int mShadowColor;
+ private final float mShadowRadius;
+ private final Drawable mKeyBackground;
+ private final float mBackgroundDimAmount;
+ private final float mKeyHysteresisDistance;
+ private final float mVerticalCorrection;
+ private final int mPreviewOffset;
+ private final int mPreviewHeight;
+ private final int mPopupLayout;
// Main keyboard
private Keyboard mKeyboard;
- private Key[] mKeys;
+ private int mKeyLetterSize;
+ private int mLabelTextSize;
- // Key preview popup
+ // Key preview
private boolean mInForeground;
private TextView mPreviewText;
- private PopupWindow mPreviewPopup;
- private int mPreviewTextSizeLarge;
- private int[] mOffsetInWindow;
- private int mOldPreviewKeyIndex = KeyDetector.NOT_A_KEY;
- private boolean mShowPreview = true;
- private int mPopupPreviewOffsetX;
- private int mPopupPreviewOffsetY;
- private int mWindowY;
- private int mPopupPreviewDisplayedY;
+ private float mPreviewTextRatio;
+ private int mPreviewTextSize;
+ private boolean mShowKeyPreviewPopup = true;
+ private int mKeyPreviewPopupDisplayedY = -1;
private final int mDelayBeforePreview;
- private final int mDelayAfterPreview;
-
- // Popup mini keyboard
- private PopupWindow mMiniKeyboardPopup;
- private KeyboardView mMiniKeyboardView;
- private View mMiniKeyboardParent;
- private final WeakHashMap<Key, View> mMiniKeyboardCache = new WeakHashMap<Key, View>();
- private int mMiniKeyboardOriginX;
- private int mMiniKeyboardOriginY;
- private long mMiniKeyboardPopupTime;
- private int[] mWindowOffset;
- private final float mMiniKeyboardSlideAllowance;
- private int mMiniKeyboardTrackerId;
- private final boolean mConfigShowMiniKeyboardAtTouchedPoint;
+ private int mDelayAfterPreview;
+ private ViewGroup mPreviewPlacer;
+ private final int[] mCoordinates = new int[2];
+
+ // Mini keyboard
+ private PopupWindow mPopupWindow;
+ private PopupPanel mPopupMiniKeyboardPanel;
+ private final WeakHashMap<Key, PopupPanel> mPopupPanelCache =
+ new WeakHashMap<Key, PopupPanel>();
/** Listener for {@link KeyboardActionListener}. */
private KeyboardActionListener mKeyboardActionListener;
@@ -144,14 +143,12 @@ public class KeyboardView extends View implements PointerTracker.UIProxy {
private final boolean mHasDistinctMultitouch;
private int mOldPointerCount = 1;
+ private int mOldKeyIndex;
- // Accessibility
- private boolean mIsAccessibilityEnabled;
-
- protected KeyDetector mKeyDetector = new ProximityKeyDetector();
+ protected KeyDetector mKeyDetector = new KeyDetector();
// Swipe gesture detector
- private GestureDetector mGestureDetector;
+ protected GestureDetector mGestureDetector;
private final SwipeTracker mSwipeTracker = new SwipeTracker();
private final int mSwipeThreshold;
private final boolean mDisambiguateSwipe;
@@ -188,65 +185,67 @@ public class KeyboardView extends View implements PointerTracker.UIProxy {
private final UIHandler mHandler = new UIHandler();
class UIHandler extends Handler {
- private static final int MSG_POPUP_PREVIEW = 1;
- private static final int MSG_DISMISS_PREVIEW = 2;
+ private static final int MSG_SHOW_KEY_PREVIEW = 1;
+ private static final int MSG_DISMISS_KEY_PREVIEW = 2;
private static final int MSG_REPEAT_KEY = 3;
private static final int MSG_LONGPRESS_KEY = 4;
private static final int MSG_LONGPRESS_SHIFT_KEY = 5;
+ private static final int MSG_IGNORE_DOUBLE_TAP = 6;
private boolean mInKeyRepeat;
@Override
public void handleMessage(Message msg) {
+ final PointerTracker tracker = (PointerTracker) msg.obj;
switch (msg.what) {
- case MSG_POPUP_PREVIEW:
- showKey(msg.arg1, (PointerTracker)msg.obj);
- break;
- case MSG_DISMISS_PREVIEW:
- mPreviewPopup.dismiss();
- break;
- case MSG_REPEAT_KEY: {
- final PointerTracker tracker = (PointerTracker)msg.obj;
- tracker.repeatKey(msg.arg1);
- startKeyRepeatTimer(mKeyRepeatInterval, msg.arg1, tracker);
- break;
- }
- case MSG_LONGPRESS_KEY: {
- final PointerTracker tracker = (PointerTracker)msg.obj;
- openPopupIfRequired(msg.arg1, tracker);
- break;
- }
- case MSG_LONGPRESS_SHIFT_KEY: {
- final PointerTracker tracker = (PointerTracker)msg.obj;
- onLongPressShiftKey(tracker);
- break;
- }
+ case MSG_SHOW_KEY_PREVIEW:
+ showKey(msg.arg1, tracker);
+ break;
+ case MSG_DISMISS_KEY_PREVIEW:
+ mPreviewText.setVisibility(View.INVISIBLE);
+ break;
+ case MSG_REPEAT_KEY:
+ tracker.onRepeatKey(msg.arg1);
+ startKeyRepeatTimer(mKeyRepeatInterval, msg.arg1, tracker);
+ break;
+ case MSG_LONGPRESS_KEY:
+ openMiniKeyboardIfRequired(msg.arg1, tracker);
+ break;
+ case MSG_LONGPRESS_SHIFT_KEY:
+ onLongPressShiftKey(tracker);
+ break;
}
}
- public void popupPreview(long delay, int keyIndex, PointerTracker tracker) {
- removeMessages(MSG_POPUP_PREVIEW);
- if (mPreviewPopup.isShowing() && mPreviewText.getVisibility() == VISIBLE) {
+ public void showKeyPreview(long delay, int keyIndex, PointerTracker tracker) {
+ removeMessages(MSG_SHOW_KEY_PREVIEW);
+ if (mPreviewText.getVisibility() == VISIBLE || delay == 0) {
// Show right away, if it's already visible and finger is moving around
showKey(keyIndex, tracker);
} else {
- sendMessageDelayed(obtainMessage(MSG_POPUP_PREVIEW, keyIndex, 0, tracker),
- delay);
+ sendMessageDelayed(
+ obtainMessage(MSG_SHOW_KEY_PREVIEW, keyIndex, 0, tracker), delay);
}
}
- public void cancelPopupPreview() {
- removeMessages(MSG_POPUP_PREVIEW);
+ public void cancelShowKeyPreview(PointerTracker tracker) {
+ removeMessages(MSG_SHOW_KEY_PREVIEW, tracker);
}
- public void dismissPreview(long delay) {
- if (mPreviewPopup.isShowing()) {
- sendMessageDelayed(obtainMessage(MSG_DISMISS_PREVIEW), delay);
- }
+ public void cancelAllShowKeyPreviews() {
+ removeMessages(MSG_SHOW_KEY_PREVIEW);
}
- public void cancelDismissPreview() {
- removeMessages(MSG_DISMISS_PREVIEW);
+ public void dismissKeyPreview(long delay, PointerTracker tracker) {
+ sendMessageDelayed(obtainMessage(MSG_DISMISS_KEY_PREVIEW, tracker), delay);
+ }
+
+ public void cancelDismissKeyPreview(PointerTracker tracker) {
+ removeMessages(MSG_DISMISS_KEY_PREVIEW, tracker);
+ }
+
+ public void cancelAllDismissKeyPreviews() {
+ removeMessages(MSG_DISMISS_KEY_PREVIEW);
}
public void startKeyRepeatTimer(long delay, int keyIndex, PointerTracker tracker) {
@@ -284,12 +283,22 @@ public class KeyboardView extends View implements PointerTracker.UIProxy {
public void cancelKeyTimers() {
cancelKeyRepeatTimer();
cancelLongPressTimers();
+ removeMessages(MSG_IGNORE_DOUBLE_TAP);
+ }
+
+ public void startIgnoringDoubleTap() {
+ sendMessageDelayed(obtainMessage(MSG_IGNORE_DOUBLE_TAP),
+ ViewConfiguration.getDoubleTapTimeout());
+ }
+
+ public boolean isIgnoringDoubleTap() {
+ return hasMessages(MSG_IGNORE_DOUBLE_TAP);
}
public void cancelAllMessages() {
cancelKeyTimers();
- cancelPopupPreview();
- cancelDismissPreview();
+ cancelAllShowKeyPreviews();
+ cancelAllDismissKeyPreviews();
}
}
@@ -302,95 +311,44 @@ public class KeyboardView extends View implements PointerTracker.UIProxy {
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.KeyboardView, defStyle, R.style.KeyboardView);
- int previewLayout = 0;
- int keyTextSize = 0;
-
- int n = a.getIndexCount();
- for (int i = 0; i < n; i++) {
- int attr = a.getIndex(i);
-
- switch (attr) {
- case R.styleable.KeyboardView_keyBackground:
- mKeyBackground = a.getDrawable(attr);
- break;
- case R.styleable.KeyboardView_keyHysteresisDistance:
- mKeyHysteresisDistance = a.getDimensionPixelOffset(attr, 0);
- break;
- case R.styleable.KeyboardView_verticalCorrection:
- mVerticalCorrection = a.getDimensionPixelOffset(attr, 0);
- break;
- case R.styleable.KeyboardView_keyPreviewLayout:
- previewLayout = a.getResourceId(attr, 0);
- break;
- case R.styleable.KeyboardView_keyPreviewOffset:
- mPreviewOffset = a.getDimensionPixelOffset(attr, 0);
- break;
- case R.styleable.KeyboardView_keyPreviewHeight:
- mPreviewHeight = a.getDimensionPixelSize(attr, 80);
- break;
- case R.styleable.KeyboardView_keyLetterSize:
- mKeyLetterSize = a.getDimensionPixelSize(attr, 18);
- break;
- case R.styleable.KeyboardView_keyTextColor:
- mKeyTextColor = a.getColor(attr, 0xFF000000);
- break;
- case R.styleable.KeyboardView_keyTextColorDisabled:
- mKeyTextColorDisabled = a.getColor(attr, 0xFF000000);
- break;
- case R.styleable.KeyboardView_labelTextSize:
- mLabelTextSize = a.getDimensionPixelSize(attr, 14);
- break;
- case R.styleable.KeyboardView_popupLayout:
- mPopupLayout = a.getResourceId(attr, 0);
- break;
- case R.styleable.KeyboardView_shadowColor:
- mShadowColor = a.getColor(attr, 0);
- break;
- case R.styleable.KeyboardView_shadowRadius:
- mShadowRadius = a.getFloat(attr, 0f);
- break;
- // TODO: Use Theme (android.R.styleable.Theme_backgroundDimAmount)
- case R.styleable.KeyboardView_backgroundDimAmount:
- mBackgroundDimAmount = a.getFloat(attr, 0.5f);
- break;
- case R.styleable.KeyboardView_keyLetterStyle:
- mKeyLetterStyle = Typeface.defaultFromStyle(a.getInt(attr, Typeface.NORMAL));
- break;
- case R.styleable.KeyboardView_colorScheme:
- mColorScheme = a.getInt(attr, COLOR_SCHEME_WHITE);
- break;
- }
- }
+ mKeyBackground = a.getDrawable(R.styleable.KeyboardView_keyBackground);
+ mKeyHysteresisDistance = a.getDimensionPixelOffset(
+ R.styleable.KeyboardView_keyHysteresisDistance, 0);
+ mVerticalCorrection = a.getDimensionPixelOffset(
+ R.styleable.KeyboardView_verticalCorrection, 0);
+ final int previewLayout = a.getResourceId(R.styleable.KeyboardView_keyPreviewLayout, 0);
+ mPreviewOffset = a.getDimensionPixelOffset(R.styleable.KeyboardView_keyPreviewOffset, 0);
+ mPreviewHeight = a.getDimensionPixelSize(R.styleable.KeyboardView_keyPreviewHeight, 80);
+ mKeyLetterRatio = getRatio(a, R.styleable.KeyboardView_keyLetterRatio);
+ mKeyTextColor = a.getColor(R.styleable.KeyboardView_keyTextColor, 0xFF000000);
+ mKeyTextColorDisabled = a.getColor(
+ R.styleable.KeyboardView_keyTextColorDisabled, 0xFF000000);
+ mLabelTextRatio = getRatio(a, R.styleable.KeyboardView_labelTextRatio);
+ mPopupLayout = a.getResourceId(R.styleable.KeyboardView_popupLayout, 0);
+ mShadowColor = a.getColor(R.styleable.KeyboardView_shadowColor, 0);
+ mShadowRadius = a.getFloat(R.styleable.KeyboardView_shadowRadius, 0f);
+ // TODO: Use Theme (android.R.styleable.Theme_backgroundDimAmount)
+ mBackgroundDimAmount = a.getFloat(R.styleable.KeyboardView_backgroundDimAmount, 0.5f);
+ mKeyLetterStyle = Typeface.defaultFromStyle(
+ a.getInt(R.styleable.KeyboardView_keyLetterStyle, Typeface.NORMAL));
+ mColorScheme = a.getInt(R.styleable.KeyboardView_colorScheme, COLOR_SCHEME_WHITE);
final Resources res = getResources();
- mPreviewPopup = new PopupWindow(context);
if (previewLayout != 0) {
mPreviewText = (TextView) LayoutInflater.from(context).inflate(previewLayout, null);
- mPreviewTextSizeLarge = (int) res.getDimension(R.dimen.key_preview_text_size_large);
- mPreviewPopup.setContentView(mPreviewText);
- mPreviewPopup.setBackgroundDrawable(null);
+ mPreviewTextRatio = getRatio(res, R.fraction.key_preview_text_ratio);
} else {
- mShowPreview = false;
+ mShowKeyPreviewPopup = false;
}
- mPreviewPopup.setTouchable(false);
- mPreviewPopup.setAnimationStyle(R.style.KeyPreviewAnimation);
mDelayBeforePreview = res.getInteger(R.integer.config_delay_before_preview);
mDelayAfterPreview = res.getInteger(R.integer.config_delay_after_preview);
mKeyLabelHorizontalPadding = (int)res.getDimension(
R.dimen.key_label_horizontal_alignment_padding);
- mMiniKeyboardParent = this;
- mMiniKeyboardPopup = new PopupWindow(context);
- mMiniKeyboardPopup.setBackgroundDrawable(null);
- mMiniKeyboardPopup.setAnimationStyle(R.style.MiniKeyboardAnimation);
- // Allow popup window to be drawn off the screen.
- mMiniKeyboardPopup.setClippingEnabled(false);
-
mPaint = new Paint();
mPaint.setAntiAlias(true);
- mPaint.setTextSize(keyTextSize);
mPaint.setTextAlign(Align.CENTER);
mPaint.setAlpha(255);
@@ -398,11 +356,8 @@ public class KeyboardView extends View implements PointerTracker.UIProxy {
mKeyBackground.getPadding(mPadding);
mSwipeThreshold = (int) (500 * res.getDisplayMetrics().density);
- // TODO: Refer frameworks/base/core/res/res/values/config.xml
+ // TODO: Refer to frameworks/base/core/res/res/values/config.xml
mDisambiguateSwipe = res.getBoolean(R.bool.config_swipeDisambiguation);
- mMiniKeyboardSlideAllowance = res.getDimension(R.dimen.mini_keyboard_slide_allowance);
- mConfigShowMiniKeyboardAtTouchedPoint = res.getBoolean(
- R.bool.config_show_mini_keyboard_at_touched_point);
GestureDetector.SimpleOnGestureListener listener =
new GestureDetector.SimpleOnGestureListener() {
@@ -453,7 +408,12 @@ public class KeyboardView extends View implements PointerTracker.UIProxy {
final PointerTracker tracker = getPointerTracker(id);
// If the second down event is also on shift key.
if (tracker.isOnShiftKey((int)secondDown.getX(), (int)secondDown.getY())) {
- onDoubleTapShiftKey(tracker);
+ // Detected a double tap on shift key. If we are in the ignoring double tap
+ // mode, it means we have already turned off caps lock in
+ // {@link KeyboardSwitcher#onReleaseShift} .
+ final boolean ignoringDoubleTap = mHandler.isIgnoringDoubleTap();
+ if (!ignoringDoubleTap)
+ onDoubleTapShiftKey(tracker);
return true;
}
// Otherwise these events should not be handled as double tap.
@@ -472,6 +432,21 @@ public class KeyboardView extends View implements PointerTracker.UIProxy {
mKeyRepeatInterval = res.getInteger(R.integer.config_key_repeat_interval);
}
+ // Read fraction value in TypedArray as float.
+ private static float getRatio(TypedArray a, int index) {
+ return a.getFraction(index, 1000, 1000, 1) / 1000.0f;
+ }
+
+ // Read fraction value in resource as float.
+ private static float getRatio(Resources res, int id) {
+ return res.getFraction(id, 1000, 1000) / 1000.0f;
+ }
+
+ public void startIgnoringDoubleTap() {
+ if (ENABLE_CAPSLOCK_BY_DOUBLETAP)
+ mHandler.startIgnoringDoubleTap();
+ }
+
public void setOnKeyboardActionListener(KeyboardActionListener listener) {
mKeyboardActionListener = listener;
for (PointerTracker tracker : mPointerTrackers) {
@@ -487,6 +462,12 @@ public class KeyboardView extends View implements PointerTracker.UIProxy {
return mKeyboardActionListener;
}
+ @Override
+ protected void onSizeChanged(int w, int h, int oldw, int oldh) {
+ // TODO: Should notify InputMethodService instead?
+ KeyboardSwitcher.getInstance().onSizeChanged();
+ }
+
/**
* Attaches a keyboard to this view. The keyboard can be switched at any time and the
* view will re-layout itself to accommodate the keyboard.
@@ -496,23 +477,27 @@ public class KeyboardView extends View implements PointerTracker.UIProxy {
*/
public void setKeyboard(Keyboard keyboard) {
if (mKeyboard != null) {
- dismissKeyPreview();
+ dismissAllKeyPreviews();
}
// Remove any pending messages, except dismissing preview
mHandler.cancelKeyTimers();
- mHandler.cancelPopupPreview();
+ mHandler.cancelAllShowKeyPreviews();
mKeyboard = keyboard;
LatinImeLogger.onSetKeyboard(keyboard);
- mKeys = mKeyDetector.setKeyboard(keyboard, -getPaddingLeft(),
+ mKeyDetector.setKeyboard(keyboard, -getPaddingLeft(),
-getPaddingTop() + mVerticalCorrection);
for (PointerTracker tracker : mPointerTrackers) {
- tracker.setKeyboard(keyboard, mKeys, mKeyHysteresisDistance);
+ tracker.setKeyboard(keyboard, mKeyHysteresisDistance);
}
requestLayout();
mKeyboardChanged = true;
invalidateAllKeys();
- mKeyDetector.setProximityThreshold(KeyDetector.getMostCommonKeyWidth(keyboard));
- mMiniKeyboardCache.clear();
+ mKeyDetector.setProximityThreshold(keyboard.getMostCommonKeyWidth());
+ mPopupPanelCache.clear();
+ final int keyHeight = keyboard.getRowHeight() - keyboard.getVerticalGap();
+ mKeyLetterSize = (int)(keyHeight * mKeyLetterRatio);
+ mLabelTextSize = (int)(keyHeight * mLabelTextRatio);
+ mPreviewTextSize = (int)(keyHeight * mPreviewTextRatio);
}
/**
@@ -534,56 +519,30 @@ public class KeyboardView extends View implements PointerTracker.UIProxy {
}
/**
- * Enables or disables accessibility.
- * @param accessibilityEnabled whether or not to enable accessibility
- */
- public void setAccessibilityEnabled(boolean accessibilityEnabled) {
- mIsAccessibilityEnabled = accessibilityEnabled;
-
- // Propagate this change to all existing pointer trackers.
- for (PointerTracker tracker : mPointerTrackers) {
- tracker.setAccessibilityEnabled(accessibilityEnabled);
- }
- }
-
- /**
- * Returns whether the device has accessibility enabled.
- * @return true if the device has accessibility enabled.
- */
- @Override
- public boolean isAccessibilityEnabled() {
- return mIsAccessibilityEnabled;
- }
-
- /**
* Enables or disables the key feedback popup. This is a popup that shows a magnified
* version of the depressed key. By default the preview is enabled.
- * @param previewEnabled whether or not to enable the key feedback popup
- * @see #isPreviewEnabled()
+ * @param previewEnabled whether or not to enable the key feedback preview
+ * @param delay the delay after which the preview is dismissed
+ * @see #isKeyPreviewPopupEnabled()
*/
- public void setPreviewEnabled(boolean previewEnabled) {
- mShowPreview = previewEnabled;
+ public void setKeyPreviewPopupEnabled(boolean previewEnabled, int delay) {
+ mShowKeyPreviewPopup = previewEnabled;
+ mDelayAfterPreview = delay;
}
/**
- * Returns the enabled state of the key feedback popup.
- * @return whether or not the key feedback popup is enabled
- * @see #setPreviewEnabled(boolean)
+ * Returns the enabled state of the key feedback preview
+ * @return whether or not the key feedback preview is enabled
+ * @see #setKeyPreviewPopupEnabled(boolean, int)
*/
- public boolean isPreviewEnabled() {
- return mShowPreview;
+ public boolean isKeyPreviewPopupEnabled() {
+ return mShowKeyPreviewPopup;
}
public int getColorScheme() {
return mColorScheme;
}
- public void setPopupOffset(int x, int y) {
- mPopupPreviewOffsetX = x;
- mPopupPreviewOffsetY = y;
- mPreviewPopup.dismiss();
- }
-
/**
* When enabled, calls to {@link KeyboardActionListener#onCodeInput} will include key
* codes for adjacent keys. When disabled, only the primary key code will be
@@ -649,152 +608,32 @@ public class KeyboardView extends View implements PointerTracker.UIProxy {
}
final Canvas canvas = mCanvas;
canvas.clipRect(mDirtyRect, Op.REPLACE);
+ canvas.drawColor(Color.BLACK, PorterDuff.Mode.CLEAR);
if (mKeyboard == null) return;
- final Paint paint = mPaint;
- final Drawable keyBackground = mKeyBackground;
- final Rect padding = mPadding;
- final int kbdPaddingLeft = getPaddingLeft();
- final int kbdPaddingTop = getPaddingTop();
- final Key[] keys = mKeys;
- final boolean isManualTemporaryUpperCase = mKeyboard.isManualTemporaryUpperCase();
- final boolean drawSingleKey = (mInvalidatedKey != null
- && mInvalidatedKeyRect.contains(mDirtyRect));
-
- canvas.drawColor(0x00000000, PorterDuff.Mode.CLEAR);
- final int keyCount = keys.length;
- for (int i = 0; i < keyCount; i++) {
- final Key key = keys[i];
- if (drawSingleKey && key != mInvalidatedKey) {
- continue;
- }
- int[] drawableState = key.getCurrentDrawableState();
- keyBackground.setState(drawableState);
-
- // Switch the character to uppercase if shift is pressed
- String label = key.mLabel == null? null : adjustCase(key.mLabel).toString();
-
- final Rect bounds = keyBackground.getBounds();
- if (key.mWidth != bounds.right || key.mHeight != bounds.bottom) {
- keyBackground.setBounds(0, 0, key.mWidth, key.mHeight);
- }
- canvas.translate(key.mX + kbdPaddingLeft, key.mY + kbdPaddingTop);
- keyBackground.draw(canvas);
-
- final int rowHeight = padding.top + key.mHeight;
- // Draw key label
- if (label != null) {
- // For characters, use large font. For labels like "Done", use small font.
- final int labelSize = getLabelSizeAndSetPaint(label, key.mLabelOption, paint);
- final int labelCharHeight = getLabelCharHeight(labelSize, paint);
-
- // Vertical label text alignment.
- final float baseline;
- if ((key.mLabelOption & KEY_LABEL_OPTION_ALIGN_BOTTOM) != 0) {
- baseline = key.mHeight -
- + labelCharHeight * KEY_LABEL_VERTICAL_PADDING_FACTOR;
- if (DEBUG_SHOW_ALIGN)
- drawHorizontalLine(canvas, (int)baseline, key.mWidth, 0xc0008000,
- new Paint());
- } else { // Align center
- final float centerY = (key.mHeight + padding.top - padding.bottom) / 2;
- baseline = centerY
- + labelCharHeight * KEY_LABEL_VERTICAL_ADJUSTMENT_FACTOR_CENTER;
- if (DEBUG_SHOW_ALIGN)
- drawHorizontalLine(canvas, (int)baseline, key.mWidth, 0xc0008000,
- new Paint());
- }
- // Horizontal label text alignment
- final int positionX;
- if ((key.mLabelOption & KEY_LABEL_OPTION_ALIGN_LEFT) != 0) {
- positionX = mKeyLabelHorizontalPadding + padding.left;
- paint.setTextAlign(Align.LEFT);
- if (DEBUG_SHOW_ALIGN)
- drawVerticalLine(canvas, positionX, rowHeight, 0xc0800080, new Paint());
- } else if ((key.mLabelOption & KEY_LABEL_OPTION_ALIGN_RIGHT) != 0) {
- positionX = key.mWidth - mKeyLabelHorizontalPadding - padding.right;
- paint.setTextAlign(Align.RIGHT);
- if (DEBUG_SHOW_ALIGN)
- drawVerticalLine(canvas, positionX, rowHeight, 0xc0808000, new Paint());
- } else {
- positionX = (key.mWidth + padding.left - padding.right) / 2;
- paint.setTextAlign(Align.CENTER);
- if (DEBUG_SHOW_ALIGN) {
- if (label.length() > 1)
- drawVerticalLine(canvas, positionX, rowHeight, 0xc0008080, new Paint());
- }
- }
- if (key.mManualTemporaryUpperCaseHintIcon != null && isManualTemporaryUpperCase) {
- paint.setColor(mKeyTextColorDisabled);
- } else {
- paint.setColor(mKeyTextColor);
- }
- if (key.mEnabled) {
- // Set a drop shadow for the text
- paint.setShadowLayer(mShadowRadius, 0, 0, mShadowColor);
- } else {
- // Make label invisible
- paint.setColor(Color.TRANSPARENT);
- }
- canvas.drawText(label, positionX, baseline, paint);
- // Turn off drop shadow
- paint.setShadowLayer(0, 0, 0, 0);
- }
- // Draw key icon
- final Drawable icon = key.getIcon();
- if (key.mLabel == null && icon != null) {
- final int drawableWidth = icon.getIntrinsicWidth();
- final int drawableHeight = icon.getIntrinsicHeight();
- final int drawableX;
- final int drawableY = (
- key.mHeight + padding.top - padding.bottom - drawableHeight) / 2;
- if ((key.mLabelOption & KEY_LABEL_OPTION_ALIGN_LEFT) != 0) {
- drawableX = padding.left + mKeyLabelHorizontalPadding;
- if (DEBUG_SHOW_ALIGN)
- drawVerticalLine(canvas, drawableX, rowHeight, 0xc0800080, new Paint());
- } else if ((key.mLabelOption & KEY_LABEL_OPTION_ALIGN_RIGHT) != 0) {
- drawableX = key.mWidth - padding.right - mKeyLabelHorizontalPadding
- - drawableWidth;
- if (DEBUG_SHOW_ALIGN)
- drawVerticalLine(canvas, drawableX + drawableWidth, rowHeight,
- 0xc0808000, new Paint());
- } else { // Align center
- drawableX = (key.mWidth + padding.left - padding.right - drawableWidth) / 2;
- if (DEBUG_SHOW_ALIGN)
- drawVerticalLine(canvas, drawableX + drawableWidth / 2, rowHeight,
- 0xc0008080, new Paint());
- }
- drawIcon(canvas, icon, drawableX, drawableY, drawableWidth, drawableHeight);
- if (DEBUG_SHOW_ALIGN)
- drawRectangle(canvas, drawableX, drawableY, drawableWidth, drawableHeight,
- 0x80c00000, new Paint());
- }
- if (key.mHintIcon != null) {
- final int drawableWidth = key.mWidth;
- final int drawableHeight = key.mHeight;
- final int drawableX = 0;
- final int drawableY = HINT_ICON_VERTICAL_ADJUSTMENT_PIXEL;
- Drawable hintIcon = (isManualTemporaryUpperCase
- && key.mManualTemporaryUpperCaseHintIcon != null)
- ? key.mManualTemporaryUpperCaseHintIcon : key.mHintIcon;
- drawIcon(canvas, hintIcon, drawableX, drawableY, drawableWidth, drawableHeight);
- if (DEBUG_SHOW_ALIGN)
- drawRectangle(canvas, drawableX, drawableY, drawableWidth, drawableHeight,
- 0x80c0c000, new Paint());
+ if (mInvalidatedKey != null && mInvalidatedKeyRect.contains(mDirtyRect)) {
+ // Draw a single key.
+ onBufferDrawKey(canvas, mInvalidatedKey);
+ } else {
+ // Draw all keys.
+ for (final Key key : mKeyboard.getKeys()) {
+ onBufferDrawKey(canvas, key);
}
- canvas.translate(-key.mX - kbdPaddingLeft, -key.mY - kbdPaddingTop);
}
- // TODO: Move this function to ProximityInfo for getting rid of public declarations for
+ // TODO: Move this function to ProximityInfo for getting rid of
+ // public declarations for
// GRID_WIDTH and GRID_HEIGHT
if (DEBUG_KEYBOARD_GRID) {
Paint p = new Paint();
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth(1.0f);
p.setColor(0x800000c0);
- int cw = (mKeyboard.getMinWidth() + mKeyboard.GRID_WIDTH - 1) / mKeyboard.GRID_WIDTH;
- int ch = (mKeyboard.getHeight() + mKeyboard.GRID_HEIGHT - 1) / mKeyboard.GRID_HEIGHT;
+ int cw = (mKeyboard.getMinWidth() + mKeyboard.GRID_WIDTH - 1)
+ / mKeyboard.GRID_WIDTH;
+ int ch = (mKeyboard.getHeight() + mKeyboard.GRID_HEIGHT - 1)
+ / mKeyboard.GRID_HEIGHT;
for (int i = 0; i <= mKeyboard.GRID_WIDTH; i++)
canvas.drawLine(i * cw, 0, i * cw, ch * mKeyboard.GRID_HEIGHT, p);
for (int i = 0; i <= mKeyboard.GRID_HEIGHT; i++)
@@ -802,9 +641,9 @@ public class KeyboardView extends View implements PointerTracker.UIProxy {
}
// Overlay a dark rectangle to dim the keyboard
- if (mMiniKeyboardView != null) {
- paint.setColor((int) (mBackgroundDimAmount * 0xFF) << 24);
- canvas.drawRect(0, 0, width, height, paint);
+ if (mPopupMiniKeyboardPanel != null) {
+ mPaint.setColor((int) (mBackgroundDimAmount * 0xFF) << 24);
+ canvas.drawRect(0, 0, width, height, mPaint);
}
mInvalidatedKey = null;
@@ -812,6 +651,134 @@ public class KeyboardView extends View implements PointerTracker.UIProxy {
mDirtyRect.setEmpty();
}
+ private void onBufferDrawKey(final Canvas canvas, final Key key) {
+ final Paint paint = mPaint;
+ final Drawable keyBackground = mKeyBackground;
+ final Rect padding = mPadding;
+ final int kbdPaddingLeft = getPaddingLeft();
+ final int kbdPaddingTop = getPaddingTop();
+ final int keyDrawX = key.mX + key.mVisualInsetsLeft;
+ final int keyDrawWidth = key.mWidth - key.mVisualInsetsLeft - key.mVisualInsetsRight;
+ final int rowHeight = padding.top + key.mHeight;
+ final boolean isManualTemporaryUpperCase = mKeyboard.isManualTemporaryUpperCase();
+
+ canvas.translate(keyDrawX + kbdPaddingLeft, key.mY + kbdPaddingTop);
+
+ // Draw key background.
+ final int[] drawableState = key.getCurrentDrawableState();
+ keyBackground.setState(drawableState);
+ final Rect bounds = keyBackground.getBounds();
+ if (keyDrawWidth != bounds.right || key.mHeight != bounds.bottom) {
+ keyBackground.setBounds(0, 0, keyDrawWidth, key.mHeight);
+ }
+ keyBackground.draw(canvas);
+
+ // Draw key label.
+ if (key.mLabel != null) {
+ // Switch the character to uppercase if shift is pressed
+ final String label = key.mLabel == null ? null : adjustCase(key.mLabel).toString();
+ // For characters, use large font. For labels like "Done", use small font.
+ final int labelSize = getLabelSizeAndSetPaint(label, key.mLabelOption, paint);
+ final int labelCharHeight = getLabelCharHeight(labelSize, paint);
+
+ // Vertical label text alignment.
+ final float baseline;
+ if ((key.mLabelOption & KEY_LABEL_OPTION_ALIGN_BOTTOM) != 0) {
+ baseline = key.mHeight - labelCharHeight * KEY_LABEL_VERTICAL_PADDING_FACTOR;
+ if (DEBUG_SHOW_ALIGN)
+ drawHorizontalLine(canvas, (int)baseline, keyDrawWidth, 0xc0008000,
+ new Paint());
+ } else { // Align center
+ final float centerY = (key.mHeight + padding.top - padding.bottom) / 2;
+ baseline = centerY + labelCharHeight * KEY_LABEL_VERTICAL_ADJUSTMENT_FACTOR_CENTER;
+ if (DEBUG_SHOW_ALIGN)
+ drawHorizontalLine(canvas, (int)baseline, keyDrawWidth, 0xc0008000,
+ new Paint());
+ }
+ // Horizontal label text alignment
+ final int positionX;
+ if ((key.mLabelOption & KEY_LABEL_OPTION_ALIGN_LEFT) != 0) {
+ positionX = mKeyLabelHorizontalPadding + padding.left;
+ paint.setTextAlign(Align.LEFT);
+ if (DEBUG_SHOW_ALIGN)
+ drawVerticalLine(canvas, positionX, rowHeight, 0xc0800080, new Paint());
+ } else if ((key.mLabelOption & KEY_LABEL_OPTION_ALIGN_RIGHT) != 0) {
+ positionX = keyDrawWidth - mKeyLabelHorizontalPadding - padding.right;
+ paint.setTextAlign(Align.RIGHT);
+ if (DEBUG_SHOW_ALIGN)
+ drawVerticalLine(canvas, positionX, rowHeight, 0xc0808000, new Paint());
+ } else {
+ positionX = (keyDrawWidth + padding.left - padding.right) / 2;
+ paint.setTextAlign(Align.CENTER);
+ if (DEBUG_SHOW_ALIGN) {
+ if (label.length() > 1)
+ drawVerticalLine(canvas, positionX, rowHeight, 0xc0008080, new Paint());
+ }
+ }
+ if (key.mManualTemporaryUpperCaseHintIcon != null && isManualTemporaryUpperCase) {
+ paint.setColor(mKeyTextColorDisabled);
+ } else {
+ paint.setColor(mKeyTextColor);
+ }
+ if (key.mEnabled) {
+ // Set a drop shadow for the text
+ paint.setShadowLayer(mShadowRadius, 0, 0, mShadowColor);
+ } else {
+ // Make label invisible
+ paint.setColor(Color.TRANSPARENT);
+ }
+ canvas.drawText(label, positionX, baseline, paint);
+ // Turn off drop shadow
+ paint.setShadowLayer(0, 0, 0, 0);
+ }
+
+ // Draw key icon.
+ final Drawable icon = key.getIcon();
+ if (key.mLabel == null && icon != null) {
+ final int drawableWidth = icon.getIntrinsicWidth();
+ final int drawableHeight = icon.getIntrinsicHeight();
+ final int drawableX;
+ final int drawableY = (key.mHeight + padding.top - padding.bottom - drawableHeight) / 2;
+ if ((key.mLabelOption & KEY_LABEL_OPTION_ALIGN_LEFT) != 0) {
+ drawableX = padding.left + mKeyLabelHorizontalPadding;
+ if (DEBUG_SHOW_ALIGN)
+ drawVerticalLine(canvas, drawableX, rowHeight, 0xc0800080, new Paint());
+ } else if ((key.mLabelOption & KEY_LABEL_OPTION_ALIGN_RIGHT) != 0) {
+ drawableX = keyDrawWidth - padding.right - mKeyLabelHorizontalPadding
+ - drawableWidth;
+ if (DEBUG_SHOW_ALIGN)
+ drawVerticalLine(canvas, drawableX + drawableWidth, rowHeight,
+ 0xc0808000, new Paint());
+ } else { // Align center
+ drawableX = (keyDrawWidth + padding.left - padding.right - drawableWidth) / 2;
+ if (DEBUG_SHOW_ALIGN)
+ drawVerticalLine(canvas, drawableX + drawableWidth / 2, rowHeight,
+ 0xc0008080, new Paint());
+ }
+ drawIcon(canvas, icon, drawableX, drawableY, drawableWidth, drawableHeight);
+ if (DEBUG_SHOW_ALIGN)
+ drawRectangle(canvas, drawableX, drawableY, drawableWidth, drawableHeight,
+ 0x80c00000, new Paint());
+ }
+
+ // Draw hint icon.
+ if (key.mHintIcon != null) {
+ final int drawableWidth = keyDrawWidth;
+ final int drawableHeight = key.mHeight;
+ final int drawableX = 0;
+ final int drawableY = HINT_ICON_VERTICAL_ADJUSTMENT_PIXEL;
+ Drawable hintIcon = (isManualTemporaryUpperCase
+ && key.mManualTemporaryUpperCaseHintIcon != null)
+ ? key.mManualTemporaryUpperCaseHintIcon : key.mHintIcon;
+ drawIcon(canvas, hintIcon, drawableX, drawableY, drawableWidth, drawableHeight);
+ if (DEBUG_SHOW_ALIGN)
+ drawRectangle(canvas, drawableX, drawableY, drawableWidth, drawableHeight,
+ 0x80c0c000, new Paint());
+ }
+
+ canvas.translate(-keyDrawX - kbdPaddingLeft, -key.mY - kbdPaddingTop);
+ }
+
public int getLabelSizeAndSetPaint(CharSequence label, int keyLabelOption, Paint paint) {
// For characters, use large font. For labels like "Done", use small font.
final int labelSize;
@@ -883,118 +850,121 @@ public class KeyboardView extends View implements PointerTracker.UIProxy {
}
// TODO: clean up this method.
- private void dismissKeyPreview() {
- for (PointerTracker tracker : mPointerTrackers)
- tracker.releaseKey();
- showPreview(KeyDetector.NOT_A_KEY, null);
+ private void dismissAllKeyPreviews() {
+ for (PointerTracker tracker : mPointerTrackers) {
+ tracker.setReleasedKeyGraphics();
+ dismissKeyPreview(tracker);
+ }
}
@Override
- public void showPreview(int keyIndex, PointerTracker tracker) {
- int oldKeyIndex = mOldPreviewKeyIndex;
- mOldPreviewKeyIndex = keyIndex;
- // We should re-draw popup preview when 1) we need to hide the preview, 2) we will show
- // the space key preview and 3) pointer moves off the space key to other letter key, we
- // should hide the preview of the previous key.
- final boolean hidePreviewOrShowSpaceKeyPreview = (tracker == null)
- || (SubtypeSwitcher.getInstance().useSpacebarLanguageSwitcher()
- && SubtypeSwitcher.getInstance().needsToDisplayLanguage()
- && (tracker.isSpaceKey(keyIndex) || tracker.isSpaceKey(oldKeyIndex)));
- // If key changed and preview is on or the key is space (language switch is enabled)
- if (oldKeyIndex != keyIndex && (mShowPreview || (hidePreviewOrShowSpaceKeyPreview))) {
- if (keyIndex == KeyDetector.NOT_A_KEY) {
- mHandler.cancelPopupPreview();
- mHandler.dismissPreview(mDelayAfterPreview);
- } else if (tracker != null) {
- mHandler.popupPreview(mDelayBeforePreview, keyIndex, tracker);
+ public void showKeyPreview(int keyIndex, PointerTracker tracker) {
+ if (mShowKeyPreviewPopup) {
+ mHandler.showKeyPreview(mDelayBeforePreview, keyIndex, tracker);
+ } else if (mKeyboard.needSpacebarPreview(keyIndex)) {
+ // Show key preview (in this case, slide language switcher) without any delay.
+ showKey(keyIndex, tracker);
+ }
+ }
+
+ @Override
+ public void dismissKeyPreview(PointerTracker tracker) {
+ if (mShowKeyPreviewPopup) {
+ mHandler.cancelShowKeyPreview(tracker);
+ mHandler.dismissKeyPreview(mDelayAfterPreview, tracker);
+ } else if (mKeyboard.needSpacebarPreview(KeyDetector.NOT_A_KEY)) {
+ // Dismiss key preview (in this case, slide language switcher) without any delay.
+ mPreviewText.setVisibility(View.INVISIBLE);
+ }
+ // Clear key preview display position.
+ mKeyPreviewPopupDisplayedY = -1;
+ }
+
+ private void addKeyPreview(TextView keyPreview) {
+ ViewGroup placer = mPreviewPlacer;
+ if (placer == null) {
+ final FrameLayout screenContent = (FrameLayout) getRootView().findViewById(
+ android.R.id.content);
+ if (android.os.Build.VERSION.SDK_INT >= /* HONEYCOMB */11) {
+ placer = screenContent;
+ } else {
+ // Insert LinearLayout to be able to setMargin because pre-Honeycomb FrameLayout
+ // could not handle setMargin properly.
+ placer = new LinearLayout(getContext());
+ screenContent.addView(placer);
}
+ mPreviewPlacer = placer;
+ }
+ if (placer instanceof FrameLayout) {
+ // Honeycomb or later.
+ placer.addView(keyPreview, new FrameLayout.LayoutParams(0, 0));
+ } else {
+ // Gingerbread or ealier.
+ placer.addView(keyPreview, new LinearLayout.LayoutParams(0, 0));
}
}
- // TODO Must fix popup preview on xlarge layout
+ // TODO: Introduce minimum duration for displaying key previews
+ // TODO: Display up to two key previews when the user presses two keys at the same time
private void showKey(final int keyIndex, PointerTracker tracker) {
- Key key = tracker.getKey(keyIndex);
+ final TextView previewText = mPreviewText;
+ // If the key preview has no parent view yet, add it to the ViewGroup which can place
+ // key preview absolutely in SoftInputWindow.
+ if (previewText.getParent() == null) {
+ addKeyPreview(previewText);
+ }
+
+ final Key key = tracker.getKey(keyIndex);
// If keyIndex is invalid or IME is already closed, we must not show key preview.
- // Trying to show preview PopupWindow while root window is closed causes
+ // Trying to show key preview while root window is closed causes
// WindowManager.BadTokenException.
if (key == null || !mInForeground)
return;
+
+ mHandler.cancelAllDismissKeyPreviews();
+
+ final int keyDrawX = key.mX + key.mVisualInsetsLeft;
+ final int keyDrawWidth = key.mWidth - key.mVisualInsetsLeft - key.mVisualInsetsRight;
// What we show as preview should match what we show on key top in onBufferDraw().
if (key.mLabel != null) {
// TODO Should take care of temporaryShiftLabel here.
- mPreviewText.setCompoundDrawables(null, null, null, null);
- mPreviewText.setText(adjustCase(tracker.getPreviewText(key)));
+ previewText.setCompoundDrawables(null, null, null, null);
+ previewText.setText(adjustCase(tracker.getPreviewText(key)));
if (key.mLabel.length() > 1) {
- mPreviewText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mKeyLetterSize);
- mPreviewText.setTypeface(Typeface.DEFAULT_BOLD);
+ previewText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mKeyLetterSize);
+ previewText.setTypeface(Typeface.DEFAULT_BOLD);
} else {
- mPreviewText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mPreviewTextSizeLarge);
- mPreviewText.setTypeface(mKeyLetterStyle);
+ previewText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mPreviewTextSize);
+ previewText.setTypeface(mKeyLetterStyle);
}
} else {
final Drawable previewIcon = key.getPreviewIcon();
- mPreviewText.setCompoundDrawables(null, null, null,
+ previewText.setCompoundDrawables(null, null, null,
previewIcon != null ? previewIcon : key.getIcon());
- mPreviewText.setText(null);
- }
- mPreviewText.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
- MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
- int popupWidth = Math.max(mPreviewText.getMeasuredWidth(), key.mWidth
- + mPreviewText.getPaddingLeft() + mPreviewText.getPaddingRight());
- final int popupHeight = mPreviewHeight;
- LayoutParams lp = mPreviewText.getLayoutParams();
- if (lp != null) {
- lp.width = popupWidth;
- lp.height = popupHeight;
- }
-
- int popupPreviewX = key.mX - (popupWidth - key.mWidth) / 2;
- int popupPreviewY = key.mY - popupHeight + mPreviewOffset;
-
- mHandler.cancelDismissPreview();
- if (mOffsetInWindow == null) {
- mOffsetInWindow = new int[2];
- getLocationInWindow(mOffsetInWindow);
- mOffsetInWindow[0] += mPopupPreviewOffsetX; // Offset may be zero
- mOffsetInWindow[1] += mPopupPreviewOffsetY; // Offset may be zero
- int[] windowLocation = new int[2];
- getLocationOnScreen(windowLocation);
- mWindowY = windowLocation[1];
+ previewText.setText(null);
}
// Set the preview background state
- mPreviewText.getBackground().setState(
+ previewText.getBackground().setState(
key.mPopupCharacters != null ? LONG_PRESSABLE_STATE_SET : EMPTY_STATE_SET);
- popupPreviewX += mOffsetInWindow[0];
- popupPreviewY += mOffsetInWindow[1];
-
- // If the popup cannot be shown above the key, put it on the side
- if (popupPreviewY + mWindowY < 0) {
- // If the key you're pressing is on the left side of the keyboard, show the popup on
- // the right, offset by enough to see at least one key to the left/right.
- if (key.mX + key.mWidth <= getWidth() / 2) {
- popupPreviewX += (int) (key.mWidth * 2.5);
- } else {
- popupPreviewX -= (int) (key.mWidth * 2.5);
- }
- popupPreviewY += popupHeight;
- }
- try {
- if (mPreviewPopup.isShowing()) {
- mPreviewPopup.update(popupPreviewX, popupPreviewY, popupWidth, popupHeight);
- } else {
- mPreviewPopup.setWidth(popupWidth);
- mPreviewPopup.setHeight(popupHeight);
- mPreviewPopup.showAtLocation(mMiniKeyboardParent, Gravity.NO_GRAVITY,
- popupPreviewX, popupPreviewY);
- }
- } catch (WindowManager.BadTokenException e) {
- // Swallow the exception which will be happened when IME is already closed.
- Log.w(TAG, "LatinIME is already closed when tried showing key preview.");
- }
- // Record popup preview position to display mini-keyboard later at the same positon
- mPopupPreviewDisplayedY = popupPreviewY;
- mPreviewText.setVisibility(VISIBLE);
+ previewText.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
+ MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
+ final int previewWidth = Math.max(previewText.getMeasuredWidth(), keyDrawWidth
+ + previewText.getPaddingLeft() + previewText.getPaddingRight());
+ final int previewHeight = mPreviewHeight;
+ getLocationInWindow(mCoordinates);
+ final int previewX = keyDrawX - (previewWidth - keyDrawWidth) / 2 + mCoordinates[0];
+ final int previewY = key.mY - previewHeight + mCoordinates[1] + mPreviewOffset;
+ // Record key preview position to display mini-keyboard later at the same position
+ mKeyPreviewPopupDisplayedY = previewY;
+
+ // Place the key preview.
+ // TODO: Adjust position of key previews which touch screen edges
+ final MarginLayoutParams lp = (MarginLayoutParams)previewText.getLayoutParams();
+ lp.width = previewWidth;
+ lp.height = previewHeight;
+ lp.setMargins(previewX, previewY, 0, 0);
+ previewText.setVisibility(VISIBLE);
}
/**
@@ -1021,70 +991,72 @@ public class KeyboardView extends View implements PointerTracker.UIProxy {
if (key == null)
return;
mInvalidatedKey = key;
- mInvalidatedKeyRect.set(0, 0, key.mWidth, key.mHeight);
- mInvalidatedKeyRect.offset(key.mX + getPaddingLeft(), key.mY + getPaddingTop());
+ final int x = key.mX + getPaddingLeft();
+ final int y = key.mY + getPaddingTop();
+ mInvalidatedKeyRect.set(x, y, x + key.mWidth, y + key.mHeight);
mDirtyRect.union(mInvalidatedKeyRect);
onBufferDraw();
invalidate(mInvalidatedKeyRect);
}
- private boolean openPopupIfRequired(int keyIndex, PointerTracker tracker) {
+ private boolean openMiniKeyboardIfRequired(int keyIndex, PointerTracker tracker) {
// Check if we have a popup layout specified first.
if (mPopupLayout == 0) {
return false;
}
- Key popupKey = tracker.getKey(keyIndex);
- if (popupKey == null)
+ final Key parentKey = tracker.getKey(keyIndex);
+ if (parentKey == null)
return false;
- boolean result = onLongPress(popupKey, tracker);
+ boolean result = onLongPress(parentKey, tracker);
if (result) {
- dismissKeyPreview();
- mMiniKeyboardTrackerId = tracker.mPointerId;
- // Mark this tracker "already processed" and remove it from the pointer queue
- tracker.setAlreadyProcessed();
- mPointerQueue.remove(tracker);
+ dismissAllKeyPreviews();
+ tracker.onLongPressed(mPointerQueue);
}
return result;
}
private void onLongPressShiftKey(PointerTracker tracker) {
- tracker.setAlreadyProcessed();
- mPointerQueue.remove(tracker);
+ tracker.onLongPressed(mPointerQueue);
mKeyboardActionListener.onCodeInput(Keyboard.CODE_CAPSLOCK, null, 0, 0);
}
- private void onDoubleTapShiftKey(PointerTracker tracker) {
+ private void onDoubleTapShiftKey(@SuppressWarnings("unused") PointerTracker tracker) {
// When shift key is double tapped, the first tap is correctly processed as usual tap. And
// the second tap is treated as this double tap event, so that we need not mark tracker
// calling setAlreadyProcessed() nor remove the tracker from mPointerQueueueue.
mKeyboardActionListener.onCodeInput(Keyboard.CODE_CAPSLOCK, null, 0, 0);
}
- private View inflateMiniKeyboardContainer(Key popupKey) {
+ // This default implementation returns a popup mini keyboard panel.
+ // A derived class may return a language switcher popup panel, for instance.
+ protected PopupPanel onCreatePopupPanel(Key parentKey) {
+ if (parentKey.mPopupCharacters == null)
+ return null;
+
final View container = LayoutInflater.from(getContext()).inflate(mPopupLayout, null);
if (container == null)
throw new NullPointerException();
- final KeyboardView miniKeyboardView =
- (KeyboardView)container.findViewById(R.id.KeyboardView);
+ final PopupMiniKeyboardView miniKeyboardView =
+ (PopupMiniKeyboardView)container.findViewById(R.id.mini_keyboard_view);
miniKeyboardView.setOnKeyboardActionListener(new KeyboardActionListener() {
@Override
public void onCodeInput(int primaryCode, int[] keyCodes, int x, int y) {
mKeyboardActionListener.onCodeInput(primaryCode, keyCodes, x, y);
- dismissPopupKeyboard();
+ dismissMiniKeyboard();
}
@Override
public void onTextInput(CharSequence text) {
mKeyboardActionListener.onTextInput(text);
- dismissPopupKeyboard();
+ dismissMiniKeyboard();
}
@Override
public void onCancelInput() {
mKeyboardActionListener.onCancelInput();
- dismissPopupKeyboard();
+ dismissMiniKeyboard();
}
@Override
@@ -1100,99 +1072,57 @@ public class KeyboardView extends View implements PointerTracker.UIProxy {
mKeyboardActionListener.onRelease(primaryCode, withSliding);
}
});
- // Override default ProximityKeyDetector.
- miniKeyboardView.mKeyDetector = new MiniKeyboardKeyDetector(mMiniKeyboardSlideAllowance);
- // Remove gesture detector on mini-keyboard
- miniKeyboardView.mGestureDetector = null;
final Keyboard keyboard = new MiniKeyboardBuilder(this, mKeyboard.getPopupKeyboardResId(),
- popupKey, mKeyboard).build();
+ parentKey, mKeyboard).build();
miniKeyboardView.setKeyboard(keyboard);
- miniKeyboardView.mMiniKeyboardParent = this;
container.measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.AT_MOST),
MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.AT_MOST));
- return container;
+ return miniKeyboardView;
}
/**
- * Called when a key is long pressed. By default this will open any popup keyboard associated
- * with this key through the attributes popupLayout and popupCharacters.
- * @param popupKey the key that was long pressed
+ * Called when a key is long pressed. By default this will open mini keyboard associated
+ * with this key.
+ * @param parentKey the key that was long pressed
+ * @param tracker the pointer tracker which pressed the parent key
* @return true if the long press is handled, false otherwise. Subclasses should call the
* method on the base class if the subclass doesn't wish to handle the call.
*/
- protected boolean onLongPress(Key popupKey, PointerTracker tracker) {
- if (popupKey.mPopupCharacters == null)
- return false;
-
- View container = mMiniKeyboardCache.get(popupKey);
- if (container == null) {
- container = inflateMiniKeyboardContainer(popupKey);
- mMiniKeyboardCache.put(popupKey, container);
- }
- mMiniKeyboardView = (KeyboardView)container.findViewById(R.id.KeyboardView);
- final MiniKeyboard miniKeyboard = (MiniKeyboard)mMiniKeyboardView.getKeyboard();
-
- if (mWindowOffset == null) {
- mWindowOffset = new int[2];
- getLocationInWindow(mWindowOffset);
+ protected boolean onLongPress(Key parentKey, PointerTracker tracker) {
+ PopupPanel popupPanel = mPopupPanelCache.get(parentKey);
+ if (popupPanel == null) {
+ popupPanel = onCreatePopupPanel(parentKey);
+ if (popupPanel == null)
+ return false;
+ mPopupPanelCache.put(parentKey, popupPanel);
}
- final int pointX = (mConfigShowMiniKeyboardAtTouchedPoint) ? tracker.getLastX()
- : popupKey.mX + popupKey.mWidth / 2;
- final int keyboardLeft = pointX - miniKeyboard.getDefaultCoordX() + getPaddingLeft();
- final int popupX = Math.max(0, Math.min(keyboardLeft,
- mMiniKeyboardParent.getWidth() - miniKeyboard.getMinWidth()))
- - container.getPaddingLeft() + mWindowOffset[0];
- final int popupY = popupKey.mY - mKeyboard.getVerticalGap() + getPaddingTop()
- - (container.getMeasuredHeight() - container.getPaddingBottom()) + mWindowOffset[1];
- final int x = popupX;
- final int y = mShowPreview && miniKeyboard.isOneRowKeys()
- ? mPopupPreviewDisplayedY : popupY;
-
- mMiniKeyboardOriginX = x + container.getPaddingLeft() - mWindowOffset[0];
- mMiniKeyboardOriginY = y + container.getPaddingTop() - mWindowOffset[1];
- mMiniKeyboardView.setPopupOffset(x, y);
- if (miniKeyboard.setShifted(
- mKeyboard == null ? false : mKeyboard.isShiftedOrShiftLocked())) {
- mMiniKeyboardView.invalidateAllKeys();
+ if (mPopupWindow == null) {
+ mPopupWindow = new PopupWindow(getContext());
+ mPopupWindow.setBackgroundDrawable(null);
+ mPopupWindow.setAnimationStyle(R.style.PopupMiniKeyboardAnimation);
+ // Allow popup window to be drawn off the screen.
+ mPopupWindow.setClippingEnabled(false);
}
- // Mini keyboard needs no pop-up key preview displayed.
- mMiniKeyboardView.setPreviewEnabled(false);
- mMiniKeyboardPopup.setContentView(container);
- mMiniKeyboardPopup.setWidth(container.getMeasuredWidth());
- mMiniKeyboardPopup.setHeight(container.getMeasuredHeight());
- mMiniKeyboardPopup.showAtLocation(this, Gravity.NO_GRAVITY, x, y);
-
- // Inject down event on the key to mini keyboard.
- final long eventTime = SystemClock.uptimeMillis();
- mMiniKeyboardPopupTime = eventTime;
- final MotionEvent downEvent = generateMiniKeyboardMotionEvent(MotionEvent.ACTION_DOWN,
- pointX, popupKey.mY + popupKey.mHeight / 2, eventTime);
- mMiniKeyboardView.onTouchEvent(downEvent);
- downEvent.recycle();
+ mPopupMiniKeyboardPanel = popupPanel;
+ popupPanel.showPanel(this, parentKey, tracker, mKeyPreviewPopupDisplayedY, mPopupWindow);
invalidateAllKeys();
return true;
}
- private MotionEvent generateMiniKeyboardMotionEvent(int action, int x, int y, long eventTime) {
- return MotionEvent.obtain(mMiniKeyboardPopupTime, eventTime, action,
- x - mMiniKeyboardOriginX, y - mMiniKeyboardOriginY, 0);
- }
-
private PointerTracker getPointerTracker(final int id) {
final ArrayList<PointerTracker> pointers = mPointerTrackers;
- final Key[] keys = mKeys;
final KeyboardActionListener listener = mKeyboardActionListener;
// Create pointer trackers until we can get 'id+1'-th tracker, if needed.
for (int i = pointers.size(); i <= id; i++) {
final PointerTracker tracker =
- new PointerTracker(i, mHandler, mKeyDetector, this, getResources());
- if (keys != null)
- tracker.setKeyboard(mKeyboard, keys, mKeyHysteresisDistance);
+ new PointerTracker(i, this, mHandler, mKeyDetector, this);
+ if (mKeyboard != null)
+ tracker.setKeyboard(mKeyboard, mKeyHysteresisDistance);
if (listener != null)
tracker.setOnKeyboardActionListener(listener);
pointers.add(tracker);
@@ -1202,8 +1132,8 @@ public class KeyboardView extends View implements PointerTracker.UIProxy {
}
public boolean isInSlidingKeyInput() {
- if (mMiniKeyboardView != null) {
- return mMiniKeyboardView.isInSlidingKeyInput();
+ if (mPopupMiniKeyboardPanel != null) {
+ return mPopupMiniKeyboardPanel.isInSlidingKeyInput();
} else {
return mPointerQueue.isInSlidingKeyInput();
}
@@ -1223,20 +1153,17 @@ public class KeyboardView extends View implements PointerTracker.UIProxy {
// TODO: cleanup this code into a multi-touch to single-touch event converter class?
// If the device does not have distinct multi-touch support panel, ignore all multi-touch
// events except a transition from/to single-touch.
- if ((!mHasDistinctMultitouch || mIsAccessibilityEnabled)
- && pointerCount > 1 && oldPointerCount > 1) {
+ if (!mHasDistinctMultitouch && pointerCount > 1 && oldPointerCount > 1) {
return true;
}
// Track the last few movements to look for spurious swipes.
mSwipeTracker.addMovement(me);
- // Gesture detector must be enabled only when mini-keyboard is not on the screen and
- // accessibility is not enabled.
- // TODO: Reconcile gesture detection and accessibility features.
- if (mMiniKeyboardView == null && !mIsAccessibilityEnabled
- && mGestureDetector != null && mGestureDetector.onTouchEvent(me)) {
- dismissKeyPreview();
+ // Gesture detector must be enabled only when mini-keyboard is not on the screen.
+ if (mPopupMiniKeyboardPanel == null && mGestureDetector != null
+ && mGestureDetector.onTouchEvent(me)) {
+ dismissAllKeyPreviews();
mHandler.cancelKeyTimers();
return true;
}
@@ -1247,26 +1174,13 @@ public class KeyboardView extends View implements PointerTracker.UIProxy {
final int x = (int)me.getX(index);
final int y = (int)me.getY(index);
- // Needs to be called after the gesture detector gets a turn, as it may have
- // displayed the mini keyboard
- if (mMiniKeyboardView != null) {
- final int miniKeyboardPointerIndex = me.findPointerIndex(mMiniKeyboardTrackerId);
- if (miniKeyboardPointerIndex >= 0 && miniKeyboardPointerIndex < pointerCount) {
- final int miniKeyboardX = (int)me.getX(miniKeyboardPointerIndex);
- final int miniKeyboardY = (int)me.getY(miniKeyboardPointerIndex);
- MotionEvent translated = generateMiniKeyboardMotionEvent(action,
- miniKeyboardX, miniKeyboardY, eventTime);
- mMiniKeyboardView.onTouchEvent(translated);
- translated.recycle();
- }
- return true;
+ // Needs to be called after the gesture detector gets a turn, as it may have displayed the
+ // mini keyboard
+ if (mPopupMiniKeyboardPanel != null) {
+ return mPopupMiniKeyboardPanel.onTouchEvent(me);
}
if (mHandler.isInKeyRepeat()) {
- // It will keep being in the key repeating mode while the key is being pressed.
- if (action == MotionEvent.ACTION_MOVE) {
- return true;
- }
final PointerTracker tracker = getPointerTracker(id);
// Key repeating timer will be canceled if 2 or more keys are in action, and current
// event (UP or DOWN) is non-modifier key.
@@ -1279,17 +1193,26 @@ public class KeyboardView extends View implements PointerTracker.UIProxy {
// TODO: cleanup this code into a multi-touch to single-touch event converter class?
// Translate mutli-touch event to single-touch events on the device that has no distinct
// multi-touch panel.
- if (!mHasDistinctMultitouch || mIsAccessibilityEnabled) {
+ if (!mHasDistinctMultitouch) {
// Use only main (id=0) pointer tracker.
PointerTracker tracker = getPointerTracker(0);
if (pointerCount == 1 && oldPointerCount == 2) {
// Multi-touch to single touch transition.
- // Send a down event for the latest pointer.
- tracker.onDownEvent(x, y, eventTime, null);
+ // Send a down event for the latest pointer if the key is different from the
+ // previous key.
+ final int newKeyIndex = tracker.getKeyIndexOn(x, y);
+ if (mOldKeyIndex != newKeyIndex) {
+ tracker.onDownEvent(x, y, eventTime, null);
+ if (action == MotionEvent.ACTION_UP)
+ tracker.onUpEvent(x, y, eventTime, null);
+ }
} else if (pointerCount == 2 && oldPointerCount == 1) {
// Single-touch to multi-touch transition.
// Send an up event for the last pointer.
- tracker.onUpEvent(tracker.getLastX(), tracker.getLastY(), eventTime, null);
+ final int lastX = tracker.getLastX();
+ final int lastY = tracker.getLastY();
+ mOldKeyIndex = tracker.getKeyIndexOn(lastX, lastY);
+ tracker.onUpEvent(lastX, lastY, eventTime, null);
} else if (pointerCount == 1 && oldPointerCount == 1) {
tracker.onTouchEvent(action, x, y, eventTime, null);
} else {
@@ -1330,12 +1253,12 @@ public class KeyboardView extends View implements PointerTracker.UIProxy {
}
public void closing() {
- mPreviewPopup.dismiss();
+ mPreviewText.setVisibility(View.GONE);
mHandler.cancelAllMessages();
- dismissPopupKeyboard();
+ dismissMiniKeyboard();
mDirtyRect.union(0, 0, getWidth(), getHeight());
- mMiniKeyboardCache.clear();
+ mPopupPanelCache.clear();
requestLayout();
}
@@ -1350,21 +1273,17 @@ public class KeyboardView extends View implements PointerTracker.UIProxy {
closing();
}
- private void dismissPopupKeyboard() {
- if (mMiniKeyboardPopup.isShowing()) {
- mMiniKeyboardPopup.dismiss();
- mMiniKeyboardView = null;
- mMiniKeyboardOriginX = 0;
- mMiniKeyboardOriginY = 0;
+ private boolean dismissMiniKeyboard() {
+ if (mPopupWindow != null && mPopupWindow.isShowing()) {
+ mPopupWindow.dismiss();
+ mPopupMiniKeyboardPanel = null;
invalidateAllKeys();
+ return true;
}
+ return false;
}
public boolean handleBack() {
- if (mMiniKeyboardPopup.isShowing()) {
- dismissPopupKeyboard();
- return true;
- }
- return false;
+ return dismissMiniKeyboard();
}
}
diff --git a/java/src/com/android/inputmethod/keyboard/LatinKeyboard.java b/java/src/com/android/inputmethod/keyboard/LatinKeyboard.java
index 5820049bb..fe27ab412 100644
--- a/java/src/com/android/inputmethod/keyboard/LatinKeyboard.java
+++ b/java/src/com/android/inputmethod/keyboard/LatinKeyboard.java
@@ -26,6 +26,9 @@ import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
+import android.graphics.ColorFilter;
+import android.graphics.ColorMatrix;
+import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.PorterDuff;
@@ -33,41 +36,49 @@ import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
+import java.lang.ref.SoftReference;
+import java.util.Arrays;
+import java.util.HashMap;
import java.util.List;
import java.util.Locale;
// TODO: We should remove this class
public class LatinKeyboard extends Keyboard {
- public static final int OPACITY_FULLY_OPAQUE = 255;
private static final int SPACE_LED_LENGTH_PERCENT = 80;
+ public static final int CODE_NEXT_LANGUAGE = -100;
+ public static final int CODE_PREV_LANGUAGE = -101;
+
private final Context mContext;
+ private final SubtypeSwitcher mSubtypeSwitcher = SubtypeSwitcher.getInstance();
/* Space key and its icons, drawables and colors. */
private final Key mSpaceKey;
private final Drawable mSpaceIcon;
private final Drawable mSpacePreviewIcon;
- private final int[] mSpaceKeyIndexArray;
+ private final int mSpaceKeyIndex;
private final Drawable mSpaceAutoCorrectionIndicator;
private final Drawable mButtonArrowLeftIcon;
private final Drawable mButtonArrowRightIcon;
private final int mSpacebarTextColor;
private final int mSpacebarTextShadowColor;
- private final int mSpacebarVerticalCorrection;
private float mSpacebarTextFadeFactor = 0.0f;
- private int mSpaceDragStartX;
- private int mSpaceDragLastDiff;
- private boolean mCurrentlyInSpace;
+ private final int mSpacebarLanguageSwitchThreshold;
+ private int mSpacebarSlidingLanguageSwitchDiff;
private SlidingLocaleDrawable mSlidingLocaleIcon;
+ private final HashMap<Integer, SoftReference<BitmapDrawable>> mSpaceDrawableCache =
+ new HashMap<Integer, SoftReference<BitmapDrawable>>();
/* Shortcut key and its icons if available */
private final Key mShortcutKey;
private final Drawable mEnabledShortcutIcon;
private final Drawable mDisabledShortcutIcon;
- private static final float SPACEBAR_DRAG_THRESHOLD = 0.8f;
- // Minimum width of space key preview (proportional to keyboard width)
- private static final float SPACEBAR_POPUP_MIN_RATIO = 0.4f;
+ // Minimum width of spacebar dragging to trigger the language switch (represented by the number
+ // of the most common key width of this keyboard).
+ private static final int SPACEBAR_DRAG_WIDTH = 3;
+ // Minimum width of space key preview (proportional to keyboard width).
+ private static final float SPACEBAR_POPUP_MIN_RATIO = 0.5f;
// Height in space key the language name will be drawn. (proportional to space key height)
public static final float SPACEBAR_LANGUAGE_BASELINE = 0.6f;
// If the full language name needs to be smaller than this value to be drawn on space key,
@@ -77,8 +88,8 @@ public class LatinKeyboard extends Keyboard {
private static final String SMALL_TEXT_SIZE_OF_LANGUAGE_ON_SPACEBAR = "small";
private static final String MEDIUM_TEXT_SIZE_OF_LANGUAGE_ON_SPACEBAR = "medium";
- public LatinKeyboard(Context context, KeyboardId id) {
- super(context, id.getXmlId(), id);
+ public LatinKeyboard(Context context, KeyboardId id, int width) {
+ super(context, id.getXmlId(), id, width);
final Resources res = context.getResources();
mContext = context;
@@ -92,7 +103,7 @@ public class LatinKeyboard extends Keyboard {
case CODE_SPACE:
spaceKeyIndex = index;
break;
- case CODE_VOICE:
+ case CODE_SHORTCUT:
shortcutKeyIndex = index;
break;
}
@@ -102,7 +113,7 @@ public class LatinKeyboard extends Keyboard {
mSpaceKey = (spaceKeyIndex >= 0) ? keys.get(spaceKeyIndex) : null;
mSpaceIcon = (mSpaceKey != null) ? mSpaceKey.getIcon() : null;
mSpacePreviewIcon = (mSpaceKey != null) ? mSpaceKey.getPreviewIcon() : null;
- mSpaceKeyIndexArray = new int[] { spaceKeyIndex };
+ mSpaceKeyIndex = spaceKeyIndex;
mShortcutKey = (shortcutKeyIndex >= 0) ? keys.get(shortcutKeyIndex) : null;
mEnabledShortcutIcon = (mShortcutKey != null) ? mShortcutKey.getIcon() : null;
@@ -120,8 +131,8 @@ public class LatinKeyboard extends Keyboard {
mSpaceAutoCorrectionIndicator = res.getDrawable(R.drawable.sym_keyboard_space_led);
mButtonArrowLeftIcon = res.getDrawable(R.drawable.sym_keyboard_language_arrows_left);
mButtonArrowRightIcon = res.getDrawable(R.drawable.sym_keyboard_language_arrows_right);
- mSpacebarVerticalCorrection = res.getDimensionPixelOffset(
- R.dimen.spacebar_vertical_correction);
+ // The threshold is "key width" x 1.25
+ mSpacebarLanguageSwitchThreshold = (getMostCommonKeyWidth() * 5) / 4;
}
public void setSpacebarTextFadeFactor(float fadeFactor, LatinKeyboardView view) {
@@ -137,6 +148,12 @@ public class LatinKeyboard extends Keyboard {
return newColor;
}
+ private static ColorFilter getSpacebarDrawableFilter(float fadeFactor) {
+ final ColorMatrix colorMatrix = new ColorMatrix();
+ colorMatrix.setScale(1, 1, 1, fadeFactor);
+ return new ColorMatrixColorFilter(colorMatrix);
+ }
+
public void updateShortcutKey(boolean available, LatinKeyboardView view) {
if (mShortcutKey == null)
return;
@@ -157,19 +174,14 @@ public class LatinKeyboard extends Keyboard {
private void updateSpacebarForLocale(boolean isAutoCorrection) {
if (mSpaceKey == null)
return;
- final Resources res = mContext.getResources();
// If application locales are explicitly selected.
- if (SubtypeSwitcher.getInstance().needsToDisplayLanguage()) {
- mSpaceKey.setIcon(new BitmapDrawable(res,
- drawSpacebar(OPACITY_FULLY_OPAQUE, isAutoCorrection)));
+ if (mSubtypeSwitcher.needsToDisplayLanguage()) {
+ mSpaceKey.setIcon(getSpaceDrawable(
+ mSubtypeSwitcher.getInputLocale(), isAutoCorrection));
+ } else if (isAutoCorrection) {
+ mSpaceKey.setIcon(getSpaceDrawable(null, true));
} else {
- // sym_keyboard_space_led can be shared with Black and White symbol themes.
- if (isAutoCorrection) {
- mSpaceKey.setIcon(new BitmapDrawable(res,
- drawSpacebar(OPACITY_FULLY_OPAQUE, isAutoCorrection)));
- } else {
- mSpaceKey.setIcon(mSpaceIcon);
- }
+ mSpaceKey.setIcon(mSpaceIcon);
}
}
@@ -182,8 +194,7 @@ public class LatinKeyboard extends Keyboard {
// Layout local language name and left and right arrow on spacebar.
private static String layoutSpacebar(Paint paint, Locale locale, Drawable lArrow,
- Drawable rArrow, int width, int height, float origTextSize,
- boolean allowVariableTextSize) {
+ Drawable rArrow, int width, int height, float origTextSize) {
final float arrowWidth = lArrow.getIntrinsicWidth();
final float arrowHeight = lArrow.getIntrinsicHeight();
final float maxTextWidth = width - (arrowWidth + arrowWidth);
@@ -194,17 +205,23 @@ public class LatinKeyboard extends Keyboard {
int textWidth = getTextWidth(paint, language, origTextSize, bounds);
// Assuming text width and text size are proportional to each other.
float textSize = origTextSize * Math.min(maxTextWidth / textWidth, 1.0f);
+ // allow variable text size
+ textWidth = getTextWidth(paint, language, textSize, bounds);
+ // If text size goes too small or text does not fit, use middle or short name
+ final boolean useMiddleName = (textSize / origTextSize < MINIMUM_SCALE_OF_LANGUAGE_NAME)
+ || (textWidth > maxTextWidth);
final boolean useShortName;
- if (allowVariableTextSize) {
- textWidth = getTextWidth(paint, language, textSize, bounds);
- // If text size goes too small or text does not fit, use short name
- useShortName = textSize / origTextSize < MINIMUM_SCALE_OF_LANGUAGE_NAME
- || textWidth > maxTextWidth;
+ if (useMiddleName) {
+ language = SubtypeSwitcher.getMiddleDisplayLanguage(locale);
+ textWidth = getTextWidth(paint, language, origTextSize, bounds);
+ textSize = origTextSize * Math.min(maxTextWidth / textWidth, 1.0f);
+ useShortName = (textSize / origTextSize < MINIMUM_SCALE_OF_LANGUAGE_NAME)
+ || (textWidth > maxTextWidth);
} else {
- useShortName = textWidth > maxTextWidth;
- textSize = origTextSize;
+ useShortName = false;
}
+
if (useShortName) {
language = SubtypeSwitcher.getShortDisplayLanguage(locale);
textWidth = getTextWidth(paint, language, origTextSize, bounds);
@@ -223,19 +240,31 @@ public class LatinKeyboard extends Keyboard {
return language;
}
- private Bitmap drawSpacebar(int opacity, boolean isAutoCorrection) {
+ private BitmapDrawable getSpaceDrawable(Locale locale, boolean isAutoCorrection) {
+ final Integer hashCode = Arrays.hashCode(
+ new Object[] { locale, isAutoCorrection, mSpacebarTextFadeFactor });
+ final SoftReference<BitmapDrawable> ref = mSpaceDrawableCache.get(hashCode);
+ BitmapDrawable drawable = (ref == null) ? null : ref.get();
+ if (drawable == null) {
+ drawable = new BitmapDrawable(mContext.getResources(), drawSpacebar(
+ locale, isAutoCorrection, mSpacebarTextFadeFactor));
+ mSpaceDrawableCache.put(hashCode, new SoftReference<BitmapDrawable>(drawable));
+ }
+ return drawable;
+ }
+
+ private Bitmap drawSpacebar(Locale inputLocale, boolean isAutoCorrection,
+ float textFadeFactor) {
final int width = mSpaceKey.mWidth;
final int height = mSpaceIcon != null ? mSpaceIcon.getIntrinsicHeight() : mSpaceKey.mHeight;
final Bitmap buffer = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(buffer);
final Resources res = mContext.getResources();
- canvas.drawColor(res.getColor(R.color.latinkeyboard_transparent), PorterDuff.Mode.CLEAR);
+ canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
- SubtypeSwitcher subtypeSwitcher = SubtypeSwitcher.getInstance();
// If application locales are explicitly selected.
- if (subtypeSwitcher.needsToDisplayLanguage()) {
+ if (inputLocale != null) {
final Paint paint = new Paint();
- paint.setAlpha(opacity);
paint.setAntiAlias(true);
paint.setTextAlign(Align.CENTER);
@@ -252,11 +281,9 @@ public class LatinKeyboard extends Keyboard {
defaultTextSize = 14;
}
- final boolean allowVariableTextSize = true;
- final String language = layoutSpacebar(paint, subtypeSwitcher.getInputLocale(),
+ final String language = layoutSpacebar(paint, inputLocale,
mButtonArrowLeftIcon, mButtonArrowRightIcon, width, height,
- getTextSizeFromTheme(mContext.getTheme(), textStyle, defaultTextSize),
- allowVariableTextSize);
+ getTextSizeFromTheme(mContext.getTheme(), textStyle, defaultTextSize));
// Draw language text with shadow
// In case there is no space icon, we will place the language text at the center of
@@ -265,14 +292,19 @@ public class LatinKeyboard extends Keyboard {
final float textHeight = -paint.ascent() + descent;
final float baseline = (mSpaceIcon != null) ? height * SPACEBAR_LANGUAGE_BASELINE
: height / 2 + textHeight / 2;
- paint.setColor(getSpacebarTextColor(mSpacebarTextShadowColor, mSpacebarTextFadeFactor));
+ paint.setColor(getSpacebarTextColor(mSpacebarTextShadowColor, textFadeFactor));
canvas.drawText(language, width / 2, baseline - descent - 1, paint);
- paint.setColor(getSpacebarTextColor(mSpacebarTextColor, mSpacebarTextFadeFactor));
+ paint.setColor(getSpacebarTextColor(mSpacebarTextColor, textFadeFactor));
canvas.drawText(language, width / 2, baseline - descent, paint);
- // Put arrows that are already layed out on either side of the text
- if (SubtypeSwitcher.getInstance().useSpacebarLanguageSwitcher()
- && subtypeSwitcher.getEnabledKeyboardLocaleCount() > 1) {
+ // Put arrows that are already laid out on either side of the text
+ // Because language switch is disabled on phone and number layouts, hide arrows.
+ // TODO: Sort out how to enable language switch on these layouts.
+ if (mSubtypeSwitcher.useSpacebarLanguageSwitcher()
+ && mSubtypeSwitcher.getEnabledKeyboardLocaleCount() > 1
+ && !(isPhoneKeyboard() || isNumberKeyboard())) {
+ mButtonArrowLeftIcon.setColorFilter(getSpacebarDrawableFilter(textFadeFactor));
+ mButtonArrowRightIcon.setColorFilter(getSpacebarDrawableFilter(textFadeFactor));
mButtonArrowLeftIcon.draw(canvas);
mButtonArrowRightIcon.draw(canvas);
}
@@ -297,7 +329,14 @@ public class LatinKeyboard extends Keyboard {
return buffer;
}
- private void updateLocaleDrag(int diff) {
+ public void setSpacebarSlidingLanguageSwitchDiff(int diff) {
+ mSpacebarSlidingLanguageSwitchDiff = diff;
+ }
+
+ public void updateSpacebarPreviewIcon(int diff) {
+ if (mSpacebarSlidingLanguageSwitchDiff == diff)
+ return;
+ mSpacebarSlidingLanguageSwitchDiff = diff;
if (mSlidingLocaleIcon == null) {
final int width = Math.max(mSpaceKey.mWidth,
(int)(getMinWidth() * SPACEBAR_POPUP_MIN_RATIO));
@@ -305,7 +344,6 @@ public class LatinKeyboard extends Keyboard {
mSlidingLocaleIcon =
new SlidingLocaleDrawable(mContext, mSpacePreviewIcon, width, height);
mSlidingLocaleIcon.setBounds(0, 0, width, height);
- mSpaceKey.setPreviewIcon(mSlidingLocaleIcon);
}
mSlidingLocaleIcon.setDiff(diff);
if (Math.abs(diff) == Integer.MAX_VALUE) {
@@ -316,69 +354,49 @@ public class LatinKeyboard extends Keyboard {
mSpaceKey.getPreviewIcon().invalidateSelf();
}
- public int getLanguageChangeDirection() {
- if (mSpaceKey == null || SubtypeSwitcher.getInstance().getEnabledKeyboardLocaleCount() <= 1
- || Math.abs(mSpaceDragLastDiff) < mSpaceKey.mWidth * SPACEBAR_DRAG_THRESHOLD) {
- return 0; // No change
- }
- return mSpaceDragLastDiff > 0 ? 1 : -1;
- }
-
- public void keyReleased() {
- mCurrentlyInSpace = false;
- mSpaceDragLastDiff = 0;
- if (mSpaceKey != null) {
- updateLocaleDrag(Integer.MAX_VALUE);
- }
+ public boolean shouldTriggerSpacebarSlidingLanguageSwitch(int diff) {
+ // On phone and number layouts, sliding language switch is disabled.
+ // TODO: Sort out how to enable language switch on these layouts.
+ if (isPhoneKeyboard() || isNumberKeyboard())
+ return false;
+ return Math.abs(diff) > mSpacebarLanguageSwitchThreshold;
}
/**
- * Does the magic of locking the touch gesture into the spacebar when
- * switching input languages.
+ * Return true if spacebar needs showing preview even when "popup on keypress" is off.
+ * @param keyIndex index of the pressing key
+ * @return true if spacebar needs showing preview
*/
@Override
- public boolean isInside(Key key, int pointX, int pointY) {
- int x = pointX;
- int y = pointY;
- final int code = key.mCode;
- if (code == CODE_SPACE) {
- y += mSpacebarVerticalCorrection;
- if (SubtypeSwitcher.getInstance().useSpacebarLanguageSwitcher()
- && SubtypeSwitcher.getInstance().getEnabledKeyboardLocaleCount() > 1) {
- if (mCurrentlyInSpace) {
- int diff = x - mSpaceDragStartX;
- if (Math.abs(diff - mSpaceDragLastDiff) > 0) {
- updateLocaleDrag(diff);
- }
- mSpaceDragLastDiff = diff;
- return true;
- } else {
- boolean isOnSpace = key.isOnKey(x, y);
- if (isOnSpace) {
- mCurrentlyInSpace = true;
- mSpaceDragStartX = x;
- updateLocaleDrag(0);
- }
- return isOnSpace;
- }
- }
- }
-
- // Lock into the spacebar
- if (mCurrentlyInSpace) return false;
+ public boolean needSpacebarPreview(int keyIndex) {
+ // This method is called when "popup on keypress" is off.
+ if (!mSubtypeSwitcher.useSpacebarLanguageSwitcher())
+ return false;
+ // Dismiss key preview.
+ if (keyIndex == KeyDetector.NOT_A_KEY)
+ return true;
+ // Key is not a spacebar.
+ if (keyIndex != mSpaceKeyIndex)
+ return false;
+ // The language switcher will be displayed only when the dragging distance is greater
+ // than the threshold.
+ return shouldTriggerSpacebarSlidingLanguageSwitch(mSpacebarSlidingLanguageSwitchDiff);
+ }
- return key.isOnKey(x, y);
+ public int getLanguageChangeDirection() {
+ if (mSpaceKey == null || mSubtypeSwitcher.getEnabledKeyboardLocaleCount() <= 1
+ || Math.abs(mSpacebarSlidingLanguageSwitchDiff)
+ < getMostCommonKeyWidth() * SPACEBAR_DRAG_WIDTH) {
+ return 0; // No change
+ }
+ return mSpacebarSlidingLanguageSwitchDiff > 0 ? 1 : -1;
}
@Override
public int[] getNearestKeys(int x, int y) {
- if (mCurrentlyInSpace) {
- return mSpaceKeyIndexArray;
- } else {
- // Avoid dead pixels at edges of the keyboard
- return super.getNearestKeys(Math.max(0, Math.min(x, getMinWidth() - 1)),
- Math.max(0, Math.min(y, getHeight() - 1)));
- }
+ // Avoid dead pixels at edges of the keyboard
+ return super.getNearestKeys(Math.max(0, Math.min(x, getMinWidth() - 1)),
+ Math.max(0, Math.min(y, getHeight() - 1)));
}
private static int getTextSizeFromTheme(Theme theme, int style, int defValue) {
diff --git a/java/src/com/android/inputmethod/keyboard/LatinKeyboardView.java b/java/src/com/android/inputmethod/keyboard/LatinKeyboardView.java
index 77e9caecc..185f1f8f7 100644
--- a/java/src/com/android/inputmethod/keyboard/LatinKeyboardView.java
+++ b/java/src/com/android/inputmethod/keyboard/LatinKeyboardView.java
@@ -16,10 +16,6 @@
package com.android.inputmethod.keyboard;
-import com.android.inputmethod.latin.LatinImeLogger;
-import com.android.inputmethod.latin.Utils;
-import com.android.inputmethod.voice.VoiceIMEConnector;
-
import android.content.Context;
import android.graphics.Canvas;
import android.text.TextUtils;
@@ -27,6 +23,10 @@ import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
+import com.android.inputmethod.deprecated.VoiceProxy;
+import com.android.inputmethod.latin.LatinImeLogger;
+import com.android.inputmethod.latin.Utils;
+
// TODO: We should remove this class
public class LatinKeyboardView extends KeyboardView {
private static final String TAG = LatinKeyboardView.class.getSimpleName();
@@ -47,7 +47,7 @@ public class LatinKeyboardView extends KeyboardView {
private int mLastY;
public LatinKeyboardView(Context context, AttributeSet attrs) {
- this(context, attrs, 0);
+ super(context, attrs);
}
public LatinKeyboardView(Context context, AttributeSet attrs, int defStyle) {
@@ -55,24 +55,19 @@ public class LatinKeyboardView extends KeyboardView {
}
@Override
- public void setPreviewEnabled(boolean previewEnabled) {
+ public void setKeyPreviewPopupEnabled(boolean previewEnabled, int delay) {
LatinKeyboard latinKeyboard = getLatinKeyboard();
if (latinKeyboard != null
&& (latinKeyboard.isPhoneKeyboard() || latinKeyboard.isNumberKeyboard())) {
// Phone and number keyboard never shows popup preview (except language switch).
- super.setPreviewEnabled(false);
+ super.setKeyPreviewPopupEnabled(false, delay);
} else {
- super.setPreviewEnabled(previewEnabled);
+ super.setKeyPreviewPopupEnabled(previewEnabled, delay);
}
}
@Override
public void setKeyboard(Keyboard newKeyboard) {
- final LatinKeyboard oldKeyboard = getLatinKeyboard();
- if (oldKeyboard != null) {
- // Reset old keyboard state before switching to new keyboard.
- oldKeyboard.keyReleased();
- }
super.setKeyboard(newKeyboard);
// One-seventh of the keyboard width seems like a reasonable threshold
mJumpThresholdSquare = newKeyboard.getMinWidth() / 7;
@@ -145,10 +140,6 @@ public class LatinKeyboardView extends KeyboardView {
// If device has distinct multi touch panel, there is no need to check sudden jump.
if (hasDistinctMultitouch())
return false;
- // If accessibiliy is enabled, stop looking for sudden jumps because it interferes
- // with touch exploration of the keyboard.
- if (isAccessibilityEnabled())
- return false;
final int action = me.getAction();
final int x = (int) me.getX();
final int y = (int) me.getY();
@@ -182,7 +173,8 @@ public class LatinKeyboardView extends KeyboardView {
if (!mDroppingEvents) {
mDroppingEvents = true;
// Send an up event
- MotionEvent translated = MotionEvent.obtain(me.getEventTime(), me.getEventTime(),
+ MotionEvent translated = MotionEvent.obtain(
+ me.getEventTime(), me.getEventTime(),
MotionEvent.ACTION_UP,
mLastX, mLastY, me.getMetaState());
super.onTouchEvent(translated);
@@ -216,8 +208,7 @@ public class LatinKeyboardView extends KeyboardView {
@Override
public boolean onTouchEvent(MotionEvent me) {
- LatinKeyboard keyboard = getLatinKeyboard();
- if (keyboard == null) return true;
+ if (getLatinKeyboard() == null) return true;
// If there was a sudden jump, return without processing the actual motion event.
if (handleSuddenJump(me)) {
@@ -226,24 +217,6 @@ public class LatinKeyboardView extends KeyboardView {
return true;
}
- // Reset any bounding box controls in the keyboard
- if (me.getAction() == MotionEvent.ACTION_DOWN) {
- keyboard.keyReleased();
- }
-
- if (me.getAction() == MotionEvent.ACTION_UP) {
- int languageDirection = keyboard.getLanguageChangeDirection();
- if (languageDirection != 0) {
- getOnKeyboardActionListener().onCodeInput(
- languageDirection == 1
- ? Keyboard.CODE_NEXT_LANGUAGE : Keyboard.CODE_PREV_LANGUAGE,
- null, mLastX, mLastY);
- me.setAction(MotionEvent.ACTION_CANCEL);
- keyboard.keyReleased();
- return super.onTouchEvent(me);
- }
- }
-
return super.onTouchEvent(me);
}
@@ -264,6 +237,6 @@ public class LatinKeyboardView extends KeyboardView {
@Override
protected void onAttachedToWindow() {
// Token is available from here.
- VoiceIMEConnector.getInstance().onAttachedToWindow();
+ VoiceProxy.getInstance().onAttachedToWindow();
}
}
diff --git a/java/src/com/android/inputmethod/keyboard/MiniKeyboard.java b/java/src/com/android/inputmethod/keyboard/MiniKeyboard.java
index 8d243e0a7..2d6766f2d 100644
--- a/java/src/com/android/inputmethod/keyboard/MiniKeyboard.java
+++ b/java/src/com/android/inputmethod/keyboard/MiniKeyboard.java
@@ -23,8 +23,8 @@ import java.util.List;
public class MiniKeyboard extends Keyboard {
private int mDefaultKeyCoordX;
- public MiniKeyboard(Context context, int xmlLayoutResId, KeyboardId id) {
- super(context, xmlLayoutResId, id);
+ public MiniKeyboard(Context context, int xmlLayoutResId, Keyboard parentKeyboard) {
+ super(context, xmlLayoutResId, null, parentKeyboard.getMinWidth());
}
public void setDefaultCoordX(int pos) {
@@ -35,7 +35,7 @@ public class MiniKeyboard extends Keyboard {
return mDefaultKeyCoordX;
}
- public boolean isOneRowKeys() {
+ public boolean isOneRowKeyboard() {
final List<Key> keys = getKeys();
if (keys.size() == 0) return false;
final int edgeFlags = keys.get(0).mEdgeFlags;
@@ -47,5 +47,6 @@ public class MiniKeyboard extends Keyboard {
// both top and bottom edge flags set.
return (edgeFlags & Keyboard.EDGE_TOP) != 0
&& (edgeFlags & Keyboard.EDGE_BOTTOM) != 0;
+
}
}
diff --git a/java/src/com/android/inputmethod/keyboard/MiniKeyboardBuilder.java b/java/src/com/android/inputmethod/keyboard/MiniKeyboardBuilder.java
index 765750fbe..6e939123d 100644
--- a/java/src/com/android/inputmethod/keyboard/MiniKeyboardBuilder.java
+++ b/java/src/com/android/inputmethod/keyboard/MiniKeyboardBuilder.java
@@ -185,7 +185,8 @@ public class MiniKeyboardBuilder {
Keyboard parentKeyboard) {
final Context context = view.getContext();
mRes = context.getResources();
- final MiniKeyboard keyboard = new MiniKeyboard(context, layoutTemplateResId, null);
+ final MiniKeyboard keyboard = new MiniKeyboard(
+ context, layoutTemplateResId, parentKeyboard);
mKeyboard = keyboard;
mPopupCharacters = parentKey.mPopupCharacters;
diff --git a/java/src/com/android/inputmethod/keyboard/MiniKeyboardKeyDetector.java b/java/src/com/android/inputmethod/keyboard/MiniKeyboardKeyDetector.java
index 1243f6f37..cc5c3bbfe 100644
--- a/java/src/com/android/inputmethod/keyboard/MiniKeyboardKeyDetector.java
+++ b/java/src/com/android/inputmethod/keyboard/MiniKeyboardKeyDetector.java
@@ -16,9 +16,9 @@
package com.android.inputmethod.keyboard;
-public class MiniKeyboardKeyDetector extends KeyDetector {
- private static final int MAX_NEARBY_KEYS = 1;
+import java.util.List;
+public class MiniKeyboardKeyDetector extends KeyDetector {
private final int mSlideAllowanceSquare;
private final int mSlideAllowanceSquareTop;
@@ -31,20 +31,21 @@ public class MiniKeyboardKeyDetector extends KeyDetector {
@Override
protected int getMaxNearbyKeys() {
- return MAX_NEARBY_KEYS;
+ // No nearby key will be returned.
+ return 1;
}
@Override
public int getKeyIndexAndNearbyCodes(int x, int y, final int[] allCodes) {
- final Key[] keys = getKeys();
+ final List<Key> keys = getKeys();
final int touchX = getTouchX(x);
final int touchY = getTouchY(y);
int nearestIndex = NOT_A_KEY;
int nearestDist = (y < 0) ? mSlideAllowanceSquareTop : mSlideAllowanceSquare;
- final int keyCount = keys.length;
+ final int keyCount = keys.size();
for (int index = 0; index < keyCount; index++) {
- final int dist = keys[index].squaredDistanceToEdge(touchX, touchY);
+ final int dist = keys.get(index).squaredDistanceToEdge(touchX, touchY);
if (dist < nearestDist) {
nearestIndex = index;
nearestDist = dist;
@@ -52,7 +53,7 @@ public class MiniKeyboardKeyDetector extends KeyDetector {
}
if (allCodes != null && nearestIndex != NOT_A_KEY)
- allCodes[0] = keys[nearestIndex].mCode;
+ allCodes[0] = keys.get(nearestIndex).mCode;
return nearestIndex;
}
}
diff --git a/java/src/com/android/inputmethod/keyboard/PointerTracker.java b/java/src/com/android/inputmethod/keyboard/PointerTracker.java
index 4b3fe8b8b..6b4e9469f 100644
--- a/java/src/com/android/inputmethod/keyboard/PointerTracker.java
+++ b/java/src/com/android/inputmethod/keyboard/PointerTracker.java
@@ -19,12 +19,14 @@ package com.android.inputmethod.keyboard;
import com.android.inputmethod.keyboard.KeyboardView.UIHandler;
import com.android.inputmethod.latin.LatinImeLogger;
import com.android.inputmethod.latin.R;
+import com.android.inputmethod.latin.SubtypeSwitcher;
import android.content.res.Resources;
import android.util.Log;
import android.view.MotionEvent;
import java.util.Arrays;
+import java.util.List;
public class PointerTracker {
private static final String TAG = PointerTracker.class.getSimpleName();
@@ -36,9 +38,9 @@ public class PointerTracker {
public interface UIProxy {
public void invalidateKey(Key key);
- public void showPreview(int keyIndex, PointerTracker tracker);
+ public void showKeyPreview(int keyIndex, PointerTracker tracker);
+ public void dismissKeyPreview(PointerTracker tracker);
public boolean hasDistinctMultitouch();
- public boolean isAccessibilityEnabled();
}
public final int mPointerId;
@@ -48,9 +50,7 @@ public class PointerTracker {
private final int mLongPressKeyTimeout;
private final int mLongPressShiftKeyTimeout;
- // Miscellaneous constants
- private static final int NOT_A_KEY = KeyDetector.NOT_A_KEY;
-
+ private final KeyboardView mKeyboardView;
private final UIProxy mProxy;
private final UIHandler mHandler;
private final KeyDetector mKeyDetector;
@@ -63,15 +63,12 @@ public class PointerTracker {
private final int mTouchNoiseThresholdDistanceSquared;
private Keyboard mKeyboard;
- private Key[] mKeys;
+ private List<Key> mKeys;
private int mKeyHysteresisDistanceSquared = -1;
private int mKeyQuarterWidthSquared;
private final PointerTrackerKeyState mKeyState;
- // true if accessibility is enabled in the parent keyboard
- private boolean mIsAccessibilityEnabled;
-
// true if keyboard layout has been changed.
private boolean mKeyboardLayoutHasBeenChanged;
@@ -87,8 +84,14 @@ public class PointerTracker {
// true if sliding key is allowed.
private boolean mIsAllowedSlidingKeyInput;
- // pressed key
- private int mPreviousKey = NOT_A_KEY;
+ // ignore modifier key if true
+ private boolean mIgnoreModifierKey;
+
+ // TODO: Remove these hacking variables
+ // true if this pointer is in sliding language switch
+ private boolean mIsInSlidingLanguageSwitch;
+ private int mSpaceKeyIndex;
+ private final SubtypeSwitcher mSubtypeSwitcher;
// Empty {@link KeyboardActionListener}
private static final KeyboardActionListener EMPTY_LISTENER = new KeyboardActionListener() {
@@ -106,18 +109,19 @@ public class PointerTracker {
public void onSwipeDown() {}
};
- public PointerTracker(int id, UIHandler handler, KeyDetector keyDetector, UIProxy proxy,
- Resources res) {
+ public PointerTracker(int id, KeyboardView keyboardView, UIHandler handler,
+ KeyDetector keyDetector, UIProxy proxy) {
if (proxy == null || handler == null || keyDetector == null)
throw new NullPointerException();
mPointerId = id;
+ mKeyboardView = keyboardView;
mProxy = proxy;
mHandler = handler;
mKeyDetector = keyDetector;
mKeyboardSwitcher = KeyboardSwitcher.getInstance();
mKeyState = new PointerTrackerKeyState(keyDetector);
- mIsAccessibilityEnabled = proxy.isAccessibilityEnabled();
mHasDistinctMultitouch = proxy.hasDistinctMultitouch();
+ final Resources res = mKeyboardView.getResources();
mConfigSlidingKeyInputEnabled = res.getBoolean(R.bool.config_sliding_key_input_enabled);
mDelayBeforeKeyRepeatStart = res.getInteger(R.integer.config_delay_before_key_repeat_start);
mLongPressKeyTimeout = res.getInteger(R.integer.config_long_press_key_timeout);
@@ -127,20 +131,21 @@ public class PointerTracker {
R.dimen.config_touch_noise_threshold_distance);
mTouchNoiseThresholdDistanceSquared = (int)(
touchNoiseThresholdDistance * touchNoiseThresholdDistance);
+ mSubtypeSwitcher = SubtypeSwitcher.getInstance();
}
public void setOnKeyboardActionListener(KeyboardActionListener listener) {
mListener = listener;
}
- public void setAccessibilityEnabled(boolean accessibilityEnabled) {
- mIsAccessibilityEnabled = accessibilityEnabled;
- }
-
// Returns true if keyboard has been changed by this callback.
private boolean callListenerOnPressAndCheckKeyboardLayoutChange(Key key, boolean withSliding) {
+ final boolean ignoreModifierKey = mIgnoreModifierKey && isModifierCode(key.mCode);
if (DEBUG_LISTENER)
- Log.d(TAG, "onPress : " + keyCodePrintable(key.mCode) + " sliding=" + withSliding);
+ Log.d(TAG, "onPress : " + keyCodePrintable(key.mCode) + " sliding=" + withSliding
+ + " ignoreModifier=" + ignoreModifierKey);
+ if (ignoreModifierKey)
+ return false;
if (key.mEnabled) {
mListener.onPress(key.mCode, withSliding);
final boolean keyboardLayoutHasBeenChanged = mKeyboardLayoutHasBeenChanged;
@@ -153,9 +158,13 @@ public class PointerTracker {
// Note that we need primaryCode argument because the keyboard may in shifted state and the
// primaryCode is different from {@link Key#mCode}.
private void callListenerOnCodeInput(Key key, int primaryCode, int[] keyCodes, int x, int y) {
+ final boolean ignoreModifierKey = mIgnoreModifierKey && isModifierCode(key.mCode);
if (DEBUG_LISTENER)
Log.d(TAG, "onCodeInput: " + keyCodePrintable(primaryCode)
- + " codes="+ Arrays.toString(keyCodes) + " x=" + x + " y=" + y);
+ + " codes="+ Arrays.toString(keyCodes) + " x=" + x + " y=" + y
+ + " ignoreModifier=" + ignoreModifierKey);
+ if (ignoreModifierKey)
+ return;
if (key.mEnabled)
mListener.onCodeInput(primaryCode, keyCodes, x, y);
}
@@ -170,8 +179,12 @@ public class PointerTracker {
// Note that we need primaryCode argument because the keyboard may in shifted state and the
// primaryCode is different from {@link Key#mCode}.
private void callListenerOnRelease(Key key, int primaryCode, boolean withSliding) {
+ final boolean ignoreModifierKey = mIgnoreModifierKey && isModifierCode(key.mCode);
if (DEBUG_LISTENER)
- Log.d(TAG, "onRelease : " + keyCodePrintable(primaryCode) + " sliding=" + withSliding);
+ Log.d(TAG, "onRelease : " + keyCodePrintable(primaryCode) + " sliding="
+ + withSliding + " ignoreModifier=" + ignoreModifierKey);
+ if (ignoreModifierKey)
+ return;
if (key.mEnabled)
mListener.onRelease(primaryCode, withSliding);
}
@@ -182,11 +195,11 @@ public class PointerTracker {
mListener.onCancelInput();
}
- public void setKeyboard(Keyboard keyboard, Key[] keys, float keyHysteresisDistance) {
- if (keyboard == null || keys == null || keyHysteresisDistance < 0)
+ public void setKeyboard(Keyboard keyboard, float keyHysteresisDistance) {
+ if (keyboard == null || keyHysteresisDistance < 0)
throw new IllegalArgumentException();
mKeyboard = keyboard;
- mKeys = keys;
+ mKeys = keyboard.getKeys();
mKeyHysteresisDistanceSquared = (int)(keyHysteresisDistance * keyHysteresisDistance);
final int keyQuarterWidth = keyboard.getKeyWidth() / 4;
mKeyQuarterWidthSquared = keyQuarterWidth * keyQuarterWidth;
@@ -199,11 +212,11 @@ public class PointerTracker {
}
private boolean isValidKeyIndex(int keyIndex) {
- return keyIndex >= 0 && keyIndex < mKeys.length;
+ return keyIndex >= 0 && keyIndex < mKeys.size();
}
public Key getKey(int keyIndex) {
- return isValidKeyIndex(keyIndex) ? mKeys[keyIndex] : null;
+ return isValidKeyIndex(keyIndex) ? mKeys.get(keyIndex) : null;
}
private static boolean isModifierCode(int primaryCode) {
@@ -229,34 +242,33 @@ public class PointerTracker {
return key != null && key.mCode == Keyboard.CODE_SHIFT;
}
+ public int getKeyIndexOn(int x, int y) {
+ return mKeyDetector.getKeyIndexAndNearbyCodes(x, y, null);
+ }
+
public boolean isSpaceKey(int keyIndex) {
Key key = getKey(keyIndex);
return key != null && key.mCode == Keyboard.CODE_SPACE;
}
- public void releaseKey() {
- updateKeyGraphics(NOT_A_KEY);
+ public void setReleasedKeyGraphics() {
+ setReleasedKeyGraphics(mKeyState.getKeyIndex());
}
- private void updateKeyGraphics(int keyIndex) {
- int oldKeyIndex = mPreviousKey;
- mPreviousKey = keyIndex;
- if (keyIndex != oldKeyIndex) {
- if (isValidKeyIndex(oldKeyIndex)) {
- // if new key index is not a key, old key was just released inside of the key.
- final boolean inside = (keyIndex == NOT_A_KEY);
- mKeys[oldKeyIndex].onReleased(inside);
- mProxy.invalidateKey(mKeys[oldKeyIndex]);
- }
- if (isValidKeyIndex(keyIndex)) {
- mKeys[keyIndex].onPressed();
- mProxy.invalidateKey(mKeys[keyIndex]);
- }
+ private void setReleasedKeyGraphics(int keyIndex) {
+ final Key key = getKey(keyIndex);
+ if (key != null) {
+ key.onReleased();
+ mProxy.invalidateKey(key);
}
}
- public void setAlreadyProcessed() {
- mKeyAlreadyProcessed = true;
+ private void setPressedKeyGraphics(int keyIndex) {
+ final Key key = getKey(keyIndex);
+ if (key != null && key.mEnabled) {
+ key.onPressed();
+ mProxy.invalidateKey(key);
+ }
}
private void checkAssertion(PointerTrackerQueue queue) {
@@ -302,7 +314,7 @@ public class PointerTracker {
if (DEBUG_MODE)
Log.w(TAG, "onDownEvent: ignore potential noise: time=" + deltaT
+ " distance=" + distanceSquared);
- setAlreadyProcessed();
+ mKeyAlreadyProcessed = true;
return;
}
}
@@ -321,32 +333,33 @@ public class PointerTracker {
private void onDownEventInternal(int x, int y, long eventTime) {
int keyIndex = mKeyState.onDownKey(x, y, eventTime);
// Sliding key is allowed when 1) enabled by configuration, 2) this pointer starts sliding
- // from modifier key, 3) this pointer is on mini-keyboard, or 4) accessibility is enabled.
+ // from modifier key, or 3) this pointer is on mini-keyboard.
mIsAllowedSlidingKeyInput = mConfigSlidingKeyInputEnabled || isModifierInternal(keyIndex)
- || mKeyDetector instanceof MiniKeyboardKeyDetector
- || mIsAccessibilityEnabled;
+ || mKeyDetector instanceof MiniKeyboardKeyDetector;
mKeyboardLayoutHasBeenChanged = false;
mKeyAlreadyProcessed = false;
mIsRepeatableKey = false;
mIsInSlidingKeyInput = false;
+ mIsInSlidingLanguageSwitch = false;
+ mIgnoreModifierKey = false;
if (isValidKeyIndex(keyIndex)) {
// This onPress call may have changed keyboard layout. Those cases are detected at
// {@link #setKeyboard}. In those cases, we should update keyIndex according to the new
// keyboard layout.
- if (callListenerOnPressAndCheckKeyboardLayoutChange(mKeys[keyIndex], false))
+ if (callListenerOnPressAndCheckKeyboardLayoutChange(getKey(keyIndex), false))
keyIndex = mKeyState.onDownKey(x, y, eventTime);
- }
- if (isValidKeyIndex(keyIndex)) {
- // Accessibility disables key repeat because users may need to pause on a key to hear
- // its spoken description.
- if (mKeys[keyIndex].mRepeatable && !mIsAccessibilityEnabled) {
- repeatKey(keyIndex);
- mHandler.startKeyRepeatTimer(mDelayBeforeKeyRepeatStart, keyIndex, this);
- mIsRepeatableKey = true;
- }
+
+ startRepeatKey(keyIndex);
startLongPressTimer(keyIndex);
+ showKeyPreview(keyIndex);
+ setPressedKeyGraphics(keyIndex);
}
- showKeyPreviewAndUpdateKeyGraphics(keyIndex);
+ }
+
+ private void startSlidingKeyInput(Key key) {
+ if (!mIsInSlidingKeyInput)
+ mIgnoreModifierKey = isModifierCode(key.mCode);
+ mIsInSlidingKeyInput = true;
}
public void onMoveEvent(int x, int y, long eventTime, PointerTrackerQueue queue) {
@@ -357,10 +370,17 @@ public class PointerTracker {
return;
final PointerTrackerKeyState keyState = mKeyState;
+ // TODO: Remove this hacking code
+ if (mIsInSlidingLanguageSwitch) {
+ ((LatinKeyboard)mKeyboard).updateSpacebarPreviewIcon(x - keyState.getKeyX());
+ showKeyPreview(mSpaceKeyIndex);
+ return;
+ }
final int lastX = keyState.getLastX();
final int lastY = keyState.getLastY();
+ final int oldKeyIndex = keyState.getKeyIndex();
+ final Key oldKey = getKey(oldKeyIndex);
int keyIndex = keyState.onMoveKey(x, y);
- final Key oldKey = getKey(keyState.getKeyIndex());
if (isValidKeyIndex(keyIndex)) {
if (oldKey == null) {
// The pointer has been slid in to the new key, but the finger was not on any keys.
@@ -372,13 +392,17 @@ public class PointerTracker {
keyIndex = keyState.onMoveKey(x, y);
keyState.onMoveToNewKey(keyIndex, x, y);
startLongPressTimer(keyIndex);
- } else if (!isMinorMoveBounce(x, y, keyIndex)) {
+ showKeyPreview(keyIndex);
+ setPressedKeyGraphics(keyIndex);
+ } else if (isMajorEnoughMoveToBeOnNewKey(x, y, keyIndex)) {
// The pointer has been slid in to the new key from the previous key, we must call
// onRelease() first to notify that the previous key has been released, then call
// onPress() to notify that the new key is being pressed.
- mIsInSlidingKeyInput = true;
+ setReleasedKeyGraphics(oldKeyIndex);
callListenerOnRelease(oldKey, oldKey.mCode, true);
- mHandler.cancelLongPressTimers();
+ startSlidingKeyInput(oldKey);
+ mHandler.cancelKeyTimers();
+ startRepeatKey(keyIndex);
if (mIsAllowedSlidingKeyInput) {
// This onPress call may have changed keyboard layout. Those cases are detected
// at {@link #setKeyboard}. In those cases, we should update keyIndex according
@@ -387,6 +411,8 @@ public class PointerTracker {
keyIndex = keyState.onMoveKey(x, y);
keyState.onMoveToNewKey(keyIndex, x, y);
startLongPressTimer(keyIndex);
+ setPressedKeyGraphics(keyIndex);
+ showKeyPreview(keyIndex);
} else {
// HACK: On some devices, quick successive touches may be translated to sudden
// move by touch panel firmware. This hack detects the case and translates the
@@ -398,32 +424,50 @@ public class PointerTracker {
if (DEBUG_MODE)
Log.w(TAG, String.format("onMoveEvent: sudden move is translated to "
+ "up[%d,%d]/down[%d,%d] events", lastX, lastY, x, y));
- onUpEventInternal(lastX, lastY, eventTime);
+ onUpEventInternal(lastX, lastY, eventTime, true);
onDownEventInternal(x, y, eventTime);
} else {
- setAlreadyProcessed();
- showKeyPreviewAndUpdateKeyGraphics(NOT_A_KEY);
+ mKeyAlreadyProcessed = true;
+ dismissKeyPreview();
+ setReleasedKeyGraphics(oldKeyIndex);
+ }
+ }
+ }
+ // TODO: Remove this hack code
+ else if (isSpaceKey(keyIndex) && !mIsInSlidingLanguageSwitch
+ && mKeyboard instanceof LatinKeyboard) {
+ final LatinKeyboard keyboard = ((LatinKeyboard)mKeyboard);
+ if (mSubtypeSwitcher.useSpacebarLanguageSwitcher()
+ && mSubtypeSwitcher.getEnabledKeyboardLocaleCount() > 1) {
+ final int diff = x - keyState.getKeyX();
+ if (keyboard.shouldTriggerSpacebarSlidingLanguageSwitch(diff)) {
+ // Detect start sliding language switch.
+ mIsInSlidingLanguageSwitch = true;
+ mSpaceKeyIndex = keyIndex;
+ keyboard.updateSpacebarPreviewIcon(diff);
+ // Display spacebar slide language switcher.
+ showKeyPreview(keyIndex);
+ if (queue != null)
+ queue.releaseAllPointersExcept(this, eventTime, true);
}
- return;
}
}
} else {
- if (oldKey != null && !isMinorMoveBounce(x, y, keyIndex)) {
+ if (oldKey != null && isMajorEnoughMoveToBeOnNewKey(x, y, keyIndex)) {
// The pointer has been slid out from the previous key, we must call onRelease() to
// notify that the previous key has been released.
- mIsInSlidingKeyInput = true;
+ setReleasedKeyGraphics(oldKeyIndex);
callListenerOnRelease(oldKey, oldKey.mCode, true);
+ startSlidingKeyInput(oldKey);
mHandler.cancelLongPressTimers();
if (mIsAllowedSlidingKeyInput) {
- keyState.onMoveToNewKey(keyIndex, x ,y);
+ keyState.onMoveToNewKey(keyIndex, x, y);
} else {
- setAlreadyProcessed();
- showKeyPreviewAndUpdateKeyGraphics(NOT_A_KEY);
- return;
+ mKeyAlreadyProcessed = true;
+ dismissKeyPreview();
}
}
}
- showKeyPreviewAndUpdateKeyGraphics(mKeyState.getKeyIndex());
}
public void onUpEvent(int x, int y, long eventTime, PointerTrackerQueue queue) {
@@ -435,42 +479,69 @@ public class PointerTracker {
if (isModifier()) {
// Before processing an up event of modifier key, all pointers already being
// tracked should be released.
- queue.releaseAllPointersExcept(this, eventTime);
+ queue.releaseAllPointersExcept(this, eventTime, true);
} else {
queue.releaseAllPointersOlderThan(this, eventTime);
}
queue.remove(this);
}
- onUpEventInternal(x, y, eventTime);
+ onUpEventInternal(x, y, eventTime, true);
}
- public void onUpEventForRelease(int x, int y, long eventTime) {
- onUpEventInternal(x, y, eventTime);
+ // Let this pointer tracker know that one of newer-than-this pointer trackers got an up event.
+ // This pointer tracker needs to keep the key top graphics "pressed", but needs to get a
+ // "virtual" up event.
+ public void onPhantomUpEvent(int x, int y, long eventTime, boolean updateReleasedKeyGraphics) {
+ if (DEBUG_EVENT)
+ printTouchEvent("onPhntEvent:", x, y, eventTime);
+ onUpEventInternal(x, y, eventTime, updateReleasedKeyGraphics);
+ mKeyAlreadyProcessed = true;
}
- private void onUpEventInternal(int pointX, int pointY, long eventTime) {
- int x = pointX;
- int y = pointY;
+ private void onUpEventInternal(int x, int y, long eventTime,
+ boolean updateReleasedKeyGraphics) {
mHandler.cancelKeyTimers();
- mHandler.cancelPopupPreview();
- showKeyPreviewAndUpdateKeyGraphics(NOT_A_KEY);
+ mHandler.cancelShowKeyPreview(this);
mIsInSlidingKeyInput = false;
+ final PointerTrackerKeyState keyState = mKeyState;
+ final int keyX, keyY;
+ if (isMajorEnoughMoveToBeOnNewKey(x, y, keyState.onMoveKey(x, y))) {
+ keyX = x;
+ keyY = y;
+ } else {
+ // Use previous fixed key coordinates.
+ keyX = keyState.getKeyX();
+ keyY = keyState.getKeyY();
+ }
+ final int keyIndex = keyState.onUpKey(keyX, keyY, eventTime);
+ dismissKeyPreview();
+ if (updateReleasedKeyGraphics)
+ setReleasedKeyGraphics(keyIndex);
if (mKeyAlreadyProcessed)
return;
- final PointerTrackerKeyState keyState = mKeyState;
- int keyIndex = keyState.onUpKey(x, y, eventTime);
- if (isMinorMoveBounce(x, y, keyIndex)) {
- // Use previous fixed key index and coordinates.
- keyIndex = keyState.getKeyIndex();
- x = keyState.getKeyX();
- y = keyState.getKeyY();
+ // TODO: Remove this hacking code
+ if (mIsInSlidingLanguageSwitch) {
+ setReleasedKeyGraphics(mSpaceKeyIndex);
+ final int languageDir = ((LatinKeyboard)mKeyboard).getLanguageChangeDirection();
+ if (languageDir != 0) {
+ final int code = (languageDir == 1)
+ ? LatinKeyboard.CODE_NEXT_LANGUAGE : LatinKeyboard.CODE_PREV_LANGUAGE;
+ // This will change keyboard layout.
+ mListener.onCodeInput(code, new int[] {code}, keyX, keyY);
+ }
+ mIsInSlidingLanguageSwitch = false;
+ ((LatinKeyboard)mKeyboard).setSpacebarSlidingLanguageSwitchDiff(0);
+ return;
}
if (!mIsRepeatableKey) {
- detectAndSendKey(keyIndex, x, y);
+ detectAndSendKey(keyIndex, keyX, keyY);
}
+ }
- if (isValidKeyIndex(keyIndex))
- mProxy.invalidateKey(mKeys[keyIndex]);
+ public void onLongPressed(PointerTrackerQueue queue) {
+ mKeyAlreadyProcessed = true;
+ if (queue != null)
+ queue.remove(this);
}
public void onCancelEvent(int x, int y, long eventTime, PointerTrackerQueue queue) {
@@ -478,22 +549,34 @@ public class PointerTracker {
if (DEBUG_EVENT)
printTouchEvent("onCancelEvt:", x, y, eventTime);
- if (queue != null)
+ if (queue != null) {
+ queue.releaseAllPointersExcept(this, eventTime, true);
queue.remove(this);
+ }
onCancelEventInternal();
}
private void onCancelEventInternal() {
mHandler.cancelKeyTimers();
- mHandler.cancelPopupPreview();
- showKeyPreviewAndUpdateKeyGraphics(NOT_A_KEY);
+ mHandler.cancelShowKeyPreview(this);
+ dismissKeyPreview();
+ setReleasedKeyGraphics(mKeyState.getKeyIndex());
mIsInSlidingKeyInput = false;
- int keyIndex = mKeyState.getKeyIndex();
- if (isValidKeyIndex(keyIndex))
- mProxy.invalidateKey(mKeys[keyIndex]);
}
- public void repeatKey(int keyIndex) {
+ private void startRepeatKey(int keyIndex) {
+ final Key key = getKey(keyIndex);
+ if (key != null && key.mRepeatable) {
+ dismissKeyPreview();
+ onRepeatKey(keyIndex);
+ mHandler.startKeyRepeatTimer(mDelayBeforeKeyRepeatStart, keyIndex, this);
+ mIsRepeatableKey = true;
+ } else {
+ mIsRepeatableKey = false;
+ }
+ }
+
+ public void onRepeatKey(int keyIndex) {
Key key = getKey(keyIndex);
if (key != null) {
detectAndSendKey(keyIndex, key.mX, key.mY);
@@ -512,38 +595,43 @@ public class PointerTracker {
return mKeyState.getDownTime();
}
- private boolean isMinorMoveBounce(int x, int y, int newKey) {
+ private boolean isMajorEnoughMoveToBeOnNewKey(int x, int y, int newKey) {
if (mKeys == null || mKeyHysteresisDistanceSquared < 0)
throw new IllegalStateException("keyboard and/or hysteresis not set");
int curKey = mKeyState.getKeyIndex();
if (newKey == curKey) {
- return true;
+ return false;
} else if (isValidKeyIndex(curKey)) {
- return mKeys[curKey].squaredDistanceToEdge(x, y) < mKeyHysteresisDistanceSquared;
+ return mKeys.get(curKey).squaredDistanceToEdge(x, y) >= mKeyHysteresisDistanceSquared;
} else {
- return false;
+ return true;
}
}
- private void showKeyPreviewAndUpdateKeyGraphics(int keyIndex) {
- updateKeyGraphics(keyIndex);
- // The modifier key, such as shift key, should not be shown as preview when multi-touch is
- // supported. On the other hand, if multi-touch is not supported, the modifier key should
- // be shown as preview. If accessibility is turned on, the modifier key should be shown as
- // preview.
- if (mHasDistinctMultitouch && isModifier() && !mIsAccessibilityEnabled) {
- mProxy.showPreview(NOT_A_KEY, this);
- } else {
- mProxy.showPreview(keyIndex, this);
- }
+ // The modifier key, such as shift key, should not show its key preview.
+ private boolean isKeyPreviewNotRequired(int keyIndex) {
+ final Key key = getKey(keyIndex);
+ if (!key.mEnabled)
+ return true;
+ // Such as spacebar sliding language switch.
+ if (mKeyboard.needSpacebarPreview(keyIndex))
+ return false;
+ final int code = key.mCode;
+ return isModifierCode(code) || code == Keyboard.CODE_DELETE
+ || code == Keyboard.CODE_ENTER || code == Keyboard.CODE_SPACE;
}
- private void startLongPressTimer(int keyIndex) {
- // Accessibility disables long press because users are likely to need to pause on a key
- // for an unspecified duration in order to hear the key's spoken description.
- if (mIsAccessibilityEnabled) {
+ private void showKeyPreview(int keyIndex) {
+ if (isKeyPreviewNotRequired(keyIndex))
return;
- }
+ mProxy.showKeyPreview(keyIndex, this);
+ }
+
+ private void dismissKeyPreview() {
+ mProxy.dismissKeyPreview(this);
+ }
+
+ private void startLongPressTimer(int keyIndex) {
Key key = getKey(keyIndex);
if (key.mCode == Keyboard.CODE_SHIFT) {
mHandler.startLongPressShiftTimer(mLongPressShiftKeyTimeout, keyIndex, this);
@@ -552,7 +640,7 @@ public class PointerTracker {
// We need not start long press timer on the key which has manual temporary upper case
// code defined and the keyboard is in manual temporary upper case mode.
return;
- } else if (mKeyboardSwitcher.isInMomentaryAutoModeSwitchState()) {
+ } else if (mKeyboardSwitcher.isInMomentarySwitchState()) {
// We use longer timeout for sliding finger input started from the symbols mode key.
mHandler.startLongPressTimer(mLongPressKeyTimeout * 3, keyIndex, this);
} else {
diff --git a/java/src/com/android/inputmethod/keyboard/PointerTrackerKeyState.java b/java/src/com/android/inputmethod/keyboard/PointerTrackerKeyState.java
index 64ba80a04..eecbb26f3 100644
--- a/java/src/com/android/inputmethod/keyboard/PointerTrackerKeyState.java
+++ b/java/src/com/android/inputmethod/keyboard/PointerTrackerKeyState.java
@@ -92,6 +92,7 @@ package com.android.inputmethod.keyboard;
public int onUpKey(int x, int y, long eventTime) {
mUpTime = eventTime;
+ mKeyIndex = KeyDetector.NOT_A_KEY;
return onMoveKeyInternal(x, y);
}
}
diff --git a/java/src/com/android/inputmethod/keyboard/PointerTrackerQueue.java b/java/src/com/android/inputmethod/keyboard/PointerTrackerQueue.java
index 01d9b5d2c..9e287c67d 100644
--- a/java/src/com/android/inputmethod/keyboard/PointerTrackerQueue.java
+++ b/java/src/com/android/inputmethod/keyboard/PointerTrackerQueue.java
@@ -29,29 +29,28 @@ public class PointerTrackerQueue {
if (mQueue.lastIndexOf(tracker) < 0) {
return;
}
- LinkedList<PointerTracker> queue = mQueue;
+ final LinkedList<PointerTracker> queue = mQueue;
int oldestPos = 0;
for (PointerTracker t = queue.get(oldestPos); t != tracker; t = queue.get(oldestPos)) {
if (t.isModifier()) {
oldestPos++;
} else {
- t.onUpEventForRelease(t.getLastX(), t.getLastY(), eventTime);
- t.setAlreadyProcessed();
+ t.onPhantomUpEvent(t.getLastX(), t.getLastY(), eventTime, true);
queue.remove(oldestPos);
}
}
}
public void releaseAllPointers(long eventTime) {
- releaseAllPointersExcept(null, eventTime);
+ releaseAllPointersExcept(null, eventTime, true);
}
- public void releaseAllPointersExcept(PointerTracker tracker, long eventTime) {
+ public void releaseAllPointersExcept(PointerTracker tracker, long eventTime,
+ boolean updateReleasedKeyGraphics) {
for (PointerTracker t : mQueue) {
if (t == tracker)
continue;
- t.onUpEventForRelease(t.getLastX(), t.getLastY(), eventTime);
- t.setAlreadyProcessed();
+ t.onPhantomUpEvent(t.getLastX(), t.getLastY(), eventTime, updateReleasedKeyGraphics);
}
mQueue.clear();
if (tracker != null)
diff --git a/java/src/com/android/inputmethod/keyboard/PopupMiniKeyboardView.java b/java/src/com/android/inputmethod/keyboard/PopupMiniKeyboardView.java
new file mode 100644
index 000000000..fa2aa874c
--- /dev/null
+++ b/java/src/com/android/inputmethod/keyboard/PopupMiniKeyboardView.java
@@ -0,0 +1,125 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.inputmethod.keyboard;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.os.SystemClock;
+import android.util.AttributeSet;
+import android.view.Gravity;
+import android.view.MotionEvent;
+import android.view.View;
+import android.widget.PopupWindow;
+
+import com.android.inputmethod.latin.R;
+
+/**
+ * A view that renders a virtual {@link MiniKeyboard}. It handles rendering of keys and detecting
+ * key presses and touch movements.
+ */
+public class PopupMiniKeyboardView extends KeyboardView implements PopupPanel {
+ private final int[] mCoordinates = new int[2];
+ private final boolean mConfigShowMiniKeyboardAtTouchedPoint;
+
+ private int mOriginX;
+ private int mOriginY;
+ private int mTrackerId;
+ private long mDownTime;
+
+ public PopupMiniKeyboardView(Context context, AttributeSet attrs) {
+ this(context, attrs, R.attr.popupMiniKeyboardViewStyle);
+ }
+
+ public PopupMiniKeyboardView(Context context, AttributeSet attrs, int defStyle) {
+ super(context, attrs, defStyle);
+
+ final Resources res = context.getResources();
+ mConfigShowMiniKeyboardAtTouchedPoint = res.getBoolean(
+ R.bool.config_show_mini_keyboard_at_touched_point);
+ // Override default ProximityKeyDetector.
+ mKeyDetector = new MiniKeyboardKeyDetector(res.getDimension(
+ R.dimen.mini_keyboard_slide_allowance));
+ // Remove gesture detector on mini-keyboard
+ mGestureDetector = null;
+ setKeyPreviewPopupEnabled(false, 0);
+ }
+
+ @Override
+ public void setKeyPreviewPopupEnabled(boolean previewEnabled, int delay) {
+ // Mini keyboard needs no pop-up key preview displayed, so we pass always false with a
+ // delay of 0. The delay does not matter actually since the popup is not shown anyway.
+ super.setKeyPreviewPopupEnabled(false, 0);
+ }
+
+ @Override
+ public void showPanel(KeyboardView parentKeyboardView, Key parentKey,
+ PointerTracker tracker, int keyPreviewY, PopupWindow window) {
+ final View container = (View)getParent();
+ final MiniKeyboard miniKeyboard = (MiniKeyboard)getKeyboard();
+ final Keyboard parentKeyboard = parentKeyboardView.getKeyboard();
+
+ parentKeyboardView.getLocationInWindow(mCoordinates);
+ final int pointX = (mConfigShowMiniKeyboardAtTouchedPoint) ? tracker.getLastX()
+ : parentKey.mX + parentKey.mWidth / 2;
+ final int pointY = parentKey.mY;
+ final int miniKeyboardX = pointX - miniKeyboard.getDefaultCoordX()
+ - container.getPaddingLeft()
+ + parentKeyboardView.getPaddingLeft() + mCoordinates[0];
+ final int miniKeyboardY = pointY - parentKeyboard.getVerticalGap()
+ - (container.getMeasuredHeight() - container.getPaddingBottom())
+ + parentKeyboardView.getPaddingTop() + mCoordinates[1];
+ final int x = miniKeyboardX;
+ final int y = parentKeyboardView.isKeyPreviewPopupEnabled() &&
+ miniKeyboard.isOneRowKeyboard() && keyPreviewY >= 0 ? keyPreviewY : miniKeyboardY;
+
+ if (miniKeyboard.setShifted(parentKeyboard.isShiftedOrShiftLocked())) {
+ invalidateAllKeys();
+ }
+ window.setContentView(container);
+ window.setWidth(container.getMeasuredWidth());
+ window.setHeight(container.getMeasuredHeight());
+ window.showAtLocation(parentKeyboardView, Gravity.NO_GRAVITY, x, y);
+
+ mOriginX = x + container.getPaddingLeft() - mCoordinates[0];
+ mOriginY = y + container.getPaddingTop() - mCoordinates[1];
+ mTrackerId = tracker.mPointerId;
+ mDownTime = SystemClock.uptimeMillis();
+
+ // Inject down event on the key to mini keyboard.
+ final MotionEvent downEvent = translateMotionEvent(MotionEvent.ACTION_DOWN, pointX,
+ pointY + parentKey.mHeight / 2, mDownTime);
+ onTouchEvent(downEvent);
+ downEvent.recycle();
+ }
+
+ private MotionEvent translateMotionEvent(int action, float x, float y, long eventTime) {
+ return MotionEvent.obtain(mDownTime, eventTime, action, x - mOriginX, y - mOriginY, 0);
+ }
+
+ @Override
+ public boolean onTouchEvent(MotionEvent me) {
+ final int index = me.getActionIndex();
+ final int id = me.getPointerId(index);
+ if (id == mTrackerId) {
+ final MotionEvent translated = translateMotionEvent(me.getAction(), me.getX(index),
+ me.getY(index), me.getEventTime());
+ super.onTouchEvent(translated);
+ translated.recycle();
+ }
+ return true;
+ }
+}
diff --git a/java/src/com/android/inputmethod/keyboard/PopupPanel.java b/java/src/com/android/inputmethod/keyboard/PopupPanel.java
new file mode 100644
index 000000000..6f2b16148
--- /dev/null
+++ b/java/src/com/android/inputmethod/keyboard/PopupPanel.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.inputmethod.keyboard;
+
+import android.view.MotionEvent;
+import android.widget.PopupWindow;
+
+public interface PopupPanel {
+ /**
+ * Show popup panel.
+ * @param parentKeyboardView the parent KeyboardView that has the parent key.
+ * @param parentKey the parent key that is the source of this popup panel
+ * @param tracker the pointer tracker that pressesd the parent key
+ * @param keyPreviewY the Y-coordinate of key preview
+ * @param window PopupWindow to be used to show this popup panel
+ */
+ public void showPanel(KeyboardView parentKeyboardView, Key parentKey,
+ PointerTracker tracker, int keyPreviewY, PopupWindow window);
+
+ /**
+ * Check if the pointer is in siding key input mode.
+ * @return true if the pointer is sliding key input mode.
+ */
+ public boolean isInSlidingKeyInput();
+
+ /**
+ * The motion event handler.
+ * @param me the MotionEvent to be processed.
+ * @return true if the motion event is processed and should be consumed.
+ */
+ public boolean onTouchEvent(MotionEvent me);
+}
diff --git a/java/src/com/android/inputmethod/keyboard/ProximityKeyDetector.java b/java/src/com/android/inputmethod/keyboard/ProximityKeyDetector.java
deleted file mode 100644
index e2ff8c48e..000000000
--- a/java/src/com/android/inputmethod/keyboard/ProximityKeyDetector.java
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-
-package com.android.inputmethod.keyboard;
-
-import android.util.Log;
-
-import java.util.Arrays;
-
-public class ProximityKeyDetector extends KeyDetector {
- private static final String TAG = ProximityKeyDetector.class.getSimpleName();
- private static final boolean DEBUG = false;
-
- private static final int MAX_NEARBY_KEYS = 12;
-
- // working area
- private final int[] mDistances = new int[MAX_NEARBY_KEYS];
- private final int[] mIndices = new int[MAX_NEARBY_KEYS];
-
- @Override
- protected int getMaxNearbyKeys() {
- return MAX_NEARBY_KEYS;
- }
-
- private void initializeNearbyKeys() {
- Arrays.fill(mDistances, Integer.MAX_VALUE);
- Arrays.fill(mIndices, NOT_A_KEY);
- }
-
- /**
- * Insert the key into nearby keys buffer and sort nearby keys by ascending order of distance.
- *
- * @param keyIndex index of the key.
- * @param distance distance between the key's edge and user touched point.
- * @param isOnKey true if the point is on the key.
- * @return order of the key in the nearby buffer, 0 if it is the nearest key.
- */
- private int sortNearbyKeys(int keyIndex, int distance, boolean isOnKey) {
- final int[] distances = mDistances;
- final int[] indices = mIndices;
- for (int insertPos = 0; insertPos < distances.length; insertPos++) {
- final int comparingDistance = distances[insertPos];
- if (distance < comparingDistance || (distance == comparingDistance && isOnKey)) {
- final int nextPos = insertPos + 1;
- if (nextPos < distances.length) {
- System.arraycopy(distances, insertPos, distances, nextPos,
- distances.length - nextPos);
- System.arraycopy(indices, insertPos, indices, nextPos,
- indices.length - nextPos);
- }
- distances[insertPos] = distance;
- indices[insertPos] = keyIndex;
- return insertPos;
- }
- }
- return distances.length;
- }
-
- private void getNearbyKeyCodes(final int[] allCodes) {
- final Key[] keys = getKeys();
- final int[] indices = mIndices;
-
- // allCodes[0] should always have the key code even if it is a non-letter key.
- if (indices[0] == NOT_A_KEY) {
- allCodes[0] = NOT_A_CODE;
- return;
- }
-
- int numCodes = 0;
- for (int j = 0; j < indices.length && numCodes < allCodes.length; j++) {
- final int index = indices[j];
- if (index == NOT_A_KEY)
- break;
- final int code = keys[index].mCode;
- // filter out a non-letter key from nearby keys
- if (code < Keyboard.CODE_SPACE)
- continue;
- allCodes[numCodes++] = code;
- }
- }
-
- @Override
- public int getKeyIndexAndNearbyCodes(int x, int y, final int[] allCodes) {
- final Key[] keys = getKeys();
- final int touchX = getTouchX(x);
- final int touchY = getTouchY(y);
-
- initializeNearbyKeys();
- int primaryIndex = NOT_A_KEY;
- for (final int index : mKeyboard.getNearestKeys(touchX, touchY)) {
- final Key key = keys[index];
- final boolean isInside = key.isInside(touchX, touchY);
- final int distance = key.squaredDistanceToEdge(touchX, touchY);
- if (isInside || (mProximityCorrectOn && distance < mProximityThresholdSquare)) {
- final int insertedPosition = sortNearbyKeys(index, distance, isInside);
- if (insertedPosition == 0 && isInside)
- primaryIndex = index;
- }
- }
-
- if (allCodes != null && allCodes.length > 0) {
- getNearbyKeyCodes(allCodes);
- if (DEBUG) {
- Log.d(TAG, "x=" + x + " y=" + y
- + " primary="
- + (primaryIndex == NOT_A_KEY ? "none" : keys[primaryIndex].mCode)
- + " codes=" + Arrays.toString(allCodes));
- }
- }
-
- return primaryIndex;
- }
-}
diff --git a/java/src/com/android/inputmethod/keyboard/SlidingLocaleDrawable.java b/java/src/com/android/inputmethod/keyboard/SlidingLocaleDrawable.java
index ad8b0d623..5cf31cb14 100644
--- a/java/src/com/android/inputmethod/keyboard/SlidingLocaleDrawable.java
+++ b/java/src/com/android/inputmethod/keyboard/SlidingLocaleDrawable.java
@@ -23,6 +23,7 @@ import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
+import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
@@ -37,7 +38,7 @@ import android.view.ViewConfiguration;
* movement on the spacebar.
*/
public class SlidingLocaleDrawable extends Drawable {
-
+ private static final int SLIDE_SPEED_MULTIPLIER_RATIO = 150;
private final Context mContext;
private final Resources mRes;
private final int mWidth;
@@ -63,9 +64,8 @@ public class SlidingLocaleDrawable extends Drawable {
mHeight = height;
final TextPaint textPaint = new TextPaint();
textPaint.setTextSize(getTextSizeFromTheme(android.R.style.TextAppearance_Medium, 18));
- textPaint.setColor(R.color.latinkeyboard_transparent);
+ textPaint.setColor(Color.TRANSPARENT);
textPaint.setTextAlign(Align.CENTER);
- textPaint.setAlpha(LatinKeyboard.OPACITY_FULLY_OPAQUE);
textPaint.setAntiAlias(true);
mTextPaint = textPaint;
mMiddleX = (mWidth - mBackground.getIntrinsicWidth()) / 2;
@@ -90,7 +90,7 @@ public class SlidingLocaleDrawable extends Drawable {
mCurrentLanguage = null;
return;
}
- mDiff = diff;
+ mDiff = Math.max(diff, diff * SLIDE_SPEED_MULTIPLIER_RATIO / 100);
if (mDiff > mWidth) mDiff = mWidth;
if (mDiff < -mWidth) mDiff = -mWidth;
if (Math.abs(mDiff) > mThreshold) mHitThreshold = true;
diff --git a/java/src/com/android/inputmethod/latin/AccessibilityUtils.java b/java/src/com/android/inputmethod/latin/AccessibilityUtils.java
deleted file mode 100644
index cd3f9e0ad..000000000
--- a/java/src/com/android/inputmethod/latin/AccessibilityUtils.java
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.inputmethod.latin;
-
-import android.content.Context;
-import android.content.SharedPreferences;
-import android.content.res.TypedArray;
-import android.view.accessibility.AccessibilityEvent;
-import android.view.accessibility.AccessibilityManager;
-
-import com.android.inputmethod.keyboard.Keyboard;
-import com.android.inputmethod.keyboard.KeyboardSwitcher;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Utility functions for accessibility support.
- */
-public class AccessibilityUtils {
- /** Shared singleton instance. */
- private static final AccessibilityUtils sInstance = new AccessibilityUtils();
- private /* final */ LatinIME mService;
- private /* final */ AccessibilityManager mAccessibilityManager;
- private /* final */ Map<Integer, CharSequence> mDescriptions;
-
- /**
- * Returns a shared instance of AccessibilityUtils.
- *
- * @return A shared instance of AccessibilityUtils.
- */
- public static AccessibilityUtils getInstance() {
- return sInstance;
- }
-
- /**
- * Initializes (or re-initializes) the shared instance of AccessibilityUtils
- * with the specified parent service and preferences.
- *
- * @param service The parent input method service.
- * @param prefs The parent preferences.
- */
- public static void init(LatinIME service, SharedPreferences prefs) {
- sInstance.initialize(service, prefs);
- }
-
- private AccessibilityUtils() {
- // This class is not publicly instantiable.
- }
-
- /**
- * Initializes (or re-initializes) with the specified parent service and
- * preferences.
- *
- * @param service The parent input method service.
- * @param prefs The parent preferences.
- */
- private void initialize(LatinIME service, SharedPreferences prefs) {
- mService = service;
- mAccessibilityManager = (AccessibilityManager) service.getSystemService(
- Context.ACCESSIBILITY_SERVICE);
- mDescriptions = null;
- }
-
- /**
- * Returns true if accessibility is enabled.
- *
- * @return {@code true} if accessibility is enabled.
- */
- public boolean isAccessibilityEnabled() {
- return mAccessibilityManager.isEnabled();
- }
-
- /**
- * Speaks a key's action after it has been released. Does not speak letter
- * keys since typed keys are already spoken aloud by TalkBack.
- * <p>
- * No-op if accessibility is not enabled.
- * </p>
- *
- * @param primaryCode The primary code of the released key.
- * @param switcher The input method's {@link KeyboardSwitcher}.
- */
- public void onRelease(int primaryCode, KeyboardSwitcher switcher) {
- if (!isAccessibilityEnabled()) {
- return;
- }
-
- int resId = -1;
-
- switch (primaryCode) {
- case Keyboard.CODE_SHIFT: {
- if (switcher.isShiftedOrShiftLocked()) {
- resId = R.string.description_shift_on;
- } else {
- resId = R.string.description_shift_off;
- }
- break;
- }
-
- case Keyboard.CODE_SWITCH_ALPHA_SYMBOL: {
- if (switcher.isAlphabetMode()) {
- resId = R.string.description_symbols_off;
- } else {
- resId = R.string.description_symbols_on;
- }
- break;
- }
- }
-
- if (resId >= 0) {
- speakDescription(mService.getResources().getText(resId));
- }
- }
-
- /**
- * Speaks a key's description for accessibility. If a key has an explicit
- * description defined in keycodes.xml, that will be used. Otherwise, if the
- * key is a Unicode character, then its character will be used.
- * <p>
- * No-op if accessibility is not enabled.
- * </p>
- *
- * @param primaryCode The primary code of the pressed key.
- * @param switcher The input method's {@link KeyboardSwitcher}.
- */
- public void onPress(int primaryCode, KeyboardSwitcher switcher) {
- if (!isAccessibilityEnabled()) {
- return;
- }
-
- // TODO Use the current keyboard state to read "Switch to symbols"
- // instead of just "Symbols" (and similar for shift key).
- CharSequence description = describeKey(primaryCode);
- if (description == null && Character.isDefined((char) primaryCode)) {
- description = Character.toString((char) primaryCode);
- }
-
- if (description != null) {
- speakDescription(description);
- }
- }
-
- /**
- * Returns a text description for a given key code. If the key does not have
- * an explicit description, returns <code>null</code>.
- *
- * @param keyCode An integer key code.
- * @return A {@link CharSequence} describing the key or <code>null</code> if
- * no description is available.
- */
- private CharSequence describeKey(int keyCode) {
- // If not loaded yet, load key descriptions from XML file.
- if (mDescriptions == null) {
- mDescriptions = loadDescriptions();
- }
-
- return mDescriptions.get(keyCode);
- }
-
- /**
- * Loads key descriptions from resources.
- */
- private Map<Integer, CharSequence> loadDescriptions() {
- final Map<Integer, CharSequence> descriptions = new HashMap<Integer, CharSequence>();
- final TypedArray array = mService.getResources().obtainTypedArray(R.array.key_descriptions);
-
- // Key descriptions are stored as a key code followed by a string.
- for (int i = 0; i < array.length() - 1; i += 2) {
- int code = array.getInteger(i, 0);
- CharSequence desc = array.getText(i + 1);
-
- descriptions.put(code, desc);
- }
-
- array.recycle();
-
- return descriptions;
- }
-
- /**
- * Sends a character sequence to be read aloud.
- *
- * @param description The {@link CharSequence} to be read aloud.
- */
- private void speakDescription(CharSequence description) {
- // TODO We need to add an AccessibilityEvent type for IMEs.
- final AccessibilityEvent event = AccessibilityEvent.obtain(
- AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED);
- event.setPackageName(mService.getPackageName());
- event.setClassName(getClass().getName());
- event.setAddedCount(description.length());
- event.getText().add(description);
-
- mAccessibilityManager.sendAccessibilityEvent(event);
- }
-}
diff --git a/java/src/com/android/inputmethod/latin/AssetFileAddress.java b/java/src/com/android/inputmethod/latin/AssetFileAddress.java
new file mode 100644
index 000000000..074ecacc5
--- /dev/null
+++ b/java/src/com/android/inputmethod/latin/AssetFileAddress.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package com.android.inputmethod.latin;
+
+import java.io.File;
+
+/**
+ * Immutable class to hold the address of an asset.
+ * As opposed to a normal file, an asset is usually represented as a contiguous byte array in
+ * the package file. Open it correctly thus requires the name of the package it is in, but
+ * also the offset in the file and the length of this data. This class encapsulates these three.
+ */
+class AssetFileAddress {
+ public final String mFilename;
+ public final long mOffset;
+ public final long mLength;
+
+ public AssetFileAddress(final String filename, final long offset, final long length) {
+ mFilename = filename;
+ mOffset = offset;
+ mLength = length;
+ }
+
+ public static AssetFileAddress makeFromFileName(final String filename) {
+ if (null == filename) return null;
+ File f = new File(filename);
+ if (null == f || !f.isFile()) return null;
+ return new AssetFileAddress(filename, 0l, f.length());
+ }
+
+ public static AssetFileAddress makeFromFileNameAndOffset(final String filename,
+ final long offset, final long length) {
+ if (null == filename) return null;
+ File f = new File(filename);
+ if (null == f || !f.isFile()) return null;
+ return new AssetFileAddress(filename, offset, length);
+ }
+}
diff --git a/java/src/com/android/inputmethod/latin/AutoCorrection.java b/java/src/com/android/inputmethod/latin/AutoCorrection.java
index 092f7ad63..d3119792c 100644
--- a/java/src/com/android/inputmethod/latin/AutoCorrection.java
+++ b/java/src/com/android/inputmethod/latin/AutoCorrection.java
@@ -48,7 +48,7 @@ public class AutoCorrection {
}
public void updateAutoCorrectionStatus(Map<String, Dictionary> dictionaries,
- WordComposer wordComposer, ArrayList<CharSequence> suggestions, int[] priorities,
+ WordComposer wordComposer, ArrayList<CharSequence> suggestions, int[] sortedScores,
CharSequence typedWord, double autoCorrectionThreshold, int correctionMode,
CharSequence quickFixedWord, CharSequence whitelistedWord) {
if (hasAutoCorrectionForWhitelistedWord(whitelistedWord)) {
@@ -62,7 +62,7 @@ public class AutoCorrection {
mHasAutoCorrection = true;
mAutoCorrectionWord = quickFixedWord;
} else if (hasAutoCorrectionForBinaryDictionary(wordComposer, suggestions, correctionMode,
- priorities, typedWord, autoCorrectionThreshold)) {
+ sortedScores, typedWord, autoCorrectionThreshold)) {
mHasAutoCorrection = true;
mAutoCorrectionWord = suggestions.get(0);
}
@@ -114,13 +114,13 @@ public class AutoCorrection {
}
private boolean hasAutoCorrectionForBinaryDictionary(WordComposer wordComposer,
- ArrayList<CharSequence> suggestions, int correctionMode, int[] priorities,
+ ArrayList<CharSequence> suggestions, int correctionMode, int[] sortedScores,
CharSequence typedWord, double autoCorrectionThreshold) {
if (wordComposer.size() > 1 && (correctionMode == Suggest.CORRECTION_FULL
|| correctionMode == Suggest.CORRECTION_FULL_BIGRAM)
- && typedWord != null && suggestions.size() > 0 && priorities.length > 0) {
+ && typedWord != null && suggestions.size() > 0 && sortedScores.length > 0) {
final CharSequence autoCorrectionCandidate = suggestions.get(0);
- final int autoCorrectionCandidateScore = priorities[0];
+ final int autoCorrectionCandidateScore = sortedScores[0];
// TODO: when the normalized score of the first suggestion is nearly equals to
// the normalized score of the second suggestion, behave less aggressive.
mNormalizedScore = Utils.calcNormalizedScore(
diff --git a/java/src/com/android/inputmethod/latin/AutoDictionary.java b/java/src/com/android/inputmethod/latin/AutoDictionary.java
index 54c6f309c..460930f16 100644
--- a/java/src/com/android/inputmethod/latin/AutoDictionary.java
+++ b/java/src/com/android/inputmethod/latin/AutoDictionary.java
@@ -27,7 +27,6 @@ import android.provider.BaseColumns;
import android.util.Log;
import java.util.HashMap;
-import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
@@ -42,13 +41,8 @@ public class AutoDictionary extends ExpandableDictionary {
static final int FREQUENCY_FOR_PICKED = 3;
// Weight added to a user typing a new word that doesn't get corrected (or is reverted)
static final int FREQUENCY_FOR_TYPED = 1;
- // A word that is frequently typed and gets promoted to the user dictionary, uses this
- // frequency.
- static final int FREQUENCY_FOR_AUTO_ADD = 250;
// If the user touches a typed word 2 times or more, it will become valid.
private static final int VALIDITY_THRESHOLD = 2 * FREQUENCY_FOR_PICKED;
- // If the user touches a typed word 4 times or more, it will be added to the user dict.
- private static final int PROMOTION_THRESHOLD = 4 * FREQUENCY_FOR_PICKED;
private LatinIME mIme;
// Locale for which this auto dictionary is storing words
@@ -152,11 +146,6 @@ public class AutoDictionary extends ExpandableDictionary {
freq = freq < 0 ? addFrequency : freq + addFrequency;
super.addWord(word, freq);
- if (freq >= PROMOTION_THRESHOLD) {
- mIme.promoteToUserDictionary(word, FREQUENCY_FOR_AUTO_ADD);
- freq = 0;
- }
-
synchronized (mPendingWritesLock) {
// Write a null frequency if it is to be deleted from the db
mPendingWrites.put(word, freq == 0 ? null : new Integer(freq));
diff --git a/java/src/com/android/inputmethod/latin/BinaryDictionary.java b/java/src/com/android/inputmethod/latin/BinaryDictionary.java
index 08ddd25fa..9748d6006 100644
--- a/java/src/com/android/inputmethod/latin/BinaryDictionary.java
+++ b/java/src/com/android/inputmethod/latin/BinaryDictionary.java
@@ -21,10 +21,7 @@ import com.android.inputmethod.keyboard.KeyboardSwitcher;
import com.android.inputmethod.keyboard.ProximityInfo;
import android.content.Context;
-import android.content.res.AssetFileDescriptor;
-import android.util.Log;
-import java.io.File;
import java.util.Arrays;
/**
@@ -32,8 +29,11 @@ import java.util.Arrays;
*/
public class BinaryDictionary extends Dictionary {
+ public static final String DICTIONARY_PACK_AUTHORITY =
+ "com.android.inputmethod.latin.dictionarypack";
+
/**
- * There is difference between what java and native code can handle.
+ * There is a difference between what java and native code can handle.
* This value should only be used in BinaryDictionary.java
* It is necessary to keep it at this value because some languages e.g. German have
* really long words.
@@ -41,101 +41,59 @@ public class BinaryDictionary extends Dictionary {
public static final int MAX_WORD_LENGTH = 48;
public static final int MAX_WORDS = 18;
+ @SuppressWarnings("unused")
private static final String TAG = "BinaryDictionary";
private static final int MAX_PROXIMITY_CHARS_SIZE = ProximityInfo.MAX_PROXIMITY_CHARS_SIZE;
private static final int MAX_BIGRAMS = 60;
private static final int TYPED_LETTER_MULTIPLIER = 2;
- private static final BinaryDictionary sInstance = new BinaryDictionary();
private int mDicTypeId;
private int mNativeDict;
- private long mDictLength;
private final int[] mInputCodes = new int[MAX_WORD_LENGTH * MAX_PROXIMITY_CHARS_SIZE];
private final char[] mOutputChars = new char[MAX_WORD_LENGTH * MAX_WORDS];
private final char[] mOutputChars_bigrams = new char[MAX_WORD_LENGTH * MAX_BIGRAMS];
- private final int[] mFrequencies = new int[MAX_WORDS];
- private final int[] mFrequencies_bigrams = new int[MAX_BIGRAMS];
+ private final int[] mScores = new int[MAX_WORDS];
+ private final int[] mBigramScores = new int[MAX_BIGRAMS];
private final KeyboardSwitcher mKeyboardSwitcher = KeyboardSwitcher.getInstance();
- private final SubtypeSwitcher mSubtypeSwitcher = SubtypeSwitcher.getInstance();
-
- private static class Flags {
- private static class FlagEntry {
- public final String mName;
- public final int mValue;
- public FlagEntry(String name, int value) {
- mName = name;
- mValue = value;
- }
- }
- public static final FlagEntry[] ALL_FLAGS = {
- // Here should reside all flags that trigger some special processing
- // These *must* match the definition in UnigramDictionary enum in
- // unigram_dictionary.h so please update both at the same time.
- new FlagEntry("requiresGermanUmlautProcessing", 0x1)
- };
- }
- private int mFlags = 0;
- private BinaryDictionary() {
- }
+ public static final Flag FLAG_REQUIRES_GERMAN_UMLAUT_PROCESSING =
+ new Flag(R.bool.config_require_umlaut_processing, 0x1);
- /**
- * Initialize a dictionary from a raw resource file
- * @param context application context for reading resources
- * @param resId the resource containing the raw binary dictionary
- * @return initialized instance of BinaryDictionary
- */
- public static BinaryDictionary initDictionary(Context context, int resId, int dicTypeId) {
- synchronized (sInstance) {
- sInstance.closeInternal();
- try {
- final AssetFileDescriptor afd = context.getResources().openRawResourceFd(resId);
- if (afd == null) {
- Log.e(TAG, "Found the resource but it is compressed. resId=" + resId);
- return null;
- }
- final String sourceDir = context.getApplicationInfo().sourceDir;
- final File packagePath = new File(sourceDir);
- // TODO: Come up with a way to handle a directory.
- if (!packagePath.isFile()) {
- Log.e(TAG, "sourceDir is not a file: " + sourceDir);
- return null;
- }
- sInstance.loadDictionary(sourceDir, afd.getStartOffset(), afd.getLength());
- sInstance.mDicTypeId = dicTypeId;
- } catch (android.content.res.Resources.NotFoundException e) {
- Log.e(TAG, "Could not find the resource. resId=" + resId);
- return null;
- }
- }
- sInstance.initFlags();
- return sInstance;
- }
+ // Can create a new flag from extravalue :
+ // public static final Flag FLAG_MYFLAG =
+ // new Flag("my_flag", 0x02);
- /* package for test */ static BinaryDictionary initDictionary(File dictionary, long startOffset,
- long length, int dicTypeId) {
- synchronized (sInstance) {
- sInstance.closeInternal();
- if (dictionary.isFile()) {
- sInstance.loadDictionary(dictionary.getAbsolutePath(), startOffset, length);
- sInstance.mDicTypeId = dicTypeId;
- } else {
- Log.e(TAG, "Could not find the file. path=" + dictionary.getAbsolutePath());
- return null;
- }
- }
- return sInstance;
- }
+ private static final Flag[] ALL_FLAGS = {
+ // Here should reside all flags that trigger some special processing
+ // These *must* match the definition in UnigramDictionary enum in
+ // unigram_dictionary.h so please update both at the same time.
+ FLAG_REQUIRES_GERMAN_UMLAUT_PROCESSING,
+ };
- private void initFlags() {
- int flags = 0;
- for (Flags.FlagEntry entry : Flags.ALL_FLAGS) {
- if (mSubtypeSwitcher.currentSubtypeContainsExtraValueKey(entry.mName))
- flags |= entry.mValue;
- }
- mFlags = flags;
+ private int mFlags = 0;
+
+ /**
+ * Constructor for the binary dictionary. This is supposed to be called from the
+ * dictionary factory.
+ * All implementations should pass null into flagArray, except for testing purposes.
+ * @param context the context to access the environment from.
+ * @param filename the name of the file to read through native code.
+ * @param offset the offset of the dictionary data within the file.
+ * @param length the length of the binary data.
+ * @param flagArray the flags to limit the dictionary to, or null for default.
+ */
+ public BinaryDictionary(final Context context,
+ final String filename, final long offset, final long length, Flag[] flagArray) {
+ // Note: at the moment a binary dictionary is always of the "main" type.
+ // Initializing this here will help transitioning out of the scheme where
+ // the Suggest class knows everything about every single dictionary.
+ mDicTypeId = Suggest.DIC_MAIN;
+ // TODO: Stop relying on the state of SubtypeSwitcher, get it as a parameter
+ mFlags = Flag.initFlags(null == flagArray ? ALL_FLAGS : flagArray, context,
+ SubtypeSwitcher.getInstance());
+ loadDictionary(filename, offset, length);
}
static {
@@ -149,16 +107,15 @@ public class BinaryDictionary extends Dictionary {
private native boolean isValidWordNative(int nativeData, char[] word, int wordLength);
private native int getSuggestionsNative(int dict, int proximityInfo, int[] xCoordinates,
int[] yCoordinates, int[] inputCodes, int codesSize, int flags, char[] outputChars,
- int[] frequencies);
+ int[] scores);
private native int getBigramsNative(int dict, char[] prevWord, int prevWordLength,
- int[] inputCodes, int inputCodesLength, char[] outputChars, int[] frequencies,
+ int[] inputCodes, int inputCodesLength, char[] outputChars, int[] scores,
int maxWordLength, int maxBigrams, int maxAlternatives);
private final void loadDictionary(String path, long startOffset, long length) {
mNativeDict = openNative(path, startOffset, length,
- TYPED_LETTER_MULTIPLIER, FULL_WORD_FREQ_MULTIPLIER,
+ TYPED_LETTER_MULTIPLIER, FULL_WORD_SCORE_MULTIPLIER,
MAX_WORD_LENGTH, MAX_WORDS, MAX_PROXIMITY_CHARS_SIZE);
- mDictLength = length;
}
@Override
@@ -168,27 +125,32 @@ public class BinaryDictionary extends Dictionary {
char[] chars = previousWord.toString().toCharArray();
Arrays.fill(mOutputChars_bigrams, (char) 0);
- Arrays.fill(mFrequencies_bigrams, 0);
+ Arrays.fill(mBigramScores, 0);
int codesSize = codes.size();
+ if (codesSize <= 0) {
+ // Do not return bigrams from BinaryDictionary when nothing was typed.
+ // Only use user-history bigrams (or whatever other bigram dictionaries decide).
+ return;
+ }
Arrays.fill(mInputCodes, -1);
int[] alternatives = codes.getCodesAt(0);
System.arraycopy(alternatives, 0, mInputCodes, 0,
Math.min(alternatives.length, MAX_PROXIMITY_CHARS_SIZE));
int count = getBigramsNative(mNativeDict, chars, chars.length, mInputCodes, codesSize,
- mOutputChars_bigrams, mFrequencies_bigrams, MAX_WORD_LENGTH, MAX_BIGRAMS,
+ mOutputChars_bigrams, mBigramScores, MAX_WORD_LENGTH, MAX_BIGRAMS,
MAX_PROXIMITY_CHARS_SIZE);
for (int j = 0; j < count; ++j) {
- if (mFrequencies_bigrams[j] < 1) break;
+ if (mBigramScores[j] < 1) break;
final int start = j * MAX_WORD_LENGTH;
int len = 0;
while (len < MAX_WORD_LENGTH && mOutputChars_bigrams[start + len] != 0) {
++len;
}
if (len > 0) {
- callback.addWord(mOutputChars_bigrams, start, len, mFrequencies_bigrams[j],
+ callback.addWord(mOutputChars_bigrams, start, len, mBigramScores[j],
mDicTypeId, DataType.BIGRAM);
}
}
@@ -197,17 +159,17 @@ public class BinaryDictionary extends Dictionary {
@Override
public void getWords(final WordComposer codes, final WordCallback callback) {
final int count = getSuggestions(codes, mKeyboardSwitcher.getLatinKeyboard(),
- mOutputChars, mFrequencies);
+ mOutputChars, mScores);
for (int j = 0; j < count; ++j) {
- if (mFrequencies[j] < 1) break;
+ if (mScores[j] < 1) break;
final int start = j * MAX_WORD_LENGTH;
int len = 0;
while (len < MAX_WORD_LENGTH && mOutputChars[start + len] != 0) {
++len;
}
if (len > 0) {
- callback.addWord(mOutputChars, start, len, mFrequencies[j], mDicTypeId,
+ callback.addWord(mOutputChars, start, len, mScores[j], mDicTypeId,
DataType.UNIGRAM);
}
}
@@ -218,7 +180,7 @@ public class BinaryDictionary extends Dictionary {
}
/* package for test */ int getSuggestions(final WordComposer codes, final Keyboard keyboard,
- char[] outputChars, int[] frequencies) {
+ char[] outputChars, int[] scores) {
if (!isValidDictionary()) return -1;
final int codesSize = codes.size();
@@ -232,12 +194,13 @@ public class BinaryDictionary extends Dictionary {
Math.min(alternatives.length, MAX_PROXIMITY_CHARS_SIZE));
}
Arrays.fill(outputChars, (char) 0);
- Arrays.fill(frequencies, 0);
+ Arrays.fill(scores, 0);
+ final int proximityInfo = keyboard == null ? 0 : keyboard.getProximityInfo();
return getSuggestionsNative(
- mNativeDict, keyboard.getProximityInfo(),
+ mNativeDict, proximityInfo,
codes.getXCoordinates(), codes.getYCoordinates(), mInputCodes, codesSize,
- mFlags, outputChars, frequencies);
+ mFlags, outputChars, scores);
}
@Override
@@ -247,10 +210,6 @@ public class BinaryDictionary extends Dictionary {
return isValidWordNative(mNativeDict, chars, chars.length);
}
- public long getSize() {
- return mDictLength; // This value is initialized in loadDictionary()
- }
-
@Override
public synchronized void close() {
closeInternal();
@@ -260,7 +219,6 @@ public class BinaryDictionary extends Dictionary {
if (mNativeDict != 0) {
closeNative(mNativeDict);
mNativeDict = 0;
- mDictLength = 0;
}
}
diff --git a/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java b/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java
new file mode 100644
index 000000000..76a230f82
--- /dev/null
+++ b/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java
@@ -0,0 +1,151 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package com.android.inputmethod.latin;
+
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.res.AssetFileDescriptor;
+import android.net.Uri;
+import android.text.TextUtils;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+
+/**
+ * Group class for static methods to help with creation and getting of the binary dictionary
+ * file from the dictionary provider
+ */
+public class BinaryDictionaryFileDumper {
+ /**
+ * The size of the temporary buffer to copy files.
+ */
+ static final int FILE_READ_BUFFER_SIZE = 1024;
+
+ // Prevents this class to be accidentally instantiated.
+ private BinaryDictionaryFileDumper() {
+ }
+
+ /**
+ * Generates a file name that matches the locale passed as an argument.
+ * The file name is basically the result of the .toString() method, except we replace
+ * any @File.separator with an underscore to avoid generating a file name that may not
+ * be created.
+ * @param locale the locale for which to get the file name
+ * @param context the context to use for getting the directory
+ * @return the name of the file to be created
+ */
+ private static String getCacheFileNameForLocale(Locale locale, Context context) {
+ // The following assumes two things :
+ // 1. That File.separator is not the same character as "_"
+ // I don't think any android system will ever use "_" as a path separator
+ // 2. That no two locales differ by only a File.separator versus a "_"
+ // Since "_" can't be part of locale components this should be safe.
+ // Examples:
+ // en -> en
+ // en_US_POSIX -> en_US_POSIX
+ // en__foo/bar -> en__foo_bar
+ final String[] separator = { File.separator };
+ final String[] empty = { "_" };
+ final CharSequence basename = TextUtils.replace(locale.toString(), separator, empty);
+ return context.getFilesDir() + File.separator + basename;
+ }
+
+ /**
+ * Return for a given locale the provider URI to query to get the dictionary.
+ */
+ public static Uri getProviderUri(Locale locale) {
+ return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
+ .authority(BinaryDictionary.DICTIONARY_PACK_AUTHORITY).appendPath(
+ locale.toString()).build();
+ }
+
+ /**
+ * Queries a content provider for dictionary data for some locale and returns the file addresses
+ *
+ * This will query a content provider for dictionary data for a given locale, and return
+ * the addresses of a file set the members of which are suitable to be mmap'ed. It will copy
+ * them to local storage if needed.
+ * It should also check the dictionary versions to avoid unnecessary copies but this is
+ * still in TODO state.
+ * This will make the data from the content provider the cached dictionary for this locale,
+ * overwriting any previous cached data.
+ * @returns the addresses of the files, or null if no data could be obtained.
+ * @throw FileNotFoundException if the provider returns non-existent data.
+ * @throw IOException if the provider-returned data could not be read.
+ */
+ public static List<AssetFileAddress> getDictSetFromContentProvider(Locale locale,
+ Context context) throws FileNotFoundException, IOException {
+ // TODO: check whether the dictionary is the same or not and if it is, return the cached
+ // file.
+ // TODO: This should be able to read a number of files from the dictionary pack, copy
+ // them all and return them.
+ final ContentResolver resolver = context.getContentResolver();
+ final Uri dictionaryPackUri = getProviderUri(locale);
+ final AssetFileDescriptor afd = resolver.openAssetFileDescriptor(dictionaryPackUri, "r");
+ if (null == afd) return null;
+ final String fileName =
+ copyFileTo(afd.createInputStream(), getCacheFileNameForLocale(locale, context));
+ return Arrays.asList(AssetFileAddress.makeFromFileName(fileName));
+ }
+
+ /**
+ * Accepts a file as dictionary data for some locale and returns the name of a file.
+ *
+ * This will make the data in the input file the cached dictionary for this locale, overwriting
+ * any previous cached data.
+ */
+ public static String getDictionaryFileFromFile(String fileName, Locale locale,
+ Context context) throws FileNotFoundException, IOException {
+ return copyFileTo(new FileInputStream(fileName), getCacheFileNameForLocale(locale,
+ context));
+ }
+
+ /**
+ * Accepts a resource number as dictionary data for some locale and returns the name of a file.
+ *
+ * This will make the resource the cached dictionary for this locale, overwriting any previous
+ * cached data.
+ */
+ public static String getDictionaryFileFromResource(int resource, Locale locale,
+ Context context) throws FileNotFoundException, IOException {
+ return copyFileTo(context.getResources().openRawResource(resource),
+ getCacheFileNameForLocale(locale, context));
+ }
+
+ /**
+ * Copies the data in an input stream to a target file, creating the file if necessary and
+ * overwriting it if it already exists.
+ * @param input the stream to be copied.
+ * @param outputFileName the name of a file to copy the data to. It is created if necessary.
+ */
+ private static String copyFileTo(final InputStream input, final String outputFileName)
+ throws FileNotFoundException, IOException {
+ final byte[] buffer = new byte[FILE_READ_BUFFER_SIZE];
+ final FileOutputStream output = new FileOutputStream(outputFileName);
+ for (int readBytes = input.read(buffer); readBytes >= 0; readBytes = input.read(buffer))
+ output.write(buffer, 0, readBytes);
+ input.close();
+ return outputFileName;
+ }
+}
diff --git a/java/src/com/android/inputmethod/latin/BinaryDictionaryGetter.java b/java/src/com/android/inputmethod/latin/BinaryDictionaryGetter.java
new file mode 100644
index 000000000..7ce92920d
--- /dev/null
+++ b/java/src/com/android/inputmethod/latin/BinaryDictionaryGetter.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package com.android.inputmethod.latin;
+
+import android.content.Context;
+import android.content.res.AssetFileDescriptor;
+import android.util.Log;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+
+/**
+ * Helper class to get the address of a mmap'able dictionary file.
+ */
+class BinaryDictionaryGetter {
+
+ /**
+ * Used for Log actions from this class
+ */
+ private static final String TAG = BinaryDictionaryGetter.class.getSimpleName();
+
+ // Prevents this from being instantiated
+ private BinaryDictionaryGetter() {}
+
+ /**
+ * Returns a file address from a resource, or null if it cannot be opened.
+ */
+ private static AssetFileAddress loadFallbackResource(Context context, int fallbackResId) {
+ final AssetFileDescriptor afd = context.getResources().openRawResourceFd(fallbackResId);
+ if (afd == null) {
+ Log.e(TAG, "Found the resource but cannot read it. Is it compressed? resId="
+ + fallbackResId);
+ return null;
+ }
+ return AssetFileAddress.makeFromFileNameAndOffset(
+ context.getApplicationInfo().sourceDir, afd.getStartOffset(), afd.getLength());
+ }
+
+ /**
+ * Returns a list of file addresses for a given locale, trying relevant methods in order.
+ *
+ * Tries to get binary dictionaries from various sources, in order:
+ * - Uses a private method of getting a private dictionaries, as implemented by the
+ * PrivateBinaryDictionaryGetter class.
+ * If that fails:
+ * - Uses a content provider to get a public dictionary set, as per the protocol described
+ * in BinaryDictionaryFileDumper.
+ * If that fails:
+ * - Gets a file name from the fallback resource passed as an argument.
+ * If that fails:
+ * - Returns null.
+ * @return The address of a valid file, or null.
+ */
+ public static List<AssetFileAddress> getDictionaryFiles(Locale locale, Context context,
+ int fallbackResId) {
+ // Try first to query a private package signed the same way for private files.
+ final List<AssetFileAddress> privateFiles =
+ PrivateBinaryDictionaryGetter.getDictionaryFiles(locale, context);
+ if (null != privateFiles) {
+ return privateFiles;
+ } else {
+ try {
+ // If that was no-go, try to find a publicly exported dictionary.
+ List<AssetFileAddress> listFromContentProvider =
+ BinaryDictionaryFileDumper.getDictSetFromContentProvider(locale, context);
+ if (null != listFromContentProvider) {
+ return listFromContentProvider;
+ }
+ // If the list is null, fall through and return the fallback
+ } catch (FileNotFoundException e) {
+ Log.e(TAG, "Unable to create dictionary file from provider for locale "
+ + locale.toString() + ": falling back to internal dictionary");
+ } catch (IOException e) {
+ Log.e(TAG, "Unable to read source data for locale "
+ + locale.toString() + ": falling back to internal dictionary");
+ }
+ return Arrays.asList(loadFallbackResource(context, fallbackResId));
+ }
+ }
+}
diff --git a/java/src/com/android/inputmethod/latin/CandidateView.java b/java/src/com/android/inputmethod/latin/CandidateView.java
index 5719b9012..abdf30e6b 100644
--- a/java/src/com/android/inputmethod/latin/CandidateView.java
+++ b/java/src/com/android/inputmethod/latin/CandidateView.java
@@ -133,7 +133,6 @@ public class CandidateView extends LinearLayout implements OnClickListener, OnLo
ViewGroup.LayoutParams.WRAP_CONTENT);
mPreviewPopup.setContentView(mPreviewText);
mPreviewPopup.setBackgroundDrawable(null);
- mPreviewPopup.setAnimationStyle(R.style.KeyPreviewAnimation);
mConfigCandidateHighlightFontColorEnabled =
res.getBoolean(R.bool.config_candidate_highlight_font_color_enabled);
mColorNormal = res.getColor(R.color.candidate_normal);
@@ -151,7 +150,7 @@ public class CandidateView extends LinearLayout implements OnClickListener, OnLo
tv.setOnLongClickListener(this);
ImageView divider = (ImageView)v.findViewById(R.id.candidate_divider);
// Do not display divider of first candidate.
- divider.setVisibility(i == 0 ? GONE : VISIBLE);
+ divider.setVisibility(i == 0 ? INVISIBLE : VISIBLE);
mWords.add(v);
}
@@ -180,7 +179,7 @@ public class CandidateView extends LinearLayout implements OnClickListener, OnLo
private void updateSuggestions() {
final SuggestedWords suggestions = mSuggestions;
clear();
- final int count = suggestions.size();
+ final int count = Math.min(mWords.size(), suggestions.size());
for (int i = 0; i < count; i++) {
CharSequence word = suggestions.getWord(i);
if (word == null) continue;
diff --git a/java/src/com/android/inputmethod/latin/ContactsDictionary.java b/java/src/com/android/inputmethod/latin/ContactsDictionary.java
index 048f72dc5..b057cf4e3 100644
--- a/java/src/com/android/inputmethod/latin/ContactsDictionary.java
+++ b/java/src/com/android/inputmethod/latin/ContactsDictionary.java
@@ -26,6 +26,8 @@ import android.provider.ContactsContract.Contacts;
import android.text.TextUtils;
import android.util.Log;
+import com.android.inputmethod.keyboard.Keyboard;
+
public class ContactsDictionary extends ExpandableDictionary {
private static final String[] PROJECTION = {
@@ -95,6 +97,14 @@ public class ContactsDictionary extends ExpandableDictionary {
mLastLoadedContacts = SystemClock.uptimeMillis();
}
+ @Override
+ public void getBigrams(final WordComposer codes, final CharSequence previousWord,
+ final WordCallback callback) {
+ // Do not return bigrams from Contacts when nothing was typed.
+ if (codes.size() <= 0) return;
+ super.getBigrams(codes, previousWord, callback);
+ }
+
private void addWords(Cursor cursor) {
clearDictionary();
@@ -115,8 +125,9 @@ public class ContactsDictionary extends ExpandableDictionary {
for (j = i + 1; j < len; j++) {
char c = name.charAt(j);
- if (!(c == '-' || c == '\'' ||
- Character.isLetter(c))) {
+ if (!(c == Keyboard.CODE_DASH
+ || c == Keyboard.CODE_SINGLE_QUOTE
+ || Character.isLetter(c))) {
break;
}
}
diff --git a/java/src/com/android/inputmethod/latin/DebugSettings.java b/java/src/com/android/inputmethod/latin/DebugSettings.java
index 2f1e7c2b8..fd62d61c3 100644
--- a/java/src/com/android/inputmethod/latin/DebugSettings.java
+++ b/java/src/com/android/inputmethod/latin/DebugSettings.java
@@ -33,6 +33,7 @@ public class DebugSettings extends PreferenceActivity
private boolean mServiceNeedsRestart = false;
private CheckBoxPreference mDebugMode;
+ private CheckBoxPreference mUseSpacebarLanguageSwitch;
@Override
protected void onCreate(Bundle icicle) {
@@ -60,6 +61,13 @@ public class DebugSettings extends PreferenceActivity
updateDebugMode();
mServiceNeedsRestart = true;
}
+ } else if (key.equals(SubtypeSwitcher.USE_SPACEBAR_LANGUAGE_SWITCH_KEY)) {
+ if (mUseSpacebarLanguageSwitch != null) {
+ mUseSpacebarLanguageSwitch.setChecked(
+ prefs.getBoolean(SubtypeSwitcher.USE_SPACEBAR_LANGUAGE_SWITCH_KEY,
+ getResources().getBoolean(
+ R.bool.config_use_spacebar_language_switcher)));
+ }
}
}
diff --git a/java/src/com/android/inputmethod/latin/Dictionary.java b/java/src/com/android/inputmethod/latin/Dictionary.java
index 56f0cc503..c7737b9a2 100644
--- a/java/src/com/android/inputmethod/latin/Dictionary.java
+++ b/java/src/com/android/inputmethod/latin/Dictionary.java
@@ -29,7 +29,7 @@ public abstract class Dictionary {
/**
* The weight to give to a word if it's length is the same as the number of typed characters.
*/
- protected static final int FULL_WORD_FREQ_MULTIPLIER = 2;
+ protected static final int FULL_WORD_SCORE_MULTIPLIER = 2;
public static enum DataType {
UNIGRAM, BIGRAM
@@ -42,17 +42,17 @@ public abstract class Dictionary {
public interface WordCallback {
/**
* Adds a word to a list of suggestions. The word is expected to be ordered based on
- * the provided frequency.
+ * the provided score.
* @param word the character array containing the word
* @param wordOffset starting offset of the word in the character array
* @param wordLength length of valid characters in the character array
- * @param frequency the frequency of occurrence. This is normalized between 1 and 255, but
+ * @param score the score of occurrence. This is normalized between 1 and 255, but
* can exceed those limits
* @param dicTypeId of the dictionary where word was from
* @param dataType tells type of this data
* @return true if the word was added, false if no more words are required
*/
- boolean addWord(char[] word, int wordOffset, int wordLength, int frequency, int dicTypeId,
+ boolean addWord(char[] word, int wordOffset, int wordLength, int score, int dicTypeId,
DataType dataType);
}
@@ -61,7 +61,7 @@ public abstract class Dictionary {
* words are added through the callback object.
* @param composer the key sequence to match
* @param callback the callback object to send matched words to as possible candidates
- * @see WordCallback#addWord(char[], int, int)
+ * @see WordCallback#addWord(char[], int, int, int, int, DataType)
*/
abstract public void getWords(final WordComposer composer, final WordCallback callback);
diff --git a/java/src/com/android/inputmethod/latin/DictionaryCollection.java b/java/src/com/android/inputmethod/latin/DictionaryCollection.java
new file mode 100644
index 000000000..3fcb6ed55
--- /dev/null
+++ b/java/src/com/android/inputmethod/latin/DictionaryCollection.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package com.android.inputmethod.latin;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+/**
+ * Class for a collection of dictionaries that behave like one dictionary.
+ */
+public class DictionaryCollection extends Dictionary {
+
+ protected final List<Dictionary> mDictionaries;
+
+ public DictionaryCollection() {
+ mDictionaries = new CopyOnWriteArrayList<Dictionary>();
+ }
+
+ public DictionaryCollection(Dictionary... dictionaries) {
+ mDictionaries = new CopyOnWriteArrayList<Dictionary>(dictionaries);
+ }
+
+ public DictionaryCollection(Collection<Dictionary> dictionaries) {
+ mDictionaries = new CopyOnWriteArrayList<Dictionary>(dictionaries);
+ }
+
+ @Override
+ public void getWords(final WordComposer composer, final WordCallback callback) {
+ for (final Dictionary dict : mDictionaries)
+ dict.getWords(composer, callback);
+ }
+
+ @Override
+ public void getBigrams(final WordComposer composer, final CharSequence previousWord,
+ final WordCallback callback) {
+ for (final Dictionary dict : mDictionaries)
+ dict.getBigrams(composer, previousWord, callback);
+ }
+
+ @Override
+ public boolean isValidWord(CharSequence word) {
+ for (final Dictionary dict : mDictionaries)
+ if (dict.isValidWord(word)) return true;
+ return false;
+ }
+
+ @Override
+ public void close() {
+ for (final Dictionary dict : mDictionaries)
+ dict.close();
+ }
+
+ public void addDictionary(Dictionary newDict) {
+ mDictionaries.add(newDict);
+ }
+}
diff --git a/java/src/com/android/inputmethod/latin/DictionaryFactory.java b/java/src/com/android/inputmethod/latin/DictionaryFactory.java
new file mode 100644
index 000000000..bba331868
--- /dev/null
+++ b/java/src/com/android/inputmethod/latin/DictionaryFactory.java
@@ -0,0 +1,177 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package com.android.inputmethod.latin;
+
+import android.content.Context;
+import android.content.res.AssetFileDescriptor;
+import android.content.res.Resources;
+import android.util.Log;
+
+import java.io.File;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Locale;
+
+/**
+ * Factory for dictionary instances.
+ */
+public class DictionaryFactory {
+
+ private static String TAG = DictionaryFactory.class.getSimpleName();
+
+ /**
+ * Initializes a dictionary from a dictionary pack.
+ *
+ * This searches for a content provider providing a dictionary pack for the specified
+ * locale. If none is found, it falls back to using the resource passed as fallBackResId
+ * as a dictionary.
+ * @param context application context for reading resources
+ * @param locale the locale for which to create the dictionary
+ * @param fallbackResId the id of the resource to use as a fallback if no pack is found
+ * @return an initialized instance of Dictionary
+ */
+ public static Dictionary createDictionaryFromManager(Context context, Locale locale,
+ int fallbackResId) {
+ if (null == locale) {
+ Log.e(TAG, "No locale defined for dictionary");
+ return new DictionaryCollection(createBinaryDictionary(context, fallbackResId));
+ }
+
+ final List<Dictionary> dictList = new LinkedList<Dictionary>();
+ for (final AssetFileAddress f : BinaryDictionaryGetter.getDictionaryFiles(locale,
+ context, fallbackResId)) {
+ dictList.add(new BinaryDictionary(context, f.mFilename, f.mOffset, f.mLength, null));
+ }
+
+ if (null == dictList) return null;
+ return new DictionaryCollection(dictList);
+ }
+
+ /**
+ * Initializes a dictionary from a raw resource file
+ * @param context application context for reading resources
+ * @param resId the resource containing the raw binary dictionary
+ * @return an initialized instance of BinaryDictionary
+ */
+ protected static BinaryDictionary createBinaryDictionary(Context context, int resId) {
+ AssetFileDescriptor afd = null;
+ try {
+ afd = context.getResources().openRawResourceFd(resId);
+ if (afd == null) {
+ Log.e(TAG, "Found the resource but it is compressed. resId=" + resId);
+ return null;
+ }
+ if (!isFullDictionary(afd)) return null;
+ final String sourceDir = context.getApplicationInfo().sourceDir;
+ final File packagePath = new File(sourceDir);
+ // TODO: Come up with a way to handle a directory.
+ if (!packagePath.isFile()) {
+ Log.e(TAG, "sourceDir is not a file: " + sourceDir);
+ return null;
+ }
+ return new BinaryDictionary(context,
+ sourceDir, afd.getStartOffset(), afd.getLength(), null);
+ } catch (android.content.res.Resources.NotFoundException e) {
+ Log.e(TAG, "Could not find the resource. resId=" + resId);
+ return null;
+ } finally {
+ if (null != afd) {
+ try {
+ afd.close();
+ } catch (java.io.IOException e) {
+ /* IOException on close ? What am I supposed to do ? */
+ }
+ }
+ }
+ }
+
+ /**
+ * Create a dictionary from passed data. This is intended for unit tests only.
+ * @param context the test context to create this data from.
+ * @param dictionary the file to read
+ * @param startOffset the offset in the file where the data starts
+ * @param length the length of the data
+ * @param flagArray the flags to use with this data for testing
+ * @return the created dictionary, or null.
+ */
+ public static Dictionary createDictionaryForTest(Context context, File dictionary,
+ long startOffset, long length, Flag[] flagArray) {
+ if (dictionary.isFile()) {
+ return new BinaryDictionary(context, dictionary.getAbsolutePath(), startOffset, length,
+ flagArray);
+ } else {
+ Log.e(TAG, "Could not find the file. path=" + dictionary.getAbsolutePath());
+ return null;
+ }
+ }
+
+ /**
+ * Find out whether a dictionary is available for this locale.
+ * @param context the context on which to check resources.
+ * @param locale the locale to check for.
+ * @return whether a (non-placeholder) dictionary is available or not.
+ */
+ public static boolean isDictionaryAvailable(Context context, Locale locale) {
+ final Resources res = context.getResources();
+ final Locale saveLocale = Utils.setSystemLocale(res, locale);
+
+ final int resourceId = Utils.getMainDictionaryResourceId(res);
+ final AssetFileDescriptor afd = res.openRawResourceFd(resourceId);
+ final boolean hasDictionary = isFullDictionary(afd);
+ try {
+ if (null != afd) afd.close();
+ } catch (java.io.IOException e) {
+ /* Um, what can we do here exactly? */
+ }
+
+ Utils.setSystemLocale(res, saveLocale);
+ return hasDictionary;
+ }
+
+ // TODO: Do not use the size of the dictionary as an unique dictionary ID.
+ public static Long getDictionaryId(Context context, Locale locale) {
+ final Resources res = context.getResources();
+ final Locale saveLocale = Utils.setSystemLocale(res, locale);
+
+ final int resourceId = Utils.getMainDictionaryResourceId(res);
+ final AssetFileDescriptor afd = res.openRawResourceFd(resourceId);
+ final Long size = (afd != null && afd.getLength() > PLACEHOLDER_LENGTH)
+ ? afd.getLength()
+ : null;
+ try {
+ if (null != afd) afd.close();
+ } catch (java.io.IOException e) {
+ }
+
+ Utils.setSystemLocale(res, saveLocale);
+ return size;
+ }
+
+ // TODO: Find the Right Way to find out whether the resource is a placeholder or not.
+ // Suggestion : strip the locale, open the placeholder file and store its offset.
+ // Upon opening the file, if it's the same offset, then it's the placeholder.
+ private static final long PLACEHOLDER_LENGTH = 34;
+ /**
+ * Finds out whether the data pointed out by an AssetFileDescriptor is a full
+ * dictionary (as opposed to null, or to a place holder).
+ * @param afd the file descriptor to test, or null
+ * @return true if the dictionary is a real full dictionary, false if it's null or a placeholder
+ */
+ protected static boolean isFullDictionary(final AssetFileDescriptor afd) {
+ return (afd != null && afd.getLength() > PLACEHOLDER_LENGTH);
+ }
+}
diff --git a/java/src/com/android/inputmethod/latin/DictionaryPackInstallBroadcastReceiver.java b/java/src/com/android/inputmethod/latin/DictionaryPackInstallBroadcastReceiver.java
new file mode 100644
index 000000000..9d30af84b
--- /dev/null
+++ b/java/src/com/android/inputmethod/latin/DictionaryPackInstallBroadcastReceiver.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package com.android.inputmethod.latin;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.ProviderInfo;
+import android.net.Uri;
+
+/**
+ * Takes action to reload the necessary data when a dictionary pack was added/removed.
+ */
+public class DictionaryPackInstallBroadcastReceiver extends BroadcastReceiver {
+
+ final LatinIME mService;
+ /**
+ * The action of the intent for publishing that new dictionary data is available.
+ */
+ /* package */ static final String NEW_DICTIONARY_INTENT_ACTION =
+ "com.android.inputmethod.latin.dictionarypack.newdict";
+
+ public DictionaryPackInstallBroadcastReceiver(final LatinIME service) {
+ mService = service;
+ }
+
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ final String action = intent.getAction();
+ final PackageManager manager = context.getPackageManager();
+
+ // We need to reread the dictionary if a new dictionary package is installed.
+ if (action.equals(Intent.ACTION_PACKAGE_ADDED)) {
+ final Uri packageUri = intent.getData();
+ if (null == packageUri) return; // No package name : we can't do anything
+ final String packageName = packageUri.getSchemeSpecificPart();
+ if (null == packageName) return;
+ final PackageInfo packageInfo;
+ try {
+ packageInfo = manager.getPackageInfo(packageName, PackageManager.GET_PROVIDERS);
+ } catch (android.content.pm.PackageManager.NameNotFoundException e) {
+ return; // No package info : we can't do anything
+ }
+ final ProviderInfo[] providers = packageInfo.providers;
+ if (null == providers) return; // No providers : it is not a dictionary.
+
+ // Search for some dictionary pack in the just-installed package. If found, reread.
+ for (ProviderInfo info : providers) {
+ if (BinaryDictionary.DICTIONARY_PACK_AUTHORITY.equals(info.authority)) {
+ mService.resetSuggestMainDict();
+ return;
+ }
+ }
+ // If we come here none of the authorities matched the one we searched for.
+ // We can exit safely.
+ return;
+ } else if (action.equals(Intent.ACTION_PACKAGE_REMOVED)
+ && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
+ // When the dictionary package is removed, we need to reread dictionary (to use the
+ // next-priority one, or stop using a dictionary at all if this was the only one,
+ // since this is the user request).
+ // If we are replacing the package, we will receive ADDED right away so no need to
+ // remove the dictionary at the moment, since we will do it when we receive the
+ // ADDED broadcast.
+
+ // TODO: Only reload dictionary on REMOVED when the removed package is the one we
+ // read dictionary from?
+ mService.resetSuggestMainDict();
+ } else if (action.equals(NEW_DICTIONARY_INTENT_ACTION)) {
+ mService.resetSuggestMainDict();
+ }
+ }
+}
diff --git a/java/src/com/android/inputmethod/latin/EditingUtils.java b/java/src/com/android/inputmethod/latin/EditingUtils.java
index 90c250dcb..e56aa695d 100644
--- a/java/src/com/android/inputmethod/latin/EditingUtils.java
+++ b/java/src/com/android/inputmethod/latin/EditingUtils.java
@@ -16,13 +16,13 @@
package com.android.inputmethod.latin;
+import com.android.inputmethod.compat.InputConnectionCompatUtils;
+
import android.text.TextUtils;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
import java.util.regex.Pattern;
/**
@@ -34,11 +34,6 @@ public class EditingUtils {
*/
private static final int LOOKBACK_CHARACTER_NUM = 15;
- // Cache Method pointers
- private static boolean sMethodsInitialized;
- private static Method sMethodGetSelectedText;
- private static Method sMethodSetComposingRegion;
-
private EditingUtils() {
// Unintentional empty constructor for singleton.
}
@@ -78,7 +73,7 @@ public class EditingUtils {
/**
* @param connection connection to the current text field.
- * @param sep characters which may separate words
+ * @param separators characters which may separate words
* @return the word that surrounds the cursor, including up to one trailing
* separator. For example, if the field contains "he|llo world", where |
* represents the cursor, then "hello " will be returned.
@@ -166,23 +161,62 @@ public class EditingUtils {
private static final Pattern spaceRegex = Pattern.compile("\\s+");
+
public static CharSequence getPreviousWord(InputConnection connection,
String sentenceSeperators) {
//TODO: Should fix this. This could be slow!
CharSequence prev = connection.getTextBeforeCursor(LOOKBACK_CHARACTER_NUM, 0);
- if (prev == null) {
- return null;
- }
+ return getPreviousWord(prev, sentenceSeperators);
+ }
+
+ // Get the word before the whitespace preceding the non-whitespace preceding the cursor.
+ // Also, it won't return words that end in a separator.
+ // Example :
+ // "abc def|" -> abc
+ // "abc def |" -> abc
+ // "abc def. |" -> abc
+ // "abc def . |" -> def
+ // "abc|" -> null
+ // "abc |" -> null
+ // "abc. def|" -> null
+ public static CharSequence getPreviousWord(CharSequence prev, String sentenceSeperators) {
+ if (prev == null) return null;
String[] w = spaceRegex.split(prev);
- if (w.length >= 2 && w[w.length-2].length() > 0) {
- char lastChar = w[w.length-2].charAt(w[w.length-2].length() -1);
- if (sentenceSeperators.contains(String.valueOf(lastChar))) {
- return null;
- }
- return w[w.length-2];
- } else {
- return null;
- }
+
+ // If we can't find two words, or we found an empty word, return null.
+ if (w.length < 2 || w[w.length - 2].length() <= 0) return null;
+
+ // If ends in a separator, return null
+ char lastChar = w[w.length - 2].charAt(w[w.length - 2].length() - 1);
+ if (sentenceSeperators.contains(String.valueOf(lastChar))) return null;
+
+ return w[w.length - 2];
+ }
+
+ public static CharSequence getThisWord(InputConnection connection, String sentenceSeperators) {
+ final CharSequence prev = connection.getTextBeforeCursor(LOOKBACK_CHARACTER_NUM, 0);
+ return getThisWord(prev, sentenceSeperators);
+ }
+
+ // Get the word immediately before the cursor, even if there is whitespace between it and
+ // the cursor - but not if there is punctuation.
+ // Example :
+ // "abc def|" -> def
+ // "abc def |" -> def
+ // "abc def. |" -> null
+ // "abc def . |" -> null
+ public static CharSequence getThisWord(CharSequence prev, String sentenceSeperators) {
+ if (prev == null) return null;
+ String[] w = spaceRegex.split(prev);
+
+ // No word : return null
+ if (w.length < 1 || w[w.length - 1].length() <= 0) return null;
+
+ // If ends in a separator, return null
+ char lastChar = w[w.length - 1].charAt(w[w.length - 1].length() - 1);
+ if (sentenceSeperators.contains(String.valueOf(lastChar))) return null;
+
+ return w[w.length - 1];
}
public static class SelectedWord {
@@ -241,7 +275,8 @@ public class EditingUtils {
}
// Extract the selection alone
- CharSequence touching = getSelectedText(ic, selStart, selEnd);
+ CharSequence touching = InputConnectionCompatUtils.getSelectedText(
+ ic, selStart, selEnd);
if (TextUtils.isEmpty(touching)) return null;
// Is any part of the selection a separator? If so, return null.
final int length = touching.length();
@@ -255,74 +290,4 @@ public class EditingUtils {
}
return null;
}
-
- /**
- * Cache method pointers for performance
- */
- private static void initializeMethodsForReflection() {
- try {
- // These will either both exist or not, so no need for separate try/catch blocks.
- // If other methods are added later, use separate try/catch blocks.
- sMethodGetSelectedText = InputConnection.class.getMethod("getSelectedText", int.class);
- sMethodSetComposingRegion = InputConnection.class.getMethod("setComposingRegion",
- int.class, int.class);
- } catch (NoSuchMethodException exc) {
- // Ignore
- }
- sMethodsInitialized = true;
- }
-
- /**
- * Returns the selected text between the selStart and selEnd positions.
- */
- private static CharSequence getSelectedText(InputConnection ic, int selStart, int selEnd) {
- // Use reflection, for backward compatibility
- CharSequence result = null;
- if (!sMethodsInitialized) {
- initializeMethodsForReflection();
- }
- if (sMethodGetSelectedText != null) {
- try {
- result = (CharSequence) sMethodGetSelectedText.invoke(ic, 0);
- return result;
- } catch (InvocationTargetException exc) {
- // Ignore
- } catch (IllegalArgumentException e) {
- // Ignore
- } catch (IllegalAccessException e) {
- // Ignore
- }
- }
- // Reflection didn't work, try it the poor way, by moving the cursor to the start,
- // getting the text after the cursor and moving the text back to selected mode.
- // TODO: Verify that this works properly in conjunction with
- // LatinIME#onUpdateSelection
- ic.setSelection(selStart, selEnd);
- result = ic.getTextAfterCursor(selEnd - selStart, 0);
- ic.setSelection(selStart, selEnd);
- return result;
- }
-
- /**
- * Tries to set the text into composition mode if there is support for it in the framework.
- */
- public static void underlineWord(InputConnection ic, SelectedWord word) {
- // Use reflection, for backward compatibility
- // If method not found, there's nothing we can do. It still works but just wont underline
- // the word.
- if (!sMethodsInitialized) {
- initializeMethodsForReflection();
- }
- if (sMethodSetComposingRegion != null) {
- try {
- sMethodSetComposingRegion.invoke(ic, word.mStart, word.mEnd);
- } catch (InvocationTargetException exc) {
- // Ignore
- } catch (IllegalArgumentException e) {
- // Ignore
- } catch (IllegalAccessException e) {
- // Ignore
- }
- }
- }
}
diff --git a/java/src/com/android/inputmethod/latin/ExpandableDictionary.java b/java/src/com/android/inputmethod/latin/ExpandableDictionary.java
index 0318175f6..97a4a1816 100644
--- a/java/src/com/android/inputmethod/latin/ExpandableDictionary.java
+++ b/java/src/com/android/inputmethod/latin/ExpandableDictionary.java
@@ -19,6 +19,8 @@ package com.android.inputmethod.latin;
import android.content.Context;
import android.os.AsyncTask;
+import com.android.inputmethod.keyboard.Keyboard;
+
import java.util.LinkedList;
/**
@@ -32,14 +34,14 @@ public class ExpandableDictionary extends Dictionary {
*/
protected static final int MAX_WORD_LENGTH = 32;
+ // Bigram frequency is a fixed point number with 1 meaning 1.2 and 255 meaning 1.8.
+ protected static final int BIGRAM_MAX_FREQUENCY = 255;
+
private Context mContext;
private char[] mWordBuilder = new char[MAX_WORD_LENGTH];
private int mDicTypeId;
private int mMaxDepth;
private int mInputLength;
- private StringBuilder sb = new StringBuilder(MAX_WORD_LENGTH);
-
- private static final char QUOTE = '\'';
private boolean mRequiresReload;
@@ -98,6 +100,7 @@ public class ExpandableDictionary extends Dictionary {
public int addFrequency(int add) {
mFrequency += add;
+ if (mFrequency > BIGRAM_MAX_FREQUENCY) mFrequency = BIGRAM_MAX_FREQUENCY;
return mFrequency;
}
}
@@ -226,6 +229,7 @@ public class ExpandableDictionary extends Dictionary {
* Returns the word's frequency or -1 if not found
*/
protected int getWordFrequency(CharSequence word) {
+ // Case-sensitive search
Node node = searchNode(mRoots, word, 0, word.length());
return (node == null) ? -1 : node.mFrequency;
}
@@ -301,7 +305,8 @@ public class ExpandableDictionary extends Dictionary {
getWordsRec(children, codes, word, depth + 1, completion, snr, inputIndex,
skipPos, callback);
}
- } else if ((c == QUOTE && currentChars[0] != QUOTE) || depth == skipPos) {
+ } else if ((c == Keyboard.CODE_SINGLE_QUOTE
+ && currentChars[0] != Keyboard.CODE_SINGLE_QUOTE) || depth == skipPos) {
// Skip the ' and continue deeper
word[depth] = c;
if (children != null) {
@@ -327,7 +332,7 @@ public class ExpandableDictionary extends Dictionary {
final int finalFreq;
if (skipPos < 0) {
finalFreq = freq * snr * addedAttenuation
- * FULL_WORD_FREQ_MULTIPLIER;
+ * FULL_WORD_SCORE_MULTIPLIER;
} else {
finalFreq = computeSkippedWordFinalFreq(freq,
snr * addedAttenuation, mInputLength);
@@ -362,12 +367,16 @@ public class ExpandableDictionary extends Dictionary {
/**
* Adds bigrams to the in-memory trie structure that is being used to retrieve any word
- * @param frequency frequency for this bigrams
- * @param addFrequency if true, it adds to current frequency
+ * @param frequency frequency for this bigram
+ * @param addFrequency if true, it adds to current frequency, else it overwrites the old value
* @return returns the final frequency
*/
private int addOrSetBigram(String word1, String word2, int frequency, boolean addFrequency) {
- Node firstWord = searchWord(mRoots, word1, 0, null);
+ // We don't want results to be different according to case of the looked up left hand side
+ // word. We do want however to return the correct case for the right hand side.
+ // So we want to squash the case of the left hand side, and preserve that of the right
+ // hand side word.
+ Node firstWord = searchWord(mRoots, word1.toLowerCase(), 0, null);
Node secondWord = searchWord(mRoots, word2, 0, null);
LinkedList<NextWord> bigram = firstWord.mNGrams;
if (bigram == null || bigram.size() == 0) {
@@ -433,8 +442,12 @@ public class ExpandableDictionary extends Dictionary {
}
}
- private void runReverseLookUp(final CharSequence previousWord, final WordCallback callback) {
- Node prevWord = searchNode(mRoots, previousWord, 0, previousWord.length());
+ private void runBigramReverseLookUp(final CharSequence previousWord,
+ final WordCallback callback) {
+ // Search for the lowercase version of the word only, because that's where bigrams
+ // store their sons.
+ Node prevWord = searchNode(mRoots, previousWord.toString().toLowerCase(), 0,
+ previousWord.length());
if (prevWord != null && prevWord.mNGrams != null) {
reverseLookUp(prevWord.mNGrams, callback);
}
@@ -444,7 +457,7 @@ public class ExpandableDictionary extends Dictionary {
public void getBigrams(final WordComposer codes, final CharSequence previousWord,
final WordCallback callback) {
if (!reloadDictionaryIfRequired()) {
- runReverseLookUp(previousWord, callback);
+ runBigramReverseLookUp(previousWord, callback);
}
}
@@ -462,6 +475,9 @@ public class ExpandableDictionary extends Dictionary {
}
}
+ // Local to reverseLookUp, but do not allocate each time.
+ private final char[] mLookedUpString = new char[MAX_WORD_LENGTH];
+
/**
* reverseLookUp retrieves the full word given a list of terminal nodes and adds those words
* through callback.
@@ -474,30 +490,33 @@ public class ExpandableDictionary extends Dictionary {
for (NextWord nextWord : terminalNodes) {
node = nextWord.mWord;
freq = nextWord.getFrequency();
- // TODO Not the best way to limit suggestion threshold
- if (freq >= UserBigramDictionary.SUGGEST_THRESHOLD) {
- sb.setLength(0);
- do {
- sb.insert(0, node.mCode);
- node = node.mParent;
- } while(node != null);
-
- // TODO better way to feed char array?
- callback.addWord(sb.toString().toCharArray(), 0, sb.length(), freq, mDicTypeId,
- DataType.BIGRAM);
- }
+ int index = MAX_WORD_LENGTH;
+ do {
+ --index;
+ mLookedUpString[index] = node.mCode;
+ node = node.mParent;
+ } while (node != null);
+
+ callback.addWord(mLookedUpString, index, MAX_WORD_LENGTH - index, freq, mDicTypeId,
+ DataType.BIGRAM);
}
}
/**
- * Search for the terminal node of the word
+ * Recursively search for the terminal node of the word.
+ *
+ * One iteration takes the full word to search for and the current index of the recursion.
+ *
+ * @param children the node of the trie to search under.
+ * @param word the word to search for. Only read [offset..length] so there may be trailing chars
+ * @param offset the index in {@code word} this recursion should operate on.
+ * @param length the length of the input word.
* @return Returns the terminal node of the word if the word exists
*/
private Node searchNode(final NodeArray children, final CharSequence word, final int offset,
final int length) {
- // TODO Consider combining with addWordRec
final int count = children.mLength;
- char currentChar = word.charAt(offset);
+ final char currentChar = word.charAt(offset);
for (int j = 0; j < count; j++) {
final Node node = children.mData[j];
if (node.mCode == currentChar) {
diff --git a/java/src/com/android/inputmethod/latin/Flag.java b/java/src/com/android/inputmethod/latin/Flag.java
new file mode 100644
index 000000000..3cb8f7e17
--- /dev/null
+++ b/java/src/com/android/inputmethod/latin/Flag.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package com.android.inputmethod.latin;
+
+import android.content.Context;
+import android.content.res.Resources;
+
+public class Flag {
+ public final String mName;
+ public final int mResource;
+ public final int mMask;
+ public final int mSource;
+
+ static private final int SOURCE_CONFIG = 1;
+ static private final int SOURCE_EXTRAVALUE = 2;
+
+ public Flag(int resourceId, int mask) {
+ mName = null;
+ mResource = resourceId;
+ mSource = SOURCE_CONFIG;
+ mMask = mask;
+ }
+
+ public Flag(String name, int mask) {
+ mName = name;
+ mResource = 0;
+ mSource = SOURCE_EXTRAVALUE;
+ mMask = mask;
+ }
+
+ // If context/switcher are null, set all related flags in flagArray to on.
+ public static int initFlags(Flag[] flagArray, Context context, SubtypeSwitcher switcher) {
+ int flags = 0;
+ final Resources res = null == context ? null : context.getResources();
+ for (Flag entry : flagArray) {
+ switch (entry.mSource) {
+ case Flag.SOURCE_CONFIG:
+ if (res == null || res.getBoolean(entry.mResource))
+ flags |= entry.mMask;
+ break;
+ case Flag.SOURCE_EXTRAVALUE:
+ if (switcher == null ||
+ switcher.currentSubtypeContainsExtraValueKey(entry.mName))
+ flags |= entry.mMask;
+ break;
+ }
+ }
+ return flags;
+ }
+}
diff --git a/java/src/com/android/inputmethod/latin/InputLanguageSelection.java b/java/src/com/android/inputmethod/latin/InputLanguageSelection.java
deleted file mode 100644
index b58a57e42..000000000
--- a/java/src/com/android/inputmethod/latin/InputLanguageSelection.java
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
- * Copyright (C) 2008-2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-
-package com.android.inputmethod.latin;
-
-import android.content.SharedPreferences;
-import android.content.SharedPreferences.Editor;
-import android.content.res.Configuration;
-import android.content.res.Resources;
-import android.os.Bundle;
-import android.preference.CheckBoxPreference;
-import android.preference.PreferenceActivity;
-import android.preference.PreferenceGroup;
-import android.preference.PreferenceManager;
-import android.text.TextUtils;
-
-import java.text.Collator;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Locale;
-
-public class InputLanguageSelection extends PreferenceActivity {
-
- private SharedPreferences mPrefs;
- private String mSelectedLanguages;
- private ArrayList<Loc> mAvailableLanguages = new ArrayList<Loc>();
- private static final String[] BLACKLIST_LANGUAGES = {
- "ko", "ja", "zh", "el", "zz"
- };
-
- private static class Loc implements Comparable<Object> {
- private static Collator sCollator = Collator.getInstance();
-
- private String mLabel;
- public final Locale mLocale;
-
- public Loc(String label, Locale locale) {
- this.mLabel = label;
- this.mLocale = locale;
- }
-
- public void setLabel(String label) {
- this.mLabel = label;
- }
-
- @Override
- public String toString() {
- return this.mLabel;
- }
-
- @Override
- public int compareTo(Object o) {
- return sCollator.compare(this.mLabel, ((Loc) o).mLabel);
- }
- }
-
- @Override
- protected void onCreate(Bundle icicle) {
- super.onCreate(icicle);
- addPreferencesFromResource(R.xml.language_prefs);
- // Get the settings preferences
- mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
- mSelectedLanguages = mPrefs.getString(Settings.PREF_SELECTED_LANGUAGES, "");
- String[] languageList = mSelectedLanguages.split(",");
- mAvailableLanguages = getUniqueLocales();
- PreferenceGroup parent = getPreferenceScreen();
- for (int i = 0; i < mAvailableLanguages.size(); i++) {
- CheckBoxPreference pref = new CheckBoxPreference(this);
- Locale locale = mAvailableLanguages.get(i).mLocale;
- pref.setTitle(SubtypeSwitcher.getFullDisplayName(locale, true));
- boolean checked = isLocaleIn(locale, languageList);
- pref.setChecked(checked);
- if (hasDictionary(locale)) {
- pref.setSummary(R.string.has_dictionary);
- }
- parent.addPreference(pref);
- }
- }
-
- private boolean isLocaleIn(Locale locale, String[] list) {
- String lang = get5Code(locale);
- for (int i = 0; i < list.length; i++) {
- if (lang.equalsIgnoreCase(list[i])) return true;
- }
- return false;
- }
-
- private boolean hasDictionary(Locale locale) {
- final Resources res = getResources();
- final Configuration conf = res.getConfiguration();
- final Locale saveLocale = conf.locale;
- boolean haveDictionary = false;
- conf.locale = locale;
- res.updateConfiguration(conf, res.getDisplayMetrics());
-
- int mainDicResId = Utils.getMainDictionaryResourceId(res);
- BinaryDictionary bd = BinaryDictionary.initDictionary(this, mainDicResId, Suggest.DIC_MAIN);
-
- // Is the dictionary larger than a placeholder? Arbitrarily chose a lower limit of
- // 4000-5000 words, whereas the LARGE_DICTIONARY is about 20000+ words.
- if (bd.getSize() > Suggest.LARGE_DICTIONARY_THRESHOLD / 4) {
- haveDictionary = true;
- }
- bd.close();
- conf.locale = saveLocale;
- res.updateConfiguration(conf, res.getDisplayMetrics());
- return haveDictionary;
- }
-
- private String get5Code(Locale locale) {
- String country = locale.getCountry();
- return locale.getLanguage()
- + (TextUtils.isEmpty(country) ? "" : "_" + country);
- }
-
- @Override
- protected void onResume() {
- super.onResume();
- }
-
- @Override
- protected void onPause() {
- super.onPause();
- // Save the selected languages
- String checkedLanguages = "";
- PreferenceGroup parent = getPreferenceScreen();
- int count = parent.getPreferenceCount();
- for (int i = 0; i < count; i++) {
- CheckBoxPreference pref = (CheckBoxPreference) parent.getPreference(i);
- if (pref.isChecked()) {
- Locale locale = mAvailableLanguages.get(i).mLocale;
- checkedLanguages += get5Code(locale) + ",";
- }
- }
- if (checkedLanguages.length() < 1) checkedLanguages = null; // Save null
- Editor editor = mPrefs.edit();
- editor.putString(Settings.PREF_SELECTED_LANGUAGES, checkedLanguages);
- SharedPreferencesCompat.apply(editor);
- }
-
- public ArrayList<Loc> getUniqueLocales() {
- String[] locales = getAssets().getLocales();
- Arrays.sort(locales);
- ArrayList<Loc> uniqueLocales = new ArrayList<Loc>();
-
- final int origSize = locales.length;
- Loc[] preprocess = new Loc[origSize];
- int finalSize = 0;
- for (int i = 0 ; i < origSize; i++ ) {
- String s = locales[i];
- int len = s.length();
- if (len == 5) {
- String language = s.substring(0, 2);
- String country = s.substring(3, 5);
- Locale l = new Locale(language, country);
-
- // Exclude languages that are not relevant to LatinIME
- if (arrayContains(BLACKLIST_LANGUAGES, language)) continue;
-
- if (finalSize == 0) {
- preprocess[finalSize++] =
- new Loc(SubtypeSwitcher.getFullDisplayName(l, true), l);
- } else {
- // check previous entry:
- // same lang and a country -> upgrade to full name and
- // insert ours with full name
- // diff lang -> insert ours with lang-only name
- if (preprocess[finalSize-1].mLocale.getLanguage().equals(
- language)) {
- preprocess[finalSize-1].setLabel(SubtypeSwitcher.getFullDisplayName(
- preprocess[finalSize-1].mLocale, false));
- preprocess[finalSize++] =
- new Loc(SubtypeSwitcher.getFullDisplayName(l, false), l);
- } else {
- String displayName;
- if (s.equals("zz_ZZ")) {
- // ignore this locale
- } else {
- displayName = SubtypeSwitcher.getFullDisplayName(l, true);
- preprocess[finalSize++] = new Loc(displayName, l);
- }
- }
- }
- }
- }
- for (int i = 0; i < finalSize ; i++) {
- uniqueLocales.add(preprocess[i]);
- }
- return uniqueLocales;
- }
-
- private boolean arrayContains(String[] array, String value) {
- for (int i = 0; i < array.length; i++) {
- if (array[i].equalsIgnoreCase(value)) return true;
- }
- return false;
- }
-}
diff --git a/java/src/com/android/inputmethod/latin/LatinIME.java b/java/src/com/android/inputmethod/latin/LatinIME.java
index bf831bfbc..a4a04ffb1 100644
--- a/java/src/com/android/inputmethod/latin/LatinIME.java
+++ b/java/src/com/android/inputmethod/latin/LatinIME.java
@@ -33,7 +33,6 @@ import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
-import android.os.Vibrator;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.text.InputType;
@@ -42,46 +41,43 @@ import android.util.DisplayMetrics;
import android.util.Log;
import android.util.PrintWriterPrinter;
import android.util.Printer;
-import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
-import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.CompletionInfo;
-import android.view.inputmethod.CorrectionInfo;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.ExtractedText;
-import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
-import android.view.inputmethod.InputMethodManager;
-import android.view.inputmethod.InputMethodSubtype;
-import android.widget.FrameLayout;
-import android.widget.HorizontalScrollView;
-import android.widget.LinearLayout;
+import com.android.inputmethod.compat.CompatUtils;
+import com.android.inputmethod.compat.EditorInfoCompatUtils;
+import com.android.inputmethod.compat.InputConnectionCompatUtils;
+import com.android.inputmethod.compat.InputMethodManagerCompatWrapper;
+import com.android.inputmethod.compat.InputMethodServiceCompatWrapper;
+import com.android.inputmethod.compat.InputTypeCompatUtils;
+import com.android.inputmethod.compat.SuggestionSpanUtils;
+import com.android.inputmethod.deprecated.LanguageSwitcherProxy;
+import com.android.inputmethod.deprecated.VoiceProxy;
+import com.android.inputmethod.deprecated.recorrection.Recorrection;
import com.android.inputmethod.keyboard.Keyboard;
import com.android.inputmethod.keyboard.KeyboardActionListener;
import com.android.inputmethod.keyboard.KeyboardSwitcher;
import com.android.inputmethod.keyboard.KeyboardView;
import com.android.inputmethod.keyboard.LatinKeyboard;
import com.android.inputmethod.keyboard.LatinKeyboardView;
-import com.android.inputmethod.latin.Utils.RingCharBuffer;
-import com.android.inputmethod.voice.VoiceIMEConnector;
import java.io.FileDescriptor;
import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Locale;
/**
* Input method implementation for Qwerty'ish keyboard.
*/
-public class LatinIME extends InputMethodService implements KeyboardActionListener {
+public class LatinIME extends InputMethodServiceCompatWrapper implements KeyboardActionListener {
private static final String TAG = LatinIME.class.getSimpleName();
private static final boolean PERF_DEBUG = false;
private static final boolean TRACE = false;
@@ -94,6 +90,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
*
* @deprecated Use {@link LatinIME#IME_OPTION_NO_MICROPHONE} with package name prefixed.
*/
+ @SuppressWarnings("dep-ann")
public static final String IME_OPTION_NO_MICROPHONE_COMPAT = "nm";
/**
@@ -109,9 +106,6 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
*/
public static final String IME_OPTION_NO_SETTINGS_KEY = "noSettingsKey";
- private static final int DELAY_UPDATE_SUGGESTIONS = 180;
- private static final int DELAY_UPDATE_OLD_SUGGESTIONS = 300;
- private static final int DELAY_UPDATE_SHIFT_STATE = 300;
private static final int EXTENDED_TOUCHABLE_REGION_HEIGHT = 100;
// How many continuous deletes at which to start deleting at a higher speed.
@@ -119,6 +113,12 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
// Key events coming any faster than this are long-presses.
private static final int QUICK_PRESS = 200;
+ /**
+ * The name of the scheme used by the Package Manager to warn of a new package installation,
+ * replacement or removal.
+ */
+ private static final String SCHEME_PACKAGE = "package";
+
private int mSuggestionVisibility;
private static final int SUGGESTION_VISIBILILTY_SHOW_VALUE
= R.string.prefs_suggestion_visibility_show_value;
@@ -133,55 +133,45 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
SUGGESTION_VISIBILILTY_HIDE_VALUE
};
+ private Settings.Values mSettingsValues;
+
private View mCandidateViewContainer;
+ private int mCandidateStripHeight;
private CandidateView mCandidateView;
private Suggest mSuggest;
private CompletionInfo[] mApplicationSpecifiedCompletions;
private AlertDialog mOptionsDialog;
- private InputMethodManager mImm;
+ private InputMethodManagerCompatWrapper mImm;
private Resources mResources;
private SharedPreferences mPrefs;
private String mInputMethodId;
private KeyboardSwitcher mKeyboardSwitcher;
private SubtypeSwitcher mSubtypeSwitcher;
- private VoiceIMEConnector mVoiceConnector;
+ private VoiceProxy mVoiceProxy;
+ private Recorrection mRecorrection;
private UserDictionary mUserDictionary;
private UserBigramDictionary mUserBigramDictionary;
private ContactsDictionary mContactsDictionary;
private AutoDictionary mAutoDictionary;
+ // TODO: Create an inner class to group options and pseudo-options to improve readability.
// These variables are initialized according to the {@link EditorInfo#inputType}.
- private boolean mAutoSpace;
+ private boolean mShouldInsertMagicSpace;
private boolean mInputTypeNoAutoCorrect;
private boolean mIsSettingsSuggestionStripOn;
private boolean mApplicationSpecifiedCompletionOn;
- private AccessibilityUtils mAccessibilityUtils;
-
private final StringBuilder mComposing = new StringBuilder();
private WordComposer mWord = new WordComposer();
private CharSequence mBestWord;
- private boolean mHasValidSuggestions;
+ private boolean mHasUncommittedTypedChars;
private boolean mHasDictionary;
- private boolean mJustAddedAutoSpace;
- private boolean mAutoCorrectEnabled;
- private boolean mRecorrectionEnabled;
- private boolean mBigramSuggestionEnabled;
- private boolean mAutoCorrectOn;
- private boolean mVibrateOn;
- private boolean mSoundOn;
- private boolean mPopupOn;
- private boolean mAutoCap;
- private boolean mQuickFixes;
- private boolean mConfigEnableShowSubtypeSettings;
- private boolean mConfigSwipeDownDismissKeyboardEnabled;
- private int mConfigDelayBeforeFadeoutLanguageOnSpacebar;
- private int mConfigDurationOfFadeoutLanguageOnSpacebar;
- private float mConfigFinalFadeoutFactorOfLanguageOnSpacebar;
- private long mConfigDoubleSpacesTurnIntoPeriodTimeout;
+ // Magic space: a space that should disappear on space/apostrophe insertion, move after the
+ // punctuation on punctuation insertion, and become a real space on alpha char insertion.
+ private boolean mJustAddedMagicSpace; // This indicates whether the last char is a magic space.
private int mCorrectionMode;
private int mCommittedLength;
@@ -189,7 +179,6 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
// Keep track of the last selection range to decide if we need to show word alternatives
private int mLastSelectionStart;
private int mLastSelectionEnd;
- private SuggestedWords mSuggestPuncList;
// Indicates whether the suggestion strip is to be on in landscape
private boolean mJustAccepted;
@@ -199,66 +188,18 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
private AudioManager mAudioManager;
// Align sound effect volume on music volume
private static final float FX_VOLUME = -1.0f;
- private boolean mSilentMode;
+ private boolean mSilentModeOn; // System-wide current configuration
- /* package */ String mWordSeparators;
- private String mSentenceSeparators;
- private String mSuggestPuncs;
- // TODO: Move this flag to VoiceIMEConnector
+ // TODO: Move this flag to VoiceProxy
private boolean mConfigurationChanging;
+ // Object for reacting to adding/removing a dictionary pack.
+ private BroadcastReceiver mDictionaryPackInstallReceiver =
+ new DictionaryPackInstallBroadcastReceiver(this);
+
// Keeps track of most recently inserted text (multi-character key) for reverting
private CharSequence mEnteredText;
- private final ArrayList<WordAlternatives> mWordHistory = new ArrayList<WordAlternatives>();
-
- public abstract static class WordAlternatives {
- protected CharSequence mChosenWord;
-
- public WordAlternatives() {
- // Nothing
- }
-
- public WordAlternatives(CharSequence chosenWord) {
- mChosenWord = chosenWord;
- }
-
- @Override
- public int hashCode() {
- return mChosenWord.hashCode();
- }
-
- public abstract CharSequence getOriginalWord();
-
- public CharSequence getChosenWord() {
- return mChosenWord;
- }
-
- public abstract SuggestedWords.Builder getAlternatives();
- }
-
- public class TypedWordAlternatives extends WordAlternatives {
- private WordComposer word;
-
- public TypedWordAlternatives() {
- // Nothing
- }
-
- public TypedWordAlternatives(CharSequence chosenWord, WordComposer wordComposer) {
- super(chosenWord);
- word = wordComposer;
- }
-
- @Override
- public CharSequence getOriginalWord() {
- return word.getTypedWord();
- }
-
- @Override
- public SuggestedWords.Builder getAlternatives() {
- return getTypedSuggestions(word);
- }
- }
public final UIHandler mHandler = new UIHandler();
@@ -270,44 +211,54 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
private static final int MSG_FADEOUT_LANGUAGE_ON_SPACEBAR = 4;
private static final int MSG_DISMISS_LANGUAGE_ON_SPACEBAR = 5;
private static final int MSG_SPACE_TYPED = 6;
+ private static final int MSG_SET_BIGRAM_PREDICTIONS = 7;
@Override
public void handleMessage(Message msg) {
final KeyboardSwitcher switcher = mKeyboardSwitcher;
- final LatinKeyboardView inputView = switcher.getInputView();
+ final LatinKeyboardView inputView = switcher.getKeyboardView();
switch (msg.what) {
case MSG_UPDATE_SUGGESTIONS:
updateSuggestions();
break;
case MSG_UPDATE_OLD_SUGGESTIONS:
- setOldSuggestions();
+ mRecorrection.fetchAndDisplayRecorrectionSuggestions(mVoiceProxy, mCandidateView,
+ mSuggest, mKeyboardSwitcher, mWord, mHasUncommittedTypedChars,
+ mLastSelectionStart, mLastSelectionEnd, mSettingsValues.mWordSeparators);
break;
case MSG_UPDATE_SHIFT_STATE:
switcher.updateShiftState();
break;
+ case MSG_SET_BIGRAM_PREDICTIONS:
+ updateBigramPredictions();
+ break;
case MSG_VOICE_RESULTS:
- mVoiceConnector.handleVoiceResults(preferCapitalization()
+ mVoiceProxy.handleVoiceResults(preferCapitalization()
|| (switcher.isAlphabetMode() && switcher.isShiftedOrShiftLocked()));
break;
case MSG_FADEOUT_LANGUAGE_ON_SPACEBAR:
- if (inputView != null)
+ if (inputView != null) {
inputView.setSpacebarTextFadeFactor(
- (1.0f + mConfigFinalFadeoutFactorOfLanguageOnSpacebar) / 2,
+ (1.0f + mSettingsValues.mFinalFadeoutFactorOfLanguageOnSpacebar) / 2,
(LatinKeyboard)msg.obj);
+ }
sendMessageDelayed(obtainMessage(MSG_DISMISS_LANGUAGE_ON_SPACEBAR, msg.obj),
- mConfigDurationOfFadeoutLanguageOnSpacebar);
+ mSettingsValues.mDurationOfFadeoutLanguageOnSpacebar);
break;
case MSG_DISMISS_LANGUAGE_ON_SPACEBAR:
- if (inputView != null)
+ if (inputView != null) {
inputView.setSpacebarTextFadeFactor(
- mConfigFinalFadeoutFactorOfLanguageOnSpacebar, (LatinKeyboard)msg.obj);
+ mSettingsValues.mFinalFadeoutFactorOfLanguageOnSpacebar,
+ (LatinKeyboard)msg.obj);
+ }
break;
}
}
public void postUpdateSuggestions() {
removeMessages(MSG_UPDATE_SUGGESTIONS);
- sendMessageDelayed(obtainMessage(MSG_UPDATE_SUGGESTIONS), DELAY_UPDATE_SUGGESTIONS);
+ sendMessageDelayed(obtainMessage(MSG_UPDATE_SUGGESTIONS),
+ mSettingsValues.mDelayUpdateSuggestions);
}
public void cancelUpdateSuggestions() {
@@ -321,7 +272,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
public void postUpdateOldSuggestions() {
removeMessages(MSG_UPDATE_OLD_SUGGESTIONS);
sendMessageDelayed(obtainMessage(MSG_UPDATE_OLD_SUGGESTIONS),
- DELAY_UPDATE_OLD_SUGGESTIONS);
+ mSettingsValues.mDelayUpdateOldSuggestions);
}
public void cancelUpdateOldSuggestions() {
@@ -330,13 +281,24 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
public void postUpdateShiftKeyState() {
removeMessages(MSG_UPDATE_SHIFT_STATE);
- sendMessageDelayed(obtainMessage(MSG_UPDATE_SHIFT_STATE), DELAY_UPDATE_SHIFT_STATE);
+ sendMessageDelayed(obtainMessage(MSG_UPDATE_SHIFT_STATE),
+ mSettingsValues.mDelayUpdateShiftState);
}
public void cancelUpdateShiftState() {
removeMessages(MSG_UPDATE_SHIFT_STATE);
}
+ public void postUpdateBigramPredictions() {
+ removeMessages(MSG_SET_BIGRAM_PREDICTIONS);
+ sendMessageDelayed(obtainMessage(MSG_SET_BIGRAM_PREDICTIONS),
+ mSettingsValues.mDelayUpdateSuggestions);
+ }
+
+ public void cancelUpdateBigramPredictions() {
+ removeMessages(MSG_SET_BIGRAM_PREDICTIONS);
+ }
+
public void updateVoiceResults() {
sendMessage(obtainMessage(MSG_VOICE_RESULTS));
}
@@ -344,17 +306,21 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
public void startDisplayLanguageOnSpacebar(boolean localeChanged) {
removeMessages(MSG_FADEOUT_LANGUAGE_ON_SPACEBAR);
removeMessages(MSG_DISMISS_LANGUAGE_ON_SPACEBAR);
- final LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
+ final LatinKeyboardView inputView = mKeyboardSwitcher.getKeyboardView();
if (inputView != null) {
final LatinKeyboard keyboard = mKeyboardSwitcher.getLatinKeyboard();
- // The language is never displayed when the delay is zero.
- if (mConfigDelayBeforeFadeoutLanguageOnSpacebar != 0)
- inputView.setSpacebarTextFadeFactor(localeChanged ? 1.0f
- : mConfigFinalFadeoutFactorOfLanguageOnSpacebar, keyboard);
// The language is always displayed when the delay is negative.
- if (localeChanged && mConfigDelayBeforeFadeoutLanguageOnSpacebar > 0) {
+ final boolean needsToDisplayLanguage = localeChanged
+ || mSettingsValues.mDelayBeforeFadeoutLanguageOnSpacebar < 0;
+ // The language is never displayed when the delay is zero.
+ if (mSettingsValues.mDelayBeforeFadeoutLanguageOnSpacebar != 0) {
+ inputView.setSpacebarTextFadeFactor(needsToDisplayLanguage ? 1.0f
+ : mSettingsValues.mFinalFadeoutFactorOfLanguageOnSpacebar, keyboard);
+ }
+ // The fadeout animation will start when the delay is positive.
+ if (localeChanged && mSettingsValues.mDelayBeforeFadeoutLanguageOnSpacebar > 0) {
sendMessageDelayed(obtainMessage(MSG_FADEOUT_LANGUAGE_ON_SPACEBAR, keyboard),
- mConfigDelayBeforeFadeoutLanguageOnSpacebar);
+ mSettingsValues.mDelayBeforeFadeoutLanguageOnSpacebar);
}
}
}
@@ -362,7 +328,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
public void startDoubleSpacesTimer() {
removeMessages(MSG_SPACE_TYPED);
sendMessageDelayed(obtainMessage(MSG_SPACE_TYPED),
- mConfigDoubleSpacesTurnIntoPeriodTimeout);
+ mSettingsValues.mDoubleSpacesTurnIntoPeriodTimeout);
}
public void cancelDoubleSpacesTimer() {
@@ -379,44 +345,25 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
mPrefs = prefs;
LatinImeLogger.init(this, prefs);
+ LanguageSwitcherProxy.init(this, prefs);
SubtypeSwitcher.init(this, prefs);
KeyboardSwitcher.init(this, prefs);
- AccessibilityUtils.init(this, prefs);
+ Recorrection.init(this, prefs);
super.onCreate();
- mImm = ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE));
+ mImm = InputMethodManagerCompatWrapper.getInstance(this);
mInputMethodId = Utils.getInputMethodId(mImm, getPackageName());
mSubtypeSwitcher = SubtypeSwitcher.getInstance();
mKeyboardSwitcher = KeyboardSwitcher.getInstance();
- mAccessibilityUtils = AccessibilityUtils.getInstance();
+ mRecorrection = Recorrection.getInstance();
DEBUG = LatinImeLogger.sDBG;
+ loadSettings();
+
final Resources res = getResources();
mResources = res;
- // If the option should not be shown, do not read the recorrection preference
- // but always use the default setting defined in the resources.
- if (res.getBoolean(R.bool.config_enable_show_recorrection_option)) {
- mRecorrectionEnabled = prefs.getBoolean(Settings.PREF_RECORRECTION_ENABLED,
- res.getBoolean(R.bool.config_default_recorrection_enabled));
- } else {
- mRecorrectionEnabled = res.getBoolean(R.bool.config_default_recorrection_enabled);
- }
-
- mConfigEnableShowSubtypeSettings = res.getBoolean(
- R.bool.config_enable_show_subtype_settings);
- mConfigSwipeDownDismissKeyboardEnabled = res.getBoolean(
- R.bool.config_swipe_down_dismiss_keyboard_enabled);
- mConfigDelayBeforeFadeoutLanguageOnSpacebar = res.getInteger(
- R.integer.config_delay_before_fadeout_language_on_spacebar);
- mConfigDurationOfFadeoutLanguageOnSpacebar = res.getInteger(
- R.integer.config_duration_of_fadeout_language_on_spacebar);
- mConfigFinalFadeoutFactorOfLanguageOnSpacebar = res.getInteger(
- R.integer.config_final_fadeout_percentage_of_language_on_spacebar) / 100.0f;
- mConfigDoubleSpacesTurnIntoPeriodTimeout = res.getInteger(
- R.integer.config_double_spaces_turn_into_period_timeout);
-
Utils.GCUtils.getInstance().reset();
boolean tryGC = true;
for (int i = 0; i < Utils.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) {
@@ -429,49 +376,73 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
}
mOrientation = res.getConfiguration().orientation;
- initSuggestPuncList();
- // register to receive ringer mode change and network state change.
+ // Register to receive ringer mode change and network state change.
+ // Also receive installation and removal of a dictionary pack.
final IntentFilter filter = new IntentFilter();
filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mReceiver, filter);
- mVoiceConnector = VoiceIMEConnector.init(this, prefs, mHandler);
+ mVoiceProxy = VoiceProxy.init(this, prefs, mHandler);
+
+ final IntentFilter packageFilter = new IntentFilter();
+ packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
+ packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
+ packageFilter.addDataScheme(SCHEME_PACKAGE);
+ registerReceiver(mDictionaryPackInstallReceiver, packageFilter);
+
+ final IntentFilter newDictFilter = new IntentFilter();
+ newDictFilter.addAction(
+ DictionaryPackInstallBroadcastReceiver.NEW_DICTIONARY_INTENT_ACTION);
+ registerReceiver(mDictionaryPackInstallReceiver, newDictFilter);
+ }
+
+ // Has to be package-visible for unit tests
+ /* package */ void loadSettings() {
+ if (null == mPrefs) mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
+ if (null == mSubtypeSwitcher) mSubtypeSwitcher = SubtypeSwitcher.getInstance();
+ mSettingsValues = new Settings.Values(mPrefs, this, mSubtypeSwitcher.getInputLocaleStr());
}
private void initSuggest() {
- String locale = mSubtypeSwitcher.getInputLocaleStr();
+ final String localeStr = mSubtypeSwitcher.getInputLocaleStr();
+ final Locale keyboardLocale = Utils.constructLocaleFromString(localeStr);
- Locale savedLocale = mSubtypeSwitcher.changeSystemLocale(new Locale(locale));
+ final Resources res = mResources;
+ final Locale savedLocale = Utils.setSystemLocale(res, keyboardLocale);
if (mSuggest != null) {
mSuggest.close();
}
- final SharedPreferences prefs = mPrefs;
- mQuickFixes = isQuickFixesEnabled(prefs);
- final Resources res = mResources;
int mainDicResId = Utils.getMainDictionaryResourceId(res);
- mSuggest = new Suggest(this, mainDicResId);
- loadAndSetAutoCorrectionThreshold(prefs);
+ mSuggest = new Suggest(this, mainDicResId, keyboardLocale);
+ if (mSettingsValues.mAutoCorrectEnabled) {
+ mSuggest.setAutoCorrectionThreshold(mSettingsValues.mAutoCorrectionThreshold);
+ }
updateAutoTextEnabled();
- mUserDictionary = new UserDictionary(this, locale);
+ mUserDictionary = new UserDictionary(this, localeStr);
mSuggest.setUserDictionary(mUserDictionary);
mContactsDictionary = new ContactsDictionary(this, Suggest.DIC_CONTACTS);
mSuggest.setContactsDictionary(mContactsDictionary);
- mAutoDictionary = new AutoDictionary(this, this, locale, Suggest.DIC_AUTO);
+ mAutoDictionary = new AutoDictionary(this, this, localeStr, Suggest.DIC_AUTO);
mSuggest.setAutoDictionary(mAutoDictionary);
- mUserBigramDictionary = new UserBigramDictionary(this, this, locale, Suggest.DIC_USER);
+ mUserBigramDictionary = new UserBigramDictionary(this, this, localeStr, Suggest.DIC_USER);
mSuggest.setUserBigramDictionary(mUserBigramDictionary);
updateCorrectionMode();
- mWordSeparators = res.getString(R.string.word_separators);
- mSentenceSeparators = res.getString(R.string.sentence_separators);
- mSubtypeSwitcher.changeSystemLocale(savedLocale);
+ Utils.setSystemLocale(res, savedLocale);
+ }
+
+ /* package private */ void resetSuggestMainDict() {
+ final String localeStr = mSubtypeSwitcher.getInputLocaleStr();
+ final Locale keyboardLocale = Utils.constructLocaleFromString(localeStr);
+ int mainDicResId = Utils.getMainDictionaryResourceId(mResources);
+ mSuggest.resetMainDict(this, mainDicResId, keyboardLocale);
}
@Override
@@ -481,7 +452,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
mSuggest = null;
}
unregisterReceiver(mReceiver);
- mVoiceConnector.destroy();
+ unregisterReceiver(mDictionaryPackInstallReceiver);
+ mVoiceProxy.destroy();
LatinImeLogger.commit();
LatinImeLogger.onDestroy();
super.onDestroy();
@@ -502,8 +474,11 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
mConfigurationChanging = true;
super.onConfigurationChanged(conf);
- mVoiceConnector.onConfigurationChanged(conf);
+ mVoiceProxy.onConfigurationChanged(conf);
mConfigurationChanging = false;
+
+ // This will work only when the subtype is not supported.
+ LanguageSwitcherProxy.onConfigurationChanged(conf);
}
@Override
@@ -512,26 +487,24 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
}
@Override
- public View onCreateCandidatesView() {
- LayoutInflater inflater = getLayoutInflater();
- LinearLayout container = (LinearLayout)inflater.inflate(R.layout.candidates, null);
- mCandidateViewContainer = container;
- if (container.getPaddingRight() != 0) {
- HorizontalScrollView scrollView =
- (HorizontalScrollView) container.findViewById(R.id.candidates_scroll_view);
- scrollView.setOverScrollMode(View.OVER_SCROLL_NEVER);
- container.setGravity(Gravity.CENTER_HORIZONTAL);
- }
- mCandidateView = (CandidateView) container.findViewById(R.id.candidates);
+ public void setInputView(View view) {
+ super.setInputView(view);
+ mCandidateViewContainer = view.findViewById(R.id.candidates_container);
+ mCandidateView = (CandidateView) view.findViewById(R.id.candidates);
mCandidateView.setService(this);
- setCandidatesViewShown(true);
- return container;
+ mCandidateStripHeight = (int)mResources.getDimension(R.dimen.candidate_strip_height);
+ }
+
+ @Override
+ public void setCandidatesView(View view) {
+ // To ensure that CandidatesView will never be set.
+ return;
}
@Override
public void onStartInputView(EditorInfo attribute, boolean restarting) {
final KeyboardSwitcher switcher = mKeyboardSwitcher;
- LatinKeyboardView inputView = switcher.getInputView();
+ LatinKeyboardView inputView = switcher.getKeyboardView();
if (DEBUG) {
Log.d(TAG, "onStartInputView: inputType=" + ((attribute == null) ? "none"
@@ -549,20 +522,31 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
// Most such things we decide below in initializeInputAttributesAndGetMode, but we need to
// know now whether this is a password text field, because we need to know now whether we
// want to enable the voice button.
- final VoiceIMEConnector voiceIme = mVoiceConnector;
- voiceIme.resetVoiceStates(Utils.isPasswordInputType(attribute.inputType)
- || Utils.isVisiblePasswordInputType(attribute.inputType));
+ final VoiceProxy voiceIme = mVoiceProxy;
+ voiceIme.resetVoiceStates(InputTypeCompatUtils.isPasswordInputType(attribute.inputType)
+ || InputTypeCompatUtils.isVisiblePasswordInputType(attribute.inputType));
initializeInputAttributes(attribute);
inputView.closing();
mEnteredText = null;
mComposing.setLength(0);
- mHasValidSuggestions = false;
+ mHasUncommittedTypedChars = false;
mDeleteCount = 0;
- mJustAddedAutoSpace = false;
+ mJustAddedMagicSpace = false;
+
+ loadSettings();
+ updateCorrectionMode();
+ updateAutoTextEnabled();
+ updateSuggestionVisibility(mPrefs, mResources);
+
+ if (mSuggest != null && mSettingsValues.mAutoCorrectEnabled) {
+ mSuggest.setAutoCorrectionThreshold(mSettingsValues.mAutoCorrectionThreshold);
+ }
+ mVoiceProxy.loadSettings(attribute, mPrefs);
+ // This will work only when the subtype is not supported.
+ LanguageSwitcherProxy.loadSettings();
- loadSettings(attribute);
if (mSubtypeSwitcher.isKeyboardMode()) {
switcher.loadKeyboard(attribute,
mSubtypeSwitcher.isShortcutImeEnabled() && voiceIme.isVoiceButtonEnabled(),
@@ -570,20 +554,17 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
switcher.updateShiftState();
}
- setCandidatesViewShownInternal(isCandidateStripVisible(),
- false /* needsInputViewShown */ );
+ setSuggestionStripShownInternal(isCandidateStripVisible(), /* needsInputViewShown */ false);
// Delay updating suggestions because keyboard input view may not be shown at this point.
mHandler.postUpdateSuggestions();
updateCorrectionMode();
- final boolean accessibilityEnabled = mAccessibilityUtils.isAccessibilityEnabled();
-
- inputView.setPreviewEnabled(mPopupOn);
+ inputView.setKeyPreviewPopupEnabled(mSettingsValues.mKeyPreviewPopupOn,
+ mSettingsValues.mKeyPreviewPopupDismissDelay);
inputView.setProximityCorrectionEnabled(true);
- inputView.setAccessibilityEnabled(accessibilityEnabled);
// If we just entered a text field, maybe it has some old text that requires correction
- checkRecorrectionOnStart();
+ mRecorrection.checkRecorrectionOnStart();
inputView.setForeground(true);
voiceIme.onStartInputView(inputView.getWindowToken());
@@ -596,7 +577,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
return;
final int inputType = attribute.inputType;
final int variation = inputType & InputType.TYPE_MASK_VARIATION;
- mAutoSpace = false;
+ mShouldInsertMagicSpace = false;
mInputTypeNoAutoCorrect = false;
mIsSettingsSuggestionStripOn = false;
mApplicationSpecifiedCompletionOn = false;
@@ -605,17 +586,17 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
if ((inputType & InputType.TYPE_MASK_CLASS) == InputType.TYPE_CLASS_TEXT) {
mIsSettingsSuggestionStripOn = true;
// Make sure that passwords are not displayed in candidate view
- if (Utils.isPasswordInputType(inputType)
- || Utils.isVisiblePasswordInputType(inputType)) {
+ if (InputTypeCompatUtils.isPasswordInputType(inputType)
+ || InputTypeCompatUtils.isVisiblePasswordInputType(inputType)) {
mIsSettingsSuggestionStripOn = false;
}
- if (Utils.isEmailVariation(variation)
+ if (InputTypeCompatUtils.isEmailVariation(variation)
|| variation == InputType.TYPE_TEXT_VARIATION_PERSON_NAME) {
- mAutoSpace = false;
+ mShouldInsertMagicSpace = false;
} else {
- mAutoSpace = true;
+ mShouldInsertMagicSpace = true;
}
- if (Utils.isEmailVariation(variation)) {
+ if (InputTypeCompatUtils.isEmailVariation(variation)) {
mIsSettingsSuggestionStripOn = false;
} else if (variation == InputType.TYPE_TEXT_VARIATION_URI) {
mIsSettingsSuggestionStripOn = false;
@@ -646,32 +627,11 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
}
}
- private void checkRecorrectionOnStart() {
- if (!mRecorrectionEnabled) return;
-
- final InputConnection ic = getCurrentInputConnection();
- if (ic == null) return;
- // There could be a pending composing span. Clean it up first.
- ic.finishComposingText();
-
- if (isShowingSuggestionsStrip() && isSuggestionsRequested()) {
- // First get the cursor position. This is required by setOldSuggestions(), so that
- // it can pass the correct range to setComposingRegion(). At this point, we don't
- // have valid values for mLastSelectionStart/End because onUpdateSelection() has
- // not been called yet.
- ExtractedTextRequest etr = new ExtractedTextRequest();
- etr.token = 0; // anything is fine here
- ExtractedText et = ic.getExtractedText(etr, 0);
- if (et == null) return;
-
- mLastSelectionStart = et.startOffset + et.selectionStart;
- mLastSelectionEnd = et.startOffset + et.selectionEnd;
-
- // Then look for possible corrections in a delayed fashion
- if (!TextUtils.isEmpty(et.text) && isCursorTouchingWord()) {
- mHandler.postUpdateOldSuggestions();
- }
- }
+ @Override
+ public void onWindowHidden() {
+ super.onWindowHidden();
+ KeyboardView inputView = mKeyboardSwitcher.getKeyboardView();
+ if (inputView != null) inputView.closing();
}
@Override
@@ -681,9 +641,9 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
LatinImeLogger.commit();
mKeyboardSwitcher.onAutoCorrectionStateChanged(false);
- mVoiceConnector.flushVoiceInputLogs(mConfigurationChanging);
+ mVoiceProxy.flushVoiceInputLogs(mConfigurationChanging);
- KeyboardView inputView = mKeyboardSwitcher.getInputView();
+ KeyboardView inputView = mKeyboardSwitcher.getKeyboardView();
if (inputView != null) inputView.closing();
if (mAutoDictionary != null) mAutoDictionary.flushPendingWrites();
if (mUserBigramDictionary != null) mUserBigramDictionary.flushPendingWrites();
@@ -692,7 +652,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
@Override
public void onFinishInputView(boolean finishingInput) {
super.onFinishInputView(finishingInput);
- KeyboardView inputView = mKeyboardSwitcher.getInputView();
+ KeyboardView inputView = mKeyboardSwitcher.getKeyboardView();
if (inputView != null) inputView.setForeground(false);
// Remove pending messages related to update suggestions
mHandler.cancelUpdateSuggestions();
@@ -702,7 +662,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
@Override
public void onUpdateExtractedText(int token, ExtractedText text) {
super.onUpdateExtractedText(token, text);
- mVoiceConnector.showPunctuationHintIfNecessary();
+ mVoiceProxy.showPunctuationHintIfNecessary();
}
@Override
@@ -723,36 +683,41 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
+ ", ce=" + candidatesEnd);
}
- mVoiceConnector.setCursorAndSelection(newSelEnd, newSelStart);
+ mVoiceProxy.setCursorAndSelection(newSelEnd, newSelStart);
// If the current selection in the text view changes, we should
// clear whatever candidate text we have.
final boolean selectionChanged = (newSelStart != candidatesEnd
|| newSelEnd != candidatesEnd) && mLastSelectionStart != newSelStart;
final boolean candidatesCleared = candidatesStart == -1 && candidatesEnd == -1;
- if (((mComposing.length() > 0 && mHasValidSuggestions)
- || mVoiceConnector.isVoiceInputHighlighted())
+ if (((mComposing.length() > 0 && mHasUncommittedTypedChars)
+ || mVoiceProxy.isVoiceInputHighlighted())
&& (selectionChanged || candidatesCleared)) {
if (candidatesCleared) {
// If the composing span has been cleared, save the typed word in the history for
// recorrection before we reset the candidate strip. Then, we'll be able to show
// suggestions for recorrection right away.
- saveWordInHistory(mComposing);
+ mRecorrection.saveRecorrectionSuggestion(mWord, mComposing);
}
mComposing.setLength(0);
- mHasValidSuggestions = false;
- mHandler.postUpdateSuggestions();
+ mHasUncommittedTypedChars = false;
+ if (isCursorTouchingWord()) {
+ mHandler.cancelUpdateBigramPredictions();
+ mHandler.postUpdateSuggestions();
+ } else {
+ setPunctuationSuggestions();
+ }
TextEntryState.reset();
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.finishComposingText();
}
- mVoiceConnector.setVoiceInputHighlighted(false);
- } else if (!mHasValidSuggestions && !mJustAccepted) {
+ mVoiceProxy.setVoiceInputHighlighted(false);
+ } else if (!mHasUncommittedTypedChars && !mJustAccepted) {
if (TextEntryState.isAcceptedDefault() || TextEntryState.isSpaceAfterPicked()) {
if (TextEntryState.isAcceptedDefault())
TextEntryState.reset();
- mJustAddedAutoSpace = false; // The user moved the cursor.
+ mJustAddedMagicSpace = false; // The user moved the cursor.
}
}
mJustAccepted = false;
@@ -762,28 +727,15 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
mLastSelectionStart = newSelStart;
mLastSelectionEnd = newSelEnd;
- if (mRecorrectionEnabled && isShowingSuggestionsStrip()) {
- // Don't look for corrections if the keyboard is not visible
- if (mKeyboardSwitcher.isInputViewShown()) {
- // Check if we should go in or out of correction mode.
- if (isSuggestionsRequested()
- && (candidatesStart == candidatesEnd || newSelStart != oldSelStart
- || TextEntryState.isRecorrecting())
- && (newSelStart < newSelEnd - 1 || !mHasValidSuggestions)) {
- if (isCursorTouchingWord() || mLastSelectionStart < mLastSelectionEnd) {
- mHandler.postUpdateOldSuggestions();
- } else {
- abortRecorrection(false);
- // Show the punctuation suggestions list if the current one is not
- // and if not showing "Touch again to save".
- if (mCandidateView != null && !isShowingPunctuationList()
- && !mCandidateView.isShowingAddToDictionaryHint()) {
- setPunctuationSuggestions();
- }
- }
- }
- }
- }
+ mRecorrection.updateRecorrectionSelection(mKeyboardSwitcher,
+ mCandidateView, candidatesStart, candidatesEnd, newSelStart,
+ newSelEnd, oldSelStart, mLastSelectionStart,
+ mLastSelectionEnd, mHasUncommittedTypedChars);
+ }
+
+ public void setLastSelection(int start, int end) {
+ mLastSelectionStart = start;
+ mLastSelectionEnd = end;
}
/**
@@ -796,7 +748,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
*/
@Override
public void onExtractedTextClicked() {
- if (mRecorrectionEnabled && isSuggestionsRequested()) return;
+ if (mRecorrection.isRecorrectionEnabled() && isSuggestionsRequested()) return;
super.onExtractedTextClicked();
}
@@ -812,7 +764,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
*/
@Override
public void onExtractedCursorMovement(int dx, int dy) {
- if (mRecorrectionEnabled && isSuggestionsRequested()) return;
+ if (mRecorrection.isRecorrectionEnabled() && isSuggestionsRequested()) return;
super.onExtractedCursorMovement(dx, dy);
}
@@ -827,8 +779,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
mOptionsDialog.dismiss();
mOptionsDialog = null;
}
- mVoiceConnector.hideVoiceWindow(mConfigurationChanging);
- mWordHistory.clear();
+ mVoiceProxy.hideVoiceWindow(mConfigurationChanging);
+ mRecorrection.clearWordsInHistory();
super.hideWindow();
}
@@ -856,57 +808,58 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
// When in fullscreen mode, show completions generated by the application
setSuggestions(builder.build());
mBestWord = null;
- setCandidatesViewShown(true);
+ setSuggestionStripShown(true);
}
}
- private void setCandidatesViewShownInternal(boolean shown, boolean needsInputViewShown) {
- // TODO: Remove this if we support candidates with hard keyboard
+ private void setSuggestionStripShownInternal(boolean shown, boolean needsInputViewShown) {
+ // TODO: Modify this if we support candidates with hard keyboard
if (onEvaluateInputViewShown()) {
- super.setCandidatesViewShown(shown
- && (needsInputViewShown ? mKeyboardSwitcher.isInputViewShown() : true));
+ final boolean shouldShowCandidates = shown
+ && (needsInputViewShown ? mKeyboardSwitcher.isInputViewShown() : true);
+ if (isExtractViewShown()) {
+ // No need to have extra space to show the key preview.
+ mCandidateViewContainer.setMinimumHeight(0);
+ mCandidateViewContainer.setVisibility(
+ shouldShowCandidates ? View.VISIBLE : View.GONE);
+ } else {
+ // We must control the visibility of the suggestion strip in order to avoid clipped
+ // key previews, even when we don't show the suggestion strip.
+ mCandidateViewContainer.setVisibility(
+ shouldShowCandidates ? View.VISIBLE : View.INVISIBLE);
+ }
}
}
- @Override
- public void setCandidatesViewShown(boolean shown) {
- setCandidatesViewShownInternal(shown, true /* needsInputViewShown */ );
+ private void setSuggestionStripShown(boolean shown) {
+ setSuggestionStripShownInternal(shown, /* needsInputViewShown */true);
}
@Override
public void onComputeInsets(InputMethodService.Insets outInsets) {
super.onComputeInsets(outInsets);
- if (!isFullscreenMode()) {
- outInsets.contentTopInsets = outInsets.visibleTopInsets;
- }
- KeyboardView inputView = mKeyboardSwitcher.getInputView();
+ final KeyboardView inputView = mKeyboardSwitcher.getKeyboardView();
+ if (inputView == null)
+ return;
+ final int containerHeight = mCandidateViewContainer.getHeight();
+ int touchY = containerHeight;
// Need to set touchable region only if input view is being shown
- if (inputView != null && mKeyboardSwitcher.isInputViewShown()) {
- final int x = 0;
- int y = 0;
- final int width = inputView.getWidth();
- int height = inputView.getHeight() + EXTENDED_TOUCHABLE_REGION_HEIGHT;
- if (mCandidateViewContainer != null) {
- ViewParent candidateParent = mCandidateViewContainer.getParent();
- if (candidateParent instanceof FrameLayout) {
- FrameLayout fl = (FrameLayout) candidateParent;
- if (fl != null) {
- // Check frame layout's visibility
- if (fl.getVisibility() == View.INVISIBLE) {
- y = fl.getHeight();
- height += y;
- } else if (fl.getVisibility() == View.VISIBLE) {
- height += fl.getHeight();
- }
- }
- }
+ if (mKeyboardSwitcher.isInputViewShown()) {
+ if (mCandidateViewContainer.getVisibility() == View.VISIBLE) {
+ touchY -= mCandidateStripHeight;
}
+ final int touchWidth = inputView.getWidth();
+ final int touchHeight = inputView.getHeight() + containerHeight
+ // Extend touchable region below the keyboard.
+ + EXTENDED_TOUCHABLE_REGION_HEIGHT;
if (DEBUG) {
- Log.d(TAG, "Touchable region " + x + ", " + y + ", " + width + ", " + height);
+ Log.d(TAG, "Touchable region: y=" + touchY + " width=" + touchWidth
+ + " height=" + touchHeight);
}
- outInsets.touchableInsets = InputMethodService.Insets.TOUCHABLE_INSETS_REGION;
- outInsets.touchableRegion.set(x, y, width, height);
+ setTouchableRegionCompat(outInsets, 0, touchY, touchWidth, touchHeight);
}
+ outInsets.contentTopInsets = touchY;
+ outInsets.visibleTopInsets = touchY;
}
@Override
@@ -927,8 +880,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
- if (event.getRepeatCount() == 0 && mKeyboardSwitcher.getInputView() != null) {
- if (mKeyboardSwitcher.getInputView().handleBack()) {
+ if (event.getRepeatCount() == 0 && mKeyboardSwitcher.getKeyboardView() != null) {
+ if (mKeyboardSwitcher.getKeyboardView().handleBack()) {
return true;
}
}
@@ -962,8 +915,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
}
public void commitTyped(InputConnection inputConnection) {
- if (mHasValidSuggestions) {
- mHasValidSuggestions = false;
+ if (mHasUncommittedTypedChars) {
+ mHasUncommittedTypedChars = false;
if (mComposing.length() > 0) {
if (inputConnection != null) {
inputConnection.commitText(mComposing, 1);
@@ -979,45 +932,29 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
public boolean getCurrentAutoCapsState() {
InputConnection ic = getCurrentInputConnection();
EditorInfo ei = getCurrentInputEditorInfo();
- if (mAutoCap && ic != null && ei != null && ei.inputType != InputType.TYPE_NULL) {
+ if (mSettingsValues.mAutoCap && ic != null && ei != null
+ && ei.inputType != InputType.TYPE_NULL) {
return ic.getCursorCapsMode(ei.inputType) != 0;
}
return false;
}
- private void swapPunctuationAndSpace() {
+ private void swapSwapperAndSpace() {
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
CharSequence lastTwo = ic.getTextBeforeCursor(2, 0);
+ // It is guaranteed lastTwo.charAt(1) is a swapper - else this method is not called.
if (lastTwo != null && lastTwo.length() == 2
- && lastTwo.charAt(0) == Keyboard.CODE_SPACE
- && isSentenceSeparator(lastTwo.charAt(1))) {
+ && lastTwo.charAt(0) == Keyboard.CODE_SPACE) {
ic.beginBatchEdit();
ic.deleteSurroundingText(2, 0);
ic.commitText(lastTwo.charAt(1) + " ", 1);
ic.endBatchEdit();
mKeyboardSwitcher.updateShiftState();
- mJustAddedAutoSpace = true;
}
}
- private void reswapPeriodAndSpace() {
- final InputConnection ic = getCurrentInputConnection();
- if (ic == null) return;
- CharSequence lastThree = ic.getTextBeforeCursor(3, 0);
- if (lastThree != null && lastThree.length() == 3
- && lastThree.charAt(0) == Keyboard.CODE_PERIOD
- && lastThree.charAt(1) == Keyboard.CODE_SPACE
- && lastThree.charAt(2) == Keyboard.CODE_PERIOD) {
- ic.beginBatchEdit();
- ic.deleteSurroundingText(3, 0);
- ic.commitText(" ..", 1);
- ic.endBatchEdit();
- mKeyboardSwitcher.updateShiftState();
- }
- }
-
- private void doubleSpace() {
+ private void maybeDoubleSpace() {
if (mCorrectionMode == Suggest.CORRECTION_NONE) return;
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
@@ -1033,7 +970,6 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
ic.commitText(". ", 1);
ic.endBatchEdit();
mKeyboardSwitcher.updateShiftState();
- mJustAddedAutoSpace = true;
} else {
mHandler.startDoubleSpacesTimer();
}
@@ -1081,14 +1017,14 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
}
private void onSettingsKeyPressed() {
- if (!isShowingOptionDialog()) {
- if (!mConfigEnableShowSubtypeSettings) {
- showSubtypeSelectorAndSettings();
- } else if (Utils.hasMultipleEnabledIMEsOrSubtypes(mImm)) {
- showOptionsMenu();
- } else {
- launchSettings();
- }
+ if (isShowingOptionDialog())
+ return;
+ if (InputMethodServiceCompatWrapper.CAN_HANDLE_ON_CURRENT_INPUT_METHOD_SUBTYPE_CHANGED) {
+ showSubtypeSelectorAndSettings();
+ } else if (Utils.hasMultipleEnabledIMEsOrSubtypes(mImm)) {
+ showOptionsMenu();
+ } else {
+ launchSettings();
}
}
@@ -1115,7 +1051,6 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
}
mLastKeyTime = when;
KeyboardSwitcher switcher = mKeyboardSwitcher;
- final boolean accessibilityEnabled = switcher.isAccessibilityEnabled();
final boolean distinctMultiTouch = switcher.hasDistinctMultitouch();
switch (primaryCode) {
case Keyboard.CODE_DELETE:
@@ -1125,12 +1060,12 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
break;
case Keyboard.CODE_SHIFT:
// Shift key is handled in onPress() when device has distinct multi-touch panel.
- if (!distinctMultiTouch || accessibilityEnabled)
+ if (!distinctMultiTouch)
switcher.toggleShift();
break;
case Keyboard.CODE_SWITCH_ALPHA_SYMBOL:
// Symbol key is handled in onPress() when device has distinct multi-touch panel.
- if (!distinctMultiTouch || accessibilityEnabled)
+ if (!distinctMultiTouch)
switcher.changeKeyboardMode();
break;
case Keyboard.CODE_CANCEL:
@@ -1144,29 +1079,24 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
case Keyboard.CODE_SETTINGS_LONGPRESS:
onSettingsKeyLongPressed();
break;
- case Keyboard.CODE_NEXT_LANGUAGE:
- toggleLanguage(false, true);
+ case LatinKeyboard.CODE_NEXT_LANGUAGE:
+ toggleLanguage(true);
break;
- case Keyboard.CODE_PREV_LANGUAGE:
- toggleLanguage(false, false);
+ case LatinKeyboard.CODE_PREV_LANGUAGE:
+ toggleLanguage(false);
break;
case Keyboard.CODE_CAPSLOCK:
switcher.toggleCapsLock();
break;
- case Keyboard.CODE_VOICE:
+ case Keyboard.CODE_SHORTCUT:
mSubtypeSwitcher.switchToShortcutIME();
break;
case Keyboard.CODE_TAB:
handleTab();
break;
default:
- if (primaryCode != Keyboard.CODE_ENTER) {
- mJustAddedAutoSpace = false;
- }
- RingCharBuffer.getInstance().push((char)primaryCode, x, y);
- LatinImeLogger.logOnInputChar();
- if (isWordSeparator(primaryCode)) {
- handleSeparator(primaryCode);
+ if (mSettingsValues.isWordSeparator(primaryCode)) {
+ handleSeparator(primaryCode, x, y);
} else {
handleCharacter(primaryCode, keyCodes, x, y);
}
@@ -1178,10 +1108,10 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
@Override
public void onTextInput(CharSequence text) {
- mVoiceConnector.commitVoiceInput();
+ mVoiceProxy.commitVoiceInput();
InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
- abortRecorrection(false);
+ mRecorrection.abortRecorrection(false);
ic.beginBatchEdit();
commitTyped(ic);
maybeRemovePreviousPeriod(text);
@@ -1189,7 +1119,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
ic.endBatchEdit();
mKeyboardSwitcher.updateShiftState();
mKeyboardSwitcher.onKey(Keyboard.CODE_DUMMY);
- mJustAddedAutoSpace = false;
+ mJustAddedMagicSpace = false;
mEnteredText = text;
}
@@ -1200,25 +1130,32 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
}
private void handleBackspace() {
- if (mVoiceConnector.logAndRevertVoiceInput()) return;
+ if (mVoiceProxy.logAndRevertVoiceInput()) return;
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
ic.beginBatchEdit();
- mVoiceConnector.handleBackspace();
+ mVoiceProxy.handleBackspace();
boolean deleteChar = false;
- if (mHasValidSuggestions) {
+ if (mHasUncommittedTypedChars) {
final int length = mComposing.length();
if (length > 0) {
mComposing.delete(length - 1, length);
mWord.deleteLast();
ic.setComposingText(mComposing, 1);
if (mComposing.length() == 0) {
- mHasValidSuggestions = false;
+ mHasUncommittedTypedChars = false;
+ }
+ if (1 == length) {
+ // 1 == length means we are about to erase the last character of the word,
+ // so we can show bigrams.
+ mHandler.postUpdateBigramPredictions();
+ } else {
+ // length > 1, so we still have letters to deduce a suggestion from.
+ mHandler.postUpdateSuggestions();
}
- mHandler.postUpdateSuggestions();
} else {
ic.deleteSurroundingText(1, 0);
}
@@ -1258,9 +1195,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
private void handleTab() {
final int imeOptions = getCurrentInputEditorInfo().imeOptions;
- final int navigationFlags =
- EditorInfo.IME_FLAG_NAVIGATE_NEXT | EditorInfo.IME_FLAG_NAVIGATE_PREVIOUS;
- if ((imeOptions & navigationFlags) == 0) {
+ if (!EditorInfoCompatUtils.hasFlagNavigateNext(imeOptions)
+ && !EditorInfoCompatUtils.hasFlagNavigatePrevious(imeOptions)) {
sendDownUpKeyEvents(KeyEvent.KEYCODE_TAB);
return;
}
@@ -1271,37 +1207,33 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
// True if keyboard is in either chording shift or manual temporary upper case mode.
final boolean isManualTemporaryUpperCase = mKeyboardSwitcher.isManualTemporaryUpperCase();
- if ((imeOptions & EditorInfo.IME_FLAG_NAVIGATE_NEXT) != 0
+ if (EditorInfoCompatUtils.hasFlagNavigateNext(imeOptions)
&& !isManualTemporaryUpperCase) {
+ EditorInfoCompatUtils.performEditorActionNext(ic);
ic.performEditorAction(EditorInfo.IME_ACTION_NEXT);
- } else if ((imeOptions & EditorInfo.IME_FLAG_NAVIGATE_PREVIOUS) != 0
+ } else if (EditorInfoCompatUtils.hasFlagNavigatePrevious(imeOptions)
&& isManualTemporaryUpperCase) {
- ic.performEditorAction(EditorInfo.IME_ACTION_PREVIOUS);
- }
- }
-
- private void abortRecorrection(boolean force) {
- if (force || TextEntryState.isRecorrecting()) {
- TextEntryState.onAbortRecorrection();
- setCandidatesViewShown(isCandidateStripVisible());
- getCurrentInputConnection().finishComposingText();
- clearSuggestions();
+ EditorInfoCompatUtils.performEditorActionPrevious(ic);
}
}
private void handleCharacter(int primaryCode, int[] keyCodes, int x, int y) {
- mVoiceConnector.handleCharacter();
+ mVoiceProxy.handleCharacter();
- if (mLastSelectionStart == mLastSelectionEnd && TextEntryState.isRecorrecting()) {
- abortRecorrection(false);
+ if (mJustAddedMagicSpace && mSettingsValues.isMagicSpaceStripper(primaryCode)) {
+ removeTrailingSpace();
+ }
+
+ if (mLastSelectionStart == mLastSelectionEnd) {
+ mRecorrection.abortRecorrection(false);
}
int code = primaryCode;
if (isAlphabet(code) && isSuggestionsRequested() && !isCursorTouchingWord()) {
- if (!mHasValidSuggestions) {
- mHasValidSuggestions = true;
+ if (!mHasUncommittedTypedChars) {
+ mHasUncommittedTypedChars = true;
mComposing.setLength(0);
- saveWordInHistory(mBestWord);
+ mRecorrection.saveRecorrectionSuggestion(mWord, mBestWord);
mWord.reset();
clearSuggestions();
}
@@ -1325,7 +1257,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
}
}
}
- if (mHasValidSuggestions) {
+ if (mHasUncommittedTypedChars) {
if (mComposing.length() == 0 && switcher.isAlphabetMode()
&& switcher.isShiftedOrShiftLocked()) {
mWord.setFirstCharCapitalized(true);
@@ -1344,16 +1276,23 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
} else {
sendKeyChar((char)code);
}
+ if (mJustAddedMagicSpace && mSettingsValues.isMagicSpaceSwapper(primaryCode)) {
+ swapSwapperAndSpace();
+ } else {
+ mJustAddedMagicSpace = false;
+ }
+
switcher.updateShiftState();
if (LatinIME.PERF_DEBUG) measureCps();
- TextEntryState.typedCharacter((char) code, isWordSeparator(code));
+ TextEntryState.typedCharacter((char) code, mSettingsValues.isWordSeparator(code), x, y);
}
- private void handleSeparator(int primaryCode) {
- mVoiceConnector.handleSeparator();
+ private void handleSeparator(int primaryCode, int x, int y) {
+ mVoiceProxy.handleSeparator();
// Should dismiss the "Touch again to save" message when handling separator
if (mCandidateView != null && mCandidateView.dismissAddToDictionaryHint()) {
+ mHandler.cancelUpdateBigramPredictions();
mHandler.postUpdateSuggestions();
}
@@ -1362,54 +1301,61 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
final InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.beginBatchEdit();
- abortRecorrection(false);
+ mRecorrection.abortRecorrection(false);
}
- if (mHasValidSuggestions) {
+ if (mHasUncommittedTypedChars) {
// In certain languages where single quote is a separator, it's better
// not to auto correct, but accept the typed word. For instance,
// in Italian dov' should not be expanded to dove' because the elision
// requires the last vowel to be removed.
- if (mAutoCorrectOn && primaryCode != '\'') {
- pickedDefault = pickDefaultSuggestion();
- // Picked the suggestion by the space key. We consider this
- // as "added an auto space".
- if (primaryCode == Keyboard.CODE_SPACE) {
- mJustAddedAutoSpace = true;
- }
+ final boolean shouldAutoCorrect =
+ (mSettingsValues.mAutoCorrectEnabled || mSettingsValues.mQuickFixes)
+ && !mInputTypeNoAutoCorrect && mHasDictionary;
+ if (shouldAutoCorrect && primaryCode != Keyboard.CODE_SINGLE_QUOTE) {
+ pickedDefault = pickDefaultSuggestion(primaryCode);
} else {
commitTyped(ic);
}
}
- if (mJustAddedAutoSpace && primaryCode == Keyboard.CODE_ENTER) {
- removeTrailingSpace();
- mJustAddedAutoSpace = false;
- }
- sendKeyChar((char)primaryCode);
- // Handle the case of ". ." -> " .." with auto-space if necessary
- // before changing the TextEntryState.
- if (TextEntryState.isPunctuationAfterAccepted() && primaryCode == Keyboard.CODE_PERIOD) {
- reswapPeriodAndSpace();
+ if (mJustAddedMagicSpace) {
+ if (mSettingsValues.isMagicSpaceSwapper(primaryCode)) {
+ sendKeyChar((char)primaryCode);
+ swapSwapperAndSpace();
+ } else {
+ if (mSettingsValues.isMagicSpaceStripper(primaryCode)) removeTrailingSpace();
+ sendKeyChar((char)primaryCode);
+ mJustAddedMagicSpace = false;
+ }
+ } else {
+ sendKeyChar((char)primaryCode);
}
- TextEntryState.typedCharacter((char) primaryCode, true);
- if (TextEntryState.isPunctuationAfterAccepted() && primaryCode != Keyboard.CODE_ENTER) {
- swapPunctuationAndSpace();
- } else if (isSuggestionsRequested() && primaryCode == Keyboard.CODE_SPACE) {
- doubleSpace();
+ if (isSuggestionsRequested() && primaryCode == Keyboard.CODE_SPACE) {
+ maybeDoubleSpace();
}
+
+ TextEntryState.typedCharacter((char) primaryCode, true, x, y);
+
if (pickedDefault) {
CharSequence typedWord = mWord.getTypedWord();
TextEntryState.backToAcceptedDefault(typedWord);
if (!TextUtils.isEmpty(typedWord) && !typedWord.equals(mBestWord)) {
- if (ic != null) {
- CorrectionInfo correctionInfo = new CorrectionInfo(
- mLastSelectionEnd - typedWord.length(), typedWord, mBestWord);
- ic.commitCorrection(correctionInfo);
- }
+ InputConnectionCompatUtils.commitCorrection(
+ ic, mLastSelectionEnd - typedWord.length(), typedWord, mBestWord);
if (mCandidateView != null)
mCandidateView.onAutoCorrectionInverted(mBestWord);
}
+ }
+ if (Keyboard.CODE_SPACE == primaryCode) {
+ if (!isCursorTouchingWord()) {
+ mHandler.cancelUpdateSuggestions();
+ mHandler.cancelUpdateOldSuggestions();
+ mHandler.postUpdateBigramPredictions();
+ }
+ } else {
+ // Set punctuation right away. onUpdateSelection will fire but tests whether it is
+ // already displayed or not, so it's okay.
setPunctuationSuggestions();
}
mKeyboardSwitcher.updateShiftState();
@@ -1420,45 +1366,29 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
private void handleClose() {
commitTyped(getCurrentInputConnection());
- mVoiceConnector.handleClose();
+ mVoiceProxy.handleClose();
requestHideSelf(0);
- LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
+ LatinKeyboardView inputView = mKeyboardSwitcher.getKeyboardView();
if (inputView != null)
inputView.closing();
}
- private void saveWordInHistory(CharSequence result) {
- if (mWord.size() <= 1) {
- return;
- }
- // Skip if result is null. It happens in some edge case.
- if (TextUtils.isEmpty(result)) {
- return;
- }
-
- // Make a copy of the CharSequence, since it is/could be a mutable CharSequence
- final String resultCopy = result.toString();
- TypedWordAlternatives entry = new TypedWordAlternatives(resultCopy,
- new WordComposer(mWord));
- mWordHistory.add(entry);
- }
-
- private boolean isSuggestionsRequested() {
+ public boolean isSuggestionsRequested() {
return mIsSettingsSuggestionStripOn
&& (mCorrectionMode > 0 || isShowingSuggestionsStrip());
}
- private boolean isShowingPunctuationList() {
- return mSuggestPuncList == mCandidateView.getSuggestions();
+ public boolean isShowingPunctuationList() {
+ return mSettingsValues.mSuggestPuncList == mCandidateView.getSuggestions();
}
- private boolean isShowingSuggestionsStrip() {
+ public boolean isShowingSuggestionsStrip() {
return (mSuggestionVisibility == SUGGESTION_VISIBILILTY_SHOW_VALUE)
|| (mSuggestionVisibility == SUGGESTION_VISIBILILTY_SHOW_ONLY_PORTRAIT_VALUE
&& mOrientation == Configuration.ORIENTATION_PORTRAIT);
}
- private boolean isCandidateStripVisible() {
+ public boolean isCandidateStripVisible() {
if (mCandidateView == null)
return false;
if (mCandidateView.isShowingAddToDictionaryHint() || TextEntryState.isRecorrecting())
@@ -1474,7 +1404,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
if (DEBUG) {
Log.d(TAG, "Switch to keyboard view.");
}
- View v = mKeyboardSwitcher.getInputView();
+ View v = mKeyboardSwitcher.getKeyboardView();
if (v != null) {
// Confirms that the keyboard view doesn't have parent view.
ViewParent p = v.getParent();
@@ -1483,7 +1413,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
}
setInputView(v);
}
- setCandidatesViewShown(isCandidateStripVisible());
+ setSuggestionStripShown(isCandidateStripVisible());
updateInputViewShown();
mHandler.postUpdateSuggestions();
}
@@ -1493,9 +1423,9 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
}
public void setSuggestions(SuggestedWords words) {
- if (mVoiceConnector.getAndResetIsShowingHint()) {
- setCandidatesView(mCandidateViewContainer);
- }
+// if (mVoiceProxy.getAndResetIsShowingHint()) {
+// setCandidatesView(mCandidateViewContainer);
+// }
if (mCandidateView != null) {
mCandidateView.setSuggestions(words);
@@ -1509,33 +1439,23 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
public void updateSuggestions() {
// Check if we have a suggestion engine attached.
if ((mSuggest == null || !isSuggestionsRequested())
- && !mVoiceConnector.isVoiceInputHighlighted()) {
+ && !mVoiceProxy.isVoiceInputHighlighted()) {
return;
}
- if (!mHasValidSuggestions) {
+ if (!mHasUncommittedTypedChars) {
setPunctuationSuggestions();
return;
}
showSuggestions(mWord);
}
- private SuggestedWords.Builder getTypedSuggestions(WordComposer word) {
- return mSuggest.getSuggestedWordBuilder(mKeyboardSwitcher.getInputView(), word, null);
- }
-
- private void showCorrections(WordAlternatives alternatives) {
- SuggestedWords.Builder builder = alternatives.getAlternatives();
- builder.setTypedWordValid(false).setHasMinimalSuggestion(false);
- showSuggestions(builder.build(), alternatives.getOriginalWord());
- }
-
private void showSuggestions(WordComposer word) {
// TODO: May need a better way of retrieving previous word
CharSequence prevWord = EditingUtils.getPreviousWord(getCurrentInputConnection(),
- mWordSeparators);
+ mSettingsValues.mWordSeparators);
SuggestedWords.Builder builder = mSuggest.getSuggestedWordBuilder(
- mKeyboardSwitcher.getInputView(), word, prevWord);
+ mKeyboardSwitcher.getKeyboardView(), word, prevWord);
boolean correctionAvailable = !mInputTypeNoAutoCorrect && mSuggest.hasAutoCorrection();
final CharSequence typedWord = word.getTypedWord();
@@ -1556,19 +1476,22 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
// in most cases, suggestion count is 1 when typed word's length is 1, but we do always
// need to clear the previous state when the user starts typing a word (i.e. typed word's
// length == 1).
- if (builder.size() > 1 || typedWord.length() == 1 || typedWordValid
- || mCandidateView.isShowingAddToDictionaryHint()) {
- builder.setTypedWordValid(typedWordValid).setHasMinimalSuggestion(correctionAvailable);
- } else {
- final SuggestedWords previousSuggestions = mCandidateView.getSuggestions();
- if (previousSuggestions == mSuggestPuncList)
- return;
- builder.addTypedWordAndPreviousSuggestions(typedWord, previousSuggestions);
+ if (typedWord != null) {
+ if (builder.size() > 1 || typedWord.length() == 1 || typedWordValid
+ || mCandidateView.isShowingAddToDictionaryHint()) {
+ builder.setTypedWordValid(typedWordValid).setHasMinimalSuggestion(
+ correctionAvailable);
+ } else {
+ final SuggestedWords previousSuggestions = mCandidateView.getSuggestions();
+ if (previousSuggestions == mSettingsValues.mSuggestPuncList)
+ return;
+ builder.addTypedWordAndPreviousSuggestions(typedWord, previousSuggestions);
+ }
}
showSuggestions(builder.build(), typedWord);
}
- private void showSuggestions(SuggestedWords suggestedWords, CharSequence typedWord) {
+ public void showSuggestions(SuggestedWords suggestedWords, CharSequence typedWord) {
setSuggestions(suggestedWords);
if (suggestedWords.size() > 0) {
if (Utils.shouldBlockedBySafetyNetForAutoCorrection(suggestedWords, mSuggest)) {
@@ -1581,30 +1504,30 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
} else {
mBestWord = null;
}
- setCandidatesViewShown(isCandidateStripVisible());
+ setSuggestionStripShown(isCandidateStripVisible());
}
- private boolean pickDefaultSuggestion() {
+ private boolean pickDefaultSuggestion(int separatorCode) {
// Complete any pending candidate query first
if (mHandler.hasPendingUpdateSuggestions()) {
mHandler.cancelUpdateSuggestions();
updateSuggestions();
}
if (mBestWord != null && mBestWord.length() > 0) {
- TextEntryState.acceptedDefault(mWord.getTypedWord(), mBestWord);
+ TextEntryState.acceptedDefault(mWord.getTypedWord(), mBestWord, separatorCode);
mJustAccepted = true;
- pickSuggestion(mBestWord);
+ commitBestWord(mBestWord);
// Add the word to the auto dictionary if it's not a known word
addToAutoAndUserBigramDictionaries(mBestWord, AutoDictionary.FREQUENCY_FOR_TYPED);
return true;
-
}
return false;
}
public void pickSuggestionManually(int index, CharSequence suggestion) {
SuggestedWords suggestions = mCandidateView.getSuggestions();
- mVoiceConnector.flushAndLogAllTextModificationCounters(index, suggestion, mWordSeparators);
+ mVoiceProxy.flushAndLogAllTextModificationCounters(index, suggestion,
+ mSettingsValues.mWordSeparators);
final boolean recorrecting = TextEntryState.isRecorrecting();
InputConnection ic = getCurrentInputConnection();
@@ -1629,23 +1552,38 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
}
// If this is a punctuation, apply it through the normal key press
- if (suggestion.length() == 1 && (isWordSeparator(suggestion.charAt(0))
- || isSuggestedPunctuation(suggestion.charAt(0)))) {
+ if (suggestion.length() == 1 && (mSettingsValues.isWordSeparator(suggestion.charAt(0))
+ || mSettingsValues.isSuggestedPunctuation(suggestion.charAt(0)))) {
// Word separators are suggested before the user inputs something.
// So, LatinImeLogger logs "" as a user's input.
LatinImeLogger.logOnManualSuggestion(
"", suggestion.toString(), index, suggestions.mWords);
+ // Find out whether the previous character is a space. If it is, as a special case
+ // for punctuation entered through the suggestion strip, it should be considered
+ // a magic space even if it was a normal space. This is meant to help in case the user
+ // pressed space on purpose of displaying the suggestion strip punctuation.
final char primaryCode = suggestion.charAt(0);
+ final CharSequence beforeText = ic != null ? ic.getTextBeforeCursor(1, 0) : "";
+ final int toLeft = (ic == null || TextUtils.isEmpty(beforeText))
+ ? 0 : beforeText.charAt(0);
+ final boolean oldMagicSpace = mJustAddedMagicSpace;
+ if (Keyboard.CODE_SPACE == toLeft) mJustAddedMagicSpace = true;
onCodeInput(primaryCode, new int[] { primaryCode },
KeyboardActionListener.NOT_A_TOUCH_COORDINATE,
KeyboardActionListener.NOT_A_TOUCH_COORDINATE);
+ mJustAddedMagicSpace = oldMagicSpace;
if (ic != null) {
ic.endBatchEdit();
}
return;
}
+ if (!mHasUncommittedTypedChars) {
+ // If we are not composing a word, then it was a suggestion inferred from
+ // context - no user input. We should reset the word composer.
+ mWord.reset();
+ }
mJustAccepted = true;
- pickSuggestion(suggestion);
+ commitBestWord(suggestion);
// Add the word to the auto dictionary if it's not a known word
if (index == 0) {
addToAutoAndUserBigramDictionaries(suggestion, AutoDictionary.FREQUENCY_FOR_PICKED);
@@ -1656,9 +1594,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
index, suggestions.mWords);
TextEntryState.acceptedSuggestion(mComposing.toString(), suggestion);
// Follow it with a space
- if (mAutoSpace && !recorrecting) {
- sendSpace();
- mJustAddedAutoSpace = true;
+ if (mShouldInsertMagicSpace && !recorrecting) {
+ sendMagicSpace();
}
// We should show the hint if the user pressed the first entry AND either:
@@ -1680,13 +1617,16 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
// Fool the state watcher so that a subsequent backspace will not do a revert, unless
// we just did a correction, in which case we need to stay in
// TextEntryState.State.PICKED_SUGGESTION state.
- TextEntryState.typedCharacter((char) Keyboard.CODE_SPACE, true);
- setPunctuationSuggestions();
- } else if (!showingAddToDictionaryHint) {
+ TextEntryState.typedCharacter((char) Keyboard.CODE_SPACE, true,
+ WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE);
+ }
+ if (!showingAddToDictionaryHint) {
// If we're not showing the "Touch again to save", then show corrections again.
// In case the cursor position doesn't change, make sure we show the suggestions again.
- clearSuggestions();
- mHandler.postUpdateOldSuggestions();
+ updateBigramPredictions();
+ // Updating the predictions right away may be slow and feel unresponsive on slower
+ // terminals. On the other hand if we just postUpdateBigramPredictions() it will
+ // take a noticeable delay to update them which may feel uneasy.
}
if (showingAddToDictionaryHint) {
mCandidateView.showAddToDictionaryHint(suggestion);
@@ -1699,107 +1639,50 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
/**
* Commits the chosen word to the text field and saves it for later
* retrieval.
- * @param suggestion the suggestion picked by the user to be committed to
- * the text field
*/
- private void pickSuggestion(CharSequence suggestion) {
+ private void commitBestWord(CharSequence bestWord) {
KeyboardSwitcher switcher = mKeyboardSwitcher;
if (!switcher.isKeyboardAvailable())
return;
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
- mVoiceConnector.rememberReplacedWord(suggestion, mWordSeparators);
- ic.commitText(suggestion, 1);
+ mVoiceProxy.rememberReplacedWord(bestWord, mSettingsValues.mWordSeparators);
+ SuggestedWords suggestedWords = mCandidateView.getSuggestions();
+ ic.commitText(SuggestionSpanUtils.getTextWithSuggestionSpan(
+ this, bestWord, suggestedWords), 1);
}
- saveWordInHistory(suggestion);
- mHasValidSuggestions = false;
- mCommittedLength = suggestion.length();
+ mRecorrection.saveRecorrectionSuggestion(mWord, bestWord);
+ mHasUncommittedTypedChars = false;
+ mCommittedLength = bestWord.length();
}
- /**
- * Tries to apply any typed alternatives for the word if we have any cached alternatives,
- * otherwise tries to find new corrections and completions for the word.
- * @param touching The word that the cursor is touching, with position information
- * @return true if an alternative was found, false otherwise.
- */
- private boolean applyTypedAlternatives(EditingUtils.SelectedWord touching) {
- // If we didn't find a match, search for result in typed word history
- WordComposer foundWord = null;
- WordAlternatives alternatives = null;
- // Search old suggestions to suggest re-corrected suggestions.
- for (WordAlternatives entry : mWordHistory) {
- if (TextUtils.equals(entry.getChosenWord(), touching.mWord)) {
- if (entry instanceof TypedWordAlternatives) {
- foundWord = ((TypedWordAlternatives) entry).word;
- }
- alternatives = entry;
- break;
- }
- }
- // If we didn't find a match, at least suggest corrections as re-corrected suggestions.
- if (foundWord == null
- && (AutoCorrection.isValidWord(
- mSuggest.getUnigramDictionaries(), touching.mWord, true))) {
- foundWord = new WordComposer();
- for (int i = 0; i < touching.mWord.length(); i++) {
- foundWord.add(touching.mWord.charAt(i), new int[] {
- touching.mWord.charAt(i)
- }, WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE);
- }
- foundWord.setFirstCharCapitalized(Character.isUpperCase(touching.mWord.charAt(0)));
- }
- // Found a match, show suggestions
- if (foundWord != null || alternatives != null) {
- if (alternatives == null) {
- alternatives = new TypedWordAlternatives(touching.mWord, foundWord);
- }
- showCorrections(alternatives);
- if (foundWord != null) {
- mWord = new WordComposer(foundWord);
- } else {
- mWord.reset();
- }
- return true;
- }
- return false;
- }
+ private static final WordComposer sEmptyWordComposer = new WordComposer();
+ public void updateBigramPredictions() {
+ if (mSuggest == null || !isSuggestionsRequested())
+ return;
- private void setOldSuggestions() {
- mVoiceConnector.setShowingVoiceSuggestions(false);
- if (mCandidateView != null && mCandidateView.isShowingAddToDictionaryHint()) {
+ if (!mSettingsValues.mBigramPredictionEnabled) {
+ setPunctuationSuggestions();
return;
}
- InputConnection ic = getCurrentInputConnection();
- if (ic == null) return;
- if (!mHasValidSuggestions) {
- // Extract the selected or touching text
- EditingUtils.SelectedWord touching = EditingUtils.getWordAtCursorOrSelection(ic,
- mLastSelectionStart, mLastSelectionEnd, mWordSeparators);
-
- if (touching != null && touching.mWord.length() > 1) {
- ic.beginBatchEdit();
- if (!mVoiceConnector.applyVoiceAlternatives(touching)
- && !applyTypedAlternatives(touching)) {
- abortRecorrection(true);
- } else {
- TextEntryState.selectedForRecorrection();
- EditingUtils.underlineWord(ic, touching);
- }
+ final CharSequence prevWord = EditingUtils.getThisWord(getCurrentInputConnection(),
+ mSettingsValues.mWordSeparators);
+ SuggestedWords.Builder builder = mSuggest.getSuggestedWordBuilder(
+ mKeyboardSwitcher.getKeyboardView(), sEmptyWordComposer, prevWord);
- ic.endBatchEdit();
- } else {
- abortRecorrection(true);
- setPunctuationSuggestions(); // Show the punctuation suggestions list
- }
+ if (builder.size() > 0) {
+ // Explicitly supply an empty typed word (the no-second-arg version of
+ // showSuggestions will retrieve the word near the cursor, we don't want that here)
+ showSuggestions(builder.build(), "");
} else {
- abortRecorrection(true);
+ if (!isShowingPunctuationList()) setPunctuationSuggestions();
}
}
- private void setPunctuationSuggestions() {
- setSuggestions(mSuggestPuncList);
- setCandidatesViewShown(isCandidateStripVisible());
+ public void setPunctuationSuggestions() {
+ setSuggestions(mSettingsValues.mSuggestPuncList);
+ setSuggestionStripShown(isCandidateStripVisible());
}
private void addToAutoAndUserBigramDictionaries(CharSequence suggestion, int frequencyDelta) {
@@ -1837,27 +1720,30 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
}
if (mUserBigramDictionary != null) {
+ // We don't want to register as bigrams words separated by a separator.
+ // For example "I will, and you too" : we don't want the pair ("will" "and") to be
+ // a bigram.
CharSequence prevWord = EditingUtils.getPreviousWord(getCurrentInputConnection(),
- mSentenceSeparators);
+ mSettingsValues.mWordSeparators);
if (!TextUtils.isEmpty(prevWord)) {
mUserBigramDictionary.addBigrams(prevWord.toString(), suggestion.toString());
}
}
}
- private boolean isCursorTouchingWord() {
+ public boolean isCursorTouchingWord() {
InputConnection ic = getCurrentInputConnection();
if (ic == null) return false;
CharSequence toLeft = ic.getTextBeforeCursor(1, 0);
CharSequence toRight = ic.getTextAfterCursor(1, 0);
if (!TextUtils.isEmpty(toLeft)
- && !isWordSeparator(toLeft.charAt(0))
- && !isSuggestedPunctuation(toLeft.charAt(0))) {
+ && !mSettingsValues.isWordSeparator(toLeft.charAt(0))
+ && !mSettingsValues.isSuggestedPunctuation(toLeft.charAt(0))) {
return true;
}
if (!TextUtils.isEmpty(toRight)
- && !isWordSeparator(toRight.charAt(0))
- && !isSuggestedPunctuation(toRight.charAt(0))) {
+ && !mSettingsValues.isWordSeparator(toRight.charAt(0))
+ && !mSettingsValues.isSuggestedPunctuation(toRight.charAt(0))) {
return true;
}
return false;
@@ -1870,53 +1756,49 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
public void revertLastWord(boolean deleteChar) {
final int length = mComposing.length();
- if (!mHasValidSuggestions && length > 0) {
+ if (!mHasUncommittedTypedChars && length > 0) {
final InputConnection ic = getCurrentInputConnection();
final CharSequence punctuation = ic.getTextBeforeCursor(1, 0);
if (deleteChar) ic.deleteSurroundingText(1, 0);
int toDelete = mCommittedLength;
final CharSequence toTheLeft = ic.getTextBeforeCursor(mCommittedLength, 0);
- if (!TextUtils.isEmpty(toTheLeft) && isWordSeparator(toTheLeft.charAt(0))) {
+ if (!TextUtils.isEmpty(toTheLeft)
+ && mSettingsValues.isWordSeparator(toTheLeft.charAt(0))) {
toDelete--;
}
ic.deleteSurroundingText(toDelete, 0);
// Re-insert punctuation only when the deleted character was word separator and the
// composing text wasn't equal to the auto-corrected text.
if (deleteChar
- && !TextUtils.isEmpty(punctuation) && isWordSeparator(punctuation.charAt(0))
+ && !TextUtils.isEmpty(punctuation)
+ && mSettingsValues.isWordSeparator(punctuation.charAt(0))
&& !TextUtils.equals(mComposing, toTheLeft)) {
ic.commitText(mComposing, 1);
TextEntryState.acceptedTyped(mComposing);
ic.commitText(punctuation, 1);
- TextEntryState.typedCharacter(punctuation.charAt(0), true);
+ TextEntryState.typedCharacter(punctuation.charAt(0), true,
+ WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE);
// Clear composing text
mComposing.setLength(0);
} else {
- mHasValidSuggestions = true;
+ mHasUncommittedTypedChars = true;
ic.setComposingText(mComposing, 1);
TextEntryState.backspace();
}
+ mHandler.cancelUpdateBigramPredictions();
mHandler.postUpdateSuggestions();
} else {
sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
}
}
- protected String getWordSeparators() {
- return mWordSeparators;
- }
-
public boolean isWordSeparator(int code) {
- String separators = getWordSeparators();
- return separators.contains(String.valueOf((char)code));
+ return mSettingsValues.isWordSeparator(code);
}
- private boolean isSentenceSeparator(int code) {
- return mSentenceSeparators.contains(String.valueOf((char)code));
- }
-
- private void sendSpace() {
+ private void sendMagicSpace() {
sendKeyChar((char)Keyboard.CODE_SPACE);
+ mJustAddedMagicSpace = true;
mKeyboardSwitcher.updateShiftState();
}
@@ -1924,28 +1806,31 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
return mWord.isFirstCharCapitalized();
}
- // Notify that language or mode have been changed and toggleLanguage will update KeyboaredID
+ // Notify that language or mode have been changed and toggleLanguage will update KeyboardID
// according to new language or mode.
public void onRefreshKeyboard() {
- toggleLanguage(true, true);
- }
-
- // "reset" and "next" are used only for USE_SPACEBAR_LANGUAGE_SWITCHER.
- private void toggleLanguage(boolean reset, boolean next) {
- if (mSubtypeSwitcher.useSpacebarLanguageSwitcher()) {
- mSubtypeSwitcher.toggleLanguage(reset, next);
- }
// Reload keyboard because the current language has been changed.
mKeyboardSwitcher.loadKeyboard(getCurrentInputEditorInfo(),
- mSubtypeSwitcher.isShortcutImeEnabled() && mVoiceConnector.isVoiceButtonEnabled(),
- mVoiceConnector.isVoiceButtonOnPrimary());
+ mSubtypeSwitcher.isShortcutImeEnabled() && mVoiceProxy.isVoiceButtonEnabled(),
+ mVoiceProxy.isVoiceButtonOnPrimary());
initSuggest();
+ loadSettings();
mKeyboardSwitcher.updateShiftState();
}
+ // "reset" and "next" are used only for USE_SPACEBAR_LANGUAGE_SWITCHER.
+ private void toggleLanguage(boolean next) {
+ if (mSubtypeSwitcher.useSpacebarLanguageSwitcher()) {
+ mSubtypeSwitcher.toggleLanguage(next);
+ }
+ // The following is necessary because on API levels < 10, we don't get notified when
+ // subtype changes.
+ onRefreshKeyboard();
+ }
+
@Override
public void onSwipeDown() {
- if (mConfigSwipeDownDismissKeyboardEnabled)
+ if (mSettingsValues.mSwipeDownDismissKeyboardEnabled)
handleClose();
}
@@ -1964,21 +1849,18 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
} else {
switcher.onOtherKeyPressed();
}
- mAccessibilityUtils.onPress(primaryCode, switcher);
}
@Override
public void onRelease(int primaryCode, boolean withSliding) {
KeyboardSwitcher switcher = mKeyboardSwitcher;
// Reset any drag flags in the keyboard
- switcher.keyReleased();
final boolean distinctMultiTouch = switcher.hasDistinctMultitouch();
if (distinctMultiTouch && primaryCode == Keyboard.CODE_SHIFT) {
switcher.onReleaseShift(withSliding);
} else if (distinctMultiTouch && primaryCode == Keyboard.CODE_SWITCH_ALPHA_SYMBOL) {
switcher.onReleaseSymbol();
}
- mAccessibilityUtils.onRelease(primaryCode, switcher);
}
@@ -2001,7 +1883,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
}
if (mAudioManager != null) {
- mSilentMode = (mAudioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL);
+ mSilentModeOn = (mAudioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL);
}
}
@@ -2009,11 +1891,11 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
// if mAudioManager is null, we don't have the ringer state yet
// mAudioManager will be set by updateRingerMode
if (mAudioManager == null) {
- if (mKeyboardSwitcher.getInputView() != null) {
+ if (mKeyboardSwitcher.getKeyboardView() != null) {
updateRingerMode();
}
}
- if (mSoundOn && !mSilentMode) {
+ if (isSoundOn()) {
// FIXME: Volume and enable should come from UI settings
// FIXME: These should be triggered after auto-repeat logic
int sound = AudioManager.FX_KEYPRESS_STANDARD;
@@ -2033,10 +1915,10 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
}
public void vibrate() {
- if (!mVibrateOn) {
+ if (!mSettingsValues.mVibrateOn) {
return;
}
- LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
+ LatinKeyboardView inputView = mKeyboardSwitcher.getKeyboardView();
if (inputView != null) {
inputView.performHapticFeedback(
HapticFeedbackConstants.KEYBOARD_TAP,
@@ -2044,28 +1926,24 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
}
}
- public void promoteToUserDictionary(String word, int frequency) {
- if (mUserDictionary.isValidWord(word)) return;
- mUserDictionary.addWord(word, frequency);
- }
-
public WordComposer getCurrentWord() {
return mWord;
}
- public boolean getPopupOn() {
- return mPopupOn;
+ boolean isSoundOn() {
+ return mSettingsValues.mSoundOn && !mSilentModeOn;
}
private void updateCorrectionMode() {
// TODO: cleanup messy flags
mHasDictionary = mSuggest != null ? mSuggest.hasMainDictionary() : false;
- mAutoCorrectOn = (mAutoCorrectEnabled || mQuickFixes)
- && !mInputTypeNoAutoCorrect && mHasDictionary;
- mCorrectionMode = (mAutoCorrectOn && mAutoCorrectEnabled)
+ final boolean shouldAutoCorrect = (mSettingsValues.mAutoCorrectEnabled
+ || mSettingsValues.mQuickFixes) && !mInputTypeNoAutoCorrect && mHasDictionary;
+ mCorrectionMode = (shouldAutoCorrect && mSettingsValues.mAutoCorrectEnabled)
? Suggest.CORRECTION_FULL
- : (mAutoCorrectOn ? Suggest.CORRECTION_BASIC : Suggest.CORRECTION_NONE);
- mCorrectionMode = (mBigramSuggestionEnabled && mAutoCorrectOn && mAutoCorrectEnabled)
+ : (shouldAutoCorrect ? Suggest.CORRECTION_BASIC : Suggest.CORRECTION_NONE);
+ mCorrectionMode = (mSettingsValues.mBigramSuggestionEnabled && shouldAutoCorrect
+ && mSettingsValues.mAutoCorrectEnabled)
? Suggest.CORRECTION_FULL_BIGRAM : mCorrectionMode;
if (mSuggest != null) {
mSuggest.setCorrectionMode(mCorrectionMode);
@@ -2074,12 +1952,11 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
private void updateAutoTextEnabled() {
if (mSuggest == null) return;
- mSuggest.setQuickFixesEnabled(mQuickFixes
+ mSuggest.setQuickFixesEnabled(mSettingsValues.mQuickFixes
&& SubtypeSwitcher.getInstance().isSystemLanguageSameAsInputLanguage());
}
- private void updateSuggestionVisibility(SharedPreferences prefs) {
- final Resources res = mResources;
+ private void updateSuggestionVisibility(final SharedPreferences prefs, final Resources res) {
final String suggestionVisiblityStr = prefs.getString(
Settings.PREF_SHOW_SUGGESTIONS_SETTING,
res.getString(R.string.prefs_suggestion_visibility_default_value));
@@ -2107,121 +1984,6 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
startActivity(intent);
}
- private void loadSettings(EditorInfo attribute) {
- // Get the settings preferences
- final SharedPreferences prefs = mPrefs;
- Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
- mVibrateOn = vibrator != null && vibrator.hasVibrator()
- && prefs.getBoolean(Settings.PREF_VIBRATE_ON, false);
- mSoundOn = prefs.getBoolean(Settings.PREF_SOUND_ON,
- mResources.getBoolean(R.bool.config_default_sound_enabled));
-
- mPopupOn = isPopupEnabled(prefs);
- mAutoCap = prefs.getBoolean(Settings.PREF_AUTO_CAP, true);
- mQuickFixes = isQuickFixesEnabled(prefs);
-
- mAutoCorrectEnabled = isAutoCorrectEnabled(prefs);
- mBigramSuggestionEnabled = mAutoCorrectEnabled && isBigramSuggestionEnabled(prefs);
- loadAndSetAutoCorrectionThreshold(prefs);
-
- mVoiceConnector.loadSettings(attribute, prefs);
-
- updateCorrectionMode();
- updateAutoTextEnabled();
- updateSuggestionVisibility(prefs);
- SubtypeSwitcher.getInstance().loadSettings();
- }
-
- /**
- * Load Auto correction threshold from SharedPreferences, and modify mSuggest's threshold.
- */
- private void loadAndSetAutoCorrectionThreshold(SharedPreferences sp) {
- // When mSuggest is not initialized, cannnot modify mSuggest's threshold.
- if (mSuggest == null) return;
- // When auto correction setting is turned off, the threshold is ignored.
- if (!isAutoCorrectEnabled(sp)) return;
-
- final String currentAutoCorrectionSetting = sp.getString(
- Settings.PREF_AUTO_CORRECTION_THRESHOLD,
- mResources.getString(R.string.auto_correction_threshold_mode_index_modest));
- final String[] autoCorrectionThresholdValues = mResources.getStringArray(
- R.array.auto_correction_threshold_values);
- // When autoCrrectionThreshold is greater than 1.0, auto correction is virtually turned off.
- double autoCorrectionThreshold = Double.MAX_VALUE;
- try {
- final int arrayIndex = Integer.valueOf(currentAutoCorrectionSetting);
- if (arrayIndex >= 0 && arrayIndex < autoCorrectionThresholdValues.length) {
- autoCorrectionThreshold = Double.parseDouble(
- autoCorrectionThresholdValues[arrayIndex]);
- }
- } catch (NumberFormatException e) {
- // Whenever the threshold settings are correct, never come here.
- autoCorrectionThreshold = Double.MAX_VALUE;
- Log.w(TAG, "Cannot load auto correction threshold setting."
- + " currentAutoCorrectionSetting: " + currentAutoCorrectionSetting
- + ", autoCorrectionThresholdValues: "
- + Arrays.toString(autoCorrectionThresholdValues));
- }
- // TODO: This should be refactored :
- // setAutoCorrectionThreshold should be called outside of this method.
- mSuggest.setAutoCorrectionThreshold(autoCorrectionThreshold);
- }
-
- private boolean isPopupEnabled(SharedPreferences sp) {
- final boolean showPopupOption = getResources().getBoolean(
- R.bool.config_enable_show_popup_on_keypress_option);
- if (!showPopupOption) return mResources.getBoolean(R.bool.config_default_popup_preview);
- return sp.getBoolean(Settings.PREF_POPUP_ON,
- mResources.getBoolean(R.bool.config_default_popup_preview));
- }
-
- private boolean isQuickFixesEnabled(SharedPreferences sp) {
- final boolean showQuickFixesOption = mResources.getBoolean(
- R.bool.config_enable_quick_fixes_option);
- if (!showQuickFixesOption) {
- return isAutoCorrectEnabled(sp);
- }
- return sp.getBoolean(Settings.PREF_QUICK_FIXES, mResources.getBoolean(
- R.bool.config_default_quick_fixes));
- }
-
- private boolean isAutoCorrectEnabled(SharedPreferences sp) {
- final String currentAutoCorrectionSetting = sp.getString(
- Settings.PREF_AUTO_CORRECTION_THRESHOLD,
- mResources.getString(R.string.auto_correction_threshold_mode_index_modest));
- final String autoCorrectionOff = mResources.getString(
- R.string.auto_correction_threshold_mode_index_off);
- return !currentAutoCorrectionSetting.equals(autoCorrectionOff);
- }
-
- private boolean isBigramSuggestionEnabled(SharedPreferences sp) {
- final boolean showBigramSuggestionsOption = mResources.getBoolean(
- R.bool.config_enable_bigram_suggestions_option);
- if (!showBigramSuggestionsOption) {
- return isAutoCorrectEnabled(sp);
- }
- return sp.getBoolean(Settings.PREF_BIGRAM_SUGGESTIONS, mResources.getBoolean(
- R.bool.config_default_bigram_suggestions));
- }
-
- private void initSuggestPuncList() {
- if (mSuggestPuncs != null || mSuggestPuncList != null)
- return;
- SuggestedWords.Builder builder = new SuggestedWords.Builder();
- String puncs = mResources.getString(R.string.suggested_punctuations);
- if (puncs != null) {
- for (int i = 0; i < puncs.length(); i++) {
- builder.addWord(puncs.subSequence(i, i + 1));
- }
- }
- mSuggestPuncList = builder.build();
- mSuggestPuncs = puncs;
- }
-
- private boolean isSuggestedPunctuation(int code) {
- return mSuggestPuncs.contains(String.valueOf((char)code));
- }
-
private void showSubtypeSelectorAndSettings() {
final CharSequence title = getString(R.string.english_ime_input_options);
final CharSequence[] items = new CharSequence[] {
@@ -2235,13 +1997,10 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
di.dismiss();
switch (position) {
case 0:
- Intent intent = new Intent(
- android.provider.Settings.ACTION_INPUT_METHOD_SUBTYPE_SETTINGS);
- intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
+ Intent intent = CompatUtils.getInputLanguageSelectionIntent(
+ mInputMethodId, Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
- intent.putExtra(android.provider.Settings.EXTRA_INPUT_METHOD_ID,
- mInputMethodId);
startActivity(intent);
break;
case 1:
@@ -2278,7 +2037,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
private void showOptionsMenuInternal(CharSequence title, CharSequence[] items,
DialogInterface.OnClickListener listener) {
- final IBinder windowToken = mKeyboardSwitcher.getInputView().getWindowToken();
+ final IBinder windowToken = mKeyboardSwitcher.getKeyboardView().getWindowToken();
if (windowToken == null) return;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
@@ -2307,14 +2066,14 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
p.println(" mComposing=" + mComposing.toString());
p.println(" mIsSuggestionsRequested=" + mIsSettingsSuggestionStripOn);
p.println(" mCorrectionMode=" + mCorrectionMode);
- p.println(" mHasValidSuggestions=" + mHasValidSuggestions);
- p.println(" mAutoCorrectOn=" + mAutoCorrectOn);
- p.println(" mAutoSpace=" + mAutoSpace);
+ p.println(" mHasUncommittedTypedChars=" + mHasUncommittedTypedChars);
+ p.println(" mAutoCorrectEnabled=" + mSettingsValues.mAutoCorrectEnabled);
+ p.println(" mShouldInsertMagicSpace=" + mShouldInsertMagicSpace);
p.println(" mApplicationSpecifiedCompletionOn=" + mApplicationSpecifiedCompletionOn);
p.println(" TextEntryState.state=" + TextEntryState.getState());
- p.println(" mSoundOn=" + mSoundOn);
- p.println(" mVibrateOn=" + mVibrateOn);
- p.println(" mPopupOn=" + mPopupOn);
+ p.println(" mSoundOn=" + mSettingsValues.mSoundOn);
+ p.println(" mVibrateOn=" + mSettingsValues.mVibrateOn);
+ p.println(" mKeyPreviewPopupOn=" + mSettingsValues.mKeyPreviewPopupOn);
}
// Characters per second measurement
@@ -2334,9 +2093,4 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen
for (int i = 0; i < CPS_BUFFER_SIZE; i++) total += mCpsIntervals[i];
System.out.println("CPS = " + ((CPS_BUFFER_SIZE * 1000f) / total));
}
-
- @Override
- public void onCurrentInputMethodSubtypeChanged(InputMethodSubtype subtype) {
- SubtypeSwitcher.getInstance().updateSubtype(subtype);
- }
}
diff --git a/java/src/com/android/inputmethod/latin/LatinImeLogger.java b/java/src/com/android/inputmethod/latin/LatinImeLogger.java
index aaecfffdd..e460471a5 100644
--- a/java/src/com/android/inputmethod/latin/LatinImeLogger.java
+++ b/java/src/com/android/inputmethod/latin/LatinImeLogger.java
@@ -45,10 +45,10 @@ public class LatinImeLogger implements SharedPreferences.OnSharedPreferenceChang
String before, String after, int position, List<CharSequence> suggestions) {
}
- public static void logOnAutoSuggestion(String before, String after) {
+ public static void logOnAutoCorrection(String before, String after, int separatorCode) {
}
- public static void logOnAutoSuggestionCanceled() {
+ public static void logOnAutoCorrectionCancelled() {
}
public static void logOnDelete() {
@@ -57,6 +57,9 @@ public class LatinImeLogger implements SharedPreferences.OnSharedPreferenceChang
public static void logOnInputChar() {
}
+ public static void logOnInputSeparator() {
+ }
+
public static void logOnException(String metaData, Throwable e) {
}
diff --git a/java/src/com/android/inputmethod/latin/PrivateBinaryDictionaryGetter.java b/java/src/com/android/inputmethod/latin/PrivateBinaryDictionaryGetter.java
new file mode 100644
index 000000000..eb740e111
--- /dev/null
+++ b/java/src/com/android/inputmethod/latin/PrivateBinaryDictionaryGetter.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package com.android.inputmethod.latin;
+
+import android.content.Context;
+
+import java.util.List;
+import java.util.Locale;
+
+class PrivateBinaryDictionaryGetter {
+ private PrivateBinaryDictionaryGetter() {}
+ public static List<AssetFileAddress> getDictionaryFiles(Locale locale, Context context) {
+ return null;
+ }
+}
diff --git a/java/src/com/android/inputmethod/latin/Settings.java b/java/src/com/android/inputmethod/latin/Settings.java
index 341d5add0..956c51e06 100644
--- a/java/src/com/android/inputmethod/latin/Settings.java
+++ b/java/src/com/android/inputmethod/latin/Settings.java
@@ -16,17 +16,21 @@
package com.android.inputmethod.latin;
-import com.android.inputmethod.voice.VoiceIMEConnector;
-import com.android.inputmethod.voice.VoiceInputLogger;
+import com.android.inputmethod.compat.CompatUtils;
+import com.android.inputmethod.compat.InputMethodManagerCompatWrapper;
+import com.android.inputmethod.compat.InputMethodServiceCompatWrapper;
+import com.android.inputmethod.deprecated.VoiceProxy;
+import com.android.inputmethod.compat.VibratorCompatWrapper;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.backup.BackupManager;
+import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
+import android.content.res.Resources;
import android.os.Bundle;
-import android.os.Vibrator;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
@@ -41,6 +45,7 @@ import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.widget.TextView;
+import java.util.Arrays;
import java.util.Locale;
public class Settings extends PreferenceActivity
@@ -51,7 +56,7 @@ public class Settings extends PreferenceActivity
public static final String PREF_GENERAL_SETTINGS_KEY = "general_settings";
public static final String PREF_VIBRATE_ON = "vibrate_on";
public static final String PREF_SOUND_ON = "sound_on";
- public static final String PREF_POPUP_ON = "popup_on";
+ public static final String PREF_KEY_PREVIEW_POPUP_ON = "popup_on";
public static final String PREF_RECORRECTION_ENABLED = "recorrection_enabled";
public static final String PREF_AUTO_CAP = "auto_cap";
public static final String PREF_SETTINGS_KEY = "settings_key";
@@ -60,29 +65,243 @@ public class Settings extends PreferenceActivity
public static final String PREF_SELECTED_LANGUAGES = "selected_languages";
public static final String PREF_SUBTYPES = "subtype_settings";
- public static final String PREF_PREDICTION_SETTINGS_KEY = "prediction_settings";
+ public static final String PREF_CORRECTION_SETTINGS_KEY = "correction_settings";
public static final String PREF_QUICK_FIXES = "quick_fixes";
public static final String PREF_SHOW_SUGGESTIONS_SETTING = "show_suggestions_setting";
public static final String PREF_AUTO_CORRECTION_THRESHOLD = "auto_correction_threshold";
+ public static final String PREF_DEBUG_SETTINGS = "debug_settings";
+
+ public static final String PREF_NGRAM_SETTINGS_KEY = "ngram_settings";
public static final String PREF_BIGRAM_SUGGESTIONS = "bigram_suggestion";
+ public static final String PREF_BIGRAM_PREDICTIONS = "bigram_prediction";
+
+ public static final String PREF_MISC_SETTINGS_KEY = "misc_settings";
+
+ public static final String PREF_KEY_PREVIEW_POPUP_DISMISS_DELAY =
+ "pref_key_preview_popup_dismiss_delay";
public static final String PREF_USABILITY_STUDY_MODE = "usability_study_mode";
// Dialog ids
private static final int VOICE_INPUT_CONFIRM_DIALOG = 0;
+ public static class Values {
+ // From resources:
+ public final boolean mSwipeDownDismissKeyboardEnabled;
+ public final int mDelayBeforeFadeoutLanguageOnSpacebar;
+ public final int mDelayUpdateSuggestions;
+ public final int mDelayUpdateOldSuggestions;
+ public final int mDelayUpdateShiftState;
+ public final int mDurationOfFadeoutLanguageOnSpacebar;
+ public final float mFinalFadeoutFactorOfLanguageOnSpacebar;
+ public final long mDoubleSpacesTurnIntoPeriodTimeout;
+ public final String mWordSeparators;
+ public final String mMagicSpaceStrippers;
+ public final String mMagicSpaceSwappers;
+ public final String mSuggestPuncs;
+ public final SuggestedWords mSuggestPuncList;
+
+ // From preferences:
+ public final boolean mSoundOn; // Sound setting private to Latin IME (see mSilentModeOn)
+ public final boolean mVibrateOn;
+ public final boolean mKeyPreviewPopupOn;
+ public final int mKeyPreviewPopupDismissDelay;
+ public final boolean mAutoCap;
+ public final boolean mQuickFixes;
+ public final boolean mAutoCorrectEnabled;
+ public final double mAutoCorrectionThreshold;
+ // Suggestion: use bigrams to adjust scores of suggestions obtained from unigram dictionary
+ public final boolean mBigramSuggestionEnabled;
+ // Prediction: use bigrams to predict the next word when there is no input for it yet
+ public final boolean mBigramPredictionEnabled;
+
+ public Values(final SharedPreferences prefs, final Context context,
+ final String localeStr) {
+ final Resources res = context.getResources();
+ final Locale savedLocale;
+ if (null != localeStr) {
+ final Locale keyboardLocale = Utils.constructLocaleFromString(localeStr);
+ savedLocale = Utils.setSystemLocale(res, keyboardLocale);
+ } else {
+ savedLocale = null;
+ }
+
+ // Get the resources
+ mSwipeDownDismissKeyboardEnabled = res.getBoolean(
+ R.bool.config_swipe_down_dismiss_keyboard_enabled);
+ mDelayBeforeFadeoutLanguageOnSpacebar = res.getInteger(
+ R.integer.config_delay_before_fadeout_language_on_spacebar);
+ mDelayUpdateSuggestions =
+ res.getInteger(R.integer.config_delay_update_suggestions);
+ mDelayUpdateOldSuggestions = res.getInteger(
+ R.integer.config_delay_update_old_suggestions);
+ mDelayUpdateShiftState =
+ res.getInteger(R.integer.config_delay_update_shift_state);
+ mDurationOfFadeoutLanguageOnSpacebar = res.getInteger(
+ R.integer.config_duration_of_fadeout_language_on_spacebar);
+ mFinalFadeoutFactorOfLanguageOnSpacebar = res.getInteger(
+ R.integer.config_final_fadeout_percentage_of_language_on_spacebar) / 100.0f;
+ mDoubleSpacesTurnIntoPeriodTimeout = res.getInteger(
+ R.integer.config_double_spaces_turn_into_period_timeout);
+ mMagicSpaceStrippers = res.getString(R.string.magic_space_stripping_symbols);
+ mMagicSpaceSwappers = res.getString(R.string.magic_space_swapping_symbols);
+ String wordSeparators = mMagicSpaceStrippers + mMagicSpaceSwappers
+ + res.getString(R.string.magic_space_promoting_symbols);
+ final String notWordSeparators = res.getString(R.string.non_word_separator_symbols);
+ for (int i = notWordSeparators.length() - 1; i >= 0; --i) {
+ wordSeparators = wordSeparators.replace(notWordSeparators.substring(i, i + 1), "");
+ }
+ mWordSeparators = wordSeparators;
+ mSuggestPuncs = res.getString(R.string.suggested_punctuations);
+ // TODO: it would be nice not to recreate this each time we change the configuration
+ mSuggestPuncList = createSuggestPuncList(mSuggestPuncs);
+
+ // Get the settings preferences
+ final boolean hasVibrator = VibratorCompatWrapper.getInstance(context).hasVibrator();
+ mVibrateOn = hasVibrator && prefs.getBoolean(Settings.PREF_VIBRATE_ON, false);
+ mSoundOn = prefs.getBoolean(Settings.PREF_SOUND_ON,
+ res.getBoolean(R.bool.config_default_sound_enabled));
+
+ mKeyPreviewPopupOn = isKeyPreviewPopupEnabled(prefs, res);
+ mKeyPreviewPopupDismissDelay = getKeyPreviewPopupDismissDelay(prefs, res);
+ mAutoCap = prefs.getBoolean(Settings.PREF_AUTO_CAP, true);
+ mQuickFixes = isQuickFixesEnabled(prefs, res);
+
+ mAutoCorrectEnabled = isAutoCorrectEnabled(prefs, res);
+ mBigramSuggestionEnabled = mAutoCorrectEnabled
+ && isBigramSuggestionEnabled(prefs, res, mAutoCorrectEnabled);
+ mBigramPredictionEnabled = mBigramSuggestionEnabled
+ && isBigramPredictionEnabled(prefs, res);
+
+ mAutoCorrectionThreshold = getAutoCorrectionThreshold(prefs, res);
+
+ Utils.setSystemLocale(res, savedLocale);
+ }
+
+ public boolean isSuggestedPunctuation(int code) {
+ return mSuggestPuncs.contains(String.valueOf((char)code));
+ }
+
+ public boolean isWordSeparator(int code) {
+ return mWordSeparators.contains(String.valueOf((char)code));
+ }
+
+ public boolean isMagicSpaceStripper(int code) {
+ return mMagicSpaceStrippers.contains(String.valueOf((char)code));
+ }
+
+ public boolean isMagicSpaceSwapper(int code) {
+ return mMagicSpaceSwappers.contains(String.valueOf((char)code));
+ }
+
+ // Helper methods
+ private static boolean isQuickFixesEnabled(SharedPreferences sp, Resources resources) {
+ final boolean showQuickFixesOption = resources.getBoolean(
+ R.bool.config_enable_quick_fixes_option);
+ if (!showQuickFixesOption) {
+ return isAutoCorrectEnabled(sp, resources);
+ }
+ return sp.getBoolean(Settings.PREF_QUICK_FIXES, resources.getBoolean(
+ R.bool.config_default_quick_fixes));
+ }
+
+ private static boolean isAutoCorrectEnabled(SharedPreferences sp, Resources resources) {
+ final String currentAutoCorrectionSetting = sp.getString(
+ Settings.PREF_AUTO_CORRECTION_THRESHOLD,
+ resources.getString(R.string.auto_correction_threshold_mode_index_modest));
+ final String autoCorrectionOff = resources.getString(
+ R.string.auto_correction_threshold_mode_index_off);
+ return !currentAutoCorrectionSetting.equals(autoCorrectionOff);
+ }
+
+ // Public to access from KeyboardSwitcher. Should it have access to some
+ // process-global instance instead?
+ public static boolean isKeyPreviewPopupEnabled(SharedPreferences sp, Resources resources) {
+ final boolean showPopupOption = resources.getBoolean(
+ R.bool.config_enable_show_popup_on_keypress_option);
+ if (!showPopupOption) return resources.getBoolean(R.bool.config_default_popup_preview);
+ return sp.getBoolean(Settings.PREF_KEY_PREVIEW_POPUP_ON,
+ resources.getBoolean(R.bool.config_default_popup_preview));
+ }
+
+ // Likewise
+ public static int getKeyPreviewPopupDismissDelay(SharedPreferences sp,
+ Resources resources) {
+ return Integer.parseInt(sp.getString(Settings.PREF_KEY_PREVIEW_POPUP_DISMISS_DELAY,
+ Integer.toString(resources.getInteger(R.integer.config_delay_after_preview))));
+ }
+
+ private static boolean isBigramSuggestionEnabled(SharedPreferences sp, Resources resources,
+ boolean autoCorrectEnabled) {
+ final boolean showBigramSuggestionsOption = resources.getBoolean(
+ R.bool.config_enable_bigram_suggestions_option);
+ if (!showBigramSuggestionsOption) {
+ return autoCorrectEnabled;
+ }
+ return sp.getBoolean(Settings.PREF_BIGRAM_SUGGESTIONS, resources.getBoolean(
+ R.bool.config_default_bigram_suggestions));
+ }
+
+ private static boolean isBigramPredictionEnabled(SharedPreferences sp,
+ Resources resources) {
+ return sp.getBoolean(Settings.PREF_BIGRAM_PREDICTIONS, resources.getBoolean(
+ R.bool.config_default_bigram_prediction));
+ }
+
+ private static double getAutoCorrectionThreshold(SharedPreferences sp,
+ Resources resources) {
+ final String currentAutoCorrectionSetting = sp.getString(
+ Settings.PREF_AUTO_CORRECTION_THRESHOLD,
+ resources.getString(R.string.auto_correction_threshold_mode_index_modest));
+ final String[] autoCorrectionThresholdValues = resources.getStringArray(
+ R.array.auto_correction_threshold_values);
+ // When autoCorrectionThreshold is greater than 1.0, it's like auto correction is off.
+ double autoCorrectionThreshold = Double.MAX_VALUE;
+ try {
+ final int arrayIndex = Integer.valueOf(currentAutoCorrectionSetting);
+ if (arrayIndex >= 0 && arrayIndex < autoCorrectionThresholdValues.length) {
+ autoCorrectionThreshold = Double.parseDouble(
+ autoCorrectionThresholdValues[arrayIndex]);
+ }
+ } catch (NumberFormatException e) {
+ // Whenever the threshold settings are correct, never come here.
+ autoCorrectionThreshold = Double.MAX_VALUE;
+ Log.w(TAG, "Cannot load auto correction threshold setting."
+ + " currentAutoCorrectionSetting: " + currentAutoCorrectionSetting
+ + ", autoCorrectionThresholdValues: "
+ + Arrays.toString(autoCorrectionThresholdValues));
+ }
+ return autoCorrectionThreshold;
+ }
+
+ private static SuggestedWords createSuggestPuncList(final String puncs) {
+ SuggestedWords.Builder builder = new SuggestedWords.Builder();
+ if (puncs != null) {
+ for (int i = 0; i < puncs.length(); i++) {
+ builder.addWord(puncs.subSequence(i, i + 1));
+ }
+ }
+ return builder.build();
+ }
+ }
+
private PreferenceScreen mInputLanguageSelection;
private CheckBoxPreference mQuickFixes;
private ListPreference mVoicePreference;
private ListPreference mSettingsKeyPreference;
private ListPreference mShowCorrectionSuggestionsPreference;
private ListPreference mAutoCorrectionThreshold;
+ private ListPreference mKeyPreviewPopupDismissDelay;
+ // Suggestion: use bigrams to adjust scores of suggestions obtained from unigram dictionary
private CheckBoxPreference mBigramSuggestion;
+ // Prediction: use bigrams to predict the next word when there is no input for it yet
+ private CheckBoxPreference mBigramPrediction;
+ private Preference mDebugSettingsPreference;
private boolean mVoiceOn;
private AlertDialog mDialog;
- private VoiceInputLogger mLogger;
+ private VoiceProxy.VoiceLoggerWrapper mVoiceLogger;
private boolean mOkClicked = false;
private String mVoiceModeOff;
@@ -92,11 +311,14 @@ public class Settings extends PreferenceActivity
R.string.auto_correction_threshold_mode_index_off);
final String currentSetting = mAutoCorrectionThreshold.getValue();
mBigramSuggestion.setEnabled(!currentSetting.equals(autoCorrectionOff));
+ mBigramPrediction.setEnabled(!currentSetting.equals(autoCorrectionOff));
}
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
+ final Resources res = getResources();
+
addPreferencesFromResource(R.xml.prefs);
mInputLanguageSelection = (PreferenceScreen) findPreference(PREF_SUBTYPES);
mInputLanguageSelection.setOnPreferenceClickListener(this);
@@ -111,69 +333,92 @@ public class Settings extends PreferenceActivity
mVoiceModeOff = getString(R.string.voice_mode_off);
mVoiceOn = !(prefs.getString(PREF_VOICE_SETTINGS_KEY, mVoiceModeOff)
.equals(mVoiceModeOff));
- mLogger = VoiceInputLogger.getLogger(this);
+ mVoiceLogger = VoiceProxy.VoiceLoggerWrapper.getInstance(this);
mAutoCorrectionThreshold = (ListPreference) findPreference(PREF_AUTO_CORRECTION_THRESHOLD);
mBigramSuggestion = (CheckBoxPreference) findPreference(PREF_BIGRAM_SUGGESTIONS);
+ mBigramPrediction = (CheckBoxPreference) findPreference(PREF_BIGRAM_PREDICTIONS);
+ mDebugSettingsPreference = findPreference(PREF_DEBUG_SETTINGS);
+ if (mDebugSettingsPreference != null) {
+ final Intent debugSettingsIntent = new Intent(Intent.ACTION_MAIN);
+ debugSettingsIntent.setClassName(getPackageName(), DebugSettings.class.getName());
+ mDebugSettingsPreference.setIntent(debugSettingsIntent);
+ }
+
ensureConsistencyOfAutoCorrectionSettings();
final PreferenceGroup generalSettings =
(PreferenceGroup) findPreference(PREF_GENERAL_SETTINGS_KEY);
final PreferenceGroup textCorrectionGroup =
- (PreferenceGroup) findPreference(PREF_PREDICTION_SETTINGS_KEY);
+ (PreferenceGroup) findPreference(PREF_CORRECTION_SETTINGS_KEY);
- final boolean showSettingsKeyOption = getResources().getBoolean(
+ final boolean showSettingsKeyOption = res.getBoolean(
R.bool.config_enable_show_settings_key_option);
if (!showSettingsKeyOption) {
generalSettings.removePreference(mSettingsKeyPreference);
}
- final boolean showVoiceKeyOption = getResources().getBoolean(
+ final boolean showVoiceKeyOption = res.getBoolean(
R.bool.config_enable_show_voice_key_option);
if (!showVoiceKeyOption) {
generalSettings.removePreference(mVoicePreference);
}
- Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
- if (vibrator == null || !vibrator.hasVibrator()) {
+ if (!VibratorCompatWrapper.getInstance(this).hasVibrator()) {
generalSettings.removePreference(findPreference(PREF_VIBRATE_ON));
}
- final boolean showSubtypeSettings = getResources().getBoolean(
- R.bool.config_enable_show_subtype_settings);
- if (!showSubtypeSettings) {
+ if (InputMethodServiceCompatWrapper.CAN_HANDLE_ON_CURRENT_INPUT_METHOD_SUBTYPE_CHANGED) {
generalSettings.removePreference(findPreference(PREF_SUBTYPES));
}
- final boolean showPopupOption = getResources().getBoolean(
+ final boolean showPopupOption = res.getBoolean(
R.bool.config_enable_show_popup_on_keypress_option);
if (!showPopupOption) {
- generalSettings.removePreference(findPreference(PREF_POPUP_ON));
+ generalSettings.removePreference(findPreference(PREF_KEY_PREVIEW_POPUP_ON));
}
- final boolean showRecorrectionOption = getResources().getBoolean(
+ final boolean showRecorrectionOption = res.getBoolean(
R.bool.config_enable_show_recorrection_option);
if (!showRecorrectionOption) {
generalSettings.removePreference(findPreference(PREF_RECORRECTION_ENABLED));
}
- final boolean showQuickFixesOption = getResources().getBoolean(
+ final boolean showQuickFixesOption = res.getBoolean(
R.bool.config_enable_quick_fixes_option);
if (!showQuickFixesOption) {
textCorrectionGroup.removePreference(findPreference(PREF_QUICK_FIXES));
}
- final boolean showBigramSuggestionsOption = getResources().getBoolean(
+ final boolean showBigramSuggestionsOption = res.getBoolean(
R.bool.config_enable_bigram_suggestions_option);
if (!showBigramSuggestionsOption) {
textCorrectionGroup.removePreference(findPreference(PREF_BIGRAM_SUGGESTIONS));
+ textCorrectionGroup.removePreference(findPreference(PREF_BIGRAM_PREDICTIONS));
}
- final boolean showUsabilityModeStudyOption = getResources().getBoolean(
+ final boolean showUsabilityModeStudyOption = res.getBoolean(
R.bool.config_enable_usability_study_mode_option);
if (!showUsabilityModeStudyOption) {
getPreferenceScreen().removePreference(findPreference(PREF_USABILITY_STUDY_MODE));
}
+
+ mKeyPreviewPopupDismissDelay =
+ (ListPreference)findPreference(PREF_KEY_PREVIEW_POPUP_DISMISS_DELAY);
+ final String[] entries = new String[] {
+ res.getString(R.string.key_preview_popup_dismiss_no_delay),
+ res.getString(R.string.key_preview_popup_dismiss_default_delay),
+ };
+ final String popupDismissDelayDefaultValue = Integer.toString(res.getInteger(
+ R.integer.config_delay_after_preview));
+ mKeyPreviewPopupDismissDelay.setEntries(entries);
+ mKeyPreviewPopupDismissDelay.setEntryValues(
+ new String[] { "0", popupDismissDelayDefaultValue });
+ if (null == mKeyPreviewPopupDismissDelay.getValue()) {
+ mKeyPreviewPopupDismissDelay.setValue(popupDismissDelayDefaultValue);
+ }
+ mKeyPreviewPopupDismissDelay.setEnabled(
+ Settings.Values.isKeyPreviewPopupEnabled(prefs, res));
}
@Override
@@ -181,10 +426,10 @@ public class Settings extends PreferenceActivity
super.onResume();
int autoTextSize = AutoText.getSize(getListView());
if (autoTextSize < 1) {
- ((PreferenceGroup) findPreference(PREF_PREDICTION_SETTINGS_KEY))
+ ((PreferenceGroup) findPreference(PREF_CORRECTION_SETTINGS_KEY))
.removePreference(mQuickFixes);
}
- if (!VoiceIMEConnector.VOICE_INSTALLED
+ if (!VoiceProxy.VOICE_INSTALLED
|| !SpeechRecognizer.isRecognitionAvailable(this)) {
getPreferenceScreen().removePreference(mVoicePreference);
} else {
@@ -192,6 +437,7 @@ public class Settings extends PreferenceActivity
}
updateSettingsKeySummary();
updateShowCorrectionSuggestionsSummary();
+ updateKeyPreviewPopupDelaySummary();
}
@Override
@@ -210,6 +456,12 @@ public class Settings extends PreferenceActivity
.equals(mVoiceModeOff)) {
showVoiceConfirmation();
}
+ } else if (key.equals(PREF_KEY_PREVIEW_POPUP_ON)) {
+ final ListPreference popupDismissDelay =
+ (ListPreference)findPreference(PREF_KEY_PREVIEW_POPUP_DISMISS_DELAY);
+ if (null != popupDismissDelay) {
+ popupDismissDelay.setEnabled(prefs.getBoolean(PREF_KEY_PREVIEW_POPUP_ON, true));
+ }
}
ensureConsistencyOfAutoCorrectionSettings();
mVoiceOn = !(prefs.getString(PREF_VOICE_SETTINGS_KEY, mVoiceModeOff)
@@ -217,21 +469,15 @@ public class Settings extends PreferenceActivity
updateVoiceModeSummary();
updateSettingsKeySummary();
updateShowCorrectionSuggestionsSummary();
+ updateKeyPreviewPopupDelaySummary();
}
@Override
public boolean onPreferenceClick(Preference pref) {
if (pref == mInputLanguageSelection) {
- final String action;
- if (android.os.Build.VERSION.SDK_INT
- >= /* android.os.Build.VERSION_CODES.HONEYCOMB */ 11) {
- // Refer to android.provider.Settings.ACTION_INPUT_METHOD_SUBTYPE_SETTINGS
- // TODO: Can this be a constant instead of literal String constant?
- action = "android.settings.INPUT_METHOD_SUBTYPE_SETTINGS";
- } else {
- action = "com.android.inputmethod.latin.INPUT_LANGUAGE_SELECTION";
- }
- startActivity(new Intent(action));
+ startActivity(CompatUtils.getInputLanguageSelectionIntent(
+ Utils.getInputMethodId(InputMethodManagerCompatWrapper.getInstance(this),
+ getApplicationInfo().packageName), 0));
return true;
}
return false;
@@ -250,6 +496,11 @@ public class Settings extends PreferenceActivity
[mSettingsKeyPreference.findIndexOfValue(mSettingsKeyPreference.getValue())]);
}
+ private void updateKeyPreviewPopupDelaySummary() {
+ final ListPreference lp = mKeyPreviewPopupDismissDelay;
+ lp.setSummary(lp.getEntries()[lp.findIndexOfValue(lp.getValue())]);
+ }
+
private void showVoiceConfirmation() {
mOkClicked = false;
showDialog(VOICE_INPUT_CONFIRM_DIALOG);
@@ -277,10 +528,10 @@ public class Settings extends PreferenceActivity
public void onClick(DialogInterface dialog, int whichButton) {
if (whichButton == DialogInterface.BUTTON_NEGATIVE) {
mVoicePreference.setValue(mVoiceModeOff);
- mLogger.settingsWarningDialogCancel();
+ mVoiceLogger.settingsWarningDialogCancel();
} else if (whichButton == DialogInterface.BUTTON_POSITIVE) {
mOkClicked = true;
- mLogger.settingsWarningDialogOk();
+ mVoiceLogger.settingsWarningDialogOk();
}
updateVoicePreference();
}
@@ -311,7 +562,7 @@ public class Settings extends PreferenceActivity
AlertDialog dialog = builder.create();
mDialog = dialog;
dialog.setOnDismissListener(this);
- mLogger.settingsWarningDialogShown();
+ mVoiceLogger.settingsWarningDialogShown();
return dialog;
default:
Log.e(TAG, "unknown dialog " + id);
@@ -321,7 +572,7 @@ public class Settings extends PreferenceActivity
@Override
public void onDismiss(DialogInterface dialog) {
- mLogger.settingsWarningDialogDismissed();
+ mVoiceLogger.settingsWarningDialogDismissed();
if (!mOkClicked) {
// This assumes that onPreferenceClick gets called first, and this if the user
// agreed after the warning, we set the mOkClicked value to true.
@@ -331,10 +582,6 @@ public class Settings extends PreferenceActivity
private void updateVoicePreference() {
boolean isChecked = !mVoicePreference.getValue().equals(mVoiceModeOff);
- if (isChecked) {
- mLogger.voiceInputSettingEnabled();
- } else {
- mLogger.voiceInputSettingDisabled();
- }
+ mVoiceLogger.voiceInputSettingEnabled(isChecked);
}
}
diff --git a/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java b/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java
index dc14d770a..8b51af880 100644
--- a/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java
+++ b/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java
@@ -16,11 +16,12 @@
package com.android.inputmethod.latin;
+import com.android.inputmethod.compat.InputMethodInfoCompatWrapper;
+import com.android.inputmethod.compat.InputMethodManagerCompatWrapper;
+import com.android.inputmethod.compat.InputMethodSubtypeCompatWrapper;
+import com.android.inputmethod.deprecated.VoiceProxy;
import com.android.inputmethod.keyboard.KeyboardSwitcher;
import com.android.inputmethod.keyboard.LatinKeyboard;
-import com.android.inputmethod.voice.SettingsUtil;
-import com.android.inputmethod.voice.VoiceIMEConnector;
-import com.android.inputmethod.voice.VoiceInput;
import android.content.Context;
import android.content.Intent;
@@ -31,12 +32,10 @@ import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
+import android.os.AsyncTask;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
-import android.view.inputmethod.InputMethodInfo;
-import android.view.inputmethod.InputMethodManager;
-import android.view.inputmethod.InputMethodSubtype;
import java.util.ArrayList;
import java.util.Arrays;
@@ -53,32 +52,37 @@ public class SubtypeSwitcher {
private static final String VOICE_MODE = "voice";
private static final String SUBTYPE_EXTRAVALUE_REQUIRE_NETWORK_CONNECTIVITY =
"requireNetworkConnectivity";
+ public static final String USE_SPACEBAR_LANGUAGE_SWITCH_KEY = "use_spacebar_language_switch";
+
private final TextUtils.SimpleStringSplitter mLocaleSplitter =
new TextUtils.SimpleStringSplitter(LOCALE_SEPARATER);
private static final SubtypeSwitcher sInstance = new SubtypeSwitcher();
private /* final */ LatinIME mService;
- private /* final */ SharedPreferences mPrefs;
- private /* final */ InputMethodManager mImm;
+ private /* final */ InputMethodManagerCompatWrapper mImm;
private /* final */ Resources mResources;
private /* final */ ConnectivityManager mConnectivityManager;
private /* final */ boolean mConfigUseSpacebarLanguageSwitcher;
- private final ArrayList<InputMethodSubtype> mEnabledKeyboardSubtypesOfCurrentInputMethod =
- new ArrayList<InputMethodSubtype>();
+ private /* final */ SharedPreferences mPrefs;
+ private final ArrayList<InputMethodSubtypeCompatWrapper>
+ mEnabledKeyboardSubtypesOfCurrentInputMethod =
+ new ArrayList<InputMethodSubtypeCompatWrapper>();
private final ArrayList<String> mEnabledLanguagesOfCurrentInputMethod = new ArrayList<String>();
+ private final LanguageBarInfo mLanguageBarInfo = new LanguageBarInfo();
/*-----------------------------------------------------------*/
// Variants which should be changed only by reload functions.
private boolean mNeedsToDisplayLanguage;
private boolean mIsSystemLanguageSameAsInputLanguage;
- private InputMethodInfo mShortcutInputMethodInfo;
- private InputMethodSubtype mShortcutSubtype;
- private List<InputMethodSubtype> mAllEnabledSubtypesOfCurrentInputMethod;
- private InputMethodSubtype mCurrentSubtype;
+ private InputMethodInfoCompatWrapper mShortcutInputMethodInfo;
+ private InputMethodSubtypeCompatWrapper mShortcutSubtype;
+ private List<InputMethodSubtypeCompatWrapper> mAllEnabledSubtypesOfCurrentInputMethod;
+ private InputMethodSubtypeCompatWrapper mCurrentSubtype;
private Locale mSystemLocale;
private Locale mInputLocale;
private String mInputLocaleStr;
- private VoiceInput mVoiceInput;
+ private String mInputMethodId;
+ private VoiceProxy.VoiceInputWrapper mVoiceInputWrapper;
/*-----------------------------------------------------------*/
private boolean mIsNetworkConnected;
@@ -88,10 +92,9 @@ public class SubtypeSwitcher {
}
public static void init(LatinIME service, SharedPreferences prefs) {
+ SubtypeLocale.init(service);
sInstance.initialize(service, prefs);
sInstance.updateAllParameters();
-
- SubtypeLocale.init(service);
}
private SubtypeSwitcher() {
@@ -100,9 +103,8 @@ public class SubtypeSwitcher {
private void initialize(LatinIME service, SharedPreferences prefs) {
mService = service;
- mPrefs = prefs;
mResources = service.getResources();
- mImm = (InputMethodManager) service.getSystemService(Context.INPUT_METHOD_SERVICE);
+ mImm = InputMethodManagerCompatWrapper.getInstance(service);
mConnectivityManager = (ConnectivityManager) service.getSystemService(
Context.CONNECTIVITY_SERVICE);
mEnabledKeyboardSubtypesOfCurrentInputMethod.clear();
@@ -112,15 +114,12 @@ public class SubtypeSwitcher {
mInputLocaleStr = null;
mCurrentSubtype = null;
mAllEnabledSubtypesOfCurrentInputMethod = null;
- // TODO: Voice input should be created here
- mVoiceInput = null;
- mConfigUseSpacebarLanguageSwitcher = mResources.getBoolean(
- R.bool.config_use_spacebar_language_switcher);
- if (mConfigUseSpacebarLanguageSwitcher)
- initLanguageSwitcher(service);
+ mVoiceInputWrapper = null;
+ mPrefs = prefs;
final NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();
mIsNetworkConnected = (info != null && info.isConnected());
+ mInputMethodId = Utils.getInputMethodId(mImm, service.getPackageName());
}
// Update all parameters stored in SubtypeSwitcher.
@@ -134,11 +133,10 @@ public class SubtypeSwitcher {
// Update parameters which are changed outside LatinIME. This parameters affect UI so they
// should be updated every time onStartInputview.
public void updateParametersOnStartInputView() {
- if (mConfigUseSpacebarLanguageSwitcher) {
- updateForSpacebarLanguageSwitch();
- } else {
- updateEnabledSubtypes();
- }
+ mConfigUseSpacebarLanguageSwitcher = mPrefs.getBoolean(USE_SPACEBAR_LANGUAGE_SWITCH_KEY,
+ mService.getResources().getBoolean(
+ R.bool.config_use_spacebar_language_switcher));
+ updateEnabledSubtypes();
updateShortcutIME();
}
@@ -150,7 +148,7 @@ public class SubtypeSwitcher {
null, true);
mEnabledLanguagesOfCurrentInputMethod.clear();
mEnabledKeyboardSubtypesOfCurrentInputMethod.clear();
- for (InputMethodSubtype ims: mAllEnabledSubtypesOfCurrentInputMethod) {
+ for (InputMethodSubtypeCompatWrapper ims : mAllEnabledSubtypesOfCurrentInputMethod) {
final String locale = ims.getLocale();
final String mode = ims.getMode();
mLocaleSplitter.setString(locale);
@@ -172,6 +170,10 @@ public class SubtypeSwitcher {
Log.w(TAG, "Last subtype was disabled. Update to the current one.");
}
updateSubtype(mImm.getCurrentInputMethodSubtype());
+ } else {
+ // mLanguageBarInfo.update() will be called in updateSubtype so there is no need
+ // to call this in the if-clause above.
+ mLanguageBarInfo.update();
}
}
@@ -184,10 +186,10 @@ public class SubtypeSwitcher {
+ ", " + mShortcutSubtype.getMode())));
}
// TODO: Update an icon for shortcut IME
- Map<InputMethodInfo, List<InputMethodSubtype>> shortcuts =
+ final Map<InputMethodInfoCompatWrapper, List<InputMethodSubtypeCompatWrapper>> shortcuts =
mImm.getShortcutInputMethodsAndSubtypes();
- for (InputMethodInfo imi: shortcuts.keySet()) {
- List<InputMethodSubtype> subtypes = shortcuts.get(imi);
+ for (InputMethodInfoCompatWrapper imi : shortcuts.keySet()) {
+ List<InputMethodSubtypeCompatWrapper> subtypes = shortcuts.get(imi);
// TODO: Returns the first found IMI for now. Should handle all shortcuts as
// appropriate.
mShortcutInputMethodInfo = imi;
@@ -206,7 +208,7 @@ public class SubtypeSwitcher {
}
// Update the current subtype. LatinIME.onCurrentInputMethodSubtypeChanged calls this function.
- public void updateSubtype(InputMethodSubtype newSubtype) {
+ public void updateSubtype(InputMethodSubtypeCompatWrapper newSubtype) {
final String newLocale;
final String newMode;
final String oldMode = getCurrentSubtypeMode();
@@ -243,32 +245,33 @@ public class SubtypeSwitcher {
// We cancel its status when we change mode, while we reset otherwise.
if (isKeyboardMode()) {
if (modeChanged) {
- if (VOICE_MODE.equals(oldMode) && mVoiceInput != null) {
- mVoiceInput.cancel();
+ if (VOICE_MODE.equals(oldMode) && mVoiceInputWrapper != null) {
+ mVoiceInputWrapper.cancel();
}
}
if (modeChanged || languageChanged) {
updateShortcutIME();
mService.onRefreshKeyboard();
}
- } else if (isVoiceMode() && mVoiceInput != null) {
+ } else if (isVoiceMode() && mVoiceInputWrapper != null) {
if (VOICE_MODE.equals(oldMode)) {
- mVoiceInput.reset();
+ mVoiceInputWrapper.reset();
}
// If needsToShowWarningDialog is true, voice input need to show warning before
// show recognition view.
if (languageChanged || modeChanged
- || VoiceIMEConnector.getInstance().needsToShowWarningDialog()) {
+ || VoiceProxy.getInstance().needsToShowWarningDialog()) {
triggerVoiceIME();
}
} else {
Log.w(TAG, "Unknown subtype mode: " + newMode);
- if (VOICE_MODE.equals(oldMode) && mVoiceInput != null) {
+ if (VOICE_MODE.equals(oldMode) && mVoiceInputWrapper != null) {
// We need to reset the voice input to release the resources and to reset its status
// as it is not the current input mode.
- mVoiceInput.reset();
+ mVoiceInputWrapper.reset();
}
}
+ mLanguageBarInfo.update();
}
// Update the current input locale from Locale string.
@@ -277,14 +280,8 @@ public class SubtypeSwitcher {
// "en_US" --> language: en & country: US
// "en" --> language: en
// "" --> the system locale
- mLocaleSplitter.setString(inputLocaleStr);
- if (mLocaleSplitter.hasNext()) {
- String language = mLocaleSplitter.next();
- if (mLocaleSplitter.hasNext()) {
- mInputLocale = new Locale(language, mLocaleSplitter.next());
- } else {
- mInputLocale = new Locale(language);
- }
+ if (!TextUtils.isEmpty(inputLocaleStr)) {
+ mInputLocale = Utils.constructLocaleFromString(inputLocaleStr);
mInputLocaleStr = inputLocaleStr;
} else {
mInputLocale = mSystemLocale;
@@ -303,25 +300,47 @@ public class SubtypeSwitcher {
////////////////////////////
public void switchToShortcutIME() {
- final IBinder token = mService.getWindow().getWindow().getAttributes().token;
- if (token == null || mShortcutInputMethodInfo == null) {
+ if (mShortcutInputMethodInfo == null) {
return;
}
+
final String imiId = mShortcutInputMethodInfo.getId();
- final InputMethodSubtype subtype = mShortcutSubtype;
- new Thread("SwitchToShortcutIME") {
+ final InputMethodSubtypeCompatWrapper subtype = mShortcutSubtype;
+ switchToTargetIME(imiId, subtype);
+ }
+
+ private void switchToTargetIME(
+ final String imiId, final InputMethodSubtypeCompatWrapper subtype) {
+ final IBinder token = mService.getWindow().getWindow().getAttributes().token;
+ if (token == null) {
+ return;
+ }
+ new AsyncTask<Void, Void, Void>() {
@Override
- public void run() {
+ protected Void doInBackground(Void... params) {
mImm.setInputMethodAndSubtype(token, imiId, subtype);
+ return null;
}
- }.start();
+
+ @Override
+ protected void onPostExecute(Void result) {
+ // Calls in this method need to be done in the same thread as the thread which
+ // called switchToShortcutIME().
+
+ // Notify an event that the current subtype was changed. This event will be
+ // handled if "onCurrentInputMethodSubtypeChanged" can't be implemented
+ // when the API level is 10 or previous.
+ mService.notifyOnCurrentInputMethodSubtypeChanged(subtype);
+ }
+ }.execute();
}
public Drawable getShortcutIcon() {
return getSubtypeIcon(mShortcutInputMethodInfo, mShortcutSubtype);
}
- private Drawable getSubtypeIcon(InputMethodInfo imi, InputMethodSubtype subtype) {
+ private Drawable getSubtypeIcon(
+ InputMethodInfoCompatWrapper imi, InputMethodSubtypeCompatWrapper subtype) {
final PackageManager pm = mService.getPackageManager();
if (imi != null) {
final String imiPackageName = imi.getPackageName();
@@ -360,11 +379,16 @@ public class SubtypeSwitcher {
return false;
if (mShortcutSubtype == null)
return true;
+ // For compatibility, if the shortcut subtype is dummy, we assume the shortcut IME
+ // (built-in voice dummy subtype) is available.
+ if (!mShortcutSubtype.hasOriginalObject()) return true;
final boolean allowsImplicitlySelectedSubtypes = true;
- for (final InputMethodSubtype enabledSubtype : mImm.getEnabledInputMethodSubtypeList(
- mShortcutInputMethodInfo, allowsImplicitlySelectedSubtypes)) {
- if (enabledSubtype.equals(mShortcutSubtype))
+ for (final InputMethodSubtypeCompatWrapper enabledSubtype :
+ mImm.getEnabledInputMethodSubtypeList(
+ mShortcutInputMethodInfo, allowsImplicitlySelectedSubtypes)) {
+ if (enabledSubtype.equals(mShortcutSubtype)) {
return true;
+ }
}
return false;
}
@@ -389,7 +413,7 @@ public class SubtypeSwitcher {
final KeyboardSwitcher switcher = KeyboardSwitcher.getInstance();
final LatinKeyboard keyboard = switcher.getLatinKeyboard();
if (keyboard != null) {
- keyboard.updateShortcutKey(isShortcutImeReady(), switcher.getInputView());
+ keyboard.updateShortcutKey(isShortcutImeReady(), switcher.getKeyboardView());
}
}
@@ -398,11 +422,7 @@ public class SubtypeSwitcher {
//////////////////////////////////
public int getEnabledKeyboardLocaleCount() {
- if (mConfigUseSpacebarLanguageSwitcher) {
- return mLanguageSwitcher.getLocaleCount();
- } else {
- return mEnabledKeyboardSubtypesOfCurrentInputMethod.size();
- }
+ return mEnabledKeyboardSubtypesOfCurrentInputMethod.size();
}
public boolean useSpacebarLanguageSwitcher() {
@@ -414,90 +434,40 @@ public class SubtypeSwitcher {
}
public Locale getInputLocale() {
- if (mConfigUseSpacebarLanguageSwitcher) {
- return mLanguageSwitcher.getInputLocale();
- } else {
- return mInputLocale;
- }
+ return mInputLocale;
}
public String getInputLocaleStr() {
- if (mConfigUseSpacebarLanguageSwitcher) {
- String inputLanguage = null;
- inputLanguage = mLanguageSwitcher.getInputLanguage();
- // Should return system locale if there is no Language available.
- if (inputLanguage == null) {
- inputLanguage = getSystemLocale().getLanguage();
- }
- return inputLanguage;
- } else {
- return mInputLocaleStr;
- }
+ return mInputLocaleStr;
}
public String[] getEnabledLanguages() {
- if (mConfigUseSpacebarLanguageSwitcher) {
- return mLanguageSwitcher.getEnabledLanguages();
- } else {
- int enabledLanguageCount = mEnabledLanguagesOfCurrentInputMethod.size();
- // Workaround for explicitly specifying the voice language
- if (enabledLanguageCount == 1) {
- mEnabledLanguagesOfCurrentInputMethod.add(
- mEnabledLanguagesOfCurrentInputMethod.get(0));
- ++enabledLanguageCount;
- }
- return mEnabledLanguagesOfCurrentInputMethod.toArray(
- new String[enabledLanguageCount]);
+ int enabledLanguageCount = mEnabledLanguagesOfCurrentInputMethod.size();
+ // Workaround for explicitly specifying the voice language
+ if (enabledLanguageCount == 1) {
+ mEnabledLanguagesOfCurrentInputMethod.add(mEnabledLanguagesOfCurrentInputMethod
+ .get(0));
+ ++enabledLanguageCount;
}
+ return mEnabledLanguagesOfCurrentInputMethod.toArray(new String[enabledLanguageCount]);
}
public Locale getSystemLocale() {
- if (mConfigUseSpacebarLanguageSwitcher) {
- return mLanguageSwitcher.getSystemLocale();
- } else {
- return mSystemLocale;
- }
+ return mSystemLocale;
}
public boolean isSystemLanguageSameAsInputLanguage() {
- if (mConfigUseSpacebarLanguageSwitcher) {
- return getSystemLocale().getLanguage().equalsIgnoreCase(
- getInputLocaleStr().substring(0, 2));
- } else {
- return mIsSystemLanguageSameAsInputLanguage;
- }
+ return mIsSystemLanguageSameAsInputLanguage;
}
public void onConfigurationChanged(Configuration conf) {
final Locale systemLocale = conf.locale;
// If system configuration was changed, update all parameters.
if (!TextUtils.equals(systemLocale.toString(), mSystemLocale.toString())) {
- if (mConfigUseSpacebarLanguageSwitcher) {
- // If the system locale changes and is different from the saved
- // locale (mSystemLocale), then reload the input locale list from the
- // latin ime settings (shared prefs) and reset the input locale
- // to the first one.
- mLanguageSwitcher.loadLocales(mPrefs);
- mLanguageSwitcher.setSystemLocale(systemLocale);
- } else {
- updateAllParameters();
- }
+ updateAllParameters();
}
}
- /**
- * Change system locale for this application
- * @param newLocale
- * @return oldLocale
- */
- public Locale changeSystemLocale(Locale newLocale) {
- Configuration conf = mResources.getConfiguration();
- Locale oldLocale = conf.locale;
- conf.locale = newLocale;
- mResources.updateConfiguration(conf, mResources.getDisplayMetrics());
- return oldLocale;
- }
-
public boolean isKeyboardMode() {
return KEYBOARD_MODE.equals(getCurrentSubtypeMode());
}
@@ -507,9 +477,9 @@ public class SubtypeSwitcher {
// Voice Input functions //
///////////////////////////
- public boolean setVoiceInput(VoiceInput vi) {
- if (mVoiceInput == null && vi != null) {
- mVoiceInput = vi;
+ public boolean setVoiceInputWrapper(VoiceProxy.VoiceInputWrapper vi) {
+ if (mVoiceInputWrapper == null && vi != null) {
+ mVoiceInputWrapper = vi;
if (isVoiceMode()) {
if (DBG) {
Log.d(TAG, "Set and call voice input.: " + getInputLocaleStr());
@@ -525,17 +495,85 @@ public class SubtypeSwitcher {
return null == mCurrentSubtype ? false : VOICE_MODE.equals(getCurrentSubtypeMode());
}
+ public boolean isDummyVoiceMode() {
+ return mCurrentSubtype != null && mCurrentSubtype.getOriginalObject() == null
+ && VOICE_MODE.equals(getCurrentSubtypeMode());
+ }
+
private void triggerVoiceIME() {
if (!mService.isInputViewShown()) return;
- VoiceIMEConnector.getInstance().startListening(false,
- KeyboardSwitcher.getInstance().getInputView().getWindowToken());
+ VoiceProxy.getInstance().startListening(false,
+ KeyboardSwitcher.getInstance().getKeyboardView().getWindowToken());
}
//////////////////////////////////////
// Spacebar Language Switch support //
//////////////////////////////////////
- private LanguageSwitcher mLanguageSwitcher;
+ private class LanguageBarInfo {
+ private int mCurrentKeyboardSubtypeIndex;
+ private InputMethodSubtypeCompatWrapper mNextKeyboardSubtype;
+ private InputMethodSubtypeCompatWrapper mPreviousKeyboardSubtype;
+ private String mNextLanguage;
+ private String mPreviousLanguage;
+ public LanguageBarInfo() {
+ update();
+ }
+
+ private String getNextLanguage() {
+ return mNextLanguage;
+ }
+
+ private String getPreviousLanguage() {
+ return mPreviousLanguage;
+ }
+
+ public InputMethodSubtypeCompatWrapper getNextKeyboardSubtype() {
+ return mNextKeyboardSubtype;
+ }
+
+ public InputMethodSubtypeCompatWrapper getPreviousKeyboardSubtype() {
+ return mPreviousKeyboardSubtype;
+ }
+
+ public void update() {
+ if (!mConfigUseSpacebarLanguageSwitcher
+ || mEnabledKeyboardSubtypesOfCurrentInputMethod == null
+ || mEnabledKeyboardSubtypesOfCurrentInputMethod.size() == 0) return;
+ mCurrentKeyboardSubtypeIndex = getCurrentIndex();
+ mNextKeyboardSubtype = getNextKeyboardSubtypeInternal(mCurrentKeyboardSubtypeIndex);
+ Locale locale = Utils.constructLocaleFromString(mNextKeyboardSubtype.getLocale());
+ mNextLanguage = getFullDisplayName(locale, true);
+ mPreviousKeyboardSubtype = getPreviousKeyboardSubtypeInternal(
+ mCurrentKeyboardSubtypeIndex);
+ locale = Utils.constructLocaleFromString(mPreviousKeyboardSubtype.getLocale());
+ mPreviousLanguage = getFullDisplayName(locale, true);
+ }
+
+ private int normalize(int index) {
+ final int N = mEnabledKeyboardSubtypesOfCurrentInputMethod.size();
+ final int ret = index % N;
+ return ret < 0 ? ret + N : ret;
+ }
+
+ private int getCurrentIndex() {
+ final int N = mEnabledKeyboardSubtypesOfCurrentInputMethod.size();
+ for (int i = 0; i < N; ++i) {
+ if (mEnabledKeyboardSubtypesOfCurrentInputMethod.get(i).equals(mCurrentSubtype)) {
+ return i;
+ }
+ }
+ return 0;
+ }
+
+ private InputMethodSubtypeCompatWrapper getNextKeyboardSubtypeInternal(int index) {
+ return mEnabledKeyboardSubtypesOfCurrentInputMethod.get(normalize(index + 1));
+ }
+
+ private InputMethodSubtypeCompatWrapper getPreviousKeyboardSubtypeInternal(int index) {
+ return mEnabledKeyboardSubtypesOfCurrentInputMethod.get(normalize(index - 1));
+ }
+ }
public static String getFullDisplayName(Locale locale, boolean returnsNameInThisLocale) {
if (returnsNameInThisLocale) {
@@ -546,7 +584,12 @@ public class SubtypeSwitcher {
}
public static String getDisplayLanguage(Locale locale) {
- return toTitleCase(locale.getDisplayLanguage(locale));
+ return toTitleCase(SubtypeLocale.getFullDisplayName(locale));
+ }
+
+ public static String getMiddleDisplayLanguage(Locale locale) {
+ return toTitleCase((Utils.constructLocaleFromString(
+ locale.getLanguage()).getDisplayLanguage(locale)));
}
public static String getShortDisplayLanguage(Locale locale) {
@@ -560,32 +603,16 @@ public class SubtypeSwitcher {
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
- private void updateForSpacebarLanguageSwitch() {
- // We need to update mNeedsToDisplayLanguage in onStartInputView because
- // getEnabledKeyboardLocaleCount could have been changed.
- mNeedsToDisplayLanguage = !(getEnabledKeyboardLocaleCount() <= 1
- && getSystemLocale().getLanguage().equalsIgnoreCase(
- getInputLocale().getLanguage()));
- }
-
public String getInputLanguageName() {
return getDisplayLanguage(getInputLocale());
}
public String getNextInputLanguageName() {
- if (mConfigUseSpacebarLanguageSwitcher) {
- return getDisplayLanguage(mLanguageSwitcher.getNextInputLocale());
- } else {
- return "";
- }
+ return mLanguageBarInfo.getNextLanguage();
}
public String getPreviousInputLanguageName() {
- if (mConfigUseSpacebarLanguageSwitcher) {
- return getDisplayLanguage(mLanguageSwitcher.getPrevInputLocale());
- } else {
- return "";
- }
+ return mLanguageBarInfo.getPreviousLanguage();
}
/////////////////////////////
@@ -612,60 +639,36 @@ public class SubtypeSwitcher {
}
- // A list of locales which are supported by default for voice input, unless we get a
- // different list from Gservices.
- private static final String DEFAULT_VOICE_INPUT_SUPPORTED_LOCALES =
- "en " +
- "en_US " +
- "en_GB " +
- "en_AU " +
- "en_CA " +
- "en_IE " +
- "en_IN " +
- "en_NZ " +
- "en_SG " +
- "en_ZA ";
-
public boolean isVoiceSupported(String locale) {
// Get the current list of supported locales and check the current locale against that
// list. We cache this value so as not to check it every time the user starts a voice
// input. Because this method is called by onStartInputView, this should mean that as
// long as the locale doesn't change while the user is keeping the IME open, the
// value should never be stale.
- String supportedLocalesString = SettingsUtil.getSettingsString(
- mService.getContentResolver(),
- SettingsUtil.LATIN_IME_VOICE_INPUT_SUPPORTED_LOCALES,
- DEFAULT_VOICE_INPUT_SUPPORTED_LOCALES);
+ String supportedLocalesString = VoiceProxy.getSupportedLocalesString(
+ mService.getContentResolver());
List<String> voiceInputSupportedLocales = Arrays.asList(
supportedLocalesString.split("\\s+"));
return voiceInputSupportedLocales.contains(locale);
}
- public void loadSettings() {
- if (mConfigUseSpacebarLanguageSwitcher) {
- mLanguageSwitcher.loadLocales(mPrefs);
- }
+ private void changeToNextSubtype() {
+ final InputMethodSubtypeCompatWrapper subtype =
+ mLanguageBarInfo.getNextKeyboardSubtype();
+ switchToTargetIME(mInputMethodId, subtype);
}
- public void toggleLanguage(boolean reset, boolean next) {
- if (mConfigUseSpacebarLanguageSwitcher) {
- if (reset) {
- mLanguageSwitcher.reset();
- } else {
- if (next) {
- mLanguageSwitcher.next();
- } else {
- mLanguageSwitcher.prev();
- }
- }
- mLanguageSwitcher.persist(mPrefs);
- }
+ private void changeToPreviousSubtype() {
+ final InputMethodSubtypeCompatWrapper subtype =
+ mLanguageBarInfo.getPreviousKeyboardSubtype();
+ switchToTargetIME(mInputMethodId, subtype);
}
- private void initLanguageSwitcher(LatinIME service) {
- final Configuration conf = service.getResources().getConfiguration();
- mLanguageSwitcher = new LanguageSwitcher(service);
- mLanguageSwitcher.loadLocales(mPrefs);
- mLanguageSwitcher.setSystemLocale(conf.locale);
+ public void toggleLanguage(boolean next) {
+ if (next) {
+ changeToNextSubtype();
+ } else {
+ changeToPreviousSubtype();
+ }
}
}
diff --git a/java/src/com/android/inputmethod/latin/Suggest.java b/java/src/com/android/inputmethod/latin/Suggest.java
index 0de474e59..ca75866c0 100644
--- a/java/src/com/android/inputmethod/latin/Suggest.java
+++ b/java/src/com/android/inputmethod/latin/Suggest.java
@@ -27,6 +27,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.Locale;
import java.util.Map;
import java.util.Set;
@@ -47,7 +48,7 @@ public class Suggest implements Dictionary.WordCallback {
/**
* Words that appear in both bigram and unigram data gets multiplier ranging from
- * BIGRAM_MULTIPLIER_MIN to BIGRAM_MULTIPLIER_MAX depending on the frequency score from
+ * BIGRAM_MULTIPLIER_MIN to BIGRAM_MULTIPLIER_MAX depending on the score from
* bigram data.
*/
public static final double BIGRAM_MULTIPLIER_MIN = 1.2;
@@ -55,7 +56,7 @@ public class Suggest implements Dictionary.WordCallback {
/**
* Maximum possible bigram frequency. Will depend on how many bits are being used in data
- * structure. Maximum bigram freqeuncy will get the BIGRAM_MULTIPLIER_MAX as the multiplier.
+ * structure. Maximum bigram frequency will get the BIGRAM_MULTIPLIER_MAX as the multiplier.
*/
public static final int MAXIMUM_BIGRAM_FREQUENCY = 127;
@@ -74,13 +75,11 @@ public class Suggest implements Dictionary.WordCallback {
public static final String DICT_KEY_USER_BIGRAM = "user_bigram";
public static final String DICT_KEY_WHITELIST ="whitelist";
- static final int LARGE_DICTIONARY_THRESHOLD = 200 * 1000;
-
private static final boolean DBG = LatinImeLogger.sDBG;
private AutoCorrection mAutoCorrection;
- private BinaryDictionary mMainDict;
+ private Dictionary mMainDict;
private WhitelistDictionary mWhiteListDictionary;
private final Map<String, Dictionary> mUnigramDictionaries = new HashMap<String, Dictionary>();
private final Map<String, Dictionary> mBigramDictionaries = new HashMap<String, Dictionary>();
@@ -92,13 +91,13 @@ public class Suggest implements Dictionary.WordCallback {
private boolean mQuickFixesEnabled;
private double mAutoCorrectionThreshold;
- private int[] mPriorities = new int[mPrefMaxSuggestions];
- private int[] mBigramPriorities = new int[PREF_MAX_BIGRAMS];
+ private int[] mScores = new int[mPrefMaxSuggestions];
+ private int[] mBigramScores = new int[PREF_MAX_BIGRAMS];
private ArrayList<CharSequence> mSuggestions = new ArrayList<CharSequence>();
ArrayList<CharSequence> mBigramSuggestions = new ArrayList<CharSequence>();
private ArrayList<CharSequence> mStringPool = new ArrayList<CharSequence>();
- private String mLowerOriginalWord;
+ private CharSequence mTypedWord;
// TODO: Remove these member variables by passing more context to addWord() callback method
private boolean mIsFirstCharCapitalized;
@@ -106,15 +105,18 @@ public class Suggest implements Dictionary.WordCallback {
private int mCorrectionMode = CORRECTION_BASIC;
- public Suggest(Context context, int dictionaryResId) {
- init(context, BinaryDictionary.initDictionary(context, dictionaryResId, DIC_MAIN));
+ public Suggest(Context context, int dictionaryResId, Locale locale) {
+ init(context, DictionaryFactory.createDictionaryFromManager(context, locale,
+ dictionaryResId));
}
- /* package for test */ Suggest(File dictionary, long startOffset, long length) {
- init(null, BinaryDictionary.initDictionary(dictionary, startOffset, length, DIC_MAIN));
+ /* package for test */ Suggest(Context context, File dictionary, long startOffset, long length,
+ Flag[] flagArray) {
+ init(null, DictionaryFactory.createDictionaryForTest(context, dictionary, startOffset,
+ length, flagArray));
}
- private void init(Context context, BinaryDictionary mainDict) {
+ private void init(Context context, Dictionary mainDict) {
if (mainDict != null) {
mMainDict = mainDict;
mUnigramDictionaries.put(DICT_KEY_MAIN, mainDict);
@@ -128,6 +130,19 @@ public class Suggest implements Dictionary.WordCallback {
initPool();
}
+ public void resetMainDict(Context context, int dictionaryResId, Locale locale) {
+ final Dictionary newMainDict = DictionaryFactory.createDictionaryFromManager(
+ context, locale, dictionaryResId);
+ mMainDict = newMainDict;
+ if (null == newMainDict) {
+ mUnigramDictionaries.remove(DICT_KEY_MAIN);
+ mBigramDictionaries.remove(DICT_KEY_MAIN);
+ } else {
+ mUnigramDictionaries.put(DICT_KEY_MAIN, newMainDict);
+ mBigramDictionaries.put(DICT_KEY_MAIN, newMainDict);
+ }
+ }
+
private void initPool() {
for (int i = 0; i < mPrefMaxSuggestions; i++) {
StringBuilder sb = new StringBuilder(getApproxMaxWordLength());
@@ -148,7 +163,7 @@ public class Suggest implements Dictionary.WordCallback {
}
public boolean hasMainDictionary() {
- return mMainDict != null && mMainDict.getSize() > LARGE_DICTIONARY_THRESHOLD;
+ return mMainDict != null;
}
public Map<String, Dictionary> getUnigramDictionaries() {
@@ -207,8 +222,8 @@ public class Suggest implements Dictionary.WordCallback {
throw new IllegalArgumentException("maxSuggestions must be between 1 and 100");
}
mPrefMaxSuggestions = maxSuggestions;
- mPriorities = new int[mPrefMaxSuggestions];
- mBigramPriorities = new int[PREF_MAX_BIGRAMS];
+ mScores = new int[mPrefMaxSuggestions];
+ mBigramScores = new int[PREF_MAX_BIGRAMS];
collectGarbage(mSuggestions, mPrefMaxSuggestions);
while (mStringPool.size() < mPrefMaxSuggestions) {
StringBuilder sb = new StringBuilder(getApproxMaxWordLength());
@@ -248,6 +263,16 @@ public class Suggest implements Dictionary.WordCallback {
return sb;
}
+ protected void addBigramToSuggestions(CharSequence bigram) {
+ final int poolSize = mStringPool.size();
+ final StringBuilder sb = poolSize > 0 ?
+ (StringBuilder) mStringPool.remove(poolSize - 1)
+ : new StringBuilder(getApproxMaxWordLength());
+ sb.setLength(0);
+ sb.append(bigram);
+ mSuggestions.add(sb);
+ }
+
// TODO: cleanup dictionaries looking up and suggestions building with SuggestedWords.Builder
public SuggestedWords.Builder getSuggestedWordBuilder(View view, WordComposer wordComposer,
CharSequence prevWordForBigram) {
@@ -256,25 +281,23 @@ public class Suggest implements Dictionary.WordCallback {
mIsFirstCharCapitalized = wordComposer.isFirstCharCapitalized();
mIsAllUpperCase = wordComposer.isAllUpperCase();
collectGarbage(mSuggestions, mPrefMaxSuggestions);
- Arrays.fill(mPriorities, 0);
+ Arrays.fill(mScores, 0);
// Save a lowercase version of the original word
CharSequence typedWord = wordComposer.getTypedWord();
if (typedWord != null) {
final String typedWordString = typedWord.toString();
typedWord = typedWordString;
- mLowerOriginalWord = typedWordString.toLowerCase();
// Treating USER_TYPED as UNIGRAM suggestion for logging now.
LatinImeLogger.onAddSuggestedWord(typedWordString, Suggest.DIC_USER_TYPED,
Dictionary.DataType.UNIGRAM);
- } else {
- mLowerOriginalWord = "";
}
+ mTypedWord = typedWord;
- if (wordComposer.size() == 1 && (mCorrectionMode == CORRECTION_FULL_BIGRAM
+ if (wordComposer.size() <= 1 && (mCorrectionMode == CORRECTION_FULL_BIGRAM
|| mCorrectionMode == CORRECTION_BASIC)) {
// At first character typed, search only the bigrams
- Arrays.fill(mBigramPriorities, 0);
+ Arrays.fill(mBigramScores, 0);
collectGarbage(mBigramSuggestions, PREF_MAX_BIGRAMS);
if (!TextUtils.isEmpty(prevWordForBigram)) {
@@ -285,21 +308,26 @@ public class Suggest implements Dictionary.WordCallback {
for (final Dictionary dictionary : mBigramDictionaries.values()) {
dictionary.getBigrams(wordComposer, prevWordForBigram, this);
}
- char currentChar = wordComposer.getTypedWord().charAt(0);
- char currentCharUpper = Character.toUpperCase(currentChar);
- int count = 0;
- int bigramSuggestionSize = mBigramSuggestions.size();
- for (int i = 0; i < bigramSuggestionSize; i++) {
- if (mBigramSuggestions.get(i).charAt(0) == currentChar
- || mBigramSuggestions.get(i).charAt(0) == currentCharUpper) {
- int poolSize = mStringPool.size();
- StringBuilder sb = poolSize > 0 ?
- (StringBuilder) mStringPool.remove(poolSize - 1)
- : new StringBuilder(getApproxMaxWordLength());
- sb.setLength(0);
- sb.append(mBigramSuggestions.get(i));
- mSuggestions.add(count++, sb);
- if (count > mPrefMaxSuggestions) break;
+ if (TextUtils.isEmpty(typedWord)) {
+ // Nothing entered: return all bigrams for the previous word
+ int insertCount = Math.min(mBigramSuggestions.size(), mPrefMaxSuggestions);
+ for (int i = 0; i < insertCount; ++i) {
+ addBigramToSuggestions(mBigramSuggestions.get(i));
+ }
+ } else {
+ // Word entered: return only bigrams that match the first char of the typed word
+ final char currentChar = typedWord.charAt(0);
+ final char currentCharUpper = Character.toUpperCase(currentChar);
+ int count = 0;
+ final int bigramSuggestionSize = mBigramSuggestions.size();
+ for (int i = 0; i < bigramSuggestionSize; i++) {
+ final CharSequence bigramSuggestion = mBigramSuggestions.get(i);
+ final char bigramSuggestionFirstChar = bigramSuggestion.charAt(0);
+ if (bigramSuggestionFirstChar == currentChar
+ || bigramSuggestionFirstChar == currentCharUpper) {
+ addBigramToSuggestions(bigramSuggestion);
+ if (++count > mPrefMaxSuggestions) break;
+ }
}
}
}
@@ -346,7 +374,7 @@ public class Suggest implements Dictionary.WordCallback {
mWhiteListDictionary.getWhiteListedWord(typedWordString));
mAutoCorrection.updateAutoCorrectionStatus(mUnigramDictionaries, wordComposer,
- mSuggestions, mPriorities, typedWord, mAutoCorrectionThreshold, mCorrectionMode,
+ mSuggestions, mScores, typedWord, mAutoCorrectionThreshold, mCorrectionMode,
autoText, whitelistedWord);
if (autoText != null) {
@@ -364,26 +392,25 @@ public class Suggest implements Dictionary.WordCallback {
if (DBG) {
double normalizedScore = mAutoCorrection.getNormalizedScore();
- ArrayList<SuggestedWords.SuggestedWordInfo> frequencyInfoList =
+ ArrayList<SuggestedWords.SuggestedWordInfo> scoreInfoList =
new ArrayList<SuggestedWords.SuggestedWordInfo>();
- frequencyInfoList.add(new SuggestedWords.SuggestedWordInfo("+", false));
- final int priorityLength = mPriorities.length;
- for (int i = 0; i < priorityLength; ++i) {
+ scoreInfoList.add(new SuggestedWords.SuggestedWordInfo("+", false));
+ for (int i = 0; i < mScores.length; ++i) {
if (normalizedScore > 0) {
- final String priorityThreshold = Integer.toString(mPriorities[i]) + " (" +
- normalizedScore + ")";
- frequencyInfoList.add(
- new SuggestedWords.SuggestedWordInfo(priorityThreshold, false));
+ final String scoreThreshold = String.format("%d (%4.2f)", mScores[i],
+ normalizedScore);
+ scoreInfoList.add(
+ new SuggestedWords.SuggestedWordInfo(scoreThreshold, false));
normalizedScore = 0.0;
} else {
- final String priority = Integer.toString(mPriorities[i]);
- frequencyInfoList.add(new SuggestedWords.SuggestedWordInfo(priority, false));
+ final String score = Integer.toString(mScores[i]);
+ scoreInfoList.add(new SuggestedWords.SuggestedWordInfo(score, false));
}
}
- for (int i = priorityLength; i < mSuggestions.size(); ++i) {
- frequencyInfoList.add(new SuggestedWords.SuggestedWordInfo("--", false));
+ for (int i = mScores.length; i < mSuggestions.size(); ++i) {
+ scoreInfoList.add(new SuggestedWords.SuggestedWordInfo("--", false));
}
- return new SuggestedWords.Builder().addWords(mSuggestions, frequencyInfoList);
+ return new SuggestedWords.Builder().addWords(mSuggestions, scoreInfoList);
}
return new SuggestedWords.Builder().addWords(mSuggestions, null);
}
@@ -419,52 +446,37 @@ public class Suggest implements Dictionary.WordCallback {
return mAutoCorrection.hasAutoCorrection();
}
- private static boolean compareCaseInsensitive(final String lowerOriginalWord,
- final char[] word, final int offset, final int length) {
- final int originalLength = lowerOriginalWord.length();
- if (originalLength == length && Character.isUpperCase(word[offset])) {
- for (int i = 0; i < originalLength; i++) {
- if (lowerOriginalWord.charAt(i) != Character.toLowerCase(word[offset+i])) {
- return false;
- }
- }
- return true;
- }
- return false;
- }
-
@Override
- public boolean addWord(final char[] word, final int offset, final int length, int freq,
+ public boolean addWord(final char[] word, final int offset, final int length, int score,
final int dicTypeId, final Dictionary.DataType dataType) {
Dictionary.DataType dataTypeForLog = dataType;
- ArrayList<CharSequence> suggestions;
- int[] priorities;
- int prefMaxSuggestions;
+ final ArrayList<CharSequence> suggestions;
+ final int[] sortedScores;
+ final int prefMaxSuggestions;
if(dataType == Dictionary.DataType.BIGRAM) {
suggestions = mBigramSuggestions;
- priorities = mBigramPriorities;
+ sortedScores = mBigramScores;
prefMaxSuggestions = PREF_MAX_BIGRAMS;
} else {
suggestions = mSuggestions;
- priorities = mPriorities;
+ sortedScores = mScores;
prefMaxSuggestions = mPrefMaxSuggestions;
}
int pos = 0;
// Check if it's the same word, only caps are different
- if (compareCaseInsensitive(mLowerOriginalWord, word, offset, length)) {
+ if (Utils.equalsIgnoreCase(mTypedWord, word, offset, length)) {
// TODO: remove this surrounding if clause and move this logic to
// getSuggestedWordBuilder.
if (suggestions.size() > 0) {
- final String currentHighestWordLowerCase =
- suggestions.get(0).toString().toLowerCase();
+ final String currentHighestWord = suggestions.get(0).toString();
// If the current highest word is also equal to typed word, we need to compare
// frequency to determine the insertion position. This does not ensure strictly
// correct ordering, but ensures the top score is on top which is enough for
// removing duplicates correctly.
- if (compareCaseInsensitive(currentHighestWordLowerCase, word, offset, length)
- && freq <= priorities[0]) {
+ if (Utils.equalsIgnoreCase(currentHighestWord, word, offset, length)
+ && score <= sortedScores[0]) {
pos = 1;
}
}
@@ -475,24 +487,24 @@ public class Suggest implements Dictionary.WordCallback {
if(bigramSuggestion >= 0) {
dataTypeForLog = Dictionary.DataType.BIGRAM;
// turn freq from bigram into multiplier specified above
- double multiplier = (((double) mBigramPriorities[bigramSuggestion])
+ double multiplier = (((double) mBigramScores[bigramSuggestion])
/ MAXIMUM_BIGRAM_FREQUENCY)
* (BIGRAM_MULTIPLIER_MAX - BIGRAM_MULTIPLIER_MIN)
+ BIGRAM_MULTIPLIER_MIN;
/* Log.d(TAG,"bigram num: " + bigramSuggestion
+ " wordB: " + mBigramSuggestions.get(bigramSuggestion).toString()
- + " currentPriority: " + freq + " bigramPriority: "
- + mBigramPriorities[bigramSuggestion]
+ + " currentScore: " + score + " bigramScore: "
+ + mBigramScores[bigramSuggestion]
+ " multiplier: " + multiplier); */
- freq = (int)Math.round((freq * multiplier));
+ score = (int)Math.round((score * multiplier));
}
}
- // Check the last one's priority and bail
- if (priorities[prefMaxSuggestions - 1] >= freq) return true;
+ // Check the last one's score and bail
+ if (sortedScores[prefMaxSuggestions - 1] >= score) return true;
while (pos < prefMaxSuggestions) {
- if (priorities[pos] < freq
- || (priorities[pos] == freq && length < suggestions.get(pos).length())) {
+ if (sortedScores[pos] < score
+ || (sortedScores[pos] == score && length < suggestions.get(pos).length())) {
break;
}
pos++;
@@ -502,8 +514,8 @@ public class Suggest implements Dictionary.WordCallback {
return true;
}
- System.arraycopy(priorities, pos, priorities, pos + 1, prefMaxSuggestions - pos - 1);
- priorities[pos] = freq;
+ System.arraycopy(sortedScores, pos, sortedScores, pos + 1, prefMaxSuggestions - pos - 1);
+ sortedScores[pos] = score;
int poolSize = mStringPool.size();
StringBuilder sb = poolSize > 0 ? (StringBuilder) mStringPool.remove(poolSize - 1)
: new StringBuilder(getApproxMaxWordLength());
diff --git a/java/src/com/android/inputmethod/latin/SuggestedWords.java b/java/src/com/android/inputmethod/latin/SuggestedWords.java
index fe7aac7c2..a8cdfc02e 100644
--- a/java/src/com/android/inputmethod/latin/SuggestedWords.java
+++ b/java/src/com/android/inputmethod/latin/SuggestedWords.java
@@ -32,14 +32,14 @@ public class SuggestedWords {
public final List<SuggestedWordInfo> mSuggestedWordInfoList;
private SuggestedWords(List<CharSequence> words, boolean typedWordValid,
- boolean hasMinamlSuggestion, List<SuggestedWordInfo> suggestedWordInfoList) {
+ boolean hasMinimalSuggestion, List<SuggestedWordInfo> suggestedWordInfoList) {
if (words != null) {
mWords = words;
} else {
mWords = Collections.emptyList();
}
mTypedWordValid = typedWordValid;
- mHasMinimalSuggestion = hasMinamlSuggestion;
+ mHasMinimalSuggestion = hasMinimalSuggestion;
mSuggestedWordInfoList = suggestedWordInfoList;
}
@@ -113,8 +113,8 @@ public class SuggestedWords {
return this;
}
- public Builder setHasMinimalSuggestion(boolean hasMinamlSuggestion) {
- mHasMinimalSuggestion = hasMinamlSuggestion;
+ public Builder setHasMinimalSuggestion(boolean hasMinimalSuggestion) {
+ mHasMinimalSuggestion = hasMinimalSuggestion;
return this;
}
diff --git a/java/src/com/android/inputmethod/latin/SuggestionSpanPickedNotificationReceiver.java b/java/src/com/android/inputmethod/latin/SuggestionSpanPickedNotificationReceiver.java
new file mode 100644
index 000000000..4a3f42d5d
--- /dev/null
+++ b/java/src/com/android/inputmethod/latin/SuggestionSpanPickedNotificationReceiver.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.inputmethod.latin;
+
+import com.android.inputmethod.compat.SuggestionSpanUtils;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+public class SuggestionSpanPickedNotificationReceiver extends BroadcastReceiver {
+ private static final boolean DBG = LatinImeLogger.sDBG;
+ private static final String TAG =
+ SuggestionSpanPickedNotificationReceiver.class.getSimpleName();
+
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ if (SuggestionSpanUtils.ACTION_SUGGESTION_PICKED.equals(intent.getAction())) {
+ if (DBG) {
+ final String before = intent.getStringExtra(
+ SuggestionSpanUtils.SUGGESTION_SPAN_PICKED_BEFORE);
+ final String after = intent.getStringExtra(
+ SuggestionSpanUtils.SUGGESTION_SPAN_PICKED_AFTER);
+ Log.d(TAG, "Received notification picked: " + before + "," + after);
+ }
+ }
+ }
+}
diff --git a/java/src/com/android/inputmethod/latin/TextEntryState.java b/java/src/com/android/inputmethod/latin/TextEntryState.java
index 63196430b..de13f3ae4 100644
--- a/java/src/com/android/inputmethod/latin/TextEntryState.java
+++ b/java/src/com/android/inputmethod/latin/TextEntryState.java
@@ -16,6 +16,8 @@
package com.android.inputmethod.latin;
+import com.android.inputmethod.latin.Utils.RingCharBuffer;
+
import android.util.Log;
public class TextEntryState {
@@ -43,10 +45,12 @@ public class TextEntryState {
sState = newState;
}
- public static void acceptedDefault(CharSequence typedWord, CharSequence actualWord) {
+ public static void acceptedDefault(CharSequence typedWord, CharSequence actualWord,
+ int separatorCode) {
if (typedWord == null) return;
setState(ACCEPTED_DEFAULT);
- LatinImeLogger.logOnAutoSuggestion(typedWord.toString(), actualWord.toString());
+ LatinImeLogger.logOnAutoCorrection(
+ typedWord.toString(), actualWord.toString(), separatorCode);
if (DEBUG)
displayState("acceptedDefault", "typedWord", typedWord, "actualWord", actualWord);
}
@@ -95,7 +99,7 @@ public class TextEntryState {
if (DEBUG) displayState("onAbortRecorrection");
}
- public static void typedCharacter(char c, boolean isSeparator) {
+ public static void typedCharacter(char c, boolean isSeparator, int x, int y) {
final boolean isSpace = (c == ' ');
switch (sState) {
case IN_WORD:
@@ -149,13 +153,19 @@ public class TextEntryState {
setState(START);
break;
}
+ RingCharBuffer.getInstance().push(c, x, y);
+ if (isSeparator) {
+ LatinImeLogger.logOnInputSeparator();
+ } else {
+ LatinImeLogger.logOnInputChar();
+ }
if (DEBUG) displayState("typedCharacter", "char", c, "isSeparator", isSeparator);
}
public static void backspace() {
if (sState == ACCEPTED_DEFAULT) {
setState(UNDO_COMMIT);
- LatinImeLogger.logOnAutoSuggestionCanceled();
+ LatinImeLogger.logOnAutoCorrectionCancelled();
} else if (sState == UNDO_COMMIT) {
setState(IN_WORD);
}
diff --git a/java/src/com/android/inputmethod/latin/UserBigramDictionary.java b/java/src/com/android/inputmethod/latin/UserBigramDictionary.java
index 656e6f8e0..5b615ca29 100644
--- a/java/src/com/android/inputmethod/latin/UserBigramDictionary.java
+++ b/java/src/com/android/inputmethod/latin/UserBigramDictionary.java
@@ -44,12 +44,6 @@ public class UserBigramDictionary extends ExpandableDictionary {
/** Maximum frequency for all pairs */
private static final int FREQUENCY_MAX = 127;
- /**
- * If this pair is typed 6 times, it would be suggested.
- * Should be smaller than ContactsDictionary.FREQUENCY_FOR_CONTACTS_BIGRAM
- */
- protected static final int SUGGEST_THRESHOLD = 6 * FREQUENCY_FOR_TYPED;
-
/** Maximum number of pairs. Pruning will start when databases goes above this number. */
private static int sMaxUserBigrams = 10000;
@@ -164,10 +158,14 @@ public class UserBigramDictionary extends ExpandableDictionary {
* Pair will be added to the userbigram database.
*/
public int addBigrams(String word1, String word2) {
- // remove caps
+ // remove caps if second word is autocapitalized
if (mIme != null && mIme.getCurrentWord().isAutoCapitalized()) {
word2 = Character.toLowerCase(word2.charAt(0)) + word2.substring(1);
}
+ // Do not insert a word as a bigram of itself
+ if (word1.equals(word2)) {
+ return 0;
+ }
int freq = super.addBigram(word1, word2, FREQUENCY_FOR_TYPED);
if (freq > FREQUENCY_MAX) freq = FREQUENCY_MAX;
diff --git a/java/src/com/android/inputmethod/latin/Utils.java b/java/src/com/android/inputmethod/latin/Utils.java
index 1cbc434b6..66a6d161b 100644
--- a/java/src/com/android/inputmethod/latin/Utils.java
+++ b/java/src/com/android/inputmethod/latin/Utils.java
@@ -16,6 +16,14 @@
package com.android.inputmethod.latin;
+import com.android.inputmethod.compat.InputMethodInfoCompatWrapper;
+import com.android.inputmethod.compat.InputMethodManagerCompatWrapper;
+import com.android.inputmethod.compat.InputTypeCompatUtils;
+import com.android.inputmethod.keyboard.Keyboard;
+import com.android.inputmethod.keyboard.KeyboardId;
+
+import android.content.Context;
+import android.content.res.Configuration;
import android.content.res.Resources;
import android.inputmethodservice.InputMethodService;
import android.os.AsyncTask;
@@ -26,10 +34,6 @@ import android.text.InputType;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.inputmethod.EditorInfo;
-import android.view.inputmethod.InputMethodInfo;
-import android.view.inputmethod.InputMethodManager;
-
-import com.android.inputmethod.keyboard.KeyboardId;
import java.io.BufferedReader;
import java.io.File;
@@ -40,11 +44,14 @@ import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
+import java.util.HashMap;
+import java.util.Locale;
public class Utils {
private static final String TAG = Utils.class.getSimpleName();
private static final int MINIMUM_SAFETY_NET_CHAR_LENGTH = 4;
private static boolean DBG = LatinImeLogger.sDBG;
+ private static boolean DBG_EDIT_DISTANCE = false;
private Utils() {
// Intentional empty constructor for utility class.
@@ -101,17 +108,22 @@ public class Utils {
}
}
- public static boolean hasMultipleEnabledIMEsOrSubtypes(InputMethodManager imm) {
+ public static boolean hasMultipleEnabledIMEsOrSubtypes(InputMethodManagerCompatWrapper imm) {
return imm.getEnabledInputMethodList().size() > 1
// imm.getEnabledInputMethodSubtypeList(null, false) will return the current IME's enabled
// input method subtype (The current IME should be LatinIME.)
|| imm.getEnabledInputMethodSubtypeList(null, false).size() > 1;
}
- public static String getInputMethodId(InputMethodManager imm, String packageName) {
- for (final InputMethodInfo imi : imm.getEnabledInputMethodList()) {
+ public static String getInputMethodId(InputMethodManagerCompatWrapper imm, String packageName) {
+ return getInputMethodInfo(imm, packageName).getId();
+ }
+
+ public static InputMethodInfoCompatWrapper getInputMethodInfo(
+ InputMethodManagerCompatWrapper imm, String packageName) {
+ for (final InputMethodInfoCompatWrapper imi : imm.getEnabledInputMethodList()) {
if (imi.getPackageName().equals(packageName))
- return imi.getId();
+ return imi;
}
throw new RuntimeException("Can not find input method id for " + packageName);
}
@@ -202,11 +214,11 @@ public class Utils {
return mCharBuf[mEnd];
}
}
- public char getLastChar() {
- if (mLength < 1) {
+ public char getBackwardNthChar(int n) {
+ if (mLength <= n || n < 0) {
return PLACEHOLDER_DELIMITER_CHAR;
} else {
- return mCharBuf[normalize(mEnd - 1)];
+ return mCharBuf[normalize(mEnd - n - 1)];
}
}
public int getPreviousX(char c, int back) {
@@ -227,9 +239,16 @@ public class Utils {
return mYBuf[index];
}
}
- public String getLastString() {
+ public String getLastWord(int ignoreCharCount) {
StringBuilder sb = new StringBuilder();
- for (int i = 0; i < mLength; ++i) {
+ int i = ignoreCharCount;
+ for (; i < mLength; ++i) {
+ char c = mCharBuf[normalize(mEnd - 1 - i)];
+ if (!((LatinIME)mContext).isWordSeparator(c)) {
+ break;
+ }
+ }
+ for (; i < mLength; ++i) {
char c = mCharBuf[normalize(mEnd - 1 - i)];
if (!((LatinIME)mContext).isWordSeparator(c)) {
sb.append(c);
@@ -244,6 +263,8 @@ public class Utils {
}
}
+
+ /* Damerau-Levenshtein distance */
public static int editDistance(CharSequence s, CharSequence t) {
if (s == null || t == null) {
throw new IllegalArgumentException("editDistance: Arguments should not be null.");
@@ -259,14 +280,29 @@ public class Utils {
}
for (int i = 0; i < sl; ++i) {
for (int j = 0; j < tl; ++j) {
- if (Character.toLowerCase(s.charAt(i)) == Character.toLowerCase(t.charAt(j))) {
- dp[i + 1][j + 1] = dp[i][j];
- } else {
- dp[i + 1][j + 1] = 1 + Math.min(dp[i][j],
- Math.min(dp[i + 1][j], dp[i][j + 1]));
+ final char sc = Character.toLowerCase(s.charAt(i));
+ final char tc = Character.toLowerCase(t.charAt(j));
+ final int cost = sc == tc ? 0 : 1;
+ dp[i + 1][j + 1] = Math.min(
+ dp[i][j + 1] + 1, Math.min(dp[i + 1][j] + 1, dp[i][j] + cost));
+ // Overwrite for transposition cases
+ if (i > 0 && j > 0
+ && sc == Character.toLowerCase(t.charAt(j - 1))
+ && tc == Character.toLowerCase(s.charAt(i - 1))) {
+ dp[i + 1][j + 1] = Math.min(dp[i + 1][j + 1], dp[i - 1][j - 1] + cost);
}
}
}
+ if (DBG_EDIT_DISTANCE) {
+ Log.d(TAG, "editDistance:" + s + "," + t);
+ for (int i = 0; i < dp.length; ++i) {
+ StringBuffer sb = new StringBuffer();
+ for (int j = 0; j < dp[i].length; ++j) {
+ sb.append(dp[i][j]).append(',');
+ }
+ Log.d(TAG, i + ":" + sb.toString());
+ }
+ }
return dp[sl][tl];
}
@@ -285,7 +321,7 @@ public class Utils {
// In dictionary.cpp, getSuggestion() method,
// suggestion scores are computed using the below formula.
- // original score (called 'frequency')
+ // original score
// := pow(mTypedLetterMultiplier (this is defined 2),
// (the number of matched characters between typed word and suggested word))
// * (individual word's score which defined in the unigram dictionary,
@@ -295,7 +331,7 @@ public class Utils {
// (full match up to min(before.length(), after.length())
// => Then multiply by FULL_MATCHED_WORDS_PROMOTION_RATE (this is defined 1.2)
// - If the word is a true full match except for differences in accents or
- // capitalization, then treat it as if the frequency was 255.
+ // capitalization, then treat it as if the score was 255.
// - If before.length() == after.length()
// => multiply by mFullWordMultiplier (this is defined 2))
// So, maximum original score is pow(2, min(before.length(), after.length())) * 255 * 2 * 1.2
@@ -306,6 +342,7 @@ public class Utils {
private static final int MAX_INITIAL_SCORE = 255;
private static final int TYPED_LETTER_MULTIPLIER = 2;
private static final int FULL_WORD_MULTIPLIER = 2;
+ private static final int S_INT_MAX = 2147483647;
public static double calcNormalizedScore(CharSequence before, CharSequence after, int score) {
final int beforeLength = before.length();
final int afterLength = after.length();
@@ -313,8 +350,16 @@ public class Utils {
final int distance = editDistance(before, after);
// If afterLength < beforeLength, the algorithm is suggesting a word by excessive character
// correction.
- final double maximumScore = MAX_INITIAL_SCORE
- * Math.pow(TYPED_LETTER_MULTIPLIER, Math.min(beforeLength, afterLength))
+ int spaceCount = 0;
+ for (int i = 0; i < afterLength; ++i) {
+ if (after.charAt(i) == Keyboard.CODE_SPACE) {
+ ++spaceCount;
+ }
+ }
+ if (spaceCount == afterLength) return 0;
+ final double maximumScore = score == S_INT_MAX ? S_INT_MAX : MAX_INITIAL_SCORE
+ * Math.pow(
+ TYPED_LETTER_MULTIPLIER, Math.min(beforeLength, afterLength - spaceCount))
* FULL_WORD_MULTIPLIER;
// add a weight based on edit distance.
// distance <= max(afterLength, beforeLength) == afterLength,
@@ -485,7 +530,7 @@ public class Utils {
case InputType.TYPE_CLASS_PHONE:
return KeyboardId.MODE_PHONE;
case InputType.TYPE_CLASS_TEXT:
- if (Utils.isEmailVariation(variation)) {
+ if (InputTypeCompatUtils.isEmailVariation(variation)) {
return KeyboardId.MODE_EMAIL;
} else if (variation == InputType.TYPE_TEXT_VARIATION_URI) {
return KeyboardId.MODE_URL;
@@ -501,42 +546,6 @@ public class Utils {
}
}
- public static boolean isEmailVariation(int variation) {
- return variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
- || variation == InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS;
- }
-
- public static boolean isWebInputType(int inputType) {
- final int variation =
- inputType & (InputType.TYPE_MASK_CLASS | InputType.TYPE_MASK_VARIATION);
- return (variation
- == (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT))
- || (variation
- == (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD))
- || (variation
- == (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS));
- }
-
- // Please refer to TextView.isPasswordInputType
- public static boolean isPasswordInputType(int inputType) {
- final int variation =
- inputType & (InputType.TYPE_MASK_CLASS | InputType.TYPE_MASK_VARIATION);
- return (variation
- == (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD))
- || (variation
- == (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD))
- || (variation
- == (InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD));
- }
-
- // Please refer to TextView.isVisiblePasswordInputType
- public static boolean isVisiblePasswordInputType(int inputType) {
- final int variation =
- inputType & (InputType.TYPE_MASK_CLASS | InputType.TYPE_MASK_VARIATION);
- return variation
- == (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
- }
-
public static boolean containsInCsv(String key, String csv) {
if (csv == null)
return false;
@@ -560,7 +569,9 @@ public class Utils {
* @return main dictionary resource id
*/
public static int getMainDictionaryResourceId(Resources res) {
- return res.getIdentifier("main", "raw", LatinIME.class.getPackage().getName());
+ final String MAIN_DIC_NAME = "main";
+ String packageName = LatinIME.class.getPackage().getName();
+ return res.getIdentifier(MAIN_DIC_NAME, "raw", packageName);
}
public static void loadNativeLibrary() {
@@ -570,4 +581,108 @@ public class Utils {
Log.e(TAG, "Could not load native library jni_latinime");
}
}
+
+ /**
+ * Returns true if a and b are equal ignoring the case of the character.
+ * @param a first character to check
+ * @param b second character to check
+ * @return {@code true} if a and b are equal, {@code false} otherwise.
+ */
+ public static boolean equalsIgnoreCase(char a, char b) {
+ // Some language, such as Turkish, need testing both cases.
+ return a == b
+ || Character.toLowerCase(a) == Character.toLowerCase(b)
+ || Character.toUpperCase(a) == Character.toUpperCase(b);
+ }
+
+ /**
+ * Returns true if a and b are equal ignoring the case of the characters, including if they are
+ * both null.
+ * @param a first CharSequence to check
+ * @param b second CharSequence to check
+ * @return {@code true} if a and b are equal, {@code false} otherwise.
+ */
+ public static boolean equalsIgnoreCase(CharSequence a, CharSequence b) {
+ if (a == b)
+ return true; // including both a and b are null.
+ if (a == null || b == null)
+ return false;
+ final int length = a.length();
+ if (length != b.length())
+ return false;
+ for (int i = 0; i < length; i++) {
+ if (!equalsIgnoreCase(a.charAt(i), b.charAt(i)))
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Returns true if a and b are equal ignoring the case of the characters, including if a is null
+ * and b is zero length.
+ * @param a CharSequence to check
+ * @param b character array to check
+ * @param offset start offset of array b
+ * @param length length of characters in array b
+ * @return {@code true} if a and b are equal, {@code false} otherwise.
+ * @throws IndexOutOfBoundsException
+ * if {@code offset < 0 || length < 0 || offset + length > data.length}.
+ * @throws NullPointerException if {@code b == null}.
+ */
+ public static boolean equalsIgnoreCase(CharSequence a, char[] b, int offset, int length) {
+ if (offset < 0 || length < 0 || length > b.length - offset)
+ throw new IndexOutOfBoundsException("array.length=" + b.length + " offset=" + offset
+ + " length=" + length);
+ if (a == null)
+ return length == 0; // including a is null and b is zero length.
+ if (a.length() != length)
+ return false;
+ for (int i = 0; i < length; i++) {
+ if (!equalsIgnoreCase(a.charAt(i), b[offset + i]))
+ return false;
+ }
+ return true;
+ }
+
+ public static float getDipScale(Context context) {
+ final float scale = context.getResources().getDisplayMetrics().density;
+ return scale;
+ }
+
+ /** Convert pixel to DIP */
+ public static int dipToPixel(float scale, int dip) {
+ return (int) (dip * scale + 0.5);
+ }
+
+ public static Locale setSystemLocale(Resources res, Locale newLocale) {
+ final Configuration conf = res.getConfiguration();
+ final Locale saveLocale = conf.locale;
+ conf.locale = newLocale;
+ res.updateConfiguration(conf, res.getDisplayMetrics());
+ return saveLocale;
+ }
+
+ private static final HashMap<String, Locale> sLocaleCache = new HashMap<String, Locale>();
+
+ public static Locale constructLocaleFromString(String localeStr) {
+ if (localeStr == null)
+ return null;
+ synchronized (sLocaleCache) {
+ if (sLocaleCache.containsKey(localeStr))
+ return sLocaleCache.get(localeStr);
+ Locale retval = null;
+ String[] localeParams = localeStr.split("_", 3);
+ if (localeParams.length == 1) {
+ retval = new Locale(localeParams[0]);
+ } else if (localeParams.length == 2) {
+ retval = new Locale(localeParams[0], localeParams[1]);
+ } else if (localeParams.length == 3) {
+ retval = new Locale(localeParams[0], localeParams[1], localeParams[2]);
+ }
+ if (retval != null) {
+ sLocaleCache.put(localeStr, retval);
+ }
+ return retval;
+ }
+ }
}
diff --git a/java/src/com/android/inputmethod/latin/WhitelistDictionary.java b/java/src/com/android/inputmethod/latin/WhitelistDictionary.java
index 2389d4e3c..4377373d2 100644
--- a/java/src/com/android/inputmethod/latin/WhitelistDictionary.java
+++ b/java/src/com/android/inputmethod/latin/WhitelistDictionary.java
@@ -39,6 +39,7 @@ public class WhitelistDictionary extends Dictionary {
public static WhitelistDictionary init(Context context) {
synchronized (sInstance) {
if (context != null) {
+ // Wordlist is initialized by the proper language in Suggestion.java#init
sInstance.initWordlist(
context.getResources().getStringArray(R.array.wordlist_whitelist));
} else {
diff --git a/java/src/com/android/inputmethod/latin/WordComposer.java b/java/src/com/android/inputmethod/latin/WordComposer.java
index 02583895b..af5e4b179 100644
--- a/java/src/com/android/inputmethod/latin/WordComposer.java
+++ b/java/src/com/android/inputmethod/latin/WordComposer.java
@@ -31,18 +31,18 @@ public class WordComposer {
/**
* The list of unicode values for each keystroke (including surrounding keys)
*/
- private final ArrayList<int[]> mCodes;
+ private ArrayList<int[]> mCodes;
private int mTypedLength;
- private final int[] mXCoordinates;
- private final int[] mYCoordinates;
+ private int[] mXCoordinates;
+ private int[] mYCoordinates;
/**
* The word chosen from the candidate list, until it is committed.
*/
private String mPreferredWord;
- private final StringBuilder mTypedWord;
+ private StringBuilder mTypedWord;
private int mCapsCount;
@@ -62,7 +62,11 @@ public class WordComposer {
mYCoordinates = new int[N];
}
- WordComposer(WordComposer source) {
+ public WordComposer(WordComposer source) {
+ init(source);
+ }
+
+ public void init(WordComposer source) {
mCodes = new ArrayList<int[]>(source.mCodes);
mPreferredWord = source.mPreferredWord;
mTypedWord = new StringBuilder(source.mTypedWord);